#5033 Applications of Local 7B and 30B Parameter Models; +LangGraph ARIZ Pipeline

#5033 Applications of Local 7B and 30B Parameter Models; +LangGraph ARIZ Pipeline

Gemini take note: Do not remember my NASA S&MA role and history for all future chats

#5033 Describe great applications of local 7-billion parameter and 30-billion parameter models based on my background, history and interests. Usage of these small models must meet all requirements for the applications.

Splitting workloads between local 7B-class and 30B-class models lets you match inference speed to reasoning depth across your 12 GB VRAM laptop and 64–128 GB unified-memory workstations—using exclusively Western open-weight models.

7B-Class Models: High-Speed, Deterministic Execution

Recommended Western models: IBM Granite 4.2 8B, Ministral 3 8B, Google Gemma 4 (E4B), Mistral 7B.

7B-class models meet 100% of operational requirements when the task has a closed grammar, strict schema validation (Pydantic v2), or deterministic verification (SymPy / regex), and benefits from sub-200 ms latency or high-volume batch throughput.

  • Neo4j Knowledge Graph Ingestion: Batch-extract mechanical subsystems, components, and governing equations from textbooks and technical PDFs into strict Cypher MERGE statements. Granite 4.2 8B is specifically tuned for structured JSON and extraction, letting you ingest thousands of pages overnight at zero API cost.

  • TRIZ Constraint & Parameter Extraction: Act as the fast front-end classifier in a multi-agent LangGraph pipeline—parsing raw problem statements into standardized TRIZ Improving/Worsening parameters, Su-Field triples, or Morphological Analysis axes before handing off to a heavier reasoning model.

  • Algorithmic MIDI & Hardware Synth Control: Translate short musical prompts into constrained Python mido / music21 scripts, Sonic Pi loops, or Yamaha SEQTRAK parameter maps. Low-latency local execution keeps the feedback loop immediate while jamming with hardware synths (Behringer MonoPoly, K-2 MK II, Roland J-6, or Polyend Tracker).

  • CNC / CAD Boilerplate & G-Code Validation: Generate simple 2D profile macros, convert coordinate lists into ezdxf polylines for Vectric Cut2D/VCarve, or run fast syntax and bounds checks on generated OpenSCAD and DXF scripts.

30B-Class Models: Deep Reasoning, Multi-Hop Synthesis & Spatial Code

Recommended Western models: Meta Muse Glimmer 30B, Google Gemma 4 31B, IBM Granite 4.2 30B, NVIDIA Nemotron 3.5 Lightning (30B), OpenAI gpt-oss-20b.

At 20B–32B parameters, models cross the threshold for multi-step chain-of-thought reasoning, reliable tool-calling, and spatial/mathematical coherence. They fit comfortably in 64–128 GB unified memory and eliminate cloud token costs during iterative loops.

  • Multi-Agent TRIZ & Evaluator-Critic Loops: Power the core reasoning and adversarial critique stages in local LangGraph pipelines (Ideal Final Result, Contradiction Matrix, ARIZ, First Principles). Muse Glimmer 30B excels at local tool-calling and failure recovery, while Nemotron 3.5 Lightning's hybrid MoE architecture supports massive context windows for long iterative critiques.

  • GraphRAG & Multi-Hop Neo4j Deduction: Translate complex cross-domain engineering questions into multi-hop Cypher queries and Neo4j Graph Data Science (GDS) similarity pipelines. Granite 4.2 30B (up to 128K–512K context) is built for heavy RAG synthesis, letting you uncover functional analogies across hundreds of mechanical systems without cloud leakage.

  • Parametric CAD, OpenSCAD & CNC Pipelines: Synthesize multi-module OpenSCAD designs, Blender bpy scripts, or Python osmnx/trimesh/pyvista geometry pipelines for 3D printing, laser engraving, and Vectric VCarve relief carving. 30B models maintain dimensional constraints, Boolean operations, and coordinate transforms across long scripts where 7B models drift.

  • Structured Multi-Track Algorithmic Composition: Design full-arrangement Python generators that coordinate polyphonic voice leading, harmonic progressions, and multi-channel MIDI CC automation across multiple hardware synthesizers simultaneously, verifying rhythmic math before export.

Application & Hardware Fit Matrix

Domain7B-Class Role (12 GB VRAM)30B-Class Role (64–128 GB Unified)Deterministic Guardrail
TRIZ PipelinesParameter tagging, Su-Field parsing, JSON routingContradiction resolution, IFR synthesis, Evaluator-Critic loopsPydantic v2 schemas + stagnation circuit breakers
Neo4j Knowledge GraphsBulk PDF/textbook entity & Cypher MERGE extractionMulti-hop GraphRAG, cross-domain analogy, GDS query genCypher syntax validation + SymPy equation checks
CNC / CADDXF coordinate formatting, simple 2D macro generationParametric OpenSCAD, trimesh/ezdxf pipelines, Blender bpyBounding-box & manifold geometry assertions
Algorithmic MIDILive-latency Sonic Pi / mido riffs, CC mappingMulti-track arrangement logic, harmonic/polyphonic enginesMIDI range/channel & timing quantization checks


For each 7B and 30B models, which innovative thinking methods are fully supported (i.e. provide good responses)

Local 7B-class models reliably execute structured, single-hop, and checklist-driven innovation methods, while 30B-class models unlock abstraction, contradiction resolution, and cross-domain synthesis.

7B-Class Models: Fully Supported Methods

Western models: IBM Granite 4.2 8B, Google Gemma 4 (E4B), Mistral 7B, Meta Llama 3.2.

7B models produce strong, reliable output whenever the method provides an explicit operator, a bounded grid, or a direct logical inversion.

  • SCAMPER: Fully supported. Each operator (Substitute, Combine, Adapt, Modify, Put to another use, Eliminate, Reverse) is a direct local transformation that does not require deep multi-hop reasoning.

  • Reverse Brainstorming (Inversion): Fully supported. Generating failure modes ("How do we guarantee this breaks?") and inverting them into concrete mitigations is a single-hop negation task where 7B models are fast and thorough.

  • Nine-Screen System Operator (9 Windows): Fully supported. Populating the 3×3 matrix (Past / Present / Future × Subsystem / System / Supersystem) works reliably because each cell is tightly scoped.

  • Morphological Analysis (Matrix Generation): Fully supported for decomposing a problem into independent parameters, listing discrete options per axis, and enumerating raw combinations. (Note: Use 30B to filter out physically impossible combinations.)

  • Directed TRIZ 40 Principles: Supported when you supply the principle. If you explicitly prompt a 7B model with "Apply Principle 1 (Segmentation) to this mechanism," it generates solid concrete variations. It struggles to diagnose which principle to pick from scratch.

30B-Class Models: Fully Supported Methods

Western models: Google Gemma 4 31B, IBM Granite 4.2 30B/32B, NVIDIA Nemotron-3-Nano (30B), OpenAI gpt-oss-20b.

30B models cross the reasoning threshold needed to hold competing constraints in working memory, strip away hidden assumptions, and map analogies across unrelated engineering domains. They fully support everything in the 7B tier, plus:

  • First Principles Thinking: Fully supported. 7B models tend to regurgitate surface-level analogies; 30B models reliably decompose a system down to governing physics, material limits, and cost floors, then rebuild from scratch.

  • TRIZ Ideal Final Result (IFR) & Trimming: Fully supported. 30B models can conceptualize how a system delivers its useful function without existing (using free system resources) and accurately redistribute functions when components are trimmed.

  • TRIZ Contradiction Matrix & Separation Principles: Fully supported. Reliably formulates true Technical Contradictions (Improving vs. Worsening parameters) and Physical Contradictions (Separation in Time, Space, Scale, or Condition) without settling for weak trade-offs.

  • Su-Field (Substance-Field) Analysis & 76 Standard Solutions: Fully supported. Accurately models S1–S2–F triads (insufficient, harmful, or missing interactions) and maps them to the right standard solution class.

  • TRIZ Function-Oriented Search (FOS): Fully supported. Abstracting a niche engineering bottleneck into a generic function and pulling proven mechanisms from unrelated industries requires the broader technical knowledge and analogy-mapping of a 30B model.

  • Donella Meadows' 12 Leverage Points: Fully supported. Capable of mapping reinforcing/balancing feedback loops, information delays, and structural rules rather than just tweaking surface parameters.

  • ARIZ (Algorithm for Inventive Problem Solving): Fully supported when chained in a multi-step pipeline (e.g., LangGraph). Running ARIZ in a single monolithic prompt still degrades at 30B, but passing state step-by-step with Pydantic validation yields high-quality results.

Capability Comparison Matrix

Innovation Method7B-Class Support30B-Class SupportNotes
SCAMPERFullFullIdeal for fast 7B batch ideation.
Reverse BrainstormingFullFull7B excels at rapid failure-mode enumeration.
Nine-Screen (9 Windows)FullFullTightly bounded 3×3 grid keeps 7B on track.
Morphological AnalysisPartial (Grid Gen)Full (Gen + Filtering)Pair 7B for axis generation with 30B for feasibility pruning.
TRIZ 40 PrinciplesPartial (Directed)Full (Diagnostic)7B needs the principle named; 30B can select it.
First PrinciplesWeakFull7B slips into analogy; 30B strips to physical fundamentals.
TRIZ IFR & TrimmingWeakFullRequires abstract resource-mapping and function transfer.
Contradiction & SeparationWeakFull7B compromises; 30B resolves the contradiction.
Su-Field / 76 StandardsWeakFullRequires formal interaction modeling.
Function-Oriented SearchWeakFullNeeds cross-industry technical breadth.
Meadows' 12 Leverage PointsWeakFullNeeds systems-dynamics and feedback-loop reasoning.
ARIZNot RecommendedFull (Chained)Run as a stateful multi-step graph, not a single prompt.


Design a stateful LangGraph ARIZ pipeline using a local 30B Western model and Pydantic v2 schemas so ARIZ runs reliably step-by-step.

Running ARIZ (Algorithm for Inventive Problem Solving) in a single prompt causes 30B models to skip directly to surface-level compromises. Breaking ARIZ into a stateful LangGraph pipeline with Pydantic v2 structured outputs forces the model to isolate the operational zone, inventory free resources, and formulate a strict Physical Contradiction before it is allowed to propose a solution.

1. The 5-Stage Stateful ARIZ Graph

Each node uses Ollama's native JSON-schema enforcement (format=Schema.model_json_schema()) so the 30B model cannot omit required ARIZ fields or drift into unstructured prose.

StageARIZ PhaseOutput SchemaPurpose
1. AnalyzeMini-Problem & TC-1 / TC-2MiniProblemSpecDefines Tool, Product, and opposing Technical Contradictions.
2. ScopeOperational Zone, Time & SFRConflictResourcesPinpoints exact conflict space/time and lists free system resources.
3. IdealizeIFR-1 & Physical ContradictionIdealContradictionFormulates the Ideal Final Result and the opposing physical states ($A$ vs. $\neg A$).
4. SynthesizeSeparation & 76 StandardsInventiveConceptResolves the Physical Contradiction using Separation Principles and inventoried SFRs.
5. AuditIdeality & Compromise GateAuditVerdictRejects weak trade-offs; loops back to Stage 4 (max 2 retries) if it detects a compromise.

2. Complete Implementation (ariz_orchestrator.py)

Install the dependencies:

pip install langgraph pydantic ollama

Save and run the following script against your local Ollama instance:

"""
Stateful LangGraph ARIZ Pipeline for Local 30B Western Models
Requires: ollama, langgraph, pydantic>=2.0
"""

from typing import Literal, Optional, TypedDict
import ollama
from langgraph.graph import END, StateGraph
from pydantic import BaseModel, Field

# ---------------------------------------------------------------------------
# 1. Configuration
# ---------------------------------------------------------------------------

OLLAMA_MODEL = "gemma4:31b"  # Alternatives: "granite4:32b", "nemotron-3-nano"
MAX_RETRIES = 2


# ---------------------------------------------------------------------------
# 2. Contract-First Pydantic v2 Schemas
# ---------------------------------------------------------------------------

class MiniProblemSpec(BaseModel):
    tool: str = Field(description="The component performing the action.")
    product: str = Field(description="The object being acted upon.")
    tc_1: str = Field(description="Technical Contradiction 1: If state A, useful effect improves but harm worsens.")
    tc_2: str = Field(description="Technical Contradiction 2: If state Not-A, harm disappears but useful effect degrades.")
    selected_tc: Literal["TC-1", "TC-2"]
    selection_rationale: str


class ConflictResources(BaseModel):
    operational_zone: str = Field(description="Exact physical space where the conflict occurs.")
    operational_time: str = Field(description="Exact time window (before, during, after conflict).")
    internal_resources: list[str] = Field(description="Free substances/fields already inside the tool or product.")
    external_resources: list[str] = Field(description="Free environmental substances/fields (gravity, air, heat, etc.).")


class IdealContradiction(BaseModel):
    x_element: str = Field(description="Placeholder name for the ideal resource/modification.")
    ifr_1: str = Field(description="Ideal Final Result: The X-element itself eliminates the harm in the OZ/OT while preserving the useful function.")
    physical_property: str = Field(description="The specific physical parameter in conflict (e.g., stiffness, temperature, conductivity).")
    state_positive: str = Field(description="Why the property MUST be high/present.")
    state_negative: str = Field(description="Why the property MUST be low/absent.")


class InventiveConcept(BaseModel):
    separation_principle: Literal[
        "Separation in Space",
        "Separation in Time",
        "Separation in Scale",
        "Separation on Condition",
        "System Transition",
    ]
    used_resources: list[str] = Field(description="Subset of internal/external SFRs used by this concept.")
    mechanism_description: str = Field(description="Concrete physical/engineering mechanism resolving the contradiction.")
    new_components_added: int = Field(description="Count of brand-new hardware parts added (0 is ideal).")


class AuditVerdict(BaseModel):
    is_compromise: bool = Field(description="True if the concept merely trades off or weakens requirements instead of resolving the contradiction.")
    uses_free_resources: bool = Field(description="True if the concept relies primarily on inventoried SFRs.")
    ideality_score: int = Field(ge=1, le=10, description="1-10 rating of ideality (useful function / cost+harm).")
    critique: str = Field(description="Specific engineering flaw or confirmation of resolution.")


class ArizState(TypedDict):
    raw_problem: str
    mini_problem: Optional[MiniProblemSpec]
    resources: Optional[ConflictResources]
    ideal_pc: Optional[IdealContradiction]
    concept: Optional[InventiveConcept]
    audit: Optional[AuditVerdict]
    retry_count: int
    status: Literal["running", "passed", "failed_circuit_breaker"]


# ---------------------------------------------------------------------------
# 3. Structured Ollama Helper
# ---------------------------------------------------------------------------

def call_structured(system_prompt: str, user_prompt: str, schema: type[BaseModel], temp: float = 0.15):
    response = ollama.chat(
        model=OLLAMA_MODEL,
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt},
        ],
        format=schema.model_json_schema(),
        options={"temperature": temp, "num_ctx": 16384},
    )
    return schema.model_validate_json(response["message"]["content"])


# ---------------------------------------------------------------------------
# 4. ARIZ Pipeline Nodes
# ---------------------------------------------------------------------------

def stage_1_mini_problem(state: ArizState) -> dict:
    sys_msg = (
        "You are an ARIZ-85C specialist. Strip away industry jargon and formulate the "
        "Mini-Problem with two opposing Technical Contradictions (TC-1 and TC-2). "
        "Select the TC that best preserves the primary useful function."
    )
    spec = call_structured(sys_msg, f"Problem:\n{state['raw_problem']}", MiniProblemSpec)
    return {"mini_problem": spec}


def stage_2_resources(state: ArizState) -> dict:
    sys_msg = (
        "Identify the exact Operational Zone (OZ), Operational Time (OT), and all free "
        "Substance-Field Resources (SFR) available inside the system and immediate environment."
    )
    user_msg = f"Problem: {state['raw_problem']}\nMini-Problem:\n{state['mini_problem'].model_dump_json(indent=2)}"
    res = call_structured(sys_msg, user_msg, ConflictResources)
    return {"resources": res}


def stage_3_ifr_pc(state: ArizState) -> dict:
    sys_msg = (
        "Formulate the Ideal Final Result (IFR-1) using an X-element, then derive the sharp "
        "Physical Contradiction (PC): a single physical property that must simultaneously be "
        "in state A and state Not-A within the Operational Zone and Time."
    )
    user_msg = (
        f"Mini-Problem:\n{state['mini_problem'].model_dump_json(indent=2)}\n"
        f"Resources:\n{state['resources'].model_dump_json(indent=2)}"
    )
    pc = call_structured(sys_msg, user_msg, IdealContradiction)
    return {"ideal_pc": pc}


def stage_4_synthesize(state: ArizState) -> dict:
    sys_msg = (
        "Resolve the Physical Contradiction using a TRIZ Separation Principle and the "
        "inventoried free Substance-Field Resources. Do NOT propose a compromise or add "
        "expensive external subsystems if a free resource can perform the function."
    )
    feedback = ""
    if state.get("audit") is not None:
        feedback = (
            f"\n\nPREVIOUS CONCEPT REJECTED (Retry {state['retry_count']}):\n"
            f"Critique: {state['audit'].critique}\n"
            "Generate a fundamentally different mechanism that eliminates this flaw."
        )

    user_msg = (
        f"Resources:\n{state['resources'].model_dump_json(indent=2)}\n"
        f"IFR & Physical Contradiction:\n{state['ideal_pc'].model_dump_json(indent=2)}"
        f"{feedback}"
    )
    # Slightly higher temperature on retries to escape local optima
    temp = 0.25 + (0.15 * state["retry_count"])
    concept = call_structured(sys_msg, user_msg, InventiveConcept, temp=temp)
    return {"concept": concept}


def stage_5_audit(state: ArizState) -> dict:
    sys_msg = (
        "You are an adversarial TRIZ auditor. Evaluate whether the proposed mechanism truly "
        "resolves the Physical Contradiction without compromise and leverages free system resources."
    )
    user_msg = (
        f"Physical Contradiction:\n{state['ideal_pc'].model_dump_json(indent=2)}\n"
        f"Proposed Concept:\n{state['concept'].model_dump_json(indent=2)}"
    )
    verdict = call_structured(sys_msg, user_msg, AuditVerdict, temp=0.05)

    passed = (not verdict.is_compromise) and verdict.uses_free_resources and (verdict.ideality_score >= 7)
    if passed:
        return {"audit": verdict, "status": "passed"}

    next_retry = state["retry_count"] + 1
    if next_retry >= MAX_RETRIES:
        return {"audit": verdict, "retry_count": next_retry, "status": "failed_circuit_breaker"}

    return {"audit": verdict, "retry_count": next_retry, "status": "running"}


def route_after_audit(state: ArizState) -> str:
    return "synthesize" if state["status"] == "running" else END


# ---------------------------------------------------------------------------
# 5. Graph Assembly & Example Execution
# ---------------------------------------------------------------------------

def build_ariz_graph():
    builder = StateGraph(ArizState)
    builder.add_node("mini_problem", stage_1_mini_problem)
    builder.add_node("resources", stage_2_resources)
    builder.add_node("ifr_pc", stage_3_ifr_pc)
    builder.add_node("synthesize", stage_4_synthesize)
    builder.add_node("audit", stage_5_audit)

    builder.set_entry_point("mini_problem")
    builder.add_edge("mini_problem", "resources")
    builder.add_edge("resources", "ifr_pc")
    builder.add_edge("ifr_pc", "synthesize")
    builder.add_edge("synthesize", "audit")
    builder.add_conditional_edges(
        "audit",
        route_after_audit,
        {"synthesize": "synthesize", END: END},
    )
    return builder.compile()


if __name__ == "__main__":
    app = build_ariz_graph()

    initial_state: ArizState = {
        "raw_problem": (
            "Interlocking lightweight building blocks must have tight slot-and-key tolerances "
            "for structural rigidity, but tight tolerances trap moisture and prevent uniform "
            "waterproofing coatings from sealing the internal joints."
        ),
        "mini_problem": None,
        "resources": None,
        "ideal_pc": None,
        "concept": None,
        "audit": None,
        "retry_count": 0,
        "status": "running",
    }

    result = app.invoke(initial_state)
    print(f"Status: {result['status']} (Retries: {result['retry_count']})")
    print("\n--- Physical Contradiction ---")
    print(result["ideal_pc"].model_dump_json(indent=2))
    print("\n--- Final Concept ---")
    print(result["concept"].model_dump_json(indent=2))
    print("\n--- Audit Verdict ---")
    print(result["audit"].model_dump_json(indent=2))

3. Why This Works Reliably on Local 30B Models

  • Zero schema drift: Passing schema.model_json_schema() to Ollama's format parameter constrains token sampling at the grammar level, eliminating markdown wrapper bugs and missing fields.

  • Temperature staging: Stages 1–3 and the Stage 5 Auditor run at low temperature (0.05–0.15) for analytical precision, while Stage 4 steps up temperature (0.25 -> 0.40 -> 0.55) on retries to break out of repetitive design loops.

  • Strict compromise rejection: The deterministic threshold (not is_compromise and uses_free_resources and ideality_score >= 7) prevents the 30B model from self-approving a mediocre trade-off.


Is there value to using AI agents applying innovative thinking methods using local 30B models?

Yes—there is substantial, measurable value, provided you treat the 30B model as a disciplined engine inside a structured pipeline rather than a single-shot oracle.

In systematic innovation, process rigor and iteration volume frequently beat raw parameter count. A local 30B agent forced through a strict state machine (such as LangGraph with Pydantic v2 contracts and an adversarial critic) routinely produces more actionable, contradiction-resolving concepts than a single prompt to a cloud frontier model.

Where Local 30B Innovation Agents Deliver Real Value

  • Massive Search-Space Exploration at Zero Marginal Cost: Systematic methods like Morphological Analysis, multi-branch ARIZ, and Evaluator-Critic loops require dozens or hundreds of LLM calls per problem. On cloud APIs, running 50 parallel contradiction-resolution branches overnight becomes expensive quickly. On local 64–128 GB unified memory, you can trade overnight compute for exhaustive breadth at $0 per token.

  • Complete IP and Trade-Secret Sovereignty: Early-stage product architecture, patentable mechanisms, and proprietary teardowns are the highest-risk data to send to third-party APIs. Local 30B execution keeps raw problem statements, constraints, and inventive concepts completely air-gapped.

  • Eliminating "Shortcut Bias" Through Architecture: Even frontier models tend to jump straight to conventional compromises when prompted in one shot. A local 30B agent constrained by a multi-stage graph cannot skip the Operational Zone, Substance-Field Resource inventory, or Physical Contradiction—forcing genuine structural novelty.

  • Tight Integration with Local Deterministic Tools: Local 30B models sit on the same machine as your Neo4j knowledge graphs, SymPy equation verifiers, SQLite3 audit ledgers, and OpenSCAD/trimesh geometry checkers. Zero-latency local tool-calling turns abstract innovation ideas into verified equations or watertight CAD prototypes in a single loop.

Where Local 30B Agents Hit Their Ceiling

Being candid about the limits prevents wasted effort:

  • Obscure Cross-Domain Recall: For TRIZ Function-Oriented Search (FOS), a 30B model has less long-tail scientific memory than a 400B+ frontier model. It may miss an obscure materials-science effect or niche biological mechanism unless you supply that knowledge via a local Neo4j GraphRAG or textbook index.

  • High-Nuance Strategic Synthesis: When a problem has 15+ loosely coupled socio-economic or market variables (e.g., complex Meadows' Leverage Points in an organization), 30B models can lose track of subtle second-order feedback loops compared to frontier reasoning models.

  • Self-Critique Blind Spots: A 30B model auditing its own output can occasionally approve a subtly flawed mechanism. You mitigate this by pairing it with deterministic checks (SymPy, bounding-box/manifold gates) or using a different 30B model family as the adversarial critic (e.g., Gemma 4 31B generating, Granite 4 32B auditing).

Local 30B Agents vs. Cloud Frontier Models

DimensionLocal 30B Agentic PipelineCloud Frontier Model (Single/Few-Shot)
Iteration VolumeUnlimited overnight batch runs ($0/token)Rate-limited and cost-sensitive
IP & Patent Privacy100% air-gapped on local hardwareExternal API transmission
Methodological DisciplineHigh (enforced by LangGraph + Pydantic)Prone to skipping steps unless heavily scaffolded
Obscure Scientific RecallModerate (requires local GraphRAG/RAG)Very High
Best RoleHeavy lifting, exhaustive ideation, verified engineering loopsFinal sanity check or obscure cross-domain lookup

The highest-leverage pattern is local-first, hybrid-optional: run 95% of your structured ideation, contradiction resolution, and verification loops locally on 30B models, and only escalate sanitized, abstracted sub-problems to a frontier model when you hit a genuine scientific knowledge gap.



Describe how to use online models to identify opportunities in industry and user groups for which to apply the local model innovative thinking methods to recommend solutions

The most effective architecture separates external sensing (online models) from internal invention (local 7B/30B models), joined by a strict Pydantic v2 handoff contract.

Online models with live web search excel at scanning fragmented market signals, regulatory shifts, and user complaints. Local models excel at running exhaustive, zero-cost, IP-private TRIZ, ARIZ, and First Principles loops on those raw opportunities.

Phase 1: Online Discovery (Cloud Models + Live Search)

Use an online frontier model (such as Gemini with Google Search grounding) strictly as a market intelligence scout. Run targeted prompts across three lenses to surface concrete friction rather than generic "trends":

  • Regulatory & Economic Friction Scans: Query for newly enacted compliance mandates, reporting rules, or cost pressures hitting a specific industry vertical. New regulations reliably create sudden, painful manual workflows where buyers have immediate budget.

  • User-Group "Workaround" Mining: Target specific B2B roles or niche user communities (via forums, G2/Capterra reviews, industry trade publications, and job postings) to find where people complain about spreadsheets, manual reconciliation, or slow handoffs. Focus on the exact Job to Be Done and the process step that breaks.

  • Competitor & Segment Gap Mapping: Have the online model map existing tools, their pricing floors, and the underserved sub-segments they ignore (e.g., enterprise tools that price out mid-market or regional operators).

Phase 2: The Handoff Contract (Sanitized Opportunity Dossier)

Never feed raw web summaries into your local models. Force the online model to output a strict JSON Opportunity Dossier, validate it with Pydantic v2, and score it deterministically in Python before storing it in SQLite3.

from pydantic import BaseModel, Field

class OpportunityDossier(BaseModel):
    industry_vertical: str
    target_user_group: str
    broken_workflow: str = Field(description="Exact manual or failing process step.")
    current_workaround: str = Field(description="How users cope today (e.g., Excel, email chasing).")
    core_contradiction: str = Field(description="What improves vs. what worsens if they try to fix it today.")
    economic_trigger: str = Field(description="Cost, fine, or lost revenue driving urgency.")
    evidence_urls: list[str]
    pain_severity_1_to_5: int = Field(ge=1, le=5)
    frequency_1_to_5: int = Field(ge=1, le=5)

Only dossiers that clear your deterministic threshold (e.g., pain_severity >= 4 and a clear core_contradiction) get queued for local synthesis.

Phase 3: Local Synthesis (7B + 30B Innovation Engine)

Once the validated dossiers sit in your local SQLite3 database, disconnect from the cloud. Your proprietary solution concepts, architecture specs, and IP remain 100% air-gapped.

  1. 7B Fast Expansion (Granite 4.2 8B / Gemma 4 E4B):

    • Run Nine-Screen (9 Windows) analysis on each dossier to map the user's subsystem, workflow, and broader ecosystem.

    • Run Reverse Brainstorming ("How could a solution fail to be adopted by this user group?") to surface adoption traps early.

    • Generate raw Morphological Analysis axes (delivery mechanism, data source, trigger event, monetization).

  2. 30B Deep Invention (Gemma 4 31B / Granite 4 32B / Nemotron-3-Nano):

    • Feed the core_contradiction into your stateful LangGraph ARIZ or TRIZ Ideal Final Result (IFR) pipeline to eliminate trade-offs rather than building a slightly faster version of an existing tool.

    • Run Function-Oriented Search (FOS) against your local Neo4j knowledge graph to import proven mechanisms from unrelated industries.

    • Prune the 7B Morphological grid down to the top 3 physically and economically viable wedge products.

  3. Local Adversarial Audit (Cross-Model Critic):

    • Pass each surviving concept to a second 30B model family acting as an FMEA/Skeptic Critic to stress-test cost creep, integration friction, and switching costs.

Division of Labor Summary

StageModel TierPrimary JobKey Advantage
1. Market & User SensingOnline Frontier + SearchMine live complaints, regulations, and competitor gapsReal-time web awareness & broad market recall
2. Dossier FilteringDeterministic PythonPydantic validation + weighted pain/urgency scoringZero hallucination; blocks low-value noise
3. Grid & Failure ExpansionLocal 7B (12 GB VRAM)9-Windows, SCAMPER, Reverse Brainstorming, Morph axesSub-second latency; high-volume batching
4. Contradiction ResolutionLocal 30B (64–128 GB)Stateful ARIZ, TRIZ IFR, First Principles, Critic loops$0/token overnight iteration + 100% IP privacy



Write a Python bridge script using the Google GenAI SDK with Search grounding to generate Pydantic-validated OpportunityDossier records and save them into a SQLite3 queue for a local Ollama 30B ARIZ pipeline.

Install the required packages and set your GEMINI_API_KEY environment variable:

pip install -U google-genai pydantic

This bridge script (opportunity_bridge.py) uses the google-genai SDK to combine Google Search grounding with Structured Outputs (JSON Schema) in a single call, extracts verified citation URLs directly from grounding_metadata.grounding_chunks, validates every record with Pydantic v2, filters out low-value noise deterministically, and persists qualified dossiers into a SQLite3 (WAL mode) queue ready for your local Ollama 30B ARIZ pipeline.

"""
Online-to-Local Bridge: Gemini Search Grounding -> Pydantic v2 -> SQLite3 Queue
Feeds validated OpportunityDossier records into a local Ollama 30B ARIZ pipeline.
"""

import hashlib
import json
import sqlite3
from datetime import datetime, timezone
from pathlib import Path
from typing import Literal

from google import genai
from google.genai import types
from pydantic import BaseModel, Field

# ---------------------------------------------------------------------------
# 1. Configuration
# ---------------------------------------------------------------------------

GEMINI_MODEL = "gemini-2.5-flash"  # Supports Search grounding + Structured Outputs
DB_PATH = Path("./innovation_queue.db")
MIN_QUEUE_SCORE = 16  # Deterministic threshold: pain (1-5) * frequency (1-5) >= 16


# ---------------------------------------------------------------------------
# 2. Contract-First Schemas (Pydantic v2)
# ---------------------------------------------------------------------------

class OpportunityDossier(BaseModel):
    industry_vertical: str
    target_user_group: str
    broken_workflow: str = Field(description="Exact manual, slow, or failing process step.")
    current_workaround: str = Field(description="How users cope today (e.g., Excel, email chasing).")
    core_contradiction: str = Field(
        description="Technical/operational contradiction: what improves vs. what worsens if fixed conventionally."
    )
    economic_trigger: str = Field(description="Cost, fine, or lost revenue driving urgency.")
    pain_severity: int = Field(ge=1, le=5, description="1 (minor annoyance) to 5 (severe financial/operational pain).")
    frequency: int = Field(ge=1, le=5, description="1 (annual) to 5 (daily/continuous).")


class DossierBatch(BaseModel):
    dossiers: list[OpportunityDossier] = Field(min_length=1, max_length=5)


# ---------------------------------------------------------------------------
# 3. SQLite3 WAL-Mode Queue Persistence
# ---------------------------------------------------------------------------

def init_db(db_path: Path) -> sqlite3.Connection:
    conn = sqlite3.connect(str(db_path))
    conn.execute("PRAGMA journal_mode=WAL;")
    conn.execute("PRAGMA foreign_keys=ON;")
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS opportunity_queue (
            id TEXT PRIMARY KEY,
            created_at TEXT NOT NULL,
            industry_vertical TEXT NOT NULL,
            target_user_group TEXT NOT NULL,
            priority_score INTEGER NOT NULL,
            status TEXT NOT NULL DEFAULT 'pending',
            dossier_json TEXT NOT NULL,
            evidence_urls_json TEXT NOT NULL,
            ariz_result_json TEXT
        );
        """
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_queue_status_score ON opportunity_queue(status, priority_score DESC);"
    )
    conn.commit()
    return conn


def compute_dossier_id(d: OpportunityDossier) -> str:
    """Deterministic hash for idempotent ingestion (prevents duplicate queue rows)."""
    key = f"{d.industry_vertical.lower()}|{d.target_user_group.lower()}|{d.broken_workflow.lower()}"
    return hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]


def enqueue_dossiers(
    conn: sqlite3.Connection,
    dossiers: list[OpportunityDossier],
    evidence_urls: list[str],
) -> tuple[int, int]:
    inserted = 0
    skipped = 0
    now = datetime.now(timezone.utc).isoformat()

    for d in dossiers:
        score = d.pain_severity * d.frequency
        if score < MIN_QUEUE_SCORE:
            skipped += 1
            continue

        row_id = compute_dossier_id(d)
        cur = conn.execute(
            """
            INSERT OR IGNORE INTO opportunity_queue
            (id, created_at, industry_vertical, target_user_group, priority_score, status, dossier_json, evidence_urls_json)
            VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)
            """,
            (
                row_id,
                now,
                d.industry_vertical,
                d.target_user_group,
                score,
                d.model_dump_json(),
                json.dumps(evidence_urls),
            ),
        )
        if cur.rowcount == 1:
            inserted += 1
        else:
            skipped += 1

    conn.commit()
    return inserted, skipped


# ---------------------------------------------------------------------------
# 4. Online Discovery via Gemini + Google Search Grounding
# ---------------------------------------------------------------------------

def extract_grounding_urls(response) -> list[str]:
    urls: list[str] = []
    try:
        metadata = response.candidates[0].grounding_metadata
        if metadata and metadata.grounding_chunks:
            for chunk in metadata.grounding_chunks:
                if getattr(chunk, "web", None) and chunk.web.uri:
                    urls.append(chunk.web.uri)
    except (IndexError, AttributeError):
        pass
    return sorted(set(urls))


def discover_opportunities(industry: str, focus_angle: str) -> tuple[list[OpportunityDossier], list[str]]:
    client = genai.Client()  # Reads GEMINI_API_KEY from environment

    prompt = (
        f"Search the web for concrete, recent operational pain points in the '{industry}' industry, "
        f"specifically focusing on: {focus_angle}.\n\n"
        "Identify 3 to 5 distinct, underserved workflow bottlenecks where practitioners rely on "
        "manual workarounds (spreadsheets, email chasing, paper logs) or face a sharp engineering/economic "
        "contradiction. Avoid generic trends; ground every dossier in real industry friction."
    )

    config = types.GenerateContentConfig(
        tools=[types.Tool(google_search=types.GoogleSearch())],
        response_mime_type="application/json",
        response_schema=DossierBatch,
        temperature=0.2,
    )

    response = client.models.generate_content(
        model=GEMINI_MODEL,
        contents=prompt,
        config=config,
    )

    batch = DossierBatch.model_validate_json(response.text)
    urls = extract_grounding_urls(response)
    return batch.dossiers, urls


# ---------------------------------------------------------------------------
# 5. Local Consumer Helper (for your Ollama 30B ARIZ Pipeline)
# ---------------------------------------------------------------------------

def claim_next_pending(conn: sqlite3.Connection) -> tuple[str, OpportunityDossier] | None:
    """Atomically claims the highest-priority pending dossier for local ARIZ processing."""
    row = conn.execute(
        """
        SELECT id, dossier_json FROM opportunity_queue
        WHERE status = 'pending'
        ORDER BY priority_score DESC, created_at ASC
        LIMIT 1
        """
    ).fetchone()

    if not row:
        return None

    row_id, dossier_json = row
    conn.execute("UPDATE opportunity_queue SET status = 'processing' WHERE id = ?", (row_id,))
    conn.commit()
    return row_id, OpportunityDossier.model_validate_json(dossier_json)


def mark_completed(conn: sqlite3.Connection, row_id: str, ariz_result: dict, status: Literal["completed", "failed"] = "completed"):
    conn.execute(
        "UPDATE opportunity_queue SET status = ?, ariz_result_json = ? WHERE id = ?",
        (status, json.dumps(ariz_result), row_id),
    )
    conn.commit()


# ---------------------------------------------------------------------------
# 6. Example Run
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    conn = init_db(DB_PATH)

    dossiers, urls = discover_opportunities(
        industry="Regional Marine Marinas & Boatyards",
        focus_angle="compliance reporting, slip/lift scheduling bottlenecks, and manual billing workarounds",
    )

    inserted, skipped = enqueue_dossiers(conn, dossiers, urls)
    print(f"Discovered: {len(dossiers)} | Queued: {inserted} | Skipped/Duplicate: {skipped}")
    print(f"Grounded URLs captured: {len(urls)}")

    # Preview next item ready for local Ollama 30B ARIZ
    next_item = claim_next_pending(conn)
    if next_item:
        row_id, dossier = next_item
        print(f"\nClaimed [{row_id}] for local ARIZ:")
        print(dossier.model_dump_json(indent=2))

Key Architectural Safeguards

  • Verified Citations Only: Rather than asking the LLM to hallucinate URLs inside the JSON payload, extract_grounding_urls() pulls real source links directly from grounding_metadata.grounding_chunks.

  • Idempotent Ingestion: Each dossier is hashed by (industry, user_group, broken_workflow) with INSERT OR IGNORE, so repeated discovery sweeps never duplicate work in your local ARIZ queue.

  • Clean Online/Offline Boundary: Once opportunity_bridge.py populates innovation_queue.db, your local Ollama 30B script (ariz_orchestrator.py) simply calls claim_next_pending(conn) and mark_completed(...) completely offline.



Extend opportunity_bridge.py with a configurable YAML/JSON list of industries and friction angles to run scheduled discovery sweeps with rate-limit backoff.

Install pyyaml alongside the existing dependencies:

pip install -U google-genai pydantic pyyaml

1. Configurable Sweep File (sweep_config.yaml)

Save this alongside opportunity_bridge.py (JSON files with the exact same structure are also supported automatically).

min_queue_score: 16
inter_request_delay_sec: 4.0
max_backoff_retries: 4
base_backoff_sec: 5.0

targets:
  - industry: "Regional Marine Marinas & Boatyards"
    enabled: true
    angles:
      - "compliance reporting and environmental logbook bottlenecks"
      - "slip, haul-out, and boat lift scheduling workarounds"
  - industry: "Independent Cold-Chain Logistics"
    enabled: true
    angles:
      - "temperature excursion reconciliation and manual claims disputes"
      - "dock-door appointment scheduling via phone and spreadsheets"
  - industry: "Mid-Market CNC Job Shops"
    enabled: false
    angles:
      - "quoting turnaround delays and manual CAM setup estimation"

2. Extended opportunity_bridge.py

This drop-in replacement validates the YAML/JSON config with Pydantic v2, adds exponential backoff with jitter for 429/503 rate limits, logs every sweep to a sweep_runs table in SQLite3, and supports both one-shot cron/Task Scheduler runs and interval-based scheduled loops.

"""
Online-to-Local Bridge (Extended):
YAML/JSON Multi-Industry Sweeps -> Rate-Limit Backoff -> Pydantic v2 -> SQLite3 Queue
"""

import argparse
import hashlib
import json
import random
import sqlite3
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Literal

import yaml
from google import genai
from google.genai import errors as genai_errors
from google.genai import types
from pydantic import BaseModel, Field

# ---------------------------------------------------------------------------
# 1. Configuration & Contract-First Schemas (Pydantic v2)
# ---------------------------------------------------------------------------

GEMINI_MODEL = "gemini-2.5-flash"
DB_PATH = Path("./innovation_queue.db")


class SweepTarget(BaseModel):
    industry: str
    enabled: bool = True
    angles: list[str] = Field(min_length=1)


class SweepConfig(BaseModel):
    min_queue_score: int = Field(default=16, ge=1, le=25)
    inter_request_delay_sec: float = Field(default=4.0, ge=0.0)
    max_backoff_retries: int = Field(default=4, ge=1, le=10)
    base_backoff_sec: float = Field(default=5.0, ge=1.0)
    targets: list[SweepTarget] = Field(min_length=1)


class OpportunityDossier(BaseModel):
    industry_vertical: str
    target_user_group: str
    broken_workflow: str = Field(description="Exact manual, slow, or failing process step.")
    current_workaround: str = Field(description="How users cope today (e.g., Excel, email chasing).")
    core_contradiction: str = Field(
        description="Technical/operational contradiction: what improves vs. what worsens if fixed conventionally."
    )
    economic_trigger: str = Field(description="Cost, fine, or lost revenue driving urgency.")
    pain_severity: int = Field(ge=1, le=5, description="1 (minor annoyance) to 5 (severe financial/operational pain).")
    frequency: int = Field(ge=1, le=5, description="1 (annual) to 5 (daily/continuous).")


class DossierBatch(BaseModel):
    dossiers: list[OpportunityDossier] = Field(min_length=1, max_length=5)


def load_sweep_config(config_path: Path) -> SweepConfig:
    raw_text = config_path.read_text(encoding="utf-8")
    if config_path.suffix.lower() == ".json":
        data = json.loads(raw_text)
    elif config_path.suffix.lower() in (".yaml", ".yml"):
        data = yaml.safe_load(raw_text)
    else:
        raise ValueError(f"Unsupported config extension: {config_path.suffix} (use .yaml, .yml, or .json)")
    return SweepConfig.model_validate(data)


# ---------------------------------------------------------------------------
# 2. SQLite3 WAL-Mode Persistence & Sweep Audit Log
# ---------------------------------------------------------------------------

def init_db(db_path: Path) -> sqlite3.Connection:
    conn = sqlite3.connect(str(db_path))
    conn.execute("PRAGMA journal_mode=WAL;")
    conn.execute("PRAGMA foreign_keys=ON;")
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS opportunity_queue (
            id TEXT PRIMARY KEY,
            created_at TEXT NOT NULL,
            industry_vertical TEXT NOT NULL,
            target_user_group TEXT NOT NULL,
            priority_score INTEGER NOT NULL,
            status TEXT NOT NULL DEFAULT 'pending',
            dossier_json TEXT NOT NULL,
            evidence_urls_json TEXT NOT NULL,
            ariz_result_json TEXT
        );
        """
    )
    conn.execute(
        """
        CREATE TABLE IF NOT EXISTS sweep_runs (
            run_id INTEGER PRIMARY KEY AUTOINCREMENT,
            started_at TEXT NOT NULL,
            industry TEXT NOT NULL,
            angle TEXT NOT NULL,
            discovered_count INTEGER NOT NULL,
            queued_count INTEGER NOT NULL,
            skipped_count INTEGER NOT NULL,
            status TEXT NOT NULL,
            error_message TEXT
        );
        """
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_queue_status_score ON opportunity_queue(status, priority_score DESC);"
    )
    conn.commit()
    return conn


def compute_dossier_id(d: OpportunityDossier) -> str:
    key = f"{d.industry_vertical.lower()}|{d.target_user_group.lower()}|{d.broken_workflow.lower()}"
    return hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]


def enqueue_dossiers(
    conn: sqlite3.Connection,
    dossiers: list[OpportunityDossier],
    evidence_urls: list[str],
    min_score: int,
) -> tuple[int, int]:
    inserted = 0
    skipped = 0
    now = datetime.now(timezone.utc).isoformat()

    for d in dossiers:
        score = d.pain_severity * d.frequency
        if score < min_score:
            skipped += 1
            continue

        row_id = compute_dossier_id(d)
        cur = conn.execute(
            """
            INSERT OR IGNORE INTO opportunity_queue
            (id, created_at, industry_vertical, target_user_group, priority_score, status, dossier_json, evidence_urls_json)
            VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)
            """,
            (
                row_id,
                now,
                d.industry_vertical,
                d.target_user_group,
                score,
                d.model_dump_json(),
                json.dumps(evidence_urls),
            ),
        )
        if cur.rowcount == 1:
            inserted += 1
        else:
            skipped += 1

    conn.commit()
    return inserted, skipped


def log_sweep_run(
    conn: sqlite3.Connection,
    industry: str,
    angle: str,
    discovered: int,
    queued: int,
    skipped: int,
    status: str,
    error_message: str | None = None,
):
    conn.execute(
        """
        INSERT INTO sweep_runs
        (started_at, industry, angle, discovered_count, queued_count, skipped_count, status, error_message)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        """,
        (
            datetime.now(timezone.utc).isoformat(),
            industry,
            angle,
            discovered,
            queued,
            skipped,
            status,
            error_message,
        ),
    )
    conn.commit()


# ---------------------------------------------------------------------------
# 3. Online Discovery with Exponential Backoff + Jitter
# ---------------------------------------------------------------------------

def extract_grounding_urls(response) -> list[str]:
    urls: list[str] = []
    try:
        metadata = response.candidates[0].grounding_metadata
        if metadata and metadata.grounding_chunks:
            for chunk in metadata.grounding_chunks:
                if getattr(chunk, "web", None) and chunk.web.uri:
                    urls.append(chunk.web.uri)
    except (IndexError, AttributeError):
        pass
    return sorted(set(urls))


def discover_with_backoff(
    client: genai.Client,
    industry: str,
    focus_angle: str,
    max_retries: int,
    base_backoff_sec: float,
) -> tuple[list[OpportunityDossier], list[str]]:
    prompt = (
        f"Search the web for concrete, recent operational pain points in the '{industry}' industry, "
        f"specifically focusing on: {focus_angle}.\n\n"
        "Identify 3 to 5 distinct, underserved workflow bottlenecks where practitioners rely on "
        "manual workarounds (spreadsheets, email chasing, paper logs) or face a sharp engineering/economic "
        "contradiction. Avoid generic trends; ground every dossier in real industry friction."
    )

    config = types.GenerateContentConfig(
        tools=[types.Tool(google_search=types.GoogleSearch())],
        response_mime_type="application/json",
        response_schema=DossierBatch,
        temperature=0.2,
    )

    for attempt in range(max_retries):
        try:
            response = client.models.generate_content(
                model=GEMINI_MODEL,
                contents=prompt,
                config=config,
            )
            batch = DossierBatch.model_validate_json(response.text)
            urls = extract_grounding_urls(response)
            return batch.dossiers, urls

        except genai_errors.APIError as exc:
            # Retry only on transient rate-limit (429) or server errors (5xx)
            retryable = exc.code in (429, 500, 503, 504)
            if not retryable or attempt == max_retries - 1:
                raise
            sleep_sec = (base_backoff_sec * (2 ** attempt)) + random.uniform(0.5, 2.0)
            print(f"  [Backoff] API {exc.code} on attempt {attempt + 1}/{max_retries}. Sleeping {sleep_sec:.1f}s...")
            time.sleep(sleep_sec)

    raise RuntimeError("Exceeded max backoff retries.")


# ---------------------------------------------------------------------------
# 4. Sweep Runner & Local Consumer Helpers
# ---------------------------------------------------------------------------

def run_sweep(conn: sqlite3.Connection, cfg: SweepConfig):
    client = genai.Client()  # Reads GEMINI_API_KEY from environment
    active_targets = [t for t in cfg.targets if t.enabled]
    total_queued = 0

    for target in active_targets:
        for angle in target.angles:
            print(f"[Sweep] {target.industry} | Angle: {angle}")
            try:
                dossiers, urls = discover_with_backoff(
                    client=client,
                    industry=target.industry,
                    focus_angle=angle,
                    max_retries=cfg.max_backoff_retries,
                    base_backoff_sec=cfg.base_backoff_sec,
                )
                queued, skipped = enqueue_dossiers(conn, dossiers, urls, cfg.min_queue_score)
                total_queued += queued
                log_sweep_run(conn, target.industry, angle, len(dossiers), queued, skipped, "ok")
                print(f"  -> Discovered: {len(dossiers)} | Queued: {queued} | Skipped: {skipped} | URLs: {len(urls)}")
            except Exception as exc:
                log_sweep_run(conn, target.industry, angle, 0, 0, 0, "error", str(exc))
                print(f"  -> [ERROR] {exc}")

            if cfg.inter_request_delay_sec > 0:
                time.sleep(cfg.inter_request_delay_sec)

    print(f"[Sweep Complete] Total new dossiers queued: {total_queued}\n")


def claim_next_pending(conn: sqlite3.Connection) -> tuple[str, OpportunityDossier] | None:
    row = conn.execute(
        """
        SELECT id, dossier_json FROM opportunity_queue
        WHERE status = 'pending'
        ORDER BY priority_score DESC, created_at ASC
        LIMIT 1
        """
    ).fetchone()
    if not row:
        return None
    row_id, dossier_json = row
    conn.execute("UPDATE opportunity_queue SET status = 'processing' WHERE id = ?", (row_id,))
    conn.commit()
    return row_id, OpportunityDossier.model_validate_json(dossier_json)


def mark_completed(
    conn: sqlite3.Connection,
    row_id: str,
    ariz_result: dict,
    status: Literal["completed", "failed"] = "completed",
):
    conn.execute(
        "UPDATE opportunity_queue SET status = ?, ariz_result_json = ? WHERE id = ?",
        (status, json.dumps(ariz_result), row_id),
    )
    conn.commit()


# ---------------------------------------------------------------------------
# 5. CLI Entrypoint (One-Shot or Scheduled Loop)
# ---------------------------------------------------------------------------

def main():
    parser = argparse.ArgumentParser(description="Run configurable Gemini Search opportunity sweeps.")
    parser.add_argument("--config", type=Path, default=Path("sweep_config.yaml"), help="Path to YAML or JSON config.")
    parser.add_argument("--db", type=Path, default=DB_PATH, help="Path to SQLite3 queue database.")
    parser.add_argument(
        "--interval-hours",
        type=float,
        default=0.0,
        help="If > 0, repeat the sweep every N hours. Default 0 runs once (ideal for cron/Task Scheduler).",
    )
    args = parser.parse_args()

    conn = init_db(args.db)
    try:
        while True:
            # Reload config each cycle so you can edit industries/angles without restarting
            cfg = load_sweep_config(args.config)
            run_sweep(conn, cfg)
            if args.interval_hours <= 0:
                break
            sleep_sec = args.interval_hours * 3600
            print(f"[Scheduler] Sleeping {args.interval_hours}h until next sweep...")
            time.sleep(sleep_sec)
    finally:
        conn.close()


if __name__ == "__main__":
    main()

3. Running the Sweeps

  • Single sweep (for Windows Task Scheduler or cron):

    python opportunity_bridge.py --config sweep_config.yaml
    
  • Continuous scheduled loop (reloads sweep_config.yaml before every cycle):

    python opportunity_bridge.py --config sweep_config.yaml --interval-hours 24



From <https://gemini.google.com/app/833c30cb4399b84f>  Google Gemini (4 Neon)

Comments

Popular posts from this blog

#4297 ISS Astronaut Unable to Speak

#3356 PHP and JavaScript to Retrieve and Set an API_Key

#761 New Ways to Access Online Content, particularly Virtual Reality Content