跳转到主要内容
从零开始在10分钟内构建一个完整的 Agent 应用。你将创建一个 Agent,启动服务,并将其集成到 Web 应用中。

前置要求

  • 你选择的 LLM 提供商的 API 密钥
  • 基础编程知识
  • 已安装 Node.js 20+(前端开发必需)
  • 已安装 Python 3.11+
  • pip 或 uv 包管理器
  • 基础 Python 知识
1

创建项目结构

创建一个新目录并初始化项目:
mkdir my-first-agent
cd my-first-agent
python -m venv venv
source venv/bin/activate  # Windows 系统:venv\Scripts\activate
安装 AG-Kit 依赖:
pip install ag_kit_py
2

创建你的 Agent

使用一个简单的基于 OpenAI 的 agent 创建你的 agent 文件:创建 src/agent.py
import os
from langchain_core.messages import AIMessage, SystemMessage, convert_to_openai_messages
from langchain_core.messages.ai import add_ai_message_chunks
from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.memory import MemorySaver
from langgraph.config import get_stream_writer
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.graph.state import CompiledStateGraph

from ag_kit_py.agents.langgraph import LangGraphAgent
from ag_kit_py.providers import create_provider_from_env
from ag_kit_py.server import AgentCreatorResult


def chat_node(state: dict, config: RunnableConfig = None) -> dict:
    """生成带流式支持的 AI 响应。"""
    writer = get_stream_writer()
    try:
        provider = create_provider_from_env("openai")
        chat_model = provider.get_langchain_model()

        if config is None:
            config = RunnableConfig(recursion_limit=25)

        system_message = SystemMessage(content="You are a helpful assistant. Be friendly and concise.")
        messages = [system_message, *convert_to_openai_messages(state["messages"])]

        chunks = []
        for chunk in chat_model.stream(messages, config):
            writer({"messages": [chunk]})
            chunks.append(chunk)

        if chunks:
            from langchain_core.messages import AIMessageChunk
            ai_chunks = [
                chunk if isinstance(chunk, AIMessageChunk) else AIMessageChunk(content=str(chunk))
                for chunk in chunks
            ]
            merged_message = add_ai_message_chunks(*ai_chunks)
            return {"messages": [merged_message]}
        return {"messages": []}
    except Exception as e:
        return {"messages": [AIMessage(content=f"Error: {str(e)}")]}


def build_chat_workflow() -> CompiledStateGraph:
    """构建 LangGraph 工作流。"""
    graph = StateGraph(MessagesState)
    memory = MemorySaver()

    graph.add_node("ai_response", chat_node)
    graph.set_entry_point("ai_response")
    graph.add_edge(START, "ai_response")
    graph.add_edge("ai_response", END)

    return graph.compile(checkpointer=memory)


def create_my_agent() -> AgentCreatorResult:
    """创建 agent 实例。"""
    workflow = build_chat_workflow()
    agent = LangGraphAgent(
        name="my-first-agent",
        description="A helpful AI assistant",
        graph=workflow,
    )
    return {"agent": agent}
有关更多高级 Agent 配置选项,请参阅 核心 Agent 参考
3

创建服务器

创建你的服务器文件来运行你的 agent:创建 src/server.py
from ag_kit_py.server import AGKitAPIApp
from src.agent import create_my_agent

if __name__ == "__main__":
    AGKitAPIApp().run(
        create_my_agent,
        port=9000,
        enable_openai_endpoint=True,
    )
    print("Server running at http://localhost:9000")
有关更多服务器配置选项,请参阅 运行 Agent
4

配置环境

创建一个包含你的 API 密钥的 .env 文件:AG-Kit 通过 OpenAI 兼容的 API 支持多个 LLM 提供商。选择你喜欢的模型:
OPENAI_API_KEY=sk-your_openai_api_key
OPENAI_MODEL=gpt-4o-mini
# OPENAI_BASE_URL 对于 OpenAI 是可选的
添加开发脚本:服务器可以直接用 Python 运行:
python src/server.py
或者添加一个 pyproject.toml 用于项目配置:
[project]
name = "my-first-agent"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = ["ag_kit_py"]
5

启动服务器

启动你的 agent 服务器:
python src/server.py
你应该看到:
✓ Server running at http://localhost:9000
6

使用 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]
7

创建前端

为前端创建一个新目录并设置:
# 创建前端目录(在单独的终端/位置)
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"
  }
}
启动前端:
npm run dev
在浏览器中打开 http://localhost:5173有关更多 UI 组件选项,请参阅 UI 组件参考
8

试用一下

使用以下消息测试你的 agent:
  1. “Hello, how are you?” - 基本问候
  2. “What can you help me with?” - 探索功能
  3. “Tell me about AI” - 知识展示
  4. “Write a short poem” - 创造性任务
  5. “Alert me with a message” - 测试自定义工具(仅 TypeScript 前端)

你已经构建的内容

恭喜!你已经创建了:
  1. 一个 Agent,具有自定义工具和状态管理
  2. 一个后端服务,处理 Agent 请求
  3. 一个前端应用,具有实时聊天功能

架构

下一步

现在你已经有了一个可以工作的 Agent,探索更多功能:

故障排除

  • 检查 9000 端口是否已被占用
  • 确认你的 .env 文件包含 API 密钥
  • 检查控制台的错误消息
  • 确保 Agent 服务器正在运行
  • 检查前端配置中的服务器 URL
  • 确认服务器配置中的 CORS 设置
  • 检查你的 OpenAI API 密钥是否有效
  • 确认你有 API 额度
  • 检查服务器日志中的错误
  • 确保已安装 Python 3.11+
  • 确认虚拟环境已激活
  • 检查依赖是否正确安装
  • 查看控制台中的 Python 错误消息

了解更多