File size: 32,156 Bytes
68394ea
adb504f
d3051c0
 
68394ea
b1c8f17
26e0ddc
d3051c0
68394ea
 
 
 
 
 
2bb5179
f5f5951
62ab01b
 
 
4d0ec3e
 
 
 
 
 
 
 
 
 
 
 
26e0ddc
b1c8f17
2e76cf7
adb504f
4bf6be6
adb504f
 
d3051c0
751cd9f
d3051c0
 
 
 
 
 
 
 
b1c8f17
1fc729a
d3051c0
 
 
 
 
68394ea
 
26e0ddc
 
 
 
d3051c0
68394ea
 
 
26e0ddc
 
 
2bb5179
 
2e6b166
751cd9f
2e6b166
 
2bb5179
 
 
2e6b166
751cd9f
2bb5179
 
 
26e0ddc
 
4d0ec3e
26e0ddc
2bb5179
 
26e0ddc
 
d3051c0
 
26e0ddc
68394ea
 
 
 
 
 
 
 
 
 
 
768bfff
68394ea
751cd9f
4d0ec3e
68394ea
 
 
 
 
 
bc4a455
4d0ec3e
f8ac6db
68394ea
26e0ddc
f8ac6db
d3051c0
 
 
 
 
adb504f
68394ea
b4b055b
 
 
 
 
68394ea
 
 
4d0ec3e
26e0ddc
4d0ec3e
d3051c0
 
adb504f
 
4d0ec3e
adb504f
 
 
68394ea
5c4af3f
 
68394ea
4d0ec3e
5c4af3f
 
68394ea
 
 
 
 
 
 
 
 
 
4d0ec3e
68394ea
 
 
 
4d0ec3e
5c4af3f
68394ea
 
 
 
 
4d0ec3e
68394ea
 
 
902db61
68394ea
 
 
 
 
 
 
 
 
 
 
 
4d0ec3e
62ab01b
68394ea
 
d3051c0
68394ea
768bfff
 
 
 
 
 
 
 
 
 
751cd9f
768bfff
 
4d0ec3e
68394ea
 
 
 
 
 
 
 
 
 
 
f8ac6db
68394ea
f8ac6db
68394ea
 
 
4d0ec3e
68394ea
 
2fc91ef
2bb5179
62ab01b
91592b0
 
 
 
2bb5179
 
 
 
 
 
 
 
 
768bfff
4d0ec3e
b66bfbf
768bfff
91592b0
 
 
 
768bfff
 
186c81e
287c42b
768bfff
91592b0
 
 
768bfff
4d0ec3e
91592b0
2bb5179
16ef4d2
768bfff
4d0ec3e
91592b0
e7c157d
91592b0
 
2bb5179
91592b0
 
 
 
 
 
 
 
 
 
 
 
2bb5179
91592b0
2bb5179
91592b0
2bb5179
 
 
91592b0
39d8469
2bb5179
91592b0
113e85f
 
751cd9f
113e85f
 
 
 
 
 
 
 
 
 
149368e
91592b0
543eb4f
113e85f
 
91592b0
 
 
113e85f
a5175b8
 
e5c2d73
91592b0
113e85f
91592b0
a5175b8
e0c39a8
149368e
113e85f
149368e
 
113e85f
91592b0
 
 
 
 
 
149368e
 
91592b0
 
 
 
 
 
 
149368e
 
effe83d
 
 
 
5d03011
effe83d
 
 
 
 
 
 
 
 
01f7187
 
 
 
effe83d
 
 
 
 
 
 
01f7187
 
effe83d
 
 
5594ef5
 
788373a
f029274
 
f5f5951
 
 
 
f029274
9056c98
f029274
 
9056c98
f5f5951
 
 
 
8456762
f5f5951
8456762
f5f5951
 
 
 
 
 
 
f029274
 
f5f5951
 
8456762
f5f5951
 
f029274
 
f5f5951
 
 
 
effe83d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cda7d3
 
66cde55
effe83d
 
 
b26206f
effe83d
 
 
 
 
 
 
 
5c074f1
effe83d
 
 
d7f34ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66cde55
d7f34ff
 
 
 
 
1ed50ec
 
 
d7f34ff
 
 
 
 
ecd288b
 
 
6474977
ecd288b
149368e
ecd288b
 
 
 
 
 
 
1e5af2b
ecd288b
 
 
 
 
 
 
149368e
ecd288b
 
0509a02
ecd288b
01f7187
 
 
 
 
 
 
 
 
 
 
 
 
 
ecd288b
01f7187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a18670
 
 
ecd288b
0509a02
149368e
d7f34ff
 
91592b0
f6c67ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95fd325
e93eaf6
5a0dcce
f6c67ca
 
 
 
5a0dcce
95fd325
f6c67ca
 
e93eaf6
0a18cf1
e93eaf6
 
f6c67ca
 
 
 
5a0dcce
 
 
f6c67ca
 
 
 
 
 
 
 
4a4b7af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9720994
4a4b7af
 
 
 
9720994
4a4b7af
 
 
 
 
 
 
 
 
 
9720994
4a4b7af
9720994
4a4b7af
 
 
 
 
 
 
 
bfcfdb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b36ea83
bfcfdb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6c67ca
2739d48
fdd448f
6474977
2739d48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30d2a63
2739d48
 
 
6474977
2739d48
 
 
 
30d2a63
2739d48
 
 
 
 
 
 
 
 
 
a9d9604
 
 
cdc3feb
 
 
58b4c6a
0f044f0
4a8152e
58b4c6a
 
 
6c8ee89
58b4c6a
4a8152e
 
 
 
0f044f0
 
 
 
4730670
 
58b4c6a
 
 
 
a139462
58b4c6a
54210e7
 
4d0ec3e
adb504f
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
from fastapi import FastAPI, HTTPException, Depends, Security, BackgroundTasks
from fastapi.security import APIKeyHeader
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from typing import Literal, List, Dict
import os
from functools import lru_cache
from openai import OpenAI
from uuid import uuid4
import tiktoken
import sqlite3
import time
from datetime import datetime, timedelta
import asyncio
import requests
from prompts import *
from fastapi_cache import FastAPICache
from fastapi_cache.backends.inmemory import InMemoryBackend
from fastapi_cache.decorator import cache
import logging

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("app.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

app = FastAPI()

API_KEY_NAME = "X-API-Key"
API_KEY = os.environ.get("CHAT_AUTH_KEY", "default_secret_key")
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)

ModelID = Literal[
    "openai/gpt-4o-mini",
    "meta-llama/llama-3-70b-instruct",
    "anthropic/claude-3.5-sonnet",
    "deepseek/deepseek-coder",
    "anthropic/claude-3-haiku",
    "openai/gpt-3.5-turbo-instruct",
    "qwen/qwen-72b-chat",
    "google/gemma-2-27b-it"
]

class QueryModel(BaseModel):
    user_query: str = Field(..., description="User's coding query")
    model_id: ModelID = Field(
        default="meta-llama/llama-3-70b-instruct",
        description="ID of the model to use for response generation"
    )
    conversation_id: str = Field(default_factory=lambda: str(uuid4()), description="Unique identifier for the conversation")
    user_id: str = Field(..., description="Unique identifier for the user")

    class Config:
        schema_extra = {
            "example": {
                "user_query": "How do I implement a binary search in Python?",
                "model_id": "meta-llama/llama-3-70b-instruct",
                "conversation_id": "123e4567-e89b-12d3-a456-426614174000",
                "user_id": "user123"
            }
        }

class NewsQueryModel(BaseModel):
    query: str = Field(..., description="News topic to search for")
    model_id: ModelID = Field(
        default="openai/gpt-4o-mini",
        description="ID of the model to use for response generation"
    )
    class Config:
        schema_extra = {
            "example": {
                "query": "Latest developments in AI",
                "model_id": "openai/gpt-4o-mini"
            }
        }

@lru_cache()
def get_api_keys():
    logger.info("Loading API keys")
    return {
        "OPENROUTER_API_KEY": f"sk-or-v1-{os.environ['OPENROUTER_API_KEY']}",
        "BRAVE_API_KEY": os.environ['BRAVE_API_KEY']
    }

api_keys = get_api_keys()
or_client = OpenAI(api_key=api_keys["OPENROUTER_API_KEY"], base_url="https://openrouter.ai/api/v1")

# In-memory storage for conversations
conversations: Dict[str, List[Dict[str, str]]] = {}
last_activity: Dict[str, float] = {}

# Token encoding
encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")

def limit_tokens(input_string, token_limit=6000):
    return encoding.decode(encoding.encode(input_string)[:token_limit])

def calculate_tokens(msgs):
    return sum(len(encoding.encode(str(m))) for m in msgs)

def chat_with_llama_stream(messages, model="openai/gpt-4o-mini", max_llm_history=4, max_output_tokens=2500):
    logger.info(f"Starting chat with model: {model}")
    while calculate_tokens(messages) > (8000 - max_output_tokens):
        if len(messages) > max_llm_history:
            messages = [messages[0]] + messages[-max_llm_history:]
        else:
            max_llm_history -= 1
            if max_llm_history < 2:
                error_message = "Token limit exceeded. Please shorten your input or start a new conversation."
                logger.error(error_message)
                raise HTTPException(status_code=400, detail=error_message)

    try:
        response = or_client.chat.completions.create(
            model=model,
            messages=messages,
            max_tokens=max_output_tokens,
            stream=True
        )
        
        full_response = ""
        for chunk in response:
            if chunk.choices[0].delta.content is not None:
                content = chunk.choices[0].delta.content
                full_response += content
                yield content
        
        # After streaming, add the full response to the conversation history
        messages.append({"role": "assistant", "content": full_response})
        logger.info("Chat completed successfully")
    except Exception as e:
        logger.error(f"Error in model response: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error in model response: {str(e)}")

async def verify_api_key(api_key: str = Security(api_key_header)):
    if api_key != API_KEY:
        logger.warning("Invalid API key used")
        raise HTTPException(status_code=403, detail="Could not validate credentials")
    return api_key

# SQLite setup
DB_PATH = '/app/data/conversations.db'

def init_db():
    logger.info("Initializing database")
    os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS conversations
                 (id INTEGER PRIMARY KEY AUTOINCREMENT,
                  user_id TEXT,
                  conversation_id TEXT,
                  message TEXT,
                  response TEXT,
                  timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''')
    conn.commit()
    conn.close()
    logger.info("Database initialized successfully")

init_db()

def update_db(user_id, conversation_id, message, response):
    logger.info(f"Updating database for conversation: {conversation_id}")
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    c.execute('''INSERT INTO conversations (user_id, conversation_id, message, response)
                 VALUES (?, ?, ?, ?)''', (user_id, conversation_id, message, response))
    conn.commit()
    conn.close()
    logger.info("Database updated successfully")

async def clear_inactive_conversations():
    while True:
        
        current_time = time.time()
        inactive_convos = [conv_id for conv_id, last_time in last_activity.items() 
                           if current_time - last_time > 1800]  # 30 minutes
        for conv_id in inactive_convos:
            if conv_id in conversations:
                del conversations[conv_id]
            if conv_id in last_activity:
                del last_activity[conv_id]
        await asyncio.sleep(60)  # Check every minute

@app.on_event("startup")
async def startup_event():
    logger.info("Starting up the application")
    FastAPICache.init(InMemoryBackend(), prefix="fastapi-cache")
    asyncio.create_task(clear_inactive_conversations())

@app.post("/coding-assistant")
async def coding_assistant(query: QueryModel, background_tasks: BackgroundTasks, api_key: str = Depends(verify_api_key)):
    """
    Coding assistant endpoint that provides programming help based on user queries.
    Available models:
    - meta-llama/llama-3-70b-instruct (default)
    - anthropic/claude-3.5-sonnet
    - deepseek/deepseek-coder
    - anthropic/claude-3-haiku
    - openai/gpt-3.5-turbo-instruct
    - qwen/qwen-72b-chat
    - google/gemma-2-27b-it
    - openai/gpt-4o-mini
    Requires API Key authentication via X-API-Key header.
    """
    logger.info(f"Received coding assistant query: {query.user_query}")
    if query.conversation_id not in conversations:
        conversations[query.conversation_id] = [
            {"role": "system", "content": "You are a helpful assistant proficient in coding tasks. Help the user in understanding and writing code."}
        ]
    
    conversations[query.conversation_id].append({"role": "user", "content": query.user_query})
    last_activity[query.conversation_id] = time.time()
    
    # Limit tokens in the conversation history
    limited_conversation = conversations[query.conversation_id]

    def process_response():
        full_response = ""
        for content in chat_with_llama_stream(limited_conversation, model=query.model_id):
            full_response += content
            yield content
        background_tasks.add_task(update_db, query.user_id, query.conversation_id, query.user_query, full_response)
        logger.info(f"Completed coding assistant response for query: {query.user_query}")

    return StreamingResponse(process_response(), media_type="text/event-stream")

# New functions for news assistant

def internet_search(query, search_type="web", num_results=20):
    logger.info(f"Performing internet search for query: {query}, type: {search_type}")
    url = f"https://api.search.brave.com/res/v1/{'web' if search_type == 'web' else 'news'}/search"
    
    headers = {
        "Accept": "application/json",
        "Accept-Encoding": "gzip",
        "X-Subscription-Token": api_keys["BRAVE_API_KEY"]
    }
    params = {"q": query}

    response = requests.get(url, headers=headers, params=params)

    if response.status_code != 200:
        logger.error(f"Failed to fetch search results. Status code: {response.status_code}")
        return []
    
    search_data = response.json()["web"]["results"] if search_type == "web" else response.json()["results"]
    
    processed_results = [
        {
            "title": item["title"],
            "snippet": item["extra_snippets"][0],
            "last_updated": item.get("age", ""),
            "url":item.get("url", "")
        }
        for item in search_data
        if item.get("extra_snippets")
    ][:num_results]

    logger.info(f"Retrieved {len(processed_results)} search results")
    return processed_results

@lru_cache(maxsize=100)
def cached_internet_search(query: str):
    logger.info(f"Performing cached internet search for query: {query}")
    return internet_search(query, search_type="news")

def analyze_data(query, data_type="news"):
    logger.info(f"Analyzing {data_type} for query: {query}")
    
    if data_type == "news":
        data = cached_internet_search(query)
        prompt_generator = generate_news_prompt
        system_prompt = NEWS_ASSISTANT_PROMPT
    else:
        data = internet_search(query, search_type="web")
        prompt_generator = generate_search_prompt
        system_prompt = SEARCH_ASSISTANT_PROMPT
    
    if not data:
        logger.error(f"Failed to fetch {data_type} data")
        return None

    prompt = prompt_generator(query, data)
    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": prompt}
    ]

    logger.info(f"{data_type.capitalize()} analysis completed")
    return messages,data

class QueryModel(BaseModel):
    query: str = Field(..., description="Search query")
    model_id: ModelID = Field(
        default="openai/gpt-4o-mini",
        description="ID of the model to use for response generation"
    )
    class Config:
        schema_extra = {
            "example": {
                "query": "What are the latest advancements in quantum computing?",
                "model_id": "meta-llama/llama-3-70b-instruct"
            }
        }

def search_assistant_api(query, data_type, model="openai/gpt-4o-mini"):
    logger.info(f"Received {data_type} assistant query: {query}")
    messages, search_data = analyze_data(query, data_type)
    
    if not messages:
        logger.error(f"Failed to fetch {data_type} data")
        raise HTTPException(status_code=500, detail=f"Failed to fetch {data_type} data")
    
    def process_response():
        logger.info(f"Generating response using LLM: {messages}")
        full_response = ""
        for content in chat_with_llama_stream(messages, model=model):
            full_response += content
            yield content
        logger.info(f"Completed {data_type} assistant response for query: {query}")
        logger.info(f"LLM Response: {full_response}")
        yield "<json><ref>"+ json.dumps(search_data)+"</ref></json>"
    return process_response

def create_streaming_response(generator):
    return StreamingResponse(generator(), media_type="text/event-stream")

@app.post("/news-assistant")
async def news_assistant(query: QueryModel, api_key: str = Depends(verify_api_key)):
    """
    News assistant endpoint that provides summaries and analysis of recent news based on user queries.
    Requires API Key authentication via X-API-Key header.
    """
    response_generator = search_assistant_api(query.query, "news", model=query.model_id)
    return create_streaming_response(response_generator)

@app.post("/search-assistant")
async def search_assistant(query: QueryModel, api_key: str = Depends(verify_api_key)):
    """
    Search assistant endpoint that provides summaries and analysis of web search results based on user queries.
    Requires API Key authentication via X-API-Key header.
    """
    response_generator = search_assistant_api(query.query, "web", model=query.model_id)
    return create_streaming_response(response_generator)

from pydantic import BaseModel, Field
import yaml
import json
from yaml.loader import SafeLoader

class FollowupQueryModel(BaseModel):
    query: str = Field(..., description="User's query for the followup agent")
    model_id: ModelID = Field(
        default="openai/gpt-4o-mini",
        description="ID of the model to use for response generation"
    )
    conversation_id: str = Field(default_factory=lambda: str(uuid4()), description="Unique identifier for the conversation")
    user_id: str = Field(..., description="Unique identifier for the user")
    tool_call: Literal["web", "news", "auto"] = Field(
        default="auto",
        description="Type of tool to call (web, news, auto)"
    )

    class Config:
        schema_extra = {
            "example": {
                "query": "How can I improve my productivity?",
                "model_id": "openai/gpt-4o-mini",
                "conversation_id": "123e4567-e89b-12d3-a456-426614174000",
                "user_id": "user123",
                "tool_call": "auto"
            }
        }

import re

def parse_followup_and_tools(input_text):
    # Remove extra brackets and excess quotes
    cleaned_text = re.sub(r'\[|\]|"+', ' ', input_text)
    
    # Extract response content
    response_pattern = re.compile(r'<response>(.*?)</response>', re.DOTALL)
    response_parts = response_pattern.findall(cleaned_text)
    combined_response = ' '.join(response_parts)
    
    # Normalize spaces in the combined response
    combined_response = ' '.join(combined_response.split())
    
    parsed_interacts = []
    parsed_tools = []
    
    # Parse interacts and tools
    blocks = re.finditer(r'<(interact|tools?)(.*?)>(.*?)</\1>', cleaned_text, re.DOTALL)
    for block in blocks:
        block_type, _, content = block.groups()
        content = content.strip()
        
        if block_type == 'interact':
            question_blocks = re.split(r'\s*-\s*text:', content)[1:]
            for qblock in question_blocks:
                parts = re.split(r'\s*options:\s*', qblock, maxsplit=1)
                if len(parts) == 2:
                    question = ' '.join(parts[0].split())  # Normalize spaces
                    options = [' '.join(opt.split()) for opt in re.split(r'\s*-\s*', parts[1]) if opt.strip()]
                    parsed_interacts.append({'question': question, 'options': options})
        
        elif block_type.startswith('tool'):  # This will match both 'tool' and 'tools'
            tool_match = re.search(r'text:\s*(.*?)\s*options:\s*-\s*(.*)', content, re.DOTALL)
            if tool_match:
                tool_name = ' '.join(tool_match.group(1).split())  # Normalize spaces
                option = ' '.join(tool_match.group(2).split())  # Normalize spaces
                parsed_tools.append({'name': tool_name, 'input': option})
    
    return combined_response, parsed_interacts, parsed_tools

@app.post("/followup-agent")
async def followup_agent(query: FollowupQueryModel, background_tasks: BackgroundTasks, api_key: str = Depends(verify_api_key)):
    """
    Followup agent endpoint that provides helpful responses or generates clarifying questions based on user queries.
    Requires API Key authentication via X-API-Key header.
    """
    logger.info(f"Received followup agent query: {query.query}")

    if query.conversation_id not in conversations:
        conversations[query.conversation_id] = [
            {"role": "system", "content": FOLLOWUP_AGENT_PROMPT}
        ]
    
    conversations[query.conversation_id].append({"role": "user", "content": query.query})
    last_activity[query.conversation_id] = time.time()
    
    # Limit tokens in the conversation history
    limited_conversation = conversations[query.conversation_id]

    def process_response():
        full_response = ""
        for content in chat_with_llama_stream(limited_conversation, model=query.model_id):
            full_response += content
            yield content

        logger.info(f"LLM RAW response for query: {query.query}: {full_response}")
        response_content, interact,tools = parse_followup_and_tools(full_response)
        
        result = {
            "response": response_content,
            "clarification": interact
        }
        
        yield "\n\n" + json.dumps(result)
        
        # Add the assistant's response to the conversation history
        conversations[query.conversation_id].append({"role": "assistant", "content": full_response})
        
        background_tasks.add_task(update_db, query.user_id, query.conversation_id, query.query, full_response)
        logger.info(f"Completed followup agent response for query: {query.query}, send result: {result}")

    return StreamingResponse(process_response(), media_type="text/event-stream")

@app.post("/v2/followup-agent")
async def followup_agent(query: FollowupQueryModel, background_tasks: BackgroundTasks, api_key: str = Depends(verify_api_key)):
    """
    Followup agent endpoint that provides helpful responses or generates clarifying questions based on user queries.
    Requires API Key authentication via X-API-Key header.
    """
    logger.info(f"Received followup agent query: {query.query}")

    if query.conversation_id not in conversations:
        conversations[query.conversation_id] = [
            {"role": "system", "content": FOLLOWUP_AGENT_PROMPT}
        ]
    
    conversations[query.conversation_id].append({"role": "user", "content": query.query})
    last_activity[query.conversation_id] = time.time()
    
    # Limit tokens in the conversation history
    limited_conversation = conversations[query.conversation_id]

    def process_response():
        full_response = ""
        for content in chat_with_llama_stream(limited_conversation, model=query.model_id):
            full_response += content
            yield content

        logger.info(f"LLM RAW response for query: {query.query}: {full_response}")
        response_content, interact,tools = parse_followup_and_tools(full_response)
        
        result = {
            "clarification": interact
        }
        
        yield "\n<json>"
        yield json.dumps(result)

        
        # Add the assistant's response to the conversation history
        conversations[query.conversation_id].append({"role": "assistant", "content": full_response})
        
        background_tasks.add_task(update_db, query.user_id, query.conversation_id, query.query, full_response)
        logger.info(f"Completed followup agent response for query: {query.query}, send result: {result}")

    return StreamingResponse(process_response(), media_type="text/event-stream")
    
@app.post("/v2/followup-tools-agent")
def followup_agent(query: FollowupQueryModel, background_tasks: BackgroundTasks, api_key: str = Depends(verify_api_key)):
    """
    Followup agent endpoint that provides helpful responses or generates clarifying questions based on user queries.
    Requires API Key authentication via X-API-Key header.
    """
    logger.info(f"Received followup agent query: {query.query}")
    if query.conversation_id not in conversations:
        conversations[query.conversation_id] = [
            {"role": "system", "content": MULTI_AGENT_PROMPT_V2}
        ]
    
    conversations[query.conversation_id].append({"role": "user", "content": query.query})
    last_activity[query.conversation_id] = time.time()
    
    # Limit tokens in the conversation history
    limited_conversation = conversations[query.conversation_id]
    
    def process_response():
        full_response = ""
        result = dict()
        
        # Check if tool_call is specified and call the tool directly
        if query.tool_call in ["web", "news"]:
            search_query = query.query
            search_response = search_assistant_api(search_query, query.tool_call, model=query.model_id)
            
            yield "<report>"
            for content in search_response():
                yield content
                full_response += content
            yield "</report>"
        else:
            for content in chat_with_llama_stream(limited_conversation, model=query.model_id):
                yield content
                full_response += content
        
            logger.info(f"LLM RAW response for query: {query.query}: {full_response}")
            response_content, interact, tools = parse_followup_and_tools(full_response)
            
            result = {
                "clarification": interact,
                "tools": tools
            }
            
            yield "<json>"+ json.dumps(result)+"</json>"
            
            
            # Process tool if present
            if tools and len(tools) > 0:
                tool = tools[0]  # Assume only one tool is present
                if tool["name"] in ["news", "web"]:
                    search_query = tool["input"]
                    search_response = search_assistant_api(search_query, tool["name"], model=query.model_id)
                    
                    yield "<report>"
                    for content in search_response():
                        yield content
                        full_response += content
                    yield "</report>"
        
        # Add the assistant's response to the conversation history
        conversations[query.conversation_id].append({"role": "assistant", "content": full_response})
        background_tasks.add_task(update_db, query.user_id, query.conversation_id, query.query, full_response)
        logger.info(f"Completed followup agent response for query: {query.query}, send result:{result}, Full response: {full_response}")
    
    return StreamingResponse(process_response(), media_type="text/event-stream")


@app.post("/v3/followup-agent")
async def followup_agent(query: FollowupQueryModel, background_tasks: BackgroundTasks, api_key: str = Depends(verify_api_key)):
    """
    Followup agent endpoint that provides helpful responses or generates clarifying questions based on user queries.
    Requires API Key authentication via X-API-Key header.
    """
    logger.info(f"Received followup agent query: {query.query}")

    if query.conversation_id not in conversations:
        conversations[query.conversation_id] = [
            {"role": "system", "content": FOLLOWUP_AGENT_PROMPT}
        ]
    
    conversations[query.conversation_id].append({"role": "user", "content": query.query})
    last_activity[query.conversation_id] = time.time()
    
    # Limit tokens in the conversation history
    limited_conversation = conversations[query.conversation_id]

    
    async def process_response():
        yield "<followup-response>\n\n"
        full_response = ""
        for content in chat_with_llama_stream(limited_conversation, model=query.model_id):
            full_response += content
            yield content
        yield "</followup-response>\n\n"
        
        logger.info(f"LLM RAW response for query: {query.query}: {full_response}")
        
        # Add a slight delay after sending the full LLM response
        await asyncio.sleep(0.01)
        
        response_content, interact, tools = parse_followup_and_tools(full_response)
        result = {
            "clarification": interact
        }
        
        yield "<followup-json>\n\n"
        yield json.dumps(result) + "\n\n"
        yield "</followup-json>\n\n"
        
        # Add the assistant's response to the conversation history
        conversations[query.conversation_id].append({"role": "assistant", "content": full_response})
        background_tasks.add_task(update_db, query.user_id, query.conversation_id, query.query, full_response)
        logger.info(f"Completed followup agent response for query: {query.query}, send result: {result}")

    return StreamingResponse(process_response(), media_type="text/event-stream")


@app.post("/v4/followup-agent")
async def followup_agent_v4(query: FollowupQueryModel, background_tasks: BackgroundTasks, api_key: str = Depends(verify_api_key)):
    """
    Followup agent endpoint that provides helpful responses or generates clarifying questions based on user queries.
    Requires API Key authentication via X-API-Key header.
    """
    logger.info(f"Received followup agent query: {query.query}")

    if query.conversation_id not in conversations:
        conversations[query.conversation_id] = [
            {"role": "system", "content": FOLLOWUP_AGENT_PROMPT}
        ]
    
    conversations[query.conversation_id].append({"role": "user", "content": query.query})
    last_activity[query.conversation_id] = time.time()
    
    # Limit tokens in the conversation history
    limited_conversation = conversations[query.conversation_id]

    
    async def process_response():
        yield "<followup-response>"+"\n"
        full_response = ""
        for content in chat_with_llama_stream(limited_conversation, model=query.model_id):
            full_response += content
            yield content
        yield "</followup-response>"+"\n"
        yield "--END_SECTION--\n"
        
        logger.info(f"LLM RAW response for query: {query.query}: {full_response}")

        
        response_content, interact, tools = parse_followup_and_tools(full_response)
        result = {
            "clarification": interact
        }
        
        yield "<followup-json>" + "\n"
        yield json.dumps(result) + "\n"
        yield "</followup-json>" +"\n"
        yield "--END_SECTION--\n"
        # Add the assistant's response to the conversation history
        conversations[query.conversation_id].append({"role": "assistant", "content": full_response})
        background_tasks.add_task(update_db, query.user_id, query.conversation_id, query.query, full_response)
        logger.info(f"Completed followup agent response for query: {query.query}, send result: {result}")

    return StreamingResponse(process_response(), media_type="text/event-stream")

## Digiyatra

@app.post("/digiyatra-followup")
async def followup_agent(query: FollowupQueryModel, background_tasks: BackgroundTasks, api_key: str = Depends(verify_api_key)):
    """
    Followup agent endpoint that provides helpful responses or generates clarifying questions based on user queries.
    Requires API Key authentication via X-API-Key header.
    """
    logger.info(f"Received followup agent query: {query.query}")

    if query.conversation_id not in conversations:
        conversations[query.conversation_id] = [
            {"role": "system", "content": FOLLOWUP_DIGIYATRA_PROMPT}
        ]
    
    conversations[query.conversation_id].append({"role": "user", "content": query.query})
    last_activity[query.conversation_id] = time.time()
    
    # Limit tokens in the conversation history
    limited_conversation = conversations[query.conversation_id]

    def process_response():
        full_response = ""
        for content in chat_with_llama_stream(limited_conversation, model=query.model_id):
            full_response += content
            yield content

        logger.info(f"LLM RAW response for query: {query.query}: {full_response}")
        response_content, interact,tools = parse_followup_and_tools(full_response)
        
        result = {
            "response": response_content,
            "clarification": interact
        }
        
        yield "\n\n" + json.dumps(result)
        
        # Add the assistant's response to the conversation history
        conversations[query.conversation_id].append({"role": "assistant", "content": full_response})
        
        background_tasks.add_task(update_db, query.user_id, query.conversation_id, query.query, full_response)
        logger.info(f"Completed followup agent response for query: {query.query}, send result: {result}")

    return StreamingResponse(process_response(), media_type="text/event-stream")


@app.post("/v2/digiyatra-followup")
async def digi_followup_agent_v2(query: FollowupQueryModel, background_tasks: BackgroundTasks, api_key: str = Depends(verify_api_key)):
    """
    Followup agent endpoint that provides helpful responses or generates clarifying questions based on user queries.
    Requires API Key authentication via X-API-Key header.
    """
    logger.info(f"Received followup agent query: {query.query}")

    if query.conversation_id not in conversations:
        conversations[query.conversation_id] = [
            {"role": "system", "content": FOLLOWUP_DIGIYATRA_PROMPT}
        ]
    
    conversations[query.conversation_id].append({"role": "user", "content": query.query})
    last_activity[query.conversation_id] = time.time()
    
    # Limit tokens in the conversation history
    limited_conversation = conversations[query.conversation_id]

    def process_response():
        full_response = ""
        for content in chat_with_llama_stream(limited_conversation, model=query.model_id):
            full_response += content
            yield json.dumps({"type": "response","content": content}) + "\n"

        logger.info(f"LLM RAW response for query: {query.query}: {full_response}")
        response_content, interact,tools = parse_followup_and_tools(full_response)
        
        result = {
            "response": response_content,
            "clarification": interact
        }
        yield json.dumps({"type": "interact","content": result}) +"\n"
        
        # Add the assistant's response to the conversation history
        conversations[query.conversation_id].append({"role": "assistant", "content": full_response})
        
        background_tasks.add_task(update_db, query.user_id, query.conversation_id, query.query, full_response)
        logger.info(f"Completed followup agent response for query: {query.query}, send result: {result}")

    return StreamingResponse(process_response(), media_type="text/event-stream")


from document_generator import router as document_generator_router
app.include_router(document_generator_router, prefix="/api/v1")

from document_generator_v2 import router as document_generator_router_v2
app.include_router(document_generator_router_v2, prefix="/api/v2")

from fastapi.middleware.cors import CORSMiddleware

# CORS middleware setup
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://127.0.0.1:5501/",
        "http://localhost:3000",
        "https://www.elevaticsai.com",
        "https://www.elevatics.cloud",
        "https://www.elevatics.online",
        "https://www.elevatics.ai",
        "https://elevaticsai.com",
        "https://elevatics.cloud",
        "https://elevatics.online",
        "https://elevatics.ai",
        "https://pvanand-specialized-agents.hf.space",
        "https://pvanand-general-chat.hf.space"
    ],
    allow_credentials=True,
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
    expose_headers=["Content-Disposition"]
)
if __name__ == "__main__":
    import uvicorn
    logger.info("Starting the application")
    uvicorn.run(app, host="0.0.0.0", port=7860)