Spaces:
Sleeping
Sleeping
Switch backend from Claude to Gemini (free tier)
Browse filesReplace Anthropic API calls with Google Gemini 2.0 Flash.
Free tier with no credit card required. Uses async API,
proper error handling for rate limits, and clear error messages.
Co-authored-by: Cursor <cursoragent@cursor.com>
Files changed (3)
123456# Get your Anthropic key at https://console.anthropic.com/ANTHROPIC_API_KEY=sk-ant-...# Request a PatentsView key at https://patentsview.org/apis/keyrequest# (optional β falls back to Claude-simulated results without it)PATENTSVIEW_API_KEY=123456# Get a free key at https://aistudio.google.com/apikeyGEMINI_API_KEY=your-gemini-key-here# Request a PatentsView key at https://patentsview.org/apis/keyrequest# (optional β falls back to Gemini-simulated results without it)PATENTSVIEW_API_KEY=
2 unmodified lines3452 unmodified lineshttpxpython-dotenvpydantic2 unmodified lines34562 unmodified lineshttpxpython-dotenvpydanticgoogle-generativeai
12345678910111213141516171819204 unmodified lines2526272829306 unmodified lines373839404142434445464748495051525354555657585960616263646566672 unmodified lines7071727374757677787980818283845 unmodified lines909192939495964 unmodified lines10110210310410510610710810911011111211311 unmodified lines1251261271281291301311321331341351361371381391401411421438 unmodified lines1521531541551561571581591607 unmodified lines1681691701711721731741751761771781791801811821831841 unmodified line186187188189190191192193194195196197import jsonimport osimport httpxfrom dotenv import load_dotenvfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponsefrom pydantic import BaseModelload_dotenv()ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "")PATENTSVIEW_API_KEY = os.getenv("PATENTSVIEW_API_KEY", "")ANTHROPIC_MODEL = "claude-sonnet-4-20250514"PATENTSVIEW_BASE = "https://search.patentsview.org/api/v1/patent"app = FastAPI(title="Eddison Intelligence API")app.add_middleware(4 unmodified lines)class AnalyzeRequest(BaseModel):text: str6 unmodified linesprior_art: list[dict]async def call_claude(system: str, user_message: str, max_tokens: int = 1024) -> str:if not ANTHROPIC_API_KEY:raise HTTPException(503, "ANTHROPIC_API_KEY not configured")async with httpx.AsyncClient(timeout=60) as client:resp = await client.post("https://api.anthropic.com/v1/messages",headers={"x-api-key": ANTHROPIC_API_KEY,"anthropic-version": "2023-06-01","content-type": "application/json",},json={"model": ANTHROPIC_MODEL,"max_tokens": max_tokens,"system": system,"messages": [{"role": "user", "content": user_message}],},)if resp.status_code != 200:raise HTTPException(resp.status_code, f"Claude API error: {resp.text}")data = resp.json()return "".join(block.get("text", "") for block in data.get("content", []))def build_patentsview_query(keywords: list[str], kind_codes: list[str]) -> dict:keyword_clauses = []for kw in keywords:keyword_clauses.append(2 unmodified lines{"_text_any": {"patent_title": kw}},]})query = {"_and": keyword_clauses} if len(keyword_clauses) > 1 else keyword_clauses[0]if kind_codes:code_clause = {"_or": [{"patent_type": code} for code in kind_codes]}query = {"_and": [query, code_clause]}return query@app.post("/api/analyze")async def analyze_invention(req: AnalyzeRequest):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 each5 unmodified lines{"code": "A1", "label": "Published Application", "reason": "relevant because..."}]}"""raw = await call_claude(system_prompt, f"Invention: {req.text}")clean = raw.replace("```json", "").replace("```", "").strip()try:parsed = json.loads(clean)4 unmodified lines@app.post("/api/search")async def search_prior_art(req: SearchRequest):if not req.keywords:raise HTTPException(400, "At least one keyword is required")if not PATENTSVIEW_API_KEY:return await _fallback_search_with_claude(req)query = build_patentsview_query(req.keywords, req.kind_codes)headers = {"X-Api-Key": PATENTSVIEW_API_KEY, "Content-Type": "application/json"}params = {"q": query,11 unmodified linesresp = await client.post(PATENTSVIEW_BASE, headers=headers, json=params)if resp.status_code != 200:return await _fallback_search_with_claude(req)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("cpcs", [])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", ""),8 unmodified linesreturn {"results": results, "source": "patentsview", "total": data.get("total_patent_count", len(results))}async def _fallback_search_with_claude(req: SearchRequest) -> dict:if not ANTHROPIC_API_KEY:raise HTTPException(503, "No API keys configured (need PATENTSVIEW_API_KEY or ANTHROPIC_API_KEY)")system_prompt = """You are a USPTO patent database expert. Simulate a prior art search and return 5 realistic patent results.Respond ONLY with valid JSON array, no markdown:[7 unmodified lines}]"""user_msg = f"Search for prior art with keywords: {', '.join(req.keywords)}. Kind codes: {', '.join(req.kind_codes)}."raw = await call_claude(system_prompt, user_msg)clean = raw.replace("```json", "").replace("```", "").strip()try:results = json.loads(clean)except json.JSONDecodeError:raise HTTPException(502, "Failed to parse Claude search response")return {"results": results, "source": "claude_simulated", "total": len(results)}@app.post("/api/generate-claim")async def generate_claim(req: ClaimRequest):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_art1 unmodified linesystem_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_claude(system_prompt, user_msg, max_tokens=1500)return {"claims": claim_text.strip()}FRONTEND_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")@app.get("/")async def serve_app():12345678910111213141516171819202122234 unmodified lines28293031323334356 unmodified lines4243444546474849505152535455565758596061626364656667682 unmodified lines7172737475767778798081828384858687888990915 unmodified lines9798991001011021034 unmodified lines10810911011111211311411511611711811912012112211 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551568 unmodified lines1651661671681691701711721731741757 unmodified lines1831841851861871881891901911921931941951961971981992001 unmodified line202203204205206207208209210211212213214215216import osimport jsonimport httpximport google.generativeai as genaifrom dotenv import load_dotenvfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import FileResponsefrom pydantic import BaseModelload_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"if GEMINI_API_KEY:genai.configure(api_key=GEMINI_API_KEY)app = FastAPI(title="Eddison Intelligence API")app.add_middleware(4 unmodified lines)# ββ Request / Response Models ββββββββββββββββββββββββββββββββββββββββββββββββclass AnalyzeRequest(BaseModel):text: str6 unmodified linesprior_art: list[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.textexcept 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 build_patentsview_query(keywords: list[str], kind_codes: list[str]) -> dict:"""Build a PatentsView API query from keywords and kind codes."""keyword_clauses = []for kw in keywords:keyword_clauses.append(2 unmodified lines{"_text_any": {"patent_title": kw}},]})query = {"_and": keyword_clauses} if len(keyword_clauses) > 1 else keyword_clauses[0]if kind_codes:code_clause = {"_or": [{"patent_type": code} for code in kind_codes]}query = {"_and": [query, code_clause]}return query# ββ 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 each5 unmodified lines{"code": "A1", "label": "Published Application", "reason": "relevant because..."}]}"""raw = await call_gemini(system_prompt, f"Invention: {req.text}")clean = raw.replace("```json", "").replace("```", "").strip()try:parsed = json.loads(clean)4 unmodified lines@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:return await _fallback_search_with_gemini(req)query = build_patentsview_query(req.keywords, req.kind_codes)headers = {"X-Api-Key": PATENTSVIEW_API_KEY, "Content-Type": "application/json"}params = {"q": query,11 unmodified linesresp = await client.post(PATENTSVIEW_BASE, headers=headers, json=params)if resp.status_code != 200:return await _fallback_search_with_gemini(req)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("cpcs", [])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", ""),8 unmodified linesreturn {"results": results, "source": "patentsview", "total": data.get("total_patent_count", len(results))}async def _fallback_search_with_gemini(req: SearchRequest) -> dict:"""If no PatentsView key is available, use Gemini to simulate results."""if not GEMINI_API_KEY:raise HTTPException(503, "No API keys configured (need PATENTSVIEW_API_KEY or GEMINI_API_KEY)")system_prompt = """You are a USPTO patent database expert. Simulate a prior art search and return 5 realistic patent results.Respond ONLY with valid JSON array, no markdown:[7 unmodified lines}]"""user_msg = f"Search for prior art with keywords: {', '.join(req.keywords)}. Kind codes: {', '.join(req.kind_codes)}."raw = await call_gemini(system_prompt, user_msg)clean = raw.replace("```json", "").replace("```", "").strip()try:results = json.loads(clean)except json.JSONDecodeError:raise HTTPException(502, "Failed to parse Claude search response")return {"results": results, "source": "gemini_simulated", "total": len(results)}@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_art1 unmodified linesystem_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()}# ββ Serve the frontend βββββββββββββββββββββββββββββββββββββββββββββββββββββββFRONTEND_DIR = os.path.join(os.path.dirname(__file__), "..")@app.get("/")async def serve_app():
backend/.env.example+3-3
backend/requirements.txt+1
backend/server.py+54-35