乐于分享
好东西不私藏

Python AI Agent 零基础教程 | 第4篇:API调用基础——让程序与对话

Python AI Agent 零基础教程 | 第4篇:API调用基础——让程序与对话
   

Python AI Agent 零基础教程 | 第4篇:API调用基础——让程序与AI对话


前言

经过前三期的学习,你已经掌握了 Python 的基础语法。今天我们正式开始与 AI 对话! 本期将讲解什么是 API,如何获取 API Key,以及如何使用 Python 调用 AI 大模型。


一、什么是 API?
1.1 通俗理解 API
API(Application Programming Interface)

就像餐厅的服务员。 想象你去餐厅吃饭:

  • - 👨‍🍳 厨房 = 服务器(处理请求的地方)
  • - 📋 菜单 = API 文档(告诉你有什么菜)
  • - 👨‍🍳 服务员 = API(传递你的请求和返回结果)
你(客户端) ──请求──▶ API ──▶ 服务器(AI)  │                              ▼ 你(客户端) ◀──响应──  API ◀── 服务器(AI)
1.2 HTTP 请求基础

最常用的 API 调用方式是HTTP 请求,主要有两种: 

 | 请求类型 | 说明 | 场景 | 

 |---------|------|------| 

 | GET | 获取数据 | 查询信息 | 

 | POST | 发送数据 | 提交表单、发送消息 |

1.3 请求结构

一个 HTTP 请求包含:

请求方法 URL路径 
GET /api/users?id=1
Headers(请求头) 
Content-Type: application/json 
Body(请求体) 
{"name": "鹏鹏", "age": 25}

二、获取 API Key
2.1 什么是 API Key?
API Key

就像你的身份证号码,用于:

  • - 身份验证(证明你是谁)
  • - 计费统计(统计你用了多少)
  • - 权限控制(你能访问什么)
2.2 获取 OpenAI API Key(以 ChatGPT 为例)
步骤 1:注册 OpenAI 账号

访问:https://platform.openai.com 点击 "Sign up" 注册账号

步骤 2:登录并进入 API 页面

登录后,点击右上角头像 → 选择 "API keys"

步骤 3:创建 API Key

1. 点击 "Create new secret key" 

2. 给 Key 起个名字(方便管理) 

3. 点击复制按钮 🔗 复制 Key ⚠️

重要提醒
  • - API Key 只显示一次!复制后要保存好
  • - 不要分享给他人
  • - 不要上传到 GitHub
步骤 4:充值或查看额度

新用户有 $5 免费额度,可以点击 "Usage" 查看使用情况。 

2.3 国内替代方案

如果 OpenAI 访问困难,可以使用国内大模型:

 | 提供商 | 产品 | 特点 | 

 |-------|------|------| 

 | 百度 | 文心一言 | 中文能力强 | 

 | 阿里 | 通义千问 | 免费额度大 |

 | 智谱 | GLM-4 | 性价比高 |

 | 月之暗面 | Kimi | 长文本处理强 |


三、安装必要的库
3.1 安装 requests 库

requests 是 Python 最常用的 HTTP 请求库。

方法 1:使用 pip 安装

打开终端(Windows 按 Win+R,输入 cmd),执行:

pip install requests
方法 2:在 PyCharm 中安装

1.File → Settings → Project → Python Interpreter

2. 点击+号 

3. 搜索requests

4. 点击Install Package

3.2 安装 openai 库(可选)

如果使用官方 OpenAI API,可以安装 openai 库:

pip install openai

四、第一个 API 调用:天气查询
4.1 选择天气 API

我们使用免费的心知天气 API 来学习: 访问:https://www.seniverse.com 注册获取 API Key

4.2 完整代码实现
import requests 
import json 
def get_weather(city="北京"): 
 """获取天气信息"""        # API 配置 
  api_key = "你的API密钥"  # 替换为你的密钥 
 url = f"https://api.seniverse.com/v3/weather/now.json"        # 请求参数 
 params = {        "key": api_key,        "location": city,        "language": "zh-Hans",        "unit": "c"    }        # 发送请求 
 response = requests.get(url, params=params)        # 解析结果 
 if response.status_code == 200: 
   data = response.json() 
   weather = data["results"][0]  
   print(f"\n📍 {city} 天气情况:") 
  print(f"天气:{weather['now']['text']}") 
  print(f"温度:{weather['now']['temperature']}°C") 
   print(f"体感温度:{weather['now']['feels_like']}°C") 
  print(f"更新时间:{weather['last_update']}") 
 else: 
  print(f"请求失败:{response.status_code}") 
测试 
get_weather("北京") 
get_weather("上海")
4.3 代码详解
1. 构建 URL + 参数                              │ 
url = "https://api...?" + params 
 2. 发送请求 
response = requests.get(url, params) 
3. 检查状态码 
if response.status_code == 200: 
 4. 解析响应数据
data = response.json() 
5. 提取需要的信息 
weather = data["results"][0]["now"]

五、调用 OpenAI API
5.1 使用 requests 直接调用
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 Key
answer = chat_with_gpt("你好,请介绍一下你自己", api_key) 
print(answer)
5.2 使用 openai 库调用(更简单)
from openai import OpenAI 
设置 API Key
client = 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)
5.3 代码解析
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 # 创造性 } 

六、调用国内大模型 API
6.1 百度文心一言
import requests 
import json 
def chat_with_wenxin(prompt):
 """调用百度文心一言 API""" 
 # API 配置 
 api_key = "你的API Key" 
 secret_key = "你的Secret Key" # 获取 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")        # 调用 API 
 url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions" 
 url += f"?access_token={access_token}" 
 headers = {"Content-Type": "application/json"} 
  data = {        "messages": [{"role": "user", "content": prompt}]    } 
 response = requests.post(url, headers=headers, json=data) 
  result = response.json() 
 return result["result"] 
使用
answer = chat_with_wenxin("用一句话介绍AI Agent") 
print(answer)
6.2 智谱 GLM
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)

七、错误处理与调试
7.1 常见错误及解决
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)}") 
 return None
7.2 调试技巧
打印完整的请求信息(调试用)
print(f"请求 URL: {response.url}") 
print(f"状态码: {response.status_code}") 
print(f"响应头: {response.headers}") 
print(f"响应内容: {response.text}")

八、综合实战:AI 对话助手
8.1 完整代码
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")
8.2 运行效果
=== AI 对话助手 === 
输入 'quit' 退出,'clear' 清空历史,'history' 查看历史 
你: 你好
AI: 你好!有什么我可以帮助你的吗? 
 你: 什么是AI Agent? 
AI: AI Agent(人工智能代理)是一种能够自主理解目标、规划决策、执行复杂任务的智能系统...
 你: history
 === 对话历史 === 
👤 你: 你好 
🤖 AI: 你好!有什么我可以帮助你的吗? 
👤 你: 什么是AI Agent? 
🤖 AI: AI Agent(人工智能代理)是一种能够自主理解目标...
 你: quit 再见!

九、本章小结

今天我们学习了: 

 | 知识点 | 说明 | 

|-------|------|

 | ✅ API 基础 | 什么是 API、如何工作 | 

 | ✅ 获取 API Key | OpenAI、国内大模型 |

 | ✅ requests 库 | 发送 HTTP 请求 | 

 | ✅ 调用 AI API | OpenAI、文心一言、智谱 | 

 | ✅ 错误处理 | try/except 捕获异常 

 | ✅ 对话助手 | 带历史记录的对话系统 |


下期预告
第5篇:手把手构建你的第一个 AI Agent

下一期我们将学习:

  • - AI Agent 的核心架构
  • - 完整的 Agent 代码实现
  • - 运行和测试你的 Agent

👨‍💻 作者:鹏鹏 | 专注于 AI + 编程教育 📱 关注公众号「跟着鹏鹏学技术」
💬 互动:你成功调用了哪个 AI API?效果如何?

   

👨‍💻 作者:鹏鹏

   

📱 关注公众号「跟着鹏鹏学技术」

  

🔔 点赞 + 在看,让更多人看到!