Python AI Agent 零基础教程 | 第4篇:API调用基础——让程序与AI对话
经过前三期的学习,你已经掌握了 Python 的基础语法。今天我们正式开始与 AI 对话! 本期将讲解什么是 API,如何获取 API Key,以及如何使用 Python 调用 AI 大模型。
就像餐厅的服务员。 想象你去餐厅吃饭:
- - 👨🍳 厨房 = 服务器(处理请求的地方)
- - 📋 菜单 = API 文档(告诉你有什么菜)
- - 👨🍳 服务员 = API(传递你的请求和返回结果)
你(客户端) ──请求──▶ API ──▶ 服务器(AI) │
▼
你(客户端) ◀──响应── API ◀── 服务器(AI)最常用的 API 调用方式是HTTP 请求,主要有两种:
| 请求类型 | 说明 | 场景 |
|---------|------|------|
| GET | 获取数据 | 查询信息 |
| POST | 发送数据 | 提交表单、发送消息 |
一个 HTTP 请求包含:
请求方法 URL路径 GET /api/users?id=1Headers(请求头) Content-Type: application/json Body(请求体) {"name": "鹏鹏", "age": 25}
就像你的身份证号码,用于:
- - 身份验证(证明你是谁)
- - 计费统计(统计你用了多少)
- - 权限控制(你能访问什么)
访问:https://platform.openai.com 点击 "Sign up" 注册账号
步骤 2:登录并进入 API 页面登录后,点击右上角头像 → 选择 "API keys"
步骤 3:创建 API Key1. 点击 "Create new secret key"
2. 给 Key 起个名字(方便管理)
3. 点击复制按钮 🔗 复制 Key ⚠️
重要提醒:- - API Key 只显示一次!复制后要保存好
- - 不要分享给他人
- - 不要上传到 GitHub
新用户有 $5 免费额度,可以点击 "Usage" 查看使用情况。
如果 OpenAI 访问困难,可以使用国内大模型:
| 提供商 | 产品 | 特点 |
|-------|------|------|
| 百度 | 文心一言 | 中文能力强 |
| 阿里 | 通义千问 | 免费额度大 |
| 智谱 | GLM-4 | 性价比高 |
| 月之暗面 | Kimi | 长文本处理强 |
requests 是 Python 最常用的 HTTP 请求库。
方法 1:使用 pip 安装打开终端(Windows 按 Win+R,输入 cmd),执行:
pip install requests
1.File → Settings → Project → Python Interpreter
2. 点击+号
3. 搜索requests
4. 点击Install Package
如果使用官方 OpenAI API,可以安装 openai 库:
pip install openai
我们使用免费的心知天气 API 来学习: 访问:https://www.seniverse.com 注册获取 API Key
import requests import json import requests import json def chat_with_gpt(prompt, api_key): """调用 ChatGPT API""" url = "https://api.openai.com/v1/chat/completions" headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
} data = {
"model": "gpt-3.5-turbo", # 或 "gpt-4"
"messages": [
{"role": "user", "content": prompt}
],
"temperature": 0.7 # 创造性参数(0-2)
} response = requests.post(url, headers=headers, json=data) if response.status_code == 200: result = response.json() answer = result["choices"][0]["message"]["content"] return answer else: return f"错误:{response.status_code} - {response.text}" 使用示例api_key = "sk-xxxxxx" # 替换为你的 API Keyanswer = chat_with_gpt("你好,请介绍一下你自己", api_key) print(answer)
from openai import OpenAI 设置 API Keyclient = OpenAI(api_key="sk-xxxxxx") # 替换为你的 API Key
<h1 发送对话请求chat_completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "用一句话介绍Python"}
]
) 获取回复print(chat_completion.choices[0].message.content)
OpenAI API 请求结构url: "https://api.openai.com/v1/chat/completions" headers: Authorization: "Bearer {api_key}" Content-Type: "application/json" body: { "model": "gpt-3.5-turbo", # 模型选择 "messages": [ # 对话历史 {"role": "user", "content": "..."},{"role": "assistant", "content": "..."}, {"role": "user", "content": "..."} ], "temperature": 0.7 # 创造性 } import requests import json def chat_with_wenxin(prompt): """调用百度文心一言 API""" # API 配置 api_key = "你的API Key" secret_key = "你的Secret Key"
# 获取 access_token import requests def chat_with_zhipu(prompt, api_key): """调用智谱 GLM API""" url = "https://open.bigmodel.cn/api/paas/v4/chat/completions" headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
} data = {
"model": "glm-4",
"messages": [{"role": "user", "content": prompt}]
} response = requests.post(url, headers=headers, json=data) result = response.json() return result["choices"][0]["message"]["content"] 使用answer = chat_with_zhipu("什么是AI Agent?", "你的API Key") print(answer)
import requests def safe_api_call(url, params): """安全的 API 调用(带错误处理)""" try: response = requests.get(url, params=params, timeout=10)
# 检查 HTTP 状态码 if response.status_code == 200: return response.json() elif response.status_code == 401: print("❌ API Key 无效或已过期") elif response.status_code == 429: print("⏰ 请求过于频繁,请稍后重试") elif response.status_code == 500: print("⚠️ 服务器内部错误") else: print(f"❌ 请求失败:{response.status_code}") except requests.exceptions.Timeout: print("❌ 请求超时,请检查网络连接") except requests.exceptions.ConnectionError: print("❌ 网络连接失败,请检查网络") except Exception as e: print(f"❌ 未知错误:{str(e)}") 打印完整的请求信息(调试用)print(f"请求 URL: {response.url}") print(f"状态码: {response.status_code}") print(f"响应头: {response.headers}") print(f"响应内容: {response.text}")
import requests import json class AIAssistant: """AI 对话助手""" def __init__(self, api_key, base_url="https://api.openai.com/v1"): self.api_key = api_key self.base_url = base_url self.conversation_history = [] def chat(self, message): """发送消息并获取回复""" # 添加用户消息到历史 self.conversation_history.append({
"role": "user",
"content": message
})
# 构建请求 url = f"{self.base_url}/chat/completions" headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
} data = {
"model": "gpt-3.5-turbo",
"messages": self.conversation_history,
"temperature": 0.7
}
# 发送请求 response = requests.post(url, headers=headers, json=data) if response.status_code == 200: result = response.json() assistant_message = result["choices"][0]["message"]
# 添加助手回复到历史 self.conversation_history.append(assistant_message) return assistant_message["content"] else: return f"错误:{response.status_code}" def clear_history(self): """清空对话历史""" self.conversation_history = [] print("✓ 对话历史已清空") def show_history(self): """显示对话历史""" print("\n=== 对话历史 ===") for msg in self.conversation_history: role = "👤 你" if msg["role"] == "user" else "🤖 AI" print(f"{role}:{msg['content']}") 使用示例if __name__ == "__main__": # 初始化(替换为你的 API Key) assistant = AIAssistant("sk-xxxxxx") print("=== AI 对话助手 ===") print("输入 'quit' 退出,'clear' 清空历史,'history' 查看历史\n") while True: user_input = input("你: ") if user_input.lower() == "quit": print("再见!") break elif user_input.lower() == "clear": assistant.clear_history() elif user_input.lower() == "history": assistant.show_history() else: response = assistant.chat(user_input) print(f"AI: {response}\n")
=== AI 对话助手 === 输入 'quit' 退出,'clear' 清空历史,'history' 查看历史 你: 你好今天我们学习了:
| 知识点 | 说明 |
|-------|------|
| ✅ API 基础 | 什么是 API、如何工作 |
| ✅ 获取 API Key | OpenAI、国内大模型 |
| ✅ requests 库 | 发送 HTTP 请求 |
| ✅ 调用 AI API | OpenAI、文心一言、智谱 |
| ✅ 错误处理 | try/except 捕获异常 |
| ✅ 对话助手 | 带历史记录的对话系统 |
下一期我们将学习:
- - AI Agent 的核心架构
- - 完整的 Agent 代码实现
- - 运行和测试你的 Agent
💬 互动:你成功调用了哪个 AI API?效果如何?
👨💻 作者:鹏鹏
📱 关注公众号「跟着鹏鹏学技术」
🔔 点赞 + 在看,让更多人看到!
夜雨聆风