python机器人Agent编程——使用swarm框架和ollama实现一个本地大模型和爬虫结合的手机号归属地天气查询Agent流(体会)-三、完整代码

完整代码如下:

import streamlit as st  
from swarm import Swarm, Agent  

import requests
import re
from phone import Phone
from city import *
  
from openai import OpenAI
# 定义模型  
MODEL = "llama3.2:latest"  
#MODEL = "qwen2.5:0.5b"
ollama_client = OpenAI(
    base_url = 'http://localhost:11434/v1',
    api_key='None', # required, but unused
)
# 初始化 Swarm 客户端  
client = Swarm(client=ollama_client)  
  
# 通过 Streamlit 创建用户界面,为页面和应用程序添加一个标题  
st.set_page_config(page_title="AI News Processor", page_icon="????")  
st.title("???? Phone Location And Weather Searcher Agent")  

p = Phone()  
# 定义新闻搜索 Function,使用 DuckDuckGo 搜索 API,获取当月新闻,并返回结构化结果  
def get_mobile_address(number:str):  
    """Search for the location according the number input"""     
    res=p.find(number)
    print("1原始查询结果:",type(res),res)
    if res:
        if "city" in res.keys(): 
            key=  res['city']    
            if key in citycode:                
                code=citycode[key]       
                print("城市的代码:",code)
                return f"according the phon number:{number},it belong to the city whose name is:{key},according the name of city I find the citynumber,the citynumber is "+code
            else:
                print("未找到城市的代码")
                return "sorry I cant find the citynumber"            
            
        else:
            print("未找到手机号归属地,抱歉")
            return "sorry I cant find the citynumber"
    else:
        print("未找到手机号归属地,抱歉")
        return "未找到手机号归属地,抱歉"


def get_weather(citynumber: str):
    """Search for the weather according the city name"""     
    print("2 输入查询的天气对应城市号码:",citynumber)
    try:
        url=f'https://www.weather.com.cn/weather1d/{citynumber}.shtml#input'         
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
            "Cookie": "userNewsPort0=1; defaultCty=101010100; defaultCtyName=%u5317%u4EAC; f_city=%E5%8C%97%E4%BA%AC%7C101010100%7C; Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b=1730788105,1730874362; HMACCOUNT=5E07A605B65ACF5F; Hm_lpvt_080dabacb001ad3dc8b9b9049b36d43b=1730875029"
        }
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            html_content = response.content.decode('utf-8')  # Decode response content to support Chinese
            #print(html_content)
            # 使用正则表达式查找<script>标签中的变量
            script_matches = re.findall(r'<script.*?>(.*?)</script>', html_content, re.DOTALL)
            match=False
            if len(script_matches)>4:
                hour3data = script_matches[4] 
                import json
                
                # Extract the hour3data variable from the script
                hour3data_str = hour3data
                
                # Parse the string to extract the 7d data
                hour3data_json = json.loads(hour3data_str.split('=')[1].strip().rstrip(';'))
                seven_day_data = hour3data_json["7d"]
                
                # Format the extracted data for output
                formatted_data = []
                for day in seven_day_data:
                    formatted_data.append(", ".join(day))
                
                # Join the formatted data into a single string
                hour3data_output = "\n".join(formatted_data)
                print("提取的7天天气数据:", hour3data_output)  
                from datetime import datetime
                # Get the current date and time
                current_datetime = datetime.now()
                current_date_hour = current_datetime.strftime("%Y年-%m月-%d日 %H:00时")
                print("当前日期到小时:", current_date_hour)
                return f"今天的日期和小时时间是 {current_date_hour},the next hours of today's weather and the next 7 day's weather datas is follows:"+hour3data
            else:
                print("未找到天气小时数据")
                return "未找到天气小时数据"
        else:
            print("请求失败,状态码")
            return "请求失败,状态码: {}".format(response.status_code)        
      
    except : 
        print("error")       
        return "error"


  
# 创建智能体  
search_agent = Agent(  
    name="receptionist agent",  
    instructions="""  
    You are a receptionist, and you need to respond according to the user's requests. Your tasks are: 
    1) If the user provides a phone number and does not ask about the weather, you should call the get_mobile_address function and then directly return the query result; 
    2) If the user provides a phone number and requests to check the weather, you should first call the mobile phone origin query tool, then call the weather query tool, and finally return the query results.

    """,  
    functions=[get_mobile_address],  
    model=MODEL  
)  


weather_agent = Agent(  
    name="weather search agent",  
    instructions="""  
    you are a weather search server,your task are:
    1) if the user find a citynumber (which begin with "10" and must be a number), you should use the value of citynumbe(which begin with "10" and must be a number) as parameter and call the get_weather funciton to get the weather information.
    2) if the user did not find a citynumber,do not call any funciton and just respone the orignal message.
    """,  
    functions=[get_weather],  
    model=MODEL  
)  
  
summary_agent = Agent(  
    name="Summarizer weather reporter agent",  
    instructions="""  
    You are a summarization weather reporter, who can analyzes the input information. 
    If there is weather information, Based on the data from the next few hours and the data for the next 7 days, you summarize the weather for today and the weather trends for the next 7 days , and give a weather report,
    you should strictly using the information and do not say anything else out of the information, at the head of the report,you should say the city name belong to phone number,speak in simple chinese.
.   If there is no weather information, you should say sorry to the user.
    """,      
    model=MODEL  
)  
  
# 实施新闻处理工作流程,按顺序处理,显示进度指标  
def process_ask(topic):  
    """Run the searching workflow"""  
    with st.spinner("Processing ..."):  # Changed to st.spinner for better context
        # Search  
        st.write(f"1.Searching the location for your phone number...{topic}")  
        search_response = client.run(  
            agent=search_agent,  
            messages=[{"role": "user", "content": f"what is location of this number:{topic}"}]  
        )  
        response1 = search_response.messages[-2]["content"] 
        print("search_response.messages\n",response1)
        # Synthesize  
        st.write(f"2.weather_agent processing...")  
        synthesis_response = client.run(  
            agent=weather_agent,  
            messages=[{"role": "user", "content": f"{response1}"}]  
        )  
        response2 = synthesis_response.messages[-1]["content"]  
        print("synthesis_response.messages\n",response2)
        # Summarize  
        st.write(f"3.Creating summary...")  
        summary_response = client.run(  
            agent=summary_agent,  
            messages=[{"role": "user", "content": f"Summarize this information:\n{response2}"}]  
        )  
     
        return summary_response.messages[-1]["content"]  
  
# 用户web交互界面  
topic = st.text_input("Enter your number:", value="13858130853")  
if st.button("Process searching", type="primary"):  
    if topic:  
        try:  
            final_summary = process_ask(topic)  
            st.header(f"Searching: {topic}")  
            st.markdown(final_summary)  
        except Exception as e:  
            st.error(f"An error occurred: {str(e)}")  
    else:  
        st.error("Please enter a number!")  


上一篇:【Node-Red】使用文件或相机拍摄实现图像识别


下一篇:宏定义和函数调用的区别