azils3/bash
0
1# Ultroid - UserBot2# Copyright (C) 2021-2025 TeamUltroid3#4# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >5# PLease read the GNU Affero General Public License in6# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.7 8"""9✘ Commands Available -10 11• `{i}gemini <prompt>`12 Get response from Google Gemini.13 14• `{i}antr <prompt>`15 Get response from Anthropic Claude.16 17• `{i}gpt <prompt>`18 Get response from OpenAI GPT.19 20• `{i}deepseek <prompt>`21 Get response from DeepSeek AI.22 23Set custom models using:24 • OPENAI_MODEL25 • ANTHROPIC_MODEL26 • GEMINI_MODEL27 • DEEPSEEK_MODEL28"""29 30import json31from . import LOGS, eor, get_string, udB, ultroid_cmd, async_searcher32import aiohttp33import asyncio34 35 36ENDPOINTS = {37 "gpt": "https://api.openai.com/v1/chat/completions",38 "antr": "https://api.anthropic.com/v1/messages",39 "gemini": "https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent",40 "deepseek": "https://api.deepseek.com/chat/completions"41}42 43DEFAULT_MODELS = {44 "gpt": "gpt-3.5-turbo",45 "antr": "claude-3-opus-20240229",46 "gemini": "gemini-pro",47 "deepseek": "deepseek-chat"48}49 50 51def get_model(provider):52 """Get model name from database or use default"""53 model_keys = {54 "gpt": "OPENAI_MODEL",55 "antr": "ANTHROPIC_MODEL",56 "gemini": "GEMINI_MODEL",57 "deepseek": "DEEPSEEK_MODEL"58 }59 return udB.get_key(model_keys[provider]) or DEFAULT_MODELS[provider]60 61 62async def stream_response(msg, text):63 """Stream response by editing message"""64 current = ""65 # Split into chunks of ~100 characters at word boundaries66 words = text.split()67 chunks = []68 current_chunk = []69 70 for word in words:71 current_chunk.append(word)72 if len(" ".join(current_chunk)) > 100:73 chunks.append(" ".join(current_chunk[:-1]))74 current_chunk = [word]75 if current_chunk:76 chunks.append(" ".join(current_chunk))77 78 for chunk in chunks:79 current += chunk + " "80 try:81 await msg.edit(current)82 except Exception:83 pass84 await asyncio.sleep(0.5)85 return current86 87 88async def get_ai_response(provider, prompt, api_key, stream=False):89 """Get response from AI provider"""90 try:91 headers = {"Content-Type": "application/json"}92 model = get_model(provider)93 94 if provider == "gpt":95 headers["Authorization"] = f"Bearer {api_key}"96 data = {97 "model": model,98 "messages": [{"role": "user", "content": prompt}],99 "stream": stream100 }101 if not stream:102 response = await async_searcher(103 ENDPOINTS[provider],104 headers=headers,105 post=True,106 json=data,107 re_json=True108 )109 yield response["choices"][0]["message"]["content"]110 return111 112 async with aiohttp.ClientSession() as session:113 async with session.post(114 ENDPOINTS[provider],115 headers=headers,116 json=data117 ) as resp:118 async for line in resp.content:119 if line:120 try:121 json_line = json.loads(line.decode('utf-8').strip().strip('data:').strip())122 if 'choices' in json_line and json_line['choices']:123 content = json_line['choices'][0].get('delta', {}).get('content', '')124 if content:125 yield content126 except Exception:127 continue128 129 elif provider == "antr":130 headers["x-api-key"] = api_key131 headers["anthropic-version"] = "2023-06-01"132 data = {133 "model": model,134 "messages": [{"role": "user", "content": prompt}],135 "stream": stream136 }137 if not stream:138 response = await async_searcher(139 ENDPOINTS[provider],140 headers=headers,141 post=True,142 json=data,143 re_json=True144 )145 yield response["content"][0]["text"]146 return147 148 async with aiohttp.ClientSession() as session:149 async with session.post(150 ENDPOINTS[provider],151 headers=headers,152 json=data153 ) as resp:154 async for line in resp.content:155 if line:156 try:157 json_line = json.loads(line.decode('utf-8').strip())158 if 'content' in json_line:159 content = json_line['content'][0]['text']160 if content:161 yield content162 except Exception:163 continue164 165 elif provider == "gemini":166 params = {"key": api_key}167 data = {168 "contents": [{169 "parts": [{"text": prompt}]170 }]171 }172 response = await async_searcher(173 ENDPOINTS[provider],174 params=params,175 headers=headers,176 post=True,177 json=data,178 re_json=True179 )180 text = response["candidates"][0]["content"]["parts"][0]["text"]181 if not stream:182 yield text183 return184 185 # Simulate streaming by yielding chunks186 words = text.split()187 buffer = []188 for word in words:189 buffer.append(word)190 if len(' '.join(buffer)) > 20: # Adjust chunk size as needed191 yield ' '.join(buffer) + ' '192 buffer = []193 if buffer:194 yield ' '.join(buffer)195 196 elif provider == "deepseek":197 headers["Authorization"] = f"Bearer {api_key}"198 data = {199 "model": model,200 "messages": [{"role": "user", "content": prompt}],201 "stream": stream202 }203 if not stream:204 response = await async_searcher(205 ENDPOINTS[provider],206 headers=headers,207 post=True,208 json=data,209 re_json=True210 )211 yield response["choices"][0]["message"]["content"]212 return213 214 async with aiohttp.ClientSession() as session:215 async with session.post(216 ENDPOINTS[provider],217 headers=headers,218 json=data219 ) as resp:220 async for line in resp.content:221 if line:222 try:223 json_line = json.loads(line.decode('utf-8').strip())224 if 'choices' in json_line and json_line['choices']:225 content = json_line['choices'][0].get('delta', {}).get('content', '')226 if content:227 yield content228 except Exception:229 continue230 231 except Exception as e:232 LOGS.exception(e)233 yield f"Error: {str(e)}"234 235 236@ultroid_cmd(pattern="gemini( (.*)|$)")237async def gemini_ai(event):238 """Use Google Gemini"""239 prompt = event.pattern_match.group(1).strip()240 if not prompt:241 return await event.eor("❌ Please provide a prompt!")242 243 api_key = udB.get_key("GEMINI_API_KEY")244 if not api_key:245 return await event.eor("⚠️ Please set Gemini API key using `setdb GEMINI_API_KEY your_api_key`")246 247 msg = await event.eor("🤔 Thinking...")248 model = get_model("gemini")249 250 header = (251 "🤖 **Google Gemini**\n"252 f"**Model:** `{model}`\n"253 "➖➖➖➖➖➖➖➖➖➖\n\n"254 f"**🔍 Prompt:**\n{prompt}\n\n"255 "**💡 Response:**\n"256 )257 258 if event.client.me.bot:259 await msg.edit(header)260 response = ""261 async for chunk in get_ai_response("gemini", prompt, api_key, stream=True):262 response += chunk263 try:264 await msg.edit(header + response)265 except Exception:266 pass267 else:268 response = ""269 async for chunk in get_ai_response("gemini", prompt, api_key, stream=True):270 response += chunk271 try:272 await msg.edit(header + response)273 except Exception:274 pass275 276@ultroid_cmd(pattern="antr( (.*)|$)")277async def anthropic_ai(event):278 """Use Anthropic Claude"""279 prompt = event.pattern_match.group(1).strip()280 if not prompt:281 return await event.eor("❌ Please provide a prompt!")282 283 api_key = udB.get_key("ANTHROPIC_KEY")284 if not api_key:285 return await event.eor("⚠️ Please set Anthropic API key using `setdb ANTHROPIC_KEY your_api_key`")286 287 msg = await event.eor("🤔 Thinking...")288 model = get_model("antr")289 290 formatted_response = (291 "🧠 **Anthropic Claude**\n"292 f"**Model:** `{model}`\n"293 "➖➖➖➖➖➖➖➖➖➖\n\n"294 f"**🔍 Prompt:**\n{prompt}\n\n"295 f"**💡 Response:**\n"296 )297 298 if event.client.me.bot:299 await msg.edit(formatted_response)300 response = ""301 async for chunk in get_ai_response("antr", prompt, api_key, stream=True):302 response += chunk303 try:304 await msg.edit(formatted_response + response)305 except Exception:306 pass307 else:308 response = ""309 async for chunk in get_ai_response("antr", prompt, api_key, stream=True):310 response += chunk311 try:312 await msg.edit(formatted_response + response)313 except Exception:314 pass315 316@ultroid_cmd(pattern="gpt( (.*)|$)")317async def openai_ai(event):318 """Use OpenAI GPT"""319 prompt = event.pattern_match.group(1).strip()320 if not prompt:321 return await event.eor("❌ Please provide a prompt!")322 323 api_key = udB.get_key("OPENAI_API_KEY")324 if not api_key:325 return await event.eor("⚠️ Please set GPT API key using `setdb OPENAI_API_KEY your_api_key`")326 327 msg = await event.eor("🤔 Thinking...")328 model = get_model("gpt")329 330 header = (331 "🌟 **OpenAI GPT**\n"332 f"**Model:** `{model}`\n"333 "➖➖➖➖➖➖➖➖➖➖\n\n"334 f"**🔍 Prompt:**\n{prompt}\n\n"335 "**💡 Response:**\n"336 )337 338 if event.client.me.bot:339 await msg.edit(header)340 response = ""341 async for chunk in get_ai_response("gpt", prompt, api_key, stream=True):342 response += chunk343 try:344 await msg.edit(header + response)345 except Exception:346 pass347 else:348 response =""349 async for chunk in get_ai_response("gpt", prompt, api_key, stream=True):350 response += chunk351 try:352 await msg.edit(header + response)353 except Exception:354 pass355 356@ultroid_cmd(pattern="deepseek( (.*)|$)")357async def deepseek_ai(event):358 """Use DeepSeek AI"""359 prompt = event.pattern_match.group(1).strip()360 if not prompt:361 return await event.eor("❌ Please provide a prompt!")362 363 api_key = udB.get_key("DEEPSEEK_API_KEY")364 if not api_key:365 return await event.eor("⚠️ Please set DeepSeek API key using `setdb DEEPSEEK_API_KEY your_api_key`")366 367 msg = await event.eor("🤔 Thinking...")368 model = get_model("deepseek")369 370 formatted_response = (371 "🤖 **DeepSeek AI**\n"372 f"**Model:** `{model}`\n"373 "➖➖➖➖➖➖➖➖➖➖\n\n"374 f"**🔍 Prompt:**\n{prompt}\n\n"375 f"**💡 Response:**\n"376 )377 378 if event.client.me.bot:379 await msg.edit(formatted_response)380 response = ""381 async for chunk in get_ai_response("deepseek", prompt, api_key, stream=True):382 response += chunk383 try:384 await msg.edit(formatted_response + response)385 except Exception:386 pass387 else:388 response = ""389 async for chunk in get_ai_response("deepseek", prompt, api_key, stream=True):390 response += chunk391 392 try:393 await msg.edit(formatted_response + response)394 except Exception:395 pass396 397 