studio / src /components /panels /ToolsPanel.jsx
cheumk's picture
Upload 32 files
4e039c5 verified
Raw History Blame Contribute Delete
7.51 kB
import { useState } from 'react'
import { Plus, Trash2, Play, Loader2, Save } from 'lucide-react'
import { useStore, useActiveProject } from '../../store/useStore'
import { BUILTIN_TOOLS, executeToolCall, resolveTools } from '../../lib/tools'
import { Btn, Field, Section, inputCls } from '../ui'
const SAMPLE_ARGS = {
web_search: { query: '大型語言模型' },
wikipedia_article: { title: 'Taipei', lang: 'en' },
fetch_url: { url: 'https://example.com' },
get_weather: { city: 'Taipei', days: 2 },
currency_convert: { amount: 100, from: 'USD', to: 'TWD' },
calculate: { expression: '(2+3)^2 * sqrt(16)' },
get_current_time: { timezone: 'Asia/Taipei' },
search_github: { query: 'llm agent', limit: 3 },
search_hackernews: { query: 'LLM', recent: true },
search_papers: { query: 'retrieval augmented generation' },
search_books: { query: '三體' },
save_note: { title: '測試筆記', content: '由工具測試寫入' },
read_notes: {},
}
function Tester({ name, defaultArgs }) {
const project = useActiveProject()
const customTools = useStore((s) => s.customTools)
const [args, setArgs] = useState(JSON.stringify(defaultArgs || {}, null, 0))
const [out, setOut] = useState('')
const [busy, setBusy] = useState(false)
const run = async () => {
setBusy(true); setOut('')
const st = useStore.getState()
const tools = resolveTools([name], customTools)
const res = await executeToolCall(
{ function: { name, arguments: args } },
tools,
{ settings: st.settings, project, addNote: st.addNote, signal: undefined },
)
setOut(res); setBusy(false)
}
return (
<div className="space-y-2">
<div className="flex gap-2">
<input className={`${inputCls} font-mono text-xs`} value={args} onChange={(e) => setArgs(e.target.value)} />
<Btn onClick={run} disabled={busy} title="測試執行">{busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}</Btn>
</div>
{out && <pre className="text-[11px] whitespace-pre-wrap break-words bg-app rounded p-2 max-h-60 overflow-y-auto">{out}</pre>}
</div>
)
}
const EMPTY = { name: '', description: '', method: 'GET', endpoint: '', headers: '', parameters: '{"type":"object","properties":{"q":{"type":"string","description":"查詢字串"}},"required":["q"]}' }
function CustomToolForm({ initial, onDone }) {
const [d, setD] = useState(initial ? { ...initial, parameters: JSON.stringify(initial.parameters, null, 2) } : EMPTY)
const [err, setErr] = useState('')
const save = () => {
const name = d.name.trim()
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(name)) return setErr('名稱只能用英數字、底線、連字號')
if (!initial && [...BUILTIN_TOOLS, ...useStore.getState().customTools].some((t) => t.name === name)) return setErr('名稱重複')
let parameters
try { parameters = JSON.parse(d.parameters || '{}') } catch { return setErr('parameters 不是合法 JSON') }
if (d.headers?.trim()) { try { JSON.parse(d.headers) } catch { return setErr('headers 不是合法 JSON') } }
useStore.getState().saveCustomTool({ ...d, name, parameters })
onDone()
}
return (
<div className="space-y-2 bg-field rounded-lg p-3">
<input className={inputCls} placeholder="name,例如 get_joke" value={d.name} disabled={!!initial} onChange={(e) => setD({ ...d, name: e.target.value })} />
<input className={inputCls} placeholder="description(模型靠它決定何時呼叫)" value={d.description} onChange={(e) => setD({ ...d, description: e.target.value })} />
<div className="flex gap-2">
<select className={`${inputCls} w-24`} value={d.method} onChange={(e) => setD({ ...d, method: e.target.value })}>
<option>GET</option><option>POST</option><option>PUT</option>
</select>
<input className={inputCls} placeholder="https://api.example.com/x?q={q}" value={d.endpoint} onChange={(e) => setD({ ...d, endpoint: e.target.value })} />
</div>
<Field hint="{參數名} 會替換成參數值;POST/PUT 會把全部參數以 JSON body 送出。目標 API 必須允許 CORS。">
<textarea className={`${inputCls} font-mono text-[11px]`} rows={4} placeholder="parameters(JSON Schema)" value={d.parameters} onChange={(e) => setD({ ...d, parameters: e.target.value })} />
</Field>
<input className={`${inputCls} font-mono text-[11px]`} placeholder='headers(選填 JSON),例如 {"X-Api-Key":"..."}' value={d.headers} onChange={(e) => setD({ ...d, headers: e.target.value })} />
{err && <p className="text-xs text-red-400">{err}</p>}
<div className="flex gap-2">
<Btn variant="primary" className="flex-1" onClick={save}><Save className="w-4 h-4" /> 儲存</Btn>
<Btn onClick={onDone}>取消</Btn>
</div>
</div>
)
}
export default function ToolsPanel() {
const customTools = useStore((s) => s.customTools)
const [form, setForm] = useState(null) // null | 'new' | tool
return (
<div>
<Section title={`內建工具(${BUILTIN_TOOLS.length})`}>
<p className="text-[11px] text-muted">全部是真的,直接從瀏覽器呼叫公開 API。展開可測試。要給哪個 Agent 用,到「Agent」頁勾選。</p>
<div className="space-y-1.5">
{BUILTIN_TOOLS.map((t) => (
<details key={t.name} className="bg-field rounded-lg">
<summary className="cursor-pointer px-3 py-2 text-sm">
<span className="font-medium">{t.label}</span> <span className="text-[11px] text-muted font-mono">{t.name}</span>
</summary>
<div className="px-3 pb-3 space-y-2">
<p className="text-[11px] text-muted">{t.description}</p>
<Tester name={t.name} defaultArgs={SAMPLE_ARGS[t.name]} />
</div>
</details>
))}
</div>
</Section>
<Section title={`自訂 HTTP 工具(${customTools.length})`}>
<p className="text-[11px] text-muted">設定 endpoint 就能真的執行:把任何允許 CORS 的 API 變成 Agent 工具。</p>
{customTools.map((t) => (
form?.name === t.name ? <CustomToolForm key={t.name} initial={t} onDone={() => setForm(null)} /> : (
<details key={t.name} className="bg-field rounded-lg">
<summary className="cursor-pointer px-3 py-2 text-sm flex items-center gap-2">
<span className="flex-1 font-mono truncate">{t.name}</span>
<button type="button" className="text-[11px] text-muted hover:text-ink" onClick={(e) => { e.preventDefault(); setForm(t) }}>編輯</button>
<button type="button" className="text-muted hover:text-red-500" onClick={(e) => { e.preventDefault(); confirm(`刪除工具 ${t.name}?`) && useStore.getState().removeCustomTool(t.name) }}><Trash2 className="w-3.5 h-3.5" /></button>
</summary>
<div className="px-3 pb-3 space-y-2">
<p className="text-[11px] text-muted">{t.description} · {t.method} {t.endpoint || '(未設定 endpoint)'}</p>
<Tester name={t.name} defaultArgs={{}} />
</div>
</details>
)
))}
{form === 'new' ? <CustomToolForm onDone={() => setForm(null)} /> : (
<Btn className="w-full" onClick={() => setForm('new')}><Plus className="w-4 h-4" /> 新增自訂工具</Btn>
)}
</Section>
</div>
)
}