> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.joytokens.ai/llms.txt.

# Chat Completions

POST https://api.joytokens.ai/openai/v1/chat/completions
Content-Type: application/json

Creates a model response for a chat conversation. This endpoint accepts OpenAI-compatible chat payloads and adds JoyToken routing, policy, wallet, and usage metadata around the provider call.

When JoyToken routes a request through orchestration (multi-task planning) mode, the gateway first produces a task `plan`, executes each task with a selected sub-model, and then aggregates a final answer. In this mode: the non-streaming `choices[].message.content` is a JSON-encoded array of per-task outputs (each with `content` and `title`), the top-level `plan` lists the tasks, and `metadata` is an array with one entry per task (including the reserved `__planner__` and `__final__` tasks). When streaming, a leading planning event arrives first (a chunk whose `orchestration.phase` is `planning`, carrying the ordered `plan`) followed by the `__planner__` `metadata` event; then each task's full content arrives as a chunk that carries an `orchestration` field (`task_id`, `task_seq`, `task_status`, `title`), each followed by one standalone `metadata` event (a single object, not an array) before `[DONE]`.


Reference: https://docs.joytokens.ai/open-api/api-reference/compatible-model-ap-is/chat/create-chat-completion

## Authentication

- `Authorization` header (bearer token, required) — Use `Authorization: Bearer $JOY_TOKEN_API_KEY`.

## Request

### Headers

- `X-Request-ID` (string, optional) — Optional request identifier for log, billing, and debugging correlation.

### Body (application/json)

This endpoint expects a ChatCompletionRequest.

- `model` (string, required) — Use `auto` to let the gateway pick the model, or pass a concrete `modelName` from the model catalog to pin that model. Both ways are available to every account. When a model is pinned, `tier` is ignored, orchestration is not used, and there is no fallback to another model.
- `messages` (list of ChatMessage, required) — OpenAI-compatible chat messages.
- `tier` (enum, optional) — JoyToken model tier.
  - Allowed values: `economy`, `standard`, `premium`
- `stream` (boolean, optional, default: false) — Return an OpenAI-compatible SSE stream when true.
- `temperature` (double, optional) — Sampling temperature forwarded to the selected provider when supported.
- `top_p` (double, optional) — Nucleus sampling value forwarded to the selected provider when supported.
- `max_tokens` (integer, optional) — Maximum output tokens. Also participates in JoyToken billing estimation.
- `user` (string, optional) — Optional end-user identifier used as route session context.
- `tools` (list of ChatTool, optional) — OpenAI-compatible tool definitions.

## Response

### 200

Successful chat completion response.

- `id` (string, required)
- `object` (string, required)
- `choices` (list of ChatChoice, required)
- `created` (long, optional)
- `model` (string, optional)
- `usage` (Usage, optional)
- `metadata` (list of JoyTokenMetadata, optional) — Array of JoyToken metadata objects. Always an array: a normal single-model response returns one element, while orchestration (multi-task planning) mode returns one element per task.
- `plan` (list of OrchestrationPlanItem, optional) — Present only in orchestration mode. The ordered task plan produced by the planner. Each item maps to a task whose output appears as one entry in the JSON-encoded choices[].message.content array.

## Errors

### 400 Bad Request Error

Invalid request parameters or malformed input.

- `error` (ErrorResponseError, required)

### 401 Unauthorized Error

Missing, invalid, revoked, or expired API key.

- `error` (ErrorResponseError, required)

### 402 Payment Required Error

Insufficient wallet balance or billing freeze failure.

- `error` (ErrorResponseError, required)

### 403 Forbidden Error

Request blocked by API key policy, IP policy, model blacklist, or route strategy.

- `error` (ErrorResponseError, required)

### 429 Too Many Requests Error

Rate limit exceeded.

- `error` (ErrorResponseError, required)

### 500 Internal Server Error

Internal gateway error.

- `error` (ErrorResponseError, required)

## Types

### ChatMessage

- `role` (enum, required)
  - Allowed values: `system`, `user`, `assistant`, `tool`
- `content` (ChatMessageContent, required)
- `name` (string, optional)
- `tool_call_id` (string, optional)

### ChatTool

- `type` (enum, required)
  - Allowed values: `function`
- `function` (ChatToolFunction, optional)

### ChatChoice

- `index` (integer, optional)
- `message` (ChatMessage, optional)
- `delta` (ChatMessage, optional)
- `finish_reason` (string, optional, nullable)

### Usage

- `prompt_tokens` (integer, optional)
- `completion_tokens` (integer, optional)
- `total_tokens` (integer, optional)

### JoyTokenMetadata

JoyToken routing and billing metadata appended by the gateway when available. In orchestration (multi-task planning) mode this object also carries per-task identifiers, and the response returns one metadata object per task.

- `model` (string, optional) — Final model used. May be `auto` for aggregation tasks, or a concrete sub-model (for example `Gemini-3-Flash-Preview`, `gpt-5.6-luna`) that executed a specific task.
- `tier` (enum, optional) — JoyToken model tier.
  - Allowed values: `economy`, `standard`, `premium`
- `score` (double, optional)
- `billing_id` (string, optional) — Billing account identifier. Present in orchestration metadata events.
- `tag` (list of string, optional) — Role tags describing what a task did. Present in orchestration mode. Common values include orchestration, search, reasoning, writing, and aggregation.
- `task_id` (string, optional) — Task identifier. Reserved values are `__planner__` and `__final__`.
- `task_seq` (integer, optional) — Execution sequence of the task. `0` is the planner.
- `task_status` (enum, optional) — Task lifecycle status.
  - Allowed values: `DONE`
- `title` (string, optional) — Human-readable task title from the plan.
- `billing` (JoyTokenMetadataBilling, optional)
- `usage` (map from string to any, optional) — Provider usage plus JoyToken credits_used when available.
- `latency` (JoyTokenMetadataLatency, optional) — Latency breakdown. Orchestration tasks report first_token_ms and stream_ms.
- `request_id` (string, optional) — Gateway request identifier for log, billing, and debugging correlation. Present on non-streaming top-level metadata.
- `model_recommendation` (JoyTokenMetadataModelRecommendation, optional) — Router's model recommendation for this request, including candidate models and their scores.
- `task_score` (JoyTokenMetadataTaskScore, optional) — Router scoring breakdown used to select the model.

### OrchestrationPlanItem

A single task in the orchestration plan.

- `seq` (integer, required) — Task order within the plan.
- `task_id` (string, required) — Task identifier. The final aggregation task uses `__final__`.
- `title` (string, required)

### ErrorResponseError

- `message` (string, required)
- `type` (string, optional)
- `code` (ErrorResponseErrorCode, optional, nullable)

### ChatMessageContent

- string
- list of map from string to any

### ChatToolFunction

- `name` (string, required)
- `description` (string, optional)
- `parameters` (map from string to any, optional)

### JoyTokenMetadataBilling

- `credits_used` (string, optional)
- `input_tokens` (integer, optional)
- `output_tokens` (integer, optional)
- `cached_input_tokens` (integer, optional)
- `cached_output_tokens` (integer, optional)

### JoyTokenMetadataLatency

Latency breakdown. Orchestration tasks report first_token_ms and stream_ms.

- `routing_ms` (integer, optional)
- `first_token_ms` (integer, optional)
- `stream_ms` (integer, optional)

### JoyTokenMetadataModelRecommendation

Router's model recommendation for this request, including candidate models and their scores.

- `models` (list of JoyTokenMetadataModelRecommendationModelsItems, optional)

### JoyTokenMetadataTaskScore

Router scoring breakdown used to select the model.

- `history_score` (double, optional)
- `latest_conversation_score` (double, optional)
- `multimodal_score` (double, optional)
- `system_score` (double, optional)
- `tool_score` (double, optional)
- `total_score` (double, optional)

### ErrorResponseErrorCode

- string
- integer

### JoyTokenMetadataModelRecommendationModelsItems

- `model_id` (string, optional)
- `probability` (double, optional)
- `selected` (boolean, optional)
- `feature_tags` (list of string, optional)

## Examples

### Single-model response

**Request**

```json
{
  "model": "auto",
  "messages": [
    {
      "role": "user",
      "content": "Please test the gateway connectivity for me."
    }
  ],
  "stream": false,
  "temperature": 0.7,
  "max_tokens": 1024
}
```

**Response**

```json
{
  "id": "chatcmpl_xxx",
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "JoyToken is a governed model gateway for OpenAI-compatible apps."
      },
      "finish_reason": "stop"
    }
  ],
  "created": 1793395200,
  "model": "auto",
  "usage": {
    "prompt_tokens": 24,
    "completion_tokens": 14,
    "total_tokens": 38
  },
  "metadata": [
    {
      "model": "auto",
      "tier": "economy",
      "score": 4.0238,
      "billing_id": "bill-e9c9a188a7f26fc1892431345dfd7818",
      "tag": [
        "chat"
      ],
      "billing": {
        "credits_used": "0.2288",
        "input_tokens": 24,
        "output_tokens": 14,
        "cached_input_tokens": 0,
        "cached_output_tokens": 0
      },
      "latency": {
        "routing_ms": 6
      },
      "request_id": "auto-req-562c72b27f191b4d4a22b9af",
      "model_recommendation": {
        "models": [
          {
            "model_id": "gpt-5.6-luna",
            "probability": 0.9922,
            "selected": true,
            "feature_tags": [
              "chat",
              "coding",
              "writing",
              "orchestration",
              "aggregation"
            ]
          },
          {
            "model_id": "Gemini-3.1-Flash-Lite",
            "probability": 0.0077,
            "selected": false,
            "feature_tags": [
              "chat",
              "search",
              "summarization",
              "aggregation",
              "orchestration"
            ]
          }
        ]
      },
      "task_score": {
        "history_score": 0.1038,
        "latest_conversation_score": 3.92,
        "multimodal_score": 0,
        "system_score": 0,
        "tool_score": 0,
        "total_score": 4.0238
      }
    }
  ]
}
```

**SDK Code**

```python Single-model response
import requests

url = "https://api.joytokens.ai/openai/v1/chat/completions"

payload = {
    "model": "auto",
    "messages": [
        {
            "role": "user",
            "content": "Please test the gateway connectivity for me."
        }
    ],
    "stream": False,
    "temperature": 0.7,
    "max_tokens": 1024
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript Single-model response
const url = 'https://api.joytokens.ai/openai/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"auto","messages":[{"role":"user","content":"Please test the gateway connectivity for me."}],"stream":false,"temperature":0.7,"max_tokens":1024}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Single-model response
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.joytokens.ai/openai/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"auto\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Please test the gateway connectivity for me.\"\n    }\n  ],\n  \"stream\": false,\n  \"temperature\": 0.7,\n  \"max_tokens\": 1024\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Single-model response
require 'uri'
require 'net/http'

url = URI("https://api.joytokens.ai/openai/v1/chat/completions")

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 = "{\n  \"model\": \"auto\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Please test the gateway connectivity for me.\"\n    }\n  ],\n  \"stream\": false,\n  \"temperature\": 0.7,\n  \"max_tokens\": 1024\n}"

response = http.request(request)
puts response.read_body
```

```java Single-model response
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.joytokens.ai/openai/v1/chat/completions")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"auto\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Please test the gateway connectivity for me.\"\n    }\n  ],\n  \"stream\": false,\n  \"temperature\": 0.7,\n  \"max_tokens\": 1024\n}")
  .asString();
```

```php Single-model response
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.joytokens.ai/openai/v1/chat/completions', [
  'body' => '{
  "model": "auto",
  "messages": [
    {
      "role": "user",
      "content": "Please test the gateway connectivity for me."
    }
  ],
  "stream": false,
  "temperature": 0.7,
  "max_tokens": 1024
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp Single-model response
using RestSharp;

var client = new RestClient("https://api.joytokens.ai/openai/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"auto\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Please test the gateway connectivity for me.\"\n    }\n  ],\n  \"stream\": false,\n  \"temperature\": 0.7,\n  \"max_tokens\": 1024\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Single-model response
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "auto",
  "messages": [
    [
      "role": "user",
      "content": "Please test the gateway connectivity for me."
    ]
  ],
  "stream": false,
  "temperature": 0.7,
  "max_tokens": 1024
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.joytokens.ai/openai/v1/chat/completions")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### Orchestration (multi-task planning) response

**Request**

```json
{
  "model": "auto",
  "messages": [
    {
      "role": "user",
      "content": "Find indoor spots for a rainy day and plan a walking route between them."
    }
  ],
  "stream": false,
  "temperature": 0.7,
  "max_tokens": 1024
}
```

**Response**

```json
{
  "id": "orch-pg-1788095975442-8a9c3cf28015e8",
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "[{\"content\":\"...search task output...\",\"title\":\"Search indoor spots and food\"},{\"content\":\"...itinerary planning output...\",\"title\":\"Plan the itinerary\"},{\"content\":\"...formatted itinerary output...\",\"title\":\"Format the itinerary\"},{\"content\":\"...final aggregated answer...\",\"title\":\"Aggregate\"}]"
      },
      "finish_reason": "stop"
    }
  ],
  "created": 1788096039,
  "model": "auto",
  "metadata": [
    {
      "model": "Gemini-3.1-Flash-Lite",
      "tier": "economy",
      "billing_id": "5000000000000000013",
      "tag": [
        "orchestration"
      ],
      "task_id": "__planner__",
      "task_seq": 0,
      "task_status": "DONE",
      "billing": {
        "credits_used": "0.431579",
        "input_tokens": 1254,
        "output_tokens": 337,
        "cached_input_tokens": 0,
        "cached_output_tokens": 0
      },
      "latency": {
        "first_token_ms": 2552,
        "stream_ms": 2552
      }
    },
    {
      "model": "Gemini-3-Flash-Preview",
      "tier": "standard",
      "billing_id": "5000000000000000013",
      "tag": [
        "search"
      ],
      "task_id": "search_spots",
      "task_seq": 1,
      "task_status": "DONE",
      "title": "Search indoor spots and food",
      "billing": {
        "credits_used": "0.651435",
        "input_tokens": 48,
        "output_tokens": 1191,
        "cached_input_tokens": 0,
        "cached_output_tokens": 0
      },
      "latency": {
        "first_token_ms": 14489,
        "stream_ms": 14489
      }
    },
    {
      "model": "Gemini-3-Flash-Preview",
      "tier": "standard",
      "billing_id": "5000000000000000013",
      "tag": [
        "reasoning"
      ],
      "task_id": "plan_itinerary",
      "task_seq": 2,
      "task_status": "DONE",
      "title": "Plan the itinerary",
      "billing": {
        "credits_used": "0.671414",
        "input_tokens": 1288,
        "output_tokens": 1020,
        "cached_input_tokens": 0,
        "cached_output_tokens": 0
      },
      "latency": {
        "first_token_ms": 13304,
        "stream_ms": 13304
      }
    },
    {
      "model": "gpt-5.6-luna",
      "tier": "economy",
      "billing_id": "5000000000000000013",
      "tag": [
        "writing"
      ],
      "task_id": "format_output",
      "task_seq": 3,
      "task_status": "DONE",
      "title": "Format the itinerary",
      "billing": {
        "credits_used": "1.179563",
        "input_tokens": 1190,
        "output_tokens": 1784,
        "cached_input_tokens": 0,
        "cached_output_tokens": 0
      },
      "latency": {
        "first_token_ms": 17981,
        "stream_ms": 17981
      }
    },
    {
      "model": "gpt-5.6-luna",
      "tier": "economy",
      "billing_id": "5000000000000000013",
      "tag": [
        "aggregation"
      ],
      "task_id": "__final__",
      "task_seq": 4,
      "task_status": "DONE",
      "title": "Aggregate",
      "billing": {
        "credits_used": "1.130254",
        "input_tokens": 4307,
        "output_tokens": 1184,
        "cached_input_tokens": 0,
        "cached_output_tokens": 0
      },
      "latency": {
        "first_token_ms": 15000,
        "stream_ms": 15000
      }
    }
  ],
  "plan": [
    {
      "seq": 1,
      "task_id": "search_spots",
      "title": "Search indoor spots and food"
    },
    {
      "seq": 2,
      "task_id": "plan_itinerary",
      "title": "Plan the itinerary"
    },
    {
      "seq": 3,
      "task_id": "format_output",
      "title": "Format the itinerary"
    },
    {
      "seq": 4,
      "task_id": "__final__",
      "title": "Aggregate"
    }
  ]
}
```

**SDK Code**

```python Orchestration (multi-task planning) response
import requests

url = "https://api.joytokens.ai/openai/v1/chat/completions"

payload = {
    "model": "auto",
    "messages": [
        {
            "role": "user",
            "content": "Find indoor spots for a rainy day and plan a walking route between them."
        }
    ],
    "stream": False,
    "temperature": 0.7,
    "max_tokens": 1024
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript Orchestration (multi-task planning) response
const url = 'https://api.joytokens.ai/openai/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"auto","messages":[{"role":"user","content":"Find indoor spots for a rainy day and plan a walking route between them."}],"stream":false,"temperature":0.7,"max_tokens":1024}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Orchestration (multi-task planning) response
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.joytokens.ai/openai/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"auto\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Find indoor spots for a rainy day and plan a walking route between them.\"\n    }\n  ],\n  \"stream\": false,\n  \"temperature\": 0.7,\n  \"max_tokens\": 1024\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Orchestration (multi-task planning) response
require 'uri'
require 'net/http'

url = URI("https://api.joytokens.ai/openai/v1/chat/completions")

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 = "{\n  \"model\": \"auto\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Find indoor spots for a rainy day and plan a walking route between them.\"\n    }\n  ],\n  \"stream\": false,\n  \"temperature\": 0.7,\n  \"max_tokens\": 1024\n}"

response = http.request(request)
puts response.read_body
```

```java Orchestration (multi-task planning) response
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.joytokens.ai/openai/v1/chat/completions")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"auto\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Find indoor spots for a rainy day and plan a walking route between them.\"\n    }\n  ],\n  \"stream\": false,\n  \"temperature\": 0.7,\n  \"max_tokens\": 1024\n}")
  .asString();
```

```php Orchestration (multi-task planning) response
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.joytokens.ai/openai/v1/chat/completions', [
  'body' => '{
  "model": "auto",
  "messages": [
    {
      "role": "user",
      "content": "Find indoor spots for a rainy day and plan a walking route between them."
    }
  ],
  "stream": false,
  "temperature": 0.7,
  "max_tokens": 1024
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp Orchestration (multi-task planning) response
using RestSharp;

var client = new RestClient("https://api.joytokens.ai/openai/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"auto\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Find indoor spots for a rainy day and plan a walking route between them.\"\n    }\n  ],\n  \"stream\": false,\n  \"temperature\": 0.7,\n  \"max_tokens\": 1024\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Orchestration (multi-task planning) response
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "auto",
  "messages": [
    [
      "role": "user",
      "content": "Find indoor spots for a rainy day and plan a walking route between them."
    ]
  ],
  "stream": false,
  "temperature": 0.7,
  "max_tokens": 1024
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.joytokens.ai/openai/v1/chat/completions")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```