class ModelClient:
def init(self):
self.model = Client("gokaygokay/Gemma-2-llamacpp")
code
def get_response(self, message, history, sys_prompt):
result = self.model.predict(
message=message,
model="gemma-2-27b-it-Q5_K_M.gguf",
system_message=sys_prompt,
max_tokens=2048,
temperature=0.7,
top_p=0.95,
top_k=40,
repeat_penalty=1.1,
api_name="/chat"
)
return result
У меня есть класс моей модели. Мне нужно написать скрипт который с помощью FastApi на python будет запускать api сервер на котором будет развернуто взаимодействие с моей моделью. Пример запроса к api должен быть такой:
Certainly! Below is a complete Python script that sets up a FastAPI server to interact with your ModelClient class. This server will expose an endpoint /v1/chat/completions that accepts POST requests in the format you've specified and returns responses from your model.
Step-by-Step Guide
Install Required Packages
First, ensure you have the necessary packages installed. You can install them using pip:
Below is the complete script. Save it as api_server.py or any name you prefer.
python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from typing import List, Optional
from gradio_client import Client
import uuid
import time
# Define the structure of each message
class Message(BaseModel):
role: str
content: str
# Define the structure of the chat completion request
class ChatCompletionRequest(BaseModel):
model: str
messages: List[Message]
temperature: Optional[float] = 0.7
max_tokens: Optional[int] = 2048
top_p: Optional[float] = 0.95
top_k: Optional[int] = 40
repeat_penalty: Optional[float] = 1.1
stream: Optional[bool] = False # Not implemented in this example
# Define the structure of each choice in the response
class Choice(BaseModel):
message: Message
finish_reason: Optional[str] = None
index: int
# Define the structure of the chat completion response
class ChatCompletionResponse(BaseModel):
id: str
object: str
created: int
choices: List[Choice]
usage: Optional[dict] = None # Can be populated with token usage info if available
# Your ModelClient class interfacing with the Gradio model
class ModelClient:
def __init__(self):
# Initialize the Gradio client with your specific model
self.model = Client("gokaygokay/Gemma-2-llamacpp")
def get_response(self, message: str, sys_prompt: str, max_tokens: int, temperature: float,
top_p: float, top_k: int, repeat_penalty: float) -> str:
try:
result = self.model.predict(
message=message,
model="gemma-2-27b-it-Q5_K_M.gguf",
system_message=sys_prompt,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
top_k=top_k,
repeat_penalty=repeat_penalty,
api_name="/chat"
)
return result
except Exception as e:
raise RuntimeError(f"Model prediction failed: {e}")
# Initialize FastAPI app and ModelClient
app = FastAPI()
client = ModelClient()
@app.post("/v1/chat/completions", response_model=ChatCompletionResponse)
def chat_completions(request: ChatCompletionRequest):
"""
Endpoint to handle chat completions.
"""
try:
system_message = ""
user_message = ""
# Extract system and user messages from the request
for msg in request.messages:
if msg.role == "system":
system_message = msg.content
elif msg.role == "user":
user_message = msg.content
else:
# You can handle other roles like "assistant" here if needed
pass
# Handle max_tokens parameter, ensuring it's positive
max_tokens = request.max_tokens if request.max_tokens > 0 else 2048
# Get the model's response
response_text = client.get_response(
message=user_message,
sys_prompt=system_message,
max_tokens=max_tokens,
temperature=request.temperature,
top_p=request.top_p,
top_k=request.top_k,
repeat_penalty=request.repeat_penalty
)
# Construct the response in OpenAI's format
response = ChatCompletionResponse(
id=str(uuid.uuid4()),
object="chat.completion",
created=int(time.time()),
choices=[
Choice(
message=Message(role="assistant", content=response_text),
index=0
)
],
usage=None # You can add token usage details here if available
)
return response
except Exception as e:
# Handle exceptions and return a 500 error with details
raise HTTPException(status_code=500, detail=str(e))
# Optional: Root endpoint for health checks or welcome message
@app.get("/")
def read_root():
return {"message": "Welcome to the Gemma-2 Chat API"}
# To run the server, use the following command:
# uvicorn api_server:app --host 0.0.0.0 --port 1234
Run the FastAPI Server
Open your terminal, navigate to the directory containing api_server.py, and run:
bash
uvicorn api_server:app --host 0.0.0.0 --port 1234
This command starts the FastAPI server on http://localhost:1234.
Testing the API
You can test the API using the curl command you provided. Here's how you can do it:
Note: In the script above, if max_tokens is set to a value less than or equal to 0, it defaults to 2048. You can adjust this logic as needed.
Optional Enhancements
Error Handling: The script includes basic error handling. Depending on your needs, you might want to enhance this to handle different types of errors more gracefully.
Logging: Integrate logging for better monitoring and debugging.
Authentication: If you plan to expose this API publicly, consider adding authentication mechanisms to secure access.
Streaming Responses: The current implementation does not support streaming responses ("stream": false). Implementing streaming would require a different approach, potentially using WebSockets or Server-Sent Events (SSE).
Understanding the Response Structure
The API responds with a JSON object structured similarly to OpenAI's Chat Completions API. Here's an example of what the response might look like:
object: The type of object returned, e.g., "chat.completion".
created: Unix timestamp of when the completion was created.
choices: An array of possible completions. Each choice includes the message, finish reason, and an index.
usage: (Optional) Information about token usage.
Conclusion
This setup provides a functional FastAPI server that interfaces with your ModelClient to handle chat-based requests. You can further customize and expand this server based on your specific requirements, such as adding more parameters, handling different roles, or integrating additional features.
Feel free to reach out if you have any questions or need further assistance!