Compare commits

..

4 Commits

3 changed files with 120 additions and 38 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,42 @@
# 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
# In Sage system, params passed via urlwidget are available in request.form
form_data = {}
# Try to get data from request.form (standard for POST requests)
if hasattr(request, 'form'):
form_data = dict(request.form)
# Fallback: check if data is passed as keyword arguments
elif hasattr(locals(), 'service_id'):
form_data = {
'service_id': locals().get('service_id', ''),
'initial-prompt': locals().get('initial-prompt', '')
}
# Get required parameters
service_id = form_data.get('service_id')
initial_prompt = form_data.get('initial-prompt', '')
if not service_id:
# Redirect back to form with error
await redirect("/hermes-web-cli/new_session.ui?error=Service+ID+is+required")
# 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:
# Redirect to the new session's user interaction page
await redirect(f"/hermes-web-cli/sessions/{session_result}")
else:
# Redirect back to form with error
await redirect("/hermes-web-cli/new_session.ui?error=Failed+to+create+session")
except Exception as e:
# Log the error and redirect back with error message
print(f"Error creating session: {str(e)}")
await redirect(f"/hermes-web-cli/new_session.ui?error=Internal+error:+{str(e)}")

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",
@ -33,41 +43,20 @@
"height": "100px", "height": "100px",
"marginBottom": "24px" "marginBottom": "24px"
} }
], ]
"toolbar": {
"tools": [
{
"label": "Create Session",
"bgcolor": "#22C55E",
"color": "#FFFFFF",
"border": "none",
"borderRadius": "6px",
"padding": "10px 20px",
"fontWeight": "600",
"action": "create_session"
},
{
"label": "Cancel",
"bgcolor": "#64748B",
"color": "#FFFFFF",
"border": "none",
"borderRadius": "6px",
"padding": "10px 20px",
"action": "cancel"
}
]
}
}, },
"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",
} "params": "{{ 'new-session-form'.data }}"
},
"mode": "replace"
}, },
{ {
"wid": "self", "wid": "self",