huijio commited on
Commit
900e81e
·
verified ·
1 Parent(s): f6491ad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -37
app.py CHANGED
@@ -1,43 +1,49 @@
 
 
 
 
 
 
1
  from fastapi import FastAPI, HTTPException, Depends, Security
2
  from fastapi.security import APIKeyHeader
3
  from fastapi.responses import JSONResponse
4
  from pydantic import BaseModel
5
- import requests
6
- import uuid
7
- from datetime import datetime
8
  import uvicorn
9
- import os
 
 
 
10
 
11
  app = FastAPI()
12
 
13
  # Configuration
14
  API_KEY_NAME = "X-API-KEY"
15
- API_KEYS = os.getenv("API_KEYS", "").split(",") # Comma-separated list of valid API keys
 
 
 
 
 
16
 
17
  # Security
18
  api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
19
 
20
- async def get_api_key(api_key_header: str = Security(api_key_header)):
21
- if not api_key_header:
22
- raise HTTPException(
23
- status_code=401,
24
- detail="API key is missing"
25
- )
26
- if api_key_header not in API_KEYS:
27
- raise HTTPException(
28
- status_code=401,
29
- detail="Invalid API key"
30
- )
31
- return api_key_header
32
 
33
  class Message(BaseModel):
34
  role: str
35
  content: str
36
 
37
  class ChatRequest(BaseModel):
38
- messages: list[Message]
39
- model: str = "deepseek-ai/DeepSeek-R1"
40
  temperature: float = 0.7
 
41
 
42
  @app.get("/")
43
  async def health_check():
@@ -49,23 +55,19 @@ async def chat_completion(
49
  api_key: str = Depends(get_api_key)
50
  ):
51
  try:
52
- response = requests.post(
53
- "https://www.multichatai.com/api/chat/deepinfra",
54
- json={
55
- "chatSettings": {
56
- "model": request.model,
57
- "prompt": "You are helpful.",
58
- "temperature": request.temperature,
59
- "contextLength": 4096
60
- },
61
- "messages": [
62
- {"role": "system", "content": "You are helpful."},
63
- *[{"role": m.role, "content": m.content} for m in request.messages]
64
- ]
65
- },
66
- timeout=10
67
  )
68
- response.raise_for_status()
69
 
70
  return JSONResponse({
71
  "id": str(uuid.uuid4()),
@@ -75,7 +77,7 @@ async def chat_completion(
75
  "choices": [{
76
  "message": {
77
  "role": "assistant",
78
- "content": response.text.strip()
79
  }
80
  }]
81
  })
@@ -83,4 +85,7 @@ async def chat_completion(
83
  raise HTTPException(status_code=500, detail=str(e))
84
 
85
  if __name__ == "__main__":
86
- uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=False)
 
 
 
 
1
+ import os
2
+ import uuid
3
+ from datetime import datetime
4
+ from typing import List
5
+
6
+ from dotenv import load_dotenv
7
  from fastapi import FastAPI, HTTPException, Depends, Security
8
  from fastapi.security import APIKeyHeader
9
  from fastapi.responses import JSONResponse
10
  from pydantic import BaseModel
 
 
 
11
  import uvicorn
12
+ from huggingface_hub import InferenceClient
13
+
14
+ # Load environment variables
15
+ load_dotenv()
16
 
17
  app = FastAPI()
18
 
19
  # Configuration
20
  API_KEY_NAME = "X-API-KEY"
21
+ API_KEYS = os.getenv("API_KEYS", "").split(",")
22
+ HF_MODEL = os.getenv("HF_MODEL_NAME", "deepseek-ai/deepseek-llm-7b")
23
+ HF_TOKEN = os.getenv("HF_API_TOKEN")
24
+
25
+ # Initialize Hugging Face client
26
+ client = InferenceClient(token=HF_TOKEN)
27
 
28
  # Security
29
  api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
30
 
31
+ async def get_api_key(api_key: str = Security(api_key_header)):
32
+ if not api_key:
33
+ raise HTTPException(status_code=401, detail="API key is missing")
34
+ if api_key not in API_KEYS:
35
+ raise HTTPException(status_code=401, detail="Invalid API key")
36
+ return api_key
 
 
 
 
 
 
37
 
38
  class Message(BaseModel):
39
  role: str
40
  content: str
41
 
42
  class ChatRequest(BaseModel):
43
+ messages: List[Message]
44
+ model: str = HF_MODEL
45
  temperature: float = 0.7
46
+ max_tokens: int = 200
47
 
48
  @app.get("/")
49
  async def health_check():
 
55
  api_key: str = Depends(get_api_key)
56
  ):
57
  try:
58
+ # Format messages for HF inference
59
+ prompt = "\n".join(
60
+ f"{msg.role}: {msg.content}"
61
+ for msg in request.messages
62
+ )
63
+
64
+ # Call Hugging Face model
65
+ response = client.text_generation(
66
+ prompt=prompt,
67
+ model=request.model,
68
+ temperature=request.temperature,
69
+ max_new_tokens=request.max_tokens
 
 
 
70
  )
 
71
 
72
  return JSONResponse({
73
  "id": str(uuid.uuid4()),
 
77
  "choices": [{
78
  "message": {
79
  "role": "assistant",
80
+ "content": response.strip()
81
  }
82
  }]
83
  })
 
85
  raise HTTPException(status_code=500, detail=str(e))
86
 
87
  if __name__ == "__main__":
88
+ uvicorn.run(
89
+ app,
90
+ host="0.0.0.0",
91
+ port=int(os.getenv("PORT", 7860))