利用langchain实现结构化输出的两种方式

BaseModel

这个类非常重要,非常重要,非常重要,如果需要利用langgraph构建路由函数,那么这个类是必须的,它的基础使用非常简单。

class get_entities(BaseModel):
    '''你需要抽取输入文本中关于疾病,症状,治疗药物相关的实体,并分别填充到对应的列表中'''
    disease: list=Field(description='疾病名称实体')
    symptom: list=Field(description='疾病症状实体')
    drug: list=Field(description='药物名称实体')

llm_gpt = ChatOpenAI(model="gpt-4o", temperature=0)
llm_qwen = ChatTongyi(model_name='qwen2.5-72b-instruct')

structured_llm_gpt = llm_gpt.with_structured_output(get_entities)
structured_llm_qwen = llm_qwen.with_structured_output(get_entities)

structured_llm_gpt.invoke(test_text)# get_entities(disease=['感冒'], symptom=[], drug=['阿莫西林'])
structured_llm_qwen.invoke(test_text)# get_entities(disease=['感冒'], symptom=[], drug=['阿莫西林'])

利用输出解释器

from langchain.prompts import PromptTemplate
from langchain.output_parsers import ResponseSchema, StructuredOutputParser

def structured_output_parser(response_schemas):
    text = '''
    请从以下文本中,抽取出实体信息,并按json格式返回,json包含首尾的 "```json" 和 "```"。
    以下是字段含义和类型,要求保留所有字段:\n
    '''
    for schema in response_schemas:
        text += schema.name + ' 字段,表示:' + schema.description + ',类型为:' + schema.type + '\n'
    return text

response_schemas = [
    ResponseSchema(type='list', name='disease', description='疾病名称实体'),
    ResponseSchema(type='list', name='symptom', description='疾病症状实体'),
    ResponseSchema(type='list', name='drug', description='药物名称实体'),
]

format_instructions = structured_output_parser(response_schemas)

output_parser = StructuredOutputParser.from_response_schemas(response_schemas)

template = '''
1、从以下用户输入的句子中,提取实体内容。
2、注意:根据用户输入的事实抽取内容,不要推理,不要补充信息。

{format_instructions}
------------
用户输入:{input}
------------
输出:
'''

prompt = PromptTemplate(
    template=template,
    partial_variables={'format_instructions': format_instructions},
    input_variables=['input']
)

chain = prompt|llm_qwen


llm_output = chain.invoke(input='感冒吃什么药好得快?可以吃阿莫西林吗?').content
print(llm_output)

output = output_parser.parse(llm_output)
print(output, type(output))
/```json
{
  "disease": ["感冒"],
  "symptom": [],
  "drug": ["阿莫西林"]
}
/```
{'disease': ['感冒'], 'symptom': [], 'drug': ['阿莫西林']} <class 'dict'>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值