完全なサンプル
Beeuni SDK でセッションを実行し、応答を受け取ります。
スクリプトを full-example.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;
});
実行
beeuni tokens new sdk で個人用アクセストークンを作成します(--project は付けません)。そのトークンでアクセスできるプロジェクトを指定します。プロジェクトに設定されたモデルを使用し、セッションの実行にはクレジットを消費します。
npm install @beeuni/sdk
BEEUNI_API_KEY=your-api-key BEEUNI_PROJECT_ID=your-project-id npx tsx full-example.ts
プロジェクトを作成してセッションを実行する
対象の組織でプロジェクトを作成できる個人 API キーを使います。BEEUNI_ACCOUNT_ID には GET /v1/accounts が返す組織 ID を設定します。
プロジェクトごとに新しい UUID を BEEUNI_PROVISION_KEY に設定し、作成を再試行する場合は同じ値を使います。
import { randomUUID } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';
const { BEEUNI_API_KEY, BEEUNI_ACCOUNT_ID, BEEUNI_PROVISION_KEY } = process.env;
if (!BEEUNI_API_KEY || !BEEUNI_ACCOUNT_ID || !BEEUNI_PROVISION_KEY) {
throw new Error('Set BEEUNI_API_KEY, BEEUNI_ACCOUNT_ID, and BEEUNI_PROVISION_KEY.');
}
async function api(path, body) {
const response = await fetch('https://api.beeuni.ai/v1' + path, {
method: body === undefined ? 'GET' : 'POST',
headers: {
Authorization: 'Bearer ' + BEEUNI_API_KEY,
'Content-Type': 'application/json',
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(60_000),
});
if (!response.ok) throw new Error(`${path}: HTTP ${response.status}`);
return response.json();
}
const project = await api('/projects/provision', {
name: 'API example',
account_id: BEEUNI_ACCOUNT_ID,
idempotency_key: BEEUNI_PROVISION_KEY,
seed_starter: true,
});
const path = `/projects/${project.project_id}`;
const picker = await api(path + '/model-picker');
if (picker.models?.['gpt-6.2-astra']?.enabled !== true) {
throw new Error('GPT-6.2 Astra is not enabled in this project.');
}
const session = await api(path + '/sessions', {
agent_name: 'worker',
model: 'beeuni/gpt-6.2-astra',
});
const sessionPath = `${path}/sessions/${session.session_id}`;
console.log('Project:', project.project_id, 'Session:', session.session_id);
const prompt = await api(sessionPath + '/prompts', {
client_message_id: randomUUID(),
parts: [{ type: 'text', text: 'Reply with a one-sentence introduction.' }],
});
const deadline = Date.now() + 180_000;
while (true) {
const result = await api(sessionPath + '/result?prompt_id=' + prompt.prompt_id);
if (result.status === 'completed') {
console.log(result.output.map(({ text }) => text).join('\n'));
if (result.truncated) console.warn('Read the session log for the full reply.');
break;
}
if (result.status === 'failed') throw new Error(result.error?.message ?? 'Prompt failed.');
if (Date.now() >= deadline) throw new Error('Still waiting; check the existing session.');
await sleep(2_000);
}
次のステップ
React の画面には React hooks を使用します。権限要求、質問、起動エラーについては Sessions を参照してください。