from fastapi import FastAPI, HTTPException, UploadFile, File, Security, status from fastapi.security.api_key import APIKeyHeader from environs import Env import json # Importing modules from both scripts from coresugg import ConversationPayload as ConversationPayloadSugg, create_conversation_starter_prompt, generate_conversation_starters, NUMBER_OF_MESSAGES_FOR_CONTEXT as NUMBER_OF_MESSAGES_FOR_CONTEXT_SUGG from corechat import ConversationPayload as ConversationPayloadChat, get_conversation_suggestions, NUMBER_OF_MESSAGES_FOR_CONTEXT as NUMBER_OF_MESSAGES_FOR_CONTEXT_CHAT # Load environment variables env = Env() API_KEY = env.str("API_KEY", "koottu123456abcDEF") api_key_header = APIKeyHeader(name="X-API-KEY", auto_error=False) app = FastAPI() async def get_api_key(api_key_header: str = Security(api_key_header)): if api_key_header == API_KEY: return api_key_header else: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid API Key") # Route from app.py @app.post("/integration") def integration(payload: ConversationPayloadSugg, api_key: str = Security(get_api_key)): from_user_questions = payload.FromUserKavasQuestions[-NUMBER_OF_MESSAGES_FOR_CONTEXT_SUGG:] to_user_questions = payload.ToUserKavasQuestions[-NUMBER_OF_MESSAGES_FOR_CONTEXT_SUGG:] ai_prompt = create_conversation_starter_prompt(from_user_questions + to_user_questions, payload.Chatmood) conversation_starters = generate_conversation_starters(ai_prompt) return {"conversation_starters": conversation_starters} # Route from chatt.py @app.post("/chat_integration") def chat_integration(payload: ConversationPayloadChat, api_key: str = Security(get_api_key)): last_chat_messages = payload.LastChatMessages[-NUMBER_OF_MESSAGES_FOR_CONTEXT_CHAT:] suggestions = get_conversation_suggestions(last_chat_messages) return {"version": "1.0.0-alpha", "suggested_responses": suggestions} # Combined upload endpoint @app.post("/upload") async def upload_file(file: UploadFile = File(...), api_key: str = Security(get_api_key)): if file.content_type != 'application/json': raise HTTPException(status_code=400, detail="Invalid file type. Please upload a JSON file.") data = await file.read() try: json_data = json.loads(data) except json.JSONDecodeError: raise HTTPException(status_code=400, detail="Invalid JSON format.") if "FromUserKavasQuestions" in json_data and "Chatmood" in json_data: prompt = create_conversation_starter_prompt( json_data["FromUserKavasQuestions"], json_data["Chatmood"] ) starter_suggestion = generate_conversation_starters(prompt) return {"conversation_starter": starter_suggestion} elif "LastChatMessages" in json_data: last_chat_messages = json_data["LastChatMessages"][-NUMBER_OF_MESSAGES_FOR_CONTEXT_CHAT:] response = { "version": "1.0.0-alpha", "suggested_responses": get_conversation_suggestions(last_chat_messages) } return response else: raise HTTPException(status_code=400, detail="Invalid JSON structure.") #uvicorn app:app --reload #uvicorn aisugg22:app --reload