百炼( Bailian)是阿里云旗下的模型服务与数据平台,提供 API 方式调用通义系列及第三方开源大模型。本文从零演示 Python 如何接入百炼平台,涵盖环境准备、核心 SDK 使用、常用场景代码示例,以及避坑指南。
一、百炼平台简介
百炼平台提供两大类模型调用方式:
| | |
|---|
| 模型 API(直接调用) | 通过 HTTP 请求调用模型接口,按 token 计费 | |
| 模型服务(部署调用) | | |
对于大多数开发者场景,直接调用模型 API 即可满足需求,本文重点覆盖这种方式。
二、前置准备
2.1 开通百炼服务
- 在API-KEY 管理页面创建一个 API-KEY,妥善保存(不要泄露或提交到代码仓库)
2.2 安装依赖
百炼平台提供两种 SDK:新版 DashScope SDK(推荐) 和 旧版 openapi-sdk-python。推荐使用新版,体验更流畅。
pip install dashscope
2.3 环境变量配置(推荐)
将 API-KEY 写入环境变量,代码中读取,避免硬编码:
# Linux / macOSexport DASHSCOPE_API_KEY="your-api-key-here"# Windows PowerShell$env:DASHSCOPE_API_KEY="your-api-key-here"
三、快速上手:最简单的调用方式
3.1 同步调用
import osfrom dashscope import Generation# 推荐:从环境变量读取 API-KEYapi_key = os.getenv("DASHSCOPE_API_KEY")response = Generation.call( model="qwen-plus", # 可选:qwen-turbo / qwen-plus / qwen-max / qwen-long 等 prompt="请用三句话解释什么是大语言模型", api_key=api_key)print(response.output.text)print(f"Token消耗: {response.usage}")
运行结果示例:
大语言模型(LLM)是基于海量文本数据训练的人工智能系统,能够理解和生成自然语言。它们通过学习语言模式,从而完成问答、写作、代码生成等多样化的任务。Token消耗: {'input_tokens': 28, 'output_tokens': 65}
3.2 流式输出(Streaming)
适合打字机效果或长文本生成场景:
from dashscope import Generationapi_key = os.getenv("DASHSCOPE_API_KEY")responses = Generation.call( model="qwen-turbo", prompt="写一个快速排序算法的 Python 实现,并加上注释", api_key=api_key, stream=True, # 开启流式 incremental_output=True# True: 增量输出(推荐);False: 全量片段输出)for resp in responses:if resp.status_code == 200: print(resp.output.text, end="", flush=True)else: print(f"请求失败: {resp.code} - {resp.message}")
四、系统提示词与对话
4.1 带系统提示词的对话
from dashscope import Generationapi_key = os.getenv("DASHSCOPE_API_KEY")messages = [ {"role": "system","content": "你是一位资深汽车嵌入式软件工程师,回答问题要专业、准确。" }, {"role": "user","content": "BootLoader 和 App 程序是如何跳转的?" }]response = Generation.call( model="qwen-plus", messages=messages, api_key=api_key)print(response.output.text)
4.2 多轮对话
from dashscope import Generationapi_key = os.getenv("DASHSCOPE_API_KEY")messages = []system_prompt = "你是一位技术博主,语言风格简洁有趣。"messages.append({"role": "system", "content": system_prompt})whileTrue: user_input = input("你: ")if user_input.lower() in ["exit", "quit", "q"]: print("再见!")break messages.append({"role": "user", "content": user_input}) response = Generation.call( model="qwen-turbo", messages=messages, api_key=api_key )if response.status_code == 200: answer = response.output.text print(f"AI: {answer}") messages.append({"role": "assistant", "content": answer})else: print(f"错误: {response.message}")
五、常用参数详解
from dashscope import Generationapi_key = os.getenv("DASHSCOPE_API_KEY")response = Generation.call( model="qwen-plus", prompt="解释一下什么是 OTA 技术",# 🔥 核心调参 temperature=0.7, # 创造性控制:0=确定输出,1=高随机性,默认 0.7 max_tokens=500, # 最大生成长度(token 数),防止无限输出 top_p=0.8, # 核采样概率,值越小越保守,默认 0.8# 可选高级参数 stop=["。", "\n\n"], # 遇到指定字符停止生成 api_key=api_key)print(response.output.text)
| | |
|---|
temperature | | 0.7(通用)/ 0.3(代码)/ 1.0(创意写作) |
max_tokens | | |
top_p | | |
top_k | | |
六、Function Call(函数调用)
百炼平台支持 Function Call,让模型调用外部工具或 API,实现 Agent 能力:
from dashscope import Generationfrom dashscope function_callapi_key = os.getenv("DASHSCOPE_API_KEY")defget_weather(city: str) -> str:"""查询城市天气"""# 实际项目中这里调用天气 APIreturnf"{city} 今天晴,气温 22°C"# 定义工具函数functions = {"type": "function","function": {"name": "get_weather","description": "查询指定城市的天气情况","parameters": {"type": "object","properties": {"city": {"type": "string","description": "城市名称,例如:北京、上海" } },"required": ["city"] } }}messages = [ {"role": "user", "content": "上海今天天气怎么样?"}]response = Generation.call( model="qwen-plus", messages=messages, functions=functions, api_key=api_key)# 解析模型返回的函数调用指令if response.output.choices[0].message.function_call: fc = response.output.choices[0].message.function_call print(f"模型要求调用函数: {fc.name}") print(f"参数: {fc.arguments}")# 执行函数 result = get_weather(**json.loads(fc.arguments))# 将函数结果反馈给模型 messages.append(response.output.choices[0].message.to_dict()) messages.append({"role": "function","content": result,"name": fc.name })# 二次调用获取最终回答 final_response = Generation.call( model="qwen-plus", messages=messages, api_key=api_key ) print(final_response.output.text)
七、异步调用
适用于高并发场景,避免阻塞主线程:
import asynciofrom dashscope import Generationapi_key = os.getenv("DASHSCOPE_API_KEY")asyncdefcall_model(prompt: str, model: str = "qwen-turbo"): response = await Generation.acall( model=model, prompt=prompt, api_key=api_key )return response.output.textasyncdefmain(): tasks = [ call_model("什么是 CAN 总线?"), call_model("什么是 UDS 协议?"), call_model("OTA 升级有哪些方案?"), ] results = await asyncio.gather(*tasks)for i, r in enumerate(results): print(f"任务{i+1}: {r}")asyncio.run(main())
八、常见问题与避坑
❌ 报错 400:Invalid request
通常为请求格式错误,常见原因:
prompt 传了 messages 参数(两者二选一,不能同时传)messages 格式不符合 [{"role": "...", "content": "..."}]
❌ 报错 401:Unauthorized
API-KEY 无效或未正确传入,检查:
❌ 响应超时
Generation.call() 默认有超时限制,高并发或长文本场景建议:
import dashscopedashscope.base_http_api_kwargs['timeout'] = 120# 超时时间设为 120 秒
⚠️ 成本控制建议
- 优先使用 turbo 模型:qwen-turbo 速度快、成本低,适合日常对话和快速验证
- 设置 max_tokens:防止模型输出过长导致额外扣费
- 及时捕获异常:网络波动可能导致重试,计费按成功响应计算
九、完整项目模板
"""百炼平台 Python SDK 封装模板文件: bailian_client.py"""import osimport jsonfrom dashscope import GenerationclassBailianClient:"""百炼平台客户端封装"""def__init__(self, api_key: str = None, model: str = "qwen-turbo"): self.api_key = api_key or os.getenv("DASHSCOPE_API_KEY") self.model = modeldefchat(self, prompt: str, temperature: float = 0.7, max_tokens: int = 1024, **kwargs) -> str:"""通用对话接口""" response = Generation.call( model=self.model, prompt=prompt, temperature=temperature, max_tokens=max_tokens, api_key=self.api_key, **kwargs ) self._check_response(response)return response.output.textdefchat_with_messages(self, messages: list, temperature: float = 0.7, max_tokens: int = 1024) -> str:"""多轮对话接口""" response = Generation.call( model=self.model, messages=messages, temperature=temperature, max_tokens=max_tokens, api_key=self.api_key ) self._check_response(response)return response.output.text @staticmethoddef_check_response(response):if response.status_code != 200:raise Exception(f"请求失败 [{response.code}]: {response.message}")# 使用示例if __name__ == "__main__": client = BailianClient(model="qwen-plus") print(client.chat("用一句话介绍你自己"))
十、总结
| |
|---|
| |
| pip install dashscope |
| |
| 调用 Generation.call() 完成对话 |
| 按需配置流式输出、Function Call、异步调用 |
百炼平台的 Python SDK 设计简洁,上手成本极低。结合通义系列模型的强大能力,可以快速构建智能问答、内容生成、代码助手等应用。Function Call 的支持更是打开了 Agent 开发的大门。
参考资料