当前位置:首页>python>python实现简版openclaw

python实现简版openclaw

  • 2026-10-11 08:30:49
python实现简版openclaw
主文件app.py
import jsonfrom openai import OpenAIfrom tools.tools import TOOLS, execute_toolclient = OpenAI(api_key="lm-studio", base_url="AI地址")messages = [    {        "role": "system",        "content": "你是一个专业的 AI 助手,可以使用工具来完成任务。当需要搜索信息时请调用 web_search,当需要读取网页内容时请调用 fetch_content,当需要在桌面创建文件时请调用 create_file。\n\n重要:当用户说'创建文件,你需要在 content 参数中自己生成完整的内容,不要把'xxx'直接当作内容。内容尽量丰富,要罗列出所有可能的内容。",    }]def chat_loop():    print("=== AI 对话助手 ===")    print("输入你的问题,或输入 'quit' 退出")    print("-" * 40)    while True:        user_input = input("\n你: ").strip()        if not user_input:            continue        if user_input.lower() == "quit":            print("再见!")            break        messages.append({"role": "user", "content": user_input})        response = client.chat.completions.create(            model="local-model", messages=messages, tools=TOOLS        )        msg = response.choices[0].message        messages.append(msg)        if msg.tool_calls:            for tool_call in msg.tool_calls:                args = json.loads(tool_call.function.arguments)                print(f"\n[调用工具: {tool_call.function.name}]")                result = execute_tool(tool_call.function.name, args)                messages.append(                    {                        "role": "tool",                        "tool_call_id": tool_call.id,                        "content": json.dumps(result),                    }                )            final_response = client.chat.completions.create(                model="local-model", messages=messages            )            final_msg = final_response.choices[0].message            messages.append(final_msg)        else:            print(f"\nAI: {msg.content}")if __name__ == "__main__":    chat_loop()
建一个tools文件夹存放技能
tools.py代码示例
import osdef web_search(query):    """模拟联网搜索。真实落地可调用 Serper 或 Tavily API"""    print(f"【执行中】正在搜索关键词: {query}")    return [        {"title": "2026 AI Agent 趋势", "url": "https://example.com/agent2026"},        {"title": "提示词工程已死?", "url": "https://example.com/prompt-dead"}    ]def fetch_content(url):    """模拟网页抓取。真实落地可使用 BeautifulSoup 或 Jina Reader"""    print(f"【执行中】正在抓取网页内容: {url}")    return "这是一篇关于 AI 智能体落地的深度文章,提到了 Agentic Workflow 是未来的核心..."def create_file(filename, content):    """在用户桌面创建文件"""    desktop = os.path.join(os.path.expanduser("~"), "Desktop")    filepath = os.path.join(desktop, filename)    with open(filepath, "w", encoding="utf-8") as f:        f.write(content)    print(f"文件已创建: {filepath}")    return f"文件已创建: {filepath}"TOOLS = [    {        "type": "function",        "function": {            "name": "web_search",            "description": "当用户需要查找最新的咨询或网页链接时使用",            "parameters": {                "type": "object",                "properties": {"query": {"type": "string", "description": "搜索关键词"}},                "required": ["query"]            }        }    },    {        "type": "function",        "function": {            "name": "fetch_content",            "description": "当有了具体 URL 后,需要读取网页全文进行总结时使用",            "parameters": {                "type": "object",                "properties": {"url": {"type": "string", "description": "网页链接"}},                "required": ["url"]            }        }    },    {        "type": "function",        "function": {            "name": "create_file",            "description": "在桌面创建一个文件,需要指定文件名和内容",            "parameters": {                "type": "object",                "properties": {                    "filename": {"type": "string", "description": "文件名,包含扩展名,如 report.txt"},                    "content": {"type": "string", "description": "文件内容"}                },                "required": ["filename", "content"]            }        }    }]TOOL_FUNCTIONS = {    "web_search": web_search,    "fetch_content": fetch_content,    "create_file": create_file}def execute_tool(tool_name, arguments):    """根据工具名称执行对应的工具函数"""    tool_func = TOOL_FUNCTIONS.get(tool_name)    if tool_func:        if tool_name == "web_search":            return tool_func(arguments.get("query"))        elif tool_name == "fetch_content":            return tool_func(arguments.get("url"))        elif tool_name == "create_file":            return tool_func(arguments.get("filename"), arguments.get("content"))    return None
执行程序

最新文章

随机文章