Files
uzbekgpt/supergenerator.py
T

305 lines
12 KiB
Python
Raw Normal View History

2026-05-22 19:34:48 +03:00
import random
import re
import shelve
import time
import ai
import json
2026-05-22 19:34:48 +03:00
from configparser import DEFAULTSECT
2026-07-09 12:34:37 +03:00
from pprint import pprint
2026-05-23 18:09:50 +03:00
from statistics import *
2026-05-22 19:34:48 +03:00
from colors import *
from helpers import *
2026-05-22 19:34:48 +03:00
from config import *
from vars import *
2026-05-22 19:34:48 +03:00
from aiogram.exceptions import TelegramBadRequest, TelegramForbiddenError
2026-05-22 19:34:48 +03:00
async def generate(
prompt: str, bot=None, user_id=None, chat_id=None, message_id=None, images=None, msg=None, process=None, message=None, inline_id=None
2026-05-22 19:34:48 +03:00
) -> str:
if user_id:
if user_id not in user_contexts:
user_contexts[user_id] = []
config = get_user_config(user_id)
if "*" in config.get("model", ""):
model = config.get("model").split("*", 2)
else:
print(f"{RED} -- err model - failed to get prov&model in \"{config.get('model','')}\"{RESET}")
return "произошла ошибка при парсинге вашей выбранной модели. либо хост бота гандон либо тебе надо сменить модель в настройках!!"
2026-07-09 12:34:37 +03:00
settings = MODELS.get(model[0]).get(model[1])
2026-07-05 17:06:11 +03:00
2026-08-03 09:37:10 +03:00
stream_cf = config.get("stream", "none")
system_prompt_name = config.get("prompt", "")
user_prompts = config.get("prompts", {})
prompts = SYSTEM_PROMPTS | user_prompts
if system_prompt_name in prompts:
is_user_prompt = False
if system_prompt_name in SYSTEM_PROMPTS:
system_prompt = prompts[system_prompt_name]["text"] + ADD_TO_PROMPT
if config["markdown"] == "new":
system_prompt += NEW_MD
else:
system_prompt += OLD_MD
2026-07-14 08:23:17 +03:00
else:
2026-08-03 09:37:10 +03:00
is_user_prompt = True
system_prompt = prompts[system_prompt_name]["text"]
2026-07-05 17:06:11 +03:00
else:
text = "❌произошла ошибка, возможные проблемы:\n" \
f"1. у вас выбран удалённый сист промпт (`{system_prompt_name}`)\n" \
f"2. конфиг бота настроен неправильно и надо связаться с тем кто его хостит"
return text
2026-05-22 19:34:48 +03:00
if stream_cf == "native" and user_id == chat_id and settings.get("nostream", False) == False:
2026-05-22 19:34:48 +03:00
stream = True
elif stream_cf == "edit" and chat_id and message_id and settings.get("nostream", False) == False:
stream = True
elif stream_cf == "edit" or stream_cf == "native" and inline_id:
2026-05-22 19:34:48 +03:00
stream = True
else:
stream = False
2026-07-09 12:34:37 +03:00
content = []
if images:
if settings.get("vision"):
for image in images:
content += [{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image}"}}]
else:
for image in images:
try:
if process and msg and message:
process[image["process"]] = "make"
await msg.edit_text(make_graph(message, process))
image_text = await image2text(image["data"])
2026-07-09 12:34:37 +03:00
prompt = f"<фото>{image_text}</фото>\n{prompt}"
except Exception as e:
if process and msg and message:
process[image["process"]] = "error"
await msg.edit_text(make_graph(message, process))
2026-07-09 12:34:37 +03:00
print(f"{RED} -- err photo - {e} : {config.get('model', '')}{RESET}")
else:
if process and msg and message:
process[image["process"]] = "done"
await msg.edit_text(make_graph(message, process))
2026-07-09 12:34:37 +03:00
content += [{"type": "text", "text": prompt}]
user_contexts[user_id].append({"role": "user", "content": content})
2026-05-22 19:34:48 +03:00
user_contexts[user_id] = user_contexts[user_id][-MAX_CONTEXT:]
2026-07-05 17:06:11 +03:00
messages = [{"role": "system", "content": system_prompt}] + user_contexts[
2026-05-22 19:34:48 +03:00
user_id
]
else:
model = DEFAULT_MODEL.split("*", 2)
2026-07-09 12:34:37 +03:00
settings = MODELS.get(model[0]).get(model[1])
2026-05-22 19:34:48 +03:00
stream = False
stream_cf = "none"
2026-07-09 12:34:37 +03:00
content = []
if images:
if settings.get("vision"):
for image in images:
content += [{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image}"}}]
else:
for image in images:
try:
image_text = await image2text(image)
prompt = f"<фото>{image_text}</фото>\n{prompt}"
except Exception as e:
print(f"{RED} -- err photo - {e} : {model}{RESET}")
content += [{"type": "text", "text": prompt}]
2026-08-03 09:45:12 +03:00
messages = [{"role": "system", "content": SYSTEM_PROMPTS[DEFAULT_PROMPT]["text"]+ADD_TO_PROMPT+OLD_MD}] + [
2026-07-09 12:34:37 +03:00
{"role": "user", "content": content}
2026-05-22 19:34:48 +03:00
]
text = ""
2026-05-23 18:09:50 +03:00
add_one_to("stats/gens")
2026-07-05 14:52:57 +03:00
try:
provider = PROVIDERS[model[0]]
2026-07-05 14:52:57 +03:00
except Exception:
2026-07-05 17:06:11 +03:00
text = "❌произошла ошибка, возможные проблемы:\n" \
2026-07-05 14:52:57 +03:00
"1. у вас выбрана удалённая модель или провайдер\n" \
2026-07-05 17:06:11 +03:00
"2. конфиг бота настроен неправильно и надо связаться с тем кто его хостит"
2026-07-05 14:52:57 +03:00
return text
if process and msg and message:
process["text"] = "make"
await msg.edit_text(make_graph(message, process))
2026-05-22 19:34:48 +03:00
text = await openai_generate_text(
api=provider,
2026-05-22 19:34:48 +03:00
bot=bot,
model=model[1],
2026-07-09 12:34:37 +03:00
settings=settings,
2026-05-22 19:34:48 +03:00
messages=messages,
stream=stream,
stream_cf=stream_cf,
chat_id=chat_id,
draft_id=chat_id,
message_id=message_id,
inline_id=inline_id
2026-05-22 19:34:48 +03:00
)
if user_id:
2026-07-09 12:34:37 +03:00
user_contexts[user_id].append({"role": "assistant", "content": [{"type": "text", "text": text}]})
2026-05-22 19:34:48 +03:00
user_contexts[user_id] = user_contexts[user_id][-MAX_CONTEXT:]
return text
async def image2text(image) -> str:
if IMAGE_MODEL == "":
return ""
model = IMAGE_MODEL.split("*", 1)
api = PROVIDERS[model[0]]
2026-05-22 19:34:48 +03:00
text = ""
messages = [
{
"role": "user",
"content": [
{"type": "input_text", "text": IMAGE_PROMPT},
{"type": "input_image", "image_url": f"data:image/jpeg;base64,{image}"},
],
}
]
async for response in ai.responses(
url=api["url"], api_key=api["key"], model=model[1], input=messages, stream=False
):
pass
2026-05-22 19:34:48 +03:00
text = response.output_text
return text
async def openai_generate_text(
api,
2026-05-22 19:34:48 +03:00
bot,
model,
settings,
messages,
stream,
stream_cf,
chat_id=None,
draft_id=None,
message_id=None,
inline_id=None
2026-05-22 19:34:48 +03:00
) -> str:
try:
2026-07-16 13:00:25 +03:00
extra_body = {
"think": "false"
}
if settings.get("noexb"):
extra_body = None
alo = {
"url": api["url"],
"api_key": api["key"],
"model": model,
"messages": messages,
"stream": stream,
"max_tokens": MAX_TOKENS,
"extra": extra_body
}
2026-05-22 19:34:48 +03:00
if stream:
message = ""
t_counter = 0
2026-05-22 19:34:48 +03:00
counter = 0
counter_2 = 1
2026-05-22 19:34:48 +03:00
if not draft_id:
draft_id = chat_id
async for chunk in ai.completions(**alo):
# chunk = json.loads(chunk)
try:
content = chunk["choices"][0]["delta"]["content"]
except:
continue
2026-05-22 19:34:48 +03:00
if content:
message += content
counter += len(content)
t_counter += 1
if counter > MAX_SYMBOLS:
break
if int(counter / STREAMING_SPLIT_SYMBOLS) == counter_2:
counter_2 += 1
2026-05-22 19:34:48 +03:00
display_text, s = clean_tail_repeats(message)
if s > 0:
display_text += f"*... <{s} обрезано>*"
if display_text.count("```") % 2 != 0:
display_text += "\n```"
if counter < 3950:
display_text += "▋"
try:
if stream_cf == "native" and chat_id and draft_id:
await bot.send_message_draft(
chat_id=chat_id,
draft_id=draft_id,
text=display_text,
)
elif stream_cf == "edit" and chat_id and message_id:
await bot.edit_message_text(
chat_id=chat_id,
message_id=message_id,
text=display_text,
)
elif stream_cf == "edit" or stream_cf == "native" and inline_id:
await bot.edit_message_text(
inline_message_id=inline_id,
text=display_text,
)
except TelegramBadRequest as e:
if "can't parse entities" in str(e):
if stream_cf == "native" and chat_id and draft_id:
await bot.send_message_draft(
chat_id=chat_id,
draft_id=draft_id,
text=display_text,
parse_mode=None,
)
elif stream_cf == "edit" and chat_id and message_id:
await bot.edit_message_text(
chat_id=chat_id,
message_id=message_id,
text=display_text,
parse_mode=None,
)
elif stream_cf == "edit" or stream_cf == "native" and inline_id:
await bot.edit_message_text(
inline_message_id=inline_id,
text=display_text,
parse_mode=None,
)
else:
print(f"{YELLOW} -- {e}{RESET}")
except Exception as e:
print(f"{YELLOW} -- {e}{RESET}")
2026-05-22 19:34:48 +03:00
text = message
else:
async for completion in ai.completions(**alo):
pass
text = completion["choices"][0]["message"]["content"]
2026-05-22 19:34:48 +03:00
except Exception as e:
error = parse_response(str(e).lower())
2026-05-22 19:34:48 +03:00
print(f"{RED} -- {error['type']} - {e}{RESET}")
return error["message"]
else:
text, s = clean_tail_repeats(text)
if s > 0:
text += f"*... <{s} обрезано>*"
2026-07-09 12:34:37 +03:00
if text == "":
text = "(пустой ответ)"
2026-05-22 19:34:48 +03:00
return text