Introduction & Overview

Welcome! In our previous lesson, you learned the fundamentals of communicating with Gemini through the Google Generative AI API. You mastered sending single requests, understanding response structures, and managing multi-turn conversations within a single interaction. Now, you're ready to take the next step and unlock even more powerful ways to work with Gemini.

In this lesson, you'll discover how to design and implement multi-step workflows using Gemini, with a special focus on a technique called prompt chaining. By the end, you'll know how to break down sophisticated tasks into manageable, reliable steps and connect them together for robust AI-powered solutions.

What is a Workflow?

A workflow is a structured sequence of steps or actions designed to accomplish a specific goal. In the context of AI systems, workflows help you organize and coordinate tasks so that each step has a clear purpose, defined inputs and outputs, and measurable success criteria. There are many types of workflows — some involve a single interaction, while others may require multiple steps, validation, or branching logic. Well-designed workflows make complex processes more predictable, easier to debug, and simpler to maintain.

Prompt Chaining and Why it Matters

Prompt chaining is a workflow pattern where you connect multiple separate Gemini calls together, with each call building upon the output of the previous one. Unlike multi-turn conversations that happen within a single session, prompt chaining involves distinct API calls that work together to solve complex problems step by step.

The power of prompt chaining lies in its reliability and modularity. Instead of asking Gemini to perform multiple complex tasks in a single prompt (which can lead to inconsistent results), you break the work into focused steps where you can validate and control the output at each stage. This approach makes your AI workflows more predictable and easier to debug.

Setup: Initializing the Gemini API

Before you start building your workflow, you need to set up the Gemini API client and select the model you want to use. This setup step ensures your code is ready to make calls to Gemini in a robust and configurable way.

First, make sure you have the google-genai Python package installed:

pip install google-genai

Now, initialize the Gemini API and select your model in Python:

import os
from google import genai
from google.genai import types

# Initialize the Gemini API
API = os.environ["GOOGLE_API_KEY"]
BASE = os.environ.get("GOOGLE_BASE_URL", "").rstrip("/")

client_kwargs = {"api_key": API}
if BASE:
    client_kwargs["http_options"] = types.HttpOptions(base_url=BASE)

client = genai.Client(**client_kwargs)

# Choose a model to use
model_name = "models/gemini-flash-latest"

With this setup, you're ready to build your workflow.

Design the Workflow Before Coding

Before writing any code, it's important to break your task into clear, manageable steps. For our example, we'll build a simple three-step workflow:

  1. Generate a summary about AI in healthcare, with a strict character limit (around 300 characters).
  2. Validate that the summary meets the character requirement.
  3. Translate the validated summary into Spanish, returning only the translated text.

Each step will have its own focused prompt and clear input/output, making the workflow easy to follow and debug. This approach helps ensure each part works as expected before moving to the next.

Step 1: Generate a Constrained Summary (with Retry Logic)

Let's start building our chain by creating the first step: generating a summary with specific character constraints. Sometimes, even with clear instructions, Gemini may return a summary that doesn't meet the character requirement. To make our workflow robust, we'll add a retry loop that gives Gemini several chances to produce a summary within the required range.

Note: Instead of embedding the system behavior in the prompt text, we use the system_instruction parameter to set the assistant's role and behavior. This ensures persistent and consistent behavior, and aligns with specialist/routing patterns you'll see later in the course.

system_instruction = "You are a helpful assistant that writes clear, concise summaries."
user_prompt = (
    "Write a summary of artificial intelligence and its current applications in healthcare. "
    "The summary must be between 250 and 350 characters. "
    "Do not exceed the character limit."
)

max_attempts = 5
summary_text = None
for attempt in range(max_attempts):
    response = client.models.generate_content(
        model=model_name,
        contents=user_prompt,
        config=types.GenerateContentConfig(
            system_instruction=system_instruction,
        ),
    )
    summary_text = response.text.strip()
    if 250 <= len(summary_text) <= 350:
        break
    if attempt == max_attempts - 1:
        raise ValueError(
            f"Summary does not meet character requirement (250-350 characters). Got {len(summary_text)} characters."
        )

print("Summary:")
print(summary_text)
Step 2: Validate and Guardrail the Output

After generating the summary, it's important to validate that the output meets your requirements before proceeding. Even with retry logic, you should always check the output and handle any issues gracefully. This step acts as a guardrail, ensuring that only valid data moves forward in your workflow.

# Step 2: Validate that the summary meets our character requirements
if not (250 <= len(summary_text) <= 350):
    raise ValueError(
        f"Summary does not meet character requirement (250-350 characters). Got {len(summary_text)} characters."
    )

print(f"✅ SUCCESS: Summary meets character requirement: {len(summary_text)} characters")

This validation step uses a programmatic check to ensure the summary is within the required range. If the summary is invalid, the code raises an error and stops the workflow. If valid, it prints a success message and you can proceed to the next step.

Step 3: Feed the Output into Translation

The third step demonstrates the core concept of prompt chaining: using the output from one Gemini call as input to another. This step takes our validated summary and translates it into Spanish using a focused instruction.

Again, we use the system_instruction parameter to specify the assistant's role for this step.

translation_instruction = "You are a professional translator that provides accurate Spanish translations."
translation_prompt = (
    "Return me just the Spanish translation of the following text:\n\n"
    f"{summary_text}"
)

translation_response = client.models.generate_content(
    model=model_name,
    contents=translation_prompt,
    config=types.GenerateContentConfig(
        system_instruction=translation_instruction,
    ),
)
translation_text = translation_response.text.strip()

print("Spanish Translation:")
print(translation_text)

The instruction for this step is focused specifically on translation rather than general assistance. This specialization helps Gemini understand its role in this step of the chain and produces more consistent results.

The key insight here is how we safely pass the summary_text variable from step one into the prompt for step three. We use an f-string to embed the summary directly into the prompt, creating a clear separation between our instruction ("Return me just the Spanish translation") and the content to be translated.

When you run this final step, you'll see output like:

Spanish Translation:
La IA en salud revoluciona el diagnóstico mediante análisis de imágenes médicas, permite planes de tratamiento personalizados, automatiza tareas administrativas, ayuda en el descubrimiento de medicamentos y potencia asistentes virtuales de salud para el cuidado y monitoreo de pacientes.

Each step builds naturally on the previous one, creating a smooth workflow from English summary generation through validation to Spanish translation.

Summary & Prep for Practice

You've successfully designed and implemented a three-step prompt chain that demonstrates the core concepts of sequential AI workflows. Your chain writes a constrained summary (with retry logic to ensure it meets requirements), validates that it meets requirements, then uses that validated output as input for translation. The key patterns you've learned include decomposing complex tasks into focused steps, using validation and guardrails between steps, and safely passing output from one Gemini call as input to the next.

In the upcoming practice exercises, you'll implement this code yourself and extend it with additional features. The foundation you've built with prompt chaining opens up possibilities for much more sophisticated AI workflows. As you continue through this course, you'll see how these basic chaining concepts extend to tool usage, dynamic workflows, and complex agent behaviors that can handle real-world business problems.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal