@staticmethod
def _generate_random_hash(length=10):
"""Генерирует случайный хэш указанной длины"""
characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return ''.join(secrets.choice(characters) for _ in range(length))
def _make_join_request(self, body):
try:
response = requests.post(self.join_url, headers=self.headers, json=body)
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(f"HTTP error occurred: {e}")
except Exception as e:
print(f"An error occurred: {e}")
return None
def _make_stream_request(self):
try:
response = requests.get(self.stream_url, headers={**self.headers, 'accept': "text/event-stream"},
stream=True)
response.raise_for_status()
return response
except requests.exceptions.HTTPError as e:
print(f"HTTP error occurred: {e}")
except Exception as e:
print(f"An error occurred: {e}")
return None
@staticmethod
def _process_stream_response(response):
response_message = ""
if response:
for chunk in response.iter_lines():
if chunk:
try:
event_data = json.loads(chunk.decode('utf-8').replace("data: ", ""))
if event_data.get('msg') == "process_generating":
if event_data['output']['data'][0]:
output = event_data['output']['data'][0][-1]
response_message += output[-1] # аккумулируем текст
yield response_message # отдаём текущее состояние текста
except json.JSONDecodeError:
continue
yield response_message # Возвращаем окончательный ответ
def get_response(self, message, history, sys_prompt):
if not history:
self.session_hash = self._generate_random_hash()
self.stream_url = f"https://yuntian-deng-chatgpt.hf.space/queue/data?session_hash={self.session_hash}"
input_message = sys_prompt + "\n" + message
else:
input_message = message
body = {
"data": [input_message, 1, 1, len(history), history, None],
"event_data": None,
"fn_index": 3,
"trigger_id": 5,
"session_hash": self.session_hash
}
self._make_join_request(body)
stream_response = self._make_stream_request()
# Используем цикл for для последовательной обработки
for chunk in self._process_stream_response(stream_response):
yield chunk # Теперь передаём каждый кусок данных Gradio
The provided code sets up a Gradio-based chat application named NeuroRavenApp that interacts with a model client to process text-based queries in a conversational context. Below, I’ll outline the main components and functionality of the code as well as some suggestions for improvement or additional features.
Key Components
NeuroRavenApp Class:
Initialization: Loads configuration, initializes model client, and sets up conversation themes.
get_conversation_themes(): Fetches conversation themes from a JSON file.
handle_query(): Processes user messages and returns responses. Supports saving messages to a context and loading previous conversation themes.
launch_app(): Launches the Gradio chat interface with the specified layout and components.
load_model_client(): Loads the appropriate model client based on a configuration file.
ModelClient Class:
Manages interaction with the external model service. Handles request making and processes streaming responses.
Uses session handling to connect with the model and manage state.
Processing Messages
User messages can be saved to a specific context theme, enabling personalized or context-driven responses.
Messages can be sent to the model for processing, and responses are generated as streams, allowing real-time interaction.
Real-time Response Handling
Uses a generator to yield responses chunk by chunk, enhancing the user experience during waiting.
Suggestions for Improvement
Error Handling:
While some basic error handling is present, logging more detailed error messages can help in debugging and improving user experience.
Consider incorporating user-facing notifications for handling HTTP errors or other exceptions gracefully in the UI.
User Authentication:
If the application is intended for multiple users, consider implementing an authentication mechanism for users to store and manage their own context data securely.
Enhanced UI Features:
Add more UI options (like themes or layouts) for a better user experience.
Consider implementing a loading spinner or progress indicator when longer responses are expected.
State Management:
The application could benefit from better state management, especially if it needs to coordinate user interactions, history, and context themes more reliably.
Extensibility:
The ability to add more models or easily switch between them based on user preference could enhance the application's versatility.
Documentation:
Add docstrings and comments for complex methods to enhance code maintainability and understanding for future developers.
Unit Testing:
Implement unit tests for critical components and handling of expected edge cases, ensuring reliability and robustness of the system.
Remove Hardcoded Values:
Store URLs and other configurations in environment variables or a config file to enhance security and flexibility.
Overall, the code establishes a straightforward, scalable chat application framework, leveraging Gradio for the UI and providing a solid foundation for further enhancements and feature additions.
To adapt your application to support the new ModelClient class that uses the Gradio client for the Gemma-2 model, you will need to adjust the way you handle the response from the model. The get_response method of this new ModelClient does not provide streaming output but instead returns a complete response at once. Here’s how you can make that work while integrating it into your NeuroRavenApp.
Adjustments Needed
Modify the get_response Method:
The new method returns a single response instead of a stream. You'll need to update the calling conventions in your NeuroRavenApp class accordingly.
Update the handle_query Method:
Since the new model client does not yield responses in a loop, your handle_query method should handle responses differently.
Updated Code Example
Here’s how your code would look like after making the necessary adjustments. I’ll provide the new ModelClient code, along with how to integrate it into your NeuroRavenApp class.
python
import json
import gradio as gr
from context.db_loader import SQLiteContextLoader
import constants
from helpers import load_json_file
from gradio_client import Client
class ModelClient:
def __init__(self):
self.model = Client("gokaygokay/Gemma-2-llamacpp")
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
class NeuroRavenApp:
def __init__(self):
self.system_prompt = None
self.current_theme = None
self.client = self.load_model_client()
self.context_loader = SQLiteContextLoader()
self.conversation_themes = self.get_conversation_themes()
if constants.NO_CONTEXT not in self.conversation_themes:
self.conversation_themes.append(constants.NO_CONTEXT)
@staticmethod
def get_conversation_themes():
themes = load_json_file(constants.CONVERSATION_THEMES_JSON)
return themes
def handle_query(self, message, history, context_theme, should_save):
if should_save and isinstance(self.context_loader, SQLiteContextLoader):
if context_theme == constants.NO_CONTEXT:
return constants.ERROR_CANNOT_SAVE_MESSAGE
self.context_loader.save_message(context_theme, message)
self.current_theme = None
return constants.MESSAGE_SAVED_TO_CONTEXT
if context_theme != self.current_theme:
context = self.context_loader.load_context(context_theme)
if context:
self.system_prompt = constants.ANSWER_USING_CONTEXT_PROMPT.format(context=context)
else:
self.system_prompt = constants.DEFAULT_SYSTEM_PROMPT
self.current_theme = context_theme
# Call the model client to get the response
response = self.client.get_response(
message=message,
history=history,
sys_prompt=self.system_prompt
)
return response # Return the complete response
def launch_app(self):
gr.ChatInterface(
fn=self.handle_query,
chatbot=gr.Chatbot(height=500),
textbox=gr.Textbox(
placeholder=constants.INPUT_PLACEHOLDER,
container=False,
scale=7
),
title="NeuroRaven",
theme="soft",
retry_btn=None,
clear_btn=constants.CLEAR_BUTTON_LABEL,
additional_inputs=[
gr.Dropdown(
self.conversation_themes,
label=constants.SELECT_CONTEXT_THEME_LABEL,
value=constants.NO_CONTEXT
),
gr.Checkbox(
label=constants.SAVE_MESSAGE_LABEL,
value=False
)
],
css="footer{display:none !important}"
).launch(server_name=constants.SERVER_NAME, server_port=constants.SERVER_PORT)
@staticmethod
def load_model_client():
# Initialize the specific model client for Gemma
return ModelClient()
if __name__ == "__main__":
app = NeuroRavenApp()
app.launch_app()
Changes Explained
Response Handling:
The handle_query function now directly assigns the result of self.client.get_response() to the response variable and returns it. This change accommodates the non-streaming design of the Gemma-2 model.
ModelClient Integration:
The ModelClient class provides a simple interface that directly interacts with the Gemma-2 model, without the need for managing session hashes or stream URLs.
Deploying and Testing
After implementing these changes, test the application by running it and interacting with the UI. Validate that user input correctly invokes the model and that the responses appear as expected.
This setup should allow you to use the Gemma-2 model within your Gradio application seamlessly.
Got it! If you need your application to support multiple models, including those that return streaming responses and those that return static responses, you'll need to design your ModelClient interface in a way that abstracts the differences between the streaming and non-streaming models.
Solution Design
Base Class for ModelClient: Create a base class or interface for ModelClient that both streaming and non-streaming clients will inherit from. This allows you to define a common get_response method that all models will implement.
Streaming and Non-Streaming Clients: Create two subclasses of ModelClient: one for handling streaming models and another for non-streaming models.
Dynamic Client Selection: Based on configuration or user input, you can choose which ModelClient to instantiate and use.
Here's how you can redesign the classes:
Updated Code Example
python
import json
import gradio as gr
from context.db_loader import SQLiteContextLoader
import constants
from helpers import load_json_file
from gradio_client import Client # For non-streaming models
import requests # Assuming you still want to support streaming through requests
# Base class for Model Clients
class BaseModelClient:
def get_response(self, message, history, sys_prompt):
raise NotImplementedError("This method should be overridden by subclasses.")
# For non-streaming model (Gemma-2)
class GemmaClient(BaseModelClient):
def __init__(self):
self.model = Client("gokaygokay/Gemma-2-llamacpp")
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
# For streaming model (example model)
class StreamingModelClient(BaseModelClient):
def __init__(self):
self.session_hash = None
self.stream_url = None
# Add other initialization as needed
def _generate_random_hash(self, length=10):
"""Generates a random hash of the given length"""
characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return ''.join(secrets.choice(characters) for _ in range(length))
def get_response(self, message, history, sys_prompt):
# Implement streaming call logic here, yielding responses as needed
self.session_hash = self._generate_random_hash()
self.stream_url = f"https://example.com/queue/data?session_hash={self.session_hash}"
input_message = sys_prompt + "\n" + message
# Assuming we call some API and yield responses
yield from self._make_streaming_request(input_message)
def _make_streaming_request(self, input_message):
# Send request and handle streaming responses
pass
class NeuroRavenApp:
def __init__(self, model_type):
self.system_prompt = None
self.current_theme = None
self.client = self.load_model_client(model_type)
self.context_loader = SQLiteContextLoader()
self.conversation_themes = self.get_conversation_themes()
if constants.NO_CONTEXT not in self.conversation_themes:
self.conversation_themes.append(constants.NO_CONTEXT)
@staticmethod
def get_conversation_themes():
themes = load_json_file(constants.CONVERSATION_THEMES_JSON)
return themes
def handle_query(self, message, history, context_theme, should_save):
if should_save and isinstance(self.context_loader, SQLiteContextLoader):
if context_theme == constants.NO_CONTEXT:
return constants.ERROR_CANNOT_SAVE_MESSAGE
self.context_loader.save_message(context_theme, message)
self.current_theme = None
return constants.MESSAGE_SAVED_TO_CONTEXT
if context_theme != self.current_theme:
context = self.context_loader.load_context(context_theme)
if context:
self.system_prompt = constants.ANSWER_USING_CONTEXT_PROMPT.format(context=context)
else:
self.system_prompt = constants.DEFAULT_SYSTEM_PROMPT
self.current_theme = context_theme
# Call the model client to get the response
response = self.client.get_response(message, history, self.system_prompt)
if isinstance(response, str):
return response # For non-streaming (Gemma)
else:
# For streaming (streaming models return generators)
# You may want to handle streaming differently
return response # This should yield chunks in Gradio
def launch_app(self):
gr.ChatInterface(
fn=self.handle_query,
chatbot=gr.Chatbot(height=500),
textbox=gr.Textbox(
placeholder=constants.INPUT_PLACEHOLDER,
container=False,
scale=7
),
title="NeuroRaven",
theme="soft",
retry_btn=None,
clear_btn=constants.CLEAR_BUTTON_LABEL,
additional_inputs=[
gr.Dropdown(
self.conversation_themes,
label=constants.SELECT_CONTEXT_THEME_LABEL,
value=constants.NO_CONTEXT
),
gr.Checkbox(
label=constants.SAVE_MESSAGE_LABEL,
value=False
)
],
css="footer{display:none !important}"
).launch(server_name=constants.SERVER_NAME, server_port=constants.SERVER_PORT)
@staticmethod
def load_model_client(model_type):
if model_type == 'gemma':
return GemmaClient()
elif model_type == 'streaming_model':
return StreamingModelClient()
else:
raise ValueError("Unknown model type")
if __name__ == "__main__":
# Replace 'gemma' with the actual model type you want to use
app = NeuroRavenApp(model_type='gemma')
app.launch_app()
Key Changes
Base Class Definition: The BaseModelClient class defines an interface for model clients. Subclassing allows for specialization for different models.
Subclass Implementation:
GemmaClient: Implements the non-streaming model.
StreamingModelClient: Implements the streaming model. You need to fill in the streaming logic in _make_streaming_request().
Dynamic Model Selection: The NeuroRavenApp class can dynamically choose which model client to use based on input or configuration.
Response Handling:
In handle_query, you need to check the type of response to differentiate between streaming and non-streaming outputs.
Conclusion
With this setup, your application can easily support both streaming and non-streaming models, allowing flexibility in the usage of different AI models. You may need to further customize how you handle messages and responses based on the specifics of the models and your application's requirements.