# OpenAI

## 1. Overview

The industry's leading large language model.

**Model List:**

* `gpt-4o`
* `gpt-4o-mini`
* `gpt-4.1`
* `gpt-4.1-mini`
* `gpt-4.1-nano`
* `gpt-5`
* `gpt-5-chat-latest`
* `gpt-5-mini`
* `gpt-5-nano`
* `gpt-5-codex`
* `gpt-5.1`
* `gpt-5.1-chat-latest`
* `gpt-5.1-codex`
* `gpt-5.1-codex-mini`
* `gpt-5.1-codex-max`
* `gpt-5.2`
* `gpt-5.2-chat-latest`
* `gpt-5.2-codex`
* `gpt-5.3-codex`
* `gpt-5.4`
* `gpt-5.4-pro`
* `gpt-5.5`
* `chat-latest` (Gpt-5.5 Instant)

## 2. Request Description

* **Request Method**: `POST`
* **Request URL**:

  > `https://gateway.theturbo.ai/v1/chat/completions`

{% hint style="info" %}
To ensure sufficient concurrency resources, the platform uses multi-account load balancing on the backend. To improve cache hit rates, you can include the HTTP request header `X-Conversation-Id` with a random string in multi-turn conversation mode. The platform will prioritize routing requests to the same backend account. [Reference Documentation](/api/compute/aig/gateway-features/cache-optimization.md)
{% endhint %}

***

## 3. 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 use `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 model ID to use. See the available versions listed in [Overview](#id-1.-overview), e.g. `gpt-4o`.                                                | `gpt-4o`                                |
| **messages**       | array   | Yes      | A list of chat messages. Each object in the array contains `role` and `content`.                                                                     | `[{"role": "user","content": "Hello"}]` |
| role               | string  | No       | The message role. Possible values: `system`, `user`, `assistant`.                                                                                    | `user`                                  |
| content            | string  | No       | The specific content of the message.                                                                                                                 | `Hello, please tell me a joke.`         |
| temperature        | number  | No       | Sampling temperature, ranging from `0` to `2`. Higher values produce more random output; lower values produce more focused and deterministic output. | `0.7`                                   |
| top\_p             | number  | No       | An alternative way to adjust the sampling distribution, ranging from `0` to `1`. Usually set as an alternative to `temperature`.                     | `0.9`                                   |
| n                  | number  | No       | The number of replies to generate for each input message.                                                                                            | `1`                                     |
| stream             | boolean | No       | Whether to enable streaming output. When set to `true`, returns streaming data similar to ChatGPT.                                                   | `false`                                 |
| stop               | string  | No       | Up to 4 strings can be specified. Generation stops when any of these strings appear in the output.                                                   | `"\n"`                                  |
| max\_tokens        | number  | No       | The maximum number of tokens to generate in a single reply, limited by the model's context length.                                                   | `1024`                                  |
| presence\_penalty  | number  | No       | -2.0 \~ 2.0. Positive values encourage the model to generate more new topics; negative values reduce the likelihood of new topics.                   | `0`                                     |
| frequency\_penalty | number  | No       | -2.0 \~ 2.0. Positive values reduce the frequency of repeated phrases; negative values increase the likelihood of repetition.                        | `0`                                     |

***

## 4. Request Examples

### 4.1 Chat Conversation

{% tabs %}
{% tab title="HTTP" %}

```http
POST /v1/chat/completions
Content-Type: application/json
Accept: application/json
Authorization: Bearer $YOUR_API_KEY

{
	"model": "gpt-4o",
	"messages": [
		{
			"role": "user",
			"content": "Hello, can you explain quantum mechanics to me?"
		}
	]
}
```

{% endtab %}

{% tab title="Shell" %}

```sh
curl https://gateway.theturbo.ai/v1/chat/completions \
	-H "Content-Type: application/json" \
	-H "Accept: application/json" \
	-H "Authorization: Bearer $YOUR_API_KEY" \
	-d "{
	\"model\": \"gpt-4o\",
	\"messages\": [{
		\"role\": \"user\",
		\"content\": \"Hello, can you explain quantum mechanics to me?\"
	}]
}"
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"context"
	"fmt"

	"github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
)

func main() {
	apiKey := "sk-123456789012345678901234567890123456789012345678"

	client := openai.NewClient(
		option.WithAPIKey(apiKey),
		option.WithBaseURL("https://gateway.theturbo.ai/v1"),
	)

	resp, err := client.Chat.Completions.New(
		context.Background(),
		openai.ChatCompletionNewParams{
			Model: "gpt-4o",
			Messages: []openai.ChatCompletionMessageParamUnion{
				openai.UserMessage("Hello, can you explain quantum mechanics to me?"),
			},
		},
	)

	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println(resp.Choices[0].Message.Content)
}

```

{% endtab %}

{% tab title="Python" %}

```python
#!/usr/bin/env python3

from openai import OpenAI

def main():
    api_key = "sk-123456789012345678901234567890123456789012345678"

    client = OpenAI(
        api_key=api_key,
        base_url="https://gateway.theturbo.ai/v1"
    )

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "user", "content": "Hello, can you explain quantum mechanics to me?"}
        ]
    )

    print(response.choices[0].message.content)

if __name__ == "__main__":
    main()

```

{% endtab %}
{% endtabs %}

### 4.2 Image Understanding

{% tabs %}
{% tab title="HTTP" %}

```http
POST /v1/chat/completions
Content-Type: application/json
Accept: application/json
Authorization: Bearer $YOUR_API_KEY

{
	"model": "gpt-4o",
	"messages": [
		{
			"role": "user",
			"content": [
				{
					"type": "text",
					"text": "What's in this image?"
				},
				{
					"type": "image_url",
					"image_url": {
						"url": "data:image/jpeg;base64,${base64_image}"
					}
				}
			]
		}
	]
}
```

{% endtab %}

{% tab title="Shell" %}

```sh
base64_image=$(base64 -i "Path/to/agi/image.jpeg");
curl https://gateway.theturbo.ai/v1/chat/completions \
	-H "Content-Type: application/json" \
	-H "Accept: application/json" \
	-H "Authorization: Bearer $YOUR_API_KEY" \
	-d "{
	\"model\": \"gpt-4o\",
	\"messages\": [{
		\"role\": \"user\",
		\"content\": [{
				\"type\": \"text\",
				\"text\": \"What's in this image?\"
			},
			{
				\"type\": \"image_url\",
				\"image_url\": {
					\"url\": \"data:image/jpeg;base64,${base64_image}\"
				}
			}
		]
	}]
}"
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"context"
	"encoding/base64"
	"fmt"
	"os"

	"github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
)

func main() {
	apiKey := "sk-123456789012345678901234567890123456789012345678"

	client := openai.NewClient(
		option.WithAPIKey(apiKey),
		option.WithBaseURL("https://gateway.theturbo.ai/v1"),
	)

	imagePath := "Path/to/agi/image.jpeg"
	imageBytes, err := os.ReadFile(imagePath)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	base64Image := base64.StdEncoding.EncodeToString(imageBytes)
	imageURL := "data:image/jpeg;base64," + base64Image

	resp, err := client.Chat.Completions.New(
		context.Background(),
		openai.ChatCompletionNewParams{
			Model: "gpt-4o",
			Messages: []openai.ChatCompletionMessageParamUnion{
				openai.UserMessage([]openai.ChatCompletionContentPartUnionParam{
					openai.TextContentPart("What's in this image?"),
					openai.ImageContentPart(openai.ChatCompletionContentPartImageImageURLParam{
						URL: imageURL,
					}),
				}),
			},
		},
	)

	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println(resp.Choices[0].Message.Content)
}

```

{% endtab %}

{% tab title="Python" %}

```python
#!/usr/bin/env python3

import base64
from openai import OpenAI

def main():
    api_key = "sk-123456789012345678901234567890123456789012345678"

    client = OpenAI(
        api_key=api_key,
        base_url="https://gateway.theturbo.ai/v1"
    )

    image_path = "Path/to/agi/image.jpeg"
    with open(image_path, "rb") as f:
        image_bytes = f.read()

    base64_image = base64.b64encode(image_bytes).decode("utf-8")
    image_url = f"data:image/jpeg;base64,{base64_image}"

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{
            "role": "user",
            "content": [
                {"type": "text", "text": "What's in this image?"},
                {"type": "image_url", "image_url": {"url": image_url}}
            ]
        }]
    )

    print(response.choices[0].message.content)

if __name__ == "__main__":
    main()

```

{% endtab %}
{% endtabs %}

### 4.3 Function Calling

{% tabs %}
{% tab title="HTTP" %}

```http
POST /v1/chat/completions
Content-Type: application/json
Accept: application/json
Authorization: Bearer $YOUR_API_KEY

{
	"model": "gpt-4o",
	"messages": [{
		"role": "user",
		"content": "What's the weather like in Boston today?"
	}],
	"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"
}
```

{% endtab %}

{% tab title="Shell" %}

```sh
curl https://gateway.theturbo.ai/v1/chat/completions \
	-H "Content-Type: application/json" \
	-H "Accept: application/json" \
	-H "Authorization: Bearer $YOUR_API_KEY" \
	-d "{
	\"model\": \"gpt-4o\",
	\"messages\": [{
		\"role\": \"user\",
		\"content\": \"What's the weather like in Boston today?\"
	}],
	\"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\"
}"
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
	"github.com/openai/openai-go/packages/param"
	"github.com/openai/openai-go/shared"
)

func main() {
	apiKey := "sk-123456789012345678901234567890123456789012345678"

	client := openai.NewClient(
		option.WithAPIKey(apiKey),
		option.WithBaseURL("https://gateway.theturbo.ai/v1"),
	)

	tools := []openai.ChatCompletionToolParam{
		{
			Type: "function",
			Function: shared.FunctionDefinitionParam{
				Name:        "get_current_weather",
				Description: param.NewOpt("Get the current weather in a given location"),
				Parameters: shared.FunctionParameters{
					"type": "object",
					"properties": map[string]interface{}{
						"location": map[string]interface{}{
							"type":        "string",
							"description": "The city and state, e.g. San Francisco, CA",
						},
						"unit": map[string]interface{}{
							"type": "string",
							"enum": []string{"celsius", "fahrenheit"},
						},
					},
					"required": []string{"location"},
				},
			},
		},
	}

	resp, err := client.Chat.Completions.New(
		context.Background(),
		openai.ChatCompletionNewParams{
			Model: "gpt-4o",
			Messages: []openai.ChatCompletionMessageParamUnion{
				openai.UserMessage("What's the weather like in Boston today?"),
			},
			Tools: tools,
			ToolChoice: openai.ChatCompletionToolChoiceOptionUnionParam{
				OfAuto: param.NewOpt("auto"),
			},
		},
	)

	if err != nil {
		fmt.Println("error:", err)
		return
	}

	msg := resp.Choices[0].Message

	if msg.ToolCalls != nil && len(msg.ToolCalls) > 0 {
		for _, call := range msg.ToolCalls {
			fmt.Println("🔧 Function called:", call.Function.Name)
			fmt.Println("📥 Arguments JSON:", call.Function.Arguments)

			// Parse the arguments if needed
			var args map[string]any
			_ = json.Unmarshal([]byte(call.Function.Arguments), &args)
			fmt.Println("📦 Parsed args:", args)
		}
	} else {
		fmt.Println("💬 Assistant reply:", msg.Content)
	}
}

```

{% endtab %}

{% tab title="Python" %}

```python
#!/usr/bin/env python3

import json
from openai import OpenAI

def main():
    api_key = "sk-123456789012345678901234567890123456789012345678"

    client = OpenAI(
        api_key=api_key,
        base_url="https://gateway.theturbo.ai/v1"
    )

    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"]
            }
        }
    }]

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "user", "content": "What's the weather like in Boston today?"}
        ],
        tools=tools,
        tool_choice="auto"
    )

    msg = response.choices[0].message

    if msg.tool_calls:
        for call in msg.tool_calls:
            print(f"🔧 Function called: {call.function.name}")
            print(f"📥 Arguments JSON: {call.function.arguments}")

            args = json.loads(call.function.arguments)
            print(f"📦 Parsed args: {args}")
    else:
        print(f"💬 Assistant reply: {msg.content}")

if __name__ == "__main__":
    main()

```

{% endtab %}
{% endtabs %}

## 5. Response Example

```json
{
	"id": "chatcmpl-1234567890",
	"object": "chat.completion",
	"created": 1699999999,
	"model": "gpt-4o",
	"choices": [
		{
			"message": {
				"role": "assistant",
				"content": "Quantum mechanics is a branch of physics that studies the microscopic world..."
			},
			"finish_reason": "stop"
		}
	],
	"usage": {
		"prompt_tokens": 10,
		"completion_tokens": 30,
		"total_tokens": 40
	}
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.console.zenlayer.com/api/compute/aig/chat-completion/openai-chat-completion.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
