Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import os
|
| 4 |
+
from groq import Groq
|
| 5 |
+
|
| 6 |
+
app = FastAPI(title="Simple AI Chat")
|
| 7 |
+
|
| 8 |
+
# Initialize Groq client
|
| 9 |
+
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
|
| 10 |
+
|
| 11 |
+
class ChatRequest(BaseModel):
|
| 12 |
+
message: str
|
| 13 |
+
|
| 14 |
+
class ChatResponse(BaseModel):
|
| 15 |
+
response: str
|
| 16 |
+
|
| 17 |
+
@app.get("/")
|
| 18 |
+
def home():
|
| 19 |
+
return {"message": "AI Chat API is running"}
|
| 20 |
+
|
| 21 |
+
@app.post("/chat")
|
| 22 |
+
def chat(request: ChatRequest):
|
| 23 |
+
try:
|
| 24 |
+
if not client.api_key:
|
| 25 |
+
return ChatResponse(response="❌ GROQ_API_KEY not configured")
|
| 26 |
+
|
| 27 |
+
completion = client.chat.completions.create(
|
| 28 |
+
model="llama-3.1-8b-instant",
|
| 29 |
+
messages=[
|
| 30 |
+
{"role": "system", "content": "You are a helpful AI assistant."},
|
| 31 |
+
{"role": "user", "content": request.message}
|
| 32 |
+
],
|
| 33 |
+
temperature=0.7,
|
| 34 |
+
max_tokens=1024
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
response = completion.choices[0].message.content
|
| 38 |
+
return ChatResponse(response=response)
|
| 39 |
+
|
| 40 |
+
except Exception as e:
|
| 41 |
+
return ChatResponse(response=f"Error: {str(e)}")
|