SmolAgents
HuggingFace SmolAgents 是一个用于构建 AI Agent 的 Python 库。这些 Agent 编写 Python 代码来调用工具和协调其他 Agent。
它使用 CodeAgent
,一个将自身行为写成代码的 LLM 引擎。SmolAgents 表明,这种方法被证明比当前行业实践(即让 LLM 输出它想调用的工具的字典)效果更好:使用的步骤减少 30%(因此 LLM 调用减少 30%),并且在困难基准测试中达到更高的性能。
与 Qdrant 一起使用
我们将演示如何通过构建一个电影推荐 Agent 来将 SmolAgents 与 Qdrant 的检索功能相结合。
安装
pip install smolagents qdrant-client fastembed
设置一个 Qdrant 工具
我们将构建一个能够查询 Qdrant Collection 的 SmolAgents 工具。该工具将使用 FastEmbed 在本地向量化查询。
首先,我们将使用来自 IMDb 的约 1000 部电影信息填充一个 Qdrant Collection,以便进行搜索。
from fastembed import TextEmbedding
from qdrant_client import QdrantClient
from smolagents import Tool
class QdrantQueryTool(Tool):
name = "qdrant_query"
description = "Uses semantic search to retrieve movies from a Qdrant collection."
inputs = {
"query": {
"type": "string",
"description": "The query to perform. This should be semantically close to your target documents.",
}
}
output_type = "string"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.collection_name = "smolagents"
self.client = QdrantClient()
if not self.client.collection_exists(self.collection_name):
self.client.recover_snapshot(
collection_name=self.collection_name,
location="https://snapshots.qdrant.io/imdb-1000-jina.snapshot",
)
self.embedder = TextEmbedding(model_name="jinaai/jina-embeddings-v2-base-en")
def forward(self, query: str) -> str:
points = self.client.query_points(
self.collection_name, query=next(self.embedder.query_embed(query)), limit=5
).points
docs = "Retrieved documents:\n" + "".join(
[
f"== Document {str(i)} ==\n"
+ f"MOVIE TITLE: {point.payload['movie_name']}\n"
+ f"MOVIE SUMMARY: {point.payload['description']}\n"
for i, point in enumerate(points)
]
)
return docs
定义 Agent
现在我们可以设置 CodeAgent
来使用我们的 QdrantQueryTool
。
from smolagents import CodeAgent, HfApiModel
import os
# HuggingFace Access Token
# https://hugging-face.cn/docs/hub/en/security-tokens
os.environ["HF_TOKEN"] = "----------"
agent = CodeAgent(
tools=[QdrantQueryTool()], model=HfApiModel(), max_iterations=4, verbose=True
)
最后,我们可以使用用户查询来运行 Agent。
agent_output = agent.run("Movie about people taking a strong action for justice")
print(agent_output)
结果应类似于
[...truncated]
Out - Final answer: Jai Bhim
[Step 1: Duration 0.25 seconds| Input tokens: 4,497 | Output tokens: 134]
Jai Bhim