forked from get-convex/agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.ts
More file actions
77 lines (69 loc) · 2.32 KB
/
Copy pathbasic.ts
File metadata and controls
77 lines (69 loc) · 2.32 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// See the docs at https://docs.convex.dev/agents/messages
import { components, internal } from "../_generated/api";
import { action, internalAction, mutation, query } from "../_generated/server";
import { saveMessage } from "@convex-dev/agent";
import { v } from "convex/values";
import { agent } from "../agents/simple";
import { authorizeThreadAccess } from "../threads";
import { paginationOptsValidator } from "convex/server";
/**
* OPTION 1 (BASIC):
* Generating via a single action call
*/
export const generateTextInAnAction = action({
args: { prompt: v.string(), threadId: v.string() },
handler: async (ctx, { prompt, threadId }) => {
await authorizeThreadAccess(ctx, threadId);
const result = await agent.generateText(ctx, { threadId }, { prompt });
return result.text;
},
});
/**
* OPTION 2 (RECOMMENDED):
* Generating via a mutation & async action
* This enables optimistic updates on the client.
*/
// Save a user message, and kick off an async response.
export const sendMessage = mutation({
args: { prompt: v.string(), threadId: v.string() },
handler: async (ctx, { prompt, threadId }) => {
await authorizeThreadAccess(ctx, threadId);
const { messageId } = await saveMessage(ctx, components.agent, {
threadId,
prompt,
});
await ctx.scheduler.runAfter(0, internal.chat.basic.generateResponse, {
threadId,
promptMessageId: messageId,
});
},
});
// Generate a response to a user message.
// Any clients listing the messages will automatically get the new message.
export const generateResponse = internalAction({
args: { promptMessageId: v.string(), threadId: v.string() },
handler: async (ctx, { promptMessageId, threadId }) => {
await agent.generateText(ctx, { threadId }, { promptMessageId });
},
});
// Equivalent:
// export const generateResponse = agent.asTextAction();
/**
* Query & subscribe to messages & threads
*/
export const listMessages = query({
args: {
threadId: v.string(),
paginationOpts: paginationOptsValidator,
},
handler: async (ctx, args) => {
const { threadId, paginationOpts } = args;
await authorizeThreadAccess(ctx, threadId);
const messages = await agent.listMessages(ctx, {
threadId,
paginationOpts,
});
// You could add more fields here, join with other tables, etc.
return messages;
},
});