基本概念
我们先温习一些AI Agent有关的基本概念和有关工具与框架的介绍:
AI Agent :AI Agent 是一个具备"目标驱动 + 感知 + 决策 + 行动"闭环的软件系统,通常以 LLM 作为核心推理引擎。形式化一点可以写成:Agent = Policy(LLM) + Memory + Tools + Execution Loop。
Policy:通常由 LLM 实现(prompt + weights)。输入为当前 state(上下文 + memory),输出为下一步 action(tool call / text / plan)。
AI Tools:AI Tools 是 Agent 可调用的外部函数(function calling abstraction),用于扩展模型能力边界。
LangChain:LangChain 是一个用于构建 LLM 应用(尤其是 Agent / RAG)的 orchestration 框架。
Ollama:Ollama 是一个本地运行大语言模型的 runtime + model management system。
为什么使用Ollama
为什么要使用Ollama?最主要的原因当然是为了节省银子。如果你心疼直接调用外部的大语言模型带来的巨额花费,那么Ollama一定会成为你的最爱。在本地安装后,你就拥有了丰富的选择在本地安装不同的模型,免费进行各种学习和实验。当你觉得你已经有了一个非常成熟的应用后,再利用外部模型进行实际数据收集不失为一个聪明的选择。第二个好处是方便。相比于要计算和控制使用外部模型的token的花费,Ollama省掉了这些操心。虽然功能弱了一些,可是因为上面的两个好处,Ollama依然应该成为工具库中不可缺少的一员。
安装和Coding
我们利用Ollama和LangChain尝试一个最基本的AI Agent。
首先安装Ollama。请直接访问Ollama的官网,选择你的平台进行安装。非常方便和直接。安装之后,请访问一下Ollama支持的模型库。你可以看到非常多种选择。我们今天使用qwen3.5,所以请使用下面的命令安装这个model:
bash
ollama pull qwen3.5
第二步,使用langchain和ollama的python library编写一个简单的AI Agent。首先使用下面的命令创建一个python virtual environment。这样我们后面的操作都在这个virtual environment里进行,避免和其它python编程时可能发生的互相影响。
bash
python -m venv venv
.\venv\Scripts\activate
然后在你的source目录下创建一个requirements.txt文件,定义我们依赖的python library。在requirements.txt里定义下面两个需要的python library。
bash
ollama
langchain
然后运行下面的命令进行python library的安装:
bash
pip -r requirements.txt
现在我们改写langchain官网上提供的一个简单的AI Agent的例子。langchain官网使用的是ChatGPT,这里我们稍加改变,使用我们本地安装的Ollama qwen3.5的模型:
python
from langchain_ollama import ChatOllama
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
llm = ChatOllama(
model="qwen3.5"
)
agent = create_agent(
model=llm,
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
response = agent.invoke(
{"messages": [{
"role": "user",
"content": "what is the weather in sf?"
}]}
)
print(response)
这里对这个代码稍加解释。get_weather()是一个提供给AI Agent使用的tool。作为规定,我们必须在该method内的第一行加上对该tool的描述,以是LLM Model可以更好的理解该tool的用途。然后我们利用本地安装的Ollama qwen3.5定义了一个llm模型。然后我们定义了一个agent,并且定义了该agent使用的模型,tools,和它的系统提示词。最后我们调用该agent,回答sf的天气如何。
测试
如果你运行这个python脚本,你会看到:
bash
(venv) PS C:\Users\houzh\source\python\langchain> python ollama_test.py
{'messages': [HumanMessage(content='what is the weather in sf?', additional_kwargs={}, response_metadata={}, id='9d6f02e5-aada-450f-87b0-5ceb3f012390'), AIMessage(content='', additional_kwargs={}, response_metadata={'model': 'qwen3.5', 'created_at': '2026-04-13T15:25:55.9821411Z', 'done': True, 'done_reason': 'stop', 'total_duration': 17232548600, 'load_duration': 13073848800, 'prompt_eval_count': 281, 'prompt_eval_duration': 519827100, 'eval_count': 84, 'eval_duration': 3479336000, 'logprobs': None, 'model_name': 'qwen3.5', 'model_provider': 'ollama'}, id='lc_run--019d8772-c405-7790-8366-0a4d18fc0ecb-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'sf'}, 'id': 'dae4d82d-71ff-4972-96a5-4188bf00c739', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 281, 'output_tokens': 84, 'total_tokens': 365}), ToolMessage(content="It's always sunny in sf!", name='get_weather', id='f207771a-e2bf-4640-ac8b-ad5e22cf9d1f', tool_call_id='dae4d82d-71ff-4972-96a5-4188bf00c739'), AIMessage(content="It's always sunny in San Francisco!", additional_kwargs={}, response_metadata={'model': 'qwen3.5', 'created_at': '2026-04-13T15:25:57.0989276Z', 'done': True, 'done_reason': 'stop', 'total_duration': 1068090400, 'load_duration': 393427700, 'prompt_eval_count': 331, 'prompt_eval_duration': 246942000, 'eval_count': 11, 'eval_duration': 409399100, 'logprobs': None, 'model_name': 'qwen3.5', 'model_provider': 'ollama'}, id='lc_run--019d8773-07bd-7131-b778-aa963bc27d8d-0', tool_calls=[], invalid_tool_calls=[], usage_metadata={'input_tokens': 331, 'output_tokens': 11, 'total_tokens': 342})]}
如果我们仔细看一下这个response,我们会发现里面有很多有用信息。比如这一次运行消耗了多少token,模型的一些推理细节。作为终端用户,我们感兴趣的是这一个attribute:AIMessage(content="It's always sunny in San Francisco!"。我们看到model成功找到了注册的tool,并且进行了某些推理将sf识别为San Franciscol。
请注意,这里tool的调用和对于回答内容的组织是基于模型的推理,而不是按照某个简单的规则。我们可以再加上另一个tool,对地方进行描述。并且改写我们的问题,来测试一下模型如何决定调用tool。代码如下:
python
from langchain_ollama import ChatOllama
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
def get_location(city: str) -> str:
"""Get location description for a given city."""
return f"{city} is a very beautiful place."
llm = ChatOllama(
model="qwen3.5"
)
agent = create_agent(
model=llm,
tools=[get_weather, get_location],
system_prompt="You are a helpful assistant",
)
response = agent.invoke(
{"messages": [{
"role": "user",
"content": "Please provide me detail information about sf?"
}]}
)
print(response)
运行这个代码,你会得到输出:"Here is the information I found for San Francisco:\n\n* **Weather:** It's always sunny in San Francisco.\n* **Location:** San Francisco is a very beautiful place."。我们看到模型这个时候调用了两个tools,来为我们尽可能多的提供sf的信息。我们还可以进行更多问题的测试,比如我们问对sf的描述,模型就会只调用对地区提供描述的tool而忽略掉提供天气的tool。
小结
在这篇文章里我们介绍了Ollama的安装和使用。并且通过langchain调用Ollama初步实验了怎样用Ollama和langchain实现一个简单的AI Agent。