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

server-tools.ts

152 lines4.8 KB

1/**
2 * Provider-hosted tool type ids (issue #123). A page that does not name a
3 * type id for a model contributes nothing. Grok (`grok.ts`) and BytePlus
4 * MCP (`byteplus-tools.ts`) are read beside their adapters; OpenRouter ids
5 * are router-level and are not parsed.
6 */
7import { tagDocsFacts } from './fact-sources.ts'
8import { assertParsed, cachedDocs, markdownTableRows } from './model-facts.ts'
9import { fetchText, sha256Text } from './types.ts'
10import type { ModelInfo } from './types.ts'
11​
12export const GROQ_BUILTIN_TOOLS_URL =
13 'https://console.groq.com/docs/tool-use/built-in-tools.md'
14​
15type HostedFacts = Pick<ModelInfo, 'serverTools' | 'factSources'>
16​
17function unescapeDocs(markdown: string): string {
18 return markdown.replace(/\\([_`])/g, '$1')
20​
21/**
22 * Built-in tools page: each `###` section names model ids in bullets and
23 * tool type ids in an Identifier column. Sections that name neither stay
24 * out of the map.
25 */
26export function parseGroqBuiltinTools(
27 markdown: string,
28): Map<string, Array<string>> {
29 const out = new Map<string, Array<string>>()
30 const text = unescapeDocs(markdown)
31 for (const section of text.split(/\n### /).slice(1)) {
32 const rows = markdownTableRows(section)
33 const header = rows.find((row) =>
34 row.some((cell) => /^identifier$/i.test(cell)),
35 )
36 const column = header?.findIndex((cell) => /^identifier$/i.test(cell)) ?? -1
37 if (!header || column < 0) continue
38 const tools = [
39 ...new Set(
40 rows
41 .filter((row) => row !== header)
42 .flatMap((row) => {
43 const id = row[column]?.trim() ?? ''
44 return /^[a-z][a-z0-9_]*$/.test(id) ? [id] : []
45 }),
46 ),
47 ]
48 if (tools.length === 0) continue
49 const toolSet = new Set(tools)
50 for (const match of section.matchAll(/^[*+-]\s+`([^`]+)`/gm)) {
51 const id = match[1]?.trim() ?? ''
52 if (id.length === 0 || toolSet.has(id) || id.startsWith('http')) continue
53 out.set(id, tools)
54 }
55 }
56 return out
58​
59/**
60 * Lookup from the built-in tools page. A fetch or empty parse throws so the
61 * poll keeps stored tools. The page is not exhaustive (the browser search
62 * page names `openai/gpt-oss-safeguard-20b`, this one does not), so a model
63 * it does not name states nothing (#707).
64 */
65export async function groqModelServerTools(
66 kv?: KVNamespace,
67): Promise<(rawId: string) => HostedFacts> {
68 const doc = await cachedDocs(kv, GROQ_BUILTIN_TOOLS_URL, async () => {
69 const markdown = await fetchText(GROQ_BUILTIN_TOOLS_URL)
70 const parsed = parseGroqBuiltinTools(markdown)
71 assertParsed(parsed, 'groq built-in tools')
72 return {
73 tools: Object.fromEntries(parsed),
74 hash: await sha256Text(markdown),
75 }
76 })
77 return (rawId) => {
78 const tools = doc.tools[rawId]
79 if (!tools || tools.length === 0) return {}
80 return {
81 serverTools: tools,
82 factSources: tagDocsFacts(
83 { serverTools: tools },
84 GROQ_BUILTIN_TOOLS_URL,
85 doc.hash,
86 ),
87 }
88 }
90​
91const CLIENT_TOOL = 'function'
92​
93/**
94 * Tool type ids a Mistral model page names under Supported tools or
95 * Built-in tools. `function` is a client tool. Nav and scripts are not
96 * the model page.
97 */
98export function parseMistralPageTools(html: string): Array<string> {
99 const text = html
100 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
101 .replace(/<style[\s\S]*?<\/style>/gi, ' ')
102 .replace(/<code>([^<]+)<\/code>/gi, '`$1`')
103 .replace(/<[^>]+>/g, ' ')
104 const start = text.search(/supported tools|built-in tools/i)
105 if (start < 0) return []
106 const section = text.slice(start, start + 2500)
107 const ids = [
108 ...section.matchAll(/`([a-z][a-z0-9_]*)`/g),
109 ...section.matchAll(/"type"\s*:\s*"([a-z][a-z0-9_]*)"/g),
110 ].flatMap((match) => {
111 const id = match[1] ?? ''
112 return id.length > 0 && id !== CLIENT_TOOL ? [id] : []
113 })
114 return [...new Set(ids)]
116​
117/**
118 * Ark docs: a `##` section that names catalog ids and a `tools` entry's
119 * `type` assigns those ids. A section that only says a capability is not
120 * supported does not.
121 */
122export function parseByteplusServerTools(
123 doc: string,
124): Map<string, Array<string>> {
125 const out = new Map<string, Array<string>>()
126 const text = doc.replace(/\\n/g, '\n').replace(/\\"/g, '"')
127 for (const section of text.split(/\n## /).slice(1)) {
128 if (
129 /not currently supported/i.test(section) &&
130 !/"type"\s*:/.test(section)
131 ) {
132 continue
133 }
134 const tools = [
135 ...new Set(
136 [
137 ...section.matchAll(
138 /tools[\s\S]{0,400}?"type"\s*:\s*"([a-z][a-z0-9_]*)"/g,
139 ),
140 ].flatMap((match) => (match[1] ? [match[1]] : [])),
141 ),
142 ]
143 if (tools.length === 0) continue
144 for (const match of section.matchAll(
145 /`([a-z0-9][a-z0-9.-]*\d[a-z0-9.-]*)`/g,
146 )) {
147 const id = match[1]
148 if (id) out.set(id, tools)
149 }
150 }
151 return out