chat/plugin.py

145 lines
5.6 KiB
Python

###
# Copyright (c) 2023, John Burwell
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
import configparser
import json
import os
import requests
from supybot import utils, plugins, ircutils, callbacks, conf
from supybot.commands import *
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('Chat')
except ImportError:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
_ = lambda x: x
class Chat(callbacks.Plugin):
"""Sends message to ChatGPT and replies with the response
"""
def __init__(self, irc):
self.__parent = super(Chat, self)
self.__parent.__init__(irc)
# Load the API key from the configuration file
config_path = os.path.join(os.path.dirname(__file__), 'config.ini')
self.config = configparser.ConfigParser()
self.config.read(config_path)
self.api_key = self.config.get('Chat', 'api_key')
def conversation_history(self):
history = irclib.IrcState.history[-30:]
filtered_messages = [(msg.args[0], msg.args[1]) for msg in history if msg.command == 'PRIVMSG']
return [{"role": "user", "content": f"{nick}: {msg}"} for nick, msg in history]
def filter_prefix(self, msg, prefix):
if msg.startswith(prefix):
return msg[len(prefix):]
else:
return msg
def chat(self, irc, msg, args, string):
"""
Sends your comment to ChatGPT and returns the response.
Args:
string (str): The string to send to ChatGPT.
Returns:
str: ChatGPT's response
"""
invocation_string = f"{conf.supybot.reply.whenAddressedBy.chars()}{self.name().lower()} "
# self.log.info(f"invocation_string: {invocation_string}")
model = self.registryValue("model")
max_tokens = self.registryValue("max_tokens")
# If the configured system prompt contains BOTNAME and IRCCHANNEL tokens, replace those with real values
system_prompt = self.registryValue("system_prompt").replace("$bot_name", irc.nick).replace("$channel_name", msg.args[0])
# Get the last few lines of the chat scrollback to include in the prompt
history = irc.state.history[-self.registryValue("scrollback_lines"):]
for message in history:
self.log.info(f"{message.nick}: {json.dumps(message.args)}")
# Restrict the scrollback to PRIVMSGs in the current channel, filtering out the invocation prefix
filtered_messages = [
(message.nick, (self.filter_prefix(message.args[1], f"{invocation_string}")))
for message in history
if message.command == 'PRIVMSG' and message.args[0] == msg.args[0]
]
# Format the conversation history for submission to the API
conversation_history = [
{
"role": "assistant" if nick == irc.nick else "user",
"content": f"{nick}: {msg}"
}
for nick, msg in filtered_messages
]
# Combine the system prompt, and the scrollback (which already includes the invocation)
messages = [{"role": "system", "content": system_prompt}] + conversation_history
self.log.info(json.dumps(messages))
# Submit the request to the API
# res = requests.post(f"http://localhost:8000/capture", headers = {
res = requests.post(f"https://api.openai.com/v1/chat/completions", headers = {
"Content-Type":"application/json",
"Authorization":f"Bearer {self.registryValue('api_key')}"
},
json={
"model": model,
"messages": messages,
"max_tokens": max_tokens,
}).json()
# Pick a response
response = res['choices'][0]['message']['content'].strip()
# Combine multiple lines
line = response.replace("\n", self.registryValue("join_string"))
# Post the reply to the channel
irc.reply( line )
# for line in conversation_history:
# irc.reply( line )
chat = wrap(chat, ['text'])
Class = Chat