使用Langchain处理结构化数据,以JsonOutputParser为例。以下是具体步骤和代码示例:
-
导入所需库:
from config import llm from langchain_core.output_parsers import JsonOutputParser from langchain_core.prompts import PromptTemplate from langchain_core.pydantic_v1 import BaseModel, Field
-
定义数据模型:
class People(BaseModel): name: str = Field(description="人物的名称") age: str = Field(description="人物的年龄") country: str = Field(description="人物的国籍")
-
设置JsonOutputParser:
parser = JsonOutputParser(pydantic_object=People)
-
设置提示模板:
prompt = PromptTemplate( template="Answer the user query.\n{format_instructions}\n{query}\n", input_variables=["query"], partial_variables={"format_instructions": parser.get_format_instructions()}, )
-
定义链操作:
chain = prompt | llm | parser
-
调用链操作并处理查询:
query = "姚明" result = chain.invoke({"query": query}) print(result)
-
示例输出:
{'name': '姚明', 'age': '40', 'country': '中国'}
Process finished with exit code 0