crewai - ✅(Solved) Fix [BUG] OpenAI API key works locally but fails inside CrewAI with 401 invalid_api_key [1 pull requests, 1 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
crewAIInc/crewAI#5622Fetched 2026-04-26 05:13:37
View on GitHub
Comments
0
Participants
1
Timeline
2
Reactions
0
Participants
Timeline (top)
cross-referenced ×1labeled ×1

'm experiencing an authentication issue when running a Crew inside CrewAI. The same OpenAI API key works correctly when tested in isolation (Python script and curl), but fails when executed within CrewAI. Error message: Error code: 401 - {'error': {'message': 'Incorrect API key provided', 'type': 'invalid_request_error', 'code': 'invalid_api_key'}} Context: The API key is valid and has been tested outside CrewAI successfully The error only occurs during Crew execution (crew.kickoff()) Logs show repeated authentication failures when calling OpenAI There is also a warning related to virtual environments: VIRTUAL_ENV does not match the project environment path What I’ve tried: Regenerated the API key Set OPENAI_API_KEY via environment variable Restarted the environment Verified the key works with: Python (OpenAI client) curl request Hypothesis: It seems CrewAI might not be correctly reading or propagating the environment variable to the runtime where the agents execute. Questions: Is there a known issue with environment variable handling in CrewAI? Do I need to explicitly pass the API key in the Crew or Agent configuration? Could this be related to virtual environment isolation? Any guidance would be appreciated.

Error Message

Error message: Error code: 401 - {'error': {'message': 'Incorrect API key provided', 'type': 'invalid_request_error', 'code': 'invalid_api_key'}} The error only occurs during Crew execution (crew.kickoff()) 6. The execution fails with a 401 invalid_api_key error, even though the same key works outside CrewAI. Error code: 401 ... 'Incorrect API key provided' Error message: Error code: 401 - {'error': {'message': 'Incorrect API key provided', 'type': 'invalid_request_error', 'code': 'invalid_api_key'}} The error only occurs during Crew execution (crew.kickoff()) The execution fails with a 401 invalid_api_key error, even though the same key works outside CrewAI. ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} Error during execution: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c28*******************95b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} Traceback (most recent call last): raise e # Re-raise the exception after emitting the event openai.AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c28**************95b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} Error code: 401 ... 'Incorrect API key provided' Error message: Error code: 401 - {'error': {'message': 'Incorrect API key provided', 'type': 'invalid_request_error', 'code': 'invalid_api_key'}} The error only occurs during Crew execution (crew.kickoff()) The execution fails with a 401 invalid_api_key error, even though the same key works outside CrewAI. ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401}

Root Cause

'm experiencing an authentication issue when running a Crew inside CrewAI. The same OpenAI API key works correctly when tested in isolation (Python script and curl), but fails when executed within CrewAI. Error message: Error code: 401 - {'error': {'message': 'Incorrect API key provided', 'type': 'invalid_request_error', 'code': 'invalid_api_key'}} Context: The API key is valid and has been tested outside CrewAI successfully The error only occurs during Crew execution (crew.kickoff()) Logs show repeated authentication failures when calling OpenAI There is also a warning related to virtual environments: VIRTUAL_ENV does not match the project environment path What I’ve tried: Regenerated the API key Set OPENAI_API_KEY via environment variable Restarted the environment Verified the key works with: Python (OpenAI client) curl request Hypothesis: It seems CrewAI might not be correctly reading or propagating the environment variable to the runtime where the agents execute. Questions: Is there a known issue with environment variable handling in CrewAI? Do I need to explicitly pass the API key in the Crew or Agent configuration? Could this be related to virtual environment isolation? Any guidance would be appreciated.

Fix Action

Fixed

PR fix notes

PR #5623: fix: strip whitespace from API keys and handle AuthenticationError with guidance

Description (problem / solution / changelog)

Summary

Fixes #5622

Addresses the issue where OPENAI_API_KEY works locally but fails inside CrewAI with a 401 invalid_api_key error. The root cause is that API keys read from environment variables or .env files may contain trailing whitespace, newlines, or tabs that cause authentication failures. Additionally, AuthenticationError (401) was not specifically caught, falling through to a generic exception handler with a poor error message.

Changes:

  • Strip whitespace from API keys in _normalize_openai_fields() and _get_client_params() in OpenAICompletion to sanitize keys read from env vars or passed directly
  • Strip whitespace from env var values in llm_utils.py _llm_via_environment_or_fallback() path
  • Add specific AuthenticationError handling in all 4 OpenAI completion methods (sync/async completions and responses) with actionable troubleshooting guidance
  • Let AuthenticationError propagate through call()/acall() without being swallowed by the generic Exception handler
  • Add _format_auth_error() helper for consistent error formatting with troubleshooting steps

Review & Testing Checklist for Human

  • Verify the whitespace stripping logic doesn't break valid API keys that happen to contain special characters (the fix only strips leading/trailing whitespace via .strip())
  • Confirm the AuthenticationError handling in all 4 completion methods follows the same pattern and provides useful guidance
  • Test with a real .env file that has trailing whitespace/newlines in the API key to verify the fix resolves the 401 error

Notes

  • 12 new tests added covering: whitespace stripping from env vars (spaces, newlines, tabs), direct API key stripping, _get_client_params env var fallback, missing key error, AuthenticationError propagation and logging, and _format_auth_error output
  • All existing tests continue to pass

Link to Devin session: https://app.devin.ai/sessions/97f73126972c4b3d9f01abc74d602a4c

Changed files

  • lib/crewai/src/crewai/llms/providers/openai/completion.py (modified, +56/-3)
  • lib/crewai/src/crewai/utilities/llm_utils.py (modified, +1/-0)
  • lib/crewai/tests/llms/openai/test_openai.py (modified, +131/-0)
  • lib/crewai/tests/utilities/test_llm_utils.py (modified, +21/-0)
RAW_BUFFERClick to expand / collapse

Description

'm experiencing an authentication issue when running a Crew inside CrewAI. The same OpenAI API key works correctly when tested in isolation (Python script and curl), but fails when executed within CrewAI. Error message: Error code: 401 - {'error': {'message': 'Incorrect API key provided', 'type': 'invalid_request_error', 'code': 'invalid_api_key'}} Context: The API key is valid and has been tested outside CrewAI successfully The error only occurs during Crew execution (crew.kickoff()) Logs show repeated authentication failures when calling OpenAI There is also a warning related to virtual environments: VIRTUAL_ENV does not match the project environment path What I’ve tried: Regenerated the API key Set OPENAI_API_KEY via environment variable Restarted the environment Verified the key works with: Python (OpenAI client) curl request Hypothesis: It seems CrewAI might not be correctly reading or propagating the environment variable to the runtime where the agents execute. Questions: Is there a known issue with environment variable handling in CrewAI? Do I need to explicitly pass the API key in the Crew or Agent configuration? Could this be related to virtual environment isolation? Any guidance would be appreciated.

Steps to Reproduce

  1. Create or open a CrewAI project using OpenAI as the LLM provider.

  2. Configure a valid OpenAI API key using the OPENAI_API_KEY environment variable.

  3. Verify that the same API key works outside CrewAI by running a simple OpenAI API test using Python or curl.

  4. Run the CrewAI project and start the crew execution with crew.kickoff().

  5. Observe that CrewAI validates the tools successfully, but fails when the agent tries to call the OpenAI API.

  6. The execution fails with a 401 invalid_api_key error, even though the same key works outside CrewAI.

Expected behavior

CrewAI should successfully authenticate with the OpenAI API using the configured OPENAI_API_KEY and execute the crew without authentication errors. The same API key that works in standalone tests (Python client and curl) should be correctly recognized and used within CrewAI, allowing agents to complete their tasks normally.

Screenshots/Code snippets

Texto colado(3).txt Documento o que quer dizer esse erro no meu creia? []

Direto ao ponto: esse erro não tem nada de misterioso — é falha de autenticação da API. O trecho crítico é esse aqui:

Error code: 401 ... 'Incorrect API key provided' O que isso significa na prática Seu CrewAI está tentando chamar a API da OpenAI, mas: a chave (API key) está errada, ou está mal configurada, ou não está sendo carregada corretamente no ambiente Erro 401 = não autorizado. Onde normalmente está o problema Vou ser direto porque aqui costuma ser erro básico (mas comum): Chave inválida ou copiada errado espaço extra caractere faltando chave antiga revogada Variável de ambiente não está ativa você definiu OPENAI_API_KEY, mas o processo do Crew não está enxergando Ambiente errado você rodou o Crew em um ambiente diferente do que configurou a chave (isso aparece no seu log: conflito de VIRTUAL_ENV) Chave de outro serviço já vi gente usar chave de outra plataforma achando que era da OpenAI Como resolver (sem rodeio) Faça esse checklist:

  1. Gere uma nova chave

Vá em: https://platform.openai.com/api-keys Crie uma nova (não reutiliza a antiga) 2. Configure corretamente No terminal:

export OPENAI_API_KEY="sua_chave_aqui" ou no .env: OPENAI_API_KEY=sua_chave_aqui 3. Teste isolado (antes do Crew) Se isso falhar, o problema não é o Crew — é a chave:

from openai import OpenAI client = OpenAI()

resp = client.responses.create( model="gpt-4.1-mini", input="teste" )

print(resp.output_text) 4. Reinicie o ambiente Especialmente se estiver usando: Docker VSCode Jupyter CrewAI Studio Um detalhe importante do seu log Isso aqui chama atenção: VIRTUAL_ENV does not match... Você provavelmente está com: ambiente virtual inconsistente ou rodando o Crew em outro contexto Isso não quebra sozinho, mas facilmente faz sua chave “sumir” do runtime. Em resumo Seu sistema está funcionando. Seu Crew também. O que está quebrando é simples:

A autenticação com a OpenAI não está válida. Se quiser, me manda como você está configurando a chave (env, código, Crew config) que eu te digo exatamente onde está o erro — sem tentativa e erro.

Se a chave funciona fora do CrewAI, então o problema não é a API — é como o CrewAI está recebendo (ou não) essa chave. Vale abrir issue mesmo. Aqui vai um texto direto, técnico e objetivo (sem enrolação), pronto pra colar no GitHub:

Escrita Title: OpenAI API key works locally but fails inside CrewAI with 401 invalid_api_key Description:

I'm experiencing an authentication issue when running a Crew inside CrewAI.

The same OpenAI API key works correctly when tested in isolation (Python script and curl), but fails when executed within CrewAI.

Error message:

Error code: 401 - {'error': {'message': 'Incorrect API key provided', 'type': 'invalid_request_error', 'code': 'invalid_api_key'}} Context: The API key is valid and has been tested outside CrewAI successfully The error only occurs during Crew execution (crew.kickoff()) Logs show repeated authentication failures when calling OpenAI There is also a warning related to virtual environments: VIRTUAL_ENV does not match the project environment path What I’ve tried: Regenerated the API key Set OPENAI_API_KEY via environment variable Restarted the environment Verified the key works with: Python (OpenAI client) curl request Hypothesis: It seems CrewAI might not be correctly reading or propagating the environment variable to the runtime where the agents execute. Questions:

Is there a known issue with environment variable handling in CrewAI? Do I need to explicitly pass the API key in the Crew or Agent configuration? Could this be related to virtual environment isolation? Any guidance would be appreciated. Se quiser deixar mais forte ainda (o que eu recomendo), você pode anexar: versão do crewai (pip show crewai) como você está rodando (CLI, Docker, Studio, etc.) Se você me disser qual ambiente está usando (Studio, local, Docker), eu consigo refinar essa issue pra ficar praticamente impossível de ignorar.

preciso disso tbm Steps to Reproduce * Provide a step-by-step process to reproduce the behavior.

Escrita Steps to Reproduce: Create or open a CrewAI project using OpenAI as the LLM provider. Configure a valid OpenAI API key using the OPENAI_API_KEY environment variable. Verify that the same API key works outside CrewAI by running a simple OpenAI API test using Python or curl. Run the CrewAI project and start the crew execution with crew.kickoff(). Observe that CrewAI validates the tools successfully, but fails when the agent tries to call the OpenAI API. The execution fails with a 401 invalid_api_key error, even though the same key works outside CrewAI.

Expected behavior * A clear and concise description of what you expected to happen.

Escrita Expected behavior: CrewAI should successfully authenticate with the OpenAI API using the configured OPENAI_API_KEY and execute the crew without authentication errors.

The same API key that works in standalone tests (Python client and curl) should be correctly recognized and used within CrewAI, allowing agents to complete their tasks normally.

Subprocess execution failed: Subprocess failed with return code 1. STDERR: warning: VIRTUAL_ENV=/data/internal/venv does not match the project environment path /shared_venv and will be ignored; use --active to target the active environment instead Building crew-de-gestao-de-mudanca-organizacional @ file:///tmp/crewai_sspxfkjn Built crew-de-gestao-de-mudanca-organizacional @ file:///tmp/crewai_sspxfkjn Uninstalled 1 package in 0.23ms Installed 1 package in 4ms INFO:root:OpenAI: Successfully validated tool 'read_a_files_content' INFO:root:OpenAI: Successfully validated tool 'read_file' ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} INFO:root:OpenAI: Successfully validated tool 'read_a_files_content' INFO:root:OpenAI: Successfully validated tool 'read_file' ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} INFO:root:OpenAI: Successfully validated tool 'read_a_files_content' INFO:root:OpenAI: Successfully validated tool 'read_file' ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} Error during execution: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c28*******************95b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} Traceback (most recent call last): File "/automation/src/crewai_studio_runner/subprocess/launcher.py", line 385, in main execute_crew(args.module_name, args.class_name, inputs, built) File "/automation/src/crewai_studio_runner/subprocess/launcher.py", line 294, in execute_crew crew_output = crew.kickoff(inputs=inputs, input_files=input_files) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/crew.py", line 779, in kickoff result = self._run_sequential_process() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/crew.py", line 1204, in _run_sequential_process return self._execute_tasks(self.tasks) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/crew.py", line 1296, in _execute_tasks task_output = task.execute_sync( ^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/task.py", line 523, in execute_sync return self._execute_core(agent, context, tools) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/task.py", line 814, in _execute_core raise e # Re-raise the exception after emitting the event ^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/task.py", line 721, in _execute_core result = agent.execute_task( ^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 767, in execute_task result = self._handle_execution_error(e, task, context, tools) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 677, in _handle_execution_error return self.execute_task(task, context, tools) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 767, in execute_task result = self._handle_execution_error(e, task, context, tools) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 677, in _handle_execution_error return self.execute_task(task, context, tools) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 767, in execute_task result = self._handle_execution_error(e, task, context, tools) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 676, in _handle_execution_error self._check_execution_error(e, task) File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 656, in _check_execution_error raise e File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 754, in execute_task result = self._execute_without_timeout(task_prompt, task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 821, in _execute_without_timeout self.agent_executor.invoke( File "/shared_venv/lib/python3.12/site-packages/crewai/agents/crew_agent_executor.py", line 227, in invoke formatted_answer = self._invoke_loop() ^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agents/crew_agent_executor.py", line 323, in _invoke_loop return self._invoke_loop_native_tools() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agents/crew_agent_executor.py", line 597, in _invoke_loop_native_tools raise e File "/shared_venv/lib/python3.12/site-packages/crewai/agents/crew_agent_executor.py", line 516, in _invoke_loop_native_tools answer = get_llm_response( ^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/utilities/agent_utils.py", line 475, in get_llm_response raise e File "/shared_venv/lib/python3.12/site-packages/crewai/utilities/agent_utils.py", line 465, in get_llm_response answer = llm.call( ^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/llms/providers/openai/completion.py", line 407, in call return self._call_completions( ^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/llms/providers/openai/completion.py", line 447, in _call_completions return self._handle_completion( ^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/llms/providers/openai/completion.py", line 1708, in _handle_completion raise e from e File "/shared_venv/lib/python3.12/site-packages/crewai/llms/providers/openai/completion.py", line 1603, in _handle_completion response: ChatCompletion = self._client.chat.completions.create(params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/openai/_utils/_utils.py", line 286, in wrapper return func(args, kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/openai/resources/chat/completions/completions.py", line 1211, in create return self._post( ^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/openai/_base_client.py", line 1297, in post return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/openai/_base_client.py", line 1070, in request raise self._make_status_error_from_response(err.response) from None openai.AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c28**************95b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401}

Operating System

Ubuntu 20.04

Python Version

3.10

crewAI Version

platform

crewAI Tools Version

none

Virtual Environment

Venv

Evidence

Texto colado(3).txt Documento o que quer dizer esse erro no meu creia? []

Direto ao ponto: esse erro não tem nada de misterioso — é falha de autenticação da API. O trecho crítico é esse aqui:

Error code: 401 ... 'Incorrect API key provided' O que isso significa na prática Seu CrewAI está tentando chamar a API da OpenAI, mas: a chave (API key) está errada, ou está mal configurada, ou não está sendo carregada corretamente no ambiente Erro 401 = não autorizado. Onde normalmente está o problema Vou ser direto porque aqui costuma ser erro básico (mas comum): Chave inválida ou copiada errado espaço extra caractere faltando chave antiga revogada Variável de ambiente não está ativa você definiu OPENAI_API_KEY, mas o processo do Crew não está enxergando Ambiente errado você rodou o Crew em um ambiente diferente do que configurou a chave (isso aparece no seu log: conflito de VIRTUAL_ENV) Chave de outro serviço já vi gente usar chave de outra plataforma achando que era da OpenAI Como resolver (sem rodeio) Faça esse checklist:

  1. Gere uma nova chave

Vá em: https://platform.openai.com/api-keys Crie uma nova (não reutiliza a antiga) 2. Configure corretamente No terminal:

export OPENAI_API_KEY="sua_chave_aqui" ou no .env: OPENAI_API_KEY=sua_chave_aqui 3. Teste isolado (antes do Crew) Se isso falhar, o problema não é o Crew — é a chave:

from openai import OpenAI client = OpenAI()

resp = client.responses.create( model="gpt-4.1-mini", input="teste" )

print(resp.output_text) 4. Reinicie o ambiente Especialmente se estiver usando: Docker VSCode Jupyter CrewAI Studio Um detalhe importante do seu log Isso aqui chama atenção: VIRTUAL_ENV does not match... Você provavelmente está com: ambiente virtual inconsistente ou rodando o Crew em outro contexto Isso não quebra sozinho, mas facilmente faz sua chave “sumir” do runtime. Em resumo Seu sistema está funcionando. Seu Crew também. O que está quebrando é simples:

A autenticação com a OpenAI não está válida. Se quiser, me manda como você está configurando a chave (env, código, Crew config) que eu te digo exatamente onde está o erro — sem tentativa e erro.

Se a chave funciona fora do CrewAI, então o problema não é a API — é como o CrewAI está recebendo (ou não) essa chave. Vale abrir issue mesmo. Aqui vai um texto direto, técnico e objetivo (sem enrolação), pronto pra colar no GitHub:

Escrita Title: OpenAI API key works locally but fails inside CrewAI with 401 invalid_api_key Description:

I'm experiencing an authentication issue when running a Crew inside CrewAI.

The same OpenAI API key works correctly when tested in isolation (Python script and curl), but fails when executed within CrewAI.

Error message:

Error code: 401 - {'error': {'message': 'Incorrect API key provided', 'type': 'invalid_request_error', 'code': 'invalid_api_key'}} Context: The API key is valid and has been tested outside CrewAI successfully The error only occurs during Crew execution (crew.kickoff()) Logs show repeated authentication failures when calling OpenAI There is also a warning related to virtual environments: VIRTUAL_ENV does not match the project environment path What I’ve tried: Regenerated the API key Set OPENAI_API_KEY via environment variable Restarted the environment Verified the key works with: Python (OpenAI client) curl request Hypothesis: It seems CrewAI might not be correctly reading or propagating the environment variable to the runtime where the agents execute. Questions:

Is there a known issue with environment variable handling in CrewAI? Do I need to explicitly pass the API key in the Crew or Agent configuration? Could this be related to virtual environment isolation? Any guidance would be appreciated. Se quiser deixar mais forte ainda (o que eu recomendo), você pode anexar: versão do crewai (pip show crewai) como você está rodando (CLI, Docker, Studio, etc.) Se você me disser qual ambiente está usando (Studio, local, Docker), eu consigo refinar essa issue pra ficar praticamente impossível de ignorar.

preciso disso tbm Steps to Reproduce * Provide a step-by-step process to reproduce the behavior.

Escrita Steps to Reproduce: Create or open a CrewAI project using OpenAI as the LLM provider. Configure a valid OpenAI API key using the OPENAI_API_KEY environment variable. Verify that the same API key works outside CrewAI by running a simple OpenAI API test using Python or curl. Run the CrewAI project and start the crew execution with crew.kickoff(). Observe that CrewAI validates the tools successfully, but fails when the agent tries to call the OpenAI API. The execution fails with a 401 invalid_api_key error, even though the same key works outside CrewAI.

Expected behavior * A clear and concise description of what you expected to happen.

Escrita Expected behavior: CrewAI should successfully authenticate with the OpenAI API using the configured OPENAI_API_KEY and execute the crew without authentication errors.

The same API key that works in standalone tests (Python client and curl) should be correctly recognized and used within CrewAI, allowing agents to complete their tasks normally.

Subprocess execution failed: Subprocess failed with return code 1. STDERR: warning: VIRTUAL_ENV=/data/internal/venv does not match the project environment path /shared_venv and will be ignored; use --active to target the active environment instead Building crew-de-gestao-de-mudanca-organizacional @ file:///tmp/crewai_sspxfkjn Built crew-de-gestao-de-mudanca-organizacional @ file:///tmp/crewai_sspxfkjn Uninstalled 1 package in 0.23ms Installed 1 package in 4ms INFO:root:OpenAI: Successfully validated tool 'read_a_files_content' INFO:root:OpenAI: Successfully validated tool 'read_file' ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} INFO:root:OpenAI: Successfully validated tool 'read_a_files_content' INFO:root:OpenAI: Successfully validated tool 'read_file' ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} INFO:root:OpenAI: Successfully validated tool 'read_a_files_content' INFO:root:OpenAI: Successfully validated tool 'read_file' ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} ERROR:root API call failed: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c2895b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} Error during execution: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c28*******************95b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401} Traceback (most recent call last): File "/automation/src/crewai_studio_runner/subprocess/launcher.py", line 385, in main execute_crew(args.module_name, args.class_name, inputs, built) File "/automation/src/crewai_studio_runner/subprocess/launcher.py", line 294, in execute_crew crew_output = crew.kickoff(inputs=inputs, input_files=input_files) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/crew.py", line 779, in kickoff result = self._run_sequential_process() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/crew.py", line 1204, in _run_sequential_process return self._execute_tasks(self.tasks) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/crew.py", line 1296, in _execute_tasks task_output = task.execute_sync( ^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/task.py", line 523, in execute_sync return self._execute_core(agent, context, tools) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/task.py", line 814, in _execute_core raise e # Re-raise the exception after emitting the event ^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/task.py", line 721, in _execute_core result = agent.execute_task( ^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 767, in execute_task result = self._handle_execution_error(e, task, context, tools) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 677, in _handle_execution_error return self.execute_task(task, context, tools) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 767, in execute_task result = self._handle_execution_error(e, task, context, tools) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 677, in _handle_execution_error return self.execute_task(task, context, tools) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 767, in execute_task result = self._handle_execution_error(e, task, context, tools) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 676, in _handle_execution_error self._check_execution_error(e, task) File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 656, in _check_execution_error raise e File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 754, in execute_task result = self._execute_without_timeout(task_prompt, task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agent/core.py", line 821, in _execute_without_timeout self.agent_executor.invoke( File "/shared_venv/lib/python3.12/site-packages/crewai/agents/crew_agent_executor.py", line 227, in invoke formatted_answer = self._invoke_loop() ^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agents/crew_agent_executor.py", line 323, in _invoke_loop return self._invoke_loop_native_tools() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/agents/crew_agent_executor.py", line 597, in _invoke_loop_native_tools raise e File "/shared_venv/lib/python3.12/site-packages/crewai/agents/crew_agent_executor.py", line 516, in _invoke_loop_native_tools answer = get_llm_response( ^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/utilities/agent_utils.py", line 475, in get_llm_response raise e File "/shared_venv/lib/python3.12/site-packages/crewai/utilities/agent_utils.py", line 465, in get_llm_response answer = llm.call( ^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/llms/providers/openai/completion.py", line 407, in call return self._call_completions( ^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/llms/providers/openai/completion.py", line 447, in _call_completions return self._handle_completion( ^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/crewai/llms/providers/openai/completion.py", line 1708, in _handle_completion raise e from e File "/shared_venv/lib/python3.12/site-packages/crewai/llms/providers/openai/completion.py", line 1603, in _handle_completion response: ChatCompletion = self._client.chat.completions.create(params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/openai/_utils/_utils.py", line 286, in wrapper return func(args, kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/openai/resources/chat/completions/completions.py", line 1211, in create return self._post( ^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/openai/_base_client.py", line 1297, in post return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/shared_venv/lib/python3.12/site-packages/openai/_base_client.py", line 1070, in request raise self._make_status_error_from_response(err.response) from None openai.AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-58c28**************95b4. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key', 'param': None}, 'status': 401}

Possible Solution

None

Additional context

None

extent analysis

TL;DR

The most likely fix is to ensure the OpenAI API key is correctly configured and propagated to the CrewAI runtime environment, potentially by explicitly passing the API key in the Crew or Agent configuration.

Guidance

  1. Verify API Key Configuration: Double-check that the OpenAI API key is correctly set in the environment variable OPENAI_API_KEY and that there are no extra spaces or characters.
  2. Check Virtual Environment: Ensure that the virtual environment used by CrewAI matches the one where the OPENAI_API_KEY is set, as indicated by the VIRTUAL_ENV warning.
  3. Test Isolation: Run a simple OpenAI API test using Python or curl to confirm the API key works outside of CrewAI.
  4. Explicitly Pass API Key: Consider explicitly passing the OpenAI API key in the Crew or Agent configuration to avoid reliance on environment variables.

Example

No code example is provided as the issue seems to be related to configuration rather than code.

Notes

  • The problem might be related to how CrewAI handles environment variables or virtual environment isolation.
  • Ensuring the API key is correctly set and accessible within the CrewAI runtime environment is crucial.

Recommendation

Apply a workaround by explicitly passing the OpenAI API key in the Crew or Agent configuration to avoid potential issues with environment variable propagation.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

FAQ

Expected behavior

CrewAI should successfully authenticate with the OpenAI API using the configured OPENAI_API_KEY and execute the crew without authentication errors. The same API key that works in standalone tests (Python client and curl) should be correctly recognized and used within CrewAI, allowing agents to complete their tasks normally.

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

crewai - ✅(Solved) Fix [BUG] OpenAI API key works locally but fails inside CrewAI with 401 invalid_api_key [1 pull requests, 1 participants]