基于langchain和gradio实现天气查询智能体,本地ollama大模型调实时天气api,前端输入即可自动返回天气

介绍:众所周知大模型训练数据都是用的历史数据,无法实时查询天气信息,因此使用本地ollama大模型调实时天气api接口的方式,大模型识别和理解你要查询的请求,然后调第三方天气api接口返回实时天气。

python代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 20 13:43:03 2024
@author: xiaobai
"""

# 引入langchain_ollama中的ChatOllama
from langchain_ollama import ChatOllama
import os
import gradio as gr
import requests

# 配置大模型
model_tool = ChatOllama(model='llama3.2:3b', base_url='http://localhost:11434', format='json')

# 1. 获取北京天气的方法
def get_beijing_weather():
    weather_api_url = 'https://api.seniverse.com/v3/weather/now.json'
    params = {
        'key': '替换成你自己的key', #需要你自己申请一个查天气api接口的key,替换成你自己的
        'location': 'beijing',
        'language': 'zh-Hans',
        'unit': 'c'
    }
    response = requests.get(weather_api_url, params=params)
    weather_data = response.json()
    
    if 'results' in weather_data and weather_data['results']:
        result = weather_data['results'][0]['now']
        return f"北京当前天气:{result['text']},温度:{result['temperature']}°C"
    else:
        return "无法获取北京天气信息,请稍后再试。"

# 2. 业务处理函数映射,方便后续调用
fn_map = {
    'get_beijing_weather': get_beijing_weather
}

# 3. 业务函数绑定大模型
llm_with_tool = model_tool.bind_tools(
    tools=[
        {
            'name': 'get_beijing_weather',
            'description': '获取北京的当前天气信息',
            'parameters': {},
        }
    ]
)

# 4. 大模型处理输入,调用业务函数
def chat_handler(chat_str):
    print("====================")
    print(f"user: {chat_str}")
    print("--------------------")
    ai_msg = llm_with_tool.invoke(chat_str)
    print(ai_msg.tool_calls)
    if ai_msg.tool_calls:
        fn_name = ai_msg.tool_calls[0]['name']
        print("ai:......")
        print(f"调用函数:{fn_name}")
        res = fn_map[fn_name]()
        return res
    else:
        return ai_msg.content

# 5. 前端输入操作命令
# 格式如“北京天气”、“查询北京天气”等,包含关键字“北京天气”即可,大模型可自动识别
interface = gr.Interface(
    fn=chat_handler, 
    inputs=gr.Textbox(label="请输入请求"), 
    outputs=gr.Textbox(label="输出结果")
)

# 6. 启动本地服务器,在前端查看
interface.launch()

运行效果:
基于langchain和gradio实现天气查询智能体,本地ollama大模型调实时天气api,前端输入即可自动返回天气_第1张图片

你可能感兴趣的:(langchain,前端)