Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -224,8 +224,9 @@
|
|
| 224 |
# return {"message": "Welcome to the API"}
|
| 225 |
|
| 226 |
import os
|
| 227 |
-
import
|
| 228 |
-
import
|
|
|
|
| 229 |
from fastapi import FastAPI, Request, HTTPException
|
| 230 |
from fastapi.responses import HTMLResponse, JSONResponse
|
| 231 |
from fastapi.staticfiles import StaticFiles
|
|
@@ -233,10 +234,8 @@ from pydantic import BaseModel
|
|
| 233 |
from fastapi.middleware.cors import CORSMiddleware
|
| 234 |
from fastapi.templating import Jinja2Templates
|
| 235 |
from simple_salesforce import Salesforce, SalesforceLogin
|
| 236 |
-
import
|
| 237 |
-
import
|
| 238 |
-
import json
|
| 239 |
-
import logging
|
| 240 |
|
| 241 |
# Configure logging
|
| 242 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -252,7 +251,7 @@ app = FastAPI()
|
|
| 252 |
# Allow CORS requests from any domain (not recommended for production)
|
| 253 |
app.add_middleware(
|
| 254 |
CORSMiddleware,
|
| 255 |
-
allow_origins=["*"],
|
| 256 |
allow_credentials=True,
|
| 257 |
allow_methods=["*"],
|
| 258 |
allow_headers=["*"],
|
|
@@ -263,16 +262,25 @@ app.mount("/static", StaticFiles(directory="static"), name="static")
|
|
| 263 |
templates = Jinja2Templates(directory="static")
|
| 264 |
|
| 265 |
# Validate environment variables
|
| 266 |
-
required_env_vars = ["
|
| 267 |
for var in required_env_vars:
|
| 268 |
if not os.getenv(var):
|
| 269 |
logger.error(f"Environment variable {var} is not set")
|
| 270 |
raise ValueError(f"Environment variable {var} is not set")
|
| 271 |
|
| 272 |
-
#
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
# Salesforce credentials
|
| 278 |
username = os.getenv("username")
|
|
@@ -303,35 +311,24 @@ def handle_query(query):
|
|
| 303 |
context_str += f"User asked: '{past_query}'\nBot answered: '{response}'\n"
|
| 304 |
|
| 305 |
# Construct the prompt
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
"Authorization": f"Bearer {CHATGROQ_API_KEY}",
|
| 319 |
-
"Content-Type": "application/json",
|
| 320 |
-
}
|
| 321 |
-
payload = {
|
| 322 |
-
"model": CHATGROQ_MODEL, # Use configured model
|
| 323 |
-
"messages": [{"role": "user", "content": prompt}],
|
| 324 |
-
"max_tokens": 50,
|
| 325 |
-
"temperature": 0.1,
|
| 326 |
-
}
|
| 327 |
|
| 328 |
try:
|
| 329 |
-
response =
|
| 330 |
-
response.
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
except requests.exceptions.RequestException as e:
|
| 334 |
-
logger.error(f"Error querying ChatGroq API: {e}")
|
| 335 |
response_text = "Sorry, I couldn't find an answer."
|
| 336 |
|
| 337 |
# Update chat history
|
|
@@ -388,7 +385,7 @@ async def receive_form_data(request: Request):
|
|
| 388 |
return JSONResponse({"id": unique_id})
|
| 389 |
except Exception as e:
|
| 390 |
logger.error(f"Failed to create lead: {e}")
|
| 391 |
-
raise HTTPException(status_code=500, detail="Failed to create lead: {str(e)}")
|
| 392 |
|
| 393 |
@app.post("/chat/")
|
| 394 |
async def chat(request: MessageRequest):
|
|
|
|
| 224 |
# return {"message": "Welcome to the API"}
|
| 225 |
|
| 226 |
import os
|
| 227 |
+
import datetime
|
| 228 |
+
import json
|
| 229 |
+
import logging
|
| 230 |
from fastapi import FastAPI, Request, HTTPException
|
| 231 |
from fastapi.responses import HTMLResponse, JSONResponse
|
| 232 |
from fastapi.staticfiles import StaticFiles
|
|
|
|
| 234 |
from fastapi.middleware.cors import CORSMiddleware
|
| 235 |
from fastapi.templating import Jinja2Templates
|
| 236 |
from simple_salesforce import Salesforce, SalesforceLogin
|
| 237 |
+
from langchain_groq import ChatGroq
|
| 238 |
+
from langchain_core.prompts import ChatPromptTemplate
|
|
|
|
|
|
|
| 239 |
|
| 240 |
# Configure logging
|
| 241 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 251 |
# Allow CORS requests from any domain (not recommended for production)
|
| 252 |
app.add_middleware(
|
| 253 |
CORSMiddleware,
|
| 254 |
+
allow_origins=["*"],
|
| 255 |
allow_credentials=True,
|
| 256 |
allow_methods=["*"],
|
| 257 |
allow_headers=["*"],
|
|
|
|
| 262 |
templates = Jinja2Templates(directory="static")
|
| 263 |
|
| 264 |
# Validate environment variables
|
| 265 |
+
required_env_vars = ["GROQ_API_KEY", "username", "password", "security_token", "domain"]
|
| 266 |
for var in required_env_vars:
|
| 267 |
if not os.getenv(var):
|
| 268 |
logger.error(f"Environment variable {var} is not set")
|
| 269 |
raise ValueError(f"Environment variable {var} is not set")
|
| 270 |
|
| 271 |
+
# Initialize Groq model
|
| 272 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 273 |
+
GROQ_MODEL = "llama3-8b-8192" # Default to a valid Groq model
|
| 274 |
+
try:
|
| 275 |
+
llm = ChatGroq(
|
| 276 |
+
model_name=GROQ_MODEL,
|
| 277 |
+
api_key=GROQ_API_KEY,
|
| 278 |
+
temperature=0.1,
|
| 279 |
+
max_tokens=50
|
| 280 |
+
)
|
| 281 |
+
except Exception as e:
|
| 282 |
+
logger.error(f"Failed to initialize Groq model: {e}")
|
| 283 |
+
raise HTTPException(status_code=500, detail="Failed to initialize Groq model")
|
| 284 |
|
| 285 |
# Salesforce credentials
|
| 286 |
username = os.getenv("username")
|
|
|
|
| 311 |
context_str += f"User asked: '{past_query}'\nBot answered: '{response}'\n"
|
| 312 |
|
| 313 |
# Construct the prompt
|
| 314 |
+
prompt_template = ChatPromptTemplate.from_messages([
|
| 315 |
+
("system", """
|
| 316 |
+
You are the Clara Redfernstech chatbot. Provide accurate, professional answers in 10-15 words.
|
| 317 |
+
|
| 318 |
+
Context:
|
| 319 |
+
{context}
|
| 320 |
+
|
| 321 |
+
Question:
|
| 322 |
+
{query}
|
| 323 |
+
"""),
|
| 324 |
+
])
|
| 325 |
+
prompt = prompt_template.format(context=context_str, query=query)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
|
| 327 |
try:
|
| 328 |
+
response = llm.invoke(prompt)
|
| 329 |
+
response_text = response.content.strip()
|
| 330 |
+
except Exception as e:
|
| 331 |
+
logger.error(f"Error querying Groq API: {e}")
|
|
|
|
|
|
|
| 332 |
response_text = "Sorry, I couldn't find an answer."
|
| 333 |
|
| 334 |
# Update chat history
|
|
|
|
| 385 |
return JSONResponse({"id": unique_id})
|
| 386 |
except Exception as e:
|
| 387 |
logger.error(f"Failed to create lead: {e}")
|
| 388 |
+
raise HTTPException(status_code=500, detail=f"Failed to create lead: {str(e)}")
|
| 389 |
|
| 390 |
@app.post("/chat/")
|
| 391 |
async def chat(request: MessageRequest):
|