@krutai/ai-provider 0.2.13 → 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/AI_REFERENCE.md CHANGED
@@ -3,7 +3,7 @@
3
3
  ## Package Overview
4
4
 
5
5
  - **Name**: `@krutai/ai-provider`
6
- - **Version**: `0.2.2`
6
+ - **Version**: `0.2.14`
7
7
  - **Purpose**: AI provider for KrutAI — fetch-based client for your deployed LangChain server with API key validation
8
8
  - **Entry**: `src/index.ts` → `dist/index.{js,mjs,d.ts}`
9
9
  - **Build**: `tsup` (CJS + ESM, no external SDK deps)
@@ -11,7 +11,7 @@
11
11
  ## Architecture
12
12
 
13
13
  ```
14
- @krutai/ai-provider@0.2.2
14
+ @krutai/ai-provider@0.2.14
15
15
  └── peerDep: krutai (core utilities)
16
16
 
17
17
  AI Flow:
@@ -41,7 +41,7 @@ packages/ai-provider/
41
41
  | Endpoint | Method | Body | Response |
42
42
  |---|---|---|---|
43
43
  | `/validate` | POST | `{ apiKey }` | `{ valid: true/false, message? }` |
44
- | `/generate` | POST | `{ prompt, model, system?, maxTokens?, temperature? }` | `{ text/content/message: string }` |
44
+ | `/generate` | POST | `{ prompt, model, system?, maxTokens?, temperature?, isStructure?, output_structure?, history?, attachments? }` | `{ text/content/message: string }` or `any` (if structured) |
45
45
  | `/stream` | POST | `{ messages, model, system?, maxTokens?, temperature? }` | SSE stream `data: <chunk>` |
46
46
 
47
47
  All AI endpoints receive `Authorization: Bearer <apiKey>` and `x-api-key: <apiKey>` headers.
@@ -68,6 +68,17 @@ Used to get a single, non-streaming text response from a string prompt.
68
68
  ```typescript
69
69
  const text = await ai.chat('Write a poem about TypeScript');
70
70
  console.log(text);
71
+
72
+ // Example: Structured Output
73
+ interface UserProfile {
74
+ name: string;
75
+ age: number;
76
+ }
77
+ const profile = await ai.chat<UserProfile>('Generate a profile for John Doe', {
78
+ isStructure: true,
79
+ output_structure: ['name', 'age'] // or a JSON Schema
80
+ });
81
+ console.log(profile.name, profile.age);
71
82
  ```
72
83
 
73
84
  ### 2. `streamChatResponse(messages: ChatMessage[])` — Multi-Turn & Streaming
@@ -102,7 +113,7 @@ import { KrutAIProvider } from '@krutai/ai-provider';
102
113
  const ai = new KrutAIProvider({
103
114
  apiKey: process.env.KRUTAI_API_KEY!,
104
115
  // serverUrl: 'https://krut.ai', // Optional: defaults to localhost:8000
105
- model: 'gpt-4o', // optional, default: 'default'
116
+ model: 'gemini-3.1-pro-preview', // optional, default: 'default'
106
117
  validateOnInit: true, // default: true
107
118
  });
108
119
 
@@ -151,6 +162,10 @@ interface GenerateOptions {
151
162
  images?: string[]; // Array of image URLs or base64 data URIs
152
163
  documents?: string[]; // Array of document URLs or base64 data URIs
153
164
  pdf?: string[]; // Array of PDF URLs or base64 data URIs
165
+ history?: ChatMessage[]; // Optional: conversation history
166
+ attachments?: any[]; // Optional: multimodal attachments
167
+ isStructure?: boolean; // Whether to return structured output
168
+ output_structure?: any; // The schema (JSON Schema or field array) for structured output
154
169
  }
155
170
  ```
156
171
 
package/README.md CHANGED
@@ -42,7 +42,7 @@ console.log(text);
42
42
  const ai = krutAI({
43
43
  apiKey: process.env.KRUTAI_API_KEY!,
44
44
  serverUrl: 'https://krut.ai', // Override default for production
45
- model: 'gpt-4o', // optional — server's default is used if omitted
45
+ model: 'gemini-3.1-pro-preview', // optional — server's default is used if omitted
46
46
  });
47
47
 
48
48
  await ai.initialize();
@@ -93,7 +93,7 @@ const response = await ai.chat([
93
93
  ]
94
94
  }
95
95
  ], {
96
- model: 'gpt-4o',
96
+ model: 'gemini-3.1-pro-preview',
97
97
  // You can also pass images, documents, or pdfs via GenerateOptions
98
98
  images: ['https://example.com/photo.jpg'],
99
99
  documents: ['https://example.com/doc.docx'],
@@ -139,6 +139,26 @@ if (reader) {
139
139
  }
140
140
  ```
141
141
 
142
+ ### Structured Output
143
+
144
+ You can request the AI to return data in a specific JSON structure (e.g. for generating models, summaries, or profiles).
145
+
146
+ ```typescript
147
+ interface Profile {
148
+ name: string;
149
+ age: number;
150
+ }
151
+
152
+ const profile = await ai.chat<Profile>('Generate a profile for John Doe', {
153
+ isStructure: true,
154
+ // Pass an array of field names for simple string objects...
155
+ output_structure: ['name', 'age'],
156
+ // ...or pass a full JSON Schema for complex objects
157
+ });
158
+
159
+ console.log(profile.name, profile.age);
160
+ ```
161
+
142
162
  ### Skip validation (useful for tests)
143
163
 
144
164
  ```typescript
@@ -159,7 +179,7 @@ Your LangChain server must expose these endpoints:
159
179
  | Endpoint | Method | Auth | Body |
160
180
  |---|---|---|---|
161
181
  | `/validate` | POST | `x-api-key` header | `{ "apiKey": "..." }` |
162
- | `/generate` | POST | `Authorization: Bearer <key>` | `{ "prompt": "...", "model": "...", ... }` |
182
+ | `/generate` | POST | `Authorization: Bearer <key>` | `{ "prompt": "...", "isStructure": boolean, "output_structure": any, ... }` |
163
183
  | `/stream` | POST | `Authorization: Bearer <key>` | `{ "messages": [...], "model": "...", ... }` |
164
184
 
165
185
  **Validation response:** `{ "valid": true }` or `{ "valid": false, "message": "reason" }`
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- export { ApiKeyValidationError as KrutAIKeyValidationError, validateApiKeyWithService as validateApiKey, validateApiKeyFormat } from 'krutai';
1
+ export { KrutAIKeyValidationError, validateApiKeyWithService as validateApiKey, validateApiKeyFormat } from 'krutai';
2
2
 
3
3
  /**
4
4
  * Types for @krutai/ai-provider
@@ -7,7 +7,57 @@ export { ApiKeyValidationError as KrutAIKeyValidationError, validateApiKeyWithSe
7
7
  * Default model identifier sent to the LangChain server when no model is specified.
8
8
  * Your server can use this value to route to its own default model.
9
9
  */
10
- declare const DEFAULT_MODEL: "default";
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
  */
@@ -92,6 +142,23 @@ interface GenerateOptions {
92
142
  * Array of PDF URLs or base64 data URIs to include with the request.
93
143
  */
94
144
  pdf?: string[];
145
+ /**
146
+ * Optional conversation history.
147
+ */
148
+ history?: ChatMessage[];
149
+ /**
150
+ * Optional attachments.
151
+ */
152
+ attachments?: any[];
153
+ /**
154
+ * Whether to return structured output.
155
+ */
156
+ isStructure?: boolean;
157
+ /**
158
+ * The schema for structured output.
159
+ * Can be a JSON Schema object or an array of field names.
160
+ */
161
+ output_structure?: any;
95
162
  }
96
163
 
97
164
  /**
@@ -164,9 +231,9 @@ declare class KrutAIProvider {
164
231
  *
165
232
  * @param prompt - The user prompt string
166
233
  * @param options - Optional overrides (model, system, maxTokens, temperature)
167
- * @returns The assistant's response text
234
+ * @returns The assistant's response text (or an object if structured)
168
235
  */
169
- chat(prompt: string, options?: GenerateOptions): Promise<string>;
236
+ chat<T = any>(prompt: string, options?: GenerateOptions): Promise<T>;
170
237
  }
171
238
 
172
239
  /**
@@ -195,7 +262,7 @@ declare class KrutAIProvider {
195
262
  * const ai = krutAI({
196
263
  * apiKey: process.env.KRUTAI_API_KEY!,
197
264
  * serverUrl: 'https://krut.ai',
198
- * model: 'gpt-4o',
265
+ * model: 'gemini-3.1-pro-preview',
199
266
  * });
200
267
  * await ai.initialize();
201
268
  * const text = await ai.chat('Hello!');
@@ -240,6 +307,6 @@ declare class KrutAIProvider {
240
307
  declare function krutAI(config: KrutAIProviderConfig & {
241
308
  model?: string;
242
309
  }): KrutAIProvider;
243
- declare const VERSION = "0.2.0";
310
+ declare const VERSION = "0.3.4";
244
311
 
245
- 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 { ApiKeyValidationError as KrutAIKeyValidationError, validateApiKeyWithService as validateApiKey, validateApiKeyFormat } from 'krutai';
1
+ export { KrutAIKeyValidationError, validateApiKeyWithService as validateApiKey, validateApiKeyFormat } from 'krutai';
2
2
 
3
3
  /**
4
4
  * Types for @krutai/ai-provider
@@ -7,7 +7,57 @@ export { ApiKeyValidationError as KrutAIKeyValidationError, validateApiKeyWithSe
7
7
  * Default model identifier sent to the LangChain server when no model is specified.
8
8
  * Your server can use this value to route to its own default model.
9
9
  */
10
- declare const DEFAULT_MODEL: "default";
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
  */
@@ -92,6 +142,23 @@ interface GenerateOptions {
92
142
  * Array of PDF URLs or base64 data URIs to include with the request.
93
143
  */
94
144
  pdf?: string[];
145
+ /**
146
+ * Optional conversation history.
147
+ */
148
+ history?: ChatMessage[];
149
+ /**
150
+ * Optional attachments.
151
+ */
152
+ attachments?: any[];
153
+ /**
154
+ * Whether to return structured output.
155
+ */
156
+ isStructure?: boolean;
157
+ /**
158
+ * The schema for structured output.
159
+ * Can be a JSON Schema object or an array of field names.
160
+ */
161
+ output_structure?: any;
95
162
  }
96
163
 
97
164
  /**
@@ -164,9 +231,9 @@ declare class KrutAIProvider {
164
231
  *
165
232
  * @param prompt - The user prompt string
166
233
  * @param options - Optional overrides (model, system, maxTokens, temperature)
167
- * @returns The assistant's response text
234
+ * @returns The assistant's response text (or an object if structured)
168
235
  */
169
- chat(prompt: string, options?: GenerateOptions): Promise<string>;
236
+ chat<T = any>(prompt: string, options?: GenerateOptions): Promise<T>;
170
237
  }
171
238
 
172
239
  /**
@@ -195,7 +262,7 @@ declare class KrutAIProvider {
195
262
  * const ai = krutAI({
196
263
  * apiKey: process.env.KRUTAI_API_KEY!,
197
264
  * serverUrl: 'https://krut.ai',
198
- * model: 'gpt-4o',
265
+ * model: 'gemini-3.1-pro-preview',
199
266
  * });
200
267
  * await ai.initialize();
201
268
  * const text = await ai.chat('Hello!');
@@ -240,6 +307,6 @@ declare class KrutAIProvider {
240
307
  declare function krutAI(config: KrutAIProviderConfig & {
241
308
  model?: string;
242
309
  }): KrutAIProvider;
243
- declare const VERSION = "0.2.0";
310
+ declare const VERSION = "0.3.4";
244
311
 
245
- 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
@@ -3,7 +3,7 @@
3
3
  var krutai = require('krutai');
4
4
 
5
5
  // src/types.ts
6
- var DEFAULT_MODEL = "default";
6
+ var DEFAULT_MODEL = "gemini-3.1-pro-preview";
7
7
  var DEFAULT_SERVER_URL = "http://localhost:8000";
8
8
  var KrutAIProvider = class {
9
9
  apiKey;
@@ -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.validateApiKeyWithService(this.apiKey, this.serverUrl);
33
+ await krutai.validateApiKey(this.apiKey, this.serverUrl);
34
34
  }
35
35
  this.initialized = true;
36
36
  }
@@ -119,7 +119,7 @@ var KrutAIProvider = class {
119
119
  *
120
120
  * @param prompt - The user prompt string
121
121
  * @param options - Optional overrides (model, system, maxTokens, temperature)
122
- * @returns The assistant's response text
122
+ * @returns The assistant's response text (or an object if structured)
123
123
  */
124
124
  async chat(prompt, options = {}) {
125
125
  this.assertInitialized();
@@ -135,7 +135,11 @@ var KrutAIProvider = class {
135
135
  ...options.documents !== void 0 ? { documents: options.documents } : {},
136
136
  ...options.pdf !== void 0 ? { pdf: options.pdf } : {},
137
137
  ...options.maxTokens !== void 0 ? { maxTokens: options.maxTokens } : {},
138
- ...options.temperature !== void 0 ? { temperature: options.temperature } : {}
138
+ ...options.temperature !== void 0 ? { temperature: options.temperature } : {},
139
+ ...options.isStructure !== void 0 ? { isStructure: options.isStructure } : {},
140
+ ...options.output_structure !== void 0 ? { output_structure: options.output_structure } : {},
141
+ ...options.history !== void 0 ? { history: options.history } : {},
142
+ ...options.attachments !== void 0 ? { attachments: options.attachments } : {}
139
143
  })
140
144
  });
141
145
  if (!response.ok) {
@@ -149,6 +153,9 @@ var KrutAIProvider = class {
149
153
  throw new Error(errorMessage);
150
154
  }
151
155
  const data = await response.json();
156
+ if (options.isStructure) {
157
+ return data;
158
+ }
152
159
  return data.text ?? data.content ?? data.message ?? "";
153
160
  }
154
161
  };
@@ -158,11 +165,11 @@ function krutAI(config) {
158
165
  ...config
159
166
  });
160
167
  }
161
- var VERSION = "0.2.0";
168
+ var VERSION = "0.3.4";
162
169
 
163
170
  Object.defineProperty(exports, "KrutAIKeyValidationError", {
164
171
  enumerable: true,
165
- get: function () { return krutai.ApiKeyValidationError; }
172
+ get: function () { return krutai.KrutAIKeyValidationError; }
166
173
  });
167
174
  Object.defineProperty(exports, "validateApiKey", {
168
175
  enumerable: true,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../src/client.ts","../src/index.ts"],"names":["validateApiKeyFormat","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,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AK,OAAA,IAAW,EAAA;AAAA,EACxD;AACJ;AClIO,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 = 'default' 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","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\n */\n async chat(prompt: string, options: GenerateOptions = {}): Promise<string> {\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 }),\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 {\n text?: string;\n content?: string;\n message?: string;\n };\n\n return data.text ?? data.content ?? data.message ?? '';\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: 'gpt-4o',\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.0';\n"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/client.ts","../src/index.ts"],"names":["validateApiKeyFormat","validateApiKey"],"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,IAAAA,2BAAA,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;AACtC,MAAA,MAAMC,qBAAA,CAAe,IAAA,CAAK,MAAA,EAAQ,IAAA,CAAK,SAAS,CAAA;AAAA,IACpD;AAEA,IAAA,IAAA,CAAK,WAAA,GAAc,IAAA;AAAA,EACvB;AAAA;AAAA;AAAA;AAAA,EAKA,QAAA,GAAmB;AACf,IAAA,OAAO,IAAA,CA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S,OAAA,CAAQ,OAAA,EAAQ,GAAI,EAAC;AAAA,QACpE,GAAI,QAAQ,WAAA,KAAgB,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,8 +1,8 @@
1
- import { validateApiKeyFormat, validateApiKeyWithService } from 'krutai';
2
- export { ApiKeyValidationError as KrutAIKeyValidationError, validateApiKeyWithService as validateApiKey, validateApiKeyFormat } from 'krutai';
1
+ import { validateApiKeyFormat, validateApiKey } from 'krutai';
2
+ export { KrutAIKeyValidationError, validateApiKeyWithService as validateApiKey, validateApiKeyFormat } from 'krutai';
3
3
 
4
4
  // src/types.ts
5
- var DEFAULT_MODEL = "default";
5
+ var DEFAULT_MODEL = "gemini-3.1-pro-preview";
6
6
  var DEFAULT_SERVER_URL = "http://localhost:8000";
7
7
  var KrutAIProvider = class {
8
8
  apiKey;
@@ -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 validateApiKeyWithService(this.apiKey, this.serverUrl);
32
+ await validateApiKey(this.apiKey, this.serverUrl);
33
33
  }
34
34
  this.initialized = true;
35
35
  }
@@ -118,7 +118,7 @@ var KrutAIProvider = class {
118
118
  *
119
119
  * @param prompt - The user prompt string
120
120
  * @param options - Optional overrides (model, system, maxTokens, temperature)
121
- * @returns The assistant's response text
121
+ * @returns The assistant's response text (or an object if structured)
122
122
  */
123
123
  async chat(prompt, options = {}) {
124
124
  this.assertInitialized();
@@ -134,7 +134,11 @@ var KrutAIProvider = class {
134
134
  ...options.documents !== void 0 ? { documents: options.documents } : {},
135
135
  ...options.pdf !== void 0 ? { pdf: options.pdf } : {},
136
136
  ...options.maxTokens !== void 0 ? { maxTokens: options.maxTokens } : {},
137
- ...options.temperature !== void 0 ? { temperature: options.temperature } : {}
137
+ ...options.temperature !== void 0 ? { temperature: options.temperature } : {},
138
+ ...options.isStructure !== void 0 ? { isStructure: options.isStructure } : {},
139
+ ...options.output_structure !== void 0 ? { output_structure: options.output_structure } : {},
140
+ ...options.history !== void 0 ? { history: options.history } : {},
141
+ ...options.attachments !== void 0 ? { attachments: options.attachments } : {}
138
142
  })
139
143
  });
140
144
  if (!response.ok) {
@@ -148,6 +152,9 @@ var KrutAIProvider = class {
148
152
  throw new Error(errorMessage);
149
153
  }
150
154
  const data = await response.json();
155
+ if (options.isStructure) {
156
+ return data;
157
+ }
151
158
  return data.text ?? data.content ?? data.message ?? "";
152
159
  }
153
160
  };
@@ -157,7 +164,7 @@ function krutAI(config) {
157
164
  ...config
158
165
  });
159
166
  }
160
- var VERSION = "0.2.0";
167
+ var VERSION = "0.3.4";
161
168
 
162
169
  export { DEFAULT_MODEL, KrutAIProvider, VERSION, krutAI };
163
170
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../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AAA,CAAA,MAAQ;AAAA,MAAE;AACV,MAAA,MAAM,IAAI,MAAM,YAAY,CAAA;AAAA,IAChC;AAEA,IAAA,MAAM,IAAA,GAAQ,MAAM,QAAA,CAAS,IAAA,EAAK;AAMlC,IAAA,OAAO,IAAA,CAAK,IAAA,IAAQ,IAAA,CAAK,OAAA,IAAW,KAAK,OAAA,IAAW,EAAA;AAAA,EACxD;AACJ;AClIO,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.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 = 'default' 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","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\n */\n async chat(prompt: string, options: GenerateOptions = {}): Promise<string> {\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 }),\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 {\n text?: string;\n content?: string;\n message?: string;\n };\n\n return data.text ?? data.content ?? data.message ?? '';\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: 'gpt-4o',\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.0';\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;AACtC,MAAA,MAAM,cAAA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/**\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.2.13",
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",