Skip to content

feat (core, react): refactor useChat to use MessageStore #5770

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
105 commits
Select commit Hold shift + click to select a range
a4aa963
WIP
iteratetograceness Apr 14, 2025
b9ab5a4
wip: messages store
iteratetograceness Apr 16, 2025
7f88649
v2
iteratetograceness Apr 16, 2025
d9232fd
fix: tool result
iteratetograceness Apr 16, 2025
8e054e1
undo unnecessary formatting
iteratetograceness Apr 16, 2025
3526bf3
chore: clean up reasoning
iteratetograceness Apr 17, 2025
6f5d55a
fix: step
iteratetograceness Apr 17, 2025
66947be
smol fix
iteratetograceness Apr 17, 2025
81bb42d
Merge branch 'v5' into chat-hook-sync-ext-store
iteratetograceness Apr 17, 2025
787c867
Merge upstream/v5 into chat-hook-sync-ext-store
iteratetograceness Apr 17, 2025
cfd0c39
rename ChatStore, start TDD
iteratetograceness Apr 17, 2025
9ab67ad
flesh out chat store tests
iteratetograceness Apr 18, 2025
1cad64d
maybe: partial state reset
iteratetograceness Apr 18, 2025
b879c8b
fix: step
iteratetograceness Apr 18, 2025
933534c
fix: ux tests
iteratetograceness Apr 18, 2025
40830a9
wip
iteratetograceness Apr 22, 2025
72f7ca2
more tests
iteratetograceness Apr 24, 2025
b9f5348
use chat v2
iteratetograceness Apr 24, 2025
9add3c0
wip
iteratetograceness Apr 27, 2025
49a337b
wip
iteratetograceness Apr 27, 2025
233e996
step logic
iteratetograceness Apr 27, 2025
9d5fdde
oop
iteratetograceness Apr 27, 2025
6a122cf
merge upstream
iteratetograceness Apr 27, 2025
0e112dd
Merge branch 'v5' into chat-hook-sync-ext-store
iteratetograceness Apr 29, 2025
afed9ba
WIP
iteratetograceness Apr 29, 2025
33f4df5
wip: pull critical changes before merge conflicts
iteratetograceness May 9, 2025
5f3a254
fix(react-native): support experimental_attachments without FileList …
lgrammel Apr 30, 2025
2bd0d65
chore (ai/mcp): add `assertCapability` method to experimental MCP cli…
lgrammel Apr 30, 2025
c5af8a6
chore (ai): replace `Message` with `UIMessage` (#6061)
lgrammel Apr 30, 2025
f961d93
chore (ai): remove "data" UIMessage role (#6063)
lgrammel Apr 30, 2025
7fcd13b
fix (react): integrate addToolResult into UseChatHelpers type without…
cgoinglove Apr 30, 2025
68d92fe
fix (provider/gladia): correct workspace dependencies (#6065)
lgrammel Apr 30, 2025
d1bb77b
fix (release): update changeset (#6066)
lgrammel Apr 30, 2025
64aa78b
chore (ai): rename reasoning UI parts 'reasoning' property to 'text' …
lgrammel Apr 30, 2025
30b89b7
Version Packages (canary) (#6040)
github-actions[bot] Apr 30, 2025
bc431d6
chore (ai): change file to parts to use urls instead of data (#6068)
lgrammel Apr 30, 2025
ec8f135
chore (ai): remove redundant `mimeType` property (#6070)
lgrammel Apr 30, 2025
ae6b97e
feat (provider): add `providerMetadata` to `ImageModelV2` interface (…
gr2m Apr 30, 2025
5053fc2
chore(providers/openai): re-introduce logprobs as providerMetadata (#…
samdenty Apr 30, 2025
13d8103
test (openai): update snapshot (#6086)
gr2m May 1, 2025
990ae52
feat (ui/react): support resuming an ongoing stream (#6053)
jeremyphilemon May 1, 2025
c0482f6
chore (ai): replace useChat attachments with file ui parts (#6071)
lgrammel May 1, 2025
a3eebf5
fix (docs): update formatting in useChat reference docs (#6100)
jeremyphilemon May 1, 2025
8644ac1
core (ai/mcp): update experimental MCP client documentation for Strea…
samdenty May 2, 2025
54d45bd
feat(docs): add Weave observability provider (#6029) (#6094)
samdenty May 2, 2025
306084d
fix(providers/openai): zod parse error with function (#6074) (#6095)
samdenty May 2, 2025
14f373a
feat (docs): add Sarvam community provider (#6079) (#6096)
samdenty May 2, 2025
cc64187
feat (docs): add Dify community provider (#4084) (#6067) (#6103)
lgrammel May 2, 2025
18ded47
feat (ai): add filename to file ui parts (#6104)
lgrammel May 2, 2025
d6e608b
chore (ai): rename CoreMessage to ModelMessage (#6105)
lgrammel May 2, 2025
dde3570
chore (provider-utils): rename TestServerCall.requestBody to requestB…
lgrammel May 2, 2025
a4f0596
Version Packages (canary) (#6069)
github-actions[bot] May 2, 2025
30bfaba
chore: update references to use ai-sdk.dev (#6076) (#6107)
samdenty May 2, 2025
94eb2ed
docs (ai): add notes on schema .optional() (#6111)
lgrammel May 2, 2025
3099525
chore (ai): move maxSteps into UseChatOptions (#6113)
lgrammel May 2, 2025
39288b7
fix(providers/openai): logprobs for stream alongside completion model…
samdenty May 2, 2025
30a3676
chore (ai): remove useChat keepLastMessageOnError (#6114)
lgrammel May 2, 2025
35f15bc
chore (ai): remove outdated typecasts (#6116)
lgrammel May 2, 2025
72899ed
chore (provider): improve jsdoc comments (#6117)
lgrammel May 2, 2025
bdb6689
chore (provider-utils): return IdGenerator interface (#6118)
lgrammel May 2, 2025
be53dd2
feat(embed-many): respect supportsParallelCalls & concurrency (#6108)
samdenty May 2, 2025
ff6de2c
chore(provider-utils): move ToolResultContent to provider-utils (#6121)
samdenty May 2, 2025
9c871fa
chore (ai): remove sendExtraMessageFields (#6120)
lgrammel May 2, 2025
94d492b
fix(providers): always use optional instead of mix of nullish for pro…
samdenty May 3, 2025
0c0e67b
test (ai): use `mock-provider` instead of `openai` to match used `Moc…
gr2m May 4, 2025
08de0c1
feat (provider): support reasoning tokens, cached input tokens, total…
lgrammel May 5, 2025
8430609
Version Packages (canary) (#6115)
github-actions[bot] May 5, 2025
2e2a955
chore (ai): remove content from ui messages (#6145)
lgrammel May 5, 2025
f02bb05
chore (ai): remove IdGenerator duplication (#6147)
lgrammel May 5, 2025
41609fe
chore (build): fix typecheck setup (#6151)
lgrammel May 5, 2025
2217b37
chore (ai): remove StreamData and mergeStreams (#6150)
lgrammel May 5, 2025
a4de660
chore (ai): remove StreamCallbacks.onCompletion (#6152)
lgrammel May 5, 2025
3fabc90
chore (ai): rename DataStreamString to DataStreamText (#6153)
lgrammel May 5, 2025
3262a5a
chore: remove misplaced changeset (#6154)
lgrammel May 5, 2025
7f2e805
chore (ai): simplify streamText data stream apis (#6155)
lgrammel May 5, 2025
cde9ca4
chore (ai): move data stream related sources to `src/data-stream` (#6…
lgrammel May 5, 2025
a9b308b
chore: add note on provider method names (#6160)
lgrammel May 5, 2025
37e7cbd
chore (ai): data stream updates (#6158)
lgrammel May 6, 2025
976744b
chore (ai): refactor header preparation (#6165)
lgrammel May 6, 2025
c9ad5ec
chore (ui): data stream protocol v2 with SSEs (#6167)
lgrammel May 6, 2025
388a814
Version Packages (canary) (#6146)
github-actions[bot] May 6, 2025
c661754
chore(providers/openai): enable strict compatibility by default (#6169)
samdenty May 6, 2025
7a4255c
refactoring (ai): move errors to src/error (#6173)
lgrammel May 6, 2025
2d9f47e
chore (ai): move ui-related files to src/ui (#6187)
lgrammel May 7, 2025
6253ada
chore (ai): remove automatic conversion of UI messages to model messa…
lgrammel May 7, 2025
0db0a90
feat (ai): support model message array in prompt (#6189)
lgrammel May 7, 2025
f1ce24b
chore (ai): rename DataStreamToSSETransformStream to JsonToSseTransfo…
lgrammel May 7, 2025
fa1cb1e
feat (ai): add content to generateText result (#6192)
lgrammel May 7, 2025
c9d947e
chore (ui): rename RequestOptions to CompletionRequestOptions (#6194)
lgrammel May 7, 2025
5c739de
chore (rsc): move HANGING_STREAM_WARNING_TIME constant into @ai-sdk/r…
lgrammel May 7, 2025
29a3bb9
chore (ai): move utils to src/util (#6196)
lgrammel May 7, 2025
0d43fba
chore (ai): restructure index files and entry point (#6198)
lgrammel May 7, 2025
409d1ee
fix(provider-utils): fix SSE parser bug (CRLF) (#6197) (#6200)
lgrammel May 7, 2025
eff70cc
fix (docs): typo (#6164) (#6201)
lgrammel May 7, 2025
b318e18
chore (ai): push stream-callbacks into langchain/llamaindex adapters …
lgrammel May 7, 2025
f3cb8a6
chore (ai): remove getUIText() (#6202)
lgrammel May 7, 2025
0603099
chore (ui): inline/remove ChatRequest type (#6207)
lgrammel May 7, 2025
fd57f95
feat (ai): add content to streamText result (#6209)
lgrammel May 7, 2025
9b42e71
Version Packages (canary) (#6172)
github-actions[bot] May 7, 2025
a5af996
fix (ai)!: move image model settings into `generateImage({maxImagesPe…
gr2m May 7, 2025
8a00804
chore (docs): update code snippets to handle race condition when resu…
lgrammel May 8, 2025
412355b
fix (build): fix changeset (#6231)
lgrammel May 8, 2025
13f11c9
chore (ai): remove default setting values (#6223)
lgrammel May 8, 2025
c7ddff1
merge conflicts
iteratetograceness May 9, 2025
3ca05bf
Merge branch 'v5' into chat-hook-sync-ext-store
iteratetograceness May 9, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
154 changes: 154 additions & 0 deletions examples/next-openai/app/use-chat-v2/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
'use client';

import { useChatV2 } from '@ai-sdk/react';

export default function Chat() {
const { messages, input, handleInputChange, handleSubmit, addToolResult } =
useChatV2({
api: '/api/use-chat-tools',
maxSteps: 5,

// run client-side tools that are automatically executed:
async onToolCall({ toolCall }) {
// artificial 2 second delay
await new Promise(resolve => setTimeout(resolve, 2000));

if (toolCall.toolName === 'getLocation') {
const cities = [
'New York',
'Los Angeles',
'Chicago',
'San Francisco',
];
return cities[Math.floor(Math.random() * cities.length)];
}
},

onError(error) {
console.error(error);
},
});

return (
<div className="flex flex-col w-full max-w-md py-24 mx-auto stretch">
{messages?.map(message => (
<div key={message.id} className="whitespace-pre-wrap">
<strong>{`${message.role}: `}</strong>
{message.parts.map((part, index) => {
switch (part.type) {
case 'text':
return <div key={index}>{part.text}</div>;
case 'step-start':
return index > 0 ? (
<div key={index} className="text-gray-500">
<hr className="my-2 border-gray-300" />
</div>
) : null;
case 'tool-invocation': {
switch (part.toolInvocation.toolName) {
case 'askForConfirmation': {
switch (part.toolInvocation.state) {
case 'call':
return (
<div key={index} className="text-gray-500">
{part.toolInvocation.args.message}
<div className="flex gap-2">
<button
className="px-4 py-2 font-bold text-white bg-blue-500 rounded hover:bg-blue-700"
onClick={() =>
addToolResult({
toolCallId: part.toolInvocation.toolCallId,
result: 'Yes, confirmed.',
})
}
>
Yes
</button>
<button
className="px-4 py-2 font-bold text-white bg-red-500 rounded hover:bg-red-700"
onClick={() =>
addToolResult({
toolCallId: part.toolInvocation.toolCallId,
result: 'No, denied',
})
}
>
No
</button>
</div>
</div>
);
case 'result':
return (
<div key={index} className="text-gray-500">
Location access allowed:{' '}
{part.toolInvocation.result}
</div>
);
}
break;
}

case 'getLocation': {
switch (part.toolInvocation.state) {
case 'call':
return (
<div key={index} className="text-gray-500">
Getting location...
</div>
);
case 'result':
return (
<div key={index} className="text-gray-500">
Location: {part.toolInvocation.result}
</div>
);
}
break;
}

case 'getWeatherInformation': {
switch (part.toolInvocation.state) {
// example of pre-rendering streaming tool calls:
case 'partial-call':
return (
<pre key={index}>
{JSON.stringify(part.toolInvocation, null, 2)}
</pre>
);
case 'call':
return (
<div key={index} className="text-gray-500">
Getting weather information for{' '}
{part.toolInvocation.args.city}...
</div>
);
case 'result':
return (
<div key={index} className="text-gray-500">
Weather in {part.toolInvocation.args.city}:{' '}
{part.toolInvocation.result}
</div>
);
}
break;
}
}
}
}
})}
<br />
</div>
))}

<form onSubmit={handleSubmit}>
<input
className="fixed bottom-0 w-full max-w-md p-2 mb-8 border border-gray-300 rounded shadow-xl"
value={input}
placeholder="Say something..."
onChange={handleInputChange}
/>
</form>
</div>
);
}
2 changes: 1 addition & 1 deletion packages/ai/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@
"@opentelemetry/api": "1.9.0"
},
"devDependencies": {
"@types/json-schema": "7.0.15",
"@edge-runtime/vm": "^5.0.0",
"@types/json-schema": "7.0.15",
"@types/node": "20.17.24",
"@vercel/ai-tsconfig": "workspace:*",
"eslint": "8.57.1",
Expand Down
110 changes: 110 additions & 0 deletions packages/ai/src/ui/call-chat-api-v2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { IdGenerator, JSONValue, UseChatOptions } from '../types';
import { ChatStore } from './chat-store';
import { processChatResponseV2 } from './process-chat-response-v2';
import { processChatTextResponseV2 } from './process-chat-text-response-v2';

// use function to allow for mocking in tests:
const getOriginalFetch = () => fetch;

export async function callChatApiV2({
api,
body,
streamProtocol = 'data',
credentials,
headers,
abortController,
restoreMessagesOnFailure,
onResponse,
onUpdate,
onFinish,
onToolCall,
generateId,
fetch = getOriginalFetch(),
store,
chatId,
}: {
api: string;
body: Record<string, any>;
streamProtocol: 'data' | 'text' | undefined;
credentials: RequestCredentials | undefined;
headers: HeadersInit | undefined;
abortController: (() => AbortController | null) | undefined;
restoreMessagesOnFailure: () => void;
onResponse: ((response: Response) => void | Promise<void>) | undefined;
onUpdate: (options: { data: JSONValue[] | undefined }) => void;
onFinish: UseChatOptions['onFinish'];
onToolCall: UseChatOptions['onToolCall'];
generateId: IdGenerator;
fetch: ReturnType<typeof getOriginalFetch> | undefined;
store: ChatStore;
chatId: string;
}) {
const response = await fetch(api, {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
...headers,
},
signal: abortController?.()?.signal,
credentials,
}).catch(err => {
restoreMessagesOnFailure();
throw err;
});

if (onResponse) {
try {
await onResponse(response);
} catch (err) {
throw err;
}
}

if (!response.ok) {
restoreMessagesOnFailure();
throw new Error(
(await response.text()) ?? 'Failed to fetch the chat response.',
);
}

if (!response.body) {
throw new Error('The response body is empty.');
}

switch (streamProtocol) {
case 'text': {
await processChatTextResponseV2({
chatId,
stream: response.body,
update: onUpdate,
onFinish,
generateId,
store,
});
return;
}

case 'data': {
await processChatResponseV2({
chatId,
stream: response.body,
update: onUpdate,
store,
onToolCall,
onFinish({ message, finishReason, usage }) {
if (onFinish && message != null) {
onFinish(message, { usage, finishReason });
}
},
generateId,
});
return;
}

default: {
const exhaustiveCheck: never = streamProtocol;
throw new Error(`Unknown stream protocol: ${exhaustiveCheck}`);
}
}
}
Loading