Apigee AI Gateway(适用于 ADK 代理)¶
Apigee 提供了一个强大的工具(或系统)…… AI Gateway这将会改变您管理和控制生成式 AI 模型数据流的方式。通过使用 Apigee 代理来公开您的 AI 模型端点(例如 Agent Platform 或 Gemini API),您可以立即获得企业级功能:
-
模型安全性(Model Safety): 实施诸如 Model Armor 之类的安全策略,以保护系统免受威胁。
-
交通治理(Traffic Governance): 实施速率限制和令牌限制机制,以控制成本并防止滥用行为。
-
性能: 通过使用语义缓存(Semantic Caching)和先进的模型路由(Advanced Model Routing)技术,可以提升响应速度和系统效率。
-
监控与可见性: 实现对所有 AI 请求的详细监控、分析及审计功能。
The ApigeeLlm `wrapper` 是专为与 Agent Platform 以及 Gemini API(`generateContent`)配合使用而设计的。我们正在不断扩展对其他模型和接口的支持。对于兼容 OpenAI 的模型(包括自托管模型或其他提供商提供的模型),请使用相应的工具或方法进行集成。 CompletionsHTTPClient 目的是将流量通过您的 Apigee 代理进行路由(即引导流量经过该代理进行处理)。
实现示例¶
通过实例化相关组件,将 Apigee 的治理机制集成到您的代理(agent)的工作流程中。
ApigeeLlm 创建一个“包装对象”(wrapper object),然后将其传递给某个函数或系统。 LlmAgent 或其他类型的代理。
from google.adk.agents import LlmAgent
from google.adk.models.apigee_llm import ApigeeLlm
# Instantiate the ApigeeLlm wrapper
model = ApigeeLlm(
# Specify the Apigee route to your model. For more info, check out the ApigeeLlm documentation (https://github.com/google/adk-python/tree/main/contributing/samples/models/hello_world_apigeellm).
model="apigee/gemini-flash-latest",
# The proxy URL of your deployed Apigee proxy including the base path
proxy_url=f"https://{APIGEE_PROXY_URL}",
# Pass necessary authentication/authorization headers (like an API key)
custom_headers={"foo": "bar"},
# Optional: Pass google-auth credentials if the proxy requires additional OAuth scopes
# credentials=my_credentials
)
# Pass the configured model wrapper to your LlmAgent
agent = LlmAgent(
model=model,
name="my_governed_agent",
instruction="You are a helpful assistant powered by Gemini and governed by Apigee.",
# ... other agent parameters
)
import com.google.adk.agents.LlmAgent;
import com.google.adk.models.ApigeeLlm;
import com.google.common.collect.ImmutableMap;
ApigeeLlm apigeeLlm =
ApigeeLlm.builder()
.modelName("apigee/gemini-flash-latest") // Specify the Apigee route to your model. For more info, check out the ApigeeLlm documentation
.proxyUrl(APIGEE_PROXY_URL) //The proxy URL of your deployed Apigee proxy including the base path
.customHeaders(ImmutableMap.of("foo", "bar")) //Pass necessary authentication/authorization headers (like an API key)
.build();
LlmAgent agent =
LlmAgent.builder()
.model(apigeeLlm)
.name("my_governed_agent")
.description("my_governed_agent")
.instruction("You are a helpful assistant powered by Gemini and governed by Apigee.")
// tools will be added next
.build();
通过这种配置,您的代理发出的每个 API 请求都会首先经过 Apigee;在请求被安全地转发到相应的 AI 模型端点之前,Apigee 会执行所有必要的策略(如安全控制、速率限制、日志记录等)。有关使用 Apigee 代理的完整代码示例,请参见…… Hello World Apigee LLM.
与 OpenAI 的兼容性¶
The CompletionsHTTPClient 这是一个通用的 HTTP 客户端,专为与 OpenAI API 格式兼容而设计。它允许您通过代理(例如 Apigee)来路由请求;这些代理需要处理符合 OpenAI 标准的请求。 /chat/completions 这些客户端使用的是第三方端点(endpoints),而不是 Gemini 或 Vertex AI 的原生协议。这些客户端可以处理以下任务:
- 有效载荷(Payload)的构建:将 LlmRequest 对象转换为 OpenAI 兼容 API 所要求的格式。
- 响应处理:负责管理来自代理服务器的流式(streaming)和非流式(non-streaming)响应数据。
- 可靠性:使用方法
tenacity用于重试非流式请求,但仅在你提供相应的参数(或条件)时才会执行重试操作。retry_options=types.HttpRetryOptions(...)这些请求会被传递给相应的构造函数(constructor)。默认情况下,每个请求只会被尝试一次;对于那些需要持续传输数据(即流式传输)的请求,系统永远不会重新尝试发送它们。 - 规范化(Normalization):将响应数据以及流式传输的数据块解析为 ADK 框架其他部分所期望的标准格式。
实现示例¶
import asyncio
from google.adk.models.apigee_llm import CompletionsHTTPClient
from google.adk.models.llm_request import LlmRequest
from google.genai import types
async def test_client():
# 1. Initialize the client
client = CompletionsHTTPClient(
base_url="https://your-apigee-proxy-url.com/v1",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
# 2. Construct a minimal request
request = LlmRequest(
model="gpt-4o", # Replace with your target model ID
contents=[types.Content(role="user", parts=[types.Part.from_text(text="Hello!")])]
)
# 3. Execute a non-streaming generation
async for response in client.generate_content_async(request, stream=False):
if response.content and response.content.parts:
print(f"Response: {response.content.parts[0].text}")
if __name__ == "__main__":
asyncio.run(test_client())