const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
const require_responses = require('../converters/responses.cjs');
const __langchain_core_utils_env = require_rolldown_runtime.__toESM(require("@langchain/core/utils/env"));
const __langchain_core_language_models_chat_models = require_rolldown_runtime.__toESM(require("@langchain/core/language_models/chat_models"));

//#region src/chat_models/responses.ts
/**
* xAI Responses API chat model integration.
*
* This class provides access to xAI's Responses API, which offers enhanced
* capabilities including built-in tools, reasoning, and search.
*
* @example
* ```typescript
* import { ChatXAIResponses } from "@langchain/xai";
*
* const llm = new ChatXAIResponses({
*   model: "grok-3",
*   temperature: 0.7,
* });
*
* const result = await llm.invoke("What is the capital of France?");
* console.log(result.content);
* ```
*/
var ChatXAIResponses = class extends __langchain_core_language_models_chat_models.BaseChatModel {
	static lc_name() {
		return "ChatXAIResponses";
	}
	lc_serializable = true;
	lc_namespace = [
		"langchain",
		"chat_models",
		"xai"
	];
	get lc_secrets() {
		return { apiKey: "XAI_API_KEY" };
	}
	get lc_aliases() {
		return { apiKey: "xai_api_key" };
	}
	apiKey;
	model;
	streaming;
	temperature;
	topP;
	maxOutputTokens;
	store;
	user;
	baseURL;
	searchParameters;
	reasoning;
	tools;
	constructor(fields) {
		super(fields ?? {});
		const apiKey = fields?.apiKey ?? (0, __langchain_core_utils_env.getEnvironmentVariable)("XAI_API_KEY");
		if (!apiKey) throw new Error(`xAI API key not found. Please set the XAI_API_KEY environment variable or provide the key in the "apiKey" field.`);
		this.apiKey = apiKey;
		this.model = fields?.model ?? "grok-3";
		this.streaming = fields?.streaming ?? false;
		this.temperature = fields?.temperature;
		this.topP = fields?.topP;
		this.maxOutputTokens = fields?.maxOutputTokens;
		this.store = fields?.store;
		this.user = fields?.user;
		this.baseURL = fields?.baseURL ?? "https://api.x.ai/v1";
		this.searchParameters = fields?.searchParameters;
		this.reasoning = fields?.reasoning;
		this.tools = fields?.tools;
	}
	_llmType() {
		return "xai-responses";
	}
	getLsParams(options) {
		const params = super.getLsParams(options);
		params.ls_provider = "xai";
		params.ls_model_name = this.model;
		params.ls_model_type = "chat";
		params.ls_temperature = this.temperature;
		params.ls_max_tokens = this.maxOutputTokens;
		return params;
	}
	toJSON() {
		const result = super.toJSON();
		if ("kwargs" in result && typeof result.kwargs === "object" && result.kwargs != null) delete result.kwargs.apiKey;
		return result;
	}
	invocationParams(options) {
		return {
			model: this.model,
			temperature: this.temperature,
			top_p: this.topP,
			max_output_tokens: this.maxOutputTokens,
			store: this.store,
			user: this.user,
			stream: this.streaming,
			previous_response_id: options?.previous_response_id,
			include: options?.include,
			text: options?.text,
			search_parameters: options?.search_parameters ?? this.searchParameters,
			reasoning: options?.reasoning ?? this.reasoning,
			tools: options?.tools ?? this.tools,
			tool_choice: options?.tool_choice,
			parallel_tool_calls: options?.parallel_tool_calls
		};
	}
	async _makeRequest(request) {
		const url = `${this.baseURL}/responses`;
		const headers = {
			"Content-Type": "application/json",
			Authorization: `Bearer ${this.apiKey}`
		};
		if (request.stream) return this._makeStreamingRequest(url, headers, request);
		const response = await this.caller.call(async () => {
			const res = await fetch(url, {
				method: "POST",
				headers,
				body: JSON.stringify(request)
			});
			if (!res.ok) {
				const errorBody = await res.text();
				throw new Error(`xAI API error: ${res.status} ${res.statusText} - ${errorBody}`);
			}
			return res.json();
		});
		return response;
	}
	/**
	* Makes a streaming request to the xAI Responses API.
	*/
	async *_makeStreamingRequest(url, headers, request) {
		const response = await this.caller.call(async () => {
			const res = await fetch(url, {
				method: "POST",
				headers,
				body: JSON.stringify(request)
			});
			if (!res.ok) {
				const errorBody = await res.text();
				throw new Error(`xAI API error: ${res.status} ${res.statusText} - ${errorBody}`);
			}
			return res;
		});
		const reader = response.body?.getReader();
		if (!reader) throw new Error("No response body");
		const decoder = new TextDecoder();
		let buffer = "";
		try {
			while (true) {
				const { done, value } = await reader.read();
				if (done) break;
				buffer += decoder.decode(value, { stream: true });
				const lines = buffer.split("\n");
				buffer = lines.pop() ?? "";
				for (const line of lines) {
					const trimmed = line.trim();
					if (!trimmed || trimmed === "data: [DONE]") continue;
					if (trimmed.startsWith("data: ")) try {
						const data = JSON.parse(trimmed.slice(6));
						yield data;
					} catch {}
				}
			}
		} finally {
			reader.releaseLock();
		}
	}
	async _generate(messages, options, runManager) {
		options.signal?.throwIfAborted();
		const invocationParams = this.invocationParams(options);
		const input = require_responses.convertMessagesToResponsesInput(messages);
		if (invocationParams.stream) {
			const stream = this._streamResponseChunks(messages, options, runManager);
			let finalChunk;
			for await (const chunk of stream) {
				chunk.message.response_metadata = {
					...chunk.generationInfo,
					...chunk.message.response_metadata
				};
				finalChunk = finalChunk?.concat(chunk) ?? chunk;
			}
			return {
				generations: finalChunk ? [finalChunk] : [],
				llmOutput: { estimatedTokenUsage: (finalChunk?.message)?.usage_metadata }
			};
		}
		const response = await this._makeRequest({
			input,
			...invocationParams,
			stream: false
		});
		const aiMessage = require_responses.convertResponseToAIMessage(response);
		const text = require_responses.extractTextFromOutput(response.output);
		return {
			generations: [{
				text,
				message: aiMessage
			}],
			llmOutput: {
				id: response.id,
				estimatedTokenUsage: response.usage ? {
					promptTokens: response.usage.input_tokens,
					completionTokens: response.usage.output_tokens,
					totalTokens: response.usage.total_tokens
				} : void 0
			}
		};
	}
	async *_streamResponseChunks(messages, options, runManager) {
		const invocationParams = this.invocationParams(options);
		const input = require_responses.convertMessagesToResponsesInput(messages);
		const streamIterable = await this._makeRequest({
			input,
			...invocationParams,
			stream: true
		});
		for await (const event of streamIterable) {
			if (options.signal?.aborted) return;
			const chunk = require_responses.convertStreamEventToChunk(event);
			if (chunk) {
				yield chunk;
				await runManager?.handleLLMNewToken(chunk.text || "", {
					prompt: 0,
					completion: 0
				});
			}
		}
	}
};

//#endregion
exports.ChatXAIResponses = ChatXAIResponses;
//# sourceMappingURL=responses.cjs.map