@umituz/react-native-ai-groq-provider 1.0.20 → 1.0.22

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.
@@ -1,104 +0,0 @@
1
- /**
2
- * Streaming Service
3
- * Handles streaming responses from Groq API
4
- */
5
-
6
- import type {
7
- GroqChatRequest,
8
- GroqMessage,
9
- GroqGenerationConfig,
10
- } from "../../domain/entities";
11
- import { groqHttpClient } from "./GroqClient";
12
- import { DEFAULT_MODELS } from "../../domain/entities";
13
-
14
- export interface StreamingCallbacks {
15
- /** Called when new content chunk is received */
16
- onChunk?: (chunk: string) => void;
17
- /** Called when streaming completes */
18
- onComplete?: (fullContent: string) => void;
19
- /** Called when an error occurs */
20
- onError?: (error: Error) => void;
21
- }
22
-
23
- export interface StreamingOptions {
24
- model?: string;
25
- generationConfig?: GroqGenerationConfig;
26
- callbacks?: StreamingCallbacks;
27
- }
28
-
29
- /**
30
- * Stream text generation from a prompt
31
- */
32
- export async function* streaming(
33
- prompt: string,
34
- options: StreamingOptions = {}
35
- ): AsyncGenerator<string> {
36
- const model = options.model || DEFAULT_MODELS.TEXT;
37
-
38
- const messages: GroqMessage[] = [
39
- {
40
- role: "user",
41
- content: prompt,
42
- },
43
- ];
44
-
45
- const request: GroqChatRequest = {
46
- model,
47
- messages,
48
- temperature: options.generationConfig?.temperature || 0.7,
49
- max_tokens: options.generationConfig?.maxTokens || 1024,
50
- top_p: options.generationConfig?.topP,
51
- };
52
-
53
- let fullContent = "";
54
-
55
- try {
56
- for await (const chunk of groqHttpClient.chatCompletionStream(request)) {
57
- const content = chunk.choices[0]?.delta?.content;
58
- if (content) {
59
- fullContent += content;
60
- options.callbacks?.onChunk?.(content);
61
- yield content;
62
- }
63
- }
64
- options.callbacks?.onComplete?.(fullContent);
65
- } catch (error) {
66
- options.callbacks?.onError?.(error as Error);
67
- throw error;
68
- }
69
- }
70
-
71
- /**
72
- * Stream chat generation from messages
73
- */
74
- export async function* streamingChat(
75
- messages: GroqMessage[],
76
- options: StreamingOptions = {}
77
- ): AsyncGenerator<string> {
78
- const model = options.model || DEFAULT_MODELS.TEXT;
79
-
80
- const request: GroqChatRequest = {
81
- model,
82
- messages,
83
- temperature: options.generationConfig?.temperature || 0.7,
84
- max_tokens: options.generationConfig?.maxTokens || 1024,
85
- top_p: options.generationConfig?.topP,
86
- };
87
-
88
- let fullContent = "";
89
-
90
- try {
91
- for await (const chunk of groqHttpClient.chatCompletionStream(request)) {
92
- const content = chunk.choices[0]?.delta?.content;
93
- if (content) {
94
- fullContent += content;
95
- options.callbacks?.onChunk?.(content);
96
- yield content;
97
- }
98
- }
99
- options.callbacks?.onComplete?.(fullContent);
100
- } catch (error) {
101
- options.callbacks?.onError?.(error as Error);
102
- throw error;
103
- }
104
- }
@@ -1,245 +0,0 @@
1
- /**
2
- * Structured Text Generation Service
3
- * Generates structured JSON output from Groq API
4
- */
5
-
6
- import type {
7
- GroqChatRequest,
8
- GroqMessage,
9
- GroqGenerationConfig,
10
- } from "../../domain/entities";
11
- import { groqHttpClient } from "./GroqClient";
12
- import { DEFAULT_MODELS } from "../../domain/entities";
13
- import { GroqError, GroqErrorType } from "../../domain/entities/error.types";
14
- import { cleanJsonResponse } from "../../infrastructure/utils/content-mapper.util";
15
-
16
- export interface StructuredTextOptions<T> {
17
- model?: string;
18
- generationConfig?: GroqGenerationConfig;
19
- schema?: Record<string, unknown>;
20
- example?: T;
21
- }
22
-
23
- /**
24
- * Generate structured JSON output from a prompt
25
- */
26
- export async function structuredText<T = Record<string, unknown>>(
27
- prompt: string,
28
- options: StructuredTextOptions<T> = {}
29
- ): Promise<T> {
30
- const startTime = Date.now();
31
- const model = options.model || DEFAULT_MODELS.TEXT;
32
-
33
- if (typeof __DEV__ !== "undefined" && __DEV__) {
34
- console.log("[Groq] structuredText called:", {
35
- model,
36
- promptLength: prompt.length,
37
- promptPreview: prompt.substring(0, 150) + "...",
38
- hasSchema: !!options.schema,
39
- hasExample: !!options.example,
40
- generationConfig: options.generationConfig,
41
- });
42
- }
43
-
44
- let systemPrompt = "You are a helpful assistant that generates valid JSON output.";
45
-
46
- if (options.schema) {
47
- systemPrompt += `\n\nResponse must conform to this JSON schema:\n${JSON.stringify(options.schema, null, 2)}`;
48
- }
49
-
50
- if (options.example) {
51
- systemPrompt += `\n\nExample response format:\n${JSON.stringify(options.example, null, 2)}`;
52
- }
53
-
54
- systemPrompt += "\n\nIMPORTANT: Respond ONLY with valid JSON. No markdown, no code blocks, no explanations.";
55
-
56
- const messages: GroqMessage[] = [
57
- {
58
- role: "system",
59
- content: systemPrompt,
60
- },
61
- {
62
- role: "user",
63
- content: prompt,
64
- },
65
- ];
66
-
67
- const request: GroqChatRequest = {
68
- model,
69
- messages,
70
- temperature: options.generationConfig?.temperature || 0.3,
71
- max_tokens: options.generationConfig?.maxTokens || 2048,
72
- top_p: options.generationConfig?.topP || 0.9,
73
- };
74
-
75
- if (typeof __DEV__ !== "undefined" && __DEV__) {
76
- console.log("[Groq] Sending structured request:", {
77
- endpoint: "/v1/chat/completions",
78
- requestBody: {
79
- model: request.model,
80
- temperature: request.temperature,
81
- max_tokens: request.max_tokens,
82
- top_p: request.top_p,
83
- },
84
- });
85
- }
86
-
87
- const apiStartTime = Date.now();
88
- const response = await groqHttpClient.chatCompletion(request);
89
- const apiDuration = Date.now() - apiStartTime;
90
-
91
- if (typeof __DEV__ !== "undefined" && __DEV__) {
92
- console.log("[Groq] Structured API response:", {
93
- apiDuration: `${apiDuration}ms`,
94
- usage: response.usage,
95
- finishReason: response.choices?.[0]?.finish_reason,
96
- hasContent: !!response.choices?.[0]?.message?.content,
97
- });
98
- }
99
-
100
- let content = response.choices[0]?.message?.content;
101
- if (!content) {
102
- throw new GroqError(
103
- GroqErrorType.UNKNOWN_ERROR,
104
- "No content generated from Groq API"
105
- );
106
- }
107
-
108
- if (typeof __DEV__ !== "undefined" && __DEV__) {
109
- console.log("[Groq] Raw response content:", {
110
- length: content.length,
111
- preview: content.substring(0, 300) + "...",
112
- });
113
- }
114
-
115
- content = cleanJsonResponse(content);
116
-
117
- if (typeof __DEV__ !== "undefined" && __DEV__) {
118
- console.log("[Groq] Attempting JSON parse...");
119
- }
120
-
121
- try {
122
- const parsed = JSON.parse(content) as T;
123
- const totalDuration = Date.now() - startTime;
124
-
125
- if (typeof __DEV__ !== "undefined" && __DEV__) {
126
- console.log("[Groq] structuredText complete:", {
127
- totalDuration: `${totalDuration}ms`,
128
- apiDuration: `${apiDuration}ms`,
129
- parseDuration: `${totalDuration - apiDuration}ms`,
130
- parsedKeys: Object.keys(parsed),
131
- });
132
- }
133
-
134
- return parsed;
135
- } catch (error) {
136
- if (typeof __DEV__ !== "undefined" && __DEV__) {
137
- console.error("[Groq] JSON parse failed:", {
138
- error,
139
- contentLength: content.length,
140
- contentPreview: content.substring(0, 500) + "...",
141
- });
142
- }
143
-
144
- throw new GroqError(
145
- GroqErrorType.UNKNOWN_ERROR,
146
- `Failed to parse JSON response: ${content}`,
147
- error
148
- );
149
- }
150
- }
151
-
152
- /**
153
- * Generate structured JSON output from messages
154
- */
155
- export async function structuredChat<T = Record<string, unknown>>(
156
- messages: GroqMessage[],
157
- options: StructuredTextOptions<T> = {}
158
- ): Promise<T> {
159
- const startTime = Date.now();
160
- const model = options.model || DEFAULT_MODELS.TEXT;
161
-
162
- if (typeof __DEV__ !== "undefined" && __DEV__) {
163
- console.log("[Groq] structuredChat called:", {
164
- model,
165
- messageCount: messages.length,
166
- hasSchema: !!options.schema,
167
- hasExample: !!options.example,
168
- });
169
- }
170
-
171
- let systemMessage: GroqMessage | null = null;
172
-
173
- // Check if there's already a system message
174
- const hasSystemMessage = messages.some((m) => m.role === "system");
175
-
176
- if (!hasSystemMessage) {
177
- let systemPrompt = "You are a helpful assistant that generates valid JSON output.";
178
-
179
- if (options.schema) {
180
- systemPrompt += `\n\nResponse must conform to this JSON schema:\n${JSON.stringify(options.schema, null, 2)}`;
181
- }
182
-
183
- if (options.example) {
184
- systemPrompt += `\n\nExample response format:\n${JSON.stringify(options.example, null, 2)}`;
185
- }
186
-
187
- systemPrompt += "\n\nIMPORTANT: Respond ONLY with valid JSON. No markdown, no code blocks, no explanations.";
188
-
189
- systemMessage = {
190
- role: "system",
191
- content: systemPrompt,
192
- };
193
- }
194
-
195
- const requestMessages = systemMessage
196
- ? [systemMessage, ...messages]
197
- : messages;
198
-
199
- const request: GroqChatRequest = {
200
- model,
201
- messages: requestMessages,
202
- temperature: options.generationConfig?.temperature || 0.3,
203
- max_tokens: options.generationConfig?.maxTokens || 2048,
204
- top_p: options.generationConfig?.topP || 0.9,
205
- };
206
-
207
- const apiStartTime = Date.now();
208
- const response = await groqHttpClient.chatCompletion(request);
209
- const apiDuration = Date.now() - apiStartTime;
210
-
211
- if (typeof __DEV__ !== "undefined" && __DEV__) {
212
- console.log("[Groq] structuredChat API response:", {
213
- apiDuration: `${apiDuration}ms`,
214
- usage: response.usage,
215
- });
216
- }
217
-
218
- let content = response.choices[0]?.message?.content;
219
- if (!content) {
220
- throw new GroqError(
221
- GroqErrorType.UNKNOWN_ERROR,
222
- "No content generated from Groq API"
223
- );
224
- }
225
-
226
- content = cleanJsonResponse(content);
227
-
228
- const totalDuration = Date.now() - startTime;
229
- if (typeof __DEV__ !== "undefined" && __DEV__) {
230
- console.log("[Groq] structuredChat complete:", {
231
- totalDuration: `${totalDuration}ms`,
232
- responseLength: content.length,
233
- });
234
- }
235
-
236
- try {
237
- return JSON.parse(content) as T;
238
- } catch (error) {
239
- throw new GroqError(
240
- GroqErrorType.UNKNOWN_ERROR,
241
- `Failed to parse JSON response: ${content}`,
242
- error
243
- );
244
- }
245
- }
@@ -1,163 +0,0 @@
1
- /**
2
- * Text Generation Service
3
- * Handles basic text generation using Groq API
4
- */
5
-
6
- import type {
7
- GroqChatRequest,
8
- GroqMessage,
9
- GroqGenerationConfig,
10
- } from "../../domain/entities";
11
- import { groqHttpClient } from "./GroqClient";
12
- import { DEFAULT_MODELS } from "../../domain/entities";
13
- import { GroqError, GroqErrorType } from "../../domain/entities/error.types";
14
-
15
- export interface TextGenerationOptions {
16
- model?: string;
17
- generationConfig?: GroqGenerationConfig;
18
- }
19
-
20
- /**
21
- * Generate text from a simple prompt
22
- */
23
- export async function textGeneration(
24
- prompt: string,
25
- options: TextGenerationOptions = {}
26
- ): Promise<string> {
27
- const startTime = Date.now();
28
- const model = options.model || DEFAULT_MODELS.TEXT;
29
-
30
- if (typeof __DEV__ !== "undefined" && __DEV__) {
31
- console.log("[Groq] textGeneration called:", {
32
- model,
33
- promptLength: prompt.length,
34
- promptPreview: prompt.substring(0, 100) + "...",
35
- options: options.generationConfig,
36
- });
37
- }
38
-
39
- const messages: GroqMessage[] = [
40
- {
41
- role: "user",
42
- content: prompt,
43
- },
44
- ];
45
-
46
- const request: GroqChatRequest = {
47
- model,
48
- messages,
49
- temperature: options.generationConfig?.temperature || 0.7,
50
- max_tokens: options.generationConfig?.maxTokens || 1024,
51
- top_p: options.generationConfig?.topP,
52
- n: options.generationConfig?.n,
53
- stop: options.generationConfig?.stop,
54
- frequency_penalty: options.generationConfig?.frequencyPenalty,
55
- presence_penalty: options.generationConfig?.presencePenalty,
56
- };
57
-
58
- if (typeof __DEV__ !== "undefined" && __DEV__) {
59
- console.log("[Groq] Sending request to API:", {
60
- endpoint: "/v1/chat/completions",
61
- requestBody: {
62
- model: request.model,
63
- messageCount: request.messages.length,
64
- temperature: request.temperature,
65
- max_tokens: request.max_tokens,
66
- },
67
- });
68
- }
69
-
70
- const apiStartTime = Date.now();
71
- const response = await groqHttpClient.chatCompletion(request);
72
- const apiDuration = Date.now() - apiStartTime;
73
-
74
- if (typeof __DEV__ !== "undefined" && __DEV__) {
75
- console.log("[Groq] API response received:", {
76
- apiDuration: `${apiDuration}ms`,
77
- hasChoices: !!response.choices?.length,
78
- choiceCount: response.choices?.length || 0,
79
- usage: response.usage,
80
- finishReason: response.choices?.[0]?.finish_reason,
81
- });
82
- }
83
-
84
- const content = response.choices[0]?.message?.content;
85
- if (!content) {
86
- throw new GroqError(
87
- GroqErrorType.UNKNOWN_ERROR,
88
- "No content generated from Groq API"
89
- );
90
- }
91
-
92
- const totalDuration = Date.now() - startTime;
93
- if (typeof __DEV__ !== "undefined" && __DEV__) {
94
- console.log("[Groq] textGeneration complete:", {
95
- totalDuration: `${totalDuration}ms`,
96
- responseLength: content.length,
97
- responsePreview: content.substring(0, 200) + "...",
98
- });
99
- }
100
-
101
- return content;
102
- }
103
-
104
- /**
105
- * Generate text from an array of messages
106
- */
107
- export async function chatGeneration(
108
- messages: GroqMessage[],
109
- options: TextGenerationOptions = {}
110
- ): Promise<string> {
111
- const startTime = Date.now();
112
- const model = options.model || DEFAULT_MODELS.TEXT;
113
-
114
- if (typeof __DEV__ !== "undefined" && __DEV__) {
115
- console.log("[Groq] chatGeneration called:", {
116
- model,
117
- messageCount: messages.length,
118
- options: options.generationConfig,
119
- });
120
- }
121
-
122
- const request: GroqChatRequest = {
123
- model,
124
- messages,
125
- temperature: options.generationConfig?.temperature || 0.7,
126
- max_tokens: options.generationConfig?.maxTokens || 1024,
127
- top_p: options.generationConfig?.topP,
128
- n: options.generationConfig?.n,
129
- stop: options.generationConfig?.stop,
130
- frequency_penalty: options.generationConfig?.frequencyPenalty,
131
- presence_penalty: options.generationConfig?.presencePenalty,
132
- };
133
-
134
- const apiStartTime = Date.now();
135
- const response = await groqHttpClient.chatCompletion(request);
136
- const apiDuration = Date.now() - apiStartTime;
137
-
138
- if (typeof __DEV__ !== "undefined" && __DEV__) {
139
- console.log("[Groq] chatGeneration API response:", {
140
- apiDuration: `${apiDuration}ms`,
141
- usage: response.usage,
142
- finishReason: response.choices?.[0]?.finish_reason,
143
- });
144
- }
145
-
146
- const content = response.choices[0]?.message?.content;
147
- if (!content) {
148
- throw new GroqError(
149
- GroqErrorType.UNKNOWN_ERROR,
150
- "No content generated from Groq API"
151
- );
152
- }
153
-
154
- const totalDuration = Date.now() - startTime;
155
- if (typeof __DEV__ !== "undefined" && __DEV__) {
156
- console.log("[Groq] chatGeneration complete:", {
157
- totalDuration: `${totalDuration}ms`,
158
- responseLength: content.length,
159
- });
160
- }
161
-
162
- return content;
163
- }
@@ -1,19 +0,0 @@
1
- /**
2
- * Infrastructure Services
3
- */
4
-
5
- export { groqHttpClient } from "./GroqClient";
6
- export { textGeneration, chatGeneration } from "./TextGeneration";
7
- export { structuredText, structuredChat } from "./StructuredText";
8
- export { streaming, streamingChat, type StreamingCallbacks, type StreamingOptions } from "./Streaming";
9
- export {
10
- chatSessionService,
11
- createChatSession,
12
- sendChatMessage,
13
- buildChatHistory,
14
- trimChatHistory,
15
- type ChatSession,
16
- type SendChatMessageOptions,
17
- type ChatSendResult,
18
- type ChatHistoryMessage,
19
- } from "./ChatSession";