您的位置:首页 > 手游攻略 > 搭建免费的Ollama AI Agent实用指南

搭建免费的Ollama AI Agent实用指南

作者:互联网  时间: 2026-08-26 13:10:02  

平时做技术实践时,很多问题不是概念不会,而是细节没串起来。拿“搭建免费的Ollama AI Agent”来说,它看着像小点,放到项目里常会牵出环境、配置、兼容性和维护成本。下面按实际采用顺序,把思路、关键写法和容易踩坑的地方讲清楚,便于大家直接对照操作。

基本概念

我们先温习一些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:

ollama pull qwen3.5

从实现思路看,第二步,采用langchain和ollama的python library编写一个轻松的AI Agent。首先采用下面的命令新建一个python virtual environment。这样我们后面的操作都在这个virtual environment里进行,避免和其它python编程时可能发生的互相影响。

python -m venv venv

.venvScriptsactivate

然后在你的source目录下新建一个requirements.txt文件,定义我们依赖的python library从实现思路看,。在requirements.txt里定义下面两个需的python library。

ollama
langchain
langchain-ollama

随后运行下面的命令进行python library的安装:

pip -r requirements.txt

结合项目来看,现在我们改写langchain官网上提供的一个轻松的AI Agent的例子。langchain官网采用的是ChatGPT,这里我们稍加改变,采用我们本地安装的Ollama qwen3.5的模型:

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脚本,你会看到:

(venv) PS C:Usershouzhsourcepythonlangchain> 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,模型的一些推理细节。更为具体的,我们这里得到是一个langchain的一次“多轮 + 工具调用”的完整运行结果对象。其格式如下所示:

{
  "messages": [ ... ]
}

“messages”是一个按照时间顺序排序的消息流。比如:

HumanMessage
→ AIMessage (tool_calls)
→ ToolMessage
→ AIMessage (final answer)

从实现思路看,这里记录了user,agent(AIMessage),和tool之间的交互。第一个消息由user发起,随后agent调用了tools,然后tool回应了消息,最后agent给出了最后的answer。

作为终端用户,我们感兴趣的是这一个attribute:AIMessage(content="It's always sunny in San Francisco!"。落到代码里,我们看到model成功找到了注册的tool,同时且进行了某些推理将sf识别为San Franciscol。我们能够用下面的代码打印出最后的agent的answer:

print("ai response: {}".format(response["messages"][-1].content))

实际处理时,请注意,这里tool的调用和对于回答内容的组织是基于模型的推理,而不是按照某个轻松的规则。我们能够再加上另一个tool,对地方进行描述。同时且改写我们的问题,来测试一下模型如何决定调用tool。代码如下所示:

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:nn* **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。

实际处理时,到此这篇关于搭建免费的Ollama AI Agent的文章就介绍到这了,更多相关搭建免费Ollama AI Agent内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多兼容脚本之家!

最新游戏

更多

Copyright©2010-2019. All rights reserved | 波波三国游戏官网|[email protected]

备案编号:湘ICP备2022015115号-4