快速入门

本节提供一个使用 Llama Stack 创建 AI 智能体的快速入门示例。

先决条件

  • Python 3.12 或更高版本(如果不满足,请参考 FAQ: 如何在 Notebook 中准备 Python 3.12
  • 通过 Operator 安装并运行的 Llama Stack Server(请参阅 安装 Llama Stack),其中 VLLM_URL 指向一个由 vLLM 提供服务的模型端点,并且已配置用于服务持久化的 POSTGRES_*(请参阅安装说明)
  • 可访问 Notebook 环境(例如 Jupyter Notebook、JupyterLab)
  • 已安装 llama-stack-client==0.7.1fastmcp(用于 MCP 部分)以及其他 notebook 依赖项的 Python 环境

快速入门示例

以下资源提供了一个使用 Llama Stack 创建 AI 智能体的简单示例:

下载该 notebook 并将其上传到 Notebook 环境中运行。

该 notebook 演示了:

  • 两种工具选项: 客户端工具(@client_tool)和 MCP 工具(FastMCP + toolgroups.register
  • 共享的智能体流程: 连接到 Llama Stack Server,选择模型,使用 tools=AGENT_TOOLS 创建 Agent,然后运行会话和流式轮次
  • 可选的向量存储流程: 上传文件,创建由 pgvectormilvus-remote 支持的向量存储,并运行搜索查询
  • 流式响应和事件日志记录
  • agent 的可选 FastAPI 部署

向量存储用法

可下载的 notebook 包含可选的 PGVector 和 Milvus 部分。

对于 PGVector,请使用 ENABLE_PGVECTOR=true 和有效的 PGVECTOR_* 连接设置启动服务器,然后执行 notebook 中的 PGVector 单元。ACP 提供的 PostgreSQL 可直接使用,因为它已包含 pgvector 扩展。

对于 Milvus,请使用 MILVUS_ENDPOINT、可选的 MILVUS_TOKENMILVUS_CONSISTENCY_LEVEL 启动服务器,然后执行 notebook 中的 Milvus 单元。在客户端请求中使用 provider_id="milvus-remote"

对于这两个向量存储示例,client.models.list() 必须包含一个 embedding 模型,例如 sentence-transformers/nomic-ai/nomic-embed-text-v1.5。如果它只返回 LLM 模型,请使用 ENABLE_SENTENCE_TRANSFORMERS=true 重新启动 LlamaStackDistribution,并按照 安装 Llama Stack 中的说明配置 Hugging Face 缓存/下载访问。

该 notebook 示例涵盖:

  • 通过 client.files.create(...) 上传文件
  • 使用 provider_id="pgvector"provider_id="milvus-remote" 创建向量存储
  • 通过 client.vector_stores.create(..., extra_body=...) 传递 embedding_modelembedding_dimension
  • 使用 client.vector_stores.search(...) 执行搜索;PGVector 在 extra_body 中使用 search_mode="hybrid"

FAQ

如何在 Notebook 中准备 Python 3.12

  1. 下载预编译的 Python 安装包:

    wget -O /tmp/python312.tar.gz https://github.com/astral-sh/python-build-standalone/releases/download/20260114/cpython-3.12.12+20260114-x86_64-unknown-linux-gnu-install_only.tar.gz
  2. 使用以下命令解压:

    mkdir -p ~/python312
    tar -xzf /tmp/python312.tar.gz -C ~/python312 --strip-components=1
  3. 安装并注册 Kernel:

    export PATH="${HOME}/python312/bin:${PATH}"
    
    python3 -m pip install ipykernel
    python3 -m ipykernel install --user --name python312 --display-name "Python 3.12"
  4. 在 notebook 页面中切换 kernel:

    • 在浏览器中打开你的 Notebook 环境(例如 Jupyter Notebook 或 JupyterLab),然后打开一个已有的 notebook 或创建一个新的 notebook。
    • 在 notebook 界面中,找到当前 kernel 名称(通常显示在页面右上角,例如 "Python 3" 或 "python3")。
    • 单击该 kernel 名称,或使用菜单 Kernel → Change Kernel
    • 在 kernel 列表中选择 "Python 3.12"(即第 3 步中注册的显示名称)。
    • 切换后,新单元将使用 Python 3.12 运行。

注意:在 notebook 页面中直接执行 python 和 pip 命令时,默认仍会使用系统默认的 python。你需要指定完整路径,才能使用 python312 版本的命令。

其他资源

有关使用 Llama Stack 开发 AI 智能体的更多资源,请参阅: