introduces support for summarizer
This commit is contained in:
7 files changed
+361
-11
No files matched your search
@@ -9,6 +9,7 @@ const typeToPathMap: Record<keyof Endpoints, string> = {
|
||||
news: '/res/v1/news/search',
|
||||
videos: '/res/v1/videos/search',
|
||||
web: '/res/v1/web/search',
|
||||
summarizer: '/res/v1/summarizer/search',
|
||||
};
|
||||
|
||||
const defaultRequestHeaders: Record<string, string> = {
|
||||
@@ -49,7 +50,12 @@ async function issueRequest<T extends keyof Endpoints>(
|
||||
|
||||
// Handle result_filter parameter
|
||||
if (key === 'result_filter') {
|
||||
if (Array.isArray(value) && value.length > 0) {
|
||||
// Handle special behavior of 'summary' parameter:
|
||||
// Requires `result_filter` to be empty, or only contain 'summarizer'
|
||||
// see: https://bravesoftware.slack.com/archives/C01NNFM9XMM/p1751654841090929
|
||||
if ('summary' in parameters && parameters.summary === true) {
|
||||
queryParams.set(key, 'summarizer');
|
||||
} else if (Array.isArray(value) && value.length > 0) {
|
||||
queryParams.set(key, value.join(','));
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,9 @@ import type { QueryParams as ImageQueryParams } from '../tools/images/params.js'
|
||||
import type { QueryParams as VideoQueryParams } from '../tools/videos/params.js';
|
||||
import type { QueryParams as NewsQueryParams } from '../tools/news/params.js';
|
||||
import type { LocalPoisParams, LocalDescriptionsParams } from '../tools/local/params.js';
|
||||
import type { SummarizerQueryParams } from '../tools/summarizer/params.js';
|
||||
import type { WebSearchApiResponse } from '../tools/web/types.js';
|
||||
import type { SummarizerSearchApiResponse } from '../tools/summarizer/types.js';
|
||||
import type { ImageSearchApiResponse } from '../tools/images/types.js';
|
||||
import type { VideoSearchApiResponse } from '../tools/videos/types.js';
|
||||
import type { NewsSearchApiResponse } from '../tools/news/types.js';
|
||||
@@ -62,4 +64,9 @@ export type Endpoints = {
|
||||
response: LocalDescriptionsSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
summarizer: {
|
||||
params: SummarizerQueryParams;
|
||||
response: SummarizerSearchApiResponse;
|
||||
requestHeaders: Headers;
|
||||
};
|
||||
};
|
||||
@@ -3,6 +3,7 @@ import LocalSearchTool from './local/index.js';
|
||||
import VideoSearchTool from './videos/index.js';
|
||||
import ImageSearchTool from './images/index.js';
|
||||
import NewsSearchTool from './news/index.js';
|
||||
import SummarizerTool from './summarizer/index.js';
|
||||
|
||||
export default {
|
||||
WebSearchTool,
|
||||
@@ -10,4 +11,5 @@ export default {
|
||||
VideoSearchTool,
|
||||
ImageSearchTool,
|
||||
NewsSearchTool,
|
||||
SummarizerTool,
|
||||
};
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { CallToolResult, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
|
||||
import { summarizerQueryParams, type SummarizerQueryParams } from './params.js';
|
||||
import API from '../../BraveAPI/index.js';
|
||||
import { type QueryParams as WebQueryParams } from '../web/params.js';
|
||||
import { SummarizerSearchApiResponse } from './types.js';
|
||||
import { log } from '../../utils.js';
|
||||
|
||||
export const name = 'brave_summarizer';
|
||||
|
||||
export const annotations: ToolAnnotations = {
|
||||
title: 'Brave Summarizer',
|
||||
openWorldHint: true,
|
||||
};
|
||||
|
||||
export const description = `
|
||||
Retrieves AI-generated summaries of web search results using Brave's Summarizer API. This tool processes search results to create concise, coherent summaries of information gathered from multiple sources.
|
||||
|
||||
When to use:
|
||||
|
||||
- When you need a concise overview of complex topics from multiple sources
|
||||
- For quick fact-checking or getting key points without reading full articles
|
||||
- When providing users with summarized information that synthesizes various perspectives
|
||||
- For research tasks requiring distilled information from web searches
|
||||
|
||||
Returns a text summary that consolidates information from the search results. Optional features include inline references to source URLs and additional entity information.
|
||||
|
||||
Requirements: Must first perform a web search using brave_web_search with summary=true parameter. Requires a Pro AI subscription to access the summarizer functionality.
|
||||
`;
|
||||
|
||||
export const execute = async (params: SummarizerQueryParams) => {
|
||||
const response: CallToolResult = { content: [], isError: false };
|
||||
|
||||
try {
|
||||
const { summary } = await pollForSummary(params);
|
||||
|
||||
if (!summary || summary.length === 0) {
|
||||
response.isError = true;
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: 'Unable to retrieve a Summarizer summary.',
|
||||
});
|
||||
} else {
|
||||
const summaryText = summary
|
||||
.map((summary_part) => {
|
||||
if (summary_part.type === 'token') {
|
||||
return summary_part.data;
|
||||
} else if (summary_part.type === 'inline_reference') {
|
||||
return ` (${summary_part.data?.url})`;
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
})
|
||||
.join('');
|
||||
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: summaryText,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
response.isError = true;
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: 'Unable to retrieve a Summarizer summary.',
|
||||
});
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
const pollForSummary = async (
|
||||
params: SummarizerQueryParams,
|
||||
pollInterval: number = 50,
|
||||
attempts: number = 20
|
||||
): Promise<SummarizerSearchApiResponse> => {
|
||||
let result: SummarizerSearchApiResponse | null = null;
|
||||
|
||||
while (!result && attempts > 0) {
|
||||
try {
|
||||
const response = await API.issueRequest<'summarizer'>('summarizer', params);
|
||||
if (response.status === 'complete') {
|
||||
result = response;
|
||||
}
|
||||
} catch (error) {
|
||||
await log('error', `Error polling for summarizer results: ${error}`);
|
||||
await new Promise((resolve) => setTimeout(resolve, pollInterval));
|
||||
}
|
||||
|
||||
attempts--;
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
throw new Error('Summarizer summary could not be retrieved after multiple attempts.');
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
export default {
|
||||
name,
|
||||
description,
|
||||
annotations,
|
||||
inputSchema: summarizerQueryParams.shape,
|
||||
execute,
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const summarizerQueryParams = z.object({
|
||||
key: z
|
||||
.string()
|
||||
.describe('The key is equal to value of field key as part of the Summarizer response model.'),
|
||||
entity_info: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe('Returns extra entities info with the summary response.')
|
||||
.optional(),
|
||||
inline_references: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe('Adds inline references to the summary response.')
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type SummarizerQueryParams = z.infer<typeof summarizerQueryParams>;
|
||||
|
||||
export const chatCompletionsMessage = z.object({
|
||||
role: z
|
||||
.enum(['user'])
|
||||
.default('user')
|
||||
.describe('The role of the message. Only "user" is supported for now.'),
|
||||
content: z
|
||||
.string()
|
||||
.describe('The content of the message. The value is the question to be answered.'),
|
||||
});
|
||||
|
||||
export type ChatCompletionsMessage = z.infer<typeof chatCompletionsMessage>;
|
||||
|
||||
export const chatCompletionParams = z.object({
|
||||
messages: z
|
||||
.array(chatCompletionsMessage)
|
||||
.describe(
|
||||
'The messages to use for the chat completion. The value is a list of ChatCompletionsMessage response models.'
|
||||
),
|
||||
model: z
|
||||
.enum(['brave-pro', 'brave'])
|
||||
.default('brave-pro')
|
||||
.optional()
|
||||
.describe(
|
||||
'The model to use for the chat completion. The value can be "brave-pro" (default) or "brave".'
|
||||
),
|
||||
stream: z
|
||||
.boolean()
|
||||
.default(true)
|
||||
.optional()
|
||||
.describe(
|
||||
'Whether to stream the response. The value is `true` by default. When using the OpenAI CLI, use `openai.AsyncOpenAI` for streaming and `openai.OpenAI` for blocking mode.'
|
||||
),
|
||||
country: z
|
||||
.string()
|
||||
.default('us')
|
||||
.optional()
|
||||
.describe(
|
||||
'The country backend to use for the chat completion. The value is "us" by default. Note: This parameter is passed in extra_body field when using the OpenAI CLI.'
|
||||
),
|
||||
language: z
|
||||
.string()
|
||||
.default('en')
|
||||
.optional()
|
||||
.describe(
|
||||
'The language to use for the chat completion. The value is "en" by default. Note: This parameter is passed in extra_body field when using the OpenAI CLI.'
|
||||
),
|
||||
enable_entities: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.optional()
|
||||
.describe(
|
||||
'Whether to enable entities in the chat completion. The value is `false` by default. Note: This parameter is passed in extra_body field when using the OpenAI CLI.'
|
||||
),
|
||||
enable_citations: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.optional()
|
||||
.describe(
|
||||
'Whether to enable citations in the chat completion. The value is `false` by default. Note: This parameter is passed in extra_body field when using the OpenAI CLI.'
|
||||
),
|
||||
});
|
||||
|
||||
export type ChatCompletionParams = z.infer<typeof chatCompletionParams>;
|
||||
@@ -0,0 +1,139 @@
|
||||
export interface SummarizerSearchApiResponse {
|
||||
/** The type of summarizer search API result. The value is always summarizer. */
|
||||
type: 'summarizer';
|
||||
/** The current status of summarizer for the given key. The value can be either failed or complete. */
|
||||
status: string;
|
||||
/** The title for the summary. */
|
||||
title?: string;
|
||||
/** Details for the summary message. */
|
||||
summary?: SummaryMessage[];
|
||||
/** Enrichments that can be added to the summary message. */
|
||||
enrichments?: SummaryEnrichments;
|
||||
/** Followup queries relevant to the current query. */
|
||||
followups?: string[];
|
||||
/** Details on the entities in the summary message. */
|
||||
entities_infos?: Record<string, SummaryEntityInfo>;
|
||||
}
|
||||
|
||||
interface SummaryMessage {
|
||||
/** The type of subset of a summary message. The value can be token (a text excerpt from the summary), enum_item (a summary entity), enum_start (describes the beginning of summary entities, which means the following item(s) in the summary list will be entities), enum_end (the end of summary entities) or inline_reference (an inline reference to the summary, requires inline_references query param to be set). */
|
||||
type: string;
|
||||
/** The summary entity or the explanation for the type field. For type enum_start the value can be ol or ul, which means an ordered list or an unordered list of entities follows respectively. For type enum_end there is no value. For type token the value is a text excerpt. For type enum_item the value is the SummaryEntity response model. For type inline_reference the value is the SummaryInlineReference response model. */
|
||||
data?: SummaryEntity | SummaryInlineReference;
|
||||
}
|
||||
|
||||
interface TextLocation {
|
||||
/** The 0-based index, where the important part of the text starts. */
|
||||
start: number;
|
||||
/** The 0-based index, where the important part of the text ends. */
|
||||
end: number;
|
||||
}
|
||||
|
||||
interface SummaryEntity {
|
||||
/** A unique identifier for the entity. */
|
||||
uuid: string;
|
||||
/** The name of the entity. */
|
||||
name: string;
|
||||
/** The URL where further details on the entity can be found. */
|
||||
url?: string;
|
||||
/** A text message describing the entity. */
|
||||
text?: string;
|
||||
/** The image associated with the entity. */
|
||||
images?: SummaryImage[];
|
||||
/** The location of the entity in the summary message. */
|
||||
highlight?: TextLocation[];
|
||||
}
|
||||
|
||||
interface SummaryInlineReference {
|
||||
/** The type of inline reference. The value is always inline_reference. */
|
||||
type: string;
|
||||
/** The URL that is being referenced. */
|
||||
url: string;
|
||||
/** The start index of the inline reference in the summary message. */
|
||||
start_index: number;
|
||||
/** The end index of the inline reference in the summary message. */
|
||||
end_index: number;
|
||||
/** The ordinal number of the inline reference. */
|
||||
number: number;
|
||||
/** The favicon of the URL that is being referenced. */
|
||||
favicon?: string;
|
||||
/** The reference text snippet. */
|
||||
snippet?: string;
|
||||
}
|
||||
|
||||
interface Thumbnail {
|
||||
/** The served URL of the picture thumbnail. */
|
||||
src: string;
|
||||
/** The original URL of the image. */
|
||||
original?: string;
|
||||
}
|
||||
|
||||
interface ImageProperties {
|
||||
/** The image URL. */
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface Image {
|
||||
/** The thumbnail associated with the image. */
|
||||
thumbnail: Thumbnail;
|
||||
/** The URL of the image. */
|
||||
url?: string;
|
||||
/** Metadata on the image. */
|
||||
properties?: ImageProperties;
|
||||
}
|
||||
|
||||
interface SummaryImage extends Image {
|
||||
/** Text associated with the image. */
|
||||
text?: string;
|
||||
}
|
||||
|
||||
interface SummaryEnrichments {
|
||||
/** The raw summary message. */
|
||||
raw: string;
|
||||
/** The images associated with the summary. */
|
||||
images?: SummaryImage[];
|
||||
/** The answers in the summary message. */
|
||||
qa?: SummaryAnswer[];
|
||||
/** The entities in the summary message. */
|
||||
entities?: SummaryEntity[];
|
||||
/** References based on which the summary was built. */
|
||||
context?: SummaryContext[];
|
||||
}
|
||||
|
||||
interface SummaryAnswer {
|
||||
/** The answer text. */
|
||||
answer: string;
|
||||
/** A score associated with the answer. */
|
||||
score?: number;
|
||||
/** The location of the answer in the summary message. */
|
||||
highlight?: TextLocation;
|
||||
}
|
||||
|
||||
interface MetaUrl {
|
||||
/** The protocol scheme extracted from the URL. */
|
||||
scheme?: string;
|
||||
/** The network location part extracted from the URL. */
|
||||
netloc?: string;
|
||||
/** The lowercased domain name extracted from the URL. */
|
||||
hostname?: string;
|
||||
/** The favicon used for the URL. */
|
||||
favicon?: string;
|
||||
/** The hierarchical path of the URL useful as a display string. */
|
||||
path?: string;
|
||||
}
|
||||
|
||||
interface SummaryContext {
|
||||
/** The title of the reference. */
|
||||
title: string;
|
||||
/** The URL where the reference can be found. */
|
||||
url: string;
|
||||
/** Details on the URL associated with the reference. */
|
||||
meta_url?: MetaUrl;
|
||||
}
|
||||
|
||||
interface SummaryEntityInfo {
|
||||
/** The name of the provider. */
|
||||
provider?: string;
|
||||
/** Description of the entity. */
|
||||
description?: string;
|
||||
}
|
||||
+18
-10
@@ -39,18 +39,26 @@ export const description = `
|
||||
|
||||
export const execute = async (params: QueryParams) => {
|
||||
const response = { content: [] as TextContent[], isError: false };
|
||||
const { web, faq, discussions, news, videos } = await API.issueRequest<'web'>('web', params);
|
||||
const { web, faq, discussions, news, videos, summarizer } = await API.issueRequest<'web'>(
|
||||
'web',
|
||||
params
|
||||
);
|
||||
|
||||
if (summarizer) {
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: `Summarizer key: ${summarizer.key}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (!web || !Array.isArray(web.results) || web.results.length < 1) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text' as const,
|
||||
text: 'No web results found',
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
response.isError = true;
|
||||
response.content.push({
|
||||
type: 'text' as const,
|
||||
text: 'No web results found',
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// TODO (Sampson): The following is unnecessarily repetitive.
|
||||
|
||||
Reference in new issue
Block a user