第四节:outputparser解析输出

在使用大语言模型(LLM)时,我们不仅需要生成文本,还需要以结构化的方式解析和处理模型的输出。Langchain Go提供了outputparser包来帮助我们完成这个任务。本文将详细介绍如何使用Langchain Go中的outputparser来解析LLM的输出。

1. OutputParser简介
OutputParser是Langchain中的一个重要组件,它用于解析大语言模型的输出,将其转换为结构化的数据格式。在Go语言版本的Langchain中,outputparser包提供了多种解析器,其中Structured是最常用的结构化输出解析器。

2. 核心概念
2.1 ResponseSchema
ResponseSchema用于定义期望的输出结构,包含两个字段:
Name:输出字段的名称
Description:对字段内容的描述
2.2 Structured Parser
Structured是一个结构化输出解析器,可以将LLM的输出解析为键值对映射。
3. 实际应用示例
以下是一个完整的示例,展示如何使用outputparser解析LLM的输出:

package main

import (
    "context"
    "fmt"
    "github.com/tmc/langchaingo/llms"
    "github.com/tmc/langchaingo/llms/ollama"
    "github.com/tmc/langchaingo/outputparser"
    "github.com/tmc/langchaingo/prompts"
    "log"
)

// getLLmOpenaiClientNew 创建并返回一个Ollama LLM客户端
func getLLmOpenaiClientNew() *ollama.LLM {
    llm, err := ollama.New(
        ollama.WithModel("llama3.2"), // 指定使用的模型
    )
    if err != nil {
        log.Fatal(err)
    }
    return llm
}

func main() {
    ctx := context.Background()
    
    // 定义提示模板和输入变量
    var (
        template           = "请你为{{.dep}} 部门入职员工{{.name}}设计一个自我介绍"
        templateInputValue = []string{"dep", "name"}
    )
    
    // 创建结构化输出解析器
    // 定义期望的输出结构:
    // 1. content字段:包含员工自我介绍
    // 2. reason字段:说明为什么这么介绍
    structured := outputparser.NewStructured([]outputparser.ResponseSchema{
        {
            Name:        "content",
            Description: "员工自我介绍",
        },
        {
            Name:        "reason",
            Description: "为什么这么介绍",
        },
    })

    // 获取格式化指令,告诉LLM如何格式化输出
    instructions := structured.GetFormatInstructions()

    // 创建提示模板,将原始模板与格式化指令结合
    promptStr := prompts.NewPromptTemplate(template+"\n"+instructions, templateInputValue)

    // 定义输入数据
    staff := map[string]any{
        "dep":  "开发部",
        "name": "张三",
    }

    // 格式化提示词
    prompt, err := promptStr.FormatPrompt(staff)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("prompt:", prompt.String())
    
    // 创建LLM客户端并生成内容
    llm := getLLmOpenaiClientNew()
    singlePrompt, err := llms.GenerateFromSinglePrompt(ctx, llm, prompt.String())
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("LLM 输出:", singlePrompt)
}

4. 工作流程详解
4.1 定义输出结构
首先,我们需要定义期望从LLM获取的输出结构:

structured := outputparser.NewStructured([]outputparser.ResponseSchema{
    {
        Name:        "content",
        Description: "员工自我介绍",
    },
    {
        Name:        "reason",
        Description: "为什么这么介绍",
    },
})

4.2 获取格式化指令
通过GetFormatInstructions()方法获取格式化指令,这些指令会告诉LLM应该如何格式化其输出:

instructions := structured.GetFormatInstructions()

对于上面的定义,生成的格式化指令如下:

The output should be a markdown code snippet formatted in the following schema:
json { "content": string // 员工自我介绍 "reason": string // 为什么这么介绍 }

4.3 构建提示词
将原始提示词模板与格式化指令结合:

promptStr := prompts.NewPromptTemplate(template+"\n"+instructions, templateInputValue)

4.4 解析输出
当LLM返回输出后,outputparser会自动解析符合格式的JSON结构,并验证是否包含所有必需的字段。

5. 总结
OutputParser是Langchain中非常有用的组件,它可以帮助我们:
1.规范LLM的输出格式
2.将非结构化的文本转换为结构化数据
3.验证输出的完整性
4.提高与LLM交互的可靠性
通过合理使用outputparser,我们可以更有效地处理LLM的输出,构建更稳定和可靠的AI应用。

 

posted @ 2025-09-18 18:02  phpwyl  阅读(17)  评论(0)    收藏  举报