إعداد بيئة Python الخاصة بكم
ثبّتوا OpenAI Python SDK، وأنشئوا بيئة افتراضية، وخزّنوا مفتاح API بأمان باستخدام متغيرات البيئة، وتحقّقوا من عمل كل شيء عبر فحص السلامة.
إعداد بيئة Python الخاصة بكم درس مجاني في AI Engineering Academy على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في AI Engineering Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة AI Engineering Academy 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Why Virtual Environments Matter
AI projects pull in lots of packages, and they clash over versions. A virtual environment gives each project its own isolated Python so nothing collides. The code sets one up.
# Create and activate a virtual environment
# Run these commands in your terminal
python3 -m venv .venv # create environment in .venv/ folder
source .venv/bin/activate # activate on macOS/Linux
# .venv\Scripts\activate # activate on Windows
python --version # verify you are using the right PythonInstalling the OpenAI Python SDK
The official OpenAI Python SDK is how you talk to the API — it handles auth, retries, and parsing. Install it inside your active environment, as the code shows.
# Install the OpenAI SDK
pip install openai
# For production projects, pin the version:
pip install 'openai>=1.30.0,<2.0.0'
# Save your dependencies to requirements.txt:
pip freeze > requirements.txt
# Install from requirements.txt on a new machine:
pip install -r requirements.txtGetting and Storing Your API Key
Your API key is a secret — never put it in code. Store it in a .env file, add that to .gitignore, and load it as an environment variable. The code shows the pattern.
# .env file (never commit this!)
# OPENAI_API_KEY=sk-proj-...
# In your Python script:
import os
from dotenv import load_dotenv
load_dotenv() # reads .env and sets environment variables
api_key = os.environ.get('OPENAI_API_KEY')
if not api_key:
raise ValueError('OPENAI_API_KEY environment variable not set!')
print('API key loaded:', api_key[:8] + '...') # only print prefixInitializing the OpenAI Client
You create one OpenAI() client and call everything through it. If your key is set as an env variable, the client finds it automatically — cleaner and safer.
from openai import OpenAI
# API key is read from OPENAI_API_KEY environment variable automatically
client = OpenAI()
# Or explicitly:
# client = OpenAI(api_key='sk-proj-...') # only for quick tests
# For alternative providers:
# client = OpenAI(
# api_key='your-together-key',
# base_url='https://api.together.xyz/v1'
# )Your First API Health Check
Before building anything, run a tiny health check that lists the models. It confirms your key works, the network is fine, and the SDK is installed. Always run it first.
from openai import OpenAI
client = OpenAI()
# Simple health check: list available models
try:
models = client.models.list()
print(f'Connection successful! Found {len(list(models))} models.')
except Exception as e:
print(f'Connection failed: {e}')Project Structure Best Practices
As projects grow, a consistent project structure saves headaches: keep secrets in .env, code in src/, and a .env.example template so teammates know what's needed.
# Recommended project structure:
# my_ai_project/
# |-- .env (secrets, gitignored)
# |-- .env.example (template, committed)
# |-- .gitignore
# |-- requirements.txt
# |-- README.md
# |-- src/
# | |-- __init__.py
# | |-- client.py (OpenAI client initialization)
# | |-- prompts.py (prompt templates)
# | |-- main.py
# |-- tests/
# |-- notebooks/
# |-- MakefileManaging Multiple API Keys Securely
Juggling many provider keys? A secrets manager like AWS Secrets Manager or Doppler scales better than one .env. Use a separate key per project so you can revoke safely.
# .env.example - commit this as a template
# OPENAI_API_KEY=sk-proj-...your key here...
# OPENAI_ORG_ID=org-...optional org id...
# COHERE_API_KEY=...cohere key...
# PINECONE_API_KEY=...pinecone key...
# PINECONE_ENVIRONMENT=us-east-1-aws
# In code, load all at once:
from dotenv import load_dotenv
import os
load_dotenv()
config = {
'openai_key': os.environ['OPENAI_API_KEY'],
'cohere_key': os.environ.get('COHERE_API_KEY'), # optional
}Using Python Version Managers
Different projects need different Python versions. A version manager like pyenv installs several and switches between them per folder — no system-level conflicts.
# Install pyenv (macOS via Homebrew)
# brew install pyenv
# Install Python 3.11
# pyenv install 3.11.9
# Set Python version for this project directory
# pyenv local 3.11.9
# This creates a .python-version file:
# cat .python-version
# 3.11.9
# Now python3 automatically uses 3.11.9 in this directoryTesting Your Setup With a Real Prompt
The real test is a live prompt that gets a real reply. This end-to-end check validates your setup, key, network, and billing in one shot. Ask for one word: READY.
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI()
response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[
{'role': 'system', 'content': 'You are a test responder.'},
{'role': 'user', 'content': 'Reply with just the word READY.'}
],
temperature=0,
max_tokens=5
)
print('Response:', response.choices[0].message.content)
print('Model used:', response.model)
print('Tokens used:', response.usage.total_tokens)Using uv for Faster Package Management
uv is a fast, Rust-based package manager that's 10-100x quicker than pip. For heavy AI libraries, a 3-minute install drops to seconds. Worth adopting from day one.
# Install uv (macOS/Linux)
# curl -LsSf https://astral.sh/uv/install.sh | sh
# Create a project with uv
# uv init my-ai-project
# cd my-ai-project
# Add dependencies
# uv add openai python-dotenv
# Run your script using the uv-managed environment
# uv run python main.py
# Generate requirements.txt for compatibility
# uv pip compile pyproject.toml -o requirements.txtEnvironment Variables in Production
In production, .env isn't enough. Platforms like Railway and Vercel inject environment variables at runtime. Your code reads os.environ; only the injected values change.
# Centralized config loader pattern for production
import os
from dataclasses import dataclass
@dataclass
class AppConfig:
openai_api_key: str
environment: str
log_level: str
@classmethod
def from_env(cls):
key = os.environ.get('OPENAI_API_KEY')
if not key:
raise EnvironmentError('OPENAI_API_KEY must be set')
return cls(
openai_api_key=key,
environment=os.environ.get('ENVIRONMENT', 'development'),
log_level=os.environ.get('LOG_LEVEL', 'INFO')
)
config = AppConfig.from_env()Quick Check
Test your understanding of AI Engineering concepts from this lesson.
Lesson Recap
You set up your toolkit: a virtual environment isolates dependencies, API keys live in env variables (never in code), and a health check runs first on any machine. Next: chat. 🎉
الأسئلة الشائعة
هل درس «إعداد بيئة Python الخاصة بكم» مجاني؟
نعم — نص درس «إعداد بيئة Python الخاصة بكم» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة AI Engineering Academy، انتقل إلى CoddyKit PRO. تتضمن دورة AI Engineering Academy 4 دروس في المجموع.
ماذا ستتعلم في «إعداد بيئة Python الخاصة بكم»؟
ثبّتوا OpenAI Python SDK، وأنشئوا بيئة افتراضية، وخزّنوا مفتاح API بأمان باستخدام متغيرات البيئة، وتحقّقوا من عمل كل شيء عبر فحص السلامة. تتمرن على AI Engineering Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ AI Engineering Academy؟
لا تُشترط خبرة سابقة. AI Engineering Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «إعداد بيئة Python الخاصة بكم»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس AI Engineering Academy هذا؟
نعم. كل درس في AI Engineering Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- إعداد بيئة Python الخاصة بكم
- نقطة نهاية إكمالات المحادثة
- التحكم في سلوك النموذج باستخدام المعلمات
- معالجة الأخطاء وحدود معدل الطلبات