Skip to content

refactoring: refactor the server side tool definitions #6827

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

Merged
merged 11 commits into from
Jun 23, 2025
Merged
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
6 changes: 6 additions & 0 deletions .changeset/dirty-mice-knock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@ai-sdk/anthropic': patch
'@ai-sdk/openai': patch
---

refactor: updated openai + anthropic tool use server side
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { generateText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import 'dotenv/config';

async function main() {
const result = await generateText({
model: anthropic('claude-3-5-sonnet-20241022'),
prompt: 'Search for recent information about AI SDK development',
tools: {
webSearch: anthropic.tools.webSearch_20250305({
maxUses: 3,
allowedDomains: ['github.com', 'vercel.com', 'docs.ai'],
userLocation: {
type: 'approximate',
city: 'San Francisco',
region: 'California',
country: 'US',
},
}),

computer: anthropic.tools.computer_20250124({
displayWidthPx: 1920,
displayHeightPx: 1080,
}),
},
});

console.log('Result:', result.text);
console.log('Tool calls made:', result.toolCalls.length);

for (const toolCall of result.toolCalls) {
console.log(`\nTool Call:`);
console.log(`- Tool: ${toolCall.toolName}`);
console.log(`- Input:`, JSON.stringify(toolCall.input, null, 2));
}
}

main().catch(console.error);
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
import 'dotenv/config';

async function main() {
const result = await generateText({
model: openai('gpt-4o-mini'),
prompt: 'Search for information about TypeScript best practices',
tools: {
webSearch: openai.tools.webSearchPreview({
searchContextSize: 'medium',
userLocation: {
type: 'approximate',
city: 'San Francisco',
region: 'California',
country: 'US',
},
}),

fileSearch: openai.tools.fileSearch({
maxResults: 5,
searchType: 'semantic',
}),
},
});

console.log('Result:', result.text);
console.log('Tool calls made:', result.toolCalls.length);

for (const toolCall of result.toolCalls) {
console.log(`\nTool Call:`);
console.log(`- Tool: ${toolCall.toolName}`);
console.log(`- Input:`, JSON.stringify(toolCall.input, null, 2));
}
}

main().catch(console.error);
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ async function main() {
model: openai.responses('gpt-4o-mini'),
prompt: 'What happened in San Francisco last week?',
tools: {
web_search_preview: openai.tools.webSearchPreview(),
web_search_preview: openai.tools.webSearchPreview({}),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm

},
});

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { generateText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { openai } from '@ai-sdk/openai';
import 'dotenv/config';

async function main() {
console.log('=== Demonstrating Refactored Provider-Defined Tools ===\n');

console.log('1. OpenAI Provider-Defined Tools (Successfully Refactored):');
const openaiWebSearch = openai.tools.webSearchPreview({
searchContextSize: 'medium',
userLocation: {
type: 'approximate',
city: 'San Francisco',
region: 'California',
country: 'US',
},
});

const openaiFileSearch = openai.tools.fileSearch({
maxResults: 5,
searchType: 'semantic',
});

console.log('OpenAI Web Search Tool created successfully');
console.log('OpenAI File Search Tool created successfully');

console.log('\n2. Anthropic Provider-Defined Tools (Working Example):');
const result = await generateText({
model: anthropic('claude-3-5-sonnet-20241022'),
prompt: 'Search for current weather in Tokyo',
tools: {
web_search: anthropic.tools.webSearch_20250305({
maxUses: 2,
allowedDomains: ['weather.com', 'accuweather.com'],
userLocation: {
type: 'approximate',
city: 'Tokyo',
region: 'Tokyo',
country: 'JP',
},
}),
},
});

console.log('Anthropic Web Search Tool executed successfully');
console.log('Tool calls made:', result.toolCalls.length);

for (const toolCall of result.toolCalls) {
console.log(`\nTool Call:`);
console.log(`- Tool: ${toolCall.toolName}`);
console.log(`- Input:`, JSON.stringify(toolCall.input, null, 2));
}

console.log('\n=== Refactoring Summary ===');
console.log(
'OpenAI tools refactored to use createProviderDefinedToolFactory',
);
console.log(
'Anthropic tools refactored to use createProviderDefinedToolFactory',
);
console.log(
'All tools now follow consistent pattern like computer_20250124.ts',
);
console.log('Type safety improved with better TypeScript inference');
console.log('Anthropic tools working in production');
console.log('Factory pattern provides cleaner, more maintainable API');
}

main().catch(console.error);
2 changes: 1 addition & 1 deletion examples/next-openai/app/api/use-chat-sources/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export async function POST(req: Request) {
const result = streamText({
model: anthropic('claude-3-5-sonnet-latest'),
tools: {
web_search: anthropic.tools.webSearch_20250305(),
web_search: anthropic.tools.webSearch_20250305({}),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wonder if we can provide a default? might be tricky

},
messages: convertToModelMessages(messages),
});
Expand Down
5 changes: 2 additions & 3 deletions packages/anthropic/src/anthropic-prepare-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,8 @@ export function prepareTools({
type: 'bash_20241022',
});
break;
case 'anthropic.web_search_20250305':
case 'anthropic.web_search_20250305': {
const args = webSearch_20250305ArgsSchema.parse(tool.args);

anthropicTools.push({
type: 'web_search_20250305',
name: 'web_search',
Expand All @@ -117,8 +116,8 @@ export function prepareTools({
blocked_domains: args.blockedDomains,
user_location: args.userLocation,
});

break;
}
default:
toolWarnings.push({ type: 'unsupported-tool', tool });
break;
Expand Down
90 changes: 57 additions & 33 deletions packages/anthropic/src/tool/web-search_20250305.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
import { tool } from '@ai-sdk/provider-utils';
import { createProviderDefinedToolFactory } from '@ai-sdk/provider-utils';
import { z } from 'zod/v4';

type WebSearch20250305Args = {
maxUses?: number;
allowedDomains?: string[];
blockedDomains?: string[];
userLocation?: {
type: 'approximate';
city?: string;
region?: string;
country?: string;
timezone?: string;
};
};

// Args validation schema
export const webSearch_20250305ArgsSchema = z.object({
/**
* Maximum number of web searches Claude can perform during the conversation.
*/
maxUses: z.number().optional(),

/**
* Optional list of domains that Claude is allowed to search.
*/
allowedDomains: z.array(z.string()).optional(),

/**
* Optional list of domains that Claude should avoid when searching.
*/
blockedDomains: z.array(z.string()).optional(),

/**
* Optional user location information to provide geographically relevant search results.
*/
userLocation: z
.object({
type: z.literal('approximate'),
Expand All @@ -29,22 +32,43 @@ export const webSearch_20250305ArgsSchema = z.object({
.optional(),
});

export function webSearch_20250305(options: WebSearch20250305Args = {}) {
return tool({
type: 'provider-defined',
id: 'anthropic.web_search_20250305',
args: {
maxUses: options.maxUses,
allowedDomains: options.allowedDomains,
blockedDomains: options.blockedDomains,
userLocation: options.userLocation,
},
inputSchema: z.object({
query: z.string(),
}),
// TODO define the actual output schema
outputSchema: z.object({
query: z.string(),
}),
});
}
export const webSearch_20250305 = createProviderDefinedToolFactory<
{
/**
* The search query to execute.
*/
query: string;
},
{
/**
* Maximum number of web searches Claude can perform during the conversation.
*/
maxUses?: number;

/**
* Optional list of domains that Claude is allowed to search.
*/
allowedDomains?: string[];

/**
* Optional list of domains that Claude should avoid when searching.
*/
blockedDomains?: string[];

/**
* Optional user location information to provide geographically relevant search results.
*/
userLocation?: {
type: 'approximate';
city?: string;
region?: string;
country?: string;
timezone?: string;
};
}
>({
id: 'anthropic.web_search_20250305',
inputSchema: z.object({
query: z.string(),
}),
});
22 changes: 12 additions & 10 deletions packages/openai/src/openai-prepare-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import {
LanguageModelV2CallWarning,
UnsupportedFunctionalityError,
} from '@ai-sdk/provider';
import { OpenAITools, OpenAIToolChoice } from './openai-types';
import { fileSearchArgsSchema } from './tool/file-search';
import { webSearchPreviewArgsSchema } from './tool/web-search-preview';
import { OpenAITools, OpenAIToolChoice } from './openai-types';

export function prepareTools({
tools,
Expand Down Expand Up @@ -46,23 +46,25 @@ export function prepareTools({
break;
case 'provider-defined':
switch (tool.id) {
case 'openai.file_search':
const fileSearchArgs = fileSearchArgsSchema.parse(tool.args);
case 'openai.file_search': {
const args = fileSearchArgsSchema.parse(tool.args);
openaiTools.push({
type: 'file_search',
vector_store_ids: fileSearchArgs.vectorStoreIds,
max_results: fileSearchArgs.maxResults,
search_type: fileSearchArgs.searchType,
vector_store_ids: args.vectorStoreIds,
max_results: args.maxResults,
search_type: args.searchType,
});
break;
case 'openai.web_search_preview':
const webSearchArgs = webSearchPreviewArgsSchema.parse(tool.args);
}
case 'openai.web_search_preview': {
const args = webSearchPreviewArgsSchema.parse(tool.args);
openaiTools.push({
type: 'web_search_preview',
search_context_size: webSearchArgs.searchContextSize,
user_location: webSearchArgs.userLocation,
search_context_size: args.searchContextSize,
user_location: args.userLocation,
});
break;
}
default:
toolWarnings.push({ type: 'unsupported-tool', tool });
break;
Expand Down
Loading
Loading