Session 與 API

Session 管理與 SDK API 參考。

SDK 透過 Lens OS SaaS API 自動建立和管理 Session。每個 useLensAgent 實例在掛載時會產生一個唯一的 sessionId

Session 管理

基本操作

Session 操作
const { sessionId, newSession, clearMessages } = useLensAgent({
  endpoint: '/api/agent/chat',
});

// 當前 Session ID
console.log(sessionId); // "session-1709123456789-abc123def"

// 開始全新 Session(清除訊息 + 產生新 ID)
newSession();

// 清除訊息但保留同一個 Session
clearMessages();

透過 API Routes 存取 Session 歷史

若要列出和載入之前的 Session,建立使用 LensClient 的 API 路由:

src/app/api/agent/sessions/route.ts
import { LensClient } from '@lens-os/sdk';

const client = new LensClient({ apiKey: process.env.LENS_API_KEY! });

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const userId = searchParams.get('userId');
  if (!userId) {
    return Response.json({ error: 'userId required' }, { status: 400 });
  }
  const sessions = await client.listSessions(userId);
  return Response.json(sessions);
}
src/app/api/agent/sessions/[id]/route.ts
import { LensClient } from '@lens-os/sdk';

const client = new LensClient({ apiKey: process.env.LENS_API_KEY! });

export async function GET(req: Request, { params }: { params: { id: string } }) {
  const messages = await client.getMessages(params.id);
  return Response.json(messages);
}

API 參考

匯出項目

  • @lens-os/sdkLensClientSupervisorAgent、所有型別(SSEEventToolResultSessionContext 等)
  • @lens-os/sdk/servercreateAgentHandlercreateActionResultHandlerPendingActionStore
  • @lens-os/sdk/reactuseLensAgentuseChat

LensClient

直接存取 Lens OS SaaS 的 API 客戶端。適用於在 agent 迴圈之外取得設定、管理 session 和搜尋知識庫。

LensClient
import { LensClient } from '@lens-os/sdk';

const client = new LensClient({
  apiKey: process.env.LENS_API_KEY!,
  baseUrl: 'https://osapi.ask-lens.ai', // 可選,這是預設值
});

// 租戶設定(快取 TTL 60 秒)
const config = await client.getConfig();

// Sessions
const sessions = await client.listSessions('user-123');
const session = await client.getSession('session-id');
const messages = await client.getMessages('session-id');

// 知識庫搜尋
const results = await client.searchKnowledge('搜尋查詢', 10);

// 商品搜尋
const products = await client.searchProducts('搜尋查詢', 10);

關鍵型別

型別
interface Message {
  role: 'user' | 'assistant' | 'system' | 'tool';
  content: string | MessageContent[];
  timestamp?: Date;
}

interface TenantConfig {
  systemPrompt?: string;
  prompts: SitePrompt[];
  skills: Skill[];
  tools: ToolRegistryItem[];
  version: string;
}

interface Skill {
  id: string;
  name: string;
  displayName: string;
  prompt: string;
  description?: string;
  temperature?: number;
  maxTokens?: number;
  enabledTools?: string[];
}

Tip

使用 LensClient 進行伺服器端操作,如列出 session 和搜尋知識庫。 絕對不要將它暴露給客戶端程式碼。