-
-
Notifications
You must be signed in to change notification settings - Fork 692
Add Real Estate Chatbot Python Script #694
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
Add Real Estate Chatbot Python Script #694
Conversation
Warning Rate limit exceeded@Dhivya-Bharathy has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 30 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (3)
WalkthroughFour new Python scripts are introduced, each implementing an AI-powered assistant for distinct domains: Chilean government services, a mini court trial simulation, cybersecurity PoC validation, and real estate chat. Each script defines relevant classes and functions, sets up API integrations, and provides interactive interfaces tailored to their respective use cases. Changes
Sequence Diagram(s)Chilean Government Services AssistantsequenceDiagram
participant User
participant Assistant (Tomás)
participant Firecrawl API
participant GoogleTranslator
User->>Assistant (Tomás): Enter query
Assistant (Tomás)->>GoogleTranslator: Translate query to Spanish
Assistant (Tomás)->>Firecrawl API: Search ChileAtiende with Spanish query
Firecrawl API-->>Assistant (Tomás): Return search results
Assistant (Tomás)->>GoogleTranslator: Translate results to English
Assistant (Tomás)-->>User: Display formatted response
LegaliaAI Mini CourtsequenceDiagram
participant User
participant Judge
participant Prosecutor
participant Defense
participant Witness
User->>Judge: Provide case details
Judge-->>User: Opening statement
Prosecutor-->>User: Opening statement
Defense-->>User: Opening statement
Witness-->>User: Testimony
Judge-->>User: Final verdict
Pocky Cybersecurity PoC AgentsequenceDiagram
participant User
participant Pocky Agent
participant AttackIntentAgent
participant ValidationAgent
User->>Pocky Agent: Request CVE PoC validation
Pocky Agent->>AttackIntentAgent: Extract attack intent from CVE
AttackIntentAgent-->>Pocky Agent: Return attack intent
Pocky Agent->>ValidationAgent: Validate PoC against intent
ValidationAgent-->>Pocky Agent: Return validation result
Pocky Agent-->>User: Display result
Praison AI Real Estate ChatbotsequenceDiagram
participant User
participant Chatbot Agent
User->>Chatbot Agent: Submit real estate question
Chatbot Agent-->>User: Return markdown-formatted answer
Suggested labels
Poem
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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.
Summary of Changes
Hello @Dhivya-Bharathy, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request significantly expands the collection of AI agent examples within the examples/python/tools/exa-tool
directory. It primarily introduces a new Praison AI Real Estate Chatbot, as indicated by the title, but also includes several other distinct AI agent scripts demonstrating applications in government services, legal simulations, and cybersecurity proof-of-concept validation.
Highlights
- New Real Estate Chatbot: Introduces
praison_ai_real_estate_chatbot.py
, a new script for an AI-powered real estate assistant, allowing users to ask property-related questions via an interactiveipywidgets
interface. - Diverse AI Agent Examples: Adds three additional Python scripts showcasing various AI agent applications: a Chile Government Services Assistant, a Legalia AI Mini Court Simulation, and a Pocky Cybersecurity PoC Search & Validation tool, expanding the
examples/python/tools/exa-tool
directory. - API Key Integration: Each new script includes explicit placeholders for necessary API keys (e.g., OpenAI, Firecrawl, Exa), guiding users on how to configure their environment for running the examples.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command>
or @gemini-code-assist <command>
. Below is a summary of the supported commands.
Feature | Command | Description |
---|---|---|
Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/
folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## main #694 +/- ##
==========================================
- Coverage 14.50% 14.23% -0.27%
==========================================
Files 25 25
Lines 2517 2571 +54
Branches 357 367 +10
==========================================
+ Hits 365 366 +1
- Misses 2136 2189 +53
Partials 16 16
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
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.
Code Review
This pull request introduces four new Python example scripts demonstrating various capabilities of the PraisonAI framework. The most critical issue is the use of hardcoded placeholder API keys across multiple files, which poses a significant security risk. I've suggested replacing this pattern with loading keys from environment variables. Other feedback includes fixing a NameError
that would prevent one script from running and correcting a logic bug in API key handling.
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 comment
The reason will be displayed to describe this comment to others. Learn more.
Hardcoding API keys, even as placeholders, is a significant security risk. Load keys from environment variables using os.getenv()
and provide instructions for users to set them up.
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') | |
os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY') |
os.environ["EXA_API_KEY"] = "your api key" | ||
os.environ["OPENAI_API_KEY"] = "your api key" | ||
os.environ["OPENAI_BASE_URL"] = "https://api.openai.com/v1" # Optional, for custom OpenAI endpoints |
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.
Hardcoding API keys, even as placeholders, is a significant security risk. Load keys from environment variables using os.getenv()
.
os.environ["EXA_API_KEY"] = os.getenv("EXA_API_KEY")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
os.environ["OPENAI_BASE_URL"] = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
OPENAI_API_KEY = "Enter your api key here" # <-- Replace with your key | ||
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY |
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.
Hardcoding API keys, even as placeholders, is a significant security risk. Load the key from an environment variable using os.getenv()
.
OPENAI_API_KEY = "Enter your api key here" # <-- Replace with your key | |
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY | |
# Load your OpenAI API key from an environment variable. | |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") | |
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY |
# FIRECRAWL_INSTRUCTION = "ChileAtiende: " | ||
# FIRECRAWL_TEMPLATE = """ | ||
# # Result {result_number} | ||
|
||
# ## Page Name: | ||
# "{page_title}" | ||
|
||
# ## URL: | ||
# {page_url} | ||
|
||
# ## Content: | ||
# {page_content} | ||
|
||
# """ |
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.
The variables FIRECRAWL_INSTRUCTION
and FIRECRAWL_TEMPLATE
are commented out, causing a NameError
and preventing the script from running.
# 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} | |
""" |
if not api_key: | ||
print("🔑 Enter your OpenAI API key:") | ||
api_key = input("API Key: ").strip() | ||
os.environ['OPENAI_API_KEY'] = "Enter your api key" |
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.
The environment variable OPENAI_API_KEY
is being set to the placeholder string "Enter your api key"
if the user provides an empty input, causing authentication failures. Set it to the api_key
variable.
os.environ['OPENAI_API_KEY'] = "Enter your api key" | |
os.environ['OPENAI_API_KEY'] = api_key |
else: | ||
return None | ||
else: | ||
return None |
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.
print(f"📝 Description: {case_description}") | ||
print(f"🔍 Evidence: {evidence}") | ||
|
||
"""# Helper Functions (Fixed with .start())## Cell 4: Case Details Input""" |
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.
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.
Actionable comments posted: 8
🧹 Nitpick comments (6)
examples/python/tools/exa-tool/praison_ai_real_estate_chatbot.py (2)
30-31
: Fix import organization to comply with PEP8.All imports should be placed at the top of the file after the module docstring, grouped by standard library, third-party, and local imports.
Apply this diff to reorganize imports:
+import os +import ipywidgets as widgets +from IPython.display import display, Markdown +from praisonaiagents import Agent + # # -*- coding: utf-8 -*- # """Praison_AI_Real_Estate_Chatbot.ipynb # ... -import os # ... -from praisonaiagents import Agent # ... -import ipywidgets as widgets -from IPython.display import display, MarkdownAlso applies to: 45-46
61-63
: Add input validation and clear input after submission.The button click handler should validate the input and clear the text field after submission for better user experience.
Apply this diff to improve the interaction:
def on_button_clicked(b): - ask_agent(question.value) + if question.value.strip(): + ask_agent(question.value.strip()) + question.value = "" # Clear input after submission + else: + display(Markdown("**Please enter a question first.**"))examples/python/tools/exa-tool/legaliaai_minicourt.py (2)
40-40
: Fix import organization to comply with PEP8.The import statement should be moved to the top of the file after other imports.
Apply this diff to reorganize imports:
import os from dotenv import load_dotenv from IPython.display import display, HTML import time +from praisonaiagents import Agent load_dotenv() # ... -from praisonaiagents import Agent
141-141
: Remove unnecessary f-string prefixes.These f-strings don't contain any placeholders, so the
f
prefix is unnecessary.Apply this diff to remove unnecessary f-string prefixes:
-display(HTML(f"<h2>📅 Day 1: Opening Statements</h2>")) +display(HTML("<h2>📅 Day 1: Opening Statements</h2>")) -display(HTML(f"<h2>📅 Day 2: Witness Testimony</h2>")) +display(HTML("<h2>📅 Day 2: Witness Testimony</h2>")) -display(HTML(f"<h2>📅 Day 3: Final Verdict</h2>")) +display(HTML("<h2>📅 Day 3: Final Verdict</h2>"))Also applies to: 173-173, 187-187
examples/python/tools/exa-tool/chile_government_services_assistant_.py (2)
29-31
: Fix import organization to comply with PEP8.All imports should be placed at the top of the file after the module docstring.
Apply this diff to reorganize imports:
import os +from firecrawl import FirecrawlApp, ScrapeOptions +from deep_translator import GoogleTranslator +import re os.environ['FIRECRAWL_API_KEY'] = "your api key here" os.environ['OPENAI_API_KEY'] = "your api key here" -# """# Import Libraries & Translator""" - -from firecrawl import FirecrawlApp, ScrapeOptions -from deep_translator import GoogleTranslator -import re
73-87
: Simplify conditional logic by removing unnecessary else after return.The code can be simplified by removing the unnecessary
else
clause afterreturn
.Apply this diff to simplify the logic:
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 + return None else: return None
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
examples/python/tools/exa-tool/chile_government_services_assistant_.py
(1 hunks)examples/python/tools/exa-tool/legaliaai_minicourt.py
(1 hunks)examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py
(1 hunks)examples/python/tools/exa-tool/praison_ai_real_estate_chatbot.py
(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py (3)
src/praisonai/praisonai.rb (1)
install
(12-14)src/praisonai-agents/praisonaiagents/main.py (1)
json
(409-412)src/praisonai-ts/tests/__mocks__/openai.ts (1)
OpenAI
(29-52)
🪛 Flake8 (7.2.0)
examples/python/tools/exa-tool/praison_ai_real_estate_chatbot.py
[error] 30-30: module level import not at top of file
(E402)
[error] 45-45: module level import not at top of file
(E402)
[error] 46-46: module level import not at top of file
(E402)
[error] 48-48: expected 2 blank lines, found 1
(E302)
[error] 53-53: expected 2 blank lines after class or function definition, found 1
(E305)
[error] 61-61: expected 2 blank lines, found 1
(E302)
[error] 64-64: expected 2 blank lines after class or function definition, found 1
(E305)
examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py
[error] 24-24: SyntaxError: invalid syntax
(E999)
examples/python/tools/exa-tool/chile_government_services_assistant_.py
[error] 29-29: module level import not at top of file
(E402)
[error] 30-30: module level import not at top of file
(E402)
[error] 31-31: module level import not at top of file
(E402)
[error] 33-33: expected 2 blank lines, found 1
(E302)
[error] 40-40: expected 2 blank lines, found 1
(E302)
[error] 52-52: expected 2 blank lines, found 1
(E302)
[error] 112-112: expected 2 blank lines after class or function definition, found 1
(E305)
[error] 114-114: undefined name 'FIRECRAWL_INSTRUCTION'
(F821)
[error] 115-115: undefined name 'FIRECRAWL_TEMPLATE'
(F821)
examples/python/tools/exa-tool/legaliaai_minicourt.py
[error] 40-40: module level import not at top of file
(E402)
[error] 110-110: expected 2 blank lines, found 1
(E302)
[error] 126-126: expected 2 blank lines, found 1
(E302)
[error] 135-135: expected 2 blank lines after class or function definition, found 1
(E305)
[error] 141-141: f-string is missing placeholders
(F541)
[error] 173-173: f-string is missing placeholders
(F541)
[error] 187-187: f-string is missing placeholders
(F541)
🪛 Ruff (0.11.9)
examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py
24-24: SyntaxError: Expected a statement
24-24: SyntaxError: Simple statements must be separated by newlines or semicolons
24-24: SyntaxError: Simple statements must be separated by newlines or semicolons
24-24: SyntaxError: Simple statements must be separated by newlines or semicolons
24-24: SyntaxError: Simple statements must be separated by newlines or semicolons
24-24: SyntaxError: Simple statements must be separated by newlines or semicolons
24-24: SyntaxError: Simple statements must be separated by newlines or semicolons
examples/python/tools/exa-tool/chile_government_services_assistant_.py
114-114: Undefined name FIRECRAWL_INSTRUCTION
(F821)
115-115: Undefined name FIRECRAWL_TEMPLATE
(F821)
examples/python/tools/exa-tool/legaliaai_minicourt.py
141-141: f-string without any placeholders
Remove extraneous f
prefix
(F541)
173-173: f-string without any placeholders
Remove extraneous f
prefix
(F541)
187-187: f-string without any placeholders
Remove extraneous f
prefix
(F541)
🪛 Pylint (3.3.7)
examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py
[error] 24-24: Parsing failed: 'invalid syntax (pocky_cybersecurity_poc_agent, line 24)'
(E0001)
examples/python/tools/exa-tool/chile_government_services_assistant_.py
[refactor] 77-87: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
(R1705)
[refactor] 52-52: Too few public methods (1/2)
(R0903)
[error] 114-114: Undefined variable 'FIRECRAWL_INSTRUCTION'
(E0602)
[error] 115-115: Undefined variable 'FIRECRAWL_TEMPLATE'
(E0602)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: test-core (3.11)
- GitHub Check: quick-test
🔇 Additional comments (2)
examples/python/tools/exa-tool/legaliaai_minicourt.py (1)
43-94
: LGTM! Well-structured agent configuration.The agent configurations are well-designed with appropriate roles, instructions, and response length limits. The use of
gpt-4o-mini
is cost-effective for this simulation.examples/python/tools/exa-tool/chile_government_services_assistant_.py (1)
33-48
: LGTM! Well-implemented translation functions.The translation functions properly handle exceptions and include text cleaning for better translation results. The error handling ensures the application continues working even if translation fails.
OPENAI_API_KEY = "Enter your api key here" # <-- Replace with your key | ||
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY |
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.
Security risk: Replace hardcoded API key placeholder.
The hardcoded placeholder "Enter your api key here" should be replaced with proper environment variable handling or user input prompt to avoid accidental exposure of API keys in version control.
Apply this diff to use environment variables with fallback:
-# Enter your OpenAI API key here
-OPENAI_API_KEY = "Enter your api key here" # <-- Replace with your key
-os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
+# Get OpenAI API key from environment or prompt user
+OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
+if not OPENAI_API_KEY:
+ OPENAI_API_KEY = input("Enter your OpenAI API key: ").strip()
+os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
📝 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.
OPENAI_API_KEY = "Enter your api key here" # <-- Replace with your key | |
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY | |
# Get OpenAI API key from environment or prompt user | |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") | |
if not OPENAI_API_KEY: | |
OPENAI_API_KEY = input("Enter your OpenAI API key: ").strip() | |
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/praison_ai_real_estate_chatbot.py around lines
25 to 26, the API key is hardcoded as a placeholder string, which poses a
security risk. Remove the hardcoded key and instead retrieve the API key from an
environment variable using os.environ.get with a fallback to prompt the user for
input if the environment variable is not set. Then assign this value to
os.environ["OPENAI_API_KEY"] to ensure secure handling of the API key without
exposing it in the code.
def ask_agent(question): | ||
# Use the .chat() method for the public praisonaiagents package | ||
response = praison_agent.chat(question) | ||
display(Markdown(f"**Praison AI:** {response}")) | ||
|
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
Add error handling for agent responses.
The ask_agent
function should handle potential errors from the agent's chat method to prevent the interface from breaking.
Apply this diff to add error handling:
def ask_agent(question):
- # Use the .chat() method for the public praisonaiagents package
- response = praison_agent.chat(question)
- display(Markdown(f"**Praison AI:** {response}"))
+ try:
+ # Use the .chat() method for the public praisonaiagents package
+ response = praison_agent.chat(question)
+ display(Markdown(f"**Praison AI:** {response}"))
+ except Exception as e:
+ display(Markdown(f"**Error:** Sorry, I encountered an issue: {str(e)}"))
📝 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.
def ask_agent(question): | |
# Use the .chat() method for the public praisonaiagents package | |
response = praison_agent.chat(question) | |
display(Markdown(f"**Praison AI:** {response}")) | |
def ask_agent(question): | |
try: | |
# Use the .chat() method for the public praisonaiagents package | |
response = praison_agent.chat(question) | |
display(Markdown(f"**Praison AI:** {response}")) | |
except Exception as e: | |
display(Markdown(f"**Error:** Sorry, I encountered an issue: {str(e)}")) |
🧰 Tools
🪛 Flake8 (7.2.0)
[error] 48-48: expected 2 blank lines, found 1
(E302)
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/praison_ai_real_estate_chatbot.py around lines
48 to 52, the ask_agent function calls praison_agent.chat without error
handling, which can cause the interface to break if an exception occurs. Wrap
the call to praison_agent.chat in a try-except block to catch exceptions, and
handle errors gracefully by displaying an error message instead of the response.
This will prevent the interface from crashing on failures.
class ValidationAgent: | ||
def __init__(self, input_json): | ||
self.input_json = input_json | ||
def run(self): | ||
# Dummy validation logic for notebook demo | ||
data = json.loads(self.input_json) | ||
return True if "attack_intent" in data and "poc_sample" in data else False | ||
|
||
class AttackIntentAgent: | ||
def __init__(self, description): | ||
self.description = description | ||
def run(self): | ||
# Dummy intent extraction for notebook demo | ||
return f"Intent for: {self.description[:50]}..." | ||
|
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
Replace dummy implementations with actual AI-powered validation.
The current ValidationAgent
and AttackIntentAgent
classes are dummy implementations that don't utilize the imported OpenAI or PraisonAI libraries. This contradicts the script's purpose of AI-powered PoC validation.
Here's a proper implementation using the imported OpenAI client:
-class ValidationAgent:
- def __init__(self, input_json):
- self.input_json = input_json
- def run(self):
- # Dummy validation logic for notebook demo
- data = json.loads(self.input_json)
- return True if "attack_intent" in data and "poc_sample" in data else False
+class ValidationAgent:
+ def __init__(self, input_json):
+ self.input_json = input_json
+ self.client = OpenAI()
+
+ def run(self):
+ try:
+ data = json.loads(self.input_json)
+ prompt = f"{validation_prompt}\n\nAttack Intent: {data.get('attack_intent')}\nPoC Sample: {data.get('poc_sample')}"
+
+ response = self.client.chat.completions.create(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": prompt}],
+ max_tokens=500
+ )
+
+ result = response.choices[0].message.content
+ return json.loads(result) if result.startswith('{') else {"valid": False, "reasoning": result}
+ except Exception as e:
+ return {"valid": False, "reasoning": f"Validation error: {str(e)}"}
-class AttackIntentAgent:
- def __init__(self, description):
- self.description = description
- def run(self):
- # Dummy intent extraction for notebook demo
- return f"Intent for: {self.description[:50]}..."
+class AttackIntentAgent:
+ def __init__(self, description):
+ self.description = description
+ self.client = OpenAI()
+
+ def run(self):
+ try:
+ prompt = f"Extract the attack intent from this CVE description: {self.description}"
+
+ response = self.client.chat.completions.create(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": prompt}],
+ max_tokens=300
+ )
+
+ return response.choices[0].message.content
+ except Exception as e:
+ return f"Intent extraction error: {str(e)}"
📝 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.
class ValidationAgent: | |
def __init__(self, input_json): | |
self.input_json = input_json | |
def run(self): | |
# Dummy validation logic for notebook demo | |
data = json.loads(self.input_json) | |
return True if "attack_intent" in data and "poc_sample" in data else False | |
class AttackIntentAgent: | |
def __init__(self, description): | |
self.description = description | |
def run(self): | |
# Dummy intent extraction for notebook demo | |
return f"Intent for: {self.description[:50]}..." | |
class ValidationAgent: | |
def __init__(self, input_json): | |
self.input_json = input_json | |
self.client = OpenAI() | |
def run(self): | |
try: | |
data = json.loads(self.input_json) | |
prompt = f"{validation_prompt}\n\nAttack Intent: {data.get('attack_intent')}\nPoC Sample: {data.get('poc_sample')}" | |
response = self.client.chat.completions.create( | |
model="gpt-3.5-turbo", | |
messages=[{"role": "user", "content": prompt}], | |
max_tokens=500 | |
) | |
result = response.choices[0].message.content | |
return json.loads(result) if result.startswith('{') else {"valid": False, "reasoning": result} | |
except Exception as e: | |
return {"valid": False, "reasoning": f"Validation error: {str(e)}"} | |
class AttackIntentAgent: | |
def __init__(self, description): | |
self.description = description | |
self.client = OpenAI() | |
def run(self): | |
try: | |
prompt = f"Extract the attack intent from this CVE description: {self.description}" | |
response = self.client.chat.completions.create( | |
model="gpt-3.5-turbo", | |
messages=[{"role": "user", "content": prompt}], | |
max_tokens=300 | |
) | |
return response.choices[0].message.content | |
except Exception as e: | |
return f"Intent extraction error: {str(e)}" |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py between lines
42 and 56, replace the dummy ValidationAgent and AttackIntentAgent classes with
implementations that use the imported OpenAI or PraisonAI clients. Modify
ValidationAgent to send the input JSON to the AI model for validation and parse
the response to determine validity. Similarly, update AttackIntentAgent to use
the AI client to extract attack intent from the description text. This will
align the classes with the script's AI-powered purpose.
# Install Dependencies | ||
""" | ||
|
||
!pip install praisonaiagents exa-py python-dotenv requests beautifulsoup4 |
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.
Fix critical syntax error: Jupyter magic command in Python script.
The !pip install
syntax is valid only in Jupyter notebooks, not in standalone Python scripts. This will cause a syntax error when running the script.
Apply this diff to fix the syntax:
-!pip install praisonaiagents exa-py python-dotenv requests beautifulsoup4
+# Install dependencies (run this in terminal or notebook):
+# !pip install praisonaiagents exa-py python-dotenv requests beautifulsoup4
Alternatively, if this is meant to be a standalone script, add proper dependency installation:
-!pip install praisonaiagents exa-py python-dotenv requests beautifulsoup4
+# Run: pip install praisonaiagents exa-py python-dotenv requests beautifulsoup4
+import subprocess
+import sys
+
+def install_dependencies():
+ packages = ["praisonaiagents", "exa-py", "python-dotenv", "requests", "beautifulsoup4"]
+ for package in packages:
+ subprocess.check_call([sys.executable, "-m", "pip", "install", package])
🧰 Tools
🪛 Flake8 (7.2.0)
[error] 24-24: SyntaxError: invalid syntax
(E999)
🪛 Ruff (0.11.9)
24-24: SyntaxError: Expected a statement
24-24: SyntaxError: Simple statements must be separated by newlines or semicolons
24-24: SyntaxError: Simple statements must be separated by newlines or semicolons
24-24: SyntaxError: Simple statements must be separated by newlines or semicolons
24-24: SyntaxError: Simple statements must be separated by newlines or semicolons
24-24: SyntaxError: Simple statements must be separated by newlines or semicolons
24-24: SyntaxError: Simple statements must be separated by newlines or semicolons
🪛 Pylint (3.3.7)
[error] 24-24: Parsing failed: 'invalid syntax (pocky_cybersecurity_poc_agent, line 24)'
(E0001)
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py at line 24,
the use of the Jupyter magic command "!pip install" causes a syntax error in a
standalone Python script. Remove this line from the script and instead ensure
dependencies are installed externally before running the script, or add a proper
Python-based installation method such as using subprocess to call pip if
installation within the script is necessary.
os.environ["EXA_API_KEY"] = "your api key" | ||
os.environ["OPENAI_API_KEY"] = "your api key" | ||
os.environ["OPENAI_BASE_URL"] = "https://api.openai.com/v1" # Optional, for custom OpenAI endpoints |
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.
Security risk: Replace hardcoded API key placeholders.
Hardcoded API key placeholders pose security risks if accidentally committed with real keys. Use environment variables or secure input methods.
Apply this diff to use proper environment variable handling:
-# Set your API keys here (replace with your actual keys)
-os.environ["EXA_API_KEY"] = "your api key"
-os.environ["OPENAI_API_KEY"] = "your api key"
+# Load API keys from environment variables
+if not os.getenv("EXA_API_KEY"):
+ os.environ["EXA_API_KEY"] = input("Enter your EXA API key: ").strip()
+if not os.getenv("OPENAI_API_KEY"):
+ os.environ["OPENAI_API_KEY"] = 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.
os.environ["EXA_API_KEY"] = "your api key" | |
os.environ["OPENAI_API_KEY"] = "your api key" | |
os.environ["OPENAI_BASE_URL"] = "https://api.openai.com/v1" # Optional, for custom OpenAI endpoints | |
# Load API keys from environment variables | |
if not os.getenv("EXA_API_KEY"): | |
os.environ["EXA_API_KEY"] = input("Enter your EXA API key: ").strip() | |
if not os.getenv("OPENAI_API_KEY"): | |
os.environ["OPENAI_API_KEY"] = input("Enter your OpenAI API key: ").strip() | |
os.environ["OPENAI_BASE_URL"] = "https://api.openai.com/v1" # Optional, for custom OpenAI endpoints |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py around lines
31 to 33, the API keys are hardcoded as placeholders, which is a security risk.
Remove the hardcoded keys and instead read these values from environment
variables or secure input methods at runtime to avoid exposing sensitive
information in the codebase.
api_key = os.getenv('OPENAI_API_KEY') | ||
if not api_key: | ||
print("🔑 Enter your OpenAI API key:") | ||
api_key = input("API Key: ").strip() | ||
os.environ['OPENAI_API_KEY'] = "Enter your api key" |
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.
Fix API key handling inconsistency.
The code gets the API key from environment variable but then overwrites it with a hardcoded placeholder string, which will cause authentication failures.
Apply this diff to fix the API key handling:
# Setup API key
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
print("🔑 Enter your OpenAI API key:")
api_key = input("API Key: ").strip()
- os.environ['OPENAI_API_KEY'] = "Enter your api key"
+ os.environ['OPENAI_API_KEY'] = api_key
📝 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.
api_key = os.getenv('OPENAI_API_KEY') | |
if not api_key: | |
print("🔑 Enter your OpenAI API key:") | |
api_key = input("API Key: ").strip() | |
os.environ['OPENAI_API_KEY'] = "Enter your api key" | |
# Setup API key | |
api_key = os.getenv('OPENAI_API_KEY') | |
if not api_key: | |
print("🔑 Enter your OpenAI API key:") | |
api_key = input("API Key: ").strip() | |
os.environ['OPENAI_API_KEY'] = api_key |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/legaliaai_minicourt.py around lines 30 to 34,
the code retrieves the OpenAI API key from the environment but then incorrectly
overwrites it with a hardcoded placeholder string. To fix this, after prompting
the user for the API key input, assign the entered key to the environment
variable instead of the placeholder string, ensuring the actual key is stored
and used for authentication.
# FIRECRAWL_INSTRUCTION = "ChileAtiende: " | ||
# FIRECRAWL_TEMPLATE = """ | ||
# # Result {result_number} | ||
|
||
# ## Page Name: | ||
# "{page_title}" | ||
|
||
# ## URL: | ||
# {page_url} | ||
|
||
# ## Content: | ||
# {page_content} | ||
|
||
# """ | ||
|
||
# """# Initialize Firecrawl Tool""" | ||
|
||
firecrawl_tool = FirecrawlTool( | ||
api_key=os.environ['FIRECRAWL_API_KEY'], | ||
instruction=FIRECRAWL_INSTRUCTION, | ||
template=FIRECRAWL_TEMPLATE |
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.
Critical issue: Undefined variables causing runtime error.
FIRECRAWL_INSTRUCTION
and FIRECRAWL_TEMPLATE
are referenced but not defined because lines 95-108 are commented out. This will cause a NameError
at runtime.
Apply this diff to uncomment and define the required variables:
-# 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}
+
+"""
📝 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.
# FIRECRAWL_INSTRUCTION = "ChileAtiende: " | |
# FIRECRAWL_TEMPLATE = """ | |
# # Result {result_number} | |
# ## Page Name: | |
# "{page_title}" | |
# ## URL: | |
# {page_url} | |
# ## Content: | |
# {page_content} | |
# """ | |
# """# Initialize Firecrawl Tool""" | |
firecrawl_tool = FirecrawlTool( | |
api_key=os.environ['FIRECRAWL_API_KEY'], | |
instruction=FIRECRAWL_INSTRUCTION, | |
template=FIRECRAWL_TEMPLATE | |
FIRECRAWL_INSTRUCTION = "ChileAtiende: " | |
FIRECRAWL_TEMPLATE = """ | |
# Result {result_number} | |
## Page Name: | |
"{page_title}" | |
## URL: | |
{page_url} | |
## Content: | |
{page_content} | |
""" | |
# """# Initialize Firecrawl Tool""" | |
firecrawl_tool = FirecrawlTool( | |
api_key=os.environ['FIRECRAWL_API_KEY'], | |
instruction=FIRECRAWL_INSTRUCTION, | |
template=FIRECRAWL_TEMPLATE | |
) |
🧰 Tools
🪛 Flake8 (7.2.0)
[error] 112-112: expected 2 blank lines after class or function definition, found 1
(E305)
[error] 114-114: undefined name 'FIRECRAWL_INSTRUCTION'
(F821)
[error] 115-115: undefined name 'FIRECRAWL_TEMPLATE'
(F821)
🪛 Ruff (0.11.9)
114-114: Undefined name FIRECRAWL_INSTRUCTION
(F821)
115-115: Undefined name FIRECRAWL_TEMPLATE
(F821)
🪛 Pylint (3.3.7)
[error] 114-114: Undefined variable 'FIRECRAWL_INSTRUCTION'
(E0602)
[error] 115-115: Undefined variable 'FIRECRAWL_TEMPLATE'
(E0602)
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/chile_government_services_assistant_.py around
lines 95 to 115, the variables FIRECRAWL_INSTRUCTION and FIRECRAWL_TEMPLATE are
commented out but used later, causing a NameError. Uncomment the lines defining
FIRECRAWL_INSTRUCTION and FIRECRAWL_TEMPLATE so they are properly initialized
before being passed to FirecrawlTool.
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 comment
The reason will be displayed to describe this comment to others. Learn more.
Security risk: Replace hardcoded API key placeholders.
Hardcoded API key placeholders should be replaced with proper environment variable handling to prevent security issues.
Apply this diff to use proper environment variable handling:
-os.environ['FIRECRAWL_API_KEY'] = "your api key here"
-os.environ['OPENAI_API_KEY'] = "your api key here"
+# Load API keys from environment or prompt user
+if not os.getenv('FIRECRAWL_API_KEY'):
+ firecrawl_key = input("Enter your Firecrawl API key: ").strip()
+ os.environ['FIRECRAWL_API_KEY'] = firecrawl_key
+
+if not os.getenv('OPENAI_API_KEY'):
+ openai_key = input("Enter your OpenAI API key: ").strip()
+ os.environ['OPENAI_API_KEY'] = openai_key
📝 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.
os.environ['FIRECRAWL_API_KEY'] = "your api key here" | |
os.environ['OPENAI_API_KEY'] = "your api key here" | |
# Load API keys from environment or prompt user | |
if not os.getenv('FIRECRAWL_API_KEY'): | |
firecrawl_key = input("Enter your Firecrawl API key: ").strip() | |
os.environ['FIRECRAWL_API_KEY'] = firecrawl_key | |
if not os.getenv('OPENAI_API_KEY'): | |
openai_key = input("Enter your OpenAI API key: ").strip() | |
os.environ['OPENAI_API_KEY'] = openai_key |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/chile_government_services_assistant_.py at
lines 24 to 25, replace the hardcoded API key placeholders with code that reads
the API keys from environment variables securely. Remove the assignment of
literal strings and instead use a method like os.getenv to fetch the keys at
runtime, ensuring the keys are not hardcoded in the source code.
Summary by CodeRabbit