為什么使用百度AI搜索
學習langchain的過程中,遇到使用search api的時候,發現langchain官方文檔中支持的搜索工具大多是國外的,例如google search或bing search,收費不說,很多還連接不上(工具 | LangChain中文網)。
經過一番尋找,發現國內也有兩家提供search api,一個是博查(博查AI開放平臺 | Search API, Reranker API),另一個就是最近剛出的百度AI搜索(百度AI搜索 - 千帆AppBuilder-產品文檔)。
博查是收費的,而百度AI搜索每天有100次的免費額度,更加適合個人學習使用。
使用方式
百度AI搜索支持post請求,OpenAI SDK,Cursor MCP組件等多種方式調用,今天主要講一下在langchain中如何使用。
第一步首先需要申請一個API KEY
通過langchain-openai直接調用
from langchain_openai import ChatOpenAIclient = ChatOpenAI(model="deepseek-r1", api_key=API_KEY, #申請的百度API KEYbase_url="https://qianfan.baidubce.com/v2/ai_search"
)response = client.invoke("今天成都天氣怎么樣")print(response)
直接調用有許多參數不支持,如果希望能夠自由設置例如最大返回數量,檢索條件等參數,可以使用工具,具體參數可以查看百度AI搜索 - 千帆AppBuilder-產品文檔
自定義langchain工具
import requests
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import tool
from langchain_qwq import ChatQwQ@tool
def baidu_search_tool(query: str) -> str:"""使用Baidu Search API進行聯網搜索,返回搜索結果的字符串。參數:- query: 搜索關鍵詞返回:- 搜索結果的字符串形式"""url = 'https://qianfan.baidubce.com/v2/ai_search'headers = {'Authorization': f'Bearer {API_KEY}', # 請替換為你的API密鑰'Content-Type': 'application/json'}messages = [{"content": query,"role": "user"}]data = {"messages": messages,"search_source": "baidu_search_v2","search_recency_filter":"month" #可以自定義各種檢索條件}response = requests.post(url, headers=headers, json=data)if response.status_code == 200:# 返回給大模型的格式化的搜索結果文本# 可以自己對博查的搜索結果進行自定義處理return str(response.json())else:raise Exception(f"API請求失敗,狀態碼: {response.status_code}, 錯誤信息: {response.text}")#打印工具名稱,描述,參數等 名稱正確、文檔正確且類型提示正確的工具更易于模型使用
print(baidu_search_tool.name)
print(baidu_search_tool.description)
print(baidu_search_tool.args)#直接使用工具
print(baidu_search_tool.invoke("介紹下langchain"))tools = [baidu_search_tool]#通義千問大模型,可以替換為任何一個支持工具調用的大模型
tongyi_chat = ChatQwQ(model="qwen-plus",api_key=QWEN_KEY, #替換為對應大模型的KEYapi_base="https://dashscope.aliyuncs.com/compatible-mode/v1"
)#查看我們的輸入是否會調用工具,注意,這里并不會真正調用工具
with_tool = tongyi_chat.bind_tools(tools)
result = with_tool.invoke("今天成都天氣怎么樣")
print(result.content)
print(result.tool_calls)#創建代理并調用工具
prompt = ChatPromptTemplate.from_template("今天{city}天氣怎么樣 {agent_scratchpad}")
agent = create_tool_calling_agent(tongyi_chat, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)
print(agent_executor.invoke({"city":"成都", "agent_scratchpad":"intermediate_steps"}))