Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

computer-use-tool.ts

83 lines2.7 KB

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/** @deprecated Renamed to `ComputerUseToolConfig`. Will be removed in a future release. */
19export type ComputerUseTool = ComputerUseToolConfig
20​
21/**
22 * Converts a standard Tool to OpenAI ComputerUseTool format
23 */
24export function convertComputerUseToolToAdapterFormat(
25 tool: Tool,
26): ComputerUseToolConfig {
27 const metadata = getOpenAIProviderToolMetadata(tool) as ComputerUseToolConfig
28 if (metadata.type === 'computer') return { type: 'computer' }
29 return {
30 type: 'computer_use_preview',
31 display_height: metadata.display_height,
32 display_width: metadata.display_width,
33 environment: metadata.environment,
34 }
36​
37/**
38 * Creates a standard Tool from ComputerUseTool parameters. The tool name is
39 * the tool type: `computer` or `computer_use_preview`.
40 *
41 * Base (non-branded) factory. Providers that need branded return types should
42 * re-wrap this in their own package.
43 */
44export function computerUseTool(toolData: ComputerUseToolConfig): Tool {
45 return openAIProviderTool(
46 {
47 name: toolData.type,
48 description: 'Control a virtual computer',
49 metadata: {
50 ...toolData,
51 },
52 },
53 'computer_use',
54 )
56​
57/**
58 * Swaps a portable computer-use tool for the native OpenAI computer tool of
59 * the model. The `computer-use-preview` models get `computer_use_preview`
60 * with the display and environment of the tool. Other models get
61 * `{ type: 'computer' }`. The result keeps the name `computer` and the
62 * `execute` of the portable tool. Other tools come back unchanged.
63 *
64 * @param tool - A tool from the chat tool list.
65 * @param model - The model of the request.
66 */
67export function resolveComputerUseTool(tool: Tool, model: string): Tool {
68 const metadata = getComputerUseToolMetadata(tool)
69 if (!metadata) return tool
70 // Dated ids such as `computer-use-preview-2025-03-11` match too.
71 const isPreviewModel = model.startsWith('computer-use-preview')
72 const native = computerUseTool(
73 isPreviewModel
74 ? {
75 type: 'computer_use_preview',
76 display_width: metadata.display.width,
77 display_height: metadata.display.height,
78 environment: metadata.environment,
79 }
80 : { type: 'computer' },
81 )
82 return { ...native, name: 'computer', execute: tool.execute }