langchain.js使用function call

2024-09-19 13:49:22 阅读:2 编辑

openai,deepseek都支持

import { z } from "zod";
import { tool } from "@langchain/core/tools";
import {ChatOpenAI} from "@langchain/openai";
/*let chat_param = {
    openAIApiKey: 'sk',
    temperature: 0,
    modelName: "deepseek-chat",
    maxTokens:500,
    configuration: {
        baseURL: 'https://api.deepseek.com',
    },
};*/
let chat_param = {
    openAIApiKey: 'sk',
    temperature: 0.9,
    modelName: "gpt-4o-mini",
    //modelName: "gpt-3.5-turbo",
    maxTokens:500,
    configuration: {
        baseURL: 'https://api.openai-proxy.org/v1',
    },
};
const llm  = new ChatOpenAI(chat_param);
const addTool = tool(
    async ({ a, b }) => {
        return a + b;
    },
    {
        name: "add",
        schema: z.object({
            a: z.number(),
            b: z.number(),
        }),
        description: "Adds a and b.",
    }
);

const multiplyTool = tool(
    async ({ a, b }) => {
        return a * b;
    },
    {
        name: "multiply",
        schema: z.object({
            a: z.number(),
            b: z.number(),
        }),
        description: "Multiplies a and b.",
    }
);

const tools = [addTool, multiplyTool];

import { HumanMessage } from "@langchain/core/messages";

const llmWithTools = llm.bindTools(tools);

const messages = [new HumanMessage("What is 3 * 12? Also, what is 11 + 49?")];

const aiMessage = await llmWithTools.invoke(messages);

console.log(aiMessage);
messages.push(aiMessage);
const toolsByName = {
    add: addTool,
    multiply: multiplyTool,
};

for (const toolCall of aiMessage.tool_calls) {
    const selectedTool = toolsByName[toolCall.name];
    const toolMessage = await selectedTool.invoke(toolCall);
    messages.push(toolMessage);
}

//messages.push(aiMessage);
console.log(messages);
let res =await llmWithTools.invoke(messages);
console.log(res);