from openai import OpenAI from pydantic import BaseModel MODEL_NAME = "Qwen/Qwen2.5-7B-Instruct" API_KEY = "您的 APIKEY", # 从https://cloud.siliconflow.cn/account/ak获取 client = OpenAI(api_key=API_KEY, base_url="https://api.siliconflow.cn/v1") class Step(BaseModel): explanation: str output: str class MathReasoning(BaseModel): steps: list[Step] final_answer: str json_schema = MathReasoning.model_json_schema() completion = client.chat.completions.create( model=MODEL_NAME, messages=[ {"role": "system", "content": "You are a helpful math tutor. Guide the user through the solution step by step."}, {"role": "user", "content": "how can I solve 8x + 7 = -23"} ], response_format={ "type": "json_schema", "json_schema": { "name": "math_response", "schema": json_schema } } ) math_reasoning = completion.choices[0].message.content print(math_reasoning)
输出示例:
Copy
{ "steps": [ { "explanation": "Start with the equation 8x + 7 = -23.", "output": "8x + 7 = -23" }, { "explanation": "Subtract 7 from both sides to isolate the term with the variable.", "output": "8x = -23 - 7" }, { "explanation": "Simplify the right side of the equation.", "output": "8x = -30" }, { "explanation": "Divide both sides by 8 to solve for x.", "output": "x = -30 / 8" }, { "explanation": "Simplify the fraction.", "output": "x = -15 / 4" } ], "final_answer": "x = -15 / 4"}
结构化数据提取
您可以定义结构化字段以从无结构输入数据中提取信息,例如研究论文。
从研究论文中提取数据使用结构化输出
Copy
from openai import OpenAI from pydantic import BaseModel MODEL_NAME = "Qwen/Qwen2.5-7B-Instruct" API_KEY = "您的 APIKEY", # 从https://cloud.siliconflow.cn/account/ak获取 client = OpenAI(api_key=API_KEY, base_url="https://api.siliconflow.cn/v1") class ResearchPaperExtraction(BaseModel): title: str authors: list[str] abstract: str keywords: list[str] json_schema = ResearchPaperExtraction.model_json_schema() completion = client.chat.completions.create( model=MODEL_NAME, messages=[ {"role": "system", "content": "You are an expert at structured data extraction. You will be given unstructured text from a research paper and should convert it into the given structure."}, {"role": "user", "content": "..."} ], response_format={ "type": "json_schema", "json_schema": { "name": "math_response", "schema": json_schema } } ) math_reasoning = completion.choices[0].message.content print(math_reasoning)
输出示例:
Copy
{ "title": "Application of Quantum Algorithms in Interstellar Navigation: A New Frontier", "authors": [ "Dr. Stella Voyager", "Dr. Nova Star", "Dr. Lyra Hunter" ], "abstract": "This paper investigates the utilization of quantum algorithms to improve interstellar navigation systems. By leveraging quantum superposition and entanglement, our proposed navigation system can calculate optimal travel paths through space-time anomalies more efficiently than classical methods. Experimental simulations suggest a significant reduction in travel time and fuel consumption for interstellar missions.", "keywords": [ "Quantum algorithms", "interstellar navigation", "space-time anomalies", "quantum superposition", "quantum entanglement", "space travel" ] }
UI生成
你可以通过将 HTML 表示为具有约束条件的递归数据结构(如枚举)来生成有效的 HTML。
使用结构化输出生成 HTML
Copy
from openai import OpenAI from pydantic import BaseModel MODEL_NAME = "Qwen/Qwen2.5-7B-Instruct" API_KEY = "您的 APIKEY", # 从https://cloud.siliconflow.cn/account/ak获取 client = OpenAI(api_key=API_KEY, base_url="https://api.siliconflow.cn/v1") class UIType(str, Enum): div = "div" button = "button" header = "header" section = "section" field = "field" form = "form" class Attribute(BaseModel): name: str value: str class UI(BaseModel): type: UIType label: str children: List["UI"] attributes: List[Attribute] UI.model_rebuild() # This is required to enable recursive types class Response(BaseModel): ui: UI json_schema = Response.model_json_schema() completion = client.chat.completions.create( model= MODEL_NAME, messages=[ {"role": "system", "content": "You are a UI generator AI. Convert the user input into a UI."}, {"role": "user", "content": "Make a User Profile Form"} ], response_format={ "type": "json_schema", "json_schema": { "name": "ui schema", "schema": json_schema } } ) math_reasoning = completion.choices[0].message.content print(math_reasoning)
try: completion = client.beta.chat.completions.parse( model="gpt-4o-2024-08-06", messages=[ {"role": "system", "content": "You are a helpful math tutor. Guide the user through the solution step by step."}, {"role": "user", "content": "how can I solve 8x + 7 = -23"} ], response_format=MathResponse, max_tokens=50 ) math_response = completion.choices[0].message if math_response.parsed: print(math_response.parsed) elif math_response.refusal: # handle refusal print(math_response.refusal)except Exception as e: # Handle edge cases if type(e) == openai.LengthFinishReasonError: # Retry with a higher max tokens print("Too many tokens: ", e) pass else: # Handle other exceptions print(e) pass