Gemini
Platform Features: OpenAI Compatibility
This platform adopts the OpenAI compatible format, allowing you to easily call Google's Gemini models without having to learn new API documentation.
Core Advantage: One Codebase, Multiple Models
Once you have the OpenAI format running, you only need to change the model name (model) to switch to Claude, Gemini, or other large models without rewriting code! This design allows you to easily compare results across different models or switch flexibly based on cost and performance needs.
Supported Google Models
gemini-3.1-pro-preview(Newest)gemini-3.1-flash-lite-previewgemini-3-flash-previewgemini-3-pro-preview(Deprecated, migrated to gemini-3.1-pro-preview)gemini-2.5-flash(Planned for deprecation in Oct 2026)gemini-2.5-pro(Planned for deprecation in Oct 2026)gemini-2.5-flash-lite
Basic Information & Authentication
API Endpoint
https://api.exchangetoken.ai/v1Chat Request Path
POST /v1/chat/completionsAuthentication
All API requests must include authentication information in the Header:
Authorization: Bearer YOUR_API_KEY3. Request Parameters
3.1 Header Parameters
| Parameter Name | Type | Required | Description | Example |
|---|---|---|---|---|
Content-Type | string | Yes | Sets the request header type, must be application/json. | application/json |
Accept | string | Yes | Sets the response type, recommended to be application/json. | application/json |
Authorization | string | Yes | API Key required for authentication, format: Bearer $YOUR_API_KEY. | Bearer $YOUR_API_KEY |
3.2 Body Parameters (application/json)
| Parameter Name | Type | Required | Description | Example |
|---|---|---|---|---|
model | string | Yes | The ID of the model to use. See the available versions listed in the Overview, e.g., gemini-2.5-flash. | gemini-2.5-flash |
messages | array | Yes | A list of chat messages, compatible with the OpenAI format. Each object in the array contains a role and content. | [{"role": "user", "content": "Hello"}] |
role | string | No | The role of the message author. Can be system, user, or assistant. | user |
content | string/array | No | The specific content of the message. | Hello, please tell me a joke. |
temperature | number | No | Sampling temperature, between 0-2. Higher values make the output more random; lower values make it more focused and deterministic. | 0.7 |
top_p | number | No | An alternative way to control sampling, between 0-1. Usually, you set either this or temperature. | 0.9 |
n | number | No | How many completions to generate for each input message. | 1 |
stream | boolean | No | Whether to enable streaming output. When set to true, returns data in a ChatGPT-like stream. | false |
stop | string | No | Up to 4 strings. Once any of these strings appears in the generated content, stop generating more tokens. | "\n" |
max_tokens | number | No | The maximum number of tokens to generate in a single response, limited by the model's context length. | 1024 |
presence_penalty | number | No | -2.0 to 2.0. Positive values encourage the model to talk about new topics, negative values reduce this probability. | 0 |
frequency_penalty | number | No | -2.0 to 2.0. Positive values decrease the model's likelihood to repeat phrases, negative values increase this probability. | 0 |
reasoning_effort | string | No | Controls the amount of "computational effort" the model puts into reasoning tasks. Currently only supported by gemini-2.5-flash-preview-04-17. Supports low medium high none. Defaults to low. | low |
web_search_options | object | No | Used to control whether to enable Google search grounding. | {} |
Complete Code Examples
bash
curl -X POST "https://api.exchangetoken.ai/v1/chat/completions" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-2.5-flash",
"messages": [
{"role": "system", "content": "You are a helpful AI assistant."},
{"role": "user", "content": "Hello! Please introduce yourself."}
],
"temperature": 0.7,
"max_tokens": 1000
}'python
from openai import OpenAI
# Initialize client
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.exchangetoken.ai/v1"
)
# Send chat request
response = client.chat.completions.create(
model="gemini-2.5-flash",
messages=[
{"role": "system", "content": "You are a helpful AI assistant."},
{"role": "user", "content": "Hello! Please introduce yourself."}
],
temperature=0.7,
max_tokens=1000
)
print(response.choices[0].message.content)python
import requests
import json
url = "https://api.exchangetoken.ai/v1/chat/completions"
headers = {
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
}
data = {
"model": "gemini-2.5-flash",
"messages": [
{"role": "system", "content": "You are a helpful AI assistant."},
{"role": "user", "content": "Hello! Please introduce yourself."}
],
"temperature": 0.7,
"max_tokens": 1000
}
response = requests.post(url, headers=headers, json=data)
result = response.json()
if response.status_code == 200:
print(result["choices"][0]["message"]["content"])
else:
print(f"Error: {result}")javascript
const OpenAI = require('openai');
const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://api.exchangetoken.ai/v1'
});
async function chatCompletion() {
try {
const response = await client.chat.completions.create({
model: 'gemini-2.5-flash',
messages: [
{"role": "system", "content": "You are a helpful AI assistant."},
{"role": "user", "content": "Hello! Please introduce yourself."}
],
temperature: 0.7,
max_tokens: 1000
});
console.log(response.choices[0].message.content);
} catch (error) {
console.error('API call error:', error);
}
}
chatCompletion();java
import okhttp3.*;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.*;
public class LaoZhangExample {
private static final String API_KEY = "YOUR_API_KEY";
private static final String BASE_URL = "https://api.exchangetoken.ai/v1";
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient();
Gson gson = new Gson();
// Build request body
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("model", "gemini-2.5-flash");
requestBody.put("temperature", 0.7);
requestBody.put("max_tokens", 1000);
List<Map<String, String>> messages = Arrays.asList(
Map.of("role", "system", "content", "You are a helpful AI assistant."),
Map.of("role", "user", "content", "Hello! Please introduce yourself.")
);
requestBody.put("messages", messages);
RequestBody body = RequestBody.create(
gson.toJson(requestBody),
MediaType.parse("application/json")
);
Request request = new Request.Builder()
.url(BASE_URL + "/chat/completions")
.addHeader("Authorization", "Bearer " + API_KEY)
.addHeader("Content-Type", "application/json")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}csharp
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
class Program
{
private static readonly string API_KEY = "YOUR_API_KEY";
private static readonly string BASE_URL = "https://api.exchangetoken.ai/v1";
static async Task Main(string[] args)
{
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {API_KEY}");
var requestBody = new
{
model = "gemini-2.5-flash",
messages = new[]
{
new { role = "system", content = "You are a helpful AI assistant." },
new { role = "user", content = "Hello! Please introduce yourself." }
},
temperature = 0.7,
max_tokens = 1000
};
var json = JsonConvert.SerializeObject(requestBody);
var content = new StringContent(json, Encoding.UTF8, "application/json");
try
{
var response = await client.PostAsync($"{BASE_URL}/chat/completions", content);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type ChatRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
Temperature float64 `json:"temperature"`
MaxTokens int `json:"max_tokens"`
}
func main() {
apiKey := "YOUR_API_KEY"
baseURL := "https://api.exchangetoken.ai/v1"
reqData := ChatRequest{
Model: "gemini-2.5-flash",
Messages: []Message{
{Role: "system", Content: "You are a helpful AI assistant."},
{Role: "user", Content: "Hello! Please introduce yourself."},
},
Temperature: 0.7,
MaxTokens: 1000,
}
jsonData, _ := json.Marshal(reqData)
req, _ := http.NewRequest("POST", baseURL+"/chat/completions", bytes.NewBuffer(jsonData))
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Request error: %v\n", err)
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}Streaming Response
Enable Streaming Output
Set stream: true in the request:
json
{
"model": "gemini-2.5-flash",
"messages": [{"role": "user", "content": "Hello"}],
"stream": true
}Streaming Response Format
Responses will be returned in Server-Sent Events (SSE) format:
data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1699000000,"model":"gemini-2.5-flash","choices":[{"delta":{"content":"Hello"},"index":0}]}
data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1699000000,"model":"gemini-2.5-flash","choices":[{"delta":{"content":" there"},"index":0}]}
data: [DONE]Error Handling
Error Response Format
json
{
"error": {
"message": "Invalid API key provided",
"type": "invalid_request_error",
"param": null,
"code": "invalid_api_key"
}
}Common Error Codes
| Error Code | HTTP Status Code | Description |
|---|---|---|
invalid_api_key | 401 | Invalid API key |
insufficient_quota | 429 | Insufficient quota |
model_not_found | 404 | Model not found |
invalid_request_error | 400 | Invalid request parameters |
server_error | 500 | Internal server error |
rate_limit_exceeded | 429 | Request frequency too high (Rate limit exceeded) |
