From ef9c388aacf2e0a60a7d00065a70f8ba190de2ab Mon Sep 17 00:00:00 2001 From: Tom Heaton Date: Tue, 26 Mar 2024 12:39:48 +0000 Subject: [PATCH 1/2] chore: run formatting - run formatting - add `format` command to `package.json` --- .editorconfig | 2 -- .watchmanconfig | 2 +- CODE_OF_CONDUCT.md | 21 ++++++------- README.md | 1 - example/next-app/app/api/assistant/route.ts | 20 ++++++------ .../app/api/chat-with-functions/route.ts | 2 +- example/next-app/app/api/chat/middleware.tsx | 31 ++++++++++--------- example/next-app/app/api/chat/route.ts | 29 +++++++++-------- .../next-app/app/function-calling/page.tsx | 4 +-- example/next-app/app/page.tsx | 2 +- .../asOpenAIMessages.tsx | 6 ++-- example/next-app/app/vision/page.tsx | 4 +-- example/next-app/next.config.js | 14 ++++----- package.json | 15 ++++----- src/shared/utils.test.ts | 4 +-- src/use-chat.ts | 2 +- src/use-completion.ts | 2 +- tsconfig.build.json | 1 - 18 files changed, 80 insertions(+), 82 deletions(-) diff --git a/.editorconfig b/.editorconfig index 65365be..6951d34 100644 --- a/.editorconfig +++ b/.editorconfig @@ -5,10 +5,8 @@ root = true [*] - indent_style = space indent_size = 2 - end_of_line = lf charset = utf-8 trim_trailing_whitespace = true diff --git a/.watchmanconfig b/.watchmanconfig index 9e26dfe..0967ef4 100644 --- a/.watchmanconfig +++ b/.watchmanconfig @@ -1 +1 @@ -{} \ No newline at end of file +{} diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 45d257b..8b4fcfd 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,4 +1,3 @@ - # Contributor Covenant Code of Conduct ## Our Pledge @@ -18,23 +17,23 @@ diverse, inclusive, and healthy community. Examples of behavior that contributes to a positive environment for our community include: -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall +- Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: -* The use of sexualized language or imagery, and sexual attention or advances of +- The use of sexualized language or imagery, and sexual attention or advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email address, +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a +- Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities diff --git a/README.md b/README.md index 41caf45..237e307 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,6 @@ Add this line to your `metro.config.js` file in order to enable [Package exports config.resolver.unstable_enablePackageExports = true; ``` - ### 2. On React Native app On your React Native app import `useChat` or `useCompletion` from `react-native-vercel-ai`. Same API as Vercel AI library. diff --git a/example/next-app/app/api/assistant/route.ts b/example/next-app/app/api/assistant/route.ts index 2950455..c92f4bc 100644 --- a/example/next-app/app/api/assistant/route.ts +++ b/example/next-app/app/api/assistant/route.ts @@ -11,11 +11,11 @@ const openai = new OpenAI({ export const runtime = 'edge'; const homeTemperatures = { - bedroom: 20, + 'bedroom': 20, 'home office': 21, 'living room': 21, - kitchen: 22, - bathroom: 23, + 'kitchen': 22, + 'bathroom': 23, }; export async function POST(req: Request) { @@ -50,7 +50,7 @@ export async function POST(req: Request) { // Poll for status change while (run.status === 'queued' || run.status === 'in_progress') { // delay for 500ms: - await new Promise(resolve => setTimeout(resolve, 500)); + await new Promise((resolve) => setTimeout(resolve, 500)); run = await openai.beta.threads.runs.retrieve(threadId!, run.id); } @@ -69,7 +69,7 @@ export async function POST(req: Request) { if (run.required_action?.type === 'submit_tool_outputs') { const tool_outputs = run.required_action.submit_tool_outputs.tool_calls.map( - toolCall => { + (toolCall) => { const parameters = JSON.parse(toolCall.function.arguments); switch (toolCall.function.name) { @@ -98,16 +98,16 @@ export async function POST(req: Request) { default: throw new Error( - `Unknown tool call function: ${toolCall.function.name}`, + `Unknown tool call function: ${toolCall.function.name}` ); } - }, + } ); run = await openai.beta.threads.runs.submitToolOutputs( threadId!, run.id, - { tool_outputs }, + { tool_outputs } ); await waitForRun(run); @@ -131,10 +131,10 @@ export async function POST(req: Request) { id: message.id, role: 'assistant', content: message.content.filter( - content => content.type === 'text', + (content) => content.type === 'text' ) as Array, }); } - }, + } ); } diff --git a/example/next-app/app/api/chat-with-functions/route.ts b/example/next-app/app/api/chat-with-functions/route.ts index 3436ee5..4be8109 100644 --- a/example/next-app/app/api/chat-with-functions/route.ts +++ b/example/next-app/app/api/chat-with-functions/route.ts @@ -62,7 +62,7 @@ export async function POST(req: Request) { const stream = OpenAIStream(response, { experimental_onFunctionCall: async ( { name, arguments: args }, - createFunctionCallMessages, + createFunctionCallMessages ) => { if (name === 'get_current_weather') { // Call a weather API here diff --git a/example/next-app/app/api/chat/middleware.tsx b/example/next-app/app/api/chat/middleware.tsx index 0d02211..e0cca2d 100644 --- a/example/next-app/app/api/chat/middleware.tsx +++ b/example/next-app/app/api/chat/middleware.tsx @@ -3,21 +3,24 @@ // src/app/middleware.js // or // src/pages/middleware.js -import { NextResponse } from "next/server"; +import { NextResponse } from 'next/server'; export function middleware() { - // retrieve the current response - const res = NextResponse.next() - // add the CORS headers to the response - res.headers.append('Access-Control-Allow-Credentials', "true") - res.headers.append('Access-Control-Allow-Origin', '*') // replace this with your actual origin - res.headers.append('Access-Control-Allow-Methods', 'GET,DELETE,PATCH,POST,PUT') - res.headers.append( - 'Access-Control-Allow-Headers', - 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version' - ) - return res + // retrieve the current response + const res = NextResponse.next(); + // add the CORS headers to the response + res.headers.append('Access-Control-Allow-Credentials', 'true'); + res.headers.append('Access-Control-Allow-Origin', '*'); // replace this with your actual origin + res.headers.append( + 'Access-Control-Allow-Methods', + 'GET,DELETE,PATCH,POST,PUT' + ); + res.headers.append( + 'Access-Control-Allow-Headers', + 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version' + ); + return res; } // specify the path regex to apply the middleware to export const config = { - matcher: '/api/:path*', -} + matcher: '/api/:path*', +}; diff --git a/example/next-app/app/api/chat/route.ts b/example/next-app/app/api/chat/route.ts index 0936c6d..89939ac 100644 --- a/example/next-app/app/api/chat/route.ts +++ b/example/next-app/app/api/chat/route.ts @@ -1,28 +1,28 @@ // /api/chat // ./app/api/chat/route.ts -import OpenAI from "openai"; -import { OpenAIStream, StreamingTextResponse } from "ai"; -import { NextResponse, userAgent } from "next/server"; +import OpenAI from 'openai'; +import { OpenAIStream, StreamingTextResponse } from 'ai'; +import { NextResponse, userAgent } from 'next/server'; // Create an OpenAI API client (that's edge friendly!) const openai = new OpenAI({ - apiKey: process.env.OPENAI_API_KEY || "", + apiKey: process.env.OPENAI_API_KEY || '', }); // IMPORTANT! Set the runtime to edge -export const runtime = "edge"; +export const runtime = 'edge'; export async function POST(req: Request, res: Response) { // Extract the `prompt` from the body of the request const { messages } = await req.json(); const userAgentData = userAgent(req); - const isNativeMobile = userAgentData.ua?.includes("Expo"); + const isNativeMobile = userAgentData.ua?.includes('Expo'); if (!isNativeMobile) { // Ask OpenAI for a streaming chat completion given the prompt const response = await openai.chat.completions.create({ - model: "gpt-3.5-turbo", + model: 'gpt-3.5-turbo', stream: true, messages, }); @@ -33,7 +33,7 @@ export async function POST(req: Request, res: Response) { } else { // Ask OpenAI for a streaming chat completion given the prompt const response = await openai.chat.completions.create({ - model: "gpt-3.5-turbo", + model: 'gpt-3.5-turbo', // Set your provider stream option to be `false` for native stream: false, messages: messages, @@ -44,18 +44,17 @@ export async function POST(req: Request, res: Response) { } export async function OPTIONS(request: Request) { - const allowedOrigin = request.headers.get("origin"); + const allowedOrigin = request.headers.get('origin'); const response = new NextResponse(null, { status: 200, headers: { - "Access-Control-Allow-Origin": allowedOrigin || "*", - "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", - "Access-Control-Allow-Headers": - "Content-Type, Authorization, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version", - "Access-Control-Max-Age": "86400", + 'Access-Control-Allow-Origin': allowedOrigin || '*', + 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', + 'Access-Control-Allow-Headers': + 'Content-Type, Authorization, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version', + 'Access-Control-Max-Age': '86400', }, }); return response; } - diff --git a/example/next-app/app/function-calling/page.tsx b/example/next-app/app/function-calling/page.tsx index 0bfd35f..40499a5 100644 --- a/example/next-app/app/function-calling/page.tsx +++ b/example/next-app/app/function-calling/page.tsx @@ -6,13 +6,13 @@ import { Message, useChat } from 'ai/react'; export default function Chat() { const functionCallHandler: FunctionCallHandler = async ( chatMessages, - functionCall, + functionCall ) => { if (functionCall.name === 'eval_code_in_browser') { if (functionCall.arguments) { // Parsing here does not always work since it seems that some characters in generated code aren't escaped properly. const parsedFunctionCallArguments: { code: string } = JSON.parse( - functionCall.arguments, + functionCall.arguments ); // WARNING: Do NOT do this in real-world applications! eval(parsedFunctionCallArguments.code); diff --git a/example/next-app/app/page.tsx b/example/next-app/app/page.tsx index 34dba4a..f8daa81 100644 --- a/example/next-app/app/page.tsx +++ b/example/next-app/app/page.tsx @@ -7,7 +7,7 @@ export default function Chat() { return (
{messages.length > 0 - ? messages.map(m => ( + ? messages.map((m) => (
{m.role === 'user' ? 'User: ' : 'AI: '} {m.content} diff --git a/example/next-app/app/stream-react-response/asOpenAIMessages.tsx b/example/next-app/app/stream-react-response/asOpenAIMessages.tsx index 50de1eb..af65fa6 100644 --- a/example/next-app/app/stream-react-response/asOpenAIMessages.tsx +++ b/example/next-app/app/stream-react-response/asOpenAIMessages.tsx @@ -2,9 +2,9 @@ import { Message } from 'ai'; import { ChatCompletionMessageParam } from 'openai/resources/chat'; export function asOpenAIMessages( - messages: Message[], + messages: Message[] ): ChatCompletionMessageParam[] { - return messages.map(message => { + return messages.map((message) => { switch (message.role) { case 'system': case 'user': @@ -23,7 +23,7 @@ export function asOpenAIMessages( function_call.name === undefined) ) { throw new Error( - 'Invalid function call in message. Expected a function call object', + 'Invalid function call in message. Expected a function call object' ); } diff --git a/example/next-app/app/vision/page.tsx b/example/next-app/app/vision/page.tsx index 2265d10..18bba85 100644 --- a/example/next-app/app/vision/page.tsx +++ b/example/next-app/app/vision/page.tsx @@ -9,7 +9,7 @@ export default function Chat() { return (
{messages.length > 0 - ? messages.map(m => ( + ? messages.map((m) => (
{m.role === 'user' ? 'User: ' : 'AI: '} {m.content} @@ -18,7 +18,7 @@ export default function Chat() { : null}
{ + onSubmit={(e) => { handleSubmit(e, { data: { imageUrl: diff --git a/example/next-app/next.config.js b/example/next-app/next.config.js index 03d3653..c4e6271 100644 --- a/example/next-app/next.config.js +++ b/example/next-app/next.config.js @@ -4,18 +4,18 @@ const nextConfig = { return [ { // matching all API routes - source: "/api/:path*", + source: '/api/:path*', headers: [ - { key: "Access-Control-Allow-Credentials", value: "true" }, - { key: "Access-Control-Allow-Origin", value: "*" }, // replace this your actual origin + { key: 'Access-Control-Allow-Credentials', value: 'true' }, + { key: 'Access-Control-Allow-Origin', value: '*' }, // replace this your actual origin { - key: "Access-Control-Allow-Methods", - value: "GET,OPTIONS,DELETE,PATCH,POST,PUT", + key: 'Access-Control-Allow-Methods', + value: 'GET,OPTIONS,DELETE,PATCH,POST,PUT', }, { - key: "Access-Control-Allow-Headers", + key: 'Access-Control-Allow-Headers', value: - "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version", + 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version', }, ], }, diff --git a/package.json b/package.json index d7058cc..8be8e0c 100644 --- a/package.json +++ b/package.json @@ -29,11 +29,12 @@ "example": "yarn workspace react-native-vercel-ai-example", "test": "jest", "typecheck": "tsc --noEmit", - "lint": "eslint \"**/*.{js,ts,tsx}\"", + "lint": "eslint \"**/*.{js,ts,jsx,tsx}\"", "clean": "del-cli lib", "prepare": "bob build", "release": "release-it", - "clean:node-modules": "find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +" + "clean:node-modules": "find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +", + "format": "prettier --write \"**/*.{js,ts,jsx,tsx,json,md,mdx}\"" }, "keywords": [ "react-native", @@ -50,6 +51,11 @@ "publishConfig": { "registry": "https://registry.npmjs.org/" }, + "dependencies": { + "ai": "^2.2.26", + "nanoid": "^5.0.2", + "swr": "^2.2.4" + }, "devDependencies": { "@commitlint/config-conventional": "^17.0.2", "@evilmartians/lefthook": "^1.5.0", @@ -154,10 +160,5 @@ } ] ] - }, - "dependencies": { - "ai": "^2.2.26", - "nanoid": "^5.0.2", - "swr": "^2.2.4" } } diff --git a/src/shared/utils.test.ts b/src/shared/utils.test.ts index ca2fa95..f3954d4 100644 --- a/src/shared/utils.test.ts +++ b/src/shared/utils.test.ts @@ -13,10 +13,10 @@ describe('utils', () => { const enqueuedChunks = []; enqueuedChunks.push( - encoder.encode(getStreamString('text', normalDecode(chunk1))), + encoder.encode(getStreamString('text', normalDecode(chunk1))) ); enqueuedChunks.push( - encoder.encode(getStreamString('text', normalDecode(chunk2))), + encoder.encode(getStreamString('text', normalDecode(chunk2))) ); let fullDecodedString = ''; diff --git a/src/use-chat.ts b/src/use-chat.ts index f9f48c8..a2785ba 100644 --- a/src/use-chat.ts +++ b/src/use-chat.ts @@ -140,7 +140,7 @@ const getResponse = async ( } // if (!res.body) { - // throw new Error("The response body is empty."); + // throw new Error('The response body is empty.'); // } const createdAt = new Date(); diff --git a/src/use-completion.ts b/src/use-completion.ts index c35948d..0b1870e 100644 --- a/src/use-completion.ts +++ b/src/use-completion.ts @@ -143,7 +143,7 @@ export function useCompletion({ } // if (!res.body) { - // throw new Error("The response body is empty."); + // throw new Error('The response body is empty.'); // } const reader = await res.json(); diff --git a/tsconfig.build.json b/tsconfig.build.json index 999d3f3..2a21c28 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -1,4 +1,3 @@ - { "extends": "./tsconfig", "exclude": ["example"] From 089cfa67e43b5bc7f6bac2746e73c6c0fb5ff1b0 Mon Sep 17 00:00:00 2001 From: Tom Heaton Date: Tue, 26 Mar 2024 13:00:03 +0000 Subject: [PATCH 2/2] chore: more formatting - add `.prettierignore` - format more files --- .gitignore | 5 - .prettierignore | 113 ++++++++++++++++++ .yarnrc.yml | 4 +- .../app/api/chat-with-vision/route.ts | 2 +- example/next-app/app/api/chat/middleware.tsx | 2 + example/next-app/app/api/completion/route.ts | 2 +- example/next-app/app/layout.tsx | 2 +- lefthook.yml | 4 +- src/index.d.ts | 14 ++- src/index.web.ts | 1 - src/shared/types.ts | 1 + src/shared/utils.test.ts | 2 +- src/use-chat.ts | 12 +- src/use-completion.ts | 3 +- 14 files changed, 143 insertions(+), 24 deletions(-) create mode 100644 .prettierignore diff --git a/.gitignore b/.gitignore index 0697aac..aaded80 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ # OSX -# .DS_Store .cosine/ @@ -11,7 +10,6 @@ jsconfig.json # Xcode -# build/ *.pbxuser !default.pbxuser @@ -31,7 +29,6 @@ DerivedData project.xcworkspace # Android/IJ -# .classpath .cxx .gradle @@ -42,14 +39,12 @@ local.properties android.iml # Cocoapods -# example/ios/Pods # Ruby example/vendor/ # node.js -# node_modules/ npm-debug.log yarn-debug.log diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..2baf0bb --- /dev/null +++ b/.prettierignore @@ -0,0 +1,113 @@ +# OSX +.DS_Store + +.cosine/ +# XDE +.expo/ + +# VSCode +.vscode/ +jsconfig.json + +# Xcode +build/ +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata +*.xccheckout +*.moved-aside +DerivedData +*.hmap +*.ipa +*.xcuserstate +project.xcworkspace + +# Android/IJ +.classpath +.cxx +.gradle +.idea +.project +.settings +local.properties +android.iml + +# Cocoapods +example/ios/Pods + +# Ruby +example/vendor/ + +# node.js +node_modules/ +npm-debug.log +yarn-debug.log +yarn-error.log + +# BUCK +buck-out/ +\.buckd/ +android/app/libs +android/keystores/debug.keystore + +# Yarn +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/sdks +!.yarn/versions + +# Expo +.expo/ + +# Turborepo +.turbo/ + +# generated by bob +lib/ + +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +node_modules +.pnp +.pnp.js + +.yarn/ +# testing +coverage + +# next.js +.next +out + +# production +build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# local env files +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts + + diff --git a/.yarnrc.yml b/.yarnrc.yml index 13215d6..5badb2e 100644 --- a/.yarnrc.yml +++ b/.yarnrc.yml @@ -3,8 +3,8 @@ nmHoistingLimits: workspaces plugins: - path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs - spec: "@yarnpkg/plugin-interactive-tools" + spec: '@yarnpkg/plugin-interactive-tools' - path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs - spec: "@yarnpkg/plugin-workspace-tools" + spec: '@yarnpkg/plugin-workspace-tools' yarnPath: .yarn/releases/yarn-3.6.1.cjs diff --git a/example/next-app/app/api/chat-with-vision/route.ts b/example/next-app/app/api/chat-with-vision/route.ts index 594c9f0..71d80b5 100644 --- a/example/next-app/app/api/chat-with-vision/route.ts +++ b/example/next-app/app/api/chat-with-vision/route.ts @@ -1,6 +1,6 @@ // ./app/api/chat/route.ts -import OpenAI from 'openai'; import { OpenAIStream, StreamingTextResponse } from 'ai'; +import OpenAI from 'openai'; // Create an OpenAI API client (that's edge friendly!) const openai = new OpenAI({ diff --git a/example/next-app/app/api/chat/middleware.tsx b/example/next-app/app/api/chat/middleware.tsx index e0cca2d..51067cc 100644 --- a/example/next-app/app/api/chat/middleware.tsx +++ b/example/next-app/app/api/chat/middleware.tsx @@ -4,6 +4,7 @@ // or // src/pages/middleware.js import { NextResponse } from 'next/server'; + export function middleware() { // retrieve the current response const res = NextResponse.next(); @@ -20,6 +21,7 @@ export function middleware() { ); return res; } + // specify the path regex to apply the middleware to export const config = { matcher: '/api/:path*', diff --git a/example/next-app/app/api/completion/route.ts b/example/next-app/app/api/completion/route.ts index fe80ccc..fc5eb60 100644 --- a/example/next-app/app/api/completion/route.ts +++ b/example/next-app/app/api/completion/route.ts @@ -1,5 +1,5 @@ -import OpenAI from 'openai'; import { OpenAIStream, StreamingTextResponse } from 'ai'; +import OpenAI from 'openai'; // Create an OpenAI API client (that's edge friendly!) const openai = new OpenAI({ diff --git a/example/next-app/app/layout.tsx b/example/next-app/app/layout.tsx index 34624c5..1adb085 100644 --- a/example/next-app/app/layout.tsx +++ b/example/next-app/app/layout.tsx @@ -1,5 +1,5 @@ -import './globals.css'; import { Inter } from 'next/font/google'; +import './globals.css'; const inter = Inter({ subsets: ['latin'] }); diff --git a/lefthook.yml b/lefthook.yml index 065a491..78cd6c1 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -3,11 +3,11 @@ pre-commit: commands: lint: files: git diff --name-only @{push} - glob: "*.{js,ts,jsx,tsx}" + glob: '*.{js,ts,jsx,tsx}' run: npx eslint {files} types: files: git diff --name-only @{push} - glob: "*.{js,ts, jsx, tsx}" + glob: '*.{js,ts, jsx, tsx}' run: npx tsc --noEmit commit-msg: parallel: true diff --git a/src/index.d.ts b/src/index.d.ts index a4aba16..1cd2372 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -1,3 +1,5 @@ +import * as react_jsx_runtime from 'react/jsx-runtime'; + interface FunctionCall { /** * The arguments to call the function with, as generated by the model in JSON @@ -54,28 +56,34 @@ interface Message { */ function_call?: string | FunctionCall; } + type CreateMessage = Omit & { id?: Message['id']; }; + type ChatRequest = { messages: Message[]; options?: RequestOptions; functions?: Array; function_call?: FunctionCall; }; + type FunctionCallHandler = ( chatMessages: Message[], functionCall: FunctionCall ) => Promise; + type RequestOptions = { headers?: Record | Headers; body?: object; }; + type ChatRequestOptions = { options?: RequestOptions; functions?: Array; function_call?: FunctionCall; }; + type UseChatOptions = { /** * The API endpoint that accepts a `{ messages: Message[] }` object and returns @@ -144,6 +152,7 @@ type UseChatOptions = { */ sendExtraMessageFields?: boolean; }; + type UseCompletionOptions = { /** * The API endpoint that accepts a `{ prompt: string }` object and returns @@ -211,6 +220,7 @@ type UseCompletionOptions = { * between the rows, but flushing the full payload on each row. */ type UINode = string | JSX.Element | JSX.Element[] | null | undefined; + /** * A utility class for streaming React responses. */ @@ -278,9 +288,11 @@ type UseChatHelpers = { /** Additional data added on the server via StreamData */ data?: any; }; + type StreamingReactResponseAction = (payload: { messages: Message[]; }) => Promise; + declare function useChat({ api, id, @@ -348,6 +360,7 @@ type UseCompletionHelpers = { /** Whether the API request is in progress */ isLoading: boolean; }; + declare function useCompletion({ api, id, @@ -370,7 +383,6 @@ export { useChat, useCompletion, }; -import * as react_jsx_runtime from 'react/jsx-runtime'; type Props = { /** diff --git a/src/index.web.ts b/src/index.web.ts index 4b04e1a..833b9b2 100644 --- a/src/index.web.ts +++ b/src/index.web.ts @@ -1,2 +1 @@ -// export * from '../node_modules/ai/react/dist/index'; export * from 'ai/react/dist/index'; diff --git a/src/shared/types.ts b/src/shared/types.ts index ba113de..fbc7292 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -89,6 +89,7 @@ export type ChatRequestOptions = { }; type RequestCredentials = 'omit' | 'same-origin' | 'include'; + export type UseChatOptions = { /** * The API endpoint that accepts a `{ messages: Message[] }` object and returns diff --git a/src/shared/utils.test.ts b/src/shared/utils.test.ts index f3954d4..235b750 100644 --- a/src/shared/utils.test.ts +++ b/src/shared/utils.test.ts @@ -35,7 +35,7 @@ describe('utils', () => { it('correctly decodes streamed utf8 chunks in simple mode', () => { const decoder = createChunkDecoder(false); - const encoder = new TextEncoder(); + // const encoder = new TextEncoder(); // const prefixChunkUint8 = encoder.encode('0:') const chunk1 = new Uint8Array([226, 153]); const chunk2 = new Uint8Array([165]); diff --git a/src/use-chat.ts b/src/use-chat.ts index a2785ba..68afcd2 100644 --- a/src/use-chat.ts +++ b/src/use-chat.ts @@ -1,19 +1,17 @@ -// @ts-ignore import { useCallback, useEffect, useId, useRef, useState } from 'react'; -import useSWR from 'swr'; import type { KeyedMutator } from 'swr'; -import { nanoid } from './shared/utils'; - +import useSWR from 'swr'; import type { ChatRequest, + ChatRequestOptions, CreateMessage, + FunctionCall, Message, UseChatOptions, - ChatRequestOptions, - FunctionCall, } from './shared/types'; +import { nanoid } from './shared/utils'; -export type { Message, CreateMessage, UseChatOptions }; +export type { CreateMessage, Message, UseChatOptions }; export type UseChatHelpers = { /** Current messages in the chat */ diff --git a/src/use-completion.ts b/src/use-completion.ts index 0b1870e..99ba258 100644 --- a/src/use-completion.ts +++ b/src/use-completion.ts @@ -1,7 +1,6 @@ import { useCallback, useEffect, useId, useRef, useState } from 'react'; import useSWR from 'swr'; - -import type { UseCompletionOptions, RequestOptions } from './shared/types'; +import type { RequestOptions, UseCompletionOptions } from './shared/types'; export type UseCompletionHelpers = { /** The current completion result */