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

# Recursos avançados

Este documento aborda recursos avançados e melhores práticas para o Novita Agent Runtime.

***

## Sumário

* [Referência do arquivo de configuração](#configuration-file-reference)
* [Gerenciamento de Variáveis de Ambiente](#environment-variables-management)
* [Respostas em Streaming](#streaming-responses)
* [Gerenciamento de versões](#version-management)
* [Verificações de integridade](#health-checks)
* [Conversas com múltiplos turnos](#multi-turn-conversations)
* [Projetos de exemplo](#example-projects)

***

## Referência do Arquivo de Configuração

### Estrutura do .novita-agent.yaml

O `.novita-agent.yaml` o arquivo de configuração usa o formato YAML no estilo do Kubernetes:

```yaml theme={"system"}
apiVersion: v1
kind: Agent
metadata:
  name: my-agent              # Agent name (must consist of lowercase letters, numbers, and hyphens only)
  version: 1.0.0              # Agent version (semantic versioning)
  author: dev@example.com     # Author email (required)
  description: My AI Agent    # Agent description (optional)
  created: '2025-10-23T10:30:00Z'  # Creation time (auto-generated)

spec:
  entrypoint: app.py          # Python entry file (must be .py file)
  
  # Environment variables configuration (optional)
  envVars:
    MODEL_NAME: deepseek/deepseek-v3-0324
    TEMPERATURE: '0.7'
  
  # Runtime configuration (optional, applied to the built sandbox template)
  runtime:
    timeout: 300              # Startup timeout in seconds (1-3600, default 300)
    memory_limit: 1Gi         # Memory limit (supports "512Mi", "1Gi", etc.)
    cpu_limit: '1'            # CPU limit (supports "1", "1000m", etc.)

# Status field (maintained by the system, should not be modified manually by users)
status:
  phase: deployed             # Current phase: pending/building/deployed/failed
  agent_id: agent-xxxxx       # Agent ID (auto-generated after deployment)
  last_deployed: '2025-10-23T10:35:00Z'  # Last deployment time
  build_id: build_xyz789      # Build ID (auto-generated after deployment)
```

### Modificando a configuração

#### Modificando as configurações de CPU e memória

Modifique a configuração de recursos em `spec.runtime` em `.novita-agent.yaml`:

```yaml theme={"system"}
spec:
  runtime:
    # CPU configuration
    cpu_limit: '2'        # 2 CPU cores
    # Memory configuration
    memory_limit: 2Gi     # 2 GB memory
```

#### Modificando variáveis de ambiente

O `spec.envVars` em `.novita-agent.yaml` é usado apenas para a CLI `agent invoke` comando e não será passado para o template de sandbox implantado.

Modifique as variáveis de ambiente em `spec.envVars` em `.novita-agent.yaml`:

```yaml theme={"system"}
spec:
  envVars:
    # LLM configuration
    MODEL_NAME: deepseek/deepseek-v3-0324
    TEMPERATURE: '0.7'
```

**Observação**:

* ⚠️ **Não armazene informações confidenciais** (como chaves de API) em `.novita-agent.yaml`
* Você também pode passar variáveis de ambiente por meio do `--env` parâmetro ao executar o `agent invoke` comando

#### Reimplante para aplicar alterações de configuração

Após modificar as especificações de recursos em `.novita-agent.yaml`, é necessário fazer o redeploy:

```bash theme={"system"}
# Redeploy (creates a new version)
npx novita-sandbox-cli agent launch
```

***

## Gerenciamento de Variáveis de Ambiente

Há várias maneiras de passar variáveis de ambiente para Agents em execução em instâncias de sandbox:

### Método 1: Definir no Arquivo de Configuração (somente invocação via CLI)

Defina variáveis de ambiente em `spec.envVars` em `.novita-agent.yaml`:

```yaml theme={"system"}
spec:
  envVars:
    MODEL_NAME: deepseek/deepseek-v3-0324
    TEMPERATURE: '0.7'
```

### Método 2: Passe dinamicamente via SDK

Ao invocar um Agent usando o SDK `invoke_agent_runtime` método, passe-os dinamicamente via o `envVars` parâmetro:

```python theme={"system"}
import os
from novita_sandbox.agent_runtime import AgentRuntimeClient

client = AgentRuntimeClient(api_key=os.getenv("NOVITA_API_KEY"))

response = await client.invoke_agent_runtime(
    agentId="agent-xxxxx",
    payload=payload,
    envVars={
        # Read sensitive information from environment variables
        "NOVITA_API_KEY": os.getenv("NOVITA_API_KEY"),
        "DATABASE_PASSWORD": os.getenv("DATABASE_PASSWORD"),
        
        # Or pass directly
        "MODEL_NAME": "deepseek/deepseek-v3-0324",
        "TEMPERATURE": "0.7"
    }
)
```

***

## Respostas em streaming

### Implementando streaming com geradores síncronos

Use geradores do Python para implementar respostas em streaming:

```python theme={"system"}
from novita_sandbox.agent_runtime import AgentRuntimeApp

app = AgentRuntimeApp()

@app.entrypoint
def streaming_agent(request: dict):
    """Synchronous streaming response"""
    prompt = request.get("prompt", "")

    # Use generator to return chunks
    for i, chunk in enumerate(generate_response(prompt)):
        yield {
            "chunk": chunk,
            "type": "content",
            "index": i
        }
    # Send end marker
    yield {"chunk": "", "type": "end"}

```

### Implementando streaming com geradores assíncronos

Use geradores assíncronos do Python:

```python theme={"system"}
import asyncio

@app.entrypoint
async def async_streaming_agent(request: dict):
    """Async streaming response"""
    prompt = request.get("prompt", "")

    async for chunk in async_generate_response(prompt):
        yield {
            "chunk": chunk,
            "type": "content"
        }
    yield {"chunk": "", "type": "end"}

```

### Exemplo de resposta em streaming com LangChain

Exemplo completo usando LangChain para respostas em streaming:

```python theme={"system"}
import os
from langchain_openai import ChatOpenAI
from langchain.callbacks.base import BaseCallbackHandler
from novita_sandbox.agent_runtime import AgentRuntimeApp

app = AgentRuntimeApp()

class StreamingHandler(BaseCallbackHandler):
    """Streaming callback handler"""
    def __init__(self):
        self.tokens = []
    
    def on_llm_new_token(self, token: str, **kwargs):
        self.tokens.append(token)

@app.entrypoint
def langchain_streaming_agent(request: dict):
    """LangChain streaming response"""
    prompt = request.get("prompt", "")

    # Create streaming-enabled LLM
    llm = ChatOpenAI(
        api_key=os.getenv("NOVITA_API_KEY"),
        streaming=True
    )
    
    # Stream invocation
    for chunk in llm.stream(prompt):
        if chunk.content:
            yield {
                "chunk": chunk.content,
                "type": "content"
            }
    yield {"chunk": "", "type": "end"}
```

### Invocando um Agent de streaming

Invoque um Agent de streaming usando o SDK:

```python theme={"system"}
import asyncio
import json
import os
from novita_sandbox.agent_runtime import AgentRuntimeClient

async def call_streaming_agent():
    client = AgentRuntimeClient(api_key=os.getenv("NOVITA_API_KEY"))
    
    payload = json.dumps({
        "prompt": "Tell me a story"
    }).encode()
    
    response = await client.invoke_agent_runtime(
        agentId="agent-xxxxx",
        payload=payload
    )
    
    # Process streaming response
    print("Streaming response:")
    print(response)
```

***

## Gerenciamento de versões

### Implantando uma nova versão do agente

Modifique o número da versão e implante uma nova versão:

```bash theme={"system"}
# Modify version number
npx novita-sandbox-cli agent configure --agent-version 1.1.0

# Deploy new version
npx novita-sandbox-cli agent launch
```

Após a implantação bem-sucedida, um novo `agent_id` é gerado. Cada implantação gera um único `agent_id` que corresponde a uma versão específica.

***

## Verificações de integridade

### Endpoint padrão de verificação de integridade

AgentRuntimeApp fornece automaticamente um `/ping` endpoint de verificação de integridade:

```python theme={"system"}
from novita_sandbox.agent_runtime import AgentRuntimeApp

app = AgentRuntimeApp()

# Default health check automatically responds with {"status": "Healthy"}
```

### Verificações de integridade personalizadas

Use o `@app.ping` decorador para personalizar a lógica de verificação de integridade:

```python theme={"system"}
@app.ping
def custom_health_check():
    """Custom health check"""
    # Check dependent services
    db_ok = check_database_connection()
    llm_ok = check_llm_service()
    
    if db_ok and llm_ok:
        return {"status": "Healthy"}
    elif db_ok or llm_ok:
        return {"status": "HealthyBusy"}  # Partially available
    else:
        return {"status": "Unhealthy"}  # Unavailable

def check_database_connection():
    """Check database connection"""
    try:
        # Simulate database check
        return True
    except:
        return False

def check_llm_service():
    """Check LLM service"""
    try:
        # Simulate LLM service check
        return True
    except:
        return False
```

### Status de verificação de integridade compatíveis

Agentes podem retornar os seguintes status de integridade:

\| Status | Descrição | Código de status HTTP |
\|--------|-------------|------------------| `Healthy` | Agente está totalmente disponível | 200 | `HealthyBusy` | O agente está parcialmente disponível (por exemplo, processando uma carga pesada) | 200 | `Unhealthy` | Agente indisponível | 503 |

***

## Conversas com múltiplos turnos

### Usando ID de sessão para conversas com múltiplos turnos

Use o `runtimeSessionId` parâmetro para rotear várias solicitações para a mesma instância de sandbox:

```python theme={"system"}
import uuid
import json
import os
from novita_sandbox.agent_runtime import AgentRuntimeClient

async def multi_turn_conversation():
    runtime_session_id = str(uuid.uuid4())
    client = AgentRuntimeClient(api_key=os.getenv("NOVITA_API_KEY"))
    agent_id = "agent-xxxxx"
    
    # First turn
    response1 = await client.invoke_agent_runtime(
        agentId=agent_id,
        payload=json.dumps({"prompt": "Hello, my name is John"}).encode(),
        runtimeSessionId=runtime_session_id,
    )
    print(f"AI: {response1}")
    
    # Second turn (sent to the same sandbox instance, Agent remembers the context)
    response2 = await client.invoke_agent_runtime(
        agentId=agent_id,
        payload=json.dumps({"prompt": "What's my name?"}).encode(),
        runtimeSessionId=runtime_session_id,
    )
    print(f"AI: {response2}")  # Should answer "John"
```

***

## Projetos de Exemplo

Fornecemos um projeto de exemplo completo baseado no LangGraph, demonstrando como criar aplicações reais de IA com o Novita Agent Runtime.

### Repositório do Projeto

🔗 [https://github.com/novitalabs/Novita-CollabHub/tree/main/examples/agent-runtime/agentic-frameworks/langgraph](https://github.com/novitalabs/Novita-CollabHub/tree/main/examples/agent-runtime/agentic-frameworks/langgraph)
