大模型结构化输出pydantic示例
【代码】大模型结构化输出pydantic示例。
·
大模型结构化输出示例
from anthropic import BaseModel
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import Field
model_name = 'qwen3-vl-plus'
base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1" # 本地模型用:http://localhost:6006/v1
api_key = 'sk-cbe6d658ada24abbbb8abc2333fcc1ba' # 本地模型用:非空字符串
extra_body = {"enable_thinking": True, "thinking_budget": 81920}
llm = ChatOpenAI(
model=model_name,
api_key=api_key,
base_url=base_url,
temperature=0.8,
extra_body=extra_body,
)
class Joke(BaseModel):
title: str = Field(description="笑话的标题")
content: str = Field(description="笑话的内容")
parse: str = Field(description="笑点的解释说明")
score: float = Field(description="笑话的评分,范围是0到100")
prompt_template = PromptTemplate.from_template("帮我生成一个关于{topic}的笑话。")
# runnable = llm.with_structured_output(Joke)
runnable = llm.bind_tools([Joke])
chain = prompt_template | runnable
resp = chain.invoke({"topic": "美女"})
print(resp.tool_calls[0].get('args'))
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)