Skip to content

Add Intelligent Cognitive Agent Python Script #698

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

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions examples/python/tools/exa-tool/chile_government_services_assistant_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# # -*- coding: utf-8 -*-
# """Chile_Government_Services_Assistant .ipynb

# Automatically generated by Colab.

# Original file is located at
# https://colab.research.google.com/drive/13IOn2Vhg0EUwuIGpVilImW0rEpYYMoFQ

# # Chile Government Services Assistant - AI Chatbot

# This notebook demonstrates how to use an AI-powered assistant to answer questions about Chilean government services and procedures, using the Firecrawl API and a friendly, step-by-step conversational approach.

# [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhivyaBharathy-web/PraisonAI/blob/main/examples/cookbooks/Chile_Government_Services_Assistant.ipynb)

# # Install dependencies
# """

# !pip install flask firecrawl praisonaiagents google-genai python-dotenv deep-translator

# """# Set API Keys"""

import os

os.environ['FIRECRAWL_API_KEY'] = "your api key here"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

Consider using a more secure method for handling API keys, such as storing them in a dedicated secrets management system or using environment variables with restricted access. Hardcoding API keys directly in the script poses a security risk if the code is exposed. This is a critical issue.

Suggested change
os.environ['FIRECRAWL_API_KEY'] = "your api key here"
# Use a more secure method to load API keys
# For example, using python-dotenv and loading from a .env file
# from dotenv import load_dotenv
# load_dotenv()
# os.environ['FIRECRAWL_API_KEY'] = os.getenv('FIRECRAWL_API_KEY')
os.environ['FIRECRAWL_API_KEY'] = "your api key here"

os.environ['OPENAI_API_KEY'] = "your api key here"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

Consider using a more secure method for handling API keys, such as storing them in a dedicated secrets management system or using environment variables with restricted access. Hardcoding API keys directly in the script poses a security risk if the code is exposed. This is a critical issue.

Suggested change
os.environ['OPENAI_API_KEY'] = "your api key here"
# Use a more secure method to load API keys
# For example, using python-dotenv and loading from a .env file
# from dotenv import load_dotenv
# load_dotenv()
# os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')
os.environ['OPENAI_API_KEY'] = "your api key here"

Comment on lines +24 to +25
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Replace placeholder API keys with proper configuration.

The hardcoded placeholders will cause authentication failures.

-os.environ['FIRECRAWL_API_KEY'] = "your api key here"
-os.environ['OPENAI_API_KEY'] = "your api key here"
+os.environ['FIRECRAWL_API_KEY'] = os.getenv('FIRECRAWL_API_KEY') or input("Enter your Firecrawl API key: ").strip()
+os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY') or input("Enter your OpenAI API key: ").strip()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
os.environ['FIRECRAWL_API_KEY'] = "your api key here"
os.environ['OPENAI_API_KEY'] = "your api key here"
os.environ['FIRECRAWL_API_KEY'] = os.getenv('FIRECRAWL_API_KEY') or input("Enter your Firecrawl API key: ").strip()
os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY') or input("Enter your OpenAI API key: ").strip()
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/chile_government_services_assistant_.py at
lines 24 to 25, replace the hardcoded placeholder API key strings with a secure
method to load the actual API keys, such as reading from environment variables
or a configuration file, to avoid authentication failures.


# """# Import Libraries & Translator"""

from firecrawl import FirecrawlApp, ScrapeOptions
from deep_translator import GoogleTranslator
import re

def translate_to_spanish(text):
try:
return GoogleTranslator(source='auto', target='es').translate(text)
except Exception as e:
print("Translation to Spanish failed:", e)
return text

def translate_to_english(text):
try:
# Remove Markdown images and None values before translation
text = str(text).replace("None", "")
text = re.sub(r'!\[.*?\]\(.*?\)', '', text)
return GoogleTranslator(source='auto', target='en').translate(text)
except Exception as e:
print("Translation to English failed:", e)
return text

# """# Firecrawl Tool Class"""

class FirecrawlTool:
def __init__(self, api_key, instruction: str, template: str):
if not api_key:
raise ValueError("Firecrawl API key not provided.")
self.app = FirecrawlApp(api_key=api_key)
self.instruction = instruction
self.template = template

def search(self, search: str) -> str:
if not search or len(search) < 5:
return "Error: Please provide a valid search query (at least 5 characters)."
response_md = ""
try:
search_result = self.app.search(
query=self.instruction + search,
limit=2,
country="cl",
lang="es", # Always search in Spanish for best results
scrape_options=ScrapeOptions(formats=["markdown", "links"])
)
if search_result and hasattr(search_result, 'data') and search_result.data:
filtered_results = [
result for result in search_result.data
if str(result.get("url", "")).startswith("https://www.chileatiende.gob.cl/fichas") and not str(result.get("url", "")).endswith("pdf")
]
if filtered_results:
for num, result in enumerate(filtered_results, start=1):
response_md += self.template.format(
result_number=num,
page_title=str(result.get("title", "")),
page_url=str(result.get("url", "")),
page_content=str(result.get("markdown", ""))
)
return response_md
else:
return None
else:
return None
except Exception as e:
return f"Error during search: {e}"

# """# Firecrawl Prompt Template"""

# FIRECRAWL_INSTRUCTION = "ChileAtiende: "
# FIRECRAWL_TEMPLATE = """
# # Result {result_number}

# ## Page Name:
# "{page_title}"

# ## URL:
# {page_url}

# ## Content:
# {page_content}

# """
Comment on lines +95 to +108
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix undefined variable references.

The code references FIRECRAWL_INSTRUCTION and FIRECRAWL_TEMPLATE variables that are commented out, causing runtime errors.

-# FIRECRAWL_INSTRUCTION = "ChileAtiende: "
-# FIRECRAWL_TEMPLATE = """
-# # Result {result_number}
-# 
-# ## Page Name:
-# "{page_title}"
-# 
-# ## URL:
-# {page_url}
-# 
-# ## Content:
-# {page_content}
-# 
-# """
+FIRECRAWL_INSTRUCTION = "ChileAtiende: "
+FIRECRAWL_TEMPLATE = """
+# Result {result_number}
+
+## Page Name:
+"{page_title}"
+
+## URL:
+{page_url}
+
+## Content:
+{page_content}
+
+"""

Also applies to: 114-115

🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/chile_government_services_assistant_.py around
lines 95 to 108 and also lines 114 to 115, the variables FIRECRAWL_INSTRUCTION
and FIRECRAWL_TEMPLATE are referenced but currently commented out, causing
undefined variable errors. To fix this, uncomment the definitions of
FIRECRAWL_INSTRUCTION and FIRECRAWL_TEMPLATE so they are properly defined before
use.


# """# Initialize Firecrawl Tool"""

firecrawl_tool = FirecrawlTool(
api_key=os.environ['FIRECRAWL_API_KEY'],
instruction=FIRECRAWL_INSTRUCTION,
template=FIRECRAWL_TEMPLATE
)

# """# Main Chat Loop"""

print("Hello! I am your ChileAtiende assistant, Tomás. How can I help you today?")
print("You can ask me, for example: How to renew your ID card, How to apply for the Winter Bonus, etc.")

while True:
user_input = input("\nYou: ")
if user_input.lower() in ["exit", "quit"]:
print("Tomás: It was a pleasure to help you. Goodbye!")
break

# Translate English input to Spanish for Firecrawl
spanish_query = translate_to_spanish(user_input)
spanish_answer = firecrawl_tool.search(spanish_query)

# Only translate if we got a real answer
if spanish_answer and isinstance(spanish_answer, str) and spanish_answer.strip() and "Error" not in spanish_answer:
try:
english_answer = translate_to_english(spanish_answer)
print("\nTomás (in English):\n", english_answer)
except Exception as e:
print(f"\nTomás: I found information, but couldn't translate it. Here it is in Spanish:\n{spanish_answer}\n(Translation error: {e})")
else:
print("\nTomás: Sorry, I couldn't find relevant information. Try rephrasing your question or ask about another service.")
81 changes: 81 additions & 0 deletions examples/python/tools/exa-tool/intelligent_cognitive_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# # -*- coding: utf-8 -*-
# """Intelligent_Cognitive_Agent.ipynb

# Automatically generated by Colab.

# Original file is located at
# https://colab.research.google.com/drive/1UssW8MZyZpMX6oVjhqn4O6euxLLIVgGM

# # 🧠 Cognitive Assistant Agent Team (PraisonAI)

# This notebook demonstrates a multi-specialist cognitive assistant using PraisonAI, with each specialist as a tool.

# [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhivyaBharathy-web/PraisonAI/blob/main/examples/cookbooks/Intelligent_Cognitive_Agent.ipynb)

# # Install Dependencies
# """

# !pip install praisonaiagents

# """# Set API Key"""

import os

# Set your OpenAI or OpenRouter API key for PraisonAI
os.environ['OPENAI_API_KEY'] = 'Enter your api key' # <-- Replace with your actual OpenAI or OpenRouter API key
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

Consider using a more secure method for handling API keys, such as storing them in a dedicated secrets management system or using environment variables with restricted access. Hardcoding API keys directly in the script poses a security risk if the code is exposed. This is a critical issue.

Suggested change
os.environ['OPENAI_API_KEY'] = 'Enter your api key' # <-- Replace with your actual OpenAI or OpenRouter API key
# Use a more secure method to load API keys
# For example, using python-dotenv and loading from a .env file
# from dotenv import load_dotenv
# load_dotenv()
# os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')
os.environ['OPENAI_API_KEY'] = 'Enter your api key' # <-- Replace with your actual OpenAI or OpenRouter API key

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Security risk: Remove hardcoded API key placeholder.

The hardcoded placeholder API key should be removed to prevent accidental exposure of real credentials.

Apply this diff to use proper environment variable handling:

-os.environ['OPENAI_API_KEY'] = 'Enter your api key'  # <-- Replace with your actual OpenAI or OpenRouter API key
+# Ensure your OPENAI_API_KEY environment variable is set
+if not os.environ.get('OPENAI_API_KEY'):
+    raise ValueError("OPENAI_API_KEY environment variable must be set")
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/intelligent_cognitive_agent.py at line 25,
remove the hardcoded placeholder API key assignment to os.environ. Instead,
ensure the code reads the API key from the environment variables set outside the
code, such as by using os.getenv('OPENAI_API_KEY'), to avoid embedding sensitive
information directly in the source code.


"""# Imports and Specialist Agent Definitions"""

import re
from praisonaiagents import Agent
Comment on lines +22 to +30
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Fix import organization and formatting issues.

The imports should be organized at the top of the file, and proper spacing should be maintained according to PEP 8.

Apply this diff to fix the import organization:

-import os
-
-# Set your OpenAI or OpenRouter API key for PraisonAI
-os.environ['OPENAI_API_KEY'] = 'Enter your api key'  # <-- Replace with your actual OpenAI or OpenRouter API key
-
-"""# Imports and Specialist Agent Definitions"""
-
-import re
-from praisonaiagents import Agent
+import os
+import re
+from praisonaiagents import Agent
+
+
+# Ensure your OPENAI_API_KEY environment variable is set
+if not os.environ.get('OPENAI_API_KEY'):
+    raise ValueError("OPENAI_API_KEY environment variable must be set")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import os
# Set your OpenAI or OpenRouter API key for PraisonAI
os.environ['OPENAI_API_KEY'] = 'Enter your api key' # <-- Replace with your actual OpenAI or OpenRouter API key
"""# Imports and Specialist Agent Definitions"""
import re
from praisonaiagents import Agent
import os
import re
from praisonaiagents import Agent
# Ensure your OPENAI_API_KEY environment variable is set
if not os.environ.get('OPENAI_API_KEY'):
raise ValueError("OPENAI_API_KEY environment variable must be set")
🧰 Tools
🪛 Flake8 (7.2.0)

[error] 29-29: module level import not at top of file

(E402)


[error] 30-30: module level import not at top of file

(E402)

🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/intelligent_cognitive_agent.py around lines 22
to 30, the import statements are not properly organized and spaced. Move all
import statements to the top of the file before any other code, group standard
library imports separately from third-party imports, and ensure there is a blank
line between different import groups to comply with PEP 8 formatting guidelines.


# Dummy specialist agent classes for demonstration.
# Replace these with your actual specialist agent logic if needed.
class SpecialistAgent:
def __init__(self, name):
self.name = name
def run(self, query):
return f"{self.name} specialist response to: {query}"

Comment on lines +34 to +39
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance the SpecialistAgent class with proper documentation and structure.

The current implementation is too simplistic and lacks proper documentation. Consider making it more aligned with PraisonAI patterns.

Apply this diff to improve the class:

-class SpecialistAgent:
-    def __init__(self, name):
-        self.name = name
-    def run(self, query):
-        return f"{self.name} specialist response to: {query}"
+class SpecialistAgent:
+    """A specialist agent representing a specific cognitive domain."""
+    
+    def __init__(self, name: str, domain: str = ""):
+        self.name = name
+        self.domain = domain or name.replace('_', ' ').title()
+    
+    def run(self, query: str) -> str:
+        """Process a query within this specialist's domain."""
+        return f"{self.domain} specialist analysis: {query}"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
class SpecialistAgent:
def __init__(self, name):
self.name = name
def run(self, query):
return f"{self.name} specialist response to: {query}"
class SpecialistAgent:
"""A specialist agent representing a specific cognitive domain."""
def __init__(self, name: str, domain: str = ""):
self.name = name
self.domain = domain or name.replace('_', ' ').title()
def run(self, query: str) -> str:
"""Process a query within this specialist's domain."""
return f"{self.domain} specialist analysis: {query}"
🧰 Tools
🪛 Flake8 (7.2.0)

[error] 34-34: expected 2 blank lines, found 1

(E302)


[error] 37-37: expected 1 blank line, found 0

(E301)

🪛 Pylint (3.3.7)

[refactor] 34-34: Too few public methods (1/2)

(R0903)

🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/intelligent_cognitive_agent.py around lines 34
to 39, the SpecialistAgent class lacks proper documentation and structure. Add a
class-level docstring explaining the purpose of the class, and include
method-level docstrings for __init__ and run methods describing their parameters
and return values. Refactor the class to follow PraisonAI patterns by ensuring
clear separation of concerns and possibly adding type hints for better clarity
and maintainability.

# Instantiate all specialist agents (replace with your real classes if available)
specialists = [
SpecialistAgent("decision_risk_agent"),
SpecialistAgent("problem_solving_innovation_agent"),
SpecialistAgent("Systems___Complexity_Agent"),
SpecialistAgent("bias_psychology_agent"),
SpecialistAgent("Strategy___Competition_Agent"),
SpecialistAgent("Learning___Communication_Agent"),
SpecialistAgent("Efficiency___Process_Agent"),
SpecialistAgent("motivation_human_factors_agent"),
]

"""# Tool Wrapping and Agent Setup"""

def make_tool(agent):
def tool(query: str):
return agent.run(query)
# Sanitize the tool name to match PraisonAI's requirements
safe_name = re.sub(r'[^a-zA-Z0-9_-]', '_', agent.name or "tool")
tool.__name__ = safe_name
return tool

Comment on lines +54 to +61
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve tool creation to follow PraisonAI best practices.

The tool creation function should include proper documentation and error handling, and ideally use the @tool decorator pattern.

Based on the retrieved learnings about PraisonAI tool implementation, consider this improved approach:

-def make_tool(agent):
-    def tool(query: str):
-        return agent.run(query)
-    # Sanitize the tool name to match PraisonAI's requirements
-    safe_name = re.sub(r'[^a-zA-Z0-9_-]', '_', agent.name or "tool")
-    tool.__name__ = safe_name
-    return tool
+def make_tool(agent: SpecialistAgent):
+    """Create a tool function from a specialist agent."""
+    def tool(query: str) -> str:
+        """Tool function that processes queries through the specialist agent."""
+        try:
+            return agent.run(query)
+        except Exception as e:
+            return f"Error in {agent.name}: {str(e)}"
+    
+    # Sanitize the tool name to match PraisonAI's requirements
+    safe_name = re.sub(r'[^a-zA-Z0-9_-]', '_', agent.name or "tool")
+    tool.__name__ = safe_name
+    tool.__doc__ = f"Specialist tool for {agent.domain}"
+    return tool
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def make_tool(agent):
def tool(query: str):
return agent.run(query)
# Sanitize the tool name to match PraisonAI's requirements
safe_name = re.sub(r'[^a-zA-Z0-9_-]', '_', agent.name or "tool")
tool.__name__ = safe_name
return tool
def make_tool(agent: SpecialistAgent):
"""Create a tool function from a specialist agent."""
def tool(query: str) -> str:
"""Tool function that processes queries through the specialist agent."""
try:
return agent.run(query)
except Exception as e:
return f"Error in {agent.name}: {str(e)}"
# Sanitize the tool name to match PraisonAI's requirements
safe_name = re.sub(r'[^a-zA-Z0-9_-]', '_', agent.name or "tool")
tool.__name__ = safe_name
tool.__doc__ = f"Specialist tool for {agent.domain}"
return tool
🧰 Tools
🪛 Flake8 (7.2.0)

[error] 54-54: expected 2 blank lines, found 1

(E302)

🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/intelligent_cognitive_agent.py around lines 54
to 61, improve the make_tool function by adding a proper docstring explaining
its purpose and usage, wrapping the inner tool function with a try-except block
to handle and log errors gracefully, and applying the @tool decorator from
PraisonAI if available to ensure compliance with best practices. This will
enhance maintainability, error resilience, and integration with PraisonAI's
tooling system.

tools = [make_tool(agent) for agent in specialists]

agent = Agent(
instructions="""
You are a cognitive assistant with access to a set of specialist tools (decision making, problem solving, systems thinking, psychology, strategy, learning, efficiency, motivation).
Use the most relevant tool(s) to answer the user's query.
""",
tools=tools,
)
Comment on lines +64 to +70
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance Agent configuration with comprehensive PraisonAI parameters.

Based on the retrieved learnings, the Agent should include more comprehensive configuration parameters for better functionality.

Apply this diff to improve the agent configuration:

-agent = Agent(
-    instructions="""
-        You are a cognitive assistant with access to a set of specialist tools (decision making, problem solving, systems thinking, psychology, strategy, learning, efficiency, motivation).
-        Use the most relevant tool(s) to answer the user's query.
-    """,
-    tools=tools,
-)
+agent = Agent(
+    name="Cognitive Assistant",
+    role="Multi-domain cognitive advisor",
+    goal="Provide comprehensive cognitive assistance by leveraging specialist tools",
+    backstory="""You are an intelligent cognitive assistant with access to multiple 
+    specialist domains including decision making, problem solving, systems thinking, 
+    psychology, strategy, learning, efficiency, and motivation. You carefully select 
+    and combine insights from the most relevant specialists to provide comprehensive answers.""",
+    instructions="""
+        You are a cognitive assistant with access to specialist tools covering:
+        - Decision making and risk assessment
+        - Problem solving and innovation
+        - Systems thinking and complexity analysis
+        - Psychology and bias awareness
+        - Strategy and competition
+        - Learning and communication
+        - Efficiency and process optimization
+        - Motivation and human factors
+        
+        Use the most relevant tool(s) to answer the user's query, and synthesize 
+        insights from multiple specialists when appropriate.
+    """,
+    tools=tools,
+    max_iter=3,
+    verbose=True,
+)
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/intelligent_cognitive_agent.py around lines 64
to 70, the Agent initialization lacks comprehensive configuration parameters for
PraisonAI. Enhance the Agent constructor by adding additional relevant
parameters such as model settings, memory configuration, or any other
recommended PraisonAI options to improve its functionality and responsiveness.
Review PraisonAI documentation or examples to identify and include these
parameters appropriately within the Agent initialization.


# """# User Query and Agent Response"""

user_query = input("Ask your question (or type 'quit' to exit): ")
while user_query.lower() != 'quit':
print("\n--- Thinking ---")
response = agent.start(user_query)
print(response)
print("\n---------------")
user_query = input("Ask your question (or type 'quit' to exit): ")
print("Cognitive Assistant Agent Team - Finished.")
Comment on lines +74 to +81
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling and improve the interactive loop.

The current interactive loop lacks error handling and could be more robust.

Apply this diff to improve the interactive loop:

-user_query = input("Ask your question (or type 'quit' to exit): ")
-while user_query.lower() != 'quit':
-    print("\n--- Thinking ---")
-    response = agent.start(user_query)
-    print(response)
-    print("\n---------------")
-    user_query = input("Ask your question (or type 'quit' to exit): ")
-print("Cognitive Assistant Agent Team - Finished.")
+def main():
+    """Main interactive loop for the cognitive assistant."""
+    print("🧠 Cognitive Assistant Agent Team")
+    print("Available domains: Decision Making, Problem Solving, Systems Thinking,")
+    print("Psychology, Strategy, Learning, Efficiency, Motivation")
+    print("Type 'quit' to exit.\n")
+    
+    while True:
+        try:
+            user_query = input("Ask your question: ").strip()
+            if user_query.lower() in ['quit', 'exit']:
+                break
+            if not user_query:
+                continue
+                
+            print("\n🤔 Analyzing your question...")
+            response = agent.start(user_query)
+            print(f"\n💡 Response:\n{response}")
+            print("\n" + "="*50 + "\n")
+            
+        except KeyboardInterrupt:
+            print("\n\nGoodbye!")
+            break
+        except Exception as e:
+            print(f"❌ Error: {str(e)}")
+            print("Please try again.\n")
+    
+    print("Cognitive Assistant Agent Team - Finished.")
+
+
+if __name__ == "__main__":
+    main()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
user_query = input("Ask your question (or type 'quit' to exit): ")
while user_query.lower() != 'quit':
print("\n--- Thinking ---")
response = agent.start(user_query)
print(response)
print("\n---------------")
user_query = input("Ask your question (or type 'quit' to exit): ")
print("Cognitive Assistant Agent Team - Finished.")
def main():
"""Main interactive loop for the cognitive assistant."""
print("🧠 Cognitive Assistant Agent Team")
print("Available domains: Decision Making, Problem Solving, Systems Thinking,")
print("Psychology, Strategy, Learning, Efficiency, Motivation")
print("Type 'quit' to exit.\n")
while True:
try:
user_query = input("Ask your question: ").strip()
if user_query.lower() in ['quit', 'exit']:
break
if not user_query:
continue
print("\n🤔 Analyzing your question...")
response = agent.start(user_query)
print(f"\n💡 Response:\n{response}")
print("\n" + "="*50 + "\n")
except KeyboardInterrupt:
print("\n\nGoodbye!")
break
except Exception as e:
print(f"❌ Error: {str(e)}")
print("Please try again.\n")
print("Cognitive Assistant Agent Team - Finished.")
if __name__ == "__main__":
main()
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/intelligent_cognitive_agent.py around lines 74
to 81, the interactive loop lacks error handling which can cause the program to
crash unexpectedly. Wrap the loop content in a try-except block to catch
exceptions during agent.start or input operations, print a user-friendly error
message, and continue the loop. Also, handle KeyboardInterrupt to allow graceful
exit when the user presses Ctrl+C. This will make the interactive session more
robust and user-friendly.

Loading
Loading