+
96
-

回答

OllamaFunctions 是一个实验性的 Python 库,它将 Ollama 模型封装为与 OpenAI Functions 相同的 API。

这使得开发者可以利用 Ollama 模型来调用特定的函数,并以结构化的方式获取输出。这个库的设计目的是为了让 Ollama 模型能够执行类似于 OpenAI 的函数调用功能,从而支持更复杂的交互和数据处理任务。通过 OllamaFunctions,可以定义函数的参数和描述,并通过模型的函数调用能力来执行这些函数,返回符合预设模式的结构化数据。

安装依赖

pip install langchain_experimental

运行代码

import requests
from langchain_experimental.llms.ollama_functions import OllamaFunctions
from langchain_core.messages import HumanMessage, ToolMessage


def exec_result(result):
    for tool_call in result.tool_calls:
        selected_tool = {"get_current_weather": get_current_weather}[tool_call["name"].lower()]
        tool_output = selected_tool(tool_call["args"])
        
def get_current_weather(args):
    
    city=args['location']
    
    # 对城市名称进行URL编码
    city_encoded = requests.utils.quote(city)
    # API URL,包含城市名称参数
    api_url = f'https://query.asilu.com/weather/baidu/?city={city_encoded}'
    
    # 发送GET请求
    response = requests.get(api_url)
    
    # 检查请求是否成功
    if response.status_code == 200:
        # 解析响应的JSON数据
        data = response.json()
        
        # 定义一个函数来显示天气数据
        def display_weather(data):
            city = data["city"]
            update_time = data["update_time"]
            date = data["date"]
            
            print(f"城市: {city}")
            print(f"更新时间: {update_time}")
            print(f"日期: {date}")
            print("\n天气预报:")
            
            for weather in data["weather"]:
                date = weather["date"]
                weather_desc = weather["weather"]
                temp = weather["temp"]
                wind = weather["wind"]
                
                print(f"{date} - 天气: {weather_desc}, 温度: {temp}, 风: {wind}")

        # 显示天气数据
        display_weather(data)
    else:
        print(f"请求失败,状态码: {response.status_code}")



model = OllamaFunctions(model="qwen2:7b", format="json")

model = model.bind_tools(
    tools=[
        {
            "name": "get_current_weather",
            "description": "获取指定城市的天气预报",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市名称, " "例如: 上海",
                    }
                },
                "required": ["location"],
            },
        }
    ],
    function_call={"name": "get_current_weather"},
)



result=model.invoke("现在上海的天气是怎么样的?")
print(result)



exec_result(result)


#get_current_weather({'location': '上海'})

网友回复

我知道答案,我要回答