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

server-tools.ts

147 lines4.6 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 and OpenRouter are not
4 * parsed here: xAI publishes no per-model list, and OpenRouter ids are
5 * router-level.
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/** Lookup from the built-in tools page. A fetch or empty parse throws so the poll keeps stored tools. */
60export async function groqModelServerTools(
61 kv?: KVNamespace,
62): Promise<(rawId: string) => HostedFacts> {
63 const doc = await cachedDocs(kv, GROQ_BUILTIN_TOOLS_URL, async () => {
64 const markdown = await fetchText(GROQ_BUILTIN_TOOLS_URL)
65 const parsed = parseGroqBuiltinTools(markdown)
66 assertParsed(parsed, 'groq built-in tools')
67 return {
68 tools: Object.fromEntries(parsed),
69 hash: await sha256Text(markdown),
70 }
71 })
72 return (rawId) => {
73 const tools = doc.tools[rawId]
74 if (!tools || tools.length === 0) return {}
75 return {
76 serverTools: tools,
77 factSources: tagDocsFacts(
78 { serverTools: tools },
79 GROQ_BUILTIN_TOOLS_URL,
80 doc.hash,
81 ),
82 }
83 }
85​
86const CLIENT_TOOL = 'function'
87​
88/**
89 * Tool type ids a Mistral model page names under Supported tools or
90 * Built-in tools. `function` is a client tool. Nav and scripts are not
91 * the model page.
92 */
93export function parseMistralPageTools(html: string): Array<string> {
94 const text = html
95 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
96 .replace(/<style[\s\S]*?<\/style>/gi, ' ')
97 .replace(/<code>([^<]+)<\/code>/gi, '`$1`')
98 .replace(/<[^>]+>/g, ' ')
99 const start = text.search(/supported tools|built-in tools/i)
100 if (start < 0) return []
101 const section = text.slice(start, start + 2500)
102 const ids = [
103 ...section.matchAll(/`([a-z][a-z0-9_]*)`/g),
104 ...section.matchAll(/"type"\s*:\s*"([a-z][a-z0-9_]*)"/g),
105 ].flatMap((match) => {
106 const id = match[1] ?? ''
107 return id.length > 0 && id !== CLIENT_TOOL ? [id] : []
108 })
109 return [...new Set(ids)]
111​
112/**
113 * Ark docs: a `##` section that names catalog ids and a `tools` entry's
114 * `type` assigns those ids. A section that only says a capability is not
115 * supported does not.
116 */
117export function parseByteplusServerTools(
118 doc: string,
119): Map<string, Array<string>> {
120 const out = new Map<string, Array<string>>()
121 const text = doc.replace(/\\n/g, '\n').replace(/\\"/g, '"')
122 for (const section of text.split(/\n## /).slice(1)) {
123 if (
124 /not currently supported/i.test(section) &&
125 !/"type"\s*:/.test(section)
126 ) {
127 continue
128 }
129 const tools = [
130 ...new Set(
131 [
132 ...section.matchAll(
133 /tools[\s\S]{0,400}?"type"\s*:\s*"([a-z][a-z0-9_]*)"/g,
134 ),
135 ].flatMap((match) => (match[1] ? [match[1]] : [])),
136 ),
137 ]
138 if (tools.length === 0) continue
139 for (const match of section.matchAll(
140 /`([a-z0-9][a-z0-9.-]*\d[a-z0-9.-]*)`/g,
141 )) {
142 const id = match[1]
143 if (id) out.set(id, tools)
144 }
145 }
146 return out