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': '上海'}) 网友回复
阿里云oss前端获取policy签名直传oss上传文件回调如何传?
如何将根据三维物体通过提示词变成可交互的4d场景动画?
浏览器中实时摄像头离线视觉ai模型有吗?
如何让ai基于Chromium内核开发自己的windows浏览器?
如何将自己从小生活的农村村庄做成3d可漫游的高斯泼溅?
同一个iframe多次write包含three的html为啥报错不显示Failed to execute 'write' on 'Document': Identifier 'scene' has a
软件工程师的工作内容将由敲代码转变成使用ai来解决现实世界的问题?
claude skills如何本地自动剪辑生成视频?
物理ai是2026年的趋势吗?
ai能对老相机拍摄的底片进行修复成彩色照片吗?


