### Install Agentset AI SDK with npm Source: https://github.com/agentset-ai/agentset-ts/blob/main/packages/ai-sdk/README.md Use this command to install the SDK using npm. ```bash npm install @agentset/ai-sdk ``` -------------------------------- ### Install Agentset AI SDK with yarn Source: https://github.com/agentset-ai/agentset-ts/blob/main/packages/ai-sdk/README.md Use this command to install the SDK using yarn. ```bash yarn add @agentset/ai-sdk ``` -------------------------------- ### Install Agentset SDK Source: https://github.com/agentset-ai/agentset-ts/blob/main/packages/agentset/README.md Install the Agentset SDK using npm, yarn, or pnpm. ```sh npm install agentset ``` ```sh yarn add agentset ``` ```sh pnpm add agentset ``` -------------------------------- ### Install Agentset AI SDK with pnpm Source: https://github.com/agentset-ai/agentset-ts/blob/main/packages/ai-sdk/README.md Use this command to install the SDK using pnpm. ```bash pnpm add @agentset/ai-sdk ``` -------------------------------- ### Install Agentset TypeScript SDK Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Install the core SDK or the AI SDK adapter using npm or pnpm. The AI SDK adapter has peer dependencies on `ai` and `zod`. ```bash # Core SDK npm install agentset # or pnpm add agentset # AI SDK adapter (requires `ai >= 5.0` and `zod >= 4.0` as peer deps) npm install @agentset/ai-sdk ``` -------------------------------- ### Initialize the client Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Creates the top-level API client. All SDK operations start here. The `apiKey` field is required; `baseUrl` defaults to `https://api.agentset.ai` and can be overridden for self-hosted deployments. A custom `fetcher` can replace the global `fetch` for environments like older Node.js. ```APIDOC ## `new Agentset(options)` — Initialize the client Creates the top-level API client. All SDK operations start here. The `apiKey` field is required; `baseUrl` defaults to `https://api.agentset.ai` and can be overridden for self-hosted deployments. A custom `fetcher` can replace the global `fetch` for environments like older Node.js. ```typescript import { Agentset } from "agentset"; import nodeFetch from "node-fetch"; // For Node.js < 18 // Standard initialization const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY!, }); // With custom base URL (self-hosted) and custom fetcher const agentsetCustom = new Agentset({ apiKey: process.env.AGENTSET_API_KEY!, baseUrl: "https://my-self-hosted-instance.example.com", fetcher: nodeFetch as typeof fetch, }); ``` ``` -------------------------------- ### Custom Fetch Implementation Source: https://github.com/agentset-ai/agentset-ts/blob/main/README.md Provide a custom fetch implementation to the Agentset client, for example, using node-fetch. ```typescript import { Agentset } from "agentset"; import nodeFetch from "node-fetch"; const agentset = new Agentset({ apiKey: "your_api_key_here", fetcher: nodeFetch, }); ``` -------------------------------- ### Ingest Content into Namespace Source: https://github.com/agentset-ai/agentset-ts/blob/main/README.md Ingest text content into a specified namespace. This example shows how to create a new ingestion job. ```typescript await ns.ingestion.create({ payload: { type: "TEXT", text: "This is some content to ingest into the knowledge base.", name: "Introduction", }, }); ``` -------------------------------- ### Custom Fetch Implementation Source: https://github.com/agentset-ai/agentset-ts/blob/main/packages/agentset/README.md Provide a custom fetch implementation to the Agentset client, for example, using node-fetch for Node.js environments. ```typescript import { Agentset } from "agentset"; import nodeFetch from "node-fetch"; const agentset = new Agentset({ apiKey: "your_api_key_here", fetcher: nodeFetch, }); ``` -------------------------------- ### Manage Namespace Hosting with Agentset Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Controls the publicly hosted chat interface for a namespace. Use `enable()` to activate, `update()` to modify configuration, `get()` to retrieve the current config, and `delete()` to disable. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); // Enable hosted chat UI const hosting = await ns.hosting.enable(); console.log(hosting); // { id: "host_abc", status: "ACTIVE", url: "https://..." } // Update configuration await ns.hosting.update({ name: "Product Support Chat", }); // Retrieve current config const config = await ns.hosting.get(); console.log(config.url); // "https://chat.agentset.ai/product-docs" // Disable await ns.hosting.delete(); ``` -------------------------------- ### Manage namespace hosting Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Controls the publicly hosted chat interface for a namespace. enable() activates it, update() modifies configuration, get() retrieves the current config, and delete() disables it. ```APIDOC ## `ns.hosting.enable()` — Enable namespace hosting Activates the publicly hosted chat interface for a namespace. ### Response #### Success Response (200) - **hosting** (object) - An object containing hosting details. - **id** (string) - The unique identifier for the hosting. - **status** (string) - The current status of the hosting (e.g., 'ACTIVE'). - **url** (string) - The URL of the hosted chat interface. ``` ```APIDOC ## `ns.hosting.update(params)` — Update namespace hosting configuration Modifies the configuration of the publicly hosted chat interface for a namespace. ### Parameters #### Request Body - **name** (string) - Optional - The new name for the hosted chat interface. ``` ```APIDOC ## `ns.hosting.get()` — Get namespace hosting configuration Retrieves the current configuration of the publicly hosted chat interface for a namespace. ### Response #### Success Response (200) - **config** (object) - An object containing the hosting configuration. - **url** (string) - The URL of the hosted chat interface. ``` ```APIDOC ## `ns.hosting.delete()` — Disable namespace hosting Disables the publicly hosted chat interface for a namespace. ``` -------------------------------- ### Get a namespace by ID or slug Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Fetches a single namespace by its `id` or `slug`. Throws `NotFoundError` if it does not exist. ```APIDOC ## `agentset.namespaces.get(namespaceId)` — Get a namespace by ID or slug Fetches a single namespace by its `id` or `slug`. Throws `NotFoundError` if it does not exist. ```typescript import { Agentset, NotFoundError } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); try { const ns = await agentset.namespaces.get("product-docs"); // by slug console.log(ns.name); // "Product Documentation" } catch (error) { if (error instanceof NotFoundError) { console.error("Namespace not found"); } } ``` ``` -------------------------------- ### Get Presigned Upload URLs with Agentset Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Low-level methods to obtain presigned upload URLs without performing the upload. Use these when you need to control the upload step yourself, such as from a browser. Requires manual PUT requests to the returned URLs. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); // Single presigned URL const { url, key } = await ns.uploads.create({ fileName: "report.pdf", contentType: "application/pdf", fileSize: 204800, // bytes }); // PUT the file to `url` manually await fetch(url, { method: "PUT", body: fileBlob, headers: { "Content-Type": "application/pdf" } }); // Batch presigned URLs const responses = await ns.uploads.createBatch({ files: [ { fileName: "a.pdf", contentType: "application/pdf", fileSize: 1024 }, { fileName: "b.pdf", contentType: "application/pdf", fileSize: 2048 }, ], }); responses.forEach(({ url, key }) => console.log(key, url)); ``` -------------------------------- ### Get presigned upload URLs Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Low-level methods that return presigned upload URLs without performing the upload. Use these when you need to control the upload step yourself (e.g., from the browser). ```APIDOC ## `ns.uploads.create(params)` — Get presigned upload URL Low-level method that returns a presigned upload URL without performing the upload. Use this when you need to control the upload step yourself. ### Parameters #### Request Body - **fileName** (string) - Required - The name of the file. - **contentType** (string) - Required - The MIME type of the file. - **fileSize** (number) - Required - The size of the file in bytes. ### Response #### Success Response (200) - **url** (string) - The presigned URL for uploading the file. - **key** (string) - The key to use for ingestion. ``` ```APIDOC ## `ns.uploads.createBatch(params)` — Get batch presigned upload URLs Low-level method that returns presigned upload URLs for multiple files without performing the uploads. Use this when you need to control the upload step yourself. ### Parameters #### Request Body - **files** (Array<{ fileName: string, contentType: string, fileSize: number }> ) - Required - An array of file objects for which to generate presigned URLs. ### Response #### Success Response (200) - **responses** (Array<{ url: string, key: string }>) - An array of objects, each containing a presigned URL and a key for a file. ``` -------------------------------- ### Get Namespace by ID or Slug Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Fetch a specific namespace using its ID or slug. This operation throws a `NotFoundError` if the namespace does not exist. ```typescript import { Agentset, NotFoundError } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); try { const ns = await agentset.namespaces.get("product-docs"); // by slug console.log(ns.name); // "Product Documentation" } catch (error) { if (error instanceof NotFoundError) { console.error("Namespace not found"); } } ``` -------------------------------- ### Get download URL for source file Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Returns a presigned URL to download the original source file for a document. Only available for documents with source type 'MANAGED_FILE' (uploaded via ns.uploads). ```typescript import { Agentset } from "agentset"; import fs from "fs"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); const { url } = await ns.documents.getFileDownloadUrl("doc_222"); const response = await fetch(url); const buffer = await response.arrayBuffer(); fs.writeFileSync("downloaded-source.pdf", Buffer.from(buffer)); ``` -------------------------------- ### Get an ingestion job by ID Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Retrieves a specific ingestion job by its ID. Use this to check the status or details of a job. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); const job = await ns.ingestion.get("job_abc123"); console.log(job.status); // "COMPLETED" console.log(job.name); // "Introduction Article" ``` -------------------------------- ### Get a document by ID Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Fetches metadata for a single document using its unique ID. Use this to retrieve details like name and status. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); const doc = await ns.documents.get("doc_111"); console.log(doc.name); // "Introduction Article" console.log(doc.status); // "COMPLETED" ``` -------------------------------- ### Get download URL for document chunks Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Returns a presigned S3 URL to download the processed text chunks for a completed document. Only available for documents with status 'COMPLETED'. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); const { url } = await ns.documents.getChunksDownloadUrl("doc_111"); // Use the URL to download the chunks JSON const response = await fetch(url); const chunks = await response.json(); console.log(`Downloaded ${chunks.length} chunks`); ``` -------------------------------- ### Handle Agentset API Errors with Typed Classes Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Import and use typed subclasses of `AgentsetError` for precise error handling. This example demonstrates catching specific errors like `NotFoundError` and `UnauthorizedError`. ```typescript import { Agentset, AgentsetError, BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitExceededError, InternalServerError, } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); try { await agentset.namespaces.get("does-not-exist"); } catch (error) { if (error instanceof NotFoundError) { console.error(`404 Not Found: ${error.message}`); } else if (error instanceof UnauthorizedError) { console.error("Invalid API key — check AGENTSET_API_KEY"); } else if (error instanceof RateLimitExceededError) { console.error("Rate limit hit, back off and retry"); } else if (error instanceof AgentsetError) { console.error(`API error [${error.status}/${error.code}]: ${error.message}`); if (error.docUrl) console.error(`Docs: ${error.docUrl}`); } else { throw error; // re-throw unexpected errors } } ``` -------------------------------- ### Initialize Agentset Client Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Create the top-level API client with your API key. Optionally, override the base URL for self-hosted instances or provide a custom fetcher for specific environments. ```typescript import { Agentset } from "agentset"; import nodeFetch from "node-fetch"; // For Node.js < 18 // Standard initialization const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY!, }); // With custom base URL (self-hosted) and custom fetcher const agentsetCustom = new Agentset({ apiKey: process.env.AGENTSET_API_KEY!, baseUrl: "https://my-self-hosted-instance.example.com", fetcher: nodeFetch as typeof fetch, }); ``` -------------------------------- ### ns.warmUp(options?) Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Pre-warms the vector search cache for a namespace to reduce cold-start latency on the first query. Useful to call before expected traffic spikes. ```APIDOC ## `ns.warmUp(options?)` — Warm namespace cache Pre-warms the vector search cache for a namespace to reduce cold-start latency on the first query. Useful to call before expected traffic spikes. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); const result = await ns.warmUp(); console.log(result); // { status: "warming" } ``` ``` -------------------------------- ### Creating a Vercel AI SDK Compatible Tool Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Shows how to use `makeAgentsetTool` to create a tool for Vercel AI SDK's `generateText` or `streamText` functions, enabling LLMs to search an Agentset namespace. ```APIDOC ## `makeAgentsetTool(namespace, options?, extra?)` — Vercel AI SDK tool (`@agentset/ai-sdk`) Creates a Vercel AI SDK-compatible `tool` that searches an Agentset namespace. Drop it into the `tools` object of any `generateText` or `streamText` call to give LLMs retrieval capability over your knowledge base. ```typescript import { Agentset } from "agentset"; import { makeAgentsetTool } from "@agentset/ai-sdk"; import { generateText } from "ai"; import { openai } from "@ai-sdk/openai"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); const knowledgeBaseTool = makeAgentsetTool( ns, { topK: 10, rerank: true, rerankLimit: 5 }, // search options ); const { text } = await generateText({ model: openai("gpt-4o-mini"), prompt: "How do I reset my password?", tools: { searchKnowledgeBase: knowledgeBaseTool }, maxSteps: 3, }); console.log(text); // "To reset your password, navigate to the login page and click 'Forgot Password'..." ``` ``` -------------------------------- ### Initialize Agentset Client and Manage Namespaces Source: https://github.com/agentset-ai/agentset-ts/blob/main/packages/agentset/README.md Initialize the Agentset client with an API key and create or access a namespace. Custom embedding models can be configured during namespace creation. ```typescript import { Agentset } from "agentset"; // Initialize the client const agentset = new Agentset({ apiKey: "your_api_key_here", }); // Create a namespace const namespace = await agentset.namespaces.create({ name: "My Knowledge Base", // Optional: provide custom embedding model embeddingConfig: { provider: "OPENAI", model: "text-embedding-3-small", apiKey: "your_openai_api_key_here", }, }); // Get a namespace by ID or slug const ns = agentset.namespace("my-knowledge-base"); ``` -------------------------------- ### Create a namespace Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Creates a new namespace (knowledge base). A `name` is required. You can optionally provide a `slug`, and configure a custom `embeddingConfig` to use your own embedding provider (e.g., OpenAI) instead of the default. ```APIDOC ## `agentset.namespaces.create(params)` — Create a namespace Creates a new namespace (knowledge base). A `name` is required. You can optionally provide a `slug`, and configure a custom `embeddingConfig` to use your own embedding provider (e.g., OpenAI) instead of the default. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); // Basic creation const ns = await agentset.namespaces.create({ name: "Product Documentation", slug: "product-docs", }); // With custom OpenAI embedding model const nsWithEmbedding = await agentset.namespaces.create({ name: "Support Knowledge Base", slug: "support-kb", embeddingConfig: { provider: "OPENAI", model: "text-embedding-3-small", apiKey: process.env.OPENAI_API_KEY!, }, }); console.log(nsWithEmbedding.id); // "ns_xyz789" ``` ``` -------------------------------- ### Create Vercel AI SDK Tool for Agentset Namespace Search Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Use `makeAgentsetTool` from `@agentset/ai-sdk` to create a Vercel AI SDK-compatible tool for searching an Agentset namespace. This allows LLMs to retrieve information from your knowledge base. ```typescript import { Agentset } from "agentset"; import { makeAgentsetTool } from "@agentset/ai-sdk"; import { generateText } from "ai"; import { openai } from "@ai-sdk/openai"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); const knowledgeBaseTool = makeAgentsetTool( ns, { topK: 10, rerank: true, rerankLimit: 5 }, // search options ); const { text } = await generateText({ model: openai("gpt-4o-mini"), prompt: "How do I reset my password?", tools: { searchKnowledgeBase: knowledgeBaseTool }, maxSteps: 3, }); console.log(text); // "To reset your password, navigate to the login page and click 'Forgot Password'..." ``` -------------------------------- ### Upload a Single File with Agentset Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Handles the full upload flow by requesting a presigned URL and then PUTting the file directly to storage. Accepts a File, Blob, or Node.js fs.ReadStream. Returns a key for ingestion. ```typescript import { Agentset } from "agentset"; import fs from "fs"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); // Browser: use a File from an // Node.js: wrap a ReadStream const stream = fs.createReadStream("./user-manual.pdf"); const { key } = await ns.uploads.upload({ file: stream, contentType: "application/pdf", }); console.log(`Uploaded with key: ${key}`); // key: "uploads/user-manual.pdf" // Then ingest it await ns.ingestion.create({ name: "User Manual", payload: { type: "FILE", fileKey: key }, }); ``` -------------------------------- ### Upload a single file Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Handles the full upload flow: requests a presigned URL from Agentset, then PUTs the file directly to storage. Accepts a File, Blob, or Node.js fs.ReadStream. Returns a key to use in ns.ingestion.create. ```APIDOC ## `ns.uploads.upload(file)` — Upload a single file Handles the full upload flow: requests a presigned URL from Agentset, then PUTs the file directly to storage. Accepts a `File`, `Blob`, or Node.js `fs.ReadStream`. Returns a `key` to use in `ns.ingestion.create`. ### Parameters #### Request Body - **file** (File | Blob | fs.ReadStream) - Required - The file to upload. - **contentType** (string) - Required - The MIME type of the file. ### Response #### Success Response (200) - **key** (string) - The key to use for ingestion. ``` -------------------------------- ### ns.ingestion.create(params) Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Creates an ingestion job to ingest content into the namespace. Supports various payload types and optional configuration. ```APIDOC ## `ns.ingestion.create(params)` — Create an ingestion job Ingests content into the namespace. The `payload` supports multiple types: `TEXT` (inline text), `FILE` (a previously uploaded file key), `URL` (a web page), and others. An optional `config` object controls chunk size, overlap, language, and OCR/LLM parsing options. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); // Ingest plain text const textJob = await ns.ingestion.create({ name: "Introduction Article", payload: { type: "TEXT", text: "Agentset is a RAG-as-a-service platform providing AI-powered search and retrieval.", }, }); console.log(textJob.id); // "job_abc123" console.log(textJob.status); // "QUEUED" // Ingest a URL const urlJob = await ns.ingestion.create({ name: "Getting Started Docs", payload: { type: "URL", url: "https://docs.example.com/getting-started", }, }); // Ingest an uploaded file (key from ns.uploads.upload()) const fileJob = await ns.ingestion.create({ name: "User Manual PDF", payload: { type: "FILE", fileKey: "uploads/user-manual.pdf", }, config: { chunkSize: 512, chunkOverlap: 50, }, }); ``` ``` -------------------------------- ### Warm namespace cache with Agentset SDK Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Pre-warms the vector search cache for a namespace to reduce cold-start latency on the first query. Useful to call before expected traffic spikes. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); const result = await ns.warmUp(); console.log(result); // { status: "warming" } ``` -------------------------------- ### ns.ingestion.all(params?, options?) Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Returns a paginated list of ingest jobs for the namespace. Supports cursor-based pagination and filtering by status. ```APIDOC ## `ns.ingestion.all(params?, options?)` — List ingestion jobs Returns a paginated list of ingest jobs for the namespace. Supports cursor-based pagination via `nextCursor` and optional filtering by `statuses`. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); // List all jobs const { jobs, pagination } = await ns.ingestion.all(); console.log(`${jobs.length} jobs, next cursor: ${pagination.nextCursor}`); // Filter by status const { jobs: failedJobs } = await ns.ingestion.all({ statuses: ["FAILED"], }); failedJobs.forEach((j) => console.log(`Failed job: ${j.id} — ${j.name}`)); // Paginate const page2 = await ns.ingestion.all({ cursor: pagination.nextCursor ?? undefined }); ``` ``` -------------------------------- ### Upload multiple files Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Uploads an array of files concurrently using batch presigned URLs. Returns an array of { key } objects in the same order as the input. ```APIDOC ## `ns.uploads.uploadBatch(files)` — Upload multiple files Uploads an array of files concurrently using batch presigned URLs. Returns an array of `{ key }` objects in the same order as the input. ### Parameters #### Request Body - **files** (Array<{ file: File | Blob | fs.ReadStream, contentType: string }> ) - Required - An array of file objects to upload. ### Response #### Success Response (200) - **keys** (Array<{ key: string }>) - An array of objects, each containing a key for the uploaded file. ``` -------------------------------- ### Multi-step Agentic RAG with AgenticEngine Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Details the usage of `AgenticEngine` for implementing multi-step agentic Retrieval-Augmented Generation (RAG) pipelines within Next.js API routes, including query generation, searching, evaluation, and streaming grounded answers. ```APIDOC ## `AgenticEngine(namespace, params, dataStreamParams?)` — Multi-step agentic RAG (`@agentset/ai-sdk`) Runs a full agentic RAG pipeline: (1) generates multiple search queries from the chat history, (2) searches the namespace for each, (3) evaluates whether retrieved sources are sufficient to answer, repeating up to `maxEvals` times, then (4) streams a grounded answer. Emits structured `data-status`, `data-queries`, and `data-sources` parts via `UIMessageStream`. Designed for Next.js App Router API routes. ```typescript // app/api/chat/route.ts (Next.js App Router) import { Agentset } from "agentset"; import { AgenticEngine } from "@agentset/ai-sdk"; import { openai } from "@ai-sdk/openai"; import type { ModelMessage } from "ai"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); export async function POST(req: Request) { const { messages }: { messages: ModelMessage[] } = await req.json(); const stream = AgenticEngine(ns, { messages, maxEvals: 3, // max query-evaluate loops tokenBudget: 4096, // stop looping if token budget exhausted queryOptions: { topK: 50, rerank: true, rerankLimit: 15 }, generateQueriesStep: { model: openai("gpt-4o-mini") }, evaluateQueriesStep: { model: openai("gpt-4o-mini") }, answerStep: { model: openai("gpt-4o"), maxTokens: 1024, }, afterQueries: (totalQueries) => { console.log(`Ran ${totalQueries} searches`); }, postProcessChunks: (chunks) => chunks.slice(0, 10), // optional chunk post-processing }); return stream.toResponse(); } // Client-side (React + useChat from "ai/react"): // The stream emits typed data parts: // - { type: "data-status", data: "generating-queries" | "searching" | "generating-answer" } // - { type: "data-queries", data: string[] } // - { type: "data-sources", data: SearchResultSchema[] } ``` ``` -------------------------------- ### Implement Agentic RAG with AgenticEngine in Next.js Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Utilize `AgenticEngine` from `@agentset/ai-sdk` for a multi-step agentic RAG pipeline in Next.js App Router API routes. This engine generates search queries, searches the namespace, evaluates sources, and streams a grounded answer. ```typescript // app/api/chat/route.ts (Next.js App Router) import { Agentset } from "agentset"; import { AgenticEngine } from "@agentset/ai-sdk"; import { openai } from "@ai-sdk/openai"; import type { ModelMessage } from "ai"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); export async function POST(req: Request) { const { messages }: { messages: ModelMessage[] } = await req.json(); const stream = AgenticEngine(ns, { messages, maxEvals: 3, // max query-evaluate loops tokenBudget: 4096, // stop looping if token budget exhausted queryOptions: { topK: 50, rerank: true, rerankLimit: 15 }, generateQueriesStep: { model: openai("gpt-4o-mini") }, evaluateQueriesStep: { model: openai("gpt-4o-mini") }, answerStep: { model: openai("gpt-4o"), maxTokens: 1024, }, afterQueries: (totalQueries) => { console.log(`Ran ${totalQueries} searches`); }, postProcessChunks: (chunks) => chunks.slice(0, 10), // optional chunk post-processing }); return stream.toResponse(); } // Client-side (React + useChat from "ai/react"): // The stream emits typed data parts: // - { type: "data-status", data: "generating-queries" | "searching" | "generating-answer" } // - { type: "data-queries", data: string[] } // - { type: "data-sources", data: SearchResultSchema[] } ``` -------------------------------- ### Upload Multiple Files Concurrently with Agentset Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Uploads an array of files concurrently using batch presigned URLs. Returns an array of { key } objects in the same order as the input. Useful for ingesting multiple documents in parallel. ```typescript import { Agentset } from "agentset"; import fs from "fs"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); const files = [ { file: fs.createReadStream("./guide-a.pdf"), contentType: "application/pdf" }, { file: fs.createReadStream("./guide-b.pdf"), contentType: "application/pdf" }, { file: fs.createReadStream("./notes.txt"), contentType: "text/plain" }, ]; const keys = await ns.uploads.uploadBatch(files); // [{ key: "uploads/guide-a.pdf" }, { key: "uploads/guide-b.pdf" }, { key: "uploads/notes.txt" }] // Ingest all in parallel await Promise.all( keys.map(({ key }, i) ns.ingestion.create({ name: `Document ${i + 1}`, payload: { type: "FILE", fileKey: key }, }), ), ); ``` -------------------------------- ### Error Handling with Typed Error Classes Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Demonstrates how to import and use typed error classes like `NotFoundError` and `AgentsetError` for precise error handling when interacting with the Agentset API. ```APIDOC ## Error Handling — Typed error classes All API errors are typed subclasses of `AgentsetError` with `status` (HTTP code), `code` (string), and optional `docUrl`. Import and use them for precise error handling. ```typescript import { Agentset, AgentsetError, BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitExceededError, InternalServerError, } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); try { await agentset.namespaces.get("does-not-exist"); } catch (error) { if (error instanceof NotFoundError) { console.error(`404 Not Found: ${error.message}`); } else if (error instanceof UnauthorizedError) { console.error("Invalid API key — check AGENTSET_API_KEY"); } else if (error instanceof RateLimitExceededError) { console.error("Rate limit hit, back off and retry"); } else if (error instanceof AgentsetError) { console.error(`API error [${error.status}/${error.code}]: ${error.message}`); if (error.docUrl) console.error(`Docs: ${error.docUrl}`); } else { throw error; // re-throw unexpected errors } } ``` ``` -------------------------------- ### Perform semantic/keyword search with Agentset SDK Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Searches the namespace for relevant chunks matching a natural-language query. Supports optional parameters for reranking and top-K control, as well as multi-tenant support. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); // Basic search const results = await ns.search("How do I reset my password?"); // With reranking and top-K control const ranked = await ns.search( "installation guide", { topK: 20, rerank: true, rerankLimit: 5, rerankModel: "cohere-rerank-v3.5", }, ); // With multi-tenant support const tenantResults = await ns.search( "billing information", {}, { tenantId: "tenant_customer_42" }, ); ranked.forEach((r, i) => { console.log(`[${i + 1}] score=${r.score.toFixed(3)} — ${r.text.slice(0, 80)}...`); }); // [1] score=0.932 — Install the package using npm: npm install my-product... // [2] score=0.871 — To get started, run the setup wizard... ``` -------------------------------- ### List ingestion jobs with Agentset SDK Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Returns a paginated list of ingest jobs for the namespace. Supports cursor-based pagination and optional filtering by statuses. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); // List all jobs const { jobs, pagination } = await ns.ingestion.all(); console.log(`${jobs.length} jobs, next cursor: ${pagination.nextCursor}`); // Filter by status const { jobs: failedJobs } = await ns.ingestion.all({ statuses: ["FAILED"], }); failedJobs.forEach((j) => console.log(`Failed job: ${j.id} — ${j.name}`)); // Paginate const page2 = await ns.ingestion.all({ cursor: pagination.nextCursor ?? undefined }); ``` -------------------------------- ### List All Namespaces Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Retrieve a list of all namespaces belonging to the authenticated organization. Each namespace object contains its ID, slug, name, and embedding configuration. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const namespaces = await agentset.namespaces.list(); // [ // { id: "ns_abc123", slug: "my-knowledge-base", name: "My Knowledge Base", ... }, // { id: "ns_def456", slug: "support-docs", name: "Support Docs", ... } // ] console.log(`Found ${namespaces.length} namespaces`); namespaces.forEach((ns) => console.log(`- ${ns.name} (${ns.slug})`)); ``` -------------------------------- ### Search Knowledge Base Source: https://github.com/agentset-ai/agentset-ts/blob/main/packages/agentset/README.md Search the knowledge base using a query string. ```typescript // Search the knowledge base const results = await ns.search("What is Agentset?"); ``` -------------------------------- ### List all namespaces Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Returns all namespaces belonging to the authenticated organization. Each `NamespaceSchema` object includes the namespace's `id`, `slug`, `name`, and embedding configuration. ```APIDOC ## `agentset.namespaces.list()` — List all namespaces Returns all namespaces belonging to the authenticated organization. Each `NamespaceSchema` object includes the namespace's `id`, `slug`, `name`, and embedding configuration. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const namespaces = await agentset.namespaces.list(); // [ // { id: "ns_abc123", slug: "my-knowledge-base", name: "My Knowledge Base", ... }, // { id: "ns_def456", slug: "support-docs", name: "Support Docs", ... } // ] console.log(`Found ${namespaces.length} namespaces`); namespaces.forEach((ns) => console.log(`- ${ns.name} (${ns.slug})`)); ``` ``` -------------------------------- ### Search Knowledge Base Source: https://github.com/agentset-ai/agentset-ts/blob/main/README.md Search the knowledge base for specific queries. ```typescript // Search the knowledge base const results = await ns.search("What is Agentset?"); ``` -------------------------------- ### ns.search(query, params?, options?) Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Searches the namespace for relevant chunks matching a natural-language query. Supports optional parameters for control and reranking. ```APIDOC ## `ns.search(query, params?, options?)` — Semantic/keyword search Searches the namespace for relevant chunks matching a natural-language query. Supports optional parameters including `topK`, `rerank`, `rerankLimit`, and `rerankModel`. Returns an array of `SearchResultSchema` objects, each with `id`, `text`, `score`, and metadata. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); // Basic search const results = await ns.search("How do I reset my password?"); // With reranking and top-K control const ranked = await ns.search( "installation guide", { topK: 20, rerank: true, rerankLimit: 5, rerankModel: "cohere-rerank-v3.5", }, ); // With multi-tenant support const tenantResults = await ns.search( "billing information", {}, { tenantId: "tenant_customer_42" }, ); ranked.forEach((r, i) => { console.log(`[${i + 1}] score=${r.score.toFixed(3)} — ${r.text.slice(0, 80)}...`); }); // [1] score=0.932 — Install the package using npm: npm install my-product... // [2] score=0.871 — To get started, run the setup wizard... ``` ``` -------------------------------- ### Manage Ingestion Jobs and Documents Source: https://github.com/agentset-ai/agentset-ts/blob/main/README.md List all ingestion jobs and documents within a namespace. Also demonstrates retrieving a specific ingestion job by its ID. ```typescript // List all ingestion jobs const { jobs, pagination } = await ns.ingestion.all(); // Get a specific ingestion job const job = await ns.ingestion.get("job_id"); // List all documents const { documents } = await ns.documents.all(); ``` -------------------------------- ### ns.documents.all(params?, options?) Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Returns a paginated list of processed documents within the namespace. Supports filtering by document statuses and cursor-based pagination for efficient data retrieval. ```APIDOC ## `ns.documents.all(params?, options?)` — List documents Returns a paginated list of processed documents for the namespace. Supports filtering by `statuses` and cursor-based pagination. ### Parameters #### Query Parameters - **statuses** (array of strings) - Optional - Filters documents by their status (e.g., `["PROCESSING"]`). - **pagination** (object) - Optional - Parameters for cursor-based pagination. - **cursor** (string) - Optional - The cursor for the next page of results. - **limit** (integer) - Optional - The maximum number of documents to return per page. ### Response #### Success Response (200) - **documents** (array of objects) - A list of document objects. - **id** (string) - The unique identifier for the document. - **name** (string) - The name of the document. - **status** (string) - The current status of the document. - **pagination** (object) - Information for paginating through results. - **nextCursor** (string) - The cursor for fetching the next page of results, or null if there are no more pages. ### Request Example ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); // List all documents const { documents, pagination } = await ns.documents.all(); documents.forEach((doc) => { console.log(`${doc.id}: ${doc.name} [${doc.status}]`); }); // Filter by status const { documents: pending } = await ns.documents.all({ statuses: ["PROCESSING"], }); ``` ### Response Example ```json { "documents": [ { "id": "doc_111", "name": "Introduction Article", "status": "COMPLETED" }, { "id": "doc_222", "name": "Getting Started Docs", "status": "COMPLETED" } ], "pagination": { "nextCursor": "some_cursor_string" } } ``` ``` -------------------------------- ### Create an ingestion job with Agentset SDK Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Ingests content into the namespace. The payload supports multiple types including TEXT, FILE, and URL. An optional config object controls chunk size, overlap, and parsing options. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); // Ingest plain text const textJob = await ns.ingestion.create({ name: "Introduction Article", payload: { type: "TEXT", text: "Agentset is a RAG-as-a-service platform providing AI-powered search and retrieval.", }, }); console.log(textJob.id); // "job_abc123" console.log(textJob.status); // "QUEUED" // Ingest a URL const urlJob = await ns.ingestion.create({ name: "Getting Started Docs", payload: { type: "URL", url: "https://docs.example.com/getting-started", }, }); // Ingest an uploaded file (key from ns.uploads.upload()) const fileJob = await ns.ingestion.create({ name: "User Manual PDF", payload: { type: "FILE", fileKey: "uploads/user-manual.pdf", }, config: { chunkSize: 512, chunkOverlap: 50, }, }); ``` -------------------------------- ### Create a New Namespace Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Create a new namespace with a required name and an optional slug. Custom embedding configurations, such as using OpenAI models, can also be specified. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); // Basic creation const ns = await agentset.namespaces.create({ name: "Product Documentation", slug: "product-docs", }); // With custom OpenAI embedding model const nsWithEmbedding = await agentset.namespaces.create({ name: "Support Knowledge Base", slug: "support-kb", embeddingConfig: { provider: "OPENAI", model: "text-embedding-3-small", apiKey: process.env.OPENAI_API_KEY!, }, }); console.log(nsWithEmbedding.id); // "ns_xyz789" ``` -------------------------------- ### Ingest Content and Manage Documents Source: https://github.com/agentset-ai/agentset-ts/blob/main/packages/agentset/README.md Ingest text content into a namespace and manage documents. This includes creating new ingestion jobs, listing all jobs, retrieving a specific job, and listing all documents within a namespace. ```typescript // Ingest content await ns.ingestion.create({ payload: { type: "TEXT", text: "This is some content to ingest into the knowledge base.", name: "Introduction", }, }); // List all ingestion jobs const { jobs, pagination } = await ns.ingestion.all(); // Get a specific ingestion job const job = await ns.ingestion.get("job_id"); // List all documents const { documents } = await ns.documents.all(); ``` -------------------------------- ### agentset.namespace(namespaceId) Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Returns a NamespaceResource scoped to a specific namespace ID or slug. This is the primary way to access sub-resources. ```APIDOC ## `agentset.namespace(namespaceId)` — Scoped namespace accessor Returns a `NamespaceResource` scoped to a specific namespace ID or slug. This is the primary way to access ingestion, documents, search, uploads, and hosting sub-resources without repeating the namespace ID on every call. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const ns = agentset.namespace("product-docs"); // All sub-resources are scoped to "product-docs" const details = await ns.get(); await ns.update({ name: "Updated Name" }); const results = await ns.search("how to install"); await ns.delete(); ``` ``` -------------------------------- ### Update a namespace Source: https://context7.com/agentset-ai/agentset-ts/llms.txt Updates namespace metadata such as `name`. Returns the updated `NamespaceSchema`. ```APIDOC ## `agentset.namespaces.update(namespaceId, params)` — Update a namespace Updates namespace metadata such as `name`. Returns the updated `NamespaceSchema`. ```typescript import { Agentset } from "agentset"; const agentset = new Agentset({ apiKey: process.env.AGENTSET_API_KEY! }); const updated = await agentset.namespaces.update("product-docs", { name: "Product Documentation v2", }); console.log(updated.name); // "Product Documentation v2" ``` ```