前情提要
為什麼我明明就有設定要使用web search tool,但查詢出來的結果就是舊的資料呢?
在使用ai api很常會使用到的tool有兩個,一個是web search,另一個是structured outputs,也就是將你的結果變成程式看得懂的格式,讓程式比較好處理
舉例來說,我是一個加密貨幣的平台,我希望可以顯示跟比特幣相關的新聞,讓使用者可以瀏覽.這時我可以使用ai api,請他幫我取得最新10筆有關比特幣的文章,且幫我轉成我指定的json格式,這樣前端就可以直接拿來使用了
node.js example code如下
const message = await anthropic.messages.create({
model: "claude-sonnet-3",
max_tokens: 4096,
messages: [
{
role: "user",
content: "give me the latest 10 news about bitcoins",
},
],
tools: [
{
type: "web_search_20250305",
name: "web_search",
max_uses: 5,
},
{
name: "article_format",
description:
"Provide the article info with url and title",
input_schema: {
type: "object",
properties: {
url: {
type: "string",
description:"The article resource url",
},
title: {
type: "string",
description:"The article title",
}
},
required: ["url", "title"],
},
},
],
tool_choice: {
type: "tool",
name: "article_format",
},
temperature: 0.3,
});
問題說明
我希望ai回傳的資料一定要是特定的資料結構,所以我設定了tool_choice來確article_format他一定會執行,的確資料都有正確被format,但問題來了,結果web search沒反應了,該怎麼辦?
源自於tool_choice的設定每一家都不太一樣,以anthropic來說 [官方文件]
tool_choice = {"type": "tool", "name": "get_weather"}
tool_choice有四種選項
- auto: 這是預設值,由claude自行決定要使用哪些提供的工具
- any: 強制claude必須至少使用其中一種工具,但不能強制使用特定工具
- tool: 強制claude必須使用特定的工具,但只能指定一個,不能指定多個
- none: 阻止claude使用任何工具,當未tools提供時,這是預設值
重點在於,如果使用tool的話,你的確一定會使用到特定工具,但他就只會使用那個工具,其他都不會使用了.所以造成web search的工具沒有被使用到的問題
解決方法
如果希望多個tool被使用的話,可以使用type=any,並且在prompt中明確的表達需要使用web search工具查詢最新資料,以及使用工具來產生怎麼樣格式的資料,這樣就能解決這個問題了!
tool_choice = {"type": "any"}