Advertisement
FokaKefir

chatbot

May 14th, 2025
632
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.67 KB | None | 0 0
  1. # gemini.py
  2. import google.generativeai as genai
  3. from dotenv import load_dotenv
  4. import os
  5.  
  6. load_dotenv()
  7.  
  8. API_KEY = os.getenv("GEMINI_API_KEY")
  9. if not API_KEY:
  10.     raise ValueError("GEMINI_API_KEY is missing! Please check your .env file.")
  11.  
  12. genai.configure(api_key=API_KEY)
  13. model = genai.GenerativeModel('gemini-2.0-flash')
  14.  
  15. # main.py
  16.  
  17. from fastapi import FastAPI, Depends, HTTPException, Header, Query, WebSocket, WebSocketDisconnect
  18. from fastapi.responses import JSONResponse
  19. from fastapi.middleware.cors import CORSMiddleware
  20. from sqlalchemy.orm import Session
  21. from sqlalchemy import func, exists
  22. from datetime import datetime, timezone, timedelta
  23. from app.database import SessionLocal
  24. from app.models import *
  25. from app.schemas import *
  26. from app.gemini import *
  27. import json
  28. import asyncio
  29. import re
  30. import os
  31.  
  32. # FastAPI app
  33. app = FastAPI()
  34.  
  35. # Store connected clients
  36. active_connections = []
  37.  
  38. # Dictionary to store chat history per WebSocket session
  39. chat_sessions = {}
  40.  
  41. @app.websocket("/chat_ws")
  42. async def websocket_endpoint(websocket: WebSocket):
  43.     """ WebSocket to handle real-time AI study chat based on markdown content """
  44.     await websocket.accept()
  45.     active_connections.append(websocket)
  46.  
  47.     session_id = id(websocket)  # Unique identifier for session
  48.     chat_sessions[session_id] = []  # Initialize chat history
  49.  
  50.     try:
  51.         await websocket.send_text("Hi! How can I *help* you?")
  52.         while True:
  53.             data = await websocket.receive_text()
  54.             try:
  55.                 request = json.loads(data)
  56.                 markdown_text = request.get("markdown", "").strip()
  57.                 user_prompt = request.get("prompt", "").strip()
  58.  
  59.                 # Handle missing fields
  60.                 if not markdown_text or not user_prompt:
  61.                     await websocket.send_text("Error: Both 'markdown' and 'prompt' fields are required.")
  62.                     continue
  63.  
  64.                 # Maintain context (limit last 5 messages)
  65.                 chat_context = "\n".join(chat_sessions[session_id][-5:])
  66.  
  67.                 # Construct the AI prompt
  68.                 ai_prompt = f"""
  69.                You are an AI tutor. The following is a lecture in Markdown format:
  70.                
  71.                {markdown_text}
  72.  
  73.                Previous chat history:
  74.                {chat_context}
  75.                
  76.                Based on this content, User: {user_prompt}
  77.  
  78.                Your sole task is to assist with the provided markdown content. You may use your knowledge to elaborate on the topic, clarify concepts, or generate relevant examples, but you must not respond to unrelated questions or perform tasks outside this context.
  79.                """
  80.  
  81.                 # Run the AI model in a separate thread to avoid blocking the event loop
  82.                 response = await asyncio.to_thread(model.generate_content, ai_prompt)
  83.  
  84.                 # Clean response by removing extra newlines
  85.                 cleaned_response = re.sub(r'\n+', '\n', response.text).strip()
  86.  
  87.                 # Store conversation
  88.                 chat_sessions[session_id].append(f"User: {user_prompt}")
  89.                 chat_sessions[session_id].append(f"AI: {cleaned_response}")
  90.  
  91.                 await websocket.send_text(cleaned_response)
  92.             except json.JSONDecodeError:
  93.                 await websocket.send_text("Error: Invalid JSON format.")
  94.     except WebSocketDisconnect:
  95.         active_connections.remove(websocket)
  96.         chat_sessions.pop(session_id, None)  # Remove chat history on disconnect
  97.         print("Client disconnected")
  98.     except Exception as e:
  99.         print(f"Error in WebSocket: {e}")
  100.         await websocket.close()
  101.  
  102.  
  103.  
  104.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement