@genkit-ai/vercel-ai 0.2.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +415 -0
- package/lib/client.d.mts +95 -0
- package/lib/client.d.ts +95 -0
- package/lib/client.js +363 -0
- package/lib/client.js.map +1 -0
- package/lib/client.mjs +345 -0
- package/lib/client.mjs.map +1 -0
- package/lib/index.d.mts +3 -0
- package/lib/index.d.ts +3 -0
- package/lib/index.js +45 -0
- package/lib/index.js.map +1 -0
- package/lib/index.mjs +23 -0
- package/lib/index.mjs.map +1 -0
- package/lib/mapping.d.mts +162 -0
- package/lib/mapping.d.ts +162 -0
- package/lib/mapping.js +280 -0
- package/lib/mapping.js.map +1 -0
- package/lib/mapping.mjs +247 -0
- package/lib/mapping.mjs.map +1 -0
- package/package.json +94 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
# @genkit-ai/vercel-ai
|
|
2
|
+
|
|
3
|
+
A [Genkit](https://github.com/genkit-ai/genkit) plugin that provides a
|
|
4
|
+
[Vercel AI SDK](https://sdk.vercel.ai/) `ChatTransport` for connecting
|
|
5
|
+
`useChat` to Genkit Agents.
|
|
6
|
+
|
|
7
|
+
Use this plugin to build rich chat UIs in React (Next.js, Vite, etc.) that
|
|
8
|
+
stream responses from Genkit agents — including multi-turn conversations,
|
|
9
|
+
tool calls, and interrupt-based human-in-the-loop flows — with zero
|
|
10
|
+
custom plumbing.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @genkit-ai/vercel-ai
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
### Peer dependencies
|
|
19
|
+
|
|
20
|
+
| Package | Required | Notes |
|
|
21
|
+
| ------- | -------- | ----- |
|
|
22
|
+
| `genkit` | ✅ | `>=1.0.0` — the agent API used by this transport lives in the `genkit/beta` subpath. |
|
|
23
|
+
| `ai` | ✅ | `^6.0.0` — provides `ChatTransport`, `UIMessage`, etc. |
|
|
24
|
+
| `@ai-sdk/react` | Client only | `^3.0.0` — only needed where you call the `useChat` hook (browser). |
|
|
25
|
+
|
|
26
|
+
> **Note:** `@ai-sdk/react` is not a declared peer dependency of this package
|
|
27
|
+
> because the server-side entry point does not require it. Install it
|
|
28
|
+
> yourself in any project that uses `useChat`.
|
|
29
|
+
|
|
30
|
+
## Quick start
|
|
31
|
+
|
|
32
|
+
### 1. Define a Genkit agent (server)
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
// app/api/chat/weather/route.ts (Next.js App Router example)
|
|
36
|
+
import { appRoute } from '@genkit-ai/next';
|
|
37
|
+
import { genkit } from 'genkit/beta';
|
|
38
|
+
import { googleAI } from '@genkit-ai/google-genai';
|
|
39
|
+
|
|
40
|
+
const ai = genkit({ plugins: [googleAI()] });
|
|
41
|
+
|
|
42
|
+
const weatherAgent = ai.defineAgent({
|
|
43
|
+
name: 'weatherAgent',
|
|
44
|
+
model: 'googleai/gemini-flash-latest',
|
|
45
|
+
tools: [/* your tools here */],
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
export const POST = appRoute(weatherAgent);
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Or with Express:
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { expressHandler } from '@genkit-ai/express';
|
|
55
|
+
import express from 'express';
|
|
56
|
+
|
|
57
|
+
const app = express();
|
|
58
|
+
app.post('/api/chat/weather', expressHandler(weatherAgent));
|
|
59
|
+
app.listen(3000);
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### 2. Connect from the client
|
|
63
|
+
|
|
64
|
+
```tsx
|
|
65
|
+
'use client';
|
|
66
|
+
import { useChat } from '@ai-sdk/react';
|
|
67
|
+
import { GenkitChatTransport } from '@genkit-ai/vercel-ai/client';
|
|
68
|
+
import { useMemo } from 'react';
|
|
69
|
+
|
|
70
|
+
export default function Chat() {
|
|
71
|
+
const transport = useMemo(
|
|
72
|
+
() => new GenkitChatTransport({ url: '/api/chat/weather' }),
|
|
73
|
+
[]
|
|
74
|
+
);
|
|
75
|
+
// The `useChat` `id` is sent to the agent as its `sessionId`; it must be a UUID.
|
|
76
|
+
const chatId = useMemo(() => crypto.randomUUID(), []);
|
|
77
|
+
|
|
78
|
+
const { messages, input, handleInputChange, handleSubmit, status } =
|
|
79
|
+
useChat({ id: chatId, transport });
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
return (
|
|
83
|
+
<div>
|
|
84
|
+
{messages.map((m) => (
|
|
85
|
+
<div key={m.id}>
|
|
86
|
+
<strong>{m.role}:</strong>{' '}
|
|
87
|
+
{m.parts
|
|
88
|
+
.filter((p) => p.type === 'text')
|
|
89
|
+
.map((p) => p.text)
|
|
90
|
+
.join('')}
|
|
91
|
+
</div>
|
|
92
|
+
))}
|
|
93
|
+
<form onSubmit={handleSubmit}>
|
|
94
|
+
<input value={input} onChange={handleInputChange} />
|
|
95
|
+
<button type="submit" disabled={status !== 'ready'}>
|
|
96
|
+
Send
|
|
97
|
+
</button>
|
|
98
|
+
</form>
|
|
99
|
+
</div>
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
That's it — text streaming, multi-turn history, tool calls, and interrupts
|
|
105
|
+
all work out of the box.
|
|
106
|
+
|
|
107
|
+
## Works with AI Elements
|
|
108
|
+
|
|
109
|
+
This transport is fully compatible with
|
|
110
|
+
[AI Elements](https://elements.ai-sdk.dev/) — the component library and
|
|
111
|
+
custom [shadcn/ui](https://ui.shadcn.com/) registry for building AI-native
|
|
112
|
+
applications. Since `GenkitChatTransport` implements the standard
|
|
113
|
+
`ChatTransport` interface, all AI Elements components (`Conversation`,
|
|
114
|
+
`Message`, `Tool`, `PromptInput`, etc.) work out of the box with Genkit
|
|
115
|
+
agents.
|
|
116
|
+
|
|
117
|
+
```tsx
|
|
118
|
+
'use client';
|
|
119
|
+
import { useChat } from '@ai-sdk/react';
|
|
120
|
+
import { GenkitChatTransport } from '@genkit-ai/vercel-ai/client';
|
|
121
|
+
import { useMemo } from 'react';
|
|
122
|
+
|
|
123
|
+
import {
|
|
124
|
+
Conversation, ConversationContent, ConversationScrollButton,
|
|
125
|
+
} from '@/components/ai-elements/conversation';
|
|
126
|
+
import { Message, MessageContent, MessageResponse } from '@/components/ai-elements/message';
|
|
127
|
+
import {
|
|
128
|
+
PromptInput, PromptInputTextarea, PromptInputFooter, PromptInputSubmit,
|
|
129
|
+
} from '@/components/ai-elements/prompt-input';
|
|
130
|
+
import { Tool, ToolHeader, ToolContent, ToolInput, ToolOutput } from '@/components/ai-elements/tool';
|
|
131
|
+
|
|
132
|
+
export default function Chat() {
|
|
133
|
+
const transport = useMemo(
|
|
134
|
+
() => new GenkitChatTransport({ url: '/api/chat/weather' }),
|
|
135
|
+
[]
|
|
136
|
+
);
|
|
137
|
+
// The `useChat` `id` is sent to the agent as its `sessionId`; it must be a UUID.
|
|
138
|
+
const chatId = useMemo(() => crypto.randomUUID(), []);
|
|
139
|
+
const { messages, status, sendMessage } = useChat({ id: chatId, transport });
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
return (
|
|
143
|
+
<Conversation>
|
|
144
|
+
<ConversationContent>
|
|
145
|
+
{messages.map((message) => (
|
|
146
|
+
<Message key={message.id} from={message.role}>
|
|
147
|
+
<MessageContent>
|
|
148
|
+
{message.parts.map((part, i) => {
|
|
149
|
+
if (part.type === 'text' && part.text) {
|
|
150
|
+
return <MessageResponse key={i}>{part.text}</MessageResponse>;
|
|
151
|
+
}
|
|
152
|
+
if (part.type.startsWith('tool-')) {
|
|
153
|
+
const toolPart = part as any;
|
|
154
|
+
return (
|
|
155
|
+
<Tool key={i}>
|
|
156
|
+
<ToolHeader type={toolPart.type} state={toolPart.state} />
|
|
157
|
+
<ToolContent>
|
|
158
|
+
<ToolInput input={toolPart.input} />
|
|
159
|
+
<ToolOutput output={toolPart.output} />
|
|
160
|
+
</ToolContent>
|
|
161
|
+
</Tool>
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
return null;
|
|
165
|
+
})}
|
|
166
|
+
</MessageContent>
|
|
167
|
+
</Message>
|
|
168
|
+
))}
|
|
169
|
+
</ConversationContent>
|
|
170
|
+
<ConversationScrollButton />
|
|
171
|
+
<PromptInput onSubmit={(msg) => sendMessage({ text: msg.text })}>
|
|
172
|
+
<PromptInputTextarea placeholder="Message..." />
|
|
173
|
+
<PromptInputFooter>
|
|
174
|
+
<div />
|
|
175
|
+
<PromptInputSubmit status={status} />
|
|
176
|
+
</PromptInputFooter>
|
|
177
|
+
</PromptInput>
|
|
178
|
+
</Conversation>
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
See the full working example in
|
|
184
|
+
[`js/testapps/vercel-ai-elements`](../../testapps/vercel-ai-elements) which
|
|
185
|
+
demonstrates multi-agent selection, tool call rendering, and interrupt-based
|
|
186
|
+
human-in-the-loop approval flows — all powered by AI SDK Elements.
|
|
187
|
+
|
|
188
|
+
## Entry points
|
|
189
|
+
|
|
190
|
+
| Import path | Environment | Contents |
|
|
191
|
+
| ----------- | ----------- | -------- |
|
|
192
|
+
| `@genkit-ai/vercel-ai` | Server / shared | Mapping utilities (`mapUIMessageToGenkit`, `mapUIPartToGenkit`, etc.) and re-exported `UIMessage` type |
|
|
193
|
+
| `@genkit-ai/vercel-ai/client` | Browser / client | `GenkitChatTransport` class |
|
|
194
|
+
|
|
195
|
+
The `/client` entry point is browser-safe and has no Node.js dependencies.
|
|
196
|
+
|
|
197
|
+
## API
|
|
198
|
+
|
|
199
|
+
### `GenkitChatTransport`
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
import { GenkitChatTransport } from '@genkit-ai/vercel-ai/client';
|
|
203
|
+
|
|
204
|
+
const transport = new GenkitChatTransport({
|
|
205
|
+
url: '/api/chat/weather',
|
|
206
|
+
headers: { Authorization: 'Bearer token' }, // static headers
|
|
207
|
+
// headers: () => ({ Authorization: `Bearer ${getToken()}` }), // or dynamic
|
|
208
|
+
});
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
#### Configuration
|
|
212
|
+
|
|
213
|
+
| Option | Type | Description |
|
|
214
|
+
| ------ | ---- | ----------- |
|
|
215
|
+
| `url` | `string` | **Required.** URL of the Genkit agent endpoint. |
|
|
216
|
+
| `headers` | `Record<string, string> \| () => Record<string, string>` | Optional HTTP headers to include on every request. Accepts a static object or a function for dynamic values (e.g. auth tokens). |
|
|
217
|
+
|
|
218
|
+
> **The `useChat` `id` must be a bare UUID.** The transport sends the chat
|
|
219
|
+
> `id` to the agent as its Genkit `sessionId`, and the agent server requires
|
|
220
|
+
> session ids to be bare UUIDs. Generate one with `crypto.randomUUID()` and
|
|
221
|
+
> pass it to `useChat({ id })`. If you omit `id`, the AI SDK generates a
|
|
222
|
+
> non-UUID id and the transport will return an error.
|
|
223
|
+
|
|
224
|
+
```tsx
|
|
225
|
+
import { useMemo } from 'react';
|
|
226
|
+
|
|
227
|
+
const chatId = useMemo(() => crypto.randomUUID(), []);
|
|
228
|
+
const { messages, sendMessage } = useChat({ id: chatId, transport });
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
#### Server-managed session state
|
|
232
|
+
|
|
233
|
+
Conversation state is **fully server-managed**. The transport sends the chat
|
|
234
|
+
`id` to the agent as a `sessionId`, and the agent persists per-session state in
|
|
235
|
+
its configured `SessionStore`. Each turn automatically resumes the session's
|
|
236
|
+
latest snapshot — there is **no client-side snapshot bookkeeping** to manage or
|
|
237
|
+
persist, and nothing is lost on a page reload (the server holds the state).
|
|
238
|
+
|
|
239
|
+
To continue an existing conversation, simply reuse the same UUID `id`.
|
|
240
|
+
|
|
241
|
+
#### Restoring a conversation after a reload
|
|
242
|
+
|
|
243
|
+
Because state is server-managed, resuming the *next* turn requires nothing more
|
|
244
|
+
than reusing the same UUID `id`. The only thing the client must rebuild is the
|
|
245
|
+
*rendered* message list (`useChat` owns those, and they are not persisted by
|
|
246
|
+
the transport).
|
|
247
|
+
|
|
248
|
+
Use `messagesFromSnapshot` to rebuild the visible messages from a Genkit
|
|
249
|
+
`SessionSnapshot` (loaded via a `/state` flow keyed by the same `sessionId`):
|
|
250
|
+
|
|
251
|
+
```tsx
|
|
252
|
+
import { useChat } from '@ai-sdk/react';
|
|
253
|
+
import { GenkitChatTransport } from '@genkit-ai/vercel-ai/client';
|
|
254
|
+
import { messagesFromSnapshot } from '@genkit-ai/vercel-ai';
|
|
255
|
+
import { runFlow } from 'genkit/beta/client';
|
|
256
|
+
import { useEffect, useMemo, useState } from 'react';
|
|
257
|
+
|
|
258
|
+
export default function RestoredChat({ sessionId }: { sessionId: string }) {
|
|
259
|
+
const transport = useMemo(() => new GenkitChatTransport({ url: '/api/chat/weather' }), []);
|
|
260
|
+
const [initialMessages, setInitialMessages] = useState([]);
|
|
261
|
+
|
|
262
|
+
useEffect(() => {
|
|
263
|
+
(async () => {
|
|
264
|
+
// Load the latest snapshot for this session (returns a SessionSnapshot).
|
|
265
|
+
const snapshot = await runFlow({ url: '/api/chat/weather/state', input: sessionId });
|
|
266
|
+
// Rebuild the visible message list from the snapshot.
|
|
267
|
+
setInitialMessages(messagesFromSnapshot(snapshot.state.messages));
|
|
268
|
+
})();
|
|
269
|
+
}, [sessionId]);
|
|
270
|
+
|
|
271
|
+
// Reuse the same UUID `id` so the next turn resumes the server-side session.
|
|
272
|
+
const { messages, sendMessage } = useChat({ id: sessionId, transport, messages: initialMessages });
|
|
273
|
+
// ...render messages, send new turns — continuity is preserved.
|
|
274
|
+
}
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
`messagesFromSnapshot` merges Genkit's separate tool request / tool response
|
|
278
|
+
messages into single AI SDK tool parts (so each tool call renders as one
|
|
279
|
+
element), maps `reasoning` and `media` parts, preserves part `metadata`, and
|
|
280
|
+
emits any unresolved tool request (e.g. a pending interrupt) in the
|
|
281
|
+
`input-available` state so the UI can still resolve it.
|
|
282
|
+
|
|
283
|
+
> **Tip:** the `sessionId` you load the snapshot with must be the same UUID you
|
|
284
|
+
> pass as the `useChat` `id`, so the rendered messages and the server-side
|
|
285
|
+
> session stay in sync.
|
|
286
|
+
|
|
287
|
+
#### Regenerating a response
|
|
288
|
+
|
|
289
|
+
When the UI triggers a regeneration (the AI SDK sends
|
|
290
|
+
`trigger: 'regenerate-message'`), the transport re-runs the last user message
|
|
291
|
+
as a **fresh turn** against the current server-side session state. This
|
|
292
|
+
produces a new answer to the same prompt. Because state is server-managed by
|
|
293
|
+
`sessionId`, there is no client-side snapshot pointer to rewind to — the
|
|
294
|
+
regenerated turn is appended to the session like any other turn.
|
|
295
|
+
|
|
296
|
+
#### How it works
|
|
297
|
+
|
|
298
|
+
1. **Sends messages** via Genkit's `streamFlow` client — a browser-safe HTTP
|
|
299
|
+
client that POSTs to the agent endpoint and reads the NDJSON streaming
|
|
300
|
+
response.
|
|
301
|
+
2. **Transforms** Genkit's `AgentStreamChunk` events into Vercel AI SDK
|
|
302
|
+
`UIMessageChunk` events (`text-delta`, `tool-input-available`,
|
|
303
|
+
`tool-output-available`, etc.).
|
|
304
|
+
3. **Sends the session id** — the transport passes `init: { sessionId: chatId }`
|
|
305
|
+
to the agent, which persists per-session state server-side and resumes the
|
|
306
|
+
session's latest snapshot on each turn. No client-side snapshot tracking is
|
|
307
|
+
needed.
|
|
308
|
+
4. **Handles interrupts** — when an agent pauses for human input (via
|
|
309
|
+
`defineInterrupt`), the transport surfaces the pending tool call to the UI.
|
|
310
|
+
On the next `sendMessages` call the resolved tool results are detected
|
|
311
|
+
directly from the message history, and the transport automatically sends a
|
|
312
|
+
`resume` payload instead of a new message.
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
### Interrupts (human-in-the-loop)
|
|
316
|
+
|
|
317
|
+
Genkit agents can **pause** mid-run to ask a human for input via
|
|
318
|
+
`defineInterrupt` (or a tool that calls `interrupt()`). When this happens,
|
|
319
|
+
the transport surfaces the paused tool call to `useChat` as a tool part in
|
|
320
|
+
the `input-available` state. There are two ways to resolve it:
|
|
321
|
+
|
|
322
|
+
1. **Respond** — supply the tool's output directly (the human's decision
|
|
323
|
+
_is_ the result). This is what a `defineInterrupt` tool expects.
|
|
324
|
+
2. **Restart** — ask the agent to **re-run** the tool server-side, optionally
|
|
325
|
+
attaching metadata. Useful for tools that `interrupt()` until confirmed and
|
|
326
|
+
then compute a real result on resume (their `resumed` argument is set).
|
|
327
|
+
|
|
328
|
+
Both are driven by the AI SDK's native HITL primitives — `addToolResult` plus
|
|
329
|
+
`sendAutomaticallyWhen` — so no manual `setMessages`/`flushSync` is needed:
|
|
330
|
+
|
|
331
|
+
```tsx
|
|
332
|
+
import { useChat } from '@ai-sdk/react';
|
|
333
|
+
import {
|
|
334
|
+
GenkitChatTransport,
|
|
335
|
+
restartInterrupt,
|
|
336
|
+
} from '@genkit-ai/vercel-ai/client';
|
|
337
|
+
import { lastAssistantMessageIsCompleteWithToolCalls } from 'ai';
|
|
338
|
+
|
|
339
|
+
const { messages, addToolResult } = useChat({
|
|
340
|
+
transport: new GenkitChatTransport({ url: '/api/chat/banking' }),
|
|
341
|
+
// Auto-resume once every paused tool call has a result.
|
|
342
|
+
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
// 1. Respond: provide the tool output (resume.respond).
|
|
346
|
+
addToolResult({
|
|
347
|
+
tool: 'userApproval',
|
|
348
|
+
toolCallId,
|
|
349
|
+
output: { approved: true, feedback: 'Looks good' },
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
// 2. Restart: re-run the tool (resume.restart). The metadata becomes the
|
|
353
|
+
// tool's `resumed` argument server-side.
|
|
354
|
+
addToolResult({
|
|
355
|
+
tool: 'getExchangeRate',
|
|
356
|
+
toolCallId,
|
|
357
|
+
output: restartInterrupt({ confirmedAt: Date.now() }),
|
|
358
|
+
});
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
> **Note:** Genkit interrupts map to the AI SDK's `addToolResult` flow, **not**
|
|
362
|
+
> the tool-_approval_ flow (`needsApproval` / `addToolApprovalResponse`). A
|
|
363
|
+
> Genkit interrupt never executes server-side on its own — the value you pass
|
|
364
|
+
> to `addToolResult` _is_ the resolution. Use `restartInterrupt()` when you
|
|
365
|
+
> want the agent to re-run the tool instead of accepting a supplied output.
|
|
366
|
+
|
|
367
|
+
See the full working example in
|
|
368
|
+
[`js/testapps/vercel-ai-elements`](../../testapps/vercel-ai-elements), which
|
|
369
|
+
demonstrates both the approval (`userApproval`) and restart (`getExchangeRate`)
|
|
370
|
+
flows.
|
|
371
|
+
|
|
372
|
+
### Mapping utilities
|
|
373
|
+
|
|
374
|
+
The root entry point (`@genkit-ai/vercel-ai`) exports mapping functions
|
|
375
|
+
between Vercel AI SDK `UIMessage` types and Genkit `MessageData`, plus
|
|
376
|
+
helper functions used by the transport:
|
|
377
|
+
|
|
378
|
+
| Function | Direction | Description |
|
|
379
|
+
| -------- | --------- | ----------- |
|
|
380
|
+
| `mapUIMessageToGenkit(msg)` | UI → Genkit | Convert a Vercel `UIMessage` to a Genkit `MessageData` |
|
|
381
|
+
| `mapUIPartToGenkit(part)` | UI → Genkit | Convert a single `UIMessagePart` to Genkit `Part[]` |
|
|
382
|
+
| `messagesFromSnapshot(msgs)` | Genkit → UI | Convert a `SessionSnapshot`'s `state.messages` into `UIMessage[]` for rehydrating `useChat` (pairs tool requests/responses, preserves metadata) |
|
|
383
|
+
| `mapGenkitMessageToUI(msg)` | Genkit → UI | Convert a single Genkit `MessageData` into a `UIMessage` |
|
|
384
|
+
| `extractResolvedToolResults(msgs)` | — | Extract resolved tool invocation results from the message array |
|
|
385
|
+
| `findLastUserMessage(msgs)` | — | Find the last user message in a `UIMessage[]` |
|
|
386
|
+
|
|
387
|
+
Tool/part metadata is preserved in both directions: `mapUIPartToGenkit`
|
|
388
|
+
carries a UI part's `metadata` onto the Genkit part, and `messagesFromSnapshot`
|
|
389
|
+
carries a Genkit part's `metadata` back onto the UI part.
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
The `UIMessage` type is also re-exported from the `ai` package for convenience.
|
|
393
|
+
|
|
394
|
+
## Features
|
|
395
|
+
|
|
396
|
+
- **Text streaming** — streams token-by-token text deltas to the UI
|
|
397
|
+
- **Multi-turn conversations** — automatic server-managed session continuity keyed by the `useChat` `id` (`sessionId`)
|
|
398
|
+
- **Tool calls** — surfaces tool inputs and outputs as they happen
|
|
399
|
+
|
|
400
|
+
- **Interrupts (human-in-the-loop)** — first-class support for `defineInterrupt` tools; pause and resume flows with user input
|
|
401
|
+
- **Custom headers** — static or dynamic headers for authentication
|
|
402
|
+
- **Browser-safe** — the `/client` entry point has no Node.js dependencies
|
|
403
|
+
- **Zero config** — no `ChatSessionStore` needed on the client side
|
|
404
|
+
|
|
405
|
+
## Requirements
|
|
406
|
+
|
|
407
|
+
- Genkit `>=1.0.0` — the agent API (`defineAgent`, `streamFlow`) used by this
|
|
408
|
+
transport is exposed via the `genkit/beta` subpath of the main `1.x` package.
|
|
409
|
+
- Vercel AI SDK `>=6.0.0` (for `useChat` with `ChatTransport`)
|
|
410
|
+
- `@ai-sdk/react` `>=3.0.0` (client-side, for the `useChat` hook)
|
|
411
|
+
- Node.js `>=20` (server-side)
|
|
412
|
+
|
|
413
|
+
## License
|
|
414
|
+
|
|
415
|
+
Apache-2.0 — see [LICENSE](./LICENSE).
|