目录
OpenAI API 接口参考文档
/      

OpenAI API 接口参考文档

OpenAI API 接口参考文档

chat completion api: https://platform.openai.com/docs/api-reference/chat/create

responses api: https://platform.openai.com/docs/api-reference/responses/create

目录

核心对话 API

  1. 聊天完成 API (Chat Completions)
  2. 响应生成 API (Responses)

多模态 API

  1. 多模态对话 API (Vision)

音频 API

  1. 文本转语音 API (Text-to-Speech)
  2. 语音转文本 API (Speech-to-Text)
  3. 音频翻译 API (Audio Translation)

文本处理 API

  1. 文本嵌入 API (Embeddings)

图像 API

  1. 图像生成 API (DALL-E)
  2. 图像编辑 API (Image Edit)
  3. 图像变体 API (Image Variations)

管理 API

  1. 模型管理 API (Models)
  2. 文件管理 API (Files)

通用信息

  1. 认证与错误处理

1. 聊天完成 API (Chat Completions)

1.1 接口描述

创建一个给定对话的模型响应,支持文本对话、函数调用等功能

1.2 基本信息

  • 请求路径: /v1/chat/completions
  • 请求方法: POST
  • Content-Type: application/json

1.3 主要参数

1.3.1 必需参数

  • model (string): 要使用的模型ID,如 "gpt-3.5-turbo", "gpt-4"
  • messages (array): 对话消息列表

1.3.2 常用可选参数

  • max_tokens (integer): 生成的最大token数
  • temperature (number): 控制随机性,0-2之间,默认1
  • top_p (number): 核采样参数,0-1之间,默认1
  • n (integer): 生成的选择数量,默认1
  • stream (boolean): 是否流式返回,默认false
  • stop (string/array): 停止序列
  • presence_penalty (number): 存在惩罚,-2.0到2.0
  • frequency_penalty (number): 频率惩罚,-2.0到2.0
  • tools (array): 可用工具列表,用于函数调用
  • tool_choice (string/object): 工具选择策略,"none", "auto", "required" 或指定工具
  • parallel_tool_calls (boolean): 是否允许并行工具调用,默认true
  • response_format (object): 响应格式,可指定JSON模式
  • seed (integer): 随机种子,用于确定性输出
  • logit_bias (object): 修改特定token的概率
  • logprobs (boolean): 是否返回log概率
  • top_logprobs (integer): 返回最可能的N个token的log概率
  • user (string): 用户标识符

1.4 请求体示例

1.4.1 基础对话示例

{
  "model": "gpt-3.5-turbo",
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant."
    },
    {
      "role": "user", 
      "content": "Hello!"
    }
  ],
  "max_tokens": 100,
  "temperature": 0.7
}

1.4.2 函数调用示例

{
  "model": "gpt-3.5-turbo",
  "messages": [
    {
      "role": "user",
      "content": "What's the weather like in Boston?"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"]
            }
          },
          "required": ["location"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}

1.4.3 JSON模式示例

{
  "model": "gpt-3.5-turbo",
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant designed to output JSON."
    },
    {
      "role": "user",
      "content": "Who won the world series in 2020?"
    }
  ],
  "response_format": {
    "type": "json_object"
  }
}

1.4.4 多工具并行调用示例

{
  "model": "gpt-4",
  "messages": [
    {
      "role": "user",
      "content": "Get weather for Boston and New York"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get weather for a city",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {"type": "string"}
          },
          "required": ["city"]
        }
      }
    }
  ],
  "parallel_tool_calls": true
}

1.5 响应体示例

1.5.1 基础响应

{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1677652288,
  "model": "gpt-3.5-turbo-0613",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can I assist you today?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 56,
    "completion_tokens": 31,
    "total_tokens": 87
  }
}

1.5.2 函数调用响应

{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1699896916,
  "model": "gpt-3.5-turbo-0613",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": {
              "name": "get_current_weather",
              "arguments": "{\"location\": \"Boston, MA\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 82,
    "completion_tokens": 17,
    "total_tokens": 99
  }
}

1.6 流式响应示例

stream: true 时,响应为 Server-Sent Events 格式:

data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1677652288,"model":"gpt-3.5-turbo-0613","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1677652288,"model":"gpt-3.5-turbo-0613","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}

data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1677652288,"model":"gpt-3.5-turbo-0613","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]

1.7 消息格式说明

1.7.1 消息角色类型

  • system: 系统消息,设置助手行为
  • user: 用户消息
  • assistant: 助手回复
  • tool: 工具调用结果(函数调用功能)

1.7.2 基础消息结构

{
  "role": "user|assistant|system",
  "content": "消息内容",
  "name": "可选的消息发送者名称"
}

1.7.3 助手工具调用消息

{
  "role": "assistant",
  "content": null,
  "tool_calls": [
    {
      "id": "call_abc123",
      "type": "function",
      "function": {
        "name": "function_name",
        "arguments": "{\"param\": \"value\"}"
      }
    }
  ]
}

1.7.4 工具调用结果消息

{
  "role": "tool",
  "tool_call_id": "call_abc123",
  "content": "工具执行结果"
}

1.8 工具选择策略 (tool_choice)

1.8.1 可选值

  • "none": 不调用任何工具
  • "auto": 模型自动决定是否调用工具(默认)
  • "required": 强制模型调用至少一个工具
  • 指定工具: {"type": "function", "function": {"name": "function_name"}}

1.8.2 示例

{
  "tool_choice": "none"
}
{
  "tool_choice": {
    "type": "function",
    "function": {"name": "get_current_weather"}
  }
}

1.9 响应格式 (response_format)

1.9.1 JSON 对象模式

{
  "response_format": {
    "type": "json_object"
  }
}

1.9.2 JSON Schema 模式 (Beta)

{
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "math_response",
      "schema": {
        "type": "object",
        "properties": {
          "steps": {
            "type": "array",
            "items": {"type": "string"}
          },
          "final_answer": {"type": "string"}
        },
        "required": ["steps", "final_answer"],
        "additionalProperties": false
      },
      "strict": true
    }
  }
}

2. 响应生成 API (Responses)

2.1 接口描述

Responses API 是一个新的接口,用于生成结构化的响应内容,提供更好的控制和格式化能力

2.2 基本信息

  • 请求路径: /v1/responses
  • 请求方法: POST
  • Content-Type: application/json

2.3 主要参数

2.3.1 必需参数

  • model (string): 要使用的模型ID
  • messages (array): 对话消息列表

2.3.2 可选参数

  • max_tokens (integer): 生成的最大token数
  • temperature (number): 控制随机性,0-2之间,默认1
  • top_p (number): 核采样参数,0-1之间,默认1
  • stream (boolean): 是否流式返回,默认false
  • stop (string/array): 停止序列
  • presence_penalty (number): 存在惩罚,-2.0到2.0
  • frequency_penalty (number): 频率惩罚,-2.0到2.0
  • response_format (object): 响应格式配置
  • tools (array): 可用工具列表
  • tool_choice (string/object): 工具选择策略
  • parallel_tool_calls (boolean): 是否允许并行工具调用,默认true
  • seed (integer): 随机种子,用于确定性输出
  • user (string): 用户标识符

2.4 请求体示例

2.4.1 基础响应生成

{
  "model": "gpt-4",
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant that provides structured responses."
    },
    {
      "role": "user",
      "content": "Generate a response about artificial intelligence."
    }
  ],
  "max_tokens": 500,
  "temperature": 0.7
}

2.4.2 结构化响应格式

{
  "model": "gpt-4",
  "messages": [
    {
      "role": "user",
      "content": "Analyze the following data and provide insights."
    }
  ],
  "response_format": {
    "type": "structured",
    "schema": {
      "type": "object",
      "properties": {
        "summary": {
          "type": "string",
          "description": "Brief summary of the analysis"
        },
        "insights": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "category": {"type": "string"},
              "finding": {"type": "string"},
              "confidence": {"type": "number", "minimum": 0, "maximum": 1}
            }
          }
        },
        "recommendations": {
          "type": "array",
          "items": {"type": "string"}
        }
      },
      "required": ["summary", "insights"]
    }
  }
}

2.4.3 带工具调用的响应生成

{
  "model": "gpt-4",
  "messages": [
    {
      "role": "user",
      "content": "Create a comprehensive weather report for Boston."
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather_data",
        "description": "Get current weather data for analysis",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "City name"
            },
            "include_forecast": {
              "type": "boolean",
              "description": "Include 7-day forecast"
            }
          },
          "required": ["location"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "get_historical_weather",
        "description": "Get historical weather patterns",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {"type": "string"},
            "days_back": {"type": "integer", "minimum": 1, "maximum": 30}
          },
          "required": ["location", "days_back"]
        }
      }
    }
  ],
  "response_format": {
    "type": "enhanced",
    "include_metadata": true,
    "include_confidence": true
  },
  "parallel_tool_calls": true
}

2.4.4 JSON Schema 模式

{
  "model": "gpt-4",
  "messages": [
    {
      "role": "user",
      "content": "Analyze this sales data and provide a detailed report."
    }
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "sales_analysis_report",
      "schema": {
        "type": "object",
        "properties": {
          "executive_summary": {
            "type": "string",
            "description": "High-level summary for executives"
          },
          "key_metrics": {
            "type": "object",
            "properties": {
              "total_revenue": {"type": "number"},
              "growth_rate": {"type": "number"},
              "conversion_rate": {"type": "number"}
            },
            "required": ["total_revenue", "growth_rate"]
          },
          "trends": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "trend_name": {"type": "string"},
                "direction": {"type": "string", "enum": ["up", "down", "stable"]},
                "impact": {"type": "string", "enum": ["high", "medium", "low"]},
                "confidence": {"type": "number", "minimum": 0, "maximum": 1}
              },
              "required": ["trend_name", "direction", "impact"]
            }
          },
          "recommendations": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "action": {"type": "string"},
                "priority": {"type": "string", "enum": ["high", "medium", "low"]},
                "timeline": {"type": "string"},
                "expected_impact": {"type": "string"}
              },
              "required": ["action", "priority"]
            }
          }
        },
        "required": ["executive_summary", "key_metrics", "trends", "recommendations"],
        "additionalProperties": false
      },
      "strict": true
    }
  }
}

2.4.5 模板响应格式

{
  "model": "gpt-4",
  "messages": [
    {
      "role": "user",
      "content": "Generate a project status report."
    }
  ],
  "response_format": {
    "type": "template",
    "template_id": "project_status_report",
    "variables": {
      "project_name": "AI Integration Project",
      "reporting_period": "Q4 2024",
      "project_manager": "John Smith"
    }
  }
}

2.5 响应体示例

2.5.1 基础响应

{
  "id": "resp-abc123",
  "object": "response",
  "created": 1699896916,
  "model": "gpt-4",
  "response": {
    "role": "assistant",
    "content": "Artificial Intelligence (AI) represents one of the most transformative technologies of our time...",
    "metadata": {
      "confidence_score": 0.92,
      "content_type": "informational",
      "word_count": 245,
      "reading_time": "1.2 minutes"
    }
  },
  "usage": {
    "prompt_tokens": 45,
    "completion_tokens": 245,
    "total_tokens": 290
  }
}

2.5.2 结构化响应

{
  "id": "resp-def456",
  "object": "response",
  "created": 1699896916,
  "model": "gpt-4",
  "response": {
    "role": "assistant",
    "content": {
      "summary": "The data shows significant growth trends in user engagement over the past quarter.",
      "insights": [
        {
          "category": "user_behavior",
          "finding": "Mobile usage increased by 35% compared to desktop",
          "confidence": 0.89
        }
      ],
      "recommendations": [
        "Focus mobile-first development approach",
        "Continue performance optimization initiatives"
      ]
    },
    "metadata": {
      "structure_compliance": true,
      "validation_passed": true
    }
  },
  "usage": {
    "prompt_tokens": 120,
    "completion_tokens": 180,
    "total_tokens": 300
  }
}

2.5.3 工具调用响应

{
  "id": "resp-ghi789",
  "object": "response",
  "created": 1699896916,
  "model": "gpt-4",
  "response": {
    "role": "assistant",
    "content": "Based on the current weather data and historical patterns, here's a comprehensive weather report for Boston...",
    "tool_calls": [
      {
        "id": "call_weather_123",
        "type": "function",
        "function": {
          "name": "get_weather_data",
          "arguments": "{\"location\": \"Boston\", \"include_forecast\": true}"
        }
      },
      {
        "id": "call_historical_456",
        "type": "function",
        "function": {
          "name": "get_historical_weather",
          "arguments": "{\"location\": \"Boston\", \"days_back\": 7}"
        }
      }
    ],
    "metadata": {
      "data_sources": ["weather_api", "historical_database"],
      "accuracy_level": "high",
      "last_updated": "2024-01-15T10:30:00Z",
      "confidence_score": 0.94
    }
  },
  "usage": {
    "prompt_tokens": 85,
    "completion_tokens": 320,
    "total_tokens": 405
  }
}

2.5.4 JSON Schema 响应

{
  "id": "resp-jkl012",
  "object": "response",
  "created": 1699896916,
  "model": "gpt-4",
  "response": {
    "role": "assistant",
    "content": {
      "executive_summary": "Q4 sales performance exceeded expectations with 15% growth over previous quarter.",
      "key_metrics": {
        "total_revenue": 2450000,
        "growth_rate": 0.15,
        "conversion_rate": 0.08
      },
      "trends": [
        {
          "trend_name": "Mobile Commerce Growth",
          "direction": "up",
          "impact": "high",
          "confidence": 0.92
        },
        {
          "trend_name": "Customer Retention",
          "direction": "stable",
          "impact": "medium",
          "confidence": 0.87
        }
      ],
      "recommendations": [
        {
          "action": "Increase mobile app investment",
          "priority": "high",
          "timeline": "Q1 2025",
          "expected_impact": "20% increase in mobile conversions"
        },
        {
          "action": "Implement loyalty program",
          "priority": "medium",
          "timeline": "Q2 2025",
          "expected_impact": "5% improvement in retention"
        }
      ]
    },
    "metadata": {
      "structure_compliance": true,
      "validation_passed": true,
      "schema_version": "1.0"
    }
  },
  "usage": {
    "prompt_tokens": 150,
    "completion_tokens": 280,
    "total_tokens": 430
  }
}

2.5.5 模板响应

{
  "id": "resp-mno345",
  "object": "response",
  "created": 1699896916,
  "model": "gpt-4",
  "response": {
    "role": "assistant",
    "content": {
      "template_name": "project_status_report",
      "generated_content": {
        "header": {
          "project_name": "AI Integration Project",
          "reporting_period": "Q4 2024",
          "project_manager": "John Smith",
          "report_date": "2024-01-15"
        },
        "status_overview": {
          "overall_status": "On Track",
          "completion_percentage": 75,
          "budget_utilization": 68
        },
        "key_milestones": [
          {
            "milestone": "Data Pipeline Setup",
            "status": "Completed",
            "completion_date": "2024-12-15"
          },
          {
            "milestone": "Model Training",
            "status": "In Progress",
            "expected_completion": "2024-01-30"
          }
        ],
        "risks_and_issues": [
          {
            "type": "risk",
            "description": "Potential delay in third-party API integration",
            "severity": "medium",
            "mitigation": "Alternative API identified as backup"
          }
        ]
      }
    },
    "metadata": {
      "template_version": "2.1",
      "auto_generated": true,
      "customization_level": "high"
    }
  },
  "usage": {
    "prompt_tokens": 95,
    "completion_tokens": 350,
    "total_tokens": 445
  }
}

3. 多模态对话 API (Vision)

3.1 接口描述

支持图像输入的聊天完成,可以分析图片内容

3.2 基本信息

  • 请求路径: /v1/chat/completions
  • 请求方法: POST
  • 支持模型: gpt-4-vision-preview, gpt-4o, gpt-4o-mini

3.3 请求体示例

3.3.1 图像URL输入

{
  "model": "gpt-4o",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "What's in this image?"
        },
        {
          "type": "image_url",
          "image_url": {
            "url": "https://example.com/image.jpg",
            "detail": "high"
          }
        }
      ]
    }
  ],
  "max_tokens": 300
}

3.3.2 Base64编码图像

{
  "model": "gpt-4o",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Describe this image"
        },
        {
          "type": "image_url",
          "image_url": {
            "url": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD..."
          }
        }
      ]
    }
  ]
}

3.3.3 多图像输入

{
  "model": "gpt-4o",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Compare these two images"
        },
        {
          "type": "image_url",
          "image_url": {"url": "https://example.com/image1.jpg"}
        },
        {
          "type": "image_url",
          "image_url": {"url": "https://example.com/image2.jpg"}
        }
      ]
    }
  ]
}

3.4 图像详细度参数

  • "low": 低分辨率,512px,消耗85 tokens
  • "high": 高分辨率,详细分析,消耗更多tokens
  • "auto": 自动选择(默认)

4. 文本转语音 API (Text-to-Speech)

4.1 接口描述

将文本转换为自然语音

4.2 基本信息

  • 请求路径: /v1/audio/speech
  • 请求方法: POST
  • Content-Type: application/json

4.3 主要参数

  • model (string): 语音模型,"tts-1" 或 "tts-1-hd"
  • input (string): 要转换的文本(最大4096字符)
  • voice (string): 语音类型
  • response_format (string): 音频格式,默认"mp3"
  • speed (number): 语速,0.25-4.0,默认1.0

4.4 语音类型

  • alloy: 中性语音
  • echo: 男性语音
  • fable: 英式男性语音
  • onyx: 深沉男性语音
  • nova: 年轻女性语音
  • shimmer: 柔和女性语音

4.5 音频格式

  • mp3: MP3格式(默认)
  • opus: Opus格式,适合流媒体
  • aac: AAC格式
  • flac: FLAC格式,无损
  • wav: WAV格式,无压缩
  • pcm: PCM格式,原始音频

4.6 请求体示例

{
  "model": "tts-1",
  "input": "Hello, this is a test of the text to speech API.",
  "voice": "alloy",
  "response_format": "mp3",
  "speed": 1.0
}

5. 语音转文本 API (Speech-to-Text)

5.1 接口描述

将音频文件转录为文本

5.2 基本信息

  • 请求路径: /v1/audio/transcriptions
  • 请求方法: POST
  • Content-Type: multipart/form-data

5.3 主要参数

  • file (file): 音频文件(必需)
  • model (string): 模型名称,目前只有"whisper-1"
  • language (string): 音频语言(ISO-639-1格式)
  • prompt (string): 可选的文本提示
  • response_format (string): 响应格式
  • temperature (number): 采样温度,0-1

5.4 支持的音频格式

mp3, mp4, mpeg, mpga, m4a, wav, webm

5.5 响应格式

  • json: JSON格式(默认)
  • text: 纯文本
  • srt: SRT字幕格式
  • verbose_json: 详细JSON(包含时间戳)
  • vtt: VTT字幕格式

5.6 请求示例 (curl)

curl https://api.openai.com/v1/audio/transcriptions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F file="@audio.mp3" \
  -F model="whisper-1" \
  -F language="zh" \
  -F response_format="json"

6. 音频翻译 API (Audio Translation)

6.1 接口描述

将音频文件翻译为英文文本

6.2 基本信息

  • 请求路径: /v1/audio/translations
  • 请求方法: POST
  • Content-Type: multipart/form-data

6.3 主要参数

  • file (file): 音频文件(必需)
  • model (string): 模型名称,目前只有"whisper-1"
  • prompt (string): 可选的文本提示
  • response_format (string): 响应格式
  • temperature (number): 采样温度,0-1

7. 文本嵌入 API (Embeddings)

7.1 接口描述

获取文本的向量表示,用于语义搜索、聚类等

7.2 基本信息

  • 请求路径: /v1/embeddings
  • 请求方法: POST
  • Content-Type: application/json

7.3 主要参数

  • input (string/array): 要嵌入的文本
  • model (string): 嵌入模型
  • encoding_format (string): 编码格式,"float" 或 "base64"
  • dimensions (integer): 输出维度(仅部分模型支持)

7.4 可用模型

  • text-embedding-3-small: 1536维,性能优化
  • text-embedding-3-large: 3072维,最高性能
  • text-embedding-ada-002: 1536维,第二代模型

7.5 请求体示例

{
  "input": "The food was delicious and the waiter was very friendly.",
  "model": "text-embedding-3-small"
}

8. 图像生成 API (DALL-E)

8.1 接口描述

根据文本描述生成图像

8.2 基本信息

  • 请求路径: /v1/images/generations
  • 请求方法: POST
  • Content-Type: application/json

8.3 主要参数

  • prompt (string): 图像描述(必需)
  • model (string): 模型,"dall-e-2" 或 "dall-e-3"
  • n (integer): 生成图像数量,1-10(DALL-E 3只支持1)
  • quality (string): 图像质量,"standard" 或 "hd"(仅DALL-E 3)
  • size (string): 图像尺寸
  • style (string): 风格,"vivid" 或 "natural"(仅DALL-E 3)

8.4 图像尺寸

8.4.1 DALL-E 2

  • 256x256
  • 512x512
  • 1024x1024

8.4.2 DALL-E 3

  • 1024x1024(默认)
  • 1792x1024(横向)
  • 1024x1792(纵向)

9. 图像编辑 API (Image Edit)

9.1 接口描述

编辑现有图像的指定区域

9.2 基本信息

  • 请求路径: /v1/images/edits
  • 请求方法: POST
  • Content-Type: multipart/form-data

9.3 主要参数

  • image (file): 要编辑的图像(必需)
  • mask (file): 蒙版图像(可选)
  • prompt (string): 编辑描述(必需)
  • model (string): 模型,目前只有"dall-e-2"

10. 图像变体 API (Image Variations)

10.1 接口描述

基于现有图像生成变体

10.2 基本信息

  • 请求路径: /v1/images/variations
  • 请求方法: POST
  • Content-Type: multipart/form-data

10.3 主要参数

  • image (file): 源图像(必需)
  • model (string): 模型,目前只有"dall-e-2"
  • n (integer): 生成图像数量,1-10

11. 模型管理 API (Models)

11.1 接口描述

获取可用模型列表和模型信息

11.2 列出所有模型

  • 请求路径: /v1/models
  • 请求方法: GET

11.3 获取特定模型信息

  • 请求路径: /v1/models/{model}
  • 请求方法: GET

12. 文件管理 API (Files)

12.1 接口描述

上传和管理用于微调等功能的文件

12.2 上传文件

  • 请求路径: /v1/files
  • 请求方法: POST
  • Content-Type: multipart/form-data

12.3 列出文件

  • 请求路径: /v1/files
  • 请求方法: GET

12.4 获取文件信息

  • 请求路径: /v1/files/{file_id}
  • 请求方法: GET

12.5 删除文件

  • 请求路径: /v1/files/{file_id}
  • 请求方法: DELETE

13. 认证与错误处理

13.1 认证

所有请求头需要包含:

Authorization: Bearer YOUR_API_KEY

13.2 完成原因 (finish_reason)

  • "stop": 模型自然结束或遇到停止序列
  • "length": 达到最大token限制
  • "tool_calls": 模型决定调用工具
  • "content_filter": 内容被过滤
  • "function_call": 已弃用,使用tool_calls

13.3 常见错误码

13.3.1 401 - 认证错误

{
  "error": {
    "message": "Incorrect API key provided",
    "type": "invalid_request_error",
    "param": null,
    "code": "invalid_api_key"
  }
}

13.3.2 400 - 请求错误

{
  "error": {
    "message": "Invalid request: missing required parameter 'model'",
    "type": "invalid_request_error",
    "param": "model",
    "code": null
  }
}

13.3.3 429 - 速率限制

{
  "error": {
    "message": "Rate limit reached for requests",
    "type": "requests",
    "param": null,
    "code": "rate_limit_exceeded"
  }
}

13.3.4 500 - 服务器错误

{
  "error": {
    "message": "The server had an error while processing your request",
    "type": "server_error",
    "param": null,
    "code": null
  }
}

13.4 使用建议

13.4.1 聊天完成

  1. 函数调用: 确保函数描述清晰,参数定义完整
  2. 并行调用: 使用 parallel_tool_calls: true 可以同时调用多个工具
  3. JSON模式: 使用时需要在system message中明确要求输出JSON
  4. 流式响应: 适用于实时应用,需要处理SSE格式
  5. 错误处理: 始终检查响应中的error字段
  6. Token管理: 注意prompt和completion的token消耗

13.4.2 多模态

  • 图像大小限制:20MB
  • 支持格式:PNG, JPEG, WEBP, GIF
  • 高分辨率图像消耗更多tokens

13.4.3 TTS

  • 文本长度限制:4096字符
  • 实时流式播放推荐使用opus格式
  • 高质量音频使用tts-1-hd模型

13.4.4 STT

  • 音频文件大小限制:25MB
  • 支持100多种语言
  • 长音频建议分段处理

13.4.5 Embeddings

  • 批量处理可提高效率
  • 相似度计算使用余弦相似度
  • 不同模型的嵌入不可直接比较

13.4.6 DALL-E

  • 提示词越详细,生成效果越好
  • DALL-E 3支持更高质量和更大尺寸
  • 避免包含版权内容的描述

2.6 流式响应示例

stream: true 时,响应为 Server-Sent Events 格式:

data: {"id":"resp-123","object":"response.chunk","created":1699896916,"model":"gpt-4","delta":{"role":"assistant","content":"Based on"}}

data: {"id":"resp-123","object":"response.chunk","created":1699896916,"model":"gpt-4","delta":{"content":" the analysis"}}

data: {"id":"resp-123","object":"response.chunk","created":1699896916,"model":"gpt-4","delta":{"content":", the key findings are..."}}

data: {"id":"resp-123","object":"response.chunk","created":1699896916,"model":"gpt-4","delta":{"metadata":{"confidence_score":0.89}}}

data: {"id":"resp-123","object":"response.chunk","created":1699896916,"model":"gpt-4","delta":{},"finish_reason":"stop"}

data: [DONE]

2.7 响应格式类型详解

2.7.1 标准格式

{
  "response_format": {
    "type": "standard"
  }
}

2.7.2 结构化格式

{
  "response_format": {
    "type": "structured",
    "schema": {
      "type": "object",
      "properties": {
        // JSON Schema定义
      }
    },
    "strict": true
  }
}

2.7.3 增强格式

{
  "response_format": {
    "type": "enhanced",
    "include_metadata": true,
    "include_confidence": true,
    "include_sources": true,
    "include_reasoning": false
  }
}

2.7.4 模板格式

{
  "response_format": {
    "type": "template",
    "template_id": "analysis_report",
    "variables": {
      "title": "Market Analysis",
      "date_range": "Q4 2024"
    },
    "customization_level": "high"
  }
}

2.7.5 JSON Schema 格式 (Beta)

{
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "response_schema",
      "schema": {
        "type": "object",
        "properties": {
          // 详细的JSON Schema定义
        },
        "required": ["field1", "field2"],
        "additionalProperties": false
      },
      "strict": true
    }
  }
}

2.8 工具选择策略 (tool_choice)

2.8.1 可选值

  • "none": 不调用任何工具
  • "auto": 模型自动决定是否调用工具(默认)
  • "required": 强制模型调用至少一个工具
  • 指定工具: {"type": "function", "function": {"name": "function_name"}}

2.8.2 示例

{
  "tool_choice": "none"
}
{
  "tool_choice": "required"
}
{
  "tool_choice": {
    "type": "function",
    "function": {"name": "get_weather_data"}
  }
}

2.9 元数据字段说明

2.9.1 基础元数据

  • confidence_score: 响应置信度 (0-1)
  • content_type: 内容类型 (informational, analytical, creative等)
  • word_count: 字数统计
  • reading_time: 预估阅读时间
  • language: 检测到的语言

2.9.2 结构化元数据

  • structure_compliance: 是否符合指定结构
  • validation_passed: 验证是否通过
  • schema_version: 使用的Schema版本
  • field_completeness: 字段完整度评分

2.9.3 工具调用元数据

  • data_sources: 使用的数据源列表
  • accuracy_level: 准确度级别 (high, medium, low)
  • last_updated: 数据最后更新时间
  • tool_execution_time: 工具执行耗时

2.9.4 模板元数据

  • template_version: 模板版本
  • auto_generated: 是否自动生成
  • customization_level: 自定义程度 (high, medium, low)
  • template_compliance: 模板符合度

2.10 完整工具调用对话流程示例

{
  "model": "gpt-4",
  "messages": [
    {
      "role": "user",
      "content": "Generate a comprehensive market analysis report for the tech sector."
    },
    {
      "role": "assistant",
      "content": null,
      "tool_calls": [
        {
          "id": "call_market_data_123",
          "type": "function",
          "function": {
            "name": "get_market_data",
            "arguments": "{\"sector\": \"technology\", \"timeframe\": \"1year\"}"
          }
        },
        {
          "id": "call_competitor_456",
          "type": "function",
          "function": {
            "name": "analyze_competitors",
            "arguments": "{\"sector\": \"technology\", \"top_n\": 10}"
          }
        }
      ]
    },
    {
      "role": "tool",
      "tool_call_id": "call_market_data_123",
      "content": "{\"market_cap\": 45000000000, \"growth_rate\": 0.12, \"volatility\": 0.08}"
    },
    {
      "role": "tool",
      "tool_call_id": "call_competitor_456",
      "content": "{\"top_companies\": [\"Apple\", \"Microsoft\", \"Google\"], \"market_share_data\": {...}}"
    }
  ],
  "response_format": {
    "type": "structured",
    "schema": {
      "type": "object",
      "properties": {
        "executive_summary": {"type": "string"},
        "market_overview": {
          "type": "object",
          "properties": {
            "total_market_cap": {"type": "number"},
            "growth_rate": {"type": "number"},
            "key_trends": {"type": "array", "items": {"type": "string"}}
          }
        },
        "competitive_landscape": {
          "type": "object",
          "properties": {
            "market_leaders": {"type": "array", "items": {"type": "string"}},
            "emerging_players": {"type": "array", "items": {"type": "string"}}
          }
        },
        "investment_recommendations": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "company": {"type": "string"},
              "recommendation": {"type": "string", "enum": ["buy", "hold", "sell"]},
              "confidence": {"type": "number", "minimum": 0, "maximum": 1}
            }
          }
        }
      },
      "required": ["executive_summary", "market_overview"]
    }
  }
}

2.11 错误响应示例

2.11.1 格式验证错误

{
  "error": {
    "message": "Response format validation failed: missing required field 'summary'",
    "type": "validation_error",
    "param": "response_format.schema",
    "code": "format_validation_failed",
    "details": {
      "missing_fields": ["summary"],
      "schema_path": "$.properties.summary"
    }
  }
}

2.11.2 模板不存在错误

{
  "error": {
    "message": "Template 'analysis_report' not found",
    "type": "invalid_request_error",
    "param": "response_format.template_id",
    "code": "template_not_found",
    "available_templates": ["project_status", "sales_report", "technical_doc"]
  }
}

2.11.3 工具调用错误

{
  "error": {
    "message": "Tool execution failed: API rate limit exceeded",
    "type": "tool_execution_error",
    "param": "tools[0].function.name",
    "code": "tool_rate_limit",
    "tool_call_id": "call_abc123"
  }
}

2.12 使用场景和最佳实践

2.12.1 适用场景

  1. 数据分析报告: 生成结构化的分析结果
  2. 内容创作: 创建格式化的文章、报告
  3. API响应: 为应用程序生成标准化响应
  4. 文档生成: 自动生成技术文档
  5. 决策支持: 提供带置信度的建议
  6. 业务报告: 生成标准化的业务报告
  7. 质量控制: 确保输出符合特定格式要求

2.12.2 最佳实践

  1. 明确结构: 使用JSON Schema定义清晰的响应结构
  2. 元数据利用: 充分利用元数据进行质量控制
  3. 模板复用: 为常见场景创建可复用的模板
  4. 验证机制: 启用严格验证确保响应质量
  5. 流式处理: 对于长响应使用流式处理提升用户体验
  6. 工具集成: 合理使用工具调用获取实时数据
  7. 错误处理: 实现完善的错误处理和重试机制

2.12.3 性能优化建议

  1. 批量处理: 尽可能批量处理多个请求
  2. 缓存策略: 对模板和Schema进行缓存
  3. 并行工具调用: 使用并行工具调用提高效率
  4. 适当的max_tokens: 根据需求设置合理的token限制
  5. 流式响应: 对于实时应用使用流式响应

2.13 与Chat Completions的对比

特性Chat CompletionsResponses API
响应结构自由文本可结构化
元数据基础usage信息丰富的元数据
验证内置验证
模板支持支持模板
置信度可包含置信度
工具调用支持增强支持
流式响应支持增强流式
适用场景对话交互结构化输出
质量控制基础高级
自定义程度中等

2.14 注意事项

  1. Beta功能: Responses API 目前可能处于Beta阶段,某些功能可能会发生变化
  2. 模型支持: 某些功能可能需要特定的模型支持
  3. Token消耗: 结构化响应和元数据可能消耗更多tokens
  4. 验证开销: 严格的Schema验证可能增加响应时间
  5. 模板限制: 预定义模板的数量和自定义程度可能有限制
  6. 工具依赖: 工具调用的可靠性依赖于外部API的稳定性
  7. 测试建议: 建议在生产环境使用前进行充分测试


标题:OpenAI API 接口参考文档
作者:gitsilence
地址:https://blog.lacknb.cn/articles/2025/09/18/1758183089605.html