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集合。这个工具将使用快速嵌入在本地向量化查询。
最初,我们将使用来自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://huggingface.co/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
