基于Flask搭建零一万物API代理服务指南
一、平台简介
零一万物(Yi-API)是新一代对话大模型开放平台,提供与OpenAI兼容的API接口。核心优势:
因为是免费api服务且同时完全支持openai的api接口,大家可以先当成demo练练手,该模型无法进行复杂思考!!
核心特性
- OpenAI兼容:平滑迁移现有ChatGPT应用
- 高性能推理:优化后的API响应延迟<800ms
- 多模态支持:文本生成/翻译/代码/数学推理
- 开发者友好:提供Python/Java/Go等多语言SDK
二、环境准备
1. Python环境
Bash
# 要求Python ≥3.7.1
python --version
2. 依赖安装
Powershell
pip install flask requests flask-cors
三、代理服务实现
1. 基础配置
Python
from flask import Flask, request, jsonify
import requests
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # 解决跨域问题
# API配置(替换为实际值)
API_CONFIG = {
"base_url": "https://api.lingyiwanwu.com/v1",
"api_key": "your_api_key_here"
}
2. 路由控制器
Python
@app.route('/api/chat/completions', methods=['POST'])
def chat_completions():
"""
对话生成接口
请求示例:POST JSON包含messages/model等参数
响应结构:{id, object, created, model, choices}
"""
return _proxy_request('POST', '/chat/completions')
@app.route('/api/models', methods=['GET'])
def list_models():
"""获取可用模型列表"""
return _proxy_request('GET', '/models')
@app.route('/', methods=['GET'])
def health_check():
"""服务健康检查"""
return jsonify({
"status": "running",
"version": "1.0.0",
"supported_routes": ["/api/chat/completions", "/api/models"]
})
3. 请求代理核心方法
Python
def _proxy_request(method, endpoint):
"""统一代理请求方法"""
try:
# 构造请求头
headers = {
"Authorization": f"Bearer {API_CONFIG['api_key']}",
"Content-Type": "application/json"
}
# 转发请求
response = requests.request(
method=method,
url=f"{API_CONFIG['base_url']}{endpoint}",
headers=headers,
json=request.json if method == 'POST' else None
)
# 处理响应
return jsonify(response.json()), response.status_code
except Exception as e:
return jsonify({
"error": f"代理请求失败: {str(e)}"
}), 500
4. 服务启动
Python
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000, debug=True)
四、服务验证
1. 启动服务
Bash
python app.py
2. 测试接口(使用curl)
Bash
# 健康检查
curl http://localhost:9000
# 获取模型列表
curl http://localhost:9000/api/models
# 对话测试
curl -X POST http://localhost:9000/api/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "yi-34b-chat",
"messages": [{
"role": "user",
"content": "请用Python实现快速排序"
}]
}'