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.
OpenAI Account
Create an OpenAI account (if needed):
Sign up with your email address or use an existing account
Generate your API key:
Log in to https://platform.openai.com
Click "+ Create new secret key"
Give your key a descriptive name (e.g., "NLP-Essentials")
Click "Create secret key"
Copy the key immediately and save it securely - you will not be able to see it again!
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
Security Warning: Never share your API key or commit it to GitHub. Treat it like a password. If you accidentally expose it, delete it immediately from the OpenAI dashboard and create a new one.
Configure API Key
Install the python-dotenv package:
pip install python-dotenvCreate 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/
.envLoad environmental variables by adding the following code:
from dotenv import load_dotenv
load_dotenv()L3: Load environment variables from the
.envfile
Security Warning: Never hardcode your API key in any of your Python files nor commit the .env file to GitHub.
Test API Connection
Install the openai package:
pip install openaiVerify 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
Hello World
ChatCompletion(
id='chatcmpl-CfaRxgTbF2CfDMo63LJwICeQBjODl',
choices=[
Choice(
finish_reason='stop',
index=0,
logprobs=None,
message=ChatCompletionMessage(
content='Hello World',
refusal=None,
role='assistant',
annotations=[],
audio=None,
function_call=None,
tool_calls=None))],
created=1764027597,
model='gpt-5-nano-2025-08-07',
object='chat.completion',
service_tier='default',
system_fingerprint=None,
usage=CompletionUsage(
completion_tokens=203,
prompt_tokens=11,
total_tokens=214,
completion_tokens_details=CompletionTokensDetails(
accepted_prediction_tokens=0,
audio_tokens=0,
reasoning_tokens=192,
rejected_prediction_tokens=0),
prompt_tokens_details=PromptTokensDetails(
audio_tokens=0,
cached_tokens=0)))Here are common issues and troubleshooting you may encounter:
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
Source: src/llm_api_access.py
Last updated
Was this helpful?