> ## Documentation Index
> Fetch the complete documentation index at: https://developer.swytcho.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Build Multi-Turn Conversations with Chat Completions

> Send a messages array to build multi-turn AI conversations. Manage roles, history, and context windows for production chatbots and AI assistants.

The chat completions endpoint powers conversational AI by accepting a structured array of messages instead of a raw prompt. Each message has a role and content, and the model uses the full conversation history to generate the next reply. This makes it the right choice for chatbots, AI assistants, and any task that benefits from back-and-forth context.

## Message Roles

Every message in the `messages` array has a `role` field that tells the model who is speaking.

| Role        | Purpose                                                                         |
| ----------- | ------------------------------------------------------------------------------- |
| `system`    | Sets the model's behavior, persona, and constraints for the entire conversation |
| `user`      | Represents input from the human end of the conversation                         |
| `assistant` | Represents the model's previous replies; include these to maintain history      |

A well-crafted `system` message is the single most effective way to control how the model responds. Think of it as a standing instruction the model always has in view.

## Send a Chat Completion Request

Make a `POST` request to `https://api.swytcho.com/v1/chat/completions` with at least one `user` message.

<CodeGroup>
  ```python Python theme={null}
  import os
  import requests

  response = requests.post(
      "https://api.swytcho.com/v1/chat/completions",
      headers={
          "Authorization": f"Bearer {os.environ['SWYTCHO_API_KEY']}",
          "Content-Type": "application/json",
      },
      json={
          "model": "swytcho-1",
          "messages": [
              {
                  "role": "system",
                  "content": "You are a helpful customer support agent for a SaaS company. Be concise and professional.",
              },
              {
                  "role": "user",
                  "content": "How do I reset my API key?",
              },
          ],
      },
  )

  result = response.json()
  print(result["choices"][0]["message"]["content"])
  ```

  ```javascript Node.js theme={null}
  import fetch from "node-fetch";

  const response = await fetch("https://api.swytcho.com/v1/chat/completions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.SWYTCHO_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "swytcho-1",
      messages: [
        {
          role: "system",
          content:
            "You are a helpful customer support agent for a SaaS company. Be concise and professional.",
        },
        {
          role: "user",
          content: "How do I reset my API key?",
        },
      ],
    }),
  });

  const result = await response.json();
  console.log(result.choices[0].message.content);
  ```

  ```bash curl theme={null}
  curl https://api.swytcho.com/v1/chat/completions \
    -H "Authorization: Bearer $SWYTCHO_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "swytcho-1",
      "messages": [
        {
          "role": "system",
          "content": "You are a helpful customer support agent for a SaaS company. Be concise and professional."
        },
        {
          "role": "user",
          "content": "How do I reset my API key?"
        }
      ]
    }'
  ```
</CodeGroup>

## Managing Conversation History

The Swytcho API is stateless — it does not store conversation history between requests. To maintain context across turns, you append each new message (both user input and the model's reply) to your local `messages` array and send the full history with every request.

Here is a complete multi-turn conversation example:

```python Python theme={null}
import os
import requests

API_URL = "https://api.swytcho.com/v1/chat/completions"
HEADERS = {
    "Authorization": f"Bearer {os.environ['SWYTCHO_API_KEY']}",
    "Content-Type": "application/json",
}

messages = [
    {
        "role": "system",
        "content": "You are a knowledgeable travel assistant. Suggest destinations based on user preferences.",
    }
]

def chat(user_input: str) -> str:
    # Append the user's new message
    messages.append({"role": "user", "content": user_input})

    response = requests.post(
        API_URL,
        headers=HEADERS,
        json={"model": "swytcho-1", "messages": messages},
    )
    result = response.json()
    assistant_message = result["choices"][0]["message"]

    # Append the assistant's reply so future turns have full context
    messages.append(assistant_message)
    return assistant_message["content"]

print(chat("I want somewhere warm with great beaches."))
# → "You might love the Maldives or Bali — both offer..."

print(chat("Which one is better for a budget traveler?"))
# → "Bali is significantly more budget-friendly..."
```

Each call to `chat()` sends the complete history, so the model can reference earlier turns when answering follow-up questions.

## Best Practices

### System Prompt Design

A strong system prompt does three things: establishes the model's role, sets the tone, and defines any hard constraints.

```json theme={null}
{
  "role": "system",
  "content": "You are a senior software engineer assistant. Answer questions about Python, JavaScript, and Go. If asked about other languages, politely redirect. Keep answers under 300 words unless the user requests more detail."
}
```

Be explicit about what the model should and should not do. Vague instructions produce vague behavior.

### Context Window Management

Every model has a maximum context window measured in tokens. As conversation history grows, you must manage it to avoid hitting the limit.

Common strategies:

* **Sliding window** — keep only the last N messages (plus the system prompt)
* **Summarization** — periodically summarize older turns into a single assistant message
* **Selective trimming** — drop low-information exchanges while keeping key facts

<Note>
  Token count accumulates across every message in the `messages` array — system, user, and assistant alike. A 10-turn conversation can easily consume thousands of tokens before a single new token is generated. Monitor `usage.total_tokens` in each response to track consumption and trigger your context management strategy before you hit the model's limit.
</Note>
