-
Notifications
You must be signed in to change notification settings - Fork 114
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Streaming and Agent Routing using langgraph #213
Merged
+784
−245
Merged
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
609a8eb
Q&A streaminh
dhirenmathur 1e41250
streaming for all agents
dhirenmathur 3c05de4
supervisour routing
dhirenmathur ade7591
update classifier prompt
dhirenmathur b280503
pre-commit
dhirenmathur 5f428d6
pre-commit
dhirenmathur File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
111 changes: 111 additions & 0 deletions
111
app/modules/intelligence/agents/agents/callback_handler.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
import os | ||
from datetime import datetime | ||
import json | ||
from typing import Any, Dict, List, Optional, Tuple, Union | ||
from crewai.agents.parser import AgentAction | ||
|
||
class FileCallbackHandler: | ||
def __init__(self, filename: str = "agent_execution_log.md"): | ||
"""Initialize the file callback handler. | ||
|
||
Args: | ||
filename (str): The markdown file to write the logs to | ||
""" | ||
self.filename = filename | ||
# Create or clear the file initially | ||
with open(self.filename, 'w', encoding='utf-8') as f: | ||
f.write(f"# Agent Execution Log\nStarted at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n") | ||
|
||
def __call__(self, step_output: Union[str, List[Tuple[Dict[str, Any], str]], AgentAction]) -> None: | ||
"""Callback function to handle agent execution steps. | ||
|
||
Args: | ||
step_output: Output from the agent's execution step. Can be: | ||
- string | ||
- list of (action, observation) tuples | ||
- AgentAction from CrewAI | ||
""" | ||
with open(self.filename, 'a', encoding='utf-8') as f: | ||
f.write(f"\n## Step - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") | ||
f.write("---\n") | ||
|
||
# Handle AgentAction output | ||
if isinstance(step_output, AgentAction): | ||
# Write thought section | ||
if hasattr(step_output, 'thought') and step_output.thought: | ||
f.write("### Thought\n") | ||
f.write(f"{step_output.thought}\n\n") | ||
|
||
# Write tool section | ||
if hasattr(step_output, 'tool'): | ||
f.write("### Action\n") | ||
f.write(f"**Tool:** {step_output.tool}\n") | ||
|
||
# if hasattr(step_output, 'tool_input'): | ||
# try: | ||
# # Try to parse and pretty print JSON input | ||
# tool_input = json.loads(step_output.tool_input) | ||
# formatted_input = json.dumps(tool_input, indent=2) | ||
# f.write(f"**Input:**\n```json\n{formatted_input}\n```\n") | ||
# except (json.JSONDecodeError, TypeError): | ||
# # Fallback to raw string if not JSON | ||
# f.write(f"**Input:**\n```\n{step_output.tool_input}\n```\n") | ||
|
||
# # Write result section | ||
# if hasattr(step_output, 'result'): | ||
# f.write("\n### Result\n") | ||
# try: | ||
# # Try to parse and pretty print JSON result | ||
# result = json.loads(step_output.result) | ||
# formatted_result = json.dumps(result, indent=2) | ||
# f.write(f"```json\n{formatted_result}\n```\n") | ||
# except (json.JSONDecodeError, TypeError): | ||
# # Fallback to raw string if not JSON | ||
# f.write(f"```\n{step_output.result}\n```\n") | ||
|
||
f.write("\n") | ||
return | ||
|
||
# Handle single string output | ||
if isinstance(step_output, str): | ||
f.write(step_output + "\n") | ||
return | ||
|
||
for step in step_output: | ||
if not isinstance(step, tuple): | ||
f.write(str(step) + "\n") | ||
continue | ||
|
||
action, observation = step | ||
|
||
# Handle action section | ||
f.write("### Action\n") | ||
if isinstance(action, dict): | ||
if "tool" in action: | ||
f.write(f"**Tool:** {action['tool']}\n") | ||
if "tool_input" in action: | ||
f.write(f"**Input:**\n```\n{action['tool_input']}\n```\n") | ||
if "log" in action: | ||
f.write(f"**Log:** {action['log']}\n") | ||
if "Action" in action: | ||
f.write(f"**Action Type:** {action['Action']}\n") | ||
else: | ||
f.write(f"{str(action)}\n") | ||
|
||
# Handle observation section | ||
f.write("\n### Observation\n") | ||
if isinstance(observation, str): | ||
# Handle special formatting for search-like results | ||
lines = observation.split('\n') | ||
for line in lines: | ||
if line.startswith(('Title:', 'Link:', 'Snippet:')): | ||
key, value = line.split(':', 1) | ||
f.write(f"**{key.strip()}:**{value}\n") | ||
elif line.startswith('-'): | ||
f.write(line + "\n") | ||
else: | ||
f.write(line + "\n") | ||
else: | ||
f.write(str(observation) + "\n") | ||
|
||
f.write("\n") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Remove unused imports to improve clarity.
The static analysis hints correctly highlight that 'typing.Any', 'typing.Optional', and 'typing.Annotated' are not used in this file. Consider removing them.
Here is a suggested diff:
📝 Committable suggestion
🧰 Tools
🪛 Ruff (0.8.2)
5-5:
typing.Any
imported but unusedRemove unused import
(F401)
5-5:
typing.Optional
imported but unusedRemove unused import
(F401)
6-6:
typing.Annotated
imported but unusedRemove unused import:
typing.Annotated
(F401)