掘金 人工智能 16小时前
使用 Google ADK, Gemma 3 和 MCP 工具构建 AI 代理
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文介绍了如何利用谷歌的代理开发工具包(ADK),结合本地LLM(如Gemma 3),通过Ollama运行,并使用模型上下文协议(MCP)调用外部工具执行实时搜索,构建一个YouTube搜索代理。该代理使用Gemma 3模型进行推理和生成响应,并通过MCP动态调用工具获取搜索结果。文章详细阐述了架构、工作流程,并提供了详细的实施指南,包括设置虚拟环境、安装MCP服务器和执行辅助函数等步骤。

💡 **核心组件**: 构建的YouTube搜索代理的核心组件包括谷歌ADK(提供代理框架)、MCP(标准化工具通信)、Gemma 3(提供语言理解和生成能力)、Ollama(本地托管Gemma模型)和MCP服务器(提供YouTube搜索功能)。

⚙️ **工作流程**: 用户提交查询后,ADK代理框架处理查询并确定意图;如果需要搜索,请求被转到MCP工具注册表;MCP搜索工具接收查询并获取结果,通过MCP标准格式返回结果;Gemma 3模型(通过Ollama和LiteLLM)接收搜索结果并生成自然语言响应,格式化的响应返回到用户界面。

🛠️ **实施指南**: 详细介绍了构建本地AI助手的步骤,包括设置虚拟环境、安装依赖项(如google-adk、mcp-youtube-search和litellm)、配置环境变量以及创建MCP工具执行器和搜索函数。还提到了解决LiteLLM/Ollama可能出现的KeyError问题的临时解决方法。

🐛 **KeyError问题**: 介绍了在使用Ollama模型时,可能出现的KeyError: 'name'错误,并提供了临时解决方案,即手动修补本地LiteLLM安装,以解决Ollama返回的JSON格式与LiteLLM解析不兼容的问题。

使用 Google ADK, Gemma 3 和 MCP 工具构建 AI 代理

简介

在本文中, 我们将探讨如何使用谷歌的 代理开发工具包(ADK)来构建具有本地 LLMs(如Gemma3 或 Llama3.2)的代理, 通过Ollama 运行, 并通过使用模型上下文协议(MCP)调用外部工具执行实时搜索.

我们将使用 ADK 框架构建一个YouTube 搜索代理, 它将利用 Gemma 3 模型进行推理和生成响应, 并通过 MCP 动态调用工具获取搜索结果.

什么是 Gemma 3 模型?

Gemma 3 是谷歌最新的开源大型语言模型, 旨在提供高性能, 高效率和多模态功能.

Gemma 3 有多种大小(1B, 4B, 12B 和 27B), 使我们能够根据硬件和性能要求选择理想的模型.

Gemma 3 - 一组轻量级, 先进的开放式模型, 采用了与 Gemini 2.0 模型相同的研究和技术.

Gemma 3 型号的几个特点

    图像和文本输入: 利用多模态输入支持分析和解释视觉数据128K 标记上下文: 16 倍大的输入上下文, 用于分析更多数据和解决更复杂的问题.功能调用: 创建自然语言界面, 与应用程序接口和工具进行交互.语言支持: 支持 140 多种语言, 适用于多语言 AI 应用程序模型尺寸: 提供 1B, 4B, 12B 和 27B 变体, 以满足我们的计算和任务需求

上一篇文章中, 探讨了ADK框架和MCP协议, 并演示了如何使用Gemini-2.5 Pro将 ADK 作为MCP客户端来构建一个代理. 我们将通过 Ollama 使用 Gemma3 模型来代替 Gemini-2.5 Pro.

架构

在本演示中, 我们将使用 ADK 框架构建一个YouTube 搜索代理, 该代理将利用 Gemma 3 模型进行推理和生成响应, 并通过 MCP 动态调用工具来获取搜索结果.

核心组件:

工作流程:

    用户通过界面提交查询.ADK 代理框架处理查询并确定意图如果需要搜索
    Gemma 3 模型(通过 Ollama 和 LiteLlm):
    格式化的响应返回到用户界面

实施指南:

让我们利用 ADK 框架和 Gemma 3 模型来逐步分解构建本地 AI 助手的过程

前提条件

    已安装Python 3.11+.已安装 Ollama下载 gemma3:12b 模型.有效的 SerpAPI key (用于搜索)安装或使用任何本地或远程 MCP 服务器(mcp-youtube-search)

项目结构

adk_mcp_gemma3/├── search/│   ├── __init__.py              # Package initialization│   └── agent.py                 # Agent implementation with ADK├── README.md                    # Project documentation└── requirements.txt             # Dependencies

步骤 1: 设置虚拟环境

安装依赖项

# Setup virtual environment (Mac or Unix )python -m venv venv && source venv/bin/active # Install agent development kitpip install google-adk# Install MCP server pip install mcp-youtube-search# Install litellmpip install litellm

设置环境变量:

export SERP_API_KEY="your-serpapi-key"

第 2 步:安装 MCP 服务器

在本文中, 我们将使用mcp-youtube-search和MCP服务器, 后者是使用adk构建的.

# Install from PyPI ( Already Installed from Step 1)pip install mcp-youtube-search

第 3 步:执行辅助函数 (agent.py)

# Step 1: Import required modulesfrom google.adk.agents import LlmAgentfrom google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioServerParametersfrom google.adk.models.lite_llm import LiteLlmimport osimport dotenv# Step 2: Load environment variablesdotenv.load_dotenv()# Step 3: Create tool execution helper functionsasync def execute_tool(tool, args):    """Execute a single tool and handle cleanup."""    try:        result = await tool.run_async(args=args, tool_context=None)        return (True, result, None)  # Success, result, no error    except Exception as e:        return (False, None, str(e))  # Failed, no result, error messageasync def try_tools_sequentially(tools, args, exit_stack):    """Try each tool in sequence until one succeeds."""    errors = []        for tool in tools:        success, result, error = await execute_tool(tool, args)        if success:            return result        errors.append(f"Tool '{tool.name}' failed: {error}")        if errors:        return f"All tools failed: {'; '.join(errors)}"    return "No tools available"

步骤 4: 创建 MCP 工具执行器

下面的函数创建了一个 async wrapper, 用于连接到 MCP 工具服务器并运行可用工具 - MCPToolset.from_server() 用于连接到工具, 按照步骤 3 中的定义依次**尝试 MCP 服务器返回的所有工具, 直到其中一个成功为止, 并通过 exit_stack.aclose() 确保适当的 资源清理.

# Step 4: Create MCP tool executordef create_mcp_tool_executor(command, args=None, env=None):    """Create a function that connects to an MCP server and executes tools."""    async def mcp_tool_executor(**kwargs):        # Connect to MCP server        tools, exit_stack = await MCPToolset.from_server(            connection_params=StdioServerParameters(                command=command,                args=args or [],                env=env or {},            )        )                try:            # Try all tools until one succeeds            return await try_tools_sequentially(tools, kwargs, exit_stack)        finally:            # cleanup            await exit_stack.aclose()        return mcp_tool_executor

第 5 步:使用上述函数创建搜索函数

我们需要确保向搜索函数提供适当的指令, 以便 LLM 翻译自然语言查询, 并在需要时调用搜索函数. 使用 mcp-youtube-search MCP 服务器, 定义工具执行器

# Step 5: Create YouTube search functionsearch_youtube = create_mcp_tool_executor(    command="mcp-youtube-search",    args=[],    env={"SERP_API_KEY": os.getenv("SERP_API_KEY")})# Step 6: Add documentation for the LLMsearch_youtube.__name__ = "search_youtube"search_youtube.__doc__ = """Search for YouTube videos based on a search query.    Args:    search_query: The search terms to look for on YouTube (e.g., 'Google Cloud Next 25')    max_results: Optional. Maximum number of results to return (default: 10)Returns:    List of YouTube videos with details including title, channel, link, published date,     duration, views, thumbnail URL, and description."""

步骤 6:创建 LlmAgent

让我们使用 LlmAgent 和 Ollama/gemma3:12b 创建代理

LiteLLM/Ollama KeyError Bug

venv/lib/python3.12/site-packages/litellm/llms/ollama/completion/transformation.py", line 266, in transform_response    "name": function_call["name"]KeyError: 'name'

临时解决方法:

使用 PR #9966中的更改手动修补本地 LiteLLM 安装, 并覆盖 .venv/lib/python3.11/site-package/litellm/llms/ollama/completion/transformation.py

如果上述错误合并到 litellm 中, 则不需要上述临时解决方法

# Step 7: Create the agent with instructions for formatting resultsagent = LlmAgent(    name="youtube_assistant",    model=LiteLlm(model="ollama/gemma3:12b"),    instruction="""You are a helpful YouTube video search assistant.Your goal is to use the search_youtube tool and present the results clearly.1.  When asked to find videos, call the search_youtube tool.2.  The tool will return a JSON object. Find the list of videos in the 'results' field of this JSON.3.  For each video in the list, create a bullet point (*).4.  Format each bullet point like this: **Title** (Link) by Channel: Description. (Published Date, Views, Duration)    - Use the 'title', 'link', 'channel', 'description', 'published_date', 'views', and 'duration' fields from the JSON for each video.    - Make the title bold.    - Put the link in parentheses right after the title.5.  Your final response should ONLY be the formatted bullet list of videos. Do not include the raw JSON.6.  If the 'results' list in the JSON is empty, simply respond: "I couldn't find any videos for that search."""",    tools=[search_youtube],)

第 7 步 : 最终演示

选项 1: ADK Web 使用 Gemma3

adk web

使用 Gemma3 和 MCP 的 ADK Web

选项 2 : ADK 在编程调试模式下使用 Gemma3

选项3 : 使用Gemma3的ADK CLI.

adk run search

在内部实现中, Gemma3 使用函数调用能力来决定何时需要工具, ADK提供连接模型和工具的框架, MCP规范工具的定义和与 MCP 服务器的通信.

GitHub 存储库:

你可以在 GitHub 上访问本文中使用的所有代码:

arjunprabhulal/adk-mcp-gemma3

结论

在本文中, 演示了如何使用谷歌的ADK, 通过OllamaGemma 3模型以及通过MCP连接的外部工具来构建本地 AI 代理.

好吧, 今天的内容就分享到这里啦!

一家之言, 欢迎拍砖

Happy Coding! Stay GOLDEN!

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

Google ADK Gemma 3 MCP AI代理 Ollama
相关文章