大模型JSON格式输出:instructor

参考:

https://github.com/567-labs/instructor

安装:

复制代码
pip install instructor

使用:

复制代码
from pydantic import BaseModel 
import instructor
from openai import OpenAI 

 # 定义你想要的数据结构 
class UserInfo(BaseModel):     
      name: str     
      age: int    
      skills: list[str]  

# 1. 準備工作:初始化用戶端
client = OpenAI(
    # 建議通過環境變數配置API Key,避免寫入程式碼。
    api_key="&&&393",
    # API Key與地區強綁定,請確保base_url與API Key的地區一致。
    base_url="https://&&olces.com/api/v3",
)

# 自动给 LLM 加上结构化约束
client = instructor.patch(client) 
 
user_info = client.chat.completions.create(    
 model="deepseek-v3-1-terminus",    
 response_model=UserInfo, #   直接传类,甚至不需要自己写 JSON Prompt    
 messages=[{"role": "user", "content": "Melon 今年 25 岁,擅长 Python 和 AI"}] ) 

print(user_info.name) # 直接拿到对象,舒服!
相关推荐
智行众维12 分钟前
数据驱动与AI融合——构建自动驾驶仿真测试新范式的实践
人工智能·测试工具·ai·自动驾驶·仿真测试·自动驾驶仿真测试·场景开发
奋进的芋圆21 分钟前
Spring Boot + RAG 项目中集成 MCP 接口技术文档
java·spring boot·ai
CodeCaptain26 分钟前
【无标题】
人工智能·经验分享·ai·ai编程
num_killer29 分钟前
小白的RAG缓存
缓存·ai·aigc
白狐_79839 分钟前
【华为认证】HCIP-AI V1.0 深度进阶:应用运营、未来展望与考前终极保过指南
大数据·人工智能·机器学习·ai·华为认证
驾数者41 分钟前
Flink SQL格式集成:JSON、Avro、Protobuf序列化详解
sql·flink·json
不会用AI的老炮1 小时前
【AI coding 智能体设计系列-06】SubAgent:上下文隔离与模块化协作
人工智能·ai·ai编程
村口曹大爷1 小时前
使用anythingLLM来调用gemini3 pro api
人工智能·ai·谷歌·gemini·anythingllm·gemini3pro
智泊AI8 小时前
一文讲清:主流大模型推理部署框架:vLLM、SGLang、TensorRT-LLM、ollama、XInference
llm
大霸王龙11 小时前
MinIO 对象存储系统架构图集
人工智能·llm·minio