Untitled

Anonymous
Python
09/25/2025 11:32 PM
2.8 KB
21
Indexable
Never
# interview_agent_min.py
import os
import json
from typing import TypedDict, List, Optional, Any

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import tool

from langgraph.graph import StateGraph, END
from langgraph.checkpoint.memory import MemorySaver


@tool("search")
def search_tool(q: str) -> str:
    return f"[search: top result for -> {q[:128]}...]"


llm = ChatOpenAI(
    model="gpt-4o",
    temperature=0.7,           # nondeterministic on purpose
    max_tokens=512,
)

system_prompt = """You are a helpful agent. Answer succinctly."""
base_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", system_prompt),
        ("placeholder", "{history}"),
        ("human", "{input}"),
    ]
)

class AgentState(TypedDict, total=False):
    input: str
    history: List[Any]
    tool_result: Optional[str]
    route: Optional[str]

def plan_node(state: AgentState) -> AgentState:
    history = state.get("history", [])
    history.append({"role": "user", "content": state["input"]})
    prompt = base_prompt.format(history=json.dumps(history), input=state["input"])
    ai = llm.invoke(prompt)                # passes a string, not messages
    content = getattr(ai, "content", "")
    route = "search_node" if "search" in content.lower() else "finalize"
    history.append({"role": "assistant", "content": content})
    return {"history": history, "route": route}

def tool_node(state: AgentState) -> AgentState:
    user_text = state.get("input", "")
    tool_out = search_tool.invoke(user_text)   # passes raw string vs {"q": ...}
    return {"tool_result": tool_out}

def finalize_node(state: AgentState) -> AgentState:
    tool_res = state.get("tool_result")
    history = state.get("history", [])
    reply = f"Answer based on tool: {tool_res}" if tool_res else "Answer without tools."
    history.append({"role": "assistant", "content": reply})
    return {"history": history}

graph = StateGraph(AgentState)
graph.add_node("plan", plan_node)
graph.add_node("search_node", tool_node)
graph.add_node("finalize", finalize_node)
graph.set_entry_point("plan")

def router(state: AgentState) -> str:
    if "urgent" in state.get("input", "").lower():
        return "priority_queue"  # no such node
    return state.get("route", "finalize")

graph.add_conditional_edges(
    "plan",
    router,
    {"search_node": "search_node", "finalize": "finalize"},
)
graph.add_edge("search_node", "finalize")
graph.add_edge("finalize", END)

app = graph.compile(checkpointer=MemorySaver())

if __name__ == "__main__":
    print("Type 'exit' to quit.")
    while True:
        text = input("You: ").strip()
        if text.lower() == "exit":
            break
        out = app.invoke({"input": text})  # no thread_id/session key
        print("Agent:", out["history"][-1]["content"])
Editor is loading...
Leave a Comment