|
from fastapi import FastAPI, HTTPException |
|
from pydantic import BaseModel |
|
import requests |
|
import json |
|
|
|
app = FastAPI() |
|
|
|
|
|
class ChatRequest(BaseModel): |
|
system_prompt: str |
|
user_query: str |
|
model: str = "gemini-1.5-pro-latest" |
|
temperature: float = 1.0 |
|
top_p: float = 0.8 |
|
max_tokens: int = 4000 |
|
|
|
|
|
url = "https://chat.typegpt.net/api/openai/v1/chat/completions" |
|
headers = { |
|
"Accept": "application/json, text/event-stream", |
|
"Content-Type": "application/json", |
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0", |
|
} |
|
|
|
@app.post("/chat") |
|
async def chat(request: ChatRequest): |
|
|
|
payload = { |
|
"messages": [ |
|
{ |
|
"role": "system", |
|
"content": request.system_prompt |
|
}, |
|
{ |
|
"role": "user", |
|
"content": request.user_query |
|
} |
|
], |
|
"stream": True, |
|
"model": request.model, |
|
"temperature": request.temperature, |
|
"top_p": request.top_p, |
|
"max_tokens": request.max_tokens |
|
} |
|
|
|
|
|
try: |
|
with requests.post(url, headers=headers, data=json.dumps(payload), stream=True) as response: |
|
|
|
if response.status_code == 200: |
|
result = "" |
|
|
|
for line in response.iter_lines(): |
|
if line: |
|
|
|
decoded_line = line.decode('utf-8') |
|
|
|
|
|
if decoded_line.startswith("data: "): |
|
|
|
json_data = decoded_line[6:] |
|
|
|
|
|
try: |
|
parsed_data = json.loads(json_data) |
|
|
|
if 'choices' in parsed_data and len(parsed_data['choices']) > 0: |
|
content = parsed_data['choices'][0]['delta'].get('content', '') |
|
if content: |
|
result += content |
|
except json.JSONDecodeError: |
|
continue |
|
return {"response": result} |
|
else: |
|
raise HTTPException(status_code=response.status_code, detail=response.text) |
|
except Exception as e: |
|
raise HTTPException(status_code=500, detail=str(e)) |
|
|
|
if __name__ == "__main__": |
|
import uvicorn |
|
uvicorn.run(app, host="0.0.0.0", port=8083) |