@umituz/web-ai-groq-provider 1.0.1 → 1.1.0

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.
Files changed (32) hide show
  1. package/package.json +3 -4
  2. package/src/domains/chat/entities/chat.entities.ts +113 -0
  3. package/src/domains/chat/entities/index.ts +14 -0
  4. package/src/domains/chat/hooks/index.ts +5 -0
  5. package/src/domains/chat/hooks/use-chat.hook.ts +231 -0
  6. package/src/domains/chat/index.ts +32 -0
  7. package/src/domains/chat/interfaces/chat.interface.ts +79 -0
  8. package/src/domains/chat/interfaces/index.ts +10 -0
  9. package/src/domains/chat/services/chat.service.ts +143 -0
  10. package/src/domains/chat/services/index.ts +5 -0
  11. package/src/domains/chat/utils/message-formatter.ts +47 -0
  12. package/src/domains/groq/entities/chat.entities.ts +113 -0
  13. package/src/domains/groq/index.ts +72 -0
  14. package/src/domains/groq/interfaces/chat.interface.ts +80 -0
  15. package/src/index.ts +6 -68
  16. package/src/domain/index.ts +0 -32
  17. /package/src/{infrastructure → domains/groq}/constants/error.constants.ts +0 -0
  18. /package/src/{infrastructure → domains/groq}/constants/groq.constants.ts +0 -0
  19. /package/src/{infrastructure → domains/groq}/constants/index.ts +0 -0
  20. /package/src/{domain → domains/groq}/entities/groq.entities.ts +0 -0
  21. /package/src/{domain → domains/groq}/entities/index.ts +0 -0
  22. /package/src/{presentation → domains/groq}/hooks/index.ts +0 -0
  23. /package/src/{presentation → domains/groq}/hooks/use-groq.hook.ts +0 -0
  24. /package/src/{domain → domains/groq}/interfaces/groq.interface.ts +0 -0
  25. /package/src/{domain → domains/groq}/interfaces/index.ts +0 -0
  26. /package/src/{infrastructure → domains/groq}/services/http-client.service.ts +0 -0
  27. /package/src/{infrastructure → domains/groq}/services/index.ts +0 -0
  28. /package/src/{infrastructure → domains/groq}/services/text-generation.service.ts +0 -0
  29. /package/src/{infrastructure → domains/groq}/utils/error.util.ts +0 -0
  30. /package/src/{infrastructure → domains/groq}/utils/groq-error.util.ts +0 -0
  31. /package/src/{infrastructure → domains/groq}/utils/index.ts +0 -0
  32. /package/src/{infrastructure → domains/groq}/utils/message.util.ts +0 -0
package/package.json CHANGED
@@ -1,15 +1,14 @@
1
1
  {
2
2
  "name": "@umituz/web-ai-groq-provider",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "Groq AI text generation provider for React web applications",
5
5
  "main": "./src/index.ts",
6
6
  "types": "./src/index.ts",
7
7
  "sideEffects": false,
8
8
  "exports": {
9
9
  ".": "./src/index.ts",
10
- "./domain": "./src/domain/index.ts",
11
- "./services": "./src/infrastructure/services/index.ts",
12
- "./hooks": "./src/presentation/hooks/index.ts",
10
+ "./groq": "./src/domains/groq/index.ts",
11
+ "./chat": "./src/domains/chat/index.ts",
13
12
  "./package.json": "./package.json"
14
13
  },
15
14
  "scripts": {
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Chat Domain Entities
3
+ * @description Core chat message and conversation types
4
+ */
5
+
6
+ /**
7
+ * Message sender type
8
+ */
9
+ export type ChatMessageSender = "user" | "assistant" | "system";
10
+
11
+ /**
12
+ * Message content types
13
+ */
14
+ export type ChatMessageType = "text" | "image" | "audio" | "sticker";
15
+
16
+ /**
17
+ * Chat message structure
18
+ */
19
+ export interface ChatMessage {
20
+ /** Unique message identifier */
21
+ readonly id: string;
22
+ /** Sender of the message */
23
+ readonly sender: ChatMessageSender;
24
+ /** Message content */
25
+ readonly content: string;
26
+ /** Timestamp in ISO format */
27
+ readonly timestamp: string;
28
+ /** Message type */
29
+ readonly type?: ChatMessageType;
30
+ /** Image URL for image messages */
31
+ readonly imageUrl?: string;
32
+ /** Reaction emoji */
33
+ readonly reaction?: string;
34
+ /** Metadata */
35
+ readonly metadata?: Record<string, unknown>;
36
+ }
37
+
38
+ /**
39
+ * Conversation/session metadata
40
+ */
41
+ export interface ChatConversation {
42
+ /** Unique conversation identifier */
43
+ readonly id: string;
44
+ /** Companion/character identifier */
45
+ readonly companionId: string;
46
+ /** Companion name */
47
+ readonly companionName: string;
48
+ /** Last message */
49
+ readonly lastMessage?: ChatMessage;
50
+ /** Message count */
51
+ readonly messageCount: number;
52
+ /** Updated timestamp */
53
+ readonly updatedAt: string;
54
+ /** Is pinned */
55
+ readonly pinned?: boolean;
56
+ /** Is archived */
57
+ readonly archived?: boolean;
58
+ }
59
+
60
+ /**
61
+ * Send message input
62
+ */
63
+ export interface SendMessageInput {
64
+ /** Companion identifier */
65
+ readonly companionId: string;
66
+ /** Message text */
67
+ readonly text: string;
68
+ /** Message type */
69
+ readonly type?: ChatMessageType;
70
+ /** Image URL */
71
+ readonly imageUrl?: string;
72
+ }
73
+
74
+ /**
75
+ * Send message result
76
+ */
77
+ export interface SendMessageResult {
78
+ /** User message */
79
+ readonly userMessage: ChatMessage;
80
+ /** AI response (if generated) */
81
+ readonly aiResponse?: ChatMessage;
82
+ }
83
+
84
+ /**
85
+ * Chat configuration
86
+ */
87
+ export interface ChatConfig {
88
+ /** System prompt for AI personality */
89
+ readonly systemPrompt?: string;
90
+ /** Temperature for randomness */
91
+ readonly temperature?: number;
92
+ /** Maximum tokens */
93
+ readonly maxTokens?: number;
94
+ /** Include timestamp in messages */
95
+ readonly includeTimestamp?: boolean;
96
+ /** Language code (e.g., 'tr', 'en') */
97
+ readonly language?: string;
98
+ }
99
+
100
+ /**
101
+ * Storage interface for persisting messages
102
+ * Implementations should be provided by the application
103
+ */
104
+ export interface IChatStorage {
105
+ /** Save message to storage */
106
+ saveMessage(conversationId: string, message: ChatMessage): Promise<void>;
107
+ /** Get messages for conversation */
108
+ getMessages(conversationId: string): Promise<ChatMessage[]>;
109
+ /** Update message */
110
+ updateMessage(messageId: string, updates: Partial<ChatMessage>): Promise<void>;
111
+ /** Delete message */
112
+ deleteMessage(messageId: string): Promise<void>;
113
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Chat Entities
3
+ */
4
+
5
+ export type {
6
+ ChatMessageSender,
7
+ ChatMessageType,
8
+ ChatMessage,
9
+ ChatConversation,
10
+ SendMessageInput,
11
+ SendMessageResult,
12
+ ChatConfig,
13
+ IChatStorage,
14
+ } from "./chat.entities";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Chat Hooks
3
+ */
4
+
5
+ export { useChat } from "./use-chat.hook";
@@ -0,0 +1,231 @@
1
+ /**
2
+ * useChat Hook
3
+ * @description Main React hook for chat functionality
4
+ */
5
+
6
+ import { useState, useCallback, useEffect, useMemo } from "react";
7
+ import type {
8
+ ChatMessage,
9
+ ChatConfig,
10
+ IChatStorage,
11
+ } from "../../entities";
12
+ import type {
13
+ UseChatOptions,
14
+ UseChatReturn,
15
+ } from "../../interfaces";
16
+ import { chatService } from "../services/chat.service";
17
+
18
+ const isDevelopment =
19
+ typeof process !== "undefined" && process.env?.NODE_ENV === "development";
20
+
21
+ /**
22
+ * Hook for chat functionality with AI integration
23
+ */
24
+ export function useChat(options: UseChatOptions): UseChatReturn {
25
+ const {
26
+ conversationId,
27
+ storage,
28
+ config,
29
+ autoSave = true,
30
+ onMessageSent,
31
+ onAIResponse,
32
+ onError,
33
+ } = options;
34
+
35
+ const [messages, setMessages] = useState<ChatMessage[]>([]);
36
+ const [isLoading, setIsLoading] = useState(false);
37
+ const [isTyping, setIsTyping] = useState(false);
38
+ const [error, setError] = useState<string | null>(null);
39
+
40
+ // Initialize chat service config
41
+ useEffect(() => {
42
+ if (config) {
43
+ chatService.initialize(config);
44
+ }
45
+ }, [config]);
46
+
47
+ // Load messages from storage on mount
48
+ useEffect(() => {
49
+ if (!storage) return;
50
+
51
+ const loadMessages = async () => {
52
+ try {
53
+ const loaded = await storage.getMessages(conversationId);
54
+ setMessages(loaded);
55
+
56
+ if (isDevelopment) {
57
+ console.log("[useChat] Loaded messages:", loaded.length);
58
+ }
59
+ } catch (err) {
60
+ console.error("[useChat] Failed to load messages:", err);
61
+ }
62
+ };
63
+
64
+ void loadMessages();
65
+ }, [conversationId, storage]);
66
+
67
+ // Save message to storage
68
+ const saveToStorage = useCallback(
69
+ async (message: ChatMessage) => {
70
+ if (!autoSave || !storage) return;
71
+
72
+ try {
73
+ await storage.saveMessage(conversationId, message);
74
+
75
+ if (isDevelopment) {
76
+ console.log("[useChat] Message saved to storage");
77
+ }
78
+ } catch (err) {
79
+ console.error("[useChat] Failed to save message:", err);
80
+ }
81
+ },
82
+ [conversationId, storage, autoSave]
83
+ );
84
+
85
+ // Send message
86
+ const sendMessage = useCallback(
87
+ async (text: string, type?: ChatMessage["type"]): Promise<void> => {
88
+ if (!text.trim() || isLoading) return;
89
+
90
+ setIsLoading(true);
91
+ setError(null);
92
+
93
+ try {
94
+ if (isDevelopment) {
95
+ console.log("[useChat] Sending message:", { text, type });
96
+ }
97
+
98
+ // Generate AI response
99
+ setIsTyping(true);
100
+ const aiResponse = await chatService.generateAIResponse(
101
+ conversationId,
102
+ text,
103
+ messages
104
+ );
105
+
106
+ // Create user message
107
+ const userMessage: ChatMessage = {
108
+ id: `msg-${Date.now()}-user`,
109
+ sender: "user",
110
+ content: text,
111
+ timestamp: new Date().toISOString(),
112
+ type: type || "text",
113
+ };
114
+
115
+ // Update messages
116
+ const newMessages = [...messages, userMessage, aiResponse];
117
+ setMessages(newMessages);
118
+
119
+ // Save to storage
120
+ await saveToStorage(userMessage);
121
+ await saveToStorage(aiResponse);
122
+
123
+ // Callbacks
124
+ onMessageSent?.(userMessage);
125
+ onAIResponse?.(aiResponse);
126
+
127
+ if (isDevelopment) {
128
+ console.log("[useChat] Message sent, AI response received");
129
+ }
130
+ } catch (err) {
131
+ const errorMessage =
132
+ err instanceof Error ? err.message : "Failed to send message";
133
+ setError(errorMessage);
134
+ onError?.(errorMessage);
135
+
136
+ if (isDevelopment) {
137
+ console.error("[useChat] Error sending message:", err);
138
+ }
139
+ } finally {
140
+ setIsLoading(false);
141
+ setIsTyping(false);
142
+ }
143
+ },
144
+ [
145
+ conversationId,
146
+ messages,
147
+ isLoading,
148
+ saveToStorage,
149
+ onMessageSent,
150
+ onAIResponse,
151
+ onError,
152
+ ]
153
+ );
154
+
155
+ // Regenerate last AI response
156
+ const regenerate = useCallback(async (): Promise<void> => {
157
+ if (messages.length === 0 || isLoading) return;
158
+
159
+ const lastUserMessage = [...messages]
160
+ .reverse()
161
+ .find((m) => m.sender === "user");
162
+
163
+ if (!lastUserMessage) return;
164
+
165
+ setIsLoading(true);
166
+ setError(null);
167
+
168
+ try {
169
+ // Remove last AI message if exists
170
+ const messagesWithoutAI = messages.filter(
171
+ (m, i) => !(i === messages.length - 1 && m.sender === "assistant")
172
+ );
173
+
174
+ setMessages(messagesWithoutAI);
175
+
176
+ // Generate new response
177
+ setIsTyping(true);
178
+ const aiResponse = await chatService.generateAIResponse(
179
+ conversationId,
180
+ lastUserMessage.content,
181
+ messagesWithoutAI.slice(0, -1)
182
+ );
183
+
184
+ // Update messages
185
+ const newMessages = [...messagesWithoutAI, aiResponse];
186
+ setMessages(newMessages);
187
+
188
+ // Save to storage
189
+ await saveToStorage(aiResponse);
190
+
191
+ onAIResponse?.(aiResponse);
192
+ } catch (err) {
193
+ const errorMessage =
194
+ err instanceof Error ? err.message : "Failed to regenerate";
195
+ setError(errorMessage);
196
+ onError?.(errorMessage);
197
+ } finally {
198
+ setIsLoading(false);
199
+ setIsTyping(false);
200
+ }
201
+ }, [
202
+ conversationId,
203
+ messages,
204
+ isLoading,
205
+ saveToStorage,
206
+ onAIResponse,
207
+ onError,
208
+ ]);
209
+
210
+ // Clear all messages
211
+ const clearMessages = useCallback(() => {
212
+ setMessages([]);
213
+ setError(null);
214
+ }, []);
215
+
216
+ // Update configuration
217
+ const updateConfig = useCallback((newConfig: Partial<ChatConfig>) => {
218
+ chatService.updateConfig(newConfig);
219
+ }, []);
220
+
221
+ return {
222
+ messages,
223
+ isLoading,
224
+ error,
225
+ isTyping,
226
+ sendMessage,
227
+ regenerate,
228
+ clearMessages,
229
+ updateConfig,
230
+ };
231
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Chat Domain
3
+ * @description Chat functionality with AI integration
4
+ * Subpath: @umituz/web-ai-groq-provider/chat
5
+ */
6
+
7
+ // Entities
8
+ export type {
9
+ ChatMessageSender,
10
+ ChatMessageType,
11
+ ChatMessage,
12
+ ChatConversation,
13
+ SendMessageInput,
14
+ SendMessageResult,
15
+ ChatConfig,
16
+ } from "./entities";
17
+
18
+ export type { IChatStorage } from "./entities";
19
+
20
+ // Interfaces
21
+ export type {
22
+ IChatService,
23
+ UseChatOptions,
24
+ UseChatReturn,
25
+ IMessageFormatter,
26
+ } from "./interfaces";
27
+
28
+ // Services
29
+ export { chatService, messageFormatter } from "./services";
30
+
31
+ // Hooks
32
+ export { useChat } from "./hooks";
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Chat Service Interfaces
3
+ * @description Contracts for chat functionality
4
+ */
5
+
6
+ import type {
7
+ ChatMessage,
8
+ ChatConversation,
9
+ SendMessageInput,
10
+ SendMessageResult,
11
+ ChatConfig,
12
+ } from "../entities";
13
+ import type { GroqMessage } from "../../groq/interfaces";
14
+
15
+ /**
16
+ * Chat service interface
17
+ */
18
+ export interface IChatService {
19
+ /** Send message and get AI response */
20
+ sendMessage(input: SendMessageInput): Promise<SendMessageResult>;
21
+ /** Get conversation history */
22
+ getConversation(conversationId: string): Promise<ChatConversation | null>;
23
+ /** Get all conversations */
24
+ getConversations(): Promise<ChatConversation[]>;
25
+ /** Generate AI response only */
26
+ generateAIResponse(companionId: string, userMessage: string, context?: ChatMessage[]): Promise<ChatMessage>;
27
+ }
28
+
29
+ /**
30
+ * Chat hook options
31
+ */
32
+ export interface UseChatOptions {
33
+ /** Conversation identifier */
34
+ readonly conversationId: string;
35
+ /** Storage implementation */
36
+ readonly storage?: import("../entities").IChatStorage;
37
+ /** Chat configuration */
38
+ readonly config?: ChatConfig;
39
+ /** Auto-save messages */
40
+ readonly autoSave?: boolean;
41
+ /** Callback on message sent */
42
+ readonly onMessageSent?: (message: ChatMessage) => void;
43
+ /** Callback on AI response */
44
+ readonly onAIResponse?: (message: ChatMessage) => void;
45
+ /** Callback on error */
46
+ readonly onError?: (error: string) => void;
47
+ }
48
+
49
+ /**
50
+ * Chat hook return value
51
+ */
52
+ export interface UseChatReturn {
53
+ /** Messages in conversation */
54
+ readonly messages: ChatMessage[];
55
+ /** Loading state */
56
+ readonly isLoading: boolean;
57
+ /** Error message */
58
+ readonly error: string | null;
59
+ /** Is AI typing */
60
+ readonly isTyping: boolean;
61
+ /** Send message */
62
+ sendMessage: (text: string, type?: ChatMessage["type"]) => Promise<void>;
63
+ /** Regenerate last AI response */
64
+ regenerate: () => Promise<void>;
65
+ /** Clear messages */
66
+ clearMessages: () => void;
67
+ /** Update configuration */
68
+ updateConfig: (config: Partial<ChatConfig>) => void;
69
+ }
70
+
71
+ /**
72
+ * Message formatter for Groq
73
+ */
74
+ export interface IMessageFormatter {
75
+ /** Format chat messages to Groq format */
76
+ toGroqMessages(messages: ChatMessage[], systemPrompt?: string): GroqMessage[];
77
+ /** Format Groq response to chat message */
78
+ toChatMessage(content: string, sender: ChatMessage["sender"]): ChatMessage;
79
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Chat Interfaces
3
+ */
4
+
5
+ export type {
6
+ IChatService,
7
+ UseChatOptions,
8
+ UseChatReturn,
9
+ IMessageFormatter,
10
+ } from "./chat.interface";
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Chat Service
3
+ * @description Core chat logic with AI integration
4
+ */
5
+
6
+ import type {
7
+ IChatService,
8
+ IMessageFormatter,
9
+ } from "../../interfaces";
10
+ import type {
11
+ ChatMessage,
12
+ ChatConversation,
13
+ SendMessageInput,
14
+ SendMessageResult,
15
+ ChatConfig,
16
+ } from "../../entities";
17
+ import { textGenerationService } from "../../../groq/services/text-generation.service";
18
+ import { messageFormatter } from "../utils/message-formatter";
19
+
20
+ const DEFAULT_CONFIG: ChatConfig = {
21
+ temperature: 0.8,
22
+ maxTokens: 500,
23
+ includeTimestamp: true,
24
+ language: "tr",
25
+ };
26
+
27
+ class ChatService implements IChatService {
28
+ private config: ChatConfig = DEFAULT_CONFIG;
29
+
30
+ initialize(config: ChatConfig): void {
31
+ this.config = { ...DEFAULT_CONFIG, ...config };
32
+ }
33
+
34
+ updateConfig(config: Partial<ChatConfig>): void {
35
+ this.config = { ...this.config, ...config };
36
+ }
37
+
38
+ async sendMessage(input: SendMessageInput): Promise<SendMessageResult> {
39
+ // Create user message
40
+ const userMessage = messageFormatter.toChatMessage(input.text, "user");
41
+ userMessage.type = input.type || "text";
42
+ if (input.imageUrl) {
43
+ userMessage.imageUrl = input.imageUrl;
44
+ }
45
+
46
+ // Generate AI response
47
+ const aiResponse = await this.generateAIResponse(
48
+ input.companionId,
49
+ input.text,
50
+ []
51
+ );
52
+
53
+ return {
54
+ userMessage,
55
+ aiResponse,
56
+ };
57
+ }
58
+
59
+ async getConversation(conversationId: string): Promise<ChatConversation | null> {
60
+ // This would fetch from storage
61
+ // For now, return null - storage is handled by application
62
+ return null;
63
+ }
64
+
65
+ async getConversations(): Promise<ChatConversation[]> {
66
+ // This would fetch from storage
67
+ return [];
68
+ }
69
+
70
+ async generateAIResponse(
71
+ companionId: string,
72
+ userMessage: string,
73
+ context: ChatMessage[] = []
74
+ ): Promise<ChatMessage> {
75
+ try {
76
+ // Build system prompt from config
77
+ const systemPrompt = this.buildSystemPrompt();
78
+
79
+ // Format messages for Groq
80
+ const groqMessages = messageFormatter.toGroqMessages(
81
+ context,
82
+ systemPrompt
83
+ );
84
+
85
+ // Add current user message
86
+ groqMessages.push({
87
+ role: "user",
88
+ content: userMessage,
89
+ });
90
+
91
+ // Generate response
92
+ const response = await textGenerationService.generateChatCompletion(
93
+ groqMessages,
94
+ {
95
+ model: "llama-3.3-70b-versatile",
96
+ generationConfig: {
97
+ temperature: this.config.temperature,
98
+ maxTokens: this.config.maxTokens,
99
+ },
100
+ }
101
+ );
102
+
103
+ // Format response as chat message
104
+ const aiMessage = messageFormatter.toChatMessage(response, "assistant");
105
+ aiMessage.metadata = {
106
+ companionId,
107
+ model: "llama-3.3-70b-versatile",
108
+ };
109
+
110
+ return aiMessage;
111
+ } catch (error) {
112
+ console.error("[ChatService] Error generating AI response:", error);
113
+
114
+ // Fallback response
115
+ return messageFormatter.toChatMessage(
116
+ "Şimdi biraz meşgulüm, ama seni duyuyorum! 💫",
117
+ "assistant"
118
+ );
119
+ }
120
+ }
121
+
122
+ private buildSystemPrompt(): string {
123
+ const language = this.config.language || "tr";
124
+ const basePrompt = this.config.systemPrompt || this.getDefaultPrompt(language);
125
+
126
+ return basePrompt;
127
+ }
128
+
129
+ private getDefaultPrompt(language: string): string {
130
+ if (language === "tr") {
131
+ return `Sen samimi, eğlenceli ve ilgi çekici bir AI companionsın. Türkçe konuşuyorsun.
132
+ Kullanıcıyla doğal, rahat ve arkadaşça bir sohbet tarzı benimseyerek iletişim kur.
133
+ Yavaş yazma stilini kullan ama abartma. Emoji kullanabilirsin ama çok da abartma.
134
+ Kısa ve öz cevaplar ver.`;
135
+ }
136
+
137
+ return `You are a friendly, engaging AI companion. Be natural, casual, and warm.
138
+ Keep responses concise and conversational. Use emojis sparingly.`;
139
+ }
140
+ }
141
+
142
+ export const chatService = new ChatService();
143
+ export { messageFormatter };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Chat Services
3
+ */
4
+
5
+ export { chatService, messageFormatter } from "./chat.service";
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Message Formatter Utility
3
+ * @description Convert between chat messages and Groq format
4
+ */
5
+
6
+ import type { IMessageFormatter } from "../interfaces";
7
+ import type { ChatMessage } from "../entities";
8
+ import type { GroqMessage } from "../../groq/interfaces";
9
+
10
+ class MessageFormatter implements IMessageFormatter {
11
+ toGroqMessages(messages: ChatMessage[], systemPrompt?: string): GroqMessage[] {
12
+ const groqMessages: GroqMessage[] = [];
13
+
14
+ // Add system prompt first
15
+ if (systemPrompt) {
16
+ groqMessages.push({
17
+ role: "system",
18
+ content: systemPrompt,
19
+ });
20
+ }
21
+
22
+ // Convert chat messages to Groq format
23
+ for (const message of messages) {
24
+ // Skip system messages from context
25
+ if (message.sender === "system") continue;
26
+
27
+ groqMessages.push({
28
+ role: message.sender === "user" ? "user" : "assistant",
29
+ content: message.content,
30
+ });
31
+ }
32
+
33
+ return groqMessages;
34
+ }
35
+
36
+ toChatMessage(content: string, sender: ChatMessage["sender"]): ChatMessage {
37
+ return {
38
+ id: `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
39
+ sender,
40
+ content: content.trim(),
41
+ timestamp: new Date().toISOString(),
42
+ type: "text",
43
+ };
44
+ }
45
+ }
46
+
47
+ export const messageFormatter = new MessageFormatter();
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Chat Domain Entities
3
+ * @description Core chat message and conversation types
4
+ */
5
+
6
+ /**
7
+ * Message sender type
8
+ */
9
+ export type ChatMessageSender = "user" | "assistant" | "system";
10
+
11
+ /**
12
+ * Message content types
13
+ */
14
+ export type ChatMessageType = "text" | "image" | "audio" | "sticker";
15
+
16
+ /**
17
+ * Chat message structure
18
+ */
19
+ export interface ChatMessage {
20
+ /** Unique message identifier */
21
+ readonly id: string;
22
+ /** Sender of the message */
23
+ readonly sender: ChatMessageSender;
24
+ /** Message content */
25
+ readonly content: string;
26
+ /** Timestamp in ISO format */
27
+ readonly timestamp: string;
28
+ /** Message type */
29
+ readonly type?: ChatMessageType;
30
+ /** Image URL for image messages */
31
+ readonly imageUrl?: string;
32
+ /** Reaction emoji */
33
+ readonly reaction?: string;
34
+ /** Metadata */
35
+ readonly metadata?: Record<string, unknown>;
36
+ }
37
+
38
+ /**
39
+ * Conversation/session metadata
40
+ */
41
+ export interface ChatConversation {
42
+ /** Unique conversation identifier */
43
+ readonly id: string;
44
+ /** Companion/character identifier */
45
+ readonly companionId: string;
46
+ /** Companion name */
47
+ readonly companionName: string;
48
+ /** Last message */
49
+ readonly lastMessage?: ChatMessage;
50
+ /** Message count */
51
+ readonly messageCount: number;
52
+ /** Updated timestamp */
53
+ readonly updatedAt: string;
54
+ /** Is pinned */
55
+ readonly pinned?: boolean;
56
+ /** Is archived */
57
+ readonly archived?: boolean;
58
+ }
59
+
60
+ /**
61
+ * Send message input
62
+ */
63
+ export interface SendMessageInput {
64
+ /** Companion identifier */
65
+ readonly companionId: string;
66
+ /** Message text */
67
+ readonly text: string;
68
+ /** Message type */
69
+ readonly type?: ChatMessageType;
70
+ /** Image URL */
71
+ readonly imageUrl?: string;
72
+ }
73
+
74
+ /**
75
+ * Send message result
76
+ */
77
+ export interface SendMessageResult {
78
+ /** User message */
79
+ readonly userMessage: ChatMessage;
80
+ /** AI response (if generated) */
81
+ readonly aiResponse?: ChatMessage;
82
+ }
83
+
84
+ /**
85
+ * Chat configuration
86
+ */
87
+ export interface ChatConfig {
88
+ /** System prompt for AI personality */
89
+ readonly systemPrompt?: string;
90
+ /** Temperature for randomness */
91
+ readonly temperature?: number;
92
+ /** Maximum tokens */
93
+ readonly maxTokens?: number;
94
+ /** Include timestamp in messages */
95
+ readonly includeTimestamp?: boolean;
96
+ /** Language code (e.g., 'tr', 'en') */
97
+ readonly language?: string;
98
+ }
99
+
100
+ /**
101
+ * Storage interface for persisting messages
102
+ * Implementations should be provided by the application
103
+ */
104
+ export interface ChatStorage {
105
+ /** Save message to storage */
106
+ saveMessage(conversationId: string, message: ChatMessage): Promise<void>;
107
+ /** Get messages for conversation */
108
+ getMessages(conversationId: string): Promise<ChatMessage[]>;
109
+ /** Update message */
110
+ updateMessage(messageId: string, updates: Partial<ChatMessage>): Promise<void>;
111
+ /** Delete message */
112
+ deleteMessage(messageId: string): Promise<void>;
113
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Groq Domain
3
+ * @description Groq API client and text generation
4
+ * Subpath: @umituz/web-ai-groq-provider/groq
5
+ */
6
+
7
+ // Entities
8
+ export type {
9
+ GroqMessageRole,
10
+ GroqMessage,
11
+ GroqChatRequest,
12
+ GroqChoice,
13
+ GroqFinishReason,
14
+ GroqUsage,
15
+ GroqChatResponse,
16
+ GroqChunkChoice,
17
+ GroqChatChunk,
18
+ GroqErrorResponse,
19
+ } from "./entities";
20
+
21
+ export type {
22
+ GroqConfig,
23
+ GroqGenerationConfig,
24
+ } from "./entities";
25
+
26
+ // Interfaces
27
+ export type {
28
+ TextGenerationOptions,
29
+ StreamingCallbacks,
30
+ StructuredGenerationOptions,
31
+ } from "./interfaces";
32
+
33
+ export type { IGroqChatService, IGroqHttpClient } from "./interfaces";
34
+
35
+ // Services
36
+ export { textGenerationService, groqHttpClient } from "./services";
37
+
38
+ // Hooks
39
+ export { useGroq } from "./hooks";
40
+ export type { UseGroqOptions, UseGroqReturn } from "./hooks";
41
+
42
+ // Constants
43
+ export {
44
+ GROQ_MODELS,
45
+ DEFAULT_MODELS,
46
+ DEFAULT_GENERATION_CONFIG,
47
+ API_ENDPOINTS,
48
+ DEFAULT_BASE_URL,
49
+ TIMEOUTS,
50
+ } from "./constants";
51
+
52
+ export {
53
+ GroqErrorType,
54
+ mapHttpStatusToErrorType,
55
+ isRetryableError,
56
+ isAuthError,
57
+ } from "./constants";
58
+
59
+ // Utils
60
+ export {
61
+ createUserMessage,
62
+ createAssistantMessage,
63
+ createSystemMessage,
64
+ createTextMessage,
65
+ promptToMessages,
66
+ extractTextFromMessages,
67
+ formatMessagesForDisplay,
68
+ } from "./utils";
69
+
70
+ export { getUserFriendlyError, formatErrorForLogging } from "./utils";
71
+
72
+ export { GroqError } from "./utils";
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Chat Service Interfaces
3
+ * @description Contracts for chat functionality
4
+ */
5
+
6
+ import type {
7
+ ChatMessage,
8
+ ChatConversation,
9
+ SendMessageInput,
10
+ SendMessageResult,
11
+ ChatConfig,
12
+ ChatStorage,
13
+ } from "../entities";
14
+ import type { GroqMessage } from "./groq.interface";
15
+
16
+ /**
17
+ * Chat service interface
18
+ */
19
+ export interface IChatService {
20
+ /** Send message and get AI response */
21
+ sendMessage(input: SendMessageInput): Promise<SendMessageResult>;
22
+ /** Get conversation history */
23
+ getConversation(conversationId: string): Promise<ChatConversation | null>;
24
+ /** Get all conversations */
25
+ getConversations(): Promise<ChatConversation[]>;
26
+ /** Generate AI response */
27
+ generateAIResponse(conversationId: string, userMessage: string): Promise<ChatMessage>;
28
+ }
29
+
30
+ /**
31
+ * Chat hook options
32
+ */
33
+ export interface UseChatOptions {
34
+ /** Conversation identifier */
35
+ readonly conversationId: string;
36
+ /** Storage implementation */
37
+ readonly storage?: ChatStorage;
38
+ /** Chat configuration */
39
+ readonly config?: ChatConfig;
40
+ /** Auto-save messages */
41
+ readonly autoSave?: boolean;
42
+ /** Callback on message sent */
43
+ readonly onMessageSent?: (message: ChatMessage) => void;
44
+ /** Callback on AI response */
45
+ readonly onAIResponse?: (message: ChatMessage) => void;
46
+ /** Callback on error */
47
+ readonly onError?: (error: string) => void;
48
+ }
49
+
50
+ /**
51
+ * Chat hook return value
52
+ */
53
+ export interface UseChatReturn {
54
+ /** Messages in conversation */
55
+ readonly messages: ChatMessage[];
56
+ /** Loading state */
57
+ readonly isLoading: boolean;
58
+ /** Error message */
59
+ readonly error: string | null;
60
+ /** Is AI typing */
61
+ readonly isTyping: boolean;
62
+ /** Send message */
63
+ sendMessage: (text: string, type?: ChatMessage["type"]) => Promise<void>;
64
+ /** Regenerate last AI response */
65
+ regenerate: () => Promise<void>;
66
+ /** Clear messages */
67
+ clearMessages: () => void;
68
+ /** Update configuration */
69
+ updateConfig: (config: Partial<ChatConfig>) => void;
70
+ }
71
+
72
+ /**
73
+ * Message formatter for Groq
74
+ */
75
+ export interface MessageFormatter {
76
+ /** Format chat messages to Groq format */
77
+ toGroqMessages(messages: ChatMessage[], systemPrompt?: string): GroqMessage[];
78
+ /** Format Groq response to chat message */
79
+ toChatMessage(content: string, sender: ChatMessage["sender"]): ChatMessage;
80
+ }
package/src/index.ts CHANGED
@@ -1,78 +1,16 @@
1
1
  /**
2
2
  * @umituz/web-ai-groq-provider
3
- * Groq AI text generation provider for React web applications
3
+ * Groq AI text generation and chat provider for React web applications
4
4
  *
5
5
  * @author umituz
6
6
  * @license MIT
7
7
  *
8
8
  * IMPORTANT: Apps should NOT use this root barrel import.
9
9
  * Use subpath imports instead:
10
- * - @umituz/web-ai-groq-provider/domain
11
- * - @umituz/web-ai-groq-provider/services
12
- * - @umituz/web-ai-groq-provider/hooks
10
+ * - @umituz/web-ai-groq-provider/groq - Groq API client
11
+ * - @umituz/web-ai-groq-provider/chat - Chat functionality
13
12
  */
14
13
 
15
- // Domain layer
16
- export type {
17
- GroqMessageRole,
18
- GroqMessage,
19
- GroqChatRequest,
20
- GroqChoice,
21
- GroqFinishReason,
22
- GroqUsage,
23
- GroqChatResponse,
24
- GroqChunkChoice,
25
- GroqChatChunk,
26
- GroqErrorResponse,
27
- } from "./domain/entities";
28
-
29
- export type {
30
- GroqConfig,
31
- GroqGenerationConfig,
32
- TextGenerationOptions,
33
- StreamingCallbacks,
34
- StructuredGenerationOptions,
35
- } from "./domain/interfaces";
36
-
37
- export type { IGroqChatService, IGroqHttpClient } from "./domain/interfaces";
38
-
39
- // Infrastructure layer
40
- export {
41
- GROQ_MODELS,
42
- DEFAULT_MODELS,
43
- DEFAULT_GENERATION_CONFIG,
44
- API_ENDPOINTS,
45
- DEFAULT_BASE_URL,
46
- TIMEOUTS,
47
- } from "./infrastructure/constants";
48
-
49
- export {
50
- GroqErrorType,
51
- mapHttpStatusToErrorType,
52
- isRetryableError,
53
- isAuthError,
54
- } from "./infrastructure/constants";
55
-
56
- export { groqHttpClient } from "./infrastructure/services";
57
- export { textGenerationService } from "./infrastructure/services";
58
-
59
- export {
60
- createUserMessage,
61
- createAssistantMessage,
62
- createSystemMessage,
63
- createTextMessage,
64
- promptToMessages,
65
- extractTextFromMessages,
66
- formatMessagesForDisplay,
67
- } from "./infrastructure/utils";
68
-
69
- export {
70
- getUserFriendlyError,
71
- formatErrorForLogging,
72
- } from "./infrastructure/utils";
73
-
74
- export { GroqError } from "./infrastructure/utils";
75
-
76
- // Presentation layer
77
- export { useGroq } from "./presentation/hooks";
78
- export type { UseGroqOptions, UseGroqReturn } from "./presentation/hooks";
14
+ // Re-export domains for backward compatibility
15
+ export * from "./domains/groq";
16
+ export * from "./domains/chat";
@@ -1,32 +0,0 @@
1
- /**
2
- * Domain Layer Index
3
- * Subpath: @umituz/web-ai-groq-provider/domain
4
- *
5
- * Exports all entities and interfaces
6
- */
7
-
8
- // Entities
9
- export type {
10
- GroqMessageRole,
11
- GroqMessage,
12
- GroqChatRequest,
13
- GroqChoice,
14
- GroqFinishReason,
15
- GroqUsage,
16
- GroqChatResponse,
17
- GroqChunkChoice,
18
- GroqChatChunk,
19
- GroqErrorResponse,
20
- GroqMessageCreateInput,
21
- } from "./entities";
22
-
23
- // Interfaces
24
- export type {
25
- GroqConfig,
26
- GroqGenerationConfig,
27
- TextGenerationOptions,
28
- StreamingCallbacks,
29
- StructuredGenerationOptions,
30
- IGroqChatService,
31
- IGroqHttpClient,
32
- } from "./interfaces";
File without changes