# Send a message

> POST /v1/conversations/{conversation_id}/messages

Send the next message in a chat started through the API, and get the agent's reply as a `chat.turn` — or, with `stream: true`, as server-sent events. One message at a time: wait for the reply before sending the next. Needs `chats:write`. An `Idempotency-Key` is optional: the same message again returns the reply it already got.

## Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `conversation_id` | path | string (uuid) | Yes |  |
| `Idempotency-Key` | header | string | No | Your own id for this message. Optional. |

## Body

Sent as JSON. A field this operation does not take is refused, so a typo fails loudly.

| Field | Type | Required | Description |
|---|---|---|---|
| `attachment_ids` | array of string (uuid) | No | Pictures to send with it, from `POST /v1/attachments`. |
| `message` | string | Yes | What the person wrote. |
| `stream` | boolean | No | Send the reply as it is written, as server-sent events. `Accept: text/event-stream` does the same. |

## Answer

`200` with [ChatTurn](/reference/objects/ChatTurn).

With `stream: true`, the same answer arrives as server-sent events instead — see [Chat and streaming](/guides/chat).

## Errors

Every error is a [problem document](/errors) with a stable `code`.

| Status | When |
|---|---|
| `401` | The key is missing, mistyped, unknown, revoked or expired. |
| `402` | The organization's credit is used up. |
| `403` | The key lacks a permission, a live key was sent from a browser, or the organization is frozen and the request would change something. |
| `404` | This key reaches no such chat, or it was not started through the API. |
| `409` | The chat has ended or reached its length, the agent is still answering the last message, or this is not a chat. |
| `422` | The message, or its Idempotency-Key, does not fit. |
| `429` | Too many requests for this key or its organization; see `Retry-After`. |
| `500` | Something went wrong on our side. Quote the `request_id` to support. |

## Examples

**curl**

```sh
#!/bin/sh
# Send the next message
curl -sS --fail-with-body -X POST "https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages" \
  -H "Authorization: Bearer $AIGENTLY_API_KEY" \
  --json '{
  "message": "For four people, at seven."
}'
```

**JavaScript**

```js
// Send the next message
const response = await fetch("https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.AIGENTLY_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "message": "For four people, at seven."
  }),
});
const answer = await response.json();
if (!response.ok) throw new Error(`${answer.code}: ${answer.detail}`);
console.log(answer);
```

**Python**

```python
# Send the next message
# pip install httpx
import os

import httpx

response = httpx.post(
    "https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages",
    headers={
        "Authorization": f"Bearer {os.environ['AIGENTLY_API_KEY']}",
    },
    json={
        "message": "For four people, at seven.",
    },
    timeout=60,
)
if response.is_error:
    raise SystemExit(response.text)
print(response.json())
```

**Go**

```go
// Send the next message
package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	payload := []byte(`{
  "message": "For four people, at seven."
}`)
	request, err := http.NewRequest("POST", "https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages", bytes.NewReader(payload))
	if err != nil {
		panic(err)
	}
	request.Header.Set("Authorization", "Bearer "+os.Getenv("AIGENTLY_API_KEY"))
	request.Header.Set("Content-Type", "application/json")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	body, _ := io.ReadAll(response.Body)
	if response.StatusCode >= 400 {
		fmt.Fprintln(os.Stderr, string(body))
		os.Exit(1)
	}
	fmt.Println(string(body))
}
```

**Java**

```java
// Send the next message
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String body = """
            {
              "message": "For four people, at seven."
            }
            """;
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages"))
            .header("Authorization", "Bearer " + System.getenv("AIGENTLY_API_KEY"))
            .header("Content-Type", "application/json")
            .method("POST", HttpRequest.BodyPublishers.ofString(body))
            .build();
        // HTTP/1.1: on a plain-http address Java's default asks to upgrade, which not every
        // server allows.
        HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
        HttpResponse<String> response =
            client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.body());
            System.exit(1);
        }
        System.out.println(response.body());
    }
}
```

**C#**

```csharp
// Send the next message
using System.Net.Http.Headers;
using System.Text;

using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("AIGENTLY_API_KEY"));
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages")
{
    Content = new StringContent(
        """
        {
          "message": "For four people, at seven."
        }
        """,
        Encoding.UTF8,
        "application/json"),
};
var response = await client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine(body);
    return 1;
}
Console.WriteLine(body);
return 0;
```

**PHP**

```php
<?php
// Send the next message
$curl = curl_init("https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages");
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("AIGENTLY_API_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "message" => "For four people, at seven.",
    ]),
]);
$body = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_RESPONSE_CODE) >= 400) {
    fwrite(STDERR, $body . "\n");
    exit(1);
}
echo $body, "\n";
```
**curl**

```sh
#!/bin/sh
# Stream the reply as it is written
curl -sS --fail-with-body -N -X POST "https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages" \
  -H "Authorization: Bearer $AIGENTLY_API_KEY" \
  --json '{
  "message": "Can I bring my dog?",
  "stream": true
}'
```

**JavaScript**

```js
// Stream the reply as it is written
const response = await fetch("https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.AIGENTLY_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "message": "Can I bring my dog?",
    "stream": true
  }),
});
if (!response.ok) {
  const problem = await response.json();
  throw new Error(`${problem.code}: ${problem.detail}`);
}
// Each event is an "event:" line, a "data:" line of JSON, and a blank line.
const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of response.body) {
  buffer += decoder.decode(chunk, { stream: true });
  let end;
  while ((end = buffer.indexOf("\n\n")) >= 0) {
    const [eventLine, dataLine] = buffer.slice(0, end).split("\n");
    buffer = buffer.slice(end + 2);
    const event = eventLine.slice("event: ".length);
    const data = JSON.parse(dataLine.slice("data: ".length));
    if (event === "delta") process.stdout.write(data.text);
    if (event === "done") console.log("\n", data);
    if (event === "error") throw new Error(`${data.code}: ${data.detail}`);
  }
}
```

**Python**

```python
# Stream the reply as it is written
# pip install httpx
import json
import os

import httpx

with httpx.stream(
    "POST",
    "https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages",
    headers={
        "Authorization": f"Bearer {os.environ['AIGENTLY_API_KEY']}",
    },
    json={
        "message": "Can I bring my dog?",
        "stream": True,
    },
    timeout=60,
) as response:
    if response.is_error:
        raise SystemExit(response.read().decode())
    # Each event is an "event:" line, a "data:" line of JSON, and a blank line.
    event = None
    for line in response.iter_lines():
        if line.startswith("event: "):
            event = line.removeprefix("event: ")
        elif line.startswith("data: "):
            data = json.loads(line.removeprefix("data: "))
            if event == "delta":
                print(data["text"], end="", flush=True)
            elif event == "done":
                print("\n", data)
            elif event == "error":
                raise SystemExit(f"{data['code']}: {data['detail']}")
```

**Go**

```go
// Stream the reply as it is written
package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

func main() {
	payload := []byte(`{
  "message": "Can I bring my dog?",
  "stream": true
}`)
	request, err := http.NewRequest("POST", "https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages", bytes.NewReader(payload))
	if err != nil {
		panic(err)
	}
	request.Header.Set("Authorization", "Bearer "+os.Getenv("AIGENTLY_API_KEY"))
	request.Header.Set("Content-Type", "application/json")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	if response.StatusCode >= 400 {
		body, _ := io.ReadAll(response.Body)
		fmt.Fprintln(os.Stderr, string(body))
		os.Exit(1)
	}
	// Each event is an "event:" line, a "data:" line of JSON, and a blank line.
	scanner := bufio.NewScanner(response.Body)
	scanner.Buffer(make([]byte, 64*1024), 1024*1024)
	event := ""
	for scanner.Scan() {
		line := scanner.Text()
		if name, found := strings.CutPrefix(line, "event: "); found {
			event = name
			continue
		}
		data, found := strings.CutPrefix(line, "data: ")
		if !found {
			continue
		}
		switch event {
		case "delta":
			var delta struct {
				Text string `json:"text"`
			}
			json.Unmarshal([]byte(data), &delta)
			fmt.Print(delta.Text)
		case "done":
			fmt.Println("\n" + data)
		case "error":
			fmt.Fprintln(os.Stderr, data)
			os.Exit(1)
		}
	}
}
```

**Java**

```java
// Stream the reply as it is written
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) throws Exception {
        String body = """
            {
              "message": "Can I bring my dog?",
              "stream": true
            }
            """;
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages"))
            .header("Authorization", "Bearer " + System.getenv("AIGENTLY_API_KEY"))
            .header("Content-Type", "application/json")
            .method("POST", HttpRequest.BodyPublishers.ofString(body))
            .build();
        // HTTP/1.1: on a plain-http address Java's default asks to upgrade, which not every
        // server allows.
        HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
        HttpResponse<Stream<String>> response =
            client.send(request, HttpResponse.BodyHandlers.ofLines());
        if (response.statusCode() >= 400) {
            response.body().forEach(System.err::println);
            System.exit(1);
        }
        // Each event is an "event:" line, a "data:" line of JSON, and a blank line.
        // Read each data line with your JSON library.
        response.body().filter(line -> !line.isEmpty()).forEach(System.out::println);
    }
}
```

**C#**

```csharp
// Stream the reply as it is written
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("AIGENTLY_API_KEY"));
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages")
{
    Content = new StringContent(
        """
        {
          "message": "Can I bring my dog?",
          "stream": true
        }
        """,
        Encoding.UTF8,
        "application/json"),
};
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine(await response.Content.ReadAsStringAsync());
    return 1;
}
// Each event is an "event:" line, a "data:" line of JSON, and a blank line.
using var reader = new StreamReader(await response.Content.ReadAsStreamAsync());
var eventName = "";
while (await reader.ReadLineAsync() is { } line)
{
    if (line.StartsWith("event: "))
    {
        eventName = line["event: ".Length..];
        continue;
    }
    if (!line.StartsWith("data: "))
    {
        continue;
    }
    var data = line["data: ".Length..];
    if (eventName == "delta")
    {
        Console.Write(JsonDocument.Parse(data).RootElement.GetProperty("text").GetString());
    }
    else if (eventName == "done")
    {
        Console.WriteLine("\n" + data);
    }
    else if (eventName == "error")
    {
        Console.Error.WriteLine(data);
        return 1;
    }
}
return 0;
```

**PHP**

```php
<?php
// Stream the reply as it is written
$event = "";
$buffer = "";
$failed = false;
$curl = curl_init("https://api.aigently.ai/v1/conversations/2e4a6c8d-0f1b-4d3e-a5c7-9e1b3d5f7a9c/messages");
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("AIGENTLY_API_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "message" => "Can I bring my dog?",
        "stream" => true,
    ]),
    // Each event is an "event:" line, a "data:" line of JSON, and a blank line.
    CURLOPT_WRITEFUNCTION => function ($curl, $chunk) use (&$event, &$buffer, &$failed) {
        $buffer .= $chunk;
        while (($end = strpos($buffer, "\n")) !== false) {
            $line = substr($buffer, 0, $end);
            $buffer = substr($buffer, $end + 1);
            if (str_starts_with($line, "event: ")) {
                $event = substr($line, 7);
            } elseif (str_starts_with($line, "data: ")) {
                $data = substr($line, 6);
                if ($event === "delta") {
                    echo json_decode($data, true)["text"];
                } elseif ($event === "done") {
                    echo "\n", $data, "\n";
                } elseif ($event === "error") {
                    fwrite(STDERR, $data . "\n");
                    $failed = true;
                }
            }
        }
        return strlen($chunk);
    },
]);
curl_exec($curl);
if ($failed || curl_getinfo($curl, CURLINFO_RESPONSE_CODE) >= 400) {
    fwrite(STDERR, $buffer . "\n");
    exit(1);
}
```
