任务10:我的API调用初体验——给AI包一层”壳”
一、目标
将 AI 能力集成到自己的程序中,通过 API 调用大模型,实现一个简单的命令行聊天机器人。
二、准备工作
2.1 获取 API Key
使用 Agnes AI 提供的 API Key,用于身份认证。
2.2 确认运行环境
- Python 版本:3.11.2
- 已安装库:
requests2.28.1 - 无需额外安装依赖
三、编写代码
3.1 核心思路
- 使用
requests库发送 HTTP POST 请求到 Agnes AI 的 API 端点 - API 地址:
https://apihub.agnes-ai.com/v1/chat/completions - 请求体包含模型名称、消息列表等参数
- 解析返回的 JSON 响应,提取 AI 的回答
3.2 完整代码
文件路径:/root/agnes_chatbot.py
#!/usr/bin/env python3
"""Agnes AI 简单聊天机器人 - 使用 requests 库"""
import requests
import os
import sys
BASE_URL = "https://apihub.agnes-ai.com/v1"
MODEL = "agnes-2.0-flash"
def get_api_key():
key = os.environ.get("AGNES_API_KEY")
if not key:
print("请先设置环境变量: export AGNES_API_KEY=你的密钥")
sys.exit(1)
return key
def chat(messages, api_key):
url = f"{BASE_URL}/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"model": MODEL,
"messages": messages,
"temperature": 0.7,
"max_tokens": 2048
}
resp = requests.post(url, json=payload, headers=headers, timeout=60)
resp.raise_for_status()
return resp.json()["choices"][0]["message"]["content"]
def test():
print("=== 测试 Agnes AI API ===")
key = get_api_key()
msgs = [{"role": "user", "content": "请用一句话介绍你自己"}]
reply = chat(msgs, key)
print(f"AI: {reply}")
def bot():
print("=== Agnes AI 聊天机器人 ===")
print("输入 quit 退出, clear 清空对话")
key = get_api_key()
history = [{"role": "system", "content": "你是一个有帮助的中文AI助手。"}]
while True:
user = input("\n你: ").strip()
if user.lower() in ("quit", "exit", "q"):
print("再见!")
break
if user.lower() == "clear":
history.clear()
history.append({"role": "system", "content": "你是一个有帮助的中文AI助手。"})
print("已清空")
continue
if not user:
continue
history.append({"role": "user", "content": user})
reply = chat(history, key)
history.append({"role": "assistant", "content": reply})
print(f"AI: {reply}")
if __name__ == "__main__":
if "--test" in sys.argv:
test()
else:
bot()
3.3 代码结构说明
| 函数 | 作用 |
|---|---|
get_api_key() |
从环境变量读取 API Key |
chat(messages, api_key) |
发送消息到 API,返回 AI 的回答 |
test() |
测试模式,发送一条消息验证连通性 |
bot() |
聊天模式,交互式命令行聊天机器人 |
四、运行步骤
4.1 设置 API Key
export AGNES_API_KEY=sk-81f0HQOPkqw1deOaYQj62igunuR4au3YihRS41KNoqjgmkxn
4.2 测试 API 连通性
python3 /root/agnes_chatbot.py --test
4.3 启动聊天机器人
python3 /root/agnes_chatbot.py
五、测试结果
测试命令执行后,AI 返回:
我是 Agnes-2.0-Flash,由 Sapiens AI 开发的大型语言模型。
API 调用成功,聊天机器人可正常使用。
六、关键知识点
- HTTP 请求:使用
requests.post()发送 POST 请求 - 身份认证:通过
Authorization: Bearer <key>头传递 API Key - JSON 数据:请求体和响应体都是 JSON 格式
- 对话历史:通过维护
messages列表实现多轮对话的上下文记忆 - 错误处理:使用
raise_for_status()捕获 HTTP 错误
七、扩展方向
- 添加更多模型选择
- 支持文件上传(图片等多模态)
- 接入 GUI 界面(如 Tkinter、Streamlit)
- 持久化对话历史到文件
- 添加流式输出(Streaming)
Comments NOTHING