自学内容网 自学内容网

基于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执行结果

在这里插入图片描述


原文地址:https://blog.csdn.net/qq_44375977/article/details/142928542

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!