Spaces:
Build error
Build error
Commit ·
27d6c4f
1
Parent(s): f79d6c4
+ added a coding agent
Browse filesFiles changed (6)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215"""LangGraph Code‑Interpreter Agent================================A minimal, production‑ready example that wires a Python code‑execution tool intoa LangGraph workflow with an *LLM → plan → execute → reflect* loop.
Key changes (2025‑06‑20)-----------------------* **Whitelisted built‑ins** for safer `python_exec`.* **Timeout guard** – aborts if the workflow exceeds a wall‑clock limit (default 30 s, configurable via `LANGGRAPH_TIMEOUT_SEC`).* **Dataclass state** – replaced untyped `Dict[str, Any]` with a typed `@dataclass AgentState` for clearer intent and static‑analysis friendliness.
Dependencies------------```bashpip install langgraph langchain openai tiktoken tenacity```
Set the environment variable `OPENAI_API_KEY` before running.Optionally, you can swap `python_exec` with a sandboxed runner such as `e2b` or`codeinterpreter-api`."""from __future__ import annotations
import contextlibimport ioimport osimport textwrapimport timeimport tracebackfrom dataclasses import dataclass, replacefrom typing import Any, Optionalimport re # For stripping markdown fences
from langchain_openai import ChatOpenAIfrom langchain_core.messages import AIMessage, HumanMessage, SystemMessagefrom langchain_core.tools import toolfrom langgraph.graph import END, StateGraph
################################################################################ 0. Global config###############################################################################
MODEL_NAME = os.getenv("LANGGRAPH_MODEL", "gpt-4o-mini")TIMEOUT_SEC = int(os.getenv("LANGGRAPH_TIMEOUT_SEC", "30"))
################################################################################ 1. Code‑execution tool (whitelisted built‑ins)###############################################################################
ALLOWED_BUILTINS: dict[str, Any] = { "print": print, "range": range, "len": len, "abs": abs, "sum": sum, "min": min, "max": max,}
@tooldef python_exec(code: str) -> str: """Execute **Python** inside a restricted namespace and capture STDOUT.""" code = textwrap.dedent(code) exec_globals = {"__builtins__": ALLOWED_BUILTINS} local_ns: dict[str, Any] = {} stdout = io.StringIO() try: with contextlib.redirect_stdout(stdout): exec(code, exec_globals, local_ns) # noqa: S102 return stdout.getvalue() or "Code executed successfully, no output." except Exception: return "ERROR:\n" + traceback.format_exc()
################################################################################ 2. LLM backend###############################################################################
llm = ChatOpenAI(model_name=MODEL_NAME, temperature=0.0)
################################################################################ 3. Dataclass‑based state & LangGraph###############################################################################
@dataclassclass AgentState: """Typed state object carried through the graph."""
input: str start_time: float code: Optional[str] = None exec_result: Optional[str] = None tries: int = 0 done: bool = False
graph = StateGraph(AgentState)
# 3‑A Plan node – write code
def plan_node(state: AgentState) -> AgentState: prompt = [ SystemMessage( content=( "You are an expert Python developer. Given a user request, " "write self‑contained Python code that prints ONLY the final " "answer via `print()`. Always avoid network calls." ) ), HumanMessage(content=state.input), ] code_block = _extract_code(llm(prompt).content) return replace(state, code=code_block)
# 3‑B Execute node – run code
def exec_node(state: AgentState) -> AgentState: output = python_exec(state.code or "") return replace(state, exec_result=output)
# 3‑C Reflect node – repair on error (max 2 retries, with timeout guard)
def reflect_node(state: AgentState) -> AgentState: if time.time() - state.start_time > TIMEOUT_SEC: return replace( state, done=True, exec_result=f"ERROR:\nTimeout: exceeded {TIMEOUT_SEC}s budget", )
tries = state.tries + 1 if tries >= 2: return replace(state, done=True, tries=tries)
prompt = [ SystemMessage( content=( "You are an expert Python debugger. Your job is to fix the " "given code so it runs without errors and still answers the " "original question. Return ONLY the corrected code." ) ), HumanMessage(content="Code:\n" + (state.code or "")), AIMessage(content="Error:\n" + (state.exec_result or "")), ] fixed_code = _extract_code(llm(prompt).content) return replace(state, code=fixed_code, tries=tries)
# 3‑D Wire nodes & conditional edges
graph.add_node("plan", plan_node)
graph.add_node("execute", exec_node)
graph.add_node("reflect", reflect_node)
graph.set_entry_point("plan")
graph.add_edge("plan", "execute")
def needs_fix(state: AgentState) -> bool: return (state.exec_result or "").startswith("ERROR")
graph.add_conditional_edges( "execute", needs_fix, {True: "reflect", False: END},)
# After reflection, either run the fixed code again or terminate if `done`.
def should_continue(state: AgentState) -> bool: """Return True to stop, False to continue executing.""" return state.done
graph.add_conditional_edges( "reflect", should_continue, {True: END, False: "execute"},)
agent = graph.compile()
################################################################################ 4. Helper function & CLI entry‑point###############################################################################
def run_agent(query: str) -> str: """Run the agent end‑to‑end and return the printed answer (or error).""" init_state = AgentState(input=query, start_time=time.time()) final_state = agent.invoke(init_state) # The compiled graph returns an AddableValuesDict (dict-like), # so we access keys rather than attributes. return final_state.get("exec_result", "No result")
# ---------------------------------------------------------------------------# Helper to strip Markdown code fences (```python ... ```)# ---------------------------------------------------------------------------
def _extract_code(text: str) -> str: """Return the first code block in *text* or the raw text if none found.""" match = re.search(r"```(?:python|py)?\s*(.*?)```", text, flags=re.S | re.I) return match.group(1).strip() if match else text.strip()
if __name__ == "__main__": import sys
question = ( sys.argv[1] if len(sys.argv) > 1 else "What is the 10th Fibonacci number?" )
print(run_agent(question))15 unmodified lines1617181920212223242514 unmodified lines4041423940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899043444556 unmodified lines10210310410510610710810911011111211311411511611711832 unmodified lines15115215319119219319419515415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021127 unmodified lines23924024123624224324473 unmodified lines31831932032132232332432532632732832933033133233331733433533633733815 unmodified linesfrom langchain.tools.retriever import create_retriever_toolfrom supabase.client import Client, create_clientimport requests # NEW: for HTTP requests to scoring APIfrom dataclasses import dataclassimport time # For timestamp in code agent wrapperfrom code_agent import run_agent # Compiled code-interpreter graph helperfrom langchain_core.messages import AIMessage
from langfuse.langchain import CallbackHandler
14 unmodified lines# Base URL of the scoring API (duplicated here to avoid circular import with basic_agent)DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@tooldef multiply(a: int, b: int) -> int: """Multiply two numbers.
Args: a: first int b: second int """ return a * b
@tooldef add(a: int, b: int) -> int: """Add two numbers. Args: a: first int b: second int """ return a + b
@tooldef subtract(a: int, b: int) -> int: """Subtract two numbers. Args: a: first int b: second int """ return a - b
@tooldef divide(a: int, b: int) -> int: """Divide two numbers. Args: a: first int b: second int """ if b == 0: raise ValueError("Cannot divide by zero.") return a / b
@tooldef modulus(a: int, b: int) -> int: """Get the modulus of two numbers. Args: a: first int b: second int """ return a % b
@tooldef wiki_search(input: str) -> str: """Search Wikipedia for a query and return maximum 2 results.56 unmodified lines print(f"Error in arvix_search: {e}") return {"arvix_results": f"Error searching Arxiv: {e}"}
@tooldef run_python(input: str) -> str: """Execute Python code in a restricted sandbox (code-interpreter).
Pass **any** coding or file-manipulation task here and the agent will compute the answer by running Python. The entire standard library is NOT available; heavy networking is disabled. Suitable for: math, data-frames, small file parsing, algorithmic questions. """ return run_agent(input)
# load the system prompt from the filewith open("system_prompt.txt", "r", encoding="utf-8") as f: system_prompt = f.read()32 unmodified lines create_retriever_tool = None
tools = [ multiply, add, subtract, divide, modulus, wiki_search, web_search, arvix_search, run_python,]if create_retriever_tool: tools.append(create_retriever_tool)
# ---------------------------------------------------------------------------# Code-interpreter integration helpers# ---------------------------------------------------------------------------
from code_agent import run_agent # Executes the compiled code-interpreter graph
def _needs_code(state: dict) -> bool: # type: ignore[override] """Heuristic: does *state* look like a coding request?""" messages = state.get("messages", []) if not messages: return False last_content = messages[-1].content.lower() triggers = [ "```python", "write python", "run this code", "file manipulation", "csv", "pandas", "json", "plot", "fibonacci", ] return any(t in last_content for t in triggers)
def _code_exec_wrapper(state: dict): # type: ignore[override] """Delegate the user query to the sandboxed Python interpreter.""" # Get the last human message's content (fallback to empty string) human_msgs = [m.content for m in state.get("messages", []) if m.type == "human"] query = "\n\n".join(human_msgs)
# Execute code-interpreter with full context (question + attachments) result = run_agent(query) # Persist the raw stdout so we can convert it to an AI message downstream return {"code_result": result}
def _code_to_message(state: dict): # type: ignore[override] """Turn the interpreter's stdout into an AIMessage so the LLM can see it.""" from langchain_core.messages import AIMessage # local import to avoid cycles
if not state.get("code_result"): return {} return {"messages": [AIMessage(content=state["code_result"])]}
# Build graph functiondef build_graph(provider: str = "groq"): """Build the graph"""27 unmodified lines return {"messages": [result]} except Exception as e: print(f"Error in assistant node: {e}") from langchain_core.messages import AIMessage error_msg = AIMessage(content=f"I encountered an error: {e}") return {"messages": [error_msg]} 73 unmodified lines builder.add_node("retriever", retriever) builder.add_node("assistant", assistant) builder.add_node("tools", ToolNode(tools)) builder.add_node("code_exec", _code_exec_wrapper) builder.add_node("code_to_message", _code_to_message)
builder.add_edge(START, "retriever") # Conditional branch: decide whether to run code interpreter builder.add_conditional_edges( "retriever", _needs_code, {True: "code_exec", False: "assistant"}, )
# Flow after code execution: inject result then resume chat builder.add_edge("code_exec", "code_to_message") builder.add_edge("retriever", "assistant") builder.add_edge("code_to_message", "assistant")
builder.add_conditional_edges( "assistant", tools_condition,15 unmodified lines1617181920212215 unmodified lines "langchain-google-genai>=2.1.5", "langchain-groq>=0.3.2", "langchain-huggingface>=0.3.0", "langchain-openai>=0.3.24", "langfuse>=3.0.0", "langgraph>=0.4.8", "llama-index>=0.12.40",500 unmodified lines50150250350450550650722 unmodified lines530531532533534535536744 unmodified lines12811282128312841285128612871288128912901291129212931294129512961297129812991300733 unmodified lines203420352036202120372038203920405 unmodified lines20462047204820332049205020352051205220532054500 unmodified lines { name = "langchain-google-genai" }, { name = "langchain-groq" }, { name = "langchain-huggingface" }, { name = "langchain-openai" }, { name = "langfuse" }, { name = "langgraph" }, { name = "llama-index" },22 unmodified lines { name = "langchain-google-genai", specifier = ">=2.1.5" }, { name = "langchain-groq", specifier = ">=0.3.2" }, { name = "langchain-huggingface", specifier = ">=0.3.0" }, { name = "langchain-openai", specifier = ">=0.3.24" }, { name = "langfuse", specifier = ">=3.0.0" }, { name = "langgraph", specifier = ">=0.4.8" }, { name = "llama-index", specifier = ">=0.12.40" },744 unmodified lines { url = "https://files.pythonhosted.org/packages/c1/da/7446c2eeacd420cb975ceb49c6feca7be40cf8ed3686a128ca78410c148f/langchain_huggingface-0.3.0-py3-none-any.whl", hash = "sha256:aab85d57e649c805d2f2a9f8d72d87b5d12c45dd4831309ac9c37753ddb237ed", size = 27359 },]
[[package]]name = "langchain-openai"version = "0.3.24"source = { registry = "https://pypi.org/simple" }dependencies = [ { name = "langchain-core" }, { name = "openai" }, { name = "tiktoken" },]sdist = { url = "https://files.pythonhosted.org/packages/da/e1/7be9384c5cb6fd6d0466ac6e781e44c3d80081c624faa7a9d2f8bf3a59ba/langchain_openai-0.3.24.tar.gz", hash = "sha256:cec1ab4ce7a8680af1eb11427b4384d2ceb46e9b20ff3f7beb0b0d83cab61a97", size = 687773 }wheels = [ { url = "https://files.pythonhosted.org/packages/fc/9b/b8f86d78dbc651decd684ab938a1340e1ad3ba1dbcef805e12db65dee0ba/langchain_openai-0.3.24-py3-none-any.whl", hash = "sha256:3db7bb2964f86636276a8f4bbed4514daf13865b80896e547ff7ea13ce98e593", size = 68950 },]
[[package]]name = "langchain-text-splitters"version = "0.3.8"733 unmodified lines
[[package]]name = "openai"version = "1.84.0"version = "1.88.0"source = { registry = "https://pypi.org/simple" }dependencies = [ { name = "anyio" },5 unmodified lines { name = "tqdm" }, { name = "typing-extensions" },]sdist = { url = "https://files.pythonhosted.org/packages/91/a3/128caf24e116f48fad3e4d5122cdf84db06c5127911849d51663c66158c8/openai-1.84.0.tar.gz", hash = "sha256:4caa43bdab262cc75680ce1a2322cfc01626204074f7e8d9939ab372acf61698", size = 467066 }sdist = { url = "https://files.pythonhosted.org/packages/5a/ea/bbeef604d1fe0f7e9111745bb8a81362973a95713b28855beb9a9832ab12/openai-1.88.0.tar.gz", hash = "sha256:122d35e42998255cf1fc84560f6ee49a844e65c054cd05d3e42fda506b832bb1", size = 470963 }wheels = [ { url = "https://files.pythonhosted.org/packages/2a/10/f245db006a860dbc1f2e2c8382e0a1762c7753e7971ba43a1dc3f3ec1404/openai-1.84.0-py3-none-any.whl", hash = "sha256:7ec4436c3c933d68dc0f5a0cef0cb3dbc0864a54d62bddaf2ed5f3d521844711", size = 725512 }, { url = "https://files.pythonhosted.org/packages/f4/03/ef68d77a38dd383cbed7fc898857d394d5a8b0520a35f054e7fe05dc3ac1/openai-1.88.0-py3-none-any.whl", hash = "sha256:7edd7826b3b83f5846562a6f310f040c79576278bf8e3687b30ba05bb5dff978", size = 734293 },]
[[package]]__pycache__/code_agent.cpython-313.pycAdded
__pycache__/langraph_agent.cpython-313.pyc
code_agent.pyAdded+215
langraph_agent.py+77-59
pyproject.toml+1
uv.lock+19-3