随着这些新工具越来越多地被日常运营采用,组织越来越多地投资于人工智能。这种持续的创新浪潮正在推动对更高效、更可靠的框架的需求。顺应这一趋势,Datapizza(意大利科技社区背后的初创公司)刚刚发布了一个使用 Python 进行 GenAI 的开源框架,称为 Datapizza AI。
创建 LLM 支持的代理时,您需要选择一个 AI 堆栈:
在本文中,我将展示如何使用新的 Datapizza 框架来构建 LLM 驱动的 AI 代理。我将介绍一些有用的 Python 代码,这些代码可以轻松应用于其他类似情况(只需复制、粘贴、运行),并用注释遍历每一行代码,以便您可以复制此示例。
设置
我将使用 Ollama 作为 LLM 引擎,因为我喜欢在我的计算机上本地托管模型。这是所有拥有敏感数据的公司的标准做法。将所有内容保持在本地,可以完全控制数据隐私、模型行为和成本。
首先,您需要从网站下载 Ollama。然后,选择一个模型并运行页面上指示的命令来拉取 LLM。我选择阿里巴巴的 Qwen,因为它既智能又精简 ()。ollama run qwen3
Datapizza AI 支持所有主要的 LLM 引擎。我们可以通过运行以下命令来完成设置:
pip install datapizza-ai
pip install datapizza-ai-clients-openai-like
如官方文档所示,我们可以通过使用简单的提示调用模型并提出问题来快速测试我们的 AI 堆栈。该对象是连接到 Ollama API 的方式,该 API 通常托管在同一个本地主机 URL 上。
from datapizza.clients.openai_like import OpenAILikeClient
llm = "qwen3"
prompt = '''
You are an intelligent assistant, provide the best possible answer to user's request.
'''
ollama = OpenAILikeClient(api_key="", model=llm, system_prompt=prompt, base_url="http://localhost:11434/v1")
q = '''
what time is it?
'''
llm_res = ollama.invoke(q)
print(llm_res.text)

聊天机器人
测试 LLM 功能的另一种方法是构建一个简单的聊天机器人并进行一些对话。为此,在每次交互中,我们需要存储聊天记录并将其反馈给模型,指定谁说了什么。Datapizza 框架已经有一个内置的内存系统。
from datapizza.memory import Memory
from datapizza.type import TextBlock, ROLE
memory = Memory()
memory.add_turn(TextBlock(content=prompt), role=ROLE.SYSTEM)
while True:
## User
q = input('🙂 >')
if q == "quit":
break
## LLM
llm_res = ollama.invoke(q, memory=memory)
res = llm_res.text
print("🍕 >", f"\x1b[1;30m{res}\x1b[0m")
## Update Memory
memory.add_turn(TextBlock(content=q), role=ROLE.USER)
memory.add_turn(TextBlock(content=res), role=ROLE.ASSISTANT)

如果您想检索聊天记录,只需访问内存即可。通常,人工智能框架在与法学硕士的交互中使用三个角色:“系统”(核心指令)、“用户”(人类所说的话)、“助手”(聊天机器人的回复)。
memory.to_dict()
显然,仅靠 LLM 是非常有限的,除了聊天之外,它无能为力。因此,我们需要让它有可能采取行动,或者换句话说,激活工具。
工具
工具是简单 LLM 和 AI 代理之间的主要区别。当用户请求超出 LLM 知识库的内容(即“现在几点了?”)时,代理应该了解它不知道答案,激活工具以获取更多信息(即检查时钟),通过 LLM 详细说明结果,并生成答案。
Datapizza 框架允许您非常轻松地从头开始创建工具。你只需要导入装饰器@tool,任何函数都可以对代理进行作。
from datapizza.tools import tool
@tool
def get_time() -> str:
'''Get the current time.'''
from datetime import datetime
return datetime.now().strftime("%H:%M")
get_time()
然后,将指定的工具分配给代理,您将拥有一个结合了语言理解 + 自主决策 + 工具使用的 AI。
from datapizza.agents import Agent
import os
os.environ["DATAPIZZA_AGENT_LOG_LEVEL"] = "DEBUG" #max logging
agent = Agent(name="single-agent", client=ollama, system_prompt=prompt,
tools=[get_time], max_steps=2)
q = '''
what time is it?
'''
agent_res = agent.run(q)

LLM 驱动的 AI 代理是一个围绕语言模型构建的智能系统,它不仅会做出响应,还会进行推理、决定和行动。除了对话(这意味着与通用知识库聊天)之外,代理可以执行的最常见作是 RAG(与文档聊天)、查询(与数据库聊天)、Web 搜索(与整个 Internet 聊天)。
例如,让我们尝试一个网络搜索工具。在 Python 中,最简单的方法是使用著名的私人浏览器 DuckDuckGo。您可以直接使用原始库或 Datapizza 框架包装器 ()。pip install datapizza-ai-tools-duckduckgo
from datapizza.tools.duckduckgo import DuckDuckGoSearchTool
DuckDuckGoSearchTool().search(query="powell")

让我们创建一个可以为我们搜索网络的代理。如果你想让它更具互动性,你可以像我为聊天机器人所做的那样构建人工智能。
os.environ["DATAPIZZA_AGENT_LOG_LEVEL"] = "ERROR" #turn off logging
prompt = '''
You are a journalist. You must make assumptions, use your tool to research, make a guess, and formulate a final answer.
The final answer must contain facts, dates, evidences to support your guess.
'''
memory = Memory()
agent = Agent(name="single-agent", client=ollama, system_prompt=prompt,
tools=[DuckDuckGoSearchTool()],
memory=memory, max_steps=2)
while True:
## User
q = input('🙂 >')
if q == "quit":
break
## Agent
agent_res = agent.run(q)
res = agent_res.text
print("🍕 >", f"\x1b[1;30m{res}\x1b[0m")
## Update Memory
memory.add_turn(TextBlock(content=q), role=ROLE.USER)
memory.add_turn(TextBlock(content=res), role=ROLE.ASSISTANT)

多智能体系统
特工的真正优势在于能够像人类一样相互协作。这些团队被称为多代理系统 (MAS),是一组 AI 代理,他们在共享环境中协同工作,解决单个团队难以单独处理的复杂问题。
这一次,让我们创建一个更高级的工具:代码执行。请注意,法学硕士通过接触大量代码和自然语言文本语料库来了解如何编码,在那里他们学习编程语言的模式、语法和语义。但由于他们无法完成任何实际作,因此他们创建的代码只是文本。简而言之,LLM 可以生成 Python 代码,但不能执行它,代理可以。
import io
import contextlib
@tool
def code_exec(code:str) -> str:
'''Execute python code. Use always the function print() to get the output'''
output = io.StringIO()
with contextlib.redirect_stdout(output):
try:
exec(code)
except Exception as e:
print(f"Error: {e}")
return output.getvalue()
code_exec("from datetime import datetime; print(datetime.now().strftime('%H:%M'))")
MAS 有两种类型:顺序过程确保任务按照线性进展一个接一个地执行。另一方面,层次结构模拟了传统的组织层次结构,以实现高效的任务委派和执行。就我个人而言,我倾向于更喜欢后者,因为它具有更多的并行性和灵活性。
使用 Datapizza 框架,您可以将两个或多个代理与函数 .这样,一个代理就可以将当前任务传递给另一个代理。can_call()
prompt_senior = '''
You are a senior Python coder. You check the code generated by the Junior,
and use your tool to execute the code only if it's correct and safe.
'''
agent_senior = Agent(name="agent-senior", client=ollama, system_prompt=prompt_senior,
tools=[code_exec])
prompt_junior = '''
You are a junior Python coder. You can generate code but you can't execute it.
You receive a request from the Manager, and your final output must be Python code to pass on.
If you don't know some specific commands, you can use your tool and search the web for "how to ... with python?".
'''
agent_junior = Agent(name="agent-junior", client=ollama, system_prompt=prompt_junior,
tools=[DuckDuckGoSearchTool()])
agent_junior.can_call([agent_senior])
prompt_manager = '''
You know nothing, you're just a manager. After you get a request from the user,
first you ask the Junior to generate the code, then you ask the Senior to execute it.
'''
agent_manager = Agent(name="agent-manager", client=ollama, system_prompt=prompt_manager,
tools=[])
agent_manager.can_call([agent_junior, agent_senior])
q = '''
Plot the Titanic dataframe. You can find the data here:
https://raw.githubusercontent.com/mdipietro09/DataScience_ArtificialIntelligence_Utils/master/machine_learning/data_titanic.csv
'''
agent_res = agent_manager.run(q)
#print(agent_res.text)


结论
本文是介绍 Datapizza AI 的教程,这是一个用于构建 LLM 驱动的聊天机器人和 AI 代理的全新框架。该库非常灵活且用户友好,可以涵盖不同的 GenAI 用例。我用它来玩 Ollama,但它可以链接到所有著名的引擎,比如 OpenAI。
