Skip to content

Set default OPENAI_API_KEY value to prevent startup crashes #72

Closed

Description

@httpdss

Summary

The STRUCT tool crashes with an OpenAI API key error when the OPENAI_API_KEY environment variable is not set, even when users may not intend to use OpenAI models or may want to use the tool without AI features.

Error Details

openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable

Full Stack Trace:

Traceback (most recent call last):
  File "/opt/hostedtoolcache/Python/3.13.5/x64/bin/struct", line 8, in <module>
    sys.exit(main())
  File "/opt/hostedtoolcache/Python/3.13.5/x64/lib/python3.13/site-packages/struct_module/main.py", line 51, in main
    args.func(args)
  File "/opt/hostedtoolcache/Python/3.13.5/x64/lib/python3.13/site-packages/struct_module/commands/generate.py", line 130, in execute
    self._create_structure(args, mappings)
  File "/opt/hostedtoolcache/Python/3.13.5/x64/lib/python3.13/site-packages/struct_module/commands/generate.py", line 260, in _create_structure
    self._create_structure({
  File "/opt/hostedtoolcache/Python/3.13.5/x64/lib/python3.13/site-packages/struct_module/commands/generate.py", line 163, in _create_structure
    file_item = FileItem(content)
  File "/opt/hostedtoolcache/Python/3.13.5/x64/lib/python3.13/site-packages/struct_module/file_item.py", line 34, in __init__
    self.model_wrapper = ModelWrapper(self.logger)
  File "/opt/hostedtoolcache/Python/3.13.5/x64/lib/python3.13/site-packages/struct_module/model_wrapper.py", line 15, in __init__
    self.agent = Agent(model=self.model_name)
  File "/opt/hostedtoolcache/Python/3.13.5/x64/lib/python3.13/site-packages/pydantic_ai/agent.py", line 338, in __init__
    self.model = models.infer_model(model)
  File "/opt/hostedtoolcache/Python/3.13.5/x64/lib/python3.13/site-packages/pydantic_ai/models/__init__.py", line 637, in infer_model
    return OpenAIModel(model_name, provider=provider)
  File "/opt/hostedtoolcache/Python/3.13.5/x64/lib/python3.13/site-packages/pydantic_ai/models/openai.py", line 226, in __init__
    provider = infer_provider(provider)
  File "/opt/hostedtoolcache/Python/3.13.5/x64/lib/python3.13/site-packages/pydantic_ai/providers/__init__.py", line 137, in infer_provider
    return provider_class()
  File "/opt/hostedtoolcache/Python/3.13.5/x64/lib/python3.13/site-packages/pydantic_ai/providers/openai.py", line 72, in __init__
    self._client = AsyncOpenAI(base_url=base_url, api_key=api_key, http_client=http_client)
  File "/opt/hostedtoolcache/Python/3.13.5/x64/lib/python3.13/site-packages/openai/_client.py", line 449, in __init__
    raise OpenAIError(

Root Cause

The issue occurs in struct_module/model_wrapper.py where:

  1. The default model is set to "openai:gpt-4.1" when AI_MODEL environment variable is not set
  2. The OpenAI model initialization always requires a valid API key
  3. No fallback or default API key is provided when the environment variable is missing

Proposed Solution

Set a programmatic default value for OPENAI_API_KEY at application startup to prevent crashes when the environment variable is not set.

Option 1: Set a placeholder default value

# In main.py or model_wrapper.py
if not os.getenv("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = "default_placeholder_key"

Option 2: Enhanced error handling with graceful fallback

# In model_wrapper.py
def __init__(self, logger=None):
    self.logger = logger or logging.getLogger(__name__)
    self.model_name = os.getenv("AI_MODEL") or "openai:gpt-4.1"
    
    # Set default API key if not provided
    if self.model_name.startswith("openai:") and not os.getenv("OPENAI_API_KEY"):
        os.environ["OPENAI_API_KEY"] = "sk-default-placeholder-key"
        self.logger.warning("OPENAI_API_KEY not set. Using placeholder. AI features may not work properly.")
    
    self.agent = Agent(model=self.model_name)

Benefits

  • Prevents crashes: Tool won't fail immediately due to missing API keys
  • Better UX: Users can explore non-AI features without setting up API keys first
  • Graceful degradation: AI features can warn users rather than crash the entire application
  • Backward compatibility: Existing configurations continue to work

Alternative Considerations

  • Lazy initialization: Only initialize AI models when actually needed
  • Optional AI features: Make AI functionality completely optional
  • Better error messages: Provide clearer guidance when API keys are missing

Files to be modified

  • struct_module/main.py or struct_module/model_wrapper.py
  • Potentially update documentation about API key requirements

Acceptance Criteria

  • STRUCT tool starts successfully without OPENAI_API_KEY environment variable
  • Default/placeholder API key is set programmatically at startup
  • Clear warning message when using placeholder API key
  • AI features gracefully handle invalid/placeholder API keys
  • Existing functionality with valid API keys remains unchanged
  • Documentation updated if necessary

Activity

  1. added a commit that references this issue on Aug 1, 2025
    6fabbc3
  2. added a commit that references this issue on Jan 7, 2026
    249cd93
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions