← 返回首頁

Imperative API

用 JavaScript navigator.modelContext.registerTool() 動態註冊工具。 適合需要複雜邏輯、動態資料或非表單互動的情境。

Imperative API 的運作原理: 透過 JavaScript 的 navigator.modelContext.registerTool() 方法,你可以註冊任意數量的工具。 每個工具包含 name(名稱)、description(描述)、inputSchema(JSON Schema 格式的參數定義)和 execute(async callback,Agent 呼叫時執行)。

核心方法: registerTool(tool) 新增工具 | unregisterTool(name) 移除工具 | clearContext() 清除全部 | provideContext(options) 批次設定

基本用法

JavaScript
navigator.modelContext.registerTool({
  name: "add_todo",
  description: "Add a new todo item to the list",
  inputSchema: {
    type: "object",
    properties: {
      text: {
        type: "string",
        description: "The todo item text"
      }
    },
    required: ["text"]
  },
  execute: async ({ text }) => {
    // 你的實作邏輯
    todos.push({ text, done: false });
    return {
      content: [{
        type: "text",
        text: JSON.stringify({ success: true })
      }]
    };
  }
});

工具註冊狀態

偵測中...

待辦事項 App

工具: add_todo, list_todos, complete_todo, delete_todo

Agent 可以透過上述 4 個工具管理待辦事項。試試在 DevTools Console 呼叫它們。

計算機

工具: calculate

Agent 可以透過 calculate 工具進行數學運算。 支援基本運算(+, -, *, /)和括號。

天氣查詢(模擬)

工具: get_weather

模擬天氣 API。預設城市:Taipei、Tokyo、New York、London、San Francisco。 其他城市會隨機產生天氣資料。

工具呼叫日誌

等待工具呼叫...