LLM API Access

Updated: 2025-11-24

To programmatically interact with LLMs, you need to set up API access. Follow these steps to obtain your GPT API key and configure it securely in PyCharm.

While we use OpenAI GPT APIs for this course, the interaction methods are similar across other LLMs such as Anthropic Claude and Google Gemini.

OpenAI Account

Create an OpenAI account (if needed):

Generate your API key:

Add Billing Information (if required):

  • OpenAI requires payment information to use the API

  • Navigate to Settings > Billing > Payment methods

  • Add a payment method

  • Consider setting usage limits to prevent unexpected charges

  • New accounts may receive free trial credits; check your usage page to see your balance

Configure API Key

Install the python-dotenv package:

pip install python-dotenv

Create a .env file in your project root directory (nlp-essentials/) and add your OpenAI API Key by replacing your-api-key-here below:

OPENAI_API_KEY=your-api-key-here

Add .env to your .gitignore file to prevent committing it:

.idea/
.venv/
.env

Load environmental variables by adding the following code:

from dotenv import load_dotenv

load_dotenv()
  • L3: Load environment variables from the .env file

Test API Connection

Install the openai package:

pip install openai

Verify if your API key works correctly:

import os

from dotenv import load_dotenv
from openai import OpenAI
from openai.types.chat import ChatCompletion

load_dotenv()

def test_llm_api() -> ChatCompletion:
    client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

        response = client.chat.completions.create(
        model="gpt-5-nano",
        messages=[
            {"role": "user", "content": "Say 'Hello World'."}
        ]
    )

    return response

if __name__ == "__main__":
    r = test_llm_api()
    print(r.choices[0].message.content)
    print(r)
  • L1: Import the os package

  • L5: ChatCompletion class

  • L9: Use typing to indicate the return type (ChatCompletion).

  • L10: Initialize the OpenAI client.

  • L12-17: Create a simple chat completion

    • L13: Use the fastest and cheapest model for testing

Here are common issues and troubleshooting you may encounter:

Issue
Solution

AuthenticationError

Your API key is invalid or not set. Double-check the key and environment variable name.

RateLimitError

You are making requests too quickly. Add delays between requests or upgrade your account tier.

InsufficientQuotaError

You have exceeded your usage limits or need to add billing information. Check your usage page.

ModuleNotFoundError: openai

The OpenAI package isn't installed. Run pip install openai in the Terminal.

Environment variable not found

Make sure you have set up the environment variable correctly and restarted PyCharm if needed.

References

Last updated

Was this helpful?