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

# Servir Modelos

> Sirva modelos treinados como APIs

# Servir Modelos

Sirva seus modelos treinados para inferência em produção.

## Interface de Chat

A forma mais simples de testar e interagir com modelos:

```bash theme={null}
aitraining chat
```

Abre uma interface web em `http://localhost:7860/inference`. O Chat UI permite carregar qualquer modelo local ou do Hub para testes interativos.

### Porta Customizada

```bash theme={null}
aitraining chat --port 3000
```

### Host Customizado

```bash theme={null}
aitraining chat --host 0.0.0.0
```

## Servidor de API

O servidor de API é um **executor de treinamento**, não um servidor de inferência. Expõe endpoints mínimos para verificações de saúde enquanto executa trabalhos de treinamento.

### Iniciar Servidor de API

```bash theme={null}
aitraining api
```

Inicia a API de treinamento em `http://127.0.0.1:7860` por padrão.

### Parâmetros

| Parameter | Description            | Default     |
| --------- | ---------------------- | ----------- |
| `--port`  | Port to run the API on | `7860`      |
| `--host`  | Host to bind to        | `127.0.0.1` |
| `--task`  | Task to run (optional) | `None`      |

### Porta/Host Customizados

```bash theme={null}
aitraining api --port 8000 --host 0.0.0.0
```

### Variáveis de Ambiente

O servidor de API lê configuração de variáveis de ambiente:

| Variable             | Description                           |
| -------------------- | ------------------------------------- |
| `HF_TOKEN`           | Hugging Face token for authentication |
| `AUTOTRAIN_USERNAME` | Username for training                 |
| `PROJECT_NAME`       | Name of the project                   |
| `TASK_ID`            | Task identifier                       |
| `PARAMS`             | Training parameters (JSON)            |
| `DATA_PATH`          | Path to training data                 |
| `MODEL`              | Model to use                          |

### Endpoints

| Endpoint      | Description                     |
| ------------- | ------------------------------- |
| `GET /`       | Returns training status message |
| `GET /health` | Health check (returns "OK")     |

<Note>
  O servidor de API desliga automaticamente quando não há trabalhos de treinamento ativos. Para inferência em produção, use vLLM ou TGI.
</Note>

## Deploy em Produção

### Usando vLLM

Para servir de nível de produção com alta taxa de transferência:

```bash theme={null}
pip install vllm

python -m vllm.entrypoints.openai.api_server \
  --model ./my-trained-model \
  --port 8000
```

### Usando Text Generation Inference (TGI)

```bash theme={null}
docker run --gpus all -p 8080:80 \
  -v ./my-model:/model \
  ghcr.io/huggingface/text-generation-inference:latest \
  --model-id /model
```

### API Compatível com OpenAI

Tanto vLLM quanto TGI fornecem endpoints compatíveis com OpenAI:

```python theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="dummy"  # Not needed for local
)

response = client.chat.completions.create(
    model="my-model",
    messages=[
        {"role": "user", "content": "Hello!"}
    ]
)
```

## Deploy Docker

### Exemplo de Dockerfile

```dockerfile theme={null}
FROM python:3.10-slim

WORKDIR /app

# Install dependencies
RUN pip install aitraining torch

# Expose port
EXPOSE 7860

# Run chat server
CMD ["aitraining", "chat", "--host", "0.0.0.0", "--port", "7860"]
```

Construir e executar:

```bash theme={null}
docker build -t my-model-server .
docker run -p 7860:7860 my-model-server
```

### Com GPU

```bash theme={null}
docker run --gpus all -p 7860:7860 my-model-server
```

## Teste de Carga

### Usando hey

```bash theme={null}
hey -n 100 -c 10 \
  -m POST \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Hello", "max_tokens": 50}' \
  http://localhost:8000/generate
```

### Usando locust

```python theme={null}
# locustfile.py
from locust import HttpUser, task

class ModelUser(HttpUser):
    @task
    def generate(self):
        self.client.post("/generate", json={
            "prompt": "Hello, how are you?",
            "max_tokens": 50
        })
```

```bash theme={null}
locust -f locustfile.py --host http://localhost:8000
```

## Monitoramento

### Métricas Prometheus

Se usar vLLM ou TGI, métricas estão disponíveis em `/metrics`.

### Logging

```bash theme={null}
aitraining api --port 8000 2>&1 | tee server.log
```

## Próximos Passos

<CardGroup cols={2}>
  <Card title="Benchmarking" href="/cli/benchmarking">
    Meça o desempenho do modelo
  </Card>

  <Card title="Interface de Chat" href="/chat/launching">
    Testes interativos
  </Card>
</CardGroup>
