id
int64 0
190k
| prompt
stringlengths 21
13.4M
| docstring
stringlengths 1
12k
⌀ |
---|---|---|
902 | from dataclasses import dataclass, field
import string
import random
from typing import List, Callable
SupportTickets = List[SupportTicket]
def fifo_ordering(list: SupportTickets) -> SupportTickets:
return list.copy() | null |
903 | from dataclasses import dataclass, field
import string
import random
from typing import List, Callable
SupportTickets = List[SupportTicket]
def filo_ordering(list: SupportTickets) -> SupportTickets:
list_copy = list.copy()
list_copy.reverse()
return list_copy | null |
904 | from dataclasses import dataclass, field
import string
import random
from typing import List, Callable
SupportTickets = List[SupportTicket]
def random_ordering(list: SupportTickets) -> SupportTickets:
list_copy = list.copy()
random.shuffle(list_copy)
return list_copy | null |
905 | from dataclasses import dataclass, field
import string
import random
from typing import List, Callable
SupportTickets = List[SupportTicket]
def blackhole_ordering(_: SupportTickets) -> SupportTickets:
return [] | null |
906 | import string
import random
from typing import List
from abc import ABC, abstractmethod
def generate_id(length=8):
# helper function for generating an id
return ''.join(random.choices(string.ascii_uppercase, k=length)) | null |
907 | import string
import random
from typing import List
def generate_id(length=8):
# helper function for generating an id
return ''.join(random.choices(string.ascii_uppercase, k=length)) | null |
908 | import tkinter as tk
import uuid
import string
import random
from abc import ABC, abstractmethod
def generate_uuid1():
return uuid.uuid1() | null |
909 | import tkinter as tk
import uuid
import string
import random
from abc import ABC, abstractmethod
def generate_uuid4():
return uuid.uuid4() | null |
910 | import tkinter as tk
import uuid
import string
import random
from abc import ABC, abstractmethod
def generate_simple_id():
return ''.join(random.choices(string.ascii_lowercase, k=30)) | null |
911 | from flask import Flask, jsonify, abort
def hello_world():
return 'Hello, World!' | null |
913 | import sqlite3
def blog_lst_to_json(item):
return {
'id': item[0],
'published': item[1],
'title': item[2],
'content': item[3],
'public': bool(item[4])
} | null |
914 | from flask import Flask, jsonify, abort
from db import fetch_blogs, fetch_blog, NotFoundError, NotAuthorizedError
def hello_world():
return 'Hello, World!' | null |
915 | from flask import Flask, jsonify, abort
from db import fetch_blogs, fetch_blog, NotFoundError, NotAuthorizedError
def fetch_blogs():
pass
def all_blogs():
return jsonify(fetch_blogs()) | null |
916 | from flask import Flask, jsonify, abort
from db import fetch_blogs, fetch_blog, NotFoundError, NotAuthorizedError
def fetch_blog(id: str):
class NotFoundError(Exception):
class NotAuthorizedError(Exception):
def get_blog(id):
try:
return jsonify(fetch_blog(id))
except NotFoundError:
abort(404, description="Resource not found")
except NotAuthorizedError:
abort(403, description="Access denied") | null |
918 | from flask import Flask, jsonify, abort
from db import fetch_blogs, fetch_blog, NotFoundError, NotAuthorizedError
def fetch_blogs():
def all_blogs():
return jsonify(fetch_blogs()) | null |
920 | import logging
from functools import wraps
logger = create_logger()
def create_logger():
# create a logger object
logger = logging.getLogger('exc_logger')
logger.setLevel(logging.INFO)
# create a file to store all the
# logged exceptions
logfile = logging.FileHandler('exc_logger.log')
fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
formatter = logging.Formatter(fmt)
logfile.setFormatter(formatter)
logger.addHandler(logfile)
return logger | null |
921 | import logging
from functools import wraps
if __name__ == '__main__':
divideByZero()
def exception(logger):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
issue = "exception in "+func.__name__+"\n"
issue = issue+"=============\n"
logger.exception(issue)
raise
return wrapper
return decorator | null |
922 | import logging
from functools import wraps
def divideByZero():
return 12/0 | null |
923 | import time
import math
from functools import wraps
The provided code snippet includes necessary dependencies for implementing the `retry` function. Write a Python function `def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None)` to solve the following problem:
Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ExceptionToCheck: the exception to check. may be a tuple of exceptions to check :type ExceptionToCheck: Exception or tuple :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int :param logger: logger to use. If None, print :type logger: logging.Logger instance
Here is the function:
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param ExceptionToCheck: the exception to check. may be a tuple of
exceptions to check
:type ExceptionToCheck: Exception or tuple
:param tries: number of times to try (not retry) before giving up
:type tries: int
:param delay: initial delay between retries in seconds
:type delay: int
:param backoff: backoff multiplier e.g. value of 2 will double the delay
each retry
:type backoff: int
:param logger: logger to use. If None, print
:type logger: logging.Logger instance
"""
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck as e:
msg = "%s, Retrying in %d seconds..." % (str(e), mdelay)
if logger:
logger.warning(msg)
else:
print(msg)
time.sleep(mdelay)
mtries -= 1
mdelay *= backoff
return f(*args, **kwargs)
return f_retry # true decorator
return deco_retry | Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ExceptionToCheck: the exception to check. may be a tuple of exceptions to check :type ExceptionToCheck: Exception or tuple :param tries: number of times to try (not retry) before giving up :type tries: int :param delay: initial delay between retries in seconds :type delay: int :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :type backoff: int :param logger: logger to use. If None, print :type logger: logging.Logger instance |
924 | import time
import math
from functools import wraps
def test_fail(text):
raise Exception("Fail") | null |
925 | import sqlite3
from returns.result import Result, safe
from returns.pipeline import flow
from returns.pointfree import bind
def fetch_blog_from_db(blog_id):
"""Fetches blog from SQLite3 database."""
with SQLite('application.db') as cur:
cur.execute(f"SELECT * FROM blogs where id=?", [blog_id])
result = cur.fetchone()
if result is None:
raise NotFoundError(f'Unable to find blog with id {blog_id}.')
return result
def blog_to_dict(item) -> 'Blog':
"""Convert SQLite result to dictionary."""
return {
'id': item[0],
'published': item[1],
'title': item[2],
'content': item[3],
'public': bool(item[4])
}
def verify_access(blog) -> 'Blog':
"""Check that blog is accessible."""
blog_id = blog['id']
blog_public = blog['public']
if not blog_public:
raise NotAuthorizedError(f'You are not allowed to access blog with id {blog_id}.')
return blog
def fetch_blog(blog_id) -> Result['Blog', Exception]:
return flow(
blog_id,
fetch_blog_from_db,
bind(blog_to_dict),
bind(verify_access)
) | null |
928 | from flask import Flask, jsonify, abort
from db import fetch_blogs, fetch_blog, NotFoundError, NotAuthorizedError
def fetch_blog(id: str):
pass
class NotFoundError(Exception):
pass
class NotAuthorizedError(Exception):
pass
def get_blog(id):
try:
return jsonify(fetch_blog(id))
except NotFoundError:
abort(404, description="Resource not found")
except NotAuthorizedError:
abort(403, description="Access denied") | null |
932 | import sqlite3
class SQLite():
def __init__(self, file='application.db'):
self.file=file
def __enter__(self):
self.conn = sqlite3.connect(self.file)
return self.conn.cursor()
def __exit__(self, type, value, traceback):
print("Closing the connection")
self.conn.close()
def blog_lst_to_json(item):
return {
'id': item[0],
'published': item[1],
'title': item[2],
'content': item[3],
'public': bool(item[4])
}
def fetch_blogs():
try:
with SQLite('application.db') as cur:
# execute the query
cur.execute('SELECT * FROM blogs where public=1')
# fetch the data and turn into a dict
return list(map(blog_lst_to_json, cur.fetchall()))
except Exception as e:
print(e)
return [] | null |
933 | import sqlite3
class SQLite():
def __init__(self, file='application.db'):
self.file=file
def __enter__(self):
self.conn = sqlite3.connect(self.file)
return self.conn.cursor()
def __exit__(self, type, value, traceback):
print("Closing the connection")
self.conn.close()
class NotFoundError(Exception):
pass
class NotAuthorizedError(Exception):
pass
def blog_lst_to_json(item):
return {
'id': item[0],
'published': item[1],
'title': item[2],
'content': item[3],
'public': bool(item[4])
}
def fetch_blog(id: str):
try:
with SQLite('application.db') as cur:
# execute the query and fetch the data
cur.execute(f"SELECT * FROM blogs where id=?", [id])
result = cur.fetchone()
# return the result or raise an error
if result is None:
raise NotFoundError(f'Unable to find blog with id {id}.')
data = blog_lst_to_json(result)
if not data['public']:
raise NotAuthorizedError(f'You are not allowed to access blog with id {id}.')
return data
except sqlite3.OperationalError:
raise NotFoundError(f'Unable to find blog with id {id}.') | null |
934 | from pydantic import ConfigDict
from llmkira.extra.user import CostControl, UserCost
from llmkira.middleware.llm_provider import GetAuthDriver
from llmkira.sdk import resign_plugin_executor
from llmkira.sdk.endpoint import openai
from llmkira.sdk.func_calling import verify_openapi_version
from loguru import logger
from pydantic import BaseModel
from llmkira.schema import RawMessage
from llmkira.sdk.func_calling import BaseTool, PluginMetadata
from llmkira.sdk.func_calling.schema import FuncPair
from llmkira.sdk.schema import create_short_task, Function
from llmkira.task import Task, TaskHeader
from typing import TYPE_CHECKING
def search_on_duckduckgo(search_sentence: str, key_words: str = None):
logger.debug(f"Plugin --search_on_duckduckgo {search_sentence}")
from duckduckgo_search import DDGS
# 内存优化抛弃 NLP
# from llmkira.sdk.filter import Sublimate
sort_text = []
link_refer = {}
with DDGS(timeout=20) as ddgs:
search_result = ddgs.text(search_sentence)
for r in search_result:
_title = r.get("title")
_href = r.get("href")
_body = r.get("body")
link_refer[_body] = _href
sort_text.append((_body, _title, _href))
# must_key = [key_words] if key_words else None
sorted_result = sort_text
# sorted_result = Sublimate(sort_text).valuation(match_sentence=search_sentence, match_keywords=must_key)
valuable_result = [item[0] for item in sorted_result[:4]]
# 构建单条内容
clues = []
for key, item in enumerate(valuable_result):
clues.append(
f"\nPage #{key}\n🔍Contents:{item}\n"
f"🔗Source:{link_refer.get(item, 'https://google.com/')}\n"
)
content = "\n".join(clues)
return (
"[🔍SearchPage]\n"
+ content
+ (
"\n[Page End]"
"\n[ReplyFormat:`$summary_answer \n [$index]($source_link) * num` to mark links]"
)
) | null |
935 | from pydantic import field_validator, ConfigDict
import re
from llmkira.sdk import resign_plugin_executor
from llmkira.sdk.func_calling import verify_openapi_version
from llmkira.sdk.schema import File, Function
from io import BytesIO
from math import floor
from PIL import Image
from loguru import logger
from pydantic import BaseModel
from llmkira.schema import RawMessage
from llmkira.sdk.func_calling import BaseTool
from llmkira.sdk.func_calling.schema import FuncPair, PluginMetadata
from llmkira.task import Task, TaskHeader
from typing import TYPE_CHECKING, Optional
async def resize_image(photo):
logger.debug(f"Plugin --resize_image")
image = Image.open(photo)
if (image.width and image.height) < 512:
size1 = image.width
size2 = image.height
if image.width > image.height:
scale = 512 / size1
size1new = 512
size2new = size2 * scale
else:
scale = 512 / size2
size1new = size1 * scale
size2new = 512
size1new = floor(size1new)
size2new = floor(size2new)
size_new = (size1new, size2new)
image = image.resize(size_new)
else:
maxsize = (512, 512)
image.thumbnail(maxsize)
return image | null |
936 | from dotenv import load_dotenv
from loguru import logger
async def aps_start():
logger.success("Receiver Runtime:APS Timer start")
SCHEDULER.start()
class FunctionReceiver(object):
"""
receive message from any platform
"""
def __init__(self):
self.task = Task(queue=__receiver__)
async def run_pending_task(task: TaskHeader, pending_task: TaskBatch):
"""
如果执行异常,必须抛出异常,否则会导致任务无法结束
如果重发认证,不需要结束任务
:param task: 任务
:param pending_task: 待执行的函数
:return: None
"""
assert isinstance(pending_task, TaskBatch), "pending task type error"
chain_func = ChainFunc()
# Parse Function Call
try:
_arg = json.loads(pending_task.get_batch_args())
except json.JSONDecodeError as decode_error:
logger.warning("Function Arguments is not json format")
await chain_func.reply_user(
platform=task.receiver.platform,
receiver=task.receiver,
task=task,
text=f"🔭 Sorry function `{pending_task.get_batch_name()}` "
f"arguments is not json format"
f"\narguments {pending_task.get_batch_args()}",
)
raise decode_error
# Get Function Object
_tool_cls = ToolRegister().get_tool(name=pending_task.get_batch_name())
if not _tool_cls:
logger.warning(f"Not found function {pending_task.get_batch_name()}")
await chain_func.reply_user(
platform=task.receiver.platform,
receiver=task.receiver,
task=task,
text=f"🔭 Sorry function `{pending_task.get_batch_name()}` executor not found",
)
raise ModuleNotFoundError(
f"Function {pending_task.get_batch_name()} not found"
)
# Run Function
_tool_obj = _tool_cls()
if _tool_obj.require_auth:
if task.task_meta.verify_uuid:
# 是携带密钥的函数,是预先构建的可信任务头
task.task_meta.verify_uuid = None
else:
# 需要认证,预构建携带密钥的待发消息并回退
await chain_func.auth_chain(task=task, task_batch=pending_task)
return logger.info(
f"[Resign Auth] \n--auth-require {pending_task.get_batch_name()} require."
)
# Get Env
_env_dict = await EnvManager.from_uid(uid=task.receiver.uid).get_env_list(
name_list=_tool_obj.env_list
)
assert isinstance(_env_dict, dict), "unexpected env dict? it should be dict..."
# Resign Chain
if (
task.task_meta.resign_next_step or task.task_meta.is_complete(num_end=1)
) and not _tool_obj.repeatable:
logger.debug(f"Function {pending_task.get_batch_name()} need resign chain")
await chain_func.resign_chain(
task=task,
parent_func=pending_task.get_batch_name(),
repeatable=_tool_obj.repeatable,
deploy_child=_tool_obj.deploy_child,
)
# 运行函数, 传递模型的信息,以及上一条的结果的openai raw信息
run_result = await _tool_obj.load(
task=task,
receiver=task.receiver,
arg=_arg,
env=_env_dict,
pending_task=pending_task,
refer_llm_result=task.task_meta.llm_result,
)
# 更新任务状态
await task.task_meta.complete_task(
task_batch=pending_task, run_result=run_result
)
return run_result
async def process_function_call(self, message: AbstractIncomingMessage):
"""
定位,解析,运行函数。要求认证,或申请结束/继续指标。
:param message: message from queue
:return: None
"""
# Parse Message
if os.getenv("LLMBOT_STOP_REPLY") == "1":
return None
task: TaskHeader = TaskHeader.model_validate_json(
json_data=message.body.decode("utf-8")
)
# Get Function Call
pending_task = await task.task_meta.work_pending_task(
verify_uuid=task.task_meta.verify_uuid
)
if not pending_task:
logger.trace("No Function Call")
return None
pending_task: TaskBatch
logger.debug("Received A Batch FunctionRequest")
try:
await self.run_pending_task(task=task, pending_task=pending_task)
except Exception as e:
await task.task_meta.complete_task(task_batch=pending_task, run_result=e)
logger.error(f"Function Call Error {e}")
raise e
finally:
logger.trace("Function Call Finished")
async def on_message(self, message: AbstractIncomingMessage):
"""
处理message
:param message: message from queue
:return: None
"""
try:
await self.process_function_call(message=message)
except Exception as e:
logger.exception(f"Function Receiver Error {e}")
await message.reject(requeue=False)
raise e
else:
await message.ack(multiple=False)
async def function(self):
logger.success("Receiver Runtime:Function Fork Cpu start")
await self.task.consuming_task(self.on_message)
global_cache_runtime: RedisRuntime = RedisRuntime()
global_mongodb_runtime: MongodbRuntime = MongodbRuntime()
def get_entrypoint_plugins(group="llmkira.extra.plugin") -> Set[str]:
import importlib_metadata
hook = importlib_metadata.entry_points().select(group=group)
plugins = [item.module for item in hook]
return {*plugins}
class StartSetting(BaseModel):
"""
平台列表
"""
discord: bool = Field(default=False)
kook: bool = Field(default=False)
slack: bool = Field(default=False)
telegram: bool = Field(default=False)
model_config = ConfigDict(from_attributes=True)
def from_subdir(cls):
_kwargs = {}
if SlackSetting.available:
_kwargs["slack"] = True
if TelegramSetting.available:
_kwargs["telegram"] = True
if DiscordSetting.available:
_kwargs["discord"] = True
if KookSetting.available:
_kwargs["kook"] = True
return cls(**_kwargs)
class TelegramReceiver(BaseReceiver):
"""
receive message from telegram
"""
async def telegram(self):
self.set_core(sender=__sender__, task=Task(queue=__receiver__))
if not BotSetting.available:
logger.warning("Receiver Runtime:TelegramBot Setting empty")
return None
logger.success("Receiver Runtime:TelegramBot start")
await self.task.consuming_task(self.on_message)
class DiscordReceiver(BaseReceiver):
"""
receive message from telegram
"""
async def discord(self):
self.set_core(sender=__sender__, task=Task(queue=__receiver__))
if not BotSetting.available:
logger.warning("Receiver Runtime:Discord Setting empty")
return None
await discord_rest.start()
__sender__.acquire()
try:
logger.success("Receiver Runtime:Discord start")
await self.task.consuming_task(self.on_message)
except KeyboardInterrupt:
logger.warning("Discord Receiver shutdown")
except Exception as e:
logger.exception(e)
raise e
finally:
await discord_rest.close()
"""
平台路由
"""
class KookReceiver(BaseReceiver):
"""
receive message from telegram
"""
async def kook(self):
self.set_core(sender=__sender__, task=Task(queue=__receiver__))
if not BotSetting.available:
logger.warning("Receiver Runtime:Kook Setting empty")
return None
try:
logger.success("Receiver Runtime:Kook start")
await self.task.consuming_task(self.on_message)
except KeyboardInterrupt:
logger.warning("Kook Receiver shutdown")
except Exception as e:
logger.exception(e)
raise e
"""
平台路由
"""
class SlackReceiver(BaseReceiver):
"""
receive message from telegram
"""
async def slack(self):
self.set_core(sender=__sender__, task=Task(queue=__receiver__))
if not BotSetting.available:
logger.warning("Receiver Runtime:Slack Setting empty")
return None
try:
logger.success("Receiver Runtime:Slack start")
await self.task.consuming_task(self.on_message)
except KeyboardInterrupt:
logger.warning("Slack Receiver shutdown")
except Exception as e:
logger.exception(e)
raise e
def run():
import asyncio
from .aps import aps_start
from .function import FunctionReceiver
from llmkira.sdk.cache import global_cache_runtime, global_mongodb_runtime
global_cache_runtime.init_cache(verbose=True)
global_mongodb_runtime.init_mongodb(verbose=True)
func = [
aps_start(),
FunctionReceiver().function(),
]
from llmkira.sdk.func_calling import load_plugins, load_from_entrypoint, get_entrypoint_plugins
from llmkira.setting import StartSetting
start_setting = StartSetting.from_subdir()
if start_setting.telegram:
from .telegram import TelegramReceiver
func.append(TelegramReceiver().telegram())
if start_setting.discord:
from .discord import DiscordReceiver
func.append(DiscordReceiver().discord())
if start_setting.kook:
from .kook import KookReceiver
func.append(KookReceiver().kook())
if start_setting.slack:
from .slack import SlackReceiver
func.append(SlackReceiver().slack())
async def _main(_func):
await asyncio.gather(
*_func
)
# 导入插件
load_plugins("llmkira/extra/plugins")
load_from_entrypoint("llmkira.extra.plugin")
loaded_message = "\n >>".join(get_entrypoint_plugins())
logger.success(f"\n===========Third Party Plugins Loaded==========\n >>{loaded_message}")
loop = asyncio.get_event_loop()
loop.run_until_complete(_main(func)) | null |
937 | import re
def replace_all(text, pattern, function):
poslist = [0]
strlist = []
originstr = []
poslist = find_all_index(text, pattern)
for i in range(1, len(poslist[:-1]), 2):
start, end = poslist[i:i + 2]
strlist.append(function(text[start:end]))
for i in range(0, len(poslist), 2):
j, k = poslist[i:i + 2]
originstr.append(text[j:k])
if len(strlist) < len(originstr):
strlist.append('')
else:
originstr.append('')
new_list = [item for pair in zip(originstr, strlist) for item in pair]
return ''.join(new_list)
def escapeshape(text):
return '▎*' + text.split()[1] + '*'
def escapeminus(text):
return '\\' + text
def escapebackquote(text):
return r'\`\`'
def escapeplus(text):
return '\\' + text
def escape(text, flag=0):
# In all other places characters
# _ * [ ] ( ) ~ ` > # + - = | { } . !
# must be escaped with the preceding character '\'.
if flag:
text = re.sub(r"\\\\", '@@@', text)
text = re.sub(r"\\", r"\\\\", text)
if flag:
text = re.sub(r"\@{3}", r"\\\\", text)
text = re.sub(r"_", '\_', text)
text = re.sub(r"\*{2}(.*?)\*{2}", '@@@\\1@@@', text)
text = re.sub(r"\n{1,2}\*\s", '\n\n• ', text)
text = re.sub(r"\*", '\*', text)
text = re.sub(r"\@{3}(.*?)\@{3}", '*\\1*', text)
text = re.sub(r"\!?\[(.*?)\]\((.*?)\)", '@@@\\1@@@^^^\\2^^^', text)
text = re.sub(r"\[", '\[', text)
text = re.sub(r"\]", '\]', text)
text = re.sub(r"\(", '\(', text)
text = re.sub(r"\)", '\)', text)
text = re.sub(r"\@{3}(.*?)\@{3}\^{3}(.*?)\^{3}", '[\\1](\\2)', text)
text = re.sub(r"~", '\~', text)
text = re.sub(r">", '\>', text)
text = replace_all(text, r"(^#+\s.+?$)|```[\D\d\s]+?```", escapeshape)
text = re.sub(r"#", '\#', text)
text = replace_all(text, r"(\+)|\n[\s]*-\s|```[\D\d\s]+?```|`[\D\d\s]*?`", escapeplus)
text = re.sub(r"\n{1,2}(\s*)-\s", '\n\n\\1• ', text)
text = re.sub(r"\n{1,2}(\s*\d{1,2}\.\s)", '\n\n\\1', text)
text = replace_all(text, r"(-)|\n[\s]*-\s|```[\D\d\s]+?```|`[\D\d\s]*?`", escapeminus)
text = re.sub(r"```([\D\d\s]+?)```", '@@@\\1@@@', text)
text = replace_all(text, r"(``)", escapebackquote)
text = re.sub(r"\@{3}([\D\d\s]+?)\@{3}", '```\\1```', text)
text = re.sub(r"=", '\=', text)
text = re.sub(r"\|", '\|', text)
text = re.sub(r"{", '\{', text)
text = re.sub(r"}", '\}', text)
text = re.sub(r"\.", '\.', text)
text = re.sub(r"!", '\!', text)
return text | null |
938 | import time
from typing import TYPE_CHECKING, Dict, Any
from typing import Tuple, List, Union, Optional
import hikari
import khl
import orjson
import shortuuid
from loguru import logger
from pydantic import model_validator, ConfigDict, Field, BaseModel
from telebot import types
from llmkira.schema import RawMessage
from llmkira.sdk.endpoint.schema import LlmResult
from llmkira.sdk.schema import File, Function, ToolMessage, FunctionMessage, TaskBatch
def orjson_dumps(v, *, default):
# orjson.dumps returns bytes, to match standard json.dumps we need to decode
return orjson.dumps(v, default=default).decode() | null |
939 | from . import resign_trigger, Trigger
The provided code snippet includes necessary dependencies for implementing the `on_chat_message` function. Write a Python function `async def on_chat_message(message: str, uid: str, **kwargs)` to solve the following problem:
:param message: RawMessage :return:
Here is the function:
async def on_chat_message(message: str, uid: str, **kwargs):
"""
:param message: RawMessage
:return:
"""
if "<deny>" in message:
return True | :param message: RawMessage :return: |
940 | from abc import abstractmethod, ABC
from typing import Any
def singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton | null |
941 | import asyncio
import hashlib
import tempfile
from bisect import bisect_left
from typing import Coroutine, Dict, List, Optional
import aiohttp
import ffmpeg
import nest_asyncio
import shortuuid
from loguru import logger
from telebot import formatting
from telebot.formatting import escape_markdown
def dict2message(data: Dict[str, str]) -> List[str]:
_res = []
for key, value in data.items():
_res.append("".join([formatting.mitalic(key), escape_markdown("="), f"`{escape_markdown(value)}`"]))
return _res | null |
942 | import asyncio
import hashlib
import tempfile
from bisect import bisect_left
from typing import Coroutine, Dict, List, Optional
import aiohttp
import ffmpeg
import nest_asyncio
import shortuuid
from loguru import logger
from telebot import formatting
from telebot.formatting import escape_markdown
def __ensure_event_loop():
try:
asyncio.get_event_loop()
except Exception:
asyncio.set_event_loop(asyncio.new_event_loop())
The provided code snippet includes necessary dependencies for implementing the `sync` function. Write a Python function `def sync(coroutine: Coroutine)` to solve the following problem:
同步执行异步函数,使用可参考 [同步执行异步代码](https://nemo2011.github.io/bilibili-api/#/sync-executor) Args: coroutine (Coroutine): 异步函数 Returns: 该异步函数的返回值
Here is the function:
def sync(coroutine: Coroutine):
"""
同步执行异步函数,使用可参考 [同步执行异步代码](https://nemo2011.github.io/bilibili-api/#/sync-executor)
Args:
coroutine (Coroutine): 异步函数
Returns:
该异步函数的返回值
"""
__ensure_event_loop()
loop = asyncio.get_event_loop()
return loop.run_until_complete(coroutine) | 同步执行异步函数,使用可参考 [同步执行异步代码](https://nemo2011.github.io/bilibili-api/#/sync-executor) Args: coroutine (Coroutine): 异步函数 Returns: 该异步函数的返回值 |
943 | import asyncio
import hashlib
import tempfile
from bisect import bisect_left
from typing import Coroutine, Dict, List, Optional
import aiohttp
import ffmpeg
import nest_asyncio
import shortuuid
from loguru import logger
from telebot import formatting
from telebot.formatting import escape_markdown
The provided code snippet includes necessary dependencies for implementing the `sha1_encrypt` function. Write a Python function `def sha1_encrypt(string)` to solve the following problem:
sha1加密算法
Here is the function:
def sha1_encrypt(string):
"""
sha1加密算法
"""
sha = hashlib.sha1(string.encode('utf-8'))
encrypts = sha.hexdigest()
return encrypts[:8] | sha1加密算法 |
944 | import asyncio
import hashlib
import tempfile
from bisect import bisect_left
from typing import Coroutine, Dict, List, Optional
import aiohttp
import ffmpeg
import nest_asyncio
import shortuuid
from loguru import logger
from telebot import formatting
from telebot.formatting import escape_markdown
def generate_uid():
return shortuuid.uuid()[0:8].upper() | null |
945 | import asyncio
import hashlib
import tempfile
from bisect import bisect_left
from typing import Coroutine, Dict, List, Optional
import aiohttp
import ffmpeg
import nest_asyncio
import shortuuid
from loguru import logger
from telebot import formatting
from telebot.formatting import escape_markdown
async def aiohttp_download_file(url,
session: aiohttp.ClientSession = None,
timeout=None,
size_limit=None,
headers=None,
**kwargs):
if not session:
session = aiohttp.ClientSession()
async with session as session:
async with session.get(url,
timeout=timeout,
headers=headers, **kwargs
) as response:
if response.status != 200:
raise Exception("无法下载文件")
content_length = response.content_length
if size_limit and content_length and content_length > size_limit:
raise Exception("文件大小超过限制")
contents = await response.read()
return contents | null |
946 | import asyncio
import hashlib
import tempfile
from bisect import bisect_left
from typing import Coroutine, Dict, List, Optional
import aiohttp
import ffmpeg
import nest_asyncio
import shortuuid
from loguru import logger
from telebot import formatting
from telebot.formatting import escape_markdown
The provided code snippet includes necessary dependencies for implementing the `prefix_search` function. Write a Python function `def prefix_search(wordlist, prefix)` to solve the following problem:
在有序列表中二分查找前缀 :param wordlist: 有序列表 :param prefix: 前缀
Here is the function:
def prefix_search(wordlist, prefix):
"""
在有序列表中二分查找前缀
:param wordlist: 有序列表
:param prefix: 前缀
"""
try:
index = bisect_left(wordlist, prefix)
return wordlist[index].startswith(prefix)
except IndexError:
return False | 在有序列表中二分查找前缀 :param wordlist: 有序列表 :param prefix: 前缀 |
947 | from pathlib import Path
from types import ModuleType
from typing import Optional, Set, Iterable, Union
from . import (
_managers,
_current_plugin_chain,
_module_name_to_plugin_name,
path_to_module_name, _find_manager_by_name, get_plugin,
)
from .model import PluginManager
from .schema import Plugin
def load_all_plugins(module_path: Iterable[str], plugin_dir: Iterable[str]) -> Set[Plugin]:
"""
导入指定列表中的插件以及指定目录下多个插件,以 `_` 开头的插件不会被导入!
:param module_path: 指定插件集合
:param plugin_dir: 指定文件夹路径集合
"""
manager = PluginManager(module_path, plugin_dir)
_managers.append(manager)
return manager.load_all_plugins()
class PluginManager:
"""插件管理器。
参数:
plugins: 独立插件模块名集合。
search_path: 插件搜索路径(文件夹)。
"""
def __init__(
self,
plugins: Optional[Iterable[str]] = None,
search_path: Optional[Iterable[str]] = None,
):
# simple plugin not in search path
self.plugins: Set[str] = set(plugins or [])
self.search_path: Set[str] = set(search_path or [])
# cache plugins
self._third_party_plugin_names: Dict[str, str] = {}
self._searched_plugin_names: Dict[str, Path] = {}
self.prepare_plugins()
def __repr__(self) -> str:
return f"PluginManager(plugins={self.plugins}, search_path={self.search_path})"
def third_party_plugins(self) -> Set[str]:
"""返回所有独立插件名称。"""
return set(self._third_party_plugin_names.keys())
def searched_plugins(self) -> Set[str]:
"""返回已搜索到的插件名称。"""
return set(self._searched_plugin_names.keys())
def available_plugins(self) -> Set[str]:
"""返回当前插件管理器中可用的插件名称。"""
return self.third_party_plugins | self.searched_plugins
def _previous_plugins(self) -> Set[str]:
_pre_managers: List[PluginManager]
if self in _managers:
_pre_managers = _managers[: _managers.index(self)]
else:
_pre_managers = _managers[:]
return {
*chain.from_iterable(manager.available_plugins for manager in _pre_managers)
}
def prepare_plugins(self) -> Set[str]:
"""搜索插件并缓存插件名称。"""
# get all previous ready to load plugins
previous_plugins = self._previous_plugins()
searched_plugins: Dict[str, Path] = {}
third_party_plugins: Dict[str, str] = {}
# check third party plugins
for plugin in self.plugins:
name = _module_name_to_plugin_name(plugin)
if name in third_party_plugins or name in previous_plugins:
raise RuntimeError(
f"Plugin already exists: {name}! Check your plugin name"
)
third_party_plugins[name] = plugin
self._third_party_plugin_names = third_party_plugins
# check plugins in search path
for module_info in pkgutil.iter_modules(self.search_path):
# ignore if startswith "_"
if module_info.name.startswith("_"):
continue
if (
module_info.name in searched_plugins
or module_info.name in previous_plugins
or module_info.name in third_party_plugins
):
raise RuntimeError(
f"Plugin already exists: {module_info.name}! Check your plugin name"
)
#
module_spec = module_info.module_finder.find_spec(module_info.name, None)
if not module_spec:
continue
module_path = module_spec.origin
if not module_path:
continue
searched_plugins[module_info.name] = Path(module_path).resolve()
self._searched_plugin_names = searched_plugins
return self.available_plugins
def load_plugin(self, name: str) -> Optional[Plugin]:
"""加载指定插件。
对于独立插件,可以使用完整插件模块名或者插件名称。
参数:
name: 插件名称。
"""
try:
if name in self.plugins:
module = importlib.import_module(name)
elif name in self._third_party_plugin_names:
module = importlib.import_module(self._third_party_plugin_names[name])
elif name in self._searched_plugin_names:
module = importlib.import_module(
path_to_module_name(self._searched_plugin_names[name])
)
else:
raise RuntimeError(f"Plugin not found: {name}! Check your plugin name")
plugin = getattr(module, "__plugin__", None)
if plugin is None or not isinstance(plugin, Plugin):
raise RuntimeError(
f"Module {module.__name__} is not loaded as a plugin! "
"Make sure not to import it before loading."
)
logger.opt(colors=True).info(
f'✨ Succeeded to load plugin "<y>{escape_tag(plugin.name)}</y>"'
+ (
f' from "<m>{escape_tag(plugin.module_name)}</m>"'
if plugin.module_name != plugin.name
else ""
)
)
return plugin
except Exception as e:
logger.opt(colors=True, exception=e).error(
f'<r><bg #f5f2f2>Failed to import "{escape_tag(name)}"</bg #f5f2f2></r>'
)
def load_all_plugins(self) -> Set[Plugin]:
"""加载所有可用插件。"""
return set(
filter(None, (self.load_plugin(name) for name in self.available_plugins))
)
def searched_plugin_names(self):
return self._searched_plugin_names
class Plugin:
"""
机制用途,不由用户实例化
"""
name: str
"""插件索引标识,Bot 使用 文件/文件夹 名称作为标识符"""
module: ModuleType
"""插件模块对象"""
module_name: str
"""点分割模块路径"""
manager: "PluginManager"
"""导入该插件的插件管理器"""
parent_plugin: Optional["Plugin"] = None
"""父插件"""
sub_plugins: Set["Plugin"] = field(default_factory=set)
"""子插件集合"""
metadata: Optional[PluginMetadata] = None
"""插件元信息"""
The provided code snippet includes necessary dependencies for implementing the `load_plugins` function. Write a Python function `def load_plugins(*plugin_dir: str) -> Set[Plugin]` to solve the following problem:
导入文件夹下多个插件,以 `_` 开头的插件不会被导入! :param plugin_dir: 文件夹路径 :return: 插件集合
Here is the function:
def load_plugins(*plugin_dir: str) -> Set[Plugin]:
"""
导入文件夹下多个插件,以 `_` 开头的插件不会被导入!
:param plugin_dir: 文件夹路径
:return: 插件集合
"""
manager = PluginManager(search_path=plugin_dir)
_managers.append(manager)
return manager.load_all_plugins() | 导入文件夹下多个插件,以 `_` 开头的插件不会被导入! :param plugin_dir: 文件夹路径 :return: 插件集合 |
948 | from pathlib import Path
from types import ModuleType
from typing import Optional, Set, Iterable, Union
from . import (
_managers,
_current_plugin_chain,
_module_name_to_plugin_name,
path_to_module_name, _find_manager_by_name, get_plugin,
)
from .model import PluginManager
from .schema import Plugin
def load_plugin(module_path: Union[str, Path]) -> Optional[Plugin]:
"""
加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。
:param module_path: 插件名称 `path.to.your.plugin`
或插件路径 `pathlib.Path(path/to/your/plugin)`
:return: 插件
"""
module_path = (
path_to_module_name(module_path)
if isinstance(module_path, Path)
else module_path
)
manager = PluginManager([module_path])
_managers.append(manager)
return manager.load_plugin(module_path)
class Plugin:
"""
机制用途,不由用户实例化
"""
name: str
"""插件索引标识,Bot 使用 文件/文件夹 名称作为标识符"""
module: ModuleType
"""插件模块对象"""
module_name: str
"""点分割模块路径"""
manager: "PluginManager"
"""导入该插件的插件管理器"""
parent_plugin: Optional["Plugin"] = None
"""父插件"""
sub_plugins: Set["Plugin"] = field(default_factory=set)
"""子插件集合"""
metadata: Optional[PluginMetadata] = None
"""插件元信息"""
The provided code snippet includes necessary dependencies for implementing the `load_builtin_plugin` function. Write a Python function `def load_builtin_plugin(name: str) -> Optional[Plugin]` to solve the following problem:
导入 Bot 内置插件。 :param name: 插件名称 :return: 插件
Here is the function:
def load_builtin_plugin(name: str) -> Optional[Plugin]:
"""导入 Bot 内置插件。
:param name: 插件名称
:return: 插件
"""
return load_plugin(f"extra.plugins.{name}") | 导入 Bot 内置插件。 :param name: 插件名称 :return: 插件 |
949 | from pathlib import Path
from types import ModuleType
from typing import Optional, Set, Iterable, Union
from . import (
_managers,
_current_plugin_chain,
_module_name_to_plugin_name,
path_to_module_name, _find_manager_by_name, get_plugin,
)
from .model import PluginManager
from .schema import Plugin
def load_all_plugins(module_path: Iterable[str], plugin_dir: Iterable[str]) -> Set[Plugin]:
"""
导入指定列表中的插件以及指定目录下多个插件,以 `_` 开头的插件不会被导入!
:param module_path: 指定插件集合
:param plugin_dir: 指定文件夹路径集合
"""
manager = PluginManager(module_path, plugin_dir)
_managers.append(manager)
return manager.load_all_plugins()
class Plugin:
"""
机制用途,不由用户实例化
"""
name: str
"""插件索引标识,Bot 使用 文件/文件夹 名称作为标识符"""
module: ModuleType
"""插件模块对象"""
module_name: str
"""点分割模块路径"""
manager: "PluginManager"
"""导入该插件的插件管理器"""
parent_plugin: Optional["Plugin"] = None
"""父插件"""
sub_plugins: Set["Plugin"] = field(default_factory=set)
"""子插件集合"""
metadata: Optional[PluginMetadata] = None
"""插件元信息"""
The provided code snippet includes necessary dependencies for implementing the `load_builtin_plugins` function. Write a Python function `def load_builtin_plugins(*plugins: str) -> Set[Plugin]` to solve the following problem:
导入多个 Bot 内置插件。 :param plugins: 插件名称集合
Here is the function:
def load_builtin_plugins(*plugins: str) -> Set[Plugin]:
"""导入多个 Bot 内置插件。
:param plugins: 插件名称集合
"""
return load_all_plugins([f"extra.plugins.{p}" for p in plugins], []) | 导入多个 Bot 内置插件。 :param plugins: 插件名称集合 |
950 | from pathlib import Path
from types import ModuleType
from typing import Optional, Set, Iterable, Union
from . import (
_managers,
_current_plugin_chain,
_module_name_to_plugin_name,
path_to_module_name, _find_manager_by_name, get_plugin,
)
from .model import PluginManager
from .schema import Plugin
def load_all_plugins(module_path: Iterable[str], plugin_dir: Iterable[str]) -> Set[Plugin]:
"""
导入指定列表中的插件以及指定目录下多个插件,以 `_` 开头的插件不会被导入!
:param module_path: 指定插件集合
:param plugin_dir: 指定文件夹路径集合
"""
manager = PluginManager(module_path, plugin_dir)
_managers.append(manager)
return manager.load_all_plugins()
class Plugin:
"""
机制用途,不由用户实例化
"""
name: str
"""插件索引标识,Bot 使用 文件/文件夹 名称作为标识符"""
module: ModuleType
"""插件模块对象"""
module_name: str
"""点分割模块路径"""
manager: "PluginManager"
"""导入该插件的插件管理器"""
parent_plugin: Optional["Plugin"] = None
"""父插件"""
sub_plugins: Set["Plugin"] = field(default_factory=set)
"""子插件集合"""
metadata: Optional[PluginMetadata] = None
"""插件元信息"""
def load_from_entrypoint(group="llmkira.extra.plugin") -> Set[Plugin]:
import importlib_metadata
hook = importlib_metadata.entry_points().select(group=group)
plugins = [item.module for item in hook]
return load_all_plugins(plugins, []) | null |
951 | from pathlib import Path
from types import ModuleType
from typing import Optional, Set, Iterable, Union
from . import (
_managers,
_current_plugin_chain,
_module_name_to_plugin_name,
path_to_module_name, _find_manager_by_name, get_plugin,
)
from .model import PluginManager
from .schema import Plugin
def load_plugin(module_path: Union[str, Path]) -> Optional[Plugin]:
"""
加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。
:param module_path: 插件名称 `path.to.your.plugin`
或插件路径 `pathlib.Path(path/to/your/plugin)`
:return: 插件
"""
module_path = (
path_to_module_name(module_path)
if isinstance(module_path, Path)
else module_path
)
manager = PluginManager([module_path])
_managers.append(manager)
return manager.load_plugin(module_path)
The provided code snippet includes necessary dependencies for implementing the `require` function. Write a Python function `def require(name: str) -> ModuleType` to solve the following problem:
获取一个插件的导出内容。 如果为 `load_plugins` 文件夹导入的插件,则为文件(夹)名。 :param name: 插件名称 即 {ref}`extra.plugin.model.Plugin.name`。 :exception RuntimeError: 插件无法加载 :return: 插件导出内容
Here is the function:
def require(name: str) -> ModuleType:
"""
获取一个插件的导出内容。
如果为 `load_plugins` 文件夹导入的插件,则为文件(夹)名。
:param name: 插件名称 即 {ref}`extra.plugin.model.Plugin.name`。
:exception RuntimeError: 插件无法加载
:return: 插件导出内容
"""
plugin = get_plugin(_module_name_to_plugin_name(name))
# if plugin not loaded
if not plugin:
# plugin already declared
manager = _find_manager_by_name(name)
if manager:
plugin = manager.load_plugin(name)
# plugin not declared, try to declare and load it
else:
# clear current plugin chain, ensure plugin loaded in a new context
_t = _current_plugin_chain.set(())
try:
plugin = load_plugin(name)
finally:
_current_plugin_chain.reset(_t)
if not plugin:
raise RuntimeError(f'Cannot load plugin "{name}"!')
return plugin.module | 获取一个插件的导出内容。 如果为 `load_plugins` 文件夹导入的插件,则为文件(夹)名。 :param name: 插件名称 即 {ref}`extra.plugin.model.Plugin.name`。 :exception RuntimeError: 插件无法加载 :return: 插件导出内容 |
952 | import re
The provided code snippet includes necessary dependencies for implementing the `escape_tag` function. Write a Python function `def escape_tag(s: str) -> str` to solve the following problem:
用于记录带颜色日志时转义 `<tag>` 类型特殊标签 参考: [loguru color 标签](https://loguru.readthedocs.io/en/stable/api/logger.html#color) 参数: s: 需要转义的字符串
Here is the function:
def escape_tag(s: str) -> str:
"""用于记录带颜色日志时转义 `<tag>` 类型特殊标签
参考: [loguru color 标签](https://loguru.readthedocs.io/en/stable/api/logger.html#color)
参数:
s: 需要转义的字符串
"""
return re.sub(r"</?((?:[fb]g\s)?[^<>\s]*)>", r"\\\g<0>", s) | 用于记录带颜色日志时转义 `<tag>` 类型特殊标签 参考: [loguru color 标签](https://loguru.readthedocs.io/en/stable/api/logger.html#color) 参数: s: 需要转义的字符串 |
953 | import asyncio
import atexit
import json
from typing import Any
import httpx
from loguru import logger
from .error import RateLimitError, ServiceUnavailableError, AuthenticationError, CheckError
def llm_error_handler(code, message: str):
if code == 429:
raise RateLimitError(message)
elif code == 404 and not message:
raise ServiceUnavailableError(f"invalid endpoint, {message}")
elif code == 500 or code != 401:
raise ServiceUnavailableError(message)
else:
raise AuthenticationError(message)
def check_json_response(status_code: int, req_data: dict):
"""
检查json响应
"""
if req_data.get("object", None) == "error":
raise CheckError(
f"[CODE]{status_code}:{req_data.get('code', 404)}"
)
# 错误消息
if req_data.get("error", None):
_error = req_data.get("error", "your endpoint is not a valid endpoint, please check it")
if status_code == 404:
raise CheckError(
f"[Invalid endpoint] {_error}, do you forget to add something like v1/chat/completions?"
)
raise CheckError(
f"{status_code}:{_error.get('type')}:{_error.get('message')}"
)
# 错误消息
if isinstance(req_data.get("message"), str):
raise CheckError(
f"{status_code}:{req_data.get('message')}"
)
if status_code == 404:
raise CheckError(
f"[Invalid endpoint] no error message return... do you forget to add something like v1/chat/completions?"
)
def get_session(proxy: str = ""):
global __session_pool
loop = asyncio.get_event_loop()
session = __session_pool.get(loop, None)
if session is None:
if proxy:
proxies = {"all://": proxy}
session = httpx.AsyncClient(timeout=300, proxies=proxies)
else:
session = httpx.AsyncClient(timeout=300)
__session_pool[loop] = session
return session
class CheckError(Exception):
"""
Raised when the API is unavailable.
"""
pass
The provided code snippet includes necessary dependencies for implementing the `request` function. Write a Python function `async def request( method: str, url: str, params: dict = None, data: Any = None, headers: dict = None, json_body: bool = False, proxy: str = "", call_func=None, timeout: int = 300, **kwargs, )` to solve the following problem:
请求 :param call_func: 错误回调函数 :param method: :param url: :param params: :param data: :param headers: :param json_body: :param proxy: :param timeout: :param kwargs: 参数 :return:
Here is the function:
async def request(
method: str,
url: str,
params: dict = None,
data: Any = None,
headers: dict = None,
json_body: bool = False,
proxy: str = "",
call_func=None,
timeout: int = 300,
**kwargs,
):
"""
请求
:param call_func: 错误回调函数
:param method:
:param url:
:param params:
:param data:
:param headers:
:param json_body:
:param proxy:
:param timeout:
:param kwargs: 参数
:return:
"""
if headers is None:
headers = {}
if params is None:
params = {}
config = {
"method": method.upper(),
"url": url,
"params": params,
"data": data,
"headers": headers,
}
# 更新
config.update(kwargs)
if json_body:
config["headers"]["Content-Type"] = "application/json"
config["data"] = json.dumps(config["data"]).encode()
# SSL
# config["ssl"] = False
# timeout
config["timeout"] = timeout
# 请求
session = get_session(proxy=proxy)
resp = await session.request(**config)
# 检查响应头 Content-Length
content_length = resp.headers.get("content-length")
if content_length and int(content_length) == 0:
return None
# 检查响应头 Content-Type
content_type = resp.headers.get("content-type")
if content_type.lower().find("application/json") == -1:
logger.error(f"[105232]Server send a invalid response {resp.text}")
raise Exception("Server send a invalid response with content-type:{}".format(content_type))
try:
req_data: dict = json.loads(resp.text)
except json.JSONDecodeError:
if resp.status_code != 200:
raise Exception(f"[Request {resp.status_code}] Request failed without any error message")
raise Exception("Server send a invalid json response")
try:
check_json_response(resp.status_code, req_data)
except CheckError as e:
logger.error(e)
# Message 格式校验失败
if call_func:
call_func(req_data, headers)
_status = req_data.get("status", None)
llm_error_handler(
code=_status,
message=f"{resp.status_code}:{req_data.get('message')}"
)
except Exception as e:
raise e
return req_data | 请求 :param call_func: 错误回调函数 :param method: :param url: :param params: :param data: :param headers: :param json_body: :param proxy: :param timeout: :param kwargs: 参数 :return: |
954 | import asyncio
import atexit
import json
from typing import Any
import httpx
from loguru import logger
from .error import RateLimitError, ServiceUnavailableError, AuthenticationError, CheckError
__session_pool = {}
The provided code snippet includes necessary dependencies for implementing the `__clean` function. Write a Python function `def __clean()` to solve the following problem:
程序退出清理操作。
Here is the function:
def __clean():
"""
程序退出清理操作。
"""
try:
loop = asyncio.get_event_loop()
except RuntimeError:
return
async def __clean_task():
await __session_pool[loop].close()
if loop.is_closed():
loop.run_until_complete(__clean_task())
else:
loop.create_task(__clean_task()) | 程序退出清理操作。 |
955 | from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
)
from urllib.parse import urlparse
from redis import RedisCluster
from loguru import logger
def _redis_sentinel_client(redis_url: str, **kwargs: Any) -> RedisType:
"""helper method to parse an (un-official) redis+sentinel url
and create a Sentinel connection to fetch the final redis client
connection to a replica-master for read-write operations.
If username and/or password for authentication is given the
same credentials are used for the Redis Sentinel as well as Redis Server.
With this implementation using a redis url only it is not possible
to use different data for authentication on booth systems.
"""
import redis
parsed_url = urlparse(redis_url)
# sentinel needs list with (host, port) tuple, use default port if none available
sentinel_list = [(parsed_url.hostname or "localhost", parsed_url.port or 26379)]
if parsed_url.path:
# "/mymaster/0" first part is service name, optional second part is db number
path_parts = parsed_url.path.split("/")
service_name = path_parts[1] or "mymaster"
if len(path_parts) > 2:
kwargs["db"] = path_parts[2]
else:
service_name = "mymaster"
sentinel_args = {}
if parsed_url.password:
sentinel_args["password"] = parsed_url.password
kwargs["password"] = parsed_url.password
if parsed_url.username:
sentinel_args["username"] = parsed_url.username
kwargs["username"] = parsed_url.username
# check for all SSL related properties and copy them into sentinel_kwargs too,
# add client_name also
for arg in kwargs:
if arg.startswith("ssl") or arg == "client_name":
sentinel_args[arg] = kwargs[arg]
# sentinel user/pass is part of sentinel_kwargs, user/pass for redis server
# connection as direct parameter in kwargs
sentinel_client = redis.sentinel.Sentinel(
sentinel_list, sentinel_kwargs=sentinel_args, **kwargs
)
# redis server might have password but not sentinel - fetch this error and try
# again without pass, everything else cannot be handled here -> user needed
try:
sentinel_client.execute_command("ping")
except redis.exceptions.AuthenticationError as ae:
if "no password is set" in ae.args[0]:
logger.warning(
"Redis sentinel connection configured with password but Sentinel \
answered NO PASSWORD NEEDED - Please check Sentinel configuration"
)
sentinel_client = redis.sentinel.Sentinel(sentinel_list, **kwargs)
else:
raise ae
return sentinel_client.master_for(service_name)
def _check_for_cluster(redis_client: RedisType) -> bool:
import redis
try:
cluster_info = redis_client.info("cluster")
return cluster_info["cluster_enabled"] == 1
except redis.exceptions.RedisError:
return False
def _redis_cluster_client(redis_url: str, **kwargs: Any) -> RedisCluster:
from redis.cluster import RedisCluster
return RedisCluster.from_url(redis_url, **kwargs)
The provided code snippet includes necessary dependencies for implementing the `get_client` function. Write a Python function `def get_client(redis_url: str, **kwargs: Any) -> RedisType` to solve the following problem:
Get a redis client from the connection url given. This helper accepts urls for Redis server (TCP with/without TLS or UnixSocket) as well as Redis Sentinel connections. Redis Cluster is not supported. Before creating a connection the existence of the database driver is checked an and ValueError raised otherwise To use, you should have the ``redis`` python package installed. Example: .. code-block:: python from langchain.utilities.redis import get_client redis_client = get_client( redis_url="redis://username:password@localhost:6379" index_name="my-index", embedding_function=embeddings.embed_query, ) To use a redis replication setup with multiple redis server and redis sentinels set "redis_url" to "redis+sentinel://" scheme. With this url format a path is needed holding the name of the redis service within the sentinels to get the correct redis server connection. The default service name is "mymaster". The optional second part of the path is the redis db number to connect to. An optional username or password is used for booth connections to the rediserver and the sentinel, different passwords for server and sentinel are not supported. And as another constraint only one sentinel instance can be given: Example: .. code-block:: python from langchain.utilities.redis import get_client redis_client = get_client( redis_url="redis+sentinel://username:password@sentinelhost:26379/mymaster/0" index_name="my-index", embedding_function=embeddings.embed_query, )
Here is the function:
def get_client(redis_url: str, **kwargs: Any) -> RedisType:
"""Get a redis client from the connection url given. This helper accepts
urls for Redis server (TCP with/without TLS or UnixSocket) as well as
Redis Sentinel connections.
Redis Cluster is not supported.
Before creating a connection the existence of the database driver is checked
an and ValueError raised otherwise
To use, you should have the ``redis`` python package installed.
Example:
.. code-block:: python
from langchain.utilities.redis import get_client
redis_client = get_client(
redis_url="redis://username:password@localhost:6379"
index_name="my-index",
embedding_function=embeddings.embed_query,
)
To use a redis replication setup with multiple redis server and redis sentinels
set "redis_url" to "redis+sentinel://" scheme. With this url format a path is
needed holding the name of the redis service within the sentinels to get the
correct redis server connection. The default service name is "mymaster". The
optional second part of the path is the redis db number to connect to.
An optional username or password is used for booth connections to the rediserver
and the sentinel, different passwords for server and sentinel are not supported.
And as another constraint only one sentinel instance can be given:
Example:
.. code-block:: python
from langchain.utilities.redis import get_client
redis_client = get_client(
redis_url="redis+sentinel://username:password@sentinelhost:26379/mymaster/0"
index_name="my-index",
embedding_function=embeddings.embed_query,
)
"""
# Initialize with necessary components.
try:
import redis
except ImportError:
raise ValueError(
"Could not import redis python package. "
"Please install it with `pip install redis>=4.1.0`."
)
# check if normal redis:// or redis+sentinel:// url
if redis_url.startswith("redis+sentinel"):
redis_client = _redis_sentinel_client(redis_url, **kwargs)
elif redis_url.startswith("rediss+sentinel"): # sentinel with TLS support enables
kwargs["ssl"] = True
if "ssl_cert_reqs" not in kwargs:
kwargs["ssl_cert_reqs"] = "none"
redis_client = _redis_sentinel_client(redis_url, **kwargs)
else:
# connect to redis server from url, reconnect with cluster client if needed
redis_client = redis.from_url(redis_url, **kwargs)
if _check_for_cluster(redis_client):
redis_client.close()
redis_client = _redis_cluster_client(redis_url, **kwargs)
return redis_client | Get a redis client from the connection url given. This helper accepts urls for Redis server (TCP with/without TLS or UnixSocket) as well as Redis Sentinel connections. Redis Cluster is not supported. Before creating a connection the existence of the database driver is checked an and ValueError raised otherwise To use, you should have the ``redis`` python package installed. Example: .. code-block:: python from langchain.utilities.redis import get_client redis_client = get_client( redis_url="redis://username:password@localhost:6379" index_name="my-index", embedding_function=embeddings.embed_query, ) To use a redis replication setup with multiple redis server and redis sentinels set "redis_url" to "redis+sentinel://" scheme. With this url format a path is needed holding the name of the redis service within the sentinels to get the correct redis server connection. The default service name is "mymaster". The optional second part of the path is the redis db number to connect to. An optional username or password is used for booth connections to the rediserver and the sentinel, different passwords for server and sentinel are not supported. And as another constraint only one sentinel instance can be given: Example: .. code-block:: python from langchain.utilities.redis import get_client redis_client = get_client( redis_url="redis+sentinel://username:password@sentinelhost:26379/mymaster/0" index_name="my-index", embedding_function=embeddings.embed_query, ) |
956 | import json
from typing import TYPE_CHECKING
from typing import Union, List, Type
import tiktoken
from loguru import logger
from pydantic import BaseModel
def _pydantic_type(_message):
if isinstance(_message, BaseModel):
return _message.model_dump()
return _message | null |
957 | import json
from typing import TYPE_CHECKING
from typing import Union, List, Type
import tiktoken
from loguru import logger
from pydantic import BaseModel
class BaseTokenizer(object):
def num_tokens_from_messages(
self, messages: List[Union[dict, BaseModel, Type[BaseModel]]], model: str
) -> int:
"""Return the number of tokens used by a list of messages_box."""
raise NotImplementedError
class OpenaiTokenizer(BaseTokenizer):
def num_tokens_from_messages(
self, messages: List[Union[dict, BaseModel, Type[BaseModel]]], model: str
) -> int:
"""Return the number of tokens used by a list of messages_box."""
if hasattr(messages, "request_final"):
messages: "Message"
messages = messages.request_final(schema_model=model)
messages: List[dict] = [_pydantic_type(message) for message in messages]
try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
print("Warning: model not found. Using cl100k_base encoding.")
encoding = tiktoken.get_encoding("cl100k_base")
if model in {
"gpt-3.5-turbo-0613",
"gpt-3.5-turbo-16k-0613",
"gpt-4-0314",
"gpt-4-32k-0314",
"gpt-4-0613",
"gpt-4-32k-0613",
}:
tokens_per_message = 3
tokens_per_name = 1
elif model == "gpt-3.5-turbo-0301":
tokens_per_message = (
4 # every message follows <|start|>{role/name}\n{content}<|end|>\n
)
tokens_per_name = -1 # if there's a name, the role is omitted
elif "gpt-3.5-turbo" in model:
print(
"Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613."
)
return self.num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613")
elif "gpt-4" in model:
print(
"Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613."
)
return self.num_tokens_from_messages(messages, model="gpt-4-0613")
else:
tokens_per_message = (
4 # every message follows <|start|>{role/name}\n{content}<|end|>\n
)
tokens_per_name = 1 # if there's a name, the role is omitted
logger.warning(
f"""num_tokens_from_messages() is not implemented for model {model}."""
""":) If you use a no-openai model, """
"""you can [one-api](https://github.com/songquanpeng/one-api) project handle token usage."""
"""or issue https://github.com/LlmKira/Openaibot/issues to request support."""
)
num_tokens = 0
for message in messages:
num_tokens += tokens_per_message
for key, value in message.items():
if isinstance(value, dict):
value = json.dumps(value, ensure_ascii=False)
if isinstance(value, list):
value = json.dumps(value, ensure_ascii=False)
if value is None:
continue
_tokens = len(encoding.encode(value))
num_tokens += _tokens
if key == "name":
num_tokens += tokens_per_name
num_tokens += 3
# every reply is primed with <|start|>assistant<|message|>
return num_tokens
def get_tokenizer(model_name: str) -> BaseTokenizer:
if model_name.startswith("gpt"):
return OpenaiTokenizer()
elif model_name.startswith("."):
raise NotImplementedError(
f"sdk.endpoint.get_tokenizer() is not implemented for model {model_name}."
)
else:
logger.warning(
f"sdk.endpoint.get_tokenizer() is not implemented for model {model_name}.\n "
f"Using default tokenizer.[cl100k]"
)
return OpenaiTokenizer() | null |
958 | import hashlib
import os
from typing import Optional
from typing import TYPE_CHECKING
from pydantic import field_validator, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
from ..error import ValidationError
The provided code snippet includes necessary dependencies for implementing the `sha1_encrypt` function. Write a Python function `def sha1_encrypt(string)` to solve the following problem:
sha1加密算法
Here is the function:
def sha1_encrypt(string):
"""
sha1加密算法
"""
sha = hashlib.sha1(string.encode('utf-8'))
encrypts = sha.hexdigest()
return encrypts[:8] | sha1加密算法 |
959 | import base64
import hashlib
import pickle
import time
from abc import abstractmethod, ABC
from io import BytesIO
from typing import Literal, Optional, List, Type, Union
from typing import TYPE_CHECKING
import aiohttp
import shortuuid
from docstring_parser import parse
from loguru import logger
from pydantic import model_validator, BaseModel, Field, ConfigDict
from .cache import global_cache_runtime
from .error import ValidationError, CheckError
from .utils import sync, aiohttp_download_file
def generate_uid():
return shortuuid.uuid()[0:8].upper() | null |
960 | import base64
import hashlib
import pickle
import time
from abc import abstractmethod, ABC
from io import BytesIO
from typing import Literal, Optional, List, Type, Union
from typing import TYPE_CHECKING
import aiohttp
import shortuuid
from docstring_parser import parse
from loguru import logger
from pydantic import model_validator, BaseModel, Field, ConfigDict
from .cache import global_cache_runtime
from .error import ValidationError, CheckError
from .utils import sync, aiohttp_download_file
class SystemMessage(Message):
role: str = Field(default="system")
content: str
name: Optional[str] = Field(
default=None, description="speaker_name", pattern=r"^[a-zA-Z0-9_]+$"
)
def request_final(
self,
*,
schema_model: str,
) -> "Message":
return self
class UserMessage(Message):
role: str = Field(default="user")
content: Union[str, List["ContentParts"], List[dict]]
name: Optional[str] = Field(
default=None, description="speaker_name", pattern=r"^[a-zA-Z0-9_]+$"
)
def fold(self) -> "Message":
"""
折叠过长特殊类型消息。消息类型为程序自有属性
插件定义 fold_id 引诱查询
:return: Message
"""
metadata_str = (
f"""[FoldText](fold_id={self._meta.index_id}"""
f"""\ntimestamp={self._meta.datatime}"""
f"""\ndescription={self.content[:20] + "..."})"""
)
return self.model_copy(update={"content": metadata_str}, deep=True)
def request_final(
self,
*,
schema_model: str,
) -> "Message":
"""
Openai 请求标准格式最终转换根据 message_class 元信息锁定字段
:param schema_model: 适配的模型
"""
if "vision" in schema_model:
_new_content: List[ContentParts] = []
if isinstance(self.content, str):
_new_content.append(
ContentParts.model_validate({"type": "text", "text": self.content})
)
if self.get_meta():
if self.get_meta().files:
logger.debug(f"vision model: {self._meta.files}")
for file in self.get_meta().files:
file: File
if file.file_url:
_new_content.append(
ContentParts(
type="image_url",
image_url=ContentParts.Image(url=file.file_url),
)
)
elif file.file_id:
if file.file_name.endswith(
("jpg", "png", "jpeg", "gif", "webp", "svg")
):
data: File.Data = sync(file.raw_file())
base64_image = base64.b64encode(
data.file_data
).decode("utf-8")
_new_content.append(
ContentParts(
type="image_url",
image_url=ContentParts.Image(
url=f"data:image/png;base64,{base64_image}"
),
)
)
else:
pass
self.content = _new_content
return self
The provided code snippet includes necessary dependencies for implementing the `create_short_task` function. Write a Python function `def create_short_task(task_desc, refer, role: str = None)` to solve the following problem:
创建单任务模板
Here is the function:
def create_short_task(task_desc, refer, role: str = None):
"""
创建单任务模板
"""
if not role:
role = (
"[RULE]"
"Please complete the order according to the task description refer to given information, "
"if can't complete, please reply 'give up'"
)
return [
SystemMessage(
role="system",
content=role,
),
UserMessage(
role="user", content=f"{refer} <hint>{task_desc}<hint>", name="task"
),
] | 创建单任务模板 |
961 | import base64
import hashlib
import pickle
import time
from abc import abstractmethod, ABC
from io import BytesIO
from typing import Literal, Optional, List, Type, Union
from typing import TYPE_CHECKING
import aiohttp
import shortuuid
from docstring_parser import parse
from loguru import logger
from pydantic import model_validator, BaseModel, Field, ConfigDict
from .cache import global_cache_runtime
from .error import ValidationError, CheckError
from .utils import sync, aiohttp_download_file
class SystemMessage(Message):
role: str = Field(default="system")
content: str
name: Optional[str] = Field(
default=None, description="speaker_name", pattern=r"^[a-zA-Z0-9_]+$"
)
def request_final(
self,
*,
schema_model: str,
) -> "Message":
return self
class UserMessage(Message):
role: str = Field(default="user")
content: Union[str, List["ContentParts"], List[dict]]
name: Optional[str] = Field(
default=None, description="speaker_name", pattern=r"^[a-zA-Z0-9_]+$"
)
def fold(self) -> "Message":
"""
折叠过长特殊类型消息。消息类型为程序自有属性
插件定义 fold_id 引诱查询
:return: Message
"""
metadata_str = (
f"""[FoldText](fold_id={self._meta.index_id}"""
f"""\ntimestamp={self._meta.datatime}"""
f"""\ndescription={self.content[:20] + "..."})"""
)
return self.model_copy(update={"content": metadata_str}, deep=True)
def request_final(
self,
*,
schema_model: str,
) -> "Message":
"""
Openai 请求标准格式最终转换根据 message_class 元信息锁定字段
:param schema_model: 适配的模型
"""
if "vision" in schema_model:
_new_content: List[ContentParts] = []
if isinstance(self.content, str):
_new_content.append(
ContentParts.model_validate({"type": "text", "text": self.content})
)
if self.get_meta():
if self.get_meta().files:
logger.debug(f"vision model: {self._meta.files}")
for file in self.get_meta().files:
file: File
if file.file_url:
_new_content.append(
ContentParts(
type="image_url",
image_url=ContentParts.Image(url=file.file_url),
)
)
elif file.file_id:
if file.file_name.endswith(
("jpg", "png", "jpeg", "gif", "webp", "svg")
):
data: File.Data = sync(file.raw_file())
base64_image = base64.b64encode(
data.file_data
).decode("utf-8")
_new_content.append(
ContentParts(
type="image_url",
image_url=ContentParts.Image(
url=f"data:image/png;base64,{base64_image}"
),
)
)
else:
pass
self.content = _new_content
return self
class AssistantMessage(Message):
role: str = Field(default="assistant")
content: Union[None, str] = Field(default="", description="assistant content")
name: Optional[str] = Field(
default=None, description="speaker_name", pattern=r"^[a-zA-Z0-9_]+$"
)
tool_calls: Optional[List[ToolCallCompletion]] = Field(
default=None, description="tool calls"
)
"""a array of tools, for result"""
function_call: Optional[FunctionCallCompletion] = Field(
default=None, description="Deprecated"
)
"""Deprecated by openai ,for result"""
def deprecate_validator(self):
if self.tool_calls and self.function_call:
raise ValidationError(
"sdk param validator:tool_calls and function_call cannot both be provided"
)
if self.function_call:
logger.warning("sdk param validator:function_call is deprecated")
if self.content is None:
self.content = ""
return self
def get_executor_batch(self) -> List[TaskBatch]:
"""
获取插件获取对应的无序函数列表,合并新旧标准
"""
_calls = []
if self.function_call:
_calls.append(TaskBatch.from_function_call(self.function_call))
_calls.extend([TaskBatch.from_tool_call(tools) for tools in self.tool_calls])
# 去None
_calls = [_x for _x in _calls if _x]
return _calls
def sign_function(self) -> bool:
"""
判断是否有函数需要执行
"""
if self.function_call:
return True
if self.tool_calls:
for tol in self.tool_calls:
if tol.function:
return True
return False
def request_final(
self,
*,
schema_model: str,
) -> "Message":
return self
class ToolMessage(Message):
role: str = Field(default="tool")
content: str
tool_call_id: str
def request_final(
self,
*,
schema_model: str,
) -> "Message":
return self
class FunctionMessage(Message):
role: str = Field(default="function")
content: str
name: str
def function_validator(self):
logger.warning("Function Message is deprecated by openai")
if self.role == "function" and not self.name:
raise ValidationError(
"sdk param validator:name must be specified when role is function"
)
return self
def request_final(
self,
*,
schema_model: str,
) -> "Message":
"""
Openai 请求标准格式最终转换根据 message_class 元信息锁定字段
:param schema_model: 适配的模型
"""
return self
class CheckError(Exception):
"""
Raised when the API is unavailable.
"""
pass
The provided code snippet includes necessary dependencies for implementing the `parse_message_dict` function. Write a Python function `def parse_message_dict(item: dict)` to solve the following problem:
将 dict 实例化,用错误hook覆盖
Here is the function:
def parse_message_dict(item: dict):
"""
将 dict 实例化,用错误hook覆盖
"""
role = item.get("role", None)
if not role:
return None
try:
if role == "assistant":
_message = AssistantMessage.model_validate(item)
elif role == "user":
_message = UserMessage.model_validate(item)
elif role == "system":
_message = SystemMessage.model_validate(item)
elif role == "tool":
_message = ToolMessage.model_validate(item)
elif role == "function":
_message = FunctionMessage.model_validate(item)
else:
raise CheckError(f"unknown message type {role}")
except Exception as e:
logger.exception(
f"[ParseError]\nparse_message_dict:Unknown message type in redis data:\n{e}"
)
return None
else:
return _message | 将 dict 实例化,用错误hook覆盖 |
962 | import base64
import hashlib
import pickle
import time
from abc import abstractmethod, ABC
from io import BytesIO
from typing import Literal, Optional, List, Type, Union
from typing import TYPE_CHECKING
import aiohttp
import shortuuid
from docstring_parser import parse
from loguru import logger
from pydantic import model_validator, BaseModel, Field, ConfigDict
from .cache import global_cache_runtime
from .error import ValidationError, CheckError
from .utils import sync, aiohttp_download_file
class Message(BaseModel, ABC):
"""
请求体
响应体
"""
class Meta(BaseModel):
# message_class: Literal[None, "system", "user", "assistant", "tool", "function"] = Field(default="user")
index_id: str = Field(default_factory=generate_uid, description="消息ID")
"""消息ID"""
datatime: str = Field(
default=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
description="消息时间",
)
timestamp: int = Field(default=int(time.time()), description="消息时间戳")
"""消息时间"""
retrieval: bool = Field(default=False, description="是否可检索")
"""是否折叠(对抗过长消息,为小上下文模型设计),同时证明我们可以在消息嵌入重整策略"""
extra: dict = Field(default_factory=dict, description="额外信息")
"""额外信息"""
files: List["File"] = Field(default_factory=list, description="文件信息")
"""文件信息"""
def default(cls, message_class):
return cls(message_class=message_class)
_meta: Optional["Meta"] = None
"""元数据"""
role: str
content: Union[str, List[ContentParts], List[dict]]
def get_meta(self) -> Meta:
return self._meta
def update_meta(self, meta: "Meta") -> "Message":
self._meta = meta
return self
def fold(self) -> "Message":
return self
def get_functions(self) -> List["TaskBatch"]:
raise NotImplementedError
def request_final(
self,
schema_model: str,
) -> "Message":
"""
Openai 请求标准格式最终转换根据 message_class 元信息锁定字段
:param schema_model: 适配的模型
"""
raise NotImplementedError
The provided code snippet includes necessary dependencies for implementing the `standardise_for_request` function. Write a Python function `def standardise_for_request(*, message: "Message", schema_model: str) -> "Message"` to solve the following problem:
标准化转换,供请求使用
Here is the function:
def standardise_for_request(*, message: "Message", schema_model: str) -> "Message":
"""
标准化转换,供请求使用
"""
if isinstance(message, dict):
message = Message.model_validate(message)
if hasattr(message, "message"):
return message.request_final(schema_model=schema_model)
else:
return message | 标准化转换,供请求使用 |
963 | import base64
import hashlib
import pickle
import time
from abc import abstractmethod, ABC
from io import BytesIO
from typing import Literal, Optional, List, Type, Union
from typing import TYPE_CHECKING
import aiohttp
import shortuuid
from docstring_parser import parse
from loguru import logger
from pydantic import model_validator, BaseModel, Field, ConfigDict
from .cache import global_cache_runtime
from .error import ValidationError, CheckError
from .utils import sync, aiohttp_download_file
def generate_short_md5(
data: Union[bytes, str, BytesIO],
*,
length: int = 8,
upper: bool = True,
):
assert 0 < length <= 32, "length must be less than 32"
# 计算 MD5 哈希值
md5_hash = hashlib.md5()
if isinstance(data, bytes) or isinstance(data, BytesIO):
if isinstance(data, BytesIO):
data = data.getvalue()
with BytesIO(data) as file:
for chunk in iter(lambda: file.read(4096), b""):
md5_hash.update(chunk)
if isinstance(data, str):
md5_hash.update(data.encode("utf-8"))
# 获取哈希值的 16 进制表示
hex_digest = md5_hash.hexdigest()
# 生成唯一的短ID
short_id = str(hex_digest[:length])
if upper:
short_id = short_id.upper()
return short_id | null |
964 | import cjieba
The provided code snippet includes necessary dependencies for implementing the `cut_words_weights` function. Write a Python function `def cut_words_weights(content)` to solve the following problem:
根据jieba分词,提取关键词及其权重 :param content: :return:
Here is the function:
def cut_words_weights(content):
"""
根据jieba分词,提取关键词及其权重
:param content:
:return:
"""
# jieba提取关键词及其权重
# 设置停用词
# jieba.analyse.set_stop_words('path_of_stopwords')
# tags = jieba.analyse.extract_tags(content, topK=20, withWeight=True)
tags = cjieba.extract(text=content, top_k=20, with_weight=True)
tags = [(keyword, int(weight * 10)) for keyword, weight in tags]
return tags | 根据jieba分词,提取关键词及其权重 :param content: :return: |
965 | import cjieba
The provided code snippet includes necessary dependencies for implementing the `hash_keyword_add_weight` function. Write a Python function `def hash_keyword_add_weight(keyword_weight, len_hash=64)` to solve the following problem:
对关键词进行hash, 然后加权 :param keyword_weight: :param len_hash: :return:
Here is the function:
def hash_keyword_add_weight(keyword_weight, len_hash=64):
"""
对关键词进行hash, 然后加权
:param keyword_weight:
:param len_hash:
:return:
"""
# 关键词hash
keyword_weight = [(bin(hash(keyword)).replace("0b", "").replace("-", "").zfill(len_hash)[-1 * len_hash:], weight)
for keyword, weight in keyword_weight]
# 加权
add_weight = [0] * len_hash
for keyword, weight in keyword_weight:
for i in range(len_hash):
if keyword[i] == "1":
add_weight[i] += weight
else:
add_weight[i] += -1 * weight
result = ""
for _ in add_weight:
if _ >= 0:
result += "1"
else:
result += "0"
return result | 对关键词进行hash, 然后加权 :param keyword_weight: :param len_hash: :return: |
966 | import cjieba
The provided code snippet includes necessary dependencies for implementing the `cal_hamming_distance` function. Write a Python function `def cal_hamming_distance(hash_file1, hash_file2)` to solve the following problem:
计算两篇文章的海明距离 :param hash_file1: :param hash_file2: :return:
Here is the function:
def cal_hamming_distance(hash_file1, hash_file2):
"""
计算两篇文章的海明距离
:param hash_file1:
:param hash_file2:
:return:
"""
hamming_dis = 0
for i in range(len(hash_file1)):
if hash_file1[i] != hash_file2[i]:
hamming_dis += 1
# print("海明距离:", hamming_dis)
return hamming_dis | 计算两篇文章的海明距离 :param hash_file1: :param hash_file2: :return: |
967 |
def singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton | null |
968 | import cjieba
from ..solo import singleton
from ..summarization import STOPWORDS
The provided code snippet includes necessary dependencies for implementing the `load_stopwords` function. Write a Python function `def load_stopwords(stopwords_path)` to solve the following problem:
加载停用词词典 :param stopwords_path: :return:
Here is the function:
def load_stopwords(stopwords_path):
"""
加载停用词词典
:param stopwords_path:
:return:
"""
with open(stopwords_path, encoding='utf-8') as f:
return [line.strip() for line in f] | 加载停用词词典 :param stopwords_path: :return: |
969 | import cjieba
from ..solo import singleton
from ..summarization import STOPWORDS
def split_doc(doc):
separators = ['。', '!', '!', '?', '?']
for sep in separators:
doc = doc.replace(sep, sep + '##')
sentences = doc.split('##')
return sentences[:-1] | null |
970 | import cjieba
from ..solo import singleton
from ..summarization import STOPWORDS
def calculate_sentence_score(sentence, stopwords):
# jieba_ret = jieba.analyse.extract_tags(sentence, topK=100, withWeight=True) # , allowPOS=('ns', 'n', 'vn', 'v'))
jieba_ret = cjieba.extract(sentence, top_k=100, with_weight=True)
sentence_score = 0
for word, score in jieba_ret:
if word not in stopwords:
sentence_score += score
return sentence_score | null |
971 | import cjieba
import numpy as np
from nltk.cluster.util import cosine_distance
from ..solo import singleton
from ..summarization import STOPWORDS as STOPWORDS_PATH
def load_stopwords(file_path):
with open(file_path, encoding='utf-8') as f:
return [line.strip() for line in f] | null |
972 | import cjieba
import numpy as np
from nltk.cluster.util import cosine_distance
from ..solo import singleton
from ..summarization import STOPWORDS as STOPWORDS_PATH
MIN_SEQ_LEN = 0
def split_doc(doc, stopwords=None):
if not stopwords:
stopwords = []
sentences = []
cut_sentences = []
origin_sentences = []
while len(doc) > 0:
for i in range(len(doc)):
if doc[i] in ['。', '!', '?', '?']:
sentences.append(doc[:i + 1])
doc = doc[i + 1:]
break
for sent in sentences:
if len(sent) > MIN_SEQ_LEN:
cut_sentences.append([word for word in cjieba.cut(sent) if word not in stopwords])
origin_sentences.append(sent)
return origin_sentences, cut_sentences | null |
973 | import cjieba
import numpy as np
from nltk.cluster.util import cosine_distance
from ..solo import singleton
from ..summarization import STOPWORDS as STOPWORDS_PATH
def sentence_similarity(sent1, sent2):
"""
计算两个句子之间的相似性
:param sent1:
:param sent2:
:return:
"""
all_words = list(set(sent1 + sent2))
vector1 = [0] * len(all_words)
vector2 = [0] * len(all_words)
for word in sent1:
vector1[all_words.index(word)] += 1
for word in sent2:
vector2[all_words.index(word)] += 1
# cosine_distance 越大越不相似
return 1 - cosine_distance(vector1, vector2)
The provided code snippet includes necessary dependencies for implementing the `build_similarity_matrix` function. Write a Python function `def build_similarity_matrix(sentences)` to solve the following problem:
构建相似矩阵 :param sentences: :return:
Here is the function:
def build_similarity_matrix(sentences):
"""
构建相似矩阵
:param sentences:
:return:
"""
S = np.zeros((len(sentences), len(sentences)))
for idx1 in range(len(sentences)):
for idx2 in range(len(sentences)):
if idx1 == idx2:
continue
S[idx1][idx2] = sentence_similarity(sentences[idx1], sentences[idx2])
# 将矩阵正则化
for idx in range(len(S)):
if S[idx].sum == 0:
continue
S[idx] /= S[idx].sum()
return S | 构建相似矩阵 :param sentences: :return: |
974 | import cjieba
import numpy as np
from nltk.cluster.util import cosine_distance
from ..solo import singleton
from ..summarization import STOPWORDS as STOPWORDS_PATH
def pagerank(A, eps=0.0001, d=0.85):
P = np.ones(len(A)) / len(A)
while True:
new_P = np.ones(len(A)) * (1 - d) / len(A) + d * A.T.dot(P)
delta = abs(new_P - P).sum()
if delta <= eps:
return new_P
P = new_P | null |
975 | import logging
import os
from typing import Dict, Union
import fasttext
import requests
def get_or_load_model(low_memory=False):
if low_memory:
model = models.get("low_mem", None)
if not model:
check_model("lid.176.ftz")
model_path = download_model("lid.176.ftz")
model = fasttext.load_model(model_path)
models["low_mem"] = model
return model
else:
model = models.get("high_mem", None)
if not model:
check_model("lid.176.ftz")
model_path = download_model("lid.176.bin")
model = fasttext.load_model(model_path)
models["high_mem"] = model
return model
def detect(text: str, low_memory=True) -> Dict[str, Union[str, float]]:
model = get_or_load_model(low_memory)
labels, scores = model.predict(text)
label = labels[0].replace("__label__", '')
score = min(float(scores[0]), 1.0)
return {
"lang": label,
"score": score,
} | null |
976 | import time
from typing import TYPE_CHECKING, Literal, Type, Optional
from typing import Union, List
import nest_asyncio
from pydantic import field_validator, ConfigDict, Field, BaseModel
from .sdk.endpoint.tokenizer import get_tokenizer
from .sdk.schema import File, generate_uid, UserMessage, Message
def singleton(cls):
_instance = {}
def inner():
if cls not in _instance:
_instance[cls] = cls()
return _instance[cls]
return inner | null |
977 | random
class MappingDefault(dict):
def __missing__(self, key):
return key
def get_request_error_message(error: str):
_txt: str = random.choice(REQUEST_ERROR_MESSAGE_TEMPLATE)
return _txt.format_map(MappingDefault(error=error)) | null |
978 | random
class MappingDefault(dict):
def __missing__(self, key):
return key
def get_upload_error_message(filename: str, error: str):
_txt: str = random.choice(REQUEST_ERROR_MESSAGE_TEMPLATE)
return _txt.format_map(MappingDefault(filename=filename, error=error)) | null |
979 | from typing import Literal, List, Union
from pydantic import BaseModel, Field, field_validator
SENDER = {}
RECEIVER = {}
def router_set(role: Literal["sender", "receiver"], name: str):
if role == "sender":
SENDER[name] = name
elif role == "receiver":
RECEIVER[name] = name
else:
raise ValueError(f"role must in sender or receiver, not {role}") | null |
980 | import pathlib
from time import sleep
import elara
from rich.console import Console
elara_client = elara.exe(path=pathlib.Path(__file__).parent / "elara.db", commitdb=True)
tutorial = [
{
"cn": "接下来进行一些说明,如果您不想看到这些说明,请使用 --no-tutorial 参数运行入口文件。",
"en": "Next, some instructions will be given. "
"If you don’t want to see these instructions, please run the entry file with the --no-tutorial flag."
},
{
"cn": "请您在 .env 文件中填写您的配置信息。"
"如果您需要配置 provider,请使用 config_dir/provider_settings.toml 文件。"
"您可以通过 `docker-compose up -f docker-compose.yml` 来测试服务。",
"en": "Please fill in your configuration information in the .env file. "
"If you need to configure the provider, please use the config_dir/provider_settings.toml file. "
"You can test the service by `docker-compose up -f docker-compose.yml`."
},
{
"cn": "数据库 RabbitMQ 的默认端口为 5672,Redis 的默认端口为 6379,MongoDB 的默认端口为 27017。"
"请您考虑是否需要添加防火墙配置。其中,RabbitMQ 和 MongoDB 均使用默认配置了密码。请查看 .env 文件进行修改。",
"en": "The default port of the database RabbitMQ is 5672, "
"the default port of Redis is 6379, and the default port of MongoDB is 27017."
"Please consider whether to add firewall configuration. "
"Among them, RabbitMQ and MongoDB use the default configuration password. "
"Please check the .env file for modification."
},
{
"cn": "请当心您的 .env 文件,其中包含了您的敏感信息。请不要将 .env 文件上传到公共仓库。",
"en": "Please be careful with your .env file, "
"which contains your sensitive information. "
"Please do not upload the .env file to the public repository."
},
{
"cn": "请当心您的 日志文件,其中包含了您的敏感信息。请不要将 日志文件上传到公共仓库。",
"en": "Please be careful with your log file, which contains your sensitive information. "
"Please do not upload the log file to the public repository."
},
{
"cn": "如果您在使用过程中遇到了问题,可以在 GitHub 上提出 issue 来完善测试。",
"en": "If you encounter any problems during use, you can raise an issue on GitHub to improve the test."
},
]
tutorial_len = len(tutorial)
def show_tutorial(skip_existing: bool = False, pre_step_stop: int = 5, database_key: str = "55123"):
global tutorial, elara_client, tutorial_len
lens = elara_client.get(database_key)
if skip_existing and str(lens) == str(len(tutorial)):
return None
# 截取未读的条目
tutorial = tutorial[lens:] if skip_existing else tutorial
console = Console()
print("\n")
with console.status("[bold green]Working on tasks...[/bold green]") as status:
index = 0
while tutorial:
info = tutorial.pop(0)
index += 1
console.print(info["cn"], style="bold cyan")
console.print(info["en"], style="bold green", end="\n\n")
for i in range(pre_step_stop):
status.update(
f"[bold green]({index}/{tutorial_len})Remaining {pre_step_stop - i} "
f"seconds to next info... [/bold green] "
)
sleep(1)
# 更新进度
elara_client.set(database_key, tutorial_len)
sleep(3) | null |
981 | from llmkira.setting.discord import BotSetting
BotSetting = DiscordBot()
def help_message():
return """
`{prefix}chat` - Chat with me :)
`{prefix}task` - Ask me do things with `func_enable`
**Slash Command**
`/help` - **You just did it :)**
`/tool` - Check all useful tools
`/clear` - wipe memory of your chat
`/auth` - activate a task (my power)
`/bind` - bind third party platform
`/unbind` - unbind platform
`/set_endpoint` - <apikey>#<endpoint>
`/clear_endpoint` - clear endpoint and key
`/env` - set environment variable
`/token` - bind your service provider token
`/token_clear` - clear your service provider token
`/func_ban` - ban function
`/func_unban` - unban function
**Please confirm that that bot instance is secure, some plugins may be dangerous on unsafe instance.**
""".format(prefix=BotSetting.prefix) | null |
982 | from typing import Tuple, Optional
from urllib.parse import urlparse
from loguru import logger
from ..middleware.chain_box import Chain, AuthReloader
from ..task import Task
The provided code snippet includes necessary dependencies for implementing the `parse_command` function. Write a Python function `def parse_command(command: str) -> Tuple[Optional[str], Optional[str]]` to solve the following problem:
:param command like `/chat something` :return command_head,command_body
Here is the function:
def parse_command(command: str) -> Tuple[Optional[str], Optional[str]]:
"""
:param command like `/chat something`
:return command_head,command_body
"""
assert isinstance(command, str), "Command Must Be Str"
if not command:
return None, None
parts = command.split(" ", 1)
if len(parts) > 1:
return parts[0], parts[1]
elif len(parts) == 1:
return parts[0], None
else:
return None, None | :param command like `/chat something` :return command_head,command_body |
983 | from typing import Tuple, Optional
from urllib.parse import urlparse
from loguru import logger
from ..middleware.chain_box import Chain, AuthReloader
from ..task import Task
The provided code snippet includes necessary dependencies for implementing the `is_valid_url` function. Write a Python function `def is_valid_url(url) -> bool` to solve the following problem:
:param url url :return bool
Here is the function:
def is_valid_url(url) -> bool:
"""
:param url url
:return bool
"""
try:
result = urlparse(url)
return all([result.scheme, result.netloc])
except ValueError:
return False | :param url url :return bool |
984 | from typing import Tuple, Optional
from urllib.parse import urlparse
from loguru import logger
from ..middleware.chain_box import Chain, AuthReloader
from ..task import Task
The provided code snippet includes necessary dependencies for implementing the `is_command` function. Write a Python function `def is_command( text: str, command: str, at_bot_username: str = None, check_empty=False ) -> bool` to solve the following problem:
:param text: message text :param command: command :param at_bot_username: check /command@bot_username :param check_empty: check /command -> False :return: bool
Here is the function:
def is_command(
text: str, command: str, at_bot_username: str = None, check_empty=False
) -> bool:
"""
:param text: message text
:param command: command
:param at_bot_username: check /command@bot_username
:param check_empty: check /command -> False
:return: bool
"""
assert text, "text is empty"
if check_empty:
if len(text.split(" ")) == 1:
return False
if text.startswith(f"{command} "):
return True
if at_bot_username:
if text.startswith(f"{command}@{at_bot_username}"):
return True
if text == command:
return True
return False | :param text: message text :param command: command :param at_bot_username: check /command@bot_username :param check_empty: check /command -> False :return: bool |
985 | from typing import Tuple, Optional
from urllib.parse import urlparse
from loguru import logger
from ..middleware.chain_box import Chain, AuthReloader
from ..task import Task
def is_empty_command(text: str) -> bool:
assert text, "Command Input Must Be Str"
if not text.startswith("/"):
return False
if len(text.split(" ")) == 1:
return True
return False | null |
986 | from typing import Tuple, Optional
from urllib.parse import urlparse
from loguru import logger
from ..middleware.chain_box import Chain, AuthReloader
from ..task import Task
class AuthReloader(object):
"""
重放任务
"""
def __init__(self, uid: str = None):
self.uid = uid
def _prefix(cls, uuid: str) -> str:
"""auth:{auth_schema_version}:uuid"""
return f"auth:v2:{uuid}"
def from_form(cls, platform: str, user_id: str):
_c = cls()
_c.uid = f"{platform}:{user_id}"
return _c
async def save_auth(self,
chain: Chain,
timeout: int = 60 * 60 * 24
):
cache = global_cache_runtime.get_redis()
logger.debug("Resign Auth Point")
assert chain.creator_uid == self.uid, "Cant Resign Uid Diff From `self`"
_cache = await cache.set_data(
key=self._prefix(uuid=chain.uuid),
value=chain.model_dump_json(),
timeout=timeout
)
return chain.uuid
async def read_auth(self, uuid: str) -> Optional[Chain]:
cache = global_cache_runtime.get_redis()
_cache = await cache.read_data(key=self._prefix(uuid=uuid))
if not _cache:
return None
logger.debug(f"Get Auth Data {_cache} {_cache}")
chain = Chain.from_redis(_cache)
if chain.is_expire:
logger.debug(f"Auth Expire {chain.uuid}")
return None
if chain.creator_uid != self.uid:
logger.debug(f"Not User {self.uid} Created Auth")
return None
return chain
class Task(object):
def __init__(self, *,
queue: str,
amqp_dsn: str = None
):
"""
:param queue: 队列名字
:param amqp_dsn: 队列数据库
"""
self.queue_name = queue
if amqp_dsn is None:
from ..setting.rabbitmq import RabbitMQSetting
amqp_dsn = RabbitMQSetting.amqp_dsn
self._amqp_url = amqp_dsn
async def send_task(self, task: TaskHeader):
connection = await aio_pika.connect_robust(self._amqp_url)
async with connection:
channel = await connection.channel(
publisher_confirms=True # 消息确认
)
# 通道超时 2s
# await channel.initialize(timeout=2000)
# Creating a message
message = Message(
body=task.model_dump_json().encode("utf-8"),
delivery_mode=DeliveryMode.PERSISTENT,
expiration=EXPIRATION_SECOND
)
# Declaring queue
try:
await channel.declare_queue(
self.queue_name,
arguments=QUEUE_ARGUMENTS,
durable=True # 持续化
)
except Exception as e:
logger.error(
f"[5941163]Rabbitmq Queue param validation error, try deleting the abnormal "
f"queue manually and retrying. "
f"\n--error {e}"
f"\n--help |web: <database_ip>:15672/#/ |shell: `rabbitmqctl delete_queue {self.queue_name}`"
)
raise e
# Sending the message
try:
confirmation = await channel.default_exchange.publish(
message,
routing_key=self.queue_name,
timeout=10
)
except DeliveryError as e:
logger.error(f"[502231]Task Delivery failed with exception: {e.reason}")
return False, "🔭 Sorry,failure to reach the control centre, possibly i reach design limit 🧯"
except TimeoutError:
logger.error(f"[528532]Task Delivery timeout")
return False, "🔭 Sorry, failure to reach the control centre, ⏱ timeout"
else:
if not isinstance(confirmation, Basic.Ack):
logger.error(f"[552123]Task Delivery failed with confirmation")
return False, "🔭 Sorry, failure to reach the control centre, sender error"
else:
logger.info("[621132]Task sent success")
return True, "Task sent success"
async def consuming_task(self, func: callable):
connection = await aio_pika.connect_robust(self._amqp_url)
async with connection:
# Creating a channel
channel = await connection.channel()
# 通道超时 1s
# await channel.initialize(timeout=1000)
await channel.set_qos(prefetch_count=CONSUMER_PREFETCH_COUNT) # 消息流控
# Declaring queue
try:
queue = await channel.declare_queue(
self.queue_name,
arguments=QUEUE_ARGUMENTS,
durable=True # 持续化
)
except Exception as e:
logger.error(
f"[502231]Rabbitmq Queue parameter validation failed, try deleting the abnormal queue manually "
f"and retrying."
f"\n--error {e}"
f"\n--help |web: <database_ip>:15672/#/ |shell: `rabbitmqctl delete_queue {self.queue_name}`"
)
raise e
await queue.consume(func)
await asyncio.Future() # run forever
async def create_and_send(cls,
*,
queue_name: str,
task: TaskHeader
):
sender = cls(queue=queue_name)
await sender.send_task(task=task)
return sender
The provided code snippet includes necessary dependencies for implementing the `auth_reloader` function. Write a Python function `async def auth_reloader(uuid: str, platform: str, user_id: str) -> None` to solve the following problem:
:param uuid: verify id :param platform: message channel :param user_id: raw user id :raise LookupError Not Found :return None
Here is the function:
async def auth_reloader(uuid: str, platform: str, user_id: str) -> None:
"""
:param uuid: verify id
:param platform: message channel
:param user_id: raw user id
:raise LookupError Not Found
:return None
"""
assert isinstance(uuid, str), "`uuid` Must Be Str"
assert isinstance(platform, str), "`platform` Must Be Str"
assert isinstance(user_id, str), "`user_id` Must Be Str"
chain: Chain = await AuthReloader.from_form(
platform=platform, user_id=user_id
).read_auth(uuid=uuid)
if not chain:
raise LookupError("Auth Task Not Found")
logger.info(f"Auth Task Sent --task uuid {uuid} --user {user_id}")
await Task(queue=chain.channel).send_task(task=chain.arg) | :param uuid: verify id :param platform: message channel :param user_id: raw user id :raise LookupError Not Found :return None |
987 | from dotenv import load_dotenv
from loguru import logger
class StartSetting(BaseModel):
def from_subdir(cls):
global_cache_runtime: RedisRuntime = RedisRuntime()
global_mongodb_runtime: MongodbRuntime = MongodbRuntime()
class TelegramBotRunner(Runner):
def __init__(self):
async def is_user_admin(self, message: types.Message):
async def upload(self, file, uid: str):
async def run(self):
async def create_task(message: types.Message, funtion_enable: bool = False):
async def listen_clear_endpoint_command(message: types.Message):
async def listen_set_endpoint_command(message: types.Message):
async def listen_func_ban_command(message: types.Message):
async def listen_func_unban_command(message: types.Message):
async def listen_token_command(message: types.Message):
async def listen_token_clear_command(message: types.Message):
async def listen_bind_command(message: types.Message):
async def listen_unbind_command(message: types.Message):
async def listen_env_command(message: types.Message):
async def listen_clear_command(message: types.Message):
async def listen_help_command(message: types.Message):
async def listen_tool_command(message: types.Message):
async def listen_auth_command(message: types.Message):
async def handle_private_msg(message: types.Message):
async def handle_group_msg(message: types.Message):
class DiscordBotRunner(Runner):
def __init__(self):
async def upload(self, attachment: hikari.Attachment, uid: str):
async def run(self):
async def create_task(message: hikari.Message, funtion_enable: bool = False):
async def endpoint_autocomplete(
ctx: crescent.AutocompleteContext, option: hikari.AutocompleteInteractionOption
) -> List[Tuple[str, str]]:
async def listen_token_clear_command(ctx: crescent.Context):
async def listen_token_command(
ctx: crescent.Context,
token: str,
):
async def listen_func_unban_command(
ctx: crescent.Context,
func_name: str
):
async def listen_func_ban_command(
ctx: crescent.Context,
func_name: str,
):
async def listen_clear_endpoint_command(ctx: crescent.Context):
async def listen_endpoint_command(
ctx: crescent.Context,
endpoint: Annotated[str, crescent.Autocomplete[endpoint_autocomplete]],
openai_key: str,
model_name: str
):
async def listen_bind_command(ctx: crescent.Context, token: str):
async def listen_unbind_command(ctx: crescent.Context, token: str):
async def listen_clear_command(ctx: crescent.Context):
async def listen_help_command(ctx: crescent.Context):
async def listen_auth_command(ctx: crescent.Context, uuid: str):
async def listen_tool_command(ctx: crescent.Context):
async def listen_env_command(ctx: crescent.Context, env_string: str):
async def on_guild_create(event_: hikari.GuildMessageCreateEvent):
async def on_dm_create(event_: hikari.DMMessageCreateEvent):
class KookBotRunner(Runner):
def __init__(self):
async def upload(self,
file_info: dict,
uid: str
):
async def run(self):
async def create_task(_event: Message, funtion_enable: bool = False):
async def listen_clear_endpoint_command(msg: Message):
async def listen_endpoint_command(
msg: Message,
openai_endpoint: str,
openai_key: str,
model: str
):
async def listen_token_clear_command(msg: Message):
async def listen_token_command(
msg: Message,
token: str
):
async def listen_func_ban_command(
msg: Message,
func_name: str
):
async def listen_func_unban_command(
msg: Message,
func_name: str
):
async def listen_bind_command(msg: Message, dsn: str):
async def listen_unbind_command(msg: Message, dsn: str):
async def listen_clear_command(msg: Message):
async def listen_help_command(msg: Message):
async def listen_tool_command(msg: Message):
async def listen_auth_command(msg: Message, uuid: str):
async def listen_env_command(msg: Message, env_string: str):
async def on_guild_create(msg: PublicMessage):
async def on_dm_create(msg: PrivateMessage):
async def handle_message(event_: Message):
class SlackBotRunner(Runner):
def __init__(self):
async def upload(self, file: SlackMessageEvent.SlackFile, uid: str):
async def run(self):
async def create_task(event_: SlackMessageEvent, funtion_enable: bool = False):
async def listen_clear_endpoint_command(ack: AsyncAck, respond: AsyncRespond, command):
async def listen_set_endpoint_command(ack: AsyncAck, respond: AsyncRespond, command):
async def listen_func_ban_command(ack: AsyncAck, respond: AsyncRespond, command):
async def listen_func_unban_command(ack: AsyncAck, respond: AsyncRespond, command):
async def listen_token_command(ack: AsyncAck, respond: AsyncRespond, command):
async def listen_unbind_command(ack: AsyncAck, respond: AsyncRespond, command):
async def listen_bind_command(ack: AsyncAck, respond: AsyncRespond, command):
async def listen_unbind_command(ack: AsyncAck, respond: AsyncRespond, command):
async def listen_env_command(ack: AsyncAck, respond: AsyncRespond, command):
async def listen_clear_command(ack: AsyncAck, respond: AsyncRespond, command):
async def listen_help_command(ack: AsyncAck, respond: AsyncRespond, command):
async def listen_tool_command(ack: AsyncAck, respond: AsyncRespond, command):
async def auth_chain(uuid, user_id):
async def listen_auth_command(ack: AsyncAck, respond: AsyncRespond, command):
async def validate_join(event_: SlackMessageEvent):
async def deal_group(event_: SlackMessageEvent):
async def listen_im(_event, _logger):
def run():
import asyncio
from llmkira import load_plugins
from llmkira.sdk import load_from_entrypoint, get_entrypoint_plugins
from llmkira.setting import StartSetting
from llmkira.sdk.cache import global_cache_runtime, global_mongodb_runtime
global_cache_runtime.init_cache(verbose=True)
global_mongodb_runtime.init_mongodb(verbose=True)
from .rss import RssAppRunner
start_setting = StartSetting.from_subdir()
wait_list = [RssAppRunner().run(interval=60 * 60 * 1)]
if start_setting.telegram:
from .telegram import TelegramBotRunner
wait_list.append(TelegramBotRunner().run())
if start_setting.discord:
from .discord import DiscordBotRunner
wait_list.append(DiscordBotRunner().run())
if start_setting.kook:
from .kook import KookBotRunner
wait_list.append(KookBotRunner().run())
if start_setting.slack:
from .slack import SlackBotRunner
wait_list.append(SlackBotRunner().run())
# 初始化插件系统
load_plugins("llmkira/extra/plugins")
load_from_entrypoint("llmkira.extra.plugin")
loaded_message = "\n >>".join(get_entrypoint_plugins())
logger.success(f"\n===========Third Party Plugins Loaded==========\n >>{loaded_message}")
async def _main(wait_list_):
await asyncio.gather(
*wait_list_
)
loop = asyncio.get_event_loop()
loop.run_until_complete(_main(wait_list_=wait_list)) | null |
988 | from llmkira.setting.discord import BotSetting
BotSetting = DiscordBot()
def help_message():
return """
`{prefix}chat` - Chat with me :)
`{prefix}task` - Ask me do things with `func_enable`
**Slash Command**
`/help` - **You just did it :)**
`/tool` - Check all useful tools
`/clear` - wipe memory of your chat
`/auth` - activate a task (my power)
`/bind` - bind third party platform
`/unbind` - unbind platform
`/set_endpoint` - set endpoint
`/clear_endpoint` - clear endpoint and key
`/env` - set environment variable
`/token` - bind your service provider token
`/token_clear` - clear your service provider token
`/func_ban` - ban function
`/func_unban` - unban function
**Please confirm that that bot instance is secure, some plugins may be dangerous on unsafe instance.**
""".format(prefix=BotSetting.prefix) | null |
989 | from pydantic import ConfigDict, BaseModel
def help_message():
return """
*Command*
!chat - chat with me in a serious way :(
@<myname> - Chat with me in a simple way :)
!task - chat with function_enable
!ask - chat with function_disable
!auth - Auth a task
*Slash Command*
`/help` - Help message
`/tool` - Tool list
`/clear` - forget...you
`/auth` - activate a task (my power),but outside the thread
`/bind` - RssUrl.....
`/unbind` - RssUrl.....
`/set_endpoint` - <apikey>#<endpoint> for your own backend
`/clear_endpoint` - clear endpoint and key
`/env` - set environment variable
`/token` - bind your service provider token
`/token_clear` - clear your service provider token
`/func_ban` - ban function
`/func_unban` - unban function
Make sure you invite me before you call me in channel, wink~
*DONT SHARE YOUR TOKEN/ENDPOINT PUBLIC!*
- Please confirm that that bot instance is secure, some plugins may be dangerous on unsafe instance.
""" | null |
990 |
def help_message():
return """
/help - HELP YOURSELF
/chat - Chat with me :)
/task - Function enable
/ask - Chat with func_disable, 禁止函数
/tool - 工具列表
/clear - 删除自己的记录
/auth - POWER
Private Chat Only:
/bind - RSS
/unbind - RSS
/set_endpoint - <apikey>#<endpoint>
/clear_endpoint - Clear endpoint and key
/env - 配置变量,use as shell
/token - bind your token
/token_clear - clear your token
/func_ban - ban function
/func_unban - unban function
!Please confirm that that bot instance is secure, some plugins may be dangerous on unsafe instance.
""" | null |
991 | import socket
import feedparser
from inscriptis import get_text
from loguru import logger
from pydantic import BaseModel
from telebot import formatting
from telebot.formatting import escape_markdown
from ..schema import Runner
from ...sdk.cache import global_cache_runtime
from ...task import Task, TaskHeader
from ...middleware.router import RouterManager
from ...middleware.router.schema import router_set
def sha1(string: str):
import hashlib
_sha1 = hashlib.sha1()
_sha1.update(string.encode('utf-8'))
return _sha1.hexdigest()[:10] | null |
992 | import os
import subprocess
import time
from setuptools import find_packages, setup
The provided code snippet includes necessary dependencies for implementing the `readme` function. Write a Python function `def readme()` to solve the following problem:
Get readme. Returns: str, readme content string.
Here is the function:
def readme():
"""Get readme.
Returns:
str, readme content string.
"""
with open('README.md') as fid:
content = fid.read()
return content | Get readme. Returns: str, readme content string. |
993 | import os
import subprocess
import time
from setuptools import find_packages, setup
SHORT_VERSION = '{}.{}.{}{}'.format(MAJOR, MINOR, PATCH, SUFFIX)
VERSION_FILE = 'pyretri/version.py'
def get_hash():
"""Get hash value.
Returns:
str, hash value.
"""
if os.path.exists('.git'):
sha = get_git_hash()[:7]
elif os.path.exists(VERSION_FILE):
try:
from pyretri.version import __version__
sha = __version__.split('+')[-1]
except ImportError:
raise ImportError('Unable to get git version')
else:
sha = 'unknown'
return sha
The provided code snippet includes necessary dependencies for implementing the `write_version_py` function. Write a Python function `def write_version_py()` to solve the following problem:
Write version.py.
Here is the function:
def write_version_py():
"""Write version.py.
"""
content = """# GENERATED VERSION FILE
# TIME: {}
__version__ = '{}'
short_version = '{}'
"""
sha = get_hash()
version = SHORT_VERSION + '+' + sha
with open(VERSION_FILE, 'w') as fid:
fid.write(content.format(time.asctime(), version, SHORT_VERSION)) | Write version.py. |
994 | import os
import subprocess
import time
from setuptools import find_packages, setup
VERSION_FILE = 'pyretri/version.py'
The provided code snippet includes necessary dependencies for implementing the `get_version` function. Write a Python function `def get_version()` to solve the following problem:
Get version. Returns: str, version string.
Here is the function:
def get_version():
"""Get version.
Returns:
str, version string.
"""
with open(VERSION_FILE, 'r') as fid:
exec (compile(fid.read(), VERSION_FILE, 'exec'))
return locals()['__version__'] | Get version. Returns: str, version string. |
995 | import os
import subprocess
import time
from setuptools import find_packages, setup
The provided code snippet includes necessary dependencies for implementing the `parse_requirements` function. Write a Python function `def parse_requirements(fname='requirements.txt', with_version=True)` to solve the following problem:
Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: python -c "import setup; print(setup.parse_requirements())"
Here is the function:
def parse_requirements(fname='requirements.txt', with_version=True):
"""
Parse the package dependencies listed in a requirements file but strips
specific versioning information.
Args:
fname (str): path to requirements file
with_version (bool, default=False): if True include version specs
Returns:
List[str]: list of requirements items
CommandLine:
python -c "import setup; print(setup.parse_requirements())"
"""
import sys
from os.path import exists
import re
require_fpath = fname
def parse_line(line):
"""
Parse information from a line in a requirements text file
"""
if line.startswith('-r '):
# Allow specifying requirements in other files
target = line.split(' ')[1]
for info in parse_require_file(target):
yield info
else:
info = {'line': line}
if line.startswith('-e '):
info['package'] = line.split('#egg=')[1]
else:
# Remove versioning from the package
pat = '(' + '|'.join(['>=', '==', '>']) + ')'
parts = re.split(pat, line, maxsplit=1)
parts = [p.strip() for p in parts]
info['package'] = parts[0]
if len(parts) > 1:
op, rest = parts[1:]
if ';' in rest:
# Handle platform specific dependencies
# http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
version, platform_deps = map(str.strip,
rest.split(';'))
info['platform_deps'] = platform_deps
else:
version = rest # NOQA
info['version'] = (op, version)
yield info
def parse_require_file(fpath):
with open(fpath, 'r') as f:
for line in f.readlines():
line = line.strip()
if line and not line.startswith('#'):
for info in parse_line(line):
yield info
def gen_packages_items():
if exists(require_fpath):
for info in parse_require_file(require_fpath):
parts = [info['package']]
if with_version and 'version' in info:
parts.extend(info['version'])
if not sys.version.startswith('3.4'):
# apparently package_deps are broken in 3.4
platform_deps = info.get('platform_deps')
if platform_deps is not None:
parts.append(';' + platform_deps)
item = ''.join(parts)
yield item
packages = list(gen_packages_items())
return packages | Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: python -c "import setup; print(setup.parse_requirements())" |
996 | import os
import argparse
import importlib
from pyretri.config import get_defaults_cfg
from pyretri.datasets import build_folder, build_loader
from pyretri.models import build_model
from pyretri.extract import build_extract_helper
def load_datasets():
data_json_dir = "/home/songrenjie/projects/RetrievalToolBox/new_data_jsons/"
datasets = {
"oxford_gallery": os.path.join(data_json_dir, "oxford_gallery.json"),
"oxford_query": os.path.join(data_json_dir, "oxford_query.json"),
"cub_gallery": os.path.join(data_json_dir, "cub_gallery.json"),
"cub_query": os.path.join(data_json_dir, "cub_query.json"),
"indoor_gallery": os.path.join(data_json_dir, "indoor_gallery.json"),
"indoor_query": os.path.join(data_json_dir, "indoor_query.json"),
"caltech_gallery": os.path.join(data_json_dir, "caltech_gallery.json"),
"caltech_query": os.path.join(data_json_dir, "caltech_query.json"),
"paris_all": os.path.join(data_json_dir, "paris.json"),
}
for data_path in datasets.values():
assert os.path.exists(data_path), "non-exist dataset path {}".format(data_path)
return datasets | null |
997 | import os
import argparse
import importlib
from pyretri.config import get_defaults_cfg
from pyretri.datasets import build_folder, build_loader
from pyretri.models import build_model
from pyretri.extract import build_extract_helper
def parse_args():
parser = argparse.ArgumentParser(description='A tool box for deep learning-based image retrieval')
parser.add_argument('opts', default=None, nargs=argparse.REMAINDER)
parser.add_argument('--save_path', '-sp', default=None, type=str, help="the save path for feature")
parser.add_argument("--search_modules", "-sm", default="", type=str, help="name of search module's directory")
args = parser.parse_args()
return args | null |
998 | import json
import importlib
import os
import argparse
from utils.misc import check_result_exist, get_dir, get_default_result_dict
from pyretri.config import get_defaults_cfg
from pyretri.index import build_index_helper, feature_loader
from pyretri.evaluate import build_evaluate_helper
def load_datasets():
datasets = {
"market_gallery": {
"gallery": "market_gallery",
"query": "market_query",
"train": "market_gallery"
},
"duke_gallery": {
"gallery": "duke_gallery",
"query": "duke_query",
"train": "duke_gallery"
},
}
return datasets | null |
999 | import json
import importlib
import os
import argparse
from utils.misc import check_result_exist, get_dir, get_default_result_dict
from pyretri.config import get_defaults_cfg
from pyretri.index import build_index_helper, feature_loader
from pyretri.evaluate import build_evaluate_helper
def parse_args():
parser = argparse.ArgumentParser(description='A tool box for deep learning-based image retrieval')
parser.add_argument('--fea_dir', '-fd', default=None, type=str, help="path of feature dirs", required=True)
parser.add_argument("--search_modules", "-sm", default=None, type=str, help="name of search module's directory")
parser.add_argument("--save_path", "-sp", default=None, type=str, help="path for saving results")
args = parser.parse_args()
return args | null |
1,000 | import json
import importlib
import os
import argparse
from utils.misc import check_result_exist, get_dir, get_default_result_dict
from pyretri.config import get_defaults_cfg
from pyretri.index import build_index_helper, feature_loader
from pyretri.evaluate import build_evaluate_helper
def load_datasets():
datasets = {
"oxford_gallery": {
"gallery": "oxford_gallery",
"query": "oxford_query",
"train": "paris_all"
},
"cub_gallery": {
"gallery": "cub_gallery",
"query": "cub_query",
"train": "cub_gallery"
},
"indoor_gallery": {
"gallery": "indoor_gallery",
"query": "indoor_query",
"train": "indoor_gallery"
},
"caltech_gallery": {
"gallery": "caltech_gallery",
"query": "caltech_query",
"train": "caltech_gallery"
}
}
return datasets | null |
1,001 | import json
import importlib
import os
import argparse
from utils.misc import check_result_exist, get_dir, get_default_result_dict
from pyretri.config import get_defaults_cfg
from pyretri.index import build_index_helper, feature_loader
from pyretri.evaluate import build_evaluate_helper
def get_evaluate(fea_dir, evaluates):
if "oxford" in fea_dir:
evaluate = evaluates["oxford_overall"]
else:
evaluate = evaluates["overall"]
return evaluate | null |
1,002 | import json
import importlib
import os
import argparse
from utils.misc import check_result_exist, get_dir, get_default_result_dict
from pyretri.config import get_defaults_cfg
from pyretri.index import build_index_helper, feature_loader
from pyretri.evaluate import build_evaluate_helper
vgg_fea = ["pool5_PWA"]
res_fea = ["pool5_PWA"]
def get_fea_names(fea_dir):
if "vgg" in fea_dir:
fea_names = vgg_fea
else:
fea_names = res_fea
return fea_names | null |
1,004 | import os
import torch
import argparse
import importlib
from pyretri.config import get_defaults_cfg
from pyretri.datasets import build_folder, build_loader
from pyretri.models import build_model
from pyretri.extract import build_extract_helper
from pyretri.models.backbone import ft_net
def load_datasets():
data_json_dir = "/home/songrenjie/projects/RetrievalToolBox/new_data_jsons/"
datasets = {
"market_gallery": os.path.join(data_json_dir, "market_gallery.json"),
"market_query": os.path.join(data_json_dir, "market_query.json"),
"duke_gallery": os.path.join(data_json_dir, "duke_gallery.json"),
"duke_query": os.path.join(data_json_dir, "duke_query.json"),
}
for data_path in datasets.values():
assert os.path.exists(data_path), "non-exist dataset path {}".format(data_path)
return datasets | null |
1,005 | import os
import torch
import argparse
import importlib
from pyretri.config import get_defaults_cfg
from pyretri.datasets import build_folder, build_loader
from pyretri.models import build_model
from pyretri.extract import build_extract_helper
from pyretri.models.backbone import ft_net
def parse_args():
parser = argparse.ArgumentParser(description='A tool box for deep learning-based image retrieval')
parser.add_argument('opts', default=None, nargs=argparse.REMAINDER)
parser.add_argument('--save_path', '-sp', default=None, type=str, help="the save path for feature")
parser.add_argument("--search_modules", "-sm", default="", type=str, help="name of search module's directory")
args = parser.parse_args()
return args | null |
1,007 | import os
import argparse
import importlib
from pyretri.config import get_defaults_cfg
from pyretri.datasets import build_folder, build_loader
from pyretri.models import build_model
from pyretri.extract import build_extract_helper
def parse_args():
parser = argparse.ArgumentParser(description='A tool box for deep learning-based image retrieval')
parser.add_argument('opts', default=None, nargs=argparse.REMAINDER)
parser.add_argument('--save_path', '-sp', default=None, type=str, help="save path for feature")
parser.add_argument("--search_modules", "-sm", default=None, type=str, help="name of search module's directory")
args = parser.parse_args()
return args | null |
1,008 | import os
import argparse
import json
import codecs
from utils.misc import save_to_csv, filter_by_keywords
def parse_args():
parser = argparse.ArgumentParser(description='A tool box for deep learning-based image retrieval')
parser.add_argument('opts', default=None, nargs=argparse.REMAINDER)
parser.add_argument('--results_json_path', '-r', default=None, type=str, help="path of the result json")
args = parser.parse_args()
return args | null |
1,009 | import os
import argparse
import json
import codecs
from utils.misc import save_to_csv, filter_by_keywords
def show_results(results):
for i in range(len(results)):
print(results[i]) | null |
1,010 | import os
from typing import Dict, List
import csv
The provided code snippet includes necessary dependencies for implementing the `check_result_exist` function. Write a Python function `def check_result_exist(now_res: Dict, exist_results: List) -> bool` to solve the following problem:
Check if the config exists. Args: now_res (Dict): configuration to be checked. exist_results (List): a list of existing configurations. Returns: bool: if the config exists.
Here is the function:
def check_result_exist(now_res: Dict, exist_results: List) -> bool:
"""
Check if the config exists.
Args:
now_res (Dict): configuration to be checked.
exist_results (List): a list of existing configurations.
Returns:
bool: if the config exists.
"""
for e_r in exist_results:
totoal_equal = True
for key in now_res:
if now_res[key] != e_r[key]:
totoal_equal = False
break
if totoal_equal:
return True
return False | Check if the config exists. Args: now_res (Dict): configuration to be checked. exist_results (List): a list of existing configurations. Returns: bool: if the config exists. |
1,011 | import os
from typing import Dict, List
import csv
The provided code snippet includes necessary dependencies for implementing the `get_dir` function. Write a Python function `def get_dir(root_path: str, dir: str, dataset: Dict) -> (str, str, str)` to solve the following problem:
Get the feature directory path of gallery set, query set and feature set for training PCA/SVD. Args: root_path (str): the root path of all extracted features. dir (str): the path of one single extracted feature directory. dataset (Dict): a dict containing the information of gallery set, query set and training set. Returns: tuple(str, str, str): path of gallery set, query set and feature set for training PCA/SVD.
Here is the function:
def get_dir(root_path: str, dir: str, dataset: Dict) -> (str, str, str):
"""
Get the feature directory path of gallery set, query set and feature set for training PCA/SVD.
Args:
root_path (str): the root path of all extracted features.
dir (str): the path of one single extracted feature directory.
dataset (Dict): a dict containing the information of gallery set, query set and training set.
Returns:
tuple(str, str, str): path of gallery set, query set and feature set for training PCA/SVD.
"""
template_dir = os.path.join(root_path, dir)
target = dir.split('_')[0] + '_' + dir.split('_')[1]
gallery_fea_dir = template_dir.replace(target, dataset["gallery"])
query_fea_dir = template_dir.replace(target, dataset["query"])
train_fea_dir = template_dir.replace(target, dataset["train"])
return gallery_fea_dir, query_fea_dir, train_fea_dir | Get the feature directory path of gallery set, query set and feature set for training PCA/SVD. Args: root_path (str): the root path of all extracted features. dir (str): the path of one single extracted feature directory. dataset (Dict): a dict containing the information of gallery set, query set and training set. Returns: tuple(str, str, str): path of gallery set, query set and feature set for training PCA/SVD. |
Subsets and Splits