Integrate OpenWebUI bot with AI service

This commit is contained in:
Iyeoluwa Akinrinola
2025-05-20 02:18:46 +01:00
parent 730009ae87
commit 0a27103875
46 changed files with 1749 additions and 3012 deletions
+22 -90
View File
@@ -11,7 +11,6 @@ from typing import List, Dict, Any, Optional
from ai_service.config import config
from ai_service.models.model_service import model_service
from ai_service.models.model_parameters import ModelParameters
from ai_service.openwebui_channels import openwebui_channels
class ChatService:
"""Service for chat functionality."""
@@ -65,34 +64,11 @@ class ChatService:
# Default title if none provided
chat_title = title or f"Chat {len(self.chats) + 1}"
# For team chats, create an OpenWebUI channel
openwebui_channel_id = None
# For team chats
if is_team_chat:
try:
print("=" * 50)
print(f"Creating team chat with title: {chat_title}")
print(f"OpenWebUI URL: {openwebui_channels.openwebui_url}")
print(f"OpenWebUI API Key: {openwebui_channels.openwebui_api_key[:5]}..." if openwebui_channels.openwebui_api_key else "No API key")
# Create a channel in OpenWebUI
channel_response = openwebui_channels.create_channel(
name=chat_title,
description=f"Team chat created by {user_id}",
is_private=True # Team chats are private by default
)
print(f"Channel response: {json.dumps(channel_response, indent=2) if channel_response else 'None'}")
if channel_response:
openwebui_channel_id = channel_response.get('id')
print(f"Created OpenWebUI channel with ID: {openwebui_channel_id}")
else:
print("Failed to create OpenWebUI channel, continuing with local team chat only")
print("=" * 50)
except Exception as e:
print("=" * 50)
print(f"Error creating OpenWebUI channel: {str(e)}")
print("=" * 50)
print("=" * 50)
print(f"Creating team chat with title: {chat_title}")
print("=" * 50)
# Create chat data
self.chats[chat_id] = {
@@ -104,8 +80,7 @@ class ChatService:
'created_at': datetime.now().isoformat(),
'updated_at': datetime.now().isoformat(),
'messages': [],
'team_members': [user_id] if is_team_chat else [],
'openwebui_channel_id': openwebui_channel_id
'team_members': [user_id] if is_team_chat else []
}
# Save chats to file
@@ -147,30 +122,18 @@ class ChatService:
# Update chat timestamp
chat['updated_at'] = datetime.now().isoformat()
# If this is a team chat with an OpenWebUI channel, send the message there too
if chat['is_team_chat'] and 'openwebui_channel_id' in chat and chat['openwebui_channel_id']:
try:
# For AI responses, use a special AI user ID
# This ensures the AI's messages are properly distinguished in OpenWebUI
sender_id = "ai-assistant" if not is_user_message else user_id
# If this is a team chat, log the message
if chat['is_team_chat']:
# For AI responses, use a special AI user ID
sender_id = "ai-assistant" if not is_user_message else user_id
# Format the message for OpenWebUI
if is_user_message:
# For user messages, use the regular format
formatted_content = content
else:
# For AI responses, add a special prefix to make it clear it's from the AI
# This helps visually distinguish AI responses in the channel
formatted_content = f"🤖 {content}"
# Format the message for logging
if is_user_message:
formatted_content = content
else:
formatted_content = f"🤖 {content}"
# Send message to OpenWebUI channel
openwebui_channels.send_message(
channel_id=chat['openwebui_channel_id'],
message=formatted_content,
user_id=sender_id
)
except Exception as e:
print(f"Error sending message to OpenWebUI channel: {str(e)}")
print(f"Team chat message in {chat_id} from {sender_id}: {formatted_content[:100]}...")
# Save chats to file
self._save_chats()
@@ -234,19 +197,8 @@ class ChatService:
if not chat['is_team_chat']:
return False
# Add to OpenWebUI channel if available
if 'openwebui_channel_id' in chat and chat['openwebui_channel_id']:
try:
# Add member to OpenWebUI channel
openwebui_success = openwebui_channels.add_member(
channel_id=chat['openwebui_channel_id'],
user_id=user_id
)
if not openwebui_success:
print(f"Warning: Failed to add user {user_id} to OpenWebUI channel {chat['openwebui_channel_id']}")
except Exception as e:
print(f"Error adding member to OpenWebUI channel: {str(e)}")
# Log the team member addition
print(f"Adding user {user_id} to team chat {chat_id}")
# Add to local team members list
if user_id not in chat['team_members']:
@@ -274,19 +226,8 @@ class ChatService:
if not chat['is_team_chat']:
return False
# Remove from OpenWebUI channel if available
if 'openwebui_channel_id' in chat and chat['openwebui_channel_id']:
try:
# Remove member from OpenWebUI channel
openwebui_success = openwebui_channels.remove_member(
channel_id=chat['openwebui_channel_id'],
user_id=user_id
)
if not openwebui_success:
print(f"Warning: Failed to remove user {user_id} from OpenWebUI channel {chat['openwebui_channel_id']}")
except Exception as e:
print(f"Error removing member from OpenWebUI channel: {str(e)}")
# Log the team member removal
print(f"Removing user {user_id} from team chat {chat_id}")
# Remove from local team members list
if user_id in chat['team_members']:
@@ -310,18 +251,9 @@ class ChatService:
chat = self.chats[chat_id]
# Delete OpenWebUI channel if this is a team chat
if chat['is_team_chat'] and 'openwebui_channel_id' in chat and chat['openwebui_channel_id']:
try:
# Delete the OpenWebUI channel
openwebui_success = openwebui_channels.delete_channel(
channel_id=chat['openwebui_channel_id']
)
if not openwebui_success:
print(f"Warning: Failed to delete OpenWebUI channel {chat['openwebui_channel_id']}")
except Exception as e:
print(f"Error deleting OpenWebUI channel: {str(e)}")
# Log the chat deletion
if chat['is_team_chat']:
print(f"Deleting team chat {chat_id}")
# Delete the chat from local storage
del self.chats[chat_id]