测试游记听白
← 文章归档

LangChain进行格式化输出

背景

LangChain是一个强大的框架,可以帮助开发者更高效地构建基于大型语言模型(LLM)的应用。在实际开发中,我们常常希望模型的输出不是一段纯文本,而是结构化、格式化的数据(如JSON、表格等),以便下游进一步处理。

一、为什么需要格式化输出?

  • 结构化数据易于处理
    可以直接转换为数据库记录、前端展示等。
  • 方便后续逻辑判断
    如根据意图分类或信息抽取结果做不同操作。
  • 提升交互体验
    让用户或系统能更好地理解和利用LLM的输出内容。

二、LangChain中的输出解析器(Output Parser)

https://python.langchain.com/api_reference/core/output_parsers.html
LangChain提供了多种内置的OutputParser,也支持自定义。常用的有:

  • StrOutputParser
    :直接返回字符串(默认)
  • JsonOutputParser
    :解析JSON格式内容

三、代码实战——让LLM返回JSON格式的测试用例

1、安装依赖

pip install -U langchain langchain_core langchain-openai openai pydantic

2、使用LangSmith观察结果

https://smith.langchain.com/

import os  

os.environ["LANGSMITH_TRACING"] = "true"  
os.environ["LANGSMITH_API_KEY"] = "lsv2_xxx"  

3、编写想要输出的json格式

from pydantic import BaseModel, Field  

class TestCase(BaseModel):  
    Method: str = Field(description="测试方法名称,例如:等价类划分、边界值分析、场景法、状态转换、安全测试、性能测试 等")  
    caseDesc: str = Field(description="用例描述")  
    caseStep: str = Field(description="用例步骤")  
    expectResult: str = Field(description="用例预期结果")  

4、拼接提示词

from langchain_core.prompts import PromptTemplate 
from langchain_core.output_parsers.json import JsonOutputParser

parser = JsonOutputParser(pydantic_object=TestCase)  

template = """你是一名资深测试工程师。请根据下述模块说明,使用适当的测试方法,编写完整的功能测试用例,数量不少于10条:  
模块说明: {module_desc}  
{format_instructions}  
"""
  

prompt = PromptTemplate(  
    template=template,  
    input_variables=["module_desc"],  
    partial_variables={"format_instructions": parser.get_format_instructions()},  
)  

5、调用大模型

from langchain_openai import ChatOpenAI  


llm = ChatOpenAI(  
    model="gpt-4.1",  
    api_key="sk-xxx",  
    base_url="https://oneapi.qunhequnhe.com/v1"  
)  

chain = prompt | llm | parser  
chain.invoke({"module_desc": "登录场景"})

四、查看结果

1、查看运行结果

image.png
image.png

2、查看LangSmith结果

可以看到合并后的提示词:

你是一名资深测试工程师。请根据下述模块说明,使用适当的测试方法,编写完整的功能测试用例,数量不少于10条:
模块说明: 登录场景
The output should be formatted as a JSON instance that conforms to the JSON schema below.

As an example, for the schema {"properties": {"foo": {"title": "Foo", "description": "a list of strings", "type": "array", "items": {"type": "string"}}}, "required": ["foo"]}
the object {"foo": ["bar", "baz"]} is a well-formatted instance of the schema. The object {"properties": {"foo": ["bar", "baz"]}} is not well-formatted.

Here is the output schema:
"""
{"
properties": {"Method": {"description": "测试方法名称,例如:等价类划分、边界值分析、场景法、状态转换、安全测试、性能测试 等", "title": "Method", "type": "string"}, "caseDesc": {"description": "用例描述", "title": "Casedesc", "type": "string"}, "caseStep": {"description": "用例步骤", "title": "Casestep", "type": "string"}, "expectResult": {"description": "用例预期结果", "title": "Expectresult", "type": "string"}}, "required": ["Method", "caseDesc", "caseStep", "expectResult"]}
"
""
image.png
image.png

五、小结

LangChain 之所以能够按照指定格式输出,核心原因就在于它对 提示词(Prompt)进行了优化和封装。

  • 优化提示词:加入具体的格式说明。
  • 引导模型生成规范结构文本/JSON等。
  • 用解析工具辅助检查/提取。
    通过这三步,LangChain 实现了高效且可靠的“指定格式输出”。

利用LangChain中的Prompt设计与Output Parser机制,可以方便地让大模型按照指定的数据结构(如JSON)返回结果,大大提升了工程效率和可维护性。在实际项目中建议优先使用Pydantic来约束数据类型,提高安全性与健壮性。


查看微信公众号原文 ↗

搜索文章