-
-
Notifications
You must be signed in to change notification settings - Fork 997
[codex] Add Bocha web search example #1341
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
NiTingKY
wants to merge
2
commits into
VoltAgent:main
Choose a base branch
from
NiTingKY:codex/add-bocha-search-example
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| }, | ||
| "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" | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 ?? []; | ||
|
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, | ||
| })); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(), | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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", | ||
| }), | ||
| ); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.