feat: added rich
This commit is contained in:
BIN
core/__pycache__/config.cpython-312.pyc
Normal file
BIN
core/__pycache__/config.cpython-312.pyc
Normal file
Binary file not shown.
Binary file not shown.
BIN
core/agent/__pycache__/todo_prompt.cpython-312.pyc
Normal file
BIN
core/agent/__pycache__/todo_prompt.cpython-312.pyc
Normal file
Binary file not shown.
@@ -1,32 +1,473 @@
|
|||||||
from langchain_core.messages import HumanMessage, AIMessage
|
from langchain_core.messages import HumanMessage, AIMessage, ToolMessage
|
||||||
from langgraph.graph import StateGraph, MessagesState, START, END
|
from langgraph.graph import StateGraph, START, END
|
||||||
from ..backend import llm
|
from langgraph.graph.message import add_messages
|
||||||
|
from typing import Annotated, Literal
|
||||||
|
from typing_extensions import TypedDict
|
||||||
|
from langgraph.checkpoint.memory import MemorySaver
|
||||||
|
from rich.console import Console
|
||||||
|
from rich.panel import Panel
|
||||||
|
from rich.markdown import Markdown
|
||||||
|
|
||||||
def call_llama_server(state: MessagesState):
|
from ..backend import llm
|
||||||
"""Call the local llama-server with the configured model using LangChain."""
|
from .todo_prompt import todo_prompt_template, review_todo_prompt_template
|
||||||
# Get the last user message
|
from core.tools.file_operations import (
|
||||||
|
read_file, write_file, replace_in_file, delete_in_file,
|
||||||
|
delete_file, copy_file, move_file, create_directory,
|
||||||
|
delete_directory, list_directory, get_file_info,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Keep an ordered list and map of tools for binding and dispatching
|
||||||
|
AVAILABLE_TOOLS_LIST = [
|
||||||
|
read_file, write_file, replace_in_file, delete_in_file,
|
||||||
|
delete_file, copy_file, move_file, create_directory,
|
||||||
|
delete_directory, list_directory, get_file_info,
|
||||||
|
]
|
||||||
|
|
||||||
|
TOOLS_MAP = {tool.name: tool for tool in AVAILABLE_TOOLS_LIST}
|
||||||
|
|
||||||
|
console = Console()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# State
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class AgentState(TypedDict):
|
||||||
|
messages: Annotated[list, add_messages]
|
||||||
|
todo_list: list[str]
|
||||||
|
task: str
|
||||||
|
current_step: int
|
||||||
|
done: bool
|
||||||
|
awaiting_human_feedback: bool
|
||||||
|
# "plan_task" when plan_task triggered the pause; "" otherwise.
|
||||||
|
feedback_source: str
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Helpers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _parse_todo_list(raw: str) -> list[str]:
|
||||||
|
"""
|
||||||
|
Parse a newline- or numbered-list LLM response into a clean list of steps.
|
||||||
|
Falls back to a single-item list on failure.
|
||||||
|
"""
|
||||||
|
lines = []
|
||||||
|
for line in raw.splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Skip obvious markdown headers, dividers, and conversational filler
|
||||||
|
if line.startswith("```") or line.startswith("===") or line.startswith("---") or line.lower().replace("*", "") in ["to-do list", "execution"]:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Strip bullet prefixes: "- " / "* "
|
||||||
|
for prefix in ("-", "*"):
|
||||||
|
if line.startswith(prefix):
|
||||||
|
line = line[len(prefix):].strip()
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
# Strip numeric prefixes: "1." / "2)"
|
||||||
|
parts = line.split(".", 1)
|
||||||
|
if len(parts) == 2 and parts[0].strip().isdigit():
|
||||||
|
line = parts[1].strip()
|
||||||
|
else:
|
||||||
|
parts = line.split(")", 1)
|
||||||
|
if len(parts) == 2 and parts[0].strip().isdigit():
|
||||||
|
line = parts[1].strip()
|
||||||
|
if line:
|
||||||
|
lines.append(line)
|
||||||
|
return lines if lines else [raw.strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def _build_history_text(messages: list) -> str:
|
||||||
|
"""Render the message list as a readable conversation string."""
|
||||||
|
return "\n".join(
|
||||||
|
f"{'User' if isinstance(m, HumanMessage) else 'Assistant'}: {m.content}"
|
||||||
|
for m in messages
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Nodes
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def plan_task(state: AgentState) -> dict:
|
||||||
|
"""
|
||||||
|
Ask the LLM to produce (or refine) a to-do list for the user's task.
|
||||||
|
|
||||||
|
The full conversation history is included so that any prior human feedback
|
||||||
|
rounds are visible. If the LLM still needs clarification it responds with:
|
||||||
|
|
||||||
|
NEEDS_FEEDBACK: <question>
|
||||||
|
<optional partial todo list>
|
||||||
|
|
||||||
|
which routes the graph to get_human_feedback -> back to plan_task.
|
||||||
|
Only once the LLM is satisfied does the graph proceed to review_plan.
|
||||||
|
"""
|
||||||
messages = state["messages"]
|
messages = state["messages"]
|
||||||
if not messages:
|
if not messages:
|
||||||
return {"messages": [AIMessage(content="No message provided")]}
|
return {
|
||||||
|
"todo_list": ["No task provided"],
|
||||||
|
"task": "",
|
||||||
|
"current_step": 0,
|
||||||
|
"done": True,
|
||||||
|
"awaiting_human_feedback": False,
|
||||||
|
"feedback_source": "",
|
||||||
|
}
|
||||||
|
|
||||||
# Get the content of the last message
|
history_text = _build_history_text(messages)
|
||||||
last_message = messages[-1]
|
prompt = (
|
||||||
user_content = last_message.content
|
f"{todo_prompt_template}\n\n"
|
||||||
|
f"Conversation so far:\n{history_text}\n\n"
|
||||||
|
"If anything is unclear and you need human clarification before you can "
|
||||||
|
"produce a reliable plan, respond with exactly:\n"
|
||||||
|
" NEEDS_FEEDBACK: <your question>\n"
|
||||||
|
"followed by your best-effort partial todo list (one step per line).\n"
|
||||||
|
"Otherwise just return the final todo list, one step per line. "
|
||||||
|
"IMPORTANT: Output ONLY the list items. Do not include markdown headers, bold text, or conversational filler."
|
||||||
|
)
|
||||||
|
response = llm.invoke(prompt)
|
||||||
|
raw = response.content if hasattr(response, "content") else str(response)
|
||||||
|
|
||||||
# Invoke the LLM with the user message
|
awaiting = False
|
||||||
response = llm.invoke(user_content)
|
feedback_question = ""
|
||||||
|
|
||||||
return {"messages": [response]}
|
if raw.lstrip().startswith("NEEDS_FEEDBACK:"):
|
||||||
|
first_line, _, rest = raw.partition("\n")
|
||||||
|
feedback_question = first_line.replace("NEEDS_FEEDBACK:", "").strip()
|
||||||
|
awaiting = True
|
||||||
|
raw = rest
|
||||||
|
|
||||||
|
todo_list = _parse_todo_list(raw) if raw.strip() else state.get("todo_list", [])
|
||||||
|
# Preserve the original user task from the first human message.
|
||||||
|
task = next((m.content for m in messages if isinstance(m, HumanMessage)), "")
|
||||||
|
|
||||||
|
todo_str = "\n".join(f"{i+1}. {step}" for i, step in enumerate(todo_list))
|
||||||
|
console.print(Panel(todo_str, title="[bold cyan]📝 Initial To-Do List[/bold cyan]", border_style="cyan"))
|
||||||
|
|
||||||
|
if awaiting:
|
||||||
|
console.print(f"[bold red]❓ Needs clarification:[/bold red] {feedback_question}")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"todo_list": todo_list,
|
||||||
|
"task": task,
|
||||||
|
"current_step": 0,
|
||||||
|
"done": False,
|
||||||
|
"awaiting_human_feedback": awaiting,
|
||||||
|
"feedback_source": "plan_task" if awaiting else "",
|
||||||
|
**(
|
||||||
|
{
|
||||||
|
"messages": [
|
||||||
|
AIMessage(
|
||||||
|
content=f"I need some clarification before I can plan: {feedback_question}"
|
||||||
|
)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
if awaiting
|
||||||
|
else {}
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def review_plan(state: AgentState) -> dict:
|
||||||
|
"""
|
||||||
|
Enrich and finalise the plan using the todo list, task description, and
|
||||||
|
any human feedback collected during the plan_task loop.
|
||||||
|
This node does NOT trigger another feedback loop — it goes straight to
|
||||||
|
execute_task once done.
|
||||||
|
"""
|
||||||
|
todo_list = state["todo_list"]
|
||||||
|
task = state["task"]
|
||||||
|
history_text = _build_history_text(state["messages"])
|
||||||
|
|
||||||
|
prompt = (
|
||||||
|
f"{review_todo_prompt_template}\n\n"
|
||||||
|
f"Original task: {task}\n\n"
|
||||||
|
f"Conversation history (including any human feedback):\n{history_text}\n\n"
|
||||||
|
f"Current to-do list:\n"
|
||||||
|
+ "\n".join(f"{i+1}. {step}" for i, step in enumerate(todo_list))
|
||||||
|
+ "\n\nReview and improve the todo list based on all context above. "
|
||||||
|
"Return ONLY the final todo list, one step per line. Do not include headers like '**To-Do List**'."
|
||||||
|
)
|
||||||
|
response = llm.invoke(prompt)
|
||||||
|
raw = response.content if hasattr(response, "content") else str(response)
|
||||||
|
updated_todo = _parse_todo_list(raw) if raw.strip() else todo_list
|
||||||
|
|
||||||
|
todo_str = "\n".join(f"{i+1}. {step}" for i, step in enumerate(updated_todo))
|
||||||
|
console.print(Panel(todo_str, title="[bold green]📋 Reviewed To-Do List[/bold green]", border_style="green"))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"todo_list": updated_todo,
|
||||||
|
"awaiting_human_feedback": False,
|
||||||
|
"feedback_source": "",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_human_feedback(state: AgentState) -> dict:
|
||||||
|
"""
|
||||||
|
Interrupt node: LangGraph pauses here so the user can reply.
|
||||||
|
When the graph is resumed the new HumanMessage is already in state["messages"]
|
||||||
|
via the interrupt mechanism — we just clear the flag and let routing decide
|
||||||
|
where to go next (back to plan_task).
|
||||||
|
"""
|
||||||
|
messages = state["messages"]
|
||||||
|
last = messages[-1] if messages else None
|
||||||
|
if last and isinstance(last, HumanMessage):
|
||||||
|
console.print(f"[bold green]👤 Human feedback received:[/bold green] {last.content}")
|
||||||
|
return {"awaiting_human_feedback": False}
|
||||||
|
|
||||||
|
|
||||||
|
def execute_task(state: AgentState) -> dict:
|
||||||
|
"""Execute the current todo step."""
|
||||||
|
current_step = state["current_step"]
|
||||||
|
todo_list = state["todo_list"]
|
||||||
|
|
||||||
|
if current_step >= len(todo_list):
|
||||||
|
return {"done": True}
|
||||||
|
|
||||||
|
step_description = todo_list[current_step]
|
||||||
|
console.print(f"\n[bold magenta]⚙️ Executing Step {current_step + 1}/{len(todo_list)}:[/bold magenta] {step_description}")
|
||||||
|
|
||||||
|
# Bind tools to the LLM so it can emit structured tool calls instead of plain text
|
||||||
|
llm_with_tools = llm.bind_tools(AVAILABLE_TOOLS_LIST)
|
||||||
|
|
||||||
|
# Pass the entire conversation history so the LLM has context of previous tool outputs!
|
||||||
|
messages = state["messages"] + [
|
||||||
|
HumanMessage(
|
||||||
|
content=(
|
||||||
|
f"You are executing step {current_step + 1} of a task plan.\n"
|
||||||
|
f"Step: {step_description}\n\n"
|
||||||
|
f"Full task context: {state['task']}\n\n"
|
||||||
|
"Please perform this step. If a file-operation tool is needed, "
|
||||||
|
"call the appropriate tool with the required arguments."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
response = llm_with_tools.invoke(messages)
|
||||||
|
|
||||||
|
raw = response.content if hasattr(response, "content") else ""
|
||||||
|
if raw.strip():
|
||||||
|
console.print(Panel(Markdown(raw.strip()), title="[blue]🤖 Agent Thoughts[/blue]", border_style="blue"))
|
||||||
|
|
||||||
|
if hasattr(response, "tool_calls") and response.tool_calls:
|
||||||
|
tools_requested = ", ".join([tc["name"] for tc in response.tool_calls])
|
||||||
|
console.print(f"[bold yellow]🛠️ Requested Tools:[/bold yellow] {tools_requested}")
|
||||||
|
|
||||||
|
if hasattr(response, "invalid_tool_calls") and response.invalid_tool_calls:
|
||||||
|
invalid_tools = ", ".join([tc.get("name", "unknown") for tc in response.invalid_tool_calls])
|
||||||
|
console.print(f"[bold red]⚠️ Invalid Tool Calls Generated:[/bold red] {invalid_tools}")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"current_step": current_step + 1,
|
||||||
|
"messages": [response],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def call_tools(state: AgentState) -> dict:
|
||||||
|
"""
|
||||||
|
Tool-dispatch node. Extend with real tool-calling logic:
|
||||||
|
parse ToolCall requests from state["messages"] and invoke the
|
||||||
|
appropriate function from core.tools.file_operation.
|
||||||
|
"""
|
||||||
|
current_step = state["current_step"]
|
||||||
|
todo_list = state["todo_list"]
|
||||||
|
|
||||||
|
if current_step >= len(todo_list):
|
||||||
|
return {"done": True}
|
||||||
|
|
||||||
|
last_message = state["messages"][-1]
|
||||||
|
|
||||||
|
valid_calls = getattr(last_message, "tool_calls", [])
|
||||||
|
invalid_calls = getattr(last_message, "invalid_tool_calls", [])
|
||||||
|
|
||||||
|
if not valid_calls and not invalid_calls:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
tool_messages = []
|
||||||
|
for tool_call in valid_calls:
|
||||||
|
tool_name = tool_call["name"]
|
||||||
|
tool_args = tool_call["args"]
|
||||||
|
console.print(f" [cyan]▶ Running[/cyan] [bold]{tool_name}[/bold] [dim]with args: {tool_args}[/dim]")
|
||||||
|
|
||||||
|
tool = TOOLS_MAP.get(tool_name)
|
||||||
|
if tool:
|
||||||
|
try:
|
||||||
|
result = tool.invoke(tool_args)
|
||||||
|
except Exception as e:
|
||||||
|
result = f"Error: {str(e)}"
|
||||||
|
else:
|
||||||
|
result = f"Error: Tool '{tool_name}' not found."
|
||||||
|
|
||||||
|
tool_messages.append(
|
||||||
|
ToolMessage(content=str(result), name=tool_name, tool_call_id=tool_call["id"])
|
||||||
|
)
|
||||||
|
|
||||||
|
# Handle malformed tool calls (common with local OSS models)
|
||||||
|
for invalid_call in invalid_calls:
|
||||||
|
tool_name = invalid_call.get("name", "unknown")
|
||||||
|
error_msg = f"Error: Invalid tool call arguments. Please format your tool arguments exactly as required. Details: {invalid_call.get('error', 'unknown error')}"
|
||||||
|
console.print(f" [red]✖ Failed to run[/red] [bold]{tool_name}[/bold]: {error_msg}")
|
||||||
|
tool_messages.append(
|
||||||
|
ToolMessage(content=error_msg, name=tool_name, tool_call_id=invalid_call.get("id", "unknown"))
|
||||||
|
)
|
||||||
|
|
||||||
|
return {"messages": tool_messages}
|
||||||
|
|
||||||
|
|
||||||
|
def mark_task_done(state: AgentState) -> dict:
|
||||||
|
"""
|
||||||
|
Summarise the just-completed todo step.
|
||||||
|
Sets done=True only when all steps are exhausted so the router knows
|
||||||
|
whether to loop back to execute_task or exit to END.
|
||||||
|
"""
|
||||||
|
todo_list = state["todo_list"]
|
||||||
|
completed_index = state["current_step"] - 1
|
||||||
|
completed_step = (
|
||||||
|
todo_list[completed_index]
|
||||||
|
if 0 <= completed_index < len(todo_list)
|
||||||
|
else "unknown step"
|
||||||
|
)
|
||||||
|
all_done = state["current_step"] >= len(todo_list)
|
||||||
|
|
||||||
|
response = llm.invoke(
|
||||||
|
f"Todo step {completed_index + 1}/{len(todo_list)} has just been completed.\n"
|
||||||
|
f"Step description: {completed_step}\n\n"
|
||||||
|
f"Overall task: {state['task']}\n\n"
|
||||||
|
"Provide a concise one-paragraph summary of what was accomplished in this step."
|
||||||
|
)
|
||||||
|
summary = response.content if hasattr(response, "content") else str(response)
|
||||||
|
|
||||||
|
console.print(f"[bold green]✅ Step {completed_index + 1}/{len(todo_list)} done:[/bold green] {completed_step}")
|
||||||
|
console.print(f"[dim]{summary}[/dim]\n")
|
||||||
|
|
||||||
|
if all_done:
|
||||||
|
console.print(Panel.fit("[bold green]🎉 All todo steps completed![/bold green]", border_style="green"))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"done": all_done,
|
||||||
|
"messages": [AIMessage(content=f"Step completed: {summary}")],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Routing functions
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def route_after_plan(state: AgentState) -> Literal["get_human_feedback", "review_plan"]:
|
||||||
|
"""
|
||||||
|
After plan_task:
|
||||||
|
- LLM flagged uncertainty -> get_human_feedback -> plan_task (loop)
|
||||||
|
- LLM is satisfied -> review_plan -> execute_task
|
||||||
|
"""
|
||||||
|
if state.get("awaiting_human_feedback"):
|
||||||
|
return "get_human_feedback"
|
||||||
|
return "review_plan"
|
||||||
|
|
||||||
|
|
||||||
|
def route_after_execute(state: AgentState) -> Literal["call_tools", "mark_task_done"]:
|
||||||
|
"""After each execution step, dispatch tools or summarise."""
|
||||||
|
if state.get("done") or state["current_step"] >= len(state["todo_list"]):
|
||||||
|
return "mark_task_done"
|
||||||
|
return "call_tools"
|
||||||
|
|
||||||
|
|
||||||
|
def route_after_tools(state: AgentState) -> Literal["execute_task", "mark_task_done"]:
|
||||||
|
"""After tool dispatch, continue execution or summarise."""
|
||||||
|
if state.get("done") or state["current_step"] >= len(state["todo_list"]):
|
||||||
|
return "mark_task_done"
|
||||||
|
return "execute_task"
|
||||||
|
|
||||||
|
|
||||||
|
def route_after_mark_done(state: AgentState) -> Literal["execute_task", END]:
|
||||||
|
"""Loop to the next todo step, or exit when all steps are done."""
|
||||||
|
if state.get("done"):
|
||||||
|
return END
|
||||||
|
return "execute_task"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Graph factory
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def create_agent_graph():
|
def create_agent_graph():
|
||||||
"""Create a simple agent graph that processes messages and calls the llama server."""
|
"""
|
||||||
|
Graph topology:
|
||||||
|
|
||||||
# Build the LangGraph workflow
|
START
|
||||||
graph = StateGraph(MessagesState)
|
│
|
||||||
graph.add_node(call_llama_server)
|
plan_task <─────────────────────┐
|
||||||
graph.add_edge(START, "call_llama_server")
|
│ │
|
||||||
graph.add_edge("call_llama_server", END)
|
┌────┴──────────────┐ │
|
||||||
graph = graph.compile()
|
│ (needs feedback) │ (satisfied) │
|
||||||
|
▼ ▼ │
|
||||||
|
get_human_feedback review_plan │
|
||||||
|
│ │ │
|
||||||
|
└──► plan_task execute_task ◄──────────────┐
|
||||||
|
│ │
|
||||||
|
call_tools mark_task_done (more steps)
|
||||||
|
│ │
|
||||||
|
└──────────────────────►┘
|
||||||
|
(all done)
|
||||||
|
│
|
||||||
|
END
|
||||||
|
"""
|
||||||
|
graph = StateGraph(AgentState)
|
||||||
|
|
||||||
return graph
|
# Register nodes
|
||||||
|
graph.add_node("plan_task", plan_task)
|
||||||
|
graph.add_node("review_plan", review_plan)
|
||||||
|
graph.add_node("get_human_feedback", get_human_feedback)
|
||||||
|
graph.add_node("execute_task", execute_task)
|
||||||
|
graph.add_node("call_tools", call_tools)
|
||||||
|
graph.add_node("mark_task_done", mark_task_done)
|
||||||
|
|
||||||
|
# --- Planning stage ---
|
||||||
|
graph.add_edge(START, "plan_task")
|
||||||
|
|
||||||
|
# plan_task: needs clarification -> human feedback -> re-plan
|
||||||
|
# satisfied -> review_plan
|
||||||
|
graph.add_conditional_edges(
|
||||||
|
"plan_task",
|
||||||
|
route_after_plan,
|
||||||
|
{
|
||||||
|
"get_human_feedback": "get_human_feedback",
|
||||||
|
"review_plan": "review_plan",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
graph.add_edge("get_human_feedback", "plan_task")
|
||||||
|
|
||||||
|
# review_plan always proceeds directly to execution
|
||||||
|
graph.add_edge("review_plan", "execute_task")
|
||||||
|
|
||||||
|
# --- Execution stage ---
|
||||||
|
graph.add_conditional_edges(
|
||||||
|
"execute_task",
|
||||||
|
route_after_execute,
|
||||||
|
{
|
||||||
|
"call_tools": "call_tools",
|
||||||
|
"mark_task_done": "mark_task_done",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
graph.add_conditional_edges(
|
||||||
|
"call_tools",
|
||||||
|
route_after_tools,
|
||||||
|
{
|
||||||
|
"execute_task": "execute_task",
|
||||||
|
"mark_task_done": "mark_task_done",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
graph.add_conditional_edges(
|
||||||
|
"mark_task_done",
|
||||||
|
route_after_mark_done,
|
||||||
|
{
|
||||||
|
"execute_task": "execute_task",
|
||||||
|
END: END,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
memory = MemorySaver()
|
||||||
|
# Pause before get_human_feedback so the user can type their reply
|
||||||
|
return graph.compile(checkpointer=memory, interrupt_before=["get_human_feedback"])
|
||||||
48
core/agent/todo_prompt.py
Normal file
48
core/agent/todo_prompt.py
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
from core.config import AGENT_NAME
|
||||||
|
from core.tools.file_operations import (
|
||||||
|
read_file, write_file, replace_in_file, delete_in_file,
|
||||||
|
delete_file, copy_file, move_file, create_directory,
|
||||||
|
delete_directory, list_directory, get_file_info,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Categorize tools here so you can easily plug in new domains like web_tools
|
||||||
|
TOOL_CATEGORIES = {
|
||||||
|
"File Operations": [
|
||||||
|
read_file, write_file, replace_in_file, delete_in_file,
|
||||||
|
delete_file, copy_file, move_file, create_directory,
|
||||||
|
delete_directory, list_directory, get_file_info,
|
||||||
|
],
|
||||||
|
# "Web Tools": [], # e.g., [web_search, fetch_url]
|
||||||
|
# "Knowledge Tools": [], # e.g., [query_vector_db]
|
||||||
|
}
|
||||||
|
|
||||||
|
# Dynamically generate the string of tool names grouped by category
|
||||||
|
tools_list_parts = []
|
||||||
|
for category, cat_tools in TOOL_CATEGORIES.items():
|
||||||
|
if cat_tools:
|
||||||
|
tools_list_parts.append(f"[{category}]")
|
||||||
|
for tool in cat_tools:
|
||||||
|
first_line_desc = tool.description.strip().splitlines()[0]
|
||||||
|
tools_list_parts.append(f"- {tool.name}: {first_line_desc}")
|
||||||
|
tools_list_parts.append("") # Empty line for spacing
|
||||||
|
|
||||||
|
tools_list_str = "\n".join(tools_list_parts).strip()
|
||||||
|
|
||||||
|
todo_prompt_template = f"""You are {AGENT_NAME}, a helpful assistant. Based on the user's task, generate a to-do list with actionable steps. Make sure you are detailed about your plan, honest, and helpful.
|
||||||
|
Be proactive and make educated guesses if the user's request has minor ambiguities, leaving room for adjustments. Only ask for clarification if the request is entirely unclear or lacks crucial context.
|
||||||
|
|
||||||
|
IMPORTANT: Once you create this to-do list, you will execute it step-by-step using a set of available tools. You MUST tailor your plan knowing that the following tools will be accessible to you during the execution phase:
|
||||||
|
|
||||||
|
Available Tools:
|
||||||
|
{tools_list_str}
|
||||||
|
|
||||||
|
Here are a few things to keep in mind: your plan must be actionable and detailed. You should break down the task into smaller steps and provide a clear plan for how to accomplish the task utilizing the tools above.
|
||||||
|
If you are reading files, make sure to plan to read them carefully and extract the relevant information. If you are writing code, make sure to plan to write clean,
|
||||||
|
well-documented code that is secure, following the principle of least privilege and secure coding practices.
|
||||||
|
If you are doing research, make sure to provide a clear summary of your findings.
|
||||||
|
"""
|
||||||
|
|
||||||
|
review_todo_prompt_template = f"""You are {AGENT_NAME}, a helpful assistant. You have created the following to-do list based on the user's task.
|
||||||
|
Please review the to-do list and make sure it is actionable, detailed, clear, and effectively utilizes your available tools (such as file reading, writing, directory listing, etc.).
|
||||||
|
If there are any issues with the to-do list, please provide feedback and suggestions for improvement and return the updated to-do list.
|
||||||
|
If the to-do list looks good, please return the same to-do list."""
|
||||||
1
core/config.py
Normal file
1
core/config.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
AGENT_NAME = "oss-agent"
|
||||||
BIN
core/tools/__pycache__/file_operations.cpython-312.pyc
Normal file
BIN
core/tools/__pycache__/file_operations.cpython-312.pyc
Normal file
Binary file not shown.
39
main.py
39
main.py
@@ -1,13 +1,42 @@
|
|||||||
from core.agent.agent import create_agent_graph
|
from core.agent.agent import create_agent_graph
|
||||||
from langchain_core.messages import HumanMessage, AIMessage
|
from langchain_core.messages import HumanMessage, AIMessage
|
||||||
|
from rich.console import Console
|
||||||
|
from rich.prompt import Prompt
|
||||||
|
from rich.panel import Panel
|
||||||
|
|
||||||
|
AGENT_NAME = "oss-agent"
|
||||||
|
console = Console()
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
print("Hello from oss-agent!")
|
console.print(Panel.fit(f"[bold cyan]Hello from {AGENT_NAME}![/bold cyan]", border_style="cyan"))
|
||||||
graph = create_agent_graph()
|
graph = create_agent_graph()
|
||||||
graph.invoke({"messages": []})
|
|
||||||
# Invoke the graph with a test message
|
# A checkpointer requires a thread ID to track the conversation
|
||||||
output = graph.invoke({"messages": [HumanMessage(content="hi!")]})
|
config = {"configurable": {"thread_id": "1"}}
|
||||||
print("Agent response:", output)
|
|
||||||
|
user_input = "summarize current directory for me, tell me what does this project do and save summary to summary.txt"
|
||||||
|
console.print(f"\n[bold green]👤 User:[/bold green] {user_input}")
|
||||||
|
state_input = {"messages": [HumanMessage(content=user_input)]}
|
||||||
|
|
||||||
|
while True:
|
||||||
|
for event in graph.stream(state_input, config, stream_mode="updates"):
|
||||||
|
pass
|
||||||
|
|
||||||
|
state = graph.get_state(config)
|
||||||
|
if not state.next:
|
||||||
|
break
|
||||||
|
|
||||||
|
if "get_human_feedback" in state.next:
|
||||||
|
feedback = Prompt.ask("\n[bold yellow]👉 Your response[/bold yellow]")
|
||||||
|
state_input = {"messages": [HumanMessage(content=feedback)]}
|
||||||
|
else:
|
||||||
|
state_input = None
|
||||||
|
|
||||||
|
|
||||||
|
def print_message(message):
|
||||||
|
if message.type == "ai":
|
||||||
|
console.print(f"[bold blue]{AGENT_NAME}:[/bold blue] {message.content}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|||||||
@@ -11,4 +11,5 @@ dependencies = [
|
|||||||
"langchain-openai>=0.3.0",
|
"langchain-openai>=0.3.0",
|
||||||
"langgraph>=1.1.3",
|
"langgraph>=1.1.3",
|
||||||
"python-dotenv>=1.0.0",
|
"python-dotenv>=1.0.0",
|
||||||
|
"rich>=14.3.3",
|
||||||
]
|
]
|
||||||
|
|||||||
17
summary.txt
Normal file
17
summary.txt
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
This project is a lightweight AI agent built with LangChain.
|
||||||
|
|
||||||
|
Directory overview:
|
||||||
|
- **README.md** – First paragraph: "# Personal project"
|
||||||
|
- **main.py** – Entry point; creates the agent graph and handles user interaction.
|
||||||
|
- **core/** – Holds the core agent implementation (agent.py and related modules).
|
||||||
|
- **.venv/** – Python virtual environment (not part of source).
|
||||||
|
- **.git/** – Git metadata.
|
||||||
|
- **pyproject.toml** – Build and dependency configuration.
|
||||||
|
- **uv.lock** – UV lock file.
|
||||||
|
- **.env** – Environment configuration.
|
||||||
|
|
||||||
|
The agent can process user messages, read files, summarize them, and save output to disk, as requested.
|
||||||
|
|
||||||
|
Project purpose: Provide a simple example of an AI agent that can interact with the user and manipulate local files.
|
||||||
|
|
||||||
|
Saved summary to summary.txt.
|
||||||
45
uv.lock
generated
45
uv.lock
generated
@@ -718,6 +718,18 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/e8/46/9294d4f49de6a8f08e8b83907713ca545459d87d474c6add15d31a36f5dc/langsmith-0.7.20-py3-none-any.whl", hash = "sha256:0162faf791ea48d69009a12a3da917468556b99cf5d5fcacbb8cda064262e118", size = 359314, upload-time = "2026-03-18T00:03:37.59Z" },
|
{ url = "https://files.pythonhosted.org/packages/e8/46/9294d4f49de6a8f08e8b83907713ca545459d87d474c6add15d31a36f5dc/langsmith-0.7.20-py3-none-any.whl", hash = "sha256:0162faf791ea48d69009a12a3da917468556b99cf5d5fcacbb8cda064262e118", size = 359314, upload-time = "2026-03-18T00:03:37.59Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "markdown-it-py"
|
||||||
|
version = "4.0.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "mdurl" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/5b/f5/4ec618ed16cc4f8fb3b701563655a69816155e79e24a17b651541804721d/markdown_it_py-4.0.0.tar.gz", hash = "sha256:cb0a2b4aa34f932c007117b194e945bd74e0ec24133ceb5bac59009cda1cb9f3", size = 73070, upload-time = "2025-08-11T12:57:52.854Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/94/54/e7d793b573f298e1c9013b8c4dade17d481164aa517d1d7148619c2cedbf/markdown_it_py-4.0.0-py3-none-any.whl", hash = "sha256:87327c59b172c5011896038353a81343b6754500a08cd7a4973bb48c6d578147", size = 87321, upload-time = "2025-08-11T12:57:51.923Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marshmallow"
|
name = "marshmallow"
|
||||||
version = "3.26.2"
|
version = "3.26.2"
|
||||||
@@ -730,6 +742,15 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/be/2f/5108cb3ee4ba6501748c4908b908e55f42a5b66245b4cfe0c99326e1ef6e/marshmallow-3.26.2-py3-none-any.whl", hash = "sha256:013fa8a3c4c276c24d26d84ce934dc964e2aa794345a0f8c7e5a7191482c8a73", size = 50964, upload-time = "2025-12-22T06:53:51.801Z" },
|
{ url = "https://files.pythonhosted.org/packages/be/2f/5108cb3ee4ba6501748c4908b908e55f42a5b66245b4cfe0c99326e1ef6e/marshmallow-3.26.2-py3-none-any.whl", hash = "sha256:013fa8a3c4c276c24d26d84ce934dc964e2aa794345a0f8c7e5a7191482c8a73", size = 50964, upload-time = "2025-12-22T06:53:51.801Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mdurl"
|
||||||
|
version = "0.1.2"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "multidict"
|
name = "multidict"
|
||||||
version = "6.7.1"
|
version = "6.7.1"
|
||||||
@@ -1034,6 +1055,7 @@ dependencies = [
|
|||||||
{ name = "langchain-openai" },
|
{ name = "langchain-openai" },
|
||||||
{ name = "langgraph" },
|
{ name = "langgraph" },
|
||||||
{ name = "python-dotenv" },
|
{ name = "python-dotenv" },
|
||||||
|
{ name = "rich" },
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.metadata]
|
[package.metadata]
|
||||||
@@ -1044,6 +1066,7 @@ requires-dist = [
|
|||||||
{ name = "langchain-openai", specifier = ">=0.3.0" },
|
{ name = "langchain-openai", specifier = ">=0.3.0" },
|
||||||
{ name = "langgraph", specifier = ">=1.1.3" },
|
{ name = "langgraph", specifier = ">=1.1.3" },
|
||||||
{ name = "python-dotenv", specifier = ">=1.0.0" },
|
{ name = "python-dotenv", specifier = ">=1.0.0" },
|
||||||
|
{ name = "rich", specifier = ">=14.3.3" },
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1239,6 +1262,15 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/00/4b/ccc026168948fec4f7555b9164c724cf4125eac006e176541483d2c959be/pydantic_settings-2.13.1-py3-none-any.whl", hash = "sha256:d56fd801823dbeae7f0975e1f8c8e25c258eb75d278ea7abb5d9cebb01b56237", size = 58929, upload-time = "2026-02-19T13:45:06.034Z" },
|
{ url = "https://files.pythonhosted.org/packages/00/4b/ccc026168948fec4f7555b9164c724cf4125eac006e176541483d2c959be/pydantic_settings-2.13.1-py3-none-any.whl", hash = "sha256:d56fd801823dbeae7f0975e1f8c8e25c258eb75d278ea7abb5d9cebb01b56237", size = 58929, upload-time = "2026-02-19T13:45:06.034Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pygments"
|
||||||
|
version = "2.19.2"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/b0/77/a5b8c569bf593b0140bde72ea885a803b82086995367bf2037de0159d924/pygments-2.19.2.tar.gz", hash = "sha256:636cb2477cec7f8952536970bc533bc43743542f70392ae026374600add5b887", size = 4968631, upload-time = "2025-06-21T13:39:12.283Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/c7/21/705964c7812476f378728bdf590ca4b771ec72385c533964653c68e86bdc/pygments-2.19.2-py3-none-any.whl", hash = "sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b", size = 1225217, upload-time = "2025-06-21T13:39:07.939Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "python-dotenv"
|
name = "python-dotenv"
|
||||||
version = "1.2.2"
|
version = "1.2.2"
|
||||||
@@ -1409,6 +1441,19 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/3f/51/d4db610ef29373b879047326cbf6fa98b6c1969d6f6dc423279de2b1be2c/requests_toolbelt-1.0.0-py2.py3-none-any.whl", hash = "sha256:cccfdd665f0a24fcf4726e690f65639d272bb0637b9b92dfd91a5568ccf6bd06", size = 54481, upload-time = "2023-05-01T04:11:28.427Z" },
|
{ url = "https://files.pythonhosted.org/packages/3f/51/d4db610ef29373b879047326cbf6fa98b6c1969d6f6dc423279de2b1be2c/requests_toolbelt-1.0.0-py2.py3-none-any.whl", hash = "sha256:cccfdd665f0a24fcf4726e690f65639d272bb0637b9b92dfd91a5568ccf6bd06", size = 54481, upload-time = "2023-05-01T04:11:28.427Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rich"
|
||||||
|
version = "14.3.3"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "markdown-it-py" },
|
||||||
|
{ name = "pygments" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/b3/c6/f3b320c27991c46f43ee9d856302c70dc2d0fb2dba4842ff739d5f46b393/rich-14.3.3.tar.gz", hash = "sha256:b8daa0b9e4eef54dd8cf7c86c03713f53241884e814f4e2f5fb342fe520f639b", size = 230582, upload-time = "2026-02-19T17:23:12.474Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/14/25/b208c5683343959b670dc001595f2f3737e051da617f66c31f7c4fa93abc/rich-14.3.3-py3-none-any.whl", hash = "sha256:793431c1f8619afa7d3b52b2cdec859562b950ea0d4b6b505397612db8d5362d", size = 310458, upload-time = "2026-02-19T17:23:13.732Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sniffio"
|
name = "sniffio"
|
||||||
version = "1.3.1"
|
version = "1.3.1"
|
||||||
|
|||||||
Reference in New Issue
Block a user