介绍
在AI驱动的应用程序中,函数(或工具)调用正在彻底改变语言模型与外部工具和系统的交互方式。这种能力使得大型语言模型(LLM)能够超越静态响应,动态地调用工具、API或数据库查询,以生成实时、可操作的见解。
本文将探讨使用LangChain、Ollama和Streamlit进行函数调用——这三个强大的框架结合起来,解锁了AI驱动自动化的新层次。我们将讨论函数调用解决的问题、其潜力以及如何将其集成到你的AI应用程序中。
函数调用解决了什么问题?
传统的大型语言模型虽然功能强大,但由于其知识截止点限制,无法与实时数据交互或执行操作。这导致了一些关键挑战:
通过启用函数调用,我们弥合了AI推理能力与现实世界执行之间的鸿沟,使AI在实际应用中更加有用。
函数调用的强大之处
函数调用在多个方面增强了AI应用程序:
接下来,让我们看看如何实现函数调用。
实现
步骤1:设置项目环境
mkdir function-calling
cd function-calling
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install langchain langchain_ollama streamlit
同时,安装并启动Ollama,并安装llama3.2。
步骤2:创建Streamlit应用。
#
# STREAMLIT
#
import streamlit as st
st.title("Function Calling in LLMs")
# Toggle to turn on function calling
use_function_calling = st.toggle("Turn on function calling for weather")
# Prompt input
prompt = st.text_input("Prompt")
# Submit button
if st.button("Submit", type="primary", use_container_width=True):
with st.spinner():
res, messages = get_response(prompt, use_function_calling)
st.write(res)
with st.expander("Chat messages"):
st.write(messages)
步骤3:Langchain和Ollama代码
from langchain_ollama.chat_models import ChatOllama
from langchain_core.tools import tool
from langchain_core.messages import SystemMessage, HumanMessage
#
# LANGCHAIN FUNCTION CALLING
#
@tool
def get_weather(city: str):
"""Fetches weather for given city"""
weather_data = { # Example data, use API in real-world
"New York": "Sunny, 25°C",
"London": "Cloudy, 18°C",
"Tokyo": "Rainy, 22°C"
}
return weather_data.get(city, "Weather data not available.")
def get_response(prompt: str, use_function_calling: bool):
messages = [
SystemMessage("You are a helpful AI assistant. Answer concisely."),
HumanMessage(prompt)
]
if use_function_calling:
model = ChatOllama(model="llama3.2").bind_tools([get_weather])
res = model.invoke(messages)
messages.append(res)
for tool_call in res.tool_calls:
selected_tool = {"get_weather": get_weather}[tool_call['name'].lower()]
tool_message = selected_tool.invoke(tool_call)
messages.append(tool_message)
res = model.invoke(messages)
messages.append(res)
return res.content, messages
else:
model = ChatOllama(model="llama3.2")
res = model.invoke(messages)
messages.append(res)
return res.content, messages
步骤4:运行应用程序
首先,启动Ollama服务器。
ollama serve
接下来,启动Streamlit应用程序。
streamlit run main.py
没有函数调用的情况下。
使用函数调用后。
我们还可以通过展开“聊天消息”来查看内部消息。
结论
通过利用LangChain、Ollama和Streamlit,开发人员可以构建不仅智能而且可操作的AI应用程序。函数调用弥合了AI生成的见解与现实世界执行之间的鸿沟,释放了大型语言模型(LLM)的真正潜力。
函数调用为代理和工具铺平了道路,使得AI应用程序更加强大。代理允许AI在多个函数调用中进行推理和决策,而工具则扩展了其与外部系统交互的能力。