
LangChain.js xAI 集成實戰ChatXAI 聊天模型與 Live Search 實時搜索工具完全指南【免費下載鏈接】langchainjsThe agent engineering platform項目地址: https://gitcode.com/GitHub_Trending/la/langchainjs本文以 LangChain.js 倉庫中的langchain/xai集成包libs/providers/langchain-xai為核心系統講解如何通過ChatXAI調用 xAI 的 Grok 系列模型并深入剖析其服務端工具Server Tool Calling機制——尤其是 Live Search 實時搜索的參數體系、數據源配置與覆蓋優先級。讀完本文你將掌握從環境配置、基礎對話到多數據源實時檢索、內置工具與自定義函數工具混用的完整實戰方案并能理解底層請求參數如何被組裝與發送。一、包概覽與安裝langchain/xai是 LangChain.js 生態中面向 xAI 平臺的官方集成包為 Grok 系列模型提供聊天模型Chat Model推理能力并封裝了 xAI 特有的服務端工具調用Server Tool Calling能力。包內核心導出由 src/index.ts 統一暴露ChatXAI系列聊天模型由chat_models模塊導出tools命名空間由tools模塊導出包含 xAI 內置工具工廠函數安裝依賴npm install langchain/xai langchain/core環境前提根據 package.json 的engines字段該包要求 Node.js 20langchain/xai以langchain/openaiworkspace 內依賴為底層實現基礎langchain/core^1.0.0作為 peer dependency。二、快速開始首個 ChatXAI 調用2.1 配置 API KeyxAI 的 API Key 可以通過環境變量注入也可以在構造函數中顯式傳入export XAI_API_KEYimport { ChatXAI } from langchain/xai; import { HumanMessage } from langchain/core/messages; const model new ChatXAI({ apiKey: process.env.XAI_API_KEY, // Default value. }); const message new HumanMessage(What color is the sky?); const res await model.invoke([message]);ChatXAI會優先讀取構造函數傳入的apiKey未傳入時默認使用process.env.XAI_API_KEY即上面導出的環境變量。這一點與 LangChain.js 其他模型提供方如ChatOpenAI的環境變量讀取約定保持一致。2.2 指定模型與流式輸出雖然 README 的基礎示例未顯式指定模型名但實際使用中通常需要傳入model參數例如 Grok 系列模型grok-3-fast。ChatXAI也支持 LangChain.js 標準的流式調用.stream、結構化輸出.withStructuredOutput等能力因為其底層直接復用langchain/openai的ChatOpenAICompletions實現可參考 completions.ts 中的類定義。2.3 底層實現要點從源碼看completions.tsChatXAI的請求參數類型擴展自 OpenAI 的ChatCompletionCreateParams額外加入了 xAI 專屬字段search_parametersexport type ChatXAICompletionsInvocationParams Omit OpenAIClient.Chat.Completions.ChatCompletionCreateParams, messages { search_parameters?: XAISearchParametersPayload; };此外xAI 模型返回的額外信息如思維鏈內容reasoning_content會被放入消息的additional_kwargs中類型定義同樣可在該文件確認。這意味著凡是 OpenAI 兼容的調用習慣tools、tool_choice、stream 等在ChatXAI上基本可以直接平移使用。三、Server Tool CallingLive Search 實時搜索3.1 什么是服務端工具xAI 支持服務端工具server-side tools這類工具由 xAI API 在服務端直接執行無需客戶端自行實現工具邏輯或二次調用。內置的live_search工具可以讓模型實時檢索網頁信息從而回答需要最新數據的問題如今天的科技新聞。3.2 使用內置 live_search 工具通過tools命名空間中的工廠函數xaiLiveSearch創建內置工具再通過bindTools綁定到模型import { ChatXAI, tools } from langchain/xai; const model new ChatXAI({ model: grok-3-fast, }); // Create the built-in live_search tool with optional parameters const searchTool tools.xaiLiveSearch({ maxSearchResults: 5, returnCitations: true, }); // Bind the live_search tool to the model const modelWithSearch model.bindTools([searchTool]); // The model will search the web for real-time information const result await modelWithSearch.invoke( What happened in tech news today? ); console.log(result.content);創建后的工具對象形如{ type: live_search_deprecated_20251215, name: live_search, ... }其類型常量XAI_LIVE_SEARCH_TOOL_TYPE與XAI_LIVE_SEARCH_TOOL_NAME定義于 tools/live_search.ts。?? 兼容性提示根據源碼中的類型注釋live_search使用的是 xAI 已棄用的 Live Search API 形態xAI 已于 2025-12-15 棄用官方推薦遷移到新的 agentic 工具調用 API即下文 3.7 節的xaiWebSearch與xaiXSearch。README 中的示例仍然可用但新項目建議優先考慮新式工具。3.3 通過 searchParameters 獲得更多控制除了綁定工具還可以在構造模型時直接配置searchParameters等效于設置請求中的search_parameters字段import { ChatXAI } from langchain/xai; const model new ChatXAI({ model: grok-3-fast, searchParameters: { mode: auto, // auto | on | off max_search_results: 5, from_date: 2024-01-01, // ISO date string return_citations: true, }, }); const result await model.invoke(What are the latest AI developments?);searchParameters的類型XAISearchParameters定義于 live_search.ts各字段語義如下字段類型默認值說明modeauto \| on \| offauto何時執行搜索auto由模型自行決定on每次都搜索off從不搜索max_search_resultsnumber20返回的最大搜索結果條數from_datestring無只包含該日期ISO 8601如2024-01-01之后的內容to_datestring無只包含該日期ISO 8601之前的內容return_citationsbooleantrue是否返回引用/來源信息sourcesXAISearchSource[]無指定使用的數據源web/news/x/rss省略時 xAI 默認啟用 web、news 和 x 三類來源其中mode是必選字段由buildSearchParametersPayload在組裝請求負載時兜底為auto詳見 live_search.ts 的負載構建函數。3.4 按請求覆蓋 searchParameters搜索參數可以做到一次配置、按需覆蓋——在每次invoke時傳入searchParameters即可臨時覆蓋實例級配置const result await model.invoke(Find recent news about SpaceX, { searchParameters: { mode: on, max_search_results: 10, sources: [ { type: web, allowed_websites: [spacex.com, nasa.gov], }, ], }, });3.5 配置數據源web / news / x / rss通過searchParameters.sources可以精細控制 Live Search 使用哪些數據源每種來源對應官方文檔中的一種類型web、news、x、rssconst result await model.invoke( What are the latest updates from xAI and related news?, { searchParameters: { mode: on, sources: [ { type: web, // Only search on these websites allowed_websites: [x.ai], }, { type: news, // Exclude specific news websites excluded_websites: [bbc.co.uk], }, { type: x, // Focus on specific X handles included_x_handles: [xai], }, ], }, } );各來源的可用字段源碼中XAISearchSource聯合類型見 live_search.tswebcountryISO alpha-2 國家代碼用于偏向某地區結果、allowed_websites僅檢索這些站點最多 5 個、excluded_websites排除這些站點最多 5 個、safe_search安全搜索開關newscountry、excluded_websites最多 5 個、safe_searchxincluded_x_handles限定檢索的 X 賬號最多 10 個、excluded_x_handles排除的 X 賬號最多 10 個、post_favorite_count帖子的最低點贊數、post_view_count帖子的最低瀏覽量rsslinksRSS 源地址列表也可以把 RSS 訂閱源作為數據源讓模型直接匯總某個 Feed 的最新內容const result await model.invoke(Summarize the latest posts from this feed, { searchParameters: { mode: on, sources: [ { type: rss, links: [https://example.com/feed.rss], }, ], }, });提示allowed_websites與excluded_websites不可同時用于同一來源allowed_x_handles與excluded_x_handles同理這是底層 API 的約束代碼注釋中已明確說明。3.6 camelCase 與 snake_case 的自動映射使用xaiLiveSearch工廠函數時TypeScript 側的工具選項采用camelCase命名它們會被自動映射為底層 JSON APIsearch_parameters對象中的snake_case字段名TypeScriptcamelCaseAPIsnake_casemaxSearchResultsmax_search_resultsfromDatefrom_datetoDateto_datereturnCitationsreturn_citationsallowedWebsitesallowed_websitesexcludedWebsitesexcluded_websitesincludedXHandlesincluded_x_handles該映射在 tools/live_search.ts 的xaiLiveSearch工廠與mapToolSourceToSearchSource函數中逐一完成——源碼對每個可選字段都做了! undefined判空未配置的字段不會出現在請求負載中。3.7 與自定義函數工具混用live_search內置工具可以與標準的 function calling 工具一起綁定實現實時搜索 業務函數調用的混合智能體import { ChatXAI, tools } from langchain/xai; const model new ChatXAI({ model: grok-3-fast }); const modelWithTools model.bindTools([ tools.xaiLiveSearch(), // Built-in server tool { // Custom function tool type: function, function: { name: get_stock_price, description: Get the current stock price, parameters: { type: object, properties: { symbol: { type: string }, }, required: [symbol], }, }, }, ]);底層實現發送請求前代碼會用filterXAIBuiltInTools將live_search這類內置工具從標準tools數組中剔除因為內置工具是通過search_parameters字段控制的不能作為普通 function tool 上報而普通函數工具則被保留并正常發送。該過濾邏輯與相關工具類型集合XAI_BUILT_IN_TOOL_TYPES均位于 completions.ts并有對應的單測覆蓋見 src/tests/live_search.test.ts。四、參數優先級tool instance call當工具定義、實例級searchParameters、單次調用覆蓋同時存在時合并策略由 live_search.ts 中的mergeSearchParams決定優先級從低到高為工具級參數如xaiLiveSearch中配置的選項實例級默認參數new ChatXAI({ searchParameters })單次調用參數invoke(msg, { searchParameters })export function mergeSearchParams( instanceParams?: XAISearchParameters, callParams?: XAISearchParameters, toolParams?: XAISearchParameters ): XAISearchParameters | undefined { return { ...(toolParams ?? {}), ...(instanceParams ?? {}), ...(callParams ?? {}), }; }即高層級參數按字段粒度覆蓋低層級參數、但不會清除低層級中未覆蓋的字段。這一點在 src/tests/live_search.test.ts 中有完整測試用例驗證例如實例級設置了mode: auto、調用級設置了mode: on時最終mode取on而實例級未被子級覆蓋的return_citations: true仍然保留。同時buildSearchParametersPayload負責把高層參數對象轉換為發送給 API 的最終負載mode缺省補auto其余字段僅在顯式配置時才寫入sources為空數組時不會發送。五、源碼視角更新一代的 agentic 內置工具README 主推的live_search屬于已棄用的 Live Search API 形態。從當前倉庫源碼看tools/index.tstools命名空間還導出了 4 個新式 agentic 工具工廠它們屬于 xAI agentic tool calling API由服務端執行適合作為長期方案工廠函數工具類型用途關鍵選項camelCasetools.xaiWebSearch()web_search網頁搜索與瀏覽支持圖片理解allowedDomains/excludedDomains各最多 5 個互斥、enableImageUnderstandingtools.xaiXSearch()x_searchX原 Twitter關鍵詞/語義/用戶搜索與帖子串抓取allowedXHandles/excludedXHandles各最多 10 個互斥、fromDate/toDate、enableImageUnderstanding、enableVideoUnderstandingtools.xaiCodeExecution()code_interpreter服務端沙箱執行 Python預裝 NumPy/Pandas/Matplotlib/SciPy用于計算、數據分析、財務建模無參數tools.xaiCollectionsSearch()file_search檢索上傳到 xAI Collections 的知識庫文檔適用于 RAG 與企業知識庫問答vectorStoreIdscollection ID 列表例如源碼中給出的遷移方式是把舊的xaiLiveSearch替換為兩個更聚焦的工具// Old (deprecated): const searchTool tools.xaiLiveSearch({ maxSearchResults: 5 }); // New (recommended): const webSearch tools.xaiWebSearch({ allowedDomains: [example.com] }); const xSearch tools.xaiXSearch({ allowedXHandles: [elonmusk] });這些工廠函數的實現與逐字段 camelCase→snake_case 映射可分別在 tools/web_search.ts、tools/x_search.ts、tools/code_execution.ts、tools/collections_search.ts 中查看且每個工具都配有獨立的單測目錄tools/tests/。六、本地開發與測試在倉庫中開發或調試langchain/xai包時官方流程如下6.1 安裝依賴pnpm install6.2 構建包pnpm build或從倉庫根目錄按包過濾構建pnpm build --filter langchain/xai構建實際執行的是tsdown編譯見 package.json 的build/build:compile腳本。6.3 運行測試測試文件應放在src/下的tests/目錄中。單元測試以.test.ts結尾集成測試以.int.test.ts結尾$ pnpm test $ pnpm test:int倉庫內測試覆蓋相當完整例如 src/tests/live_search.test.ts 覆蓋了參數合并優先級、負載構建與內置工具過濾chat_models/tests/下還有completions、responses、結構化輸出、流式事件等測試tools/tests/下則為每個內置工具live_search、web_search、x_search、code_execution、collections_search提供了獨立的測試文件。6.4 代碼規范提交代碼前運行 lint 與格式化pnpm lint pnpm format6.5 新增導出入口如果新增了需要導出的文件有兩種方式在 src/index.ts 中import并重新export將其加入 package.json 的exports字段然后運行pnpm build生成新的入口文件。七、小結langchain/xai提供了一條從基礎對話到實時信息檢索的完整鏈路ChatXAI負責與 Grok 系列模型對話tools.xaiLiveSearch/searchParameters負責讓模型獲取實時網頁信息sources支持 web、news、x、rss 四類數據源的精調而tool instance call的參數優先級讓默認配置 按需覆蓋成為可能。對于需要長期維護的新項目建議關注源碼中已提供的xaiWebSearch、xaiXSearch、xaiCodeExecution、xaiCollectionsSearch新一代 agentic 工具它們代表了 xAI 服務端工具能力的演進方向。【免費下載鏈接】langchainjsThe agent engineering platform項目地址: https://gitcode.com/GitHub_Trending/la/langchainjs創作聲明:本文部分內容由AI輔助生成(AIGC),僅供參考