This engineering guide provides copy-pasteable, production-hardened TypeScript (@google/genai v3.4.0) and Python (google-genai v3.4.0) blueprints for: (1) Dynamic ToolSearch orchestration in the Interactions API, (2) Audio and document range slicing via static media processing, and (3) Batch multimodal embeddings with usage metadata reporting on the Gemini Enterprise API.
@google/genai v3.4.0)This pattern configures an agent with access to an enterprise registry of 250 tools. Instead of sending 250 schemas upfront, we pass a dynamic tool search handler that resolves and mounts only the tools matching Gemini’s intent.
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY
});
// Mock Enterprise Tool Registry with 250+ internal functions
const enterpriseToolRegistry = [
{
name: "query_kubernetes_cluster",
description: "Inspect cluster pod statuses, restart counts, and CPU limits.",
parameters: {
type: "object",
properties: {
cluster: { type: "string" },
namespace: { type: "string" }
},
required: ["cluster"]
}
},
{
name: "fetch_crm_account",
description: "Look up enterprise customer contract value, ARR, and health score.",
parameters: {
type: "object",
properties: {
account_name: { type: "string" }
},
required: ["account_name"]
}
}
];
// Initiate interaction with dynamic ToolSearch enabled
const interaction = await ai.clients.interactions.create({
model: "gemini-4-hydrogen",
input: "Check why the pods in our us-east-prod cluster under namespace 'checkout' are restarting.",
config: {
thinking_config: { thinking_level: "high" },
automatic_continuation: true,
tools: [
{
tool_search: {
// Instruct model how to search the registry
description: "Enterprise microservice and infrastructure tool registry"
}
}
]
}
});
// Process steps: Gemini emits ToolSearchCallStep -> system returns matching tool
for (const step of interaction.steps || []) {
if (step.type === "tool_search_call") {
console.log(`[ToolSearch Query]: ${step.tool_search_call.query}`);
// Simulate registry search returning 'query_kubernetes_cluster'
const matches = enterpriseToolRegistry.filter(t =>
t.description.toLowerCase().includes("cluster") ||
t.description.toLowerCase().includes("pod")
);
console.log(`Discovered ${matches.length} matching tool(s) on-demand.`);
} else if (step.type === "tool_call") {
console.log(`[Invoking]: ${step.tool_call.name}`, step.tool_call.arguments);
}
}
console.log("Final Resolution:", interaction.output?.text);
google-genai v3.4.0)Extract specific sections from a 60-minute audio call and target pages 42–45 of a 200-page financial PDF without local preprocessing:
import os
from google import genai
from google.genai.types import InteractionsConfig
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
# 1. Target audio slice between 12.5s and 35.0s (customer dispute section)
audio_input = {
"type": "audio",
"mime_type": "audio/webm",
"audio_url": "gs://acme-recordings/call-nov-16.webm",
"processing": {
"type": "static",
"start_offset": "12.5s",
"end_offset": "35.0s"
}
}
# 2. Target specific pages in a high-density 10-K report
doc_input = {
"type": "document",
"mime_type": "application/pdf",
"document_url": "gs://acme-filings/annual-report-2026.pdf",
"processing": {
"type": "static",
"page_processing_options": {
"page_ranges": ["42-45"]
},
"media_resolution": "high" # Preserves balance sheet table fidelity
}
}
interaction = client.interactions.create(
model="gemini-4-carbon",
input=[
{"role": "user", "content": [
audio_input,
doc_input,
"Reconcile the disputed billing amount in the customer audio with the revenue footnote on page 44."
]}
],
config=InteractionsConfig(
thinking_level="high",
automatic_continuation=True
)
)
print("Agent Reconciliation Output:")
print(interaction.output.text)
print("Token Usage Metadata:", interaction.usage_metadata)
Commit 2efab95 enables batch inputs and usage metadata across gemini-embedding-2, gemini-embedding-3, and Vertex MaaS models:
import { GoogleGenAI } from "@google/genai";
// Client configured for Gemini Enterprise / Vertex AI mode
const ai = new GoogleGenAI({
vertexAI: true,
project: "my-enterprise-ai-project",
location: "us-central1"
});
// Normalize and batch multiple content items in a single roundtrip
const response = await ai.models.embedContent({
model: "publishers/google/models/gemini-embedding-2",
contents: [
"Analyze Q4 operating margins across the European manufacturing sector.",
"Evaluate structural battery degradation rates in fleet electric vehicles.",
"Summarize firmware patch notes for CVE-2026-9812 Linux kernel mitigation."
],
config: {
outputDimensionality: 768
}
});
console.log(`Generated ${response.embeddings?.length} vector embeddings.`);
console.log("Usage Metadata (Tokens Billed):", response.usageMetadata);
// Output: { promptTokenCount: 52, totalTokenCount: 52 }
With fix 411bb6f, AsyncHttpxClient scopes connection pools per event loop, eliminating cross-thread connection corruption in concurrent API workers:
from fastapi import FastAPI, BackgroundTasks
from google import genai
import asyncio
app = FastAPI()
# Shared async client remains thread-safe across dynamic event loops
gemini_async_client = genai.Client()
@app.post("/analyze-task")
async def handle_task(task_prompt: str, background_tasks: BackgroundTasks):
# Runs safely inside the current request's event loop
interaction = await gemini_async_client.aio.interactions.create(
model="gemini-4-hydrogen",
input=task_prompt,
config={"thinking_level": "medium"}
)
return {
"status": "success",
"output": interaction.output.text,
"token_usage": interaction.usage_metadata
}
Explore dynamic tool discovery, audio slicing, and batch embeddings in action without setting up API keys in the Tool Search Studio Lab [SIMULATED DEMO].