文章主要讲解LangChain中JsonOutputParser的使用方法和流式JSON数据处理。
1. 安装依赖
pip install --upgrade --quiet langchain-core langchain-community langchain-openai
2. JsonOutputParser功能详解
- 基本功能:JSON字符串解析、数据类型转换、错误处理
- 使用场景:API响应处理、配置文件读取、数据交换
3. 实战代码
使用异步方式流式输出JSON数据:
from langchain_core.output_parsers import JsonOutputParser
from langchain_openai.chat_models import ChatOpenAI
async def main():
model = ChatOpenAI(model="gpt-3.5-turbo")
chain = model | JsonOutputParser()
async for text in chain.astream('要求模型输出JSON格式数据'):
print(text, flush=True)
流式输出会逐步显示JSON构建过程,从空对象逐步填充完整数据。
4. 提取JSON中的特定字段
定义函数从流式JSON中提取所需数据,通过管道操作链接到chain上:
def _extract_country_names(inputs):
if not isinstance(inputs, dict):
return ""
if "countries" not in inputs:
return ""
countries = inputs["countries"]
country_names = [country.get("name") for country in countries if isinstance(country, dict)]
return country_names