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

# 快速开始

> 5 分钟内完成你的第一次袋袋 API 调用

本指南将带你在 5 分钟内完成第一次袋袋 API 调用。

## 前置条件

* 一个袋袋账号（在 [app.profy.cn](https://app.profy.cn) 注册）
* Python 3.8+ 或 Node.js 18+（如果使用 SDK）

## 第一步：获取 API Key

1. 登录 [app.profy.cn](https://app.profy.cn)
2. 访问 [platform.profy.cn](https://platform.profy.cn)（与主站共享登录态）
3. 进入 **API Keys** 页面
4. 点击 **创建 API Key**，填写名称，选择权限范围
5. 复制生成的 Key（以 `sk-pro-` 开头）

<Warning>
  API Key 仅在创建时展示一次，请立即保存到安全的位置。如果丢失，只能重新创建。
</Warning>

## 第二步：发起第一次调用

选择你偏好的方式进行调用：

<Tabs>
  <Tab title="Python SDK">
    安装 SDK：

    ```bash theme={null}
    pip install profy
    ```

    调用一个专家：

    ```python theme={null}
    import asyncio
    from profy import Profy

    async def main():
        async with Profy(api_key="sk-pro-your-key-here") as client:
            # 调用一个 专家
            result = await client.agents.run(
                "profy",        # 专家标识符
                "用一句话介绍你自己"  # 消息内容
            )
            print(result.text)
            print(f"模型: {result.model}")
            print(f"耗时: {result.elapsed_sec}s")

    asyncio.run(main())
    ```

    如果你更习惯同步代码：

    ```python theme={null}
    from profy import ProfySync

    with ProfySync(api_key="sk-pro-your-key-here") as client:
        result = client.agents.run("profy", "用一句话介绍你自己")
        print(result.text)
    ```
  </Tab>

  <Tab title="TypeScript SDK">
    安装 SDK：

    ```bash theme={null}
    npm install @profy-ai/sdk
    ```

    调用一个专家：

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

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

    const result = await client.agents.run(
      "profy",        // 专家标识符
      "用一句话介绍你自己"  // 消息内容
    );

    console.log(result.text);
    console.log(`模型: ${result.model}`);
    console.log(`耗时: ${result.elapsedMs}ms`);
    ```
  </Tab>

  <Tab title="curl">
    ```bash theme={null}
    curl -X POST https://api.profy.cn/v1/agents/run \
      -H "Authorization: Bearer sk-pro-your-key-here" \
      -H "Content-Type: application/json" \
      -d '{
        "expert_identifier": "profy",
        "message": "用一句话介绍你自己"
      }'
    ```

    响应是 SSE（Server-Sent Events）流：

    ```
    event: run.created
    data: {"type":"run.created","event_id":1}

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

    event: output.text.delta
    data: {"type":"output.text.delta","delta":"你好","event_id":3}

    event: output.text.delta
    data: {"type":"output.text.delta","delta":"！我是","event_id":4}

    event: run.completed
    data: {"type":"run.completed","event_id":5}

    data: [DONE]
    ```
  </Tab>
</Tabs>

## 第三步：流式获取响应

对于需要实时展示 AI 输出的场景，使用流式模式：

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

  async def main():
      async with Profy(api_key="sk-pro-your-key-here") as client:
          async for chunk in client.agents.run_stream("profy", "写一首关于编程的诗"):
              if chunk.type == "output.text.delta":
                  print(chunk.delta, end="", flush=True)
              elif chunk.type == "tool_call.created":
                  print(f"\n[调用工具: {chunk.tool_name}]")
              elif chunk.type == "run.completed":
                  print("\n[完成]")

  asyncio.run(main())
  ```

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

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

  for await (const chunk of client.agents.runStream("profy", "写一首关于编程的诗")) {
    if (chunk.type === "output.text.delta") {
      process.stdout.write(chunk.delta ?? "");
    } else if (chunk.type === "tool_call.created") {
      console.log(`\n[调用工具: ${chunk.toolName}]`);
    } else if (chunk.type === "run.completed") {
      console.log("\n[完成]");
    }
  }
  ```
</CodeGroup>

## 第四步：多轮对话

传入 `session_id` 即可延续同一对话：

<CodeGroup>
  ```python Python theme={null}
  async with Profy(api_key="sk-pro-your-key-here") as client:
      # 第一轮
      r1 = await client.agents.run("profy", "我叫小明")
      print(r1.text)
      session_id = r1.session_id

      # 第二轮 — 专家 记得你的名字
      r2 = await client.agents.run(
          "profy", "你还记得我叫什么吗？",
          session_id=session_id
      )
      print(r2.text)
  ```

  ```typescript TypeScript theme={null}
  const client = new Profy({ apiKey: "sk-pro-your-key-here" });

  // 第一轮
  const r1 = await client.agents.run("profy", "我叫小明");
  console.log(r1.text);

  // 第二轮 — 专家 记得你的名字
  const r2 = await client.agents.run("profy", "你还记得我叫什么吗？", {
    sessionId: r1.sessionId,
  });
  console.log(r2.text);
  ```
</CodeGroup>

## 理解 SSE 事件流

`/v1/agents/run` 返回的是标准 SSE 事件流。以下是你会遇到的核心事件类型：

| 事件                    | 说明                                        |
| --------------------- | ----------------------------------------- |
| `run.created`         | 请求已接收，开始处理                                |
| `run.in_progress`     | Agent 开始运行，包含 `model_name` 和 `session_id` |
| `output.text.delta`   | 文本增量输出，`delta` 字段包含新文本片段                  |
| `tool_call.created`   | Agent 开始调用工具                              |
| `tool_call.completed` | 工具调用完成                                    |
| `run.completed`       | Agent 运行完成                                |
| `run.failed`          | 运行失败，`message` 字段包含错误信息                   |

完整事件类型列表参见 [Agents Run API](/zh/developers/api/agents-run#sse-事件类型)。

## 使用 Chat Completions

如果你已经在使用 OpenAI 的 API，可以直接切换到袋袋的兼容接口：

<Tabs>
  <Tab title="调用裸模型">
    <CodeGroup>
      ```python Python theme={null}
      async with Profy(api_key="sk-pro-your-key-here") as client:
          resp = await client.chat.completions.create(
              model="deepseek-v3",
              messages=[{"role": "user", "content": "你好"}],
          )
          print(resp.text)
      ```

      ```typescript TypeScript theme={null}
      const client = new Profy({ apiKey: "sk-pro-your-key-here" });

      const resp = await client.chat.completions.create({
        model: "deepseek-v3",
        messages: [{ role: "user", content: "你好" }],
      });
      console.log(resp.text);
      ```
    </CodeGroup>
  </Tab>

  <Tab title="用 OpenAI SDK 调用专家">
    使用 `profy-<identifier>` 格式的模型名，用标准 OpenAI SDK 直接调用袋袋专家：

    ```python theme={null}
    from openai import OpenAI

    client = OpenAI(
        api_key="sk-pro-your-key-here",
        base_url="https://api.profy.cn/v1",
    )

    response = client.chat.completions.create(
        model="profy-financial-advisor",
        messages=[{"role": "user", "content": "帮我分析特斯拉的投资价值"}],
        stream=True,
    )

    for chunk in response:
        if chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="")
    ```
  </Tab>
</Tabs>

## 下一步

<CardGroup cols={2}>
  <Card title="认证指南" icon="lock" href="/zh/developers/authentication">
    深入了解 API Key 和 OAuth 的使用方式
  </Card>

  <Card title="Agents Run API" icon="robot" href="/zh/developers/api/agents-run">
    查看完整的专家调用 API 文档
  </Card>

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

  <Card title="TypeScript SDK" icon="js" href="/zh/developers/sdk-typescript">
    TypeScript SDK 的完整使用指南
  </Card>
</CardGroup>
