欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 会展 > 基于langchain.js快速搭建AI-Agent

基于langchain.js快速搭建AI-Agent

2024/10/23 21:35:17 来源:https://blog.csdn.net/qq_44375977/article/details/142928542  浏览:    关键词:基于langchain.js快速搭建AI-Agent

基于langchain.js快速搭建AI-Agent

什么是AIAgent?

在这里插入图片描述

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工具集

提供工具集,供Agent自主决策

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. 创建初始化提示词

构建对话提示词(可引入Prompt工程化能力)

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工作流

创建智能体,通过提示词,Calling工具集,让AI具有内容感知&自主决策等执行能力

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通过分布查询,聚合结果,给我想要的答案`,
});

Agent执行结果

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com