关于 Convex Agents Fundamentals
Convex Agents Fundamentals 面向使用 Convex 构建 Agent 的开发者,介绍 Agent 配置、对话线程以及文本或结构化 LLM 回复,并说明如何将消息历史纳入上下文。
主要功能
- 01配置 Agent 与模型
- 02创建并继续对话线程
- 03生成文本或结构化回复
- 04自动保存消息
- 05将近期历史纳入上下文
适用场景
- 01设置首个 Convex Agent
- 02管理按用户区分的对话
- 03构建带历史记录的聊天界面
- 04生成结构化 JSON 回复
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ sstobo/ convex-skills --skill convex-agents-fundamentals安装后在 Claude Code 中输入/convex-agents-fundamentals确认已加载。
详细介绍
用途
指导你完成设置 Convex Agent、管理对话线程以及生成大模型响应的核心模式。这是所有其他 Agent 能力构建的基础。
何时使用此技能
- 在项目中设置你的第一个 Convex Agent
- 创建或继续与用户的对话线程
- 从大模型生成文本响应或结构化 JSON 对象
- 配置 Agent 默认值(系统提示词、聊天模型、嵌入模型)
- 构建需要消息历史记录的基础聊天界面
如何使用
1. 安装与配置
将 agent 组件添加到你的 convex.config.ts:
// convex/convex.config.ts
import { defineApp } from "convex/server";
import agent from "@convex-dev/agent/convex.config";
const app = defineApp();
app.use(agent);
export default app;
运行 npx convex dev 以生成所需的代码。
2. 定义你的 Agent
使用聊天模型创建 Agent 实例:
// convex/agents/myAgent.ts
import { components } from "../_generated/api";
import { Agent } from "@convex-dev/agent";
import { openai } from "@ai-sdk/openai";
export const myAgent = new Agent(components.agent, {
name: "My Assistant",
languageModel: openai.chat("gpt-4o-mini"),
instructions: "You are a helpful assistant.", // Optional: default system prompt
});
3. 创建线程
为某个用户创建线程,以管理其对话历史记录:
// convex/threads.ts
import { action } from "../_generated/server";
import { v } from "convex/values";
import { myAgent } from "./agents/myAgent";
export const createNewThread = action({
args: { userId: v.string() },
handler: async (ctx, { userId }) => {
const { thread } = await myAgent.createThread(ctx, {
userId,
title: "New Conversation",
});
return { threadId: thread.getMetadata().threadId };
},
});
4. 生成响应
在线程中生成文本或结构化响应:
// convex/generation.ts
export const generateReply = action({
args: { threadId: v.string(), prompt: v.string() },
handler: async (ctx, { threadId, prompt }) => {
const { thread } = await myAgent.continueThread(ctx, { threadId });
const result = await thread.generateText({ prompt });
return result.text;
},
});
核心原则
- 线程隔离:每个用户/对话拥有自己的线程,历史记录相互独立
- 自动存储消息:生成的响应会自动保存到线程中
- 默认携带上下文:每次生成都会自动包含最近的消息历史记录
- 异步友好:使用 action 进行大模型调用;使用 mutation 进行事务性写入
- 类型安全:始终提供明确的返回类型,以避免循环引用错误
常见模式
- 按用户组织:创建线程时始终包含
userId - 消息历史记录:自动包含在大模型上下文中
- 线程复用:同一线程可由多个 Agent 使用
后续步骤
- 管理线程:参见 threads 技能以了解对话管理
- 处理消息:参见 messages 技能以了解保存和检索
- 添加工具:参见 tools 技能以让 Agent 执行操作
评论
支持 Markdown