This package contains the LangChain.js integrations for xAI.
npm install @langchain/xai @langchain/core
This package adds support for xAI chat model inference.
Set the necessary environment variable (or pass it in via the constructor):
export XAI_API_KEY=
import { 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]);
xAI supports server-side tools that are executed by the API rather than requiring client-side execution. The live_search tool enables the model to search the web for real-time information.
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);
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?");
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"],
},
],
},
});
sourcesYou can configure which data sources Live Search should use via the sources field
in searchParameters. Each entry corresponds to one of the sources described in the
official xAI Live Search docs (web, news, x, rss).
const 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"],
},
],
},
}
);
You can also use RSS feeds as a data source:
const result = await model.invoke("Summarize the latest posts from this feed", {
searchParameters: {
mode: "on",
sources: [
{
type: "rss",
links: ["https://example.com/feed.rss"],
},
],
},
});
Notes:
- The
xaiLiveSearchtool options use camelCase field names in TypeScript (for examplemaxSearchResults,fromDate,returnCitations,allowedWebsites,excludedWebsites,includedXHandles). These are automatically mapped to the underlying JSON API'ssearch_parametersobject, which usessnake_casefield names as documented in the official xAI Live Search docs.
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"],
},
},
},
]);
To develop the @langchain/xai package, you'll need to follow these instructions:
pnpm install
pnpm build
Or from the repo root:
pnpm build --filter @langchain/xai
Test files should live within a tests/ file in the src/ folder. Unit tests should end in .test.ts and integration tests should
end in .int.test.ts:
$ pnpm test
$ pnpm test:int
Run the linter & formatter to ensure your code is up to standard:
pnpm lint && pnpm format
If you add a new file to be exported, either import & re-export from src/index.ts, or add it to the exports field in the package.json file and run pnpm build to generate the new entrypoint.
Call options for ChatXAIResponses.
Input configuration for ChatXAIResponses constructor.
xAI-specific additional kwargs that may be present on AI messages.
xAI Responses API response body.
xAI-specific response metadata that may include usage information.
Code interpreter result item.
Code interpreter tool definition.
Code interpreter tool call from a previous response.
xAI Responses API request body parameters.
Non-streaming variant of the request params.
Streaming variant of the request params.
Debug output information (when available).
File citation annotation.
File search result item.
File search tool definition.
Function tool definition.
Function tool call from a previous response.
Function tool parameters using JSON Schema.
Function tool call output to provide results back to the model.
Details about why a response is incomplete.
File input content item.
Image input content item.
Text input content item.
Log probability content item.
Log probabilities from a previous response.
Log probability information for a token.
MCP (Model Context Protocol) tool definition.
MCP tool call from a previous response.
Message input to the model.
Code interpreter call output item.
File search call output item.
Function call output item.
MCP call output item.
Reasoning output item.
Refusal content in an output message.
Text content in an output message.
Text output item in the response.
Web search call output item.
Previous response structure that can be included in the input array.
Reasoning configuration for reasoning models.
Reasoning configuration echoed in the response.
Reasoning summary item.
Search parameters configuration.
RSS/News search source configuration.
Web search source configuration.
X (Twitter) search source configuration.
Base streaming event structure.
Response completed event.
Content part added event.
Content part done event.
Response created event.
Error event.
Response failed event.
Function call arguments delta event.
Function call arguments done event.
Response incomplete event.
Response in progress event.
Output item added event.
Output item done event.
Reasoning summary text delta event.
Reasoning summary text done event.
Text delta event (streaming text).
Text done event.
Text response configuration.
JSON object format.
JSON schema format.
Plain text format.
Function tool choice object.
Citation annotation for web search results.
Token usage information for the response.
Web search tool definition.
Web search tool call from a previous response.
X search tool definition.
xAI-specific invocation parameters that extend the OpenAI completion params
Invocation parameters for ChatXAIResponses (request params without input).
Union type for all xAI built-in server-side tools.
Union type for all annotation types.
Additional output data to include in the response.
Reason for incomplete response.
Input type - can be a string or array of input items.
Union type for all input content items.
Union type for all items that can appear in the input array.
Message role types.
Response object type literal.
Union type for output content items.
Union type for all response output items.
Reasoning effort level.
Reasoning summary style.
Search mode options.
Union type for all search sources.
Response status values.
Union type for all streaming events.
Union type for all text response formats.
Union type for all tool definitions.
Union type for all tool calls from previous responses.
Tool choice configuration.
String tool choice options.
Union type for tool outputs that can be included in input.