首页
/ 在Google ADK-Python项目中集成本地Ollama Gemma3模型的实践指南

在Google ADK-Python项目中集成本地Ollama Gemma3模型的实践指南

2025-05-29 14:45:23作者:咎岭娴Homer

背景与需求分析

Google ADK-Python是一个用于构建智能代理的开发工具包,原生支持与Gemini等云端模型的集成。但在实际开发中,开发者经常需要将本地部署的Ollama模型(如Gemma3)接入系统。本文详细记录了这一技术实现过程,并解决了其中的典型问题。

环境配置关键步骤

1. Ollama服务准备

首先确保本地已正确安装并运行Ollama服务,可通过以下命令验证:

ollama list
ollama run gemma3:latest

2. 配置文件设置

需要创建两个关键配置文件:

环境变量文件(.env)

OLLAMA_API_BASE="http://localhost:11434"
OLLAMA_KEEP_ALIVE=-1

LiteLLM配置文件(litellm.config.yaml)

model_list:
  - model_name: gemma3
    litellm_provider: ollama
    litellm_params:
      model: ollama/gemma3 
      api_base: http://localhost:11434

代理实现方案

基础代理实现

核心代理类需要继承自ADK的Agent基类,关键实现如下:

from google.adk.agents import Agent
from google.adk.models.lite_llm import LiteLlm

class WeatherTimeAgent(Agent):
    def __init__(self):
        super().__init__(
            name="weather_time_agent",
            model=LiteLlm(model="ollama_chat/gemma3:4b"),
            description="天气和时间查询代理",
            instruction="专业回答城市天气和时间问题",
            tools=[self.get_weather, self.get_current_time]
        )
    
    def get_weather(self, city: str) -> dict:
        # 实现天气查询逻辑
        pass
    
    def get_current_time(self, city: str) -> dict:
        # 实现时间查询逻辑
        pass

模型调用方式

注意模型名称需要采用特定格式:

  • ollama_chat/[模型名称] 用于对话模型
  • ollama/[模型名称] 用于基础模型

常见问题解决方案

1. 模型未找到错误

当出现"Model not found"错误时,检查:

  • Ollama服务是否正常运行
  • 模型名称是否包含必要的前缀
  • 环境变量是否生效

2. 依赖版本冲突

特定版本组合才能正常工作:

google-adk>=0.1.0
litellm>=1.13.2

建议使用requirements.txt管理依赖:

pip install -r requirements.txt

3. 功能限制

需注意当前实现存在以下限制:

  • 不支持多模态输入(如图片)
  • 流式响应需要显式配置stream=True参数

最佳实践建议

  1. 测试先行:通过curl先验证Ollama接口可用性
curl http://localhost:11434/api/generate -d '{"model": "gemma3","prompt": "测试"}'
  1. 日志监控:启用DEBUG日志定位问题
import logging
logging.basicConfig(level=logging.DEBUG)
  1. 容器部署:建议使用Docker统一运行环境
FROM ollama/ollama
RUN ollama pull gemma3

通过以上方案,开发者可以成功将本地Ollama模型集成到Google ADK-Python项目中,构建出功能完整的智能代理系统。实际应用中还需根据具体业务需求调整提示词和工具函数实现。

项目优选

收起