Z.AI provides interfaces compatible with OpenAI API, which means you can use existing OpenAI SDK code and seamlessly switch to Z.AIβs model services by simply modifying the API key and base URL. This compatibility allows you to:
Quickly migrate existing OpenAI applications
Use familiar development patterns and tools
Enjoy the powerful capabilities of Z.AI models
Maintain code consistency and maintainability
In some scenarios, there are still differences between Z.AI and OpenAI interfaces, but this does not affect overall compatibility.
from openai import OpenAIclient = OpenAI( api_key="your-Z.AI-api-key", base_url="https://api.z.ai/api/paas/v4/")completion = client.chat.completions.create( model="glm-4.5", messages=[ {"role": "system", "content": "You are a smart and creative novelist"}, {"role": "user", "content": "Please write a short fairy tale story as a fairy tale master"} ])print(completion.choices[0].message.content)
from openai import OpenAIclient = OpenAI( api_key="your-Z.AI-api-key", base_url="https://api.z.ai/api/paas/v4/")stream = client.chat.completions.create( model="glm-4.5", messages=[ {"role": "user", "content": "Write a poem about artificial intelligence"} ], stream=True, temperature=0.6)for chunk in stream: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].delta.content, end="", flush=True)print() # New line
If youβre already using OpenAI API, migrating to Z.AI is very simple:
Copy
# Original OpenAI codefrom openai import OpenAIclient = OpenAI( api_key="sk-...", # OpenAI API Key # base_url uses default value)# Migrate to Z.AI, only need to modify two placesclient = OpenAI( api_key="your-Z.AI-api-key", # Replace with Z.AI API Key base_url="https://api.z.ai/api/paas/v4/" # Add Z.AI base_url)# Other code remains unchangedresponse = client.chat.completions.create( model="glm-4.5", # Use Z.AI model messages=[{"role": "user", "content": "Hello!"}])
Z.AI is committed to maintaining compatibility with OpenAI API. If you encounter any issues during migration, please contact our technical support team.