-
Notifications
You must be signed in to change notification settings - Fork 8.4k
feat(tools): add SearchApiTool for searchapi.io #7212
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| --- | ||
| title: بحث SearchApi | ||
| description: أداة `SearchApiTool` تبحث في الإنترنت عبر SearchApi، الذي يجمع عدة محركات بحث خلف نقطة نهاية واحدة. | ||
| icon: magnifying-glass | ||
| mode: "wide" | ||
| --- | ||
|
|
||
| # `SearchApiTool` | ||
|
|
||
| ## الوصف | ||
|
|
||
| أداة `SearchApiTool` تبحث في الإنترنت عبر [SearchApi](https://www.searchapi.io). نقطة نهاية واحدة تجمع عدة محركات، تُختار بالمعامل `engine`، لذا تغطي أداة واحدة بحث Google على الويب والأخبار والأبحاث الأكاديمية والوظائف، إضافة إلى Bing و YouTube و Baidu وبقية [المحركات المدعومة](https://www.searchapi.io/docs). تُرجع الأداة JSON الخاص بالمحرك نفسه، لذا تتطابق النتائج مع توثيق ذلك المحرك. | ||
|
|
||
| يحدث أمران للاستجابة قبل أن يراها الـ Agent: | ||
|
|
||
| - تُحذف روابط `data:` المضمّنة. يُرجع SearchApi الأيقونات والصور المصغّرة كسلاسل base64، وقد تبلغ الواحدة منها عشرات الكيلوبايتات من السياق الذي لا يعني شيئًا للـ Agent. | ||
| - تُقتطع السلاسل الطويلة عند `max_string_length`، وتُحدَّد كل قائمة `*_results` بعدد `n_results`. | ||
|
|
||
| ## التثبيت | ||
|
|
||
| 1. **تثبيت الحزمة**: تأكد من تثبيت حزمة `crewai[tools]` في بيئة Python لديك. | ||
| 2. **الحصول على مفتاح API**: احصل على مفتاح SearchApi من https://www.searchapi.io (تتوفر خطة مجانية). | ||
| 3. **إعداد البيئة**: احفظ المفتاح في متغير بيئة باسم `SEARCHAPI_API_KEY`. | ||
|
|
||
| ```shell | ||
| pip install 'crewai[tools]' | ||
| ``` | ||
|
|
||
| يُرسَل المفتاح في ترويسة `Authorization` بدلًا من سلسلة الاستعلام، لذا يبقى خارج سجلات الطلبات وخارج `request_url` الذي يعيده SearchApi في `search_metadata`. | ||
|
|
||
| ## مثال | ||
|
|
||
| ```python Code | ||
| from crewai_tools import SearchApiTool | ||
|
|
||
| # Initialize the tool for internet searching capabilities | ||
| tool = SearchApiTool() | ||
| ``` | ||
|
|
||
| ## المعاملات | ||
|
|
||
| - **engine**: محرك SearchApi المطلوب، مثل `google` أو `google_news` أو `google_scholar` أو `google_jobs` أو `bing` أو `youtube` أو `baidu`. القيمة الافتراضية `google`. ويمكن تمريره مع كل استدعاء. | ||
| - **n_results**: الحد الأقصى لطول كل قائمة `*_results` في الاستجابة. القيمة الافتراضية `10`. | ||
| - **country**: اختياري. بلد البحث، يُرسَل باسم `gl` (مثل `uk`). | ||
| - **locale**: اختياري. لغة الواجهة، تُرسَل باسم `hl` (مثل `en`). | ||
| - **location**: اختياري. الموقع المعياري للبحث، مثل `London,England`. | ||
| - **max_string_length**: أطول سلسلة تبقى كما هي في الاستجابة. القيمة الافتراضية `1000`. | ||
| - **timeout**: مهلة الطلب بالثواني. القيمة الافتراضية `30`. | ||
| - **api_key**: اختياري. مفتاح SearchApi الخاص بك. وإن لم يُحدَّد، يُقرأ من متغير البيئة `SEARCHAPI_API_KEY`. | ||
| - **search_url**: نقطة النهاية التي تُستدعى. القيمة الافتراضية `https://www.searchapi.io/api/v1/search`. | ||
|
|
||
| ## مثال مع المعاملات | ||
|
|
||
| ```python Code | ||
| from crewai_tools import SearchApiTool | ||
|
|
||
| # Recent news, localized to the UK | ||
| news_tool = SearchApiTool( | ||
| engine="google_news", | ||
| country="uk", | ||
| locale="en", | ||
| location="London,England", | ||
| n_results=5, | ||
| ) | ||
|
|
||
| # Academic search through the same tool | ||
| scholar_tool = SearchApiTool(engine="google_scholar") | ||
| ``` | ||
|
|
||
| ## الأخطاء | ||
|
|
||
| يؤدي فشل الطلب إلى إطلاق `RuntimeError` يحمل رسالة SearchApi نفسها، مثل `SearchApi request failed (HTTP 401): Invalid API key.`. | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win 🔎 Supported by static analysis🏁 Script executed: #!/bin/bash
set -e
printf '%s\n' '--- applicable convention files ---'
find /tmp/coderabbit-repo-knowledge/crewaiinc-crewai-a921f2d1 -maxdepth 2 -type f -name '*.md' -print
printf '%s\n' '--- documentation context ---'
cat -n docs/edge/ar/tools/search-research/searchapitool.mdx | sed -n '1,90p'
printf '%s\n' '--- SearchApiTool definitions and references ---'
rg -n -S --glob '!docs/edge/ar/tools/search-research/searchapitool.mdx' \
'class SearchApiTool|def _run|SearchApiTool|SearchApi request failed' .
printf '%s\n' '--- candidate implementation files ---'
git ls-files | rg -i 'search.*api|api.*search'Repository: crewAIInc/crewAI Length of output: 50373 🏁 Script executed: #!/bin/bash
set -e
printf '%s\n' '--- prior log beginning ---'
sed -n '1,120p' /tmp/coderabbit-shell-logs/shell-output-nNDsXt
printf '%s\n' '--- exact SearchApi matches ---'
rg -n -S --max-count 80 \
'SearchApiTool|SearchApi request failed|searchapi' \
--glob '*.py' --glob '*.mdx' --glob '*.md' --glob '*.toml' --glob '*.yml' --glob '*.yaml' .
printf '%s\n' '--- changed documentation context ---'
cat -n docs/edge/ar/tools/search-research/searchapitool.mdx | sed -n '20,80p'Repository: crewAIInc/crewAI Length of output: 24468 🏁 Script executed: #!/bin/bash
set -e
printf '%s\n' '--- documentation convention ---'
cat -n /tmp/coderabbit-repo-knowledge/crewaiinc-crewai-a921f2d1/conventions/docs.md
printf '%s\n' '--- SearchApiTool implementation ---'
cat -n lib/crewai-tools/src/crewai_tools/tools/searchapi_tool/searchapi_tool.py | sed -n '105,180p'
printf '%s\n' '--- direct SearchApiTool tests ---'
cat -n lib/crewai-tools/tests/tools/searchapi_tool_test.py | sed -n '1,220p'Repository: crewAIInc/crewAI Length of output: 11655 Limit this sentence to HTTP failures.
🤖 Prompt for AI Agents |
||
|
|
||
| أما البحث الناجح الذي لم يجد شيئًا فليس خطأً: يُرجع SearchApi استجابة HTTP 200 مع رسالة `error` مثل `"Google didn't return any results."`، وتمرّر الأداة هذه الرسالة كما هي ليقرأ الـ Agent سبب خلو الصفحة. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| --- | ||
| title: SearchApi Search | ||
| description: The `SearchApiTool` searches the internet through SearchApi, which fronts many search engines behind one endpoint. | ||
| icon: magnifying-glass | ||
| mode: "wide" | ||
| --- | ||
|
|
||
| # `SearchApiTool` | ||
|
|
||
| ## Description | ||
|
|
||
| The `SearchApiTool` searches the internet through [SearchApi](https://www.searchapi.io). One endpoint fronts many engines, chosen with the `engine` parameter, so a single tool covers Google web search, news, scholar and jobs, plus Bing, YouTube, Baidu and the rest of the [supported engines](https://www.searchapi.io/docs). The tool returns the engine's own JSON, so results line up with the engine's documentation. | ||
|
|
||
| Two things happen to the response before an agent sees it: | ||
|
|
||
| - Inline `data:` URIs are dropped. SearchApi returns favicons and thumbnails as base64 strings, and a single one can run to tens of kilobytes of context that means nothing to an agent. | ||
| - Long strings are truncated at `max_string_length`, and every `*_results` list is capped at `n_results`. | ||
|
|
||
| ## Installation | ||
|
|
||
| 1. **Package Installation**: Confirm that the `crewai[tools]` package is installed in your Python environment. | ||
| 2. **API Key Acquisition**: Get a SearchApi key at https://www.searchapi.io (free tier available). | ||
| 3. **Environment Configuration**: Store the key in an environment variable named `SEARCHAPI_API_KEY`. | ||
|
|
||
| ```shell | ||
| pip install 'crewai[tools]' | ||
| ``` | ||
|
|
||
| The key is sent in the `Authorization` header rather than the query string, so it stays out of request logs and out of the `request_url` SearchApi echoes back in `search_metadata`. | ||
|
|
||
| ## Example | ||
|
|
||
| ```python Code | ||
| from crewai_tools import SearchApiTool | ||
|
|
||
| # Initialize the tool for internet searching capabilities | ||
| tool = SearchApiTool() | ||
| ``` | ||
|
|
||
| ## Parameters | ||
|
|
||
| - **engine**: The SearchApi engine to query, such as `google`, `google_news`, `google_scholar`, `google_jobs`, `bing`, `youtube` or `baidu`. Default is `google`. Can also be passed per call. | ||
| - **n_results**: Cap on the length of each `*_results` list in the response. Default is `10`. | ||
| - **country**: Optional. Country of the search, sent as `gl` (for example `uk`). | ||
| - **locale**: Optional. Interface language, sent as `hl` (for example `en`). | ||
| - **location**: Optional. Canonical location of the search, for example `London,England`. | ||
| - **max_string_length**: Longest string kept intact in the response. Default is `1000`. | ||
| - **timeout**: Request timeout in seconds. Default is `30`. | ||
| - **api_key**: Optional. Your SearchApi key. Falls back to the `SEARCHAPI_API_KEY` environment variable. | ||
| - **search_url**: The endpoint to call. Default is `https://www.searchapi.io/api/v1/search`. | ||
|
|
||
| ## Example with Parameters | ||
|
|
||
| ```python Code | ||
| from crewai_tools import SearchApiTool | ||
|
|
||
| # Recent news, localized to the UK | ||
| news_tool = SearchApiTool( | ||
| engine="google_news", | ||
| country="uk", | ||
| locale="en", | ||
| location="London,England", | ||
| n_results=5, | ||
| ) | ||
|
|
||
| # Academic search through the same tool | ||
| scholar_tool = SearchApiTool(engine="google_scholar") | ||
| ``` | ||
|
|
||
| ## Errors | ||
|
|
||
| A failed request raises a `RuntimeError` carrying SearchApi's own message, for example `SearchApi request failed (HTTP 401): Invalid API key.`. | ||
|
|
||
| A successful search that found nothing is not an error: SearchApi returns HTTP 200 with an `error` message such as `"Google didn't return any results."`, and the tool passes that through so the agent can read why the page was empty. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| --- | ||
| title: SearchApi 검색 | ||
| description: SearchApiTool은(는) 여러 검색 엔진을 하나의 엔드포인트로 제공하는 SearchApi를 통해 인터넷을 검색합니다. | ||
| icon: magnifying-glass | ||
| mode: "wide" | ||
| --- | ||
|
|
||
| # `SearchApiTool` | ||
|
|
||
| ## 설명 | ||
|
|
||
| `SearchApiTool`은 [SearchApi](https://www.searchapi.io)를 통해 인터넷을 검색합니다. 하나의 엔드포인트가 여러 엔진을 제공하며 `engine` 파라미터로 선택하므로, 단일 도구로 Google 웹 검색, 뉴스, 학술, 채용 정보는 물론 Bing, YouTube, Baidu 및 나머지 [지원 엔진](https://www.searchapi.io/docs)까지 다룰 수 있습니다. 이 도구는 엔진의 JSON을 그대로 반환하므로 결과는 해당 엔진의 문서와 일치합니다. | ||
|
|
||
| 에이전트가 응답을 보기 전에 두 가지 처리가 이루어집니다: | ||
|
|
||
| - 인라인 `data:` URI가 제거됩니다. SearchApi는 파비콘과 썸네일을 base64 문자열로 반환하는데, 하나만으로도 수십 킬로바이트에 이를 수 있으며 에이전트에게는 아무런 의미가 없습니다. | ||
| - 긴 문자열은 `max_string_length`에서 잘리고, 모든 `*_results` 목록은 `n_results` 개수로 제한됩니다. | ||
|
|
||
| ## 설치 | ||
|
|
||
| 1. **패키지 설치**: Python 환경에 `crewai[tools]` 패키지가 설치되어 있는지 확인하세요. | ||
| 2. **API 키 발급**: https://www.searchapi.io 에서 SearchApi 키를 발급받으세요(무료 티어 제공). | ||
| 3. **환경 설정**: 발급받은 키를 `SEARCHAPI_API_KEY`라는 환경 변수에 저장하세요. | ||
|
|
||
| ```shell | ||
| pip install 'crewai[tools]' | ||
| ``` | ||
|
|
||
| 키는 쿼리 문자열이 아니라 `Authorization` 헤더로 전송되므로, 요청 로그와 SearchApi가 `search_metadata`에 되돌려주는 `request_url`에 노출되지 않습니다. | ||
|
|
||
| ## 예제 | ||
|
|
||
| ```python Code | ||
| from crewai_tools import SearchApiTool | ||
|
|
||
| # Initialize the tool for internet searching capabilities | ||
| tool = SearchApiTool() | ||
| ``` | ||
|
|
||
| ## 파라미터 | ||
|
|
||
| - **engine**: 호출할 SearchApi 엔진입니다. 예: `google`, `google_news`, `google_scholar`, `google_jobs`, `bing`, `youtube`, `baidu`. 기본값은 `google`입니다. 호출할 때마다 전달할 수도 있습니다. | ||
| - **n_results**: 응답에서 각 `*_results` 목록의 최대 길이입니다. 기본값은 `10`입니다. | ||
| - **country**: 선택 사항. 검색 대상 국가이며 `gl`로 전송됩니다(예: `uk`). | ||
| - **locale**: 선택 사항. 인터페이스 언어이며 `hl`로 전송됩니다(예: `en`). | ||
| - **location**: 선택 사항. 검색의 표준 위치입니다(예: `London,England`). | ||
| - **max_string_length**: 응답에서 그대로 유지되는 문자열의 최대 길이입니다. 기본값은 `1000`입니다. | ||
| - **timeout**: 요청 타임아웃(초)입니다. 기본값은 `30`입니다. | ||
| - **api_key**: 선택 사항. SearchApi 키입니다. 지정하지 않으면 `SEARCHAPI_API_KEY` 환경 변수를 사용합니다. | ||
| - **search_url**: 호출할 엔드포인트입니다. 기본값은 `https://www.searchapi.io/api/v1/search`입니다. | ||
|
|
||
| ## 파라미터를 사용한 예제 | ||
|
|
||
| ```python Code | ||
| from crewai_tools import SearchApiTool | ||
|
|
||
| # Recent news, localized to the UK | ||
| news_tool = SearchApiTool( | ||
| engine="google_news", | ||
| country="uk", | ||
| locale="en", | ||
| location="London,England", | ||
| n_results=5, | ||
| ) | ||
|
|
||
| # Academic search through the same tool | ||
| scholar_tool = SearchApiTool(engine="google_scholar") | ||
| ``` | ||
|
|
||
| ## 오류 | ||
|
|
||
| 요청이 실패하면 SearchApi의 메시지를 담은 `RuntimeError`가 발생합니다. 예: `SearchApi request failed (HTTP 401): Invalid API key.` | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win 🔎 Supported by static analysis🏁 Script executed: printf '%s\n' '--- scoped conventions ---'
find /tmp/coderabbit-repo-knowledge/crewaiinc-crewai-a921f2d1 -maxdepth 2 -type f -name '*.md' -print
printf '%s\n' '--- target document ---'
sed -n '1,100p' docs/edge/ko/tools/search-research/searchapitool.mdx
printf '%s\n' '--- SearchApiTool definitions and references ---'
rg -n -S --glob '!docs/edge/ko/tools/search-research/searchapitool.mdx' 'class SearchApiTool|SearchApiTool|SearchApi request failed|searchapi|SearchApi' .Repository: crewAIInc/crewAI Length of output: 24492 🏁 Script executed: printf '%s\n' '--- documentation conventions ---'
cat /tmp/coderabbit-repo-knowledge/crewaiinc-crewai-a921f2d1/conventions/docs.md
cat /tmp/coderabbit-repo-knowledge/crewaiinc-crewai-a921f2d1/learnings/docs-edge.md
cat /tmp/coderabbit-repo-knowledge/crewaiinc-crewai-a921f2d1/learnings/mdx.md
printf '%s\n' '--- SearchApiTool source ---'
cat -n lib/crewai-tools/src/crewai_tools/tools/searchapi_tool/searchapi_tool.py | sed -n '1,190p'
printf '%s\n' '--- directly bound tests ---'
cat -n lib/crewai-tools/tests/tools/searchapi_tool_test.py | sed -n '1,215p'Repository: crewAIInc/crewAI Length of output: 17873 🌐 Web query:
💡 Result: When using the Python requests library, network issues and timeout events raise specific exceptions that you can handle to prevent your application from hanging or crashing [1][2]. All exceptions explicitly raised by requests inherit from requests.exceptions.RequestException [1]. Timeout Exceptions If you set a timeout parameter in requests.get (or other methods), requests raises a Timeout exception if the server does not respond within the specified time [1][2]. - requests.exceptions.Timeout: The base class for timeout errors. Catching this will capture both connection and read timeouts [3][4]. - requests.exceptions.ConnectTimeout: Raised specifically if the request times out while trying to establish a connection to the remote server [3][4]. Requests marks these as safe to retry [3][4]. - requests.exceptions.ReadTimeout: Raised if the server fails to send any data within the allotted time after a connection has been established [5][4]. Connection Exceptions If a network-level problem occurs—such as a DNS failure or a refused connection—requests raises a ConnectionError [1][4]. - requests.exceptions.ConnectionError: The base class for connection-related issues [3][4]. - Note: ConnectTimeout is a subclass of both ConnectionError and Timeout [5]. Example Implementation It is recommended to wrap requests in a try-except block to handle these cases gracefully: import requests from requests.exceptions import Timeout, ConnectionError, RequestException try: response = requests.get('https://example.com', timeout=(3.05, 27)) response.raise_for_status except ConnectTimeout: print("The request timed out while connecting.") except ReadTimeout: print("The request timed out while waiting for data.") except ConnectionError: print("A network error occurred (e.g., DNS, connection refused).") except Timeout: print("A generic timeout error occurred.") except RequestException as e: print(f"An ambiguous error occurred: {e}") For production code, it is essential to always provide a timeout value, as the default behavior in requests is to wait indefinitely [1][2]. You can provide a single float for both connect and read timeouts, or a tuple (connect, read) for granular control [3][2]. Citations:
Limit this sentence to HTTP failures.
🤖 Prompt for AI Agents |
||
|
|
||
| 검색은 성공했지만 결과가 없는 경우는 오류가 아닙니다. SearchApi는 HTTP 200과 함께 `"Google didn't return any results."` 같은 `error` 메시지를 반환하며, 이 도구는 에이전트가 그 이유를 읽을 수 있도록 해당 메시지를 그대로 전달합니다. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| --- | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win 🔎 Supported by static analysis🏁 Script executed: #!/bin/bash
set -eu
printf '%s\n' '--- applicable repository conventions ---'
find /tmp/coderabbit-repo-knowledge/crewaiinc-crewai-a921f2d1 -type f -name '*.md' -maxdepth 3 -print
printf '%s\n' '--- localized document excerpts ---'
for f in \
docs/edge/pt-BR/tools/search-research/searchapitool.mdx \
docs/edge/ko/tools/search-research/searchapitool.mdx \
docs/edge/ar/tools/search-research/searchapitool.mdx; do
echo "### $f"
sed -n '1,95p' "$f"
done
printf '%s\n' '--- implementation and references ---'
rg -n -C 4 'SearchApiTool|request failure|RuntimeError|transport|raise_for_status|status_code' \
docs src crewai 2>/dev/null | head -300Repository: crewAIInc/crewAI Length of output: 32428 🏁 Script executed: #!/bin/bash
set -eu
for f in /tmp/coderabbit-repo-knowledge/crewaiinc-crewai-a921f2d1/*/*.md; do
case "$f" in
*convention*|*conventions*|*/architecture/*|*/learnings/*) printf '\n### %s\n' "$f"; head -120 "$f";;
esac
doneRepository: crewAIInc/crewAI Length of output: 16757 🏁 Script executed: #!/bin/bash
set -eu
printf '%s\n' '--- SearchApiTool definitions and direct callers ---'
rg -n -C 8 'class SearchApiTool|SearchApiTool|search_url|SEARCHAPI_API_KEY' \
lib/crewai-tools/src lib/crewai-tools/tests docs/edge 2>/dev/null | head -240
printf '%s\n' '--- candidate files ---'
fd -i 'searchapi' lib/crewai-toolsRepository: crewAIInc/crewAI Length of output: 22157 🏁 Script executed: #!/bin/bash
set -eu
printf '%s\n' '--- implementation ---'
cat -n lib/crewai-tools/src/crewai_tools/tools/searchapi_tool/searchapi_tool.py
printf '%s\n' '--- error tests ---'
sed -n '155,230p' lib/crewai-tools/tests/tools/searchapi_tool_test.py
printf '%s\n' '--- English source documentation error section ---'
sed -n '65,95p' lib/crewai-tools/src/crewai_tools/tools/searchapi_tool/README.mdRepository: crewAIInc/crewAI Length of output: 11145 Document HTTP and transport failures separately. 🤖 Prompt for AI Agents |
||
| title: Pesquisa SearchApi | ||
| description: O `SearchApiTool` pesquisa na internet através do SearchApi, que reúne vários motores de busca em um único endpoint. | ||
| icon: magnifying-glass | ||
| mode: "wide" | ||
| --- | ||
|
|
||
| # `SearchApiTool` | ||
|
|
||
| ## Descrição | ||
|
|
||
| O `SearchApiTool` pesquisa na internet através do [SearchApi](https://www.searchapi.io). Um único endpoint reúne vários motores, escolhidos com o parâmetro `engine`, de modo que uma só ferramenta cobre a busca web do Google, notícias, artigos acadêmicos e vagas, além de Bing, YouTube, Baidu e os demais [motores suportados](https://www.searchapi.io/docs). A ferramenta retorna o JSON do próprio motor, então os resultados correspondem à documentação dele. | ||
|
|
||
| Duas coisas acontecem com a resposta antes que um agente a veja: | ||
|
|
||
| - URIs `data:` embutidas são descartadas. O SearchApi retorna favicons e miniaturas como strings base64, e uma única delas pode chegar a dezenas de kilobytes de contexto que não significam nada para um agente. | ||
| - Strings longas são truncadas em `max_string_length`, e cada lista `*_results` é limitada a `n_results`. | ||
|
|
||
| ## Instalação | ||
|
|
||
| 1. **Instalação do pacote**: confirme que o pacote `crewai[tools]` está instalado no seu ambiente Python. | ||
| 2. **Obtenção da chave de API**: obtenha uma chave do SearchApi em https://www.searchapi.io (há um plano gratuito). | ||
| 3. **Configuração do ambiente**: guarde a chave em uma variável de ambiente chamada `SEARCHAPI_API_KEY`. | ||
|
|
||
| ```shell | ||
| pip install 'crewai[tools]' | ||
| ``` | ||
|
|
||
| A chave é enviada no cabeçalho `Authorization` em vez da query string, portanto não aparece nos logs de requisição nem no `request_url` que o SearchApi devolve em `search_metadata`. | ||
|
|
||
| ## Exemplo | ||
|
|
||
| ```python Code | ||
| from crewai_tools import SearchApiTool | ||
|
|
||
| # Initialize the tool for internet searching capabilities | ||
| tool = SearchApiTool() | ||
| ``` | ||
|
|
||
| ## Parâmetros | ||
|
|
||
| - **engine**: o motor do SearchApi a consultar, como `google`, `google_news`, `google_scholar`, `google_jobs`, `bing`, `youtube` ou `baidu`. O padrão é `google`. Também pode ser passado a cada chamada. | ||
| - **n_results**: limite do tamanho de cada lista `*_results` na resposta. O padrão é `10`. | ||
| - **country**: opcional. País da pesquisa, enviado como `gl` (por exemplo, `uk`). | ||
| - **locale**: opcional. Idioma da interface, enviado como `hl` (por exemplo, `en`). | ||
| - **location**: opcional. Localização canônica da pesquisa, por exemplo `London,England`. | ||
| - **max_string_length**: maior string mantida intacta na resposta. O padrão é `1000`. | ||
| - **timeout**: tempo limite da requisição em segundos. O padrão é `30`. | ||
| - **api_key**: opcional. Sua chave do SearchApi. Na ausência dela, usa a variável de ambiente `SEARCHAPI_API_KEY`. | ||
| - **search_url**: o endpoint chamado. O padrão é `https://www.searchapi.io/api/v1/search`. | ||
|
|
||
| ## Exemplo com parâmetros | ||
|
|
||
| ```python Code | ||
| from crewai_tools import SearchApiTool | ||
|
|
||
| # Recent news, localized to the UK | ||
| news_tool = SearchApiTool( | ||
| engine="google_news", | ||
| country="uk", | ||
| locale="en", | ||
| location="London,England", | ||
| n_results=5, | ||
| ) | ||
|
|
||
| # Academic search through the same tool | ||
| scholar_tool = SearchApiTool(engine="google_scholar") | ||
| ``` | ||
|
|
||
| ## Erros | ||
|
|
||
| Uma requisição malsucedida levanta um `RuntimeError` com a mensagem do próprio SearchApi, por exemplo `SearchApi request failed (HTTP 401): Invalid API key.`. | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win 🔎 Supported by static analysis🏁 Script executed: printf '%s\n' '--- repository conventions ---'
find /tmp/coderabbit-repo-knowledge/crewaiinc-crewai-a921f2d1 -type f -path '*/conventions/*' -o -path '*/learnings/*' -o -path '*/architecture/*' | sort
printf '%s\n' '--- target page ---'
cat -n docs/edge/pt-BR/tools/search-research/searchapitool.mdx | sed -n '55,85p'
printf '%s\n' '--- related SearchApiTool definitions and callers ---'
rg -n -g '*.py' -g '*.mdx' 'class SearchApiTool|SearchApiTool|requests\.get|RuntimeError|SearchApi request failed' .Repository: crewAIInc/crewAI Length of output: 50375 🏁 Script executed: printf '%s\n' '--- repository conventions ---'
find /tmp/coderabbit-repo-knowledge/crewaiinc-crewai-a921f2d1 \( -path '*/conventions/*' -o -path '*/learnings/*' -o -path '*/architecture/*' \) -type f | sort
printf '%s\n' '--- target page ---'
cat -n docs/edge/pt-BR/tools/search-research/searchapitool.mdx | sed -n '55,85p'
printf '%s\n' '--- related SearchApiTool definitions and callers ---'
rg -n -g '*.py' -g '*.mdx' 'class SearchApiTool|SearchApiTool|requests\.get|RuntimeError|SearchApi request failed' .Repository: crewAIInc/crewAI Length of output: 50375 🏁 Script executed: printf '%s\n' '--- docs convention ---'
cat /tmp/coderabbit-repo-knowledge/crewaiinc-crewai-a921f2d1/conventions/docs.md
printf '%s\n' '--- docs-edge learnings ---'
cat /tmp/coderabbit-repo-knowledge/crewaiinc-crewai-a921f2d1/learnings/docs-edge.md
printf '%s\n' '--- SearchApiTool implementation ---'
cat -n lib/crewai-tools/src/crewai_tools/tools/searchapi_tool/searchapi_tool.py | sed -n '1,220p'Repository: crewAIInc/crewAI Length of output: 9383 Limite esta frase a falhas HTTP.
🧰 Tools🪛 LanguageTool[uncategorized] ~72-~72: Esta locução deve ser separada por vírgulas. (VERB_COMMA_CONJUNCTION) 🤖 Prompt for AI Agents |
||
|
|
||
| Uma pesquisa bem-sucedida que não encontrou nada não é um erro: o SearchApi retorna HTTP 200 com uma mensagem `error` como `"Google didn't return any results."`, e a ferramenta repassa isso para que o agente possa ler por que a página veio vazia. | ||
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 & Privacy | 🟡 Minor | ⚡ Quick win
Sensitive Data Exposure (CWE-532): Insertion of Sensitive Information into Log File
Limit the logging guarantee to the request URL.
Authorizationkeeps the key out ofrequest_url, but this code does not prevent clients, proxies, or middleware from logging headers. State only the URL guarantee, or document the required header-redaction policy.🤖 Prompt for AI Agents