API 集成开发指南
概述
本文档介绍如何通过 API 将大语言模型能力集成到您的应用程序中,支持多种编程语言和框架。
快速开始
获取 API 密钥
- 登录控制台: https://console.m9ai.work
- 进入「API 管理」页面
- 点击「创建密钥」,复制生成的 API Key
基础请求示例
cURL
bash1curl -X POST "https://api.m9ai.work/v1/chat/completions" \ 2 -H "Authorization: Bearer YOUR_API_KEY" \ 3 -H "Content-Type: application/json" \ 4 -d '{ 5 "model": "gpt-4", 6 "messages": [ 7 {"role": "user", "content": "你好!"} 8 ] 9 }'
Python
python1from openai import OpenAI 2 3client = OpenAI( 4 api_key="YOUR_API_KEY", 5 base_url="https://api.m9ai.work/v1" 6) 7 8response = client.chat.completions.create( 9 model="gpt-4", 10 messages=[ 11 {"role": "user", "content": "你好!"} 12 ] 13) 14 15print(response.choices[0].message.content)
JavaScript
javascript1import OpenAI from 'openai'; 2 3const client = new OpenAI({ 4 apiKey: 'YOUR_API_KEY', 5 baseURL: 'https://api.m9ai.work/v1', 6}); 7 8async function chat() { 9 const response = await client.chat.completions.create({ 10 model: 'gpt-4', 11 messages: [{ role: 'user', content: '你好!' }], 12 }); 13 14 console.log(response.choices[0].message.content); 15} 16 17chat();
API 参考
对话补全
Endpoint: POST /v1/chat/completions
请求参数
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
| model | string | 是 | 模型名称: gpt-4, gpt-3.5-turbo |
| messages | array | 是 | 消息列表 |
| temperature | float | 否 | 随机性 (0-2), 默认 0.7 |
| max_tokens | integer | 否 | 最大生成 token 数 |
| stream | boolean | 否 | 是否流式输出 |
响应格式
json1{ 2 "id": "chatcmpl-xxx", 3 "object": "chat.completion", 4 "created": 1677652288, 5 "model": "gpt-4", 6 "choices": [{ 7 "index": 0, 8 "message": { 9 "role": "assistant", 10 "content": "你好!有什么可以帮助你的吗?" 11 }, 12 "finish_reason": "stop" 13 }], 14 "usage": { 15 "prompt_tokens": 9, 16 "completion_tokens": 12, 17 "total_tokens": 21 18 } 19}
文本嵌入
Endpoint: POST /v1/embeddings
python1response = client.embeddings.create( 2 model="text-embedding-ada-002", 3 input="要嵌入的文本" 4) 5 6embedding = response.data[0].embedding
流式输出
python1response = client.chat.completions.create( 2 model="gpt-4", 3 messages=[{"role": "user", "content": "讲个故事"}], 4 stream=True 5) 6 7for chunk in response: 8 if chunk.choices[0].delta.content: 9 print(chunk.choices[0].delta.content, end="")
高级用法
函数调用
python1def get_weather(location, unit="celsius"): 2 # 实际天气查询逻辑 3 return {"temperature": 25, "condition": "sunny"} 4 5tools = [{ 6 "type": "function", 7 "function": { 8 "name": "get_weather", 9 "description": "获取指定位置的天气信息", 10 "parameters": { 11 "type": "object", 12 "properties": { 13 "location": { 14 "type": "string", 15 "description": "城市名称,如北京、上海" 16 }, 17 "unit": { 18 "type": "string", 19 "enum": ["celsius", "fahrenheit"], 20 "description": "温度单位" 21 } 22 }, 23 "required": ["location"] 24 } 25 } 26}] 27 28response = client.chat.completions.create( 29 model="gpt-4", 30 messages=[{"role": "user", "content": "北京今天天气怎么样?"}], 31 tools=tools, 32 tool_choice="auto" 33) 34 35# 处理函数调用 36if response.choices[0].finish_reason == "tool_calls": 37 tool_call = response.choices[0].message.tool_calls[0] 38 function_name = tool_call.function.name 39 arguments = json.loads(tool_call.function.arguments) 40 41 if function_name == "get_weather": 42 result = get_weather(**arguments) 43 print(result)
错误处理
python1from openai import APIError, RateLimitError, AuthenticationError 2 3try: 4 response = client.chat.completions.create(...) 5except AuthenticationError: 6 print("API 密钥无效,请检查配置") 7except RateLimitError: 8 print("请求过于频繁,请稍后重试") 9except APIError as e: 10 print(f"API 错误: {e.message}")
最佳实践
1. 连接池配置
python1import httpx 2 3# 自定义 HTTP 客户端 4http_client = httpx.Client( 5 limits=httpx.Limits( 6 max_connections=100, 7 max_keepalive_connections=20 8 ), 9 timeout=httpx.Timeout(60.0) 10) 11 12client = OpenAI( 13 api_key="YOUR_API_KEY", 14 base_url="https://api.m9ai.work/v1", 15 http_client=http_client 16)
2. 重试策略
python1from tenacity import retry, stop_after_attempt, wait_exponential 2 3@retry( 4 stop=stop_after_attempt(3), 5 wait=wait_exponential(multiplier=1, min=4, max=10) 6) 7def chat_with_retry(messages): 8 return client.chat.completions.create( 9 model="gpt-4", 10 messages=messages 11 )
3. 请求超时设置
python1response = client.chat.completions.create( 2 model="gpt-4", 3 messages=messages, 4 timeout=30.0 # 30秒超时 5)
SDK 下载
- Python:
pip install openai - JavaScript:
npm install openai - Go:
go get github.com/sashabaranov/go-openai - Java: Maven/Gradle 依赖见文档
更多资源
- 完整 API 文档: https://docs.m9ai.work/api
- 示例代码: https://github.com/m9ai/examples
- 技术支持: c@m9ai.work