API reference

API endpoints, authentication, request examples, and formats.

Supported Endpoints

/chat/completions

Common

For conversational AI interactions, supporting multi-turn dialogue and system prompts.

Full Address:https://YOUR_BASE_URL/chat/completions
Features:
StreamingMulti-turnSystem PromptFunction Call

/embeddings

Generate text embedding vectors for semantic search, similarity calculation and more.

Full Address:https://YOUR_BASE_URL/embeddings
Supported Models:
text-embedding-3-smalltext-embedding-3-largetext-embedding-ada-002

API Usage

GreatRouter is compatible with OpenAI SDK. You can quickly integrate using familiar tools and libraries. Select your programming language to view sample code.

💡 Replace YOUR_BASE_URL with your actual endpoint. See the "Route Selection" section for overseas vs domestic options.

Install SDK

pip install openai

Basic Example

from openai import OpenAI

client = OpenAI(
    api_key="sk-gr-xxxx",
    base_url="https://YOUR_BASE_URL"
)

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)

Streaming Example

stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}],
    stream=True
)
for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

Error Code Reference

When an API call fails, GreatRouter returns standard HTTP status codes and JSON error messages. Below are common error codes and how to handle them.

HTTP Status Codes

Status CodeMeaningSolution
400 Bad RequestInvalid request parameters, such as missing required fields or incorrect formatCheck request body format, required parameters, and parameter types
401 UnauthorizedInvalid or missing API KeyVerify your API Key is correct and properly passed in the Authorization header
402 Payment RequiredInsufficient account balanceTop up your account balance and try again
403 ForbiddenAccess denied — API Key disabled or account suspendedCheck API Key status or contact support
429 Too Many RequestsToo many requests — rate limit exceededReduce request frequency, use exponential backoff retry strategy
500 Server ErrorInternal server error. Contact support if it persistsRetry after a short delay. Contact support if it persists

Error Response Format

{
  "error": {
    "message": "Incorrect API key provided: sk-gr-xxxx.",
    "type": "invalid_request_error",
    "param": null,
    "code": "invalid_api_key"
  }
}
FieldDescription
messageHuman-readable error description, useful for debugging
typeError category, e.g. invalid_request_error, authentication_error
codeProgrammatic error code, e.g. invalid_api_key, insufficient_quota

Retry Best Practices

  1. Use exponential backoff for 429 errors — start at 1s and double the wait time
  2. Retry up to 3 times for 500 errors, waiting 1-2 seconds between attempts
  3. Don't retry 401/402/403 errors — check your configuration or balance instead
  4. Set reasonable timeouts (60-120 seconds recommended) to avoid hanging requests
import time
from openai import OpenAI, APIError, RateLimitError

client = OpenAI(
    api_key="sk-gr-xxxx",
    base_url="https://YOUR_BASE_URL"
)

def call_with_retry(messages, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="gpt-4o",
                messages=messages
            )
        except RateLimitError:
            wait = 2 ** attempt
            print(f"Rate limited, retrying in {wait}s...")
            time.sleep(wait)
        except APIError as e:
            if e.status_code >= 500:
                time.sleep(1)
                continue
            raise
    raise Exception("Max retries exceeded")