<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ameni Selmi on Medium]]></title>
        <description><![CDATA[Stories by Ameni Selmi on Medium]]></description>
        <link>https://medium.com/@ameniselmi1925?source=rss-d530e850bdd9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DcES9eTqDMHLD59m</url>
            <title>Stories by Ameni Selmi on Medium</title>
            <link>https://medium.com/@ameniselmi1925?source=rss-d530e850bdd9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:22:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ameniselmi1925/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Capstone: Build a Policy Assistant with Gemini, RAG, ADK and Evaluation]]></title>
            <link>https://medium.com/@ameniselmi1925/capstone-build-a-policy-assistant-with-gemini-rag-adk-and-evaluation-615d12b32d2b?source=rss-d530e850bdd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/615d12b32d2b</guid>
            <category><![CDATA[capstone]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[politics]]></category>
            <dc:creator><![CDATA[Ameni Selmi]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 16:22:13 GMT</pubDate>
            <atom:updated>2026-11-19T16:22:13.143Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Fourteen articles, one project. Here is how the pieces of the Google AI stack fit together in a small assistant that answers employee questions from company policies, and how to take it from a notebook to production.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SnXxDdPa_o3x8f8Q4BKwxw.png" /></figure><p>Over this series we covered the pieces separately: the Gemini platform, ADK, A2A, RAG, evaluation, function calling, multimodal input, voice, images, safety, caching, MCP, deployment and grounding. This last article puts the core of it into one small project, a <strong>Policy Assistant</strong>, and shows the road from a working notebook to a production service.</p><p>The assistant answers questions such as “How many days of annual leave do I get?” from a set of company policy documents. The company in the example is fictional.</p><h3>1. The architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36yCahESFv_Run2faE29Ow.png" /></figure><p>Four steps:</p><ol><li><strong>Policy documents:</strong> short texts, one per policy.</li><li><strong>Embed and index:</strong> split them into chunks, turn each chunk into a vector with a Gemini embedding model, and keep the vectors in memory.</li><li><strong>ADK agent with a search tool:</strong> the agent decides when to look up policies, calls a search_policies function, and answers only from what it finds.</li><li><strong>Evaluate the answers:</strong> a small test set checks whether the agent used the tool and whether the answer contained the right facts.</li></ol><p>The code runs in a Google Colab notebook with a free Gemini API key, so you can build it without a Google Cloud project. Replace the placeholder below with your own notebook link: <strong>[link to your Colab notebook]</strong>.</p><h3>2. Step by step</h3><h3>Documents and chunks</h3><p>python</p><pre>DOCS = {<br>    &quot;annual-leave&quot;: &quot;Every employee gets 25 paid days of annual leave per year. &quot;<br>                    &quot;Up to 5 unused days can be carried over. Request leave 2 weeks ahead.&quot;,<br>    &quot;security&quot;: &quot;Multi-factor authentication is mandatory on all work accounts. &quot;<br>                &quot;A lost or stolen device must be reported to IT within 24 hours.&quot;,<br>    # ... more policies<br>}</pre><p>The notebook splits each document into chunks of whole sentences, up to a maximum number of characters. Our documents are tiny, but for real ones you should tune chunk size and overlap on your own questions, as described in the RAG article.</p><h3>Embeddings and retrieval</h3><p>python</p><pre>import numpy as np<br>from google import genai<br>from google.genai import types</pre><pre>client = genai.Client()  # reads GEMINI_API_KEY from the environment<br></pre><pre>def embed(texts, task_type):<br>    result = client.models.embed_content(<br>        model=&quot;gemini-embedding-001&quot;,<br>        contents=texts,<br>        config=types.EmbedContentConfig(task_type=task_type, output_dimensionality=768),<br>    )<br>    vectors = np.array([e.values for e in result.embeddings], dtype=np.float32)<br>    return vectors / np.linalg.norm(vectors, axis=1, keepdims=True)  # normalize<br></pre><pre>def search(query, index, records, top_k=3):<br>    q = embed([query], &quot;RETRIEVAL_QUERY&quot;)[0]<br>    best = np.argsort(-(index @ q))[:top_k]<br>    return [records[i] for i in best]</pre><p>Documents are embedded with RETRIEVAL_DOCUMENT and questions with RETRIEVAL_QUERY. Because the vectors are normalized, similarity is a dot product. Google&#39;s embeddings page notes that for dimensions other than the default, you need to normalize yourself, which is why the code does it.</p><h3>The agent</h3><p>python</p><pre>from google.adk.agents.llm_agent import Agent<br></pre><pre>def search_policies(query: str) -&gt; dict:<br>    &quot;&quot;&quot;Search the company policy documents.</pre><pre>    Args:<br>        query: A short description of what to look up.<br>    &quot;&quot;&quot;<br>    hits = search(query, index, records)<br>    return {&quot;status&quot;: &quot;success&quot;, &quot;results&quot;: [{&quot;source&quot;: h[&quot;source&quot;], &quot;text&quot;: h[&quot;text&quot;]} for h in hits]}<br></pre><pre>policy_agent = Agent(<br>    model=&quot;gemini-flash-latest&quot;,  # pin an exact model ID for real projects<br>    name=&quot;policy_assistant&quot;,<br>    description=&quot;Answers employee questions about company policies.&quot;,<br>    instruction=(<br>        &quot;Always call search_policies before answering a policy question. &quot;<br>        &quot;Answer only from the returned passages and name the source. &quot;<br>        &quot;If they do not contain the answer, say you don&#39;t know.&quot;<br>    ),<br>    tools=[search_policies],<br>)</pre><p>The instruction does two jobs: it forces the lookup, and it gives the agent a safe way out (“say you don’t know”) instead of guessing.</p><h3>Evaluation</h3><p>python</p><pre>CASES = [<br>    {&quot;q&quot;: &quot;How many days of annual leave do I get?&quot;, &quot;must&quot;: [[&quot;25&quot;]], &quot;tool&quot;: True},<br>    {&quot;q&quot;: &quot;How long do I have to report a lost laptop?&quot;, &quot;must&quot;: [[&quot;24&quot;]], &quot;tool&quot;: True},<br>    {&quot;q&quot;: &quot;What is the CEO&#39;s favourite colour?&quot;, &quot;must&quot;: None, &quot;tool&quot;: True},  # should say it doesn&#39;t know<br>]<br></pre><pre>def score_case(case, answer, tools_used):<br>    &quot;&quot;&quot;Return (tool_ok, answer_ok).&quot;&quot;&quot;<br>    tool_ok = (&quot;search_policies&quot; in tools_used) == case[&quot;tool&quot;]<br>    text = answer.lower()<br>    if case[&quot;must&quot;] is None:<br>        answer_ok = any(p in text for p in [&quot;don&#39;t know&quot;, &quot;do not know&quot;, &quot;not mentioned&quot;, &quot;couldn&#39;t find&quot;])<br>    else:<br>        answer_ok = all(any(opt.lower() in text for opt in group) for group in case[&quot;must&quot;])<br>    return tool_ok, answer_ok</pre><p>Each case checks the <strong>trajectory</strong> (did the agent call the tool?) and the <strong>outcome</strong> (does the answer contain the required facts, or admit ignorance for out-of-scope questions?). This is a simplified version of what ADK’s adk eval and Google&#39;s agent evaluation service do at scale. Keyword checks are crude, so read the failures yourself before you trust a score.</p><h3>3. From notebook to production</h3><p>Here is the path I would take, with the articles that cover each step:</p><ol><li><strong>Move retrieval to a managed service.</strong> An in-memory index disappears with the process. Use RAG Engine or Vector Search, as in the RAG article, and tune chunking against your test set.</li><li><strong>Add safety and cost controls.</strong> Handle blocked requests and add a tool allowlist (safety article), and shape prompts for caching if you send a large fixed context (caching article).</li><li><strong>Deploy the agent.</strong> Use adk deploy cloud_run with IAM protection and a persistent session service (Cloud Run article).</li><li><strong>Connect it to other systems.</strong> Add MCP tools for data sources (MCP article), and expose the agent over A2A so other agents can call it (A2A article).</li><li><strong>Mix in other inputs.</strong> Accept scanned policy PDFs and photos (multimodal article), or add a voice front end (Live API article).</li><li><strong>Ground where the web helps.</strong> If employees also ask about public regulations, add Google Search grounding for those questions (grounding article).</li><li><strong>Monitor and evaluate continuously.</strong> Run your test set after every change, and sample production traffic (evaluation article).</li></ol><h3>4. Before you ship, check three things</h3><ul><li><strong>Retrieval:</strong> for each test question, is the right source document in the results? If not, fix chunking, the number of results or the embedding setup before touching the prompt.</li><li><strong>Agent behavior:</strong> did it call the tool when it should, and not when it should not?</li><li><strong>Answer quality and safety:</strong> are the facts right, are out-of-scope questions refused politely, and is no private data leaking?</li></ul><h3>5. The series in one picture</h3><ol><li><strong>Vertex AI and Gemini in 2026</strong>: the platform and models</li><li><strong>ADK 2.0</strong>: the agent framework</li><li><strong>Agent2Agent (A2A)</strong>: agents calling agents</li><li><strong>RAG on Google Cloud</strong>: retrieval from your data</li><li><strong>Evaluating AI agents</strong>: testing the agent</li><li><strong>Function calling and structured output</strong>: tools and JSON</li><li><strong>Gemini multimodal</strong>: images, video, audio and PDFs</li><li><strong>Gemini Live API</strong>: real-time voice</li><li><strong>Image generation</strong>: creating and editing images</li><li><strong>Safety and responsible AI</strong>: filters and defenses</li><li><strong>Context caching</strong>: cost and speed</li><li><strong>MCP tools in ADK</strong>: external tools and data</li><li><strong>Deploy to Cloud Run</strong>: going live</li><li><strong>Grounding with Google Search</strong>: fresh, cited answers</li><li><strong>This capstone</strong>: everything together</li></ol><h3>6. What I would build next</h3><ul><li>Replace the keyword evaluation with ADK evals and an LLM judge, and add your real questions.</li><li>Swap the toy documents for your own, and compare two chunk sizes on the same test set.</li><li>Put the agent behind IAM on Cloud Run, and call it from a small web page.</li><li>Add a second agent, such as an HR helper, and let the two talk over A2A.</li></ul><h3>Final thoughts</h3><p>The Google AI stack looks big when you read it piece by piece, but a useful project uses only a few pieces at a time: a model, some retrieval, an agent, a test set. Start small, measure honestly, and add one capability at a time. That is how a notebook becomes a product.</p><p><em>Every product, model name and API in this series is changing quickly. Verify details against the official documentation before you ship.</em></p><p><strong>Sources</strong></p><ul><li><a href="https://ai.google.dev/gemini-api/docs/embeddings">Embeddings (Google AI for Developers)</a></li><li><a href="https://adk.dev/evaluate/">Evaluate agents (ADK documentation)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/interactions">Interactions API overview (Google AI for Developers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=615d12b32d2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grounding with Google Search: Fresh, Cited Answers from the Live Web]]></title>
            <link>https://medium.com/@ameniselmi1925/grounding-with-google-search-fresh-cited-answers-from-the-live-web-5c19d9237a67?source=rss-d530e850bdd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c19d9237a67</guid>
            <category><![CDATA[grounding]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-search]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Ameni Selmi]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 16:18:13 GMT</pubDate>
            <atom:updated>2026-11-19T16:18:13.279Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Gemini’s built-in knowledge stops at a cutoff date. Grounding with Google Search lets it look things up and cite its sources. Here is how it works, what comes back, what it costs, and when to use it instead of RAG.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHSbu_r9b5K6S2dyaF7TMQ.png" /></figure><p>Ask a model about last week’s news and it either guesses or admits it does not know. <strong>Grounding with Google Search</strong> connects Gemini to real-time web content, so answers are more factually accurate and come with citations. This is article 14 of the series, based on Google’s grounding documentation as of October 2026. My own additions are marked.</p><h3>1. How it works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhjQRYbTMUu5O9XrOONXFA.png" /></figure><p>You add a tool to the request. After that, the model decides whether a search is needed, writes the search queries, processes the results and returns an answer with citations. You do not write any search code.</p><p>python</p><pre>from google import genai</pre><pre>client = genai.Client()</pre><pre>interaction = client.interactions.create(<br>    model=&quot;gemini-3.8-flash&quot;,  # use a current model ID<br>    input=&quot;Who won the Euro 2024?&quot;,<br>    tools=[{&quot;type&quot;: &quot;google_search&quot;}],<br>)</pre><pre>print(interaction.output_text)</pre><p>A detail that trips people up: current models use the tool type google_search. Older models used a google_search_retrieval tool, so old tutorials show different code.</p><h3>2. What comes back</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*feXA6r7BogoQsj4FJhHMxA.png" /></figure><p>A grounded response contains more than text. According to the docs, the interaction includes:</p><ul><li>a <strong>google_search_call</strong> step, listing the search queries the model ran,</li><li>a <strong>google_search_result</strong> step, which includes search_suggestions, an HTML snippet for rendering search suggestions in your UI,</li><li>and <strong>model_output</strong> text with inline <strong>url_citation annotations</strong>. Each has a URL, a title, and start_index and end_index values that map to a span of the answer text.</li></ul><p>Google says the usage requirements for search suggestions are in the Terms of Service, so read them before you build the UI.</p><h3>Showing citations</h3><p>To show sources next to the text they support, slice the answer using each annotation’s indices. This sketch follows the structure the docs describe. The exact attribute names can differ by SDK version, so print one real response and adjust:</p><p>python</p><pre>def cited_spans(interaction):<br>    &quot;&quot;&quot;Yield (cited_text, title, url) for each citation in the answer.&quot;&quot;&quot;<br>    for step in interaction.steps:<br>        if step.type != &quot;model_output&quot;:<br>            continue<br>        for block in step.content:<br>            if getattr(block, &quot;type&quot;, None) != &quot;text&quot;:<br>                continue<br>            for note in getattr(block, &quot;annotations&quot;, None) or []:<br>                if getattr(note, &quot;type&quot;, None) == &quot;url_citation&quot;:<br>                    span = block.text[note.start_index:note.end_index]<br>                    yield span, note.title, note.url<br></pre><pre>for span, title, url in cited_spans(interaction):<br>    print(f&#39;&quot;{span}&quot; -&gt; {title} ({url})&#39;)</pre><p>The point is the idea, not the exact names: every claim can be tied back to a source, so show them. This is my own advice: put the sources where users can see them, and let readers judge whether a source is trustworthy.</p><h3>3. What it costs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXchDnvfC_13EavJtHl62A.png" /></figure><p>For Gemini 3 and newer models, billing is <strong>per search query the model runs</strong>:</p><ul><li>the first <strong>5,000 search requests per month are free</strong>, shared across these models,</li><li>after that, the documented price is <strong>$14 per 1,000 requests</strong>,</li><li>one prompt can trigger several queries, and each counts. Empty queries are not counted.</li></ul><p>Gemini 2.5 and older models bill per prompt. Prices change, so check the pricing page. My own advice: because the model decides how many searches to run, track the count in your usage logs and set budget alerts.</p><h3>4. Tools you can combine it with</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzCR8CvFBJdckCZK6Uf23A.png" /></figure><p>Grounding works alongside other tools:</p><ul><li><strong>Function calling</strong>, supported on Gemini 3 models. See the function calling article.</li><li><strong>URL context</strong>, to ground answers in specific URLs you provide.</li><li><strong>Code execution</strong>, to compute on what was found.</li><li><strong>Google Maps grounding</strong>, supported on Gemini 3.5 Flash-Lite and later.</li></ul><p>A combined request simply lists several tools:</p><p>python</p><pre>interaction = client.interactions.create(<br>    model=&quot;gemini-3.8-flash&quot;,<br>    input=&quot;Find the latest Python release and write a one-line install check for it.&quot;,<br>    tools=[{&quot;type&quot;: &quot;google_search&quot;}, {&quot;type&quot;: &quot;code_execution&quot;}],<br>)</pre><p>I wrote that tool list from the types the docs name. Check the current docs for the exact tool type strings and for which model supports which combination.</p><h3>5. Grounding or RAG?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0synlWKJqq1SYqBa1SxHw.png" /></figure><p>They solve different problems. This table is my own guidance:</p><ul><li><strong>Public facts that change</strong> (news, prices, releases, documentation): use Google Search grounding.</li><li><strong>Your private documents</strong> (policies, contracts, internal wikis): use RAG, as in the RAG article. The public web does not contain them.</li><li><strong>Both kinds of questions:</strong> give the agent both tools, and instruct it which to use first. Evaluate the results, because the model chooses.</li></ul><h3>6. Practical advice</h3><ol><li><strong>Ground time-sensitive questions.</strong> Gemini 3’s knowledge cutoff is January 2025, so anything newer needs a search.</li><li><strong>Always show sources.</strong> Citations are the feature. Use the annotations, and render search suggestions as the terms require.</li><li><strong>Do not ground everything.</strong> Stable facts and pure reasoning do not need a search, which costs money and time.</li><li><strong>Test for source quality.</strong> The web includes wrong and low-quality pages. Check answers on topics where errors would matter.</li><li><strong>Treat retrieved text as untrusted.</strong> Web pages can contain instructions aimed at models. This is my own advice: validate before acting on grounded content, especially in agents with tools.</li><li><strong>Measure cost.</strong> Log the number of search queries per request.</li></ol><h3>7. Where to start</h3><ol><li>Run the basic example with a question about something recent.</li><li>Print the whole interaction and read the steps and annotations.</li><li>Build a small function that shows each citation next to the text.</li><li>Compare an answer with and without the search tool.</li><li>Add the tool to an ADK agent alongside your own tools.</li></ol><h3>Final thoughts</h3><p>Grounding turns Gemini from a model with a fixed memory into one that can check the world, and it does so with one line in the request. What makes it production-ready is what you do around it: show your sources, watch your costs, and know when your own data, not the web, is the right source.</p><p><em>Grounding behavior, pricing and supported models change often. Verify details against the official documentation before you ship.</em></p><p><strong>Sources</strong></p><ul><li><a href="https://ai.google.dev/gemini-api/docs/grounding">Grounding with Google Search (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/interactions">Interactions API overview (Google AI for Developers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c19d9237a67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy ADK Agents to Cloud Run: From Local Agent to Live Service]]></title>
            <link>https://medium.com/@ameniselmi1925/deploy-adk-agents-to-cloud-run-from-local-agent-to-live-service-dcdb06bed2e9?source=rss-d530e850bdd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcdb06bed2e9</guid>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <dc:creator><![CDATA[Ameni Selmi]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 15:54:35 GMT</pubDate>
            <atom:updated>2026-11-19T15:54:35.249Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An agent that only runs on your laptop helps nobody. Here is how to deploy an ADK agent to Cloud Run with one command, protect it, keep its state, and test it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUP508riX5RRmhnwc6lxdA.png" /></figure><p>You built an agent with ADK, gave it tools, and tested it in adk web. Now other people and other systems need to call it. <strong>Cloud Run</strong> is Google Cloud&#39;s managed container platform, and ADK ships a command that deploys an agent there. This is article 13 of the series. The commands come from the ADK deployment documentation as of October 2026, with my own additions marked.</p><h3>1. From folder to service</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_FsTep58sGII42Xtvz11g.png" /></figure><p>Your agent folder needs three things: an __init__.py, an agent.py that defines root_agent, and a requirements.txt. The deploy command packages the folder, Cloud Build creates a container image, and Cloud Run serves it at a URL.</p><p>Prerequisites, from the docs:</p><ul><li>a Google Cloud project, a location and a service account,</li><li>the gcloud CLI, logged in (gcloud auth login) with your project set (gcloud config set project &lt;your-project-id&gt;),</li><li>a GOOGLE_API_KEY secret that your service account can read,</li><li>the Cloud Build permission roles/cloudbuild.builds.builder for the default compute service account,</li><li>and secret read access with roles/secretmanager.secretAccessor.</li></ul><p>The docs set these environment variables before deploying:</p><p>bash</p><pre>export GOOGLE_CLOUD_PROJECT=&quot;your-gcp-project-id&quot;<br>export GOOGLE_CLOUD_LOCATION=&quot;us-central1&quot;<br>export GOOGLE_GENAI_USE_ENTERPRISE=True</pre><p>The docs use both a GOOGLE_API_KEY secret and the enterprise setting, which correspond to the two ways ADK can reach Gemini (the Gemini API and the Google Cloud platform). Follow the current ADK page for the combination that matches how you authenticate.</p><h3>2. Two ways to deploy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4EIykFIELVBv0pZ7yNuOw.png" /></figure><h3>Option 1: the ADK CLI (recommended for Python)</h3><p>bash</p><pre>adk deploy cloud_run \<br>  --project=$GOOGLE_CLOUD_PROJECT \<br>  --region=$GOOGLE_CLOUD_LOCATION \<br>  --service_name=capital-agent-service \<br>  --app_name=capital_agent_app \<br>  --with_ui \<br>  ./capital_agent</pre><p>Notes from the docs:</p><ul><li>--project and --region are required. --service_name defaults to adk-default-service-name.</li><li>--with_ui deploys the development UI too. By default only the API server is deployed. My advice: leave the UI off for anything other than a demo.</li><li>--port defaults to 8000, and --allow_origins sets CORS.</li><li>To pass flags to gcloud, add them after --, for example -- --no-allow-unauthenticated --min-instances=2.</li></ul><h3>Option 2: gcloud run deploy with a Dockerfile</h3><p>This is more manual but lets you embed the agent in a custom FastAPI app. The docs describe a main.py that calls get_fast_api_app() from google.adk.cli.fast_api and serves on the PORT variable, with a Dockerfile based on python:3.13-slim that runs uvicorn main:app --host 0.0.0.0 --port $PORT. Then:</p><p>bash</p><pre>gcloud run deploy capital-agent-service \<br>  --source . \<br>  --region $GOOGLE_CLOUD_LOCATION \<br>  --project $GOOGLE_CLOUD_PROJECT \<br>  --no-allow-unauthenticated \<br>  --set-env-vars=&quot;GOOGLE_CLOUD_PROJECT=$GOOGLE_CLOUD_PROJECT,GOOGLE_CLOUD_LOCATION=$GOOGLE_CLOUD_LOCATION,GOOGLE_GENAI_USE_ENTERPRISE=$GOOGLE_GENAI_USE_ENTERPRISE&quot;</pre><p>I changed the docs’ --allow-unauthenticated to --no-allow-unauthenticated here, on purpose. See the next section.</p><h3>3. Who can call your service?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlOCT9P4tveZSb6UrOHJ_w.png" /></figure><p>An agent endpoint can spend money (model calls) and reach your tools, so access control matters.</p><ul><li><strong>Public:</strong> --allow-unauthenticated lets anyone with the URL call it. In the ADK CLI you get a prompt, &quot;Allow unauthenticated invocations&quot;, and answering y means public. This is only appropriate for deliberate public demos, and you should watch costs.</li><li><strong>IAM protected:</strong> answer N in the CLI, or omit --allow-unauthenticated in gcloud. Callers must then present an identity token and have permission to invoke the service. My advice is to make this your default.</li></ul><p>To call a protected service, get a token:</p><p>bash</p><pre>export TOKEN=$(gcloud auth print-identity-token)</pre><h3>4. Test the live service</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XITiJQ0xLeGYXmUZ1Or-Ew.png" /></figure><p>The docs’ test calls use the ADK API server endpoints:</p><p>bash</p><pre>export APP_URL=&quot;YOUR_CLOUD_RUN_SERVICE_URL&quot;</pre><pre># See the deployed agents<br>curl -X GET -H &quot;Authorization: Bearer $TOKEN&quot; $APP_URL/list-apps</pre><pre># Create or update a session<br>curl -X POST -H &quot;Authorization: Bearer $TOKEN&quot; \<br>  $APP_URL/apps/capital_agent/users/user_123/sessions/session_abc \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;preferred_language&quot;: &quot;English&quot;, &quot;visit_count&quot;: 5}&#39;</pre><pre># Run the agent (set &quot;streaming&quot;: true for server-sent events)<br>curl -X POST -H &quot;Authorization: Bearer $TOKEN&quot; \<br>  $APP_URL/run_sse \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;app_name&quot;: &quot;capital_agent&quot;, &quot;user_id&quot;: &quot;user_123&quot;, &quot;session_id&quot;: &quot;session_abc&quot;,<br>       &quot;new_message&quot;: {&quot;role&quot;: &quot;user&quot;, &quot;parts&quot;: [{&quot;text&quot;: &quot;What is the capital of Canada?&quot;}]},<br>       &quot;streaming&quot;: false}&#39;</pre><p>Omit the Authorization header only if the service allows unauthenticated access.</p><h3>5. Where state lives</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XITiJQ0xLeGYXmUZ1Or-Ew.png" /></figure><p>Cloud Run instances come and go. If you set neither --session_service_uri nor --artifact_service_uri, the container uses <strong>in-memory</strong> services, and the data is lost when an instance recycles. The docs say to set both for any deployment that must keep state:</p><ul><li>Session URIs include agentengine://, memory:// and SQLAlchemy URLs.</li><li>Artifact URIs include gs://&lt;bucket&gt;, file:// and memory://.</li></ul><p>In the Dockerfile approach you configure the session service inside get_fast_api_app(). The docs&#39; example uses sqlite+aiosqlite, which needs an async driver. My own note: SQLite inside a container is still local to the instance, so for real production state use a managed database or the managed session options.</p><h3>6. Production checklist</h3><p>The items from the docs come first, and then my own guidance.</p><ol><li><strong>Set session and artifact services</strong> so state survives restarts.</li><li><strong>Use IAM authentication</strong> unless the service is meant to be public.</li><li><strong>Keep secrets in Secret Manager</strong>, not in code or images.</li><li><strong>Pin versions</strong> of google-adk and other dependencies in requirements.txt.</li><li><strong>Set min and max instances</strong> with the gcloud flags, to balance cold starts against cost.</li><li><strong>Add budgets and alerts</strong>, because every request can trigger model calls.</li><li><strong>Log and trace</strong> agent runs so you can debug failures after the fact.</li><li><strong>Run your evaluation set</strong> against the deployed service, not only locally (see the evaluation article).</li><li><strong>Control cross-origin access</strong> with --allow_origins if a browser calls it directly.</li></ol><h3>7. Where to start</h3><ol><li>Make sure your agent folder has __init__.py, agent.py and requirements.txt.</li><li>Deploy to a test project with IAM protection on.</li><li>Call /list-apps, create a session and run one message with curl.</li><li>Add a session service and check that a session survives a redeploy.</li><li>Wire the URL into your app, or expose it as an A2A agent (see the A2A article).</li></ol><h3>Final thoughts</h3><p>Deployment is where agents meet the rest of engineering: identity, state, cost and monitoring. ADK’s one-command deploy gets you a working URL in minutes. The checklist above is what turns that URL into a service you can trust.</p><p><em>Commands, flags and defaults change between ADK releases. Verify them against the current documentation before you deploy.</em></p><p><strong>Sources</strong></p><ul><li><a href="https://adk.dev/deploy/cloud-run/">Deploy to Cloud Run (adk.dev)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcdb06bed2e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCP Tools in ADK: Connect Your Agent to External Tools and Data]]></title>
            <link>https://medium.com/@ameniselmi1925/mcp-tools-in-adk-connect-your-agent-to-external-tools-and-data-62d4261a7afd?source=rss-d530e850bdd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/62d4261a7afd</guid>
            <category><![CDATA[mcp-tool]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Ameni Selmi]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 14:41:13 GMT</pubDate>
            <atom:updated>2026-11-04T14:41:13.273Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The Model Context Protocol gives agents a standard way to use tools. ADK wraps it in one class, McpToolset. Here is how to connect to local and remote MCP servers, limit what your agent can do, and handle authentication.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZv2aw6AVtkcjRIUJDICfA.png" /></figure><p>Every agent eventually needs tools: read a file, query a database, search a map. Writing a custom function for each one does not scale, especially when good tools already exist as servers. The <strong>Model Context Protocol (MCP)</strong> is the open standard for exposing tools and data to AI agents, and Google’s <strong>Agent Development Kit (ADK)</strong> supports it through McpToolset.</p><p>This is article 12 of the series. The code comes from the ADK documentation as of October 2026, with my own additions marked. If you have not read the ADK and A2A articles, a quick reminder: MCP connects an agent to <strong>tools and data</strong>, while A2A connects an agent to <strong>other agents</strong>.</p><h3>1. How an agent reaches MCP servers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-4WxkcmNYWiGrAFVI8lug.png" /></figure><p>Your agent holds a McpToolset. The toolset opens a connection to an MCP server, asks it which tools it has, and presents them to the model as ordinary tools. One agent can use several toolsets, each pointing at a different server.</p><p>Install ADK with the MCP extra:</p><p>bash</p><pre>pip install &quot;google-adk[mcp]&quot;</pre><h3>2. Three ways to connect</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5s6JmVCKB6rMPElJXtmADA.png" /></figure><ul><li><strong>StdioConnectionParams</strong> starts a local server as a subprocess. This is how most community servers run, often with npx.</li><li><strong>StreamableHTTPConnectionParams</strong> connects to a remote server over HTTP.</li><li><strong>SseConnectionParams</strong> connects to a remote server over server-sent events.</li></ul><h3>A local server (stdio)</h3><p>This example gives an agent a filesystem server. It needs Node.js and npx:</p><p>python</p><pre>import os</pre><pre>from google.adk.agents import LlmAgent<br>from google.adk.tools.mcp_tool import McpToolset<br>from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams<br>from mcp import StdioServerParameters</pre><pre>TARGET_FOLDER = os.path.abspath(&quot;./accessible_files&quot;)</pre><pre>root_agent = LlmAgent(<br>    model=&quot;gemini-flash-latest&quot;,  # pin an exact model ID for real projects<br>    name=&quot;filesystem_assistant&quot;,<br>    instruction=&quot;Help users manage local files.&quot;,<br>    tools=[<br>        McpToolset(<br>            connection_params=StdioConnectionParams(<br>                server_params=StdioServerParameters(<br>                    command=&quot;npx&quot;,<br>                    args=[&quot;-y&quot;, &quot;@modelcontextprotocol/server-filesystem&quot;, TARGET_FOLDER],<br>                ),<br>            ),<br>            tool_filter=[&quot;list_directory&quot;, &quot;read_file&quot;],<br>        )<br>    ],<br>)</pre><p>Put an __init__.py next to agent.py and run adk web from the parent directory of the agent folder.</p><h3>A remote server (HTTP)</h3><p>This example, from the docs, connects to a Google Maps MCP server with an API key header:</p><p>python</p><pre>import os</pre><pre>from google.adk.agents import LlmAgent<br>from google.adk.tools.mcp_tool import McpToolset<br>from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams</pre><pre>API_KEY = os.getenv(&quot;GOOGLE_MAPS_API_KEY&quot;)</pre><pre>root_agent = LlmAgent(<br>    model=&quot;gemini-flash-latest&quot;,<br>    name=&quot;travel_planner&quot;,<br>    instruction=&quot;Plan travel routes and search locations using Google Maps.&quot;,<br>    tools=[<br>        McpToolset(<br>            connection_params=StreamableHTTPConnectionParams(<br>                url=&quot;https://mapstools.googleapis.com/mcp&quot;,<br>                headers={<br>                    &quot;X-Goog-Api-Key&quot;: API_KEY,<br>                    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>                    &quot;Accept&quot;: &quot;application/json, text/event-stream&quot;,<br>                },<br>                timeout=5,<br>                sse_read_timeout=300,<br>            )<br>        )<br>    ],<br>)</pre><h3>3. Expose only what the agent needs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6SoNrckhoNVB429PP51aQ.png" /></figure><p>An MCP server may offer many tools, including ones that write or delete. The tool_filter parameter limits which of them the model can see and call. In the filesystem example above, the agent can only list directories and read files, so it cannot write or delete anything. The ADK docs recommend always setting it.</p><p>This is the most important security habit with MCP, and it is the same principle as the safety article’s tool allowlist: give an agent only what it needs. My own addition: also read what a third-party server’s tools actually do before you connect, and prefer servers you trust.</p><h3>4. Authentication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GS_51a6yr3zJyPfhKEnShg.png" /></figure><p>The simple way is a header. This example passes a bearer token from an environment variable:</p><p>python</p><pre>import os</pre><pre>from google.adk.tools.mcp_tool import McpToolset<br>from google.adk.tools.mcp_tool.mcp_session_manager import SseConnectionParams</pre><pre>toolset = McpToolset(<br>    connection_params=SseConnectionParams(<br>        url=&quot;https://mcp-server.example.com/sse&quot;,<br>        headers={&quot;Authorization&quot;: f&quot;Bearer {os.getenv(&#39;MCP_AUTH_TOKEN&#39;)}&quot;},<br>        timeout=5,<br>    )<br>)</pre><p>The docs also describe native auth_scheme and auth_credential parameters, which ADK uses to build Authorization headers and to handle OAuth 2.0 token refresh. The docs recommend them over manual header injection, but the page I read did not show Python code for them, so follow the current ADK documentation for the exact usage. Whichever you use, keep tokens in environment variables or a secret manager, never in source files.</p><h3>5. Production notes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOLc3dZB7bL3zLm4l4F3lg.png" /></figure><p>From the ADK docs:</p><ul><li><strong>Creation:</strong> agents deployed to production must create McpToolset synchronously in agent.py. Async initialization is only for local debugging or custom standalone runners.</li><li><strong>Timeouts:</strong> set explicit timeouts, such as timeout=5, to avoid hung subprocesses.</li><li><strong>Closing:</strong> McpToolset opens the connection when it is initialized and shuts it down when the agent or process ends. In runners other than adk web, close it with await toolset.close() or an async context manager, so subprocesses exit cleanly.</li><li><strong>Reconnects:</strong> ADK does not automatically reconnect MCP sessions after state restoration, so agents re-initialize connections as needed.</li></ul><p>My own notes for production: stdio servers run as subprocesses inside your container, so they need their runtime (such as Node.js) installed in the image. Remote servers add network latency and failure modes, so handle tool errors gracefully, as covered in the function calling article.</p><h3>6. The other direction: ADK tools as an MCP server</h3><p>ADK can also go the other way. The docs name to_mcp_server as the way to wrap ADK tools in an MCP server that external clients can call. I did not read the page that explains it, so see &quot;Agent as MCP server&quot; in the ADK documentation if you want to share your own tools with other MCP clients.</p><h3>7. Where to start</h3><ol><li>Install google-adk[mcp] and run the filesystem example with a folder of test files.</li><li>Open adk web and ask the agent to list and read files.</li><li>Try removing tool_filter and see which extra tools appear. Then put it back.</li><li>Connect a remote server with a header token.</li><li>Add the agent to an evaluation set that checks which tools it calls.</li></ol><h3>Final thoughts</h3><p>MCP turns “write a custom integration” into “connect to a server”. ADK makes that a few lines of code. The cost of that convenience is trust: every connected server extends what your agent can do, so filter tools, protect credentials and test what the agent actually calls.</p><p><em>MCP and ADK are evolving quickly. Verify imports, class names and parameters against the current documentation before you ship.</em></p><p><strong>Sources</strong></p><ul><li><a href="https://adk.dev/tools-custom/mcp-tools/">MCP tools in ADK (adk.dev)</a></li><li><a href="https://adk.dev/tools-custom/mcp-tools/agent-as-server/">Agent as MCP server (adk.dev)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62d4261a7afd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context Caching for Gemini: Pay Less and Answer Faster on Repeated Context]]></title>
            <link>https://medium.com/@ameniselmi1925/context-caching-for-gemini-pay-less-and-answer-faster-on-repeated-context-72f640debb76?source=rss-d530e850bdd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/72f640debb76</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[context]]></category>
            <dc:creator><![CDATA[Ameni Selmi]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 14:32:37 GMT</pubDate>
            <atom:updated>2026-11-04T14:32:37.102Z</atom:updated>
            <content:encoded><![CDATA[<p><em>If every request starts with the same long document or instructions, you are paying to process it again and again. Context caching fixes that. Here is how implicit and explicit caching work, and how to use both.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TR_gC1m85kd14OE6XbNFw.png" /></figure><p>Many Gemini apps send the same large block of text on every request: a long system prompt, a policy manual, a codebase, a transcript. Processing that block every time costs money and time. <strong>Context caching</strong> lets Gemini reuse it. This is article 11 of the series, based on Google’s caching documentation as of October 2026. My own additions are marked.</p><h3>1. Two kinds of caching</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YI2I62Vk1t5Ypm3t5fPIVg.png" /></figure><ul><li><strong>Implicit caching</strong> is automatic. It is on by default for Gemini 2.5 and newer models, and it works in both stateful conversations (previous_interaction_id) and stateless ones. Google says cost savings pass through automatically when a request hits a cache, and you configure nothing.</li><li><strong>Explicit caching</strong> is something you create and manage yourself. An important detail from the docs: it is <strong>not supported in the Interactions API</strong>, and not supported for Gemini 4 Argon and later. To use it on supported Gemini 3 and 2.5 models, you switch to the older generateContent API. The explicit caching docs also mark it as <strong>Beta</strong> (v1beta).</li></ul><p>So for new projects on the Interactions API, implicit caching is the path you get, and your job is to shape your prompts so it works well.</p><h3>2. Make implicit caching work for you</h3><p>Google’s two tips are simple:</p><ol><li>Put large, common content at the <strong>beginning</strong> of the prompt.</li><li>Send requests with <strong>similar prefixes</strong> within a short time.</li></ol><p>The idea is that a cache matches the start of a prompt. If the stable part comes first and the changing part (the user’s question) comes last, the stable prefix can be reused. If you put the question first, nothing matches.</p><p>python</p><pre>from google import genai</pre><pre>client = genai.Client()<br>MODEL = &quot;gemini-3.8-flash&quot;  # use a current model ID</pre><pre>POLICY_MANUAL = open(&quot;policy_manual.txt&quot;).read()  # large, same every time<br></pre><pre>def ask(question):<br>    return client.interactions.create(<br>        model=MODEL,<br>        input=[<br>            {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: POLICY_MANUAL},  # stable prefix first<br>            {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: f&quot;Question: {question}&quot;},  # changing part last<br>        ],<br>    )<br></pre><pre>for q in [&quot;How many leave days do I get?&quot;, &quot;What is the expense limit for meals?&quot;]:<br>    interaction = ask(q)<br>    print(interaction.output_text)<br>    # Google says cached tokens are reported in usage.total_cached_tokens.<br>    print(&quot;cached tokens:&quot;, getattr(interaction.usage, &quot;total_cached_tokens&quot;, None))</pre><p>The second request should report cached tokens if the first one populated a cache, but hits are not guaranteed. Print the usage field to see what actually happened.</p><h3>Minimum sizes</h3><p>Small prompts are not cached. The minimum input for implicit caching is:</p><ul><li><strong>4,096 tokens</strong> for Gemini 4 Argon, 3.8 Flash, 3.6 Flash and 3.1 Pro Preview</li><li><strong>2,048 tokens</strong> for Gemini 2.5 Flash and 2.5 Pro</li></ul><p>The docs say the explicit caching minimum varies by model, so check the token guide for it.</p><h3>3. Explicit caching with generateContent</h3><p>Use this when you need guaranteed reuse of a known document for a period of time, and you can work on a supported model with generateContent. This follows Google&#39;s examples:</p><p>python</p><pre>from google import genai<br>from google.genai import types</pre><pre>client = genai.Client()<br>model = &quot;gemini-3.8-flash&quot;  # use a model that supports explicit caching</pre><pre>doc = client.files.upload(<br>    file=&quot;path/to/transcript.pdf&quot;,<br>    config={&quot;mime_type&quot;: &quot;application/pdf&quot;},<br>)</pre><pre>cache = client.caches.create(<br>    model=model,<br>    config=types.CreateCachedContentConfig(<br>        display_name=&quot;transcript cache&quot;,<br>        system_instruction=&quot;You are an expert analyzing transcripts.&quot;,<br>        contents=[doc],<br>        ttl=&quot;300s&quot;,  # omit to use the default<br>    ),<br>)</pre><pre>response = client.models.generate_content(<br>    model=model,<br>    contents=&quot;Please summarize this transcript&quot;,<br>    config=types.GenerateContentConfig(cached_content=cache.name),<br>)<br>print(response.usage_metadata)<br>print(response.text)</pre><h3>Manage the cache</h3><p>python</p><pre># List metadata for all caches<br>for c in client.caches.list():<br>    print(c)</pre><pre># Get one cache by name<br>client.caches.get(name=cache.name)</pre><pre># Extend the TTL<br>client.caches.update(<br>    name=cache.name,<br>    config=types.UpdateCachedContentConfig(ttl=&quot;600s&quot;),<br>)</pre><pre># Delete when you are done<br>client.caches.delete(cache.name)</pre><p>Details from the docs:</p><ul><li>If you set no TTL, it defaults to <strong>1 hour</strong>, and there are no minimum or maximum bounds.</li><li>You can set expire_time (a timezone-aware datetime) instead of a TTL.</li><li>You cannot read cached content back, only its metadata.</li><li>Standard rate limits apply, and token limits include cached tokens.</li></ul><h3>4. What it costs</h3><p>For explicit caching, Google says you pay for:</p><ul><li><strong>cached input tokens</strong> at a reduced rate,</li><li><strong>storage</strong>, based on how long the TTL keeps the cache,</li><li>and the normal rates for new (non-cached) input and for output.</li></ul><p>I did not find specific prices in the pages I read, so see the pricing page. Storage time matters: a cache that sits unused still costs money. My own advice is to delete caches when a task ends and to set a TTL close to the real usage window.</p><h3>5. When is caching worth it?</h3><p>This section is my own guidance.</p><ul><li><strong>Good fit:</strong> a long, stable context asked many questions, such as a manual, a contract, a codebase or a long transcript, especially when requests arrive close together.</li><li><strong>Poor fit:</strong> one-off questions, or a stable context so small that it falls below the minimum.</li><li><strong>Measure it.</strong> Look at the usage fields before and after you reorder a prompt. If cached tokens stay at zero, check your prompt order, the minimum size and the timing of requests.</li><li><strong>Watch freshness.</strong> A cache holds the content as it was. If the document changes, create a new cache.</li><li><strong>Privacy.</strong> Cached content may include sensitive data, so apply the same retention and access thinking as for any stored data.</li></ul><h3>6. Where to start</h3><ol><li>Find the largest repeated block in your prompts.</li><li>Move it to the start and the question to the end.</li><li>Print the cached token count across several requests.</li><li>If you need guaranteed reuse and your model supports it, try an explicit cache with a short TTL.</li><li>Compare costs for a day of real traffic.</li></ol><h3>Final thoughts</h3><p>Caching is one of the cheapest optimizations available: for many apps it is a matter of reordering a prompt. Implicit caching does the work for you when your prompts are shaped well, and explicit caching is there when you need control, with the caveat that it lives on the older API for now.</p><p><em>Caching support differs by model and API and is changing. Verify details against the official documentation before you ship.</em></p><p><strong>Sources</strong></p><ul><li><a href="https://ai.google.dev/gemini-api/docs/caching">Context caching (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/generate-content/caching">Context caching with generateContent (Google AI for Developers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72f640debb76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Safety and Responsible AI with Gemini: Filters, Errors and Defenses Around Your App]]></title>
            <link>https://medium.com/@ameniselmi1925/safety-and-responsible-ai-with-gemini-filters-errors-and-defenses-around-your-app-2fac145928ab?source=rss-d530e850bdd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fac145928ab</guid>
            <category><![CDATA[safety]]></category>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[responsible-ai]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Ameni Selmi]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 15:11:54 GMT</pubDate>
            <atom:updated>2026-10-31T15:11:54.622Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A model’s built-in safety is only the first layer. Here is what the Gemini API gives you, what a blocked request looks like, and what you still have to build yourself.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eo0_oACEknOUFuSdghvkXg.png" /></figure><p>When an AI feature goes wrong in production, the cause is rarely only the model. It is usually an app that trusted user input, ran a tool without checking, or showed an answer without review. This article covers the safety controls the Gemini API provides and the extra defenses your own code needs. It is article 10 of the series, drawing on Google’s safety settings documentation as of October 2026. Parts that are my own guidance are labeled.</p><h3>1. Safety is layers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_SDX7zfGpesMcwXir2Ss8w.png" /></figure><p>Think of four layers:</p><ol><li><strong>Built-in protections</strong> that are always on. Google’s docs say protections against core harms, such as content that endangers child safety, are always blocked and cannot be changed.</li><li><strong>Adjustable safety filters</strong> whose thresholds you set.</li><li><strong>Your app:</strong> validation of inputs, outputs and tool actions. (My guidance.)</li><li><strong>People:</strong> review, user feedback and monitoring. (My guidance.)</li></ol><h3>2. The adjustable filters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgcpMyZDfwML8rWLZ0TIjw.png" /></figure><p>The documented categories are harassment, hate speech, sexually explicit content, dangerous content and jailbreak. For each one you can set a threshold:</p><ul><li>off</li><li>block_only_high (labeled &quot;Block few&quot; in AI Studio)</li><li>block_medium_and_above (&quot;Block some&quot;)</li><li>block_low_and_above (&quot;Block most&quot;)</li></ul><p>Google’s docs say the additional filters are <strong>off by default</strong> for Gemini 2.5 and later models, and that unset categories use the default. You can set one entry per category. Here is the documented Interactions API pattern:</p><p>python</p><pre>from google import genai</pre><pre>client = genai.Client()</pre><pre>interaction = client.interactions.create(<br>    model=&quot;gemini-3.8-flash&quot;,  # use a current model ID<br>    input=&quot;Summarize this customer complaint politely.&quot;,<br>    safety_settings=[<br>        {&quot;type&quot;: &quot;hate_speech&quot;, &quot;threshold&quot;: &quot;block_low_and_above&quot;},<br>        {&quot;type&quot;: &quot;harassment&quot;, &quot;threshold&quot;: &quot;block_medium_and_above&quot;},<br>    ],<br>)<br>print(interaction.output_text)</pre><p>Google’s guidance is to change settings only when your application consistently needs it, because default behavior covers most use cases. Two cautions from the docs: the API rates the <strong>probability</strong> that content is unsafe, not its <strong>severity</strong>, so severe harms can still receive a low probability score, and apps with less restrictive settings may be reviewed against the terms of service.</p><h3>3. What a blocked request looks like</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-jpkXcamNsgCNi9192DmQ.png" /></figure><p>When a filter blocks an input or a response, the request fails with <strong>HTTP 400</strong> and the blocked content is not returned. The error carries a reason code:</p><ul><li>safety: blocked by a safety filter</li><li>jailbreak, prohibited_content or blocklist: the input was blocked for that reason, with a message starting &quot;Input blocked:&quot;</li></ul><p>For background interactions the status is failed and the error appears in errors. For streaming, the error arrives as an error event.</p><p>Your code must handle this path, because a safety block is a normal outcome, not a crash. This sketch is my own, and the exact way the SDK exposes the reason code may differ, so check what your SDK version returns:</p><p>python</p><pre>from google import genai<br>from google.genai import errors</pre><pre>client = genai.Client()<br></pre><pre>def safe_ask(prompt):<br>    try:<br>        interaction = client.interactions.create(<br>            model=&quot;gemini-3.8-flash&quot;,<br>            input=prompt,<br>        )<br>        return {&quot;ok&quot;: True, &quot;text&quot;: interaction.output_text}<br>    except errors.APIError as exc:<br>        # A 400 can be a safety block, but can also be a malformed request.<br>        message = str(exc)<br>        blocked = exc.code == 400 and any(<br>            word in message.lower()<br>            for word in (&quot;safety&quot;, &quot;jailbreak&quot;, &quot;prohibited&quot;, &quot;blocklist&quot;, &quot;blocked&quot;)<br>        )<br>        if blocked:<br>            return {&quot;ok&quot;: False, &quot;reason&quot;: &quot;blocked&quot;, &quot;detail&quot;: message}<br>        raise</pre><p>Show users a clear, kind message when a request is blocked, and log the reason for your own review. Do not retry the same prompt in a loop.</p><h3>4. Defenses you add in your own code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k61wbZ2KpXYzXnVdWa2baA.png" /></figure><p>This section is my own guidance, not from the Gemini docs.</p><p><strong>Inputs.</strong> Limit length and file types, and treat user text, uploaded files and retrieved documents as untrusted. A document in your RAG index can contain text that tries to give the model instructions.</p><p><strong>Tools.</strong> Agents turn bad output into real actions, so apply least privilege. Give each agent only the tools it needs, validate arguments before running anything, and require confirmation for actions with side effects. A small allowlist plus a confirmation rule goes a long way:</p><p>python</p><pre>ALLOWED_TOOLS = {&quot;search_policies&quot;, &quot;get_weather&quot;}<br>NEEDS_CONFIRMATION = {&quot;send_email&quot;, &quot;delete_record&quot;}<br></pre><pre>def check_tool_call(name, user_confirmed=False):<br>    &quot;&quot;&quot;Return (allowed, reason) for a model-requested tool call.&quot;&quot;&quot;<br>    if name in NEEDS_CONFIRMATION:<br>        return (user_confirmed, &quot;needs user confirmation&quot;)<br>    if name not in ALLOWED_TOOLS:<br>        return (False, f&quot;tool not allowed: {name}&quot;)<br>    return (True, &quot;ok&quot;)</pre><p><strong>Outputs.</strong> Validate formats with a schema (see the function calling article), check for sensitive data before showing or storing text, and keep logs so you can review failures.</p><h3>5. A safety habit for every release</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2K1_IxykvrVLDqzvkdzwiw.png" /></figure><ol><li><strong>Test with risky inputs</strong> before launch: abusive text, injection attempts, off-topic requests, and edge cases from your own domain. Add them to your evaluation set (see the evaluation article).</li><li><strong>Adjust one setting at a time</strong> and re-run the same tests, so you know what changed.</li><li><strong>Monitor real usage.</strong> Sample conversations, track blocked requests and read user reports.</li><li><strong>Review and improve.</strong> Every incident becomes a new test case.</li></ol><h3>6. Responsible-use checklist</h3><ul><li>Tell users when they are talking to AI, and what it cannot do.</li><li>Keep a human in the loop for high-stakes decisions in medical, legal, financial or employment areas.</li><li>Do not collect more personal data than you need, and check retention terms before you store prompts and outputs.</li><li>Make it easy for users to report a bad answer.</li><li>Document your settings and the reasons for them.</li><li>Check the current terms of service and usage policies before you ship.</li></ul><h3>7. Where to start</h3><ol><li>Leave the defaults on, and write 20 risky test prompts for your own use case.</li><li>Add the safe_ask pattern so blocks are handled gracefully.</li><li>Add a tool allowlist and confirmation rule to any agent.</li><li>Run the tests after every model, prompt or setting change.</li><li>Set up a simple review process for reported problems.</li></ol><h3>Final thoughts</h3><p>Safety is not a switch you flip once. The Gemini API gives you strong defaults and a few knobs. The rest, such as validation, permissions, review and honesty with users, is your application’s job. The good news is that those habits are ordinary engineering, and they make your product better as well as safer.</p><p><em>Safety settings, defaults and error shapes can change. Verify them against the official documentation before you ship.</em></p><p><strong>Sources</strong></p><ul><li><a href="https://ai.google.dev/gemini-api/docs/safety-settings">Safety settings (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/interactions">Interactions API overview (Google AI for Developers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fac145928ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Generation with Gemini: Create and Edit Images with Nano Banana]]></title>
            <link>https://medium.com/@ameniselmi1925/image-generation-with-gemini-create-and-edit-images-with-nano-banana-fd65e41c9614?source=rss-d530e850bdd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd65e41c9614</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Ameni Selmi]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 13:44:39 GMT</pubDate>
            <atom:updated>2026-10-31T13:44:39.162Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Gemini can generate and edit images through the same API you use for text. Here are the models, how to generate, edit and refine, what the limits are, and what to remember about cost and watermarks.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQitfVvGL_1PgfxZzOOlSA.png" /></figure><p>Gemini’s image models, branded <strong>Nano Banana</strong>, let you create pictures from text, edit an existing image with instructions, and refine results over several turns. You use the same google-genai library and the same Interactions API as in the earlier articles. This is article 9 of the series, based on Google&#39;s image generation documentation as of October 2026. My own additions are marked.</p><h3>1. The model lineup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3DtY1co72gQlbT6ihi8oQ.png" /></figure><p>Per Google’s docs:</p><ul><li><strong>Nano Banana 2.1</strong> (gemini-nano-banana-2.1): the recommended model for generation and conversational editing.</li><li><strong>Nano Banana 2 Lite</strong> (gemini-3.1-flash-lite-image): the fastest and cheapest. It does not support multiple reference inputs or multi-turn sequential editing.</li><li><strong>Nano Banana Pro</strong> (gemini-3-pro-image): the premium model for complex tasks and precise creative control.</li><li><strong>Nano Banana 2</strong> (gemini-3.1-flash-image): the previous generation. New projects should use 2.1.</li><li><strong>Nano Banana</strong> (gemini-2.5-flash-image): the legacy model.</li></ul><p>Model names and IDs change often, so check the docs before you pick one.</p><h3>2. Three jobs, one API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWC5kBgmNUEFoD4waw0xPw.png" /></figure><h3>Text to image</h3><p>python</p><pre>import base64</pre><pre>from google import genai</pre><pre>client = genai.Client()<br>MODEL = &quot;gemini-nano-banana-2.1&quot;  # use a current model ID<br></pre><pre>def save_image(interaction, path):<br>    &quot;&quot;&quot;Write the last generated image to a file.&quot;&quot;&quot;<br>    with open(path, &quot;wb&quot;) as f:<br>        f.write(base64.b64decode(interaction.output_image.data))<br></pre><pre>interaction = client.interactions.create(<br>    model=MODEL,<br>    input=&quot;A watercolor painting of a lighthouse at sunrise, soft pastel colors&quot;,<br>)<br>save_image(interaction, &quot;lighthouse.png&quot;)</pre><p>The interaction.output_image property returns the last generated image block, and its data field is base64. If a response interleaves text and images, loop over interaction.steps and check each block&#39;s type yourself, because the convenience property does not cover that case.</p><h3>Edit an image</h3><p>Send a list that mixes text and an image:</p><p>python</p><pre>with open(&quot;cat.png&quot;, &quot;rb&quot;) as f:<br>    image_bytes = f.read()</pre><pre>interaction = client.interactions.create(<br>    model=MODEL,<br>    input=[<br>        {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Put this cat in a fancy restaurant, wearing a tiny bow tie&quot;},<br>        {<br>            &quot;type&quot;: &quot;image&quot;,<br>            &quot;data&quot;: base64.b64encode(image_bytes).decode(&quot;utf-8&quot;),<br>            &quot;mime_type&quot;: &quot;image/png&quot;,<br>        },<br>    ],<br>)<br>save_image(interaction, &quot;cat_restaurant.png&quot;)</pre><h3>Refine in turns</h3><p>Google recommends multi-turn editing for iterating on an image. Chain a new request to the previous interaction with previous_interaction_id. Because settings are not carried over between turns in the Interactions API, repeat the model:</p><p>python</p><pre>followup = client.interactions.create(<br>    model=MODEL,<br>    previous_interaction_id=interaction.id,<br>    input=&quot;Make the bow tie red and keep everything else the same&quot;,<br>)<br>save_image(followup, &quot;cat_restaurant_red.png&quot;)</pre><h3>3. Reference images</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1hZoi3U6mmRHSWk-AOh4w.png" /></figure><p>You can guide a result with reference images, up to <strong>14 in total</strong>. The documented limits:</p><ul><li><strong>Nano Banana 2.1 and 3.1 Flash:</strong> up to 10 object images and up to 4 character images.</li><li><strong>Nano Banana Pro:</strong> up to 6 object images, 5 character images and 3 style references.</li><li><strong>Nano Banana 2 Lite:</strong> up to 14 object images, with no character or style references.</li></ul><h3>4. Size, shape and thinking</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtGWfObzXWF-Kw2I6qllbA.png" /></figure><ul><li><strong>Aspect ratio and size</strong> are set through response_format with aspect_ratio and image_size. Ratios include 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9 and 21:9. Sizes are 1K, 2K and 4K, and the K must be uppercase. Gemini 3 models default to 1K, and the Lite model supports only 1K. The 3.1 Flash model also offers a 512px size. I did not verify the exact request structure, so copy it from the current docs.</li><li><strong>Thinking</strong> is always on for Gemini 3 image models and cannot be disabled. You can set a thinking level (for example, Nano Banana 2.1 supports minimal, medium as the default, and high). <strong>Thinking tokens are billed by default</strong>, even if you never read the thoughts.</li><li><strong>Grounding:</strong> Google Search grounding can pull in real-time information such as weather or stock data, and Image Search grounding is available on 2.1 and 3.1 Flash only.</li><li><strong>Video as context:</strong> YouTube URLs or uploaded videos can be used as context on some models.</li><li><strong>Batch API:</strong> runs image jobs with higher rate limits and up to 24 hours of turnaround.</li></ul><h3>5. A simple workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C8r5yreAPrAhrcSzbN9ojA.png" /></figure><p>My suggestions for getting good images:</p><ol><li><strong>Describe the scene like a brief.</strong> Subject, setting, lighting, style and mood work better than a few keywords.</li><li><strong>Change one thing at a time</strong> when refining. Ask for “the same image, but with a red bow tie” rather than rewriting the whole prompt.</li><li><strong>Use reference images</strong> when you need a consistent character or product.</li><li><strong>Inspect every result.</strong> Check text rendering, hands, logos and fine details before you publish.</li><li><strong>Pick the model by job.</strong> Use Lite for drafts and volume, 2.1 for everyday work, and Pro for demanding creative control.</li></ol><h3>6. Responsible use</h3><ul><li><strong>Watermark:</strong> all generated images include a <strong>SynthID</strong> watermark, per the docs. Do not present generated images as photographs of real events.</li><li><strong>Rights and likeness:</strong> my own advice is to avoid generating images of real people without consent, and to review the terms for commercial use and any content policies before you publish.</li><li><strong>Safety filters:</strong> image requests can be blocked. See the safety article in this series for how blocked requests appear.</li><li><strong>Cost:</strong> thinking tokens and image outputs add up, so measure a batch before you scale.</li></ul><h3>7. Where to start</h3><ol><li>Run the text-to-image example and open the file.</li><li>Edit an image of your own with a short instruction.</li><li>Refine it twice using previous_interaction_id.</li><li>Try a reference image for a consistent character.</li><li>Compare Lite and 2.1 on the same prompts for quality, speed and cost.</li></ol><h3>Final thoughts</h3><p>The practical lesson is that image generation is now a normal API call with the same request shape as the rest of Gemini. The decisions are about model choice, iteration and responsibility, not plumbing.</p><p><em>Models, IDs, sizes and limits for image generation change quickly. Verify them against the official documentation before you ship.</em></p><p><strong>Sources</strong></p><ul><li><a href="https://ai.google.dev/gemini-api/docs/image-generation">Image generation with Gemini (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/interactions">Interactions API overview (Google AI for Developers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd65e41c9614" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gemini Live API: Build Real-Time Voice Conversations]]></title>
            <link>https://medium.com/@ameniselmi1925/gemini-live-api-build-real-time-voice-conversations-eac94c92b691?source=rss-d530e850bdd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/eac94c92b691</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ameni Selmi]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 12:38:32 GMT</pubDate>
            <atom:updated>2026-10-31T12:38:32.339Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The Live API keeps one connection open and streams audio both ways, so users can talk to Gemini and interrupt it like a person. Here is how it works, the limits to plan around, and a first working session.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlfRXqgrx62kk0l3fjJ3Bw.png" /></figure><p>Most Gemini calls are request and response: you send a prompt, you wait, you get an answer. A voice assistant does not work like that. People talk in bursts, interrupt, and expect a reply within a moment. The <strong>Live API</strong> is Google’s answer for this: low-latency, real-time voice (and vision) interaction with Gemini over a persistent connection.</p><p>This is article 8 of the series. Everything below comes from Google’s Live API documentation as of October 2026, with my own additions marked.</p><h3>1. What the Live API is</h3><p>According to Google’s overview, the Live API processes continuous streams of audio, images and text and returns spoken responses. It uses a <strong>stateful WebSocket connection (WSS)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6gnhJsyfGNSBwXAVlmzFA.png" /></figure><p>The audio formats are fixed, so your code must convert to them:</p><ul><li><strong>Input:</strong> raw 16-bit PCM audio, 16 kHz, little-endian. Images go in as JPEG, at up to 1 frame per second.</li><li><strong>Output:</strong> raw 16-bit PCM audio, 24 kHz, little-endian.</li></ul><h3>2. What it adds to a voice chat</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WASzwXyo20M2oDwOognSEg.png" /></figure><p>The features Google lists:</p><ul><li><strong>Barge-in:</strong> users can interrupt the model mid-sentence.</li><li><strong>Tool use:</strong> function calling and Google Search work inside a live session.</li><li><strong>Audio transcription:</strong> text for both what the user said and what the model said.</li><li><strong>Proactive audio:</strong> controls when the model decides to respond.</li><li><strong>Affective dialog:</strong> adapts tone to the user’s expression.</li><li><strong>Live Transcription and Live Translation:</strong> continuous speech-to-text with automatic language detection, and voice-to-voice translation across 70+ languages.</li></ul><p>Google lists support for 70 languages overall.</p><h3>3. A first session</h3><p>The example below follows Google’s SDK tutorial, using the model name from that page (gemini-3.8-live; use a current model ID). It sends a text message and an audio file, collects the audio the model returns, and writes a WAV file. The WAV-writing part and reading audio from a file are my additions:</p><p>python</p><pre>import asyncio<br>import wave</pre><pre>from google import genai<br>from google.genai import types</pre><pre>client = genai.Client()  # reads GEMINI_API_KEY from the environment</pre><pre>MODEL = &quot;gemini-3.8-live&quot;<br>CONFIG = {&quot;response_modalities&quot;: [&quot;AUDIO&quot;]}<br>OUTPUT_RATE = 24000  # output is 16-bit PCM at 24 kHz<br></pre><pre>async def main():<br>    async with client.aio.live.connect(model=MODEL, config=CONFIG) as session:<br>        # Send text.<br>        await session.send_realtime_input(text=&quot;Hello, how are you?&quot;)</pre><pre>        # Send audio: raw 16-bit PCM, 16 kHz, little-endian, in ~100 ms chunks.<br>        with open(&quot;input_16k.pcm&quot;, &quot;rb&quot;) as f:<br>            while chunk := f.read(3200):<br>                await session.send_realtime_input(<br>                    audio=types.Blob(data=chunk, mime_type=&quot;audio/pcm;rate=16000&quot;)<br>                )</pre><pre>        # Collect the audio the model sends back.<br>        pcm_out = bytearray()<br>        async for response in session.receive():<br>            content = response.server_content<br>            if content and content.model_turn:<br>                for part in content.model_turn.parts:<br>                    if part.inline_data:<br>                        pcm_out.extend(part.inline_data.data)</pre><pre>    with wave.open(&quot;output.wav&quot;, &quot;wb&quot;) as wf:<br>        wf.setnchannels(1)<br>        wf.setsampwidth(2)  # 16-bit<br>        wf.setframerate(OUTPUT_RATE)<br>        wf.writeframes(bytes(pcm_out))<br></pre><pre>asyncio.run(main())</pre><p>Two honest caveats. The overview page gives the output rate (24 kHz), but the tutorial page I read did not show how a turn ends, so check the session guide for how to detect the end of a response before you build a real conversation loop. And a real app streams microphone audio continuously instead of reading a file; the chunking above is the same idea.</p><h3>4. Where should the connection live?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wSK8CB81CBfyyl90OpRDQ.png" /></figure><p>Google describes two designs:</p><ul><li><strong>Server to server:</strong> your backend opens the Live API connection and forwards the client’s audio streams.</li><li><strong>Client to server:</strong> the user’s browser or app connects directly. Google says this generally performs better for audio and video streaming. For production it recommends <strong>ephemeral tokens</strong> instead of standard API keys, so a key never ships to the browser.</li></ul><p>My advice: never put a normal API key in client-side code. If you connect directly from a browser, use ephemeral tokens as the docs suggest.</p><h3>5. Session limits and how to beat them</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-fwG7Zs7sYbv7Dw8GBcJA.png" /></figure><p>From the session management guide:</p><ul><li><strong>Audio-only sessions</strong> last 15 minutes without compression.</li><li><strong>Audio plus video sessions</strong> last 2 minutes without compression.</li><li><strong>A connection</strong> lasts about 10 minutes, and when it ends its session ends too.</li></ul><p>Exceeding the session limits ends the session. Two features keep a conversation going.</p><p><strong>Context window compression</strong> extends sessions indefinitely. Enable it in the config:</p><p>python</p><pre>from google.genai import types</pre><pre>config = types.LiveConnectConfig(<br>    response_modalities=[&quot;AUDIO&quot;],<br>    context_window_compression=types.ContextWindowCompressionConfig(<br>        sliding_window=types.SlidingWindow(),<br>    ),<br>)</pre><p><strong>Session resumption</strong> carries one session across several connections. The server sends SessionResumptionUpdate messages containing handles. Store the latest handle (when it is resumable), and pass it when you reconnect. Handles stay valid for 2 hours after the last session ends:</p><p>python</p><pre>config = types.LiveConnectConfig(<br>    response_modalities=[&quot;AUDIO&quot;],<br>    session_resumption=types.SessionResumptionConfig(<br>        handle=previous_session_handle  # or None to start a new session<br>    ),<br>)</pre><p><strong>GoAway</strong> warns you before a connection ends. Watch for it while receiving, and reconnect with the saved handle:</p><p>python</p><pre>async for response in session.receive():<br>    if response.go_away is not None:<br>        print(&quot;Connection ending soon, time left:&quot;, response.go_away.time_left)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09qrpTsLPcQtPLKLvjYqAg.png" /></figure><h3>6. Practical advice</h3><p>The first items follow the docs. The rest are my own guidance.</p><ol><li><strong>Convert audio carefully.</strong> Wrong sample rates or formats are the most common cause of garbled sound. Send 16 kHz in, expect 24 kHz out.</li><li><strong>Use ephemeral tokens for browser clients.</strong></li><li><strong>Turn on compression and resumption</strong> for any conversation that may run past a few minutes, and handle GoAway.</li><li><strong>Plan for failure.</strong> Networks drop. Save the latest handle and test reconnecting.</li><li><strong>Keep tools fast and safe.</strong> A tool call during a live conversation creates a silence, so keep tools quick, and confirm risky actions with the user before running them.</li><li><strong>Tell users when audio is processed or recorded</strong>, and check data retention terms for transcripts before storing them.</li><li><strong>Test with real microphones and noisy rooms</strong>, not just clean files.</li></ol><h3>7. Where to start</h3><ol><li>Run the first session above with a short recorded clip.</li><li>Add transcription and read what the model says as text.</li><li>Add one tool, such as a lookup, using the function calling article’s pattern.</li><li>Add compression, then resumption, and test a reconnect.</li><li>Move audio capture to a real microphone and playback to speakers.</li></ol><h3>Final thoughts</h3><p>The Live API changes the shape of the application: one open connection, audio in both directions, interruptions allowed. The model is the easy part. The craft is in audio handling, session management and latency. If you plan for limits from the start, a voice agent is a weekend project rather than a research project.</p><p><em>The Live API, its model names and session limits are evolving quickly. Verify details against the official documentation before you ship.</em></p><p><strong>Sources</strong></p><ul><li><a href="https://ai.google.dev/gemini-api/docs/live-api">Live API overview (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/live-api/get-started-sdk">Get started with the Live API using the SDK (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/live-api/session-management">Live API session management (Google AI for Developers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eac94c92b691" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Calling and Structured Output in Gemini: Make Your Agent Act and Answer in a Shape You…]]></title>
            <link>https://medium.com/@ameniselmi1925/function-calling-and-structured-output-in-gemini-make-your-agent-act-and-answer-in-a-shape-you-5f00ac09d398?source=rss-d530e850bdd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f00ac09d398</guid>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[structured-output]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Ameni Selmi]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 22:48:11 GMT</pubDate>
            <atom:updated>2026-10-28T22:48:11.464Z</atom:updated>
            <content:encoded><![CDATA[<h3>Function Calling and Structured Output in Gemini: Make Your Agent Act and Answer in a Shape You Control</h3><p><em>Two features turn Gemini from a chatbot into a building block for real software. Here is how each works, how the new Interactions API changes the code, and how to use them safely.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrdokHcMuwqIu3mpcihwzQ.png" /></figure><p>A language model that returns free-form text is hard to build on. Your code needs to know whether the answer is a date or a sentence, and sometimes the model needs to look something up or trigger an action before it can answer at all.</p><p>Gemini gives you two features for this. <strong>Structured output</strong> makes the final answer follow a schema you define. <strong>Function calling</strong> lets the model ask your application to run a function. This article explains both, shows working code with the current Gemini API, and covers the mistakes that matter in production.</p><h3>1. Two features, two jobs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kP5iTIkfNzJjpS4ojsOFuw.png" /></figure><p>Google’s documentation draws the line clearly:</p><ul><li><strong>Function calling</strong> lets the model request an action <em>before</em> it gives a final answer.</li><li><strong>Structured output</strong> formats the <em>final</em> answer.</li></ul><p>They are often used together: the model calls a tool, gets the result, and then replies in a fixed JSON shape.</p><h3>2. A note on the API: Interactions replaces generateContent for new work</h3><p>If you learned the Gemini API a while ago, you used generate_content. Google&#39;s docs now call that API &quot;legacy&quot; and describe the <strong>Interactions API</strong> as the best way to build with Gemini models and agents. It became generally available in June 2026. generateContent remains fully supported, and Google says new features, models and tools will launch on Interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YcZPyG7CGnkkldDn0Tu9zA.png" /></figure><p>The main ideas:</p><ul><li>An <strong>interaction</strong> is one complete turn, made of <strong>steps</strong>: model thoughts, tool calls, tool results and the final output.</li><li>You continue a conversation with previous_interaction_id instead of resending history. Tools and generation settings are not carried over, so you set them again on each turn.</li><li>State is stored by default (store=true). Retention is 1 day on the free tier and 55 days on the paid tier. Set store=false to opt out, but then you cannot use previous_interaction_id.</li><li>output_text is a convenience property, but it only holds the trailing text, so iterate over steps for anything more.</li><li>The Python docs call for google-genai version 2.3.0 or later.</li></ul><p>All code below uses the Interactions API and gemini-3.8-flash, the model in Google&#39;s current examples. Use a current model ID from the documentation, and pin it.</p><h3>3. Structured output</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfRnOMN3xPTk9FUJwhNvWw.png" /></figure><p>Define the shape with a Pydantic class, pass its JSON schema, and parse the reply back into the class:</p><p>python</p><pre>from typing import Literal</pre><pre>from google import genai<br>from pydantic import BaseModel</pre><pre>client = genai.Client()  # reads GEMINI_API_KEY from the environment<br></pre><pre>class Feedback(BaseModel):<br>    sentiment: Literal[&quot;positive&quot;, &quot;neutral&quot;, &quot;negative&quot;]<br>    summary: str<br></pre><pre>interaction = client.interactions.create(<br>    model=&quot;gemini-3.8-flash&quot;,<br>    input=&quot;The new UI is incredibly intuitive.&quot;,<br>    response_format={<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;mime_type&quot;: &quot;application/json&quot;,<br>        &quot;schema&quot;: Feedback.model_json_schema(),<br>    },<br>)</pre><pre>feedback = Feedback.model_validate_json(interaction.output_text)<br>print(feedback)</pre><p>A detail to watch: Google’s structured output page passes response_format as a single object like the one above, while the migration guide wraps it in a list. If one form is rejected by your SDK version, try the other.</p><h3>What the schema can express</h3><p>Gemini supports a <strong>subset</strong> of JSON Schema. Per the docs, that includes:</p><ul><li>types: string, number, integer, boolean, object, array and null (allow null with a type list such as [&quot;string&quot;, &quot;null&quot;])</li><li>title and description</li><li>objects: properties, required, additionalProperties</li><li>strings: enum and format (date-time, date, time)</li><li>numbers: enum, minimum, maximum</li><li>arrays: items, prefixItems, minItems, maxItems</li><li>anyOf for alternative shapes, and $ref for recursive structures</li></ul><h3>Streaming</h3><p>You can stream structured output. The chunks are partial JSON strings, so concatenate them and parse once the stream ends.</p><h3>Tips from the docs, and one of mine</h3><ul><li>Write clear description fields and use specific types. An enum or Literal beats a free string.</li><li>State the task clearly in the prompt as well as in the schema.</li><li>Very large or deeply nested schemas can be rejected, so keep them small.</li><li><strong>Valid JSON is not the same as correct values.</strong> The docs say the output is syntactically valid, but you must still check it. This is where Pydantic helps: add validators for ranges and formats, and handle the case where a schema-compliant answer is still wrong. (Adding a retry with the validation error in the prompt is my own suggestion, not from the docs.)</li></ul><h3>4. Function calling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZ1JasFr5UhiDkbKhiLKyQ.png" /></figure><p>The loop has four steps in Google’s docs: you declare functions, send a prompt with them, <strong>your code executes the function</strong> (the model never does), and you send the result back so the model can write its answer.</p><p>A function declaration is a flat object with a name, a description and JSON Schema parameters. The description matters most, because it is how the model decides when to use the tool.</p><p>Here is a complete loop. The declaration and the function_call and function_result shapes follow Google&#39;s examples; the loop around them, the error handling and the round limit are my own additions:</p><p>python</p><pre>import json</pre><pre>from google import genai</pre><pre>client = genai.Client()<br>MODEL = &quot;gemini-3.8-flash&quot;  # use a current model ID<br></pre><pre>def get_weather(location: str) -&gt; dict:<br>    &quot;&quot;&quot;Stand-in for a real weather lookup.&quot;&quot;&quot;<br>    return {&quot;location&quot;: location, &quot;forecast&quot;: &quot;52F and rain&quot;}<br></pre><pre>TOOLS = {&quot;get_weather&quot;: get_weather}</pre><pre>DECLARATIONS = [<br>    {<br>        &quot;type&quot;: &quot;function&quot;,<br>        &quot;name&quot;: &quot;get_weather&quot;,<br>        &quot;description&quot;: &quot;Gets the current weather for a city.&quot;,<br>        &quot;parameters&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;location&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;City name, e.g. Boston&quot;}<br>            },<br>            &quot;required&quot;: [&quot;location&quot;],<br>        },<br>    }<br>]<br></pre><pre>def run_tool(call):<br>    &quot;&quot;&quot;Execute one function_call step and build its function_result input.&quot;&quot;&quot;<br>    args = call.arguments<br>    if isinstance(args, str):  # some SDK versions may give a JSON string<br>        args = json.loads(args)</pre><pre>    function = TOOLS.get(call.name)<br>    if function is None:<br>        output = {&quot;error&quot;: f&quot;unknown tool: {call.name}&quot;}<br>    else:<br>        try:<br>            output = function(**args)<br>        except Exception as exc:  # return the error so the model can react<br>            output = {&quot;error&quot;: str(exc)}</pre><pre>    return {<br>        &quot;type&quot;: &quot;function_result&quot;,<br>        &quot;call_id&quot;: call.id,<br>        &quot;name&quot;: call.name,<br>        &quot;result&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: json.dumps(output)}],<br>    }<br></pre><pre>def ask(prompt, max_rounds=5):<br>    interaction = client.interactions.create(<br>        model=MODEL, input=prompt, tools=DECLARATIONS<br>    )<br>    for _ in range(max_rounds):<br>        calls = [s for s in interaction.steps if s.type == &quot;function_call&quot;]<br>        if not calls:<br>            break<br>        results = [run_tool(call) for call in calls]<br>        interaction = client.interactions.create(<br>            model=MODEL,<br>            previous_interaction_id=interaction.id,<br>            input=results,<br>            tools=DECLARATIONS,  # tools are not carried over between turns<br>        )<br>    return interaction.output_text<br></pre><pre>print(ask(&quot;Do I need an umbrella in Boston today?&quot;))</pre><p>Two things to note. The loop handles several calls in one turn, because the model can request independent functions in parallel. And it repeats, because the model may chain calls: the docs call this <strong>compositional calling</strong>, such as fetching a forecast and then using it to set a thermostat. The max_rounds cap stops a runaway loop. I have not verified that returning several function_result items in one input list works for every model and SDK version, so test it before relying on it. (Google&#39;s example shows a single result.)</p><h3>Controlling when functions are called</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lSzhWK8oEUDagXM2fDzvA.png" /></figure><p>The tool_choice setting in generation_config has four modes in the docs:</p><ul><li>auto (the default): the model decides.</li><li>any: the model must call a function.</li><li>none: function calls are not allowed.</li><li>validated: the model ensures its call follows your schema.</li></ul><p>To limit the model to certain tools, use allowed_tools:</p><p>python</p><pre>generation_config = {<br>    &quot;tool_choice&quot;: {<br>        &quot;allowed_tools&quot;: {&quot;mode&quot;: &quot;any&quot;, &quot;tools&quot;: [&quot;get_weather&quot;]}<br>    }<br>}</pre><p>Older material you will find online uses allowed_function_names with the generateContent API. In the Interactions API docs the field is allowed_tools.</p><h3>Thought signatures</h3><p>Gemini 3 models reason internally, and that reasoning helps them call functions well. The SDKs handle the reasoning context for you. The exception is stateless mode (store=false): there you must send back all the model&#39;s steps, including thought and function_call steps, exactly as you received them. Dropping them degrades tool use.</p><h3>Mixing built-in tools and your own</h3><p>Gemini 3 models can combine built-in tools such as Google Search with your own functions in one request. Passing previous_interaction_id carries the built-in tool context forward.</p><h3>5. Putting them together</h3><p>You can combine function calling and structured output: the model uses tools, then its final reply follows your schema. The docs mark combining structured output with built-in tools as a <strong>preview</strong> feature for Gemini 3 series models, and their example uses a model I could not confirm is publicly available, so check which models support your combination before you build on it.</p><p>A safer pattern that works everywhere is two stages. Let the agent loop run with tools and produce a text answer. Then make a second, plain call that converts the answer into your schema.</p><h3>6. Production checklist</h3><p>The first items come from the docs. The rest are my own guidance.</p><ol><li><strong>Validate model output.</strong> Use Pydantic on structured replies, and check function arguments before you run anything.</li><li><strong>Never run arbitrary code or queries from tool arguments.</strong> Treat arguments like untrusted user input. This is my own advice and it is the most important item here.</li><li><strong>Add confirmation for side effects.</strong> For actions such as sending email or deleting data, require a human approval step or an idempotency key.</li><li><strong>Return errors as results.</strong> As in the loop above, send {&quot;error&quot;: ...} back so the model can recover or explain.</li><li><strong>Cap the rounds and set timeouts.</strong> Loops and slow tools are the most common causes of stuck agents.</li><li><strong>Write precise tool descriptions.</strong> Say when to use the tool and when not to.</li><li><strong>Keep tool sets small.</strong> A handful of well-named tools is easier for the model than dozens.</li><li><strong>Mind data retention.</strong> Interactions are stored by default, so use store=false for sensitive data, and then manage the state yourself.</li><li><strong>Pin your model and SDK versions.</strong> Models, parameter names and SDK shapes in this area are changing fast.</li><li><strong>Test it.</strong> Add cases that check which tool was called and what the answer contained, as in the evaluation article.</li></ol><h3>7. Where to start</h3><ol><li>Upgrade to google-genai 2.3.0 or later and set GEMINI_API_KEY.</li><li>Run the structured output example on a few real inputs and add a Pydantic validator.</li><li>Add one real function to the loop above and watch the function_call steps.</li><li>Try tool_choice modes to see how behavior changes.</li><li>When your tool set grows or you need multi-agent flows, move to ADK, which wraps these ideas for you.</li></ol><h3>Final thoughts</h3><p>Structured output gives your code a reliable answer. Function calling gives the model a way to reach beyond its training data. Both are simple in isolation, and both need ordinary software discipline around them: validate inputs, limit side effects and test. The Interactions API makes the plumbing cleaner, but the habits are what make an agent safe to ship.</p><p><em>The Gemini API is evolving quickly, including the Interactions API’s field names and model support. Verify code against the current documentation before you ship.</em></p><p><strong>Sources</strong></p><ul><li><a href="https://ai.google.dev/gemini-api/docs/function-calling">Function calling with the Gemini API (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/structured-output">Structured outputs (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/interactions">Interactions API overview (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/migrate-to-interactions">Migrating to the Interactions API (Google AI for Developers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f00ac09d398" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gemini Multimodal in Practice: Images, Video, Audio and PDFs in One Request]]></title>
            <link>https://medium.com/@ameniselmi1925/gemini-multimodal-in-practice-images-video-audio-and-pdfs-in-one-request-ce0c390c0ab4?source=rss-d530e850bdd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce0c390c0ab4</guid>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[multimodal-ai]]></category>
            <category><![CDATA[google-gemini-ai]]></category>
            <dc:creator><![CDATA[Ameni Selmi]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 22:29:32 GMT</pubDate>
            <atom:updated>2026-10-28T22:29:32.127Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Gemini reads pictures, watches video, listens to audio and understands PDFs. Here is how to send each kind of file, what it costs, where the limits are, and how to get clean, structured results.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OLZaxhn1Br_BagK1sYRofg.png" /></figure><p>Much of the world’s information is not text. It is scanned invoices, product photos, recorded meetings, lecture videos and charts inside PDFs. Gemini models are natively multimodal, which means you can hand them these files directly and ask questions, without a separate OCR, transcription or vision pipeline.</p><p>This article is a practical tour with the current Gemini API: how to pass files, what each input type costs in tokens, the limits to plan around, and working examples for images, PDFs, audio and video. Everything here comes from Google’s documentation as of October 2026, with my own additions clearly marked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEpMp7l4iz7318gwGSqr_Q.png" /></figure><p>All examples use the <strong>Interactions API</strong>, which Google now recommends for new projects (the older generate_content API remains supported). Input is a list of typed items, such as {&quot;type&quot;: &quot;text&quot;, ...} and {&quot;type&quot;: &quot;image&quot;, ...}, and you read the reply from interaction.output_text. The examples use the model name from Google&#39;s docs, gemini-3.8-flash. Use a current model ID from the documentation and pin it. You need google-genai 2.3.0 or later.</p><h3>1. Three ways to give Gemini a file</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imiFiS-gZsT_hcwZUChm3A.png" /></figure><ul><li><strong>Inline data:</strong> base64 bytes inside the request. The text prompt, system instructions and inline bytes must together stay under 20 MB. Good for small, one-off inputs.</li><li><strong>Files API:</strong> upload once with client.files.upload(...), then reference the returned uri. Google recommends it for large files and for files you reuse. For PDFs, uploaded files are stored for 48 hours.</li><li><strong>URL:</strong> images can be referenced by a public https:// URI, and public YouTube videos can be passed by link (a preview feature with its own limits, such as no private or unlisted videos).</li></ul><p>Here is a helper that picks between inline and upload. The logic is my own, built on the documented request shapes:</p><p>python</p><pre>import base64<br>import mimetypes<br>import os<br>import time</pre><pre>from google import genai</pre><pre>client = genai.Client()  # reads GEMINI_API_KEY from the environment<br>MODEL = &quot;gemini-3.8-flash&quot;  # use a current model ID</pre><pre># Base64 adds about a third, so stay well below the 20 MB request cap.<br>INLINE_LIMIT = 14 * 1024 * 1024<br></pre><pre>def media_part(path, kind):<br>    &quot;&quot;&quot;Build an input item for a local file. kind: image, audio, video or document.&quot;&quot;&quot;<br>    mime_type = mimetypes.guess_type(path)[0]<br>    if mime_type is None:<br>        raise ValueError(f&quot;Cannot guess the MIME type of {path}&quot;)</pre><pre>    if os.path.getsize(path) &lt;= INLINE_LIMIT:<br>        with open(path, &quot;rb&quot;) as f:<br>            data = base64.b64encode(f.read()).decode(&quot;utf-8&quot;)<br>        return {&quot;type&quot;: kind, &quot;data&quot;: data, &quot;mime_type&quot;: mime_type}</pre><pre>    uploaded = client.files.upload(file=path)<br>    if kind == &quot;video&quot;:  # videos are processed after upload, so wait for ACTIVE<br>        while not uploaded.state or uploaded.state.name != &quot;ACTIVE&quot;:<br>            time.sleep(5)<br>            uploaded = client.files.get(name=uploaded.name)<br>    return {&quot;type&quot;: kind, &quot;uri&quot;: uploaded.uri, &quot;mime_type&quot;: uploaded.mime_type}<br></pre><pre>def ask(path, kind, question, **extra):<br>    &quot;&quot;&quot;Send one file plus a question. extra is merged into the file item.&quot;&quot;&quot;<br>    part = {**media_part(path, kind), **extra}<br>    interaction = client.interactions.create(<br>        model=MODEL,<br>        input=[part, {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: question}],<br>    )<br>    return interaction.output_text</pre><p>Where to put the prompt: Google’s docs say that for a single image plus text, the text goes before the image; for a single PDF page, after the page; and for video, after the video. The helper above puts the question last, so for the image case you may want to swap the order.</p><h3>2. What it costs and where the limits are</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOTBwmdoCV1lCIQG5sFFJg.png" /></figure><p>Everything you send becomes tokens, so media cost scales with what you send. From the docs:</p><ul><li><strong>Images:</strong> 258 tokens if both sides are 384 pixels or less. Larger images are split into 768 x 768 tiles at 258 tokens each.</li><li><strong>PDFs:</strong> 258 tokens per page. For Gemini 3, text that is natively embedded in a PDF is not charged, and page images count under the IMAGE modality.</li><li><strong>Audio:</strong> 32 tokens per second, so one minute is 1,920 tokens.</li><li><strong>Video:</strong> about 100 tokens per second at low media resolution and about 300 at high resolution (frames plus audio).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KoS2UiimwM00T5PzMCqpEg.png" /></figure><p>And the limits:</p><ul><li><strong>Images:</strong> up to 3,600 per request. Formats: PNG, JPEG, WEBP, HEIC, HEIF.</li><li><strong>PDFs:</strong> up to 50 MB or 1,000 pages, for inline and Files API alike. Other document formats are read as plain text only, which loses charts and layout.</li><li><strong>Audio:</strong> up to 9.5 hours per prompt. Audio is downsampled to 16 Kbps, and multi-channel audio is merged into one channel.</li><li><strong>Video:</strong> for models with a 1M-token context window, about 3 hours at low media resolution or 1 hour at high resolution.</li></ul><p>Two knobs reduce or raise cost. The media_resolution parameter, introduced with Gemini 3, sets the maximum tokens per image or video frame: higher values help with fine text and small details but use more tokens and add latency. And for video, you can change frame sampling (covered below). Prices change, so check the pricing page before estimating a bill.</p><h3>3. Images</h3><p>The simplest case is a question about a picture:</p><p>python</p><pre>print(ask(&quot;receipt.jpg&quot;, &quot;image&quot;, &quot;What is the total on this receipt, and which store is it from?&quot;))</pre><h3>Finding things: bounding boxes</h3><p>Gemini can return bounding boxes for objects. The documented format is box_2d as [ymin, xmin, ymax, xmax], with coordinates <strong>normalized to 0-1000</strong>, so you must convert them back to your image&#39;s pixel size. Combine it with structured output to get clean data:</p><p>python</p><pre>from pydantic import BaseModel<br></pre><pre>class Detection(BaseModel):<br>    label: str<br>    box_2d: list[int]  # [ymin, xmin, ymax, xmax], 0-1000<br></pre><pre>class Detections(BaseModel):<br>    items: list[Detection]<br></pre><pre>def box_to_pixels(box_2d, width, height):<br>    &quot;&quot;&quot;Convert a normalized [ymin, xmin, ymax, xmax] box to pixel (x1, y1, x2, y2).&quot;&quot;&quot;<br>    ymin, xmin, ymax, xmax = box_2d<br>    return (<br>        round(xmin / 1000 * width),<br>        round(ymin / 1000 * height),<br>        round(xmax / 1000 * width),<br>        round(ymax / 1000 * height),<br>    )<br></pre><pre>part = media_part(&quot;street.jpg&quot;, &quot;image&quot;)<br>interaction = client.interactions.create(<br>    model=MODEL,<br>    input=[<br>        {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Detect the cars. Give box_2d as [ymin, xmin, ymax, xmax] normalized to 0-1000.&quot;},<br>        part,<br>    ],<br>    response_format={<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;mime_type&quot;: &quot;application/json&quot;,<br>        &quot;schema&quot;: Detections.model_json_schema(),<br>    },<br>)<br>result = Detections.model_validate_json(interaction.output_text)<br>for item in result.items:<br>    print(item.label, box_to_pixels(item.box_2d, width=1920, height=1080))</pre><p>The docs also describe segmentation, which returns a mask polygon inside each box, and suggest thinking_level set to &quot;minimal&quot; in generation_config for better results there. Image tips from the docs: make sure images are correctly rotated, avoid blurry images, and for one image plus text, put the text first.</p><h3>4. PDFs</h3><p>PDFs get native vision, so Gemini reads text, tables, charts and diagrams, not only the text layer. A common job is extracting data into a fixed shape, which combines PDFs with structured output:</p><p>python</p><pre>class LineItem(BaseModel):<br>    description: str<br>    amount: float<br></pre><pre>class Invoice(BaseModel):<br>    vendor: str<br>    invoice_date: str<br>    total: float<br>    line_items: list[LineItem]<br></pre><pre>part = media_part(&quot;invoice.pdf&quot;, &quot;document&quot;)<br>interaction = client.interactions.create(<br>    model=MODEL,<br>    input=[<br>        part,<br>        {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Extract the invoice details. Dates as YYYY-MM-DD.&quot;},<br>    ],<br>    response_format={<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;mime_type&quot;: &quot;application/json&quot;,<br>        &quot;schema&quot;: Invoice.model_json_schema(),<br>    },<br>)<br>invoice = Invoice.model_validate_json(interaction.output_text)</pre><pre># Do not trust extraction blindly: cross-check the numbers yourself.<br>line_sum = round(sum(item.amount for item in invoice.line_items), 2)<br>if abs(line_sum - invoice.total) &gt; 0.01:<br>    print(f&quot;Check this invoice: line items add up to {line_sum}, total says {invoice.total}&quot;)</pre><p>The cross-check at the end is my own advice. Structured output guarantees valid JSON, not correct numbers, so verify anything that matters, such as totals, with plain code. You can also send several PDFs in one request as long as they fit in the model’s context window, and the docs advise rotating pages correctly and avoiding blurry scans.</p><h3>5. Audio</h3><p>Gemini can describe, summarize and transcribe audio, translate it, label speakers, and reason about specific time ranges. It also understands non-speech sounds. For a transcript with speakers and timestamps, ask for structured output. This follows the schema pattern in Google’s audio docs:</p><p>python</p><pre>schema = {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>        &quot;summary&quot;: {&quot;type&quot;: &quot;string&quot;},<br>        &quot;segments&quot;: {<br>            &quot;type&quot;: &quot;array&quot;,<br>            &quot;items&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;speaker&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                    &quot;timestamp&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                    &quot;content&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                },<br>                &quot;required&quot;: [&quot;speaker&quot;, &quot;timestamp&quot;, &quot;content&quot;],<br>            },<br>        },<br>    },<br>    &quot;required&quot;: [&quot;summary&quot;, &quot;segments&quot;],<br>}</pre><pre>prompt = (<br>    &quot;Transcribe this audio. Label distinct speakers as Speaker 1, Speaker 2. &quot;<br>    &quot;Give timestamps as MM:SS. Start with a short summary.&quot;<br>)</pre><pre>interaction = client.interactions.create(<br>    model=MODEL,<br>    input=[media_part(&quot;meeting.mp3&quot;, &quot;audio&quot;), {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: prompt}],<br>    response_format=schema,<br>)<br>print(interaction.output_text)</pre><p>To focus on part of a recording, include a range in the prompt, such as “Provide a transcript from 02:30 to 03:29.” Speaker labels are the model’s inference, so treat them as a convenience and review them when names matter. For real-time voice conversations the docs point to the Live API, and for dedicated speech-to-text at scale, to Google Cloud Speech-to-Text.</p><h3>6. Video</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WXwHzML5PS3qlQH5RXo4Nw.png" /></figure><p>Video goes through the Files API (the helper waits until the file is ACTIVE), or you can pass a public YouTube link. Ask about timestamps in MM:SS form:</p><p>python</p><pre>print(ask(&quot;lecture.mp4&quot;, &quot;video&quot;, &quot;Summarize this lecture, then list the key moments with MM:SS timestamps.&quot;))</pre><p>Three controls from the docs matter for cost and quality:</p><ul><li><strong>Frame rate.</strong> By default, video is sampled at 1 frame per second. Lower it to save tokens, or raise it for fast action, where quick scene changes can be missed at 1 fps.</li><li><strong>Clipping.</strong> Analyze only a section with start and end offsets (in seconds). Clipping works in &quot;static&quot; processing mode.</li><li><strong>Agentic mode.</strong> On some models (the docs list Gemini 3.8 Flash, 3.6 Flash and 3.5 Flash Lite, among others), an opt-in &quot;processing&quot;: &quot;agentic&quot; mode lets the model navigate the timeline and load only the transcript, frames or audio it needs. Google says this can use up to 88% fewer tokens on long-form content, and recommends background=True for long videos.</li></ul><p>Clipping and a lower frame rate look like this:</p><p>python</p><pre>video = media_part(&quot;lecture.mp4&quot;, &quot;video&quot;)</pre><pre>clipped = {<br>    **video,<br>    &quot;processing&quot;: {&quot;type&quot;: &quot;static&quot;, &quot;start_offset&quot;: 1200, &quot;end_offset&quot;: 1500, &quot;fps&quot;: 0.5},<br>}<br>interaction = client.interactions.create(<br>    model=MODEL,<br>    input=[clipped, {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Summarize this section.&quot;}],<br>)<br>print(interaction.output_text)</pre><p>I combined the offsets and fps in one processing object for brevity. The docs show them in separate examples, so if your SDK version rejects the combination, use them separately.</p><h3>7. Practical advice</h3><p>The first three points come from the docs. The rest are my own guidance.</p><ol><li><strong>Pick the cheapest input that does the job.</strong> Lower fps, clip the video, or lower media_resolution when you do not need fine detail.</li><li><strong>Use the Files API for anything large or reused.</strong> Remember that files expire (48 hours for PDFs), so re-upload as needed.</li><li><strong>Mind timeouts on long media.</strong> The docs suggest streaming or background execution for long or complex requests.</li><li><strong>Validate structured results.</strong> Use Pydantic, then add domain checks, such as invoice totals.</li><li><strong>Keep a human in the loop for high-stakes data.</strong> Medical, legal and financial documents deserve review, because models can misread a blurry digit.</li><li><strong>Think about privacy before you upload.</strong> Photos, recordings and documents often hold personal data. Check data retention and use terms for your tier before sending real user files.</li><li><strong>Test with your own files.</strong> Build a small set of real invoices, photos or recordings with known answers, and measure accuracy, as in the evaluation article.</li><li><strong>Pin the model and SDK versions.</strong> Media features and limits vary between models and change often.</li></ol><h3>8. Where to start</h3><ol><li>Install google-genai 2.3.0 or later and set GEMINI_API_KEY.</li><li>Run ask(...) on a photo, a PDF and a short audio clip.</li><li>Turn the PDF example into a structured extraction for a document type you care about.</li><li>Try a short video, then compare token usage with a lower fps and with clipping.</li><li>Wrap your best flow in a function tool and give it to an agent, using the function calling and ADK articles.</li></ol><h3>Final thoughts</h3><p>The shift is that files are now first-class input. A single request can include a contract PDF, a photo of a signature and a question, and come back as clean JSON. The craft is in the details: choose the right way to pass each file, watch the token cost, respect the limits, and verify what matters.</p><p><em>Models, limits and parameter names for media are changing quickly, including agentic video processing and YouTube input, which are newer features. Verify details against the official documentation before you ship.</em></p><p><strong>Sources</strong></p><ul><li><a href="https://ai.google.dev/gemini-api/docs/image-understanding">Image understanding (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/video-understanding">Video understanding (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/audio">Audio understanding (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/document-processing">Document understanding (Google AI for Developers)</a></li><li><a href="https://ai.google.dev/gemini-api/docs/interactions">Interactions API overview (Google AI for Developers)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce0c390c0ab4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>