LangChain:使用智谱glm-4.6在线大模型调用本地函数实现输出
2025年10月20日,LangChain终于发布了1.0版本,下面来整体实验一下。
安装环境
pip install langgraph
pip install langchain langchain-core langchain-ollama
pip install langchain-community
pip install pyjwt
pip install --upgrade langchain langchain-core langchain-community
pip list | grep langchain
可以看到版本号从0.3.x升级到了1.0:
langchain 1.0.2
langchain-classic 1.0.0
langchain-community 0.4
langchain-core 1.0.0
langchain-ollama 1.0.0
langchain-text-splitters 1.0.0
实例运行
下面按照官方文档: https://docs.langchain.com/oss/python/langchain/quickstart 测试下运行效果。智谱新用户注册可以送200万Token,正好用来做实验。
from langchain.agents import create_agent
from langchain_community.chat_models import ChatZhipuAI
SYSTEM_PROMPT = """You are an expert weather forecaster, who speaks in puns.
You have access to two tools:
- get_weather_for_location: use this to get the weather for a specific location
- get_user_location: use this to get the user's location
If a user asks you for the weather, make sure you know the location. If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location."""
@tool
def get_weather_for_location(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
@tool
def get_user_location(runtime: ToolRuntime[Context]) -> str:
"""Retrieve user information based on user ID."""
user_id = runtime.context.user_id
return "Florida" if user_id == "1" else "SF"
# Create ZhipuAI model instance
model = ChatZhipuAI(model="glm-4", api_key="<your api key>")
agent = create_agent(
model=model,
tools=[get_weather],
system_prompt=SYSTEM_PROMPT,
)
response = agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)
print("Model response:", response)
执行代码,可以看到长长的json输出,节选关键部分如下:
content="It's always sunny in san francisco!"
结论
通过上述示例可以看出,LangChain 能够让大模型在回答问题时调用本地函数获取数据。过去,大模型更像是"云计算"——虽然知识丰富,却难以与用户的实际场景关联起来。而 LangChain 正是那座桥梁,让大模型得以"落地",与本地数据源和业务逻辑无缝对接,从而提供真正贴合用户场景的回复。