Implement create_session.dspy script and update backend function to call hermes-service API

This commit is contained in:
yumoqing 2026-04-23 10:58:23 +08:00
parent 607718ac21
commit f6c07f6d10
3 changed files with 112 additions and 15 deletions

View File

@ -19,9 +19,31 @@ def load_hermes_web_cli():
"""Initialize and load the hermes-web-cli module. """Initialize and load the hermes-web-cli module.
This function is called by Sage system during module loading. This function is called by Sage system during module loading.
It can be used to perform any necessary initialization. It registers all module functions with the ServerEnv instance
so they can be called directly from .ui and .dspy files.
""" """
# Perform any module initialization here if needed from ahserver.serverenv import ServerEnv
# Get the ServerEnv instance
env = ServerEnv()
# Register all module functions with ServerEnv
env.get_setting = get_setting
env.save_setting = save_setting
env.get_all_services = get_all_services
env.create_service = create_service
env.delete_service = delete_service
env.get_service_by_id = get_service_by_id
env.test_service_connection = test_service_connection
env.create_session = create_session
env.send_message_to_service = send_message_to_service
env.get_session_messages = get_session_messages
env.get_active_sessions = get_active_sessions
env.get_recent_sessions = get_recent_sessions
env.get_session_by_id = get_session_by_id
env.validate_service_url = validate_service_url
env.generate_session_id = generate_session_id
return True return True
# Database operations using sqlor-database-module # Database operations using sqlor-database-module
@ -112,13 +134,42 @@ def test_service_connection(url: str, apikey: str = "") -> Tuple[bool, str]:
return False, f"Error: {str(e)}" return False, f"Error: {str(e)}"
# Session management # Session management
def create_session(service_id: str, user_message: str) -> str: def create_session(service_id: str, user_message: str = "") -> str:
"""Create a new session with a Hermes service.""" """Create a new session with a Hermes service."""
try: try:
session_id = str(uuid.uuid4()) # Get service configuration
# Save session to database service = get_service_by_id(service_id)
# Call remote service to create session if not service:
return session_id raise ValueError(f"Service {service_id} not found")
service_url = service["service_url"]
apikey = service.get("apikey", "")
# Prepare headers
headers = {
"Content-Type": "application/json"
}
# Add Authorization header if API key is provided
if apikey:
headers["Authorization"] = f"Bearer {apikey}"
# Call remote service API to create session
response = requests.post(
f"{service_url.rstrip('/')}/api/v1/sessions",
json={
"user_id": "web-cli-user", # This could be made configurable
"initial_message": user_message if user_message else None
},
headers=headers,
timeout=30
)
response.raise_for_status()
result = response.json()
# Return the session ID from the remote service
return result.get("session_id", "")
except Exception as e: except Exception as e:
print(f"Error creating session: {e}") print(f"Error creating session: {e}")
raise raise

View File

@ -0,0 +1,34 @@
# Create a new session with the selected Hermes service
# This .dspy file handles the POST request from new_session.ui form submission
# It receives form data with service_id and initial-prompt fields
try:
# Extract form data from request context
form_data = request.form if hasattr(request, 'form') else {}
# Get required parameters
service_id = form_data.get('service_id')
initial_prompt = form_data.get('initial-prompt', '')
if not service_id:
return {"error": "Service ID is required", "success": False}
# Use the function provided by the hermes-web-cli module
# This will call the remote hermes-service API
session_result = create_session(service_id, initial_prompt)
if session_result:
# Return success response with session details
return {
"success": True,
"session_id": session_result,
"service_id": service_id,
"redirect_url": f"/hermes-web-cli/sessions/{session_result}"
}
else:
return {"error": "Failed to create session", "success": False}
except Exception as e:
# Log the error and return failure
print(f"Error creating session: {str(e)}")
return {"error": f"Internal error: {str(e)}", "success": False}

View File

@ -24,6 +24,16 @@
"width": "100%", "width": "100%",
"maxWidth": "600px", "maxWidth": "600px",
"fields": [ "fields": [
{
"uitype": "select",
"name": "service_id",
"label": "Select Service",
"required": true,
"placeholder": "Choose a Hermes service",
"options": {
"url": "/hermes-web-cli/hermes_services/options"
}
},
{ {
"uitype": "text", "uitype": "text",
"name": "initial-prompt", "name": "initial-prompt",
@ -44,7 +54,7 @@
"borderRadius": "6px", "borderRadius": "6px",
"padding": "10px 20px", "padding": "10px 20px",
"fontWeight": "600", "fontWeight": "600",
"action": "create_session" "action": "submit"
}, },
{ {
"label": "Cancel", "label": "Cancel",
@ -61,13 +71,15 @@
"binds": [ "binds": [
{ {
"wid": "self", "wid": "self",
"event": "create_session", "event": "submit",
"actiontype": "registerfunction", "actiontype": "urlwidget",
"target": "app.new-session-container", "target": "app.main-content",
"rfname": "create_session", "options": {
"params": { "url": "{{entire_url('hermes-web-cli/sessions/create_session.dspy')}}",
"form_data": "{{ 'new-session-form'.data }}" "method": "POST",
} "data": "{{ 'new-session-form'.data }}"
},
"mode": "replace"
}, },
{ {
"wid": "self", "wid": "self",