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

# クイックスタート

> API キーを作成し、現在利用できるテキストモデルで Phaseo に最初のリクエストを送信します。

このチュートリアルでは、テキスト生成または構造化された判断のPhaseoリクエストを成功させ、応答の表示場所を確認します。

<Note>
  **コーディングエージェントを使っていますか？** 始める前にこのプロンプトをコピーして貼り付けてください。

  ```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>

この手順で行うこと：

* API キーを作成する
* テキストまたは構造化された判断のリクエストを送る
* 生成されたテキストや型付き回答を読む
* リクエストが失敗したときに最初に確認する項目を知る

***

## 1. API キーを作成する

1. [Phaseo ダッシュボード](https://phaseo.app/gateway/keys)を開きます。
2. **Gateway → キー**でキーを作成します。
3. キーを一度だけコピーし、安全な場所に保管します。

次の形式を使用します：

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

<Danger>
  API キーはパスワードと同じように扱ってください。クライアント側のコードに含めないでください。
</Danger>

***

## 2. テキストリクエストを送信する

最初のリクエストには `POST /v1/responses` を使用します。新しいテキスト生成の実装に推奨されるエンドポイントです。

### リクエスト

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

### レスポンス

```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
}
```

Responses API を直接呼び出す場合は、`output[].content[]` の `type` が `output_text` である項目からアシスタントの返答を読み取ります。

Vercel AI SDK を使用する場合は、`result.text` から返答を読み取ります。

***

## 3. 構造化された判断を行う

テキスト生成ではなく型付き回答が必要な場合は`POST /v1/decisions`を使います。PhaseoはTypeSafeのJev 1.13をモデルID `typesafe/jev-1.13.0`で提供します。`state`値と1つ以上の名前付き質問を送り、各回答は同じ名前で返されます。

<Note>
  Decisionsはベータ機能で、ワークスペースでの有効化が必要な場合があります。Jev 1.13の料金は入力100万トークンあたり\$0.042で、出力トークンは無料です。
</Note>

`PHASEO_API_KEY`を設定したサーバーで例を実行してください。ブラウザーのコードにGateway APIキーを公開しないでください。

質問の型は次の3つです。

* `choice`は基準のマップから1つの選択肢を選び、確率と信頼度を返します。
* `noul`は0から1のはい/いいえの確率を返します。
* `score`は順序付きの基準配列を評価し、確率で重み付けしたスコアを返します。

同じリクエストで複数の質問型を混在させられます。

### リクエスト

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

### 応答

```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
  }
}
```

質問IDに対応する回答から型付きの値を読みます。例は`answers.department.choice`、`answers.is_urgent.noul`、`answers.customer_impact.score`です。値だけで分岐せずにアプリケーションのしきい値を設定する場合は、`confidence`と`probabilities`を使ってください。

リクエストと応答の詳細は[Decisions APIリファレンス](./api-reference/endpoint/decisions)、モデルの動作と上流の制限はTypeSafeの[Jevモデルリファレンス](https://docs.typesafe.ai/models)を参照してください。

***

## 4. 最初のリクエストをトラブルシューティングする

* `401`：API キーと `Authorization` ヘッダーを確認します。
* `400`：リクエスト本文とモデル ID を確認します。
* `402`：`:free` モデルに切り替えるか、有料モデルを使う前にクレジットを追加します。
* `429` または `5xx`：指数バックオフで再試行します。

問題をすばやく調査するには、[エラー処理のリファレンス](./api-reference/errors.mdx)を参照してください。

***

## 5. 動画機能を開発する場合

動画生成は非同期です。まずジョブを作成し、その後ステータスを確認するか、結果を購読します。

1. `POST /v1/videos` でジョブを作成します。
2. 完了するまで `GET /v1/videos/{video_id}` でステータスを確認します。
3. `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. 続けて開発する

<Columns cols={2}>
  <Card title="Gateway を統合する" icon="plug" href="./developers/integrating-with-the-gateway.mdx">
    本番環境での統合パターンとエンドポイントの選び方。
  </Card>

  <Card title="API リファレンス" icon="book" href="./api-reference/introduction.mdx">
    すべてのエンドポイントのリクエストとレスポンスを網羅したドキュメント。
  </Card>

  <Card title="サンプル" icon="code" href="./guides/examples.mdx">
    一般的なワークフロー向けの、より詳しいリクエスト例。
  </Card>

  <Card title="サポート" icon="message-circle" href="https://phaseo.app/help">
    デバッグ、ルーティング、モデルの動作についてサポートを受けます。
  </Card>
</Columns>


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