from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("COMETAPI_KEY"), # or Z.ai key
base_url="https://api.cometapi.com/v1" # or "https://api.z.ai/api/paas/v4/"
)
response = client.chat.completions.create(
model="glm-5-1",
messages=[
{"role": "system", "content": "You are a world-class AI engineering assistant."},
{"role": "user", "content": "Write a FastAPI endpoint that serves GLM-5.1 completions with rate limiting."}
],
temperature=0.8,
max_tokens=2048,
thinking={"type": "enabled"} # Enables visible reasoning_content
)
print(response.choices[0].message.content)
print("Reasoning:", getattr(response.choices[0].message, "reasoning_content", "None"))
print("Usage:", response.usage)
串流版本(即時輸出):
stream = client.chat.completions.create(
model="glm-5-1",
messages=[{"role": "user", "content": "Generate a complete React + Tailwind dashboard for a SaaS AI coding tool."}],
stream=True,
temperature=0.9
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
進階功能:工具呼叫、結構化 JSON、MCP 整合
GLM-5.1 原生支援 工具呼叫(最多 128 個函數)與 JSON 模式。
範例:並行工具呼叫用於研究與程式碼產生
tools = [
{
"type": "function",
"function": {
"name": "web_search",
"description": "Search the web for latest information",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "generate_code",
"description": "Generate Python code for a given task",
"parameters": {"type": "object", "properties": {"task": {"type": "string"}}}
}
}
]
response = client.chat.completions.create(
model="glm-5-1",
messages=[{"role": "user", "content": "Research the latest SWE-Bench results and generate a benchmark comparison script."}],
tools=tools,
tool_choice="auto"
)
# Handle tool_calls in response.choices[0].message.tool_calls
結構化 JSON 輸出(非常適合代理):
response = client.chat.completions.create(
model="glm-5-1",
messages=[{"role": "user", "content": "Extract name, price, and features from this product description as JSON."}],
response_format={"type": "json_object"}
)