SmolAgents
HuggingFace SmolAgents 是一个用于构建 AI 代理的 Python 库。这些代理编写 Python 代码来调用工具和协调其他代理。
它使用 CodeAgent。一个用代码编写其操作的 LLM 引擎。SmolAgents 认为,这种方法被证明比当前行业中让 LLM 输出其想要调用的工具字典的做法效果更好:步骤减少 30%(因此 LLM 调用减少 30%),并且在困难的基准测试中达到了更高的性能。
与 Qdrant 的使用
我们将通过构建一个电影推荐代理来演示如何将 SmolAgents 与 Qdrant 的检索功能结合使用。
安装
pip install smolagents qdrant-client fastembed
设置 Qdrant 工具
我们将构建一个 SmolAgents 工具,它可以查询 Qdrant 集合。该工具将使用 FastEmbed 在本地对查询进行向量化。
最初,我们将使用来自 IMDb 的 1000 部电影的信息填充一个 Qdrant 集合,以便我们可以在其中进行搜索。
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
定义代理
现在我们可以设置 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_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