{"version":3,"file":"completions.cjs","names":["XAI_LIVE_SEARCH_TOOL_TYPE","ChatOpenAICompletions","mergeSearchParams","buildSearchParametersPayload","filterXAIBuiltInTools","PROFILES"],"sources":["../../src/chat_models/completions.ts"],"sourcesContent":["import { BaseLanguageModelInput } from \"@langchain/core/language_models/base\";\nimport {\n  BaseChatModelCallOptions,\n  BindToolsInput,\n  LangSmithParams,\n  type BaseChatModelParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n  isLangChainTool,\n  convertToOpenAITool,\n} from \"@langchain/core/utils/function_calling\";\nimport { ModelProfile } from \"@langchain/core/language_models/profile\";\nimport { Serialized } from \"@langchain/core/load/serializable\";\nimport { AIMessageChunk, type UsageMetadata } from \"@langchain/core/messages\";\nimport { Runnable } from \"@langchain/core/runnables\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport {\n  type OpenAICoreRequestOptions,\n  type OpenAIClient,\n  ChatOpenAICompletions,\n} from \"@langchain/openai\";\nimport {\n  buildSearchParametersPayload,\n  filterXAIBuiltInTools,\n  mergeSearchParams,\n  type XAISearchParameters,\n  type XAISearchParametersPayload,\n} from \"../live_search.js\";\nimport PROFILES from \"../profiles.js\";\nimport {\n  XAI_LIVE_SEARCH_TOOL_TYPE,\n  XAILiveSearchTool,\n} from \"../tools/live_search.js\";\n\nexport type OpenAIToolChoice =\n  | OpenAIClient.ChatCompletionToolChoiceOption\n  | \"any\"\n  | string;\n\n/**\n * Union type for all xAI built-in server-side tools.\n */\nexport type XAIBuiltInTool = XAILiveSearchTool;\n\n/**\n * Set of all supported xAI built-in server-side tool types.\n * This allows us to easily extend support for future built-in tools\n * without changing the core detection logic.\n */\nconst XAI_BUILT_IN_TOOL_TYPES = new Set<XAILiveSearchTool[\"type\"] | string>([\n  XAI_LIVE_SEARCH_TOOL_TYPE,\n]);\n\n/**\n * Tool type that includes both standard tools and xAI built-in tools.\n */\ntype ChatXAIToolType =\n  | BindToolsInput\n  | OpenAIClient.ChatCompletionTool\n  | XAIBuiltInTool;\n\n/**\n * xAI-specific invocation parameters that extend the OpenAI completion params\n * with xAI's search_parameters field.\n */\nexport type ChatXAICompletionsInvocationParams = Omit<\n  OpenAIClient.Chat.Completions.ChatCompletionCreateParams,\n  \"messages\"\n> & {\n  /**\n   * Search parameters for xAI's Live Search API.\n   * When present, enables the model to search the web for real-time information.\n   */\n  search_parameters?: XAISearchParametersPayload;\n};\n\n/**\n * xAI-specific additional kwargs that may be present on AI messages.\n * Includes xAI-specific fields like reasoning_content.\n */\nexport interface XAIAdditionalKwargs {\n  /**\n   * The reasoning content from xAI models that support chain-of-thought reasoning.\n   * This contains the model's internal reasoning process.\n   */\n  reasoning_content?: string;\n  /**\n   * Tool calls made by the model.\n   */\n  tool_calls?: OpenAIClient.ChatCompletionMessageToolCall[];\n  /**\n   * Additional properties that may be present.\n   */\n  [key: string]: unknown;\n}\n\n/**\n * xAI-specific response metadata that may include usage information.\n */\nexport interface XAIResponseMetadata {\n  /**\n   * Token usage information.\n   */\n  usage?: UsageMetadata;\n  /**\n   * Additional metadata properties.\n   */\n  [key: string]: unknown;\n}\n\n/**\n * Checks if a tool is an xAI built-in tool (like live_search).\n * Built-in tools are executed server-side by the xAI API.\n *\n * @param tool - The tool to check\n * @returns true if the tool is an xAI built-in tool\n */\nexport function isXAIBuiltInTool(\n  tool: ChatXAIToolType\n): tool is XAIBuiltInTool {\n  return (\n    typeof tool === \"object\" &&\n    tool !== null &&\n    \"type\" in tool &&\n    typeof (tool as { type?: unknown }).type === \"string\" &&\n    XAI_BUILT_IN_TOOL_TYPES.has((tool as { type: string }).type)\n  );\n}\n\nexport interface ChatXAICallOptions extends BaseChatModelCallOptions {\n  headers?: Record<string, string>;\n  /**\n   * A list of tools the model may call.\n   * Can include standard function tools and xAI built-in tools like `{ type: \"live_search\" }`.\n   *\n   * @example\n   * ```typescript\n   * // Using built-in live_search tool\n   * const llm = new ChatXAI().bindTools([{ type: \"live_search\" }]);\n   * const result = await llm.invoke(\"What happened in tech news today?\");\n   * ```\n   */\n  tools?: ChatXAIToolType[];\n  tool_choice?: OpenAIToolChoice | string | \"auto\" | \"any\";\n  /**\n   * Search parameters for xAI's Live Search API.\n   * Enables the model to search the web for real-time information.\n   *\n   * @note This is an alternative to using `tools: [{ type: \"live_search\" }]`.\n   * The Live Search API parameters approach may be deprecated in favor of\n   * the tool-based approach.\n   *\n   * @example\n   * ```typescript\n   * const result = await llm.invoke(\"What's the latest news?\", {\n   *   searchParameters: {\n   *     mode: \"auto\",\n   *     max_search_results: 5,\n   *   }\n   * });\n   * ```\n   */\n  searchParameters?: XAISearchParameters;\n}\n\nexport interface ChatXAIInput extends BaseChatModelParams {\n  /**\n   * The xAI API key to use for requests.\n   * @default process.env.XAI_API_KEY\n   */\n  apiKey?: string;\n  /**\n   * The name of the model to use.\n   * @default \"grok-3-fast\"\n   */\n  model?: string;\n  /**\n   * Up to 4 sequences where the API will stop generating further tokens. The\n   * returned text will not contain the stop sequence.\n   * Alias for `stopSequences`\n   */\n  stop?: Array<string>;\n  /**\n   * Up to 4 sequences where the API will stop generating further tokens. The\n   * returned text will not contain the stop sequence.\n   */\n  stopSequences?: Array<string>;\n  /**\n   * Whether or not to stream responses.\n   */\n  streaming?: boolean;\n  /**\n   * The temperature to use for sampling.\n   * @default 0.7\n   */\n  temperature?: number;\n  /**\n   * The maximum number of tokens that the model can process in a single response.\n   * This limits ensures computational efficiency and resource management.\n   */\n  maxTokens?: number;\n  /**\n   * Default search parameters for xAI's Live Search API.\n   * When set, these parameters will be applied to all requests unless\n   * overridden in the call options.\n   *\n   * @example\n   * ```typescript\n   * const llm = new ChatXAI({\n   *   model: \"grok-3-fast\",\n   *   searchParameters: {\n   *     mode: \"auto\",\n   *     max_search_results: 5,\n   *   }\n   * });\n   * ```\n   */\n  searchParameters?: XAISearchParameters;\n  /**\n   * The base URL for the xAI API.\n   * @default \"https://api.x.ai/v1\"\n   */\n  baseURL?: string;\n}\n\n/**\n * xAI chat model integration.\n *\n * The xAI API is compatible to the OpenAI API with some limitations.\n *\n * Setup:\n * Install `@langchain/xai` and set an environment variable named `XAI_API_KEY`.\n *\n * ```bash\n * npm install @langchain/xai\n * export XAI_API_KEY=\"your-api-key\"\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/_langchain_xai.ChatXAI.html#constructor)\n *\n * ## [Runtime args](https://api.js.langchain.com/interfaces/_langchain_xai.ChatXAICallOptions.html)\n *\n * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:\n *\n * ```typescript\n * // When calling `.withConfig`, call options should be passed via the first argument\n * const llmWithArgsBound = llm.withConfig({\n *   stop: [\"\\n\"],\n *   tools: [...],\n * });\n *\n * // When calling `.bindTools`, call options should be passed via the second argument\n * const llmWithTools = llm.bindTools(\n *   [...],\n *   {\n *     tool_choice: \"auto\",\n *   }\n * );\n * ```\n *\n * ## Examples\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { ChatXAI } from '@langchain/xai';\n *\n * const llm = new ChatXAI({\n *   model: \"grok-3-fast\",\n *   temperature: 0,\n *   // other params...\n * });\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Invoking</strong></summary>\n *\n * ```typescript\n * const input = `Translate \"I love programming\" into French.`;\n *\n * // Models also accept a list of chat messages or a formatted prompt\n * const result = await llm.invoke(input);\n * console.log(result);\n * ```\n *\n * ```txt\n * AIMessage {\n *   \"content\": \"The French translation of \\\"I love programming\\\" is \\\"J'aime programmer\\\". In this sentence, \\\"J'aime\\\" is the first person singular conjugation of the French verb \\\"aimer\\\" which means \\\"to love\\\", and \\\"programmer\\\" is the French infinitive for \\\"to program\\\". I hope this helps! Let me know if you have any other questions.\",\n *   \"additional_kwargs\": {},\n *   \"response_metadata\": {\n *     \"tokenUsage\": {\n *       \"completionTokens\": 82,\n *       \"promptTokens\": 20,\n *       \"totalTokens\": 102\n *     },\n *     \"finish_reason\": \"stop\"\n *   },\n *   \"tool_calls\": [],\n *   \"invalid_tool_calls\": []\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Streaming Chunks</strong></summary>\n *\n * ```typescript\n * for await (const chunk of await llm.stream(input)) {\n *   console.log(chunk);\n * }\n * ```\n *\n * ```txt\n * AIMessageChunk {\n *   \"content\": \"\",\n *   \"additional_kwargs\": {},\n *   \"response_metadata\": {\n *     \"finishReason\": null\n *   },\n *   \"tool_calls\": [],\n *   \"tool_call_chunks\": [],\n *   \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n *   \"content\": \"The\",\n *   \"additional_kwargs\": {},\n *   \"response_metadata\": {\n *     \"finishReason\": null\n *   },\n *   \"tool_calls\": [],\n *   \"tool_call_chunks\": [],\n *   \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n *   \"content\": \" French\",\n *   \"additional_kwargs\": {},\n *   \"response_metadata\": {\n *     \"finishReason\": null\n *   },\n *   \"tool_calls\": [],\n *   \"tool_call_chunks\": [],\n *   \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n *   \"content\": \" translation\",\n *   \"additional_kwargs\": {},\n *   \"response_metadata\": {\n *     \"finishReason\": null\n *   },\n *   \"tool_calls\": [],\n *   \"tool_call_chunks\": [],\n *   \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n *   \"content\": \" of\",\n *   \"additional_kwargs\": {},\n *   \"response_metadata\": {\n *     \"finishReason\": null\n *   },\n *   \"tool_calls\": [],\n *   \"tool_call_chunks\": [],\n *   \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n *   \"content\": \" \\\"\",\n *   \"additional_kwargs\": {},\n *   \"response_metadata\": {\n *     \"finishReason\": null\n *   },\n *   \"tool_calls\": [],\n *   \"tool_call_chunks\": [],\n *   \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n *   \"content\": \"I\",\n *   \"additional_kwargs\": {},\n *   \"response_metadata\": {\n *     \"finishReason\": null\n *   },\n *   \"tool_calls\": [],\n *   \"tool_call_chunks\": [],\n *   \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n *   \"content\": \" love\",\n *   \"additional_kwargs\": {},\n *   \"response_metadata\": {\n *     \"finishReason\": null\n *   },\n *   \"tool_calls\": [],\n *   \"tool_call_chunks\": [],\n *   \"invalid_tool_calls\": []\n * }\n * ...\n * AIMessageChunk {\n *   \"content\": \".\",\n *   \"additional_kwargs\": {},\n *   \"response_metadata\": {\n *     \"finishReason\": null\n *   },\n *   \"tool_calls\": [],\n *   \"tool_call_chunks\": [],\n *   \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n *   \"content\": \"\",\n *   \"additional_kwargs\": {},\n *   \"response_metadata\": {\n *     \"finishReason\": \"stop\"\n *   },\n *   \"tool_calls\": [],\n *   \"tool_call_chunks\": [],\n *   \"invalid_tool_calls\": []\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Aggregate Streamed Chunks</strong></summary>\n *\n * ```typescript\n * import { AIMessageChunk } from '@langchain/core/messages';\n * import { concat } from '@langchain/core/utils/stream';\n *\n * const stream = await llm.stream(input);\n * let full: AIMessageChunk | undefined;\n * for await (const chunk of stream) {\n *   full = !full ? chunk : concat(full, chunk);\n * }\n * console.log(full);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n *   \"content\": \"The French translation of \\\"I love programming\\\" is \\\"J'aime programmer\\\". In this sentence, \\\"J'aime\\\" is the first person singular conjugation of the French verb \\\"aimer\\\" which means \\\"to love\\\", and \\\"programmer\\\" is the French infinitive for \\\"to program\\\". I hope this helps! Let me know if you have any other questions.\",\n *   \"additional_kwargs\": {},\n *   \"response_metadata\": {\n *     \"finishReason\": \"stop\"\n *   },\n *   \"tool_calls\": [],\n *   \"tool_call_chunks\": [],\n *   \"invalid_tool_calls\": []\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Bind tools</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const llmForToolCalling = new ChatXAI({\n *   model: \"grok-3-fast\",\n *   temperature: 0,\n *   // other params...\n * });\n *\n * const GetWeather = {\n *   name: \"GetWeather\",\n *   description: \"Get the current weather in a given location\",\n *   schema: z.object({\n *     location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n *   }),\n * }\n *\n * const GetPopulation = {\n *   name: \"GetPopulation\",\n *   description: \"Get the current population in a given location\",\n *   schema: z.object({\n *     location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n *   }),\n * }\n *\n * const llmWithTools = llmForToolCalling.bindTools([GetWeather, GetPopulation]);\n * const aiMsg = await llmWithTools.invoke(\n *   \"Which city is hotter today and which is bigger: LA or NY?\"\n * );\n * console.log(aiMsg.tool_calls);\n * ```\n *\n * ```txt\n * [\n *   {\n *     name: 'GetWeather',\n *     args: { location: 'Los Angeles, CA' },\n *     type: 'tool_call',\n *     id: 'call_cd34'\n *   },\n *   {\n *     name: 'GetWeather',\n *     args: { location: 'New York, NY' },\n *     type: 'tool_call',\n *     id: 'call_68rf'\n *   },\n *   {\n *     name: 'GetPopulation',\n *     args: { location: 'Los Angeles, CA' },\n *     type: 'tool_call',\n *     id: 'call_f81z'\n *   },\n *   {\n *     name: 'GetPopulation',\n *     args: { location: 'New York, NY' },\n *     type: 'tool_call',\n *     id: 'call_8byt'\n *   }\n * ]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const Joke = z.object({\n *   setup: z.string().describe(\"The setup of the joke\"),\n *   punchline: z.string().describe(\"The punchline to the joke\"),\n *   rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n * }).describe('Joke to tell user.');\n *\n * const structuredLlm = llmForToolCalling.withStructuredOutput(Joke, { name: \"Joke\" });\n * const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n * console.log(jokeResult);\n * ```\n *\n * ```txt\n * {\n *   setup: \"Why don't cats play poker in the wild?\",\n *   punchline: 'Because there are too many cheetahs.'\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Server Tool Calling (Live Search)</strong></summary>\n *\n * xAI supports server-side tools that are executed by the API rather than\n * requiring client-side execution. The `live_search` tool enables the model\n * to search the web for real-time information.\n *\n * ```typescript\n * // Method 1: Using the built-in live_search tool\n * const llm = new ChatXAI({\n *   model: \"grok-3-fast\",\n *   temperature: 0,\n * });\n *\n * const llmWithSearch = llm.bindTools([{ type: \"live_search\" }]);\n * const result = await llmWithSearch.invoke(\"What happened in tech news today?\");\n * console.log(result.content);\n * // The model will search the web and include real-time information in its response\n * ```\n *\n * ```typescript\n * // Method 2: Using searchParameters for more control\n * const llm = new ChatXAI({\n *   model: \"grok-3-fast\",\n *   searchParameters: {\n *     mode: \"auto\", // \"auto\" | \"on\" | \"off\"\n *     max_search_results: 5,\n *     from_date: \"2024-01-01\", // ISO date string\n *     return_citations: true,\n *   }\n * });\n *\n * const result = await llm.invoke(\"What are the latest AI developments?\");\n * ```\n *\n * ```typescript\n * // Method 3: Override search parameters per request\n * const result = await llm.invoke(\"Find recent news about SpaceX\", {\n *   searchParameters: {\n *     mode: \"on\",\n *     max_search_results: 10,\n *     sources: [\n *       { type: \"web\", allowed_websites: [\"spacex.com\", \"nasa.gov\"] },\n *     ],\n *   }\n * });\n * ```\n * </details>\n *\n * <br />\n */\nexport class ChatXAI extends ChatOpenAICompletions<ChatXAICallOptions> {\n  static lc_name() {\n    return \"ChatXAI\";\n  }\n\n  _llmType() {\n    return \"xai\";\n  }\n\n  get lc_secrets(): { [key: string]: string } | undefined {\n    return {\n      apiKey: \"XAI_API_KEY\",\n    };\n  }\n\n  lc_serializable = true;\n\n  lc_namespace = [\"langchain\", \"chat_models\", \"xai\"];\n\n  /**\n   * Default search parameters for the Live Search API.\n   */\n  searchParameters?: XAISearchParameters;\n\n  constructor(model: string, fields?: Omit<ChatXAIInput, \"model\">);\n  constructor(fields?: Partial<ChatXAIInput>);\n  constructor(\n    modelOrFields?: string | Partial<ChatXAIInput>,\n    fieldsArg?: Omit<ChatXAIInput, \"model\">\n  ) {\n    const fields =\n      typeof modelOrFields === \"string\"\n        ? { ...(fieldsArg ?? {}), model: modelOrFields }\n        : (modelOrFields ?? {});\n    const apiKey = fields?.apiKey || getEnvironmentVariable(\"XAI_API_KEY\");\n    if (!apiKey) {\n      throw new Error(\n        `xAI API key not found. Please set the XAI_API_KEY environment variable or provide the key into \"apiKey\" field.`\n      );\n    }\n\n    super({\n      ...fields,\n      model: fields?.model || \"grok-3-fast\",\n      apiKey,\n      configuration: {\n        baseURL: fields?.baseURL ?? \"https://api.x.ai/v1\",\n      },\n    });\n\n    this._addVersion(\"@langchain/xai\", __PKG_VERSION__);\n\n    this.searchParameters = fields?.searchParameters;\n  }\n\n  toJSON(): Serialized {\n    const result = super.toJSON();\n\n    if (\n      \"kwargs\" in result &&\n      typeof result.kwargs === \"object\" &&\n      result.kwargs != null\n    ) {\n      delete result.kwargs.openai_api_key;\n      delete result.kwargs.configuration;\n    }\n\n    return result;\n  }\n\n  getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\n    const params = super.getLsParams(options);\n    params.ls_provider = \"xai\";\n    return params;\n  }\n\n  /**\n   * Get the effective search parameters, merging defaults with call options.\n   * @param options Call options that may contain search parameters\n   * @returns Merged search parameters or undefined if none are configured\n   */\n  protected _getEffectiveSearchParameters(\n    options?: this[\"ParsedCallOptions\"]\n  ): XAISearchParameters | undefined {\n    return mergeSearchParams(this.searchParameters, options?.searchParameters);\n  }\n\n  /**\n   * Check if any built-in tools (like live_search) are in the tools list.\n   * @param tools List of tools to check\n   * @returns true if any built-in tools are present\n   */\n  protected _hasBuiltInTools(tools?: ChatXAIToolType[]): boolean {\n    return tools?.some(isXAIBuiltInTool) ?? false;\n  }\n\n  /**\n   * Formats tools to xAI/OpenAI format, preserving provider-specific definitions.\n   *\n   * @param tools The tools to format\n   * @returns The formatted tools\n   */\n  formatStructuredToolToXAI(\n    tools: ChatXAIToolType[]\n  ): (OpenAIClient.ChatCompletionTool | XAIBuiltInTool)[] | undefined {\n    if (!tools || !tools.length) {\n      return undefined;\n    }\n    return tools.map((tool) => {\n      // 1. Check for provider definition first (from xaiLiveSearch factory)\n      if (isLangChainTool(tool) && tool.extras?.providerToolDefinition) {\n        return tool.extras.providerToolDefinition as XAIBuiltInTool;\n      }\n      // 2. Check for built-in tools (legacy { type: \"live_search\" })\n      if (isXAIBuiltInTool(tool)) {\n        return tool;\n      }\n      // 3. Convert standard tools to OpenAI format\n      return convertToOpenAITool(tool) as OpenAIClient.ChatCompletionTool;\n    });\n  }\n\n  override bindTools(\n    tools: ChatXAIToolType[],\n    kwargs?: Partial<ChatXAICallOptions>\n  ): Runnable<BaseLanguageModelInput, AIMessageChunk, ChatXAICallOptions> {\n    return this.withConfig({\n      tools: this.formatStructuredToolToXAI(tools),\n      ...kwargs,\n    } as Partial<ChatXAICallOptions>);\n  }\n\n  /** @internal */\n  override invocationParams(\n    options?: this[\"ParsedCallOptions\"],\n    extra?: { streaming?: boolean }\n  ): ChatXAICompletionsInvocationParams {\n    const baseParams = super.invocationParams(options, extra);\n\n    // Cast to xAI-specific params type\n    const params: ChatXAICompletionsInvocationParams = { ...baseParams };\n\n    // Check if live_search tool is being used\n    // We also need to extract params from the tool definition if present\n    const liveSearchTool = options?.tools?.find(isXAIBuiltInTool) as\n      | XAILiveSearchTool\n      | undefined;\n\n    const mergedSearchParams = mergeSearchParams(\n      this.searchParameters,\n      options?.searchParameters,\n      liveSearchTool\n    );\n\n    // Add search_parameters if needed\n    if (mergedSearchParams) {\n      params.search_parameters =\n        buildSearchParametersPayload(mergedSearchParams);\n    }\n\n    return params;\n  }\n\n  async completionWithRetry(\n    request: OpenAIClient.Chat.ChatCompletionCreateParamsStreaming,\n    options?: OpenAICoreRequestOptions\n  ): Promise<AsyncIterable<OpenAIClient.Chat.Completions.ChatCompletionChunk>>;\n\n  async completionWithRetry(\n    request: OpenAIClient.Chat.ChatCompletionCreateParamsNonStreaming,\n    options?: OpenAICoreRequestOptions\n  ): Promise<OpenAIClient.Chat.Completions.ChatCompletion>;\n\n  /**\n   * Calls the xAI API with retry logic in case of failures.\n   * @param request The request to send to the xAI API.\n   * @param options Optional configuration for the API call.\n   * @returns The response from the xAI API.\n   */\n  async completionWithRetry(\n    request:\n      | OpenAIClient.Chat.ChatCompletionCreateParamsStreaming\n      | OpenAIClient.Chat.ChatCompletionCreateParamsNonStreaming,\n    options?: OpenAICoreRequestOptions\n  ): Promise<\n    | AsyncIterable<OpenAIClient.Chat.Completions.ChatCompletionChunk>\n    | OpenAIClient.Chat.Completions.ChatCompletion\n  > {\n    delete request.frequency_penalty;\n    delete request.presence_penalty;\n    delete request.logit_bias;\n    delete request.functions;\n\n    const newRequestMessages = request.messages.map((msg) => {\n      if (!msg.content) {\n        return {\n          ...msg,\n          content: \"\",\n        };\n      }\n      return msg;\n    });\n\n    let filteredTools: OpenAIClient.ChatCompletionTool[] | undefined;\n    if (request.tools) {\n      filteredTools = filterXAIBuiltInTools({\n        tools: request.tools,\n        excludedTypes: [XAI_LIVE_SEARCH_TOOL_TYPE],\n      }) as OpenAIClient.ChatCompletionTool[] | undefined;\n    }\n\n    const newRequest = {\n      ...request,\n      messages: newRequestMessages,\n      tools: filteredTools,\n    };\n\n    if (newRequest.stream === true) {\n      return super.completionWithRetry(newRequest, options);\n    }\n\n    return super.completionWithRetry(newRequest, options);\n  }\n\n  protected override _convertCompletionsDeltaToBaseMessageChunk(\n    // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n    delta: Record<string, any>,\n    rawResponse: OpenAIClient.ChatCompletionChunk,\n    defaultRole?:\n      | \"function\"\n      | \"user\"\n      | \"system\"\n      | \"developer\"\n      | \"assistant\"\n      | \"tool\"\n  ): AIMessageChunk {\n    const messageChunk = super._convertCompletionsDeltaToBaseMessageChunk(\n      delta,\n      rawResponse,\n      defaultRole\n    ) as AIMessageChunk;\n\n    // Cast to xAI-specific types for proper typing\n    const responseMetadata =\n      messageChunk.response_metadata as XAIResponseMetadata;\n\n    // Make concatenating chunks work without merge warning\n    if (!rawResponse.choices[0]?.finish_reason) {\n      delete responseMetadata.usage;\n      delete messageChunk.usage_metadata;\n    } else {\n      messageChunk.usage_metadata = responseMetadata.usage;\n    }\n    return messageChunk;\n  }\n\n  protected override _convertCompletionsMessageToBaseMessage(\n    message: OpenAIClient.ChatCompletionMessage & {\n      reasoning_content?: string;\n    },\n    rawResponse: OpenAIClient.ChatCompletion\n  ): AIMessageChunk {\n    const langChainMessage = super._convertCompletionsMessageToBaseMessage(\n      message,\n      rawResponse\n    ) as AIMessageChunk;\n\n    // Cast additional_kwargs to xAI-specific type and add reasoning_content\n    const additionalKwargs =\n      langChainMessage.additional_kwargs as XAIAdditionalKwargs;\n    additionalKwargs.reasoning_content = message.reasoning_content;\n\n    return langChainMessage;\n  }\n\n  /**\n   * Return profiling information for the model.\n   *\n   * Provides information about the model's capabilities and constraints,\n   * including token limits, multimodal support, and advanced features like\n   * tool calling and structured output.\n   *\n   * @returns {ModelProfile} An object describing the model's capabilities and constraints\n   *\n   * @example\n   * ```typescript\n   * const model = new ChatXAI({ model: \"grok-3-fast\" });\n   * const profile = model.profile;\n   * console.log(profile.maxInputTokens); // 128000\n   * console.log(profile.imageInputs); // true\n   * ```\n   */\n  get profile(): ModelProfile {\n    return PROFILES[this.model] ?? {};\n  }\n}\n"],"mappings":";;;;;;;;;;;;AAiDA,MAAM,0BAA0B,IAAI,IAAwC,CAC1EA,sBAAAA,0BACD,CAAC;;;;;;;;AAkEF,SAAgB,iBACd,MACwB;AACxB,QACE,OAAO,SAAS,YAChB,SAAS,QACT,UAAU,QACV,OAAQ,KAA4B,SAAS,YAC7C,wBAAwB,IAAK,KAA0B,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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