API ReferenceText APIsGeneral Chat

Chat Completions API

OpenAI-compatible chat completions API: call GPT, Claude, Gemini and more via /v1/chat/completions, with request samples, parameters and response fields.

  • A unified chat API that supports all text generation models
  • Select different AI models via the model parameter
  • Compatible with the OpenAI Chat Completions API format

curl --request POST \
 --url https://anyrouter.win/v1/chat/completions \
 --header 'Authorization: Bearer <token>' \
 --header 'Content-Type: application/json' \
 --data '{
"model": "gpt-4o", # Replace with any supported model ID
"messages": [
{
"role": "system",
"content": "You are a professional AI assistant."
},
{
"role": "user",
"content": "Give an overview of the history of artificial intelligence."
}
]
}'
import requests

url = "https://anyrouter.win/v1/chat/completions"

payload = {
    "model": "gpt-4o",  # Replace with any supported model ID
    "messages": [
        {
            "role": "system",
            "content": "You are a professional AI assistant."
        },
        {
            "role": "user",
            "content": "Give an overview of the history of artificial intelligence."
        }
    ]
}

headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
const url = "https://anyrouter.win/v1/chat/completions";

const payload = {
  model: "gpt-4o", // Replace with any supported model ID
  messages: [
    {
      role: "system",
      content: "You are a professional AI assistant.",
    },
    {
      role: "user",
      content: "Give an overview of the history of artificial intelligence.",
    },
  ],
};

const headers = {
  Authorization: "Bearer <token>",
  "Content-Type": "application/json",
};

fetch(url, {
  method: "POST",
  headers: headers,
  body: JSON.stringify(payload),
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    url := "https://anyrouter.win/v1/chat/completions"

    payload := map[string]interface{}{
        "model": "gpt-4o",  // Replace with any supported model ID
        "messages": []map[string]string{
            {
                "role":    "system",
                "content": "You are a professional AI assistant.",
            },
            {
                "role":    "user",
                "content": "Give an overview of the history of artificial intelligence.",
            },
        },
    }

    jsonData, _ := json.Marshal(payload)

    req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    req.Header.Set("Authorization", "Bearer <token>")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

public class Main {
    public static void main(String[] args) throws Exception {
        String url = "https://anyrouter.win/v1/chat/completions";

        // Replace with any supported model ID
        String payload = """
        {
          "model": "gpt-4o",
          "messages": [
            {
              "role": "system",
              "content": "You are a professional AI assistant."
            },
            {
              "role": "user",
              "content": "Give an overview of the history of artificial intelligence."
            }
          ]
        }
        """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Authorization", "Bearer <token>")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(payload))
            .build();

        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
<?php

$url = "https://anyrouter.win/v1/chat/completions";

// Replace with any supported model ID
$payload = [
    "model" => "gpt-4o",
    "messages" => [
        [
            "role" => "system",
            "content" => "You are a professional AI assistant."
        ],
        [
            "role" => "user",
            "content" => "Give an overview of the history of artificial intelligence."
        ]
    ]
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer <token>",
    "Content-Type: application/json"
]);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>
require 'net/http'
require 'json'
require 'uri'

url = URI("https://anyrouter.win/v1/chat/completions")

# Replace with any supported model ID
payload = {
  model: "gpt-4o",
  messages: [
    {
      role: "system",
      content: "You are a professional AI assistant."
    },
    {
      role: "user",
      content: "Give an overview of the history of artificial intelligence."
    }
  ]
}

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = "Bearer <token>"
request["Content-Type"] = "application/json"
request.body = payload.to_json

response = http.request(request)
puts response.body
import Foundation

let url = URL(string: "https://anyrouter.win/v1/chat/completions")!

let payload: [String: Any] = [
    "model": "gpt-4o",  // Replace with any supported model ID
    "messages": [
        [
            "role": "system",
            "content": "You are a professional AI assistant."
        ],
        [
            "role": "user",
            "content": "Give an overview of the history of artificial intelligence."
        ]
    ]
]

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer <token>", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: payload)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }

    if let data = data, let responseString = String(data: data, encoding: .utf8) {
        print(responseString)
    }
}

task.resume()
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var url = "https://anyrouter.win/v1/chat/completions";

        // Replace with any supported model ID
        var payload = @"{
            ""model"": ""gpt-4o"",
            ""messages"": [
                {
                    ""role"": ""system"",
                    ""content"": ""You are a professional AI assistant.""
                },
                {
                    ""role"": ""user"",
                    ""content"": ""Give an overview of the history of artificial intelligence.""
                }
            ]
        }";

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");

        var content = new StringContent(payload, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(url, content);
        var result = await response.Content.ReadAsStringAsync();

        Console.WriteLine(result);
    }
}
#include <stdio.h>
#include <curl/curl.h>

int main(void) {
    CURL *curl;
    CURLcode res;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();


    if(curl) {
        const char *url = "https://anyrouter.win/v1/chat/completions";
        // Replace with any supported model ID
        const char *payload = "{"
            "\"model\":\"gpt-4o\","
            "\"messages\":[{\"role\":\"system\",\"content\":\"You are a professional AI assistant.\"},{\"role\":\"user\",\"content\":\"Give an overview of the history of artificial intelligence.\"}]"
        "}";

        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Authorization: Bearer <token>");
        headers = curl_slist_append(headers, "Content-Type: application/json");

        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                    curl_easy_strerror(res));
        }

        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }

    curl_global_cleanup();
    return 0;
}
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSURL *url = [NSURL URLWithString:@"https://anyrouter.win/v1/chat/completions"];

        // Replace with any supported model ID
        NSDictionary *payload = @{
            @"model": @"gpt-4o",
            @"messages": @[
                @{
                    @"role": @"system",
                    @"content": @"You are a professional AI assistant."
                },
                @{
                    @"role": @"user",
                    @"content": @"Give an overview of the history of artificial intelligence."
                }
            ]
        };

        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:payload
                                                          options:0
                                                            error:&error];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"Bearer <token>" forHTTPHeaderField:@"Authorization"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:jsonData];

        NSURLSessionDataTask *task = [[NSURLSession sharedSession]
            dataTaskWithRequest:request
            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                if (error) {
                    NSLog(@"Error: %@", error);
                    return;
                }
                NSString *result = [[NSString alloc] initWithData:data
                                                        encoding:NSUTF8StringEncoding];
                NSLog(@"%@", result);
            }];

        [task resume];
        [[NSRunLoop mainRunLoop] run];
    }
    return 0;
}
(* Requires cohttp and yojson libraries *)
open Lwt
open Cohttp
open Cohttp_lwt_unix

let url = "https://anyrouter.win/v1/chat/completions"

(* Replace with any supported model ID *)
let payload = {|{
  "model": "gpt-4o",
  "messages": [
    {
      "role": "system",
      "content": "You are a professional AI assistant."
    },
    {
      "role": "user",
      "content": "Give an overview of the history of artificial intelligence."
    }
  ]
}|}

let () =
  let headers = Header.init ()
    |> fun h -> Header.add h "Authorization" "Bearer <token>"
    |> fun h -> Header.add h "Content-Type" "application/json"
  in
  let body = Cohttp_lwt.Body.of_string payload in

  let response = Client.post ~headers ~body (Uri.of_string url) >>= fun (resp, body) ->
    body |> Cohttp_lwt.Body.to_string >|= fun body_str ->
    print_endline body_str
  in
  Lwt_main.run response
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  final url = Uri.parse('https://anyrouter.win/v1/chat/completions');

  // Replace with any supported model ID
  final payload = {
    'model': 'gpt-4o',
    'messages': [
      {
        'role': 'system',
        'content': 'You are a professional AI assistant.'
      },
      {
        'role': 'user',
        'content': 'Give an overview of the history of artificial intelligence.'
      }
    ]
  };

  final response = await http.post(
    url,
    headers: {
      'Authorization': 'Bearer <token>',
      'Content-Type': 'application/json',
    },
    body: jsonEncode(payload),
  );

  print(response.body);
}
library(httr)
library(jsonlite)

url <- "https://anyrouter.win/v1/chat/completions"

# Replace with any supported model ID
payload <- list(
  model = "gpt-4o",
  messages = list(
    list(
      role = "system",
      content = "You are a professional AI assistant."
    ),
    list(
      role = "user",
      content = "Give an overview of the history of artificial intelligence."
    )
  )
)

response <- POST(
  url,
  add_headers(
    Authorization = "Bearer <token>",
    `Content-Type` = "application/json"
  ),
  body = toJSON(payload, auto_unbox = TRUE),
  encode = "raw"
)

cat(content(response, "text"))
{
  "code": 200,
  "data": {
    "id": "chatcmpl-9876543210",
    "object": "chat.completion",
    "created": 1677652288,
    "model": "gpt-4o",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "The history of artificial intelligence (AI) dates back to the 1950s...\n\n1. **Early years (1950s-1960s)**: The Turing test marked the beginning of AI research...\n\n2. **Expert systems era (1970s-1980s)**: Rule-based systems began to be applied in fields such as medical diagnosis and financial analysis...\n\n3. **Rise of machine learning (1990s-2000s)**: Statistical learning methods gradually became mainstream...\n\n4. **Deep learning revolution (2010s-present)**: Breakthroughs in neural network technology brought explosive growth in AI..."
        },
        "finish_reason": "stop"
      }
    ],
    "usage": {
      "prompt_tokens": 28,
      "completion_tokens": 320,
      "total_tokens": 348
    }
  }
}
{
  "error": {
    "code": 400,
    "message": "Invalid request parameters",
    "type": "invalid_request_error"
  }
}
{
  "error": {
    "code": 401,
    "message": "Authentication failed, please check your API key",
    "type": "authentication_error"
  }
}
{
  "error": {
    "code": 402,
    "message": "Insufficient account balance, please top up and try again",
    "type": "payment_required"
  }
}
{
  "error": {
    "code": 403,
    "message": "Access forbidden, you do not have permission to access this resource",
    "type": "permission_error"
  }
}
{
  "error": {
    "code": 429,
    "message": "Too many requests, please try again later",
    "type": "rate_limit_error"
  }
}
{
  "error": {
    "code": 500,
    "message": "Internal server error, please try again later",
    "type": "server_error"
  }
}
{
  "error": {
    "code": 502,
    "message": "Gateway error, the server is temporarily unavailable",
    "type": "bad_gateway"
  }
}

Authorizations

stringrequired

All endpoints require Bearer token authentication

Get an API key:

Visit the API key management page to get your API key

Add it to the request headers:

Authorization: Bearer YOUR_API_KEY

Body

stringrequired

Model name

Supported models include:

OpenAI gpt-4.1 gpt-4o gpt-5 gpt-5-high gpt-5-codex gpt-5-low gpt-5-medium gpt-5.1 gpt-5.2 gpt-5.3 gpt-5.4 gpt-5.5

Anthropic claude-opus-4-5 claude-opus-4-6 claude-opus-4-7 claude-sonnet-4-5 claude-sonnet-4-6

Google gemini-2.5-flash gemini-2.0-flash gemini-2.0-flash-lite gemini-2.5-flash-image gemini-2.5-pro gemini-3-pro-preview gemini-3-flash gemini-3-flash-preview gemini-3.1-pro-preview gemini-3.1-flash-lite-preview

DeepSeek deepseek-r1 deepseek-v3 deepseek-v3-1-250821 deepseek-v3.2 deepseek-v4-flash deepseek-v4-pro

MiniMax MiniMax-M2.5

Zhipu glm-5 glm-5.1

Alibaba qwen-flash qwen-max qwen-plus qwen3-max qwen3-coder-flash

  • More models are being added continuously...
arrayrequired

Conversation message list

An array of messages; each message contains a role and a content field.

Field details
stringrequired

Role type

Allowed values: user (user message), assistant (AI reply, used for multi-turn conversations), system (system prompt, sets AI behavior)

stringrequired

Message content

The message or question you want to send

Example:

[{ "role": "user", "content": "Hello, please introduce yourself" }]

Advanced usage:

Add a system prompt (to have the AI play a specific role):

[
  { "role": "system", "content": "You are a professional Python tutor" },
  { "role": "user", "content": "How do I learn programming?" }
]

Multi-turn conversation (with context):

[
  { "role": "user", "content": "Hello" },
  { "role": "assistant", "content": "Hello! How can I help you?" },
  { "role": "user", "content": "Tell me about artificial intelligence" }
]

Role descriptions:

  • user: user message (use this in most cases)
  • system: system prompt that sets the AI's behavior and role
  • assistant: previous AI replies, used to provide context in multi-turn conversations
number

Controls output randomness, range 0-2

  • Lower values (e.g. 0.2) make output more deterministic
  • Higher values (e.g. 1.8) make output more random

Default: 1.0

integer

Maximum number of tokens to generate

Different models have different maximum limits; see the specific model documentation

boolean

Whether to use streaming output

  • true: streamed response (SSE format)
  • false: return the full response at once

Default: true

number

Nucleus sampling parameter, range 0-1

Controls the diversity of the generated text; use either this or temperature, not both

Default: 1.0

number

Frequency penalty, range -2.0 to 2.0

Positive values reduce the likelihood of repeating the same words

Default: 0

number

Presence penalty, range -2.0 to 2.0

Positive values increase the likelihood of talking about new topics

Default: 0

string or array

Stop sequences

Up to 4 sequences; generation stops when any of them is encountered

integer

Number of replies to generate

Default: 1

⚠️ Note: Must be a plain number (e.g. 1) without quotes, otherwise an error is returned

Response

idstring

Unique identifier for the response

objectstring

Object type, always chat.completion

createdinteger

Creation timestamp

modelstring

The model actually used

choicesarray

List of generated replies

Properties
indexinteger

Choice index

messageobject

Message content

Properties
rolestring

Role type (assistant)

contentstring

Generated text content

finish_reasonstring

Finish reason

Possible values:

  • stop - natural end
  • length - reached the maximum length
  • content_filter - content filtered
  • function_call - function call
usageobject

Token usage statistics

Properties
prompt_tokensinteger

Number of tokens in the input messages

completion_tokensinteger

Number of tokens in the generated content

total_tokensinteger

Total number of tokens

Usage Examples

Basic Conversation

{
  "model": "gpt-4o",
  "messages": [{ "role": "user", "content": "Hello" }]
}

System Prompt

{
  "model": "claude-3-5-sonnet",
  "messages": [
    { "role": "system", "content": "You are a professional Python programming tutor" },
    { "role": "user", "content": "How do I use list comprehensions?" }
  ]
}

Multi-turn Conversation

{
  "model": "gemini-2.0-flash",
  "messages": [
    { "role": "user", "content": "What is machine learning?" },
    { "role": "assistant", "content": "Machine learning is a branch of artificial intelligence..." },
    { "role": "user", "content": "Can you give an example?" }
  ]
}

Streaming Output

{
  "model": "gpt-4o",
  "messages": [{ "role": "user", "content": "Write a poem about spring" }],
  "stream": true
}

On this page