最近突然心血来潮,想着让AI直接操作我的命令行,让他帮我完成一些简单的操作,比如让AI帮你安装docker,虽然很简单()

去查了相关资料,最终选择了AI模型的Function Calling,通过编写一个接入终端的tools实例,就能让AI直接在系统下运行powershell或者bash代码。

在运行前请安装依赖以及在代码中填入API key

pip install openai

全部代码

from openai import OpenAI
import json
import subprocess
import sys
import os
from prompt_toolkit import prompt

client = OpenAI(
    api_key = "在这里填入你的deepseek API key哦~",
    base_url = "https://api.deepseek.com",
)

def send_messages(messages):
    response = client.chat.completions.create(
        model="openrouter/optimus-alpha",
        messages=messages,
        tools=tools
    )
    return response.choices[0].message

def run_command(command=None):
    if not command:
        return "未提供命令"
    try:
        # 根据操作系统选择不同的命令解释器
        if client_system == "windows":
            cmd = ["powershell", "-Command", command]
        else:
            cmd = ["bash", "-c", command]
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True
        )
        if result.returncode != 0:
            return f"错误: {result.stderr.strip()}"
        return result.stdout.strip()
    except Exception as e:
        return f"执行命令时发生异常: {str(e)}"

if sys.platform.startswith("win"):
    client_system = "windows"
    shell="powershell"
    current_dir = os.getcwd()
else:
    client_system = "linux"
    shell="bash"
    current_dir = os.getcwd()

tools = [
    {
        "type": "function",
        "function": {
            "name": "run_command",
            "description": f"Execute shell code on the user's system. The user's current system is {client_system}, the shell is {shell}, and the path is {current_dir}. If necessary, try to use the shell to perform complex tasks (e.g., calculations). If the shell code execution fails or returns unexpected results, you can directly call this function again to try other shell code until the expected result is obtained. If there is no way to obtain the expected result, please explain it to the user.",
            "parameters": {
                "type": "object",
                "properties": {
                    "command": {
                        "type": "string",
                        "description": f"Execute {shell} code, such as 'curl -o ./baidu.html https://www.baidu.com', allowing the use of all shell syntax and functions! This includes all potentially destructive operations!",
                    }
                },
                "required": []
            },
        }
    },
]

# 初始化对话历史
messages = []

print(f"{client_system}/{shell}/开始与AI对话,输入'exit'结束对话")

while True:
    # 获取用户输入
    user_input = prompt("User => ")
    if user_input.lower() == "exit":
        break
    
    # 添加用户消息到对话历史
    messages.append({"role": "user", "content": user_input})

    while True:
        # 发送消息并获取模型响应,并模型响应添加到对话历史
        message = send_messages(messages)
        messages.append(message)

        # 打印模型文字回复(有时候没有文字回复,只有Function Calling调用)
        print(f"AI   => {message.content}")

        # 检查是否需要调用函数
        if hasattr(message, "tool_calls") and message.tool_calls:
            for tool_call in message.tool_calls:
                # 解析函数调用
                if tool_call.function.name == "run_command":
                    function_args = json.loads(tool_call.function.arguments)

                    command = function_args.get("command")
                    # 打印AI函数调用详细
                    print(f"AI调用函数===>\n {tool_call.function.name}\n{command}\n")

                    # 执行函数
                    result = run_command(command)

                    # 添加函数响应到对话历史
                    messages.append({
                        "role": "tool", 
                        "tool_call_id": tool_call.id, 
                        "content": result
                    })
                    print(f"函数响应===>{result}\n")
        else:
            break

测试运行()

(test) root@debian:~# python test.py
开始与DeepSeek AI对话,输入'exit'结束对话
User===>         尝试获取我的地理位置,越具体越好
AI===>
AI调用函数===>   run_command
curl -s https://ipinfo.io/json
错误: bash: line 1: curl: command not found

AI===>   您的系统中没有安装 `curl` 工具,将尝试使用 `wget` 工具获取。
AI调用函数===>   run_command
wget -qO- https://ipinfo.io/json
{
  "ip": "已打码",
  "city": "已打码",
  "region": "已打码",
  "country": "CN",
  "loc": "已打码",
  "org": "已打码",
  "postal": "已打码",
  "timezone": "Asia/Shanghai",
  "readme": "https://ipinfo.io/missingauth"
}

AI===>   根据获取的信息,您当前的地理位置如下:

- **城市**: 已打码
- **地区**: 已打码
- **国家**: 中国 (CN)
- **经纬度**: 已打码
- **邮政编码**: 已打码
- **时区**: 亚洲/上海 (Asia/Shanghai)
- **网络运营商**: 已打码

这些信息是通过您的公网IP地址获取的,可能对应的是您的网络服务提供商的位置,而非您的精确物理位置。如果需要更精确的位置信息,可能需要通过设备的GPS或其他定位服务来实现。
User===>

可以看到deepseek v3还是挺聪明的,调用curl失败后(debian默认没安装curl)会尝试使用wget,通过公开的ip归属地http api接口来获取我的ip位置和归属地,这波属于被ai开盒了()😂

#AI开盒计😂

编辑:代码于4/14更新

枯死的灌木!