ollamarama-matrix-chatbot/bin/ollamarama.py

218 lines
8.1 KiB
Python
Raw Permalink Normal View History

2023-12-15 05:55:57 +00:00
"""
2024-11-27 19:24:10 +00:00
# Beschreibung: ollamarama-matrix: An AI chatbot for the Matrix chat protocol with infinite personalities.
# Autor: Dustin Whyte (https://github.com/h1ddenpr0cess20/ollamarama-matrix)
# Erstellt am: December 2023
# Modifiziert von: Patrick Asmus
# Web: https://www.techniverse.net
# Git-Reposit.: https://git.techniverse.net/scriptos/ollamarama-matrix.git
# Version: 2.0
# Datum: 27.11.2024
# Modifikation: Logging eingebaut
#####################################################
2023-12-15 05:55:57 +00:00
"""
from nio import AsyncClient, MatrixRoom, RoomMessageText
2024-03-15 03:01:14 +00:00
import json
import datetime
import asyncio
import requests
2024-08-14 23:44:20 +00:00
import markdown
2024-08-15 02:46:34 +00:00
2024-11-27 19:24:10 +00:00
2023-12-15 05:55:57 +00:00
class ollamarama:
2024-04-27 04:57:23 +00:00
def __init__(self):
2024-11-27 19:24:10 +00:00
# Load config file
2024-05-14 17:34:57 +00:00
self.config_file = "config.json"
with open(self.config_file, "r") as f:
2024-04-27 04:57:23 +00:00
config = json.load(f)
2024-08-07 04:15:49 +00:00
self.server, self.username, self.password, self.channels, self.admins = config["matrix"].values()
2024-08-03 03:23:56 +00:00
2024-04-27 04:57:23 +00:00
self.client = AsyncClient(self.server, self.username)
2024-11-27 19:24:10 +00:00
# Time program started and joined channels
2023-12-15 05:55:57 +00:00
self.join_time = datetime.datetime.now()
2024-11-27 19:24:10 +00:00
# Store chat history
2023-12-15 05:55:57 +00:00
self.messages = {}
2024-11-27 19:24:10 +00:00
# API URL
2024-08-22 05:57:41 +00:00
self.api_url = config["ollama"]["api_base"] + "/api/chat"
2024-11-27 19:24:10 +00:00
print(f"API URL: {self.api_url}")
2023-12-15 05:55:57 +00:00
2024-11-27 19:24:10 +00:00
# Model configuration
2024-08-07 04:15:49 +00:00
self.models = config["ollama"]["models"]
self.default_model = self.models[config["ollama"]["default_model"]]
2023-12-21 02:48:51 +00:00
self.model = self.default_model
2024-11-27 19:24:10 +00:00
print(f"Default model: {self.model}")
2023-12-21 02:48:51 +00:00
2024-11-27 19:24:10 +00:00
# Options
2024-08-07 04:15:49 +00:00
self.temperature, self.top_p, self.repeat_penalty = config["ollama"]["options"].values()
self.defaults = {
"temperature": self.temperature,
"top_p": self.top_p,
"repeat_penalty": self.repeat_penalty
}
2023-12-23 04:40:53 +00:00
2024-08-22 05:57:41 +00:00
self.default_personality = config["ollama"]["personality"]
self.personality = self.default_personality
self.prompt = config["ollama"]["prompt"]
2024-04-27 04:57:23 +00:00
2023-12-15 05:55:57 +00:00
async def display_name(self, user):
try:
name = await self.client.get_displayname(user)
return name.displayname
except Exception as e:
2024-11-27 19:24:10 +00:00
print(f"Error fetching display name: {e}")
2024-08-22 05:57:41 +00:00
return user
2023-12-15 05:55:57 +00:00
async def send_message(self, channel, message):
await self.client.room_send(
2023-12-15 05:55:57 +00:00
room_id=channel,
message_type="m.room.message",
2024-08-15 02:46:34 +00:00
content={
2024-11-27 19:24:10 +00:00
"msgtype": "m.text",
2024-08-14 23:44:20 +00:00
"body": message,
"format": "org.matrix.custom.html",
2024-11-27 19:24:10 +00:00
"formatted_body": markdown.markdown(message, extensions=["fenced_code", "nl2br"]),
},
2023-12-15 05:55:57 +00:00
)
async def add_history(self, role, channel, sender, message):
2024-08-22 05:57:41 +00:00
if channel not in self.messages:
self.messages[channel] = {}
if sender not in self.messages[channel]:
self.messages[channel][sender] = [
{"role": "system", "content": self.prompt[0] + self.personality + self.prompt[1]}
2024-11-27 19:24:10 +00:00
]
2024-08-22 05:57:41 +00:00
self.messages[channel][sender].append({"role": role, "content": message})
2024-11-27 19:24:10 +00:00
# Trim history
2024-08-22 05:57:41 +00:00
if len(self.messages[channel][sender]) > 24:
if self.messages[channel][sender][0]["role"] == "system":
del self.messages[channel][sender][1:3]
2023-12-15 05:55:57 +00:00
else:
2024-08-22 05:57:41 +00:00
del self.messages[channel][sender][0:2]
2023-12-15 05:55:57 +00:00
async def respond(self, channel, sender, message, sender2=None):
try:
data = {
2024-11-27 19:24:10 +00:00
"model": self.model,
"messages": message,
"stream": False,
"options": {
"top_p": self.top_p,
"temperature": self.temperature,
2024-11-27 19:24:10 +00:00
"repeat_penalty": self.repeat_penalty,
},
}
# Log the data being sent
print(f"Sending data to API: {json.dumps(data, indent=2)}")
response = requests.post(self.api_url, json=data, timeout=300)
response.raise_for_status()
data = response.json()
2024-11-27 19:24:10 +00:00
# Log the API response
print(f"API response: {json.dumps(data, indent=2)}")
2023-12-15 05:55:57 +00:00
except Exception as e:
2024-11-27 19:24:10 +00:00
error_message = f"Error communicating with Ollama API: {e}"
await self.send_message(channel, error_message)
print(error_message)
2023-12-15 05:55:57 +00:00
else:
2024-08-07 04:15:49 +00:00
response_text = data["message"]["content"]
2023-12-15 05:55:57 +00:00
await self.add_history("assistant", channel, sender, response_text)
2024-08-22 05:57:41 +00:00
2024-11-27 19:24:10 +00:00
display_name = await self.display_name(sender2 if sender2 else sender)
2024-08-22 05:57:41 +00:00
response_text = f"**{display_name}**:\n{response_text.strip()}"
2024-11-27 19:24:10 +00:00
2023-12-15 05:55:57 +00:00
try:
await self.send_message(channel, response_text)
2024-11-27 19:24:10 +00:00
except Exception as e:
print(f"Error sending message: {e}")
2024-08-22 05:57:41 +00:00
async def set_prompt(self, channel, sender, persona=None, custom=None, respond=True):
2023-12-15 05:55:57 +00:00
try:
2024-08-23 18:55:12 +00:00
self.messages[channel][sender].clear()
2024-11-27 19:24:10 +00:00
except KeyError:
2023-12-15 05:55:57 +00:00
pass
2024-11-27 19:24:10 +00:00
if persona:
2024-08-22 05:57:41 +00:00
prompt = self.prompt[0] + persona + self.prompt[1]
2024-11-27 19:24:10 +00:00
elif custom:
2024-08-22 05:57:41 +00:00
prompt = custom
2024-11-27 19:24:10 +00:00
2024-08-22 05:57:41 +00:00
await self.add_history("system", channel, sender, prompt)
2024-11-27 19:24:10 +00:00
2024-08-22 05:57:41 +00:00
if respond:
await self.add_history("user", channel, sender, "introduce yourself")
await self.respond(channel, sender, self.messages[channel][sender])
2024-08-07 04:15:49 +00:00
2024-08-22 05:57:41 +00:00
async def ai(self, channel, message, sender, x=False):
2023-12-15 05:55:57 +00:00
try:
2024-11-27 19:24:10 +00:00
if x and len(message) > 2:
2024-08-26 01:27:22 +00:00
name = message[1]
message = message[2:]
if channel in self.messages:
for user in self.messages[channel]:
try:
username = await self.display_name(user)
if name == username:
name_id = user
2024-11-27 19:24:10 +00:00
except Exception as e:
print(f"Error in .x command: {e}")
2024-08-26 01:27:22 +00:00
name_id = name
2024-11-27 19:24:10 +00:00
await self.add_history("user", channel, name_id, " ".join(message))
2024-08-26 01:27:22 +00:00
await self.respond(channel, name_id, self.messages[channel][name_id], sender)
2024-08-22 05:57:41 +00:00
else:
2024-11-27 19:24:10 +00:00
await self.add_history("user", channel, sender, " ".join(message[1:]))
2024-08-22 05:57:41 +00:00
await self.respond(channel, sender, self.messages[channel][sender])
2024-11-27 19:24:10 +00:00
except Exception as e:
print(f"Error in .ai command: {e}")
2024-08-22 05:57:41 +00:00
async def handle_message(self, message, sender, sender_display, channel):
user_commands = {
".ai": lambda: self.ai(channel, message, sender),
2024-11-27 19:24:10 +00:00
".reset": lambda: self.set_prompt(channel, sender, persona=self.personality, respond=False),
2024-08-22 05:57:41 +00:00
}
command = message[0]
if command in user_commands:
action = user_commands[command]
2024-09-17 15:40:00 +00:00
await action()
2024-11-27 19:24:10 +00:00
2023-12-15 05:55:57 +00:00
async def message_callback(self, room: MatrixRoom, event: RoomMessageText):
if isinstance(event, RoomMessageText):
2024-11-27 19:24:10 +00:00
message_time = datetime.datetime.fromtimestamp(event.server_timestamp / 1000)
message = event.body.split(" ")
2023-12-15 05:55:57 +00:00
sender = event.sender
sender_display = await self.display_name(sender)
2024-08-22 05:57:41 +00:00
channel = room.room_id
2024-11-27 19:24:10 +00:00
2023-12-15 05:55:57 +00:00
if message_time > self.join_time and sender != self.username:
2024-08-23 18:55:12 +00:00
try:
await self.handle_message(message, sender, sender_display, channel)
2024-11-27 19:24:10 +00:00
except Exception as e:
print(f"Error handling message: {e}")
2023-12-15 05:55:57 +00:00
async def main(self):
print(await self.client.login(self.password))
self.bot_id = await self.display_name(self.username)
2024-11-27 19:24:10 +00:00
2023-12-15 05:55:57 +00:00
for channel in self.channels:
try:
await self.client.join(channel)
print(f"{self.bot_id} joined {channel}")
2024-11-27 19:24:10 +00:00
except Exception as e:
print(f"Couldn't join {channel}: {e}")
2023-12-15 05:55:57 +00:00
self.client.add_event_callback(self.message_callback, RoomMessageText)
2024-11-27 19:24:10 +00:00
await self.client.sync_forever(timeout=30000, full_state=True)
2023-12-15 05:55:57 +00:00
if __name__ == "__main__":
2024-08-22 05:57:41 +00:00
ollamarama = ollamarama()
2024-11-27 20:38:00 +00:00
asyncio.run(ollamarama.main())