-
-
Notifications
You must be signed in to change notification settings - Fork 690
Add Government Services Assistant Python script #687
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Add Government Services Assistant Python script #687
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 9 minutes and 52 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 (1)
WalkthroughA new Python script introduces an AI chatbot named Tomás that assists users with questions about Chilean government services. The script integrates translation between English and Spanish, leverages the Firecrawl API for web searches restricted to official Chilean government pages, and provides a command-line conversational interface for user interaction. Changes
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 a new Python script that acts as an AI assistant for Chilean government services. It facilitates user interaction by translating queries and search results, making complex information accessible to English speakers, and serves as a practical demonstration of integrating external tools within the existing framework.
Highlights
- New Feature: Chile Government Services Assistant: I've added a new Python script,
chile_government_services_assistant_.py
, which implements an AI-powered assistant named 'Tomás'. This assistant is designed to help users navigate Chilean government services and procedures. - Integration with Firecrawl and Translation: The script leverages the Firecrawl API to search for information on
chileatiende.gob.cl
(Chile's government services portal). It also incorporatesdeep-translator
to automatically translate user queries from English to Spanish for searching, and then translates the Spanish search results back into English for the user, providing a seamless experience. - PraisonAI Toolkit Example: This new script serves as an example within the
examples/python/tools/exa-tool
directory, demonstrating how to integrate and utilize external APIs and translation services within the PraisonAI toolkit for practical applications.
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. ↩
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 introduces a Python script for a Chile Government Services Assistant, which uses Firecrawl and automatic translation to help users interact with Chilean government services. The script is well-structured and includes error handling, but there are opportunities to improve readability and maintainability by using more descriptive variable names, adding comments to explain certain filtering steps, and breaking down long conditional statements. Additionally, defining FIRECRAWL_INSTRUCTION
and FIRECRAWL_TEMPLATE
as constants at the beginning of the script would improve configuration and readability.
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 than just assigning the string "your api key here". This will improve readability and make it clear what the variables are used for. Suggest replacing with a placeholder such as YOUR_FIRECRAWL_API_KEY
and YOUR_OPENAI_API_KEY
.
os.environ['FIRECRAWL_API_KEY'] = "your api key here" | |
os.environ['OPENAI_API_KEY'] = "your api key here" | |
os.environ['FIRECRAWL_API_KEY'] = "YOUR_FIRECRAWL_API_KEY" | |
os.environ['OPENAI_API_KEY'] = "YOUR_OPENAI_API_KEY" |
text = str(text).replace("None", "") | ||
text = re.sub(r'!\[.*?\]\(.*?\)', '', text) |
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.
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.
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## main #687 +/- ##
==========================================
- 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: 4
🧹 Nitpick comments (4)
examples/python/tools/exa-tool/chile_government_services_assistant_.py (4)
33-38
: Improve error handling in translation functionThe translation function should provide more specific error information and handle potential network issues.
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: {type(e).__name__}: {e}") return text
124-127
: Improve input validation and user experienceAdd input validation and handle empty input gracefully.
while True: user_input = input("\nYou: ") + + # Handle empty input + if not user_input.strip(): + print("Tomás: Please ask me a question about Chilean government services.") + continue + if user_input.lower() in ["exit", "quit"]: print("Tomás: It was a pleasure to help you. Goodbye!") break
61-62
: Consider more robust query validationThe current validation only checks length, but could be more comprehensive.
def search(self, search: str) -> str: - if not search or len(search) < 5: - return "Error: Please provide a valid search query (at least 5 characters)." + if not search or not search.strip() or len(search.strip()) < 3: + return "Error: Please provide a valid search query (at least 3 characters)." + + search = search.strip()
134-139
: Enhance error handling in main loopThe error handling could be more specific and user-friendly.
if spanish_answer and isinstance(spanish_answer, str) and spanish_answer.strip() and "Error" not in spanish_answer: try: english_answer = translate_to_english(spanish_answer) print("\nTomás (in English):\n", english_answer) - except Exception as e: - print(f"\nTomás: I found information, but couldn't translate it. Here it is in Spanish:\n{spanish_answer}\n(Translation error: {e})") + 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: {type(e).__name__})") else: print("\nTomás: Sorry, I couldn't find relevant information. Try rephrasing your question or ask about another service.")
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
examples/python/tools/exa-tool/chile_government_services_assistant_.py
(1 hunks)
🧰 Additional context used
🪛 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)
🪛 Flake8 (7.2.0)
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)
🪛 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)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: quick-test
- GitHub Check: test-core (3.11)
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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Remove unnecessary else clause
The else clause after return is unnecessary and reduces readability.
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
📝 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.
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 | |
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 | |
return None |
🧰 Tools
🪛 Pylint (3.3.7)
[refactor] 77-87: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
(R1705)
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/chile_government_services_assistant_.py around
lines 77 to 87, remove the else clause following the return statement since it
is unnecessary. Instead, after the if block that returns response_md, simply
return None directly without wrapping it in an else block to improve
readability.
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.
Critical Security Issue: Remove hardcoded API keys
Hardcoded API keys in source code pose a serious security risk and should never be 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 variables or .env file
+# os.environ['FIRECRAWL_API_KEY'] should be set externally
+# os.environ['OPENAI_API_KEY'] should be set externally
+
+if not os.environ.get('FIRECRAWL_API_KEY'):
+ raise ValueError("FIRECRAWL_API_KEY environment variable is required")
+if not os.environ.get('OPENAI_API_KEY'):
+ raise ValueError("OPENAI_API_KEY environment variable is required")
📝 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 variables or .env file | |
# os.environ['FIRECRAWL_API_KEY'] should be set externally | |
# os.environ['OPENAI_API_KEY'] should be set externally | |
if not os.environ.get('FIRECRAWL_API_KEY'): | |
raise ValueError("FIRECRAWL_API_KEY environment variable is required") | |
if not os.environ.get('OPENAI_API_KEY'): | |
raise ValueError("OPENAI_API_KEY environment variable is required") |
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/chile_government_services_assistant_.py at
lines 24 to 25, the API keys are hardcoded as plain strings, which is a critical
security risk. Remove these hardcoded keys and instead load them securely from
environment variables or a secure secrets manager at runtime, ensuring no
sensitive keys are stored 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.
Critical Runtime Error: Uncomment template definitions
The template variables are commented out but referenced in the initialization code, causing a runtime error.
-# 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
between lines 95 and 108, the template variables FIRECRAWL_INSTRUCTION and
FIRECRAWL_TEMPLATE are commented out but still referenced later, causing a
runtime error. To fix this, uncomment these variable definitions so they are
properly initialized and available for use in the code.
from firecrawl import FirecrawlApp, ScrapeOptions | ||
from deep_translator import GoogleTranslator | ||
import re |
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
Fix import organization
Imports should be placed at the top of the file according to PEP8 standards.
Move these imports to the top of the file after the initial comments:
+from firecrawl import FirecrawlApp, ScrapeOptions
+from deep_translator import GoogleTranslator
+import re
import os
-from firecrawl import FirecrawlApp, ScrapeOptions
-from deep_translator import GoogleTranslator
-import re
📝 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.
from firecrawl import FirecrawlApp, ScrapeOptions | |
from deep_translator import GoogleTranslator | |
import re |
🧰 Tools
🪛 Flake8 (7.2.0)
[error] 29-29: module level import not at top of file
(E402)
[error] 30-30: module level import not at top of file
(E402)
[error] 31-31: module level import not at top of file
(E402)
🤖 Prompt for AI Agents
In examples/python/tools/exa-tool/chile_government_services_assistant_.py around
lines 29 to 31, the imports are not placed at the top of the file as required by
PEP8. Move the import statements for FirecrawlApp, ScrapeOptions,
GoogleTranslator, and re to the very top of the file, immediately after any
initial comments or module docstrings, ensuring all imports are grouped together
before any other code.
…nt-Services-Assistant.py
This pull request adds a Python script for the Chile Government Services Assistant to the examples/python/tools/exa-tool directory.
The script enables users to interact with Chilean government services using Firecrawl and automatic translation, providing step-by-step answers in English.
It is designed for easy integration and demonstration within the PraisonAI toolkit, supporting citizens in navigating public procedures.
Summary by CodeRabbit