当前位置: 首页 > article >正文

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

在这里插入图片描述


http://www.kler.cn/news/356435.html

相关文章:

  • Mybatis Plus 查看组装的SQL条件的办法
  • 叉车安全防撞装置的作用
  • Spark任务OOM问题如何解决?
  • 【C语言】数据的输入格式
  • wordpress隐藏后台管理登录地址修改wp-admin确保WordPress网站后台安全
  • Linux进程信号(个人笔记)
  • 油烟净化器科技创新,造就绿色低碳餐饮生活
  • 机器学习|Pytorch实现天气预测
  • 【踩坑随笔】按照常规操作安装VMware tools之后还是无法复制粘贴的最简解决方案
  • 【gRPC】—gRPC底层详解RPC系列
  • 【不知道原因的问题】java.lang.AbstractMethodError
  • C#两个窗体之间传递参数
  • Vert.x,Web - Web
  • Python、C#、C++音频处理库
  • 10月18日,每日信息差
  • YOLOv11来了 | 自定义目标检测
  • 如何推进重构
  • 高级java每日一道面试题-2024年10月17日-Web篇-常见的web攻击有哪些?
  • Windows+Docker
  • docker 仓库之harbor详解