AI Agent 与 LLM Skill:构建智能自主系统
AI Agent 不仅仅是一个聊天机器人,而是能够自主规划、执行任务、使用工具的智能系统。本文将深入探讨如何构建真正智能的 AI Agent,以及 LLM Skill 的设计模式。
什么是 AI Agent?
AI Agent 是一个能够:
- 感知环境:获取上下文信息
- 自主决策:规划执行步骤
- 执行动作:调用工具完成任务
- 学习改进:从反馈中优化
Agent 架构
┌─────────────────────────────────────────┐
│ AI Agent │
│ │
│ ┌──────────┐ ┌──────────┐ ┌────────┐│
│ │ Perceive │→ │ Think │→ │ Act ││
│ │ 感知 │ │ 思考 │ │ 行动 ││
│ └──────────┘ └──────────┘ └────────┘│
│ ↑ ↓ ↓ │
│ └──────────────┴────────────┘ │
│ Feedback Loop │
└─────────────────────────────────────────┘Agent 的核心组件
1. Perception(感知)
Agent 需要理解当前状态:
interface AgentPerception {
// 环境信息
environment: {
currentDirectory: string;
availableFiles: string[];
runningProcesses: Process[];
};
// 任务上下文
context: {
userGoal: string;
conversationHistory: Message[];
previousActions: Action[];
};
// 可用工具
tools: {
name: string;
description: string;
parameters: Schema;
}[];
}2. Planning(规划)
Agent 制定执行计划:
interface AgentPlan {
goal: string;
steps: {
id: string;
action: string;
tool: string;
parameters: Record<string, any>;
dependencies: string[];
expectedOutcome: string;
}[];
fallbackStrategies: {
condition: string;
alternativePlan: AgentPlan;
}[];
}3. Execution(执行)
Agent 执行计划:
class AgentExecutor {
async execute(plan: AgentPlan): Promise<ExecutionResult> {
const results: StepResult[] = [];
for (const step of plan.steps) {
// 检查依赖
await this.checkDependencies(step.dependencies, results);
// 执行步骤
const result = await this.executeStep(step);
results.push(result);
// 检查是否需要调整计划
if (result.requiresReplanning) {
const newPlan = await this.replan(plan, results);
return this.execute(newPlan);
}
}
return { success: true, results };
}
private async executeStep(step: Step): Promise<StepResult> {
const tool = this.tools.get(step.tool);
try {
const output = await tool.execute(step.parameters);
return {
stepId: step.id,
success: true,
output,
requiresReplanning: false,
};
} catch (error) {
return {
stepId: step.id,
success: false,
error: error.message,
requiresReplanning: true,
};
}
}
}4. Learning(学习)
Agent 从经验中学习:
class AgentMemory {
private experiences: Experience[] = [];
async learn(experience: Experience) {
// 存储经验
this.experiences.push(experience);
// 提取模式
const patterns = await this.extractPatterns(experience);
// 更新策略
await this.updateStrategies(patterns);
}
async recall(context: Context): Promise<Experience[]> {
// 检索相似经验
return this.experiences.filter(exp =>
this.isSimilar(exp.context, context)
);
}
private async extractPatterns(experience: Experience) {
// 使用 LLM 分析经验
const analysis = await this.llm.analyze({
prompt: `分析以下经验,提取可复用的模式:
任务:${experience.task}
行动:${experience.actions}
结果:${experience.outcome}
`,
});
return analysis.patterns;
}
}LLM Skill 设计模式
Skill 是 Agent 的能力单元,类似于函数或工具。
Skill 结构
interface Skill {
// 元数据
name: string;
description: string;
category: string;
version: string;
// 输入输出
inputSchema: JSONSchema;
outputSchema: JSONSchema;
// 执行逻辑
execute(input: any): Promise<any>;
// 示例
examples: {
input: any;
output: any;
explanation: string;
}[];
}实现 Skill
class CodeReviewSkill implements Skill {
name = 'code_review';
description = '审查代码质量、安全性和最佳实践';
category = 'development';
version = '1.0.0';
inputSchema = {
type: 'object',
properties: {
code: { type: 'string' },
language: { type: 'string' },
focusAreas: {
type: 'array',
items: { type: 'string' },
},
},
required: ['code', 'language'],
};
outputSchema = {
type: 'object',
properties: {
issues: {
type: 'array',
items: {
type: 'object',
properties: {
severity: { type: 'string' },
line: { type: 'number' },
message: { type: 'string' },
suggestion: { type: 'string' },
},
},
},
score: { type: 'number' },
summary: { type: 'string' },
},
};
async execute(input: {
code: string;
language: string;
focusAreas?: string[];
}) {
// 1. 静态分析
const staticIssues = await this.staticAnalysis(input.code, input.language);
// 2. LLM 审查
const llmReview = await this.llmReview(input.code, input.focusAreas);
// 3. 合并结果
const issues = [...staticIssues, ...llmReview.issues];
// 4. 计算分数
const score = this.calculateScore(issues);
return {
issues,
score,
summary: llmReview.summary,
};
}
private async llmReview(code: string, focusAreas?: string[]) {
const prompt = `审查以下代码:
\`\`\`
${code}
\`\`\`
${focusAreas ? `重点关注:${focusAreas.join(', ')}` : ''}
请提供:
1. 发现的问题(严重程度、位置、描述、建议)
2. 总体评价
`;
const response = await this.llm.complete(prompt);
return this.parseReviewResponse(response);
}
examples = [
{
input: {
code: 'function add(a, b) { return a + b; }',
language: 'javascript',
},
output: {
issues: [],
score: 95,
summary: '代码简洁清晰,无明显问题',
},
explanation: '简单函数的审查示例',
},
];
}Skill 组合
class SkillComposer {
async compose(skills: Skill[], workflow: Workflow) {
const results = new Map();
for (const step of workflow.steps) {
const skill = skills.find(s => s.name === step.skillName);
// 准备输入(可能来自前面步骤的输出)
const input = this.prepareInput(step, results);
// 执行 Skill
const output = await skill.execute(input);
// 存储结果
results.set(step.id, output);
}
return results;
}
private prepareInput(step: WorkflowStep, previousResults: Map<string, any>) {
const input = { ...step.input };
// 替换引用
for (const [key, value] of Object.entries(input)) {
if (typeof value === 'string' && value.startsWith('$')) {
const [stepId, field] = value.slice(1).split('.');
input[key] = previousResults.get(stepId)?.[field];
}
}
return input;
}
}
// 使用示例
const workflow = {
steps: [
{
id: 'read',
skillName: 'read_file',
input: { path: 'src/App.tsx' },
},
{
id: 'review',
skillName: 'code_review',
input: {
code: '$read.content', // 引用前面步骤的输出
language: 'typescript',
},
},
{
id: 'fix',
skillName: 'auto_fix',
input: {
code: '$read.content',
issues: '$review.issues',
},
},
],
};实战案例
案例 1:自动化测试 Agent
class TestingAgent {
async generateTests(component: string) {
// 1. 感知:分析组件
const analysis = await this.analyzeComponent(component);
// 2. 规划:制定测试策略
const plan = await this.planTests(analysis);
// 3. 执行:生成测试
const tests = await this.generateTestCode(plan);
// 4. 验证:运行测试
const results = await this.runTests(tests);
// 5. 学习:记录经验
await this.memory.learn({
task: 'generate_tests',
context: { component, analysis },
actions: plan.steps,
outcome: results,
});
return tests;
}
private async planTests(analysis: ComponentAnalysis) {
const prompt = `为以下组件制定测试计划:
组件类型:${analysis.type}
Props:${JSON.stringify(analysis.props)}
状态:${JSON.stringify(analysis.state)}
事件:${analysis.events.join(', ')}
请提供:
1. 需要测试的场景
2. 每个场景的测试步骤
3. 预期结果
`;
const response = await this.llm.complete(prompt);
return this.parseTestPlan(response);
}
}案例 2:代码重构 Agent
class RefactoringAgent {
async refactor(code: string, goal: string) {
// 1. 分析代码
const analysis = await this.skills.analyze_code.execute({ code });
// 2. 识别重构机会
const opportunities = await this.identifyOpportunities(analysis, goal);
// 3. 制定重构计划
const plan = await this.planRefactoring(opportunities);
// 4. 执行重构
let refactoredCode = code;
for (const step of plan.steps) {
refactoredCode = await this.applyRefactoring(refactoredCode, step);
// 验证重构后代码仍然正确
const isValid = await this.validateCode(refactoredCode);
if (!isValid) {
// 回滚并尝试其他方案
refactoredCode = code;
continue;
}
}
return refactoredCode;
}
private async identifyOpportunities(
analysis: CodeAnalysis,
goal: string
) {
const prompt = `分析以下代码,识别重构机会:
目标:${goal}
代码分析:
- 复杂度:${analysis.complexity}
- 重复代码:${analysis.duplications.length} 处
- 长函数:${analysis.longFunctions.length} 个
- 代码异味:${analysis.codeSmells.join(', ')}
请列出具体的重构建议,按优先级排序。
`;
const response = await this.llm.complete(prompt);
return this.parseOpportunities(response);
}
}案例 3:文档生成 Agent
class DocumentationAgent {
async generateDocs(project: Project) {
// 1. 扫描项目
const structure = await this.scanProject(project.path);
// 2. 分析代码
const analysis = await this.analyzeCodebase(structure);
// 3. 生成文档大纲
const outline = await this.generateOutline(analysis);
// 4. 填充内容
const docs = await this.fillContent(outline, analysis);
// 5. 生成示例
const examples = await this.generateExamples(analysis);
// 6. 组装文档
return this.assembleDocs(docs, examples);
}
private async generateOutline(analysis: CodebaseAnalysis) {
const prompt = `为以下项目生成文档大纲:
项目类型:${analysis.type}
主要模块:${analysis.modules.map(m => m.name).join(', ')}
API 端点:${analysis.apis.length} 个
组件:${analysis.components.length} 个
请生成详细的文档大纲,包括:
1. 快速开始
2. 核心概念
3. API 参考
4. 示例代码
5. 最佳实践
`;
const response = await this.llm.complete(prompt);
return this.parseOutline(response);
}
}Agent 设计模式
1. ReAct Pattern(推理-行动)
class ReActAgent {
async solve(problem: string) {
let thought = '';
let action = '';
let observation = '';
while (!this.isSolved(observation)) {
// Thought: 推理下一步
thought = await this.think(problem, observation);
// Action: 执行动作
action = await this.selectAction(thought);
observation = await this.executeAction(action);
// 记录轨迹
this.trace.push({ thought, action, observation });
}
return this.extractSolution(observation);
}
}2. Chain-of-Thought Pattern(思维链)
class ChainOfThoughtAgent {
async reason(problem: string) {
const steps = [];
// 分解问题
const subproblems = await this.decompose(problem);
// 逐步解决
for (const subproblem of subproblems) {
const solution = await this.solveStep(subproblem, steps);
steps.push({ problem: subproblem, solution });
}
// 综合答案
return this.synthesize(steps);
}
}3. Multi-Agent Pattern(多智能体)
class MultiAgentSystem {
private agents: Agent[] = [];
async collaborate(task: Task) {
// 分配任务
const assignments = await this.assignTasks(task, this.agents);
// 并行执行
const results = await Promise.all(
assignments.map(async ({ agent, subtask }) => {
return agent.execute(subtask);
})
);
// 协调结果
return this.coordinate(results);
}
private async assignTasks(task: Task, agents: Agent[]) {
// 根据 Agent 能力分配任务
const assignments = [];
for (const agent of agents) {
const suitability = await this.assessSuitability(agent, task);
if (suitability > 0.7) {
const subtask = await this.extractSubtask(task, agent.capabilities);
assignments.push({ agent, subtask });
}
}
return assignments;
}
}最佳实践
1. 明确的 Skill 接口
// ✅ 好:清晰的输入输出
interface Skill {
name: string;
description: string;
inputSchema: JSONSchema;
outputSchema: JSONSchema;
execute(input: any): Promise<any>;
}
// ❌ 不好:模糊的接口
interface Skill {
run(...args: any[]): any;
}2. 错误处理和重试
class ResilientAgent {
async execute(action: Action, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await this.performAction(action);
} catch (error) {
if (i === maxRetries - 1) throw error;
// 分析错误并调整策略
const adjustment = await this.analyzeError(error);
action = this.adjustAction(action, adjustment);
}
}
}
}3. 可观测性
class ObservableAgent {
private logger: Logger;
private metrics: Metrics;
async execute(task: Task) {
const span = this.tracer.startSpan('agent.execute');
try {
this.logger.info('Starting task', { task });
this.metrics.increment('tasks.started');
const result = await this.performTask(task);
this.metrics.increment('tasks.completed');
return result;
} catch (error) {
this.logger.error('Task failed', { task, error });
this.metrics.increment('tasks.failed');
throw error;
} finally {
span.end();
}
}
}工具和框架
LangChain
import { OpenAI } from 'langchain/llms/openai';
import { initializeAgentExecutorWithOptions } from 'langchain/agents';
import { Calculator } from 'langchain/tools/calculator';
const model = new OpenAI({ temperature: 0 });
const tools = [new Calculator()];
const executor = await initializeAgentExecutorWithOptions(tools, model, {
agentType: 'zero-shot-react-description',
});
const result = await executor.call({
input: 'What is 25 * 4 + 10?',
});AutoGPT
from autogpt import AutoGPT
agent = AutoGPT(
name="CodeReviewer",
role="Code review specialist",
goals=[
"Review code for quality issues",
"Suggest improvements",
"Generate test cases"
]
)
agent.run()总结
构建智能 AI Agent 需要:
- ✅ 清晰的架构设计
- ✅ 模块化的 Skill 系统
- ✅ 有效的规划和执行
- ✅ 持续的学习和改进
AI Agent 是未来软件开发的重要方向,掌握这些技术将让你在 AI 时代保持竞争力!
参考资源
开始构建你的 AI Agent,创造智能自主系统!
