Skip to content

Instantly share code, notes, and snippets.

@bramses
Last active March 12, 2025 04:58
Show Gist options
  • Save bramses/41e90b27d156590154bcefd4119f2b19 to your computer and use it in GitHub Desktop.
Save bramses/41e90b27d156590154bcefd4119f2b19 to your computer and use it in GitHub Desktop.
search web w gpt and brave api https://brave.com/search/api/
import { openai } from "@ai-sdk/openai";
import { streamText } from "ai";
// Allow streaming responses up to 30 seconds
export const maxDuration = 30;
function extractRelevantData(data: any) {
const results: any[] = [];
// Extract from web search results
if (data.web && data.web.results) {
data.web.results.forEach((item: any) => {
results.push({
title: item.title,
url: item.url,
description: item.description,
});
});
}
// Extract from video search results
if (data.videos && data.videos.results) {
data.videos.results.forEach((item: any) => {
results.push({
title: item.title,
url: item.url,
description: item.description,
});
});
}
return results;
}
function getCurrentTime() {
return new Date().toLocaleString(); // Returns the current date and time as a string
}
function errorHandler(error: unknown) {
if (error == null) {
return "unknown error";
}
if (typeof error === "string") {
return error;
}
if (error instanceof Error) {
return error.message;
}
return JSON.stringify(error);
}
export async function POST(req: Request) {
const { messages } = await req.json();
const { CLOUD_URL } = process.env;
const userLocation = 'New York, NY';
const currentTime = getCurrentTime();
const result = streamText({
model: openai("gpt-4o-mini"),
messages,
tools: {
search: {
description: `Do not include the external search results in the response WITHOUT URLs.
Prioritize user satisfaction by using context clues and related concepts to find answers. Don't hesitate to reason about analogies, metaphors, or synonyms. If the results aren't satisfactory, apply your own world knowledge to answer. Feel free to mix and match. If you are using results from the search in your answer, INCLUDE THE LINKS. Consider broader interpretations and connections to ensure comprehensive responses. If you have external search results, include them in the response WITH URLs.
The user location is ${userLocation} and the current time is ${currentTime}.`,
parameters: z.object({
query: z.string().describe("The query to search for."),
}),
execute: async ({ query }: { query: string }) => {
const headers: HeadersInit = {
Accept: "application/json",
"Accept-Encoding": "gzip",
};
const subscriptionToken = process.env.BRAVE_SUBSCRIPTION_TOKEN;
if (subscriptionToken) {
headers["X-Subscription-Token"] = subscriptionToken;
}
const response = await fetch(
"https://api.search.brave.com/res/v1/web/search?q=" +
encodeURIComponent(query),
{
method: "GET",
headers: headers,
}
);
const exdata = await response.json();
const results = extractRelevantData(exdata);
return {
externalSearchResults: results,
};
},
},
},
});
return result.toDataStreamResponse({
getErrorMessage: errorHandler,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment