AI实验室2026_第1篇:Python调用AI大模型接口
Python调用AI大模型接口,2026最全教程(百度/阿里/腾讯/智谱/Kimi全涵盖)
⏰ 更新时间:2026年5月 | 💡 阅读本文预计需要15分钟 | 🚀 国内平台全覆盖,学完即可实战
一、前言
想接入AI能力,却被"ChatGPT无法访问"卡住?
别担心!国内AI大模型已经非常强大,百度文心、阿里通义、腾讯混元、智谱GLM、Kimi等平台的API已经非常成熟,中文理解能力甚至超越ChatGPT。
本文涵盖:
- ✅ 百度文心一言(ERNIE-4.0)
- ✅ 阿里通义千问(Qwen-Turbo)
- ✅ 腾讯混元大模型(Hunyuan)
- ✅ 智谱GLM-4(支持联网搜索)
- ✅ Kimi moonshot(超长上下文128K)
所有代码2026年5月实测可用,直接复制运行!
二、环境准备
2.1 安装依赖
一行命令搞定:
pip install requests
💡 如需流式输出,无需额外安装,Python 3.7+ 原生支持
2.2 获取API密钥
各大平台均提供免费调用额度,建议先注册获取密钥测试:
| 平台 | 地址 | 免费额度 | 推荐指数 |
|---|---|---|---|
| 智谱AI | bigmodel.cn | GLM-4有免费调用 | ⭐⭐⭐⭐⭐ |
| 阿里通义 | bailian.console.aliyun.com | 通义千问有免费额度 | ⭐⭐⭐⭐⭐ |
| Kimi | platform.moonshot.cn | moonshot-v1有免费额度 | ⭐⭐⭐⭐ |
| 百度文心 | console.baidu.com | ERNIE-4.0有试用 | ⭐⭐⭐⭐ |
| 腾讯混元 | cloud.tencent.com | 混元有免费试用 | ⭐⭐⭐ |
💡 推荐入门顺序:智谱GLM → 阿里通义 → Kimi(免费额度多,上手最快)
三、百度文心一言(ERNIE-4.0)
文心一言是百度自研的国产大模型,中文理解能力业界领先。
3.1 获取密钥
- 登录 百度智能云
- 搜索"文心一言API"或"千帆大模型平台"
- 创建应用,获取
API Key和Secret Key
3.2 调用示例
import requests
def call_wenxin(prompt, api_key, secret_key):
"""调用百度文心一言API"""
# Step 1: 获取access_token
auth_url = "https://aip.baidubce.com/oauth/2.0/token"
auth_params = {
"grant_type": "client_credentials",
"client_id": api_key,
"client_secret": secret_key
}
auth_response = requests.get(auth_url, params=auth_params)
access_token = auth_response.json().get("access_token")
# Step 2: 调用文心一言
url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token={access_token}"
payload = {
"messages": [{"role": "user", "content": prompt}]
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, headers=headers, json=payload)
return response.json()["result"]
# 使用示例
API_KEY = "your_baidu_api_key"
SECRET_KEY = "your_baidu_secret_key"
response = call_wenxin("用Python写一个冒泡排序", API_KEY, SECRET_KEY)
print(response)
3.3 多轮对话
def call_wenxin_multiturn(messages, api_key, secret_key):
"""
百度文心一言多轮对话
messages格式: [{"role": "user", "content": "xxx"}, {"role": "assistant", "content": "xxx"}]
"""
# 获取access_token
auth_url = "https://aip.baidubce.com/oauth/2.0/token"
auth_params = {
"grant_type": "client_credentials",
"client_id": api_key,
"client_secret": secret_key
}
auth_response = requests.get(auth_url, params=auth_params)
access_token = auth_response.json().get("access_token")
url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-4.0-8k-latest?access_token={access_token}"
payload = {"messages": messages}
headers = {"Content-Type": "application/json"}
response = requests.post(url, headers=headers, json=payload)
return response.json()["result"]
# 多轮对话示例
messages = [
{"role": "user", "content": "什么是Python?"},
{"role": "assistant", "content": "Python是一种高级编程语言..."},
{"role": "user", "content": "它适合做什么?"}
]
result = call_wenxin_multiturn(messages, API_KEY, SECRET_KEY)
print(result)
四、阿里通义千问(Qwen-Turbo)
通义千问是阿里云自研的大语言模型,开源版本备受好评,性价比极高。
4.1 获取密钥
- 登录 阿里云百炼平台
- 开通"百炼API"服务
- 获取 API Key
4.2 调用示例
import requests
import os
DASHSCOPE_API_KEY = os.environ.get("DASHSCOPE_API_KEY", "your_api_key")
def call_qwen(prompt, model="qwen-turbo"):
"""
调用阿里通义千问API
model可选: qwen-turbo(快速), qwen-plus(增强), qwen-max(最强)
"""
url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
headers = {
"Authorization": f"Bearer {DASHSCOPE_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": [{"role": "user", "content": prompt}]
}
response = requests.post(url, headers=headers, json=payload)
result = response.json()
return result["choices"][0]["message"]["content"]
# 使用示例
response = call_qwen("解释一下什么是装饰器模式")
print(response)
4.3 流式输出(打字机效果)
import requests
import json
def call_qwen_stream(prompt, model="qwen-turbo"):
"""通义千问流式输出"""
url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
headers = {
"Authorization": f"Bearer {DASHSCOPE_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": [{"role": "user", "content": prompt}],
"stream": True # 开启流式输出
}
response = requests.post(url, headers=headers, json=payload, stream=True)
print("AI回复:")
for line in response.iter_lines():
if line:
line_text = line.decode('utf-8')
if line_text.startswith("data: "):
data = json.loads(line_text[6:])
if "choices" in data and data["choices"]:
delta = data["choices"][0].get("delta", {})
if "content" in delta:
print(delta["content"], end="", flush=True)
print()
# 使用示例
call_qwen_stream("用Python写一个快速排序算法")
五、腾讯混元大模型(Hunyuan)
腾讯混元是腾讯自主研发的大模型,与微信、QQ等生态深度集成。
5.1 获取密钥
- 登录 腾讯云
- 搜索"混元大模型"或"Hunyuan"
- 开通服务,获取 SecretId、SecretKey
5.2 调用示例(推荐使用官方SDK)
pip install tencentcloud-sdk-python
from tencentcloud.common import credential
from tencentcloud.common.profile import client_profile
from tencentcloud.common.profile import http_profile
from tencentcloud.hunyuan.v20230901 import hunyuan_client, models
import json
# 密钥配置
cred = credential.Credential("SecretId", "SecretKey")
http_profile = http_profile.HttpProfile()
http_profile.endpoint = "hunyuan.tencentcloudapi.com"
client_profile = client_profile.ClientProfile()
client_profile.httpProfile = http_profile
client = hunyuan_client.HunyuanClient(cred, "", client_profile)
# 发送请求
req = models.ChatCompletionsRequest()
req.Messages = [{"Role": "user", "Content": "介绍一下Python的列表推导式"}]
resp = client.ChatCompletions(req)
result = json.loads(resp.Response.Choices[0].Message.Content)
print(result["text"])
六、智谱GLM-4
智谱AI是国内最早开源大模型的公司之一,GLM系列在学术界口碑极佳,支持联网搜索!
6.1 获取密钥
- 登录 智谱AI开放平台
- 开通API服务,获取 API Key
6.2 调用示例
import requests
import os
ZHIPU_API_KEY = os.environ.get("ZHIPU_API_KEY", "your_api_key")
def call_glm4(prompt, model="glm-4-flash"):
"""
调用智谱GLM-4 API
model: glm-4-flash(免费), glm-4, glm-4-plus
"""
url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
headers = {
"Authorization": f"Bearer {ZHIPU_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": [{"role": "user", "content": prompt}]
}
response = requests.post(url, headers=headers, json=payload)
result = response.json()
return result["choices"][0]["message"]["content"]
# 使用示例
response = call_glm4("Python的async/await怎么理解?")
print(response)
6.3 联网搜索增强(特色功能!)
def call_glm4_with_search(prompt, model="glm-4-flash"):
"""
智谱GLM-4 联网搜索增强版本
这个功能是其他平台没有的!
"""
url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
headers = {
"Authorization": f"Bearer {ZHIPU_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": [{"role": "user", "content": prompt}],
"tools": [{
"type": "web_search",
"web_search": {
"enable": True, # 开启联网搜索
"search_engine": "baidu"
}
}]
}
response = requests.post(url, headers=headers, json=payload)
result = response.json()
return result["choices"][0]["message"]["content"]
# 使用示例:查询最新AI新闻
result = call_glm4_with_search("今天有什么AI领域的重大新闻?")
print(result)
七、Kimi moonshot-v1
月之暗面的Kimi以超长上下文著称,支持128K上下文窗口,处理长文档能力无敌!
7.1 获取密钥
- 登录 Moonshot控制台
- 创建API Key
7.2 调用示例
import requests
import os
MOONSHOT_API_KEY = os.environ.get("MOONSHOT_API_KEY", "your_api_key")
def call_kimi(prompt, model="moonshot-v1-8k"):
"""
调用Kimi moonshot API
model: moonshot-v1-8k, moonshot-v1-32k, moonshot-v1-128k
"""
url = "https://api.moonshot.cn/v1/chat/completions"
headers = {
"Authorization": f"Bearer {MOONSHOT_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.7
}
response = requests.post(url, headers=headers, json=payload)
result = response.json()
return result["choices"][0]["message"]["content"]
# 普通对话
response = call_kimi("解释一下什么是大模型的上下文窗口")
print(response)
# 长文本处理(Kimi专长!)
long_prompt = """
请阅读以下文章,然后总结核心观点:
[这里是超长的文章内容,可以达到几十万字...]
[Kimi的128K上下文窗口可以一次性处理...]
"""
result = call_kimi(long_prompt, model="moonshot-v1-128k")
print(result)
八、统一封装类(推荐)
为了方便切换不同AI服务,推荐封装一个统一调用类:
import requests
import os
class AIClient:
"""统一AI客户端,支持多平台切换"""
def __init__(self, provider="zhipu", api_key=None):
"""
初始化AI客户端
provider: zhipu | qwen | wenxin | hunyuan | kimi
"""
self.provider = provider
# API Key配置
env_vars = {
"zhipu": "ZHIPU_API_KEY",
"qwen": "DASHSCOPE_API_KEY",
"wenxin": "BAIDU_SECRET_KEY",
"hunyuan": "TENCENT_SECRET_KEY",
"kimi": "MOONSHOT_API_KEY"
}
self.api_key = api_key or os.environ.get(env_vars.get(provider, ""))
# 端点配置
self.endpoints = {
"zhipu": "https://open.bigmodel.cn/api/paas/v4/chat/completions",
"qwen": "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
"kimi": "https://api.moonshot.cn/v1/chat/completions"
}
# 默认模型
self.models = {
"zhipu": "glm-4-flash",
"qwen": "qwen-turbo",
"kimi": "moonshot-v1-8k"
}
def chat(self, prompt, model=None, **kwargs):
"""通用对话接口"""
if self.provider not in self.endpoints:
raise ValueError(f"暂不支持 {self.provider}")
url = self.endpoints[self.provider]
model = model or self.models.get(self.provider, "")
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": [{"role": "user", "content": prompt}],
**kwargs
}
response = requests.post(url, headers=headers, json=payload)
result = response.json()
if "error" in result:
raise Exception(f"API调用错误: {result['error']}")
return result["choices"][0]["message"]["content"]
# ==================== 使用示例 ====================
# 初始化不同平台客户端
clients = {
"智谱": AIClient("zhipu"),
"通义": AIClient("qwen"),
"Kimi": AIClient("kimi")
}
# 切换测试
for name, client in clients.items():
print(f"\n{'='*20} {name} 回复 {'='*20}")
try:
response = client.chat("Python的装饰器是什么?")
print(response)
except Exception as e:
print(f"调用失败: {e}")
九、常见错误处理
9.1 错误码说明
| 错误码 | 说明 | 解决方案 |
|---|---|---|
| 401 | API密钥无效 | 检查密钥是否正确,是否过期 |
| 403 | 权限不足/额度用完 | 检查账户余额或免费额度 |
| 429 | 请求过于频繁 | 添加请求间隔,使用幂等重试 |
| 500 | 服务器内部错误 | 稍后重试 |
9.2 重试机制封装
import time
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
def call_with_retry(client, prompt):
"""带重试的AI调用"""
try:
return client.chat(prompt)
except Exception as e:
print(f"调用失败: {e},正在重试...")
raise
# 安装依赖
# pip install tenacity
# 使用示例
result = call_with_retry(clients["智谱"], "解释Python的生成器")
print(result)
十、总结
本文详细介绍了Python调用国内主流AI大模型API的方法:
| 平台 | 模型 | 特点 | 推荐场景 |
|---|---|---|---|
| 百度文心 | ERNIE-4.0 | 中文理解强 | 通用对话、内容创作 |
| 阿里通义 | Qwen-Turbo | 性价比高 | 快速响应、开源集成 |
| 腾讯混元 | Hunyuan | 腾讯生态 | 微信/QQ集成 |
| 智谱GLM | GLM-4-Flash | 联网搜索 | 实时信息查询 |
| Kimi | moonshot-v1-128k | 超长上下文 | 长文档处理 |
推荐入门顺序:智谱GLM → 阿里通义 → Kimi
这些平台都提供免费调用额度,非常适合学习和原型开发。掌握其中1-2个,就能满足大部分AI应用开发需求!
👏 互动引导
觉得这篇文章有用吗?欢迎:
- 点赞 支持一下
- 评论 说你想了解哪个平台的更多用法
- 关注 获取更多AI编程实战教程
作者:AI实验室2026
来源:CSDN
原创不易,转载须注明出处!
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐

所有评论(0)