Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions examples/with-bocha-search/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# OpenAI API Key (required)
OPENAI_API_KEY=your_openai_api_key_here

# Bocha Search API Key (required)
BOCHA_SEARCH_API_KEY=your_bocha_search_api_key_here

# Optional Bocha Search API URL
BOCHA_SEARCH_API_URL=https://api.bochaai.com/v1/web-search
81 changes: 81 additions & 0 deletions examples/with-bocha-search/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# VoltAgent with Bocha Web Search

This example shows how to add Bocha Web Search to a VoltAgent agent as a typed tool. The agent can search the web for current, source-linked results and use those results to answer user questions.

## Features

- Web search through Bocha's search API
- Source-linked results with title, URL, snippet, source, and published date
- Optional freshness, result count, include-domain, and exclude-domain controls
- Clear missing-key and API error messages
- Unit-tested request and response mapping helpers

## Prerequisites

1. A Bocha Search API key.
2. An OpenAI API key for the agent model.

## Setup

Install dependencies from the repository root:

```bash
pnpm install
```

Copy the example environment file:

```bash
cp examples/with-bocha-search/.env.example examples/with-bocha-search/.env
```

Then set your keys:

```env
OPENAI_API_KEY=your_actual_openai_api_key
BOCHA_SEARCH_API_KEY=your_actual_bocha_search_api_key
BOCHA_SEARCH_API_URL=https://api.bochaai.com/v1/web-search
```

`BOCHA_SEARCH_API_URL` is optional. The example defaults to the URL shown above.

## Run

```bash
pnpm --filter voltagent-example-with-bocha-search dev
```

The agent runs on VoltAgent's default local server and exposes a `searchAgent` with the `bochaSearch` tool.

## Example Queries

- "Search the web for the latest TypeScript agent framework news."
- "Find recent information about VoltAgent and summarize the sources."
- "Search only github.com for Bocha web search integrations."
- "Find current AI agent framework announcements from the last week."

## Tool Parameters

The `bochaSearch` tool accepts:

- `query`: Search query string.
- `count`: Number of results to return, default 5 and maximum 10.
- `freshness`: Optional Bocha freshness value such as `noLimit` or `oneWeek`.
- `includeDomains`: Optional domains to include.
- `excludeDomains`: Optional domains to exclude.

## Validation

Run the focused tests:

```bash
pnpm exec vitest run --config examples/with-bocha-search/vitest.config.ts
```

Build the example:

```bash
pnpm --filter voltagent-example-with-bocha-search build
```

No real API keys are committed. Configure `BOCHA_SEARCH_API_KEY` only in your local environment.
39 changes: 39 additions & 0 deletions examples/with-bocha-search/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "voltagent-example-with-bocha-search",
"author": "",
"dependencies": {
"@voltagent/cli": "^0.1.21",
"@voltagent/core": "^2.7.7",
"@voltagent/internal": "^1.0.3",
"@voltagent/libsql": "^2.1.2",
"@voltagent/logger": "^2.0.2",
"@voltagent/server-hono": "^2.0.14",
"ai": "^6.0.0",
"zod": "^3.25.76"
},
"devDependencies": {
"@types/node": "^24.2.1",
"tsx": "^4.21.0",
"typescript": "^5.8.2"
Comment thread
NiTingKY marked this conversation as resolved.
},
"keywords": [
"agent",
"ai",
"search",
"voltagent"
],
"license": "MIT",
"private": true,
"repository": {
"type": "git",
"url": "https://github.com/VoltAgent/voltagent.git",
"directory": "examples/with-bocha-search"
},
"scripts": {
"build": "tsc",
"dev": "tsx watch --env-file=.env ./src",
"start": "node dist/index.js",
"volt": "volt"
},
"type": "module"
}
98 changes: 98 additions & 0 deletions examples/with-bocha-search/src/bocha.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
const DEFAULT_RESULT_COUNT = 5;
const MAX_RESULT_COUNT = 10;

export type BochaSearchInput = {
query: string;
count?: number;
freshness?: string;
includeDomains?: string[];
excludeDomains?: string[];
};

export type BochaSearchResult = {
title: string;
link: string;
snippet: string;
source: string;
publishedDate: string | null;
};

type BochaWebPage = {
name?: unknown;
title?: unknown;
url?: unknown;
displayUrl?: unknown;
summary?: unknown;
snippet?: unknown;
description?: unknown;
siteName?: unknown;
datePublished?: unknown;
dateLastCrawled?: unknown;
};

export type BochaSearchResponse = {
data?: {
webPages?: {
value?: BochaWebPage[];
};
};
webPages?: {
value?: BochaWebPage[];
};
};

export type BochaSearchRequest = {
query: string;
freshness: string;
summary: boolean;
count: number;
include?: string;
exclude?: string;
};

function stringValue(value: unknown): string | undefined {
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
}

function domainsToPipeList(domains: string[] | undefined): string | undefined {
const cleaned = domains?.map((domain) => domain.trim()).filter(Boolean);
return cleaned && cleaned.length > 0 ? cleaned.join("|") : undefined;
}

export function buildBochaSearchRequest(input: BochaSearchInput): BochaSearchRequest {
const count = Math.min(input.count ?? DEFAULT_RESULT_COUNT, MAX_RESULT_COUNT);
const request: BochaSearchRequest = {
query: input.query,
freshness: input.freshness ?? "noLimit",
summary: true,
count,
};

const include = domainsToPipeList(input.includeDomains);
const exclude = domainsToPipeList(input.excludeDomains);

if (include) {
request.include = include;
}
if (exclude) {
request.exclude = exclude;
}

return request;
}

export function mapBochaSearchResponse(response: BochaSearchResponse): BochaSearchResult[] {
const pages = response.data?.webPages?.value ?? response.webPages?.value ?? [];
Comment thread
NiTingKY marked this conversation as resolved.

return pages.map((page) => ({
title: stringValue(page.name) ?? stringValue(page.title) ?? "Untitled result",
link: stringValue(page.url) ?? stringValue(page.displayUrl) ?? "",
snippet:
stringValue(page.summary) ??
stringValue(page.snippet) ??
stringValue(page.description) ??
"No snippet available.",
source: stringValue(page.siteName) ?? "Bocha Web Search",
publishedDate: stringValue(page.datePublished) ?? stringValue(page.dateLastCrawled) ?? null,
}));
}
34 changes: 34 additions & 0 deletions examples/with-bocha-search/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Agent, Memory, VoltAgent } from "@voltagent/core";
import { LibSQLMemoryAdapter } from "@voltagent/libsql";
import { createPinoLogger } from "@voltagent/logger";
import { honoServer } from "@voltagent/server-hono";
import { bochaSearchTool } from "./tools";

const logger = createPinoLogger({
name: "bocha-search-agent",
level: "info",
});

const memory = new Memory({
storage: new LibSQLMemoryAdapter(),
});

const searchAgent = new Agent({
name: "Bocha Web Search Agent",
instructions: `You are a web search agent powered by Bocha Web Search.

Use the Bocha search tool when users ask for current information, source-linked web results, recent news, or fact verification.
Summarize findings clearly and include source links from the tool results.
If Bocha returns no relevant results, say so and suggest a more specific query.`,
model: "openai/gpt-4o-mini",
tools: [bochaSearchTool],
memory,
});

new VoltAgent({
agents: {
searchAgent,
},
logger,
server: honoServer(),
});
117 changes: 117 additions & 0 deletions examples/with-bocha-search/src/tools.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { buildBochaSearchRequest, mapBochaSearchResponse } from "./bocha";
import { bochaSearchTool } from "./tools";

const originalApiKey = process.env.BOCHA_SEARCH_API_KEY;
const originalApiUrl = process.env.BOCHA_SEARCH_API_URL;

afterEach(() => {
if (originalApiKey === undefined) {
Reflect.deleteProperty(process.env, "BOCHA_SEARCH_API_KEY");
} else {
process.env.BOCHA_SEARCH_API_KEY = originalApiKey;
}

if (originalApiUrl === undefined) {
Reflect.deleteProperty(process.env, "BOCHA_SEARCH_API_URL");
} else {
process.env.BOCHA_SEARCH_API_URL = originalApiUrl;
}

vi.restoreAllMocks();
});

describe("Bocha search tool helpers", () => {
it("builds a conservative Bocha search request", () => {
expect(
buildBochaSearchRequest({
query: "latest agent framework news",
count: 20,
freshness: "oneWeek",
includeDomains: ["github.com", "voltagent.dev"],
excludeDomains: ["example.com"],
}),
).toEqual({
query: "latest agent framework news",
freshness: "oneWeek",
summary: true,
count: 10,
include: "github.com|voltagent.dev",
exclude: "example.com",
});
});

it("maps Bocha web page results into source-linked search results", () => {
const mapped = mapBochaSearchResponse({
data: {
webPages: {
value: [
{
name: "VoltAgent",
url: "https://voltagent.dev/",
summary: "Open-source TypeScript agent framework.",
siteName: "VoltAgent",
datePublished: "2026-06-01",
},
{
title: "Fallback title field",
displayUrl: "https://example.com/result",
snippet: "Snippet fallback.",
},
],
},
},
});

expect(mapped).toEqual([
{
title: "VoltAgent",
link: "https://voltagent.dev/",
snippet: "Open-source TypeScript agent framework.",
source: "VoltAgent",
publishedDate: "2026-06-01",
},
{
title: "Fallback title field",
link: "https://example.com/result",
snippet: "Snippet fallback.",
source: "Bocha Web Search",
publishedDate: null,
},
]);
});

it("uses the Bocha web search endpoint by default", async () => {
process.env.BOCHA_SEARCH_API_KEY = "test-key";
Reflect.deleteProperty(process.env, "BOCHA_SEARCH_API_URL");

const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response(
JSON.stringify({
data: {
webPages: {
value: [
{
name: "Bocha result",
url: "https://example.com/result",
summary: "Result summary.",
},
],
},
},
}),
{ status: 200 },
),
);

expect(bochaSearchTool.execute).toBeDefined();
await bochaSearchTool.execute?.({ query: "agent search", count: 1 });

expect(fetchMock).toHaveBeenCalledWith(
"https://api.bochaai.com/v1/web-search",
expect.objectContaining({
method: "POST",
}),
);
});
});
Loading