> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/api/ja/api-reference/ping-gu-he-ce-shi-ji.md).

# 評価とテストセット

評価とテストセットのエンドポイントは、管理画面の AgentOps にある「テストセット」と「自動テスト」に対応しており、お使いのシステムから Agent を一括でテストできます。全体の流れは次のとおりです。

1. **テストセットを作成する**：`POST /api/v1/dataset/` で空のテストセットを作成するか、`POST /api/v1/dataset/upload/` で CSV／Excel をアップロードして一度に作成します。
2. **テストケースを追加する**：単一ターンの質問応答には `/api/v1/test-case/`（1 件ずつ作成、ファイルのアップロード、またはナレッジベースファイルからの生成）を、複数ターンの対話シナリオには `/api/v1/multi-turn-test-case/` を使用します。ナレッジベースファイルからの生成はバックグラウンドで実行され、`202` と `jobId` が返ります。進捗は [テストケース生成ジョブの進捗を取得する](#test-case-generation-jobs-retrieve) で確認してください。
3. **評価を実行する**：`POST /api/v1/evaluations/evaluate/`（単一ターン）または `POST /api/v1/evaluations/multi-turn-evaluate/`（複数ターン）でテストセットと Agent を指定します。レスポンスは `202` と `evaluationId` です。
4. **結果の取得とエクスポート**：`GET /api/v1/evaluations/{id}/` をポーリングし、`status` が `completed`、`partial_completed`、`failed` のいずれかになったら終了です。単一ターンの問題ごとの結果は `details` に、複数ターンの対話ごとの結果は `multi-turn-results` に含まれます。完了した単一ターンの評価は `export` で Excel レポートとしてエクスポートでき、ダウンロード URL は `export-status` から取得できます。

**必要な権限**：API Key は、それを作成したメンバーの身分で呼び出されます。`/dataset/`、`/test-case/`、`/multi-turn-test-case/` の一覧取得とすべての書き込み操作には、ロールに「テストセット権限」が必要です。`/evaluations/` の一覧取得とすべての書き込み操作には「自動テスト権限」が必要です（[ロール権限](https://docs.maiagent.ai/org/roles/role-permission)にある AgentOps の権限で、オーナーは常に保有しています）。権限が不足している場合は `403` が返ります。オーナー以外のメンバーは、自身のロールで利用できる Agent のみ表示および評価できます。

**Credit**：ナレッジベースファイルからテストケースを生成すると、実際に生成された問題数に応じて課金項目 `agentops_test_gen` が差し引かれます。評価の実行では、終了時に完了したテストケース数に応じて `agentops_test_run` と `agentops_deepeval` が差し引かれ、採点に使用する評価モデルの呼び出しは、そのモデルの使用量に応じて別途課金されます。生成または評価を送信する前に、システムが組織の Credit と上限を確認し、不足している場合は `402` を返します。手動での作成、ファイルのアップロード、結果の取得では Credit は差し引かれません。各項目の単価は [課金項目を一覧表示する](https://docs.maiagent.ai/api/ja/api-reference/credit.md#credit-items-list) を参照してください。

機能と管理画面での操作については、ユーザーマニュアルの[テストセット管理](https://docs.maiagent.ai/build/agent-ops/test-datasets)および[自動評価と Agent モニタリング](https://docs.maiagent.ai/build/agent-ops/evaluations)を参照してください。

### テストセット一覧の取得 <a href="#dataset-list" id="dataset-list"></a>

GET `/api/v1/dataset/`

#### パラメータ

| パラメータ名     | 必須 | 型       | 説明                                                                                            |
| ---------- | -- | ------- | --------------------------------------------------------------------------------------------- |
| `isActive` | ❌  | boolean | 有効（true）または無効（false）のデータセットのみを一覧表示します                                                         |
| `ordering` | ❌  | string  | 並べ替えフィールド：created\_at または updated\_at。先頭に - を付けると新しい順になります（例：-updated\_at）。未指定の場合は作成日時の新しい順です |
| `page`     | ❌  | integer | ページ番号（1 から開始）。最終ページを超えると 404 を返します                                                            |
| `pageSize` | ❌  | integer | 1 ページあたりの件数。デフォルトは 20、上限は 100 です（100 を超える場合は 100 として扱われます）                                    |
| `query`    | ❌  | string  | キーワード。データセット名、説明、または ID に部分一致します                                                              |
| `search`   | ❌  | string  | キーワード。データセット名または説明に部分一致します（大文字小文字は区別しません。空白で区切って複数指定した場合はすべてに一致する必要があります）                     |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/dataset/?isActive=true&ordering=example&page=1&pageSize=1&query=example&search=example" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/dataset/?isActive=true&ordering=example&page=1&pageSize=1&query=example&search=example", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/dataset/?isActive=true&ordering=example&page=1&pageSize=1&query=example&search=example"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/dataset/?isActive=true&ordering=example&page=1&pageSize=1&query=example&search=example", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "id": string (uuid)
      "name": string
      "description"?: string // 任意
      "organization": 
      {
        "id": string (uuid)
        "name": string
      }
      "createdBy": 
      {
        "id": string (uuid)
        "name": string
      }
      "isActive"?: boolean // 任意
      "passPolicy"?: object // Pre-fills the pass rules of a new evaluation of this test set; never read when a run starts. (任意)
      "singleTurnTestCaseCount": integer
      "multiTurnTestCaseCount": integer
      "createdAt": string (timestamp)
      "updatedAt": string (timestamp)
    }
  ]
}
```

**レスポンス値の例**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンス文字列",
      "description": "レスポンス文字列",
      "organization": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス文字列"
      },
      "createdBy": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス文字列"
      },
      "isActive": false,
      "passPolicy": null,
      "singleTurnTestCaseCount": 456,
      "multiTurnTestCaseCount": 456,
      "createdAt": "レスポンス文字列",
      "updatedAt": "レスポンス文字列"
    }
  ]
}
```

***

### 空のテストセットを作成する <a href="#dataset-create" id="dataset-create"></a>

POST `/api/v1/dataset/`

{% hint style="info" %}
テストセット名は組織内で重複できません。重複した場合は `400` が返ります。
{% endhint %}

#### リクエスト内容

**リクエストパラメータ**

| フィールド            | 型                        | 必須  | 説明                                                                                             |
| ---------------- | ------------------------ | --- | ---------------------------------------------------------------------------------------------- |
| name             | string                   | はい  |                                                                                                |
| description      | string                   | いいえ |                                                                                                |
| passPolicy       | object（1 個のプロパティ: rules） | いいえ | Saved pass policy that pre-fills new evaluations; checked for shape only.                      |
| passPolicy.rules | array\[PassRule]         | はい  | Checked in order: the first matching rule decides a question, and the last one is the default. |

**リクエスト構造の例**

```typescript
{
  "name": string
  "description"?: string // 任意
  "passPolicy"?:  // Saved pass policy that pre-fills new evaluations; checked for shape only. (任意)
  {
    "rules": [ // Checked in order: the first matching rule decides a question, and the last one is the default.
      {
        "id": string
        "name": string
        "when": string // "always", or {"tags_any": [...]} / {"tags_all": [...]}.
        "metrics"?: [ // Result keys this rule runs; omitted runs every metric the evaluation enables. (任意)
          string
        ]
        "verdict": { // What counts as pass: the tiered rule, or every listed gate metric passing.
        {
          "type": string (enum: tiered, gates) // * `tiered` - tiered
* `gates` - gates
          "gates"?: [ // Result keys (as stored in metric_scores) that must all pass; gates verdict only. (任意)
            string
          ]
        }
        }
      }
    ]
  }
}
```

**リクエスト値の例**

```json
{
  "name": "サンプル名",
  "description": "サンプル文字列",
  "passPolicy": {
    "rules": [
      {
        "id": "サンプル文字列",
        "name": "サンプル名",
        "when": "サンプル文字列",
        "metrics": [
          "サンプル文字列"
        ],
        "verdict": {
          "type": "tiered",
          "gates": [
            "サンプル文字列"
          ]
        }
      }
    ]
  }
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出し例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/dataset/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "サンプル名",
    "description": "サンプル文字列",
    "passPolicy": {
      "rules": [
        {
          "id": "サンプル文字列",
          "name": "サンプル名",
          "when": "サンプル文字列",
          "metrics": [
            "サンプル文字列"
          ],
          "verdict": {
            "type": "tiered",
            "gates": [
              "サンプル文字列"
            ]
          }
        }
      ]
    }
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエスト内容 (payload)
const data = {
    "name": "サンプル名",
    "description": "サンプル文字列",
    "passPolicy": {
      "rules": [
        {
          "id": "サンプル文字列",
          "name": "サンプル名",
          "when": "サンプル文字列",
          "metrics": [
            "サンプル文字列"
          ],
          "verdict": {
            "type": "tiered",
            "gates": [
              "サンプル文字列"
            ]
          }
        }
      ]
    }
  };

axios.post("https://api.maiagent.ai/api/v1/dataset/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/dataset/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエスト内容 (payload)
data = {
    "name": "サンプル名",
    "description": "サンプル文字列",
    "passPolicy": {
        "rules": [
            {
                "id": "サンプル文字列",
                "name": "サンプル名",
                "when": "サンプル文字列",
                "metrics": [
                    "サンプル文字列"
                ],
                "verdict": {
                    "type": "tiered",
                    "gates": [
                        "サンプル文字列"
                    ]
                }
            }
        ]
    }
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/dataset/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => 'サンプル名',
            'description' => 'サンプル文字列',
            'passPolicy' => [
                'rules' => [
                    [
                        'id' => 'サンプル文字列',
                        'name' => 'サンプル名',
                        'when' => 'サンプル文字列',
                        'metrics' => [
                            'サンプル文字列'
                        ],
                        'verdict' => [
                            'type' => 'tiered',
                            'gates' => [
                                'サンプル文字列'
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 201**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "name": string
  "description"?: string // 任意
  "organization": 
  {
    "id": string (uuid)
    "name": string
  }
  "createdBy": 
  {
    "id": string (uuid)
    "name": string
  }
  "isActive"?: boolean // 任意
  "passPolicy"?: object // Pre-fills the pass rules of a new evaluation of this test set; never read when a run starts. (任意)
  "singleTurnTestCaseCount": integer
  "multiTurnTestCaseCount": integer
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "description": "レスポンス文字列",
  "organization": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "isActive": false,
  "passPolicy": null,
  "singleTurnTestCaseCount": 456,
  "multiTurnTestCaseCount": 456,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

***

### CSV または Excel をアップロードしてテストセットを作成する <a href="#dataset-upload-create" id="dataset-upload-create"></a>

POST `/api/v1/dataset/upload/`

{% hint style="info" %}
`multipart/form-data` でアップロードします。`file` と `name` は必須、`description` は任意です。ファイル形式は [CSV または Excel をアップロードしてテストケースを追加する](#test-case-upload-create) と同じです。テストセット名は組織内で重複できません。
{% endhint %}

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出し例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/dataset/upload/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -F "file=@example_file.csv" \
  -F "name=サンプル文字列" \
  -F "description=サンプル文字列"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const FormData = require('form-data');

// FormData オブジェクトを作成します
const formData = new FormData();
// 実際のファイルに置き換えてください
formData.append('file', /* 実際のファイルオブジェクト */, 'example_file.csv');
formData.append('name', 'サンプル文字列');
formData.append('description', 'サンプル文字列');

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    ...formData.getHeaders()
  }
};

axios.post("https://api.maiagent.ai/api/v1/dataset/upload/", formData, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/dataset/upload/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}

# ファイルとフォームデータを作成します
files = {
    'file': ('example_file.csv', open('example_file.csv', 'rb'), 'text/csv'),
    'name': (None, 'サンプル文字列'),
    'description': (None, 'サンプル文字列')
}

response = requests.post(url, files=files, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/dataset/upload/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ],
        'multipart' => [
            [
                'name' => 'file',
                'contents' => fopen('example_file.csv', 'r'),
                'filename' => 'example_file.csv'
            ],
            [
                'name' => 'name',
                'contents' => 'サンプル文字列'
            ],
            [
                'name' => 'description',
                'contents' => 'サンプル文字列'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 201**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "name": string
  "description"?: string // 任意
  "organization": 
  {
    "id": string (uuid)
    "name": string
  }
  "createdBy": 
  {
    "id": string (uuid)
    "name": string
  }
  "isActive"?: boolean // 任意
  "passPolicy"?: object // Pre-fills the pass rules of a new evaluation of this test set; never read when a run starts. (任意)
  "singleTurnTestCaseCount": integer
  "multiTurnTestCaseCount": integer
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "description": "レスポンス文字列",
  "organization": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "isActive": false,
  "passPolicy": null,
  "singleTurnTestCaseCount": 456,
  "multiTurnTestCaseCount": 456,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

***

### ナレッジベースファイルからテストセットを生成する <a href="#dataset-generate-from-file-create" id="dataset-generate-from-file-create"></a>

POST `/api/v1/dataset/generate-from-file/`

{% hint style="info" %}
単一のナレッジベースファイル（`knowledgeBaseFileId`）から新しいテストセットを作成し、単一ターンのテストケースを生成します。`numTestCases` は 1～50 です（デフォルトは 10）。生成はバックグラウンドで実行され、実際のレスポンスは `202` と `taskId` です。テストセット ID は含まれず、進捗も確認できません。完了すると、新しいテストセットが一覧に表示されます。進捗を追跡したい場合は、先に空のテストセットを作成してから [ナレッジベースファイルから単一ターンのテストケースを生成する](#test-case-generate-from-file-create) を使用してください。**Credit**：送信前に組織の Credit を確認し、不足している場合は `402` を返します。実際に生成された問題数に応じて `agentops_test_gen` が差し引かれます。
{% endhint %}

#### リクエスト内容

**リクエストパラメータ**

| フィールド               | 型             | 必須  | 説明 |
| ------------------- | ------------- | --- | -- |
| name                | string        | はい  |    |
| description         | string        | いいえ |    |
| chatbotFileId       | string (uuid) | いいえ |    |
| knowledgeBaseFileId | string (uuid) | いいえ |    |
| numTestCases        | integer       | いいえ |    |

**リクエスト構造の例**

```typescript
{
  "name": string
  "description"?: string // 任意
  "chatbotFileId"?: string (uuid) // 任意
  "knowledgeBaseFileId"?: string (uuid) // 任意
  "numTestCases"?: integer // 任意
}
```

**リクエスト値の例**

```json
{
  "name": "サンプル名",
  "description": "サンプル文字列",
  "chatbotFileId": "550e8400-e29b-41d4-a716-446655440000",
  "knowledgeBaseFileId": "550e8400-e29b-41d4-a716-446655440000",
  "numTestCases": 123
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出し例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/dataset/generate-from-file/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "サンプル名",
    "description": "サンプル文字列",
    "chatbotFileId": "550e8400-e29b-41d4-a716-446655440000",
    "knowledgeBaseFileId": "550e8400-e29b-41d4-a716-446655440000",
    "numTestCases": 123
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエスト内容 (payload)
const data = {
    "name": "サンプル名",
    "description": "サンプル文字列",
    "chatbotFileId": "550e8400-e29b-41d4-a716-446655440000",
    "knowledgeBaseFileId": "550e8400-e29b-41d4-a716-446655440000",
    "numTestCases": 123
  };

axios.post("https://api.maiagent.ai/api/v1/dataset/generate-from-file/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/dataset/generate-from-file/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエスト内容 (payload)
data = {
    "name": "サンプル名",
    "description": "サンプル文字列",
    "chatbotFileId": "550e8400-e29b-41d4-a716-446655440000",
    "knowledgeBaseFileId": "550e8400-e29b-41d4-a716-446655440000",
    "numTestCases": 123
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/dataset/generate-from-file/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => 'サンプル名',
            'description' => 'サンプル文字列',
            'chatbotFileId' => '550e8400-e29b-41d4-a716-446655440000',
            'knowledgeBaseFileId' => '550e8400-e29b-41d4-a716-446655440000',
            'numTestCases' => 123
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 202**

**レスポンス構造の例**

```typescript
{
  "status": string (enum: accepted) // * `accepted` - 常に accepted。リクエストが受理され、バックグラウンド実行に登録されたことを示します
  "message": string // 受理メッセージ
  "taskId": string // バックグラウンドタスク ID
}
```

**レスポンス値の例**

```json
{
  "status": "accepted",
  "message": "レスポンス文字列",
  "taskId": "レスポンス文字列"
}
```

***

### テストケース生成に使用できるナレッジベースのファイルを一覧表示 <a href="#dataset-knowledge-base-files-retrieve" id="dataset-knowledge-base-files-retrieve"></a>

GET `/api/v1/dataset/knowledge-base-files/`

{% hint style="info" %}
ナレッジベースごとにグループ化し、処理が完了した txt、docx、pdf、md、markdown、mdx 形式のファイルのみを一覧表示します。`pageSize` はナレッジベースごとに返すファイル数の上限（デフォルト 5、最大 100）、`search` はファイル名によるフィルターです。
{% endhint %}

#### パラメーター

| パラメーター名    | 必須 | 型       | 説明                                     |
| ---------- | -- | ------- | -------------------------------------- |
| `pageSize` | ❌  | integer | ナレッジベースごとに返すファイル数の上限です（デフォルト 5、最大 100） |
| `search`   | ❌  | string  | ファイル名で絞り込みます（大文字・小文字を区別しない部分一致）        |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出し例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/dataset/knowledge-base-files/?pageSize=1&search=example" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/dataset/knowledge-base-files/?pageSize=1&search=example", config)
  .then(response => {
    console.log('レスポンスを取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラー:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/dataset/knowledge-base-files/?pageSize=1&search=example"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラー:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/dataset/knowledge-base-files/?pageSize=1&search=example", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラー: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス本文

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "knowledgeBases": [ // 利用可能なファイルを持つナレッジベースを名前順に並べます。利用可能なファイルがないナレッジベースは含まれません
    {
      "id": string (uuid)
      "name": string
      "files": 
      {
        "count": integer // このナレッジベースで条件に一致するファイルの総数です
        "results": [ // 最新の page_size 件のファイルです
          {
            "id": string (uuid)
            "filename": string
            "fileType": string
            "size": integer // ファイルサイズ（バイト）です
            "knowledgeBase": 
            {
              "id": string (uuid)
              "name": string
            }
          }
        ]
      }
    }
  ]
}
```

**レスポンス値の例**

```json
{
  "knowledgeBases": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンス文字列",
      "files": {
        "count": 456,
        "results": [
          {
            "id": "550e8400-e29b-41d4-a716-446655440000",
            "filename": "レスポンス文字列",
            "fileType": "レスポンス文字列",
            "size": 456,
            "knowledgeBase": {
              "id": "550e8400-e29b-41d4-a716-446655440000",
              "name": "レスポンス文字列"
            }
          }
        ]
      }
    }
  ]
}
```

***

### 特定のテストセットを取得する <a href="#dataset-retrieve" id="dataset-retrieve"></a>

GET `/api/v1/dataset/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明        |
| ------ | -- | ------ | --------- |
| `id`   | ✅  | string | データセット ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "name": string
  "description"?: string // 任意
  "organization": 
  {
    "id": string (uuid)
    "name": string
  }
  "createdBy": 
  {
    "id": string (uuid)
    "name": string
  }
  "isActive"?: boolean // 任意
  "passPolicy"?: object // Pre-fills the pass rules of a new evaluation of this test set; never read when a run starts. (任意)
  "singleTurnTestCaseCount": integer
  "multiTurnTestCaseCount": integer
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "description": "レスポンス文字列",
  "organization": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "isActive": false,
  "passPolicy": null,
  "singleTurnTestCaseCount": 456,
  "multiTurnTestCaseCount": 456,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

***

### テストセットと単一ターンのテストケースを取得する <a href="#dataset-details-retrieve" id="dataset-details-retrieve"></a>

GET `/api/v1/dataset/{id}/details/`

{% hint style="info" %}
レスポンスには、テストセットのフィールドに加えて `testCases` 配列が含まれます。この配列には単一ターンのテストケースのみが含まれます。複数ターンのテストケースは `GET /api/v1/multi-turn-test-case/?datasetId={id}` を使用してください。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明        |
| ------ | -- | ------ | --------- |
| `id`   | ✅  | string | データセット ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/details/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/details/", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/details/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/details/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "name": string
  "description"?: string // 任意
  "organization": 
  {
    "id": string (uuid)
    "name": string
  }
  "createdBy": 
  {
    "id": string (uuid)
    "name": string
  }
  "isActive"?: boolean // 任意
  "passPolicy"?: object // Pre-fills the pass rules of a new evaluation of this test set; never read when a run starts. (任意)
  "singleTurnTestCaseCount": integer
  "multiTurnTestCaseCount": integer
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
  "testCases": [ // このテストセットのすべての単一ターンのテストケース（作成日時の古い順）。テストケースがない場合は空の配列
    {
      "id": string (uuid)
      "dataset": 
      {
        "id": string (uuid)
        "name": string
      }
      "question": string
      "groundTruth"?: string // 任意
      "status"?: string (enum: active, inactive, pending) // * `active` - Active
* `inactive` - Inactive
* `pending` - Pending Review (任意)
      "creationMethod"?: string (enum: manual, file, generate) // * `manual` - Manual
* `file` - File import
* `generate` - Generated (任意)
      "sourceFile"?: string // Name of the CSV, Excel or knowledge base file this test case came from (任意)
      "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
      "tags"?: object // Labels that pick which pass rule decides this question. An empty list matches only rules that cover every question. (任意)
      "createdAt": string (timestamp)
      "updatedAt": string (timestamp)
    }
  ]
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "description": "レスポンス文字列",
  "organization": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "isActive": false,
  "passPolicy": null,
  "singleTurnTestCaseCount": 456,
  "multiTurnTestCaseCount": 456,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列",
  "testCases": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "dataset": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス文字列"
      },
      "question": "レスポンス文字列",
      "groundTruth": "レスポンス文字列",
      "status": "active",
      "creationMethod": "manual",
      "sourceFile": "レスポンス文字列",
      "flaky": false,
      "tags": null,
      "createdAt": "レスポンス文字列",
      "updatedAt": "レスポンス文字列"
    }
  ]
}
```

***

### テストセットを更新する <a href="#dataset-update" id="dataset-update"></a>

PUT `/api/v1/dataset/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明        |
| ------ | -- | ------ | --------- |
| `id`   | ✅  | string | データセット ID |

#### リクエスト内容

**リクエストパラメータ**

| フィールド            | 型                        | 必須  | 説明                                                                                             |
| ---------------- | ------------------------ | --- | ---------------------------------------------------------------------------------------------- |
| name             | string                   | はい  |                                                                                                |
| description      | string                   | いいえ |                                                                                                |
| isActive         | boolean                  | いいえ |                                                                                                |
| passPolicy       | object（1 個のプロパティ: rules） | いいえ | Saved pass policy that pre-fills new evaluations; checked for shape only. Null clears it.      |
| passPolicy.rules | array\[PassRule]         | はい  | Checked in order: the first matching rule decides a question, and the last one is the default. |

**リクエスト構造の例**

```typescript
{
  "name": string
  "description"?: string // 任意
  "isActive"?: boolean // 任意
  "passPolicy"?:  // Saved pass policy that pre-fills new evaluations; checked for shape only. Null clears it. (任意)
  {
    "rules": [ // Checked in order: the first matching rule decides a question, and the last one is the default.
      {
        "id": string
        "name": string
        "when": string // "always", or {"tags_any": [...]} / {"tags_all": [...]}.
        "metrics"?: [ // Result keys this rule runs; omitted runs every metric the evaluation enables. (任意)
          string
        ]
        "verdict": { // What counts as pass: the tiered rule, or every listed gate metric passing.
        {
          "type": string (enum: tiered, gates) // * `tiered` - tiered
* `gates` - gates
          "gates"?: [ // Result keys (as stored in metric_scores) that must all pass; gates verdict only. (任意)
            string
          ]
        }
        }
      }
    ]
  }
}
```

**リクエスト値の例**

```json
{
  "name": "サンプル名",
  "description": "サンプル文字列",
  "isActive": true,
  "passPolicy": {
    "rules": [
      {
        "id": "サンプル文字列",
        "name": "サンプル名",
        "when": "サンプル文字列",
        "metrics": [
          "サンプル文字列"
        ],
        "verdict": {
          "type": "tiered",
          "gates": [
            "サンプル文字列"
          ]
        }
      }
    ]
  }
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X PUT "https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "サンプル名",
    "description": "サンプル文字列",
    "isActive": true,
    "passPolicy": {
      "rules": [
        {
          "id": "サンプル文字列",
          "name": "サンプル名",
          "when": "サンプル文字列",
          "metrics": [
            "サンプル文字列"
          ],
          "verdict": {
            "type": "tiered",
            "gates": [
              "サンプル文字列"
            ]
          }
        }
      ]
    }
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエスト内容 (payload)
const data = {
    "name": "サンプル名",
    "description": "サンプル文字列",
    "isActive": true,
    "passPolicy": {
      "rules": [
        {
          "id": "サンプル文字列",
          "name": "サンプル名",
          "when": "サンプル文字列",
          "metrics": [
            "サンプル文字列"
          ],
          "verdict": {
            "type": "tiered",
            "gates": [
              "サンプル文字列"
            ]
          }
        }
      ]
    }
  };

axios.put("https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエスト内容 (payload)
data = {
    "name": "サンプル名",
    "description": "サンプル文字列",
    "isActive": True,
    "passPolicy": {
        "rules": [
            {
                "id": "サンプル文字列",
                "name": "サンプル名",
                "when": "サンプル文字列",
                "metrics": [
                    "サンプル文字列"
                ],
                "verdict": {
                    "type": "tiered",
                    "gates": [
                        "サンプル文字列"
                    ]
                }
            }
        ]
    }
}

response = requests.put(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->put("https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => 'サンプル名',
            'description' => 'サンプル文字列',
            'isActive' => true,
            'passPolicy' => [
                'rules' => [
                    [
                        'id' => 'サンプル文字列',
                        'name' => 'サンプル名',
                        'when' => 'サンプル文字列',
                        'metrics' => [
                            'サンプル文字列'
                        ],
                        'verdict' => [
                            'type' => 'tiered',
                            'gates' => [
                                'サンプル文字列'
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "name": string
  "description"?: string // 任意
  "organization": 
  {
    "id": string (uuid)
    "name": string
  }
  "createdBy": 
  {
    "id": string (uuid)
    "name": string
  }
  "isActive"?: boolean // 任意
  "passPolicy"?: object // Pre-fills the pass rules of a new evaluation of this test set; never read when a run starts. (任意)
  "singleTurnTestCaseCount": integer
  "multiTurnTestCaseCount": integer
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "description": "レスポンス文字列",
  "organization": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "isActive": false,
  "passPolicy": null,
  "singleTurnTestCaseCount": 456,
  "multiTurnTestCaseCount": 456,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

***

### テストセットを部分的に更新する <a href="#dataset-partial-update" id="dataset-partial-update"></a>

PATCH `/api/v1/dataset/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明        |
| ------ | -- | ------ | --------- |
| `id`   | ✅  | string | データセット ID |

#### リクエスト内容

**リクエストパラメータ**

| フィールド            | 型                        | 必須  | 説明                                                                                             |
| ---------------- | ------------------------ | --- | ---------------------------------------------------------------------------------------------- |
| name             | string                   | いいえ |                                                                                                |
| description      | string                   | いいえ |                                                                                                |
| isActive         | boolean                  | いいえ |                                                                                                |
| passPolicy       | object（1 個のプロパティ: rules） | いいえ | Saved pass policy that pre-fills new evaluations; checked for shape only. Null clears it.      |
| passPolicy.rules | array\[PassRule]         | はい  | Checked in order: the first matching rule decides a question, and the last one is the default. |

**リクエスト構造の例**

```typescript
{
  "name"?: string // 任意
  "description"?: string // 任意
  "isActive"?: boolean // 任意
  "passPolicy"?:  // Saved pass policy that pre-fills new evaluations; checked for shape only. Null clears it. (任意)
  {
    "rules": [ // Checked in order: the first matching rule decides a question, and the last one is the default.
      {
        "id": string
        "name": string
        "when": string // "always", or {"tags_any": [...]} / {"tags_all": [...]}.
        "metrics"?: [ // Result keys this rule runs; omitted runs every metric the evaluation enables. (任意)
          string
        ]
        "verdict": { // What counts as pass: the tiered rule, or every listed gate metric passing.
        {
          "type": string (enum: tiered, gates) // * `tiered` - tiered
* `gates` - gates
          "gates"?: [ // Result keys (as stored in metric_scores) that must all pass; gates verdict only. (任意)
            string
          ]
        }
        }
      }
    ]
  }
}
```

**リクエスト値の例**

```json
{
  "name": "サンプル名",
  "description": "サンプル文字列",
  "isActive": true,
  "passPolicy": {
    "rules": [
      {
        "id": "サンプル文字列",
        "name": "サンプル名",
        "when": "サンプル文字列",
        "metrics": [
          "サンプル文字列"
        ],
        "verdict": {
          "type": "tiered",
          "gates": [
            "サンプル文字列"
          ]
        }
      }
    ]
  }
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "サンプル名",
    "description": "サンプル文字列",
    "isActive": true,
    "passPolicy": {
      "rules": [
        {
          "id": "サンプル文字列",
          "name": "サンプル名",
          "when": "サンプル文字列",
          "metrics": [
            "サンプル文字列"
          ],
          "verdict": {
            "type": "tiered",
            "gates": [
              "サンプル文字列"
            ]
          }
        }
      ]
    }
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエスト内容 (payload)
const data = {
    "name": "サンプル名",
    "description": "サンプル文字列",
    "isActive": true,
    "passPolicy": {
      "rules": [
        {
          "id": "サンプル文字列",
          "name": "サンプル名",
          "when": "サンプル文字列",
          "metrics": [
            "サンプル文字列"
          ],
          "verdict": {
            "type": "tiered",
            "gates": [
              "サンプル文字列"
            ]
          }
        }
      ]
    }
  };

axios.patch("https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエスト内容 (payload)
data = {
    "name": "サンプル名",
    "description": "サンプル文字列",
    "isActive": True,
    "passPolicy": {
        "rules": [
            {
                "id": "サンプル文字列",
                "name": "サンプル名",
                "when": "サンプル文字列",
                "metrics": [
                    "サンプル文字列"
                ],
                "verdict": {
                    "type": "tiered",
                    "gates": [
                        "サンプル文字列"
                    ]
                }
            }
        ]
    }
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => 'サンプル名',
            'description' => 'サンプル文字列',
            'isActive' => true,
            'passPolicy' => [
                'rules' => [
                    [
                        'id' => 'サンプル文字列',
                        'name' => 'サンプル名',
                        'when' => 'サンプル文字列',
                        'metrics' => [
                            'サンプル文字列'
                        ],
                        'verdict' => [
                            'type' => 'tiered',
                            'gates' => [
                                'サンプル文字列'
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "name": string
  "description"?: string // 任意
  "organization": 
  {
    "id": string (uuid)
    "name": string
  }
  "createdBy": 
  {
    "id": string (uuid)
    "name": string
  }
  "isActive"?: boolean // 任意
  "passPolicy"?: object // Pre-fills the pass rules of a new evaluation of this test set; never read when a run starts. (任意)
  "singleTurnTestCaseCount": integer
  "multiTurnTestCaseCount": integer
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "description": "レスポンス文字列",
  "organization": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "createdBy": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "isActive": false,
  "passPolicy": null,
  "singleTurnTestCaseCount": 456,
  "multiTurnTestCaseCount": 456,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

***

### テストセットを削除する <a href="#dataset-destroy" id="dataset-destroy"></a>

DELETE `/api/v1/dataset/{id}/`

{% hint style="info" %}
削除すると元に戻せません。テストセット内のすべてのテストケースに加えて、このテストセットで実行した評価とその結果も一緒に削除されます。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明        |
| ------ | -- | ------ | --------- |
| `id`   | ✅  | string | データセット ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエスト内容 (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.delete(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/dataset/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

| ステータスコード | 説明               |
| -------- | ---------------- |
| 204      | No response body |

***

### 単一ターンのテストケース一覧を取得 <a href="#test-case-list" id="test-case-list"></a>

GET `/api/v1/test-case/`

{% hint style="info" %}
`datasetId` で単一のテストセットを絞り込めます。`status` や `creationMethod`（`manual`、`file`、`generate`）でも絞り込めます。
{% endhint %}

#### パラメータ

| パラメータ名           | 必須 | 型       | 説明                                                                                                          |
| ---------------- | -- | ------- | ----------------------------------------------------------------------------------------------------------- |
| `creationMethod` | ❌  | string  | この方法で作成されたテストケースのみを一覧表示します。指定可能な値： \`manual\`: Manual ; \`file\`: File import ; \`generate\`: Generated;    |
| `datasetId`      | ❌  | string  | このデータセットのテストケースのみを一覧表示します                                                                                   |
| `ordering`       | ❌  | string  | 並べ替えフィールド：created\_at または updated\_at。先頭に - を付けると新しい順になります（例：-updated\_at）。未指定の場合は作成日時の新しい順です               |
| `page`           | ❌  | integer | ページ番号（1 から開始）。最終ページを超えると 404 を返します                                                                          |
| `pageSize`       | ❌  | integer | 1 ページあたりの件数。デフォルトは 20、上限は 100 です（超過した場合は 100 として扱います）                                                       |
| `query`          | ❌  | string  | 質問、正解、または ID に照合するキーワード（部分一致）                                                                               |
| `search`         | ❌  | string  | 質問または正解に照合するキーワード（部分一致、大文字小文字を区別しません。空白で区切って複数のキーワードを指定した場合は、すべてに一致する必要があります）                               |
| `status`         | ❌  | string  | このステータスのテストケースのみを一覧表示します。指定可能な値： \`active\`: Active ; \`inactive\`: Inactive ; \`pending\`: Pending Review; |
| `tags`           | ❌  | string  | カンマ区切りのタグ（例：out\_of\_scope,red\_team）。いずれかのタグを持つテストケースのみを一覧表示します                                            |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/test-case/?creationMethod=file&datasetId=550e8400-e29b-41d4-a716-446655440000&ordering=example&page=1&pageSize=1&query=example&search=example&status=active&tags=example" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/test-case/?creationMethod=file&datasetId=550e8400-e29b-41d4-a716-446655440000&ordering=example&page=1&pageSize=1&query=example&search=example&status=active&tags=example", config)
  .then(response => {
    console.log('レスポンスの取得に成功しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('エラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/test-case/?creationMethod=file&datasetId=550e8400-e29b-41d4-a716-446655440000&ordering=example&page=1&pageSize=1&query=example&search=example&status=active&tags=example"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスの取得に成功しました:")
    print(response.json())
except Exception as e:
    print("エラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/test-case/?creationMethod=file&datasetId=550e8400-e29b-41d4-a716-446655440000&ordering=example&page=1&pageSize=1&query=example&search=example&status=active&tags=example", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスの取得に成功しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'エラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "id": string (uuid)
      "dataset": 
      {
        "id": string (uuid)
        "name": string
      }
      "question": string
      "groundTruth"?: string // 任意
      "status"?: string (enum: active, inactive, pending) // * `active` - Active
* `inactive` - Inactive
* `pending` - Pending Review (任意)
      "creationMethod"?: string (enum: manual, file, generate) // * `manual` - Manual
* `file` - File import
* `generate` - Generated (任意)
      "sourceFile"?: string // Name of the CSV, Excel or knowledge base file this test case came from (任意)
      "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
      "tags"?: object // Labels that pick which pass rule decides this question. An empty list matches only rules that cover every question. (任意)
      "createdAt": string (timestamp)
      "updatedAt": string (timestamp)
    }
  ]
}
```

**レスポンスの例**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "dataset": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス文字列"
      },
      "question": "レスポンス文字列",
      "groundTruth": "レスポンス文字列",
      "status": "active",
      "creationMethod": "manual",
      "sourceFile": "レスポンス文字列",
      "flaky": false,
      "tags": null,
      "createdAt": "レスポンス文字列",
      "updatedAt": "レスポンス文字列"
    }
  ]
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 単一ターンのテストケースを作成 <a href="#test-case-create" id="test-case-create"></a>

POST `/api/v1/test-case/`

{% hint style="info" %}
`datasetId`、`question`、`groundTruth` は必須です。`status` のデフォルトは `active` で、評価では `active` のテストケースのみが実行されます。
{% endhint %}

#### リクエスト

**リクエストパラメータ**

| フィールド       | 型              | 必須  | 説明                                                                           |
| ----------- | -------------- | --- | ---------------------------------------------------------------------------- |
| datasetId   | string (uuid)  | はい  |                                                                              |
| question    | string         | はい  |                                                                              |
| groundTruth | string         | はい  |                                                                              |
| status      | string         | いいえ |                                                                              |
| flaky       | boolean        | いいえ |                                                                              |
| tags        | array\[string] | いいえ | Labels that pick the pass rule deciding this question; empty means untagged. |

**リクエストスキーマの例**

```typescript
{
  "datasetId": string (uuid)
  "question": string
  "groundTruth": string
  "status"?: string // 任意
  "flaky"?: boolean // 任意
  "tags"?: [ // Labels that pick the pass rule deciding this question; empty means untagged. (任意)
    string
  ]
}
```

**リクエストの例**

```json
{
  "datasetId": "550e8400-e29b-41d4-a716-446655440000",
  "question": "サンプル文字列",
  "groundTruth": "サンプル文字列",
  "status": "サンプル文字列",
  "flaky": true,
  "tags": [
    "サンプル文字列"
  ]
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/test-case/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "datasetId": "550e8400-e29b-41d4-a716-446655440000",
    "question": "サンプル文字列",
    "groundTruth": "サンプル文字列",
    "status": "サンプル文字列",
    "flaky": true,
    "tags": [
      "サンプル文字列"
    ]
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストペイロード
const data = {
    "datasetId": "550e8400-e29b-41d4-a716-446655440000",
    "question": "サンプル文字列",
    "groundTruth": "サンプル文字列",
    "status": "サンプル文字列",
    "flaky": true,
    "tags": [
      "サンプル文字列"
    ]
  };

axios.post("https://api.maiagent.ai/api/v1/test-case/", data, config)
  .then(response => {
    console.log('レスポンスの取得に成功しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('エラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/test-case/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエストペイロード
data = {
    "datasetId": "550e8400-e29b-41d4-a716-446655440000",
    "question": "サンプル文字列",
    "groundTruth": "サンプル文字列",
    "status": "サンプル文字列",
    "flaky": True,
    "tags": [
        "サンプル文字列"
    ]
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスの取得に成功しました:")
    print(response.json())
except Exception as e:
    print("エラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/test-case/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'datasetId' => '550e8400-e29b-41d4-a716-446655440000',
            'question' => 'サンプル文字列',
            'groundTruth' => 'サンプル文字列',
            'status' => 'サンプル文字列',
            'flaky' => true,
            'tags' => [
                'サンプル文字列'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスの取得に成功しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'エラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス

**ステータスコード: 201**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "dataset": 
  {
    "id": string (uuid)
    "name": string
  }
  "question": string
  "groundTruth"?: string // 任意
  "status"?: string (enum: active, inactive, pending) // * `active` - Active
* `inactive` - Inactive
* `pending` - Pending Review (任意)
  "creationMethod"?: string (enum: manual, file, generate) // * `manual` - Manual
* `file` - File import
* `generate` - Generated (任意)
  "sourceFile"?: string // Name of the CSV, Excel or knowledge base file this test case came from (任意)
  "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
  "tags"?: object // Labels that pick which pass rule decides this question. An empty list matches only rules that cover every question. (任意)
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンスの例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "dataset": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "question": "レスポンス文字列",
  "groundTruth": "レスポンス文字列",
  "status": "active",
  "creationMethod": "manual",
  "sourceFile": "レスポンス文字列",
  "flaky": false,
  "tags": null,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### CSV または Excel をアップロードしてテストケースを追加 <a href="#test-case-upload-create" id="test-case-upload-create"></a>

POST `/api/v1/test-case/upload/`

{% hint style="info" %}
`multipart/form-data` でアップロードします。`file` と `dataset_id` はどちらも必須です。ファイルは `.csv`、`.xlsx`、`.xls` のいずれかで、ヘッダー行に `question` と `ground_truth` の 2 列が必要です。各行が 1 件の単一ターンのテストケースとして追加されます。CSV は UTF-8 エンコーディングを使用してください。レスポンスは追加されたテストケースの配列です。
{% endhint %}

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/test-case/upload/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -F "file=@example_file.csv" \
  -F "dataset_id=550e8400-e29b-41d4-a716-446655440000"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const FormData = require('form-data');

// FormData オブジェクトを作成
const formData = new FormData();
// 実際のファイルに置き換えてください
formData.append('file', /* 実際のファイルオブジェクト */, 'example_file.csv');
formData.append('dataset_id', '550e8400-e29b-41d4-a716-446655440000');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    ...formData.getHeaders()
  }
};

axios.post("https://api.maiagent.ai/api/v1/test-case/upload/", formData, config)
  .then(response => {
    console.log('レスポンスの取得に成功しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('エラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/test-case/upload/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}

# ファイルとフォームデータを作成
files = {
    'file': ('example_file.csv', open('example_file.csv', 'rb'), 'text/csv'),
    'dataset_id': (None, '550e8400-e29b-41d4-a716-446655440000')
}

response = requests.post(url, files=files, headers=headers)
try:
    print("レスポンスの取得に成功しました:")
    print(response.json())
except Exception as e:
    print("エラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/test-case/upload/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ],
        'multipart' => [
            [
                'name' => 'file',
                'contents' => fopen('example_file.csv', 'r'),
                'filename' => 'example_file.csv'
            ],
            [
                'name' => 'dataset_id',
                'contents' => '550e8400-e29b-41d4-a716-446655440000'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスの取得に成功しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'エラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス

**ステータスコード: 201**

**レスポンススキーマの例**

```typescript
[
  {
    "id": string (uuid)
    "dataset": 
    {
      "id": string (uuid)
      "name": string
    }
    "question": string
    "groundTruth"?: string // 任意
    "status"?: string (enum: active, inactive, pending) // * `active` - Active
* `inactive` - Inactive
* `pending` - Pending Review (任意)
    "creationMethod"?: string (enum: manual, file, generate) // * `manual` - Manual
* `file` - File import
* `generate` - Generated (任意)
    "sourceFile"?: string // Name of the CSV, Excel or knowledge base file this test case came from (任意)
    "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
    "tags"?: object // Labels that pick which pass rule decides this question. An empty list matches only rules that cover every question. (任意)
    "createdAt": string (timestamp)
    "updatedAt": string (timestamp)
  }
]
```

**レスポンスの例**

```json
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "dataset": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンス文字列"
    },
    "question": "レスポンス文字列",
    "groundTruth": "レスポンス文字列",
    "status": "active",
    "creationMethod": "manual",
    "sourceFile": "レスポンス文字列",
    "flaky": false,
    "tags": null,
    "createdAt": "レスポンス文字列",
    "updatedAt": "レスポンス文字列"
  }
]
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### ナレッジベースファイルからの単一ターンのテストケース生成 <a href="#test-case-generate-from-file-create" id="test-case-generate-from-file-create"></a>

POST `/api/v1/test-case/generate-from-file/`

{% hint style="info" %}
`knowledgeBaseIds`（ナレッジベース内の処理が完了した、対応形式のすべてのファイルに展開されます）または `knowledgeBaseFileIds` で元データを指定します。両方を併用することもできます。対応形式は txt、docx、pdf、md、markdown、mdx です。`numTestCases` は今回生成する問題の総数（デフォルトは 10）で、ファイル数または問題数がプラットフォームの上限を超えると `400` を返し、メッセージに上限が示されます。生成はバックグラウンドで実行され、レスポンスは `202` と `jobId` です。同じテストセットで生成タスクがすでに実行中の場合は、そのタスクの `jobId` が返され、重複して作成されることはありません。**Credit**：送信前に組織の Credit を確認し、不足している場合は `402` を返します。実際に生成された問題数に応じて `agentops_test_gen` が差し引かれます。
{% endhint %}

#### リクエスト内容

**リクエストパラメータ**

| フィールド                | 型              | 必須  | 説明                                                                     |
| -------------------- | -------------- | --- | ---------------------------------------------------------------------- |
| chatbotFileIds       | array\[string] | いいえ | List of KnowledgeBaseFile IDs to generate test cases from (deprecated) |
| knowledgeBaseFileIds | array\[string] | いいえ | List of KnowledgeBaseFile IDs to generate test cases from              |
| knowledgeBaseIds     | array\[string] | いいえ | List of KnowledgeBase IDs to generate test cases from all their files  |
| datasetId            | string (uuid)  | はい  |                                                                        |
| numTestCases         | integer        | いいえ |                                                                        |

**リクエスト構造の例**

```typescript
{
  "chatbotFileIds"?: [ // List of KnowledgeBaseFile IDs to generate test cases from (deprecated) (任意)
    string (uuid)
  ]
  "knowledgeBaseFileIds"?: [ // List of KnowledgeBaseFile IDs to generate test cases from (任意)
    string (uuid)
  ]
  "knowledgeBaseIds"?: [ // List of KnowledgeBase IDs to generate test cases from all their files (任意)
    string (uuid)
  ]
  "datasetId": string (uuid)
  "numTestCases"?: integer // 任意
}
```

**リクエスト値の例**

```json
{
  "chatbotFileIds": [
    "550e8400-e29b-41d4-a716-446655440000"
  ],
  "knowledgeBaseFileIds": [
    "550e8400-e29b-41d4-a716-446655440000"
  ],
  "knowledgeBaseIds": [
    "550e8400-e29b-41d4-a716-446655440000"
  ],
  "datasetId": "550e8400-e29b-41d4-a716-446655440000",
  "numTestCases": 123
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/test-case/generate-from-file/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "chatbotFileIds": [
      "550e8400-e29b-41d4-a716-446655440000"
    ],
    "knowledgeBaseFileIds": [
      "550e8400-e29b-41d4-a716-446655440000"
    ],
    "knowledgeBaseIds": [
      "550e8400-e29b-41d4-a716-446655440000"
    ],
    "datasetId": "550e8400-e29b-41d4-a716-446655440000",
    "numTestCases": 123
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストペイロード (payload)
const data = {
    "chatbotFileIds": [
      "550e8400-e29b-41d4-a716-446655440000"
    ],
    "knowledgeBaseFileIds": [
      "550e8400-e29b-41d4-a716-446655440000"
    ],
    "knowledgeBaseIds": [
      "550e8400-e29b-41d4-a716-446655440000"
    ],
    "datasetId": "550e8400-e29b-41d4-a716-446655440000",
    "numTestCases": 123
  };

axios.post("https://api.maiagent.ai/api/v1/test-case/generate-from-file/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/test-case/generate-from-file/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエストペイロード (payload)
data = {
    "chatbotFileIds": [
        "550e8400-e29b-41d4-a716-446655440000"
    ],
    "knowledgeBaseFileIds": [
        "550e8400-e29b-41d4-a716-446655440000"
    ],
    "knowledgeBaseIds": [
        "550e8400-e29b-41d4-a716-446655440000"
    ],
    "datasetId": "550e8400-e29b-41d4-a716-446655440000",
    "numTestCases": 123
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/test-case/generate-from-file/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'chatbotFileIds' => [
                '550e8400-e29b-41d4-a716-446655440000'
            ],
            'knowledgeBaseFileIds' => [
                '550e8400-e29b-41d4-a716-446655440000'
            ],
            'knowledgeBaseIds' => [
                '550e8400-e29b-41d4-a716-446655440000'
            ],
            'datasetId' => '550e8400-e29b-41d4-a716-446655440000',
            'numTestCases' => 123
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 202**

**レスポンス構造の例**

```typescript
{
  "status": string (enum: accepted) // * `accepted` - 常に accepted で、リクエストが受理され、バックグラウンド実行にキューイングされたことを示します
  "message": string // 受理メッセージ
  "jobId": string (uuid) // 生成タスク ID。GET /api/v1/test-case/generation-jobs/{jobId}/ で進捗を確認できます。同じテストセットで生成タスクがすでに実行中の場合は、そのタスクが返されます
  "taskId": string // バックグラウンドタスク ID
}
```

**レスポンス値の例**

```json
{
  "status": "accepted",
  "message": "レスポンス文字列",
  "jobId": "550e8400-e29b-41d4-a716-446655440000",
  "taskId": "レスポンス文字列"
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### テストケース生成ジョブの一覧を取得する <a href="#test-case-generation-jobs-list" id="test-case-generation-jobs-list"></a>

GET `/api/v1/test-case/generation-jobs/`

{% hint style="info" %}
組織の単一ターンおよび複数ターンの生成ジョブを新しい順に一覧表示します。`datasetId` と `status` で絞り込めます。
{% endhint %}

#### パラメータ

| パラメータ名      | 必須 | 型       | 説明                                                                     |
| ----------- | -- | ------- | ---------------------------------------------------------------------- |
| `datasetId` | ❌  | string  | このデータセットの生成ジョブのみを一覧表示します                                               |
| `page`      | ❌  | integer | ページ番号（1 から開始）。最終ページを超えると 404 を返します                                     |
| `pageSize`  | ❌  | integer | 1 ページあたりの件数。デフォルトは 20、上限は 100（超過した場合は 100 として扱います）                     |
| `status`    | ❌  | string  | ステータスで絞り込み：pending / running / completed / partial\_completed / failed |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/test-case/generation-jobs/?datasetId=example&page=1&pageSize=1&status=example" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/test-case/generation-jobs/?datasetId=example&page=1&pageSize=1&status=example", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/test-case/generation-jobs/?datasetId=example&page=1&pageSize=1&status=example"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/test-case/generation-jobs/?datasetId=example&page=1&pageSize=1&status=example", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "id": string (uuid)
      "dataset": 
      {
        "id": string (uuid)
        "name": string
      }
      "status"?: string (enum: pending, running, completed, partial_completed, failed) // * `pending` - Pending
* `running` - Generating
* `completed` - Completed
* `partial_completed` - Partially completed
* `failed` - Generation failed (任意)
      "jobType"?:  // Single-turn Q&A test data, multi-turn conversation test data, or AI-drafted expected answers for existing questions

* `single_turn` - Single turn
* `multi_turn` - Multi turn
* `expected_answer` - Expected answer drafting (任意)
      {
      }
      "requestedNumTestCases"?: integer // 任意
      "totalFiles"?: integer // 任意
      "processedFiles"?: integer // 任意
      "generatedCount"?: integer // 任意
      "progressPercentage": number (double)
      "errorMessage"?: string // Error message recorded when the whole batch fails (任意)
      "fileResults"?: object // Result for each file, such as [{'file_id', 'filename', 'status', 'generated', 'error'}] (任意)
      "startedAt"?: string (timestamp) // 任意
      "completedAt"?: string (timestamp) // 任意
      "createdAt": string (timestamp)
      "updatedAt": string (timestamp)
    }
  ]
}
```

**レスポンス値の例**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "dataset": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス文字列"
      },
      "status": "pending",
      "jobType": {},
      "requestedNumTestCases": 456,
      "totalFiles": 456,
      "processedFiles": 456,
      "generatedCount": 456,
      "progressPercentage": 456,
      "errorMessage": "レスポンス文字列",
      "fileResults": null,
      "startedAt": "レスポンス文字列",
      "completedAt": "レスポンス文字列",
      "createdAt": "レスポンス文字列",
      "updatedAt": "レスポンス文字列"
    }
  ]
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### テストケース生成ジョブの進捗を取得する <a href="#test-case-generation-jobs-retrieve" id="test-case-generation-jobs-retrieve"></a>

GET `/api/v1/test-case/generation-jobs/{jobId}/`

{% hint style="info" %}
`status` は `pending`、`running`、`completed`、`partial_completed`、`failed` のいずれかです。`generatedCount` は生成済みの問題数、`fileResults` は各ファイルの結果と失敗理由を示します。単一ターンと複数ターンの生成ジョブはどちらもこのエンドポイントで取得でき、`jobType` で区別します。
{% endhint %}

#### パラメータ

| パラメータ名  | 必須 | 型      | 説明                                                      |
| ------- | -- | ------ | ------------------------------------------------------- |
| `jobId` | ✅  | string | 生成ジョブ ID。「ナレッジベースファイルからテストケースを生成する」のレスポンスで返される jobId です |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/test-case/generation-jobs/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/test-case/generation-jobs/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/test-case/generation-jobs/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/test-case/generation-jobs/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "dataset": 
  {
    "id": string (uuid)
    "name": string
  }
  "status"?: string (enum: pending, running, completed, partial_completed, failed) // * `pending` - Pending
* `running` - Generating
* `completed` - Completed
* `partial_completed` - Partially completed
* `failed` - Generation failed (任意)
  "jobType"?:  // Single-turn Q&A test data, multi-turn conversation test data, or AI-drafted expected answers for existing questions

* `single_turn` - Single turn
* `multi_turn` - Multi turn
* `expected_answer` - Expected answer drafting (任意)
  {
  }
  "requestedNumTestCases"?: integer // 任意
  "totalFiles"?: integer // 任意
  "processedFiles"?: integer // 任意
  "generatedCount"?: integer // 任意
  "progressPercentage": number (double)
  "errorMessage"?: string // Error message recorded when the whole batch fails (任意)
  "fileResults"?: object // Result for each file, such as [{'file_id', 'filename', 'status', 'generated', 'error'}] (任意)
  "startedAt"?: string (timestamp) // 任意
  "completedAt"?: string (timestamp) // 任意
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "dataset": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "status": "pending",
  "jobType": {},
  "requestedNumTestCases": 456,
  "totalFiles": 456,
  "processedFiles": 456,
  "generatedCount": 456,
  "progressPercentage": 456,
  "errorMessage": "レスポンス文字列",
  "fileResults": null,
  "startedAt": "レスポンス文字列",
  "completedAt": "レスポンス文字列",
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 単一ターンのテストケースを更新する <a href="#test-case-update" id="test-case-update"></a>

PUT `/api/v1/test-case/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明        |
| ------ | -- | ------ | --------- |
| `id`   | ✅  | string | テストケース ID |

#### リクエスト内容

**リクエストパラメータ**

| フィールド       | 型                                        | 必須  | 説明                                                                                      |
| ----------- | ---------------------------------------- | --- | --------------------------------------------------------------------------------------- |
| question    | string                                   | はい  |                                                                                         |
| groundTruth | string                                   | いいえ |                                                                                         |
| status      | string (enum: active, inactive, pending) | いいえ | `active`: Active ; `inactive`: Inactive ; `pending`: Pending Review;                    |
| flaky       | boolean                                  | いいえ | Flaky test cases still run and keep their results, but are excluded from the pass rate. |
| tags        | array\[string]                           | いいえ | Labels that pick the pass rule deciding this question; empty means untagged.            |

**リクエスト構造の例**

```typescript
{
  "question": string
  "groundTruth"?: string // 任意
  "status"?: string (enum: active, inactive, pending) // * `active` - Active
* `inactive` - Inactive
* `pending` - Pending Review (任意)
  "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
  "tags"?: [ // Labels that pick the pass rule deciding this question; empty means untagged. (任意)
    string
  ]
}
```

**リクエスト例の値**

```json
{
  "question": "サンプル文字列",
  "groundTruth": "サンプル文字列",
  "status": "active",
  "flaky": true,
  "tags": [
    "サンプル文字列"
  ]
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X PUT "https://api.maiagent.ai/api/v1/test-case/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "question": "サンプル文字列",
    "groundTruth": "サンプル文字列",
    "status": "active",
    "flaky": true,
    "tags": [
      "サンプル文字列"
    ]
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエスト内容 (payload)
const data = {
    "question": "サンプル文字列",
    "groundTruth": "サンプル文字列",
    "status": "active",
    "flaky": true,
    "tags": [
      "サンプル文字列"
    ]
  };

axios.put("https://api.maiagent.ai/api/v1/test-case/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/test-case/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエスト内容 (payload)
data = {
    "question": "サンプル文字列",
    "groundTruth": "サンプル文字列",
    "status": "active",
    "flaky": True,
    "tags": [
        "サンプル文字列"
    ]
}

response = requests.put(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->put("https://api.maiagent.ai/api/v1/test-case/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'question' => 'サンプル文字列',
            'groundTruth' => 'サンプル文字列',
            'status' => 'active',
            'flaky' => true,
            'tags' => [
                'サンプル文字列'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "dataset": 
  {
    "id": string (uuid)
    "name": string
  }
  "question": string
  "groundTruth"?: string // 任意
  "status"?: string (enum: active, inactive, pending) // * `active` - Active
* `inactive` - Inactive
* `pending` - Pending Review (任意)
  "creationMethod"?: string (enum: manual, file, generate) // * `manual` - Manual
* `file` - File import
* `generate` - Generated (任意)
  "sourceFile"?: string // Name of the CSV, Excel or knowledge base file this test case came from (任意)
  "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
  "tags"?: object // Labels that pick which pass rule decides this question. An empty list matches only rules that cover every question. (任意)
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "dataset": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "question": "レスポンス文字列",
  "groundTruth": "レスポンス文字列",
  "status": "active",
  "creationMethod": "manual",
  "sourceFile": "レスポンス文字列",
  "flaky": false,
  "tags": null,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 単一ターンのテストケースを部分更新する <a href="#test-case-partial-update" id="test-case-partial-update"></a>

PATCH `/api/v1/test-case/{id}/`

{% hint style="info" %}
特定の問題を一時的にテスト対象から外したい場合は、`status` を `inactive` に変更します。評価ではその問題がスキップされ、過去の評価結果は保持されます。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明        |
| ------ | -- | ------ | --------- |
| `id`   | ✅  | string | テストケース ID |

#### リクエスト内容

**リクエストパラメータ**

| フィールド       | 型                                        | 必須  | 説明                                                                                      |
| ----------- | ---------------------------------------- | --- | --------------------------------------------------------------------------------------- |
| question    | string                                   | いいえ |                                                                                         |
| groundTruth | string                                   | いいえ |                                                                                         |
| status      | string (enum: active, inactive, pending) | いいえ | `active`: Active ; `inactive`: Inactive ; `pending`: Pending Review;                    |
| flaky       | boolean                                  | いいえ | Flaky test cases still run and keep their results, but are excluded from the pass rate. |
| tags        | array\[string]                           | いいえ | Labels that pick the pass rule deciding this question; empty means untagged.            |

**リクエスト構造の例**

```typescript
{
  "question"?: string // 任意
  "groundTruth"?: string // 任意
  "status"?: string (enum: active, inactive, pending) // * `active` - Active
* `inactive` - Inactive
* `pending` - Pending Review (任意)
  "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
  "tags"?: [ // Labels that pick the pass rule deciding this question; empty means untagged. (任意)
    string
  ]
}
```

**リクエスト例の値**

```json
{
  "question": "サンプル文字列",
  "groundTruth": "サンプル文字列",
  "status": "active",
  "flaky": true,
  "tags": [
    "サンプル文字列"
  ]
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/test-case/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "question": "サンプル文字列",
    "groundTruth": "サンプル文字列",
    "status": "active",
    "flaky": true,
    "tags": [
      "サンプル文字列"
    ]
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエスト内容 (payload)
const data = {
    "question": "サンプル文字列",
    "groundTruth": "サンプル文字列",
    "status": "active",
    "flaky": true,
    "tags": [
      "サンプル文字列"
    ]
  };

axios.patch("https://api.maiagent.ai/api/v1/test-case/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/test-case/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエスト内容 (payload)
data = {
    "question": "サンプル文字列",
    "groundTruth": "サンプル文字列",
    "status": "active",
    "flaky": True,
    "tags": [
        "サンプル文字列"
    ]
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/test-case/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'question' => 'サンプル文字列',
            'groundTruth' => 'サンプル文字列',
            'status' => 'active',
            'flaky' => true,
            'tags' => [
                'サンプル文字列'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "dataset": 
  {
    "id": string (uuid)
    "name": string
  }
  "question": string
  "groundTruth"?: string // 任意
  "status"?: string (enum: active, inactive, pending) // * `active` - Active
* `inactive` - Inactive
* `pending` - Pending Review (任意)
  "creationMethod"?: string (enum: manual, file, generate) // * `manual` - Manual
* `file` - File import
* `generate` - Generated (任意)
  "sourceFile"?: string // Name of the CSV, Excel or knowledge base file this test case came from (任意)
  "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
  "tags"?: object // Labels that pick which pass rule decides this question. An empty list matches only rules that cover every question. (任意)
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "dataset": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "question": "レスポンス文字列",
  "groundTruth": "レスポンス文字列",
  "status": "active",
  "creationMethod": "manual",
  "sourceFile": "レスポンス文字列",
  "flaky": false,
  "tags": null,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

**ステータスコード: 4XX - エラーレスポンス。X-Error-Code にエラーコードが含まれます（「エラーコード」を参照）。**

***

### 単一ターンのテストケースの削除 <a href="#test-case-destroy" id="test-case-destroy"></a>

DELETE `/api/v1/test-case/{id}/`

{% hint style="info" %}
このテストケースの過去の評価における問題ごとの結果も合わせて削除されます。テストを一時停止したいだけの場合は、代わりに `status` を使用してください。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明        |
| ------ | -- | ------ | --------- |
| `id`   | ✅  | string | テストケース ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/test-case/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエストペイロード (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/test-case/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/test-case/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.delete(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/test-case/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

| ステータスコード | 説明                                                                 |
| -------- | ------------------------------------------------------------------ |
| 204      | No response body                                                   |
| 4XX      | Error response; X-Error-Code carries its code (see "Error codes"). |

***

### 単一ターンのテストケースを一括削除する <a href="#test-case-bulk-delete-create" id="test-case-bulk-delete-create"></a>

POST `/api/v1/test-case/bulk-delete/`

{% hint style="info" %}
削除するテストケース ID の配列を `testCaseIds` として渡します。成功すると `204` が返ります。削除の影響は [単一ターンのテストケースを削除する](#test-case-destroy) と同じです。
{% endhint %}

#### リクエスト内容

**リクエストパラメータ**

| フィールド           | 型              | 必須 | 説明                 |
| --------------- | -------------- | -- | ------------------ |
| test\_case\_ids | array\[string] | はい | 削除するテストケース ID のリスト |

**リクエスト構造の例**

```typescript
{
  "test_case_ids": [ // 削除するテストケース ID のリスト
    string (uuid)
  ]
}
```

**リクエスト例の値**

```json
{
  "test_case_ids": [
    "550e8400-e29b-41d4-a716-446655440000"
  ]
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/test-case/bulk-delete/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "test_case_ids": [
      "550e8400-e29b-41d4-a716-446655440000"
    ]
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストペイロード (payload)
const data = {
    "test_case_ids": [
      "550e8400-e29b-41d4-a716-446655440000"
    ]
  };

axios.post("https://api.maiagent.ai/api/v1/test-case/bulk-delete/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/test-case/bulk-delete/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエストペイロード (payload)
data = {
    "test_case_ids": [
        "550e8400-e29b-41d4-a716-446655440000"
    ]
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/test-case/bulk-delete/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'test_case_ids' => [
                '550e8400-e29b-41d4-a716-446655440000'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

| ステータスコード | 説明                                                                 |
| -------- | ------------------------------------------------------------------ |
| 204      | No response body                                                   |
| 4XX      | Error response; X-Error-Code carries its code (see "Error codes"). |

***

### マルチターンテストケース一覧の取得 <a href="#multi-turn-test-case-list" id="multi-turn-test-case-list"></a>

GET `/api/v1/multi-turn-test-case/`

{% hint style="info" %}
`datasetId` で単一のテストセットを絞り込みます。
{% endhint %}

#### パラメータ

| パラメータ名      | 必須 | 型       | 説明                                                                                                       |
| ----------- | -- | ------- | -------------------------------------------------------------------------------------------------------- |
| `dataset`   | ❌  | string  | datasetId と同じです。このデータセットのマルチターン対話テストケースのみを一覧表示します                                                        |
| `datasetId` | ❌  | string  | このデータセットのマルチターン対話テストケースのみを一覧表示します                                                                        |
| `ordering`  | ❌  | string  | 並べ替えフィールド：created\_at または updated\_at。先頭に - を付けると新しい順になります（例：-updated\_at）。未指定の場合は作成日時の新しい順です            |
| `page`      | ❌  | integer | ページ番号（1 から開始）。最終ページを超えると 404 を返します                                                                       |
| `pageSize`  | ❌  | integer | 1 ページあたりの件数。デフォルトは 20、上限は 100 です（100 を超える場合は 100 として扱います）                                                |
| `search`    | ❌  | string  | キーワード。シナリオ（scenario）または期待される結果（expected\_outcome）に部分一致します（大文字小文字は区別しません。空白で区切って複数指定した場合はすべてに一致する必要があります） |
| `status`    | ❌  | string  | このステータスのマルチターン対話テストケースのみを一覧表示します。使用可能な値： \`active\`: Active ; \`inactive\`: Inactive;                    |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/multi-turn-test-case/?dataset=550e8400-e29b-41d4-a716-446655440000&datasetId=550e8400-e29b-41d4-a716-446655440000&ordering=example&page=1&pageSize=1&search=example&status=active" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/multi-turn-test-case/?dataset=550e8400-e29b-41d4-a716-446655440000&datasetId=550e8400-e29b-41d4-a716-446655440000&ordering=example&page=1&pageSize=1&search=example&status=active", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/multi-turn-test-case/?dataset=550e8400-e29b-41d4-a716-446655440000&datasetId=550e8400-e29b-41d4-a716-446655440000&ordering=example&page=1&pageSize=1&search=example&status=active"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/multi-turn-test-case/?dataset=550e8400-e29b-41d4-a716-446655440000&datasetId=550e8400-e29b-41d4-a716-446655440000&ordering=example&page=1&pageSize=1&search=example&status=active", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "id": string (uuid)
      "dataset": 
      {
        "id": string (uuid)
        "name": string
      }
      "scenario": string // Task scenario the simulated user should accomplish
      "expectedOutcome": string // Outcome a successful conversation should reach, also used as the simulation stop condition
      "userDescription"?: string // Persona of the simulated user, such as tone, background and level of expertise (任意)
      "status"?: string (enum: active, inactive) // * `active` - Active
* `inactive` - Inactive (任意)
      "creationMethod": 
      {
      }
      "sourceFile": string // Name of the knowledge base file this multi-turn test case was generated from
      "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
      "createdAt": string (timestamp)
      "updatedAt": string (timestamp)
    }
  ]
}
```

**レスポンス値の例**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "dataset": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス文字列"
      },
      "scenario": "レスポンス文字列",
      "expectedOutcome": "レスポンス文字列",
      "userDescription": "レスポンス文字列",
      "status": "active",
      "creationMethod": {},
      "sourceFile": "レスポンス文字列",
      "flaky": false,
      "createdAt": "レスポンス文字列",
      "updatedAt": "レスポンス文字列"
    }
  ]
}
```

***

### 複数ターンのテストケースを作成する <a href="#multi-turn-test-case-create" id="multi-turn-test-case-create"></a>

POST `/api/v1/multi-turn-test-case/`

{% hint style="info" %}
`datasetId`、`scenario`（シミュレートされたユーザーが達成すべきタスクシナリオ）、`expectedOutcome`（会話が成功した場合に到達すべき結果で、シミュレーション会話の終了条件にもなります）は必須です。`userDescription` は任意で、シミュレートされたユーザーの口調、背景、専門レベルを記述します。
{% endhint %}

#### リクエスト内容

**リクエストパラメータ**

| フィールド           | 型             | 必須  | 説明 |
| --------------- | ------------- | --- | -- |
| datasetId       | string (uuid) | はい  |    |
| scenario        | string        | はい  |    |
| expectedOutcome | string        | はい  |    |
| userDescription | string        | いいえ |    |
| status          | object        | いいえ |    |
| flaky           | boolean       | いいえ |    |

**リクエスト構造の例**

```typescript
{
  "datasetId": string (uuid)
  "scenario": string
  "expectedOutcome": string
  "userDescription"?: string // 任意
  "status"?:  // 任意
  {
  }
  "flaky"?: boolean // 任意
}
```

**リクエスト値の例**

```json
{
  "datasetId": "550e8400-e29b-41d4-a716-446655440000",
  "scenario": "サンプル文字列",
  "expectedOutcome": "サンプル文字列",
  "userDescription": "サンプル文字列",
  "status": {},
  "flaky": true
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出し例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/multi-turn-test-case/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "datasetId": "550e8400-e29b-41d4-a716-446655440000",
    "scenario": "サンプル文字列",
    "expectedOutcome": "サンプル文字列",
    "userDescription": "サンプル文字列",
    "status": {},
    "flaky": true
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエスト内容 (payload)
const data = {
    "datasetId": "550e8400-e29b-41d4-a716-446655440000",
    "scenario": "サンプル文字列",
    "expectedOutcome": "サンプル文字列",
    "userDescription": "サンプル文字列",
    "status": {},
    "flaky": true
  };

axios.post("https://api.maiagent.ai/api/v1/multi-turn-test-case/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/multi-turn-test-case/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエスト内容 (payload)
data = {
    "datasetId": "550e8400-e29b-41d4-a716-446655440000",
    "scenario": "サンプル文字列",
    "expectedOutcome": "サンプル文字列",
    "userDescription": "サンプル文字列",
    "status": {},
    "flaky": True
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/multi-turn-test-case/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'datasetId' => '550e8400-e29b-41d4-a716-446655440000',
            'scenario' => 'サンプル文字列',
            'expectedOutcome' => 'サンプル文字列',
            'userDescription' => 'サンプル文字列',
            'status' => new \stdClass(),
            'flaky' => true
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 201**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "dataset": 
  {
    "id": string (uuid)
    "name": string
  }
  "scenario": string // Task scenario the simulated user should accomplish
  "expectedOutcome": string // Outcome a successful conversation should reach, also used as the simulation stop condition
  "userDescription"?: string // Persona of the simulated user, such as tone, background and level of expertise (任意)
  "status"?: string (enum: active, inactive) // * `active` - Active
* `inactive` - Inactive (任意)
  "creationMethod": 
  {
  }
  "sourceFile": string // Name of the knowledge base file this multi-turn test case was generated from
  "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "dataset": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "scenario": "レスポンス文字列",
  "expectedOutcome": "レスポンス文字列",
  "userDescription": "レスポンス文字列",
  "status": "active",
  "creationMethod": {},
  "sourceFile": "レスポンス文字列",
  "flaky": false,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

***

### ナレッジベースファイルからマルチターンテストケースを生成する <a href="#multi-turn-test-case-generate-from-file-create" id="multi-turn-test-case-generate-from-file-create"></a>

POST `/api/v1/multi-turn-test-case/generate-from-file/`

{% hint style="info" %}
`knowledgeBaseFileIds` でソースファイルを指定します。`numTestCases` のデフォルトは 5、最大は 20 です。生成はバックグラウンドで実行され、レスポンスは `202` と `jobId` です。[テストケース生成ジョブの進捗を取得する](#test-case-generation-jobs-retrieve) で進捗を確認できます。**Credit**：シングルターン生成と同様に、実際に生成された問題数に応じて `agentops_test_gen` が差し引かれます。
{% endhint %}

#### リクエスト内容

**リクエストパラメータ**

| フィールド                | 型              | 必須  | 説明                                                                   |
| -------------------- | -------------- | --- | -------------------------------------------------------------------- |
| datasetId            | string (uuid)  | はい  |                                                                      |
| knowledgeBaseFileIds | array\[string] | はい  | List of KnowledgeBaseFile IDs to generate multi-turn test cases from |
| numTestCases         | integer        | いいえ |                                                                      |

**リクエスト構造の例**

```typescript
{
  "datasetId": string (uuid)
  "knowledgeBaseFileIds": [ // List of KnowledgeBaseFile IDs to generate multi-turn test cases from
    string (uuid)
  ]
  "numTestCases"?: integer // 任意
}
```

**リクエスト値の例**

```json
{
  "datasetId": "550e8400-e29b-41d4-a716-446655440000",
  "knowledgeBaseFileIds": [
    "550e8400-e29b-41d4-a716-446655440000"
  ],
  "numTestCases": 123
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出し例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/multi-turn-test-case/generate-from-file/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "datasetId": "550e8400-e29b-41d4-a716-446655440000",
    "knowledgeBaseFileIds": [
      "550e8400-e29b-41d4-a716-446655440000"
    ],
    "numTestCases": 123
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエスト内容 (payload)
const data = {
    "datasetId": "550e8400-e29b-41d4-a716-446655440000",
    "knowledgeBaseFileIds": [
      "550e8400-e29b-41d4-a716-446655440000"
    ],
    "numTestCases": 123
  };

axios.post("https://api.maiagent.ai/api/v1/multi-turn-test-case/generate-from-file/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/multi-turn-test-case/generate-from-file/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエスト内容 (payload)
data = {
    "datasetId": "550e8400-e29b-41d4-a716-446655440000",
    "knowledgeBaseFileIds": [
        "550e8400-e29b-41d4-a716-446655440000"
    ],
    "numTestCases": 123
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/multi-turn-test-case/generate-from-file/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'datasetId' => '550e8400-e29b-41d4-a716-446655440000',
            'knowledgeBaseFileIds' => [
                '550e8400-e29b-41d4-a716-446655440000'
            ],
            'numTestCases' => 123
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 202**

**レスポンス構造の例**

```typescript
{
  "status": string (enum: accepted) // * `accepted` - 常に accepted。リクエストが受理され、バックグラウンド実行のキューに追加されたことを示します
  "message": string // 受理メッセージ
  "jobId": string (uuid) // 生成ジョブ ID。GET /api/v1/test-case/generation-jobs/{jobId}/ で進捗を確認できます。同じテストセットで生成ジョブがすでに実行中の場合は、そのジョブが返されます
  "taskId": string // バックグラウンドタスク ID
}
```

**レスポンス値の例**

```json
{
  "status": "accepted",
  "message": "レスポンス文字列",
  "jobId": "550e8400-e29b-41d4-a716-446655440000",
  "taskId": "レスポンス文字列"
}
```

***

### 特定のマルチターンテストケースを取得する <a href="#multi-turn-test-case-retrieve" id="multi-turn-test-case-retrieve"></a>

GET `/api/v1/multi-turn-test-case/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明                |
| ------ | -- | ------ | ----------------- |
| `id`   | ✅  | string | マルチターン対話テストケース ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出し例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "dataset": 
  {
    "id": string (uuid)
    "name": string
  }
  "scenario": string // Task scenario the simulated user should accomplish
  "expectedOutcome": string // Outcome a successful conversation should reach, also used as the simulation stop condition
  "userDescription"?: string // Persona of the simulated user, such as tone, background and level of expertise (任意)
  "status"?: string (enum: active, inactive) // * `active` - Active
* `inactive` - Inactive (任意)
  "creationMethod": 
  {
  }
  "sourceFile": string // Name of the knowledge base file this multi-turn test case was generated from
  "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "dataset": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "scenario": "レスポンス文字列",
  "expectedOutcome": "レスポンス文字列",
  "userDescription": "レスポンス文字列",
  "status": "active",
  "creationMethod": {},
  "sourceFile": "レスポンス文字列",
  "flaky": false,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

***

### マルチターンテストケースを更新する <a href="#multi-turn-test-case-update" id="multi-turn-test-case-update"></a>

PUT `/api/v1/multi-turn-test-case/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明                |
| ------ | -- | ------ | ----------------- |
| `id`   | ✅  | string | マルチターン対話テストケース ID |

#### リクエスト内容

**リクエストパラメータ**

| フィールド           | 型                               | 必須  | 説明                                                                                         |
| --------------- | ------------------------------- | --- | ------------------------------------------------------------------------------------------ |
| scenario        | string                          | はい  | Task scenario the simulated user should accomplish                                         |
| expectedOutcome | string                          | はい  | Outcome a successful conversation should reach, also used as the simulation stop condition |
| userDescription | string                          | いいえ | Persona of the simulated user, such as tone, background and level of expertise             |
| status          | string (enum: active, inactive) | いいえ | `active`: Active ; `inactive`: Inactive;                                                   |
| flaky           | boolean                         | いいえ | Flaky test cases still run and keep their results, but are excluded from the pass rate.    |

**リクエスト構造の例**

```typescript
{
  "scenario": string // Task scenario the simulated user should accomplish
  "expectedOutcome": string // Outcome a successful conversation should reach, also used as the simulation stop condition
  "userDescription"?: string // Persona of the simulated user, such as tone, background and level of expertise (任意)
  "status"?: string (enum: active, inactive) // * `active` - Active
* `inactive` - Inactive (任意)
  "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
}
```

**リクエスト値の例**

```json
{
  "scenario": "サンプル文字列",
  "expectedOutcome": "サンプル文字列",
  "userDescription": "サンプル文字列",
  "status": "active",
  "flaky": true
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出し例 (Shell)
curl -X PUT "https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "scenario": "サンプル文字列",
    "expectedOutcome": "サンプル文字列",
    "userDescription": "サンプル文字列",
    "status": "active",
    "flaky": true
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエスト内容 (payload)
const data = {
    "scenario": "サンプル文字列",
    "expectedOutcome": "サンプル文字列",
    "userDescription": "サンプル文字列",
    "status": "active",
    "flaky": true
  };

axios.put("https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエスト内容 (payload)
data = {
    "scenario": "サンプル文字列",
    "expectedOutcome": "サンプル文字列",
    "userDescription": "サンプル文字列",
    "status": "active",
    "flaky": True
}

response = requests.put(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->put("https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'scenario' => 'サンプル文字列',
            'expectedOutcome' => 'サンプル文字列',
            'userDescription' => 'サンプル文字列',
            'status' => 'active',
            'flaky' => true
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "dataset": 
  {
    "id": string (uuid)
    "name": string
  }
  "scenario": string // Task scenario the simulated user should accomplish
  "expectedOutcome": string // Outcome a successful conversation should reach, also used as the simulation stop condition
  "userDescription"?: string // Persona of the simulated user, such as tone, background and level of expertise (任意)
  "status"?: string (enum: active, inactive) // * `active` - Active
* `inactive` - Inactive (任意)
  "creationMethod": 
  {
  }
  "sourceFile": string // Name of the knowledge base file this multi-turn test case was generated from
  "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "dataset": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "scenario": "レスポンス文字列",
  "expectedOutcome": "レスポンス文字列",
  "userDescription": "レスポンス文字列",
  "status": "active",
  "creationMethod": {},
  "sourceFile": "レスポンス文字列",
  "flaky": false,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

***

### マルチターンテストケースを部分更新する <a href="#multi-turn-test-case-partial-update" id="multi-turn-test-case-partial-update"></a>

PATCH `/api/v1/multi-turn-test-case/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明                |
| ------ | -- | ------ | ----------------- |
| `id`   | ✅  | string | マルチターン対話テストケース ID |

#### リクエスト内容

**リクエストパラメータ**

| フィールド           | 型                               | 必須  | 説明                                                                                         |
| --------------- | ------------------------------- | --- | ------------------------------------------------------------------------------------------ |
| scenario        | string                          | いいえ | Task scenario the simulated user should accomplish                                         |
| expectedOutcome | string                          | いいえ | Outcome a successful conversation should reach, also used as the simulation stop condition |
| userDescription | string                          | いいえ | Persona of the simulated user, such as tone, background and level of expertise             |
| status          | string (enum: active, inactive) | いいえ | `active`: Active ; `inactive`: Inactive;                                                   |
| flaky           | boolean                         | いいえ | Flaky test cases still run and keep their results, but are excluded from the pass rate.    |

**リクエスト構造の例**

```typescript
{
  "scenario"?: string // Task scenario the simulated user should accomplish (任意)
  "expectedOutcome"?: string // Outcome a successful conversation should reach, also used as the simulation stop condition (任意)
  "userDescription"?: string // Persona of the simulated user, such as tone, background and level of expertise (任意)
  "status"?: string (enum: active, inactive) // * `active` - Active
* `inactive` - Inactive (任意)
  "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
}
```

**リクエスト値の例**

```json
{
  "scenario": "サンプル文字列",
  "expectedOutcome": "サンプル文字列",
  "userDescription": "サンプル文字列",
  "status": "active",
  "flaky": true
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出し例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "scenario": "サンプル文字列",
    "expectedOutcome": "サンプル文字列",
    "userDescription": "サンプル文字列",
    "status": "active",
    "flaky": true
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエスト内容 (payload)
const data = {
    "scenario": "サンプル文字列",
    "expectedOutcome": "サンプル文字列",
    "userDescription": "サンプル文字列",
    "status": "active",
    "flaky": true
  };

axios.patch("https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエスト内容 (payload)
data = {
    "scenario": "サンプル文字列",
    "expectedOutcome": "サンプル文字列",
    "userDescription": "サンプル文字列",
    "status": "active",
    "flaky": True
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'scenario' => 'サンプル文字列',
            'expectedOutcome' => 'サンプル文字列',
            'userDescription' => 'サンプル文字列',
            'status' => 'active',
            'flaky' => true
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "dataset": 
  {
    "id": string (uuid)
    "name": string
  }
  "scenario": string // Task scenario the simulated user should accomplish
  "expectedOutcome": string // Outcome a successful conversation should reach, also used as the simulation stop condition
  "userDescription"?: string // Persona of the simulated user, such as tone, background and level of expertise (任意)
  "status"?: string (enum: active, inactive) // * `active` - Active
* `inactive` - Inactive (任意)
  "creationMethod": 
  {
  }
  "sourceFile": string // Name of the knowledge base file this multi-turn test case was generated from
  "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "dataset": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "scenario": "レスポンス文字列",
  "expectedOutcome": "レスポンス文字列",
  "userDescription": "レスポンス文字列",
  "status": "active",
  "creationMethod": {},
  "sourceFile": "レスポンス文字列",
  "flaky": false,
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

***

### マルチターンテストケースを削除する <a href="#multi-turn-test-case-destroy" id="multi-turn-test-case-destroy"></a>

DELETE `/api/v1/multi-turn-test-case/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明                |
| ------ | -- | ------ | ----------------- |
| `id`   | ✅  | string | マルチターン対話テストケース ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出し例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエスト内容 (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.delete(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/multi-turn-test-case/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

| ステータスコード | 説明               |
| -------- | ---------------- |
| 204      | No response body |

***

### 利用可能な評価モデルの一覧取得 <a href="#evaluations-evaluation-llms-list" id="evaluations-evaluation-llms-list"></a>

GET `/api/v1/evaluations/evaluation-llms/`

{% hint style="info" %}
`isDefault` が `true` のモデルは、評価の実行時に `evaluationLlmId` を指定しなかった場合に使用されるデフォルトの評価モデルです。
{% endhint %}

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/evaluations/evaluation-llms/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/evaluations/evaluation-llms/", config)
  .then(response => {
    console.log('レスポンスの取得に成功しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/evaluation-llms/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスの取得に成功しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/evaluations/evaluation-llms/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスの取得に成功しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
[
  {
    "id": string (uuid)
    "name": string
    "value": string
    "provider": string
    "isDefault": boolean
  }
]
```

**レスポンス値の例**

```json
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列",
    "value": "レスポンス文字列",
    "provider": "レスポンス文字列",
    "isDefault": false
  }
]
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 単一ターン評価の実行 <a href="#evaluations-evaluate-create" id="evaluations-evaluate-create"></a>

POST `/api/v1/evaluations/evaluate/`

{% hint style="info" %}
`datasetId` と `chatbotId` は必須です。`evaluationLlmId` を省略した場合は、デフォルトの評価モデルが使用されます。`metricConfig` は組み込み指標をブール値で切り替え、`customMetrics` ではカスタム指標を最大 10 個まで指定できます。評価対象はステータスが `active` のテストケースのみです。評価はバックグラウンドで実行され、レスポンスとして `202` と `evaluationId` が返されます。**Credit**：送信前に組織の Credit を確認し、不足している場合は `402` を返します。評価の終了時に、完了したテストケース数に応じて `agentops_test_run` と `agentops_deepeval` が差し引かれます。評価モデルの呼び出しは別途計上されます。
{% endhint %}

#### リクエスト内容

**リクエストパラメータ**

| フィールド            | 型                                     | 必須  | 説明                                                                                              |
| ---------------- | ------------------------------------- | --- | ----------------------------------------------------------------------------------------------- |
| datasetId        | string (uuid)                         | はい  |                                                                                                 |
| chatbotId        | string (uuid)                         | はい  |                                                                                                 |
| evaluationLlmId  | string (uuid)                         | いいえ |                                                                                                 |
| name             | string                                | いいえ |                                                                                                 |
| description      | string                                | いいえ |                                                                                                 |
| metricConfig     | object                                | いいえ |                                                                                                 |
| customMetrics    | array\[DatasetEvaluationCustomMetric] | いいえ |                                                                                                 |
| passPolicy       | object (1 個のプロパティ: rules)             | いいえ | Which metrics decide "passed"; omitted or null keeps the tiered rule over every enabled metric. |
| passPolicy.rules | array\[PassRule]                      | はい  | Checked in order: the first matching rule decides a question, and the last one is the default.  |

**リクエスト構造の例**

```typescript
{
  "datasetId": string (uuid)
  "chatbotId": string (uuid)
  "evaluationLlmId"?: string (uuid) // 任意
  "name"?: string // 任意
  "description"?: string // 任意
  "metricConfig"?: object // 任意
  "customMetrics"?: [ // 任意
    {
      "name": string
      "criteria"?: string // 任意
      "evaluationSteps"?: [ // 任意
        string
      ]
      "threshold"?: number (double) // 任意
      "includeExpectedOutput"?: boolean // Also give the judge the test case's expected answer; questions without one are skipped. (任意)
    }
  ]
  "passPolicy"?:  // Which metrics decide "passed"; omitted or null keeps the tiered rule over every enabled metric. (任意)
  {
    "rules": [ // Checked in order: the first matching rule decides a question, and the last one is the default.
      {
        "id": string
        "name": string
        "when": string // "always", or {"tags_any": [...]} / {"tags_all": [...]}.
        "metrics"?: [ // Result keys this rule runs; omitted runs every metric the evaluation enables. (任意)
          string
        ]
        "verdict": { // What counts as pass: the tiered rule, or every listed gate metric passing.
        {
          "type": string (enum: tiered, gates) // * `tiered` - tiered
* `gates` - gates
          "gates"?: [ // Result keys (as stored in metric_scores) that must all pass; gates verdict only. (任意)
            string
          ]
        }
        }
      }
    ]
  }
}
```

**リクエスト値の例**

```json
{
  "dataset_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "chatbot_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "evaluation_llm_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "name": "Evaluation Name",
  "description": "Evaluation Description",
  "metric_config": {
    "ground_truth": true,
    "task_completion": false,
    "tool_correctness": false,
    "guardrail": true,
    "summarize": false,
    "hallucination": true
  },
  "custom_metrics": [
    {
      "name": "Support Tone",
      "criteria": "The answer should be polite, empathetic, and professional in tone.",
      "threshold": 0.6
    }
  ]
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/evaluations/evaluate/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "dataset_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "chatbot_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "evaluation_llm_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "name": "Evaluation Name",
    "description": "Evaluation Description",
    "metric_config": {
      "ground_truth": true,
      "task_completion": false,
      "tool_correctness": false,
      "guardrail": true,
      "summarize": false,
      "hallucination": true
    },
    "custom_metrics": [
      {
        "name": "Support Tone",
        "criteria": "The answer should be polite, empathetic, and professional in tone.",
        "threshold": 0.6
      }
    ]
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエスト内容 (payload)
const data = {
    "dataset_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "chatbot_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "evaluation_llm_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "name": "Evaluation Name",
    "description": "Evaluation Description",
    "metric_config": {
      "ground_truth": true,
      "task_completion": false,
      "tool_correctness": false,
      "guardrail": true,
      "summarize": false,
      "hallucination": true
    },
    "custom_metrics": [
      {
        "name": "Support Tone",
        "criteria": "The answer should be polite, empathetic, and professional in tone.",
        "threshold": 0.6
      }
    ]
  };

axios.post("https://api.maiagent.ai/api/v1/evaluations/evaluate/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/evaluate/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエスト内容 (payload)
data = {
    "dataset_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "chatbot_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "evaluation_llm_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "name": "Evaluation Name",
    "description": "Evaluation Description",
    "metric_config": {
        "ground_truth": True,
        "task_completion": False,
        "tool_correctness": False,
        "guardrail": True,
        "summarize": False,
        "hallucination": True
    },
    "custom_metrics": [
        {
            "name": "Support Tone",
            "criteria": "The answer should be polite, empathetic, and professional in tone.",
            "threshold": 0.6
        }
    ]
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/evaluations/evaluate/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'dataset_id' => '3fa85f64-5717-4562-b3fc-2c963f66afa6',
            'chatbot_id' => '3fa85f64-5717-4562-b3fc-2c963f66afa6',
            'evaluation_llm_id' => '3fa85f64-5717-4562-b3fc-2c963f66afa6',
            'name' => 'Evaluation Name',
            'description' => 'Evaluation Description',
            'metric_config' => [
                'ground_truth' => true,
                'task_completion' => false,
                'tool_correctness' => false,
                'guardrail' => true,
                'summarize' => false,
                'hallucination' => true
            ],
            'custom_metrics' => [
                [
                    'name' => 'Support Tone',
                    'criteria' => 'The answer should be polite, empathetic, and professional in tone.',
                    'threshold' => 0.6
                ]
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 202**

**レスポンス構造の例**

```typescript
{
  "status": string (enum: accepted) // * `accepted` - 常に accepted。リクエストが受理され、バックグラウンド実行のキューに追加されたことを示します
  "message": string // 受理メッセージ
  "evaluationId": string (uuid) // 評価 ID。GET /api/v1/evaluations/{id}/ で status をポーリングして終了を確認できます
}
```

**レスポンス値の例**

```json
{
  "status": "accepted",
  "message": "レスポンス文字列",
  "evaluationId": "550e8400-e29b-41d4-a716-446655440000"
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### マルチターン評価の実行 <a href="#evaluations-multi-turn-evaluate-create" id="evaluations-multi-turn-evaluate-create"></a>

POST `/api/v1/evaluations/multi-turn-evaluate/`

{% hint style="info" %}
データセット内のマルチターンテストケースを使い、ユーザーと Agent の会話をシミュレーションしてスコアリングします。`maxTurns` はシミュレーションされるユーザーが発話する最大ターン数（2～10、デフォルトは 6）、`language` はシミュレーションされるユーザーの言語（`Traditional Chinese`、`Simplified Chinese`、`English`、`Japanese`、`Korean`、デフォルトは `Traditional Chinese`）です。データセットに `active` なマルチターンテストケースが 1 件もない場合は `400` を返します。レスポンスと Credit は [単一ターン評価の実行](#evaluations-evaluate-create) と同じです。
{% endhint %}

#### リクエスト

**リクエストパラメータ**

| フィールド                    | 型                             | 必須  | 説明 |
| ------------------------ | ----------------------------- | --- | -- |
| datasetId                | string (uuid)                 | はい  |    |
| chatbotId                | string (uuid)                 | はい  |    |
| evaluationLlmId          | string (uuid)                 | いいえ |    |
| name                     | string                        | いいえ |    |
| description              | string                        | いいえ |    |
| maxTurns                 | integer                       | いいえ |    |
| minTurns                 | integer                       | いいえ |    |
| turnFaithfulness         | boolean                       | いいえ |    |
| turnRelevancy            | boolean                       | いいえ |    |
| conversationCompleteness | boolean                       | いいえ |    |
| language                 | object                        | いいえ |    |
| customMetrics            | array\[MultiTurnCustomMetric] | いいえ |    |

**リクエストスキーマの例**

```typescript
{
  "datasetId": string (uuid)
  "chatbotId": string (uuid)
  "evaluationLlmId"?: string (uuid) // 任意
  "name"?: string // 任意
  "description"?: string // 任意
  "maxTurns"?: integer // 任意
  "minTurns"?: integer // 任意
  "turnFaithfulness"?: boolean // 任意
  "turnRelevancy"?: boolean // 任意
  "conversationCompleteness"?: boolean // 任意
  "language"?:  // 任意
  {
  }
  "customMetrics"?: [ // 任意
    {
      "name": string
      "criteria"?: string // 任意
      "evaluationSteps"?: [ // 任意
        string
      ]
      "threshold"?: number (double) // 任意
    }
  ]
}
```

**リクエスト値の例**

```json
{
  "dataset_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "chatbot_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "max_turns": 6,
  "min_turns": 2,
  "custom_metrics": [
    {
      "name": "Identity Check",
      "criteria": "The assistant confirms the user identity before sharing account details.",
      "threshold": 0.6
    }
  ]
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/evaluations/multi-turn-evaluate/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "dataset_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "chatbot_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "max_turns": 6,
    "min_turns": 2,
    "custom_metrics": [
      {
        "name": "Identity Check",
        "criteria": "The assistant confirms the user identity before sharing account details.",
        "threshold": 0.6
      }
    ]
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストペイロード
const data = {
    "dataset_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "chatbot_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "max_turns": 6,
    "min_turns": 2,
    "custom_metrics": [
      {
        "name": "Identity Check",
        "criteria": "The assistant confirms the user identity before sharing account details.",
        "threshold": 0.6
      }
    ]
  };

axios.post("https://api.maiagent.ai/api/v1/evaluations/multi-turn-evaluate/", data, config)
  .then(response => {
    console.log('レスポンスの取得に成功しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/multi-turn-evaluate/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエストペイロード
data = {
    "dataset_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "chatbot_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "max_turns": 6,
    "min_turns": 2,
    "custom_metrics": [
        {
            "name": "Identity Check",
            "criteria": "The assistant confirms the user identity before sharing account details.",
            "threshold": 0.6
        }
    ]
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスの取得に成功しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/evaluations/multi-turn-evaluate/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'dataset_id' => '3fa85f64-5717-4562-b3fc-2c963f66afa6',
            'chatbot_id' => '3fa85f64-5717-4562-b3fc-2c963f66afa6',
            'max_turns' => 6,
            'min_turns' => 2,
            'custom_metrics' => [
                [
                    'name' => 'Identity Check',
                    'criteria' => 'The assistant confirms the user identity before sharing account details.',
                    'threshold' => 0.6
                ]
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスの取得に成功しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス

**ステータスコード: 202**

**レスポンススキーマの例**

```typescript
{
  "status": string (enum: accepted) // * `accepted` - 常に accepted で、リクエストが受理されバックグラウンド実行のキューに入ったことを示します
  "message": string // 受理メッセージ
  "evaluationId": string (uuid) // 評価 ID。GET /api/v1/evaluations/{id}/ で status をポーリングして終了を確認できます
}
```

**レスポンス値の例**

```json
{
  "status": "accepted",
  "message": "レスポンス文字列",
  "evaluationId": "550e8400-e29b-41d4-a716-446655440000"
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 評価の一覧 <a href="#evaluations-list" id="evaluations-list"></a>

GET `/api/v1/evaluations/`

{% hint style="info" %}
`datasetId`、`chatbotId`、`status` で絞り込めます。
{% endhint %}

#### パラメータ

| パラメータ名           | 必須 | 型       | 説明                                                                                                                                                                                                                        |
| ---------------- | -- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `chatbotId`      | ❌  | string  | この AI アシスタントの評価のみを一覧表示します                                                                                                                                                                                                 |
| `datasetId`      | ❌  | string  | このデータセットを使用する評価のみを一覧表示します                                                                                                                                                                                                 |
| `excludeBuiltIn` | ❌  | string  | true の場合、公式の組み込み Agent（Agent マーケットプレイスからレンタルして作成されたロック済みインスタンス）のデータを除外し、組織が自作したアシスタントのみを対象にします。「自作としてコピー」で作成されたコピーは自作として扱われます。指定しない場合や false の場合は、この条件を付けない場合と同じです。                                                       |
| `ordering`       | ❌  | string  | 並べ替えフィールド：created\_at または updated\_at。先頭に - を付けると新しい順になります（例：-updated\_at）。未指定の場合は作成日時の新しい順です                                                                                                                             |
| `page`           | ❌  | integer | ページ番号（1 から開始）。最終ページを超えると 404 を返します                                                                                                                                                                                        |
| `pageSize`       | ❌  | integer | 1 ページあたりの件数。デフォルトは 20、上限は 100 です（100 を超える場合は 100 として扱われます）                                                                                                                                                                |
| `query`          | ❌  | string  | キーワード。評価名、説明、ID に対して部分一致で照合します                                                                                                                                                                                            |
| `search`         | ❌  | string  | キーワード。評価名、データセット名、AI アシスタント名に対して照合します（部分一致、大文字小文字は区別しません。スペース区切りで複数のキーワードを指定した場合は、すべてに一致する必要があります）                                                                                                                        |
| `status`         | ❌  | string  | このステータスの評価のみを一覧表示します。使用可能な値： \`pending\`: Pending evaluation ; \`running\`: Evaluating ; \`stopping\`: Stopping ; \`completed\`: Completed ; \`partial\_completed\`: Partially completed ; \`failed\`: Evaluation failed; |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/evaluations/?chatbotId=550e8400-e29b-41d4-a716-446655440000&datasetId=550e8400-e29b-41d4-a716-446655440000&excludeBuiltIn=example&ordering=example&page=1&pageSize=1&query=example&search=example&status=completed" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/evaluations/?chatbotId=550e8400-e29b-41d4-a716-446655440000&datasetId=550e8400-e29b-41d4-a716-446655440000&excludeBuiltIn=example&ordering=example&page=1&pageSize=1&query=example&search=example&status=completed", config)
  .then(response => {
    console.log('レスポンスを取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/?chatbotId=550e8400-e29b-41d4-a716-446655440000&datasetId=550e8400-e29b-41d4-a716-446655440000&excludeBuiltIn=example&ordering=example&page=1&pageSize=1&query=example&search=example&status=completed"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/evaluations/?chatbotId=550e8400-e29b-41d4-a716-446655440000&datasetId=550e8400-e29b-41d4-a716-446655440000&excludeBuiltIn=example&ordering=example&page=1&pageSize=1&query=example&search=example&status=completed", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "id": string (uuid)
      "name": string
      "description": string
      "chatbot": 
      {
        "id": string (uuid)
        "name": string
      }
      "dataset": 
      {
        "id": string (uuid)
        "name": string
      }
      "organization": 
      {
        "id": string (uuid)
        "name": string
      }
      "evaluationLlm": 
      {
        "id": string (uuid)
        "name": string
      }
      "status": 
      {
      }
      "queuedAt": string (timestamp) // Set while a pending evaluation is held back by the per-organization running cap and has not been sent to the workers yet; cleared when it is released. Deliberately not a status value: a held run is still pending to the frontend.
      "startedAt": string (timestamp)
      "completedAt": string (timestamp)
      "totalTestCases": integer
      "completedTestCases": integer
      "passedTestCases": integer // Number of test cases that passed
      "metricScores": object // Detailed score per evaluation metric, such as ground_truth, task_completion and tool_correctness
      "evaluationConfig": object
      "progressPercentage": number (double)
      "overallScore": number (double)
      "passRate": number (double)
      "averageExecutionTimeMs": integer
      "totalExecutionTimeMs": integer
      "chatbotConfig": string
      "createdAt": string (timestamp)
      "updatedAt": string (timestamp)
      "insights": 
      {
        "summary": string
        "metricStats"?: object // 任意
        "recommendations"?: object // 任意
      }
    }
  ]
}
```

**レスポンス値の例**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンス文字列",
      "description": "レスポンス文字列",
      "chatbot": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス文字列"
      },
      "dataset": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス文字列"
      },
      "organization": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス文字列"
      },
      "evaluationLlm": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス文字列"
      },
      "status": {},
      "queuedAt": "レスポンス文字列",
      "startedAt": "レスポンス文字列",
      "completedAt": "レスポンス文字列",
      "totalTestCases": 456,
      "completedTestCases": 456,
      "passedTestCases": 456,
      "metricScores": null,
      "evaluationConfig": null,
      "progressPercentage": 456,
      "overallScore": 456,
      "passRate": 456,
      "averageExecutionTimeMs": 456,
      "totalExecutionTimeMs": 456,
      "chatbotConfig": "レスポンス文字列",
      "createdAt": "レスポンス文字列",
      "updatedAt": "レスポンス文字列",
      "insights": {
        "summary": "レスポンス文字列",
        "metricStats": null,
        "recommendations": null
      }
    }
  ]
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 評価結果の取得 <a href="#evaluations-retrieve" id="evaluations-retrieve"></a>

GET `/api/v1/evaluations/{id}/`

{% hint style="info" %}
`status` は `pending`、`running`、`stopping`、`completed`、`partial_completed`、`failed` のいずれかです。実行中は `progressPercentage` を、終了後は `passRate`、`overallScore`、各指標の `metricScores` を確認してください。完了したテストケースが 1 件もない場合は `failed` で終了します。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明    |
| ------ | -- | ------ | ----- |
| `id`   | ✅  | string | 評価 ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('レスポンスを取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "name": string
  "description": string
  "chatbot": 
  {
    "id": string (uuid)
    "name": string
  }
  "dataset": 
  {
    "id": string (uuid)
    "name": string
  }
  "organization": 
  {
    "id": string (uuid)
    "name": string
  }
  "evaluationLlm": 
  {
    "id": string (uuid)
    "name": string
  }
  "status": 
  {
  }
  "queuedAt": string (timestamp) // Set while a pending evaluation is held back by the per-organization running cap and has not been sent to the workers yet; cleared when it is released. Deliberately not a status value: a held run is still pending to the frontend.
  "startedAt": string (timestamp)
  "completedAt": string (timestamp)
  "totalTestCases": integer
  "completedTestCases": integer
  "passedTestCases": integer // Number of test cases that passed
  "metricScores": object // Detailed score per evaluation metric, such as ground_truth, task_completion and tool_correctness
  "evaluationConfig": object
  "progressPercentage": number (double)
  "overallScore": number (double)
  "passRate": number (double)
  "averageExecutionTimeMs": integer
  "totalExecutionTimeMs": integer
  "chatbotConfig": string
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
  "insights": 
  {
    "summary": string
    "metricStats"?: object // 任意
    "recommendations"?: object // 任意
  }
  "metricSettings": [
    {
      "kind": string (enum: builtin, custom) // * `builtin` - builtin
* `custom` - custom
      "key": string // The metric_scores key of this metric in the run's case rows.
      "name": string
      "threshold": number (double)
      "passRule": string (enum: gte, lte) // * `gte` - gte
* `lte` - lte
      "criteria": string
      "evaluationSteps": [
        string
      ]
      "scoringSteps": [ // Multi-turn custom metrics only: the pinned judging steps, when they differ from evaluation_steps.
        string
      ]
    }
  ]
  "skippedNoExpectedAnswerCount": integer // Questions skipped because a metric of their rule needs an expected answer they lack.
  "passPolicy":  // The policy that decided "passed"; a run from before pass policies shows the implicit default. Null for multi-turn runs.
  {
    "rules": [ // Checked in order: the first matching rule decides a question, and the last one is the default.
      {
        "id": string
        "name": string
        "when": string // "always", or {"tags_any": [...]} / {"tags_all": [...]}.
        "metrics"?: [ // Result keys this rule runs; omitted runs every metric the evaluation enables. (任意)
          string
        ]
        "verdict": { // What counts as pass: the tiered rule, or every listed gate metric passing.
        {
          "type": string (enum: tiered, gates) // * `tiered` - tiered
* `gates` - gates
          "gates"?: [ // Result keys (as stored in metric_scores) that must all pass; gates verdict only. (任意)
            string
          ]
        }
        }
      }
    ]
  }
  "progress":  // Per-state case counts and timing for drawing the run's progress; unlike progress_percentage, errored and skipped cases count as finished.
  {
    "total": integer // Cases in this run, skipped ones included.
    "passed": integer // Cases that completed and passed.
    "failed": integer // Cases that completed without passing, hook-blocked answers included.
    "errored": integer // Cases that could not be answered or scored.
    "skipped": integer // Cases left out before the run started (single-turn only), e.g. no expected answer.
    "running": integer // Cases being answered or scored right now.
    "pending": integer // Cases not started yet.
    "finished": integer // passed + failed + errored + skipped.
    "percentage": number (double) // finished / total, 0 to 100; 0 for a run without cases.
    "elapsedMs": integer // Time since the current leg started (a resume restarts it), to completion or now; null before the run starts.
    "estimatedRemainingMs": integer // Estimated time until every case finishes, from the pace of this leg; null unless the run is running with at least one case completed in this leg and at least one case left.
  }
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "description": "レスポンス文字列",
  "chatbot": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "dataset": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "organization": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "evaluationLlm": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "status": {},
  "queuedAt": "レスポンス文字列",
  "startedAt": "レスポンス文字列",
  "completedAt": "レスポンス文字列",
  "totalTestCases": 456,
  "completedTestCases": 456,
  "passedTestCases": 456,
  "metricScores": null,
  "evaluationConfig": null,
  "progressPercentage": 456,
  "overallScore": 456,
  "passRate": 456,
  "averageExecutionTimeMs": 456,
  "totalExecutionTimeMs": 456,
  "chatbotConfig": "レスポンス文字列",
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列",
  "insights": {
    "summary": "レスポンス文字列",
    "metricStats": null,
    "recommendations": null
  },
  "metricSettings": [
    {
      "kind": "builtin",
      "key": "レスポンス文字列",
      "name": "レスポンス文字列",
      "threshold": 456,
      "passRule": "gte",
      "criteria": "レスポンス文字列",
      "evaluationSteps": [
        "レスポンス文字列"
      ],
      "scoringSteps": [
        "レスポンス文字列"
      ]
    }
  ],
  "skippedNoExpectedAnswerCount": 456,
  "passPolicy": {
    "rules": [
      {
        "id": "レスポンス文字列",
        "name": "レスポンス文字列",
        "when": "レスポンス文字列",
        "metrics": [
          "レスポンス文字列"
        ],
        "verdict": {
          "type": "tiered",
          "gates": [
            "レスポンス文字列"
          ]
        }
      }
    ]
  },
  "progress": {
    "total": 456,
    "passed": 456,
    "failed": 456,
    "errored": 456,
    "skipped": 456,
    "running": 456,
    "pending": 456,
    "finished": 456,
    "percentage": 456,
    "elapsedMs": 456,
    "estimatedRemainingMs": 456
  }
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 単一ターン評価の問題ごとの結果の取得 <a href="#evaluations-details-list" id="evaluations-details-list"></a>

GET `/api/v1/evaluations/{id}/details/`

{% hint style="info" %}
単一ターンの評価にのみ対応しています。複数ターンの評価では `400` を返します。レスポンスはすべてのテストケース結果の配列で、ページネーションはありません。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明    |
| ------ | -- | ------ | ----- |
| `id`   | ✅  | string | 評価 ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/details/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/details/", config)
  .then(response => {
    console.log('レスポンスを取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/details/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/details/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
[
  {
    "id": string (uuid)
    "datasetEvaluation": 
    {
      "id": string (uuid)
      "name": string
    }
    "testCase": 
    {
      "id": string (uuid)
      "dataset": 
      {
        "id": string (uuid)
        "name": string
      }
      "question": string
      "groundTruth"?: string // 任意
      "status"?: string (enum: active, inactive, pending) // * `active` - Active
* `inactive` - Inactive
* `pending` - Pending Review (任意)
      "creationMethod"?: string (enum: manual, file, generate) // * `manual` - Manual
* `file` - File import
* `generate` - Generated (任意)
      "sourceFile"?: string // Name of the CSV, Excel or knowledge base file this test case came from (任意)
      "flaky"?: boolean // Flaky test cases still run and keep their results, but are excluded from the pass rate. (任意)
      "tags"?: object // Labels that pick which pass rule decides this question. An empty list matches only rules that cover every question. (任意)
      "createdAt": string (timestamp)
      "updatedAt": string (timestamp)
    }
    "status": 
    {
    }
    "chatbotResponse": string
    "context": [ // Enrich each context item with is_deleted status for referenced knowledge base files.
      object
    ]
    "metricScores": object
    "executionTimeMs": integer
    "executionTimeSeconds": number (double)
    "passed": boolean
    "matchedRuleId": string // Id of the pass rule in the run's policy that decided Passed; empty for runs before pass rules.
    "errorMessage": string // Error message recorded when the evaluation fails
    "startedAt": string (timestamp)
    "completedAt": string (timestamp)
    "retryCount": integer // Number of times this test case has been retried
    "lastAttemptAt": string (timestamp) // Time of the last evaluation attempt
    "createdAt": string (timestamp)
    "updatedAt": string (timestamp)
  }
]
```

**レスポンス値の例**

```json
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "datasetEvaluation": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンス文字列"
    },
    "testCase": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "dataset": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス文字列"
      },
      "question": "レスポンス文字列",
      "groundTruth": "レスポンス文字列",
      "status": "active",
      "creationMethod": "manual",
      "sourceFile": "レスポンス文字列",
      "flaky": false,
      "tags": null,
      "createdAt": "レスポンス文字列",
      "updatedAt": "レスポンス文字列"
    },
    "status": {},
    "chatbotResponse": "レスポンス文字列",
    "context": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス例の名前",
        "description": "レスポンス例の説明"
      }
    ],
    "metricScores": null,
    "executionTimeMs": 456,
    "executionTimeSeconds": 456,
    "passed": false,
    "matchedRuleId": "レスポンス文字列",
    "errorMessage": "レスポンス文字列",
    "startedAt": "レスポンス文字列",
    "completedAt": "レスポンス文字列",
    "retryCount": 456,
    "lastAttemptAt": "レスポンス文字列",
    "createdAt": "レスポンス文字列",
    "updatedAt": "レスポンス文字列"
  }
]
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 複数ターン評価の会話ごとの結果を取得 <a href="#evaluations-multi-turn-results-list" id="evaluations-multi-turn-results-list"></a>

GET `/api/v1/evaluations/{id}/multi-turn-results/`

{% hint style="info" %}
複数ターン評価のみ対象です。単一ターン評価では `400` が返ります。レスポンスはページ分割されます。
{% endhint %}

#### パラメータ

| パラメータ名     | 必須 | 型       | 説明                                                      |
| ---------- | -- | ------- | ------------------------------------------------------- |
| `id`       | ✅  | string  | 評価 ID                                                   |
| `page`     | ❌  | integer | ページ番号。1 から始まります。最終ページを超えると 404 が返ります                    |
| `pageSize` | ❌  | integer | 1 ページあたりの件数。デフォルトは 20、上限は 100（100 を超える場合は 100 として扱われます） |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出し例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/multi-turn-results/?page=1&pageSize=1" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/multi-turn-results/?page=1&pageSize=1", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/multi-turn-results/?page=1&pageSize=1"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/multi-turn-results/?page=1&pageSize=1", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "id": string (uuid)
      "multiTurnTestCase": string (uuid)
      "scenario": string
      "expectedOutcome": string
      "flaky": boolean
      "status": 
      {
      }
      "turns": object // The whole simulated conversation; each turn is {role, content, retrieval_context}
      "metricScores": object
      "passed": boolean
      "errorMessage": string
      "startedAt": string (timestamp)
      "completedAt": string (timestamp)
      "createdAt": string (timestamp)
    }
  ]
}
```

**レスポンス値の例**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "multiTurnTestCase": "550e8400-e29b-41d4-a716-446655440000",
      "scenario": "レスポンス文字列",
      "expectedOutcome": "レスポンス文字列",
      "flaky": false,
      "status": {},
      "turns": null,
      "metricScores": null,
      "passed": false,
      "errorMessage": "レスポンス文字列",
      "startedAt": "レスポンス文字列",
      "completedAt": "レスポンス文字列",
      "createdAt": "レスポンス文字列"
    }
  ]
}
```

**ステータスコード: 4XX - エラーレスポンスです。X-Error-Code にエラーコードが含まれます（「エラーコード」を参照してください）。**

***

### 実行中の評価をキャンセル <a href="#evaluations-cancel-create" id="evaluations-cancel-create"></a>

POST `/api/v1/evaluations/{id}/cancel/`

{% hint style="info" %}
キャンセルできるのは `status` が `running` の評価のみで、それ以外の場合は `400` が返されます。キャンセル後、`status` はまず `stopping` になり、停止が完了すると `partial_completed` で終了します。計算済みのスコアは保持され、完了済みのテストケースは通常どおり Credit が消費されます。その後、[未完了の評価を再開](#evaluations-resume-create) で残りを実行できます。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明    |
| ------ | -- | ------ | ----- |
| `id`   | ✅  | string | 評価 ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/cancel/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエスト内容 (payload)
const data = null;

axios.post("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/cancel/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/cancel/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.post(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/cancel/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "name": string
  "description": string
  "chatbot": 
  {
    "id": string (uuid)
    "name": string
  }
  "dataset": 
  {
    "id": string (uuid)
    "name": string
  }
  "organization": 
  {
    "id": string (uuid)
    "name": string
  }
  "evaluationLlm": 
  {
    "id": string (uuid)
    "name": string
  }
  "status": 
  {
  }
  "queuedAt": string (timestamp) // Set while a pending evaluation is held back by the per-organization running cap and has not been sent to the workers yet; cleared when it is released. Deliberately not a status value: a held run is still pending to the frontend.
  "startedAt": string (timestamp)
  "completedAt": string (timestamp)
  "totalTestCases": integer
  "completedTestCases": integer
  "passedTestCases": integer // Number of test cases that passed
  "metricScores": object // Detailed score per evaluation metric, such as ground_truth, task_completion and tool_correctness
  "evaluationConfig": object
  "progressPercentage": number (double)
  "overallScore": number (double)
  "passRate": number (double)
  "averageExecutionTimeMs": integer
  "totalExecutionTimeMs": integer
  "chatbotConfig": string
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
  "insights": 
  {
    "summary": string
    "metricStats"?: object // 任意
    "recommendations"?: object // 任意
  }
}
```

**レスポンス例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "description": "レスポンス文字列",
  "chatbot": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "dataset": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "organization": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "evaluationLlm": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "status": {},
  "queuedAt": "レスポンス文字列",
  "startedAt": "レスポンス文字列",
  "completedAt": "レスポンス文字列",
  "totalTestCases": 456,
  "completedTestCases": 456,
  "passedTestCases": 456,
  "metricScores": null,
  "evaluationConfig": null,
  "progressPercentage": 456,
  "overallScore": 456,
  "passRate": 456,
  "averageExecutionTimeMs": 456,
  "totalExecutionTimeMs": 456,
  "chatbotConfig": "レスポンス文字列",
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列",
  "insights": {
    "summary": "レスポンス文字列",
    "metricStats": null,
    "recommendations": null
  }
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 未完了の評価を再開 <a href="#evaluations-resume-create" id="evaluations-resume-create"></a>

POST `/api/v1/evaluations/{id}/resume/`

{% hint style="info" %}
`status` が `partial_completed` の評価のみ再開できます。それ以外は `400` を返します。失敗したテストケースとまだ実行されていないテストケースを再実行し、完了済みの結果は保持されます。レスポンスは `202` で、以前に課金されていない完了済みケースに対してのみ Credit が差し引かれます。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明    |
| ------ | -- | ------ | ----- |
| `id`   | ✅  | string | 評価 ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/resume/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエスト内容 (payload)
const data = null;

axios.post("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/resume/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/resume/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.post(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/resume/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 202**

**レスポンス構造の例**

```typescript
{
  "status": string (enum: accepted) // * `accepted` - 常に accepted。リクエストが受理され、バックグラウンド実行のキューに入ったことを示します
  "message": string // 受理メッセージ
  "taskId": string // バックグラウンドタスク ID
}
```

**レスポンスのサンプル値**

```json
{
  "status": "accepted",
  "message": "レスポンス文字列",
  "taskId": "レスポンス文字列"
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 評価レポートのエクスポート <a href="#evaluations-export-create" id="evaluations-export-create"></a>

POST `/api/v1/evaluations/{id}/export/`

{% hint style="info" %}
エクスポートできるのは `status` が `completed` の単一ターン評価のみです。マルチターン評価は現在エクスポートに対応しておらず、`400` を返します。レポートはバックグラウンドで Excel ファイルとして生成され、`201` とエクスポート履歴が返されます。その後 [最新のエクスポート状況を取得](#evaluations-export-status-retrieve) でダウンロード URL を取得してください。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明    |
| ------ | -- | ------ | ----- |
| `id`   | ✅  | string | 評価 ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/export/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエスト内容 (payload)
const data = null;

axios.post("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/export/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/export/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.post(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/export/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 201**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "userEmail": string (email)
  "datasetEvaluationId": string (uuid)
  "datasetEvaluationName": string
  "status": 
  {
  }
  "statusDisplay": string
  "fileUrl": string // 返されるファイル URL
  "fileSize": integer // File size in bytes
  "errorMessage": string
  "processingDurationSeconds": number (double) // 計算された処理時間（秒）
  "createdAt": string (timestamp)
  "startedAt": string (timestamp)
  "completedAt": string (timestamp)
}
```

**レスポンスのサンプル値**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "userEmail": "response@example.com",
  "datasetEvaluationId": "550e8400-e29b-41d4-a716-446655440000",
  "datasetEvaluationName": "レスポンス文字列",
  "status": {},
  "statusDisplay": "レスポンス文字列",
  "fileUrl": "レスポンス文字列",
  "fileSize": 456,
  "errorMessage": "レスポンス文字列",
  "processingDurationSeconds": 456,
  "createdAt": "レスポンス文字列",
  "startedAt": "レスポンス文字列",
  "completedAt": "レスポンス文字列"
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 最新のエクスポート状況を取得 <a href="#evaluations-export-status-retrieve" id="evaluations-export-status-retrieve"></a>

GET `/api/v1/evaluations/{id}/export-status/`

{% hint style="info" %}
この評価の直近のエクスポート履歴を返します。`status` は `pending`、`processing`、`completed`、`failed` のいずれかで、`completed` の場合は `fileUrl` からダウンロードします。この評価にエクスポート履歴がない場合は `404` を返します。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明    |
| ------ | -- | ------ | ----- |
| `id`   | ✅  | string | 評価 ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/export-status/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/export-status/", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/export-status/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/export-status/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid)
  "userEmail": string (email)
  "datasetEvaluationId": string (uuid)
  "datasetEvaluationName": string
  "status": 
  {
  }
  "statusDisplay": string
  "fileUrl": string // 返されるファイル URL
  "fileSize": integer // File size in bytes
  "errorMessage": string
  "processingDurationSeconds": number (double) // 計算された処理時間（秒）
  "createdAt": string (timestamp)
  "startedAt": string (timestamp)
  "completedAt": string (timestamp)
}
```

**レスポンスのサンプル値**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "userEmail": "response@example.com",
  "datasetEvaluationId": "550e8400-e29b-41d4-a716-446655440000",
  "datasetEvaluationName": "レスポンス文字列",
  "status": {},
  "statusDisplay": "レスポンス文字列",
  "fileUrl": "レスポンス文字列",
  "fileSize": 456,
  "errorMessage": "レスポンス文字列",
  "processingDurationSeconds": 456,
  "createdAt": "レスポンス文字列",
  "startedAt": "レスポンス文字列",
  "completedAt": "レスポンス文字列"
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### エクスポート履歴の一覧 <a href="#evaluations-exports-list" id="evaluations-exports-list"></a>

GET `/api/v1/evaluations/{id}/exports/`

{% hint style="info" %}
レスポンスは、この評価のすべてのエクスポート履歴の配列で、新しい順に並び、ページネーションはありません。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明    |
| ------ | -- | ------ | ----- |
| `id`   | ✅  | string | 評価 ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/exports/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/exports/", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/exports/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/exports/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
[
  {
    "id": string (uuid)
    "userEmail": string (email)
    "datasetEvaluationId": string (uuid)
    "datasetEvaluationName": string
    "status": 
    {
    }
    "statusDisplay": string
    "fileUrl": string // 返されるファイル URL
    "fileSize": integer // File size in bytes
    "processingDurationSeconds": number (double) // 計算された処理時間（秒）
    "createdAt": string (timestamp)
    "startedAt": string (timestamp)
    "completedAt": string (timestamp)
  }
]
```

**レスポンスのサンプル値**

```json
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "userEmail": "response@example.com",
    "datasetEvaluationId": "550e8400-e29b-41d4-a716-446655440000",
    "datasetEvaluationName": "レスポンス文字列",
    "status": {},
    "statusDisplay": "レスポンス文字列",
    "fileUrl": "レスポンス文字列",
    "fileSize": 456,
    "processingDurationSeconds": 456,
    "createdAt": "レスポンス文字列",
    "startedAt": "レスポンス文字列",
    "completedAt": "レスポンス文字列"
  }
]
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 評価の名前と説明の編集 <a href="#evaluations-partial-update" id="evaluations-partial-update"></a>

PATCH `/api/v1/evaluations/{id}/`

{% hint style="info" %}
`name` と `description` のみ受け付けます。その他のフィールドは無視されます。どのステータスでも編集できます。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明    |
| ------ | -- | ------ | ----- |
| `id`   | ✅  | string | 評価 ID |

#### リクエストボディ

**リクエストパラメータ**

| フィールド       | 型      | 必須  | 説明 |
| ----------- | ------ | --- | -- |
| name        | string | いいえ |    |
| description | string | いいえ |    |

**リクエストスキーマの例**

```typescript
{
  "name"?: string // 任意
  "description"?: string // 任意
}
```

**リクエストの値の例**

```json
{
  "name": "サンプル名",
  "description": "サンプル文字列"
}
```

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "サンプル名",
    "description": "サンプル文字列"
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "name": "サンプル名",
    "description": "サンプル文字列"
  };

axios.patch("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY",
    "Content-Type": "application/json"
}

# リクエストボディ (payload)
data = {
    "name": "サンプル名",
    "description": "サンプル文字列"
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => 'サンプル名',
            'description' => 'サンプル文字列'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "name": string
  "description": string
  "chatbot": 
  {
    "id": string (uuid)
    "name": string
  }
  "dataset": 
  {
    "id": string (uuid)
    "name": string
  }
  "organization": 
  {
    "id": string (uuid)
    "name": string
  }
  "evaluationLlm": 
  {
    "id": string (uuid)
    "name": string
  }
  "status": 
  {
  }
  "queuedAt": string (timestamp) // Set while a pending evaluation is held back by the per-organization running cap and has not been sent to the workers yet; cleared when it is released. Deliberately not a status value: a held run is still pending to the frontend.
  "startedAt": string (timestamp)
  "completedAt": string (timestamp)
  "totalTestCases": integer
  "completedTestCases": integer
  "passedTestCases": integer // Number of test cases that passed
  "metricScores": object // Detailed score per evaluation metric, such as ground_truth, task_completion and tool_correctness
  "evaluationConfig": object
  "progressPercentage": number (double)
  "overallScore": number (double)
  "passRate": number (double)
  "averageExecutionTimeMs": integer
  "totalExecutionTimeMs": integer
  "chatbotConfig": string
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
  "insights": 
  {
    "summary": string
    "metricStats"?: object // 任意
    "recommendations"?: object // 任意
  }
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "description": "レスポンス文字列",
  "chatbot": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "dataset": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "organization": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "evaluationLlm": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "status": {},
  "queuedAt": "レスポンス文字列",
  "startedAt": "レスポンス文字列",
  "completedAt": "レスポンス文字列",
  "totalTestCases": 456,
  "completedTestCases": 456,
  "passedTestCases": 456,
  "metricScores": null,
  "evaluationConfig": null,
  "progressPercentage": 456,
  "overallScore": 456,
  "passRate": 456,
  "averageExecutionTimeMs": 456,
  "totalExecutionTimeMs": 456,
  "chatbotConfig": "レスポンス文字列",
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列",
  "insights": {
    "summary": "レスポンス文字列",
    "metricStats": null,
    "recommendations": null
  }
}
```

**ステータスコード: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### 評価の削除 <a href="#evaluations-destroy" id="evaluations-destroy"></a>

DELETE `/api/v1/evaluations/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明    |
| ------ | -- | ------ | ----- |
| `id`   | ✅  | string | 評価 ID |

#### コード例

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API 呼び出しの例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエスト内容 (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.delete(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/evaluations/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

| ステータスコード | 説明                                                                 |
| -------- | ------------------------------------------------------------------ |
| 204      | No response body                                                   |
| 4XX      | Error response; X-Error-Code carries its code (see "Error codes"). |

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/api/ja/api-reference/ping-gu-he-ce-shi-ji.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
