> 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. Atoms is the
> voice-agent platform.

# 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](/waves/documentation/llm-electron/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/waves/api-reference/api-reference/llm-chat-completions/electron-chat-completions

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: waves-v4
  version: 1.0.0
paths:
  /waves/v1/chat/completions:
    post:
      operationId: electron-chat-completions
      summary: Chat Completions (Electron)
      description: >
        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](/waves/documentation/llm-electron/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).
      tags:
        - subpackage_llm
      parameters:
        - name: Authorization
          in: header
          required: true
          schema:
            type: string
      responses:
        '200':
          description: |
            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]`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ChatCompletion'
        '400':
          description: |
            Bad request — schema validation, unsupported parameter
            (`n > 1`, `prompt_logprobs`), context length exceeded, or
            invalid field value forwarded by the model.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: Missing or invalid API key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '403':
          description: API key valid but no access to Electron on this plan.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '429':
          description: >
            Rate limit (RPM) or concurrency cap hit. See

            [Concurrency and
            Limits](/waves/api-reference/api-references/concurrency-and-limits).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '502':
          description: Upstream model unavailable. Retry with backoff.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '503':
          description: Endpoint temporarily disabled, or upstream model overloaded.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChatCompletionRequest'
servers:
  - url: https://api.smallest.ai
    description: waves
components:
  schemas:
    ToolCallType:
      type: string
      enum:
        - function
      title: ToolCallType
    ToolCallFunction:
      type: object
      properties:
        name:
          type: string
        arguments:
          type: string
          description: JSON-encoded argument object.
      required:
        - name
        - arguments
      title: ToolCallFunction
    ToolCall:
      type: object
      properties:
        id:
          type: string
        type:
          $ref: '#/components/schemas/ToolCallType'
        function:
          $ref: '#/components/schemas/ToolCallFunction'
      required:
        - id
        - type
        - function
      title: ToolCall
    ElectronMessage:
      type: object
      properties:
        role:
          type: string
          description: >
            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:
          type:
            - string
            - 'null'
          description: >-
            Text content for the message. `null` is permitted on assistant
            messages that carry only `tool_calls`.
        tool_calls:
          type: array
          items:
            $ref: '#/components/schemas/ToolCall'
        tool_call_id:
          type: string
          description: Required when `role` is `"tool"`.
      required:
        - role
      title: ElectronMessage
    ChatCompletionRequestStreamOptions:
      type: object
      properties:
        include_usage:
          type: boolean
          description: |
            Append a final SSE chunk with the `usage` block. Strongly
            recommended for any caller that tracks token consumption.
      title: ChatCompletionRequestStreamOptions
    ToolType:
      type: string
      enum:
        - function
      title: ToolType
    ToolParameters:
      type: object
      properties: {}
      description: JSON Schema for the tool's parameters.
      title: ToolParameters
    Tool:
      type: object
      properties:
        type:
          $ref: '#/components/schemas/ToolType'
        name:
          type: string
        description:
          type: string
        parameters:
          $ref: '#/components/schemas/ToolParameters'
          description: JSON Schema for the tool's parameters.
      required:
        - type
        - name
      title: Tool
    ChatCompletionRequestToolChoice0:
      type: string
      enum:
        - auto
        - required
        - none
      title: ChatCompletionRequestToolChoice0
    ChatCompletionRequestToolChoiceOneOf1Type:
      type: string
      enum:
        - function
      title: ChatCompletionRequestToolChoiceOneOf1Type
    ChatCompletionRequestToolChoiceOneOf1Function:
      type: object
      properties:
        name:
          type: string
      required:
        - name
      title: ChatCompletionRequestToolChoiceOneOf1Function
    ChatCompletionRequestToolChoice1:
      type: object
      properties:
        type:
          $ref: '#/components/schemas/ChatCompletionRequestToolChoiceOneOf1Type'
        function:
          $ref: '#/components/schemas/ChatCompletionRequestToolChoiceOneOf1Function'
      required:
        - type
        - function
      title: ChatCompletionRequestToolChoice1
    ChatCompletionRequestToolChoice:
      oneOf:
        - $ref: '#/components/schemas/ChatCompletionRequestToolChoice0'
        - $ref: '#/components/schemas/ChatCompletionRequestToolChoice1'
      title: ChatCompletionRequestToolChoice
    ChatCompletionRequestResponseFormatType:
      type: string
      enum:
        - text
        - json_object
      title: ChatCompletionRequestResponseFormatType
    ChatCompletionRequestResponseFormat:
      type: object
      properties:
        type:
          $ref: '#/components/schemas/ChatCompletionRequestResponseFormatType'
      description: |
        Output shape. `{type: "text"}` (default) or `{type: "json_object"}`.
      title: ChatCompletionRequestResponseFormat
    ChatCompletionRequestStop:
      oneOf:
        - type: string
        - type: array
          items:
            type: string
      title: ChatCompletionRequestStop
    ChatCompletionRequest:
      type: object
      properties:
        model:
          type: string
          description: Model ID. Currently only `"electron"`.
        messages:
          type: array
          items:
            $ref: '#/components/schemas/ElectronMessage'
          description: Chat history. Standard OpenAI message array.
        temperature:
          type: number
          format: double
          default: 1
          description: Sampling temperature.
        top_p:
          type: number
          format: double
          default: 1
          description: Nucleus sampling.
        max_tokens:
          type: integer
          description: |
            Maximum output tokens. Combined input + output context ceiling
            is 32,768.
        stream:
          type: boolean
          default: false
          description: |
            When true, response is `text/event-stream`. See the
            [Streaming guide](/waves/documentation/llm-electron/streaming).
        stream_options:
          $ref: '#/components/schemas/ChatCompletionRequestStreamOptions'
        tools:
          type: array
          items:
            $ref: '#/components/schemas/Tool'
          description: >
            Tool / function calling definitions. Standard OpenAI shape.

            See [Tool
            Calling](/waves/documentation/llm-electron/tool-function-calling).
        tool_choice:
          $ref: '#/components/schemas/ChatCompletionRequestToolChoice'
        response_format:
          $ref: '#/components/schemas/ChatCompletionRequestResponseFormat'
          description: |
            Output shape. `{type: "text"}` (default) or `{type: "json_object"}`.
        stop:
          $ref: '#/components/schemas/ChatCompletionRequestStop'
        seed:
          type: integer
          description: Best-effort determinism.
        logit_bias:
          type: object
          additionalProperties:
            type: number
            format: double
        logprobs:
          type: boolean
          default: false
        top_logprobs:
          type: integer
        presence_penalty:
          type: number
          format: double
          default: 0
        frequency_penalty:
          type: number
          format: double
          default: 0
        user:
          type: string
          description: Opaque end-user identifier. Not interpreted by Electron.
      required:
        - model
        - messages
      description: |
        Most OpenAI Chat Completions request fields are accepted as
        passthrough. Explicitly rejected: `n > 1`, `prompt_logprobs`.
      title: ChatCompletionRequest
    ChatCompletionObject:
      type: string
      enum:
        - chat.completion
      title: ChatCompletionObject
    ChatCompletionChoicesItemsFinishReason:
      type: string
      enum:
        - stop
        - length
        - tool_calls
        - content_filter
      title: ChatCompletionChoicesItemsFinishReason
    ChatCompletionChoicesItems:
      type: object
      properties:
        index:
          type: integer
        message:
          $ref: '#/components/schemas/ElectronMessage'
        finish_reason:
          $ref: '#/components/schemas/ChatCompletionChoicesItemsFinishReason'
      title: ChatCompletionChoicesItems
    UsagePromptTokensDetails:
      type: object
      properties:
        cached_tokens:
          type: integer
          description: |
            Subset of `prompt_tokens` served from prefix cache. Billed at
            the discounted rate ($0.10 / 1M vs $0.40 / 1M for fresh input).
      title: UsagePromptTokensDetails
    Usage:
      type: object
      properties:
        prompt_tokens:
          type: integer
          description: Total input tokens (cached + uncached).
        completion_tokens:
          type: integer
        total_tokens:
          type: integer
        prompt_tokens_details:
          $ref: '#/components/schemas/UsagePromptTokensDetails'
      title: Usage
    ChatCompletion:
      type: object
      properties:
        id:
          type: string
        object:
          $ref: '#/components/schemas/ChatCompletionObject'
        created:
          type: integer
        model:
          type: string
        choices:
          type: array
          items:
            $ref: '#/components/schemas/ChatCompletionChoicesItems'
        usage:
          $ref: '#/components/schemas/Usage'
      title: ChatCompletion
    ErrorErrorDetailsItems:
      type: object
      properties:
        code:
          type: string
        message:
          type: string
        path:
          type: array
          items:
            type: string
      title: ErrorErrorDetailsItems
    ErrorError:
      type: object
      properties:
        message:
          type: string
          description: Human-readable error message.
        type:
          type: string
        details:
          type: array
          items:
            $ref: '#/components/schemas/ErrorErrorDetailsItems'
          description: |
            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:
          type: string
          description: Echo in support tickets so the request can be traced.
      title: ErrorError
    Error:
      type: object
      properties:
        error:
          $ref: '#/components/schemas/ErrorError'
      title: Error
  securitySchemes:
    BearerAuth:
      type: apiKey
      in: header
      name: Authorization

```

## 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": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get current weather for a city.",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string",
              "description": "City name"
            }
          },
          "required": [
            "city"
          ]
        }
      }
    }
  ]
}
```

**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": [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get current weather for a city.",
                "parameters": {
                    "type": "object",
                    "properties": { "city": {
                            "type": "string",
                            "description": "City name"
                        } },
                    "required": ["city"]
                }
            }
        }
    ]
}
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":[{"type":"function","function":{"name":"get_weather","description":"Get current weather for a city.","parameters":{"type":"object","properties":{"city":{"type":"string","description":"City name"}},"required":["city"]}}}]}'
};

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      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"get_weather\",\n        \"description\": \"Get current weather for a city.\",\n        \"parameters\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"city\": {\n              \"type\": \"string\",\n              \"description\": \"City name\"\n            }\n          },\n          \"required\": [\n            \"city\"\n          ]\n        }\n      }\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      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"get_weather\",\n        \"description\": \"Get current weather for a city.\",\n        \"parameters\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"city\": {\n              \"type\": \"string\",\n              \"description\": \"City name\"\n            }\n          },\n          \"required\": [\n            \"city\"\n          ]\n        }\n      }\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      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"get_weather\",\n        \"description\": \"Get current weather for a city.\",\n        \"parameters\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"city\": {\n              \"type\": \"string\",\n              \"description\": \"City name\"\n            }\n          },\n          \"required\": [\n            \"city\"\n          ]\n        }\n      }\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": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get current weather for a city.",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string",
              "description": "City name"
            }
          },
          "required": [
            "city"
          ]
        }
      }
    }
  ]
}',
  '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      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"get_weather\",\n        \"description\": \"Get current weather for a city.\",\n        \"parameters\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"city\": {\n              \"type\": \"string\",\n              \"description\": \"City name\"\n            }\n          },\n          \"required\": [\n            \"city\"\n          ]\n        }\n      }\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": [
    [
      "type": "function",
      "function": [
        "name": "get_weather",
        "description": "Get current weather for a city.",
        "parameters": [
          "type": "object",
          "properties": ["city": [
              "type": "string",
              "description": "City name"
            ]],
          "required": ["city"]
        ]
      ]
    ]
  ]
] 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()
```