@krutai/ai-provider 0.2.15 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +53 -3
- package/dist/index.d.ts +53 -3
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { KrutAIKeyValidationError, validateApiKeyWithService as validateApiKey, validateApiKeyFormat } from 'krutai';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Types for @krutai/ai-provider
|
|
@@ -8,6 +8,56 @@ export { ApiKeyValidationError as KrutAIKeyValidationError, validateApiKeyWithSe
|
|
|
8
8
|
* Your server can use this value to route to its own default model.
|
|
9
9
|
*/
|
|
10
10
|
declare const DEFAULT_MODEL: "gemini-3.1-pro-preview";
|
|
11
|
+
interface DataRecord {
|
|
12
|
+
[key: string]: unknown;
|
|
13
|
+
}
|
|
14
|
+
interface FileSchema {
|
|
15
|
+
name: string;
|
|
16
|
+
rowCount: number;
|
|
17
|
+
columns: string[];
|
|
18
|
+
sample: DataRecord[];
|
|
19
|
+
}
|
|
20
|
+
interface ComparisonSummary {
|
|
21
|
+
totalRows: number;
|
|
22
|
+
differencesFound: number;
|
|
23
|
+
matchesFound: number;
|
|
24
|
+
status: string;
|
|
25
|
+
}
|
|
26
|
+
interface ComparisonCodeResult {
|
|
27
|
+
code: string;
|
|
28
|
+
humanExplanation: string[];
|
|
29
|
+
constants?: Record<string, unknown>;
|
|
30
|
+
}
|
|
31
|
+
interface ComparisonResult {
|
|
32
|
+
summary: ComparisonSummary;
|
|
33
|
+
metadata?: {
|
|
34
|
+
file1Columns?: string[];
|
|
35
|
+
file2Columns?: string[];
|
|
36
|
+
executionTime?: number;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
interface ComparisonResponse {
|
|
40
|
+
success: boolean;
|
|
41
|
+
result?: ComparisonResult;
|
|
42
|
+
generatedCode?: string;
|
|
43
|
+
humanExplanation?: string[];
|
|
44
|
+
downloadUrl?: string;
|
|
45
|
+
fileName?: string;
|
|
46
|
+
error?: string;
|
|
47
|
+
}
|
|
48
|
+
interface PreviewResponse {
|
|
49
|
+
success: boolean;
|
|
50
|
+
file1?: FileSchema;
|
|
51
|
+
file2?: FileSchema;
|
|
52
|
+
error?: string;
|
|
53
|
+
}
|
|
54
|
+
interface GenerateCodeOptions {
|
|
55
|
+
prompt?: string;
|
|
56
|
+
}
|
|
57
|
+
interface CompareFilesOptions {
|
|
58
|
+
code: string;
|
|
59
|
+
prompt?: string;
|
|
60
|
+
}
|
|
11
61
|
/**
|
|
12
62
|
* Configuration options for KrutAIProvider
|
|
13
63
|
*/
|
|
@@ -257,6 +307,6 @@ declare class KrutAIProvider {
|
|
|
257
307
|
declare function krutAI(config: KrutAIProviderConfig & {
|
|
258
308
|
model?: string;
|
|
259
309
|
}): KrutAIProvider;
|
|
260
|
-
declare const VERSION = "0.
|
|
310
|
+
declare const VERSION = "0.3.4";
|
|
261
311
|
|
|
262
|
-
export { type ChatMessage, DEFAULT_MODEL, type GenerateOptions, KrutAIProvider, type KrutAIProviderConfig, VERSION, krutAI };
|
|
312
|
+
export { type ChatMessage, type CompareFilesOptions, type ComparisonCodeResult, type ComparisonResponse, type ComparisonResult, type ComparisonSummary, DEFAULT_MODEL, type DataRecord, type FileSchema, type GenerateCodeOptions, type GenerateOptions, KrutAIProvider, type KrutAIProviderConfig, type PreviewResponse, VERSION, krutAI };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { KrutAIKeyValidationError, validateApiKeyWithService as validateApiKey, validateApiKeyFormat } from 'krutai';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Types for @krutai/ai-provider
|
|
@@ -8,6 +8,56 @@ export { ApiKeyValidationError as KrutAIKeyValidationError, validateApiKeyWithSe
|
|
|
8
8
|
* Your server can use this value to route to its own default model.
|
|
9
9
|
*/
|
|
10
10
|
declare const DEFAULT_MODEL: "gemini-3.1-pro-preview";
|
|
11
|
+
interface DataRecord {
|
|
12
|
+
[key: string]: unknown;
|
|
13
|
+
}
|
|
14
|
+
interface FileSchema {
|
|
15
|
+
name: string;
|
|
16
|
+
rowCount: number;
|
|
17
|
+
columns: string[];
|
|
18
|
+
sample: DataRecord[];
|
|
19
|
+
}
|
|
20
|
+
interface ComparisonSummary {
|
|
21
|
+
totalRows: number;
|
|
22
|
+
differencesFound: number;
|
|
23
|
+
matchesFound: number;
|
|
24
|
+
status: string;
|
|
25
|
+
}
|
|
26
|
+
interface ComparisonCodeResult {
|
|
27
|
+
code: string;
|
|
28
|
+
humanExplanation: string[];
|
|
29
|
+
constants?: Record<string, unknown>;
|
|
30
|
+
}
|
|
31
|
+
interface ComparisonResult {
|
|
32
|
+
summary: ComparisonSummary;
|
|
33
|
+
metadata?: {
|
|
34
|
+
file1Columns?: string[];
|
|
35
|
+
file2Columns?: string[];
|
|
36
|
+
executionTime?: number;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
interface ComparisonResponse {
|
|
40
|
+
success: boolean;
|
|
41
|
+
result?: ComparisonResult;
|
|
42
|
+
generatedCode?: string;
|
|
43
|
+
humanExplanation?: string[];
|
|
44
|
+
downloadUrl?: string;
|
|
45
|
+
fileName?: string;
|
|
46
|
+
error?: string;
|
|
47
|
+
}
|
|
48
|
+
interface PreviewResponse {
|
|
49
|
+
success: boolean;
|
|
50
|
+
file1?: FileSchema;
|
|
51
|
+
file2?: FileSchema;
|
|
52
|
+
error?: string;
|
|
53
|
+
}
|
|
54
|
+
interface GenerateCodeOptions {
|
|
55
|
+
prompt?: string;
|
|
56
|
+
}
|
|
57
|
+
interface CompareFilesOptions {
|
|
58
|
+
code: string;
|
|
59
|
+
prompt?: string;
|
|
60
|
+
}
|
|
11
61
|
/**
|
|
12
62
|
* Configuration options for KrutAIProvider
|
|
13
63
|
*/
|
|
@@ -257,6 +307,6 @@ declare class KrutAIProvider {
|
|
|
257
307
|
declare function krutAI(config: KrutAIProviderConfig & {
|
|
258
308
|
model?: string;
|
|
259
309
|
}): KrutAIProvider;
|
|
260
|
-
declare const VERSION = "0.
|
|
310
|
+
declare const VERSION = "0.3.4";
|
|
261
311
|
|
|
262
|
-
export { type ChatMessage, DEFAULT_MODEL, type GenerateOptions, KrutAIProvider, type KrutAIProviderConfig, VERSION, krutAI };
|
|
312
|
+
export { type ChatMessage, type CompareFilesOptions, type ComparisonCodeResult, type ComparisonResponse, type ComparisonResult, type ComparisonSummary, DEFAULT_MODEL, type DataRecord, type FileSchema, type GenerateCodeOptions, type GenerateOptions, KrutAIProvider, type KrutAIProviderConfig, type PreviewResponse, VERSION, krutAI };
|
package/dist/index.js
CHANGED
|
@@ -30,7 +30,7 @@ var KrutAIProvider = class {
|
|
|
30
30
|
async initialize() {
|
|
31
31
|
if (this.initialized) return;
|
|
32
32
|
if (this.config.validateOnInit !== false) {
|
|
33
|
-
await krutai.
|
|
33
|
+
await krutai.validateApiKey(this.apiKey, this.serverUrl);
|
|
34
34
|
}
|
|
35
35
|
this.initialized = true;
|
|
36
36
|
}
|
|
@@ -165,11 +165,11 @@ function krutAI(config) {
|
|
|
165
165
|
...config
|
|
166
166
|
});
|
|
167
167
|
}
|
|
168
|
-
var VERSION = "0.
|
|
168
|
+
var VERSION = "0.3.4";
|
|
169
169
|
|
|
170
170
|
Object.defineProperty(exports, "KrutAIKeyValidationError", {
|
|
171
171
|
enumerable: true,
|
|
172
|
-
get: function () { return krutai.
|
|
172
|
+
get: function () { return krutai.KrutAIKeyValidationError; }
|
|
173
173
|
});
|
|
174
174
|
Object.defineProperty(exports, "validateApiKey", {
|
|
175
175
|
enumerable: true,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.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AE,WAAA,EAAa,OAAA,CAAQ,WAAA,EAAY,GAAI;AAAC,OACnF;AAAA,KACJ,CAAA;AAED,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AACd,MAAA,IAAI,YAAA,GAAe,CAAA,wBAAA,EAA2B,QAAA,CAAS,MAAM,CAAA,cAAA,CAAA;AAC7D,MAAA,IAAI;AACA,QAAA,MAAM,SAAA,GAAa,MAAM,QAAA,CAAS,IAAA,EAAK;AACvC,QAAA,IAAI,SAAA,EAAW,KAAA,EAAO,YAAA,GAAe,SAAA,CAAU,KAAA;AAAA,aAAA,IACtC,SAAA,EAAW,OAAA,EAAS,YAAA,GAAe,SAAA,CAAU,OAAA;AAAA,MAC1D,CAAA,CAAA,MAAQ;AAAA,MAAE;AACV,MAAA,MAAM,IAAI,MAAM,YAAY,CAAA;AAAA,IAChC;AAEA,IAAA,MAAM,IAAA,GAAQ,MAAM,QAAA,CAAS,IAAA,EAAK;AAGlC,IAAA,IAAI,QAAQ,WAAA,EAAa;AACrB,MAAA,OAAO,IAAA;AAAA,IACX;AAGA,IAAA,OAAQ,IAAA,CAAK,IAAA,IAAQ,IAAA,CAAK,OAAA,IAAW,KAAK,OAAA,IAAW,EAAA;AAAA,EACzD;AACJ;ACxIO,SAAS,OACZ,MAAA,EACc;AACd,EAAA,OAAO,IAAI,cAAA,CAAe;AAAA,IACtB,KAAA,EAAO,aAAA;AAAA,IACP,GAAG;AAAA,GACN,CAAA;AACL;AAGO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * Types for @krutai/ai-provider\n */\n\n/**\n * Default model identifier sent to the LangChain server when no model is specified.\n * Your server can use this value to route to its own default model.\n */\nexport const DEFAULT_MODEL = 'gemini-3.1-pro-preview' as const;\n\n/**\n * Default base URL for the LangChain backend server.\n * Used when no serverUrl is provided in the config.\n */\nexport const DEFAULT_SERVER_URL = 'http://localhost:8000' as const;\n\n/**\n * Configuration options for KrutAIProvider\n */\nexport interface KrutAIProviderConfig {\n /**\n * KrutAI API key.\n * Validated against the LangChain server before use.\n * Optional: defaults to process.env.KRUTAI_API_KEY\n */\n apiKey?: string;\n\n /**\n * Base URL of your deployed LangChain backend server.\n * @default \"http://localhost:8000\"\n * @example \"https://ai.krut.ai\"\n */\n serverUrl?: string;\n\n /**\n * The AI model to use (passed to the server).\n * The server decides what to do with this value.\n * @default \"default\"\n */\n model?: string;\n\n /**\n * Whether to validate the API key against the server on initialization.\n * Set to false to skip the validation round-trip (e.g. in tests).\n * @default true\n */\n validateOnInit?: boolean;\n}\n\n/**\n * A part of a multimodal message\n */\nexport interface TextContentPart {\n type: 'text';\n text: string;\n}\n\nexport interface ImageContentPart {\n type: 'image_url';\n image_url: {\n url: string; // Base64 data URI or HTTP(S) URL\n detail?: 'low' | 'high' | 'auto';\n };\n}\n\nexport type ContentPart = TextContentPart | ImageContentPart;\nexport type MessageContent = string | ContentPart[];\n\n/**\n * A single chat message\n */\nexport interface ChatMessage {\n role: 'user' | 'assistant' | 'system';\n content: MessageContent;\n}\n\n/**\n * Options for a single generate / stream / chat call\n */\nexport interface GenerateOptions {\n /**\n * Override the model for this specific call.\n */\n model?: string;\n\n /**\n * System prompt (prepended as a system message).\n */\n system?: string;\n\n /**\n * Maximum tokens to generate.\n */\n maxTokens?: number;\n\n /**\n * Temperature (0–2).\n */\n temperature?: number;\n\n /**\n * Array of image URLs or base64 data URIs to include with the request.\n */\n images?: string[];\n\n /**\n * Array of document URLs or base64 data URIs (e.g. PDFs) to include with the request.\n */\n documents?: string[];\n\n /**\n * Array of PDF URLs or base64 data URIs to include with the request.\n */\n pdf?: string[];\n\n /**\n * Optional conversation history.\n */\n history?: ChatMessage[];\n\n /**\n * Optional attachments.\n */\n attachments?: any[];\n\n /**\n * Whether to return structured output.\n */\n isStructure?: boolean;\n\n /**\n * The schema for structured output.\n * Can be a JSON Schema object or an array of field names.\n */\n output_structure?: any;\n}\n","import type { KrutAIProviderConfig, GenerateOptions, ChatMessage } from './types';\nimport { DEFAULT_MODEL, DEFAULT_SERVER_URL } from './types';\nimport {\n validateApiKeyWithService as validateApiKey,\n validateApiKeyFormat,\n ApiKeyValidationError as KrutAIKeyValidationError,\n} from 'krutai';\n\nexport { KrutAIKeyValidationError };\n\n/**\n * KrutAIProvider — fetch-based AI provider for KrutAI\n *\n * Calls your deployed LangChain backend server for all AI operations.\n * The API key is validated against the server before use.\n *\n * @example\n * ```typescript\n * import { KrutAIProvider } from '@krutai/ai-provider';\n *\n * // Using local dev server (http://localhost:8000 by default)\n * const ai = new KrutAIProvider({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * });\n *\n * // Or point to a production server\n * const aiProd = new KrutAIProvider({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://ai.krut.ai',\n * });\n *\n * await ai.initialize(); // validates key against server\n *\n * const text = await ai.generate('Tell me a joke');\n * console.log(text);\n * ```\n */\nexport class KrutAIProvider {\n private readonly apiKey: string;\n private readonly serverUrl: string;\n private readonly resolvedModel: string;\n private readonly config: KrutAIProviderConfig;\n\n private initialized = false;\n\n constructor(config: KrutAIProviderConfig) {\n this.config = config;\n this.apiKey = config.apiKey || process.env.KRUTAI_API_KEY || '';\n this.serverUrl = (config.serverUrl ?? DEFAULT_SERVER_URL).replace(/\\/$/, ''); // strip trailing slash\n this.resolvedModel = config.model ?? DEFAULT_MODEL;\n\n // Basic format check immediately on construction\n validateApiKeyFormat(this.apiKey);\n\n // If validation is disabled, mark as ready immediately\n if (config.validateOnInit === false) {\n this.initialized = true;\n }\n }\n\n /**\n * Initialize the provider.\n * Validates the API key against the LangChain server, then marks provider as ready.\n *\n * @throws {KrutAIKeyValidationError} if the key is rejected or the server is unreachable\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n if (this.config.validateOnInit !== false) {\n await validateApiKey(this.apiKey, this.serverUrl);\n }\n\n this.initialized = true;\n }\n\n /**\n * Returns the currently configured default model.\n */\n getModel(): string {\n return this.resolvedModel;\n }\n\n /**\n * Returns whether the provider has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private assertInitialized(): void {\n if (!this.initialized) {\n throw new Error(\n 'KrutAIProvider not initialized. Call initialize() first or set validateOnInit to false.'\n );\n }\n }\n\n /** Common request headers sent to the server on every AI call. */\n private authHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'x-api-key': this.apiKey,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Public AI Methods\n // ---------------------------------------------------------------------------\n\n /**\n * Similar to streamChat() but returns the raw fetch Response object.\n * Useful for proxying the Server-Sent Events stream directly to a frontend client.\n *\n * @param messages - Full conversation history\n * @param options - Optional overrides (model, maxTokens, temperature)\n * @returns A Promise resolving to the native fetch Response\n */\n async streamChatResponse(messages: ChatMessage[], options: GenerateOptions = {}): Promise<Response> {\n this.assertInitialized();\n\n if (!messages.length) {\n throw new Error('Messages array cannot be empty for streamChatResponse');\n }\n\n const model = options.model ?? this.resolvedModel;\n\n const response = await fetch(`${this.serverUrl}/stream`, {\n method: 'POST',\n headers: {\n ...this.authHeaders(),\n Accept: 'text/event-stream',\n },\n body: JSON.stringify({\n messages,\n model,\n ...(options.system !== undefined ? { system: options.system } : {}),\n ...(options.images !== undefined ? { images: options.images } : {}),\n ...(options.documents !== undefined ? { documents: options.documents } : {}),\n ...(options.pdf !== undefined ? { pdf: options.pdf } : {}),\n ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n }),\n });\n\n if (!response.ok) {\n let errorMessage = `AI server returned HTTP ${response.status} for /stream`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n\n return response;\n }\n\n /**\n * Generate a response for a prompt (non-streaming).\n *\n * Calls: POST {serverUrl}/generate\n * Body: { prompt, model, system?, maxTokens?, temperature? }\n * Expected response: { text: string } or { content: string } or { message: string }\n *\n * @param prompt - The user prompt string\n * @param options - Optional overrides (model, system, maxTokens, temperature)\n * @returns The assistant's response text (or an object if structured)\n */\n async chat<T = any>(prompt: string, options: GenerateOptions = {}): Promise<T> {\n this.assertInitialized();\n const model = options.model ?? this.resolvedModel;\n\n const response = await fetch(`${this.serverUrl}/generate`, {\n method: 'POST',\n headers: this.authHeaders(),\n body: JSON.stringify({\n prompt,\n model,\n ...(options.system !== undefined ? { system: options.system } : {}),\n ...(options.images !== undefined ? { images: options.images } : {}),\n ...(options.documents !== undefined ? { documents: options.documents } : {}),\n ...(options.pdf !== undefined ? { pdf: options.pdf } : {}),\n ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n ...(options.isStructure !== undefined ? { isStructure: options.isStructure } : {}),\n ...(options.output_structure !== undefined ? { output_structure: options.output_structure } : {}),\n ...(options.history !== undefined ? { history: options.history } : {}),\n ...(options.attachments !== undefined ? { attachments: options.attachments } : {}),\n }),\n });\n\n if (!response.ok) {\n let errorMessage = `AI server returned HTTP ${response.status} for /generate`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n\n const data = (await response.json()) as any;\n\n // If isStructure was set, return the full object.\n if (options.isStructure) {\n return data as T;\n }\n\n // Otherwise return text/content/message or empty string\n return (data.text ?? data.content ?? data.message ?? '') as T;\n }\n}\n","/**\n * @krutai/ai-provider — AI Provider package for KrutAI\n *\n * A fetch-based wrapper that calls your deployed LangChain backend server.\n * The user's API key is validated against the server before any AI call is made.\n *\n * @example Basic usage\n * ```typescript\n * import { krutAI } from '@krutai/ai-provider';\n *\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await ai.initialize(); // validates key with server\n *\n * const text = await ai.chat('Write a poem about TypeScript');\n * console.log(text);\n * ```\n *\n * @example With custom model\n * ```typescript\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * model: 'gemini-3.1-pro-preview',\n * });\n * await ai.initialize();\n * const text = await ai.chat('Hello!');\n * ```\n *\n * @example Streaming\n * ```typescript\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n * await ai.initialize();\n *\n * const response = await ai.streamChatResponse([{ role: 'user', content: 'Tell me a story' }]);\n * // Example assumes you handle the SSE stream from the response body\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { KrutAIProviderConfig } from './types';\nimport { DEFAULT_MODEL } from './types';\nimport { KrutAIProvider } from './client';\n\nexport { KrutAIProvider } from './client';\nexport { KrutAIKeyValidationError } from './client';\nexport {\n validateApiKeyWithService as validateApiKey,\n validateApiKeyFormat,\n} from 'krutai';\nexport type { KrutAIProviderConfig, GenerateOptions, ChatMessage } from './types';\nexport { DEFAULT_MODEL } from './types';\n\n/**\n * krutAI — convenience factory (mirrors `krutAuth` in @krutai/auth).\n *\n * Creates a `KrutAIProvider` instance configured to call your LangChain server.\n *\n * @param config - Provider configuration (`apiKey` and `serverUrl` are required)\n * @returns A `KrutAIProvider` instance — call `.initialize()` before use\n *\n * @example\n * ```typescript\n * import { krutAI } from '@krutai/ai-provider';\n *\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await ai.initialize();\n * const text = await ai.chat('Hello!');\n * ```\n */\nexport function krutAI(\n config: KrutAIProviderConfig & { model?: string }\n): KrutAIProvider {\n return new KrutAIProvider({\n model: DEFAULT_MODEL,\n ...config,\n });\n}\n\n// Package metadata\nexport const VERSION = '0.2.15';\n"]}
|
|
1
|
+
{"version":3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MAAA,GAAY,EAAE,WAAA,EAAa,OAAA,CAAQ,WAAA,EAAY,GAAI;AAAC,OACnF;AAAA,KACJ,CAAA;AAED,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AACd,MAAA,IAAI,YAAA,GAAe,CAAA,wBAAA,EAA2B,QAAA,CAAS,MAAM,CAAA,cAAA,CAAA;AAC7D,MAAA,IAAI;AACA,QAAA,MAAM,SAAA,GAAa,MAAM,QAAA,CAAS,IAAA,EAAK;AACvC,QAAA,IAAI,SAAA,EAAW,KAAA,EAAO,YAAA,GAAe,SAAA,CAAU,KAAA;AAAA,aAAA,IACtC,SAAA,EAAW,OAAA,EAAS,YAAA,GAAe,SAAA,CAAU,OAAA;AAAA,MAC1D,CAAA,CAAA,MAAQ;AAAA,MAAE;AACV,MAAA,MAAM,IAAI,MAAM,YAAY,CAAA;AAAA,IAChC;AAEA,IAAA,MAAM,IAAA,GAAQ,MAAM,QAAA,CAAS,IAAA,EAAK;AAGlC,IAAA,IAAI,QAAQ,WAAA,EAAa;AACrB,MAAA,OAAO,IAAA;AAAA,IACX;AAGA,IAAA,OAAQ,IAAA,CAAK,IAAA,IAAQ,IAAA,CAAK,OAAA,IAAW,KAAK,OAAA,IAAW,EAAA;AAAA,EACzD;AACJ;AC/HO,SAAS,OACZ,MAAA,EACc;AACd,EAAA,OAAO,IAAI,cAAA,CAAe;AAAA,IACtB,KAAA,EAAO,aAAA;AAAA,IACP,GAAG;AAAA,GACN,CAAA;AACL;AAGO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * Types for @krutai/ai-provider\n */\n\n/**\n * Default model identifier sent to the LangChain server when no model is specified.\n * Your server can use this value to route to its own default model.\n */\nexport const DEFAULT_MODEL = 'gemini-3.1-pro-preview' as const;\n\n/**\n * Default base URL for the LangChain backend server.\n * Used when no serverUrl is provided in the config.\n */\nexport const DEFAULT_SERVER_URL = 'http://localhost:8000' as const;\n\n// ============================================================================\n// Comparison Types\n// ============================================================================\n\nexport interface DataRecord {\n [key: string]: unknown;\n}\n\nexport interface FileSchema {\n name: string;\n rowCount: number;\n columns: string[];\n sample: DataRecord[];\n}\n\nexport interface ComparisonSummary {\n totalRows: number;\n differencesFound: number;\n matchesFound: number;\n status: string;\n}\n\nexport interface ComparisonCodeResult {\n code: string;\n humanExplanation: string[];\n constants?: Record<string, unknown>;\n}\n\nexport interface ComparisonResult {\n summary: ComparisonSummary;\n metadata?: {\n file1Columns?: string[];\n file2Columns?: string[];\n executionTime?: number;\n };\n}\n\nexport interface ComparisonResponse {\n success: boolean;\n result?: ComparisonResult;\n generatedCode?: string;\n humanExplanation?: string[];\n downloadUrl?: string;\n fileName?: string;\n error?: string;\n}\n\nexport interface PreviewResponse {\n success: boolean;\n file1?: FileSchema;\n file2?: FileSchema;\n error?: string;\n}\n\nexport interface GenerateCodeOptions {\n prompt?: string;\n}\n\nexport interface CompareFilesOptions {\n code: string;\n prompt?: string;\n}\n\n/**\n * Configuration options for KrutAIProvider\n */\nexport interface KrutAIProviderConfig {\n /**\n * KrutAI API key.\n * Validated against the LangChain server before use.\n * Optional: defaults to process.env.KRUTAI_API_KEY\n */\n apiKey?: string;\n\n /**\n * Base URL of your deployed LangChain backend server.\n * @default \"http://localhost:8000\"\n * @example \"https://ai.krut.ai\"\n */\n serverUrl?: string;\n\n /**\n * The AI model to use (passed to the server).\n * The server decides what to do with this value.\n * @default \"default\"\n */\n model?: string;\n\n /**\n * Whether to validate the API key against the server on initialization.\n * Set to false to skip the validation round-trip (e.g. in tests).\n * @default true\n */\n validateOnInit?: boolean;\n}\n\n/**\n * A part of a multimodal message\n */\nexport interface TextContentPart {\n type: 'text';\n text: string;\n}\n\nexport interface ImageContentPart {\n type: 'image_url';\n image_url: {\n url: string; // Base64 data URI or HTTP(S) URL\n detail?: 'low' | 'high' | 'auto';\n };\n}\n\nexport type ContentPart = TextContentPart | ImageContentPart;\nexport type MessageContent = string | ContentPart[];\n\n/**\n * A single chat message\n */\nexport interface ChatMessage {\n role: 'user' | 'assistant' | 'system';\n content: MessageContent;\n}\n\n/**\n * Options for a single generate / stream / chat call\n */\nexport interface GenerateOptions {\n /**\n * Override the model for this specific call.\n */\n model?: string;\n\n /**\n * System prompt (prepended as a system message).\n */\n system?: string;\n\n /**\n * Maximum tokens to generate.\n */\n maxTokens?: number;\n\n /**\n * Temperature (0–2).\n */\n temperature?: number;\n\n /**\n * Array of image URLs or base64 data URIs to include with the request.\n */\n images?: string[];\n\n /**\n * Array of document URLs or base64 data URIs (e.g. PDFs) to include with the request.\n */\n documents?: string[];\n\n /**\n * Array of PDF URLs or base64 data URIs to include with the request.\n */\n pdf?: string[];\n\n /**\n * Optional conversation history.\n */\n history?: ChatMessage[];\n\n /**\n * Optional attachments.\n */\n attachments?: any[];\n\n /**\n * Whether to return structured output.\n */\n isStructure?: boolean;\n\n /**\n * The schema for structured output.\n * Can be a JSON Schema object or an array of field names.\n */\n output_structure?: any;\n}\n","import type {\n KrutAIProviderConfig,\n GenerateOptions,\n ChatMessage,\n} from './types';\nimport { DEFAULT_MODEL, DEFAULT_SERVER_URL } from './types';\nimport {\n validateApiKey,\n validateApiKeyFormat,\n KrutAIKeyValidationError,\n} from 'krutai';\n\nexport { KrutAIKeyValidationError };\n\n/**\n * KrutAIProvider — fetch-based AI provider for KrutAI\n *\n * Calls your deployed LangChain backend server for all AI operations.\n * The API key is validated against the server before use.\n *\n * @example\n * ```typescript\n * import { KrutAIProvider } from '@krutai/ai-provider';\n *\n * // Using local dev server (http://localhost:8000 by default)\n * const ai = new KrutAIProvider({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * });\n *\n * // Or point to a production server\n * const aiProd = new KrutAIProvider({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://ai.krut.ai',\n * });\n *\n * await ai.initialize(); // validates key against server\n *\n * const text = await ai.generate('Tell me a joke');\n * console.log(text);\n * ```\n */\nexport class KrutAIProvider {\n private readonly apiKey: string;\n private readonly serverUrl: string;\n private readonly resolvedModel: string;\n private readonly config: KrutAIProviderConfig;\n\n private initialized = false;\n\n constructor(config: KrutAIProviderConfig) {\n this.config = config;\n this.apiKey = config.apiKey || process.env.KRUTAI_API_KEY || '';\n this.serverUrl = (config.serverUrl ?? DEFAULT_SERVER_URL).replace(/\\/$/, ''); // strip trailing slash\n this.resolvedModel = config.model ?? DEFAULT_MODEL;\n\n // Basic format check immediately on construction\n validateApiKeyFormat(this.apiKey);\n\n // If validation is disabled, mark as ready immediately\n if (config.validateOnInit === false) {\n this.initialized = true;\n }\n }\n\n /**\n * Initialize the provider.\n * Validates the API key against the LangChain server, then marks provider as ready.\n *\n * @throws {KrutAIKeyValidationError} if the key is rejected or the server is unreachable\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n if (this.config.validateOnInit !== false) {\n await validateApiKey(this.apiKey, this.serverUrl);\n }\n\n this.initialized = true;\n }\n\n /**\n * Returns the currently configured default model.\n */\n getModel(): string {\n return this.resolvedModel;\n }\n\n /**\n * Returns whether the provider has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private assertInitialized(): void {\n if (!this.initialized) {\n throw new Error(\n 'KrutAIProvider not initialized. Call initialize() first or set validateOnInit to false.'\n );\n }\n }\n\n /** Common request headers sent to the server on every AI call. */\n private authHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'x-api-key': this.apiKey,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Public AI Methods\n // ---------------------------------------------------------------------------\n\n /**\n * Similar to streamChat() but returns the raw fetch Response object.\n * Useful for proxying the Server-Sent Events stream directly to a frontend client.\n *\n * @param messages - Full conversation history\n * @param options - Optional overrides (model, maxTokens, temperature)\n * @returns A Promise resolving to the native fetch Response\n */\n async streamChatResponse(messages: ChatMessage[], options: GenerateOptions = {}): Promise<Response> {\n this.assertInitialized();\n\n if (!messages.length) {\n throw new Error('Messages array cannot be empty for streamChatResponse');\n }\n\n const model = options.model ?? this.resolvedModel;\n\n const response = await fetch(`${this.serverUrl}/stream`, {\n method: 'POST',\n headers: {\n ...this.authHeaders(),\n Accept: 'text/event-stream',\n },\n body: JSON.stringify({\n messages,\n model,\n ...(options.system !== undefined ? { system: options.system } : {}),\n ...(options.images !== undefined ? { images: options.images } : {}),\n ...(options.documents !== undefined ? { documents: options.documents } : {}),\n ...(options.pdf !== undefined ? { pdf: options.pdf } : {}),\n ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n }),\n });\n\n if (!response.ok) {\n let errorMessage = `AI server returned HTTP ${response.status} for /stream`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n\n return response;\n }\n\n /**\n * Generate a response for a prompt (non-streaming).\n *\n * Calls: POST {serverUrl}/generate\n * Body: { prompt, model, system?, maxTokens?, temperature? }\n * Expected response: { text: string } or { content: string } or { message: string }\n *\n * @param prompt - The user prompt string\n * @param options - Optional overrides (model, system, maxTokens, temperature)\n * @returns The assistant's response text (or an object if structured)\n */\n async chat<T = any>(prompt: string, options: GenerateOptions = {}): Promise<T> {\n this.assertInitialized();\n const model = options.model ?? this.resolvedModel;\n\n const response = await fetch(`${this.serverUrl}/generate`, {\n method: 'POST',\n headers: this.authHeaders(),\n body: JSON.stringify({\n prompt,\n model,\n ...(options.system !== undefined ? { system: options.system } : {}),\n ...(options.images !== undefined ? { images: options.images } : {}),\n ...(options.documents !== undefined ? { documents: options.documents } : {}),\n ...(options.pdf !== undefined ? { pdf: options.pdf } : {}),\n ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n ...(options.isStructure !== undefined ? { isStructure: options.isStructure } : {}),\n ...(options.output_structure !== undefined ? { output_structure: options.output_structure } : {}),\n ...(options.history !== undefined ? { history: options.history } : {}),\n ...(options.attachments !== undefined ? { attachments: options.attachments } : {}),\n }),\n });\n\n if (!response.ok) {\n let errorMessage = `AI server returned HTTP ${response.status} for /generate`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n\n const data = (await response.json()) as any;\n\n // If isStructure was set, return the full object.\n if (options.isStructure) {\n return data as T;\n }\n\n // Otherwise return text/content/message or empty string\n return (data.text ?? data.content ?? data.message ?? '') as T;\n }\n}\n","/**\n * @krutai/ai-provider — AI Provider package for KrutAI\n *\n * A fetch-based wrapper that calls your deployed LangChain backend server.\n * The user's API key is validated against the server before any AI call is made.\n *\n * @example Basic usage\n * ```typescript\n * import { krutAI } from '@krutai/ai-provider';\n *\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await ai.initialize(); // validates key with server\n *\n * const text = await ai.chat('Write a poem about TypeScript');\n * console.log(text);\n * ```\n *\n * @example With custom model\n * ```typescript\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * model: 'gemini-3.1-pro-preview',\n * });\n * await ai.initialize();\n * const text = await ai.chat('Hello!');\n * ```\n *\n * @example Streaming\n * ```typescript\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n * await ai.initialize();\n *\n * const response = await ai.streamChatResponse([{ role: 'user', content: 'Tell me a story' }]);\n * // Example assumes you handle the SSE stream from the response body\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { KrutAIProviderConfig } from './types';\nimport { DEFAULT_MODEL } from './types';\nimport { KrutAIProvider } from './client';\n\nexport { KrutAIProvider } from './client';\nexport { KrutAIKeyValidationError } from './client';\nexport {\n validateApiKeyWithService as validateApiKey,\n validateApiKeyFormat,\n} from 'krutai';\nexport type {\n KrutAIProviderConfig,\n GenerateOptions,\n ChatMessage,\n DataRecord,\n FileSchema,\n ComparisonSummary,\n ComparisonCodeResult,\n ComparisonResult,\n ComparisonResponse,\n PreviewResponse,\n GenerateCodeOptions,\n CompareFilesOptions,\n} from './types';\nexport { DEFAULT_MODEL } from './types';\n\n/**\n * krutAI — convenience factory (mirrors `krutAuth` in @krutai/auth).\n *\n * Creates a `KrutAIProvider` instance configured to call your LangChain server.\n *\n * @param config - Provider configuration (`apiKey` and `serverUrl` are required)\n * @returns A `KrutAIProvider` instance — call `.initialize()` before use\n *\n * @example\n * ```typescript\n * import { krutAI } from '@krutai/ai-provider';\n *\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await ai.initialize();\n * const text = await ai.chat('Hello!');\n * ```\n */\nexport function krutAI(\n config: KrutAIProviderConfig & { model?: string }\n): KrutAIProvider {\n return new KrutAIProvider({\n model: DEFAULT_MODEL,\n ...config,\n });\n}\n\n// Package metadata\nexport const VERSION = '0.3.4';\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { validateApiKeyFormat,
|
|
2
|
-
export {
|
|
1
|
+
import { validateApiKeyFormat, validateApiKey } from 'krutai';
|
|
2
|
+
export { KrutAIKeyValidationError, validateApiKeyWithService as validateApiKey, validateApiKeyFormat } from 'krutai';
|
|
3
3
|
|
|
4
4
|
// src/types.ts
|
|
5
5
|
var DEFAULT_MODEL = "gemini-3.1-pro-preview";
|
|
@@ -29,7 +29,7 @@ var KrutAIProvider = class {
|
|
|
29
29
|
async initialize() {
|
|
30
30
|
if (this.initialized) return;
|
|
31
31
|
if (this.config.validateOnInit !== false) {
|
|
32
|
-
await
|
|
32
|
+
await validateApiKey(this.apiKey, this.serverUrl);
|
|
33
33
|
}
|
|
34
34
|
this.initialized = true;
|
|
35
35
|
}
|
|
@@ -164,7 +164,7 @@ function krutAI(config) {
|
|
|
164
164
|
...config
|
|
165
165
|
});
|
|
166
166
|
}
|
|
167
|
-
var VERSION = "0.
|
|
167
|
+
var VERSION = "0.3.4";
|
|
168
168
|
|
|
169
169
|
export { DEFAULT_MODEL, KrutAIProvider, VERSION, krutAI };
|
|
170
170
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/client.ts","../src/index.ts"],"names":["validateApiKey"],"mappings":";;;;AAQO,IAAM,aAAA,GAAgB;AAMtB,IAAM,kBAAA,GAAqB,uBAAA;ACuB3B,IAAM,iBAAN,MAAqB;AAAA,EACP,MAAA;AAAA,EACA,SAAA;AAAA,EACA,aAAA;AAAA,EACA,MAAA;AAAA,EAET,WAAA,GAAc,KAAA;AAAA,EAEtB,YAAY,MAAA,EAA8B;AACtC,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA,CAAO,MAAA,IAAU,OAAA,CAAQ,IAAI,cAAA,IAAkB,EAAA;AAC7D,IAAA,IAAA,CAAK,aAAa,MAAA,CAAO,SAAA,IAAa,kBAAA,EAAoB,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC3E,IAAA,IAAA,CAAK,aAAA,GAAgB,OAAO,KAAA,IAAS,aAAA;AAGrC,IAAA,oBAAA,CAAqB,KAAK,MAAM,CAAA;AAGhC,IAAA,IAAI,MAAA,CAAO,mBAAmB,KAAA,EAAO;AACjC,MAAA,IAAA,CAAK,WAAA,GAAc,IAAA;AAAA,IACvB;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,UAAA,GAA4B;AAC9B,IAAA,IAAI,KAAK,WAAA,EAAa;AAEtB,IAAA,IAAI,IAAA,CAAK,MAAA,CAAO,cAAA,KAAmB,KAAA,E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AA,GAAU","file":"index.mjs","sourcesContent":["/**\n * Types for @krutai/ai-provider\n */\n\n/**\n * Default model identifier sent to the LangChain server when no model is specified.\n * Your server can use this value to route to its own default model.\n */\nexport const DEFAULT_MODEL = 'gemini-3.1-pro-preview' as const;\n\n/**\n * Default base URL for the LangChain backend server.\n * Used when no serverUrl is provided in the config.\n */\nexport const DEFAULT_SERVER_URL = 'http://localhost:8000' as const;\n\n/**\n * Configuration options for KrutAIProvider\n */\nexport interface KrutAIProviderConfig {\n /**\n * KrutAI API key.\n * Validated against the LangChain server before use.\n * Optional: defaults to process.env.KRUTAI_API_KEY\n */\n apiKey?: string;\n\n /**\n * Base URL of your deployed LangChain backend server.\n * @default \"http://localhost:8000\"\n * @example \"https://ai.krut.ai\"\n */\n serverUrl?: string;\n\n /**\n * The AI model to use (passed to the server).\n * The server decides what to do with this value.\n * @default \"default\"\n */\n model?: string;\n\n /**\n * Whether to validate the API key against the server on initialization.\n * Set to false to skip the validation round-trip (e.g. in tests).\n * @default true\n */\n validateOnInit?: boolean;\n}\n\n/**\n * A part of a multimodal message\n */\nexport interface TextContentPart {\n type: 'text';\n text: string;\n}\n\nexport interface ImageContentPart {\n type: 'image_url';\n image_url: {\n url: string; // Base64 data URI or HTTP(S) URL\n detail?: 'low' | 'high' | 'auto';\n };\n}\n\nexport type ContentPart = TextContentPart | ImageContentPart;\nexport type MessageContent = string | ContentPart[];\n\n/**\n * A single chat message\n */\nexport interface ChatMessage {\n role: 'user' | 'assistant' | 'system';\n content: MessageContent;\n}\n\n/**\n * Options for a single generate / stream / chat call\n */\nexport interface GenerateOptions {\n /**\n * Override the model for this specific call.\n */\n model?: string;\n\n /**\n * System prompt (prepended as a system message).\n */\n system?: string;\n\n /**\n * Maximum tokens to generate.\n */\n maxTokens?: number;\n\n /**\n * Temperature (0–2).\n */\n temperature?: number;\n\n /**\n * Array of image URLs or base64 data URIs to include with the request.\n */\n images?: string[];\n\n /**\n * Array of document URLs or base64 data URIs (e.g. PDFs) to include with the request.\n */\n documents?: string[];\n\n /**\n * Array of PDF URLs or base64 data URIs to include with the request.\n */\n pdf?: string[];\n\n /**\n * Optional conversation history.\n */\n history?: ChatMessage[];\n\n /**\n * Optional attachments.\n */\n attachments?: any[];\n\n /**\n * Whether to return structured output.\n */\n isStructure?: boolean;\n\n /**\n * The schema for structured output.\n * Can be a JSON Schema object or an array of field names.\n */\n output_structure?: any;\n}\n","import type { KrutAIProviderConfig, GenerateOptions, ChatMessage } from './types';\nimport { DEFAULT_MODEL, DEFAULT_SERVER_URL } from './types';\nimport {\n validateApiKeyWithService as validateApiKey,\n validateApiKeyFormat,\n ApiKeyValidationError as KrutAIKeyValidationError,\n} from 'krutai';\n\nexport { KrutAIKeyValidationError };\n\n/**\n * KrutAIProvider — fetch-based AI provider for KrutAI\n *\n * Calls your deployed LangChain backend server for all AI operations.\n * The API key is validated against the server before use.\n *\n * @example\n * ```typescript\n * import { KrutAIProvider } from '@krutai/ai-provider';\n *\n * // Using local dev server (http://localhost:8000 by default)\n * const ai = new KrutAIProvider({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * });\n *\n * // Or point to a production server\n * const aiProd = new KrutAIProvider({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://ai.krut.ai',\n * });\n *\n * await ai.initialize(); // validates key against server\n *\n * const text = await ai.generate('Tell me a joke');\n * console.log(text);\n * ```\n */\nexport class KrutAIProvider {\n private readonly apiKey: string;\n private readonly serverUrl: string;\n private readonly resolvedModel: string;\n private readonly config: KrutAIProviderConfig;\n\n private initialized = false;\n\n constructor(config: KrutAIProviderConfig) {\n this.config = config;\n this.apiKey = config.apiKey || process.env.KRUTAI_API_KEY || '';\n this.serverUrl = (config.serverUrl ?? DEFAULT_SERVER_URL).replace(/\\/$/, ''); // strip trailing slash\n this.resolvedModel = config.model ?? DEFAULT_MODEL;\n\n // Basic format check immediately on construction\n validateApiKeyFormat(this.apiKey);\n\n // If validation is disabled, mark as ready immediately\n if (config.validateOnInit === false) {\n this.initialized = true;\n }\n }\n\n /**\n * Initialize the provider.\n * Validates the API key against the LangChain server, then marks provider as ready.\n *\n * @throws {KrutAIKeyValidationError} if the key is rejected or the server is unreachable\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n if (this.config.validateOnInit !== false) {\n await validateApiKey(this.apiKey, this.serverUrl);\n }\n\n this.initialized = true;\n }\n\n /**\n * Returns the currently configured default model.\n */\n getModel(): string {\n return this.resolvedModel;\n }\n\n /**\n * Returns whether the provider has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private assertInitialized(): void {\n if (!this.initialized) {\n throw new Error(\n 'KrutAIProvider not initialized. Call initialize() first or set validateOnInit to false.'\n );\n }\n }\n\n /** Common request headers sent to the server on every AI call. */\n private authHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'x-api-key': this.apiKey,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Public AI Methods\n // ---------------------------------------------------------------------------\n\n /**\n * Similar to streamChat() but returns the raw fetch Response object.\n * Useful for proxying the Server-Sent Events stream directly to a frontend client.\n *\n * @param messages - Full conversation history\n * @param options - Optional overrides (model, maxTokens, temperature)\n * @returns A Promise resolving to the native fetch Response\n */\n async streamChatResponse(messages: ChatMessage[], options: GenerateOptions = {}): Promise<Response> {\n this.assertInitialized();\n\n if (!messages.length) {\n throw new Error('Messages array cannot be empty for streamChatResponse');\n }\n\n const model = options.model ?? this.resolvedModel;\n\n const response = await fetch(`${this.serverUrl}/stream`, {\n method: 'POST',\n headers: {\n ...this.authHeaders(),\n Accept: 'text/event-stream',\n },\n body: JSON.stringify({\n messages,\n model,\n ...(options.system !== undefined ? { system: options.system } : {}),\n ...(options.images !== undefined ? { images: options.images } : {}),\n ...(options.documents !== undefined ? { documents: options.documents } : {}),\n ...(options.pdf !== undefined ? { pdf: options.pdf } : {}),\n ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n }),\n });\n\n if (!response.ok) {\n let errorMessage = `AI server returned HTTP ${response.status} for /stream`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n\n return response;\n }\n\n /**\n * Generate a response for a prompt (non-streaming).\n *\n * Calls: POST {serverUrl}/generate\n * Body: { prompt, model, system?, maxTokens?, temperature? }\n * Expected response: { text: string } or { content: string } or { message: string }\n *\n * @param prompt - The user prompt string\n * @param options - Optional overrides (model, system, maxTokens, temperature)\n * @returns The assistant's response text (or an object if structured)\n */\n async chat<T = any>(prompt: string, options: GenerateOptions = {}): Promise<T> {\n this.assertInitialized();\n const model = options.model ?? this.resolvedModel;\n\n const response = await fetch(`${this.serverUrl}/generate`, {\n method: 'POST',\n headers: this.authHeaders(),\n body: JSON.stringify({\n prompt,\n model,\n ...(options.system !== undefined ? { system: options.system } : {}),\n ...(options.images !== undefined ? { images: options.images } : {}),\n ...(options.documents !== undefined ? { documents: options.documents } : {}),\n ...(options.pdf !== undefined ? { pdf: options.pdf } : {}),\n ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n ...(options.isStructure !== undefined ? { isStructure: options.isStructure } : {}),\n ...(options.output_structure !== undefined ? { output_structure: options.output_structure } : {}),\n ...(options.history !== undefined ? { history: options.history } : {}),\n ...(options.attachments !== undefined ? { attachments: options.attachments } : {}),\n }),\n });\n\n if (!response.ok) {\n let errorMessage = `AI server returned HTTP ${response.status} for /generate`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n\n const data = (await response.json()) as any;\n\n // If isStructure was set, return the full object.\n if (options.isStructure) {\n return data as T;\n }\n\n // Otherwise return text/content/message or empty string\n return (data.text ?? data.content ?? data.message ?? '') as T;\n }\n}\n","/**\n * @krutai/ai-provider — AI Provider package for KrutAI\n *\n * A fetch-based wrapper that calls your deployed LangChain backend server.\n * The user's API key is validated against the server before any AI call is made.\n *\n * @example Basic usage\n * ```typescript\n * import { krutAI } from '@krutai/ai-provider';\n *\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await ai.initialize(); // validates key with server\n *\n * const text = await ai.chat('Write a poem about TypeScript');\n * console.log(text);\n * ```\n *\n * @example With custom model\n * ```typescript\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * model: 'gemini-3.1-pro-preview',\n * });\n * await ai.initialize();\n * const text = await ai.chat('Hello!');\n * ```\n *\n * @example Streaming\n * ```typescript\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n * await ai.initialize();\n *\n * const response = await ai.streamChatResponse([{ role: 'user', content: 'Tell me a story' }]);\n * // Example assumes you handle the SSE stream from the response body\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { KrutAIProviderConfig } from './types';\nimport { DEFAULT_MODEL } from './types';\nimport { KrutAIProvider } from './client';\n\nexport { KrutAIProvider } from './client';\nexport { KrutAIKeyValidationError } from './client';\nexport {\n validateApiKeyWithService as validateApiKey,\n validateApiKeyFormat,\n} from 'krutai';\nexport type { KrutAIProviderConfig, GenerateOptions, ChatMessage } from './types';\nexport { DEFAULT_MODEL } from './types';\n\n/**\n * krutAI — convenience factory (mirrors `krutAuth` in @krutai/auth).\n *\n * Creates a `KrutAIProvider` instance configured to call your LangChain server.\n *\n * @param config - Provider configuration (`apiKey` and `serverUrl` are required)\n * @returns A `KrutAIProvider` instance — call `.initialize()` before use\n *\n * @example\n * ```typescript\n * import { krutAI } from '@krutai/ai-provider';\n *\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await ai.initialize();\n * const text = await ai.chat('Hello!');\n * ```\n */\nexport function krutAI(\n config: KrutAIProviderConfig & { model?: string }\n): KrutAIProvider {\n return new KrutAIProvider({\n model: DEFAULT_MODEL,\n ...config,\n });\n}\n\n// Package metadata\nexport const VERSION = '0.2.15';\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/client.ts","../src/index.ts"],"names":[],"mappings":";;;;AAQO,IAAM,aAAA,GAAgB;AAMtB,IAAM,kBAAA,GAAqB,uBAAA;AC2B3B,IAAM,iBAAN,MAAqB;AAAA,EACP,MAAA;AAAA,EACA,SAAA;AAAA,EACA,aAAA;AAAA,EACA,MAAA;AAAA,EAET,WAAA,GAAc,KAAA;AAAA,EAEtB,YAAY,MAAA,EAA8B;AACtC,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA,CAAO,MAAA,IAAU,OAAA,CAAQ,IAAI,cAAA,IAAkB,EAAA;AAC7D,IAAA,IAAA,CAAK,aAAa,MAAA,CAAO,SAAA,IAAa,kBAAA,EAAoB,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC3E,IAAA,IAAA,CAAK,aAAA,GAAgB,OAAO,KAAA,IAAS,aAAA;AAGrC,IAAA,oBAAA,CAAqB,KAAK,MAAM,CAAA;AAGhC,IAAA,IAAI,MAAA,CAAO,mBAAmB,KAAA,EAAO;AACjC,MAAA,IAAA,CAAK,WAAA,GAAc,IAAA;AAAA,IACvB;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,UAAA,GAA4B;AAC9B,IAAA,IAAI,KAAK,WAAA,EAAa;AAEtB,IAAA,IAAI,IAAA,CAAK,MAAA,CAAO,cAAA,KAAmB,KAAA,EAAO;AAC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file":"index.mjs","sourcesContent":["/**\n * Types for @krutai/ai-provider\n */\n\n/**\n * Default model identifier sent to the LangChain server when no model is specified.\n * Your server can use this value to route to its own default model.\n */\nexport const DEFAULT_MODEL = 'gemini-3.1-pro-preview' as const;\n\n/**\n * Default base URL for the LangChain backend server.\n * Used when no serverUrl is provided in the config.\n */\nexport const DEFAULT_SERVER_URL = 'http://localhost:8000' as const;\n\n// ============================================================================\n// Comparison Types\n// ============================================================================\n\nexport interface DataRecord {\n [key: string]: unknown;\n}\n\nexport interface FileSchema {\n name: string;\n rowCount: number;\n columns: string[];\n sample: DataRecord[];\n}\n\nexport interface ComparisonSummary {\n totalRows: number;\n differencesFound: number;\n matchesFound: number;\n status: string;\n}\n\nexport interface ComparisonCodeResult {\n code: string;\n humanExplanation: string[];\n constants?: Record<string, unknown>;\n}\n\nexport interface ComparisonResult {\n summary: ComparisonSummary;\n metadata?: {\n file1Columns?: string[];\n file2Columns?: string[];\n executionTime?: number;\n };\n}\n\nexport interface ComparisonResponse {\n success: boolean;\n result?: ComparisonResult;\n generatedCode?: string;\n humanExplanation?: string[];\n downloadUrl?: string;\n fileName?: string;\n error?: string;\n}\n\nexport interface PreviewResponse {\n success: boolean;\n file1?: FileSchema;\n file2?: FileSchema;\n error?: string;\n}\n\nexport interface GenerateCodeOptions {\n prompt?: string;\n}\n\nexport interface CompareFilesOptions {\n code: string;\n prompt?: string;\n}\n\n/**\n * Configuration options for KrutAIProvider\n */\nexport interface KrutAIProviderConfig {\n /**\n * KrutAI API key.\n * Validated against the LangChain server before use.\n * Optional: defaults to process.env.KRUTAI_API_KEY\n */\n apiKey?: string;\n\n /**\n * Base URL of your deployed LangChain backend server.\n * @default \"http://localhost:8000\"\n * @example \"https://ai.krut.ai\"\n */\n serverUrl?: string;\n\n /**\n * The AI model to use (passed to the server).\n * The server decides what to do with this value.\n * @default \"default\"\n */\n model?: string;\n\n /**\n * Whether to validate the API key against the server on initialization.\n * Set to false to skip the validation round-trip (e.g. in tests).\n * @default true\n */\n validateOnInit?: boolean;\n}\n\n/**\n * A part of a multimodal message\n */\nexport interface TextContentPart {\n type: 'text';\n text: string;\n}\n\nexport interface ImageContentPart {\n type: 'image_url';\n image_url: {\n url: string; // Base64 data URI or HTTP(S) URL\n detail?: 'low' | 'high' | 'auto';\n };\n}\n\nexport type ContentPart = TextContentPart | ImageContentPart;\nexport type MessageContent = string | ContentPart[];\n\n/**\n * A single chat message\n */\nexport interface ChatMessage {\n role: 'user' | 'assistant' | 'system';\n content: MessageContent;\n}\n\n/**\n * Options for a single generate / stream / chat call\n */\nexport interface GenerateOptions {\n /**\n * Override the model for this specific call.\n */\n model?: string;\n\n /**\n * System prompt (prepended as a system message).\n */\n system?: string;\n\n /**\n * Maximum tokens to generate.\n */\n maxTokens?: number;\n\n /**\n * Temperature (0–2).\n */\n temperature?: number;\n\n /**\n * Array of image URLs or base64 data URIs to include with the request.\n */\n images?: string[];\n\n /**\n * Array of document URLs or base64 data URIs (e.g. PDFs) to include with the request.\n */\n documents?: string[];\n\n /**\n * Array of PDF URLs or base64 data URIs to include with the request.\n */\n pdf?: string[];\n\n /**\n * Optional conversation history.\n */\n history?: ChatMessage[];\n\n /**\n * Optional attachments.\n */\n attachments?: any[];\n\n /**\n * Whether to return structured output.\n */\n isStructure?: boolean;\n\n /**\n * The schema for structured output.\n * Can be a JSON Schema object or an array of field names.\n */\n output_structure?: any;\n}\n","import type {\n KrutAIProviderConfig,\n GenerateOptions,\n ChatMessage,\n} from './types';\nimport { DEFAULT_MODEL, DEFAULT_SERVER_URL } from './types';\nimport {\n validateApiKey,\n validateApiKeyFormat,\n KrutAIKeyValidationError,\n} from 'krutai';\n\nexport { KrutAIKeyValidationError };\n\n/**\n * KrutAIProvider — fetch-based AI provider for KrutAI\n *\n * Calls your deployed LangChain backend server for all AI operations.\n * The API key is validated against the server before use.\n *\n * @example\n * ```typescript\n * import { KrutAIProvider } from '@krutai/ai-provider';\n *\n * // Using local dev server (http://localhost:8000 by default)\n * const ai = new KrutAIProvider({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * });\n *\n * // Or point to a production server\n * const aiProd = new KrutAIProvider({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://ai.krut.ai',\n * });\n *\n * await ai.initialize(); // validates key against server\n *\n * const text = await ai.generate('Tell me a joke');\n * console.log(text);\n * ```\n */\nexport class KrutAIProvider {\n private readonly apiKey: string;\n private readonly serverUrl: string;\n private readonly resolvedModel: string;\n private readonly config: KrutAIProviderConfig;\n\n private initialized = false;\n\n constructor(config: KrutAIProviderConfig) {\n this.config = config;\n this.apiKey = config.apiKey || process.env.KRUTAI_API_KEY || '';\n this.serverUrl = (config.serverUrl ?? DEFAULT_SERVER_URL).replace(/\\/$/, ''); // strip trailing slash\n this.resolvedModel = config.model ?? DEFAULT_MODEL;\n\n // Basic format check immediately on construction\n validateApiKeyFormat(this.apiKey);\n\n // If validation is disabled, mark as ready immediately\n if (config.validateOnInit === false) {\n this.initialized = true;\n }\n }\n\n /**\n * Initialize the provider.\n * Validates the API key against the LangChain server, then marks provider as ready.\n *\n * @throws {KrutAIKeyValidationError} if the key is rejected or the server is unreachable\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n if (this.config.validateOnInit !== false) {\n await validateApiKey(this.apiKey, this.serverUrl);\n }\n\n this.initialized = true;\n }\n\n /**\n * Returns the currently configured default model.\n */\n getModel(): string {\n return this.resolvedModel;\n }\n\n /**\n * Returns whether the provider has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private assertInitialized(): void {\n if (!this.initialized) {\n throw new Error(\n 'KrutAIProvider not initialized. Call initialize() first or set validateOnInit to false.'\n );\n }\n }\n\n /** Common request headers sent to the server on every AI call. */\n private authHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'x-api-key': this.apiKey,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Public AI Methods\n // ---------------------------------------------------------------------------\n\n /**\n * Similar to streamChat() but returns the raw fetch Response object.\n * Useful for proxying the Server-Sent Events stream directly to a frontend client.\n *\n * @param messages - Full conversation history\n * @param options - Optional overrides (model, maxTokens, temperature)\n * @returns A Promise resolving to the native fetch Response\n */\n async streamChatResponse(messages: ChatMessage[], options: GenerateOptions = {}): Promise<Response> {\n this.assertInitialized();\n\n if (!messages.length) {\n throw new Error('Messages array cannot be empty for streamChatResponse');\n }\n\n const model = options.model ?? this.resolvedModel;\n\n const response = await fetch(`${this.serverUrl}/stream`, {\n method: 'POST',\n headers: {\n ...this.authHeaders(),\n Accept: 'text/event-stream',\n },\n body: JSON.stringify({\n messages,\n model,\n ...(options.system !== undefined ? { system: options.system } : {}),\n ...(options.images !== undefined ? { images: options.images } : {}),\n ...(options.documents !== undefined ? { documents: options.documents } : {}),\n ...(options.pdf !== undefined ? { pdf: options.pdf } : {}),\n ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n }),\n });\n\n if (!response.ok) {\n let errorMessage = `AI server returned HTTP ${response.status} for /stream`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n\n return response;\n }\n\n /**\n * Generate a response for a prompt (non-streaming).\n *\n * Calls: POST {serverUrl}/generate\n * Body: { prompt, model, system?, maxTokens?, temperature? }\n * Expected response: { text: string } or { content: string } or { message: string }\n *\n * @param prompt - The user prompt string\n * @param options - Optional overrides (model, system, maxTokens, temperature)\n * @returns The assistant's response text (or an object if structured)\n */\n async chat<T = any>(prompt: string, options: GenerateOptions = {}): Promise<T> {\n this.assertInitialized();\n const model = options.model ?? this.resolvedModel;\n\n const response = await fetch(`${this.serverUrl}/generate`, {\n method: 'POST',\n headers: this.authHeaders(),\n body: JSON.stringify({\n prompt,\n model,\n ...(options.system !== undefined ? { system: options.system } : {}),\n ...(options.images !== undefined ? { images: options.images } : {}),\n ...(options.documents !== undefined ? { documents: options.documents } : {}),\n ...(options.pdf !== undefined ? { pdf: options.pdf } : {}),\n ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n ...(options.isStructure !== undefined ? { isStructure: options.isStructure } : {}),\n ...(options.output_structure !== undefined ? { output_structure: options.output_structure } : {}),\n ...(options.history !== undefined ? { history: options.history } : {}),\n ...(options.attachments !== undefined ? { attachments: options.attachments } : {}),\n }),\n });\n\n if (!response.ok) {\n let errorMessage = `AI server returned HTTP ${response.status} for /generate`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n\n const data = (await response.json()) as any;\n\n // If isStructure was set, return the full object.\n if (options.isStructure) {\n return data as T;\n }\n\n // Otherwise return text/content/message or empty string\n return (data.text ?? data.content ?? data.message ?? '') as T;\n }\n}\n","/**\n * @krutai/ai-provider — AI Provider package for KrutAI\n *\n * A fetch-based wrapper that calls your deployed LangChain backend server.\n * The user's API key is validated against the server before any AI call is made.\n *\n * @example Basic usage\n * ```typescript\n * import { krutAI } from '@krutai/ai-provider';\n *\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await ai.initialize(); // validates key with server\n *\n * const text = await ai.chat('Write a poem about TypeScript');\n * console.log(text);\n * ```\n *\n * @example With custom model\n * ```typescript\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * model: 'gemini-3.1-pro-preview',\n * });\n * await ai.initialize();\n * const text = await ai.chat('Hello!');\n * ```\n *\n * @example Streaming\n * ```typescript\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n * await ai.initialize();\n *\n * const response = await ai.streamChatResponse([{ role: 'user', content: 'Tell me a story' }]);\n * // Example assumes you handle the SSE stream from the response body\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { KrutAIProviderConfig } from './types';\nimport { DEFAULT_MODEL } from './types';\nimport { KrutAIProvider } from './client';\n\nexport { KrutAIProvider } from './client';\nexport { KrutAIKeyValidationError } from './client';\nexport {\n validateApiKeyWithService as validateApiKey,\n validateApiKeyFormat,\n} from 'krutai';\nexport type {\n KrutAIProviderConfig,\n GenerateOptions,\n ChatMessage,\n DataRecord,\n FileSchema,\n ComparisonSummary,\n ComparisonCodeResult,\n ComparisonResult,\n ComparisonResponse,\n PreviewResponse,\n GenerateCodeOptions,\n CompareFilesOptions,\n} from './types';\nexport { DEFAULT_MODEL } from './types';\n\n/**\n * krutAI — convenience factory (mirrors `krutAuth` in @krutai/auth).\n *\n * Creates a `KrutAIProvider` instance configured to call your LangChain server.\n *\n * @param config - Provider configuration (`apiKey` and `serverUrl` are required)\n * @returns A `KrutAIProvider` instance — call `.initialize()` before use\n *\n * @example\n * ```typescript\n * import { krutAI } from '@krutai/ai-provider';\n *\n * const ai = krutAI({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await ai.initialize();\n * const text = await ai.chat('Hello!');\n * ```\n */\nexport function krutAI(\n config: KrutAIProviderConfig & { model?: string }\n): KrutAIProvider {\n return new KrutAIProvider({\n model: DEFAULT_MODEL,\n ...config,\n });\n}\n\n// Package metadata\nexport const VERSION = '0.3.4';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@krutai/ai-provider",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.5",
|
|
4
4
|
"description": "AI provider package for KrutAI — fetch-based client for your deployed LangChain server with API key validation",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|