页面简介
正文摘录
Structured output (JSON mode) ensures that AI returns JSON data conforming to predefined formats, providing reliable guarantees for programmatic processing of AI outputs. Features The structured output feature provides AI models with strict data format control capabilities, supporting various complex data structures and validation requirements. Core Parameters response_format: Specifies the response format, set to {"type": "json_object"} to enable JSON mode model: Use models that support structured output, such as glm-5, glm-4.7, glm-4.6, etc. messages: Define the expected JSON structure and field requirements in system messages Code Examples Install SDK # Install latest version pip install zai-sdk # Or specify version pip install zai-sdk==0.2.3 Verify Installation import zai print(zai.__version__) Complete Example The following is a complete structured output example demonstrating how to perform sentiment analysis and return structured JSON results: from zai import ZaiClient import json # Initialize client client = ZaiClient(api_key="your-api-key") # Basic JSON mode response = client.chat.completions.create( model="glm-5", messages=[ { "role": "system", "content": """ You are a sentiment analysis expert. Please return analysis results in the following JSON format: { "sentiment": "positive/negative/neutral", "confidence": 0.95, "emotions": ["joy", "excitement"], "keywords": ["weather", "mood"], "analysis": "Detailed analysis explanation" } """ }, { "role": "user", "content": "Please analyze the sentiment of this sentence: 'The weather is really nice today, I'm feeling very happy!'" } ], response_format={ "type": "json_object" } ) # Parse results result = json.loads(response.choices[0].message.content) print(f"Sentiment: {result['sentiment']}") print(f"Confidence: {result['confidence']}") print(f"Emotions: {result['emotions']}") Basic Usage Simple JSON Output Specify JSON Structure Schema ValidationSimple JSON Outputfrom zai import ZaiClient client = ZaiClient(api_key="your-api-key") # Basic JSON mode response = client.chat.completions.create( model="glm-5", messages=[ { "role": "user", "content": "Please analyze the sentiment of this sentence: 'The weather is really nice today, I'm feeling very happy!'" } ], response_format={ "type": "json_object" } ) import json result = json.loads(response.choices[0].message.content) print(result) Specify JSON Structure# Specify specific JSON structure response = client.chat.completions.create( model="glm-5", messages=[ { "role": "system", "content": """ You are a sentiment analysis expert. Please return analysis results in the following JSON format: { "sentiment": "positive/negative/neutral", "confidence": 0.95, "emotions": ["joy", "excitement"], "keywords": ["weather", "mood"], "analysis": "Detailed analysis explanation" } """ }, { "role": "user", "content": "Please analyze the sentiment of this sentence: 'The weather is really nice today, I'm feeling very happy!'" } ], response_format={ "type": "json_object" } ) result = json.loads(response.choices[0].message.content) print(f"Sentiment: {result['sentiment']}") print(f"Confidence: {result['confidence']}") print(f"Emotions: {result['emotions']}") Using JSON Schema Validationimport jsonschema from jsonschema import validate # Define JSON Schema schema = { "type": "object", "properties": { "sentiment": { "type": "string", "enum": ["positive", "negative", "neutral"] }, "confidence": { "type": "number", "minimum": 0, "maximum": 1 }, "emotions": { "type": "array", "items": {"type": "string"} }, "keywords": { "type": "array", "items": {"type": "string"} }, "analysis": { "type": "string" } }, "required": ["sentiment", "confidence", "analysis"] } def analyze_sentiment_with_validation(text): """Sentiment analysis with validation""" response = client.chat.completions.create( model="glm-5", messages=[ { "role": "system", "content": f""" Please return sentiment analysis results according to the following JSON Schema format: {json.dumps(schema, indent=2, ensure_ascii=False)} """ }, { "role": "user", "content": f"Please analyze the sentiment of this sentence: '{text}'" } ], response_format={"type": "json_object"} ) try: result = json.loads(response.choices[0].message.content) # Validate JSON structure validate(instance=result, schema=schema) return result except jsonschema.exceptions.ValidationError as e: print(f"JSON validation failed: {e}") return None except json.JSONDecodeError as e: print(f"JSON parsing failed: {e}") return None # Usage example result = analyze_sentiment_with_validation("The weather is really nice today, I'm feeling very happy!") if result: print("Analysis result:", result) Scenario Examples When using JSON mode for data extraction, please ensure the quality and format of input data to achieve the best extraction results. Data Extraction and Structuring Complete Implementationclass DataExtractor: def __init__(self, api_key): self.client = ZaiClient(api_key=api_key) def extract_contact_info(self, text): """Extract contact information""" schema = { "type": "object", "properties": { "contacts": { "type": "array", "items": { "type": "object", "properties": { "name": {"type": "string"}, "phone": {"type": "string"}, "email": {"type": "string"}, "company": {"type": "string"}, "position": {"type": "string"}, "address": {"type": "string"} }, "required": ["name"] } }, "total_count": {"type": "integer"}, "extraction_confidence": {"type": "number"} }, "required": ["contacts", "total_count"] } response = self.client.chat.completions.create( model="glm-5", messages=[ { "role": "system", "content": f""" You are an information extraction expert. Please extract all contact information from the text, return in the following JSON format: {json.dumps(schema, indent=2, ensure_ascii=False)} Note: - If a field has no information, do not include that field - phone field should be in standardized phone number format - email field should be a valid email address - extraction_confidence represents overall extraction confidence (0-1) """ }, { "role": "user", "content": f"Please extract contact information from the following text:\n\n{text}" } ], response_format={"type": "json_object"} ) try: result = json.loads(response.choices[0].message.content)["properties"] validate(instance=result, schema=schema) return result except Exception as e: print(f"Extraction failed: {e}") return None def extract_product_info(self, product_description): """Extract product information""" schema = { "type": "object", "properties": { "product_name": {"type": "string"}, "brand": {"type": "string"}, "category": {"type": "string"}, "price": { "type": "object", "properties": { "amount": {"type": "number"}, "currency": {"type": "string"}, "original_price": {"type": "number"}, "discount": {"type": "number"} } }, "specifications": { "type": "object", "additionalProperties": True }, "features": { "type": "array", "items": {"type": "string"} }, "availability": { "type": "object", "properties": { "in_stock": {"type": "boolean"}, "quantity": {"type": "integer"}, "shipping_time": {"type": "string"} } }, "ratings": { "type": "object", "properties": { "average_rating": {"type": "number"}, "total_reviews": {"type": "integer"} } } }, "required": ["product_name"] } response = self.client.chat.completions.create( model="glm-5", messages=[ { "role": "system", "content": f""" Please extract structured information from product description, return in the following format: {json.dumps(schema, indent=2, ensure_ascii=False)} Note: - Price information should accurately extract values and currency units - specifications should include all technical specifications - features should list main functional features - Do not guess if information is unclear """ }, { "role": "user", "content": f"Product description:\n{product_description}" } ], response_format={"type": "json_object"} ) try: result = json.loads(response.choices[0].message.content) validate(instance=result, schema=schema) return result except Exception as e: print(f"Product information extraction failed: {e}") return None def extract_event_info(self, event_text): """Extract event information""" schema = { "type": "object", "properties": { "events": { "type": "array", "items": { "type": "object", "properties": { "title": {"type": "string"}, "description": {"type": "string"}, "start_time": {"type": "string"}, "end_time": {"type": "string"}, "location": {"type": "string"}, "organizer": {"type": "string"}, "participants": { "type": "array", "items": {"type": "string"} }, "category": {"type": "string"}, "priority": { "type": "string", "enum": ["high", "medium", "low"] }, "status": { "type": "string", "enum": ["scheduled", "ongoing", "completed", "cancelled"] } }, "required": ["title", "start_time"] } } }, "required": ["events"] } response = self.client.chat.completions.create( model="glm-5", messages=[ { "role": "system", "content": f""" Please extract all event information from the text, return in the following format: {json.dumps(schema, indent=2, ensure_ascii=False)} Time format requirements: - Use ISO 8601 format: YYYY-MM-DDTHH:MM:SS - If only date available, use: YYYY-MM-DD - If time is unclear, try to infer reasonable time """ }, { "role": "user", "content": f"Please extract event information from the following text:\n\n{event_text}" } ], response_format={"type": "json_object"} ) try: result = json.loads(response.choices[0].message.content) validate(instance=result, schema=schema) return result except Exception as e: print(f"Event information extraction failed: {e}") return None # Usage example extractor = DataExtractor("your_api_key") # Extract contact information contact_text = """ Zhang San, mobile: 13800138000, email: zhangsan@example.com, works as Technical Director at Beijing Technology Co., Ltd. Company address: No. 123, Technology Park, Chaoyang District, Beijing. Li Si, phone: 010-12345678, work email: lisi@company.com, is a Product Manager at Shanghai Innovation Company. """ contacts = extractor.extract_contact_info(contact