Создать завершение чата

MD версия

Отправляет запрос на получение ответа модели для указанного диалога. Поддерживаются потоковый и непотоковый режимы.

OpenAPI

yaml
openapi: 3.1.0 info: contact: email: support@openrouter.ai name: OpenRouter Support url: https://openrouter.ai/docs description: OpenAI-compatible API with additional OpenRouter features license: name: MIT url: https://opensource.org/licenses/MIT title: OpenRouter API version: 1.0.0 servers: - description: Production server url: https://openrouter.ai/api/v1 x-speakeasy-server-id: production security: - apiKey: [] tags: - description: API key management endpoints name: API Keys - description: Analytics and usage endpoints name: Analytics - description: Anthropic Messages endpoints name: Anthropic Messages - description: BYOK endpoints name: BYOK - description: Benchmarks endpoints name: Benchmarks - description: Chat completion endpoints name: Chat - description: Task classification market-share endpoints name: Classifications - description: Credit management endpoints name: Credits - description: >- Public OpenRouter usage datasets. Data returned by these endpoints is licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/): reuse and republish it, including commercially, with attribution to OpenRouter. name: Datasets - description: Text embedding endpoints name: Embeddings - description: Endpoint information name: Endpoints - description: Files endpoints name: Files - description: Generation history endpoints name: Generations - description: Guardrails endpoints name: Guardrails - description: Images endpoints name: Images - description: Model information endpoints name: Models - description: OAuth authentication endpoints name: OAuth - description: Observability endpoints name: Observability - description: Organization endpoints name: Organization - description: Presets endpoints name: Presets - description: Provider information endpoints name: Providers - description: Rerank endpoints name: Rerank - description: OpenAI-compatible Responses API endpoints name: Responses - description: SCIM endpoints name: SCIM - description: Speech-to-text endpoints name: STT x-displayName: Transcriptions - description: Text-to-speech endpoints name: TTS x-displayName: Speech - description: Video Generation endpoints name: Video Generation - description: Workspaces endpoints name: Workspaces - description: beta.Analytics endpoints name: beta.Analytics externalDocs: description: OpenRouter Documentation url: https://openrouter.ai/docs paths: /chat/completions: post: tags: - Chat summary: Create a chat completion description: >- Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes. operationId: sendChatCompletionRequest parameters: - description: >- Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility. example: enabled in: header name: X-OpenRouter-Metadata required: false schema: $ref: '#/components/schemas/MetadataLevel' requestBody: content: application/json: example: max_tokens: 150 messages: - content: You are a helpful assistant. role: system - content: What is the capital of France? role: user model: openai/gpt-4 temperature: 0.7 schema: $ref: '#/components/schemas/ChatRequest' required: true responses: '200': content: application/json: example: choices: - finish_reason: stop index: 0 message: content: The capital of France is Paris. role: assistant created: 1677652288 id: chatcmpl-123 model: openai/gpt-4 object: chat.completion system_fingerprint: fp_44709d6fcb usage: completion_tokens: 10 prompt_tokens: 25 total_tokens: 35 schema: $ref: '#/components/schemas/ChatResult' text/event-stream: example: data: choices: - delta: content: Hello role: assistant finish_reason: null index: 0 created: 1677652288 id: chatcmpl-123 model: openai/gpt-4 object: chat.completion.chunk schema: $ref: '#/components/schemas/ChatStreamingResponse' x-speakeasy-sse-sentinel: '[DONE]' description: Successful chat completion response '400': content: application/json: example: error: code: 400 message: Invalid request parameters schema: $ref: '#/components/schemas/BadRequestResponse' description: Bad Request - Invalid request parameters or malformed input '401': content: application/json: example: error: code: 401 message: Missing Authentication header schema: $ref: '#/components/schemas/UnauthorizedResponse' description: Unauthorized - Authentication required or invalid credentials '402': content: application/json: example: error: code: 402 message: >- Insufficient credits. Add more using https://openrouter.ai/credits schema: $ref: '#/components/schemas/PaymentRequiredResponse' description: Payment Required - Insufficient credits or quota to complete request '403': content: application/json: examples: guardrail-blocked: summary: Guardrail blocked the request value: error: code: 403 message: 'Request blocked: prompt injection patterns detected' metadata: patterns: - ignore all previous instructions openrouter_metadata: attempt: 1 endpoints: available: - model: openai/gpt-4o provider: OpenAI selected: false total: 1 is_byok: false pipeline: - data: action: blocked detected: true engines: - regex patterns: - ignore all previous instructions guardrail_id: grd_abc123 guardrail_scope: api-key name: regex_pi_detection summary: >- Blocked: prompt injection detected (1 pattern matched) type: guardrail region: iad requested: openai/gpt-4o strategy: direct summary: available=1 insufficient-permissions: summary: Insufficient permissions value: error: code: 403 message: Only management keys can perform this operation schema: $ref: '#/components/schemas/ForbiddenResponse' description: >- Forbidden - Authentication successful but insufficient permissions, or a guardrail blocked the request. When guardrails block and the `X-OpenRouter-Metadata: enabled` header is present, the response includes `openrouter_metadata` with full routing context and a `pipeline` array containing guardrail stage details. '404': content: application/json: example: error: code: 404 message: Resource not found schema: $ref: '#/components/schemas/NotFoundResponse' description: Not Found - Resource does not exist '408': content: application/json: example: error: code: 408 message: Operation timed out. Please try again later. schema: $ref: '#/components/schemas/RequestTimeoutResponse' description: Request Timeout - Operation exceeded time limit '413': content: application/json: example: error: code: 413 message: Request payload too large schema: $ref: '#/components/schemas/PayloadTooLargeResponse' description: Payload Too Large - Request payload exceeds size limits '422': content: application/json: example: error: code: 422 message: Invalid argument schema: $ref: '#/components/schemas/UnprocessableEntityResponse' description: Unprocessable Entity - Semantic validation failure '429': content: application/json: example: error: code: 429 message: Rate limit exceeded schema: $ref: '#/components/schemas/TooManyRequestsResponse' description: Too Many Requests - Rate limit exceeded '500': content: application/json: example: error: code: 500 message: Internal Server Error schema: $ref: '#/components/schemas/InternalServerResponse' description: Internal Server Error - Unexpected server error '502': content: application/json: example: error: code: 502 message: Provider returned error schema: $ref: '#/components/schemas/BadGatewayResponse' description: Bad Gateway - Provider/upstream API failure '503': content: application/json: example: error: code: 503 message: Service temporarily unavailable schema: $ref: '#/components/schemas/ServiceUnavailableResponse' description: Service Unavailable - Service temporarily unavailable '524': content: application/json: example: error: code: 524 message: Request timed out. Please try again later. schema: $ref: '#/components/schemas/EdgeNetworkTimeoutResponse' description: Infrastructure Timeout - Provider request timed out at edge network '529': content: application/json: example: error: code: 529 message: Provider returned error schema: $ref: '#/components/schemas/ProviderOverloadedResponse' description: Provider Overloaded - Provider is temporarily overloaded components: schemas: MetadataLevel: description: >- Opt-in level for surfacing routing metadata on the response under `openrouter_metadata`. enum: - disabled - enabled example: enabled type: string ChatRequest: description: Chat completion request parameters example: max_tokens: 150 messages: - content: You are a helpful assistant. role: system - content: What is the capital of France? role: user model: openai/gpt-4 temperature: 0.7 properties: cache_control: $ref: '#/components/schemas/AnthropicCacheControlDirective' debug: $ref: '#/components/schemas/ChatDebugOptions' frequency_penalty: description: Frequency penalty (-2.0 to 2.0) example: 0 format: double type: - number - 'null' image_config: $ref: '#/components/schemas/ImageConfig' logit_bias: additionalProperties: format: double type: number description: Token logit bias adjustments example: '50256': -100 type: - object - 'null' logprobs: description: Return log probabilities example: false type: - boolean - 'null' max_completion_tokens: description: Maximum tokens in completion example: 100 type: - integer - 'null' max_tokens: description: >- Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16. example: 100 type: - integer - 'null' messages: description: List of messages for the conversation example: - content: Hello! role: user items: $ref: '#/components/schemas/ChatMessages' minItems: 1 type: array metadata: additionalProperties: type: string description: >- Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values) example: session_id: session-456 user_id: user-123 type: object min_p: description: >- Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter. example: 0.1 format: double type: - number - 'null' modalities: description: >- Output modalities for the response. Supported values are "text", "image", and "audio". example: - text - image items: enum: - text - image - audio type: string type: array model: $ref: '#/components/schemas/ModelName' models: $ref: '#/components/schemas/ChatModelNames' parallel_tool_calls: description: >- Whether to enable parallel function calling during tool use. When true, the model may generate multiple tool calls in a single response. example: true type: - boolean - 'null' plugins: description: >- Plugins you want to enable for this request, including their settings. items: discriminator: mapping: auto-beta-router: $ref: '#/components/schemas/AutoBetaRouterPlugin' auto-router: $ref: '#/components/schemas/AutoRouterPlugin' context-compression: $ref: '#/components/schemas/ContextCompressionPlugin' file-parser: $ref: '#/components/schemas/FileParserPlugin' fusion: $ref: '#/components/schemas/FusionPlugin' moderation: $ref: '#/components/schemas/ModerationPlugin' pareto-router: $ref: '#/components/schemas/ParetoRouterPlugin' response-healing: $ref: '#/components/schemas/ResponseHealingPlugin' web: $ref: '#/components/schemas/WebSearchPlugin' web-fetch: $ref: '#/components/schemas/WebFetchPlugin' propertyName: id oneOf: - $ref: '#/components/schemas/AutoRouterPlugin' - $ref: '#/components/schemas/AutoBetaRouterPlugin' - $ref: '#/components/schemas/ModerationPlugin' - $ref: '#/components/schemas/WebSearchPlugin' - $ref: '#/components/schemas/WebFetchPlugin' - $ref: '#/components/schemas/FileParserPlugin' - $ref: '#/components/schemas/ResponseHealingPlugin' - $ref: '#/components/schemas/ContextCompressionPlugin' - $ref: '#/components/schemas/ParetoRouterPlugin' - $ref: '#/components/schemas/FusionPlugin' type: array prediction: $ref: '#/components/schemas/Prediction' presence_penalty: description: Presence penalty (-2.0 to 2.0) example: 0 format: double type: - number - 'null' prompt_cache_key: type: - string - 'null' prompt_cache_options: $ref: '#/components/schemas/PromptCacheOptions' provider: $ref: '#/components/schemas/ProviderPreferences' reasoning: description: Configuration options for reasoning models example: effort: medium summary: concise properties: effort: description: Constrains effort on reasoning for reasoning models enum: - max - xhigh - high - medium - low - minimal - none - null example: medium type: - string - 'null' summary: $ref: '#/components/schemas/ChatReasoningSummaryVerbosityEnum' type: object reasoning_effort: description: >- Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ. enum: - max - xhigh - high - medium - low - minimal - none - null example: medium type: - string - 'null' repetition_penalty: description: >- Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter. example: 1 format: double type: - number - 'null' response_format: description: Response format configuration discriminator: mapping: grammar: $ref: '#/components/schemas/ChatFormatGrammarConfig' json_object: $ref: '#/components/schemas/ChatFormatJsonObjectConfig' json_schema: $ref: '#/components/schemas/ChatFormatJsonSchemaConfig' python: $ref: '#/components/schemas/ChatFormatPythonConfig' text: $ref: '#/components/schemas/ChatFormatTextConfig' propertyName: type example: type: json_object oneOf: - $ref: '#/components/schemas/ChatFormatTextConfig' - $ref: '#/components/schemas/ChatFormatJsonObjectConfig' - $ref: '#/components/schemas/ChatFormatJsonSchemaConfig' - $ref: '#/components/schemas/ChatFormatGrammarConfig' - $ref: '#/components/schemas/ChatFormatPythonConfig' route: $ref: '#/components/schemas/DeprecatedRoute' seed: description: Random seed for deterministic outputs example: 42 type: - integer - 'null' service_tier: description: >- The service tier to use for processing this request. `fast` is accepted as an alias for `priority`. enum: - auto - default - fast - flex - priority - scale - null example: auto type: - string - 'null' session_id: description: >- A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters. maxLength: 256 type: string stop: anyOf: - type: string - items: type: string maxItems: 4 type: array - type: 'null' description: Stop sequences (up to 4) example: - |+ stop_server_tools_when: $ref: '#/components/schemas/StopServerToolsWhen' stream: default: false description: Enable streaming response example: false type: boolean stream_options: $ref: '#/components/schemas/ChatStreamOptions' temperature: description: Sampling temperature (0-2) example: 0.7 format: double type: - number - 'null' tool_choice: $ref: '#/components/schemas/ChatToolChoice' tools: description: Available tools for function calling example: - function: description: Get weather name: get_weather type: function items: $ref: '#/components/schemas/ChatFunctionTool' type: array top_a: description: >- Consider only tokens with "sufficiently high" probabilities based on the probability of the most likely token. Not all providers support this parameter. example: 0 format: double type: - number - 'null' top_k: description: >- Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter. example: 40 type: - integer - 'null' top_logprobs: description: Number of top log probabilities to return (0-20) example: 5 type: - integer - 'null' top_p: description: Nucleus sampling parameter (0-1) example: 1 format: double type: - number - 'null' trace: $ref: '#/components/schemas/TraceConfig' user: description: >- Per-end-user identifier for abuse isolation. Use a stable ID, hash, or pseudonym. When a provider requires a user identity, OpenRouter folds it into the hashed identity sent upstream and never forwards it raw. If omitted, requests use an account-level identity, so provider policy blocks can affect the whole account. example: user-123 type: string required: - messages type: object