import json, subprocess, random
from typing import Any
def add_number(a: float | str, b: float | str) -> float:
return float(a) + float(b)
def multiply_number(a: float | str, b: float | str) -> float:
return float(a) * float(b)
def substract_number(a: float | str, b: float | str) -> float:
return float(a) - float(b)
def write_a_story() -> str:
return random.choice([
"很久很久以前在一个遥远的银河系……",
"有两个朋友,他们喜欢树懒和编程……",
"世界正在终结,因为每只树懒都进化出了超常的智力……",
"其中一位朋友并不知道,另一位朋友无意中编写了一个让树懒进化的程序……",
])
def terminal(command: str) -> str:
if "rm" in command or "sudo" in command or "dd" in command or "chmod" in command:
msg = "无法执行 'rm, sudo, dd, chmod' 命令,因为它们很危险"
print(msg); return msg
print(f"正在执行终端命令 `{command}`")
try:
return str(subprocess.run(command, capture_output = True, text = True, shell = True, check = True).stdout)
except subprocess.CalledProcessError as e:
return f"命令失败:{e.stderr}"
def python(code: str) -> str:
data = {}
exec(code, data)
del data["__builtins__"]
return str(data)
MAP_FN = {
"add_number": add_number,
"multiply_number": multiply_number,
"substract_number": substract_number,
"write_a_story": write_a_story,
"terminal": terminal,
"python": python,
}
tools = [
{
"type": "function",
"function": {
"name": "add_number",
"description": "将两个数字相加。",
"parameters": {
"type": "object",
"properties": {
"a": {
"type": "string",
"description": "第一个数字。",
},
"b": {
"type": "string",
"description": "第二个数字。",
},
},
"required": ["a", "b"],
},
},
},
{
"type": "function",
"function": {
"name": "multiply_number",
"description": "将两个数字相乘。",
"parameters": {
"type": "object",
"properties": {
"a": {
"type": "string",
"description": "第一个数字。",
},
"b": {
"type": "string",
"description": "第二个数字。",
},
},
"required": ["a", "b"],
},
},
},
{
"type": "function",
"function": {
"name": "substract_number",
"description": "将两个数字相减。",
"parameters": {
"type": "object",
"properties": {
"a": {
"type": "string",
"description": "第一个数字。",
},
"b": {
"type": "string",
"description": "第二个数字。",
},
},
"required": ["a", "b"],
},
},
},
{
"type": "function",
"function": {
"name": "write_a_story",
"description": "写一个随机故事。",
"parameters": {
"type": "object",
"properties": {},
"required": [],
},
},
},
{
"type": "function",
"function": {
"name": "terminal",
"description": "从终端执行操作。",
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "您希望运行的命令,例如 `ls`、`rm` 等。",
},
},
"required": ["command"],
},
},
},
{
"type": "function",
"function": {
"name": "python",
"description": "使用一些将被运行的 Python 代码调用 Python 解释器。",
"parameters": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "要运行的 Python 代码",
},
},
"required": ["code"],
},
},
},
]