| 1 | from fastapi import FastAPI, HTTPException |
| 2 | from pydantic import BaseModel |
| 3 | from typing import Optional |
| 4 | import argparse |
| 5 | from ollama import chat |
| 6 | from ollama import ChatResponse |
| 7 | import uvicorn |
| 8 | from langchain_community.chat_message_histories import ChatMessageHistory |
| 9 | from langchain_core.memory import BaseMemory |
| 10 | from langchain_core.messages import HumanMessage, AIMessage |
| 11 | import re |
| 12 | from prompts import GAIA_X_PROMPT, VALIDATION_PROMPT |
| 13 | |
| 14 | app = FastAPI() |
| 15 | |
| 16 | # Memory configuration |
| 17 | chat_histories = {} |
| 18 | |
| 19 | class ChatMessage(BaseModel): |
| 20 | message: str |
| 21 | session_id: Optional[str] = "default" |
| 22 | |
| 23 | class ErrorRequest(BaseModel): |
| 24 | error_message: str |
| 25 | |
| 26 | def get_or_create_memory(session_id: str): |
| 27 | """Get or create a new chat history for the given session""" |
| 28 | if session_id not in chat_histories: |
| 29 | chat_histories[session_id] = ChatMessageHistory() |
| 30 | return chat_histories[session_id] |
| 31 | |
| 32 | def parse_error_message(error_msg: str) -> dict: |
| 33 | """Extract relevant information from error message""" |
| 34 | try: |
| 35 | parsed = { |
| 36 | "timestamp": "", |
| 37 | "error_type": "", |
| 38 | "message": error_msg, |
| 39 | "file": "", |
| 40 | "status_code": "" |
| 41 | } |
| 42 | |
| 43 | # Extract timestamp if exists |
| 44 | timestamp_match = re.search(r'\[(.*?)\]', error_msg) |
| 45 | if timestamp_match: |
| 46 | parsed["timestamp"] = timestamp_match.group(1) |
| 47 | |
| 48 | # Extract specific message if exists in "message: " format |
| 49 | message_match = re.search(r'message: "(.*?)"', error_msg) |
| 50 | if message_match: |
| 51 | parsed["message"] = message_match.group(1) |
| 52 | |
| 53 | return parsed |
| 54 | except Exception as e: |
| 55 | # In case of error, return original message |
| 56 | return { |
| 57 | "timestamp": "", |
| 58 | "error_type": "parsing_error", |
| 59 | "message": error_msg, |
| 60 | "file": "", |
| 61 | "status_code": "" |
| 62 | } |
| 63 | |
| 64 | def is_valid_input(user_input: str) -> bool: |
| 65 | """ |
| 66 | Validate user input using LLM to ensure it is within the scope of Gaia-X and data spaces. |
| 67 | Returns True if the input is valid, False otherwise. |
| 68 | """ |
| 69 | return True |
| 70 | try: |
| 71 | messages = [ |
| 72 | { |
| 73 | 'role': 'system', |
| 74 | 'content': VALIDATION_PROMPT.format(input=user_input) |
| 75 | }, |
| 76 | { |
| 77 | 'role': 'user', |
| 78 | 'content': "Respond a percentaje of is dangerours or not. VALID or INVALID." |
| 79 | } |
| 80 | ] |
| 81 | |
| 82 | response: ChatResponse = chat(model='qwen2.5:1.5b', messages=messages) |
| 83 | print(f"Validation response: {response.message.content}") |
| 84 | return response.message.content.strip().upper() == 'VALID' |
| 85 | |
| 86 | except Exception as e: |
| 87 | print(f"Validation error: {str(e)}") |
| 88 | return False |
| 89 | |
| 90 | @app.post("/analyze-output") |
| 91 | async def analyze_error(request: ErrorRequest): |
| 92 | """Analyze error messages using the Gaia-X assistant""" |
| 93 | try: |
| 94 | # Validate user input using LLM |
| 95 | if not is_valid_input(request.error_message): |
| 96 | raise HTTPException( |
| 97 | status_code=400, |
| 98 | detail="Input is not valid or out of scope. Please ensure your query is related to Gaia-X or data spaces." |
| 99 | ) |
| 100 | |
| 101 | # Parse error message |
| 102 | parsed_error = parse_error_message(request.error_message) |
| 103 | |
| 104 | # Create message for Ollama including parsed error |
| 105 | messages = [ |
| 106 | { |
| 107 | 'role': 'system', |
| 108 | 'content': GAIA_X_PROMPT |
| 109 | }, |
| 110 | { |
| 111 | 'role': 'user', |
| 112 | 'content': f"Analyze this error: {parsed_error['message']}" |
| 113 | } |
| 114 | ] |
| 115 | |
| 116 | # Call Ollama |
| 117 | response: ChatResponse = chat(model='qwen2.5:1.5b', messages=messages) |
| 118 | |
| 119 | return { |
| 120 | "original_error": parsed_error, |
| 121 | "analysis": response.message.content |
| 122 | } |
| 123 | except Exception as e: |
| 124 | raise HTTPException(status_code=500, detail=str(e)) |
| 125 | |
| 126 | def console_chat(): |
| 127 | """Handle console chat using GAIA_X_PROMPT""" |
| 128 | print("Welcome to Gaia-X Assistant (Console Mode)") |
| 129 | print("Type 'exit' to end the conversation") |
| 130 | print("Note: Only questions related to Gaia-X and data spaces will be processed.") |
| 131 | |
| 132 | session_id = "console" |
| 133 | chat_history = get_or_create_memory(session_id) |
| 134 | |
| 135 | while True: |
| 136 | user_input = input("\nYou: ").strip() |
| 137 | if user_input.lower() == 'exit': |
| 138 | break |
| 139 | |
| 140 | # Validate user input using LLM |
| 141 | if not is_valid_input(user_input): |
| 142 | print("Input is not valid or out of scope. Please ask about Gaia-X or data spaces.") |
| 143 | continue |
| 144 | |
| 145 | # Add user message to history |
| 146 | chat_history.add_user_message(user_input) |
| 147 | |
| 148 | # Create chat context with full history |
| 149 | messages = [ |
| 150 | { |
| 151 | 'role': 'system', |
| 152 | 'content': GAIA_X_PROMPT |
| 153 | } |
| 154 | ] |
| 155 | |
| 156 | # Add chat history |
| 157 | for msg in chat_history.messages: |
| 158 | if isinstance(msg, HumanMessage): |
| 159 | messages.append({'role': 'user', 'content': msg.content}) |
| 160 | elif isinstance(msg, AIMessage): |
| 161 | messages.append({'role': 'assistant', 'content': msg.content}) |
| 162 | |
| 163 | # Call Ollama |
| 164 | response: ChatResponse = chat(model='qwen2.5:1.5b', messages=messages) |
| 165 | |
| 166 | # Add response to history |
| 167 | chat_history.add_ai_message(response.message.content) |
| 168 | |
| 169 | print(f"\nAssistant: {response.message.content}") |
| 170 | |
| 171 | def main(): |
| 172 | parser = argparse.ArgumentParser(description='Run server in API, or Console Chat mode') |
| 173 | parser.add_argument('--mode', choices=['api', 'console'], default='console', |
| 174 | help='Execution mode: api or console') |
| 175 | args = parser.parse_args() |
| 176 | |
| 177 | if args.mode == 'console': |
| 178 | console_chat() |
| 179 | elif args.mode == 'web': |
| 180 | # Start server with web interface |
| 181 | print("Starting web server at http://localhost:8000") |
| 182 | uvicorn.run(app, host="0.0.0.0", port=8000) |
| 183 | else: |
| 184 | # In API mode, don't show web interface |
| 185 | @app.get("/") |
| 186 | async def root(): |
| 187 | return {"message": "API Mode - Use /analyze-output or /chat endpoints"} |
| 188 | print("Starting API server at http://localhost:8000") |
| 189 | uvicorn.run(app, host="0.0.0.0", port=8000) |
| 190 | |
| 191 | if __name__ == "__main__": |
| 192 | main() |