TotalApp Docs

Patent Agent

The server-side engine behind the Patent & R&D Operations add-on — a jurisdiction Strategy Pattern for patent specification/statutory-rule forms, plus eleven AI reasoning endpoints that power the "Stage 2" half of every hybrid Embedding+AI screen in the add-on.

What Is the Patent Agent?

The Patent Engine is the single server-side component that backs every AI-calling and jurisdiction-aware screen in the Patent & R&D Operations add-on. It has two distinct jobs living in one place:

  • A jurisdiction Strategy Pattern (its oldest part, mirroring Compliance Engine's and FleetDriverPermitEngine's shape) — given a country code and a schema category, it picks the matching PatentSchemaStrategy (TÜRKPATENT, EPO, USPTO, WIPO/PCT, or a generic default) and returns a ready-to-render patent specification or statutory-rule form.
  • Eleven independent AI reasoning endpoints, one per screen in the add-on, each following the exact same shape: build a prompt from the request, route it to Cohere / Anthropic API / Claude CLI depending on apiMode, parse the model's JSON response, and log the result via the Event & Analytics Engine.

In one sentence

Patent Agent is where every "Stage 2" AI call in Patent & R&D Operations actually runs — the frontend's job is only to find the right context via local embeddings first (Stage 1) and hand it to one of this agent's eleven endpoints.

The Two-Stage Hybrid Pattern This Agent Completes

Nearly every screen in Patent & R&D Operations runs the same two-stage flow, and Patent Agent is always Stage 2:

Stage 1 — Embedding Engine (client, local Ollama only) Stage 2 — Patent Agent (this agent, AI Model-routed)
StageWhere it runsWhat it does
Stage 1Entirely client-side, in the Embedding Service, which wraps the shared Knowledge EngineVectorizes the user's query/spec/claim text and a small candidate corpus via the user's own local Ollama instance (ollamaEngine.embed + cosine similarity), never touching the server. This is the same primitive the Knowledge Search Service uses for My Knowledge/writer-tool "Attach Knowledge" ranking.
Stage 2Client-side (callClaude()) or server-side (this agent), depending on the user's Settings → Agentic choiceTakes the top Stage-1 matches and reasons over them — risk scoring, novelty classification, feasibility auditing, financial modeling, etc. Only reached on the server when the AI Model is set to 'api' or 'local-cli'.

Why does Stage 1 never reach the server?

ollama/local-llm/web-llm all run in the user's own browser or on their own machine — the Render server has no network path to a user's 127.0.0.1:11434 Ollama instance. If a client function skipped this check and always called the server, selecting Ollama in Settings would silently produce confusing 500s instead of routing locally. This is documented project-wide as the "Full Writer Engine Support Rule," and every one of Patent Agent's eleven client-side counterparts implements it.

Part 1 — Jurisdiction Schema Strategy

resolvePatentStrategy(countryCode) upper-cases the incoming code and switches between five concrete PatentSchemaStrategy classes, each implementing one method: getSchema(category).

StrategyJurisdictionStatute referenced
TRPatentStrategyTurkey (TÜRKPATENT)6769 Sınai Mülkiyet Kanunu
EPPatentStrategyEPO member states (DE, FR, IT, ES, NL, BE, PL, SE, AT, PT, GR, IE, DK, FI, GB, CH)European Patent Convention (EPC) Rules
USPatentStrategyUnited States (USPTO)35 U.S.C.
WIPOPatentStrategyWO — international PCT filingPatent Cooperation Treaty (PCT)
DefaultPatentStrategyAny unmapped countryGeneric fallback fields, never throws

Each strategy branches again on category, returning one of two different field sets:

patent_specifications

Application title, IPC/CPC classification, abstract text, claims text, and jurisdiction-specific fields (priority date for TR/EP/WIPO, provisional filing date and first-inventor-to-file date for US, designated states for WIPO).

jurisdiction_rules

Statute reference, official filing fee (in the jurisdiction's own currency — ₺ for TR, € for EP, $ for US, CHF for WIPO), official language, and whether translation is required. Powers the Legal Jurisdiction Setup screen's engine-driven statutory rule modal.

The resulting UiComponent Form tree is rendered by the same <DynamicScreenRenderer> component every other server-driven-UI schema in TotalApp uses — served by handlePatentEngineGenerateSchema at POST /api/patent-engine/generate-schema.

Part 2 — The Eleven AI Reasoning Endpoints

Every AI-calling screen in Patent & R&D Operations has its own dedicated handler function in this file. All eleven share one identical shape — build prompt, route by apiMode (Cohere command-r7b-12-2024 / Anthropic claude-sonnet-4-6 / Claude CLI), parse the model's JSON, log via Event & Analytics Engine — and differ only in their prompt content and output schema:

HandlerEndpointScreen it powersWhat it computes
handlePatentCollisionOverlapAnalyze/patent-engine/collision-overlap-analyzePatent Collision ScannerSemantic overlap summary + risk level (critical/moderate/safe) between a target R&D spec and a matched competitor patent.
handlePriorArtSearch/patent-engine/prior-art-searchPrior Art Search EngineTechnical relevance score + novelty impact classification (blocking/background/non-relevant) for each candidate reference.
handleClaimsMatrixCompare/patent-engine/claims-matrix-compareClaims Matrix ComparerPer-element limitation match status (literal match / doctrine of equivalents / non-infringing) plus an overall legal reasoning summary.
handleFtoRiskSynthesize/patent-engine/fto-risk-synthesizeFTO Risk AnalysisMarket clearance status (cleared/conditional/blocked) and a concrete technical design-around recommendation.
handleLiteratureSynthesize/patent-engine/literature-synthesizeLiterature SynthesisConsensus level across source papers, state-of-the-art summary, key methodologies, benchmarks, technology gaps.
handlePaperMetadataExtract/patent-engine/paper-metadata-extractResearch Paper LibraryAuto-extracts DOI, author list, journal/conference name, and a methodology summary from raw paper text.
handleSpecAuditAnalyze/patent-engine/spec-audit-analyzeR&D Project Spec AuditFeasibility score, compliance status, and conflicting-claims list for a project spec audited against literature benchmarks.
handleDisclosureAssess/patent-engine/disclosure-assessInvention Disclosure ReviewNovelty score, commercial readiness rating, inventive steps, and suggested target filing jurisdictions.
handleGrantComplianceAudit/patent-engine/grant-compliance-auditGrant & Incentive TrackingCompliance status, missing technical deliverables, and budget deviation notes against a funding authority's spec.
handleLicenseClauseAudit/patent-engine/license-clause-auditTech Transfer & LicensingNon-standard indemnity clauses, field-of-use restrictions, and territory limits found in a license's contract text.
handleIpValuationAnalyze/patent-engine/ip-valuation-analyzeIP Valuation & RoyaltyFair market value, recommended royalty rate, confidence index, and discount-rate/cash-flow/benchmark notes.

Why eleven near-identical handlers instead of one generic one?

Each handler's prompt is domain-specific — a collision-risk prompt and a royalty-valuation prompt ask the model to reason about completely different things and return a different JSON shape. Keeping them as separate, independently testable functions (rather than one parameterized mega-handler) means a change to one screen's reasoning logic can never silently affect another's, at the cost of some repeated routing boilerplate that is intentional, not accidental duplication.

How Server-Side Routing Works — apiMode

Every one of the eleven handlers applies the exact same routing logic once a request actually reaches the server (meaning the AI Model was set to 'api' or 'local-cli' on the client — Ollama/local-llm/web-llm never send a request here at all):

apiModeRouteModel
'cohere'Cohere Chat APIcommand-r7b-12-2024
anything else, with ANTHROPIC_API_KEY setAnthropic Messages APIclaude-sonnet-4-6
anything else, no API key configuredLocal Claude CLI (spawn('cmd', ['/c','claude','--print']) on Windows)Whatever the CLI session resolves to

Every completed or failed call — regardless of which of the three paths served it — is logged via logEvent() to the Event & Analytics Engine with engineName: 'PatentEngine', a per-handler workflowId (e.g. 'ip-valuation-analyze'), and a duration measurement, so every screen's AI usage shows up in the same tenant-wide analytics history as every other engine in TotalApp.

Where the Patent Agent Fits

This agent has no persistence layer of its own — every screen's ledger data (patent records, collision scans, licenses, valuations, and so on) lives in its own tenant-scoped JSON store under patent-rd-ops/, managed by the Patent R&D Service, not by this agent. Patent Agent's job is strictly the reasoning step: given the context a screen already assembled (via its own Stage-1 embedding search), produce a structured judgment and hand it back.

On the client, every one of the eleven corresponding functions in the Patent R&D Service (runCollisionOverlapAnalysis, executePriorArtSearch, runClaimMatrixCompare, runFtoRiskSynthesis, runLiteratureSynthesis, runPaperMetadataExtraction, runSpecAuditAnalysis, runDisclosureAssessment, runGrantComplianceAudit, runLicenseClauseAudit, runIpValuationAnalysis) reads the AI Model setting first, calls callClaude() directly for the three local engines, and only calls this server agent's matching endpoint for 'api'/'local-cli'.

A reasoning layer, not a data layer

Patent Agent never reads or writes a tenant's stored records directly — it receives exactly the context the calling screen assembled in its request body, reasons over it, and returns a result. Persisting that result back into the screen's own ledger (e.g. saving a new PatentCollisionRecord) is the calling screen's own responsibility, via the Patent R&D Service.

Frequently Asked Questions

Why does this one file contain both a jurisdiction strategy pattern and eleven unrelated AI endpoints?
The jurisdiction strategy pattern (patent specification/statutory-rule forms) was written first, mirroring Compliance Engine's and FleetDriverPermitEngine's shape. As each new screen in the Patent & R&D Operations add-on needed its own Stage-2 AI reasoning endpoint, its handler was added to this same file rather than creating a new one-off engine file per screen — keeping every server-side piece of the add-on in one place.
What happens if a user has Ollama selected but Stage 1 finds no good matches?
Each screen's Stage-1 search filters out low-similarity matches (typically below a 0.3–0.35 cosine similarity threshold) before ever reaching Stage 2. If nothing clears that bar, the calling screen sends an empty candidate/reference list to whichever agent Stage 2 uses — this agent's prompts are all written to handle an empty list gracefully (e.g. "None found." is substituted directly into the prompt) rather than erroring.
Does Patent Agent ever call Ollama itself?
No. Ollama only ever runs from the browser via ollamaEngine (embedding search) or callClaude() (Stage-2 text generation) — both entirely client-side. This server engine only implements the 'api'/'local-cli' half of the routing; it has no code path that reaches a user's local Ollama instance, since the Render server cannot reach 127.0.0.1 on a user's own machine.
How would a new jurisdiction, like a hypothetical CNIPA (China) strategy, get added to Part 1?
By adding a new class implementing PatentSchemaStrategy (e.g. CNPatentStrategy) and one new branch in resolvePatentStrategy()'s conditional chain. No screen calling fetchPatentSchema() needs to change — they already pass whatever countryCode the user's jurisdiction picker resolves to.
Is this agent specific to the Patent & R&D Operations add-on?
Today, yes — all eleven AI endpoints and both schema categories exist to serve that add-on's 16 screens specifically. Nothing about the Strategy Pattern or the apiMode routing shape is add-on-specific, though; both patterns are the same ones Compliance Engine and Matrix Agent already use elsewhere in TotalApp.