gpt接口教程
### 教程:调用 AI API 并封装为工具类
#### 1. 源代码
我们从你提供的原始代码开始,它是一个简单的 HTTP 请求,用于调用 AI 聊天接口并生成 Python 贪吃蛇代码。
```python
import requests
# 配置
url = "https://aiclound.vip/v1/chat/completions"
api_key = "sk-BVJMgXvwbZ86OuYJcLhgr6YaHxTTuIdvwbZ86OuYJcLh" # 替换为你的实际 API Key
# 请求头
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Bearer {api_key}"
}
data = {
"model": "gpt-4o",
"messages": [{"role": "user", "content": "帮我写一个python的贪吃蛇"}],
"stream": False
}
# 发送请求
response = requests.post(url, headers=headers, json=data)
# 输出结果
print(response.json())
```
运行说明:
- 这段代码发送一个 POST 请求到 https://aiclound.vip/v1/chat/completions
,请求 AI 生成一个 Python 贪吃蛇代码。
- 输出是 JSON 格式的响应,包含 AI 生成的内容。
- 前提是 requests
库已安装pip install requests
),且 api_key
有效。
---
#### 2. 封装为工具类
为了让代码更模块化、可重用,我们将它封装成一个工具类 AIChatClient
,提供简单的接口调用功能,并添加基本错误处理。
##### 封装步骤:
1. 定义类: 创建一个 AIChatClient
类,初始化时传入 URL 和 API Key。
2. 方法: 添加一个 chat
方法,接收用户消息并返回 AI 响应。
3. 错误处理: 检查 HTTP 状态码并处理异常。
4. 灵活性: 支持自定义模型和参数。
##### 封装后的代码
```python
import requests
class AIChatClient:
def init(self, url, api_key):
"""初始化 AI 聊天客户端"""
self.url = url
self.headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Bearer {api_key}"
}
def chat(self, message, model="gpt-4o", stream=False):
"""发送聊天请求并返回响应"""
data = {
"model": model,
"messages": [{"role": "user", "content": message}],
"stream": stream
}
try:
response = requests.post(self.url, headers=self.headers, json=data)
response.raise_for_status() # 检查 HTTP 状态码
return response.json()
except requests.exceptions.RequestException as e:
return {"error": str(e)}
# 使用示例
if name == "__main__":
url = "https://aiclound.vip/v1/chat/completions"
api_key = "sk-BVJMgXvwbZ86OuYJcLhgr6YaHxTTuIdvwbZ86OuYJcLh" # 替换为你的实际 API Key
client = AIChatClient(url, api_key)
result = client.chat("帮我写一个python的贪吃蛇")
print(result)
```
封装优点:
- 复用性: 只需实例化一次 AIChatClient
,即可多次调用 chat
方法。
- 简洁性: 用户只需关心消息内容,其他配置被隐藏。
- 健壮性: 添加了基本的错误处理,避免程序崩溃。
---
#### 3. 使用教程
1. 安装依赖:
在终端运行 pip install requests
安装 requests
库。
2. 保存代码:
将封装后的代码保存为 ai_chat_client.py
。
3. 运行示例:
- 直接运行文件python ai_chat_client.py
,会输出 AI 生成的贪吃蛇代码(JSON 格式)。
- 或在其他脚本中导入使用:
```python
from ai_chat_client import AIChatClient
client = AIChatClient("https://aiclound.vip/v1/chat/completions", "你的API_KEY")
result = client.chat("帮我写一个python的贪吃蛇")
print(result)
```
4. 提取生成内容:
如果只想要 AI 的回答,可以从返回的 JSON 中提取:
```python
content = result["choices"][0]["message"]["content"]
print(content)
```
---
#### 4. 所有代码汇总
以下是完整的代码,包括源代码和封装后的工具类。
##### 源代码 simple_request.py
)
```python
import requests
# 配置
url = "https://aiclound.vip/v1/chat/completions"
api_key = "sk-BVJMgXvwbZ86OuYJcLhgr6YaHxTTuIdvwbZ86OuYJcLh" # 替换为你的实际 API Key
# 请求头
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Bearer {api_key}"
}
data = {
"model": "gpt-4o",
"messages": [{"role": "user", "content": "帮我写一个python的贪吃蛇"}],
"stream": False
}
# 发送请求
response = requests.post(url, headers=headers, json=data)
# 输出结果
print(response.json())
```
##### 封装后的工具类 ai_chat_client.py
)
```python
import requests
class AIChatClient:
def init(self, url, api_key):
"""初始化 AI 聊天客户端"""
self.url = url
self.headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Bearer {api_key}"
}
def chat(self, message, model="gpt-4o", stream=False):
"""发送聊天请求并返回响应"""
data = {
"model": model,
"messages": [{"role": "user", "content": message}],
"stream": stream
}
try:
response = requests.post(self.url, headers=self.headers, json=data)
response.raise_for_status() # 检查 HTTP 状态码
return response.json()
except requests.exceptions.RequestException as e:
return {"error": str(e)}
# 使用示例
if name == "__main__":
url = "https://aiclound.vip/v1/chat/completions"
api_key = "sk-BVJMgXvwbZ86OuYJcLhgr6YaHxTTuIdvwbZ86OuYJcLh" # 替换为你的实际 API Key
client = AIChatClient(url, api_key)
result = client.chat("帮我写一个python的贪吃蛇")
print(result)
```
##### 示例输出提取 example_usage.py
)
```python
from ai_chat_client import AIChatClient
url = "https://aiclound.vip/v1/chat/completions"
api_key = "sk-BVJMgXvwbZ86OuYJcLhgr6YaHxTTuIdvwbZ86OuYJcLh" # 替换为你的实际 API Key
client = AIChatClient(url, api_key)
result = client.chat("帮我写一个python的贪吃蛇")
# 提取 AI 回答内容
if "choices" in result:
content = result["choices"][0]["message"]["content"]
print("AI 生成的代码:")
print(content)
else:
print("请求失败:", result)
```
---
#### 5. 扩展建议
- 参数支持: 在 chat
方法中添加更多可选参数(如 temperaturemax_tokens
)。
- 流式输出: 处理 stream=True
的情况,使用 response.iter_lines()
解析增量数据。
- 日志: 集成 logging
记录请求和响应。
希望这个教程对你有帮助!如果需要进一步优化或有其他问题,请随时告诉我。