Skip to content

feat: Add WikipediaSearchTool for free research#5824

Open
devin-ai-integration[bot] wants to merge 4 commits into
mainfrom
devin/1778870264-add-wikipedia-search-tool
Open

feat: Add WikipediaSearchTool for free research#5824
devin-ai-integration[bot] wants to merge 4 commits into
mainfrom
devin/1778870264-add-wikipedia-search-tool

Conversation

@devin-ai-integration
Copy link
Copy Markdown
Contributor

@devin-ai-integration devin-ai-integration Bot commented May 15, 2026

Summary

Adds a native WikipediaSearchTool to crewai-tools, implementing the feature requested in #5823. This tool allows agents to search Wikipedia for topics and return concise summaries without requiring an API key.

Key features:

  • Searches Wikipedia using the wikipedia Python library (optional dependency)
  • Returns article title, URL, and configurable-length summary
  • Handles disambiguation errors by listing possible matches
  • Handles page-not-found errors gracefully
  • Supports configurable sentences (summary length), language (Wikipedia edition), and top_k (number of results)
  • Graceful error message when the wikipedia package is not installed

Files changed:

  • lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py — tool implementation
  • lib/crewai-tools/src/crewai_tools/tools/__init__.py — export WikipediaSearchTool
  • lib/crewai-tools/src/crewai_tools/__init__.py — export WikipediaSearchTool
  • lib/crewai-tools/pyproject.toml — add wikipedia optional dependency
  • lib/crewai-tools/tests/tools/test_wikipedia_search_tool.py — 14 unit tests

Review & Testing Checklist for Human

  • Verify WikipediaSearchTool works with a real Wikipedia query: WikipediaSearchTool().run(search_query="Python programming language")
  • Verify disambiguation handling: WikipediaSearchTool().run(search_query="Mercury")
  • Verify the tool works as an agent tool: assign it to a CrewAI agent and run a task

Notes

  • The wikipedia package is an optional dependency — install with pip install 'crewai-tools[wikipedia]'
  • All 14 tests pass locally with full mock coverage (no network calls in tests)
  • Follows existing tool patterns (ArxivPaperTool, BraveSearchTool)

Link to Devin session: https://app.devin.ai/sessions/462dbfe9f2784c86a29811a11eae6d96

Summary by CodeRabbit

  • New Features

    • WikipediaSearchTool: search Wikipedia with configurable language, number of results, and summary length.
  • Dependencies

    • Optional extra: wikipedia (>=1.4.0) available to enable Wikipedia search functionality.
  • Tests

    • Comprehensive test coverage added for search behavior, error cases, language/summary/top_k handling, and missing-package messaging.

Review Change Stack

Closes #5823

- Add WikipediaSearchTool that searches Wikipedia and returns concise summaries
- Handle disambiguation errors by listing possible matches
- Handle page not found errors gracefully
- Support configurable sentences, language, and top_k results
- Add wikipedia as optional dependency
- Add 14 unit tests with full mock coverage

Co-Authored-By: João <joao@crewai.com>
@devin-ai-integration
Copy link
Copy Markdown
Contributor Author

Prompt hidden (unlisted session)

@devin-ai-integration
Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 15, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b4b574bc-7d1f-4c6a-9b8e-b792b7567b8a

📥 Commits

Reviewing files that changed from the base of the PR and between 190b989 and af6cd17.

📒 Files selected for processing (1)
  • lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py

📝 Walkthrough

Walkthrough

Adds WikipediaSearchTool, an optional CrewAI tool that uses the wikipedia package to search and summarize articles with configurable language, sentences, and top_k; exports the tool, adds tests, and updates tool specs and optional dependencies.

Changes

WikipediaSearchTool Feature

Layer / File(s) Summary
Dependency and public API wiring
lib/crewai-tools/pyproject.toml, lib/crewai-tools/src/crewai_tools/__init__.py, lib/crewai-tools/src/crewai_tools/tools/__init__.py
Adds wikipedia>=1.4.0 as an optional dependency and exports WikipediaSearchTool from both the main package and tools submodule.
Tool implementation
lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py
Implements WikipediaSearchTool with conditional wikipedia import, Pydantic WikipediaSearchToolInput schema, configurable sentences, language, and top_k, _run performing top-k search with error handling, and _fetch_article handling disambiguation, missing pages, and other retrieval errors.
Test suite
lib/crewai-tools/tests/tools/test_wikipedia_search_tool.py
Comprehensive pytest module with fixtures and mocks covering initialization, parameter propagation, search success, empty results, disambiguation, page-not-found, generic exceptions, search failures, missing dependency messaging, and mixed-result scenarios.
Tool specification metadata
lib/crewai-tools/tool.specs.json
JSON spec entry for WikipediaSearchTool defining init params (language, sentences, top_k), run input schema requiring search_query, and tool metadata.

Sequence Diagram(s)

sequenceDiagram
  participant Agent as Agent
  participant Tool as WikipediaSearchTool
  participant Wikipedia as wikipedia API
  participant Output as Formatter
  Agent->>Tool: _run(search_query)
  alt wikipedia package available
    Tool->>Wikipedia: set_lang(language)
    Tool->>Wikipedia: search(search_query, top_k)
    alt search succeeds
      loop each result title
        Tool->>Wikipedia: page(title)
        Wikipedia-->>Tool: page(title, url, summary) / raise DisambiguationError / raise PageError / raise Exception
        Tool->>Output: format title, url, summary or error message
      end
      Tool-->>Agent: joined formatted results with --- separators
    else no results
      Tool-->>Agent: "No results found" message
    else search exception
      Tool-->>Agent: error message with exception details
    end
  else wikipedia not available
    Tool-->>Agent: installation guidance message
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Poem

🐰 I hop through pages, titles bright,

I fetch summaries by the soft moonlight,
Sentences counted, top-k in play,
I tidy links and errors away,
Knowledge bundled for your day.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding a WikipediaSearchTool feature to enable free research without API keys.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch devin/1778870264-add-wikipedia-search-tool

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Comment @coderabbitai help to get the list of available commands and usage tips.

github-actions Bot and others added 2 commits May 15, 2026 18:44
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py`:
- Around line 62-75: wikipedia.set_lang mutates module-global state and can race
across concurrent requests; wrap the language change and all subsequent calls
(the wikipedia.search(...) and the list comprehension calling
self._fetch_article(...)) in a safe language-scope: capture the current
wikipedia language, call wikipedia.set_lang(self.language), perform the search
and fetches, then restore the original language in a finally block (or use a
process-wide lock around these operations) so other threads/requests are not
affected; ensure you reference wikipedia.set_lang, wikipedia.search,
self._fetch_article, self.language and self.top_k when applying the fix.

In `@lib/crewai-tools/tool.specs.json`:
- Line 27323: The WikipediaSearchTool class is missing a package_dependencies
declaration so the generated tool.specs.json doesn't advertise the optional
'wikipedia' dependency; update the WikipediaSearchTool class definition
(WikipediaSearchTool in
crewai_tools.tools.wikipedia_search_tool.wikipedia_search_tool) to add a class
field package_dependencies: list[str] = Field(default_factory=lambda:
["wikipedia"]) so the spec generator includes the dependency (ensure you import
Field if not already).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c2cd6a40-ef43-40b3-9613-4837dced623e

📥 Commits

Reviewing files that changed from the base of the PR and between 75bb882 and eb1379d.

📒 Files selected for processing (6)
  • lib/crewai-tools/pyproject.toml
  • lib/crewai-tools/src/crewai_tools/__init__.py
  • lib/crewai-tools/src/crewai_tools/tools/__init__.py
  • lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py
  • lib/crewai-tools/tests/tools/test_wikipedia_search_tool.py
  • lib/crewai-tools/tool.specs.json

Comment on lines +62 to +75
wikipedia.set_lang(self.language)

try:
results = wikipedia.search(search_query, results=self.top_k)
except Exception as e:
logger.error(f"Wikipedia search error: {e}")
return f"Error searching Wikipedia: {e}"

if not results:
return f"No Wikipedia articles found for '{search_query}'."

output_parts = [self._fetch_article(title) for title in results]

return "\n\n---\n\n".join(output_parts)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

In wikipedia==1.4.0, does wikipedia.set_lang() mutate shared module-level state, and is concurrent use with different languages considered thread-safe?

💡 Result:

In the wikipedia library (version 1.4.0), the wikipedia.set_lang function does mutate shared module-level state [1]. Specifically, it updates the global API_URL variable and clears the internal caches for the search, suggest, and summary functions [1]. Because this state is stored at the module level, the library is not thread-safe for concurrent use with different languages [1]. If one thread calls wikipedia.set_lang to change the language, it will affect all other threads using the same imported wikipedia module, leading to race conditions where requests may be sent to the wrong language endpoint [1]. For applications requiring concurrent access to different languages, this library is unsuitable; alternative libraries that support instance-based clients (such as Wikipedia-API) should be used instead [2][3].

Citations:


🏁 Script executed:

find . -name "wikipedia_search_tool.py" -type f

Repository: crewAIInc/crewAI

Length of output: 149


🏁 Script executed:

sed -n '62,75p' ./lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py

Repository: crewAIInc/crewAI

Length of output: 550


🏁 Script executed:

wc -l ./lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py && head -60 ./lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py

Repository: crewAIInc/crewAI

Length of output: 1808


🏁 Script executed:

tail -45 ./lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py

Repository: crewAIInc/crewAI

Length of output: 1679


Serialize language-scoped Wikipedia calls to prevent cross-request language contamination.

wikipedia.set_lang() mutates module-level state. Under concurrent execution with different language values, the library's lack of thread-safety causes race conditions—search results and article fetches may be retrieved in the wrong language.

Proposed fix
 import logging
+import threading
 from typing import Any, ClassVar
 
 logger = logging.getLogger(__file__)
+_wikipedia_lock = threading.Lock()
 
     def _run(self, search_query: str, **kwargs: Any) -> str:
         if wikipedia is None:
             return (
                 "The 'wikipedia' package is required to use WikipediaSearchTool. "
                 "Install it with: pip install wikipedia"
             )
 
-        wikipedia.set_lang(self.language)
-
-        try:
-            results = wikipedia.search(search_query, results=self.top_k)
-        except Exception as e:
-            logger.error(f"Wikipedia search error: {e}")
-            return f"Error searching Wikipedia: {e}"
-
-        if not results:
-            return f"No Wikipedia articles found for '{search_query}'."
-
-        output_parts = [self._fetch_article(title) for title in results]
+        with _wikipedia_lock:
+            wikipedia.set_lang(self.language)
+            try:
+                results = wikipedia.search(search_query, results=self.top_k)
+            except Exception as e:
+                logger.error(f"Wikipedia search error: {e}")
+                return f"Error searching Wikipedia: {e}"
+
+            if not results:
+                return f"No Wikipedia articles found for '{search_query}'."
+
+            output_parts = [self._fetch_article(title) for title in results]
 
         return "\n\n---\n\n".join(output_parts)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py`
around lines 62 - 75, wikipedia.set_lang mutates module-global state and can
race across concurrent requests; wrap the language change and all subsequent
calls (the wikipedia.search(...) and the list comprehension calling
self._fetch_article(...)) in a safe language-scope: capture the current
wikipedia language, call wikipedia.set_lang(self.language), perform the search
and fetches, then restore the original language in a finally block (or use a
process-wide lock around these operations) so other threads/requests are not
affected; ensure you reference wikipedia.set_lang, wikipedia.search,
self._fetch_article, self.language and self.top_k when applying the fix.

"type": "object"
},
"name": "WikipediaSearchTool",
"package_dependencies": [],
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

SPEC_FILE="$(fd -a 'tool.specs.json$' | head -n1)"
echo "Spec file: ${SPEC_FILE}"

echo "WikipediaSearchTool entry:"
jq -r '.[] | select(.name=="WikipediaSearchTool") | {name, package_dependencies}' "${SPEC_FILE}"

echo
echo "Examples of tools with non-empty package_dependencies (for format/convention):"
jq -r '.[] | select((.package_dependencies | length) > 0) | {name, package_dependencies}' "${SPEC_FILE}" | head -n 80

echo
echo "Places in code that reference package_dependencies / tool.specs.json:"
rg -n --type=py -C2 '\bpackage_dependencies\b|tool\.specs\.json'

Repository: crewAIInc/crewAI

Length of output: 280


🏁 Script executed:

#!/bin/bash
set -euo pipefail

SPEC_FILE="lib/crewai-tools/tool.specs.json"

echo "=== JSON Structure Analysis ==="
echo "First 50 lines of the file:"
head -50 "${SPEC_FILE}"

echo ""
echo "=== Checking for WikipediaSearchTool ==="
grep -n "WikipediaSearchTool" "${SPEC_FILE}" | head -20

echo ""
echo "=== Line count around line 27323 ==="
sed -n '27315,27330p' "${SPEC_FILE}" | cat -n

Repository: crewAIInc/crewAI

Length of output: 2522


🏁 Script executed:

#!/bin/bash
set -euo pipefail

SPEC_FILE="lib/crewai-tools/tool.specs.json"

echo "=== WikipediaSearchTool package_dependencies ==="
jq '.tools[] | select(.name=="WikipediaSearchTool") | {name, package_dependencies}' "${SPEC_FILE}"

echo ""
echo "=== Tools with non-empty package_dependencies (for convention/format) ==="
jq '.tools[] | select((.package_dependencies | length) > 0) | {name, package_dependencies}' "${SPEC_FILE}" | head -100

echo ""
echo "=== Checking where package_dependencies is referenced ==="
rg -n 'package_dependencies' --type py --type json -C 2 | head -80

echo ""
echo "=== Checking pyproject.toml for wikipedia dependency ==="
if [ -f "pyproject.toml" ]; then
  grep -A 5 -B 5 'wikipedia' pyproject.toml
else
  echo "pyproject.toml not found in current directory"
fi

Repository: crewAIInc/crewAI

Length of output: 8349


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Searching for wikipedia in pyproject.toml ==="
cat pyproject.toml | grep -A 2 -B 2 wikipedia || echo "No wikipedia found in pyproject.toml (or file not found)"

echo ""
echo "=== Checking if any Python code actually reads/consumes package_dependencies ==="
rg -n 'package_dependencies' --type py

echo ""
echo "=== Looking for WikipediaSearchTool implementation file ==="
find . -type f -name "*.py" | xargs grep -l "class WikipediaSearchTool" 2>/dev/null | head -5

echo ""
echo "=== Checking imports in WikipediaSearchTool implementation ==="
find . -type f -name "*.py" | xargs grep -l "WikipediaSearchTool" 2>/dev/null | head -1 | xargs head -100

Repository: crewAIInc/crewAI

Length of output: 13129


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== WikipediaSearchTool implementation ==="
cat lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py

echo ""
echo "=== Broader search for wikipedia dependency in any config file ==="
rg -i 'wikipedia' pyproject.toml setup.py setup.cfg poetry.lock requirements.txt 2>/dev/null | head -20 || echo "No wikipedia found in config files"

echo ""
echo "=== Check how generate_tool_specs extracts package_dependencies ==="
sed -n '150,175p' lib/crewai-tools/src/crewai_tools/generate_tool_specs.py

Repository: crewAIInc/crewAI

Length of output: 4493


🏁 Script executed:

#!/bin/bash
set -euo pipefclayton

echo "=== Double-check: does WikipediaSearchTool class define package_dependencies field? ==="
grep -n "package_dependencies" lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py || echo "No package_dependencies field in WikipediaSearchTool"

echo ""
echo "=== Check if wikipedia is in any dependencies section (optional or otherwise) ==="
cat pyproject.toml | grep -A 20 "optional-dependencies\|dependencies" | head -80

Repository: crewAIInc/crewAI

Length of output: 118


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Double-check: does WikipediaSearchTool class define package_dependencies field? ==="
grep -n "package_dependencies" lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py || echo "No package_dependencies field in WikipediaSearchTool"

echo ""
echo "=== Check if wikipedia is in any dependencies section (optional or otherwise) ==="
cat pyproject.toml | grep -A 20 "optional-dependencies\|dependencies" | head -80

Repository: crewAIInc/crewAI

Length of output: 814


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Checking generate_tool_specs.py to see how it handles missing package_dependencies ==="
sed -n '140,170p' lib/crewai-tools/src/crewai_tools/generate_tool_specs.py

echo ""
echo "=== Comparing: a tool that has package_dependencies defined in code ==="
grep -A 5 "package_dependencies" lib/crewai-tools/src/crewai_tools/tools/tavily_search_tool/tavily_search_tool.py | head -10

echo ""
echo "=== Check broader tool ecosystem for missing optional deps pattern ==="
rg 'try:\s+import' lib/crewai-tools/src/crewai_tools/tools --multiline -A 2 | head -40

Repository: crewAIInc/crewAI

Length of output: 5164


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Find all tools with try/except imports but NO package_dependencies field ==="
find lib/crewai-tools/src/crewai_tools/tools -name "*.py" -type f -exec grep -l "try:.*import" {} \; | while read file; do
  if ! grep -q "package_dependencies" "$file"; then
    basename "$(dirname "$file")"
  fi
done | sort | uniq

echo ""
echo "=== Verify: does weaviate_tool define package_dependencies? ==="
grep "package_dependencies" lib/crewai-tools/src/crewai_tools/tools/weaviate_tool/vector_search.py

echo ""
echo "=== Review the key insight: how tool specs are generated from the Python tool class ==="
sed -n '55,75p' lib/crewai-tools/src/crewai_tools/generate_tool_specs.py

Repository: crewAIInc/crewAI

Length of output: 1212


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Check how the tool behaves without the optional dependency ==="
sed -n '55,70p' lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py

echo ""
echo "=== Compare with another tool that has try/except but DOES declare package_dependencies ==="
echo "Looking at patronus_eval_tool:"
grep -A 10 "try:" lib/crewai-tools/src/crewai_tools/tools/patronus_eval_tool/patronus_local_evaluator_tool.py | head -15

echo ""
grep -B 5 -A 5 "package_dependencies" lib/crewai-tools/src/crewai_tools/tools/patronus_eval_tool/patronus_local_evaluator_tool.py | head -15

echo ""
echo "=== Look at the actual PR context: check git diff or commit message ==="
git log --oneline -20 2>/dev/null | head -10 || echo "Git log not available"

Repository: crewAIInc/crewAI

Length of output: 1668


Add package_dependencies field to WikipediaSearchTool class.

WikipediaSearchTool imports wikipedia as an optional dependency (with graceful fallback), but the Python tool class doesn't declare it in a package_dependencies field. This means the spec won't advertise the dependency to downstream tooling that reads package_dependencies from the generated tool.specs.json.

Update the WikipediaSearchTool class in lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py to add:

package_dependencies: list[str] = Field(default_factory=lambda: ["wikipedia"])

The tool spec file is auto-generated from the Python class definition, so the change will flow through to tool.specs.json when specs are regenerated.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/crewai-tools/tool.specs.json` at line 27323, The WikipediaSearchTool
class is missing a package_dependencies declaration so the generated
tool.specs.json doesn't advertise the optional 'wikipedia' dependency; update
the WikipediaSearchTool class definition (WikipediaSearchTool in
crewai_tools.tools.wikipedia_search_tool.wikipedia_search_tool) to add a class
field package_dependencies: list[str] = Field(default_factory=lambda:
["wikipedia"]) so the spec generator includes the dependency (ensure you import
Field if not already).

Co-Authored-By: João <joao@crewai.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py`:
- Around line 55-71: In the _run method of WikipediaSearchTool, reject blank or
all-whitespace search_query before calling wikipedia.search: add a guard that
trims search_query (e.g., search_query.strip()) and if it is empty return a
clear message like "Please provide a non-empty search query" (or similar) so
wikipedia.search(...) is not invoked with whitespace-only input; update any
early returns to use the same message and keep existing error handling for
network exceptions (references: _run, search_query, wikipedia.search).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6900f2e1-580a-451e-8b2e-1d35c5037fc6

📥 Commits

Reviewing files that changed from the base of the PR and between eb1379d and 190b989.

📒 Files selected for processing (1)
  • lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py

Comment on lines +55 to +71
def _run(self, search_query: str, **kwargs: Any) -> str:
if wikipedia is None:
return (
"The 'wikipedia' package is required to use WikipediaSearchTool. "
"Install it with: pip install wikipedia"
)

wikipedia.set_lang(self.language)

try:
results = wikipedia.search(search_query, results=self.top_k)
except Exception as e:
logger.error(f"Wikipedia search error: {e}")
return f"Error searching Wikipedia: {e}"

if not results:
return f"No Wikipedia articles found for '{search_query}'."
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Reject blank queries before making a network call.

On Line 65, wikipedia.search(...) still runs when search_query is only whitespace. Add a guard so the tool fails fast with a clear message.

Proposed fix
 def _run(self, search_query: str, **kwargs: Any) -> str:
     if wikipedia is None:
         return (
             "The 'wikipedia' package is required to use WikipediaSearchTool. "
             "Install it with: pip install wikipedia"
         )
 
+    search_query = search_query.strip()
+    if not search_query:
+        return "Search query cannot be empty."
+
     wikipedia.set_lang(self.language)
📝 Committable suggestion

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

Suggested change
def _run(self, search_query: str, **kwargs: Any) -> str:
if wikipedia is None:
return (
"The 'wikipedia' package is required to use WikipediaSearchTool. "
"Install it with: pip install wikipedia"
)
wikipedia.set_lang(self.language)
try:
results = wikipedia.search(search_query, results=self.top_k)
except Exception as e:
logger.error(f"Wikipedia search error: {e}")
return f"Error searching Wikipedia: {e}"
if not results:
return f"No Wikipedia articles found for '{search_query}'."
def _run(self, search_query: str, **kwargs: Any) -> str:
if wikipedia is None:
return (
"The 'wikipedia' package is required to use WikipediaSearchTool. "
"Install it with: pip install wikipedia"
)
search_query = search_query.strip()
if not search_query:
return "Search query cannot be empty."
wikipedia.set_lang(self.language)
try:
results = wikipedia.search(search_query, results=self.top_k)
except Exception as e:
logger.error(f"Wikipedia search error: {e}")
return f"Error searching Wikipedia: {e}"
if not results:
return f"No Wikipedia articles found for '{search_query}'."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@lib/crewai-tools/src/crewai_tools/tools/wikipedia_search_tool/wikipedia_search_tool.py`
around lines 55 - 71, In the _run method of WikipediaSearchTool, reject blank or
all-whitespace search_query before calling wikipedia.search: add a guard that
trims search_query (e.g., search_query.strip()) and if it is empty return a
clear message like "Please provide a non-empty search query" (or similar) so
wikipedia.search(...) is not invoked with whitespace-only input; update any
early returns to use the same message and keep existing error handling for
network exceptions (references: _run, search_query, wikipedia.search).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants