基于langchain搭建AI-Agent
什么是AIAgent?
是一种能够感知环境、进行决策和执行动作的智能实体,也可以称为“人工智能代理”或“智能体”。
- 其核心采用LLM作为Agent的大脑,利用大模型的决策与思考能力,通过记忆模块,结合大模型决策,实现长期、短期规划能力。
- 通过整合视觉、听觉甚至触觉信息、外部信息输入,展现出多类型、多感官、多模态的感知与理解能力,甚至实现环境感知。
- 通过了解和使用各种工具,AI能够扩展自身能力甚至与外界产生交互。
1. 替换默认请求地址为自定义API
import { ChatOpenAI } from '@langchain/openai';
const chat = new ChatOpenAI({
model: 'gpt4o',
temperature: 0,
apiKey: '****',
configuration: {
baseURL: 'https://www.xx.com/v1',// 替换
},
});
2. 搭建自定义Tools工具集
import { DynamicTool } from 'langchain/tools';
// 定义callback函数
function getWeather(date: string) {
console.log('Func Calling: 执行getWeather', date);
// 这里应该是实际的天气API调用
return `${date} 的天气是阴雨天`;
}
function getWeatherScore(weather: string) {
console.log('Func Calling: 执行getWeatherScore', weather);
// 这里应该是实际的天气API调用
return `${weather} 的得分是99分`;
}
// 定义callback工具
const weatherTool = new DynamicTool({
name: 'Weather',
description: '获取某天的天气,需要传入日期',
func: async (date: string) => getWeather(date),
});
const weatherScoreTool = new DynamicTool({
name: 'WeatherScore',
description: '获取某个天气的推荐出行得分,需要传入天气',
func: async (wearcher: string) => getWeatherScore(wearcher),
});
// 定义工具集合
const tools = [weatherTool, weatherScoreTool];
3. 创建初始化提示词
import { ChatPromptTemplate } from '@langchain/core/prompts';
// 创建初始化提示词
const prompt = ChatPromptTemplate.fromMessages([ ['system', 'You are a helpful assistant'],
['placeholder', '{chat_history}'],
['human', '{input}'],
['placeholder', '{agent_scratchpad}'],
]);
4. 创建AI-Agent工作流
import { AgentExecutor, createOpenAIToolsAgent } from 'langchain/agents';
// 创建智能体
const agent = await createOpenAIToolsAgent({
llm: chat,
tools,
prompt,
streamRunnable: false,
});
// 创建执行器
const agentExecutor = new AgentExecutor({
agent,
tools,
});
const result = await agentExecutor.invoke({
input: `
# 问题
你好,告诉我2024-10-01日天气如何,并告诉我那个天气的出行得分
# step1
请先调用获取天气工具查询天气
# step2
以获取的天气调用得分查询工具
# step3
通过分布查询,聚合结果,给我想要的答案`,
});