-
Notifications
You must be signed in to change notification settings - Fork 285
[Pending Evals] Update the docs-vectorize to use AI Search as backend #249
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
aninibread
wants to merge
2
commits into
cloudflare:main
Choose a base branch
from
aninibread:anni/docs-mcp-ai-search
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 1 commit
Commits
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
File renamed without changes.
11 changes: 10 additions & 1 deletion
11
apps/docs-vectorize/CHANGELOG.md → apps/docs-ai-search/CHANGELOG.md
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
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
File renamed without changes.
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
2 changes: 1 addition & 1 deletion
2
...s-vectorize/src/docs-vectorize.context.ts → ...s-ai-search/src/docs-ai-search.context.ts
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
File renamed without changes.
2 changes: 1 addition & 1 deletion
2
apps/docs-vectorize/vitest.config.ts → apps/docs-ai-search/vitest.config.ts
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
File renamed without changes.
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
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,179 @@ | ||
| import { z } from 'zod' | ||
|
|
||
| import type { CloudflareMcpAgentNoAccount } from '../types/cloudflare-mcp-agent.types' | ||
|
|
||
| interface RequiredEnv { | ||
| AI: Ai | ||
| } | ||
|
|
||
| interface AiSearchResponse { | ||
| object: string | ||
| search_query: string | ||
| data: Array<{ | ||
| file_id: string | ||
| filename: string | ||
| score: number | ||
| attributes: { | ||
| modified_date: number | ||
| folder: string | ||
| } | ||
| content: Array<{ | ||
| id: string | ||
| type: string | ||
| text: string | ||
| }> | ||
| }> | ||
| has_more: boolean | ||
| next_page: string | null | ||
| } | ||
|
|
||
| /** | ||
| * Registers the docs search tool with the MCP server using AI Search | ||
| * @param agent The MCP server instance | ||
| */ | ||
| export function registerDocsTools(agent: CloudflareMcpAgentNoAccount, env: RequiredEnv) { | ||
| agent.server.tool( | ||
| 'search_cloudflare_documentation', | ||
| `Search the Cloudflare documentation. | ||
|
|
||
| This tool should be used to answer any question about Cloudflare products or features, including: | ||
| - Workers, Pages, R2, Images, Stream, D1, Durable Objects, KV, Workflows, Hyperdrive, Queues | ||
| - AutoRAG, Workers AI, Vectorize, AI Gateway, Browser Rendering | ||
| - Zero Trust, Access, Tunnel, Gateway, Browser Isolation, WARP, DDOS, Magic Transit, Magic WAN | ||
| - CDN, Cache, DNS, Zaraz, Argo, Rulesets, Terraform, Account and Billing | ||
|
|
||
| Results are returned as semantically similar chunks to the query. | ||
| `, | ||
| { | ||
| query: z.string(), | ||
| }, | ||
| { | ||
| title: 'Search Cloudflare docs', | ||
| annotations: { | ||
| readOnlyHint: true, | ||
| }, | ||
| }, | ||
| async ({ query }) => { | ||
| const results = await queryAiSearch(env.AI, query) | ||
| const resultsAsXml = results | ||
| .map((result) => { | ||
| return `<result> | ||
| <url>${result.url}</url> | ||
| <title>${result.title}</title> | ||
| <text> | ||
| ${result.text} | ||
| </text> | ||
| </result>` | ||
| }) | ||
| .join('\n') | ||
| return { | ||
| content: [{ type: 'text', text: resultsAsXml }], | ||
| } | ||
| } | ||
| ) | ||
|
|
||
| // Note: this is a tool instead of a prompt because | ||
| // prompt support is much less common than tools. | ||
| agent.server.tool( | ||
| 'migrate_pages_to_workers_guide', | ||
| `ALWAYS read this guide before migrating Pages projects to Workers.`, | ||
| {}, | ||
| { | ||
| title: 'Get Pages migration guide', | ||
| annotations: { | ||
| readOnlyHint: true, | ||
| }, | ||
| }, | ||
| async () => { | ||
| const res = await fetch( | ||
| 'https://developers.cloudflare.com/workers/prompts/pages-to-workers.txt', | ||
| { | ||
| cf: { cacheEverything: true, cacheTtl: 3600 }, | ||
| } | ||
| ) | ||
|
|
||
| if (!res.ok) { | ||
| return { | ||
| content: [{ type: 'text', text: 'Error: Failed to fetch guide. Please try again.' }], | ||
| } | ||
| } | ||
|
|
||
| return { | ||
| content: [ | ||
| { | ||
| type: 'text', | ||
| text: await res.text(), | ||
| }, | ||
| ], | ||
| } | ||
| } | ||
| ) | ||
| } | ||
|
|
||
| async function queryAiSearch(ai: Ai, query: string) { | ||
| const response = await doWithRetries(() => | ||
| ai.autorag("docs-mcp-rag").search({ | ||
| query, | ||
| }) | ||
| ) as AiSearchResponse | ||
aninibread marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| return response.data.map((item) => ({ | ||
| similarity: item.score, | ||
| id: item.file_id, | ||
| url: sourceToUrl(item.filename), | ||
| title: extractTitle(item.filename), | ||
| text: item.content.map(c => c.text).join('\n'), | ||
| })) | ||
| } | ||
|
|
||
| function sourceToUrl(filename: string): string { | ||
| // Convert filename to URL format | ||
| // Example: "workers/configuration/index.md" -> "https://developers.cloudflare.com/workers/configuration/" | ||
| return ( | ||
| 'https://developers.cloudflare.com/' + | ||
| filename | ||
| .replace(/index\.mdx?$/, '') | ||
| .replace(/\.mdx?$/, '') | ||
| ) | ||
| } | ||
|
|
||
| function extractTitle(filename: string): string { | ||
| // Extract a reasonable title from the filename | ||
| // Example: "workers/configuration/index.md" -> "Configuration" | ||
| const parts = filename.replace(/\.mdx?$/, '').split('/') | ||
| const lastPart = parts[parts.length - 1] | ||
|
|
||
| if (lastPart === 'index') { | ||
| // Use the parent directory name if filename is index | ||
| return parts[parts.length - 2] || 'Documentation' | ||
| } | ||
|
|
||
| // Convert kebab-case or snake_case to title case | ||
| return lastPart | ||
| .replace(/[-_]/g, ' ') | ||
| .replace(/\b\w/g, l => l.toUpperCase()) | ||
| } | ||
|
|
||
| /** | ||
| * @template T | ||
| * @param {() => Promise<T>} action | ||
| */ | ||
| async function doWithRetries<T>(action: () => Promise<T>) { | ||
| const NUM_RETRIES = 10 | ||
| const INIT_RETRY_MS = 50 | ||
| for (let i = 0; i <= NUM_RETRIES; i++) { | ||
| try { | ||
| return await action() | ||
| } catch (e) { | ||
| // TODO: distinguish between user errors (4xx) and system errors (5xx) | ||
| console.error(e) | ||
| if (i === NUM_RETRIES) { | ||
| throw e | ||
| } | ||
| // Exponential backoff with full jitter | ||
| await scheduler.wait(Math.random() * INIT_RETRY_MS * Math.pow(2, i)) | ||
| } | ||
| } | ||
| // Should never reach here – last loop iteration should return | ||
| throw new Error('An unknown error occurred') | ||
| } | ||
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.