vickysrm commited on
Commit
64ce06e
·
1 Parent(s): 8e93416

fix: Load env vars first + lazy Groq init

Browse files
Files changed (2) hide show
  1. main.py +7 -4
  2. services/ollama_client.py +23 -15
main.py CHANGED
@@ -1,12 +1,15 @@
 
 
 
 
 
 
 
1
  from fastapi import FastAPI, Request, Depends
2
  from fastapi.responses import JSONResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
5
  from contextlib import asynccontextmanager
6
- from dotenv import load_dotenv
7
- import os
8
-
9
- os.environ["HF_HOME"] = os.path.join(os.getcwd(), "model_cache")
10
 
11
  from slowapi import Limiter
12
  from slowapi.middleware import SlowAPIMiddleware
 
1
+ from dotenv import load_dotenv
2
+ import os
3
+
4
+ # Load env vars FIRST before any other imports read them
5
+ load_dotenv()
6
+ os.environ.setdefault("HF_HOME", os.path.join(os.getcwd(), "model_cache"))
7
+
8
  from fastapi import FastAPI, Request, Depends
9
  from fastapi.responses import JSONResponse
10
  from fastapi.middleware.cors import CORSMiddleware
11
  from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
12
  from contextlib import asynccontextmanager
 
 
 
 
13
 
14
  from slowapi import Limiter
15
  from slowapi.middleware import SlowAPIMiddleware
services/ollama_client.py CHANGED
@@ -1,33 +1,41 @@
1
  import ollama
2
- from typing import Optional
3
  import os
4
 
5
- # Default to local qwen2:1.5b unless requested otherwise
6
  OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "qwen2:1.5b")
7
- GROQ_API_KEY = os.getenv("GROQ_API_KEY")
8
 
9
- try:
10
- if GROQ_API_KEY:
 
 
 
 
 
 
 
 
 
11
  from groq import Groq
12
- groq_client = Groq(api_key=GROQ_API_KEY)
13
- else:
14
- groq_client = None
15
- except ImportError:
16
- groq_client = None
 
17
 
18
 
19
  def _call_llm(prompt: str) -> str:
20
- """Intelligently route to Cloud Groq API if key exists, otherwise local Ollama."""
21
- if groq_client:
22
- # Use cloud Groq for blazing fast deployment inference
23
- chat_completion = groq_client.chat.completions.create(
24
  messages=[{"role": "user", "content": prompt}],
25
  model="llama3-8b-8192",
26
  temperature=0.3,
27
  )
28
  return chat_completion.choices[0].message.content
29
  else:
30
- # Fallback to local Ollama daemon
31
  response = ollama.chat(model=OLLAMA_MODEL, messages=[
32
  {'role': 'user', 'content': prompt}
33
  ])
 
1
  import ollama
 
2
  import os
3
 
4
+ # Default local model
5
  OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "qwen2:1.5b")
 
6
 
7
+ # Groq client is initialized lazily to ensure env vars are loaded first
8
+ _groq_client = None
9
+
10
+ def _get_groq_client():
11
+ global _groq_client
12
+ if _groq_client is not None:
13
+ return _groq_client
14
+ api_key = os.getenv("GROQ_API_KEY")
15
+ if not api_key:
16
+ return None
17
+ try:
18
  from groq import Groq
19
+ _groq_client = Groq(api_key=api_key)
20
+ print("Groq client initialized successfully.")
21
+ return _groq_client
22
+ except Exception as e:
23
+ print(f"Groq init failed: {e}")
24
+ return None
25
 
26
 
27
  def _call_llm(prompt: str) -> str:
28
+ """Route to Groq if key is available, otherwise Ollama."""
29
+ client = _get_groq_client()
30
+ if client:
31
+ chat_completion = client.chat.completions.create(
32
  messages=[{"role": "user", "content": prompt}],
33
  model="llama3-8b-8192",
34
  temperature=0.3,
35
  )
36
  return chat_completion.choices[0].message.content
37
  else:
38
+ # Fallback to local Ollama
39
  response = ollama.chat(model=OLLAMA_MODEL, messages=[
40
  {'role': 'user', 'content': prompt}
41
  ])