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

> ## Agent Instructions
> Phaseo Gateway base URL: https://api.phaseo.app/v1. Send `Authorization: Bearer $PHASEO_API_KEY` with every request.
> Model IDs look like `provider/model`, for example `openai/gpt-6-astra`. Do not guess IDs: list them with `GET /v1/models` or check https://phaseo.app/models. `phaseo/free` routes to an available free model and needs no wallet balance.
> For new text integrations prefer `POST /v1/responses`. `POST /v1/chat/completions` (OpenAI format) and `POST /v1/messages` (Anthropic format) suit existing code.
> The full API contract is https://phaseo.app/docs/openapi/v1/openapi.yaml. Official SDKs: `@phaseo/sdk` (TypeScript) and `phaseo` (Python), plus Go, C#, PHP, Ruby and Rust.
> Search these docs over MCP at https://phaseo.app/docs/mcp, and install Phaseo skills with `npx skills add https://phaseo.app/docs`. If a page is wrong or out of date, report it with the MCP `submit_feedback` tool.
> Manage Phaseo accounts with the `phaseo` CLI (`npm install -g @phaseo/cli`, then `phaseo login` or `phaseo login --device-code`), the `/v1` Management API or the MCP server at `https://mcp.phaseo.app/mcp?access=manage`. Do not send users to the dashboard for account tasks. A person is still needed for sign-up, approving a sign-in, paying the first top-up on the checkout link that `phaseo credits add` returns when no card is saved, confirming each saved-card top-up from the emailed link, and account security (password, MFA, passkeys). Create API keys with `phaseo keys create --name <name> --json`; never guess one. Credit top-ups need `phaseo login --scopes billing:write` first. Task map: https://phaseo.app/docs/v1/developers/manage-from-an-agent.md.

# Archivos

> Sube archivos de entrada de lotes y vuelve a leerlos por ID desde cualquier SDK de Phaseo.

Sube un archivo de entrada de lotes como formulario multipart, guarda el `id` que devuelve y vuelve a leer los metadatos y los bytes del archivo con ese ID. Los ejemplos usan un `client` creado como en [Instalación](https://phaseo.app/docs/es/v1/sdk-reference/client/installation.md).

## Sube un archivo

TypeScript y Python suben el archivo con un método del SDK, que envía `POST /v1/batches/files`. Los demás SDK no pueden enviar multipart, así que envían el formulario a `POST /v1/files` con el cliente HTTP estándar.

```typescript TypeScript theme={null}
const uploaded = await client.uploadFile({
  purpose: "batch",
  file: new Blob(["{}"], { type: "application/json" }),
  filename: "batch.jsonl",
});
```

```python Python theme={null}
from pathlib import Path

uploaded = client.upload_file(
    purpose="batch",
    file=Path("batch.jsonl"),
    content_type="application/json",
)
```

```go Go theme={null}
// El wrapper de Go no tiene método de subida, así que envía el formulario con net/http y mime/multipart.
var body bytes.Buffer
form := multipart.NewWriter(&body)
_ = form.WriteField("purpose", "batch")
part, _ := form.CreateFormFile("file", "batch.jsonl")
data, _ := os.ReadFile("batch.jsonl")
_, _ = part.Write(data)
_ = form.Close()

req, _ := http.NewRequest("POST", "https://api.phaseo.app/v1/files", &body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("PHASEO_API_KEY"))
req.Header.Set("Content-Type", form.FormDataContentType())

resp, err := http.DefaultClient.Do(req) // guarda el id que devuelve
```

```csharp C# theme={null}
// UploadFile() envía JSON, así que envía el formulario con HttpClient.
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization =
    new("Bearer", Environment.GetEnvironmentVariable("PHASEO_API_KEY"));

using var form = new MultipartFormDataContent
{
    { new StringContent("batch"), "purpose" },
    { new ByteArrayContent(await File.ReadAllBytesAsync("batch.jsonl")), "file", "batch.jsonl" },
};

var uploaded = await http.PostAsync("https://api.phaseo.app/v1/files", form);
Console.WriteLine(await uploaded.Content.ReadAsStringAsync()); // guarda el id que devuelve
```

```php PHP theme={null}
// uploadFile() envía JSON, así que envía el formulario con Guzzle.
$http = new GuzzleHttp\Client();

$uploaded = $http->post('https://api.phaseo.app/v1/files', [
    'headers' => ['Authorization' => 'Bearer ' . getenv('PHASEO_API_KEY')],
    'multipart' => [
        ['name' => 'purpose', 'contents' => 'batch'],
        ['name' => 'file', 'contents' => fopen('batch.jsonl', 'r'), 'filename' => 'batch.jsonl'],
    ],
]);

$fileId = json_decode((string) $uploaded->getBody(), true)['id'];
```

```ruby Ruby theme={null}
# upload_file envía JSON, así que envía el formulario con Net::HTTP.
require 'net/http'
require 'json'

uri = URI('https://api.phaseo.app/v1/files')
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{ENV.fetch('PHASEO_API_KEY')}"
request.set_form([['purpose', 'batch'], ['file', File.open('batch.jsonl')]], 'multipart/form-data')

response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
file_id = JSON.parse(response.body)['id']
```

```java Java theme={null}
// Los helpers JSON del SDK no codifican multipart, así que envía el formulario con java.net.http.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Path;
import java.time.Duration;
import java.util.UUID;

String baseUrl = System.getenv().getOrDefault("PHASEO_BASE_URL", "https://api.phaseo.app/v1")
    .replaceAll("/+$", "");
String apiKey = System.getenv("PHASEO_API_KEY");
String boundary = "phaseo-" + UUID.randomUUID();
var body = BodyPublishers.concat(
    BodyPublishers.ofString("--" + boundary + "\r\nContent-Disposition: form-data; name=\"purpose\"\r\n\r\nbatch\r\n"),
    BodyPublishers.ofString("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"batch.jsonl\"\r\nContent-Type: application/jsonl\r\n\r\n"),
    BodyPublishers.ofFile(Path.of("batch.jsonl")),
    BodyPublishers.ofString("\r\n--" + boundary + "--\r\n")
);
var request = HttpRequest.newBuilder(URI.create(baseUrl + "/files"))
    .header("Authorization", "Bearer " + apiKey)
    .header("Content-Type", "multipart/form-data; boundary=" + boundary)
    .timeout(Duration.ofSeconds(60))
    .POST(body)
    .build();
var response = HttpClient.newHttpClient().send(request, BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
    throw new IOException("HTTP " + response.statusCode() + ": " + response.body());
}
System.out.println(response.body()); // guarda el id que devuelve
```

### Opciones de subida

Se aplican a los métodos de subida de TypeScript y Python. En las solicitudes multipart directas, envía `purpose` y `file` como campos del formulario.

| TypeScript | Python | Notas |
| - | - | - |
| `file` | `file` | Obligatorio. TypeScript: un `Blob`, `File`, `BufferSource` o cadena. Python: `bytes`, un `Path`, un objeto de archivo o una tupla de archivo de HTTPX; una cadena simple lanza `TypeError`. |
| `purpose` | `purpose` | Por ejemplo, `batch`. |
| `filename`, `contentType` | `filename`, `content_type` | Nombre y tipo de medio de la subida. En Python, un `Path` usa su propio nombre de archivo. |
| `model`, `provider` | ninguno | Solo TypeScript. Eligen el proveedor de lotes que guarda el archivo. Sin ninguno de los dos, el archivo va a OpenAI. Las subidas de Python siempre van al proveedor de lotes predeterminado, OpenAI. |

## Vuelve a leer un archivo

```typescript TypeScript theme={null}
const file = await client.getFile(uploaded.id);
const content = await client.getFileContent(uploaded.id); // Uint8Array
```

```python Python theme={null}
file_obj = client.get_file(uploaded["id"])
file_bytes = client.get_file_content(uploaded["id"])  # bytes
```

```go Go theme={null}
file, err := client.RetrieveFile(context.Background(), "file_123")
if err != nil {
  panic(err)
}

content, err := client.RetrieveFileContent(context.Background(), "file_123") // []byte
if err != nil {
  panic(err)
}

fmt.Println(file)
fmt.Println(string(content))
```

```csharp C# theme={null}
var file = await client.RetrieveFile("file_123");
byte[] content = await client.RetrieveFileContent("file_123");
```

```php PHP theme={null}
$file = $client->retrieveFile('file_123');
$content = $client->retrieveFileContent('file_123');
```

```ruby Ruby theme={null}
file = client.retrieve_file('file_123')
content = client.retrieve_file_content('file_123')
```

```java Java theme={null}
import java.nio.charset.StandardCharsets;

var file = client.retrieveFile("file_123");
byte[] content = client.retrieveFileContent("file_123");
System.out.println(file);
System.out.println(new String(content, StandardCharsets.UTF_8));
```

Sustituye `file_123` por el ID que devolvió la subida.

| Lenguaje | Metadatos | Contenido | Método de subida | Listar |
| - | - | - | - | - |
| TypeScript | `getFile(id)` | `getFileContent(id)`, un `Uint8Array` | `uploadFile(...)`, multipart | `listFiles()` |
| Python | `get_file(id)` | `get_file_content(id)`, `bytes` | `upload_file(...)`, multipart | `list_files()` |
| Go | `RetrieveFile(ctx, id)` | `RetrieveFileContent(ctx, id)`, `[]byte` | Ninguno | `ListFiles(ctx, query)` |
| C# | `RetrieveFile(id)` | `RetrieveFileContent(id)`, `byte[]` | `UploadFile(request)` envía JSON, así que no puede subir archivos | `ListFiles(query)` |
| PHP | `retrieveFile($id)` | `retrieveFileContent($id)` | `uploadFile($payload)` envía JSON, así que no puede subir archivos | `listFiles($params)` |
| Ruby | `retrieve_file(id)` | `retrieve_file_content(id)` | `upload_file(payload)` envía JSON, así que no puede subir archivos | `list_files(...)` |
| Java | `retrieveFile(id)` | `retrieveFileContent(id)`, `byte[]` | `uploadFile(request)` envía JSON, así que no puede subir archivos | `listFiles(query)` |

En Python también puedes usarlas a través de `client.files`: `create(params)` sube el archivo igual que `upload_file`, `list()` lista, `retrieve(id)` lee los metadatos y `content(id)` lee los bytes. Rust no tiene métodos de archivos.

> [!NOTE]
>
> Los endpoints de archivos están en beta y necesitan un proveedor de lotes habilitado.

## Guarda el ID del archivo: no puedes listar archivos

Guarda el `id` de cada archivo subido. Los métodos de listado llaman a `GET /v1/files`, que devuelve `400` con el código `not_supported` y el motivo `file_list_not_supported_with_shared_gateway_key`. El contrato completo está en la [referencia de la API de archivos](https://phaseo.app/docs/es/v1/api-reference/endpoint/files.md).

## Respuesta

`FileObject`, de la subida y de los métodos de metadatos:

```json theme={null}
{
  "id": "file-123",
  "object": "file",
  "filename": "data.json",
  "purpose": "batch",
  "status": "processed",
  "created_at": 1677610602,
  "bytes": 123
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.