@@ -38,36 +38,61 @@ Review the [Agents API reference](/agents/api-reference/agents-api/) to learn mo
3838
3939### Implementing Server-Sent Events
4040
41- TODO
41+ The Agents SDK support Server-Sent Events:
42+
43+ The below example uses the AI SDK to generate text and stream it back to the client. It will automatically stream
44+
4245<TypeScriptExample >
4346
4447``` ts
45- import { Agent } from " agents-sdk" ;
48+ import { Agent , AgentNamespace , getAgentByName , routeAgentRequest } from ' agents-sdk' ;
4649import { streamText } from ' ai' ;
4750import { createOpenAI , openai } from ' @ai-sdk/openai' ;
4851
4952interface Env {
53+ MyAgent: AgentNamespace <MyAgent >;
5054 OPENAI_API_KEY: string ;
5155}
5256
53- class MyAgent extends Agent <Env > {
54- // Handle HTTP requests coming to this Agent instance
55- // Returns a Response object
56- async onRequest(request : Request ) {
57- return new Response (" Hello from Agent!" );
58- }
59-
60- async callAIModel(prompt : string ) {
61- const openai = createOpenAI ({
62- // custom settings, e.g.
63- compatibility: ' strict' , // strict mode, enable when using the OpenAI API
64- });
65- }
57+ export class MyAgent extends Agent <Env > {
58+ async onRequest(request : Request ) {
59+ // Test it via:
60+ // curl -d '{"prompt": "Write me a Cloudflare Worker"}' <url>
61+ let data = await request .json <{ prompt: string }>();
62+ let stream = await this .callAIModel (data .prompt );
63+ // This uses Server-Sent Events (SSE)
64+ return stream .toTextStreamResponse ({
65+ headers: {
66+ ' Content-Type' : ' text/x-unknown' ,
67+ ' content-encoding' : ' identity' ,
68+ ' transfer-encoding' : ' chunked' ,
69+ },
70+ });
71+ }
72+
73+ async callAIModel(prompt : string ) {
74+ const openai = createOpenAI ({
75+ apiKey: this .env .OPENAI_API_KEY ,
76+ });
77+
78+ return streamText ({
79+ model: openai (' gpt-4o' ),
80+ prompt: prompt ,
81+ });
82+ }
6683}
84+
85+ export default {
86+ async fetch(request : Request , env : Env ) {
87+ const agent = await getAgentByName <Env , MyAgent >(env .MyAgent , ' agent' );
88+ return agent .fetch (request );
89+ },
90+ };
6791```
6892
6993</TypeScriptExample >
7094
7195## WebSockets vs. Server-Sent Events
7296
73- TODO
97+ TODO
98+
0 commit comments