> ## 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.

# Início rápido

> Crie uma chave de API e faça sua primeira solicitação à Phaseo com um modelo de texto atual.

Use este tutorial para fazer uma solicitação bem-sucedida ao Phaseo, com texto gerado ou uma decisão estruturada, e confirmar onde a resposta aparece.

<Note>
  **Usando um agente de programação?** Copie e cole este prompt antes de começar:

  ```text theme={null}
  You are integrating this project with Phaseo Gateway. Read the Phaseo agent guidance at https://phaseo.app/docs/skill.md and the relevant API reference before editing anything. Inspect the existing provider configuration and identify the smallest safe change needed. Use https://api.phaseo.app with a server-side PHASEO_API_KEY, preserve the current provider/model behavior unless I explicitly ask for a migration, and never print or commit credentials. Explain the files you would change and the verification commands first. Do not deploy, rotate keys, send external messages, or make unrelated edits without my approval.
  ```
</Note>

Você vai:

* criar uma chave de API
* enviar uma solicitação de texto ou decisão estruturada
* ler o texto gerado ou respostas tipadas
* saber o que verificar primeiro se a solicitação falhar

***

## 1. Crie uma chave de API

1. Abra o [painel da Phaseo](https://phaseo.app/gateway/keys).
2. Crie uma chave em **Gateway -> Chaves**.
3. Copie-a uma única vez e guarde-a em um local seguro.

Use este formato:

```http theme={null}
Authorization: Bearer phaseo_v1_sk_<kid>_<secret>
```

<Danger>
  Trate sua chave de API como uma senha. Não a exponha em código executado no cliente.
</Danger>

***

## 2. Envie uma solicitação de texto

Use `POST /v1/responses` na primeira solicitação. Esse é o endpoint recomendado para novas integrações de geração de texto.

### Solicitação

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.phaseo.app/v1/responses \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "openai/gpt-6-astra",
      "input": "Reply with: quickstart works"
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://api.phaseo.app/v1/responses", {
    method: "POST",
    headers: {
      Authorization: "Bearer YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "openai/gpt-6-astra",
      input: "Reply with: quickstart works",
    }),
  });

  const data = await response.json();
  const assistantText = data.output
    ?.find((item) => item.type === "message")
    ?.content?.find((part) => part.type === "output_text")
    ?.text;

  console.log(assistantText);
  ```

  ```typescript TypeScript SDK theme={null}
  import Phaseo from "@phaseo/sdk";

  const client = new Phaseo({ apiKey: process.env.PHASEO_API_KEY! });

  const response = await client.generateResponse({
    model: "openai/gpt-6-astra",
    input: "Reply with: quickstart works",
  });

  const assistantText = response.output
    ?.find((item: any) => item.type === "message")
    ?.content?.find((part: any) => part.type === "output_text")
    ?.text;

  console.log(assistantText);
  ```

  ```python Python SDK theme={null}
  from phaseo import Phaseo

  client = Phaseo(api_key="YOUR_API_KEY")

  response = client.generate_response(
      {
          "model": "openai/gpt-6-astra",
          "input": "Reply with: quickstart works",
      }
  )

  assistant_text = next(
      (
          part.get("text")
          for item in response.get("output", [])
          if item.get("type") == "message"
          for part in item.get("content", [])
          if part.get("type") == "output_text"
      ),
      None,
  )

  print(assistant_text)
  ```

  ```go Go SDK theme={null}
  package main

  import (
    "context"
    "fmt"

    phaseo "github.com/phaseoteam/Phaseo/packages/sdk/sdk-go/v3"
  )

  func main() {
    client := phaseo.New("YOUR_API_KEY", "https://api.phaseo.app/v1")
    input := map[string]interface{}{
      "role": "user",
      "content": []map[string]interface{}{
        {
          "type": "input_text",
          "text": "Reply with: quickstart works",
        },
      },
    }

    response, err := client.GenerateResponse(context.Background(), phaseo.ResponsesRequest{
      Model: "openai/gpt-6-astra",
      Input: &input,
    })
    if err != nil {
      panic(err)
    }

    fmt.Println(response)
  }
  ```

  ```csharp C# SDK theme={null}
  using PhaseoSdk;
  using System.Collections.Generic;

  var client = new Phaseo("YOUR_API_KEY");

  var response = await client.GenerateResponse(new Dictionary<string, object>
  {
      ["model"] = "openai/gpt-6-astra",
      ["input"] = "Reply with: quickstart works",
  });

  Console.WriteLine(response);
  ```

  ```php PHP SDK theme={null}
  <?php
  require 'vendor/autoload.php';

  use Phaseo\Sdk\Phaseo;

  $client = new Phaseo(getenv('PHASEO_API_KEY') ?: 'YOUR_API_KEY');

  $response = $client->generateResponse([
      'model' => 'openai/gpt-6-astra',
      'input' => 'Reply with: quickstart works',
  ]);

  print_r($response);
  ```

  ```ruby Ruby SDK theme={null}
  require 'phaseo_sdk'

  client = PhaseoSdk::Phaseo.new(api_key: ENV.fetch('PHASEO_API_KEY', 'YOUR_API_KEY'))

  response = client.generate_response(
    model: 'openai/gpt-6-astra',
    input: 'Reply with: quickstart works',
  )

  puts response
  ```

  ```rust Rust SDK theme={null}
  use phaseo::Phaseo;
  use serde_json::{json, Value};

  fn main() -> Result<(), Box<dyn std::error::Error>> {
      let client = Phaseo::from_env()?;
      let response = client.responses(&json!({
          "model": "openai/gpt-6-astra",
          "input": "Reply with: quickstart works"
      }))?;

      let assistant_text = response.body
          .get("output")
          .and_then(Value::as_array)
          .into_iter()
          .flatten()
          .filter(|item| item.get("type").and_then(Value::as_str) == Some("message"))
          .flat_map(|item| {
              item.get("content")
                  .and_then(Value::as_array)
                  .into_iter()
                  .flatten()
          })
          .find_map(|part| {
              (part.get("type").and_then(Value::as_str) == Some("output_text"))
                  .then(|| part.get("text").and_then(Value::as_str))
                  .flatten()
          })
          .unwrap_or("");

      println!("{assistant_text}");
      Ok(())
  }
  ```

  ```typescript Vercel AI SDK theme={null}
  import { phaseo } from "@phaseo/ai-sdk-provider";
  import { generateText } from "ai";

  const result = await generateText({
    model: phaseo("openai/gpt-6-astra"),
    prompt: "Reply with: quickstart works",
  });

  console.log(result.text);
  ```
</CodeGroup>

### Resposta

```json theme={null}
{
  "id": "resp_...",
  "object": "response",
  "created_at": 1730000000,
  "status": "completed",
  "completed_at": 1730000001,
  "model": "openai/gpt-6-astra",
  "output": [
    {
      "type": "message",
      "id": "msg_...",
      "status": "completed",
      "role": "assistant",
      "content": [{ "type": "output_text", "text": "quickstart works", "annotations": [] }]
    }
  ],
  "usage": {
    "input_tokens": 9,
    "output_tokens": 3,
    "total_tokens": 12
  },
  "error": null,
  "incomplete_details": null
}
```

Em chamadas diretas à Responses API, leia a resposta do assistente em `output[].content[]`, no item em que `type` é `output_text`.

Se usar o Vercel AI SDK, leia a resposta em `result.text`.

***

## 3. Tome uma decisão estruturada

Use `POST /v1/decisions` quando o aplicativo precisar de respostas tipadas em vez de texto gerado. O Phaseo oferece Jev 1.13 da TypeSafe com o ID `typesafe/jev-1.13.0`. Envie um valor `state` e uma ou mais perguntas nomeadas; cada resposta retorna com o mesmo nome.

<Note>
  Decisions é um recurso beta e pode exigir ativação no espaço de trabalho. Jev 1.13 custa \$0.042 por 1 milhão de tokens de entrada; tokens de saída são gratuitos.
</Note>

Execute estes exemplos no servidor com `PHASEO_API_KEY` definido. Nunca exponha uma chave de API do Gateway no código do navegador.

Os três tipos de pergunta são:

* `choice` seleciona uma opção de um mapa de critérios e retorna probabilidades e confiança.
* `noul` retorna uma probabilidade sim/não de 0 a 1.
* `score` avalia um array ordenado de critérios e retorna uma pontuação ponderada pela probabilidade.

Você pode combinar tipos de pergunta na mesma solicitação.

### Solicitação

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.phaseo.app/v1/decisions \
    -H "Authorization: Bearer $PHASEO_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "typesafe/jev-1.13.0",
      "state": {
        "customer_message": "I was charged twice and need help with a refund.",
        "account_tier": "pro",
        "days_waiting": 3
      },
      "questions": {
        "department": {
          "type": "choice",
          "instructions": "Which team should handle this request?",
          "criteria": {
            "billing": "Payments, invoices, refunds, and duplicate charges.",
            "support": "Product usage questions and troubleshooting.",
            "sales": "Upgrades and new accounts."
          }
        },
        "is_urgent": {
          "type": "noul",
          "instructions": "Does this request require urgent handling?",
          "criteria": {
            "true": "The customer is blocked or the issue is time-sensitive.",
            "false": "The request can follow the normal support queue."
          }
        },
        "customer_impact": {
          "type": "score",
          "instructions": "How severe is the customer impact?",
          "criteria": [
            "No impact",
            "Minor inconvenience",
            "Significant impact",
            "Service blocked"
          ]
        }
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://api.phaseo.app/v1/decisions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.PHASEO_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "typesafe/jev-1.13.0",
      state: {
        customer_message: "I was charged twice and need help with a refund.",
        account_tier: "pro",
        days_waiting: 3,
      },
      questions: {
        department: {
          type: "choice",
          instructions: "Which team should handle this request?",
          criteria: {
            billing: "Payments, invoices, refunds, and duplicate charges.",
            support: "Product usage questions and troubleshooting.",
            sales: "Upgrades and new accounts.",
          },
        },
        is_urgent: {
          type: "noul",
          instructions: "Does this request require urgent handling?",
          criteria: {
            true: "The customer is blocked or the issue is time-sensitive.",
            false: "The request can follow the normal support queue.",
          },
        },
        customer_impact: {
          type: "score",
          instructions: "How severe is the customer impact?",
          criteria: [
            "No impact",
            "Minor inconvenience",
            "Significant impact",
            "Service blocked",
          ],
        },
      },
    }),
  });

  if (!response.ok) throw new Error(await response.text());
  const data = await response.json();
  console.log(data.answers);
  ```

  ```typescript TypeScript SDK theme={null}
  import Phaseo from "@phaseo/sdk";

  const client = new Phaseo({ apiKey: process.env.PHASEO_API_KEY! });

  const decision = await client.decisions.make({
    model: "typesafe/jev-1.13.0",
    state: {
      customer_message: "I was charged twice and need help with a refund.",
      account_tier: "pro",
      days_waiting: 3,
    },
    questions: {
      department: {
        type: "choice",
        instructions: "Which team should handle this request?",
        criteria: {
          billing: "Payments, invoices, refunds, and duplicate charges.",
          support: "Product usage questions and troubleshooting.",
          sales: "Upgrades and new accounts.",
        },
      },
      is_urgent: {
        type: "noul",
        instructions: "Does this request require urgent handling?",
        criteria: {
          true: "The customer is blocked or the issue is time-sensitive.",
          false: "The request can follow the normal support queue.",
        },
      },
      customer_impact: {
        type: "score",
        instructions: "How severe is the customer impact?",
        criteria: [
          "No impact",
          "Minor inconvenience",
          "Significant impact",
          "Service blocked",
        ],
      },
    },
  });

  console.log(decision.answers);
  ```

  ```python Python SDK theme={null}
  from phaseo import Phaseo

  client = Phaseo()  # Uses PHASEO_API_KEY from the environment

  decision = client.decisions.make(
      {
          "model": "typesafe/jev-1.13.0",
          "state": {
              "customer_message": "I was charged twice and need help with a refund.",
              "account_tier": "pro",
              "days_waiting": 3,
          },
          "questions": {
              "department": {
                  "type": "choice",
                  "instructions": "Which team should handle this request?",
                  "criteria": {
                      "billing": "Payments, invoices, refunds, and duplicate charges.",
                      "support": "Product usage questions and troubleshooting.",
                      "sales": "Upgrades and new accounts.",
                  },
              },
              "is_urgent": {
                  "type": "noul",
                  "instructions": "Does this request require urgent handling?",
                  "criteria": {
                      "true": "The customer is blocked or the issue is time-sensitive.",
                      "false": "The request can follow the normal support queue.",
                  },
              },
              "customer_impact": {
                  "type": "score",
                  "instructions": "How severe is the customer impact?",
                  "criteria": [
                      "No impact",
                      "Minor inconvenience",
                      "Significant impact",
                      "Service blocked",
                  ],
              },
          },
      }
  )

  print(decision["answers"])
  ```
</CodeGroup>

### Resposta

```json theme={null}
{
  "model": "typesafe/jev-1.13.0",
  "answers": {
    "department": {
      "type": "choice",
      "choice": "billing",
      "probabilities": { "billing": 0.91, "support": 0.06, "sales": 0.03 },
      "confidence": 0.89
    },
    "is_urgent": {
      "type": "noul",
      "noul": 0.84
    },
    "customer_impact": {
      "type": "score",
      "score": 2.4,
      "legend": {
        "0": "No impact",
        "1": "Minor inconvenience",
        "2": "Significant impact",
        "3": "Service blocked"
      },
      "probabilities": { "0": 0.02, "1": 0.12, "2": 0.61, "3": 0.25 },
      "confidence": 0.76
    }
  },
  "usage": {
    "input_tokens": 42,
    "output_tokens": 18,
    "total_tokens": 60
  }
}
```

Leia o valor tipado da resposta correspondente ao ID da pergunta, por exemplo `answers.department.choice`, `answers.is_urgent.noul` ou `answers.customer_impact.score`. Use `confidence` e `probabilities` para definir um limite no aplicativo em vez de decidir apenas pelo valor.

Veja a [referência da API Decisions](./api-reference/endpoint/decisions) para o contrato completo de solicitação e resposta, e a [referência do modelo Jev](https://docs.typesafe.ai/models) da TypeSafe para comportamento e limites do provedor.

***

## 4. Resolva problemas na primeira solicitação

* `401`: confira a chave de API e o cabeçalho `Authorization`.
* `400`: confira o corpo da solicitação e o ID do modelo.
* `402`: troque para um modelo `:free` ou adicione créditos antes de usar um modelo pago.
* `429` ou `5xx`: tente novamente com espera exponencial.

Consulte a [referência de tratamento de erros](./api-reference/errors.mdx) para encontrar o problema rapidamente.

***

## 5. Se você estiver criando uma função de vídeo

A geração de vídeo é assíncrona. Primeiro crie um job e depois consulte o status ou assine para receber o resultado.

1. Crie um job com `POST /v1/videos`.
2. Consulte o status com `GET /v1/videos/{video_id}` até a conclusão.
3. Baixe o conteúdo com `GET /v1/videos/{video_id}/content`.

```bash theme={null}
# Create
curl https://api.phaseo.app/v1/videos \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "<video-model-id>",
    "prompt": "A cinematic sunrise over a mountain lake"
  }'

# Poll status
curl https://api.phaseo.app/v1/videos/VIDEO_ID \
  -H "Authorization: Bearer YOUR_API_KEY"
```

***

## 6. Continue desenvolvendo

<Columns cols={2}>
  <Card title="Integração com o Gateway" icon="plug" href="./developers/integrating-with-the-gateway.mdx">
    Padrões de integração para produção e escolha de endpoint.
  </Card>

  <Card title="Referência da API" icon="book" href="./api-reference/introduction.mdx">
    Documentação completa de solicitações e respostas para todos os endpoints.
  </Card>

  <Card title="Exemplos" icon="code" href="./guides/examples.mdx">
    Mais exemplos completos de solicitações para fluxos de trabalho comuns.
  </Card>

  <Card title="Suporte" icon="message-circle" href="https://phaseo.app/help">
    Receba ajuda com depuração, roteamento e comportamento dos modelos.
  </Card>
</Columns>


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