File size: 12,949 Bytes
b66bfbf
68394ea
adb504f
d3051c0
 
68394ea
b1c8f17
26e0ddc
d3051c0
68394ea
 
 
 
 
 
2bb5179
b66bfbf
62ab01b
 
 
26e0ddc
b66bfbf
 
 
 
b1c8f17
2e76cf7
adb504f
4bf6be6
adb504f
 
d3051c0
 
 
 
 
 
 
 
 
b1c8f17
1fc729a
d3051c0
 
 
 
 
68394ea
 
26e0ddc
 
 
 
d3051c0
68394ea
 
 
26e0ddc
 
 
2bb5179
 
2e6b166
 
 
 
2bb5179
 
 
2e6b166
 
2bb5179
 
 
26e0ddc
 
b66bfbf
26e0ddc
2bb5179
 
26e0ddc
 
d3051c0
 
26e0ddc
68394ea
 
 
 
 
 
 
 
b66bfbf
68394ea
 
 
b66bfbf
 
 
68394ea
f8ac6db
b66bfbf
68394ea
 
 
 
 
 
bc4a455
b66bfbf
f8ac6db
68394ea
26e0ddc
b66bfbf
f8ac6db
d3051c0
 
 
 
 
adb504f
68394ea
b4b055b
 
 
 
 
68394ea
b66bfbf
68394ea
 
26e0ddc
b66bfbf
d3051c0
 
adb504f
 
b66bfbf
adb504f
b66bfbf
adb504f
 
68394ea
5c4af3f
 
68394ea
b66bfbf
5c4af3f
 
68394ea
 
 
 
 
 
 
 
 
 
b66bfbf
68394ea
 
 
 
b66bfbf
5c4af3f
68394ea
 
 
 
 
b66bfbf
68394ea
 
b66bfbf
68394ea
 
 
 
 
 
 
 
 
b66bfbf
68394ea
 
 
 
b66bfbf
62ab01b
68394ea
 
d3051c0
68394ea
b66bfbf
68394ea
 
 
 
 
 
 
 
 
 
 
f8ac6db
68394ea
f8ac6db
68394ea
 
b66bfbf
68394ea
 
 
2fc91ef
2bb5179
62ab01b
b66bfbf
 
 
2bb5179
 
 
 
 
 
 
 
 
b66bfbf
 
 
 
 
 
 
 
 
 
 
 
b79d37a
b66bfbf
 
2bb5179
16ef4d2
b66bfbf
 
 
e7c157d
2bb5179
b66bfbf
 
2bb5179
 
b66bfbf
2bb5179
 
 
cbcfc90
 
2bb5179
 
cbcfc90
2bb5179
 
 
b66bfbf
2bb5179
 
 
 
b66bfbf
2bb5179
 
 
b66bfbf
2bb5179
337dba1
2bb5179
2e6b166
2bb5179
dd91c47
b66bfbf
dd91c47
 
113e85f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54210e7
 
b66bfbf
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
import logging
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 CODING_ASSISTANT_PROMPT, NEWS_ASSISTANT_PROMPT, generate_news_prompt
from fastapi_cache import FastAPICache
from fastapi_cache.backends.inmemory import InMemoryBackend
from fastapi_cache.decorator import cache

# Set up logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
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[
    "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="meta-llama/llama-3-70b-instruct",
        description="ID of the model to use for response generation"
    )
    class Config:
        schema_extra = {
            "example": {
                "query": "Latest developments in AI",
                "model_id": "meta-llama/llama-3-70b-instruct"
            }
        }

@lru_cache()
def get_api_keys():
    logger.debug("Fetching 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):
    logger.debug(f"Limiting tokens for input string, token limit: {token_limit}")
    return encoding.decode(encoding.encode(input_string)[:token_limit])

def calculate_tokens(msgs):
    token_count = sum(len(encoding.encode(str(m))) for m in msgs)
    logger.debug(f"Calculated token count: {token_count}")
    return token_count

def chat_with_llama_stream(messages, model="gpt-3.5-turbo", 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:
        logger.debug("Sending request to OpenAI")
        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
        
        logger.debug("Finished streaming response")
        # After streaming, add the full response to the conversation history
        messages.append({"role": "assistant", "content": full_response})
    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 attempt")
        raise HTTPException(status_code=403, detail="Could not validate credentials")
    logger.debug("API key verified successfully")
    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.debug("Database initialized")

init_db()

def update_db(user_id, conversation_id, message, response):
    logger.debug(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.debug("Database updated successfully")

async def clear_inactive_conversations():
    logger.info("Starting inactive conversation cleanup task")
    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]
        logger.debug(f"Cleared {len(inactive_convos)} inactive conversations")
        await asyncio.sleep(60)  # Check every minute

@app.on_event("startup")
async def startup_event():
    logger.info("Starting up FastAPI 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)):
    logger.info(f"Received coding assistant request for user {query.user_id}")
    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
        logger.debug(f"Finished processing response for conversation {query.conversation_id}")
        background_tasks.add_task(update_db, query.user_id, query.conversation_id, query.user_query, full_response)

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

# New functions for news assistant

def fetch_news(query, num_results=20):
    logger.info(f"Fetching news for query: {query}")
    url = "https://api.search.brave.com/res/v1/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:
        news_data = response.json()
        logger.debug(f"Fetched {len(news_data['results'])} news items")
        return [
            {
                "title": item["title"],
                "snippet": item["extra_snippets"][0] if "extra_snippets" in item and item["extra_snippets"] else "",
                "last_updated": item.get("age", ""),
            }
            for item in news_data['results']
            if "extra_snippets" in item and item["extra_snippets"]
        ][:num_results]
    else:
        logger.error(f"Failed to fetch news. Status code: {response.status_code}")
        return []

@lru_cache(maxsize=100)
def cached_fetch_news(query: str):
    logger.debug(f"Fetching cached news for query: {query}")
    return fetch_news(query)

def analyze_news(query):
    logger.info(f"Analyzing news for query: {query}")
    news_data = cached_fetch_news(query)
    
    if not news_data:
        logger.warning("No news data fetched")
        return "Failed to fetch news data.", []

    # Prepare the prompt for the AI
    # Use the imported function to generate the prompt (now includes today's date)
    prompt = generate_news_prompt(query, news_data)

    messages = [
        {"role": "system", "content": NEWS_ASSISTANT_PROMPT},
        {"role": "user", "content": prompt}
    ]

    logger.debug("News analysis prompt prepared")
    return messages

@app.post("/news-assistant")
async def news_assistant(query: NewsQueryModel, api_key: str = Depends(verify_api_key)):
    logger.info(f"Received news assistant request for query: {query.query}")
    messages = analyze_news(query.query)
    
    if not messages:
        logger.error("Failed to fetch news data")
        raise HTTPException(status_code=500, detail="Failed to fetch news data")
        
    def process_response():
        for content in chat_with_llama_stream(messages, model=query.model_id):
            yield content

    logger.debug("Starting to stream news assistant response")
    return StreamingResponse(process_response(), media_type="text/event-stream")

class SearchQueryModel(BaseModel):
    query: str = Field(..., description="Search query")
    model_id: ModelID = Field(
        default="meta-llama/llama-3-70b-instruct",
        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 analyze_search_results(query):
    search_data = internet_search(query, type="web")
    
    if not search_data:
        logger.error("Failed to fetch search data")
        return "Failed to fetch search data.", []

    # Prepare the prompt for the AI
    prompt = generate_search_prompt(query, search_data)

    messages = [
        {"role": "system", "content": SEARCH_ASSISTANT_PROMPT},
        {"role": "user", "content": prompt}
    ]

    return messages

@app.post("/search-assistant")
async def search_assistant(query: SearchQueryModel, 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.
    """
    messages = analyze_search_results(query.query)
    
    if not messages:
        raise HTTPException(status_code=500, detail="Failed to fetch search data")
        
    def process_response():
        for content in chat_with_llama_stream(messages, model=query.model_id):
            yield content
            
    logger.debug("Starting to stream news assistant response")
    return StreamingResponse(process_response(), media_type="text/event-stream")


if __name__ == "__main__":
    import uvicorn
    logger.info("Starting uvicorn server")
    uvicorn.run(app, host="0.0.0.0", port=7860)