langchainJS -结构化输出(StructuredOutputParser )

      在LangChain的帮助下,我们可以为输出定义模式。StructuredOutputParser 使用定义的名称和描述来分析和构建模型预测的输出。

const productParser =
  StructuredOutputParser.fromNamesAndDescriptions({
    Name: "Name of The Product",
    Description: "Description Of The Product",
    Image: "Image of the Prodction",
  })

     如果我们的模型输出格式不正确,我们可以使用 OutputFixingParser。它是修复此类输出的非常有用的工具,确保我们提取的数据处于预期的结构中。

console.log("Using output fixing parser to fix output...")
const fixParser = OutputFixingParser.fromLLM(
  new OpenAI({
    apiKey: "sk-xxxxxxxx",
    baseURL:"https://api.chatanywhere.tech/v1",
    model: "gpt-3.5-turbo",
     temperature: 0, 
    }),
  productParser
)
const output = await fixParser.parse(result.output)
console.log(output)

导入模块

import {
  StructuredOutputParser,
  OutputFixingParser,
} from "langchain/output_parsers";

最后的代码

        下面的程序通过调用getProductInfomation  获取产品信息,该工具模仿了查询数据库获取产品信息,然后输出json 格式的结构。

import { initializeAgentExecutorWithOptions } from "langchain/agents";
import { OpenAI } from "@langchain/openai";
import { TavilySearchResults } from "@langchain/community/tools/tavily_search";
import { z } from "zod";
import { DynamicStructuredTool } from "@langchain/core/tools";
import {
  StructuredOutputParser,
  OutputFixingParser,
} from "langchain/output_parsers";
process.env['OPENAI_API_KEY']="sk-xxxxxxxxxxxxxxxx";
process.env['OPENAI_BASE_URL']="https://api.chatanywhere.tech/v1"
process.env['TAVILY_API_KEY']="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"


const openai = new OpenAI({
    apiKey: "sk-FfhkMFdQQwDqAR5Mta2UxsU9amU6AoIwDG1NbqqAWGzMpTyi",
    baseURL:"https://api.chatanywhere.tech/v1",
    model: "gpt-3.5-turbo",
  temperature: 0
})
const productParser =
  StructuredOutputParser.fromNamesAndDescriptions({
    Name: "Name of The Product",
    Description: "Description Of The Product",
    Image: "Image of the Prodction",
  })
const addTool = new DynamicStructuredTool({
    name: "add",
    description: "Add two integers together.",
    schema: z.object({
      firstInt: z.number(),
      secondInt: z.number(),
    }),
    func: async ({ firstInt, secondInt }) => {
      return (firstInt + secondInt).toString();
    },
  });
  const getProductInfomation = new DynamicStructuredTool({
    name: "getProductInfomation",
    description: "use this tool when you need to get product information ",
    schema: z.object({
        ID: z.string().describe("The ID of Product"),
    }),
    func: async ({ ID }) => {
      console.log("ProductID"+ID)
      return JSON.stringify({
        Name:"Milk",
        Description:"low suger milk",
        Image:"milk.png"
        });
    },
  });

const tools = [
  new TavilySearchResults(),
 addTool,  
 getProductInfomation,
];
const executor = await initializeAgentExecutorWithOptions(
     tools,
     openai,
    { agentType: "structured-chat-zero-shot-react-description", verbose: false }
   );
//Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?
const input = `get information of the product with ID=2323 ,ouput in JSON Format`;
const result = await executor.invoke(
    {
        input: input,
        
      }

)
console.log(result.output)
console.log("Using output fixing parser to fix output...")
const fixParser = OutputFixingParser.fromLLM(
  new OpenAI({
    apiKey: "sk-xxxxxxxxxxxxxxxxx",
    baseURL:"https://api.chatanywhere.tech/v1",
    model: "gpt-3.5-turbo",
     temperature: 0, 
    }),
  productParser
)
const output = await fixParser.parse(result.output)
console.log(output)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值