upgrading script to v2 with history

This commit is contained in:
2025-01-02 17:53:16 -08:00
parent 37b363b317
commit 9d6541ce75
2 changed files with 84 additions and 89 deletions

View File

@@ -2,6 +2,8 @@ import os
import discord
from discord.ext import commands
import openai
from openai import OpenAI
from collections import deque
from dotenv import load_dotenv
@@ -14,9 +16,15 @@ OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
OPENWEBUI_API_BASE = os.getenv('OPENWEBUI_API_BASE')
MODEL_NAME = os.getenv('MODEL_NAME')
# Configure OpenAI client to point to OpenWebUI
client = OpenAI(
api_key=os.getenv('OPENAI_API_KEY'),
base_url=os.getenv('OPENWEBUI_API_BASE') # e.g., "http://localhost:8080/v1"
)
# Configure OpenAI
openai.api_key = OPENAI_API_KEY
openai.api_base = OPENWEBUI_API_BASE
# TODO: The 'openai.api_base' option isn't read in the client API. You will need to pass it when you instantiate the client, e.g. 'OpenAI(base_url=OPENWEBUI_API_BASE)'
# openai.api_base = OPENWEBUI_API_BASE
# Initialize Discord bot
intents = discord.Intents.default()
@@ -35,14 +43,12 @@ async def get_chat_history(channel, limit=100):
async def get_ai_response(context, user_message):
formatted_prompt = f"##CONTEXT##\n{context}\n##ENDCONTEXT##\n\n{user_message}"
try:
response = openai.ChatCompletion.create(
model=MODEL_NAME,
messages=[
{"role": "user", "content": formatted_prompt}
]
)
response = client.chat.completions.create(model=MODEL_NAME,
messages=[
{"role": "user", "content": formatted_prompt}
])
return response.choices[0].message.content
except Exception as e:
return f"Error: {str(e)}"
@@ -58,11 +64,11 @@ async def on_message(message):
return
should_respond = False
# Check if bot was mentioned
if bot.user in message.mentions:
should_respond = True
# Check if message is a DM
if isinstance(message.channel, discord.DMChannel):
should_respond = True
@@ -71,13 +77,13 @@ async def on_message(message):
async with message.channel.typing():
# Get chat history
history = await get_chat_history(message.channel)
# Remove bot mention from the message
user_message = message.content.replace(f'<@{bot.user.id}>', '').strip()
# Get AI response
response = await get_ai_response(history, user_message)
# Send response
await message.reply(response)
@@ -87,7 +93,7 @@ def main():
if not all([DISCORD_TOKEN, OPENAI_API_KEY, OPENWEBUI_API_BASE, MODEL_NAME]):
print("Error: Missing required environment variables")
return
bot.run(DISCORD_TOKEN)
if __name__ == "__main__":