Esempio completo
Esegui una sessione e ricevi la risposta con Beeuni SDK.
Salva lo script come full-example.ts. Crea una sessione in un progetto esistente, apre il flusso di eventi, invia un prompt e legge la trascrizione.
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;
});
Esecuzione
Crea un token di accesso personale con beeuni tokens new sdk (senza --project). Scegli un progetto a cui il token può accedere. Lo script usa il modello configurato nel progetto; le sessioni consumano crediti.
npm install @beeuni/sdk
BEEUNI_API_KEY=your-api-key BEEUNI_PROJECT_ID=your-project-id npx tsx full-example.ts
Creare un progetto e avviare una sessione
Usa una chiave API personale con il permesso di creare progetti nell’organizzazione di destinazione. Imposta BEEUNI_ACCOUNT_ID con l’ID restituito da GET /v1/accounts.
Usa un nuovo UUID come BEEUNI_PROVISION_KEY per ogni progetto e riutilizzalo se ripeti la richiesta.
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);
}
Passi successivi
Per un’interfaccia React usa React hooks. Per permessi, domande ed errori di avvio vedi Sessions.