Spaces:
Runtime error
Runtime error
Update search_pipeline.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587"""Infinity GRM - Search / Execution Pipeline===========================================Standalone tool/execution layer.Responsibilities:- conversation/session management- deciding when web research is needed- DuckDuckGo search- asynchronous web retrieval- page extraction- context assembly- calling the separate reasoning engine- FastAPI APIThe reasoning model itself lives in reasoning_engine.py."""import osimport reimport asyncioimport loggingfrom contextlib import asynccontextmanagerfrom urllib.parse import urlparseimport httpximport torchimport uvicornfrom bs4 import BeautifulSoupfrom trafilatura import extractfrom ddgs import DDGSfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModelimport reasoning_enginelogging.basicConfig(level=logging.INFO,format="%(asctime)s - %(levelname)s - %(message)s",)logger = logging.getLogger("infinitygrm.pipeline")session_store = {}engine_state = {}# ---------------------------------------------------------------------# REQUEST MODEL# ---------------------------------------------------------------------class ChatRequest(BaseModel):message: strsession_id: str# ---------------------------------------------------------------------# SESSION# ---------------------------------------------------------------------def fetch_or_create_session(session_id: str) -> dict:if session_id not in session_store:session_store[session_id] = {"history": [],"last_entity": "","last_web_query": "","last_response": "","last_web_context": [],}return session_store[session_id]def update_history(session: dict, role: str, content: str):session["history"].append({"role": role,"content": content,})max_history = engine_state.get("max_history", 16)while len(session["history"]) > max_history:session["history"].pop(0)# ---------------------------------------------------------------------# FOLLOW-UP DETECTION# ---------------------------------------------------------------------def has_reference_language(query: str) -> bool:words = set(re.findall(r"\b[\w'-]+\b", query.lower()))return bool(words.intersection({"he", "him", "his","she", "her", "hers","they", "them", "their","it", "its","this", "that", "these", "those","then", "next", "after",}))def is_followup(query: str, session: dict) -> bool:if not session.get("last_response"):return Falseif len(query.split()) <= 4:return Trueif has_reference_language(query):return True# Let the reasoning engine handle semantic interpretation when# necessary rather than forcing a brittle keyword rule.return False# ---------------------------------------------------------------------# WEB SEARCH# ---------------------------------------------------------------------def isolated_ddg_search(query: str, max_results: int = 8) -> list:try:with DDGS() as ddgs:results = ddgs.text(query,max_results=max_results,)return [{"title": r.get("title", ""),"href": r.get("href", ""),"body": r.get("body", ""),}for r in resultsif r.get("href")]except Exception as exc:logger.error("DuckDuckGo search failed: %s", exc)return []async def search_web_async(query: str) -> list:return await asyncio.to_thread(isolated_ddg_search,query,)# ---------------------------------------------------------------------# WEB SCRAPING# ---------------------------------------------------------------------async def scrape_target_url(client, result: dict):url = result["href"]try:response = await client.get(url,timeout=12.0,follow_redirects=True,)if response.status_code != 200:logger.warning("HTTP %s: %s",response.status_code,url,)return Nonetext = Nonetry:text = extract(response.text)except Exception as exc:logger.warning("Trafilatura failed for %s: %s",url,exc,)if not text:try:soup = BeautifulSoup(response.text,"html.parser",)text = soup.get_text(separator=" ",strip=True,)except Exception as exc:logger.warning("BeautifulSoup failed for %s: %s",url,exc,)return Noneif not text or len(text.split()) < 20:return Nonereturn {"url": url,"title": result.get("title", ""),"domain": urlparse(url).netloc,"text": text[:7000],}except Exception as exc:logger.warning("Scraping error for %s: %s",url,exc,)return Noneasync def build_context_pipeline(query: str,max_results: int = 8,) -> tuple[str, list]:"""Search and scrape the web independently of reasoning."""search_results = await search_web_async(query)if not search_results:return "", []headers = {"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 ""(KHTML, like Gecko) ""Chrome/122.0.0.0 Safari/537.36"),"Accept": ("text/html,application/xhtml+xml,""application/xml;q=0.9,image/avif,""image/webp,*/*;q=0.8"),"Accept-Language": "en-US,en;q=0.9","Accept-Encoding": "gzip, deflate, br","Connection": "keep-alive",}try:from curl_cffi.requests import AsyncSessionexcept ImportError:AsyncSession = Noneif AsyncSession is not None:async with AsyncSession(impersonate="chrome",headers=headers,) as client:tasks = [scrape_target_url(client, result)for result in search_results[:max_results]]scraped = await asyncio.gather(*tasks,return_exceptions=False,)else:async with httpx.AsyncClient(headers=headers,follow_redirects=True,) as client:tasks = [scrape_target_url(client, result)for result in search_results[:max_results]]scraped = await asyncio.gather(*tasks,return_exceptions=False,)blocks = []sources = []for item in scraped:if not item:continueblocks.append("\n".join([f"SOURCE: {item['url']}",f"TITLE: {item['title']}",f"DOMAIN: {item['domain']}",f"CONTENT: {item['text']}",]))sources.append(item["url"])return ("\n\n---\n\n".join(blocks),list(dict.fromkeys(sources)),)# ---------------------------------------------------------------------# WEB DECISION# ---------------------------------------------------------------------SEARCH_TRIGGERS = {"latest", "today", "current", "recent","news", "update", "price", "stock","founder", "ceo", "company","documentation", "release", "version","who", "what", "when", "where","code", "python", "javascript", "html",}def obvious_web_request(query: str) -> bool:words = set(re.findall(r"\b[\w'-]+\b", query.lower()))return bool(words.intersection(SEARCH_TRIGGERS))# ---------------------------------------------------------------------# MAIN EXECUTION# ---------------------------------------------------------------------async def process_request(query: str,session: dict,):"""Separation boundary:reasoning_engine.plan()|vexecution/search|vreasoning_engine.analyze()|vreasoning_engine.final_answer()"""# ---------------------------------------------------------------# PASS 1: REASONING / PLANNING# ---------------------------------------------------------------plan = await asyncio.to_thread(reasoning_engine.plan,query,session["history"],)requires_web = bool(plan.get("requires_web")or obvious_web_request(query)or is_followup(query, session))search_queries = plan.get("search_queries") or [query]# ---------------------------------------------------------------# EXECUTION / SEARCH# ---------------------------------------------------------------evidence_blocks = []sources = []if requires_web:# Multiple searches let the reasoning engine decompose advanced# questions instead of forcing one broad query.for search_query in search_queries[:4]:search_query = str(search_query).strip()if not search_query:continuecontext, found_sources = await build_context_pipeline(search_query)if context:evidence_blocks.append(f"SEARCH QUERY: {search_query}\n{context}")sources.extend(found_sources)sources = list(dict.fromkeys(sources))session["last_web_query"] = " | ".join(str(x) for x in search_queries[:4])session["last_web_context"] = [{"user": query,"search": session["last_web_query"],}]evidence = "\n\n========\n\n".join(evidence_blocks)# ---------------------------------------------------------------# PASS 2: REASONING / EVIDENCE ANALYSIS# ---------------------------------------------------------------analysis = await asyncio.to_thread(reasoning_engine.analyze,query,plan,evidence,session["history"],)# ---------------------------------------------------------------# PASS 3: FINAL SYNTHESIS# ---------------------------------------------------------------answer = await asyncio.to_thread(reasoning_engine.final_answer,query,plan,analysis,evidence,session["history"],)# ---------------------------------------------------------------# LEARNING# ---------------------------------------------------------------# Store the solved problem as an experience. This does not mutate# model weights; it creates a retrieval corpus for future problems.await asyncio.to_thread(reasoning_engine.learn_from_result,query,plan,analysis,answer,1.0,)session["last_response"] = answersession["last_entity"] = plan.get("task", "")update_history(session,"user",query,)update_history(session,"assistant",answer,)return answer, sources# ---------------------------------------------------------------------# FASTAPI# ---------------------------------------------------------------------@asynccontextmanagerasync def lifespan(app: FastAPI):logger.info("Starting Infinity GRM execution pipeline...")await asyncio.to_thread(reasoning_engine.initialize)engine_state["max_history"] = 16yieldengine_state.clear()logger.info("Infinity GRM pipeline stopped.")app = FastAPI(title="Infinity GRM - Separated Reasoning/Search Engine",lifespan=lifespan,)app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)@app.post("/query")async def chat_endpoint(request: ChatRequest):try:session = fetch_or_create_session(request.session_id)answer, sources = await process_request(request.message,session,)return {"response": answer,"sources": sources,}except Exception as exc:logger.exception("Critical exception in Infinity GRM pipeline")raise HTTPException(status_code=500,detail=str(exc),)@app.get("/health")async def health():return {"status": "healthy","gpu_acceleration_active": torch.cuda.is_available(),"reasoning_engine": "separated","learning": "retrieval-based experience memory",}if not os.path.exists("static"):os.makedirs("static")app.mount("/static",StaticFiles(directory="static"),name="static",)@app.get("/")async def root():return {"message": "Infinity GRM separated reasoning/search engine is active.","architecture": ["reasoning_engine","search_execution","evidence_analysis","final_synthesis",],}if __name__ == "__main__":port = int(os.getenv("PORT", "7860"))uvicorn.run("search_pipeline:app",host="0.0.0.0",port=port,reload=False,)
search_pipeline.py+587