-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathchat-agent.ts
More file actions
46 lines (41 loc) · 1.52 KB
/
Copy pathchat-agent.ts
File metadata and controls
46 lines (41 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import * as restate from "@restatedev/restate-sdk";
import { durableCalls, superJson } from "@restatedev/vercel-ai-middleware";
import { openai } from "@ai-sdk/openai";
import { generateText, ModelMessage, wrapLanguageModel } from "ai";
import { handlers } from "@restatedev/restate-sdk";
import { ChatMessageSchema } from "./utils/types";
const schema = restate.serde.schema;
import shared = handlers.object.shared;
// <start_here>
const chatAgent = restate.object({
name: "Chat",
handlers: {
message: restate.createObjectHandler(
{ input: schema(ChatMessageSchema) },
async (ctx: restate.ObjectContext, { message }: { message: string }) => {
const model = wrapLanguageModel({
model: openai("gpt-5.4"),
middleware: durableCalls(ctx, { maxRetryAttempts: 3 }),
});
// Retrieve the state
const messages =
(await ctx.get<ModelMessage[]>("messages", superJson)) ?? [];
messages.push({ role: "user", content: message });
const res = await generateText({
model,
system: "You are a helpful assistant.",
messages,
});
// Update the state
ctx.set("messages", [...messages, ...res.response.messages], superJson);
return { answer: res.text };
},
),
// Shared handler to retrieve the history
getHistory: shared(async (ctx: restate.ObjectSharedContext) =>
ctx.get<ModelMessage[]>("messages", superJson),
),
},
});
// <end_here>
restate.serve({ services: [chatAgent] });