File size: 27,762 Bytes
f1fca86 |
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 |
"""
Multi-Agent Research Assistant with LangGraph (HUGGINGFACE COMPATIBLE)
======================================================================
Adapted for HuggingFace models that don't support bind_tools() or with_structured_output()
Uses: Manual tool calling with prompt engineering + JSON parsing with error handling
Supports: Both text-generation and conversational task types
Installation:
pip install langgraph langchain langchain-community langchain-huggingface pydantic numexpr
"""
import operator
import re
import json
from typing import Annotated, List, Optional, TypedDict, Literal
from pydantic import BaseModel, Field, ValidationError
import numexpr as ne
# LangGraph imports
from langgraph.graph import StateGraph, END
# LangChain imports
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 1. PYDANTIC SCHEMAS
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class ResearchOutput(BaseModel):
"""Structured output from Researcher agent"""
answer: str = Field(description="The direct answer to the question")
sources_used: List[str] = Field(description="List of tools/sources consulted")
confidence: float = Field(description="Confidence score 0-1", ge=0, le=1)
class AnalysisOutput(BaseModel):
"""Structured output from Analyst agent"""
key_points: List[str] = Field(description="2-3 key points")
implications: str = Field(description="Why this matters")
class ReportOutput(BaseModel):
"""Structured output from Writer agent"""
title: str = Field(description="Report title")
content: str = Field(description="Main report content")
class CritiqueOutput(BaseModel):
"""Structured output from Critic agent"""
score: float = Field(description="Quality score 0-10", ge=0, le=10)
needs_revision: bool = Field(description="Whether revision is needed")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 2. SHARED STATE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class AgentState(TypedDict):
"""Shared state for all agents"""
question: str
research_output: Optional[ResearchOutput]
analysis_output: Optional[AnalysisOutput]
report_output: Optional[ReportOutput]
critique_output: Optional[CritiqueOutput]
report_iterations: int
max_iterations: int
current_step: str
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 3. TOOLS
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@tool
def calculator(expression: str) -> str:
"""
Perform safe mathematical calculations.
Args:
expression: A mathematical expression like "2+2" or "(10*5)+3"
"""
try:
expression = expression.strip()
allowed = set("0123456789+-*/(). ")
if not all(c in allowed for c in expression):
return "Error: Invalid characters"
result = ne.evaluate(expression)
return str(result)
except Exception as e:
return f"Error: {str(e)}"
@tool
def search_knowledge(query: str) -> str:
"""
Search for general knowledge information.
Args:
query: The search query or topic
"""
knowledge = {
"ai": "Artificial Intelligence (AI) is the simulation of human intelligence by machines. Key applications include machine learning, natural language processing, computer vision, and robotics. AI systems can learn from data, recognize patterns, and make decisions.",
"artificial intelligence": "Artificial Intelligence (AI) is the simulation of human intelligence by machines. Key applications include machine learning, natural language processing, computer vision, and robotics. AI systems can learn from data, recognize patterns, and make decisions.",
"machine learning": "Machine Learning is a subset of AI that enables systems to learn and improve from experience without being explicitly programmed. It uses algorithms to identify patterns in data and make predictions.",
"python": "Python is a high-level, interpreted programming language known for its simplicity and readability. It's widely used in web development, data science, AI, automation, and scientific computing.",
"data science": "Data Science is an interdisciplinary field that uses scientific methods, algorithms, and systems to extract knowledge and insights from structured and unstructured data.",
}
query_lower = query.lower()
for key, value in knowledge.items():
if key in query_lower:
return value
return f"Information about '{query}' would require web search or domain expertise. This is a general knowledge topic."
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 4. TOOL EXECUTOR (Manual Implementation)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class ToolExecutor:
"""Manually execute tools based on LLM requests"""
def __init__(self, tools):
self.tools = {t.name: t for t in tools}
def detect_tool_call(self, text: str) -> Optional[tuple]:
"""Detect if text contains a tool call request"""
# Pattern: USE_TOOL: tool_name(arguments)
pattern = r'USE_TOOL:\s*(\w+)\((.*?)\)'
match = re.search(pattern, text, re.IGNORECASE)
if match:
tool_name = match.group(1)
arguments = match.group(2).strip('"\'')
return (tool_name, arguments)
# Alternative pattern: tool_name: arguments
for tool_name in self.tools.keys():
if f"{tool_name}:" in text.lower():
# Extract what comes after the tool name
pattern = rf'{tool_name}:\s*([^\n]+)'
match = re.search(pattern, text, re.IGNORECASE)
if match:
arguments = match.group(1).strip('"\'')
return (tool_name, arguments)
return None
def execute(self, tool_name: str, arguments: str) -> str:
"""Execute a tool with given arguments"""
if tool_name not in self.tools:
return f"Error: Tool '{tool_name}' not found"
try:
result = self.tools[tool_name].func(arguments)
return result
except Exception as e:
return f"Error executing {tool_name}: {str(e)}"
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 5. JSON PARSER WITH ERROR HANDLING
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def extract_json(text: str) -> Optional[dict]:
"""Extract JSON from text with multiple strategies"""
# Strategy 1: Find JSON in code blocks
json_pattern = r'```(?:json)?\s*(\{.*?\})\s*```'
matches = re.findall(json_pattern, text, re.DOTALL)
if matches:
try:
return json.loads(matches[0])
except:
pass
# Strategy 2: Find JSON without code blocks
json_pattern = r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}'
matches = re.findall(json_pattern, text, re.DOTALL)
for match in matches:
try:
parsed = json.loads(match)
if isinstance(parsed, dict) and len(parsed) > 0:
return parsed
except:
continue
return None
def safe_parse_pydantic(text: str, model: BaseModel, fallback_data: dict) -> BaseModel:
"""Safely parse text into Pydantic model with fallback"""
# Try to extract JSON
json_data = extract_json(text)
if json_data:
try:
return model(**json_data)
except ValidationError:
pass
# Try parsing text directly as JSON
try:
return model.model_validate_json(text)
except:
pass
# Fallback: Create model with fallback data
try:
return model(**fallback_data)
except:
# Last resort: minimal valid model
return model(**{k: v for k, v in fallback_data.items() if k in model.model_fields})
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 6. LLM FACTORY
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class LLMFactory:
"""Factory for creating LLM instances"""
@staticmethod
def create_llm(token: str, temperature: float = 0.3):
"""Create base LLM with conversational support"""
try:
# Try using ChatHuggingFace wrapper for conversational models
endpoint = HuggingFaceEndpoint(
repo_id="meta-llama/Llama-3.1-8B-Instruct",
huggingfacehub_api_token=token,
temperature=temperature,
max_new_tokens=1000,
top_p=0.9,
repetition_penalty=1.1,
task="conversational" # Specify conversational task
)
# Wrap with ChatHuggingFace for proper message handling
llm = ChatHuggingFace(llm=endpoint)
return llm
except Exception as e:
print(f"β οΈ ChatHuggingFace failed, trying standard endpoint: {e}")
# Fallback to standard endpoint
return HuggingFaceEndpoint(
repo_id="meta-llama/Llama-3.1-8B-Instruct",
huggingfacehub_api_token=token,
temperature=temperature,
max_new_tokens=1000,
top_p=0.9,
repetition_penalty=1.1
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 7. AGENT NODES
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class ResearcherAgent:
"""Researcher with manual tool calling"""
def __init__(self, llm, tool_executor):
self.llm = llm
self.tool_executor = tool_executor
def __call__(self, state: AgentState) -> AgentState:
"""Research node with tool execution"""
print("\nπ RESEARCHER AGENT")
question = state["question"]
# Determine which tool to use
prompt = f"""You are a research assistant. Answer this question: {question}
Available tools:
- calculator: For math operations (e.g., "2+2", "(10*5)+3")
- search_knowledge: For information lookup (e.g., "artificial intelligence", "python")
Instructions:
1. If the question involves math/calculation, respond with: USE_TOOL: calculator(expression)
2. If the question needs information, respond with: USE_TOOL: search_knowledge(topic)
3. Replace 'expression' or 'topic' with the actual query
Examples:
- For "what is 2+2": USE_TOOL: calculator(2+2)
- For "what is AI": USE_TOOL: search_knowledge(artificial intelligence)
Your response:"""
# Get LLM response (handle both chat and text models)
try:
# Try chat-style invocation first
if hasattr(self.llm, 'invoke'):
response_obj = self.llm.invoke([HumanMessage(content=prompt)])
# Extract content from response
if hasattr(response_obj, 'content'):
response = response_obj.content
else:
response = str(response_obj)
else:
response = self.llm(prompt)
except Exception as e:
print(f" β οΈ LLM error: {e}")
# Fallback: try direct call
try:
response = str(self.llm.invoke(prompt))
except:
response = f"Error: Unable to get LLM response for: {question}"
print(f" LLM Response: {response[:200]}...")
# Check for tool call
tool_call = self.tool_executor.detect_tool_call(response)
if tool_call:
tool_name, arguments = tool_call
print(f" π§ Executing: {tool_name}({arguments})")
# Execute tool
tool_result = self.tool_executor.execute(tool_name, arguments)
print(f" β
Tool Result: {tool_result}")
# Synthesize final answer
synthesis_prompt = f"""Based on this tool result, provide a clear answer to: {question}
Tool used: {tool_name}
Tool result: {tool_result}
Provide a direct, concise answer."""
try:
if hasattr(self.llm, 'invoke'):
answer_obj = self.llm.invoke([HumanMessage(content=synthesis_prompt)])
answer = answer_obj.content if hasattr(answer_obj, 'content') else str(answer_obj)
else:
answer = self.llm(synthesis_prompt)
except:
answer = f"The answer is: {tool_result}"
sources = [tool_name]
else:
# No tool needed, use LLM knowledge
answer = response
sources = ["LLM Knowledge"]
# Create research output
research_output = ResearchOutput(
answer=answer.strip(),
sources_used=sources,
confidence=0.9 if tool_call else 0.7
)
state["research_output"] = research_output
state["current_step"] = "research_complete"
print(f" β
Answer: {answer[:100]}...")
return state
class AnalystAgent:
"""Analyzes research"""
def __init__(self, llm):
self.llm = llm
def __call__(self, state: AgentState) -> AgentState:
"""Analysis node"""
print("\nπ ANALYST AGENT")
research = state["research_output"]
prompt = f"""Analyze this answer and extract key insights.
Question: {state['question']}
Answer: {research.answer}
Provide your analysis in JSON format:
{{
"key_points": ["point 1", "point 2"],
"implications": "why this matters"
}}
Analysis:"""
try:
if hasattr(self.llm, 'invoke'):
response_obj = self.llm.invoke([HumanMessage(content=prompt)])
response = response_obj.content if hasattr(response_obj, 'content') else str(response_obj)
else:
response = self.llm(prompt)
except Exception as e:
print(f" β οΈ LLM error: {e}")
response = '{"key_points": ["Analysis unavailable"], "implications": "Direct answer provided"}'
# Parse with fallback
fallback = {
"key_points": [research.answer[:100]],
"implications": "Direct answer provided"
}
analysis_output = safe_parse_pydantic(response, AnalysisOutput, fallback)
state["analysis_output"] = analysis_output
state["current_step"] = "analysis_complete"
print(f" β
Extracted {len(analysis_output.key_points)} key points")
return state
class WriterAgent:
"""Creates reports"""
def __init__(self, llm):
self.llm = llm
def __call__(self, state: AgentState) -> AgentState:
"""Writing node"""
print(f"\nβοΈ WRITER AGENT (Iteration {state['report_iterations'] + 1})")
research = state["research_output"]
analysis = state["analysis_output"]
prompt = f"""Write a clear, professional report.
Question: {state['question']}
Answer: {research.answer}
Key Points: {', '.join(analysis.key_points)}
Create a report in JSON format:
{{
"title": "descriptive title",
"content": "detailed explanation with the answer and key points"
}}
Report:"""
try:
if hasattr(self.llm, 'invoke'):
response_obj = self.llm.invoke([HumanMessage(content=prompt)])
response = response_obj.content if hasattr(response_obj, 'content') else str(response_obj)
else:
response = self.llm(prompt)
except Exception as e:
print(f" β οΈ LLM error: {e}")
response = ""
# Parse with fallback
fallback = {
"title": state['question'],
"content": f"Question: {state['question']}\n\nAnswer: {research.answer}\n\nKey Points:\n" + "\n".join(f"β’ {point}" for point in analysis.key_points)
}
report_output = safe_parse_pydantic(response, ReportOutput, fallback)
state["report_output"] = report_output
state["report_iterations"] += 1
state["current_step"] = "report_complete"
print(f" β
Report created: {len(report_output.content)} chars")
return state
class CriticAgent:
"""Reviews reports"""
def __init__(self, llm):
self.llm = llm
def __call__(self, state: AgentState) -> AgentState:
"""Critique node"""
print("\nπ― CRITIC AGENT")
report = state["report_output"]
# Simple heuristic-based scoring for reliability
score = 8.0
# Check if answer is in content
if state["research_output"].answer.lower() in report.content.lower():
score += 1.0
# Check content length
if len(report.content) > 100:
score += 0.5
# Penalize first iteration slightly to allow one revision
if state["report_iterations"] == 1:
score -= 1.0
score = min(10.0, max(0.0, score))
needs_revision = (
score < 8.0 and
state["report_iterations"] < state["max_iterations"]
)
critique_output = CritiqueOutput(
score=score,
needs_revision=needs_revision
)
state["critique_output"] = critique_output
state["current_step"] = "critique_complete"
print(f" β
Score: {score}/10 | Revision needed: {needs_revision}")
return state
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 8. CONDITIONAL ROUTING
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def route_critique(state: AgentState) -> Literal["revise", "finish"]:
"""Route from critic"""
critique = state["critique_output"]
if critique.needs_revision:
print(f"\nπ Revision needed (Score: {critique.score}/10)")
return "revise"
else:
print(f"\nβ
Report approved (Score: {critique.score}/10)")
return "finish"
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 9. MAIN SYSTEM
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class MultiAgentSystem:
"""Multi-agent system compatible with HuggingFace models"""
def __init__(self, token: str, max_iterations: int = 2):
self.max_iterations = max_iterations
print("\n" + "="*70)
print("π€ INITIALIZING MULTI-AGENT SYSTEM (HUGGINGFACE COMPATIBLE)")
print("="*70)
# Create tools and executor
tools = [calculator, search_knowledge]
self.tool_executor = ToolExecutor(tools)
print(f"π οΈ Loaded {len(tools)} tools: {[t.name for t in tools]}")
# Create LLM
print("π‘ Creating LLM...")
self.llm = LLMFactory.create_llm(token)
print(" β
LLM ready")
# Initialize agents
print("π€ Initializing agents...")
self.researcher = ResearcherAgent(self.llm, self.tool_executor)
self.analyst = AnalystAgent(self.llm)
self.writer = WriterAgent(self.llm)
self.critic = CriticAgent(self.llm)
print(" β
All agents ready")
# Build graph
print("π Building workflow...")
self.graph = self._build_graph()
print(" β
Graph compiled")
print("\nβ
System ready!\n")
def _build_graph(self) -> StateGraph:
"""Build the workflow graph"""
workflow = StateGraph(AgentState)
# Add nodes
workflow.add_node("researcher", self.researcher)
workflow.add_node("analyst", self.analyst)
workflow.add_node("writer", self.writer)
workflow.add_node("critic", self.critic)
# Set entry point
workflow.set_entry_point("researcher")
# Add edges
workflow.add_edge("researcher", "analyst")
workflow.add_edge("analyst", "writer")
workflow.add_edge("writer", "critic")
# Conditional edge from critic
workflow.add_conditional_edges(
"critic",
route_critique,
{
"revise": "writer",
"finish": END
}
)
return workflow.compile()
def research(self, question: str) -> dict:
"""Execute research workflow"""
print("="*70)
print(f"π QUESTION: {question}")
print("="*70)
initial_state = AgentState(
question=question,
research_output=None,
analysis_output=None,
report_output=None,
critique_output=None,
report_iterations=0,
max_iterations=self.max_iterations,
current_step="start"
)
try:
final_state = self.graph.invoke(initial_state)
print("\n" + "="*70)
print("β
WORKFLOW COMPLETE")
print("="*70)
if final_state.get("critique_output"):
print(f"Final score: {final_state['critique_output'].score}/10")
return final_state
except Exception as e:
print(f"\nβ Error: {e}")
import traceback
traceback.print_exc()
return None
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 10. CLI INTERFACE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def cli_demo():
"""Command-line demo"""
print("""
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MULTI-AGENT SYSTEM β
β Manual tool calling + JSON parsing with fallbacks β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
""")
token = input("Enter your Hugging Face token: ").strip()
if not token:
print("β Token required!")
return
try:
system = MultiAgentSystem(token=token, max_iterations=2)
except Exception as e:
print(f"β Initialization failed: {e}")
import traceback
traceback.print_exc()
return
print("\nπ‘ Try questions like:")
print(" β’ what is 2+2")
print(" β’ calculate (15*3)+7")
print(" β’ what is artificial intelligence")
print(" β’ what is machine learning")
while True:
print("\n" + "="*70)
question = input("\nπ€ Enter question (or 'quit'): ").strip()
if question.lower() in ['quit', 'exit', 'q']:
print("\nπ Goodbye!")
break
if not question:
continue
final_state = system.research(question)
if final_state and final_state.get("report_output"):
print("\n" + "="*70)
print("π FINAL REPORT")
print("="*70)
report = final_state["report_output"]
print(f"\nπ {report.title}")
print(f"\n{report.content}")
print("\n" + "="*70)
print("π― QUALITY SCORE")
print("="*70)
critique = final_state["critique_output"]
print(f"Score: {critique.score}/10")
if __name__ == "__main__":
cli_demo() |