Spaces:
Sleeping
Sleeping
| from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool | |
| import datetime | |
| import requests | |
| import pytz | |
| import yaml | |
| from tools.final_answer import FinalAnswerTool | |
| from Gradio_UI import GradioUI | |
| # Below is an example of a tool that does nothing. Amaze us with your creativity ! | |
| def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type | |
| #Keep this format for the description / args / args description but feel free to modify the tool | |
| """A tool that does nothing yet | |
| Args: | |
| arg1: the first argument | |
| arg2: the second argument | |
| """ | |
| return "What magic will you build ?" | |
| def get_current_time_in_timezone(timezone: str) -> str: | |
| """A tool that fetches the current local time in a specified timezone. | |
| Args: | |
| timezone: A string representing a valid timezone (e.g., 'America/New_York'). | |
| """ | |
| try: | |
| # Create timezone object | |
| tz = pytz.timezone(timezone) | |
| # Get current time in that timezone | |
| local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") | |
| return f"The current local time in {timezone} is: {local_time}" | |
| except Exception as e: | |
| return f"Error fetching time for timezone '{timezone}': {str(e)}" | |
| import numpy as np | |
| def matrix_multiplication(matrix_a: list[list[float]], matrix_b: list[list[float]]) -> list[list[float]]: | |
| """计算两个矩阵的乘积。 | |
| 此工具接受两个矩阵(表示为浮点数列表的列表)作为输入,并返回它们的乘积。 | |
| 它要求矩阵是有效的乘法(即,第一个矩阵的列数必须等于第二个矩阵的行数)。 | |
| Args: | |
| matrix_a: 第一个矩阵,表示为浮点数列表的列表。 | |
| matrix_b: 第二个矩阵,表示为浮点数列表的列表。 | |
| """ | |
| try: | |
| # 将列表的列表转换为 numpy 数组以实现高效的矩阵乘法 | |
| np_matrix_a = np.array(matrix_a) | |
| np_matrix_b = np.array(matrix_b) | |
| # 执行矩阵乘法 | |
| result_matrix = np.matmul(np_matrix_a, np_matrix_b) | |
| # 将结果转换回列表的列表以符合返回类型 | |
| return result_matrix.tolist() | |
| except ValueError as e: | |
| # 处理矩阵维度不兼容导致无法乘法的情况 | |
| raise ValueError(f"矩阵乘法错误:{e}。请确保第一个矩阵的列数等于第二个矩阵的行数。") | |
| except Exception as e: | |
| # 捕获任何其他意外错误 | |
| raise Exception(f"矩阵乘法过程中发生意外错误:{e}") | |
| import numpy as np | |
| from decimal import Decimal, getcontext # 用于精确控制小数位数 | |
| def solve_linear_equations(coefficients: list[list[float]], constants: list[float]) -> dict: | |
| """求解多元一次线性方程组。 | |
| 此工具接受一个系数矩阵和一个常数向量作为输入,并尝试求解由它们表示的线性方程组。 | |
| 方程组的通用形式为 Ax = B,其中 A 是 coefficients,B 是 constants。 | |
| 如果方程组有唯一的解,函数将返回一个字典,其中包含变量名(默认从 x1 开始)和它们对应的解。 | |
| 解会以字符串形式表示,对于浮点数保留两位小数。 | |
| Args: | |
| coefficients: 系数矩阵,表示为浮点数列表的列表。例如,对于 2x + 3y = 7, x - y = 1, | |
| 系数矩阵为 [[2, 3], [1, -1]]。 | |
| constants: 常数向量,表示为浮点数的列表。例如,对于上述方程组,常数向量为 [7, 1]。 | |
| """ | |
| try: | |
| np_coefficients = np.array(coefficients) | |
| np_constants = np.array(constants) | |
| # 检查矩阵是否为方阵,以及常数向量的维度是否匹配 | |
| if np_coefficients.shape[0] != np_coefficients.shape[1]: | |
| raise ValueError("系数矩阵必须是方阵(行数和列数必须相等),才能有唯一解。") | |
| if np_coefficients.shape[0] != np_constants.shape[0]: | |
| raise ValueError("系数矩阵的行数必须与常数向量的元素数量相等。") | |
| # 使用 numpy 求解线性方程组 | |
| solutions = np.linalg.solve(np_coefficients, np_constants) | |
| # 设置 Decimal 的精度,用于控制小数位数 | |
| getcontext().prec = 50 # 设置一个足够大的精度,以防止中间计算的损失 | |
| results = {} | |
| for i, sol in enumerate(solutions): | |
| var_name = f"x_{i+1}" | |
| # 使用 Decimal 进行精确的四舍五入到两位小数 | |
| # 先转换为 Decimal,然后使用 quantize 方法 | |
| decimal_sol = Decimal(str(sol)) # 将浮点数转换为字符串再转换为Decimal,以避免浮点数精度问题 | |
| # 将小数部分量化到小数点后两位 | |
| # ROUND_HALF_UP 是四舍五入到最近的值,如果距离相等,则向上进位 | |
| # '0.01' 表示两位小数的精度 | |
| formatted_sol = decimal_sol.quantize(Decimal('0.01'), rounding='ROUND_HALF_UP') | |
| # 检查是否为整数或者浮点数 | |
| if formatted_sol == formatted_sol.to_integral_value(): | |
| # 如果是整数,显示为整数 | |
| results[var_name] = str(int(formatted_sol)) | |
| else: | |
| # 否则,显示为两位小数 | |
| results[var_name] = str(formatted_sol) | |
| # 注意此版本不直接处理“分式”输出。如果需要分式,需要使用类似 SymPy 的符号计算库。 | |
| # 这里对于小数,我们提供格式化为两位小数的字符串。 | |
| return results | |
| except np.linalg.LinAlgError: | |
| # 捕获方程组无解或有无穷多解的情况 | |
| raise ValueError("方程组无唯一解(可能无解或有无穷多解)。") | |
| except ValueError as e: | |
| # 捕获因输入维度不匹配或其他问题引起的 ValueError | |
| raise ValueError(f"输入错误:{e}") | |
| except Exception as e: | |
| # 捕获其他所有意外错误 | |
| raise Exception(f"求解线性方程组时发生意外错误:{e}") | |
| final_answer = FinalAnswerTool() | |
| # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder: | |
| # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' | |
| model = HfApiModel( | |
| max_tokens=2096, | |
| temperature=0.5, | |
| model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded | |
| custom_role_conversions=None, | |
| ) | |
| # Import tool from Hub | |
| image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) | |
| with open("prompts.yaml", 'r') as stream: | |
| prompt_templates = yaml.safe_load(stream) | |
| agent = CodeAgent( | |
| model=model, | |
| tools=[final_answer], ## add your tools here (don't remove final answer) | |
| max_steps=6, | |
| verbosity_level=1, | |
| grammar=None, | |
| planning_interval=None, | |
| name=None, | |
| description=None, | |
| prompt_templates=prompt_templates | |
| ) | |
| GradioUI(agent).launch() |