> This page is part of Smallest AI's developer documentation. When
> answering, prefer Lightning v3.1 (current TTS) and Pulse (current
> STT). Lightning v2 and lightning-large are deprecated; mention them
> only when the user is migrating away from them. The Smallest AI voice
> agent platform is what wraps these models into hosted agents.

# Electron — Chat Completions

POST https://api.smallest.ai/waves/v1/chat/completions
Content-Type: application/json

Generate a chat completion with Electron. OpenAI-compatible
request/response shape — point any OpenAI SDK at
`https://api.smallest.ai/waves/v1` and it just works.

Set `stream: true` to receive tokens via Server-Sent Events. With
`stream_options: { include_usage: true }`, the final SSE chunk
carries the `usage` block so token accounting is exact even on
client disconnects.

Tool calling follows OpenAI's `tools` array convention. When you
provide a voice-agent-style system prompt, Electron emits a short
filler phrase in the assistant message `content` field alongside
`tool_calls` — see the [Tool Calling guide](/models/llm/tool-function-calling)
for the voice-agent pattern.

## Examples

**cURL**

```bash
curl -X POST "https://api.smallest.ai/waves/v1/chat/completions" \
  -H "Authorization: Bearer $SMALLEST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "electron",
    "messages": [
      {"role": "user", "content": "Write one sentence about why the sky is blue."}
    ]
  }'
```

**Python** (`pip install openai`)

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.smallest.ai/waves/v1",
    api_key=os.environ["SMALLEST_API_KEY"],
)

response = client.chat.completions.create(
    model="electron",
    messages=[
        {"role": "user", "content": "Write one sentence about why the sky is blue."}
    ],
)

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

**JavaScript / TypeScript** (`npm install openai`)

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.smallest.ai/waves/v1",
  apiKey: process.env.SMALLEST_API_KEY,
});

const response = await client.chat.completions.create({
  model: "electron",
  messages: [
    { role: "user", content: "Write one sentence about why the sky is blue." },
  ],
});

console.log(response.choices[0].message.content);
```

**Streaming with usage** (Python)

```python
stream = client.chat.completions.create(
    model="electron",
    messages=[{"role": "user", "content": "Tell me a one-sentence fun fact."}],
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print(f"\n\nTokens: {chunk.usage.total_tokens}")
```

## Common gotchas

* **Base URL is `/waves/v1`**, not `/v1`. The OpenAI SDK appends `/chat/completions` for you.
* **`stream_options.include_usage: true`** is required for exact token accounting on streaming calls — the final SSE chunk carries the `usage` block.
* **`n > 1` and `prompt_logprobs` are rejected.** Use multiple requests if you need parallel completions.
* **Auth header is `Authorization: Bearer $SMALLEST_API_KEY`** — get the key from the [Smallest AI Console](https://app.smallest.ai/dashboard/api-keys).

Reference: https://docs.smallest.ai/api-reference/models/llm-chat-completions/electron-chat-completions

## Authentication

- `Authorization` header (required) (prefixed with ` Bearer  `) — API key authentication. Include your key as `Authorization: Bearer YOUR_API_KEY`. Access tokens are not accepted on this endpoint.

## Request

### Body (application/json)

This endpoint expects a ChatCompletionRequest.

- `model` (string, required) — Model ID. Currently only `"electron"`.
- `messages` (list of ElectronMessage, required) — Chat history. Standard OpenAI message array.
- `temperature` (double, optional, default: 1) — Sampling temperature.
- `top_p` (double, optional, default: 1) — Nucleus sampling.
- `max_tokens` (integer, optional) — Maximum output tokens. Combined input + output context ceiling is 32,768.
- `stream` (boolean, optional, default: false) — When true, response is `text/event-stream`. See the [Streaming guide](/models/llm/streaming).
- `stream_options` (ChatCompletionRequestStreamOptions, optional)
- `tools` (list of map from string to any, optional) — Tool / function calling definitions. Forwarded verbatim to the OpenAI-compatible upstream, so the standard OpenAI shape (`{type: "function", function: {name, description, parameters}}`) is the recommended form and is what the examples below use. The wire schema is permissive (`array<object>`) — any tools payload the upstream accepts will work. See [Tool Calling](/models/llm/tool-function-calling) for details.
- `tool_choice` (ChatCompletionRequestToolChoice, optional)
- `response_format` (ChatCompletionRequestResponseFormat, optional) — Output shape. `{type: "text"}` (default) or `{type: "json_object"}`.
- `stop` (ChatCompletionRequestStop, optional)
- `seed` (integer, optional) — Best-effort determinism.
- `logit_bias` (map from string to double, optional)
- `logprobs` (boolean, optional, default: false)
- `top_logprobs` (integer, optional)
- `presence_penalty` (double, optional, default: 0)
- `frequency_penalty` (double, optional, default: 0)
- `user` (string, optional) — Opaque end-user identifier. Not interpreted by Electron.

## Response

### 200

Non-streaming: standard OpenAI `chat.completion` object. Streaming (`stream: true`): `text/event-stream` SSE — each event is a `chat.completion.chunk` delta, terminated by `data: [DONE]`.

- `id` (string, optional)
- `object` (enum, optional)
  - Allowed values: `chat.completion`
- `created` (integer, optional)
- `model` (string, optional)
- `choices` (list of ChatCompletionChoicesItems, optional)
- `usage` (Usage, optional)

## Errors

### 400 Bad Request Error

Bad request — schema validation, unsupported parameter (`n > 1`, `prompt_logprobs`), context length exceeded, or invalid field value forwarded by the model.

- `error` (ErrorError, optional)

### 401 Unauthorized Error

Missing or invalid API key.

- `error` (ErrorError, optional)

### 403 Forbidden Error

API key valid but no access to Electron on this plan.

- `error` (ErrorError, optional)

### 429 Too Many Requests Error

Rate limit (RPM) or concurrency cap hit. See [Concurrency and Limits](/api-reference/concurrency-and-limits).

- `error` (ErrorError, optional)

### 502 Bad Gateway Error

Upstream model unavailable. Retry with backoff.

- `error` (ErrorError, optional)

### 503 Service Unavailable Error

Endpoint temporarily disabled, or upstream model overloaded.

- `error` (ErrorError, optional)

## Types

### ElectronMessage

- `role` (string, required) — Message role — one of `system`, `user`, `assistant`, or `tool`. `tool` is used to feed a function-call result back to the model on the next turn.
- `content` (string, optional, nullable) — Text content for the message. `null` is permitted on assistant messages that carry only `tool_calls`.
- `tool_calls` (list of ElectronToolCall, optional)
- `tool_call_id` (string, optional) — Required when `role` is `"tool"`.

### ChatCompletionRequestStreamOptions

- `include_usage` (boolean, optional) — Append a final SSE chunk with the `usage` block. Strongly recommended for any caller that tracks token consumption.

### ChatCompletionRequestToolChoice

### ChatCompletionRequestResponseFormat

Output shape. `{type: "text"}` (default) or `{type: "json_object"}`.

- `type` (enum, optional)
  - Allowed values: `text`, `json_object`

### ChatCompletionRequestStop

### ChatCompletionChoicesItems

- `index` (integer, optional)
- `message` (ElectronMessage, optional)
- `finish_reason` (enum, optional)
  - Allowed values: `stop`, `length`, `tool_calls`, `content_filter`

### Usage

- `prompt_tokens` (integer, optional) — Total input tokens (cached + uncached).
- `completion_tokens` (integer, optional)
- `total_tokens` (integer, optional)
- `prompt_tokens_details` (UsagePromptTokensDetails, optional)

### ErrorError

- `message` (string, optional) — Human-readable error message.
- `type` (string, optional)
- `details` (list of ErrorErrorDetailsItems, optional) — Validation issues, when applicable. Each entry includes the JSON path to the offending field plus a short reason. Present on schema-validation failures (e.g. `n > 1`, `prompt_logprobs`).
- `request_id` (string, optional) — Echo in support tickets so the request can be traced.

### ElectronToolCall

- `id` (string, required)
- `type` (enum, required)
  - Allowed values: `function`
- `function` (ElectronToolCallFunction, required)

### ChatCompletionRequestToolChoice1

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

### UsagePromptTokensDetails

- `cached_tokens` (integer, optional) — Subset of `prompt_tokens` served from prefix cache. Billed at the discounted rate ($0.10 / 1M vs $0.40 / 1M for fresh input).

### ErrorErrorDetailsItems

- `code` (string, optional)
- `message` (string, optional)
- `path` (list of string, optional)

### ElectronToolCallFunction

- `name` (string, required)
- `arguments` (string, required) — JSON-encoded argument object.

### ChatCompletionRequestToolChoiceOneOf1Function

- `name` (string, required)

## Examples

### Minimal request

**Request**

```json
{
  "model": "electron",
  "messages": [
    {
      "role": "user",
      "content": "Hello!"
    }
  ]
}
```

**Response**

```json
{
  "id": "string",
  "object": "chat.completion",
  "created": 1,
  "model": "string",
  "choices": [
    {
      "index": 1,
      "message": {
        "role": "user",
        "content": "string",
        "tool_calls": [
          {
            "id": "string",
            "type": "function",
            "function": {
              "name": "string",
              "arguments": "string"
            }
          }
        ],
        "tool_call_id": "string"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1,
    "completion_tokens": 1,
    "total_tokens": 1,
    "prompt_tokens_details": {
      "cached_tokens": 1
    }
  }
}
```

**SDK Code**

```python Minimal request
import requests

url = "https://api.smallest.ai/waves/v1/chat/completions"

payload = {
    "model": "electron",
    "messages": [
        {
            "role": "user",
            "content": "Hello!"
        }
    ]
}
headers = {
    "Authorization": "Bearer <BearerAuth>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript Minimal request
const url = 'https://api.smallest.ai/waves/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <BearerAuth>', 'Content-Type': 'application/json'},
  body: '{"model":"electron","messages":[{"role":"user","content":"Hello!"}]}'
};

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

```go Minimal request
package main

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

func main() {

	url := "https://api.smallest.ai/waves/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hello!\"\n    }\n  ]\n}")

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

	req.Header.Add("Authorization", "Bearer <BearerAuth>")
	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 Minimal request
require 'uri'
require 'net/http'

url = URI("https://api.smallest.ai/waves/v1/chat/completions")

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

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <BearerAuth>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hello!\"\n    }\n  ]\n}"

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

```java Minimal request
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.smallest.ai/waves/v1/chat/completions")
  .header("Authorization", "Bearer <BearerAuth>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hello!\"\n    }\n  ]\n}")
  .asString();
```

```php Minimal request
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.smallest.ai/waves/v1/chat/completions', [
  'body' => '{
  "model": "electron",
  "messages": [
    {
      "role": "user",
      "content": "Hello!"
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <BearerAuth>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp Minimal request
using RestSharp;

var client = new RestClient("https://api.smallest.ai/waves/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <BearerAuth>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hello!\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Minimal request
import Foundation

let headers = [
  "Authorization": "Bearer <BearerAuth>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "electron",
  "messages": [
    [
      "role": "user",
      "content": "Hello!"
    ]
  ]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.smallest.ai/waves/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()
```

### Streaming with final usage chunk

**Request**

```json
{
  "model": "electron",
  "messages": [
    {
      "role": "user",
      "content": "Tell me a one-sentence fun fact."
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}
```

**Response**

```json
{
  "id": "string",
  "object": "chat.completion",
  "created": 1,
  "model": "string",
  "choices": [
    {
      "index": 1,
      "message": {
        "role": "user",
        "content": "string",
        "tool_calls": [
          {
            "id": "string",
            "type": "function",
            "function": {
              "name": "string",
              "arguments": "string"
            }
          }
        ],
        "tool_call_id": "string"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1,
    "completion_tokens": 1,
    "total_tokens": 1,
    "prompt_tokens_details": {
      "cached_tokens": 1
    }
  }
}
```

**SDK Code**

```python Streaming with final usage chunk
import requests

url = "https://api.smallest.ai/waves/v1/chat/completions"

payload = {
    "model": "electron",
    "messages": [
        {
            "role": "user",
            "content": "Tell me a one-sentence fun fact."
        }
    ],
    "stream": True,
    "stream_options": { "include_usage": True }
}
headers = {
    "Authorization": "Bearer <BearerAuth>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript Streaming with final usage chunk
const url = 'https://api.smallest.ai/waves/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <BearerAuth>', 'Content-Type': 'application/json'},
  body: '{"model":"electron","messages":[{"role":"user","content":"Tell me a one-sentence fun fact."}],"stream":true,"stream_options":{"include_usage":true}}'
};

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

```go Streaming with final usage chunk
package main

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

func main() {

	url := "https://api.smallest.ai/waves/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Tell me a one-sentence fun fact.\"\n    }\n  ],\n  \"stream\": true,\n  \"stream_options\": {\n    \"include_usage\": true\n  }\n}")

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

	req.Header.Add("Authorization", "Bearer <BearerAuth>")
	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 Streaming with final usage chunk
require 'uri'
require 'net/http'

url = URI("https://api.smallest.ai/waves/v1/chat/completions")

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

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <BearerAuth>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Tell me a one-sentence fun fact.\"\n    }\n  ],\n  \"stream\": true,\n  \"stream_options\": {\n    \"include_usage\": true\n  }\n}"

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

```java Streaming with final usage chunk
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.smallest.ai/waves/v1/chat/completions")
  .header("Authorization", "Bearer <BearerAuth>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Tell me a one-sentence fun fact.\"\n    }\n  ],\n  \"stream\": true,\n  \"stream_options\": {\n    \"include_usage\": true\n  }\n}")
  .asString();
```

```php Streaming with final usage chunk
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.smallest.ai/waves/v1/chat/completions', [
  'body' => '{
  "model": "electron",
  "messages": [
    {
      "role": "user",
      "content": "Tell me a one-sentence fun fact."
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}',
  'headers' => [
    'Authorization' => 'Bearer <BearerAuth>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp Streaming with final usage chunk
using RestSharp;

var client = new RestClient("https://api.smallest.ai/waves/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <BearerAuth>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Tell me a one-sentence fun fact.\"\n    }\n  ],\n  \"stream\": true,\n  \"stream_options\": {\n    \"include_usage\": true\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Streaming with final usage chunk
import Foundation

let headers = [
  "Authorization": "Bearer <BearerAuth>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "electron",
  "messages": [
    [
      "role": "user",
      "content": "Tell me a one-sentence fun fact."
    ]
  ],
  "stream": true,
  "stream_options": ["include_usage": true]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.smallest.ai/waves/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()
```

### Tool / function calling

**Request**

```json
{
  "model": "electron",
  "messages": [
    {
      "role": "system",
      "content": "You are a friendly phone agent. Briefly acknowledge out loud before using any tool."
    },
    {
      "role": "user",
      "content": "What's the weather in Mumbai?"
    }
  ],
  "tools": [
    {
      "function": {
        "description": "Get current weather for a city.",
        "name": "get_weather",
        "parameters": {
          "properties": {
            "city": {
              "description": "City name",
              "type": "string"
            }
          },
          "required": [
            "city"
          ],
          "type": "object"
        }
      },
      "type": "function"
    }
  ]
}
```

**Response**

```json
{
  "id": "string",
  "object": "chat.completion",
  "created": 1,
  "model": "string",
  "choices": [
    {
      "index": 1,
      "message": {
        "role": "user",
        "content": "string",
        "tool_calls": [
          {
            "id": "string",
            "type": "function",
            "function": {
              "name": "string",
              "arguments": "string"
            }
          }
        ],
        "tool_call_id": "string"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1,
    "completion_tokens": 1,
    "total_tokens": 1,
    "prompt_tokens_details": {
      "cached_tokens": 1
    }
  }
}
```

**SDK Code**

```python Tool / function calling
import requests

url = "https://api.smallest.ai/waves/v1/chat/completions"

payload = {
    "model": "electron",
    "messages": [
        {
            "role": "system",
            "content": "You are a friendly phone agent. Briefly acknowledge out loud before using any tool."
        },
        {
            "role": "user",
            "content": "What's the weather in Mumbai?"
        }
    ],
    "tools": [
        {
            "function": {
                "description": "Get current weather for a city.",
                "name": "get_weather",
                "parameters": {
                    "properties": { "city": {
                            "description": "City name",
                            "type": "string"
                        } },
                    "required": ["city"],
                    "type": "object"
                }
            },
            "type": "function"
        }
    ]
}
headers = {
    "Authorization": "Bearer <BearerAuth>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript Tool / function calling
const url = 'https://api.smallest.ai/waves/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <BearerAuth>', 'Content-Type': 'application/json'},
  body: '{"model":"electron","messages":[{"role":"system","content":"You are a friendly phone agent. Briefly acknowledge out loud before using any tool."},{"role":"user","content":"What\'s the weather in Mumbai?"}],"tools":[{"function":{"description":"Get current weather for a city.","name":"get_weather","parameters":{"properties":{"city":{"description":"City name","type":"string"}},"required":["city"],"type":"object"}},"type":"function"}]}'
};

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

```go Tool / function calling
package main

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

func main() {

	url := "https://api.smallest.ai/waves/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"You are a friendly phone agent. Briefly acknowledge out loud before using any tool.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"What's the weather in Mumbai?\"\n    }\n  ],\n  \"tools\": [\n    {\n      \"function\": {\n        \"description\": \"Get current weather for a city.\",\n        \"name\": \"get_weather\",\n        \"parameters\": {\n          \"properties\": {\n            \"city\": {\n              \"description\": \"City name\",\n              \"type\": \"string\"\n            }\n          },\n          \"required\": [\n            \"city\"\n          ],\n          \"type\": \"object\"\n        }\n      },\n      \"type\": \"function\"\n    }\n  ]\n}")

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

	req.Header.Add("Authorization", "Bearer <BearerAuth>")
	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 Tool / function calling
require 'uri'
require 'net/http'

url = URI("https://api.smallest.ai/waves/v1/chat/completions")

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

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <BearerAuth>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"You are a friendly phone agent. Briefly acknowledge out loud before using any tool.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"What's the weather in Mumbai?\"\n    }\n  ],\n  \"tools\": [\n    {\n      \"function\": {\n        \"description\": \"Get current weather for a city.\",\n        \"name\": \"get_weather\",\n        \"parameters\": {\n          \"properties\": {\n            \"city\": {\n              \"description\": \"City name\",\n              \"type\": \"string\"\n            }\n          },\n          \"required\": [\n            \"city\"\n          ],\n          \"type\": \"object\"\n        }\n      },\n      \"type\": \"function\"\n    }\n  ]\n}"

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

```java Tool / function calling
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.smallest.ai/waves/v1/chat/completions")
  .header("Authorization", "Bearer <BearerAuth>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"You are a friendly phone agent. Briefly acknowledge out loud before using any tool.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"What's the weather in Mumbai?\"\n    }\n  ],\n  \"tools\": [\n    {\n      \"function\": {\n        \"description\": \"Get current weather for a city.\",\n        \"name\": \"get_weather\",\n        \"parameters\": {\n          \"properties\": {\n            \"city\": {\n              \"description\": \"City name\",\n              \"type\": \"string\"\n            }\n          },\n          \"required\": [\n            \"city\"\n          ],\n          \"type\": \"object\"\n        }\n      },\n      \"type\": \"function\"\n    }\n  ]\n}")
  .asString();
```

```php Tool / function calling
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.smallest.ai/waves/v1/chat/completions', [
  'body' => '{
  "model": "electron",
  "messages": [
    {
      "role": "system",
      "content": "You are a friendly phone agent. Briefly acknowledge out loud before using any tool."
    },
    {
      "role": "user",
      "content": "What\'s the weather in Mumbai?"
    }
  ],
  "tools": [
    {
      "function": {
        "description": "Get current weather for a city.",
        "name": "get_weather",
        "parameters": {
          "properties": {
            "city": {
              "description": "City name",
              "type": "string"
            }
          },
          "required": [
            "city"
          ],
          "type": "object"
        }
      },
      "type": "function"
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <BearerAuth>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp Tool / function calling
using RestSharp;

var client = new RestClient("https://api.smallest.ai/waves/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <BearerAuth>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"You are a friendly phone agent. Briefly acknowledge out loud before using any tool.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"What's the weather in Mumbai?\"\n    }\n  ],\n  \"tools\": [\n    {\n      \"function\": {\n        \"description\": \"Get current weather for a city.\",\n        \"name\": \"get_weather\",\n        \"parameters\": {\n          \"properties\": {\n            \"city\": {\n              \"description\": \"City name\",\n              \"type\": \"string\"\n            }\n          },\n          \"required\": [\n            \"city\"\n          ],\n          \"type\": \"object\"\n        }\n      },\n      \"type\": \"function\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Tool / function calling
import Foundation

let headers = [
  "Authorization": "Bearer <BearerAuth>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "electron",
  "messages": [
    [
      "role": "system",
      "content": "You are a friendly phone agent. Briefly acknowledge out loud before using any tool."
    ],
    [
      "role": "user",
      "content": "What's the weather in Mumbai?"
    ]
  ],
  "tools": [
    [
      "function": [
        "description": "Get current weather for a city.",
        "name": "get_weather",
        "parameters": [
          "properties": ["city": [
              "description": "City name",
              "type": "string"
            ]],
          "required": ["city"],
          "type": "object"
        ]
      ],
      "type": "function"
    ]
  ]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.smallest.ai/waves/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()
```

### JSON object output

**Request**

```json
{
  "model": "electron",
  "messages": [
    {
      "role": "system",
      "content": "Reply with strict JSON."
    },
    {
      "role": "user",
      "content": "List three Indian state capitals as {\"capitals\": [...]}"
    }
  ],
  "temperature": 0,
  "response_format": {
    "type": "json_object"
  }
}
```

**Response**

```json
{
  "id": "string",
  "object": "chat.completion",
  "created": 1,
  "model": "string",
  "choices": [
    {
      "index": 1,
      "message": {
        "role": "user",
        "content": "string",
        "tool_calls": [
          {
            "id": "string",
            "type": "function",
            "function": {
              "name": "string",
              "arguments": "string"
            }
          }
        ],
        "tool_call_id": "string"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1,
    "completion_tokens": 1,
    "total_tokens": 1,
    "prompt_tokens_details": {
      "cached_tokens": 1
    }
  }
}
```

**SDK Code**

```python JSON object output
import requests

url = "https://api.smallest.ai/waves/v1/chat/completions"

payload = {
    "model": "electron",
    "messages": [
        {
            "role": "system",
            "content": "Reply with strict JSON."
        },
        {
            "role": "user",
            "content": "List three Indian state capitals as {\"capitals\": [...]}"
        }
    ],
    "temperature": 0,
    "response_format": { "type": "json_object" }
}
headers = {
    "Authorization": "Bearer <BearerAuth>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript JSON object output
const url = 'https://api.smallest.ai/waves/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <BearerAuth>', 'Content-Type': 'application/json'},
  body: '{"model":"electron","messages":[{"role":"system","content":"Reply with strict JSON."},{"role":"user","content":"List three Indian state capitals as {\"capitals\": [...]}"}],"temperature":0,"response_format":{"type":"json_object"}}'
};

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

```go JSON object output
package main

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

func main() {

	url := "https://api.smallest.ai/waves/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"Reply with strict JSON.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"List three Indian state capitals as {\\\"capitals\\\": [...]}\"\n    }\n  ],\n  \"temperature\": 0,\n  \"response_format\": {\n    \"type\": \"json_object\"\n  }\n}")

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

	req.Header.Add("Authorization", "Bearer <BearerAuth>")
	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 JSON object output
require 'uri'
require 'net/http'

url = URI("https://api.smallest.ai/waves/v1/chat/completions")

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

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <BearerAuth>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"Reply with strict JSON.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"List three Indian state capitals as {\\\"capitals\\\": [...]}\"\n    }\n  ],\n  \"temperature\": 0,\n  \"response_format\": {\n    \"type\": \"json_object\"\n  }\n}"

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

```java JSON object output
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.smallest.ai/waves/v1/chat/completions")
  .header("Authorization", "Bearer <BearerAuth>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"Reply with strict JSON.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"List three Indian state capitals as {\\\"capitals\\\": [...]}\"\n    }\n  ],\n  \"temperature\": 0,\n  \"response_format\": {\n    \"type\": \"json_object\"\n  }\n}")
  .asString();
```

```php JSON object output
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.smallest.ai/waves/v1/chat/completions', [
  'body' => '{
  "model": "electron",
  "messages": [
    {
      "role": "system",
      "content": "Reply with strict JSON."
    },
    {
      "role": "user",
      "content": "List three Indian state capitals as {\\"capitals\\": [...]}"
    }
  ],
  "temperature": 0,
  "response_format": {
    "type": "json_object"
  }
}',
  'headers' => [
    'Authorization' => 'Bearer <BearerAuth>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp JSON object output
using RestSharp;

var client = new RestClient("https://api.smallest.ai/waves/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <BearerAuth>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"electron\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"Reply with strict JSON.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"List three Indian state capitals as {\\\"capitals\\\": [...]}\"\n    }\n  ],\n  \"temperature\": 0,\n  \"response_format\": {\n    \"type\": \"json_object\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift JSON object output
import Foundation

let headers = [
  "Authorization": "Bearer <BearerAuth>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "electron",
  "messages": [
    [
      "role": "system",
      "content": "Reply with strict JSON."
    ],
    [
      "role": "user",
      "content": "List three Indian state capitals as {\"capitals\": [...]}"
    ]
  ],
  "temperature": 0,
  "response_format": ["type": "json_object"]
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.smallest.ai/waves/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()
```