File size: 12,243 Bytes
5fc68b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import { BaseChatModel } from "@langchain/core/language_models/chat_models";
import { Embeddings } from "@langchain/core/embeddings";
import { CHAT_MODELS, EMBEDDING_MODELS, IConfig, MODALITIES, PROVIDERS } from "@/lib/config/types";
import { ConfigManager } from "@/lib/config/manager";
import { ChatOllama, OllamaEmbeddings } from "@langchain/ollama";
import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";
import { ChatAnthropic } from "@langchain/anthropic";
import { ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings } from "@langchain/google-genai";
import { IDocument } from "../document/types";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { Tool } from "langchain/tools";
import { Calculator } from "@langchain/community/tools/calculator";
import { AgentExecutor, createToolCallingAgent } from "langchain/agents";
import { RunnableWithMessageHistory } from "@langchain/core/runnables";
import { DexieChatMemory } from "./memory";
import { DocumentManager } from "@/lib/document/manager";
import { Document } from "@langchain/core/documents";
import { HumanMessage, ToolMessage } from "@langchain/core/messages";
import { IChatSession } from "./types";

export class ChatManager {
  model!: BaseChatModel;
  embeddings!: Embeddings;
  controller!: AbortController;
  configManager!: ConfigManager;
  config!: IConfig;
  documentManager!: DocumentManager;

  constructor() {
    this.controller = new AbortController();
    this.initializeModels();
    this.documentManager = DocumentManager.getInstance();
  }

  private async initializeModels() {
    this.configManager = await ConfigManager.getInstance();
    this.config = await this.configManager.getConfig();
  }

  private async getChatModel(modelName: string): Promise<BaseChatModel> {
    const model = CHAT_MODELS.find(m => m.model === modelName);

    if (!model) {
      throw new Error(`Chat model ${modelName} not found`);
    }

    switch (model.provider) {
      case PROVIDERS.ollama:
        return new ChatOllama({
          baseUrl: this.config.ollama_base_url,
          model: model.model,
        });

      case PROVIDERS.openai:
        return new ChatOpenAI({
          modelName: model.model,
          apiKey: this.config.openai_api_key,
        });

      case PROVIDERS.anthropic:
        return new ChatAnthropic({
          modelName: model.model,
          apiKey: this.config.anthropic_api_key,
        });

      case PROVIDERS.gemini:
        return new ChatGoogleGenerativeAI({
          modelName: model.model,
          apiKey: this.config.gemini_api_key,
        });

      default:
        throw new Error(`Provider ${model.provider} not implemented yet for chat models`);
    }
  }

  private async getEmbeddingModel(modelName: string): Promise<Embeddings> {
    const model = EMBEDDING_MODELS.find(m => m.model === modelName);

    if (!model) {
      throw new Error(`Embedding model ${modelName} not found`);
    }

    switch (model.provider) {
      case PROVIDERS.ollama:
        return new OllamaEmbeddings({
          baseUrl: this.config.ollama_base_url,
          model: model.model,
        });

      case PROVIDERS.openai:
        return new OpenAIEmbeddings({
          modelName: model.model,
          apiKey: this.config.openai_api_key,
        });

      case PROVIDERS.gemini:
        return new GoogleGenerativeAIEmbeddings({
          modelName: model.model,
          apiKey: this.config.gemini_api_key,
        });

      default:
        throw new Error(`Provider ${model.provider} not implemented yet for embedding models`);
    }
  }

  private async getAgent(
    enabledTools: string[] = [],
  ) {
    const prompt = ChatPromptTemplate.fromMessages([
      ["system", "You are a helpful assistant"],
      ["placeholder", "{chat_history}"],
      ["human", "{input}"],
      ["placeholder", "{agent_scratchpad}"],
    ]);

    const tools: Tool[] = [];
    if (enabledTools?.includes("calculator")) {
      tools.push(new Calculator());
    }

    const agent = createToolCallingAgent({
      llm: this.model,
      tools,
      prompt,
    });

    const agentExecutor = new AgentExecutor({
      agent,
      tools,
      returnIntermediateSteps: true,
    })

    return new RunnableWithMessageHistory({
      runnable: agentExecutor,
      getMessageHistory: (sessionId: string) => new DexieChatMemory(sessionId),
      inputMessagesKey: "input",
      historyMessagesKey: "chat_history"
    });
  }

  private async createMessageWithAttachments(
    documents?: IDocument[],
    chatSession?: IChatSession,
  ): Promise<HumanMessage> {
    if (!documents || documents.length === 0) {
      return new HumanMessage({ content: "" });
    }
  
    const currentModel = CHAT_MODELS.find(
      m => m.model === (chatSession?.model || this.config.default_chat_model)
    );
    
    if (!currentModel) {
      throw new Error(`Model ${chatSession?.model || this.config.default_chat_model} not found in CHAT_MODELS`);
    }
  
    // Initialize containers for different file types
    const processedContent: {
      docs: Document[];
      images: File[];
      audios: File[];
      videos: File[];
      pdfs: File[];
    } = {
      docs: [],
      images: [],
      audios: [],
      videos: [],
      pdfs: []
    };
  
    // Process and categorize documents based on type and model capabilities
    for (const doc of documents) {
      const file = await this.documentManager.getDocument(doc.id);
      
      switch (doc.type) {
        case "image":
          if (currentModel.modalities.includes(MODALITIES.image)) {
            processedContent.images.push(file);
          }
          break;
        case "audio":
          if (currentModel.modalities.includes(MODALITIES.audio)) {
            processedContent.audios.push(file);
          }
          break;
        case "video":
          if (currentModel.modalities.includes(MODALITIES.video)) {
            processedContent.videos.push(file);
          }
          break;
        case "pdf":
          if (currentModel.modalities.includes(MODALITIES.pdf)) {
            processedContent.pdfs.push(file);
          } else {
            processedContent.docs.push(...(await this.documentManager.loadDocument(doc.id)));
          }
          break;
        default:
          processedContent.docs.push(...(await this.documentManager.loadDocument(doc.id)));
          break;
      }
    }
  
    // Provider-specific content formatting
    const providerFormatters = {
      [PROVIDERS.openai]: async () => {
        const content = [];
        
        // Add images
        for (const image of processedContent.images) {
          const base64 = Buffer.from(await image.arrayBuffer()).toString("base64");
          content.push({
            type: "image_url",
            image_url: {
              url: `data:${image.type};base64,${base64}`
            }
          });
        }
        
        // Add text documents
        for (const doc of processedContent.docs) {
          content.push({
            type: "text",
            text: `File name: ${doc.metadata.name}\nFile content: ${doc.pageContent}`
          });
        }
        
        return content;
      },
  
      [PROVIDERS.anthropic]: async () => {
        const content = [];
        
        // Add images
        for (const image of processedContent.images) {
          const base64 = Buffer.from(await image.arrayBuffer()).toString("base64");
          content.push({
            type: "image_url",
            image_url: {
              url: `data:${image.type};base64,${base64}`
            }
          });
        }
        
        // Add PDFs
        for (const pdf of processedContent.pdfs) {
          content.push({
            type: "document",
            source: {
              type: "base64",
              data: Buffer.from(await pdf.arrayBuffer()).toString("base64"),
              media_type: "application/pdf",
            }
          });
        }
        
        // Add text documents
        for (const doc of processedContent.docs) {
          content.push({
            type: "text",
            text: `File name: ${doc.metadata.name}\nFile content: ${doc.pageContent}`
          });
        }
        
        return content;
      },
  
      [PROVIDERS.ollama]: async () => {
        // Ollama only supports text content
        return processedContent.docs.map(doc => ({
          type: "text",
          text: `File name: ${doc.metadata.name}\nFile content: ${doc.pageContent}`
        }));
      },
  
      [PROVIDERS.gemini]: async () => {
        const content = [];
        
        // Process media files (images, audio, video)
        const mediaFiles = [...processedContent.images, ...processedContent.audios, ...processedContent.videos, ...processedContent.pdfs];
        for (const media of mediaFiles) {
          content.push({
            type: "media",
            mimeType: media.type,
            data: Buffer.from(await media.arrayBuffer()).toString("base64")
          });
        }
        
        // Add text documents
        for (const doc of processedContent.docs) {
          content.push({
            type: "text",
            text: `File name: ${doc.metadata.name}\nFile content: ${doc.pageContent}`
          });
        }
        
        return content;
      }
    };
  
    // Get the appropriate formatter for the current provider
    const formatter = providerFormatters[currentModel.provider];
    if (!formatter) {
      throw new Error(`Provider ${currentModel.provider} not implemented for message attachments`);
    }
  
    // Format the content according to provider specifications
    const content = await formatter();
  
    return new HumanMessage({
      content,
      response_metadata: {
        documents: documents.map(document => ({
          id: document.id,
          name: document.name,
          source: document.path,
          type: document.type,
          createdAt: document.createdAt,
        }))
      }
    });
  }

  async *chat(
    sessionId: string,
    input: string,
    documents?: IDocument[],
  ) {
    const memory = new DexieChatMemory(sessionId);
    await memory.initialize(); // Initialize memory once at the start
    
    const chatSession = await memory.db.table("sessions").get(sessionId);
    
    this.model = await this.getChatModel(chatSession?.model || this.config.default_chat_model);
    this.embeddings = await this.getEmbeddingModel(chatSession?.embedding_model || this.config.default_embedding_model);

    const agent = await this.getAgent(chatSession?.enabled_tools || []);

    const documentMessage = await this.createMessageWithAttachments(documents, chatSession);

    if (documentMessage.content && documentMessage.content.length > 0) {
      await memory.addMessage(documentMessage);
    }

    const eventStream = await agent.streamEvents(
      { input },
      {
        configurable: {
          sessionId,
        },
        version: "v2",
        signal: this.controller.signal,
      }
    )
    let currentResponse = "";
    for await (const event of eventStream) {
      if (event.event === "on_chat_model_stream") {
        const chunk = event.data?.chunk;
        if (chunk) {
          currentResponse += chunk;
          yield { type: "stream", content: chunk };
        }
      } else if (event.event === "on_chat_model_end") {
        yield { type: "end", content: currentResponse };
      } else if (event.event === "on_tool_start") {
        yield { type: "tool_start", name: event.name, input: event.data?.input };
      } else if (event.event === "on_tool_end") {
        // Store tool interaction in memory
        console.log(event)
        await memory.addMessage(new ToolMessage({
          tool_call_id: event.name,
          content: event.data?.output,
          name: event.name,
          status: "success", // Since we're in the on_tool_end event, we know it succeeded
          artifact: event.data, // Store the full tool output data as artifact
          response_metadata: {
            input: event.data?.input,
            timestamp: Date.now()
          }
        }));
        yield { type: "tool_end", name: event.name, output: event.data?.output };
      }
    }
  }
}