Spaces:
Runtime error
Runtime error
| import os | |
| from flask import Flask, request, jsonify, render_template | |
| from flask_cors import CORS | |
| from langchain_community.document_loaders import PyPDFLoader | |
| from langchain_text_splitters import RecursiveCharacterTextSplitter | |
| from langchain_chroma import Chroma | |
| from langchain_huggingface import HuggingFaceEmbeddings | |
| from langchain_core.prompts import ChatPromptTemplate | |
| from langchain_core.runnables import RunnablePassthrough | |
| from langchain_core.output_parsers import StrOutputParser | |
| from langchain_groq import ChatGroq | |
| app = Flask(__name__) | |
| CORS(app) | |
| print("="*50) | |
| print("--- Dr. Rajeev's AI: GROQ CLOUD v7.0 ---") | |
| print("="*50) | |
| pdf_path = "my_docs/Rajeev_CV_N.pdf" | |
| print(f"[*] Reading {pdf_path}...") | |
| loader = PyPDFLoader(pdf_path) | |
| pages = loader.load() | |
| text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100) | |
| texts = text_splitter.split_documents(pages) | |
| print("[*] Loading Embeddings...") | |
| embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2") | |
| print(" [✔] Embeddings Ready.") | |
| print("[*] Building Vector Database...") | |
| vector_db = Chroma.from_documents(documents=texts, embedding=embeddings) | |
| print("[*] Connecting to Groq (Llama3)...") | |
| llm = ChatGroq( | |
| model="llama-3.3-70b-versatile", | |
| groq_api_key=os.environ.get("GROQ_API_KEY"), | |
| temperature=0.5, | |
| max_tokens=512, | |
| ) | |
| retriever = vector_db.as_retriever() | |
| template = """You are Dr. Rajeev Kumar Chauhan's personal AI assistant on his website. | |
| Answer professionally and helpfully using ONLY the context provided below. | |
| If the answer is not in the context, say "I don't have that information in my knowledge base." | |
| Keep answers clear and concise. If the User Asks an Analyzing Question like Latest or Oldest so Analyze with Data, if the exact date is not available so Do the most that is available like year of month of date. | |
| Context: {context} | |
| Question: {question} | |
| Answer:""" | |
| prompt = ChatPromptTemplate.from_template(template) | |
| chain = ( | |
| {"context": retriever, "question": RunnablePassthrough()} | |
| | prompt | |
| | llm | |
| | StrOutputParser() | |
| ) | |
| print("\n[✔] AI READY. Server Starting...") | |
| print("="*50) | |
| def home(): | |
| return render_template("index.html") | |
| def ask(): | |
| data = request.get_json() | |
| question = data.get("question", "") | |
| if not question: | |
| return jsonify({"error": "No question provided"}), 400 | |
| try: | |
| answer = chain.invoke(question) | |
| return jsonify({"answer": answer}) | |
| except Exception as e: | |
| print(f"ERROR: {e}") | |
| return jsonify({"answer": f"Error: {str(e)}"}), 500 | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=7860, debug=False) |