基于 AI 的天气分析工具


运用AI来分析天气情况

前端界面

引入 marked.js 库,以展示 AI 返回的 Markdown 格式天气建议。

<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/9.1.6/marked.min.js"></script>

前端页面的主要功能是接收用户输入并展示结果。页面设有搜索框,方便用户直接提问。同时,预置示例问题简化了常用查询,用户点击即可快速查询。预测天数滑块允许用户自定义天气预测范围。

为了提升应用性能和离线能力,项目使用了 Service Worker 技术。

index.html 中注册了 Service Worker:

if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('/static/sw.js')
            .then(registration => {
                console.log('ServiceWorker registration successful');
            })
            .catch(error => {
                console.log('ServiceWorker registration failed:', error);
            });
    });
}

后端服务

API 密钥管理:使用 dotenv 库管理 API 密钥,如 METEOBLUE_API_KEY, WAQI_TOKEN, DEEPSEEK_API_KEY, BAIDU_MAP_AK, BAIDU_MAP_SK 等,密钥存储在 .env 文件中,提高安全性。

load_dotenv()
METEOBLUE_API_KEY = os.getenv("METEOBLUE_API_KEY")
# ... 其他 API 密钥加载

天气与空气质量数据整合:后端代码调用 Meteoblue 天气 API 和 WAQI 空气质量 API,根据经纬度实时获取天气和空气质量数据。

weather_url = f"https://my.meteoblue.com/packages/basic-3h?apikey={METEOBLUE_API_KEY}&lat={latitude}&lon={longitude}&format=json&windspeed=ms-1&forecast_days={forecast_days}"
weather_response = requests.get(weather_url)
weather_data = weather_response.json()

air_quality_url = f"https://api.waqi.info/feed/geo:{latitude};{longitude}/?token={WAQI_TOKEN}"
air_quality_response = requests.get(air_quality_url)
air_quality_data = air_quality_response.json()

DeepSeek LLM 智能建议:项目集成 DeepSeek 公司的 deepseek-reasoner LLM 模型,使用 OpenAI Python SDK 调用。系统将天气和空气质量数据以及用户问题构建为 Prompt,发送给 LLM 进行分析,生成个性化天气建议。

client = OpenAI(api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com")
messages = [{"role": "user", "content": f"{context}\n\nUser Query: {query}"}]
llm_response = client.chat.completions.create(
    model="deepseek-reasoner",
    messages=messages
)
ai_response = llm_response.choices[0].message.content

精准位置获取:系统支持多种位置获取方式。前端优先使用浏览器 Geolocation API。若用户拒绝或 API 不可用,后端将使用基于 IP 地址的位置定位,利用百度地图 IP 定位 API 获取城市信息,并实现了 API 请求的签名认证。

# 百度地图 IP 定位 API 调用示例
params = {
    "ip": effective_ip_for_baidu,
    "coor": coor,
    "ak": ak,
}
# ... SN 计算代码 ...
url = host + query_str
response = requests.get(url)
baidu_data = response.json()

追问与缓存:项目实现了追问功能和数据缓存。用户可在首次查询基础上继续提问。后端使用内存字典

# 缓存天气数据示例
weather_cache[cache_key] = {
    'weather_data': weather_data,
    'air_quality_data': air_quality_data,
    'ai_response': ai_response
}

追问功能在 /ask_followup 路由中实现,复用缓存数据,结合新问题再次调用 LLM。

@app.route('/ask_followup', methods=['POST'])
def handle_followup_question():
    # ... 获取缓存数据 ...
    messages = [{
        "role": "user",
        "content": f"""
        天气数据:{json.dumps(cached_data['weather_data'])}
        空气质量数据:{json.dumps(cached_data['air_quality_data'])}
        用户位置:纬度 {latitude},经度 {longitude}

        用户追问:{new_query}
        """
    }]
    # ... 调用 LLM ...

2 条回复

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注