Spaces:
Running
Running
Create gemini.py
Browse files
gemini.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import os
|
| 4 |
+
import requests
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
API_KEY = os.environ.get('GEMINI_KEY') # This gets the secret
|
| 8 |
+
|
| 9 |
+
class ChatRequest(BaseModel):
|
| 10 |
+
message: str
|
| 11 |
+
context: str
|
| 12 |
+
|
| 13 |
+
@app.post("/chat")
|
| 14 |
+
async def chat_endpoint(request: ChatRequest):
|
| 15 |
+
try:
|
| 16 |
+
response = requests.post(
|
| 17 |
+
"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent",
|
| 18 |
+
params={"key": API_KEY},
|
| 19 |
+
json={
|
| 20 |
+
"contents": [{
|
| 21 |
+
"parts": [{
|
| 22 |
+
"text": f"Using this context: {request.context[:3000]}\nAnswer: {request.message}"
|
| 23 |
+
}]
|
| 24 |
+
}]
|
| 25 |
+
}
|
| 26 |
+
)
|
| 27 |
+
return response.json()
|
| 28 |
+
except Exception as e:
|
| 29 |
+
raise HTTPException(status_code=500, detail=str(e))
|