# 1. 安装SDK
# pip install openai
from openai import OpenAI
# 2. 初始化客户端
client = OpenAI(
api_key="sk-your-api-key", # 👈 替换为你的API Key(从控制台获取)
base_url="https://dashuaigou.cn/v1" # 只需改这一行
)
# 3. 发起普通请求
response = client.chat.completions.create(
model="qwen-turbo", # 选择模型:qwen-turbo / qwen-plus / qwen-max
messages=[
{"role": "user", "content": "你好,帮我写一段Python代码"}
]
)
# 4. 打印回复
print(response.choices[0].message.content)
# ===== 流式输出示例 =====
# 5. 流式请求(逐字输出)
stream = client.chat.completions.create(
model="qwen-turbo",
messages=[{"role": "user", "content": "写一首关于春天的诗"}],
stream=True # 启用流式输出
)
# 6. 逐块读取并打印
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print() # 结束后换行