Update app.py
Browse files
app.py
CHANGED
@@ -1,107 +1,126 @@
|
|
|
|
1 |
import os
|
2 |
-
import
|
3 |
-
from
|
4 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
# Initialize OpenRouter client
|
7 |
-
|
8 |
base_url="https://openrouter.ai/api/v1",
|
9 |
-
api_key=
|
10 |
)
|
11 |
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
history: List[Tuple[str, str]],
|
23 |
-
system_message: str,
|
24 |
-
model: str,
|
25 |
-
max_tokens: int,
|
26 |
-
temperature: float,
|
27 |
-
top_p: float,
|
28 |
-
) -> str:
|
29 |
-
# Construct messages array with system message and history
|
30 |
-
messages = [{"role": "system", "content": system_message}]
|
31 |
-
|
32 |
-
# Add conversation history
|
33 |
-
for user_msg, assistant_msg in history:
|
34 |
-
if user_msg:
|
35 |
-
messages.append({"role": "user", "content": user_msg})
|
36 |
-
if assistant_msg:
|
37 |
-
messages.append({"role": "assistant", "content": assistant_msg})
|
38 |
-
|
39 |
-
# Add current message
|
40 |
-
messages.append({"role": "user", "content": message})
|
41 |
-
|
42 |
try:
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
messages=messages,
|
50 |
-
max_tokens=max_tokens,
|
51 |
-
temperature=temperature,
|
52 |
-
top_p=top_p,
|
53 |
-
stream=True # Enable streaming
|
54 |
-
)
|
55 |
|
56 |
-
#
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
|
|
|
|
63 |
except Exception as e:
|
64 |
-
|
|
|
65 |
|
66 |
-
#
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
value=0.95,
|
97 |
-
step=0.05,
|
98 |
-
label="Top-p (nucleus sampling)"
|
99 |
-
),
|
100 |
-
],
|
101 |
-
title="OpenRouter Chat Interface",
|
102 |
-
description="Chat with various AI models through OpenRouter API"
|
103 |
-
)
|
104 |
|
105 |
-
# Launch the app
|
106 |
if __name__ == "__main__":
|
107 |
-
|
|
|
1 |
+
import json
|
2 |
import os
|
3 |
+
import fastapi
|
4 |
+
from fastapi.responses import StreamingResponse
|
5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
6 |
+
from openai import AsyncOpenAI
|
7 |
+
import uvicorn
|
8 |
+
import logging
|
9 |
+
from dotenv import load_dotenv
|
10 |
+
from pydantic import BaseModel
|
11 |
+
from typing import List, Optional, Dict, Any
|
12 |
+
|
13 |
+
# Load environment variables
|
14 |
+
load_dotenv()
|
15 |
+
|
16 |
+
# Retrieve API key from environment
|
17 |
+
OPENROUTER_API_KEY = os.getenv('OPENROUTER_API_KEY')
|
18 |
+
if not OPENROUTER_API_KEY:
|
19 |
+
raise ValueError("OPENROUTER_API_KEY not found in environment variables")
|
20 |
+
|
21 |
+
# Setup FastAPI app
|
22 |
+
app = fastapi.FastAPI()
|
23 |
+
|
24 |
+
# Add CORS middleware
|
25 |
+
app.add_middleware(
|
26 |
+
CORSMiddleware,
|
27 |
+
allow_origins=["*"],
|
28 |
+
allow_credentials=True,
|
29 |
+
allow_methods=["*"],
|
30 |
+
allow_headers=["*"],
|
31 |
+
)
|
32 |
|
33 |
# Initialize OpenRouter client
|
34 |
+
oai_client = AsyncOpenAI(
|
35 |
base_url="https://openrouter.ai/api/v1",
|
36 |
+
api_key=OPENROUTER_API_KEY
|
37 |
)
|
38 |
|
39 |
+
class Message(BaseModel):
|
40 |
+
role: str
|
41 |
+
content: str
|
42 |
+
|
43 |
+
class ChatCompletionRequest(BaseModel):
|
44 |
+
messages: List[Message]
|
45 |
+
model: str
|
46 |
+
temperature: Optional[float] = 0.7
|
47 |
+
max_tokens: Optional[int] = None
|
48 |
+
stream: Optional[bool] = True # Default to True for ElevenLabs
|
49 |
+
user_id: Optional[str] = None
|
50 |
+
extra_headers: Optional[Dict[str, str]] = None
|
51 |
+
extra_body: Optional[Dict[str, Any]] = None
|
52 |
|
53 |
+
@app.post("/v1/chat/completions")
|
54 |
+
async def create_chat_completion(request: ChatCompletionRequest) -> StreamingResponse:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
try:
|
56 |
+
# Prepare the request for OpenRouter
|
57 |
+
oai_request = request.dict(exclude_none=True)
|
58 |
+
|
59 |
+
# Remove fields that OpenRouter doesn't expect
|
60 |
+
if "user_id" in oai_request:
|
61 |
+
oai_request["user"] = oai_request.pop("user_id")
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
+
# Add OpenRouter specific headers
|
64 |
+
extra_headers = {
|
65 |
+
"HTTP-Referer": os.getenv("SITE_URL", "https://huggingface.co/spaces"),
|
66 |
+
"X-Title": os.getenv("SITE_NAME", "ElevenLabs-OpenRouter Bridge"),
|
67 |
+
}
|
68 |
+
oai_request["extra_headers"] = extra_headers
|
69 |
+
|
70 |
+
# Ensure the model is an OpenRouter model
|
71 |
+
if not oai_request["model"].startswith("openai/") and "/" not in oai_request["model"]:
|
72 |
+
oai_request["model"] = "nousresearch/hermes-3-llama-3.1-405b"
|
73 |
+
|
74 |
+
# Create the chat completion
|
75 |
+
chat_completion_coroutine = await oai_client.chat.completions.create(**oai_request)
|
76 |
+
|
77 |
+
async def event_stream():
|
78 |
+
try:
|
79 |
+
async for chunk in chat_completion_coroutine:
|
80 |
+
# Convert the ChatCompletionChunk to a dictionary
|
81 |
+
chunk_dict = chunk.model_dump()
|
82 |
+
yield f"data: {json.dumps(chunk_dict)}\n\n"
|
83 |
+
yield "data: [DONE]\n\n"
|
84 |
+
except Exception as e:
|
85 |
+
logging.error(f"Streaming error: {str(e)}")
|
86 |
+
yield f"data: {json.dumps({'error': str(e)})}\n\n"
|
87 |
|
88 |
+
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
89 |
+
|
90 |
except Exception as e:
|
91 |
+
logging.error(f"Request error: {str(e)}")
|
92 |
+
raise fastapi.HTTPException(status_code=500, detail=str(e))
|
93 |
|
94 |
+
# Health check endpoint
|
95 |
+
@app.get("/health")
|
96 |
+
async def health_check():
|
97 |
+
return {"status": "healthy"}
|
98 |
+
|
99 |
+
# Models endpoint
|
100 |
+
@app.get("/v1/models")
|
101 |
+
async def list_models():
|
102 |
+
return {
|
103 |
+
"data": [
|
104 |
+
{
|
105 |
+
"id": "nousresearch/hermes-3-llama-3.1-405b",
|
106 |
+
"object": "model",
|
107 |
+
"created": 1677610602,
|
108 |
+
"owned_by": "openrouter",
|
109 |
+
},
|
110 |
+
{
|
111 |
+
"id": "anthropic/claude-3-opus",
|
112 |
+
"object": "model",
|
113 |
+
"created": 1677610602,
|
114 |
+
"owned_by": "openrouter",
|
115 |
+
},
|
116 |
+
{
|
117 |
+
"id": "mistralai/mixtral-8x7b",
|
118 |
+
"object": "model",
|
119 |
+
"created": 1677610602,
|
120 |
+
"owned_by": "openrouter",
|
121 |
+
}
|
122 |
+
]
|
123 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
124 |
|
|
|
125 |
if __name__ == "__main__":
|
126 |
+
uvicorn.run(app, host="0.0.0.0", port=8013)
|