Open History to see the last commit
1import {
2 getOpenAIProviderToolMetadata,
3 openAIProviderTool,
4} from './openai-provider-tool'
5import { getComputerUseToolMetadata } from '@tanstack/ai/adapter-internals'
6import type {
7 ComputerTool,
8 ComputerUsePreviewTool,
9} from 'openai/resources/responses/responses'
10import type { Tool } from '@tanstack/ai'
11
12/**
13 * The computer tool: `{ type: 'computer' }`, or the `computer_use_preview`
14 * tool of the `computer-use-preview` model.
15 */
16export type ComputerUseToolConfig = ComputerTool | ComputerUsePreviewTool
17
18/**
19 * Converts a standard Tool to OpenAI ComputerUseTool format
20 */
21export function convertComputerUseToolToAdapterFormat(
22 tool: Tool,
23): ComputerUseToolConfig {
24 const metadata = getOpenAIProviderToolMetadata(tool) as ComputerUseToolConfig
25 if (metadata.type === 'computer') return { type: 'computer' }
26 return {
27 type: 'computer_use_preview',
28 display_height: metadata.display_height,
29 display_width: metadata.display_width,
30 environment: metadata.environment,
31 }
32}
33
34/**
35 * Creates a standard Tool from ComputerUseTool parameters. The tool name is
36 * the tool type: `computer` or `computer_use_preview`.
37 *
38 * Base (non-branded) factory. Providers that need branded return types should
39 * re-wrap this in their own package.
40 */
41export function computerUseTool(toolData: ComputerUseToolConfig): Tool {
42 return openAIProviderTool(
43 {
44 name: toolData.type,
45 description: 'Control a virtual computer',
46 metadata: {
47 ...toolData,
48 },
49 },
50 'computer_use',
51 )
52}
53
54/**
55 * Swaps a portable computer-use tool for the native OpenAI computer tool of
56 * the model. The `computer-use-preview` models get `computer_use_preview`
57 * with the display and environment of the tool. Other models get
58 * `{ type: 'computer' }`. The result keeps the name `computer` and the
59 * `execute` of the portable tool. Other tools come back unchanged.
60 *
61 * @param tool - A tool from the chat tool list.
62 * @param model - The model of the request.
63 */
64export function resolveComputerUseTool(tool: Tool, model: string): Tool {
65 const metadata = getComputerUseToolMetadata(tool)
66 if (!metadata) return tool
67 // Dated ids such as `computer-use-preview-2025-03-11` match too.
68 const isPreviewModel = model.startsWith('computer-use-preview')
69 const native = computerUseTool(
70 isPreviewModel
71 ? {
72 type: 'computer_use_preview',
73 display_width: metadata.display.width,
74 display_height: metadata.display.height,
75 environment: metadata.environment,
76 }
77 : { type: 'computer' },
78 )
79 return { ...native, name: 'computer', execute: tool.execute }
80}