Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431445 unmodified lines150151152153154155156157158159160161162163164165166167168169170171172173174175176177178from google import genaifrom google.genai import typesimport gradio as grimport osMODEL_ID = "gemini-2.0-flash-thinking-exp"from google import genaiclient = genai.Client(api_key=os.getenv('api_key'))def llm_response(text):response = client.models.generate_content(model=MODEL_ID,contents= text)return response.textdef pvsnp(problem):classification = llm_response(f'''You are an expert in computational complexity theory, specializing in both classical complexity classes (P, NP, NP-complete, NP-hard) and modern developments (e.g., parameterized complexity, fine-grained complexity, Minimum Circuit Size Problem).Your task is to classify a given problem into one of the following categories:P: Solvable in deterministic polynomial time.NP: Verifiable in polynomial time.NP-complete: Both in NP and NP-hard.NP-hard: At least as hard as NP-complete problems, possibly outside NP.Beyond NP: Likely in PSPACE, EXPTIME, or undecidable.Other: Fits alternative complexity classes (e.g., BPP, co-NP).Problem Description:{problem}If the given problem is a NP-hard problem, decompose the NP-hard problem into polynomial-time solvable subproblems without solving them.🔹 Inputs:A formal definition and instance of the NP-hard problem (e.g., SAT, TSP, Graph Coloring).Optional: Constraints or domain knowledge.🔹 Decomposition Process:Graph Representation & Structural AnalysisConvert the problem into a graph (if applicable).Identify independent or tractable substructures.Classification of SubproblemsDetect polynomially solvable parts (e.g., tree structures, bipartite graphs).Separate them from harder components.Partitioning & TransformationBreak the problem into independent or loosely connected subproblems.Ensure each subproblem is in P or provably easier than the original.Output a structured breakdown.🔹 Outputs:A list of P-complexity subproblems.A dependency graph of their relationships in ASCII format.A complexity analysis report quantifying decomposition effectiveness.Guidelines for Classification:Problem AnalysisDetermine if the problem is a decision, optimization, or function computation problem.Identify key input/output characteristics and constraints.Complexity InsightsCheck for polynomial-time solvability via known techniques (dynamic programming, greedy methods).Assess reductions to/from well-studied problems.Advanced ConsiderationsIncorporate recent research (e.g., MCSP's implications for NP-completeness).Evaluate parameterized complexity (FPT results) and fine-grained complexity (SETH, other conjectures).Consider probabilistic or average-case complexity aspects.JustificationProvide a concise explanation for the classification, referencing key problem features and relevant research.Your Classification and Explanation:''')return classificationdef critic_analysis(classification_output):critic = llm_response(f'''"You are PolyCritic, an expert in computational complexity and problem decomposition. Your goal is to critically evaluate whether a givenNP-hard problem, when broken into P-solvable subproblems, can be efficiently recombined to yield the full solution. Here is the problem and the analysis: {classification_output}Instructions:1️⃣ Input: A decomposed NP-hard problem along with its P-solvable subproblems.2️⃣ Step 1 - Validate Subproblems:Do these subproblems fully cover the original problem?Are they correctly categorized as P?3️⃣ Step 2 - Analyze Recombination Complexity:Can the subproblem solutions be combined in polynomial time?If not, what is the bottleneck? (e.g., exponential merging, missing constraints)4️⃣ Step 3 - Provide Verdict:If recombination is efficient, explain why this suggests progress towards P = NP.If inefficient, identify where complexity remains and suggest next steps.5️⃣ Step 4 - Provide Complexity Insights:Offer insights into whether certain structural patterns predict efficient recombination.Suggest improvements in decomposition strategies.Example Analysis Format:💡 Problem: Traveling Salesperson (TSP)🔍 Subproblems: Shortest paths between city clusters (P-solvable)⚖ Recombination Complexity: Exponential growth in possible paths when merging clusters🚨 Verdict: Recombination remains NP-hard → Decomposition needs refinement👉 Your task is to apply this structured critique to any NP-hard problem and determine if it truly reduces to P.''')return critic'''iface = gr.Interface(fn=pvsnp,inputs=gr.Textbox(label="What problem would you like to classify as P or NP?"),5 unmodified lines)# Launch the appiface.launch() '''with gr.Blocks(theme=gr.themes.Ocean()) as app:gr.Markdown("# PolyProb & PolyCritic AI 🤖")gr.Markdown('''PolyProb and PolyCritic are AI Agents that help users classify a problem into categories such as P, NP, NP-complete, NP-hard whileproviding clear, concise explanations of its reasoning. As part of AI Quotient’s Millennium Math Challenge, it is the first step towards solving the P vs NP problem.''')with gr.Row():problem_input = gr.Textbox(label="Enter a computational problem")classify_button = gr.Button("Classify")classification_output = gr.Markdown(label="Classification (P or NP)")classify_button.click(pvsnp, inputs=problem_input, outputs=[classification_output])evaluate_button = gr.Button("Evaluate Recombination Complexity")recombination_output = gr.Textbox(label="Recombination Complexity")evaluate_button.click(critic_analysis, inputs=classification_output, outputs=recombination_output)#results_button = gr.Button("Show Stored Results")#results_display = gr.Textbox(label="Stored Results")#results_button.click(get_stored_results, outputs=results_display)app.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081095 unmodified lines115116117118import gradio as grimport osos.environ["OPENAI_API_KEY"] = os.getenv('api_key')import mathimport typesimport uuidfrom langchain.chat_models import init_chat_modelfrom langchain.embeddings import init_embeddingsfrom langgraph.store.memory import InMemoryStorefrom langgraph_bigtool import create_agentfrom langgraph_bigtool.utils import (convert_positional_only_function_to_tool)# Collect functions from `math` built-inall_tools = []for function_name in dir(math):function = getattr(math, function_name)if not isinstance(function, types.BuiltinFunctionType):continue# This is an idiosyncrasy of the `math` libraryif tool := convert_positional_only_function_to_tool(function):all_tools.append(tool)# Create registry of tools. This is a dict mapping# identifiers to tool instances.tool_registry = {str(uuid.uuid4()): toolfor tool in all_tools}# Index tool names and descriptions in the LangGraph# Store. Here we use a simple in-memory store.embeddings = init_embeddings("openai:text-embedding-3-small")store = InMemoryStore(index={"embed": embeddings,"dims": 1536,"fields": ["description"],})for tool_id, tool in tool_registry.items():store.put(("tools",),tool_id,{"description": f"{tool.name}: {tool.description}",},)# Initialize agentllm = init_chat_model("openai:gpt-4o-mini")builder = create_agent(llm, tool_registry)agent = builder.compile(store=store)from langchain_core.tools import Toolimport sympyfrom sympy import symbolsdef make_sympy_tool(func, name, description):def _tool(expr: str) -> str:local_symbols = symbols("x y z a b c n")parsed_expr = sympy.sympify(expr, locals={s.name: s for s in local_symbols})result = func(parsed_expr)return str(result)return Tool.from_function(name=name,description=description,func=_tool)from sympy import simplify, expand, factorsympy_tools = [make_sympy_tool(simplify, "simplify", "Simplifies a symbolic expression"),make_sympy_tool(expand, "expand", "Expands a symbolic expression"),make_sympy_tool(factor, "factor", "Factors a symbolic expression"),]for tool in sympy_tools:tool_id = str(uuid.uuid4())tool_registry[tool_id] = toolstore.put(("tools",),tool_id,{"description": f"{tool.name}: {tool.description}"},)builder = create_agent(llm, tool_registry)agent = builder.compile(store=store)iface = gr.Interface(fn=pvsnp,inputs=gr.Textbox(label="What problem would you like to classify as P or NP?"),5 unmodified lines)# Launch the appiface.launch()
app.py+99-159