zyw-ai-agent
v0.1.0
Published
AI agent library using MCP (Model Context Protocol) and tools for Next.js applications
Maintainers
Readme
zyw-ai-agent
基于 OpenAI 的 AI 代理工具库,支持工具集和 MCP(Model Context Protocol)服务器调用。
特性
- 基于 OpenAI API 的 AI 代理
- 支持自定义工具集
- 支持 MCP 服务器集成
- 流式传输响应
- 链式调用 API
- TypeScript 类型定义
- Next.js 14 兼容
- 易于集成到现有项目中
安装
npm install zyw-ai-agent或
yarn add zyw-ai-agent基本使用
配置
在应用程序入口点设置配置:
import { config } from 'zyw-ai-agent';
// 设置基本配置
config({
openaiApiKey: 'your-openai-api-key',
defaultModel: 'gpt-4o',
debug: true
});
// 如果使用 Prisma,可以设置共享实例
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
config({
prisma
});简单使用
import { runAgent } from 'zyw-ai-agent';
async function main() {
const result = await runAgent({
userPrompt: '今天的天气怎么样?',
systemPrompt: '你是一个有用的助手。'
});
console.log(result.messages[result.messages.length - 1].content);
}
main().catch(console.error);使用工具集
import { runAgent, createTool } from 'zyw-ai-agent';
// 创建一个天气工具
const weatherTool = createTool({
name: 'getWeather',
description: '获取指定位置的天气',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: '位置名称,如"北京"'
}
},
required: ['location']
},
handler: async ({ location }) => {
// 真实应用中应该调用天气 API
return {
location,
temperature: 22,
conditions: '晴朗',
humidity: 65
};
}
});
async function main() {
const result = await runAgent({
userPrompt: '北京的天气怎么样?',
systemPrompt: '你是一个有用的助手。',
tools: [weatherTool]
});
console.log(result.messages[result.messages.length - 1].content);
}
main().catch(console.error);使用 MCP 服务器
import { runAgent, createMcpServer } from 'zyw-ai-agent';
// 创建一个 MCP 服务器
const weatherServer = createMcpServer({
name: 'weatherServer',
url: 'https://your-weather-api-server.com/api',
description: '天气服务 API',
auth: {
type: 'bearer',
token: 'your-api-token'
}
});
async function main() {
const result = await runAgent({
userPrompt: '北京的天气怎么样?',
systemPrompt: '你是一个有用的助手。',
mcpServers: [weatherServer]
});
console.log(result.messages[result.messages.length - 1].content);
}
main().catch(console.error);流式响应
import { runAgentStream } from 'zyw-ai-agent';
async function main() {
await runAgentStream({
userPrompt: '给我讲个故事。',
systemPrompt: '你是一个有用的助手。',
onUpdate: (message) => {
if (message.role === 'assistant') {
process.stdout.write(message.content || '');
}
}
});
}
main().catch(console.error);高级功能
链式调用 API
import { openaiAgent } from 'zyw-ai-agent';
async function main() {
const result = await openaiAgent({ ifStream: true })
.addSystemPrompt({ systemPrompt: '你是一个有用的助手。' })
.addUserPrompt({ userPrompt: '北京的天气怎么样?' })
.addTools({ tools: [weatherTool] })
.addMcpServer({ mcpServers: [weatherServer] })
.goStream({
onUpdate: (message) => {
if (message.role === 'assistant') {
process.stdout.write(message.content || '');
}
}
});
}
main().catch(console.error);在 React 组件中使用
import React from 'react';
import { useAgent } from 'zyw-ai-agent/hooks';
import { exampleTools } from 'zyw-ai-agent/utils';
function ChatComponent() {
const [input, setInput] = React.useState('');
const { messages, isLoading, sendMessage } = useAgent({
initialSystemPrompt: '你是一个有用的助手。',
tools: exampleTools
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (input.trim() && !isLoading) {
sendMessage(input);
setInput('');
}
};
return (
<div>
<div className="messages">
{messages.map((message, index) => (
message.role !== 'system' && (
<div key={index} className={`message ${message.role}`}>
{message.role === 'user' ? '用户: ' : '助手: '}
{message.content}
</div>
)
))}
{isLoading && <div>正在思考...</div>}
</div>
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="输入消息..."
disabled={isLoading}
/>
<button type="submit" disabled={isLoading || !input.trim()}>
发送
</button>
</form>
</div>
);
}
export default ChatComponent;自定义工具创建
import { z } from 'zod';
import { createZodTool } from 'zyw-ai-agent';
// 使用 Zod 创建验证模式
const SearchSchema = z.object({
query: z.string().min(3).describe('搜索查询字符串'),
limit: z.number().int().min(1).max(10).optional().describe('结果限制数量')
});
// 创建基于 Zod 的工具
const searchTool = createZodTool({
name: 'search',
description: '在数据库中搜索信息',
schema: SearchSchema,
handler: async ({ query, limit = 5 }) => {
// 实际实现中应该执行真实的搜索
return {
results: [
{ title: '结果 1', snippet: '这是搜索结果 1...' },
{ title: '结果 2', snippet: '这是搜索结果 2...' }
],
count: 2,
query,
limit
};
}
});数据库集成
import { config, createDbQueryTool } from 'zyw-ai-agent';
import { PrismaClient } from '@prisma/client';
// 创建和设置 Prisma 客户端
const prisma = new PrismaClient();
config({ prisma });
// 创建数据库查询工具
const userQueryTool = createDbQueryTool({
name: 'queryUsers',
description: '查询用户数据库',
queryHandler: async (query) => {
// 这里应该进行安全检查和查询转换
// 这仅是示例,不要在生产中直接执行用户输入的查询
if (query.includes('SELECT') && query.includes('FROM users')) {
const users = await prisma.user.findMany({
take: 10
});
return { users };
}
return { error: '不支持的查询' };
}
});API 参考
配置
config({
// OpenAI 配置
openaiApiKey?: string;
openaiBaseUrl?: string;
openaiOrganization?: string;
// 模型配置
defaultModel?: string; // 默认: 'gpt-4o'
defaultSystemPrompt?: string;
// 数据库配置
prisma?: PrismaClient;
redis?: Redis;
// 其他配置
debug?: boolean;
useGlobalInstance?: boolean;
});工具创建
createTool({
name: string;
description: string;
parameters?: Record<string, any>;
handler: (args: Record<string, any>) => Promise<any>;
});
createFetchTool({
name: string;
description: string;
fetcher: (query: string) => Promise<any>;
});
createZodTool<T extends z.ZodObject<any>>({
name: string;
description: string;
schema: T;
handler: (args: z.infer<T>) => Promise<any>;
});
createDbQueryTool({
name: string;
description: string;
queryHandler: (query: string) => Promise<any>;
});MCP 服务器
createMcpServer({
name: string;
url: string;
description?: string;
auth?: {
type: 'none' | 'bearer' | 'api_key';
token?: string;
};
});Agent 执行
// 简单执行
runAgent({
userPrompt: string;
systemPrompt?: string;
tools?: Tool[];
mcpServers?: McpServer[];
options?: Partial<AgentOptions>;
ifStream?: boolean;
});
// 流式执行
runAgentStream({
userPrompt: string;
systemPrompt?: string;
tools?: Tool[];
mcpServers?: McpServer[];
options?: Partial<AgentOptions>;
onUpdate?: (message: Message) => void;
});
// 链式 API
openaiAgent({ options?: Partial<AgentOptions>, ifStream?: boolean })
.addSystemPrompt({ systemPrompt: string })
.addUserPrompt({ userPrompt: string })
.addMessages({ messages: Message[] })
.addTools({ tools: Tool[] })
.addMcpServer({ mcpServers: McpServer[] })
.go({ maxIterations?: number })
.goStream({ maxIterations?: number, onUpdate?: (message: Message) => void });React Hooks
useAgent({
initialSystemPrompt?: string;
model?: string;
temperature?: number;
tools?: Tool[];
mcpServers?: McpServer[];
debug?: boolean;
});许可证
MIT
