Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.
[OSS-149] Accept 1/yes/on on telemetry disable flags (#7185)
Vidit Ostwal818f2624e847
diff --git a/docs/edge/ar/telemetry.mdx b/docs/edge/ar/telemetry.mdxindex 0bffea1e7..dd9ac0a24 100644--- a/docs/edge/ar/telemetry.mdx+++ b/docs/edge/ar/telemetry.mdx@@ -23,7 +23,7 @@ mode: "wide"عند تفعيل ميزة `share_crew`، يتم جمع بيانات تفصيلية تشمل أوصاف المهام وخلفيات وأهداف الوكلاء وسمات محددة أخرىلتوفير رؤى أعمق. قد يتضمن جمع البيانات الموسع هذا معلومات شخصية إذا دمجها المستخدمون في طواقمهم أو مهامهم.يجب على المستخدمين النظر بعناية في محتوى طواقمهم ومهامهم قبل تفعيل `share_crew`.-يمكن للمستخدمين تعطيل القياس عن بُعد عبر تعيين متغير البيئة `CREWAI_DISABLE_TELEMETRY` إلى `true` أو تعيين `OTEL_SDK_DISABLED` إلى `true` (لاحظ أن الأخير يعطل جميع أدوات OpenTelemetry عالمياً).+يمكن للمستخدمين تعطيل القياس عن بُعد في CrewAI عبر تعيين `CREWAI_DISABLE_TELEMETRY` إلى `true` أو `1` أو `yes` أو `on` (بغض النظر عن حالة الأحرف). `OTEL_SDK_DISABLED` بنفس القيم يعطّل أيضاً مُصدِّر CrewAI. مجموعة أدوات OpenTelemetry نفسها ما تزال تقبل `true` فقط لتعطيل بقية أدوات القياس في العملية.### أمثلة:```python@@ -34,6 +34,8 @@ os.environ['CREWAI_DISABLE_TELEMETRY'] = 'true'os.environ['OTEL_SDK_DISABLED'] = 'true'```+`CREWAI_DISABLE_TELEMETRY=1` (أو `yes` / `on`) يعمل بنفس طريقة `true`. تُتجاهل القيم غير المعروفة ويبقى القياس عن بُعد مفعّلاً.+### العزل عن إعداد OpenTelemetry الخاص بكيعمل القياس عن بُعد الخاص بـ CrewAI على `TracerProvider` خاص به ولا يسجل نفسهdiff --git a/docs/edge/en/telemetry.mdx b/docs/edge/en/telemetry.mdxindex 0b5ef185c..b2c18adbb 100644--- a/docs/edge/en/telemetry.mdx+++ b/docs/edge/en/telemetry.mdx@@ -23,7 +23,7 @@ usage of tools, API calls, responses, any data processed by the agents, or secreWhen the `share_crew` feature is enabled, detailed data including task descriptions, agents' backstories or goals, and other specific attributes are collectedto provide deeper insights. This expanded data collection may include personal information if users have incorporated it into their crews or tasks.Users should carefully consider the content of their crews and tasks before enabling `share_crew`.-Users can disable telemetry by setting the environment variable `CREWAI_DISABLE_TELEMETRY` to `true` or by setting `OTEL_SDK_DISABLED` to `true` (note that the latter disables all OpenTelemetry instrumentation globally).+Users can disable CrewAI telemetry by setting `CREWAI_DISABLE_TELEMETRY` to `true`, `1`, `yes`, or `on` (any case). `OTEL_SDK_DISABLED` with the same values also disables CrewAI's exporter. The OpenTelemetry SDK itself still only honors `true` for disabling other instrumentation in the process.### Examples:```python@@ -34,6 +34,8 @@ os.environ['CREWAI_DISABLE_TELEMETRY'] = 'true'os.environ['OTEL_SDK_DISABLED'] = 'true'```+`CREWAI_DISABLE_TELEMETRY=1` (or `yes` / `on`) works the same as `true`. Unrecognized values are ignored and leave telemetry on.+### Isolation from your own OpenTelemetry setupCrewAI's telemetry runs on its own private `TracerProvider` and never registersdiff --git a/docs/edge/ko/telemetry.mdx b/docs/edge/ko/telemetry.mdxindex e406af951..6d83e8a1a 100644--- a/docs/edge/ko/telemetry.mdx+++ b/docs/edge/ko/telemetry.mdx@@ -22,7 +22,7 @@ CrewAI는 익명 텔레메트리를 활용하여 사용 통계를 수집하며,`share_crew` 기능이 활성화되면, 보다 심층적인 통찰을 제공하기 위해 작업 설명, 에이전트의 배경 이야기나 목표, 기타 특정 속성 등 상세한 데이터가 수집됩니다.이 확대된 데이터 수집에는 사용자가 crew나 작업에 개인정보를 포함한 경우, 개인정보가 포함될 수 있습니다.사용자는 `share_crew`를 활성화하기 전에 crew와 작업의 내용을 신중하게 검토해야 합니다.-사용자는 환경 변수 `CREWAI_DISABLE_TELEMETRY`를 `true`로 설정하거나, `OTEL_SDK_DISABLED`를 `true`로 설정하여 텔레메트리를 비활성화할 수 있습니다(후자의 경우 전체 OpenTelemetry 계측이 전역에서 비활성화된다는 점에 유의하십시오).+사용자는 `CREWAI_DISABLE_TELEMETRY`를 `true`, `1`, `yes`, `on` 중 하나로 설정하여 CrewAI 텔레메트리를 비활성화할 수 있습니다(대소문자 무관). 같은 값의 `OTEL_SDK_DISABLED`도 CrewAI exporter를 끕니다. 프로세스 내 다른 OpenTelemetry 계측을 끄려면 OpenTelemetry SDK는 여전히 `true`만 인식합니다.### 예시:```python@@ -33,6 +33,8 @@ os.environ['CREWAI_DISABLE_TELEMETRY'] = 'true'os.environ['OTEL_SDK_DISABLED'] = 'true'```+`CREWAI_DISABLE_TELEMETRY=1`(`yes` / `on`도 동일)은 `true`와 같습니다. 인식되지 않는 값은 무시되며 텔레메트리는 켜진 채로 남습니다.+### 사용자 OpenTelemetry 설정과의 격리CrewAI의 telemetry는 자체 전용 `TracerProvider`에서 실행되며 자신을 전역diff --git a/docs/edge/pt-BR/telemetry.mdx b/docs/edge/pt-BR/telemetry.mdxindex 03533b301..1b5517ff6 100644--- a/docs/edge/pt-BR/telemetry.mdx+++ b/docs/edge/pt-BR/telemetry.mdx@@ -23,7 +23,7 @@ uso de ferramentas, chamadas de API, respostas, quaisquer dados processados peloQuando o recurso `share_crew` está ativado, dados detalhados, incluindo descrições das tarefas, histórias ou objetivos dos agentes e outros atributos específicos são coletadospara fornecer insights mais detalhados. Essa coleta expandida pode incluir informações pessoais caso o usuário as tenha inserido em seus crews ou tarefas.Usuários devem considerar cuidadosamente o conteúdo de seus crews e tarefas antes de habilitar o `share_crew`.-A telemetria pode ser desabilitada ao definir a variável de ambiente `CREWAI_DISABLE_TELEMETRY` como `true` ou ao definir `OTEL_SDK_DISABLED` como `true` (observe que esta última desabilita toda instrumentação OpenTelemetry globalmente).+A telemetria do CrewAI pode ser desabilitada ao definir `CREWAI_DISABLE_TELEMETRY` como `true`, `1`, `yes` ou `on` (qualquer capitalização). `OTEL_SDK_DISABLED` com os mesmos valores também desabilita o exportador do CrewAI. O SDK do OpenTelemetry em si ainda só reconhece `true` para desabilitar as demais instrumentações do processo.### Exemplos:```python@@ -34,6 +34,8 @@ os.environ['CREWAI_DISABLE_TELEMETRY'] = 'true'os.environ['OTEL_SDK_DISABLED'] = 'true'```+`CREWAI_DISABLE_TELEMETRY=1` (ou `yes` / `on`) funciona como `true`. Valores não reconhecidos são ignorados e a telemetria permanece ligada.+### Isolamento da sua própria configuração do OpenTelemetryA telemetria do CrewAI roda em seu próprio `TracerProvider` privado e nunca sediff --git a/lib/crewai-core/src/crewai_core/telemetry.py b/lib/crewai-core/src/crewai_core/telemetry.pyindex 237a10656..bb39d4265 100644--- a/lib/crewai-core/src/crewai_core/telemetry.py+++ b/lib/crewai-core/src/crewai_core/telemetry.py@@ -181,6 +181,9 @@ class Telemetry:_instance: ClassVar[Self | None] = None_lock: ClassVar[threading.Lock] = threading.Lock()+ _TRUTHY_ENV: ClassVar[frozenset[str]] = frozenset({"1", "on", "true", "yes"})+ _FALSY_ENV: ClassVar[frozenset[str]] = frozenset({"", "0", "false", "no", "off"})+ _warned_env_flags: ClassVar[set[tuple[str, str]]] = set()def __new__(cls) -> Self:if cls._instance is None:@@ -233,12 +236,39 @@ class Telemetry:raiseself.ready = False+ @classmethod+ def _env_flag_enabled(cls, name: str, *, default: bool = False) -> bool:+ """Return whether ``name`` is a conventional yes-value.++ Yes: ``true``, ``1``, ``yes``, ``on``. No: unset, ``false``, ``0``,+ ``no``, ``off``, empty. Anything else is treated as unset and logged+ once per ``(name, raw)`` pair for the process.+ """+ raw = os.getenv(name)+ if raw is None:+ return default+ value = raw.strip().lower()+ if value in cls._TRUTHY_ENV:+ return True+ if value in cls._FALSY_ENV:+ return False+ warning_key = (name, raw)+ if warning_key not in cls._warned_env_flags:+ cls._warned_env_flags.add(warning_key)+ logger.warning(+ "Unrecognized value %r for %s; expected true/1/yes/on or "+ "false/0/no/off. Treating as unset.",+ raw,+ name,+ )+ return default+@classmethoddef _is_telemetry_disabled(cls) -> bool:return (- os.getenv("OTEL_SDK_DISABLED", "false").lower() == "true"- or os.getenv("CREWAI_DISABLE_TELEMETRY", "false").lower() == "true"- or os.getenv("CREWAI_DISABLE_TRACKING", "false").lower() == "true"+ cls._env_flag_enabled("OTEL_SDK_DISABLED")+ or cls._env_flag_enabled("CREWAI_DISABLE_TELEMETRY")+ or cls._env_flag_enabled("CREWAI_DISABLE_TRACKING"))def _should_execute_telemetry(self) -> bool:diff --git a/lib/crewai-core/tests/test_smoke.py b/lib/crewai-core/tests/test_smoke.pyindex f08a3df7f..beba3a868 100644--- a/lib/crewai-core/tests/test_smoke.py+++ b/lib/crewai-core/tests/test_smoke.py@@ -2,6 +2,7 @@from __future__ import annotations+import loggingimport osfrom pathlib import Pathfrom unittest.mock import Mock@@ -175,6 +176,48 @@ def test_configured_project_definition_rejects_empty_definition()[email protected]("value", ["true", "TRUE", "1", "yes", "on", " yes "])+def test_core_telemetry_disabled_by_conventional_yes_values(+ monkeypatch: pytest.MonkeyPatch, value: str+) -> None:+ from crewai_core.telemetry import Telemetry++ monkeypatch.setenv("CREWAI_DISABLE_TELEMETRY", value)+ monkeypatch.delenv("OTEL_SDK_DISABLED", raising=False)+ monkeypatch.delenv("CREWAI_DISABLE_TRACKING", raising=False)+ assert Telemetry._is_telemetry_disabled() is True++[email protected]("value", ["false", "0", "no", "off", ""])+def test_core_telemetry_stays_enabled_for_conventional_no_values(+ monkeypatch: pytest.MonkeyPatch, value: str+) -> None:+ from crewai_core.telemetry import Telemetry++ monkeypatch.setenv("CREWAI_DISABLE_TELEMETRY", value)+ monkeypatch.delenv("OTEL_SDK_DISABLED", raising=False)+ monkeypatch.delenv("CREWAI_DISABLE_TRACKING", raising=False)+ assert Telemetry._is_telemetry_disabled() is False+++def test_core_telemetry_unrecognized_disable_value_warns_once(+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+) -> None:+ from crewai_core.telemetry import Telemetry++ monkeypatch.setenv("CREWAI_DISABLE_TELEMETRY", "maybe")+ Telemetry._warned_env_flags.clear()++ with caplog.at_level(logging.WARNING, logger="crewai_core.telemetry"):+ assert Telemetry._env_flag_enabled("CREWAI_DISABLE_TELEMETRY") is False+ assert Telemetry._env_flag_enabled("CREWAI_DISABLE_TELEMETRY") is False++ warnings = [r for r in caplog.records if r.levelno == logging.WARNING]+ assert len(warnings) == 1+ assert "CREWAI_DISABLE_TELEMETRY" in warnings[0].getMessage()+ assert "maybe" in warnings[0].getMessage()++def test_core_telemetry_never_installs_a_global_provider(monkeypatch: pytest.MonkeyPatch,) -> None:diff --git a/lib/crewai/README.md b/lib/crewai/README.mdindex 8c3550734..6efbc3847 100644--- a/lib/crewai/README.md+++ b/lib/crewai/README.md@@ -576,7 +576,7 @@ pip install dist/*.tar.gzCrewAI uses anonymous telemetry to collect usage data with the main purpose of helping us improve the library by focusing our efforts on the most used features, integrations and tools.-It's pivotal to understand that **NO data is collected** concerning prompts, task descriptions, agents' backstories or goals, usage of tools, API calls, responses, any data processed by the agents, or secrets and environment variables, with the exception of the conditions mentioned. When the `share_crew` feature is enabled, detailed data including task descriptions, agents' backstories or goals, and other specific attributes are collected to provide deeper insights while respecting user privacy. Users can disable telemetry by setting the environment variable OTEL_SDK_DISABLED to true.+It's pivotal to understand that **NO data is collected** concerning prompts, task descriptions, agents' backstories or goals, usage of tools, API calls, responses, any data processed by the agents, or secrets and environment variables, with the exception of the conditions mentioned. When the `share_crew` feature is enabled, detailed data including task descriptions, agents' backstories or goals, and other specific attributes are collected to provide deeper insights while respecting user privacy. Users can disable telemetry by setting `CREWAI_DISABLE_TELEMETRY` to `true`, `1`, `yes`, or `on`. `OTEL_SDK_DISABLED` with the same values also disables CrewAI telemetry; the OpenTelemetry SDK itself still only honors `true` for other instrumentation.Data collected includes:diff --git a/lib/crewai/src/crewai/telemetry/telemetry.py b/lib/crewai/src/crewai/telemetry/telemetry.pyindex 749fc5496..514aeacf0 100644--- a/lib/crewai/src/crewai/telemetry/telemetry.py+++ b/lib/crewai/src/crewai/telemetry/telemetry.py@@ -22,6 +22,7 @@ from typing import TYPE_CHECKING, Anyfrom crewai_core.telemetry import (CommonAttributesSpanProcessor,+ Telemetry as CoreTelemetry,common_span_attributes,)from opentelemetry.exporter.otlp.proto.http.trace_exporter import (@@ -161,11 +162,7 @@ class Telemetry:@classmethoddef _is_telemetry_disabled(cls) -> bool:"""Check if telemetry should be disabled based on environment variables."""- return (- os.getenv("OTEL_SDK_DISABLED", "false").lower() == "true"- or os.getenv("CREWAI_DISABLE_TELEMETRY", "false").lower() == "true"- or os.getenv("CREWAI_DISABLE_TRACKING", "false").lower() == "true"- )+ return CoreTelemetry._is_telemetry_disabled()def _should_execute_telemetry(self) -> bool:"""Check if telemetry operations should be executed."""diff --git a/lib/crewai/tests/telemetry/test_telemetry.py b/lib/crewai/tests/telemetry/test_telemetry.pyindex d1f2bd077..0afc82163 100644--- a/lib/crewai/tests/telemetry/test_telemetry.py+++ b/lib/crewai/tests/telemetry/test_telemetry.py@@ -28,10 +28,21 @@ def cleanup_telemetry():[("OTEL_SDK_DISABLED", "true", False),("OTEL_SDK_DISABLED", "TRUE", False),+ ("OTEL_SDK_DISABLED", "1", False),+ ("OTEL_SDK_DISABLED", "yes", False),+ ("OTEL_SDK_DISABLED", "on", False),("CREWAI_DISABLE_TELEMETRY", "true", False),("CREWAI_DISABLE_TELEMETRY", "TRUE", False),+ ("CREWAI_DISABLE_TELEMETRY", "1", False),+ ("CREWAI_DISABLE_TELEMETRY", "yes", False),+ ("CREWAI_DISABLE_TELEMETRY", "on", False),+ ("CREWAI_DISABLE_TRACKING", "1", False),("OTEL_SDK_DISABLED", "false", True),+ ("OTEL_SDK_DISABLED", "0", True),("CREWAI_DISABLE_TELEMETRY", "false", True),+ ("CREWAI_DISABLE_TELEMETRY", "0", True),+ ("CREWAI_DISABLE_TELEMETRY", "no", True),+ ("CREWAI_DISABLE_TELEMETRY", "off", True),],)def test_telemetry_environment_variables(env_var, value, expected_ready):diff --git a/lib/crewai/tests/telemetry/test_telemetry_disable.py b/lib/crewai/tests/telemetry/test_telemetry_disable.pyindex 7b111efd7..184c89770 100644--- a/lib/crewai/tests/telemetry/test_telemetry_disable.py+++ b/lib/crewai/tests/telemetry/test_telemetry_disable.py@@ -19,10 +19,21 @@ def cleanup_telemetry():[("OTEL_SDK_DISABLED", "true", False),("OTEL_SDK_DISABLED", "TRUE", False),+ ("OTEL_SDK_DISABLED", "1", False),+ ("OTEL_SDK_DISABLED", "yes", False),+ ("OTEL_SDK_DISABLED", "on", False),("CREWAI_DISABLE_TELEMETRY", "true", False),("CREWAI_DISABLE_TELEMETRY", "TRUE", False),+ ("CREWAI_DISABLE_TELEMETRY", "1", False),+ ("CREWAI_DISABLE_TELEMETRY", "yes", False),+ ("CREWAI_DISABLE_TELEMETRY", "on", False),+ ("CREWAI_DISABLE_TRACKING", "1", False),("OTEL_SDK_DISABLED", "false", True),+ ("OTEL_SDK_DISABLED", "0", True),("CREWAI_DISABLE_TELEMETRY", "false", True),+ ("CREWAI_DISABLE_TELEMETRY", "0", True),+ ("CREWAI_DISABLE_TELEMETRY", "no", True),+ ("CREWAI_DISABLE_TELEMETRY", "off", True),],)def test_telemetry_environment_variables(env_var, value, expected_ready):