-
-
Notifications
You must be signed in to change notification settings - Fork 689
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
base: main
Are you sure you want to change the base?
Changes from all commits
0f2dc2b
cf4229a
5a57b4c
dea4a7f
7662077
ad70771
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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. | ||||||||||||||||||||||||
|
||||||||||||||||||||||||
# [](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" | ||||||||||||||||||||||||
os.environ['OPENAI_API_KEY'] = "your api key here" | ||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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
Suggested change
Comment on lines
+24
to
+25
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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
Suggested change
🤖 Prompt for AI Agents
|
||||||||||||||||||||||||
|
||||||||||||||||||||||||
# """# 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix undefined variable references. The code references -# 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
|
||||||||||||||||||||||||
|
||||||||||||||||||||||||
# """# 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.") |
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. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# [](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 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"""# Imports and Specialist Agent Definitions""" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
import re | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
from praisonaiagents import Agent | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Comment on lines
+22
to
+30
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Suggested change
🧰 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
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Suggested change
🧰 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
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Suggested change
🧰 Tools🪛 Flake8 (7.2.0)[error] 54-54: expected 2 blank lines, found 1 (E302) 🤖 Prompt for AI Agents
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# """# 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Suggested change
🤖 Prompt for AI Agents
|
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.
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.