Hub documentation

使用 SDK 进行构建

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

使用 SDK 进行构建

使用 Hugging Face 智能体 SDK 构建基于 MCP 的智能体。huggingface_hub(Python)和 @huggingface/tiny-agents(JavaScript)库提供了将 LLM 连接到 MCP 工具所需的一切。

安装

Python
JavaScript
pip install "huggingface_hub[mcp]"

快速入门:运行一个 Agent

最快的入门方式是使用 tiny-agents CLI:

Python
JavaScript
tiny-agents run julien-c/flux-schnell-generator

这将从 tiny-agents 集合 中加载一个智能体,连接到其 MCP 服务器,并启动交互式聊天。

使用 Agent 类

Agent 类负责管理聊天循环和 MCP 工具执行。它使用 Inference Providers 来运行 LLM。

Python
JavaScript
from huggingface_hub import Agent
import asyncio

agent = Agent(
    model="Qwen/Qwen2.5-72B-Instruct",
    provider="novita",
    servers=[
        {
            "type": "sse",
            "url": "https://huggingface.co/proxy/evalstate-flux1-schnell.hf.space/gradio_api/mcp/sse"
        }
    ]
)

async def main():
    async for chunk in agent.run("Generate an image of a sunset"):
        if hasattr(chunk, 'choices'):
            delta = chunk.choices[0].delta
            if delta.content:
                print(delta.content, end="")

asyncio.run(main())

有关所有选项,请参阅 Agent 参考。

直接使用 MCPClient

如需更多控制,请使用 MCPClient 直接管理 MCP 服务器和工具调用。

Python
JavaScript
import asyncio
from huggingface_hub import MCPClient

async def main():
    async with MCPClient(
        model="Qwen/Qwen2.5-72B-Instruct",
        provider="novita",
    ) as client:
        # Connect to an MCP server
        await client.add_mcp_server(
            type="sse", 
            url="https://huggingface.co/proxy/evalstate-flux1-schnell.hf.space/gradio_api/mcp/sse"
        )
        
        # Process a request with tools
        messages = [{"role": "user", "content": "Generate an image of a sunset"}]
        
        async for chunk in client.process_single_turn_with_tools(messages):
            if hasattr(chunk, 'choices'):
                delta = chunk.choices[0].delta
                if delta.content:
                    print(delta.content, end="")

asyncio.run(main())

有关所有选项,请参阅 MCPClient 参考。

分享您的 Agent

在 Hub 上为 tiny-agents 集合 贡献智能体。包括:

  • agent.json - 智能体配置(必需)
  • PROMPT.md 或 AGENTS.md - 系统提示词(可选)
  • EXAMPLES.md - 示例提示词和使用场景(可选)

了解更多

Update on GitHub