大模型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) # 直接拿到对象,舒服!
相关推荐
程序员于老七16 分钟前
漫话大模型:先画轮廓再画细节——从 Flow Matching 看生成模型的“殊途同归“
深度学习·大模型·ai编程·diffusion·flowmatching
像风一样自由202028 分钟前
17.Milvus如何完成一次向量相似度检索
人工智能·postgresql·大模型·milvus·rag·智能体
像风一样自由20201 小时前
19.Milvus数据分片扩展与高并发设计
postgresql·大模型·milvus·rag·智能体
艺杯羹1 小时前
双轨大模型路由实战:从端侧Ollama边缘推理到云端大模型容灾降级架构深度拆解
开发语言·人工智能·ai·架构·php
知了一笑1 小时前
AI生产力:从效率到工作流重构
人工智能·ai·ai工作流
苏灵凯1 小时前
Codex 官网前端可以抄吗?从设计到实现的技术拆解
笔记·ai·agent·codex·deepseek
苏子寒4 小时前
Nano-VLLM全代码解析笔记(10)-GemmaRMSNorm和MRoPE
笔记·机器学习·ai·nlp·vllm
绵满9 小时前
"AgentOPSD: Recursive Self-Distillation for Agentic Reinforcement Learning" 论文笔记
大模型·智能体记忆
yiwanbin9 小时前
Codex 企业级安装教程
ai
知了一笑9 小时前
个体看衰AI,企业加速转型
人工智能·ai