mominah commited on
Commit
8e4d654
·
verified ·
1 Parent(s): d062f19

Create llm_router.py

Browse files
Files changed (1) hide show
  1. llm_router.py +50 -0
llm_router.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # llm_router.py
2
+
3
+ import os
4
+ from fastapi import APIRouter, HTTPException
5
+ from pydantic import BaseModel
6
+ from groq import ChatGroq
7
+
8
+ router = APIRouter()
9
+
10
+ # Load context once at startup
11
+ _context_path = 'output.txt'
12
+ if os.path.exists(_context_path):
13
+ with open(_context_path, 'r', encoding='utf-8') as f:
14
+ data = f.read()
15
+ else:
16
+ data = ""
17
+
18
+ def get_llm():
19
+ """
20
+ Returns the language model instance (LLM) using ChatGroq API.
21
+ Reads the API key from the GROQ_API_KEY environment variable.
22
+ """
23
+ api_key = os.getenv("GROQ_API_KEY")
24
+ if not api_key:
25
+ raise RuntimeError("Environment variable GROQ_API_KEY is not set")
26
+ return ChatGroq(
27
+ model="llama-3.3-70b-versatile",
28
+ temperature=0,
29
+ max_tokens=1024,
30
+ api_key=api_key
31
+ )
32
+
33
+ llm = get_llm()
34
+
35
+ class QueryRequest(BaseModel):
36
+ query: str
37
+
38
+ @router.post("/ask")
39
+ async def ask_query(request: QueryRequest):
40
+ prompt = f"""You are EduLearnAI. A useful Assistant which helps people answer queries related to the Comsats University Islamabad Attock campus.
41
+ Using the provided context. If you don't know the answer, just say you don't know—don't hallucinate.
42
+ context:
43
+ {data}
44
+
45
+ question: {request.query}
46
+
47
+ answer:
48
+ """
49
+ ans = llm.invoke(prompt)
50
+ return {"response": ans.content}