Documentation Index Fetch the complete documentation index at: https://docs.ag-kit.dev/llms.txt
Use this file to discover all available pages before exploring further.
从零开始在10分钟内构建一个完整的 Agent 应用。你将创建一个 Agent,启动服务,并将其集成到 Web 应用中。
前置要求
你选择的 LLM 提供商的 API 密钥
基础编程知识
已安装 Node.js 20+ (前端开发必需)
npm 或 yarn 包管理器
基础 TypeScript 知识
创建项目结构
创建一个新目录并初始化项目: mkdir my-first-agent
cd my-first-agent
npm init -y
npm pkg set type=module
安装 AG-Kit 依赖: npm install @ag-kit/agents @ag-kit/adapter-langgraph @ag-kit/server @langchain/core @langchain/langgraph @langchain/openai langchain
npm install -D typescript tsx nodemon dotenv @types/node
初始化 TypeScript:
创建你的 Agent
使用一个简单的基于 OpenAI 的 agent 创建你的 agent 文件: 创建 src/agent.ts: import 'dotenv/config' ;
import { LanggraphAgent } from '@ag-kit/adapter-langgraph' ;
import { ChatOpenAI } from "@langchain/openai" ;
import { AIMessage , SystemMessage } from "@langchain/core/messages" ;
import {
StateGraph ,
START ,
END ,
MessagesAnnotation ,
MemorySaver ,
} from "@langchain/langgraph" ;
import { ToolNode } from "@langchain/langgraph/prebuilt" ;
import { tool } from "langchain" ;
import { z } from "zod" ;
const getWeather = tool (
async ({ location }) => ({
location ,
condition: "Sunny" ,
temperatureC: 25 ,
}),
{
name: "getWeather" ,
description: "Get mock weather for a location" ,
schema: z . object ({
location: z . string (). optional (),
}),
}
);
const tools = [ getWeather ];
async function chatNode ( state : typeof MessagesAnnotation . State ) {
const model = new ChatOpenAI ({
model: process . env . OPENAI_MODEL || "gpt-4o-mini" ,
apiKey: process . env . OPENAI_API_KEY ,
configuration: {
baseURL: process . env . OPENAI_BASE_URL ,
},
}). bindTools ( tools );
const systemMessage = new SystemMessage ({
content: "You are a helpful assistant." ,
});
const response = await model . invoke ([ systemMessage , ... state . messages ]);
return { messages: [ response ] };
}
function shouldContinue ( state : typeof MessagesAnnotation . State ) {
const lastMessage = state . messages . at ( - 1 );
if ( AIMessage . isInstance ( lastMessage )) {
const toolCalls = lastMessage . tool_calls ;
const shouldCallTool = toolCalls ?. some (( c ) =>
tools . some (( t ) => t . name === c ?. name )
);
return shouldCallTool ? "tools" : END ;
}
return END ;
}
const workflow = new StateGraph ( MessagesAnnotation )
. addNode ( "chat_node" , chatNode )
. addNode ( "tools" , new ToolNode ( tools ))
. addEdge ( START , "chat_node" )
. addConditionalEdges ( "chat_node" , shouldContinue )
. addEdge ( "tools" , "chat_node" )
. addEdge ( "chat_node" , END );
const compiledWorkflow = workflow . compile ({
checkpointer: new MemorySaver (),
});
const agent = new LanggraphAgent ({ compiledWorkflow });
export function createAgent () {
return { agent };
}
有关更多高级 Agent 配置选项,请参阅 LangGraph Agent 参考 。
创建服务器
创建你的服务器文件来运行你的 agent: 创建 src/server.ts: import { run } from '@ag-kit/server' ;
import { createAgent } from './agent.js' ;
// 启动服务器
run ({
createAgent ,
cors: true ,
port: 9000 ,
});
console . log ( 'Server running at http://localhost:9000' );
注意 :使用 ES 模块时,你必须在导入中使用 .js 扩展名。有关更多服务器配置选项,请参阅 运行 Agent 。
配置环境
创建一个包含你的 API 密钥的 .env 文件: AG-Kit 通过 OpenAI 兼容的 API 支持多个 LLM 提供商。选择你喜欢的模型: OpenAI
Zhipu GLM-4
Qwen
DeepSeek
Local (Ollama)
OPENAI_API_KEY = sk-your_openai_api_key
OPENAI_MODEL = gpt-4o-mini
# OPENAI_BASE_URL 对于 OpenAI 是可选的
OPENAI_API_KEY = your_zhipu_api_key
OPENAI_MODEL = glm-4-flash
OPENAI_BASE_URL = https://open.bigmodel.cn/api/paas/v4/
OPENAI_API_KEY = sk-your_qwen_api_key
OPENAI_MODEL = qwen-plus
OPENAI_BASE_URL = https://dashscope.aliyuncs.com/compatible-mode/v1
OPENAI_API_KEY = sk-your_deepseek_api_key
OPENAI_MODEL = deepseek-chat
OPENAI_BASE_URL = https://api.deepseek.com/v1
OPENAI_API_KEY = ollama
OPENAI_MODEL = llama3.2
OPENAI_BASE_URL = http://localhost:11434/v1
添加开发脚本: 添加到 package.json: {
"scripts" : {
"dev" : "nodemon --exec tsx src/server.ts" ,
"build" : "tsc" ,
"start" : "node dist/server.js"
}
}
启动服务器
启动你的 agent 服务器: 你应该看到: ✓ Server running at http://localhost:9000
使用 cURL 测试
使用一个简单的请求测试你的 agent: curl --request POST \
--url http://localhost:9000/send-message \
--header 'Accept: text/event-stream' \
--header 'Content-Type: application/json' \
--data '{
"messages": [
{
"role": "user",
"content": "Hello, how are you?"
}
],
"conversationId": "test-conversation"
}'
你应该获得一个带有如下事件的流式响应: data: {"type":"text","content":"Hello"}
data: {"type":"text","content":"!"}
data: {"type":"text","content":" I"}
data: {"type":"text","content":"'m"}
data: {"type":"text","content":" doing"}
data: {"type":"text","content":" well"}
data: {"type":"text","content":","}
data: {"type":"text","content":" thank"}
data: {"type":"text","content":" you"}
data: {"type":"text","content":" for"}
data: {"type":"text","content":" asking"}
data: {"type":"text","content":"."}
data: {"type":"text","content":" How"}
data: {"type":"text","content":" can"}
data: {"type":"text","content":" I"}
data: {"type":"text","content":" help"}
data: {"type":"text","content":" you"}
data: {"type":"text","content":" today"}
data: {"type":"text","content":"?"}
data: [DONE]
创建前端
为前端创建一个新目录并设置: # 创建前端目录(在单独的终端/位置)
mkdir my-agent-frontend
cd my-agent-frontend
# 初始化 npm 项目
npm init -y
# 安装依赖
npm install react react-dom @ag-kit/example-ui-web-shared @ag-kit/ui-react zod
npm install -D typescript @types/react @types/react-dom vite @vitejs/plugin-react
创建 index.html: <! DOCTYPE html >
< html lang = "en" >
< head >
< meta charset = "UTF-8" />
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
< title > My Agent Chat </ title >
</ head >
< body >
< div id = "root" ></ div >
< script type = "module" src = "/src/main.tsx" ></ script >
</ body >
</ html >
创建 src/main.tsx: import React from 'react' ;
import { createRoot } from 'react-dom/client' ;
import { AgKitChat } from '@ag-kit/example-ui-web-shared' ;
import { useChat , clientTool } from '@ag-kit/ui-react' ;
import z from 'zod' ;
import '@ag-kit/example-ui-web-shared/style.css' ;
const suggestions = [
{ id: "1" , text: "Hello, how are you?" , category: "Greeting" },
{ id: "2" , text: "What can you help me with?" , category: "Help" },
{ id: "3" , text: "Tell me a joke" , category: "Fun" },
];
function App () {
const { sendMessage , uiMessages , streaming } = useChat ({
url: 'http://localhost:9000/send-message' ,
clientTools: [
clientTool ({
name: "alert" ,
description: "Alert the user" ,
parameters: z . object ({ message: z . string () }),
handler : async ({ message }) => {
await new Promise (( resolve ) => setTimeout ( resolve , 1000 ));
alert ( message );
return "done" ;
},
}),
],
});
return (
< AgKitChat
title = "My First Agent"
suggestions = { suggestions }
welcomeMessage = "Welcome! Try selecting a suggestion or type your own message."
uiMessages = { uiMessages }
onMessageSend = { sendMessage }
status = {streaming ? "streaming" : "idle" }
/>
);
}
const root = createRoot ( document . getElementById ( 'root' ) ! );
root . render (< App />);
创建 vite.config.ts: import { defineConfig } from 'vite' ;
import react from '@vitejs/plugin-react' ;
export default defineConfig ({
plugins: [ react ()] ,
server: { port: 5173 }
}) ;
添加到 package.json: {
"type" : "module" ,
"scripts" : {
"dev" : "vite" ,
"build" : "vite build" ,
"preview" : "vite preview"
}
}
启动前端: 在浏览器中打开 http://localhost:5173! 有关更多 UI 组件选项,请参阅 UI 组件参考 。
试用一下
使用以下消息测试你的 agent:
“Hello, how are you?” - 基本问候
“What can you help me with?” - 探索功能
“Tell me about AI” - 知识展示
“Write a short poem” - 创造性任务
“Alert me with a message” - 测试自定义工具(仅 TypeScript 前端)
AG-Kit CLI 将提供简化的设置体验: 敬请期待更新!
你已经构建的内容
恭喜!你已经创建了:
一个 Agent ,具有自定义工具和状态管理
一个后端服务 ,处理 Agent 请求
一个前端应用 ,具有实时聊天功能
下一步
现在你已经有了一个可以工作的 Agent,探索更多功能:
故障排除
检查 9000 端口是否已被占用
确认你的 .env 文件包含 API 密钥
检查控制台的错误消息
确保 Agent 服务器正在运行
检查前端配置中的服务器 URL
确认服务器配置中的 CORS 设置
检查你的 OpenAI API 密钥是否有效
确认你有 API 额度
检查服务器日志中的错误
了解更多
核心概念 - 深入了解 AG-Kit 架构
示例 - 更多示例应用
API 参考 - 完整的 API 文档
社区 - 加入我们的 Discord 和 GitHub