---
title: 完整示例
description: 使用 Beeuni SDK 运行会话并接收回复。
---

将脚本保存为 `full-example.ts`。它会在已有项目中创建会话、打开事件流、发送提示词，并读取对话记录。

```ts
import { createBeeuni, narrowChatEvent } from '@beeuni/sdk';

async function main() {
  const apiKey = process.env.BEEUNI_API_KEY;
  const projectId = process.env.BEEUNI_PROJECT_ID;
  if (!apiKey || !projectId) {
    throw new Error('Set BEEUNI_API_KEY and BEEUNI_PROJECT_ID.');
  }

  const beeuni = createBeeuni({
    backendUrl: 'https://api.beeuni.ai/v1',
    getToken: async () => apiKey,
  });
  const created = await beeuni.project(projectId).sessions.create({
    name: 'SDK example',
  });
  console.log('Session:', created.session_id);

  const session = beeuni.session(projectId, created.session_id);
  const { runtimeSessionId } = await session.ensureReady();
  let finish!: () => void;
  let failure: string | undefined;
  let submitted = false;
  const finished = new Promise<void>((resolve) => { finish = resolve; });

  const stream = await session.stream({
    onEvent: (event) => {
      const e = narrowChatEvent(event);
      if (!e || !submitted || !('sessionID' in e) || e.sessionID !== runtimeSessionId) return;
      if (e.type === 'message.part.updated') console.log(e.part);
      if (e.type === 'session.error') {
        failure = JSON.stringify(e.error ?? 'Session failed.');
        finish();
      }
      if (e.type === 'session.idle') finish();
    },
  });

  const timer = setTimeout(() => {
    failure = 'Reply timed out. Check the session for pending permissions or questions.';
    finish();
  }, 180_000);

  try {
    submitted = true;
    await session.send('Describe your capabilities in one paragraph.');
    await finished;
    if (failure) throw new Error(failure);
    console.log(JSON.stringify(await session.messages(), null, 2));
  } finally {
    clearTimeout(timer);
    stream.close();
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
```

## 运行

在 **Account → Tokens** 创建 API key，并填写该凭据有权访问的项目 ID。脚本使用项目已配置的模型；运行会话会消耗额度。

```bash
npm install @beeuni/sdk
BEEUNI_API_KEY=your-api-key BEEUNI_PROJECT_ID=your-project-id npx tsx full-example.ts
```

## 后续接入

[身份认证](/docs/zh/sdk/auth)

React 界面可使用 [React hooks](/docs/zh/sdk/react)。权限请求、提问和启动错误见 [Sessions](/docs/zh/sdk/sessions)。
