-
-
Notifications
You must be signed in to change notification settings - Fork 721
Add MemoryPal Search Agent Python Script #696
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 MemoryPal Search Agent Python Script #696
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 21 minutes and 8 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 (4)
WalkthroughSeveral new Python scripts are introduced, each implementing a distinct AI-powered tool or agent. These include a Chilean government services chatbot, a mini court simulation with AI agents, an internet search agent using DuckDuckGo, a cybersecurity PoC validation agent, and a real estate chatbot. Each script defines its own classes, functions, and interactive flows, integrating APIs and agent frameworks as needed. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Chatbot (Tomás)
participant FirecrawlTool
participant Firecrawl API
participant Translator
User->>Chatbot (Tomás): Enter question
Chatbot (Tomás)->>Translator: Translate question to Spanish
Translator-->>Chatbot (Tomás): Spanish question
Chatbot (Tomás)->>FirecrawlTool: search(Spanish question)
FirecrawlTool->>Firecrawl API: Query government service pages
Firecrawl API-->>FirecrawlTool: Search results
FirecrawlTool-->>Chatbot (Tomás): Formatted results
Chatbot (Tomás)->>Translator: Translate results to English
Translator-->>Chatbot (Tomás): English results
Chatbot (Tomás)-->>User: Display answer
sequenceDiagram
participant User
participant MiniCourt
participant Judge
participant Prosecutor
participant Defense
participant Witness
User->>MiniCourt: Provide case details
MiniCourt->>Judge: Opening statement
Judge-->>MiniCourt: Judge's statement
MiniCourt->>Prosecutor: Opening statement
Prosecutor-->>MiniCourt: Prosecutor's statement
MiniCourt->>Defense: Opening statement
Defense-->>MiniCourt: Defense's statement
MiniCourt->>Witness: Testimony
Witness-->>MiniCourt: Witness's testimony
MiniCourt->>Judge: Final verdict
Judge-->>MiniCourt: Verdict
MiniCourt-->>User: Display all responses
sequenceDiagram
participant User
participant PraisonAI Agent
participant InternetSearchTool (DuckDuckGo)
User->>PraisonAI Agent: Query (e.g., "AI job trends in 2025")
PraisonAI Agent->>InternetSearchTool: Search query
InternetSearchTool-->>PraisonAI Agent: Search results
PraisonAI Agent-->>User: Response
sequenceDiagram
participant User
participant Pocky PoC Agent
participant AttackIntentAgent
participant ValidationAgent
User->>Pocky PoC Agent: Provide CVE ID
Pocky PoC Agent->>AttackIntentAgent: Extract attack intent from CVE description
AttackIntentAgent-->>Pocky PoC Agent: Attack intent
Pocky PoC Agent->>ValidationAgent: Validate PoC sample against intent
ValidationAgent-->>Pocky PoC Agent: Validation result
Pocky PoC Agent-->>User: Display result
sequenceDiagram
participant User
participant RealEstateChatbot
participant PraisonAI Agent
User->>RealEstateChatbot: Enter question
RealEstateChatbot->>PraisonAI Agent: Send question
PraisonAI Agent-->>RealEstateChatbot: Response
RealEstateChatbot-->>User: Display response
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 introduces five new Python scripts that showcase the capabilities of PraisonAI agents in various applications, including government services assistance, legal simulations, internet search, cybersecurity PoC validation, and real estate chatbots. Each script provides a self-contained example with necessary dependencies and setup instructions.
Highlights
- New Script: Added a new Python script,
chile_government_services_assistant_.py
, which implements an AI chatbot to answer questions about Chilean government services using the Firecrawl API. It translates queries to Spanish, searches ChileAtiende, and translates the results back to English. - New Script: Added a new Python script,
legaliaai_minicourt.py
, which simulates a simplified court case with AI agents (Judge, Prosecutor, Defense, Witness) using thepraisonaiagents
library. It takes case details as input and runs a 3-day trial simulation. - New Script: Added a new Python script,
memorypal_search_agent.py
, demonstrating the use of PraisonAI's Agent with a custom internet search tool (DuckDuckGo) in Python. It searches for AI job trends and prints the response. - New Script: Added a new Python script,
pocky_cybersecurity_poc_agent.py
, which automates CVE PoC search and validation. It simulates fetching a description and PoC, extracts the attack intent, and validates the PoC. - New Script: Added a new Python script,
praison_ai_real_estate_chatbot.py
, which creates a real estate AI chatbot using PraisonAI and OpenAI. It allows users to ask real estate questions and receive advice.
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 #696 +/- ##
==========================================
- 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.
Actionable comments posted: 16
🧹 Nitpick comments (18)
examples/python/tools/exa-tool/legaliaai_minicourt.py (6)
40-40
: Move import statement to the top of the file.The import statement should be placed at the top with other imports for better code organization and compliance with PEP 8.
Apply this diff to move the import statement:
import os from dotenv import load_dotenv from IPython.display import display, HTML import time +from praisonaiagents import Agent load_dotenv()
And remove the import from line 40:
-from praisonaiagents import Agent
107-107
: Remove leftover notebook conversion comment.The comment appears to be leftover from Jupyter notebook conversion and contains confusing mixed content.
Apply this diff to clean up the comment:
-"""# Helper Functions (Fixed with .start())## Cell 4: Case Details Input""" +"""# Helper Functions"""
110-123
: Add proper spacing before function definition.Missing blank lines before function definition according to PEP 8.
Apply this diff to add proper spacing:
+ + def show_message(name, role, message, color="#4CAF50"):
126-134
: Add proper spacing before function definition.Missing blank lines before function definition according to PEP 8.
Apply this diff to add proper spacing:
+ + def run_agent(agent, prompt, name, role, color="#4CAF50"):
135-135
: Add proper spacing after function definition.Missing blank lines after function definition according to PEP 8.
Apply this diff to add proper spacing:
return "" + """## Mini Court Simulation"""
141-141
: Remove unnecessary f-string prefixes.The f-strings don't contain any placeholders, so the
f
prefix is redundant.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/praison_ai_real_estate_chatbot.py (3)
18-18
: Consider removing pip install command from production code.The pip install command should typically be handled via requirements.txt or setup.py rather than inline in the script, especially for production code.
48-52
: Fix PEP 8 formatting issues.The code has several formatting issues flagged by static analysis tools regarding blank lines between function definitions.
Apply this diff to fix formatting:
# """## 4. Chat with the Agent""" + def ask_agent(question): # Use the .chat() method for the public praisonaiagents package response = praison_agent.chat(question) display(Markdown(f"**Praison AI:** {response}")) + question = widgets.Text( value='', placeholder='Type your real estate question here...', description='You:', disabled=False ) + + button = widgets.Button(description="Ask Praison AI") + def on_button_clicked(b): ask_agent(question.value) + button.on_click(on_button_clicked) display(question, button)Also applies to: 61-65
48-52
: Verify error handling for agent responses.Consider adding error handling around the
praison_agent.chat()
call to gracefully handle potential API failures or network issues.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:** Failed to get response: {str(e)}"))examples/python/tools/exa-tool/chile_government_services_assistant_.py (8)
18-18
: Remove commented pip install command from production code.This commented pip install command should be removed from the production script. Package dependencies should be managed through proper dependency files like
requirements.txt
orsetup.py
.-# !pip install flask firecrawl praisonaiagents google-genai python-dotenv deep-translator
29-31
: Move imports to the top of the file.According to PEP 8, imports should be at the top of the file, after module comments and docstrings.
+from firecrawl import FirecrawlApp, ScrapeOptions +from deep_translator import GoogleTranslator +import re + import os -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 +# Set environment variables after imports +os.environ['FIRECRAWL_API_KEY'] = "your api key here" +os.environ['OPENAI_API_KEY'] = "your api key here"
33-38
: Add proper spacing and improve error handling.The function lacks proper spacing and could benefit from more specific error handling.
+ + def translate_to_spanish(text): try: return GoogleTranslator(source='auto', target='es').translate(text) except Exception as e: - print("Translation to Spanish failed:", e) + print(f"Translation to Spanish failed: {e}") return text
40-48
: Add proper spacing and improve regex handling.The function needs proper spacing and the regex operation could be more robust.
+ + def translate_to_english(text): try: # Remove Markdown images and None values before translation text = str(text).replace("None", "") - text = re.sub(r'!\[.*?\]\(.*?\)', '', text) + text = re.sub(r'!\[.*?\]\(.*?\)', '', text) # Remove markdown images return GoogleTranslator(source='auto', target='en').translate(text) except Exception as e: - print("Translation to English failed:", e) + print(f"Translation to English failed: {e}") return text
52-58
: Add proper spacing and improve class documentation.The class needs proper spacing and could benefit from a docstring.
+ + class FirecrawlTool: + """A tool for searching Chilean government services using Firecrawl API.""" + 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
77-89
: Simplify conditional logic by removing unnecessary else clause.The else clause after return is unnecessary and can be simplified.
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
112-116
: Add proper spacing after class definition.There should be two blank lines after a class definition according to PEP 8.
except Exception as e: return f"Error during search: {e}" + + # """# Firecrawl Prompt Template""" FIRECRAWL_INSTRUCTION = "ChileAtiende: "
134-139
: Improve error handling and user feedback.The error handling could be more specific and provide better user feedback.
# 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: + if (spanish_answer and + isinstance(spanish_answer, str) and + spanish_answer.strip() and + not spanish_answer.startswith("Error")): 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})") + print(f"\nTomás: I found information, but couldn't translate it. " + f"Here it is in Spanish:\n{spanish_answer}\nTranslation error: {e}") else: - print("\nTomás: Sorry, I couldn't find relevant information. Try rephrasing your question or ask about another service.") + print("\nTomás: Sorry, I couldn't find relevant information. " + "Try rephrasing your question or ask about another service.")examples/python/tools/exa-tool/memorypal_search_agent.py (1)
1-21
: Consider cleaning up the header documentation.The extensive commented header suggests this was auto-generated from a Jupyter notebook. For a standalone Python script, consider simplifying the header to include only essential documentation like purpose, usage, and requirements.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
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/memorypal_search_agent.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 (3)
examples/python/tools/exa-tool/praison_ai_real_estate_chatbot.py (2)
src/praisonai-agents/praisonaiagents/knowledge/knowledge.py (1)
markdown
(167-168)src/praisonai-agents/praisonaiagents/llm/llm.py (1)
response
(1525-1630)
examples/python/tools/exa-tool/legaliaai_minicourt.py (2)
src/praisonai-agents/praisonaiagents/knowledge/knowledge.py (1)
markdown
(167-168)src/praisonai-agents/praisonaiagents/llm/llm.py (1)
response
(1525-1630)
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/memorypal_search_agent.py
[error] 29-29: module level import not at top of file
(E402)
[error] 31-31: expected 2 blank lines, found 1
(E302)
[error] 44-44: expected 2 blank lines after class or function definition, found 1
(E305)
[error] 44-44: module level import not at top of file
(E402)
[error] 73-73: module level import not at top of file
(E402)
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)
examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py
[error] 24-24: SyntaxError: invalid syntax
(E999)
🪛 Ruff (0.11.9)
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)
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
🪛 Pylint (3.3.7)
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)
examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py
[error] 24-24: Parsing failed: 'invalid syntax (pocky_cybersecurity_poc_agent, line 24)'
(E0001)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: test-core (3.11)
- GitHub Check: quick-test
🔇 Additional comments (7)
examples/python/tools/exa-tool/legaliaai_minicourt.py (2)
43-94
: Well-structured agent configuration.The AI agents are properly configured with appropriate roles, instructions, and consistent parameters. The word limits for each agent type are thoughtfully set to maintain focused responses.
144-196
: Solid simulation flow with contextual prompts.The three-day court simulation structure is well-designed, with each agent receiving appropriate context and clear instructions. The progression from opening statements through testimony to final verdict creates a realistic courtroom experience.
examples/python/tools/exa-tool/praison_ai_real_estate_chatbot.py (1)
32-41
: LGTM! Agent configuration looks good.The agent setup with appropriate name, role, instructions, and markdown formatting is well-structured and follows the expected pattern for PraisonAI agents.
examples/python/tools/exa-tool/chile_government_services_assistant_.py (1)
24-25
: Verify API key security practices.The script contains placeholder API keys that could be accidentally committed with real values.
#!/bin/bash # Description: Check for potential API key leaks in the repository # Expected: No real API keys should be found in committed code # Search for potential API key patterns rg -i "api.{0,5}key.{0,10}=" --type py -A 2 -B 2 # Check for common API key patterns rg -i "(sk-|pk_|AIza|ya29\.|glpat-)" --type py -A 1 -B 1examples/python/tools/exa-tool/memorypal_search_agent.py (2)
46-60
: YAML configuration looks good.The agent configuration is well-structured with clear role definition, backstory, goal, and task specification.
75-84
: Agent implementation looks good.The agent initialization with instructions and tools, followed by query execution, is implemented correctly.
examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py (1)
38-40
: Add missing imports and verify API client initialization.The OpenAI and Exa clients are imported but never used in the current implementation.
Verify that the imported libraries are actually needed and properly utilized:
#!/bin/bash # Description: Check if OpenAI and Exa clients are used in the implementation # Search for OpenAI client usage echo "Searching for OpenAI client usage:" rg -A 3 -B 1 "OpenAI\(\)" # Search for Exa client usage echo "Searching for Exa client usage:" rg -A 3 -B 1 "Exa\(\)" # Check for any API calls echo "Searching for API method calls:" rg -A 2 "\.chat\.|\.search\.|\.completions\."
import os | ||
from dotenv import load_dotenv | ||
from IPython.display import display, HTML | ||
import time | ||
|
||
load_dotenv() | ||
|
||
# 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" | ||
|
||
print("✅ Setup complete!") |
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 security issue: API key is hardcoded to placeholder value.
The code prompts the user for their OpenAI API key but then overwrites it with a placeholder string on line 34, which will cause authentication failures.
Apply this diff to fix the API key handling:
- 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.
import os | |
from dotenv import load_dotenv | |
from IPython.display import display, HTML | |
import time | |
load_dotenv() | |
# 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" | |
print("✅ Setup complete!") | |
import os | |
from dotenv import load_dotenv | |
from IPython.display import display, HTML | |
import time | |
load_dotenv() | |
# 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 | |
print("✅ Setup complete!") |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/legaliaai_minicourt.py between lines 22 and
36, the API key is requested from the user but then overwritten with a hardcoded
placeholder string, causing authentication failures. To fix this, remove the
line that sets os.environ['OPENAI_API_KEY'] to the placeholder and instead
assign the user input directly to this environment variable so the actual key is
used for authentication.
|
||
# """## 2. Set Your OpenAI API Key""" | ||
|
||
import os |
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
Organize imports at the top of the file.
Following PEP 8 guidelines, all imports should be placed at the top of the file after module docstrings and before module globals and constants.
Apply this diff to reorganize imports:
+import os
+from praisonaiagents import Agent
+import ipywidgets as widgets
+from IPython.display import display, Markdown
+
# # -*- coding: utf-8 -*-
# """Praison_AI_Real_Estate_Chatbot.ipynb
@@ -19,8 +24,6 @@
# """## 2. Set Your OpenAI API Key"""
-import os
-
# 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
@@ -28,8 +31,6 @@
# """## 3. Create the Praison AI Agent"""
-from praisonaiagents import Agent
-
praison_agent = Agent(
name="Praison Real Estate Chatbot",
role="Answer real estate questions and provide helpful advice.",
@@ -42,9 +43,6 @@
# """## 4. Chat with the Agent"""
-import ipywidgets as widgets
-from IPython.display import display, Markdown
-
def ask_agent(question):
# Use the .chat() method for the public praisonaiagents package
response = praison_agent.chat(question)
Also applies to: 30-30, 45-46
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/praison_ai_real_estate_chatbot.py at lines 22,
30, and 45-46, imports are not properly organized according to PEP 8. Move all
import statements to the top of the file, immediately after any module
docstrings and before any global variables or constants. Ensure no imports are
scattered throughout the code and that they are grouped together at the
beginning.
import os | ||
|
||
# Enter your OpenAI API key here | ||
OPENAI_API_KEY = "Enter your api key here" # <-- Replace with your 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 concern: Replace hardcoded API key placeholder.
The hardcoded placeholder "Enter your api key here" poses a security risk if users accidentally commit their actual API keys. Consider using environment variable loading with proper validation.
Apply this diff to improve security:
-# 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
+# Load OpenAI API key from environment
+OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
+if not OPENAI_API_KEY:
+ raise ValueError("Please set your OPENAI_API_KEY environment variable")
+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 | |
# Load OpenAI API key from environment | |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") | |
if not OPENAI_API_KEY: | |
raise ValueError("Please set your OPENAI_API_KEY environment variable") | |
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/praison_ai_real_estate_chatbot.py at line 25,
replace the hardcoded API key placeholder with code that loads the API key from
an environment variable. Use a method like os.getenv to retrieve the key and add
validation to ensure the key is present, raising an error or warning if it is
missing. This prevents accidental exposure of API keys in the codebase.
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.
Avoid hardcoded API keys in source code.
Hardcoded API keys pose a security risk. Use environment variables or configuration files that are not committed to version control.
-os.environ['FIRECRAWL_API_KEY'] = "your api key here"
-os.environ['OPENAI_API_KEY'] = "your api key here"
+# Load API keys from environment or .env file
+# os.environ['FIRECRAWL_API_KEY'] should be set externally
+# os.environ['OPENAI_API_KEY'] should be set externally
📝 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 .env file | |
# os.environ['FIRECRAWL_API_KEY'] should be set externally | |
# os.environ['OPENAI_API_KEY'] should be set externally |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/chile_government_services_assistant_.py around
lines 24 to 25, the API keys are hardcoded as plain strings, which is a security
risk. Remove the hardcoded keys and instead load these API keys from environment
variables or external configuration files that are excluded from version
control. Update the code to read the keys dynamically at runtime without
embedding sensitive information directly in the source code.
# 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.
Uncomment and define required template variables.
The template variables are commented out but used in the initialization, causing undefined variable 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}
+
+"""
📝 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} | |
# """ | |
FIRECRAWL_INSTRUCTION = "ChileAtiende: " | |
FIRECRAWL_TEMPLATE = """ | |
# Result {result_number} | |
## Page Name: | |
"{page_title}" | |
## URL: | |
{page_url} | |
## Content: | |
{page_content} | |
""" |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/chile_government_services_assistant_.py around
lines 95 to 108, the template variables FIRECRAWL_INSTRUCTION and
FIRECRAWL_TEMPLATE are commented out but still referenced later, causing
undefined variable errors. Uncomment these lines and ensure all placeholders
like {result_number}, {page_title}, {page_url}, and {page_content} are correctly
defined within the template string to fix the issue.
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.
Avoid hardcoded API key placeholders.
Hardcoded API key placeholders pose security risks and can lead to accidental exposure.
Apply this diff to use environment variables safely:
-# 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"
-os.environ["OPENAI_BASE_URL"] = "https://api.openai.com/v1" # Optional, for custom OpenAI endpoints
+# Load API keys from environment or .env file
+from dotenv import load_dotenv
+load_dotenv()
+
+# Ensure required API keys are set
+required_keys = ["EXA_API_KEY", "OPENAI_API_KEY"]
+for key in required_keys:
+ if not os.environ.get(key):
+ raise ValueError(f"Missing required environment variable: {key}")
+
+# Optional: Set default OpenAI base URL if not provided
+if not os.environ.get("OPENAI_BASE_URL"):
+ os.environ["OPENAI_BASE_URL"] = "https://api.openai.com/v1"
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py around lines
31 to 33, avoid hardcoding API key placeholders directly in the code. Instead,
remove the hardcoded strings and ensure the code reads these keys from
environment variables already set in the system or through a secure
configuration method. This prevents accidental exposure and improves security by
not embedding sensitive information in the source code.
# 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 the invalid Python syntax.
The !pip install
command is specific to Jupyter notebooks and causes a syntax error in regular Python scripts.
Apply this diff to fix the syntax error:
-!pip install praisonaiagents exa-py python-dotenv requests beautifulsoup4
+# Install dependencies with: pip install praisonaiagents exa-py python-dotenv requests beautifulsoup4
+# Or add to requirements.txt file
Alternatively, if this script is intended to run programmatically, use:
-!pip install praisonaiagents exa-py python-dotenv requests beautifulsoup4
+import subprocess
+import sys
+
+def install_dependencies():
+ """Install required packages programmatically."""
+ packages = ['praisonaiagents', 'exa-py', 'python-dotenv', 'requests', 'beautifulsoup4']
+ for package in packages:
+ subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])
+
+# Uncomment to install dependencies
+# install_dependencies()
📝 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.
!pip install praisonaiagents exa-py python-dotenv requests beautifulsoup4 | |
# Install dependencies with: pip install praisonaiagents exa-py python-dotenv requests beautifulsoup4 | |
# Or add them to your requirements.txt file |
🧰 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 "!pip install" is invalid Python syntax outside of Jupyter notebooks.
Remove this line or replace it with a comment instructing users to install the
required packages via the command line before running the script. If package
installation is needed programmatically, use subprocess calls to pip instead of
the "!pip" syntax.
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
Implement proper agent functionality or document as placeholder.
The agent classes contain only dummy implementations that don't provide real functionality for PoC validation or attack intent extraction.
If these are placeholder implementations, consider adding proper documentation:
+# TODO: Replace with actual implementation
class ValidationAgent:
+ """Placeholder agent for PoC validation. Requires implementation."""
def __init__(self, input_json):
self.input_json = input_json
+
def run(self):
- # Dummy validation logic for notebook demo
+ # TODO: Implement actual validation logic using AI/ML models
data = json.loads(self.input_json)
- return True if "attack_intent" in data and "poc_sample" in data else False
+ # Current implementation is a placeholder
+ if "attack_intent" not in data or "poc_sample" not in data:
+ raise ValueError("Missing required fields: attack_intent or poc_sample")
+ return {"valid": True, "reasoning": "Placeholder validation - needs implementation"}
+# TODO: Replace with actual implementation
class AttackIntentAgent:
+ """Placeholder agent for attack intent extraction. Requires implementation."""
def __init__(self, description):
self.description = description
+
def run(self):
- # Dummy intent extraction for notebook demo
- return f"Intent for: {self.description[:50]}..."
+ # TODO: Implement actual intent extraction using NLP/AI
+ if not self.description:
+ raise ValueError("Description cannot be empty")
+ return f"Extracted intent for: {self.description[:50]}... (placeholder)"
📝 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]}..." | |
# TODO: Replace with actual implementation | |
class ValidationAgent: | |
"""Placeholder agent for PoC validation. Requires implementation.""" | |
def __init__(self, input_json): | |
self.input_json = input_json | |
def run(self): | |
# TODO: Implement actual validation logic using AI/ML models | |
data = json.loads(self.input_json) | |
# Current implementation is a placeholder | |
if "attack_intent" not in data or "poc_sample" not in data: | |
raise ValueError("Missing required fields: attack_intent or poc_sample") | |
return {"valid": True, "reasoning": "Placeholder validation - needs implementation"} | |
# TODO: Replace with actual implementation | |
class AttackIntentAgent: | |
"""Placeholder agent for attack intent extraction. Requires implementation.""" | |
def __init__(self, description): | |
self.description = description | |
def run(self): | |
# TODO: Implement actual intent extraction using NLP/AI | |
if not self.description: | |
raise ValueError("Description cannot be empty") | |
return f"Extracted intent for: {self.description[:50]}... (placeholder)" |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py around lines
42 to 56, the ValidationAgent and AttackIntentAgent classes currently have only
dummy implementations without real functionality. To fix this, either implement
the actual logic for PoC validation and attack intent extraction or clearly
document these classes as placeholders by adding explanatory comments or
docstrings indicating they are for demonstration purposes only.
data = json.loads(self.input_json) | ||
return True if "attack_intent" in data and "poc_sample" in data else False |
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 JSON parsing.
The JSON parsing operation can fail with malformed input, but there's no error handling.
Apply this diff to add proper error handling:
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
+ # TODO: Implement actual validation logic
+ try:
+ data = json.loads(self.input_json)
+ except json.JSONDecodeError as e:
+ raise ValueError(f"Invalid JSON input: {e}")
+
+ if "attack_intent" not in data or "poc_sample" not in data:
+ raise ValueError("Missing required fields: attack_intent or poc_sample")
+ return {"valid": True, "reasoning": "Placeholder validation - needs implementation"}
📝 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.
data = json.loads(self.input_json) | |
return True if "attack_intent" in data and "poc_sample" in data else False | |
def run(self): | |
# TODO: Implement actual validation logic | |
try: | |
data = json.loads(self.input_json) | |
except json.JSONDecodeError as e: | |
raise ValueError(f"Invalid JSON input: {e}") | |
if "attack_intent" not in data or "poc_sample" not in data: | |
raise ValueError("Missing required fields: attack_intent or poc_sample") | |
return {"valid": True, "reasoning": "Placeholder validation - needs implementation"} |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py around lines
47 to 48, the code parses JSON without handling potential parsing errors. Wrap
the json.loads call in a try-except block to catch JSONDecodeError exceptions,
and return False if an error occurs. This will prevent the function from
crashing on malformed input and handle the error gracefully.
def run_pocky_for_cve(cve_id): | ||
# Example: Simulate fetching a description and PoC (replace with real logic) | ||
description = f"Description for {cve_id} (replace with real Exa/OpenAI search)" | ||
poc_sample = f"PoC code for {cve_id} (replace with real PoC search)" | ||
|
||
# Stage 2: Attack Intent | ||
intent = AttackIntentAgent(description).run() | ||
print(f"Attack Intent: {intent}") | ||
|
||
# Stage 3: Validation | ||
validation_input = json.dumps({"attack_intent": intent, "poc_sample": poc_sample}, indent=2) | ||
valid = ValidationAgent(validation_input).run() | ||
print(f"Validation Result: {valid}") | ||
if valid: | ||
print(f"PoC for {cve_id} is valid and ready to use.") | ||
else: | ||
print(f"PoC for {cve_id} failed validation.") | ||
|
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
Enhance the main function with proper implementation structure.
The function contains only placeholder logic without real CVE description fetching or PoC validation.
Apply this diff to improve the function structure:
def run_pocky_for_cve(cve_id):
- # Example: Simulate fetching a description and PoC (replace with real logic)
- description = f"Description for {cve_id} (replace with real Exa/OpenAI search)"
- poc_sample = f"PoC code for {cve_id} (replace with real PoC search)"
+ """
+ Process a CVE ID to find and validate PoC exploits.
+
+ Args:
+ cve_id (str): The CVE identifier to process
+
+ Returns:
+ dict: Validation results with status and details
+ """
+ if not cve_id or not isinstance(cve_id, str):
+ raise ValueError("CVE ID must be a non-empty string")
+
+ try:
+ # TODO: Implement real CVE description fetching using Exa API
+ description = f"Description for {cve_id} (TODO: implement real Exa/OpenAI search)"
+ poc_sample = f"PoC code for {cve_id} (TODO: implement real PoC search)"
- # Stage 2: Attack Intent
- intent = AttackIntentAgent(description).run()
- print(f"Attack Intent: {intent}")
+ # Stage 1: Extract attack intent
+ intent_agent = AttackIntentAgent(description)
+ intent = intent_agent.run()
+ print(f"Attack Intent: {intent}")
- # Stage 3: Validation
- validation_input = json.dumps({"attack_intent": intent, "poc_sample": poc_sample}, indent=2)
- valid = ValidationAgent(validation_input).run()
- print(f"Validation Result: {valid}")
- if valid:
- print(f"PoC for {cve_id} is valid and ready to use.")
- else:
- print(f"PoC for {cve_id} failed validation.")
+ # Stage 2: Validate PoC
+ validation_input = json.dumps({"attack_intent": intent, "poc_sample": poc_sample}, indent=2)
+ validation_agent = ValidationAgent(validation_input)
+ result = validation_agent.run()
+ print(f"Validation Result: {result}")
+
+ return {
+ "cve_id": cve_id,
+ "intent": intent,
+ "validation": result,
+ "status": "completed"
+ }
+
+ except Exception as e:
+ error_msg = f"Error processing {cve_id}: {str(e)}"
+ print(error_msg)
+ return {
+ "cve_id": cve_id,
+ "error": error_msg,
+ "status": "failed"
+ }
📝 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 run_pocky_for_cve(cve_id): | |
# Example: Simulate fetching a description and PoC (replace with real logic) | |
description = f"Description for {cve_id} (replace with real Exa/OpenAI search)" | |
poc_sample = f"PoC code for {cve_id} (replace with real PoC search)" | |
# Stage 2: Attack Intent | |
intent = AttackIntentAgent(description).run() | |
print(f"Attack Intent: {intent}") | |
# Stage 3: Validation | |
validation_input = json.dumps({"attack_intent": intent, "poc_sample": poc_sample}, indent=2) | |
valid = ValidationAgent(validation_input).run() | |
print(f"Validation Result: {valid}") | |
if valid: | |
print(f"PoC for {cve_id} is valid and ready to use.") | |
else: | |
print(f"PoC for {cve_id} failed validation.") | |
def run_pocky_for_cve(cve_id): | |
""" | |
Process a CVE ID to find and validate PoC exploits. | |
Args: | |
cve_id (str): The CVE identifier to process | |
Returns: | |
dict: Validation results with status and details | |
""" | |
if not cve_id or not isinstance(cve_id, str): | |
raise ValueError("CVE ID must be a non-empty string") | |
try: | |
# TODO: Implement real CVE description fetching using Exa API | |
description = f"Description for {cve_id} (TODO: implement real Exa/OpenAI search)" | |
poc_sample = f"PoC code for {cve_id} (TODO: implement real PoC search)" | |
# Stage 1: Extract attack intent | |
intent_agent = AttackIntentAgent(description) | |
intent = intent_agent.run() | |
print(f"Attack Intent: {intent}") | |
# Stage 2: Validate PoC | |
validation_input = json.dumps( | |
{"attack_intent": intent, "poc_sample": poc_sample}, | |
indent=2 | |
) | |
validation_agent = ValidationAgent(validation_input) | |
result = validation_agent.run() | |
print(f"Validation Result: {result}") | |
return { | |
"cve_id": cve_id, | |
"intent": intent, | |
"validation": result, | |
"status": "completed" | |
} | |
except Exception as e: | |
error_msg = f"Error processing {cve_id}: {str(e)}" | |
print(error_msg) | |
return { | |
"cve_id": cve_id, | |
"error": error_msg, | |
"status": "failed" | |
} |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/pocky_cybersecurity_poc_agent.py around lines
80 to 97, the run_pocky_for_cve function currently uses placeholder logic for
fetching CVE descriptions and PoC validation. Replace the placeholders with
actual implementations to fetch real CVE descriptions and PoC samples, and
implement proper validation logic in the ValidationAgent. Structure the function
to clearly separate fetching, intent analysis, and validation stages with real
data and meaningful processing.
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
The pull request adds several example Python scripts that demonstrate the use of PraisonAI agents with various tools. The scripts cover different use cases, including a Chile government services assistant, a mini court simulation, a memory pal search agent, a cybersecurity PoC agent, and a real estate chatbot. The main concern is the insecure practice of storing placeholder API keys directly in the code, which could lead to accidental commits of sensitive information.
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.
Storing the API key directly in os.environ
with a placeholder value is insecure. This could lead to accidental commits of the placeholder value. Consider removing this line and instructing users to set the environment variable externally.
os.environ['OPENAI_API_KEY'] = "Enter your api key" | |
# Remove this line to avoid committing the placeholder API key | |
# os.environ['OPENAI_API_KEY'] = "Enter your api key" |
import os | ||
|
||
# Enter your OpenAI API key here | ||
os.environ['OPENAI_API_KEY'] = 'Enter your api key' # <-- Replace with your 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.
Storing the API key directly in os.environ
with a placeholder value is insecure. This could lead to accidental commits of the placeholder value. Consider removing this line and instructing users to set the environment variable externally.
os.environ['OPENAI_API_KEY'] = 'Enter your api key' # <-- Replace with your OpenAI API key | |
# Remove this line to avoid committing the placeholder API key | |
# os.environ['OPENAI_API_KEY'] = 'Enter your api key' # <-- Replace with your OpenAI API key |
|
||
# 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 |
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.
Storing the API key directly in os.environ
with a placeholder value is insecure. This could lead to accidental commits of the placeholder value. Consider removing this line and instructing users to set the environment variable externally.
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY | |
# Remove this line to avoid committing the placeholder API key | |
# os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY |
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.
Consider using more descriptive variable names instead of directly assigning string literals to os.environ
. This improves readability and maintainability. For example, use firecrawl_api_key
and openai_api_key
.
os.environ['FIRECRAWL_API_KEY'] = "your api key here" | |
os.environ['OPENAI_API_KEY'] = "your api key here" | |
firecrawl_api_key = "your api key here" | |
openai_api_key = "your api key here" | |
os.environ['FIRECRAWL_API_KEY'] = firecrawl_api_key | |
os.environ['OPENAI_API_KEY'] = openai_api_key |
…nt-Services-Assistant.py
Summary by CodeRabbit