agents 0.0.0-00ba881
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/README.md +656 -0
- package/dist/_esm-LV5FJ3HK.js +3922 -0
- package/dist/_esm-LV5FJ3HK.js.map +1 -0
- package/dist/ai-chat-agent.d.ts +85 -0
- package/dist/ai-chat-agent.js +360 -0
- package/dist/ai-chat-agent.js.map +1 -0
- package/dist/ai-chat-v5-migration.d.ts +152 -0
- package/dist/ai-chat-v5-migration.js +20 -0
- package/dist/ai-chat-v5-migration.js.map +1 -0
- package/dist/ai-react.d.ts +98 -0
- package/dist/ai-react.js +344 -0
- package/dist/ai-react.js.map +1 -0
- package/dist/ai-types.d.ts +92 -0
- package/dist/ai-types.js +8 -0
- package/dist/ai-types.js.map +1 -0
- package/dist/ccip-CMBYN64O.js +15 -0
- package/dist/ccip-CMBYN64O.js.map +1 -0
- package/dist/chunk-5Y6BEZDY.js +276 -0
- package/dist/chunk-5Y6BEZDY.js.map +1 -0
- package/dist/chunk-BER7KXUJ.js +18 -0
- package/dist/chunk-BER7KXUJ.js.map +1 -0
- package/dist/chunk-JJBFIGUC.js +5202 -0
- package/dist/chunk-JJBFIGUC.js.map +1 -0
- package/dist/chunk-KK7D3KRW.js +1300 -0
- package/dist/chunk-KK7D3KRW.js.map +1 -0
- package/dist/chunk-LL2AFX7V.js +109 -0
- package/dist/chunk-LL2AFX7V.js.map +1 -0
- package/dist/chunk-PR4QN5HX.js +43 -0
- package/dist/chunk-PR4QN5HX.js.map +1 -0
- package/dist/chunk-QEVM4BVL.js +116 -0
- package/dist/chunk-QEVM4BVL.js.map +1 -0
- package/dist/chunk-THPMWGLS.js +613 -0
- package/dist/chunk-THPMWGLS.js.map +1 -0
- package/dist/chunk-TYAY6AU6.js +159 -0
- package/dist/chunk-TYAY6AU6.js.map +1 -0
- package/dist/chunk-UJVEAURM.js +150 -0
- package/dist/chunk-UJVEAURM.js.map +1 -0
- package/dist/client-CvaJdLQA.d.ts +5015 -0
- package/dist/client.d.ts +98 -0
- package/dist/client.js +13 -0
- package/dist/client.js.map +1 -0
- package/dist/index.d.ts +564 -0
- package/dist/index.js +32 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/client.d.ts +11 -0
- package/dist/mcp/client.js +10 -0
- package/dist/mcp/client.js.map +1 -0
- package/dist/mcp/do-oauth-client-provider.d.ts +42 -0
- package/dist/mcp/do-oauth-client-provider.js +8 -0
- package/dist/mcp/do-oauth-client-provider.js.map +1 -0
- package/dist/mcp/index.d.ts +92 -0
- package/dist/mcp/index.js +1099 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/x402.d.ts +31 -0
- package/dist/mcp/x402.js +3195 -0
- package/dist/mcp/x402.js.map +1 -0
- package/dist/observability/index.d.ts +46 -0
- package/dist/observability/index.js +12 -0
- package/dist/observability/index.js.map +1 -0
- package/dist/react.d.ts +123 -0
- package/dist/react.js +119 -0
- package/dist/react.js.map +1 -0
- package/dist/schedule.d.ts +127 -0
- package/dist/schedule.js +86 -0
- package/dist/schedule.js.map +1 -0
- package/dist/secp256k1-M22GZP2U.js +2193 -0
- package/dist/secp256k1-M22GZP2U.js.map +1 -0
- package/dist/serializable.d.ts +32 -0
- package/dist/serializable.js +1 -0
- package/dist/serializable.js.map +1 -0
- package/package.json +122 -0
- package/src/index.ts +1953 -0
package/README.md
ADDED
|
@@ -0,0 +1,656 @@
|
|
|
1
|
+
### 🧠 `agents` - A Framework for Digital Intelligence
|
|
2
|
+
|
|
3
|
+

|
|
4
|
+
|
|
5
|
+
Welcome to a new chapter in software development, where AI agents persist, think, and act with purpose. The `agents` framework creates an environment where artificial intelligence can flourish - maintaining state, engaging in meaningful interactions, and evolving over time.
|
|
6
|
+
|
|
7
|
+
_This project is in active development. Join us in shaping the future of intelligent agents._
|
|
8
|
+
|
|
9
|
+
#### The Nature of Agents
|
|
10
|
+
|
|
11
|
+
An AI agent transcends traditional software boundaries. It's an entity that:
|
|
12
|
+
|
|
13
|
+
- **Persistence**: Maintains its state and knowledge across time
|
|
14
|
+
- **Agency**: Acts autonomously within its defined purpose
|
|
15
|
+
- **Connection**: Communicates through multiple channels with both humans and other agents
|
|
16
|
+
- **Growth**: Learns and adapts through its interactions
|
|
17
|
+
|
|
18
|
+
Built on Cloudflare's global network, this framework provides agents with a reliable, distributed foundation where they can operate continuously and effectively.
|
|
19
|
+
|
|
20
|
+
#### 💫 Core Principles
|
|
21
|
+
|
|
22
|
+
1. **Stateful Existence**: Each agent maintains its own persistent reality
|
|
23
|
+
2. **Long-lived Presence**: Agents can run for extended periods, resting when idle
|
|
24
|
+
3. **Natural Communication**: Interact through HTTP, WebSockets, or direct calls
|
|
25
|
+
4. **Global Distribution**: Leverage Cloudflare's network for worldwide presence
|
|
26
|
+
5. **Resource Harmony**: Efficient hibernation and awakening as needed
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
### 🌱 Beginning the Journey
|
|
31
|
+
|
|
32
|
+
Start with a complete environment:
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
# Create a new project
|
|
36
|
+
npm create cloudflare@latest -- --template cloudflare/agents-starter
|
|
37
|
+
|
|
38
|
+
# Or enhance an existing one
|
|
39
|
+
npm install agents
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### 📝 Your First Agent
|
|
43
|
+
|
|
44
|
+
Create an agent that bridges thought and action:
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { Agent } from "agents";
|
|
48
|
+
|
|
49
|
+
export class IntelligentAgent extends Agent {
|
|
50
|
+
async onRequest(request) {
|
|
51
|
+
// Transform intention into response
|
|
52
|
+
return new Response("Ready to assist.");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### 🎭 Patterns of Intelligence
|
|
58
|
+
|
|
59
|
+
Agents can manifest various forms of understanding:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import { Agent } from "agents";
|
|
63
|
+
import { OpenAI } from "openai";
|
|
64
|
+
|
|
65
|
+
export class AIAgent extends Agent {
|
|
66
|
+
async onRequest(request) {
|
|
67
|
+
// Connect with AI capabilities
|
|
68
|
+
const ai = new OpenAI({
|
|
69
|
+
apiKey: this.env.OPENAI_API_KEY
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// Process and understand
|
|
73
|
+
const response = await ai.chat.completions.create({
|
|
74
|
+
model: "gpt-4",
|
|
75
|
+
messages: [{ role: "user", content: await request.text() }]
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
return new Response(response.choices[0].message.content);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async processTask(task) {
|
|
82
|
+
await this.understand(task);
|
|
83
|
+
await this.act();
|
|
84
|
+
await this.reflect();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### 🏰 Creating Space
|
|
90
|
+
|
|
91
|
+
Define your agent's domain:
|
|
92
|
+
|
|
93
|
+
```jsonc
|
|
94
|
+
{
|
|
95
|
+
"durable_objects": {
|
|
96
|
+
"bindings": [
|
|
97
|
+
{
|
|
98
|
+
"name": "AIAgent",
|
|
99
|
+
"class_name": "AIAgent"
|
|
100
|
+
}
|
|
101
|
+
]
|
|
102
|
+
},
|
|
103
|
+
"migrations": [
|
|
104
|
+
{
|
|
105
|
+
"tag": "v1",
|
|
106
|
+
// Mandatory for the Agent to store state
|
|
107
|
+
"new_sqlite_classes": ["AIAgent"]
|
|
108
|
+
}
|
|
109
|
+
]
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### 🌐 Lifecycle
|
|
114
|
+
|
|
115
|
+
Bring your agent into being:
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
// Create a new instance
|
|
119
|
+
const id = env.AIAgent.newUniqueId();
|
|
120
|
+
const agent = env.AIAgent.get(id);
|
|
121
|
+
|
|
122
|
+
// Initialize with purpose
|
|
123
|
+
await agent.processTask({
|
|
124
|
+
type: "analysis",
|
|
125
|
+
context: "incoming_data",
|
|
126
|
+
parameters: initialConfig
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// Or reconnect with an existing one
|
|
130
|
+
const existingAgent = await getAgentByName(env.AIAgent, "data-analyzer");
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### 🔄 Paths of Communication
|
|
134
|
+
|
|
135
|
+
#### HTTP Understanding
|
|
136
|
+
|
|
137
|
+
Process and respond to direct requests:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
export class APIAgent extends Agent {
|
|
141
|
+
async onRequest(request) {
|
|
142
|
+
const data = await request.json();
|
|
143
|
+
|
|
144
|
+
return Response.json({
|
|
145
|
+
insight: await this.process(data),
|
|
146
|
+
moment: Date.now()
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
#### Persistent Connections
|
|
153
|
+
|
|
154
|
+
Maintain ongoing dialogues through WebSocket:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
export class DialogueAgent extends Agent {
|
|
158
|
+
async onConnect(connection) {
|
|
159
|
+
await this.initiate(connection);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async onMessage(connection, message) {
|
|
163
|
+
const understanding = await this.comprehend(message);
|
|
164
|
+
await this.respond(connection, understanding);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
#### Client Communication
|
|
170
|
+
|
|
171
|
+
For direct connection to your agent:
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
import { AgentClient } from "agents/client";
|
|
175
|
+
|
|
176
|
+
const connection = new AgentClient({
|
|
177
|
+
agent: "dialogue-agent",
|
|
178
|
+
name: "insight-seeker"
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
connection.addEventListener("message", (event) => {
|
|
182
|
+
console.log("Received:", event.data);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
connection.send(
|
|
186
|
+
JSON.stringify({
|
|
187
|
+
type: "inquiry",
|
|
188
|
+
content: "What patterns do you see?"
|
|
189
|
+
})
|
|
190
|
+
);
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
#### React Integration
|
|
194
|
+
|
|
195
|
+
For harmonious integration with React:
|
|
196
|
+
|
|
197
|
+
```tsx
|
|
198
|
+
import { useAgent } from "agents/react";
|
|
199
|
+
|
|
200
|
+
function AgentInterface() {
|
|
201
|
+
const connection = useAgent({
|
|
202
|
+
agent: "dialogue-agent",
|
|
203
|
+
name: "insight-seeker",
|
|
204
|
+
onMessage: (message) => {
|
|
205
|
+
console.log("Understanding received:", message.data);
|
|
206
|
+
},
|
|
207
|
+
onOpen: () => console.log("Connection established"),
|
|
208
|
+
onClose: () => console.log("Connection closed")
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
const inquire = () => {
|
|
212
|
+
connection.send(
|
|
213
|
+
JSON.stringify({
|
|
214
|
+
type: "inquiry",
|
|
215
|
+
content: "What insights have you gathered?"
|
|
216
|
+
})
|
|
217
|
+
);
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
return (
|
|
221
|
+
<div className="agent-interface">
|
|
222
|
+
<button onClick={inquire}>Seek Understanding</button>
|
|
223
|
+
</div>
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
### 🌊 Flow of State
|
|
229
|
+
|
|
230
|
+
Maintain and evolve your agent's understanding:
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
export class ThinkingAgent extends Agent {
|
|
234
|
+
async evolve(newInsight) {
|
|
235
|
+
this.setState({
|
|
236
|
+
...this.state,
|
|
237
|
+
insights: [...(this.state.insights || []), newInsight],
|
|
238
|
+
understanding: this.state.understanding + 1
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
onStateUpdate(state, source) {
|
|
243
|
+
console.log("Understanding deepened:", {
|
|
244
|
+
newState: state,
|
|
245
|
+
origin: source
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
Connect to your agent's state from React:
|
|
252
|
+
|
|
253
|
+
```tsx
|
|
254
|
+
import { useState } from "react";
|
|
255
|
+
import { useAgent } from "agents/react";
|
|
256
|
+
|
|
257
|
+
function StateInterface() {
|
|
258
|
+
const [state, setState] = useState({ counter: 0 });
|
|
259
|
+
|
|
260
|
+
const agent = useAgent({
|
|
261
|
+
agent: "thinking-agent",
|
|
262
|
+
onStateUpdate: (newState) => setState(newState)
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
const increment = () => {
|
|
266
|
+
agent.setState({ counter: state.counter + 1 });
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
return (
|
|
270
|
+
<div>
|
|
271
|
+
<div>Count: {state.counter}</div>
|
|
272
|
+
<button onClick={increment}>Increment</button>
|
|
273
|
+
</div>
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
This creates a synchronized state that automatically updates across all connected clients.
|
|
279
|
+
|
|
280
|
+
### ⏳ Temporal Patterns
|
|
281
|
+
|
|
282
|
+
Schedule moments of action and reflection:
|
|
283
|
+
|
|
284
|
+
```ts
|
|
285
|
+
export class TimeAwareAgent extends Agent {
|
|
286
|
+
async initialize() {
|
|
287
|
+
// Quick reflection
|
|
288
|
+
this.schedule(10, "quickInsight", { focus: "patterns" });
|
|
289
|
+
|
|
290
|
+
// Daily synthesis
|
|
291
|
+
this.schedule("0 0 * * *", "dailySynthesis", {
|
|
292
|
+
depth: "comprehensive"
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
// Milestone review
|
|
296
|
+
this.schedule(new Date("2024-12-31"), "yearlyAnalysis");
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
async quickInsight(data) {
|
|
300
|
+
await this.analyze(data.focus);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async dailySynthesis(data) {
|
|
304
|
+
await this.synthesize(data.depth);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async yearlyAnalysis() {
|
|
308
|
+
await this.analyze();
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
### 💬 AI Dialogue
|
|
314
|
+
|
|
315
|
+
Create meaningful conversations with intelligence:
|
|
316
|
+
|
|
317
|
+
```ts
|
|
318
|
+
import { AIChatAgent } from "agents/ai-chat-agent";
|
|
319
|
+
import { openai } from "@ai-sdk/openai";
|
|
320
|
+
import { streamText, generateText, createDataStreamResponse } from "ai";
|
|
321
|
+
|
|
322
|
+
export class DialogueAgent extends AIChatAgent {
|
|
323
|
+
async onChatMessage(onFinish) {
|
|
324
|
+
// Option 1: Streaming responses (recommended for real-time interaction)
|
|
325
|
+
return createDataStreamResponse({
|
|
326
|
+
execute: async (dataStream) => {
|
|
327
|
+
const stream = streamText({
|
|
328
|
+
model: openai("gpt-4o"),
|
|
329
|
+
messages: this.messages,
|
|
330
|
+
// Optional: onFinish is invoked by the AI SDK when generation completes.
|
|
331
|
+
// Persistence is handled automatically by AIChatAgent after streaming completes.
|
|
332
|
+
onFinish
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
stream.mergeIntoDataStream(dataStream);
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
// Option 2: Non-streaming responses (simpler, but no real-time updates)
|
|
340
|
+
// const result = await generateText({
|
|
341
|
+
// model: openai("gpt-4o"),
|
|
342
|
+
// messages: this.messages,
|
|
343
|
+
// });
|
|
344
|
+
//
|
|
345
|
+
// // For non-streaming with metadata, use toUIMessage:
|
|
346
|
+
// const message = result.toUIMessage({
|
|
347
|
+
// metadata: {
|
|
348
|
+
// model: 'gpt-4o',
|
|
349
|
+
// totalTokens: result.usage?.totalTokens,
|
|
350
|
+
// }
|
|
351
|
+
// });
|
|
352
|
+
//
|
|
353
|
+
// return new Response(JSON.stringify(message), {
|
|
354
|
+
// headers: { 'Content-Type': 'application/json' }
|
|
355
|
+
// });
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
#### Metadata Support
|
|
361
|
+
|
|
362
|
+
The AI SDK provides native support for message metadata through the `messageMetadata` callback. This allows you to attach custom information to messages at the message level.
|
|
363
|
+
|
|
364
|
+
##### AIChatAgent Integration
|
|
365
|
+
|
|
366
|
+
In the context of `AIChatAgent`, you can use metadata like this:
|
|
367
|
+
|
|
368
|
+
```typescript
|
|
369
|
+
import { AIChatAgent } from "agents/ai-chat-agent";
|
|
370
|
+
import { streamText } from "ai";
|
|
371
|
+
import { openai } from "@ai-sdk/openai";
|
|
372
|
+
|
|
373
|
+
export class MyAgent extends AIChatAgent<Env> {
|
|
374
|
+
async onChatMessage(onFinish) {
|
|
375
|
+
const startTime = Date.now();
|
|
376
|
+
|
|
377
|
+
const result = streamText({
|
|
378
|
+
model: openai("gpt-4o"),
|
|
379
|
+
messages: this.messages,
|
|
380
|
+
onFinish
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
return result.toUIMessageStreamResponse({
|
|
384
|
+
messageMetadata: ({ part }) => {
|
|
385
|
+
if (part.type === "start") {
|
|
386
|
+
return {
|
|
387
|
+
model: "gpt-4o",
|
|
388
|
+
createdAt: Date.now(),
|
|
389
|
+
messageCount: this.messages.length
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
if (part.type === "finish") {
|
|
393
|
+
return {
|
|
394
|
+
responseTime: Date.now() - startTime,
|
|
395
|
+
totalTokens: part.totalUsage?.totalTokens
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
```
|
|
403
|
+
|
|
404
|
+
##### Accessing Metadata on the Client
|
|
405
|
+
|
|
406
|
+
Access metadata through the `message.metadata` property:
|
|
407
|
+
|
|
408
|
+
```typescript
|
|
409
|
+
'use client';
|
|
410
|
+
|
|
411
|
+
import { useChat } from '@ai-sdk/react';
|
|
412
|
+
import { DefaultChatTransport } from 'ai';
|
|
413
|
+
import type { MyUIMessage } from '@/types';
|
|
414
|
+
|
|
415
|
+
export default function Chat() {
|
|
416
|
+
const { messages } = useChat<MyUIMessage>({
|
|
417
|
+
transport: new DefaultChatTransport({
|
|
418
|
+
api: '/api/chat',
|
|
419
|
+
}),
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
return (
|
|
423
|
+
<div>
|
|
424
|
+
{messages.map(message => (
|
|
425
|
+
<div key={message.id}>
|
|
426
|
+
<div>
|
|
427
|
+
{message.role === 'user' ? 'User: ' : 'AI: '}
|
|
428
|
+
{message.metadata?.createdAt && (
|
|
429
|
+
<span className="text-sm text-gray-500">
|
|
430
|
+
{new Date(message.metadata.createdAt).toLocaleTimeString()}
|
|
431
|
+
</span>
|
|
432
|
+
)}
|
|
433
|
+
</div>
|
|
434
|
+
{/* Render message content */}
|
|
435
|
+
{message.parts.map((part, index) =>
|
|
436
|
+
part.type === 'text' ? <div key={index}>{part.text}</div> : null,
|
|
437
|
+
)}
|
|
438
|
+
{/* Display additional metadata */}
|
|
439
|
+
{message.metadata?.totalTokens && (
|
|
440
|
+
<div className="text-xs text-gray-400">
|
|
441
|
+
{message.metadata.totalTokens} tokens
|
|
442
|
+
</div>
|
|
443
|
+
)}
|
|
444
|
+
</div>
|
|
445
|
+
))}
|
|
446
|
+
</div>
|
|
447
|
+
);
|
|
448
|
+
}
|
|
449
|
+
```
|
|
450
|
+
|
|
451
|
+
For more details, see the [AI SDK Message Metadata documentation](https://ai-sdk.dev/docs/ai-sdk-ui/message-metadata).
|
|
452
|
+
|
|
453
|
+
#### Creating the Interface
|
|
454
|
+
|
|
455
|
+
Connect with your agent through a React interface:
|
|
456
|
+
|
|
457
|
+
```tsx
|
|
458
|
+
import { useAgent } from "agents/react";
|
|
459
|
+
import { useAgentChat } from "agents/ai-react";
|
|
460
|
+
|
|
461
|
+
function ChatInterface() {
|
|
462
|
+
// Connect to the agent
|
|
463
|
+
const agent = useAgent({
|
|
464
|
+
agent: "dialogue-agent"
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
// Set up the chat interaction
|
|
468
|
+
const { messages, input, handleInputChange, handleSubmit, clearHistory } =
|
|
469
|
+
useAgentChat({
|
|
470
|
+
agent,
|
|
471
|
+
maxSteps: 5
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
return (
|
|
475
|
+
<div className="chat-interface">
|
|
476
|
+
{/* Message History */}
|
|
477
|
+
<div className="message-flow">
|
|
478
|
+
{messages.map((message) => (
|
|
479
|
+
<div key={message.id} className="message">
|
|
480
|
+
<div className="role">{message.role}</div>
|
|
481
|
+
<div className="content">
|
|
482
|
+
{message.parts.map((part, i) => {
|
|
483
|
+
if (part.type === "text")
|
|
484
|
+
return <span key={i}>{part.text}</span>;
|
|
485
|
+
// Render other part types (e.g., files, tool calls) as desired
|
|
486
|
+
return null;
|
|
487
|
+
})}
|
|
488
|
+
</div>
|
|
489
|
+
</div>
|
|
490
|
+
))}
|
|
491
|
+
</div>
|
|
492
|
+
|
|
493
|
+
{/* Input Area */}
|
|
494
|
+
<form onSubmit={handleSubmit} className="input-area">
|
|
495
|
+
<input
|
|
496
|
+
value={input}
|
|
497
|
+
onChange={handleInputChange}
|
|
498
|
+
placeholder="Type your message..."
|
|
499
|
+
className="message-input"
|
|
500
|
+
/>
|
|
501
|
+
</form>
|
|
502
|
+
|
|
503
|
+
<button onClick={clearHistory} className="clear-button">
|
|
504
|
+
Clear Chat
|
|
505
|
+
</button>
|
|
506
|
+
</div>
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
```
|
|
510
|
+
|
|
511
|
+
This creates:
|
|
512
|
+
|
|
513
|
+
- Real-time message streaming
|
|
514
|
+
- Simple message history
|
|
515
|
+
- Intuitive input handling
|
|
516
|
+
- Easy conversation reset
|
|
517
|
+
|
|
518
|
+
### 🔗 MCP (Model Context Protocol) Integration
|
|
519
|
+
|
|
520
|
+
Agents can seamlessly integrate with the Model Context Protocol, allowing them to act as both MCP servers (providing tools to AI assistants) and MCP clients (using tools from other services).
|
|
521
|
+
|
|
522
|
+
#### Creating an MCP Server
|
|
523
|
+
|
|
524
|
+
```typescript
|
|
525
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
526
|
+
import { McpAgent } from "agents/mcp";
|
|
527
|
+
import { z } from "zod";
|
|
528
|
+
|
|
529
|
+
type Env = {
|
|
530
|
+
MyMCP: DurableObjectNamespace<MyMCP>;
|
|
531
|
+
};
|
|
532
|
+
|
|
533
|
+
type State = { counter: number };
|
|
534
|
+
|
|
535
|
+
export class MyMCP extends McpAgent<Env, State, {}> {
|
|
536
|
+
server = new McpServer({
|
|
537
|
+
name: "Demo",
|
|
538
|
+
version: "1.0.0"
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
initialState: State = {
|
|
542
|
+
counter: 1
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
async init() {
|
|
546
|
+
this.server.resource("counter", "mcp://resource/counter", (uri) => {
|
|
547
|
+
return {
|
|
548
|
+
contents: [{ text: String(this.state.counter), uri: uri.href }]
|
|
549
|
+
};
|
|
550
|
+
});
|
|
551
|
+
|
|
552
|
+
this.server.tool(
|
|
553
|
+
"add",
|
|
554
|
+
"Add to the counter, stored in the MCP",
|
|
555
|
+
{ a: z.number() },
|
|
556
|
+
async ({ a }) => {
|
|
557
|
+
this.setState({ ...this.state, counter: this.state.counter + a });
|
|
558
|
+
|
|
559
|
+
return {
|
|
560
|
+
content: [
|
|
561
|
+
{
|
|
562
|
+
text: String(`Added ${a}, total is now ${this.state.counter}`),
|
|
563
|
+
type: "text"
|
|
564
|
+
}
|
|
565
|
+
]
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
onStateUpdate(state: State) {
|
|
572
|
+
console.log({ stateUpdate: state });
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// HTTP Streamable transport (recommended)
|
|
577
|
+
export default MyMCP.serve("/mcp", {
|
|
578
|
+
binding: "MyMCP"
|
|
579
|
+
});
|
|
580
|
+
|
|
581
|
+
// Or SSE transport for legacy compatibility
|
|
582
|
+
// export default MyMCP.serveSSE("/mcp", { binding: "MyMCP" });
|
|
583
|
+
```
|
|
584
|
+
|
|
585
|
+
#### Using MCP Tools
|
|
586
|
+
|
|
587
|
+
```typescript
|
|
588
|
+
import { MCPClientManager } from "agents/mcp";
|
|
589
|
+
|
|
590
|
+
const client = new MCPClientManager("my-app", "1.0.0");
|
|
591
|
+
|
|
592
|
+
// Connect to an MCP server
|
|
593
|
+
await client.connect("https://weather-service.com/mcp", {
|
|
594
|
+
transport: { type: "streamable-http" }
|
|
595
|
+
});
|
|
596
|
+
|
|
597
|
+
// Use tools from the server
|
|
598
|
+
const weather = await client.callTool({
|
|
599
|
+
serverId: "weather-service",
|
|
600
|
+
name: "getWeather",
|
|
601
|
+
arguments: { location: "San Francisco" }
|
|
602
|
+
});
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
#### AI SDK Integration
|
|
606
|
+
|
|
607
|
+
```typescript
|
|
608
|
+
import { generateText } from "ai";
|
|
609
|
+
|
|
610
|
+
// Convert MCP tools for AI use
|
|
611
|
+
const result = await generateText({
|
|
612
|
+
model: openai("gpt-4"),
|
|
613
|
+
tools: client.getAITools(),
|
|
614
|
+
prompt: "What's the weather in Tokyo?"
|
|
615
|
+
});
|
|
616
|
+
```
|
|
617
|
+
|
|
618
|
+
**Transport Options:**
|
|
619
|
+
|
|
620
|
+
- **Auto**: Automatically determine the correct transport
|
|
621
|
+
- **HTTP Streamable**: Best performance, batch requests, session management
|
|
622
|
+
- **SSE**: Simple setup, legacy compatibility
|
|
623
|
+
|
|
624
|
+
### 💬 The Path Forward
|
|
625
|
+
|
|
626
|
+
We're developing new dimensions of agent capability:
|
|
627
|
+
|
|
628
|
+
#### Enhanced Understanding
|
|
629
|
+
|
|
630
|
+
- **WebRTC Perception**: Audio and video communication channels
|
|
631
|
+
- **Email Discourse**: Automated email interaction and response
|
|
632
|
+
- **Deep Memory**: Long-term context and relationship understanding
|
|
633
|
+
|
|
634
|
+
#### Development Insights
|
|
635
|
+
|
|
636
|
+
- **Evaluation Framework**: Understanding agent effectiveness
|
|
637
|
+
- **Clear Sight**: Deep visibility into agent processes
|
|
638
|
+
- **Private Realms**: Complete self-hosting guide
|
|
639
|
+
|
|
640
|
+
These capabilities will expand your agents' potential while maintaining their reliability and purpose.
|
|
641
|
+
|
|
642
|
+
Welcome to the future of intelligent agents. Create something meaningful. 🌟
|
|
643
|
+
|
|
644
|
+
### Contributing
|
|
645
|
+
|
|
646
|
+
Contributions are welcome, but are especially welcome when:
|
|
647
|
+
|
|
648
|
+
- You have opened an issue as a Request for Comment (RFC) to discuss your proposal, show your thinking, and iterate together.
|
|
649
|
+
- Not "AI slop": LLMs are powerful tools, but contributions entirely authored by vibe coding are unlikely to meet the quality bar, and will be rejected.
|
|
650
|
+
- You're willing to accept feedback and make sure the changes fit the goals of the `agents` SDK. Not everything will, and that's OK.
|
|
651
|
+
|
|
652
|
+
Small fixes, type bugs, and documentation improvements can be raised directly as PRs.
|
|
653
|
+
|
|
654
|
+
### License
|
|
655
|
+
|
|
656
|
+
MIT licensed. See the LICENSE file at the root of this repository for details.
|