added_ai_proxy
This commit is contained in:
51
app/main.py
51
app/main.py
@@ -6,6 +6,7 @@ from . import models, schemas, auth, database
|
||||
from passlib.context import CryptContext
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from contextlib import asynccontextmanager
|
||||
import httpx
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
@@ -212,3 +213,53 @@ async def test1():
|
||||
c = a+b
|
||||
return {"msg": f"this is a msg {c}"}
|
||||
|
||||
|
||||
@app.post("/ai/proxy", response_model=schemas.AIResponse)
|
||||
async def ai_proxy(
|
||||
ai_request: schemas.AIRequest,
|
||||
current_user: models.User = Depends(auth.get_current_user),
|
||||
db: AsyncSession = Depends(database.get_db)
|
||||
):
|
||||
"""
|
||||
Proxy relay for AI requests.
|
||||
Fetches AI configuration from the database.
|
||||
"""
|
||||
# Fetch active AI config
|
||||
result = await db.execute(
|
||||
select(models.AIConfig).where(models.AIConfig.is_active == True)
|
||||
)
|
||||
config = result.scalars().first()
|
||||
|
||||
if not config:
|
||||
raise HTTPException(status_code=500, detail="AI configuration not found")
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {config.api_key}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
# Prepare payload
|
||||
payload = ai_request.model_dump()
|
||||
payload["model"] = config.default_model
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
response = await client.post(
|
||||
config.api_url,
|
||||
json=payload,
|
||||
headers=headers,
|
||||
timeout=30.0
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise HTTPException(
|
||||
status_code=e.response.status_code,
|
||||
detail=f"AI provider returned an error: {e.response.text}"
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"An error occurred while requesting AI provider: {str(e)}"
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user