#4843 Skill: Applying Innovative Thinking Method SCAMPER

#4843 Skill: Applying Innovative Thinking Method SCAMPER

#4843 Provide a skill markdown document for applying innovative thinking method SCAMPER

I will now generate a comprehensive skill guide and operational playbook for applying the SCAMPER innovative thinking methodology.

SCAMPER Innovation Method

Skill Playbook: Applying the SCAMPER Innovation Framework

1. Overview & Purpose

SCAMPER is a lateral thinking and creative ideation technique designed to spark innovation by systematically challenging existing products, services, processes, or business models. Developed by Bob Eberle based on Alex Osborn’s brainstorming principles, SCAMPER guides teams away from linear iteration into unconventional problem-solving.

When to Use

  • Product Revitalization: Evolving a mature product or breaking through market saturation.

  • Service Redesign: Reducing friction points or designing novel customer touchpoints.

  • Process Optimization: Eliminating bottlenecks or re-architecting workflows.

  • Feature Ideation: Generating a high volume of candidate backlog items rapidly.

2. The SCAMPER Framework Breakdown

LensStrategic FocusPrimary Objective

S – Substitute

Swap components, materials, audiences, or steps.

Reduce cost, increase access, or alter function.

C – Combine

Merge two separate ideas, offerings, or tech stacks.

Create synergy, multi-functionality, or new value.

A – Adapt

Borrow solutions from adjacent industries or nature.

Leverage proven concepts in a novel domain.

M – Modify / Magnify / Minify

Scale attributes up, down, or alter form factors.

Exaggerate a core differentiator or streamline.

P – Put to Another Use

Repurpose the asset for a completely new context.

Unlock new market segments without new R&D.

E – Eliminate

Strip away features, steps, or dependencies.

Deliver radical simplicity, lower overhead, or ultra-focus.

R – Reverse / Rearrange

Invert sequence, cause-and-effect, or layout.

Uncover counter-intuitive workflows and interactions.

3. Operational Prompt Engine

Use these targeted inquiry prompts during ideation sessions:

S — Substitute

  • What materials, technologies, or partners can be replaced with lighter/cheaper/more sustainable alternatives?

  • Can we change the who, when, or where of the service delivery?

  • What rule or premise are we treating as mandatory that could be swapped?

  • Example: Substituting brick-and-mortar storefronts with direct-to-consumer digital distribution.

C — Combine

  • What complementary service or feature can we integrate into an all-in-one bundle?

  • Can we blend our product with an unexpected partner or contradictory concept?

  • Which disconnected workflows can be unified into a single pipeline?

  • Example: Combining mobile phones with digital cameras and GPS navigation.

A — Adapt

  • How would an entirely different industry (e.g., hospitality, gaming, aviation) solve this?

  • What natural or biological mechanisms solve an analogous problem?

  • What legacy process can be modernized with modern automation or AI paradigms?

  • Example: Speedo adapting shark-skin fluid dynamics into Olympic racing swimsuits.

M — Modify / Magnify / Minify

  • Magnify: What happens if we make a single feature 10x larger, louder, faster, or central?

  • Minify: What if the product was micro-sized, disposable, or took 1/10th the time?

  • Modify: What if we change the shape, texture, cadence, or payment schedule?

  • Example (Magnify): Giant-screen IMAX cinema.

  • Example (Minify): Micro-learning apps (e.g., 2-minute bite-sized lessons instead of hour-long lectures).

P — Put to Another Use

  • Who else could benefit from this solution outside our current ICP (Ideal Customer Profile)?

  • Can byproducts or residual data from our workflow become a standalone product?

  • How would a child, an elderly user, or an enterprise operator interact with this?

  • Example: Play-Doh originally invented as a wallpaper cleaner, repurposed as a children's toy.

E — Eliminate

  • What would happen if we stripped out the primary feature entirely?

  • How can we design an experience with zero setup, zero waiting, or zero maintenance?

  • Which operational steps cost 80% of our effort but deliver only 20% of user satisfaction?

  • Example: Apple eliminating the 3.5mm headphone jack and physical keyboard on smartphones.

R — Reverse / Rearrange

  • What if we inverted the sequence of events (pay before consuming vs. consume before paying)?

  • What happens if the customer does the work of the creator, or vice versa?

  • How can we turn our biggest constraint or weakness into the primary feature?

  • Example: IKEA reversing furniture assembly to have the customer construct flat-pack items at home.

4. Step-by-Step Workshop Protocol

[Phase 1: Scope & Deconstruct] ➔ [Phase 2: Individual Divergence] ➔ [Phase 3: Cluster & Cross-Pollinate] ➔ [Phase 4: Impact/Feasibility Prioritization]

Step 1: Deconstruct the Baseline Subject (15 mins)

  1. Pick a clear target: a tangible product, specific workflow, or business model.

  2. Dissect it into its core anatomy:

    • Components / Materials

    • Target User / Context

    • Sequential User Flow

    • Assumptions & Rules

Step 2: Timeboxed Sprinting (40 mins)

  • Run rapid, timed rounds (5–6 minutes per SCAMPER letter).

  • Encourage extreme, radical answers. Quantity precedes quality in this phase.

  • Rule of thumb: Aim for a minimum of 5 ideas per category before moving on.

Step 3: Synthesis & Hybridization (20 mins)

  • Group related ideas into clusters.

  • Cross-pollinate ideas across categories (e.g., combine an Eliminate concept with a Substitute concept).

Step 4: Feasibility & Impact Matrix (15 mins)

Map ideas onto a 2x2 grid:

               High Impact
                   │
      Quick Wins   │   Game Changers
    (Low Effort,   │   (High Effort,
     High Impact)  │    High Impact)
───────────────────┼───────────────────
      Backlog /    │   Money Pits
      Fill-ins     │   (High Effort,
    (Low Effort,   │    Low Impact)
     Low Impact)   │
                   │
               Low Impact
   Low Effort ─────────────── High Effort

5. Facilitator Anti-Patterns & Best Practices

PitfallWarning SignRemediation Strategy

Premature Pruning

"We tried that before" or "Compliance won't allow that."

Enforce strict deferred judgment until Phase 4.

Shallow Tweaks

Ideas consist solely of minor color or copy changes.

Apply deliberate constraints: "Imagine budget is unlimited" or "Imagine bandwidth is zero."

Linear Lock-in

Team treats SCAMPER as a checklist rather than lateral prompts.

Shuffle the order (e.g., start with Eliminate or Reverse).


How is this skill assigned to an AI agent?

Assigning a skill markdown document to an AI agent depends on the agent framework or platform being used, but it fundamentally works through context injection—providing the instructions either statically in the system prompt or dynamically via retrieval.

Here is how it is implemented across the standard agent architectures:

1. Custom Agent Platforms & Assistants (Gems, GPTs, Claude Projects)

For managed persona-based systems (such as Gemini Gems, OpenAI Custom GPTs, or Claude Projects/Artifacts), skills are assigned directly through UI configuration:

  • System Instructions / Base Prompt: Paste the core methodology, rules, and triggers directly into the agent’s "Instructions" box.

  • Knowledge / Reference Files: Upload the .md file as a knowledge source. In the instructions, add an explicit directive:

    "When the user requests brainstorming, product redesign, or innovative thinking, consult and follow the SCAMPER methodology outlined in scamper_skill_guide.md."

2. Static System Prompt Injection (Code-Based Frameworks)

In frameworks like LangChain, LlamaIndex, AutoGen, or direct API integration, the markdown file is loaded at startup and injected into the system message.

from pathlib import Path
from langchain_core.messages import SystemMessage

# Read the skill document
skill_content = Path("scamper_skill_guide.md").read_text()

# Inject into the system prompt
system_prompt = f"""
You are an innovation and design strategy agent.
You have access to the following operating skill:

{skill_content}

Apply this methodology systematically whenever tasked with product or process ideation.
"""

messages = [SystemMessage(content=system_prompt), ...]

3. Dynamic Tool Calling & On-Demand Retrieval

When an agent manages dozens of skills, injecting all of them into the system prompt wastes context window tokens and dilutes attention. Instead, the skill is assigned dynamically:

  • As a Tool (Function Calling): The model has a tool like get_skill(skill_name="scamper"). The system prompt lists only summaries and trigger criteria. When a relevant query arrives, the model invokes the tool to pull the full .md instructions into memory.

  • RAG (Retrieval-Augmented Generation): The skill library is vectorized and stored in a vector database. When a user asks a question about ideation or SCAMPER, semantic search fetches the relevant sections and appends them to the working context.

Key Requirements for Reliable Execution

Regardless of deployment method, ensure the markdown document contains clear boundaries so the agent knows how to act:

ComponentPurpose
Trigger ConditionsTells the agent when to activate the skill (e.g., "Activate when users request creative ideation or feature reimagining").
Step-by-Step ProcedureClear sequential steps the model must follow rather than open-ended advice.
Output Schema / FormatDefines the exact structure (tables, headers, bullet points) the agent must return to the user.
Negative ConstraintsDefines what not to do (e.g., "Do not skip straight to solutions without running through each SCAMPER category").


Provide this example using Google Gemini API in Python

To assign this SCAMPER skill document to Gemini using the official Google GenAI Python SDK (google-genai), pass the markdown document into system_instruction via GenerateContentConfig.

1. Installation and API Key Setup

Install the SDK:

pip install -U google-genai

Set your API key in your terminal or .env file:

export GEMINI_API_KEY="your-api-key-here"

2. Implementation

Place scamper_skill_guide.md in your project folder alongside your script. The script reads the markdown file and passes it directly as a system instruction to instruct the agent:

from pathlib import Path
from google import genai
from google.genai import types

# 1. Load the skill instructions from the markdown file
skill_path = Path("scamper_skill_guide.md")
if not skill_path.exists():
    raise FileNotFoundError("Please ensure 'scamper_skill_guide.md' is in your working directory.")

scamper_instructions = skill_path.read_text(encoding="utf-8")

# 2. Initialize the Gemini client (picks up GEMINI_API_KEY automatically)
client = genai.Client()

# 3. Configure the agent with the SCAMPER skill as system instruction
config = types.GenerateContentConfig(
    system_instruction=(
        "You are an expert product innovation and design thinking assistant.\n"
        "Strictly adhere to the following SCAMPER skill guide and protocol "
        "when analyzing user challenges:\n\n"
        f"{scamper_instructions}"
    ),
    temperature=0.7, # Slightly higher temperature encourages creative divergence
)

# 4. Generate ideas for a target product or process
target_problem = (
    "Run a full SCAMPER session on the traditional physical passport/travel ID. "
    "Focus on modern security, user convenience, and cross-border logistics."
)

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=target_problem,
    config=config,
)

print(response.text)

3. Interactive Multi-Turn Ideation Chat

If you want the model to act as a facilitator that coaches the user through SCAMPER step-by-step rather than dumping all ideas at once, instantiate a persistent chat session:

chat = client.chats.create(
    model="gemini-2.5-flash",
    config=config
)

# Turn 1
response = chat.send_message("Let's redesign an electric bicycle for extreme winter commuters.")
print(response.text)

# Turn 2: Gemini retains the SCAMPER methodology context across subsequent prompts
response = chat.send_message("Let's dive deeper into 'M' (Modify/Magnify) for battery performance.")
print(response.text)


Show me how to constrain the Gemini output to a structured JSON schema using Pydantic in python.

To constrain Gemini's output to a strict JSON structure, define a standard Pydantic model and pass it directly to response_schema alongside response_mime_type="application/json" in GenerateContentConfig.

The google-genai SDK converts the Pydantic class into an internal JSON Schema that the model follows.

Implementation

from enum import Enum
from pathlib import Path
from typing import List
from pydantic import BaseModel, Field
from google import genai
from google.genai import types


# 1. Define SCAMPER categories as an Enum
class ScamperCategory(str, Enum):
    SUBSTITUTE = "Substitute"
    COMBINE = "Combine"
    ADAPT = "Adapt"
    MODIFY_MAGNIFY = "Modify/Magnify"
    PUT_TO_ANOTHER_USE = "Put to Another Use"
    ELIMINATE = "Eliminate"
    REVERSE_REARRANGE = "Reverse/Rearrange"


# 2. Define the individual idea structure
class ScamperIdea(BaseModel):
    category: ScamperCategory = Field(
        description="The SCAMPER category used for this idea."
    )
    title: str = Field(
        description="Short, descriptive title of the innovative concept."
    )
    description: str = Field(
        description="Detailed explanation of the change and mechanism."
    )
    feasibility_score: int = Field(
        ge=1, le=5, description="Feasibility rating from 1 (moonshot) to 5 (immediate)."
    )
    expected_impact: str = Field(
        description="Primary user or business benefit."
    )


# 3. Define the root container schema
class ScamperAnalysisReport(BaseModel):
    target_subject: str = Field(
        description="The product, service, or process analyzed."
    )
    core_problem_statement: str = Field(
        description="The bottleneck or limitation addressed."
    )
    ideas: List[ScamperIdea] = Field(
        description="Collection of generated SCAMPER ideas across relevant categories."
    )


# 4. Initialize client and run inference
client = genai.Client(api_key=".................")

config = types.GenerateContentConfig(
    system_instruction="You are an expert innovation strategist specializing in SCAMPER.",
    response_mime_type="application/json",
    response_schema=ScamperAnalysisReport,
    temperature=0.4,  # Lower temperature prevents schema deviations while keeping ideas creative
)

prompt = (
    "Run a SCAMPER ideation session to modernize airport security checkpoints, "
    "focusing on passenger throughput and non-intrusive scanning."
)

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=prompt,
    config=config,
)

# 5. Parse and validate the response directly back into your Pydantic model
report = ScamperAnalysisReport.model_validate_json(response.text)

print(f"Target: {report.target_subject}")
print(f"Problem: {report.core_problem_statement}\n")

for idea in report.ideas:
    print(f"[{idea.category.value}] {idea.title} (Feasibility: {idea.feasibility_score}/5)")
    print(f"  Concept: {idea.description}")
    print(f"  Impact:  {idea.expected_impact}\n")

Key Mechanics

  • response_mime_type="application/json": Enforces raw JSON syntax without markdown backticks (no ```json blocks to strip).

  • response_schema=ScamperAnalysisReport: Translates field types, nested classes, Enum constraints, and Field(ge=..., le=...) ranges directly into the model's generation constraints.

  • model_validate_json(...): Restores full type safety in Python, providing IDE autocomplete and instant validation error handling if parsing fails.


Describe how to package the skill and Pydantic class(es) together

Packaging a skill markdown guide and its Pydantic models together turns unstructured guidelines into a modular, self-contained Python component.

The standard pattern is to organize the skill into a reusable package or class module that couples:

  1. The Skill Asset: Markdown instructions (loaded cleanly from package data).

  2. The Output Contract: Pydantic schema enforcing data boundaries.

  3. The Execution Harness: A runner or factory that binds the instructions and schema directly into Gemini's GenerateContentConfig.

1. Recommended Package Structure

Structure the skill as an importable module within your application or agent library:

my_agent_platform/
├── skills/
│   ├── __init__.py
│   └── scamper/
│       ├── __init__.py           # Public exports (classes & runner)
│       ├── instructions.md       # The methodology guide & constraints
│       ├── schemas.py            # Pydantic data structures
│       └── skill.py              # Packaging wrapper / execution logic
└── main.py

2. Code Implementation

skills/scamper/schemas.py

Defines the output structure and validation rules:

from enum import Enum
from typing import List
from pydantic import BaseModel, Field


class ScamperCategory(str, Enum):
    SUBSTITUTE = "Substitute"
    COMBINE = "Combine"
    ADAPT = "Adapt"
    MODIFY_MAGNIFY = "Modify/Magnify"
    PUT_TO_ANOTHER_USE = "Put to Another Use"
    ELIMINATE = "Eliminate"
    REVERSE_REARRANGE = "Reverse/Rearrange"


class ScamperIdea(BaseModel):
    category: ScamperCategory = Field(description="The SCAMPER category used.")
    title: str = Field(description="Action-oriented concept title.")
    description: str = Field(description="Technical or operational mechanism.")
    feasibility_score: int = Field(ge=1, le=5, description="1 (moonshot) to 5 (immediate).")
    expected_impact: str = Field(description="Primary user or business benefit.")


class ScamperAnalysisReport(BaseModel):
    target_subject: str = Field(description="Item or process analyzed.")
    core_problem_statement: str = Field(description="The core limitation or bottleneck.")
    ideas: List[ScamperIdea] = Field(description="List of ideas produced.")

skills/scamper/skill.py

Bundles the markdown content, Pydantic model, and configuration into an executable skill object:

from pathlib import Path
from google import genai
from google.genai import types
from .schemas import ScamperAnalysisReport


class ScamperSkill:
    """Encapsulates the SCAMPER methodology instructions and structured schema."""

    def __init__(self):
        # Resolve instructions.md relative to this file's location
        guide_file = Path(__file__).parent / "instructions.md"
        self.instructions = guide_file.read_text(encoding="utf-8")
        self.response_schema = ScamperAnalysisReport

    def get_config(self, temperature: float = 0.5) -> types.GenerateContentConfig:
        """Returns the turnkey GenerateContentConfig for Gemini."""
        return types.GenerateContentConfig(
            system_instruction=self.instructions,
            response_mime_type="application/json",
            response_schema=self.response_schema,
            temperature=temperature,
        )

    def execute(
        self,
        client: genai.Client,
        subject: str,
        model: str = "gemini-2.5-flash",
    ) -> ScamperAnalysisReport:
        """Runs the skill against a target subject and returns validated Pydantic output."""
        response = client.models.generate_content(
            model=model,
            contents=f"Execute a SCAMPER ideation session on: {subject}",
            config=self.get_config(),
        )
        return self.response_schema.model_validate_json(response.text)

skills/scamper/__init__.py

Exposes a clean API for consumers:

from .schemas import ScamperIdea, ScamperAnalysisReport, ScamperCategory
from .skill import ScamperSkill

__all__ = [
    "ScamperSkill",
    "ScamperIdea",
    "ScamperAnalysisReport",
    "ScamperCategory",
]

3. Usage in Agent Workflows

Consumers of your agent framework can now import and invoke the skill in three lines:

from google import genai
from skills.scamper import ScamperSkill

client = genai.Client()
scamper = ScamperSkill()

# Run the packaged skill
report = scamper.execute(client, subject="Urban food delivery packaging")

print(f"Target: {report.target_subject}")
for idea in report.ideas:
    print(f"- [{idea.category.value}] {idea.title}: {idea.description}")

Packaging Benefits

  • Zero Schema Drift: The system prompt (instructions.md) and data contract (schemas.py) live side-by-side in source control. If you update categories or prompt rules, the schema stays synchronized.

  • Portable Integration: You can pass skill.get_config() to standalone scripts, expose skill.execute() as a callable tool in LangGraph/AutoGen, or bundle it as an internal library via pyproject.toml.

  • Runtime Safety: The caller always receives an instantiated Pydantic model (ScamperAnalysisReport), guaranteeing type completion and automated runtime validation.



Show me how to wrap this packaged ScamperSkill into a callable tool definition for an autonomous Gemini agent router.

To expose the packaged ScamperSkill to an autonomous Gemini router, define a plain Python function with explicit type hints and docstrings. The google-genai SDK converts standard Python functions directly into model tool declarations.

When the router identifies an ideation request, it invokes the tool, triggers the underlying sub-agent execution, and feeds the structured findings back into the orchestrator loop.

1. Tool Definition Wrapper (tools.py)

Create a tool function that instantiates the skill and returns serializable data (dict or JSON string) for the router:

from google import genai
from skills.scamper import ScamperSkill

# Shared client instance
client = genai.Client()
scamper_service = ScamperSkill()


def run_scamper_ideation(target_subject: str) -> dict:
    """Runs a structured SCAMPER innovative thinking session on a specific subject, product, or workflow.

    Use this tool whenever the user needs creative brainstorming, feature redesign,
    or systematic innovation exploration across SCAMPER categories (Substitute, Combine,
    Adapt, Modify, Put to another use, Eliminate, Reverse).

    Args:
        target_subject: The specific product, service, feature, or workflow to innovate.

    Returns:
        dict: A structured report containing problem statement and categorized innovation ideas.
    """
    report = scamper_service.execute(client=client, subject=target_subject)
    # Convert Pydantic object to native dictionary for tool response serialization
    return report.model_dump()

2. Autonomous Agent Router Implementation (agent.py)

Pass run_scamper_ideation to config.tools. Set mode="AUTO" on function_calling_config so Gemini autonomously decides whether to answer directly or route to the tool.

from google import genai
from google.genai import types
from tools import run_scamper_ideation

client = genai.Client()

# System instructions defining router behavior and scope
ROUTER_SYSTEM_INSTRUCTION = """
You are an executive product strategy orchestrator.
When the user asks for creative solutions, redesigns, or innovation workflows,
delegate the analysis to the `run_scamper_ideation` tool.
Once the tool returns the ideas, synthesize the highest-leverage concepts
and present a prioritized strategic recommendation to the user.
"""

config = types.GenerateContentConfig(
    system_instruction=ROUTER_SYSTEM_INSTRUCTION,
    tools=[run_scamper_ideation],
    temperature=0.2,
)

# Multi-turn chat session with autonomous function calling
chat = client.chats.create(
    model="gemini-2.5-flash",
    config=config,
)

user_query = "Our team is redesigning hospital patient wristbands to reduce medical errors. Help us brainstorm."

# The SDK automatically handles the tool call loop (model call -> execute python function -> return result)
response = chat.send_message(user_query)
print(response.text)

Key Mechanics

  • Docstring as Tool Meta-Prompt: Gemini relies directly on the function docstring and argument descriptions to understand when and how to route queries to the tool.

  • Separation of Concerns: The router agent operates with a low temperature (0.2) for orchestration and synthesis, while the nested ScamperSkill runs at its own configured temperature (0.5) to encourage creative divergence.

  • Automatic Execution Loop: Under google-genai, passing a standard Python callable in tools enables automatic function execution by default: Gemini invokes the function, receives the Pydantic dictionary output, and synthesizes the final response in one call.


Show me how to manually handle tool execution and send function responses back to Gemini in python.

To handle tool execution manually using the google-genai SDK, disable automatic tool execution, inspect the model's function call requests, execute your custom logic locally, and pass the results back as a types.Part.from_function_response in the conversation history.

Step-by-Step Implementation

from google import genai
from google.genai import types
from skills.scamper import ScamperSkill

client = genai.Client()
scamper_service = ScamperSkill()


# 1. Define the local function and its tool declaration
def run_scamper_ideation(target_subject: str) -> dict:
    """Executes a structured SCAMPER innovation session on a target subject."""
    report = scamper_service.execute(client=client, subject=target_subject)
    return report.model_dump()


# Map function names to actual callables for lookup
TOOL_REGISTRY = {
    "run_scamper_ideation": run_scamper_ideation,
}

# 2. Configure manual tool calling
# Passing tools as Python functions lets Gemini auto-generate the tool schemas,
# but using client.models.generate_content directly gives you control over the loop.
config = types.GenerateContentConfig(
    system_instruction="You are a strategic innovation consultant. Use tools when asked to brainstorm or redesign products.",
    tools=[run_scamper_ideation],
    temperature=0.2,
)

# 3. Initialize message history
contents = [
    types.Content(
        role="user",
        parts=[types.Part.from_text("Redesign a standard commercial airplane tray table.")],
    )
]

# --- Round 1: Model decides to call a function ---
response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents=contents,
    config=config,
)

# Append the model's response (which contains function_calls) to history
contents.append(response.candidates[0].content)

# 4. Check for function calls and execute manually
function_calls = response.function_calls

if function_calls:
    tool_response_parts = []

    for call in function_calls:
        func_name = call.name
        func_args = call.args

        print(f"-> Router requested function: {func_name}")
        print(f"-> Arguments: {func_args}\n")

        # Execute the matched function
        if func_name in TOOL_REGISTRY:
            tool_result = TOOL_REGISTRY[func_name](**func_args)
        else:
            tool_result = {"error": f"Function {func_name} not found"}

        # Format the result back into a FunctionResponse part
        tool_response_parts.append(
            types.Part.from_function_response(
                name=func_name,
                response={"result": tool_result},
            )
        )

    # 5. Append function response(s) under the 'user' role
    contents.append(
        types.Content(
            role="user",
            parts=tool_response_parts,
        )
    )

    # --- Round 2: Gemini consumes the tool response and synthesizes final output ---
    final_response = client.models.generate_content(
        model="gemini-2.5-flash",
        contents=contents,
        config=config,
    )

    print("=== Final Synthesized Output ===")
    print(final_response.text)

Core Mechanics of the Manual Loop

  • Inspect with response.function_calls: Instead of automatically invoking the Python function behind the scenes, you inspect call.name and call.args to validate permissions, log queries, or request human approval before execution.

  • Keep Turn History Intact: When handling calls manually, you must append the assistant's turn containing the function_call directly into contents before providing the tool's answer. Omitting it breaks the conversation ordering.

  • Part.from_function_response: The function output must be packaged with types.Part.from_function_response(name=..., response={...}) where response takes a dictionary.

  • Role Mapping: The tool execution response is sent back with role="user". Gemini then ingests the payload and performs final reasoning.


Provide a Python application using Google Gemini API and a list of skill descriptions to create the skill library previously discussed. Include directories and files generation

This end-to-end Python script takes a list of skill descriptions, calls the Google Gemini API with structured outputs (response_schema), and writes out fully organized skill packages directly to your filesystem.

Generated Directory Structure

For each skill processed, the application generates a self-contained directory under skills/:

skills/
└── <skill_slug>/
    ├── __init__.py           # Exports skill class and Pydantic schemas
    ├── instructions.md       # Full operational markdown prompt and rules
    ├── schemas.py            # Generated Pydantic schema code for the skill's output
    └── skill.py              # Execution harness binding instructions + schemas

Prerequisites

Install the official Google GenAI and Pydantic packages:

pip install -U google-genai pydantic

Set your API key:

export GEMINI_API_KEY="your-api-key-here"

Skill Library Generator Application (generate_library.py)

import os
import re
from pathlib import Path
from typing import List
from pydantic import BaseModel, Field
from google import genai
from google.genai import types


# ==========================================
# 1. Pydantic Contract for Meta-Generation
# ==========================================

class SkillBundleSpecification(BaseModel):
    """Structured format Gemini must return for each skill package."""
    slug: str = Field(
        description="Lowercase snake_case folder name (e.g. 'scamper', 'first_principles')."
    )
    class_name: str = Field(
        description="PascalCase class name (e.g. 'ScamperSkill', 'FirstPrinciplesSkill')."
    )
    report_schema_name: str = Field(
        description="PascalCase name of the primary Pydantic report model (e.g. 'ScamperReport')."
    )
    instructions_md: str = Field(
        description="Complete operational guidelines, steps, edge cases, and examples in Markdown."
    )
    schemas_py: str = Field(
        description="Valid Python code defining Pydantic schemas required for the skill output."
    )


# ==========================================
# 2. File and Directory Builder
# ==========================================

def write_skill_package(base_dir: Path, spec: SkillBundleSpecification) -> None:
    """Creates the skill folder and writes __init__.py, instructions.md, schemas.py, and skill.py."""
    skill_dir = base_dir / spec.slug
    skill_dir.mkdir(parents=True, exist_ok=True)

    # 1. instructions.md
    (skill_dir / "instructions.md").write_text(spec.instructions_md.strip(), encoding="utf-8")

    # 2. schemas.py
    (skill_dir / "schemas.py").write_text(spec.schemas_py.strip(), encoding="utf-8")

    # 3. skill.py - Generic execution harness
    skill_py_code = f'''from pathlib import Path
from google import genai
from google.genai import types
from .schemas import {spec.report_schema_name}


class {spec.class_name}:
    """Packaged execution harness for the {spec.slug} skill."""

    def __init__(self):
        guide_file = Path(__file__).parent / "instructions.md"
        self.instructions = guide_file.read_text(encoding="utf-8")
        self.response_schema = {spec.report_schema_name}

    def get_config(self, temperature: float = 0.4) -> types.GenerateContentConfig:
        return types.GenerateContentConfig(
            system_instruction=self.instructions,
            response_mime_type="application/json",
            response_schema=self.response_schema,
            temperature=temperature,
        )

    def execute(
        self,
        client: genai.Client,
        subject: str,
        model: str = "gemini-2.5-flash",
    ) -> {spec.report_schema_name}:
        response = client.models.generate_content(
            model=model,
            contents=f"Execute analysis on: {{subject}}",
            config=self.get_config(),
        )
        return self.response_schema.model_validate_json(response.text)
'''
    (skill_dir / "skill.py").write_text(skill_py_code, encoding="utf-8")

    # 4. __init__.py - Exposing clean package imports
    init_py_code = f'''from .schemas import {spec.report_schema_name}
from .skill import {spec.class_name}

__all__ = ["{spec.class_name}", "{spec.report_schema_name}"]
'''
    (skill_dir / "__init__.py").write_text(init_py_code, encoding="utf-8")
    print(f"✓ Generated package at: {skill_dir}")


# ==========================================
# 3. Main Generator Pipeline
# ==========================================

SYSTEM_PROMPT = """You are a senior AI agent architect.
Given an innovation/thinking skill description, generate the complete skill package:
1. 'slug': lowercase_snake_case folder name.
2. 'class_name': PascalCase skill class name.
3. 'report_schema_name': PascalCase name of the primary output model.
4. 'instructions_md': In-depth, exhaustive Markdown guide detailing the methodology, prompts, and steps.
5. 'schemas_py': Syntactically valid Python code with Pydantic BaseModel definitions (using standard typing and pydantic imports) that define the structured data model for this skill. Ensure the root model name matches report_schema_name.
"""

def generate_skill_library(skill_descriptions: List[str], output_dir: str = "skills"):
    client = genai.Client(api_key="................")
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    # Root library __init__.py
    (output_path / "__init__.py").touch()

    config = types.GenerateContentConfig(
        system_instruction=SYSTEM_PROMPT,
        response_mime_type="application/json",
        response_schema=SkillBundleSpecification,
        temperature=0.3,
    )

    for idx, desc in enumerate(skill_descriptions, 1):
        print(f"\nProcessing [{idx}/{len(skill_descriptions)}]: {desc[:50]}...")
        
        prompt = f"Build an agent skill package for the following methodology:\n\n{desc}"
        
        response = client.models.generate_content(
            model="gemini-2.5-flash",
            contents=prompt,
            config=config,
        )

        # Parse output into our Pydantic spec and build directory files
        spec = SkillBundleSpecification.model_validate_json(response.text)
        write_skill_package(output_path, spec)


# ==========================================
# 4. Execution Entry Point
# ==========================================

if __name__ == "__main__":
    # Define the skills you want to generate
    skills_to_build = [
        (
            "SCAMPER Innovative Thinking: Guide the model through Substitute, Combine, "
            "Adapt, Modify/Magnify, Put to another use, Eliminate, and Reverse to redesign products."
        ),
        (
            "First Principles Deconstruction: Break down complex business or engineering problems "
            "into elemental foundational truths, identify flawed assumptions, and reconstruct solutions from scratch."
        ),
        (
            "Six Thinking Hats: Analyze a critical decision from all six Edward de Bono perspectives: "
            "White (Data), Red (Emotion), Black (Risks), Yellow (Benefits), Green (Creativity), and Blue (Process)."
        ),
    ]

    generate_skill_library(skill_descriptions=skills_to_build, output_dir="skills")

How to Consume the Generated Library

Once the script completes, any generated skill can be imported and executed in your agent runtime:

from google import genai
from skills.scamper import ScamperSkill
from skills.six_thinking_hats import SixThinkingHatsSkill

client = genai.Client(api_key="...............")

# 1. Run SCAMPER
scamper = ScamperSkill()
scamper_report = scamper.execute(client, subject="Smart re-usable coffee mug")
print(f"SCAMPER generated {len(scamper_report.ideas)} concepts.")

# 2. Run Six Thinking Hats
hats = SixThinkingHatsSkill()
hats_report = hats.execute(client, subject="Replacing physical offices with VR workspaces")
print(f"Analysis complete for: {hats_report.subject}")


What determines best temperature(s)?

The "best" temperature in generative AI sampling governs the trade-off between determinism (precision) and entropy (creativity).

Mathematically, temperature scales the raw output logits before the softmax function converts them into token probabilities:

P(y_i) = {exp(z_i / T)} / {sum_j exp(z_j / T)}

As T --> 0, the highest-scoring token dominates (approaching greedy decoding). As T increases, the probability distribution flattens, giving lower-ranked tokens a higher likelihood of selection.

Key Determining Factors

FactorLow Temperature (0.0 – 0.3)High Temperature (0.7 – 1.2)
Tolerance for HallucinationZero tolerance. Factual Q&A, math, citations, policy extraction.Tolerant. Storytelling, speculative brainstorming, roleplay.
Output Format RigidityStrict schemas. JSON parsing, SQL queries, regex generation.Freeform prose. Creative essays, poetry, conversational dialogue.
Pipeline PredictabilityDeterministic. Tool calling, agent routing, classification.Stochastic. Generating multiple distinct options or alternatives.
Verification LoopNo verifier. Single-shot execution needing the safest top token.External verifier. Best-of-N sampling, unit test execution loops.

Recommended Settings by Task

  • 0.0 (Greedy / Deterministic): Classification, code debugging, mathematical calculation, JSON/schema generation, and agent routing logic where consistency and tool-call reliability matter most.

  • 0.2 – 0.4 (Focused & Factual): Technical documentation, factual synthesis, data summarization, and business reports where slight linguistic variance is fine but accuracy is critical.

  • 0.7 – 0.9 (Balanced & Creative): Brainstorming frameworks (e.g., SCAMPER, lateral thinking), marketing copy, creative writing, and natural multi-turn conversational agents.

  • 1.0+ (High Entropy): Generative poetry, exploratory ideation runs, or synthetic data variation where novelty outweighs strict adherence.


From <https://gemini.google.com/app/abc8b76b0ae00ee6>  Google Gemini (3.8 Flash)

Comments

Popular posts from this blog

#4297 ISS Astronaut Unable to Speak

#4188 Hybrid/GraphRAG

#3356 PHP and JavaScript to Retrieve and Set an API_Key