AI 大模型应用进阶系列(四):简单智能体实现

103 阅读2分钟
import requests
import re


class Tool:
    """工具基类,所有工具需继承此类"""

    def name(self):
        """返回工具名称"""
        return "未知工具"

    def description(self):
        """返回工具功能描述"""
        return "未提供描述"

    def required_params(self):
        """返回工具所需参数列表"""
        return []

    def can_handle(self, query):
        """判断是否能处理该查询"""
        return False

    def parse_params(self, query):
        """从查询中解析参数"""
        return {}

    def execute(self, params):
        """执行工具功能"""
        return "工具未实现"


class WeatherTool(Tool):
    """天气查询工具,基于聚合数据API"""

    def __init__(self, api_key):
        self.api_key = api_key
        self.api_url = "http://apis.juhe.cn/simpleWeather/query"

    def name(self):
        return "天气查询"

    def description(self):
        return "查询指定城市的实时天气和当日预报"

    def required_params(self):
        return ["city"]

    def can_handle(self, query):
        """判断是否为天气相关查询"""
        weather_keywords = ["天气", "温度", "下雨", "晴天", "气温", "预报"]
        return any(keyword in query for keyword in weather_keywords)

    def parse_params(self, query):
        """从查询中提取城市名称"""
        # 匹配带行政区划的城市名
        city_pattern = re.compile(r'([\u4e00-\u9fa5]+[市|省|区|县])')
        match = city_pattern.search(query)

        if match:
            return {"city": match.group(1)}

        # 匹配常见直辖市
        common_cities = ["北京", "上海", "广州", "深圳", "重庆", "天津"]
        for city in common_cities:
            if city in query:
                return {"city": city}

        return None

    def execute(self, params):
        """调用聚合数据API获取天气信息"""
        try:
            response = requests.get(self.api_url, params={
                "city": params["city"],
                "key": self.api_key
            })

            data = response.json()

            if data["error_code"] != 0:
                return f"查询失败:{data['reason']}"

            realtime = data["result"]["realtime"]
            today = data["result"]["future"][0]

            return (f"{params['city']}天气信息:\n"
                    f"当前:{realtime['info']}{realtime['temperature']}°C\n"
                    f"风向:{realtime['direct']} {realtime['power']}\n"
                    f"今日预报:{today['weather']}{today['temperature']}")

        except Exception as e:
            return f"查询出错:{str(e)}"


class SimpleAgent:
    """简单智能体"""

    def __init__(self):
        self.tools = []
        print("智能体已启动!我可以帮你查询天气。")
        print("输入问题进行交流,输入'exit'退出,输入'工具'查看可用功能\n")

    def add_tool(self, tool):
        """添加工具到智能体"""
        self.tools.append(tool)
        print(f"已加载工具:{tool.name()} - {tool.description()}")

    def list_tools(self):
        """列出所有可用工具"""
        if not self.tools:
            return "暂无可用工具"

        tool_list = "可用工具:\n"
        for i, tool in enumerate(self.tools, 1):
            tool_list += f"{i}. {tool.name()}\n"
            tool_list += f"   功能:{tool.description()}\n"
            tool_list += f"   需要参数:{', '.join(tool.required_params())}\n"
        return tool_list

    def find_suitable_tool(self, query):
        """寻找适合处理查询的工具"""
        for tool in self.tools:
            if tool.can_handle(query):
                return tool
        return None

    def process_query(self, query):
        """处理用户查询"""
        # 查找合适的工具
        tool = self.find_suitable_tool(query)

        if tool:
            # 解析参数
            params = tool.parse_params(query)

            # 检查参数是否完整
            if not params:
                return f"使用{tool.name()}需要提供{', '.join(tool.required_params())},例如:'查询北京市的天气'"

            # 执行工具
            return tool.execute(params)
        else:
            # 无合适工具
            return f"抱歉,我无法处理这个问题。{self.list_tools()}"

    def chat(self):
        """启动对话循环"""
        while True:
            user_input = input("请输入: ")

            if user_input.lower() == "exit":
                print("智能体: 再见!")
                break

            if user_input.lower() == "工具":
                print(f"智能体: {self.list_tools()}")
                continue

            response = self.process_query(user_input)
            print(f"智能体: {response}\n")


if __name__ == "__main__":
    # 初始化智能体
    agent = SimpleAgent()

    # 添加天气工具(请替换为你的API密钥)
    # 聚合数据天气API申请:https://www.juhe.cn/docs/api/id/73
    WEATHER_API_KEY = "your apiKey"  # 替换为实际API密钥
    agent.add_tool(WeatherTool(WEATHER_API_KEY))

    # 启动对话
    agent.chat()