# Upload a picture

> POST /v1/attachments

Upload a picture to send with a chat message, as `multipart/form-data` with the `agent_id` and the `file`. Send its `id` in the message's `attachment_ids`. A picture nobody sends is deleted after six hours. Needs `chats:write`.

## Body

Sent as `multipart/form-data`.

| Field | Type | Required | Description |
|---|---|---|---|
| `agent_id` | string (uuid) | Yes | The agent the picture is for. |
| `file` | string | Yes | A JPEG, PNG, WebP or GIF. |

## Answer

`201` with [Attachment](/reference/objects/Attachment).

## Errors

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

| Status | When |
|---|---|
| `401` | The key is missing, mistyped, unknown, revoked or expired. |
| `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 agent. |
| `409` | The project is frozen. |
| `413` | The picture is larger than the agent accepts. |
| `422` | The agent does not accept pictures, or the file is not one. |
| `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
# Upload a picture to send. Send the id it returns in a message's attachment_ids.
curl -sS --fail-with-body -X POST "https://api.aigently.ai/v1/attachments" \
  -H "Authorization: Bearer $AIGENTLY_API_KEY" \
  -F "agent_id=3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f" \
  -F "file=@photo.jpg;type=image/jpeg"
```

**JavaScript**

```js
import { readFile } from "node:fs/promises";

// Upload a picture to send. Send the id it returns in a message's attachment_ids.
const form = new FormData();
form.append("agent_id", "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f");
form.append("file", new Blob([await readFile("photo.jpg")], { type: "image/jpeg" }), "photo.jpg");

const response = await fetch("https://api.aigently.ai/v1/attachments", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.AIGENTLY_API_KEY}`,
  },
  body: form,
});
const answer = await response.json();
if (!response.ok) throw new Error(`${answer.code}: ${answer.detail}`);
console.log(answer);
```

**Python**

```python
# Upload a picture to send. Send the id it returns in a message's attachment_ids.
# pip install httpx
import os

import httpx

with open("photo.jpg", "rb") as upload:
    response = httpx.post(
        "https://api.aigently.ai/v1/attachments",
        headers={
            "Authorization": f"Bearer {os.environ['AIGENTLY_API_KEY']}",
        },
        data={
            "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
        },
        files={"file": ("photo.jpg", upload, "image/jpeg")},
    )
if response.is_error:
    raise SystemExit(response.text)
print(response.json())
```

**Go**

```go
// Upload a picture to send. Send the id it returns in a message's attachment_ids.
package main

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

func main() {
	var form bytes.Buffer
	writer := multipart.NewWriter(&form)
	writer.WriteField("agent_id", "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f")
	part, _ := writer.CreateFormFile("file", "photo.jpg")
	contents, err := os.ReadFile("photo.jpg")
	if err != nil {
		panic(err)
	}
	part.Write(contents)
	writer.Close()
	request, err := http.NewRequest("POST", "https://api.aigently.ai/v1/attachments", &form)
	if err != nil {
		panic(err)
	}
	request.Header.Set("Authorization", "Bearer "+os.Getenv("AIGENTLY_API_KEY"))
	request.Header.Set("Content-Type", writer.FormDataContentType())
	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
// Upload a picture to send. Send the id it returns in a message's attachment_ids.
import java.io.ByteArrayOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
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 boundary = Long.toHexString(System.nanoTime());
        ByteArrayOutputStream form = new ByteArrayOutputStream();
        form.write(("--" + boundary
            + "\r\nContent-Disposition: form-data; name=\"agent_id\"\r\n\r\n3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f\r\n--" + boundary
            + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"photo.jpg\"\r\n"
            + "Content-Type: image/jpeg\r\n\r\n").getBytes());
        form.write(Files.readAllBytes(Path.of("photo.jpg")));
        form.write(("\r\n--" + boundary + "--\r\n").getBytes());
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.aigently.ai/v1/attachments"))
            .header("Authorization", "Bearer " + System.getenv("AIGENTLY_API_KEY"))
            .header("Content-Type", "multipart/form-data; boundary=" + boundary)
            .method("POST", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray()))
            .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
// Upload a picture to send. Send the id it returns in a message's attachment_ids.
using System.Net.Http.Headers;
using System.Text;

var form = new MultipartFormDataContent();
form.Add(new StringContent("3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f"), "agent_id");
var upload = new ByteArrayContent(File.ReadAllBytes("photo.jpg"));
upload.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
form.Add(upload, "file", "photo.jpg");

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/attachments")
{
    Content = form,
};
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
// Upload a picture to send. Send the id it returns in a message's attachment_ids.
$curl = curl_init("https://api.aigently.ai/v1/attachments");
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("AIGENTLY_API_KEY"),
    ],
    CURLOPT_POSTFIELDS => [
        "agent_id" => "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
        "file" => new CURLFile("photo.jpg", "image/jpeg"),
    ],
]);
$body = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_RESPONSE_CODE) >= 400) {
    fwrite(STDERR, $body . "\n");
    exit(1);
}
echo $body, "\n";
```
