Spaces:
Sleeping
Sleeping
File size: 24,418 Bytes
af6094d febd4c2 af6094d febd4c2 af6094d febd4c2 af6094d febd4c2 af6094d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 |
"""
LangGraph State Machine for Secure Reasoning MCP Server
Implements the Chain-of-Checks workflow with cryptographic logging.
"""
import json
import os
import re
from huggingface_hub import InferenceClient
from typing import Literal
from datetime import datetime
from langgraph.graph import StateGraph, END
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
from state import AgentState
from schemas import (
ExecutionPlan, StepPlan, SafetyCheckResult, ExecutionResult,
Justification, CryptoLogEntry, HashRequest, MerkleUpdateRequest,
WORMWriteRequest
)
from prompts import (
format_planner_prompt, format_safety_prompt, format_executor_prompt,
format_justification_prompt, format_synthesis_prompt
)
from mock_tools import MockCryptoTools
# ============================================================================
# GLOBAL CONFIGURATION
# ============================================================================
# HuggingFace Inference Client - Γcretsiz tier kullanΔ±yor
HF_TOKEN = os.getenv("HF_TOKEN")
MODEL_ID = "Qwen/Qwen2.5-72B-Instruct" # GΓΌΓ§lΓΌ ve ΓΌcretsiz
hf_client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
# Initialize crypto tools
crypto_tools = MockCryptoTools()
# ============================================================================
# HuggingFace LLM Wrapper - LangChain benzeri interface
# ============================================================================
class HuggingFaceLLM:
"""
HuggingFace Inference API wrapper that mimics LangChain LLM interface.
"""
def __init__(self, client: InferenceClient):
self.client = client
def invoke(self, messages: list) -> "LLMResponse":
"""
Call HuggingFace model with messages.
Returns object with .content attribute like LangChain.
"""
# Convert LangChain messages to HF format
hf_messages = []
for msg in messages:
if isinstance(msg, SystemMessage):
hf_messages.append({"role": "system", "content": msg.content})
elif isinstance(msg, HumanMessage):
hf_messages.append({"role": "user", "content": msg.content})
elif isinstance(msg, AIMessage):
hf_messages.append({"role": "assistant", "content": msg.content})
try:
response = self.client.chat_completion(
messages=hf_messages,
max_tokens=2048,
temperature=0.1, # Low for deterministic reasoning
stream=False
)
content = response.choices[0].message.content
return LLMResponse(content)
except Exception as e:
print(f"HF API Error: {e}")
return LLMResponse(f'{{"error": "{str(e)}"}}')
class LLMResponse:
"""Simple response object with content attribute."""
def __init__(self, content: str):
self.content = content
# Initialize our HF-based LLM
llm = HuggingFaceLLM(hf_client)
# ============================================================================
# NODE 1: PLANNER
# ============================================================================
def planner_node(state: AgentState) -> AgentState:
"""
Generate a step-by-step execution plan for the task.
Args:
state: Current agent state with the task
Returns:
Updated state with the execution plan
"""
print(f"\n{'='*60}")
print(f"π§ PLANNER NODE - Generating execution plan")
print(f"{'='*60}")
# Format the prompt
prompts = format_planner_prompt(state["task"])
# Create messages
messages = [
SystemMessage(content=prompts["system"]),
HumanMessage(content=prompts["user"])
]
# Call LLM
response = llm.invoke(messages)
# Parse JSON response
try:
plan_data = json.loads(response.content)
# Convert to ExecutionPlan model
steps = [StepPlan(**step) for step in plan_data["steps"]]
plan = ExecutionPlan(
steps=steps,
total_steps=plan_data["total_steps"]
)
print(f"β
Generated plan with {plan.total_steps} steps:")
for step in steps:
print(f" Step {step.step_number}: {step.action}")
# Update state
state["plan"] = plan
state["current_step_index"] = 0
state["status"] = "executing"
state["messages"].extend([
HumanMessage(content=prompts["user"]),
AIMessage(content=response.content)
])
return state
except json.JSONDecodeError as e:
print(f"β Failed to parse planner response: {e}")
state["error"] = f"Planner failed to generate valid JSON: {str(e)}"
state["status"] = "failed"
return state
# ============================================================================
# NODE 2: SAFETY CHECKER
# ============================================================================
def safety_node(state: AgentState) -> AgentState:
"""
Validate that the current step is safe to execute.
Args:
state: Current agent state with the plan
Returns:
Updated state with safety validation result
"""
print(f"\n{'='*60}")
print(f"π‘οΈ SAFETY NODE - Validating step {state['current_step_index'] + 1}")
print(f"{'='*60}")
# Get current step
current_step = state["plan"].steps[state["current_step_index"]]
# Format previous steps for context
previous_steps = "None"
if state["current_step_index"] > 0:
prev_steps_list = [
f"Step {i+1}: {state['plan'].steps[i].action}"
for i in range(state["current_step_index"])
]
previous_steps = "\n".join(prev_steps_list)
# Format the prompt
prompts = format_safety_prompt(
step_description=current_step.action,
task=state["task"],
step_number=state["current_step_index"] + 1,
total_steps=state["plan"].total_steps,
previous_steps=previous_steps,
additional_context="This is a secure reasoning system with cryptographic logging."
)
# Create messages
messages = [
SystemMessage(content=prompts["system"]),
HumanMessage(content=prompts["user"])
]
# Call LLM
response = llm.invoke(messages)
# Parse JSON response
try:
safety_data = json.loads(response.content)
safety_result = SafetyCheckResult(**safety_data)
print(f"π Safety Check Result:")
print(f" Is Safe: {safety_result.is_safe}")
print(f" Risk Level: {safety_result.risk_level}")
print(f" Reasoning: {safety_result.reasoning[:100]}...")
# Update state
state["safety_status"] = safety_result
state["messages"].extend([
HumanMessage(content=prompts["user"]),
AIMessage(content=response.content)
])
# Mark if blocked
if not safety_result.is_safe:
state["safety_blocked"] = True
print(f"π« Step BLOCKED due to safety concerns")
else:
print(f"β
Step approved for execution")
return state
except json.JSONDecodeError as e:
print(f"β Failed to parse safety response: {e}")
# Default to blocking if parsing fails (fail-safe)
state["safety_status"] = SafetyCheckResult(
is_safe=False,
risk_level="critical",
reasoning=f"Safety check failed due to parsing error: {str(e)}",
blocked_reasons=["parsing_error"]
)
state["safety_blocked"] = True
return state
# ============================================================================
# NODE 3: EXECUTOR
# ============================================================================
def executor_node(state: AgentState) -> AgentState:
"""
Execute the current step (call tools if needed).
Args:
state: Current agent state with approved step
Returns:
Updated state with execution result
"""
print(f"\n{'='*60}")
print(f"β‘ EXECUTOR NODE - Executing step {state['current_step_index'] + 1}")
print(f"{'='*60}")
# Get current step
current_step = state["plan"].steps[state["current_step_index"]]
# Format previous results for context
previous_results = "None"
if state["justifications"]:
prev_results_list = [
f"Step {j.step_number}: {j.reasoning[:100]}..."
for j in state["justifications"][-3:] # Last 3 steps
]
previous_results = "\n".join(prev_results_list)
# Format the prompt
prompts = format_executor_prompt(
step_description=current_step.action,
task=state["task"],
expected_outcome=current_step.expected_outcome,
requires_tools=current_step.requires_tools,
previous_results=previous_results
)
# Create messages
messages = [
SystemMessage(content=prompts["system"]),
HumanMessage(content=prompts["user"])
]
# Call LLM
response = llm.invoke(messages)
# Parse JSON response
try:
executor_data = json.loads(response.content)
tool_needed = executor_data.get("tool_needed", "internal_reasoning")
tool_params = executor_data.get("tool_params")
direct_result = executor_data.get("direct_result")
print(f"π§ Tool Selection: {tool_needed}")
# Execute based on tool selection
if tool_needed == "internal_reasoning":
result = ExecutionResult(
success=True,
output=direct_result or "Analysis completed through reasoning",
tool_calls=["internal_reasoning"]
)
else:
# Simulate tool execution (in real system, dispatch to actual tools)
result = ExecutionResult(
success=True,
output=f"Simulated result from {tool_needed} with params: {tool_params}",
tool_calls=[tool_needed]
)
print(f"β
Execution successful")
print(f" Output: {str(result.output)[:100]}...")
# Update state
state["execution_result"] = result
state["messages"].extend([
HumanMessage(content=prompts["user"]),
AIMessage(content=response.content)
])
return state
except json.JSONDecodeError as e:
print(f"β Execution failed: {e}")
state["execution_result"] = ExecutionResult(
success=False,
output=None,
error=f"Failed to parse executor response: {str(e)}",
tool_calls=[]
)
return state
except Exception as e:
print(f"β Execution error: {e}")
state["execution_result"] = ExecutionResult(
success=False,
output=None,
error=str(e),
tool_calls=[]
)
return state
# ============================================================================
# NODE 4: LOGGER (Cryptographic Logging)
# ============================================================================
def logger_node(state: AgentState) -> AgentState:
"""
Hash the execution result and log it to Merkle Tree + WORM storage.
Args:
state: Current agent state with execution result
Returns:
Updated state with cryptographic log entry
"""
print(f"\n{'='*60}")
print(f"π LOGGER NODE - Creating cryptographic proof")
print(f"{'='*60}")
current_step = state["plan"].steps[state["current_step_index"]]
execution_result = state["execution_result"]
try:
# 1. Prepare the data to log
log_data = {
"task_id": state["task_id"],
"step_number": state["current_step_index"] + 1,
"action": current_step.action,
"result": execution_result.output if execution_result.success else execution_result.error,
"timestamp": datetime.utcnow().isoformat(),
"safety_approved": state["safety_status"].is_safe if state["safety_status"] else False
}
# 2. Hash the action data
hash_request = HashRequest(
data=json.dumps(log_data, sort_keys=True),
algorithm="sha256"
)
hash_response = crypto_tools.hash_tool(hash_request)
action_hash = hash_response.hash
print(f"π Action Hash: {action_hash[:16]}...")
# 3. Update Merkle Tree
merkle_request = MerkleUpdateRequest(
leaf_hash=action_hash,
metadata={"step": state["current_step_index"] + 1}
)
merkle_response = crypto_tools.merkle_update_tool(merkle_request)
merkle_root = merkle_response.merkle_root
print(f"π³ Merkle Root: {merkle_root[:16]}...")
# 4. Write to WORM storage
entry_id = f"{state['task_id']}_step_{state['current_step_index'] + 1}"
worm_request = WORMWriteRequest(
entry_id=entry_id,
data=log_data,
merkle_root=merkle_root
)
worm_response = crypto_tools.worm_write_tool(worm_request)
print(f"πΎ WORM Path: {worm_response.storage_path}")
# 5. Create log entry
log_entry = CryptoLogEntry(
step_number=state["current_step_index"] + 1,
action_hash=action_hash,
merkle_root=merkle_root,
worm_path=worm_response.storage_path
)
# Update state
state["logs"].append(log_entry)
print(f"β
Cryptographic logging complete")
return state
except Exception as e:
print(f"β Logging failed: {e}")
state["error"] = f"Cryptographic logging failed: {str(e)}"
return state
# ============================================================================
# NODE 5: JUSTIFICATION
# ============================================================================
def justification_node(state: AgentState) -> AgentState:
"""
Generate an explanation for why the action was taken.
Args:
state: Current agent state with execution result
Returns:
Updated state with justification
"""
print(f"\n{'='*60}")
print(f"π JUSTIFICATION NODE - Explaining the action")
print(f"{'='*60}")
current_step = state["plan"].steps[state["current_step_index"]]
execution_result = state["execution_result"]
# Determine tool used
tool_used = ", ".join(execution_result.tool_calls) if execution_result.tool_calls else "none"
# Format the prompt
prompts = format_justification_prompt(
step_description=current_step.action,
tool_used=tool_used,
execution_result=str(execution_result.output)[:500] if execution_result.success else execution_result.error,
task=state["task"],
step_number=state["current_step_index"] + 1,
total_steps=state["plan"].total_steps,
expected_outcome=current_step.expected_outcome
)
# Create messages
messages = [
SystemMessage(content=prompts["system"]),
HumanMessage(content=prompts["user"])
]
# Call LLM
response = llm.invoke(messages)
# Parse JSON response
try:
justification_data = json.loads(response.content)
justification = Justification(**justification_data)
print(f"π Justification generated:")
print(f" {justification.reasoning[:150]}...")
# Update state
state["justifications"].append(justification)
state["messages"].extend([
HumanMessage(content=prompts["user"]),
AIMessage(content=response.content)
])
return state
except json.JSONDecodeError as e:
print(f"β οΈ Failed to parse justification, using fallback: {e}")
# Create fallback justification
fallback = Justification(
step_number=state["current_step_index"] + 1,
reasoning=f"Executed {current_step.action} as planned. Result: {execution_result.success}",
evidence=None,
alternatives_considered=None
)
state["justifications"].append(fallback)
return state
# ============================================================================
# NODE 6: STEP ITERATOR
# ============================================================================
def step_iterator_node(state: AgentState) -> AgentState:
"""
Move to the next step or complete the task.
Args:
state: Current agent state
Returns:
Updated state with incremented step index
"""
print(f"\n{'='*60}")
print(f"β‘οΈ STEP ITERATOR - Moving to next step")
print(f"{'='*60}")
# Increment step index
state["current_step_index"] += 1
# Check if we're done
if state["current_step_index"] >= state["plan"].total_steps:
print(f"π All steps completed!")
state["status"] = "completed"
else:
print(f"π Moving to step {state['current_step_index'] + 1}/{state['plan'].total_steps}")
return state
# ============================================================================
# NODE 7: REFINER (for unsafe steps)
# ============================================================================
def refiner_node(state: AgentState) -> AgentState:
"""
Handle unsafe steps by modifying or skipping them.
Args:
state: Current agent state with blocked step
Returns:
Updated state with refinement decision
"""
print(f"\n{'='*60}")
print(f"π§ REFINER NODE - Handling unsafe step")
print(f"{'='*60}")
current_step = state["plan"].steps[state["current_step_index"]]
safety_status = state["safety_status"]
# Log the blocked action
print(f"π« Step blocked: {current_step.action}")
print(f" Reason: {safety_status.reasoning}")
# Create a null execution result
state["execution_result"] = ExecutionResult(
success=False,
output=None,
error=f"Step blocked by safety guardrails: {safety_status.reasoning}",
tool_calls=[]
)
# Create justification for blocking
justification = Justification(
step_number=state["current_step_index"] + 1,
reasoning=f"Step was blocked by safety guardrails. Risk level: {safety_status.risk_level}. Reason: {safety_status.reasoning}",
evidence=safety_status.blocked_reasons or [],
alternatives_considered=["Skip this step", "Abort entire task"]
)
state["justifications"].append(justification)
# Mark status
state["status"] = "blocked"
print(f"β οΈ Task blocked due to safety concerns")
return state
# ============================================================================
# CONDITIONAL EDGES
# ============================================================================
def should_execute_or_refine(state: AgentState) -> Literal["execute", "refine"]:
"""
Decide whether to execute or refine based on safety check.
Args:
state: Current agent state
Returns:
"execute" if safe, "refine" if unsafe
"""
if state["safety_status"] and state["safety_status"].is_safe:
return "execute"
else:
return "refine"
def should_continue_or_end(state: AgentState) -> Literal["continue", "end"]:
"""
Decide whether to continue to next step or end the workflow.
Args:
state: Current agent state
Returns:
"continue" if more steps remain, "end" if done or blocked
"""
# End if blocked
if state["safety_blocked"] and state["status"] == "blocked":
return "end"
# End if error occurred
if state["error"]:
return "end"
# End if all steps completed
if state["current_step_index"] >= state["plan"].total_steps:
return "end"
# Continue to next step
return "continue"
# ============================================================================
# GRAPH CONSTRUCTION
# ============================================================================
def create_reasoning_graph() -> StateGraph:
"""
Construct the full LangGraph state machine.
Returns:
Compiled StateGraph ready for execution
"""
# Create the graph
workflow = StateGraph(AgentState)
# Add nodes
workflow.add_node("planner", planner_node)
workflow.add_node("safety", safety_node)
workflow.add_node("executor", executor_node)
workflow.add_node("logger", logger_node)
workflow.add_node("justification", justification_node)
workflow.add_node("iterator", step_iterator_node)
workflow.add_node("refiner", refiner_node)
# Set entry point
workflow.set_entry_point("planner")
# Add edges
workflow.add_edge("planner", "safety")
# Conditional: safe -> execute, unsafe -> refine
workflow.add_conditional_edges(
"safety",
should_execute_or_refine,
{
"execute": "executor",
"refine": "refiner"
}
)
# After execution: log -> justify -> iterate
workflow.add_edge("executor", "logger")
workflow.add_edge("logger", "justification")
workflow.add_edge("justification", "iterator")
# After refining: go to iterator (to mark as done)
workflow.add_edge("refiner", "iterator")
# Conditional: continue to next step or end
workflow.add_conditional_edges(
"iterator",
should_continue_or_end,
{
"continue": "safety", # Loop back to safety check for next step
"end": END
}
)
# Compile the graph
return workflow.compile()
# ============================================================================
# CONVENIENCE FUNCTION
# ============================================================================
def run_reasoning_task(task: str, task_id: str, user_id: str = None) -> AgentState:
"""
Execute a reasoning task through the full pipeline.
Args:
task: The task to solve
task_id: Unique identifier for this execution
user_id: Optional user identifier
Returns:
Final agent state with results and logs
"""
from state import create_initial_state
# Create initial state
initial_state = create_initial_state(task, task_id, user_id)
# Create and run the graph
graph = create_reasoning_graph()
print(f"\n{'#'*60}")
print(f"π STARTING REASONING PIPELINE")
print(f" Task: {task}")
print(f" Task ID: {task_id}")
print(f"{'#'*60}")
# Execute
final_state = graph.invoke(initial_state)
print(f"\n{'#'*60}")
print(f"π REASONING PIPELINE COMPLETE")
print(f" Status: {final_state['status']}")
print(f" Steps Executed: {len(final_state['justifications'])}/{final_state['plan'].total_steps if final_state['plan'] else 0}")
print(f" Cryptographic Logs: {len(final_state['logs'])}")
print(f"{'#'*60}\n")
return final_state
# ============================================================================
# EXAMPLE USAGE
# ============================================================================
if __name__ == "__main__":
# Test the graph
result = run_reasoning_task(
task="Analyze the current state of AI safety research and provide 3 key findings",
task_id="test_001",
user_id="demo_user"
)
# Print results
print("\n=== FINAL RESULTS ===")
print(f"Status: {result['status']}")
print(f"\nJustifications:")
for j in result['justifications']:
print(f" Step {j.step_number}: {j.reasoning[:100]}...")
print(f"\nCryptographic Audit Trail:")
for log in result['logs']:
print(f" Step {log.step_number}: Hash {log.action_hash[:16]}... -> Root {log.merkle_root[:16]}...") |