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

# 调用专家

> POST /v1/agents/run — 调用袋袋专家，获取 SSE 流式响应

调用一个袋袋专家（AI Agent），通过 SSE 流式获取完整回复，包括文本输出、工具调用和 token 用量。

```
POST https://api.profy.cn/v1/agents/run
```

## 认证

<ParamField header="Authorization" type="string" required>
  `Bearer sk-pro-xxxx`（API Key）或 `Bearer <access_token>`（OAuth）
</ParamField>

## 请求体

<ParamField body="expert_identifier" type="string" required>
  专家的唯一标识符。你可以在专家的市场页面或 Studio 中找到它。
</ParamField>

<ParamField body="message" type="string" required>
  发送给专家的消息内容。
</ParamField>

<ParamField body="session_id" type="string">
  会话 ID，用于多轮对话。首次调用无需传入，响应头 `X-Session-Id` 中会返回新的 session\_id。
</ParamField>

<ParamField body="model" type="string">
  指定使用的模型。不传则使用平台默认模型。可通过 `GET /v1/models` 查询可用模型。
</ParamField>

## 请求示例

<CodeGroup>
  ```python Python theme={null}
  from profy import Profy

  async with Profy(api_key="sk-pro-your-key") as client:
      result = await client.agents.run(
          "my-expert",
          "帮我分析一下这段代码的性能问题",
          session_id="existing-session-id",  # 可选
          model="deepseek-v3",               # 可选
      )
      print(result.text)
      print(f"工具调用: {[t.name for t in result.tool_calls]}")
  ```

  ```typescript TypeScript theme={null}
  import { Profy } from "@profy-ai/sdk";

  const client = new Profy({ apiKey: "sk-pro-your-key" });

  const result = await client.agents.run(
    "my-expert",
    "帮我分析一下这段代码的性能问题",
    {
      sessionId: "existing-session-id",
      model: "deepseek-v3",
    }
  );

  console.log(result.text);
  console.log("工具调用:", result.toolCalls.map(t => t.name));
  ```

  ```bash curl theme={null}
  curl -X POST https://api.profy.cn/v1/agents/run \
    -H "Authorization: Bearer sk-pro-your-key" \
    -H "Content-Type: application/json" \
    -d '{
      "expert_identifier": "my-expert",
      "message": "帮我分析一下这段代码的性能问题"
    }'
  ```
</CodeGroup>

## 响应格式

响应为 SSE（Server-Sent Events）流，事件使用层级点分命名（对标 OpenAI Responses API）。响应头中包含 `X-Session-Id`，用于后续多轮对话。

```
event: run.in_progress
data: {"type":"run.in_progress","model_name":"deepseek-v3","session_id":"ses_abc123","event_id":2}
```

## SSE 事件类型

### 生命周期事件

| 事件                | 说明          | 关键字段                       |
| ----------------- | ----------- | -------------------------- |
| `run.created`     | Agent 运行已创建 | `event_id`                 |
| `run.in_progress` | Agent 开始运行  | `model_name`, `session_id` |
| `run.completed`   | Agent 运行完成  | `event_id`                 |
| `run.failed`      | Agent 运行失败  | `message`                  |

### 输出事件

| 事件                      | 说明          | 关键字段    |
| ----------------------- | ----------- | ------- |
| `output.text.delta`     | 文本增量输出      | `delta` |
| `output.thinking.delta` | 思维链增量（推理模型） | `delta` |

### 工具调用事件

| 事件                          | 说明     | 关键字段                        |
| --------------------------- | ------ | --------------------------- |
| `tool_call.created`         | 工具调用开始 | `tool_name`, `tool_call_id` |
| `tool_call.arguments.delta` | 工具参数增量 | `delta`                     |
| `tool_call.completed`       | 工具调用完成 | `tool_name`, `result`       |
| `tool_call.failed`          | 工具调用失败 | `tool_name`, `error`        |

### 用量事件

| 事件                      | 说明         | 关键字段                            |
| ----------------------- | ---------- | ------------------------------- |
| `usage.token`           | Token 用量统计 | `input_tokens`, `output_tokens` |
| `usage.trial_exhausted` | 试用次数耗尽     | `message`                       |

## 流式解析示例

<CodeGroup>
  ```python Python（流式） theme={null}
  from profy import Profy

  async with Profy(api_key="sk-pro-your-key") as client:
      async for chunk in client.agents.run_stream("my-expert", "你好"):
          match chunk.type:
              case "run.in_progress":
                  print(f"会话: {chunk.raw.get('session_id')}")
              case "output.text.delta":
                  print(chunk.delta, end="", flush=True)
              case "tool_call.created":
                  print(f"\n调用工具: {chunk.raw.get('tool_name')}")
              case "run.completed":
                  print("\n--- 完成 ---")
              case "run.failed":
                  print(f"\n错误: {chunk.raw.get('message')}")
  ```

  ```typescript TypeScript（流式） theme={null}
  import { Profy } from "@profy-ai/sdk";

  const client = new Profy({ apiKey: "sk-pro-your-key" });

  for await (const chunk of client.agents.runStream("my-expert", "你好")) {
    switch (chunk.type) {
      case "run.in_progress":
        console.log(`会话: ${chunk.raw.session_id}`);
        break;
      case "output.text.delta":
        process.stdout.write(chunk.delta ?? "");
        break;
      case "tool_call.created":
        console.log(`\n调用工具: ${chunk.raw.tool_name}`);
        break;
      case "run.completed":
        console.log("\n--- 完成 ---");
        break;
    }
  }
  ```

  ```bash curl（原始 SSE） theme={null}
  curl -N -X POST https://api.profy.cn/v1/agents/run \
    -H "Authorization: Bearer sk-pro-your-key" \
    -H "Content-Type: application/json" \
    -H "Accept: text/event-stream" \
    -d '{"expert_identifier":"my-expert","message":"你好"}'
  ```
</CodeGroup>

## 计费

按 token 用量计费（METERED），积分从调用者账户扣除。具体费率以产品内实时显示为准。你可以在 `usage.token` 事件中获取本次调用的 token 消耗。

## 错误码

| HTTP 状态码 | 说明                         |
| -------- | -------------------------- |
| `400`    | 请求参数缺失或无效                  |
| `401`    | 认证失败（API Key 无效或 Token 过期） |
| `403`    | 专家访问被拒绝（未购买或试用次数耗尽）        |
| `404`    | 专家不存在或未发布                  |
| `502`    | 智能体运行时上游错误                 |
| `504`    | 智能体运行时超时                   |

## 下一步

<CardGroup cols={2}>
  <Card title="对话补全" icon="comments" href="/zh/developers/api/chat-completions">
    OpenAI 兼容的对话补全接口
  </Card>

  <Card title="Python SDK" icon="python" href="/zh/developers/sdk-python">
    Python SDK 完整指南
  </Card>
</CardGroup>
