From e498df0647caa0360513da80fded4f5e5ea8cf2e Mon Sep 17 00:00:00 2001 From: salmonik Date: Thu, 21 May 2026 16:38:01 +0200 Subject: make the assistant simpler Signed-off-by: salmonik --- cogs/assistant.py | 111 +++++++++++------------------------------------------- 1 file changed, 21 insertions(+), 90 deletions(-) diff --git a/cogs/assistant.py b/cogs/assistant.py index 9926361..fed7825 100644 --- a/cogs/assistant.py +++ b/cogs/assistant.py @@ -3,16 +3,11 @@ # Copyright (C) 2026 Salmonik @ salmonik@tuta.io # https://codeberg.org/salmonik/senator-sperma -import re import discord from discord.ext import commands import httpx -import json import logging -import shutil import os -from tempfile import NamedTemporaryFile -from cogs.downloader import Downloader logger = logging.getLogger(__name__) @@ -46,15 +41,16 @@ class Jarvis(commands.Cog): messages = Jarvis._build_messages(message, chain) payload = Jarvis._build_payload(messages) - response_data = await Jarvis._make_api_request(payload, headers) - response_message, action = Jarvis._parse_response(response_data) + response_data = await Jarvis._safe_api_call(payload, headers) + if response_data is None: + await message.reply("Przepraszam, nie mogę teraz odpowiedzieć. Spróbuj ponownie później.") + return + + response_message = Jarvis._parse_response(response_data) channel = message.channel await message.reply(response_message) - if action == "download": - await Jarvis._handle_download_action(message, channel) - @staticmethod async def _build_message_chain(message): chain = [] @@ -80,10 +76,10 @@ class Jarvis(commands.Cog): messages = [{ "role": "system", "content": "Jesteś Senator Sperma Armostrong, także znany jako Jarvis." - "Twoim zadaniem, po za asystowaniem użytkownika, jest mówienie programowi nadrzędnemu jak sie zachować" - "pole 'message' może być tylko wypełnione w języku Polskim." + "Twoim zadaniem jest asystowanie użytkownika" "zachowuj sie jak Jarvis, bądź osobistym asystentem użytkownika, nie używaj emotikon" - "nie pytaj sie użytkownika czy chcesz abyś coś zrobił, użytkownik ci sam powie abyś coś wykonał" + "nie pytaj sie użytkownika czy chce abyś coś zrobił, użytkownik ci sam powie abyś coś wykonał" + "Nie pozostawiaj wiadomości pustej oraz nie dawaj swojej wiadomości w pole myślenia" }] if chain is None: @@ -92,7 +88,7 @@ class Jarvis(commands.Cog): for msg in chain: messages.append({ "role": "user", - "content": f"{msg.author.display_name}: {msg.content}" + "content": f"USER: {msg.author.display_name}\nMESSAGE: {msg.content}" }) return messages @@ -102,38 +98,12 @@ class Jarvis(commands.Cog): return { "model": os.getenv("OPENROUTER_MODEL"), "messages": messages, - "response_format": Jarvis._get_response_schema(), "plugins": [{"id": "response-healing"}] } - @staticmethod - def _get_response_schema(): - return { - "type": "json_schema", - "json_schema": { - "name": "response", - "strict": True, - "schema": { - "type": "object", - "properties": { - "message": { - "type": "string", - "description": "the message that user will receive", - }, - "action": { - "type": "string", - "description": "the action to do, either download, compress or none" - } - }, - "required": ["message", "action"], - "additionalProperties": False, - } - } - } - @staticmethod async def _make_api_request(payload, headers): - async with httpx.AsyncClient() as client: + async with httpx.AsyncClient(timeout=30.0) as client: url = "https://openrouter.ai/api/v1/chat/completions" response = await client.post(url=url, headers=headers, json=payload) response_data = response.json() @@ -141,59 +111,20 @@ class Jarvis(commands.Cog): return response_data @staticmethod - def _parse_response(response_data): - content = response_data['choices'][0]['message']['content'] - inner_json_str = content.strip('```json\n').strip('```').strip() - inner_data = json.loads(inner_json_str) - - response_message = inner_data['message'] - action = inner_data['action'] - - logger.info(response_message) - logger.info(action) - - return response_message, action - - @staticmethod - async def _handle_download_action(message, channel): - url_match = Jarvis._extract_url(message.content) - if not url_match: - await channel.send("Nie znaleziono poprawnego linku w odpowiedzi.") - return - - response = await Downloader.download_standalone(url=url_match) - await Jarvis._process_download_response(response, channel) - - @staticmethod - def _extract_url(content): - match = re.search(r'https://(?:[A-Za-z0-9-]+\.)*[A-Za-z0-9-]{1,63}\.[A-Za-z]{2,63}/\S*', content) - return match.group(0) if match else None + async def _safe_api_call(payload, headers): + try: + return await Jarvis._make_api_request(payload, headers) + except httpx.HTTPError as e: + logger.error(f"API request failed: {e}") + return None @staticmethod - async def _process_download_response(response, channel): - if not isinstance(response, dict): - return - - if response["status"] == "success": - await Jarvis._handle_successful_download(response, channel) - else: - await Jarvis._handle_failed_download(response) + def _parse_response(response_data): + content = response_data['choices'][0]['message']['content'] - @staticmethod - async def _handle_successful_download(response, channel): - if response["type"] == "url": - await channel.send(f"pobioron i wysyłon: {response['content']}") - elif response["type"] == "file": - file_data = response["content"] - await channel.send("wysyłon:", file=discord.File(file_data)) - shutil.rmtree(response["temp_dir"]) + logger.info(content) - @staticmethod - async def _handle_failed_download(response): - logger.error(f"Error: {response['content']}") - if 'details' in response: - logger.error(f"Details: {response['details']}") - shutil.rmtree(response["temp_dir"]) + return content def setup(bot): bot.add_cog(Jarvis(bot)) -- cgit v1.2.3