progvm commited on
Commit
fffd7ba
·
verified ·
1 Parent(s): 6b4a905

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +34 -30
main.py CHANGED
@@ -1,45 +1,49 @@
1
- import os
2
- from typing import List, Optional
3
- from fastapi import FastAPI, Header, HTTPException, Depends
4
- from transformers import pipeline
5
  from pydantic import BaseModel
6
- from dotenv import load_dotenv
 
7
 
8
- load_dotenv()
9
- ALLOWED_API_KEYS = os.getenv("API_KEYS", "").split(",")
10
 
11
- app = FastAPI(title="Gemma 4 API", description="Gemma 4 API with Multi-modal support")
 
 
 
 
 
12
 
13
  pipe = pipeline(
14
  task="any-to-any",
15
- model="google/gemma-4-E2B-it",
16
- device="cpu",
17
- model_kwargs={"load_in_4bit": True}
18
  )
19
 
20
- def verify_key(x_api_key: str = Header(...)):
21
- if x_api_key not in ALLOWED_API_KEYS:
22
- raise HTTPException(status_code=403, detail="Invalid API Key")
23
- return x_api_key
24
-
25
  class Message(BaseModel):
26
  role: str
27
  content: List[dict]
 
 
 
 
 
28
 
29
- @app.post("/chat", dependencies=[Depends(verify_key)])
30
- def chat(messages: List[Message], system_prompt: str = "You are a helpful assistant."):
31
- """
32
- Отправить список сообщений.
33
- Пример content: [{"type": "text", "text": "Привет"}]
34
- Для картинок: [{"type": "image", "url": "http://..."}]
35
- """
36
 
37
- # Формируем промпт
38
- formatted_messages = [
39
- {"role": "system", "content":[{"type": "text", "text": system_prompt}]}
40
  ]
41
- for msg in messages:
42
- formatted_messages.append({"role": msg.role, "content": msg.content})
43
 
44
- result = pipe(formatted_messages, return_full_text=False)
45
- return {"response": result[0]['generated_text']}
 
 
 
 
 
1
+ from fastapi import FastAPI, Header, HTTPException
2
+ from transformers import pipeline, BitsAndBytesConfig
 
 
3
  from pydantic import BaseModel
4
+ from typing import List, Optional, Any
5
+ import logging
6
 
7
+ logging.basicConfig(level=logging.INFO)
8
+ app = FastAPI()
9
 
10
+ MODEL_ID = "google/gemma-4-E2B-it"
11
+
12
+ quantization_config = BitsAndBytesConfig(
13
+ load_in_4bit=True,
14
+ bnb_4bit_compute_dtype="bfloat16"
15
+ )
16
 
17
  pipe = pipeline(
18
  task="any-to-any",
19
+ model=MODEL_ID,
20
+ device="cpu",
21
+ model_kwargs={"quantization_config": quantization_config}
22
  )
23
 
 
 
 
 
 
24
  class Message(BaseModel):
25
  role: str
26
  content: List[dict]
27
+ class ChatRequest(BaseModel):
28
+ messages: List[Message]
29
+ system_prompt: Optional[str] = "You are a helpful assistant."
30
+
31
+ API_KEY = "bazi2281488133767695242"
32
 
33
+ @app.post("/chat")
34
+ def chat(request: ChatRequest, x_api_key: str = Header(None)):
35
+ if x_api_key != API_KEY:
36
+ raise HTTPException(status_code=403, detail="Invalid API Key")
 
 
 
37
 
38
+ messages =[
39
+ {"role": "system", "content":[{"type": "text", "text": request.system_prompt}]}
 
40
  ]
41
+ for msg in request.messages:
42
+ messages.append({"role": msg.role, "content": msg.content})
43
 
44
+ try:
45
+ result = pipe(messages, return_full_text=False)
46
+ return {"response": result[0]['generated_text']}
47
+ except Exception as e:
48
+ logging.error(f"Error: {e}")
49
+ raise HTTPException(status_code=500, detail=str(e))