intelligence / backend /server.py
exp98's picture
Claude Opus 4.6
Add 7-step USPTO search methodology integration
33233d1
Raw History Blame Contribute Delete
23.8 kB
import os
import json
import httpx
import google.generativeai as genai
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from pydantic import BaseModel
load_dotenv()
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
PATENTSVIEW_API_KEY = os.getenv("PATENTSVIEW_API_KEY", "")
PATENTSVIEW_BASE = "https://search.patentsview.org/api/v1/patent"
PATENTSVIEW_CITATIONS = "https://search.patentsview.org/api/v1/patent/us_patent_citation"
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
app = FastAPI(title="Eddison Intelligence API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ── Request / Response Models ────────────────────────────────────────────────
class AnalyzeRequest(BaseModel):
text: str
class SearchRequest(BaseModel):
keywords: list[str]
kind_codes: list[str] = []
cpc_codes: list[str] = []
sort_by: str = "date"
after: list | None = None
class ClaimRequest(BaseModel):
invention_text: str
prior_art: list[dict]
improvement_focus: str | None = None
previous_claims: str | None = None
analysis_feedback: dict | None = None
class ClaimAnalysisRequest(BaseModel):
claims: str
invention_text: str
prior_art: list[dict]
class EvaluatePatentRequest(BaseModel):
invention_text: str
patent: dict
decomposition: dict
# ── Helpers ──────────────────────────────────────────────────────────────────
async def call_gemini(system: str, user_message: str) -> str:
if not GEMINI_API_KEY:
raise HTTPException(503, "GEMINI_API_KEY not configured β€” get a free key at https://aistudio.google.com/apikey")
try:
model = genai.GenerativeModel(
model_name="gemini-2.0-flash",
system_instruction=system,
)
response = await model.generate_content_async(user_message)
return response.text
except Exception as e:
error_msg = str(e)
if "RESOURCE_EXHAUSTED" in error_msg or "429" in error_msg:
raise HTTPException(429, "Gemini free-tier quota exceeded. Try again later or check https://aistudio.google.com for limits.")
raise HTTPException(502, f"Gemini API error: {error_msg}")
def clean_json(raw: str) -> str:
"""Strip markdown fences from Gemini JSON responses."""
return raw.replace("```json", "").replace("```", "").strip()
def build_patentsview_query(keywords: list[str], kind_codes: list[str], cpc_codes: list[str]) -> dict:
"""Build a PatentsView API query from keywords, kind codes, and CPC codes.
Each keyword phrase is matched with _text_all (all words must appear)
against title OR abstract. A patent matches if ANY keyword phrase hits.
"""
keyword_clauses = []
for kw in keywords:
keyword_clauses.append({"_or": [
{"_text_all": {"patent_abstract": kw}},
{"_text_all": {"patent_title": kw}},
]})
if len(keyword_clauses) > 1:
text_clause = {"_or": keyword_clauses}
else:
text_clause = keyword_clauses[0]
clauses = [text_clause]
if kind_codes:
clauses.append({"wipo_kind": kind_codes})
if cpc_codes:
clauses.append({"cpc_at_issue.cpc_group_id": cpc_codes})
if len(clauses) > 1:
return {"_and": clauses}
return text_clause
# ── Endpoints ────────────────────────────────────────────────────────────────
@app.post("/api/analyze")
async def analyze_invention(req: AnalyzeRequest):
"""Step 1: Extract keywords and suggest kind codes from an invention description."""
system_prompt = """You are a USPTO patent expert. Given an invention description, extract:
1. 8-12 specific technical keywords/phrases for prior art search (precise, domain-specific)
2. 4-6 relevant USPTO Kind Codes with a one-line reason each
3. 3-5 relevant CPC (Cooperative Patent Classification) codes, e.g. G06F40/30, G06N20/00, with a one-line reason each
Respond ONLY with valid JSON in this exact format, no markdown:
{
"keywords": ["keyword1", "keyword2"],
"kindCodes": [
{"code": "A1", "label": "Published Application", "reason": "relevant because..."}
],
"cpcCodes": [
{"code": "G06F40/30", "reason": "relevant because..."}
]
}"""
raw = await call_gemini(system_prompt, f"Invention: {req.text}")
try:
parsed = json.loads(clean_json(raw))
except json.JSONDecodeError:
raise HTTPException(502, "Failed to parse Gemini response as JSON")
return parsed
@app.post("/api/search")
async def search_prior_art(req: SearchRequest):
"""Step 2: Search PatentsView for real prior art matching keywords."""
if not req.keywords:
raise HTTPException(400, "At least one keyword is required")
if not PATENTSVIEW_API_KEY:
raise HTTPException(503, "PatentsView API key not configured. Add PATENTSVIEW_API_KEY to your .env file β€” request one at https://patentsview.org/apis/keyrequest")
query = build_patentsview_query(req.keywords, req.kind_codes, req.cpc_codes)
fields = [
"patent_id", "patent_title", "patent_abstract", "patent_date",
"patent_type", "wipo_kind",
"assignees.assignee_organization",
"cpc_at_issue.cpc_group_id", "cpc_at_issue.cpc_group",
]
if req.sort_by == "citations":
fields.append("patent_num_times_cited_by_us_patents")
sort = (
[{"patent_num_times_cited_by_us_patents": "desc"}, {"patent_id": "asc"}]
if req.sort_by == "citations"
else [{"patent_date": "desc"}, {"patent_id": "asc"}]
)
options = {"size": 25}
if req.after:
options["after"] = req.after
headers = {"X-Api-Key": PATENTSVIEW_API_KEY, "Content-Type": "application/json"}
params = {
"q": query,
"f": fields,
"s": sort,
"o": options,
}
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.post(PATENTSVIEW_BASE, headers=headers, json=params)
if resp.status_code != 200:
reason = resp.headers.get("X-Status-Reason", resp.text[:500])
print(f"[PatentsView] HTTP {resp.status_code}: {reason}")
raise HTTPException(502, f"PatentsView API error (HTTP {resp.status_code}): {reason}")
data = resp.json()
patents = data.get("patents", [])
results = []
for p in patents:
assignee = "Unknown"
assignees = p.get("assignees", [])
if assignees and assignees[0].get("assignee_organization"):
assignee = assignees[0]["assignee_organization"]
cpcs = p.get("cpc_at_issue", [])
cpc_str = cpcs[0]["cpc_group_id"] if cpcs else ""
year = p.get("patent_date", "")[:4]
results.append({
"patentNumber": f"US{p.get('patent_id', '')}",
"title": p.get("patent_title", ""),
"assignee": assignee,
"year": int(year) if year.isdigit() else 0,
"kindCode": p.get("wipo_kind", ""),
"abstract": p.get("patent_abstract", "")[:500],
"cpc": cpc_str,
})
last = patents[-1] if patents else None
after_cursor = None
if last and len(patents) >= 25:
if req.sort_by == "citations":
after_cursor = [last.get("patent_num_times_cited_by_us_patents") or 0, last.get("patent_id")]
else:
after_cursor = [last.get("patent_date", ""), last.get("patent_id")]
return {
"results": results,
"source": "patentsview",
"total": data.get("total_hits", len(results)),
"after": after_cursor,
}
@app.get("/api/patent/{patent_id}/citations")
async def get_patent_citations(patent_id: str):
"""Fetch patents that cite this one (forward) and patents this one cites (backward)."""
if not PATENTSVIEW_API_KEY:
raise HTTPException(503, "PatentsView API key not configured")
pid = patent_id.replace("US", "").replace(",", "").replace(" ", "").strip()
if not pid or not pid.replace("0", ""):
raise HTTPException(400, "Invalid patent ID")
headers = {"X-Api-Key": PATENTSVIEW_API_KEY, "Content-Type": "application/json"}
citing = []
cited = []
async with httpx.AsyncClient(timeout=30) as client:
resp_forward = await client.post(
PATENTSVIEW_CITATIONS,
headers=headers,
json={
"q": {"citation_patent_id": pid},
"f": ["patent_id"],
"o": {"size": 10},
},
)
if resp_forward.status_code == 200:
data = resp_forward.json()
for r in data.get("us_patent_citations", []):
citing.append({"patent_id": r.get("patent_id", "")})
resp_backward = await client.post(
PATENTSVIEW_CITATIONS,
headers=headers,
json={
"q": {"patent_id": pid},
"f": ["citation_patent_id"],
"o": {"size": 10},
},
)
if resp_backward.status_code == 200:
data = resp_backward.json()
for r in data.get("us_patent_citations", []):
cited.append({"patent_id": r.get("citation_patent_id", "")})
return {"citing": citing, "cited": cited}
@app.post("/api/generate-claim")
async def generate_claim(req: ClaimRequest):
"""Step 3: Draft patent claims based on invention and approved prior art."""
prior_art_summary = "\n".join(
f"- {p.get('patentNumber', 'N/A')}: \"{p.get('title', '')}\" ({p.get('assignee', '')}, {p.get('year', '')}): {p.get('abstract', '')}"
for p in req.prior_art
)
if req.improvement_focus and req.previous_claims and req.analysis_feedback:
dimension_labels = {
"specificity": "specificity (how precise and well-defined the claim elements are)",
"protection": "protection scope (how broad the coverage is without being vulnerable to invalidation)",
"infringements": "infringement potential (how commercially relevant and broadly applicable the claims are)",
}
dim_label = dimension_labels.get(req.improvement_focus, req.improvement_focus)
fb = req.analysis_feedback
bullets = "\n".join(f"- {b}" for b in fb.get("bullets", []))
system_prompt = f"""You are a senior USPTO patent attorney. Rewrite the following patent claims to specifically improve their {dim_label}.
The previous analysis rated this dimension as: {fb.get('rating', 'Unknown')}
Assessment: {fb.get('summary', '')}
Key issues identified:
{bullets}
IMPORTANT INSTRUCTIONS:
- Rewrite ALL claims (independent and dependent) to address the identified weaknesses
- Maintain proper patent claim language (wherein, comprising, wherein said...)
- Keep the same structure: 1 independent claim + 3 dependent claims
- Preserve the claims' strengths in other dimensions while improving {req.improvement_focus}
- Number each claim. Be precise and technically accurate.
- Distinguish from the provided prior art."""
user_msg = (
f"Previous Claims to Improve:\n{req.previous_claims}\n\n"
f"Invention: {req.invention_text}\n\n"
f"Prior Art to distinguish from:\n{prior_art_summary}\n\n"
f"Rewrite the claims with improved {req.improvement_focus}."
)
else:
system_prompt = """You are a senior USPTO patent attorney. Write a professional first-draft patent claim set.
Format: 1 independent claim + 3 dependent claims. Use proper patent claim language (wherein, comprising, wherein said...).
Number each claim. Be precise and technically accurate. Distinguish from the provided prior art."""
user_msg = f"Invention: {req.invention_text}\n\nPrior Art to distinguish from:\n{prior_art_summary}\n\nDraft the claim set."
claim_text = await call_gemini(system_prompt, user_msg)
return {"claims": claim_text.strip()}
@app.post("/api/analyze-claim")
async def analyze_claim(req: ClaimAnalysisRequest):
"""Analyze generated patent claims for specificity, protection scope, and potential infringements."""
prior_art_summary = "\n".join(
f"- {p.get('patentNumber', 'N/A')}: \"{p.get('title', '')}\" ({p.get('assignee', '')}, {p.get('year', '')}): {p.get('abstract', '')}"
for p in req.prior_art
)
system_prompt = """You are a senior patent litigation attorney and patent prosecution strategist with 20+ years of experience. Analyze the given patent claims in the context of the invention description and relevant prior art.
Evaluate three dimensions:
1. SPECIFICITY β€” How specific and well-defined are the claim elements compared to the prior art? Consider whether the claims use precise technical language, clearly define boundaries, and differentiate from existing patents. Rate as "High" (claims are precisely scoped with clear technical boundaries), "Medium" (claims have reasonable specificity but some terms are broad), or "Low" (claims are vague or overlap significantly with prior art language).
2. PROTECTION SCOPE β€” How broad or narrow is the protection these claims would provide? Consider the independent claim's reach, whether dependent claims meaningfully narrow scope, and whether the claims cover the core inventive concept without being so broad as to be vulnerable to invalidation. Rate as "Broad" (wide protection covering many implementations), "Moderate" (balanced coverage of the inventive concept), or "Narrow" (limited to a very specific implementation).
3. POTENTIAL INFRINGEMENTS β€” What types of existing or future products, methods, systems, or services might fall within the scope of these claims? Consider both literal infringement and doctrine-of-equivalents scenarios. Rate the commercial relevance as "High" (large market, many potential infringers), "Medium" (niche market or moderate number of potential infringers), or "Low" (very narrow applicability).
Respond ONLY with valid JSON in this exact format, no markdown fences:
{
"specificity": {
"rating": "High or Medium or Low",
"summary": "One sentence summarizing the specificity assessment.",
"bullets": ["First key observation", "Second key observation", "Third key observation"]
},
"protection": {
"rating": "Broad or Moderate or Narrow",
"summary": "One sentence summarizing the protection scope.",
"bullets": ["First key observation", "Second key observation", "Third key observation"]
},
"infringements": {
"rating": "High or Medium or Low",
"summary": "One sentence summarizing potential infringement landscape.",
"bullets": ["First category of potentially infringing products/methods", "Second category", "Third category"]
}
}"""
user_msg = f"Patent Claims to Analyze:\n{req.claims}\n\nInvention Description:\n{req.invention_text}\n\nRelevant Prior Art:\n{prior_art_summary}\n\nProvide your structured analysis."
raw = await call_gemini(system_prompt, user_msg)
try:
parsed = json.loads(clean_json(raw))
except json.JSONDecodeError:
raise HTTPException(502, "Failed to parse Gemini claim analysis response as JSON")
for key in ("specificity", "protection", "infringements"):
if key not in parsed:
raise HTTPException(502, f"Gemini response missing '{key}' section")
section = parsed[key]
if "rating" not in section or "summary" not in section or "bullets" not in section:
raise HTTPException(502, f"Gemini response '{key}' section missing required fields")
return parsed
# ── USPTO 7-Step Methodology Endpoints ────────────────────────────────────────
SYSTEM_DECOMPOSE = """You are a USPTO patent search expert. Given an invention description, perform two tasks:
TASK 1 β€” DECOMPOSE THE INVENTION
Extract and categorize:
- core_features: 3-5 core technical features that define the invention's novelty
- supporting_features: 2-4 supporting/secondary features that enable or enhance the core
- claimed_improvements: 1-3 specific technical improvements over existing solutions
- components: hardware/software interaction components involved
TASK 2 β€” SYNONYM EXPANSION
For EACH core_feature, generate:
- technical_synonyms: 2-3 precise technical synonyms (no marketing terms)
- industry_terms: 1-2 industry-specific terminology equivalents
- broader: 1 broader/more generic term
- narrower: 1 narrower/more specific term
From the decomposition and synonyms, also extract:
- keywords: 8-12 specific search keywords/phrases combining core features and their best synonyms
- kindCodes: 4-6 relevant USPTO Kind Codes with label and one-line reason
Respond ONLY with valid JSON, no markdown fences:
{
"decomposition": {
"core_features": ["feature1", "feature2"],
"supporting_features": ["feat1", "feat2"],
"claimed_improvements": ["improvement1"],
"components": ["component1", "component2"]
},
"synonyms": {
"feature name here": {
"technical_synonyms": ["syn1", "syn2"],
"industry_terms": ["term1"],
"broader": "broader_term",
"narrower": "narrower_term"
}
},
"keywords": ["keyword1", "keyword2"],
"kindCodes": [
{"code": "A1", "label": "Published Application", "reason": "relevant because..."}
]
}"""
SYSTEM_CPC_BOOLEAN = """You are a USPTO patent classification and search strategy expert. Given an invention description and its decomposed features, perform two tasks:
TASK 1 β€” CPC CLASSIFICATION
Identify likely Cooperative Patent Classification codes:
- 2-3 primary CPC codes most directly relevant to the invention, with explanation
- 2-3 secondary/adjacent CPC codes, with explanation
Prioritize AI, data processing, memory, or hardware interaction classes when applicable.
TASK 2 β€” BOOLEAN SEARCH STRINGS
Construct three tiers of search queries:
- broad: 2 queries combining 1 core feature OR its synonyms β€” maximum recall
- intermediate: 2 queries combining 2 core features AND 1 secondary feature β€” balanced
- examiner: 2 queries using specific technical terms with classification restrictions β€” maximum precision
Each query must use Boolean operators (AND/OR), include parentheses, and combine 1-2 core features + 1 secondary feature. Avoid over-constraining.
For each query, also extract keyword_sets: arrays of keyword phrases suitable for PatentsView API full-text search.
Respond ONLY with valid JSON, no markdown fences:
{
"cpcCodes": [
{"code": "G06F40/30", "type": "primary", "reason": "relevant because..."},
{"code": "H04L67/00", "type": "secondary", "reason": "relevant because..."}
],
"booleanQueries": [
{
"level": "broad",
"label": "Broad β€” Maximum Recall",
"query": "(term1 OR term2) AND (term3)",
"keyword_sets": ["term1 term3", "term2 term3"]
}
]
}"""
SYSTEM_EVALUATE = """You are a USPTO patent examiner performing a prior art comparison. Given an invention and a prior art patent, evaluate using the standard examiner comparison framework.
For each core feature of the invention, determine:
- disclosed: Does the prior art explicitly disclose this feature? ("yes", "partial", or "no")
- equivalent: Does it describe an equivalent structure or method? ("yes", "partial", or "no")
- same_solution: Does it achieve the same technical solution? ("yes", "partial", or "no")
- problem_only: Does it merely describe the problem without the solution? ("yes" or "no")
Also provide:
- overlap_summary: One sentence on how much this prior art overlaps with the invention
- threat_level: "high" (blocks patentability), "medium" (requires claim narrowing), or "low" (distinguishable)
- distinguishing_features: list of invention features NOT found in this prior art
Respond ONLY with valid JSON, no markdown fences:
{
"feature_comparison": [
{
"feature": "the core feature text",
"disclosed": "yes",
"equivalent": "partial",
"same_solution": "no",
"problem_only": "no"
}
],
"overlap_summary": "...",
"threat_level": "medium",
"distinguishing_features": ["feature1", "feature2"]
}"""
@app.post("/api/analyze-deep")
async def analyze_deep(req: AnalyzeRequest):
"""USPTO 7-Step: Decompose invention, expand synonyms, classify CPC, and build search queries."""
# Call 1: Decomposition + Synonyms + Keywords + Kind Codes (Steps 1-2)
raw1 = await call_gemini(SYSTEM_DECOMPOSE, f"Invention: {req.text}")
try:
parsed1 = json.loads(clean_json(raw1))
except json.JSONDecodeError:
raise HTTPException(502, "Failed to parse decomposition response as JSON")
# Call 2: CPC Classification + Boolean Queries (Steps 3-4)
decomp_context = json.dumps(parsed1.get("decomposition", {}))
synonym_context = json.dumps(parsed1.get("synonyms", {}))
context_msg = (
f"Invention: {req.text}\n\n"
f"Decomposition:\n{decomp_context}\n\n"
f"Core feature synonyms:\n{synonym_context}"
)
try:
raw2 = await call_gemini(SYSTEM_CPC_BOOLEAN, context_msg)
parsed2 = json.loads(clean_json(raw2))
except json.JSONDecodeError:
# If Call 2 fails, return Call 1 results with empty CPC/boolean fields
parsed2 = {"cpcCodes": [], "booleanQueries": []}
except HTTPException:
parsed2 = {"cpcCodes": [], "booleanQueries": []}
return {
"decomposition": parsed1.get("decomposition"),
"synonyms": parsed1.get("synonyms"),
"keywords": parsed1.get("keywords", []),
"kindCodes": parsed1.get("kindCodes", []),
"cpcCodes": parsed2.get("cpcCodes", []),
"booleanQueries": parsed2.get("booleanQueries", []),
}
@app.post("/api/evaluate-patent")
async def evaluate_patent(req: EvaluatePatentRequest):
"""USPTO Step 6: Examiner-level comparison of a prior art patent against the invention."""
patent_info = (
f"Patent {req.patent.get('patentNumber', 'N/A')}: "
f"\"{req.patent.get('title', '')}\"\n"
f"Assignee: {req.patent.get('assignee', 'Unknown')}\n"
f"Abstract: {req.patent.get('abstract', '')}"
)
features = "\n".join(
f"- {f}" for f in req.decomposition.get("core_features", [])
)
user_msg = (
f"Invention: {req.invention_text}\n\n"
f"Core Features to evaluate against:\n{features}\n\n"
f"Prior Art to Evaluate:\n{patent_info}\n\n"
f"Provide your structured comparison."
)
raw = await call_gemini(SYSTEM_EVALUATE, user_msg)
try:
parsed = json.loads(clean_json(raw))
except json.JSONDecodeError:
raise HTTPException(502, "Failed to parse evaluation response as JSON")
return parsed
# ── Serve the frontend ───────────────────────────────────────────────────────
FRONTEND_DIR = os.path.join(os.path.dirname(__file__), "..")
@app.get("/")
async def serve_app():
return FileResponse(os.path.join(FRONTEND_DIR, "eddison-app.html"))
@app.get("/{filename}.html")
async def serve_html(filename: str):
path = os.path.join(FRONTEND_DIR, f"{filename}.html")
if os.path.exists(path):
return FileResponse(path)
raise HTTPException(404)