Windows SDK Quickstart

Complete Windows setup guide for PraisonAI SDK with virtual environments, environment variables, and networking configuration

Windows SDK setup for PraisonAI with virtual environments, environment variables, and UTF-8 configurations tailored for non-developers.

python
from praisonaiagents import Agent

agent = Agent(
    name="Windows Helper",
    instructions="You are a helpful assistant running on Windows.",
)
agent.start("Hello from Windows!")

The user sends a message from Windows; the agent responds once the SDK environment is configured.

Diagram

Windows Setup Flow

🪟 Python Install

📦 Virtual Environment

🔧 Environment Variables

🌐 Network & Firewall

🚀 Agent Ready

Quick Start

  1. Python Installation & Virtual Environment

    Install Python 3.10+ from python.org (recommended over Windows Store version for fewer PATH issues):

    powershell
    # Check Python version
    py --version
    
    # Create virtual environment with specific Python version
    py -3.12 -m venv .venv
    
    # Activate virtual environment (PowerShell)
    .\.venv\Scripts\Activate.ps1
    
    # Upgrade pip
    python -m pip install -U pip
    
    # Install PraisonAI
    pip install praisonaiagents

    If you get execution policy errors, run:

    powershell
    Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
  2. Basic Agent Setup

    Create a simple agent to verify installation:

    python
    from praisonaiagents import Agent
    
    agent = Agent(
        name="Windows Helper",
        instructions="You are a helpful assistant running on Windows"
    )
    
    result = agent.start("Hello, test my setup")
    print(result)
  3. Environment Variables Configuration

    Create a .env file in your working directory:

    bash
    # .env file — paste keys after each equals sign
    OPENAI_API_KEY=
    ANTHROPIC_API_KEY=
    PRAISONAI_LOG_LEVEL=INFO

    Load and use environment variables:

    python
    from praisonaiagents import Agent
    from dotenv import load_dotenv
    import os
    
    # Load environment variables
    load_dotenv()
    
    agent = Agent(
        name="API Agent",
        instructions="You have access to API keys from environment",
        llm_model="gpt-4"
    )
    
    result = agent.start("What's my current configuration?")
  4. Sandbox on Windows

    Agent(sandbox=True) runs on Windows out of the box using the subprocess backend, but with weaker isolation than POSIX — for untrusted code, use docker or a cloud backend.

    python
    from praisonaiagents import Agent
    
    agent = Agent(
        name="Coder",
        instructions="Run code safely",
        sandbox=True,  # subprocess backend on Windows — see limitations below
    )
    agent.start("Print the current working directory")

    What applies on Windows:

    • ✅ ../ and absolute-path traversal protection is fully enforced
    • ✅ Static code safety pre-checks (check_code_safety) run normally
    • ❌ setrlimit memory / process / file-descriptor limits are not enforced
    • ❌ Process-group kill on timeout is unavailable — only the leader is killed
    • ⚠️ Symlink escape protection only triggers when symlink creation is permitted (Developer Mode / SeCreateSymbolicLinkPrivilege)

    See /docs/features/sandbox#resource-limits-in-practice for the full capability matrix.

    To harden a Windows sandbox, switch backends — see Sandbox Backends.

  5. CLI Sessions on Windows

    The praisonai session commands now work on Windows out of the box — sessions are persisted to %USERPROFILE%\.praison\sessions\ using msvcrt-based file locking.

    powershell
    praisonai session start my-project
    praisonai "What's in my project?" --session my-project
    praisonai session list

    This functionality was fixed in PR #1837. Prior releases failed with ModuleNotFoundError: No module named 'fcntl' on Windows when these subcommands were invoked.

  6. Running the MCP host on Windows

    Serve your agents to Claude Desktop or Cursor over STDIO — supported on Windows, including Python 3.13:

    bash
    pip install "praisonai-mcp[all]"
    praisonai-mcp serve --transport stdio

    Python 3.13 is supported. Earlier praisonai-mcp releases crashed on Windows with OSError: [WinError 6] The handle is invalid; the STDIO transport now reads stdin on a dedicated thread, so it works under the ProactorEventLoop.

    Point your MCP client at the command:

    json
    {
      "mcpServers": {
        "praisonai": {
          "command": "praisonai-mcp",
          "args": ["serve", "--transport", "stdio"]
        }
      }
    }

    See MCP STDIO Server Transport for the reliability guarantees.


How It Works

Diagram
APIAgentVirtualEnvPowerShellUserAPIAgentVirtualEnvPowerShellUserpy -3.12 -m venv .venvCreate isolated environment.\.venv\Scripts\Activate.ps1Activated environmentCreate agent instanceLoad environment variablesAPI connection establishedReady for tasks
ComponentPurposeWindows-Specific
Virtual EnvironmentIsolate Python dependenciesUse .\.venv\Scripts\Activate.ps1
Environment VariablesStore API keys securely.env files in working directory
PowerShellCommand executionHandle execution policy settings
UTF-8 EncodingPrevent character issuesSave files as UTF-8 in editors

Prerequisites

Python Installation

  • Python 3.10+ from python.org (recommended)
  • Avoid Windows Store Python for fewer PATH conflicts
  • Git for Windows with proper line endings: git config --global core.autocrlf true

IDE Configuration

Point your IDE to the virtual environment Python interpreter:

  • VS Code: Select .venv\Scripts\python.exe as interpreter
  • Cursor: Use Command Palette > Python: Select Interpreter

Virtual Environment Management

PowerShell Commands

powershell
# Create environment
py -3.12 -m venv .venv

# Activate environment
.\.venv\Scripts\Activate.ps1

# Deactivate environment
deactivate

# Check active environment
where python

Execution Policy Issues

If activation fails with execution policy errors:

powershell
# Check current policy
Get-ExecutionPolicy -Scope CurrentUser

# Set policy for current user only
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned

# Verify change
Get-ExecutionPolicy -Scope CurrentUser

Environment Variables

.env File Location

  • Working Directory: Place .env in your project root
  • Current Directory: load_dotenv() reads from os.getcwd()
  • Multiple Files: Use single .env file to avoid conflicts

Precedence and Loading

python
from dotenv import load_dotenv
import os

# Basic loading (from current working directory)
load_dotenv()

# Explicit path loading
load_dotenv(dotenv_path=".env.local")

# Override existing environment variables
load_dotenv(override=True)

# Check if variable loaded
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
    print("API key not found!")

PYTHONPATH Configuration

For monorepo or src layouts, use session-scoped variables:

powershell
# Temporary PYTHONPATH (session only)
$env:PYTHONPATH = (Resolve-Path .).Path + "\src"

# Verify setting
echo $env:PYTHONPATH

Warning: Avoid persistent PYTHONPATH via setx as it affects other projects.

Environment Variable Security

powershell
# Session-scoped (recommended for development)
$env:OPENAI_API_KEY = "..."  # paste your OpenAI key

# Avoid setx for API keys (hard to rotate, visible system-wide)
# setx OPENAI_API_KEY "your-key" # DON'T DO THIS

Unicode and Encoding

File Encoding Issues

Save all Python files as UTF-8 to prevent character encoding errors:

  • VS Code: Check status bar, ensure “UTF-8”
  • Notepad++: Encoding menu > “UTF-8”
  • Windows Notepad: Save As > Encoding: UTF-8

Common Encoding Error

python
# This will fail with cp1252 encoding
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 1854

# Solution: Ensure UTF-8 file encoding

Python Script Encoding

Add encoding declaration to Python files:

python
# -*- coding: utf-8 -*-

Networking and Firewall

Windows Defender Prompts

When running agents with network access:

  • Allow access when Windows Defender prompts
  • Add exception for Python.exe in Windows Security

Port Conflicts

Check for port conflicts when running multiple agents:

powershell
# Check what's using port 8000
netstat -ano | findstr :8000

# Kill process by PID
taskkill /PID 1234 /F

Localhost vs External Access

python
from praisonaiagents import Agent

# Localhost only (default)
agent = Agent(
    name="Local Agent",
    host="127.0.0.1",
    port=8000
)

# External access (for team development)
agent = Agent(
    name="Network Agent", 
    host="0.0.0.0",
    port=8000
)

OpenClaw Integration

Subprocess Configuration

Use absolute paths for reliable subprocess execution:

python
import subprocess
import sys
from pathlib import Path

# Get absolute path to praisonai executable
praisonai_path = Path(sys.executable).parent / "praisonai.exe"

# Or use python -m for cross-platform compatibility
subprocess.run([sys.executable, "-m", "praisonai", "--help"])

Virtual Environment in Subprocesses

Ensure subprocesses use the same virtual environment:

python
import os
import subprocess

# Get current virtual environment path
venv_python = sys.executable

# Run subprocess with same Python
result = subprocess.run([
    venv_python, "-c", 
    "import praisonaiagents; print('Success')"
], capture_output=True, text=True)

Common Patterns

Development Workflow

python
# development_setup.py
from pathlib import Path
from dotenv import load_dotenv
from praisonaiagents import Agent
import os

# Ensure we're in project directory
os.chdir(Path(__file__).parent)

# Load environment variables
load_dotenv()

# Create development agent
dev_agent = Agent(
    name="Dev Assistant",
    instructions="Help with Windows development tasks",
    llm_model=os.getenv("DEFAULT_MODEL", "gpt-4o-mini")
)

if __name__ == "__main__":
    result = dev_agent.start("Check my development environment")
    print(result)

Multi-Agent Windows Setup

python
from praisonaiagents import Agent, Task, PraisonAIAgents

# Create multiple agents for Windows tasks
system_agent = Agent(
    name="System Monitor",
    instructions="Monitor Windows system resources"
)

file_agent = Agent(
    name="File Manager", 
    instructions="Handle file operations with proper Windows paths"
)

# Define tasks
tasks = [
    Task(description="Check system status", expected_output="System report", agent=system_agent),
    Task(description="Organize project files", expected_output="File structure", agent=file_agent)
]

# Run multi-agent system
agents_system = PraisonAIAgents(agents=[system_agent, file_agent], tasks=tasks)
result = agents_system.start()

Best Practices

Virtual Environment Management
  • Always activate virtual environment before installing packages
  • Use py -3.12 -m venv instead of python -m venv for version specificity
  • Keep virtual environments in project directories (.venv)
  • Add .venv/ to your .gitignore file
  • Document Python version requirements in README.md
Environment Variable Security
  • Use .env files for development, proper secret management for production
  • Never commit .env files to version control (add to .gitignore)
  • Use session-scoped variables for temporary testing
  • Rotate API keys regularly and update .env files
  • Consider using Azure Key Vault or similar for production deployments
File Encoding and Paths
  • Always save Python files as UTF-8 encoding
  • Use pathlib.Path for cross-platform path handling
  • Use forward slashes in Python strings: "data/file.txt"
  • Test with non-ASCII characters in file names and content
  • Set Git to handle line endings: git config core.autocrlf true
Networking and Firewall
  • Allow Python.exe through Windows Firewall for network features
  • Use localhost (127.0.0.1) for development, specific IPs for production
  • Check for port conflicts with netstat before starting services
  • Consider Windows network profiles (Public/Private/Domain)
  • Test connectivity with different antivirus software

Troubleshooting

SymptomLikely CauseFix
'py' is not recognizedPython not in PATHReinstall Python, check “Add to PATH”
Activate.ps1 cannot be loadedExecution policySet-ExecutionPolicy -Scope CurrentUser RemoteSigned
UnicodeDecodeError: 'charmap'File not UTF-8Save files as UTF-8 encoding
WinError 10048 (port in use)Port conflictUse netstat to find and kill process
.env file not loadingWrong working directoryCheck os.getcwd(), move .env to correct location
Import errors after installWrong virtual environmentVerify where python points to .venv
ModuleNotFoundError: No module named 'fcntl' when running praisonai session …Pre-PR #1837 release on WindowsUpgrade to the release that includes PR #1837; CLI session store is now cross-platform
OSError: [WinError 1314] A required privilege is not held by the client in a sandboxed job that creates symlinksDefault non-admin Windows users cannot create symlinksEnable Windows Developer Mode (Settings → System → For developers), or run under an account that holds SeCreateSymbolicLinkPrivilege. See PR #3224.
Sandbox process still running after a timeout on Windowsos.killpg is POSIX-only — only the leader process is killed on WindowsPrefer the docker backend for reliable timeout enforcement on Windows. See the Windows tab of the sandbox docs.
pytest tests -m "not network" fails in src/praisonai-sandbox with WinError 1314 / AttributeError: os.killpg on WindowsPre-release before PR #3224 lacked platform skips on those testsUpgrade to a release that contains PR #3224.
RuntimeError: MCP server produced 0 tools ... when calling MCP("npx ...")npx on Windows is a .cmd shim; the SDK spawns the wrong executable and the server lists no tools. Fail-closed since PraisonAI #4423.Pass the shim explicitly: MCP(command="npx.cmd", args=["-y", "@pkg"]). Or switch to a Python MCP server: MCP(command=sys.executable, args=["server.py"]). See MCP → Errors on construction.
TimeoutError: MCP initialization timed out after N seconds when calling MCP(...)The stdio subprocess did not complete the MCP handshake within timeout=. Common causes on Windows: Node not on PATH, offline -y install, antivirus blocking npx.Raise timeout= (e.g. MCP(..., timeout=90)), verify node --version and npx --version work in the same shell, or pre-install the MCP server so -y skips the download.
RuntimeError: MCP initialization failed: ... fileno on Windows when calling MCP("npx ...") or MCP("uvx ...")MCPToolRunner‘s background thread had a SelectorEventLoop, which cannot spawn subprocesses on Windows. Fixed in PraisonAI #5601 — the runner now installs a ProactorEventLoop on Windows.Upgrade praisonaiagents to a release containing PR #5601: pip install -U praisonaiagents. No code change required. See MCP → Errors on construction → Init error.

Related

See Command-Aware Permissions → Windows / PowerShell dialect for how PraisonAI gates PowerShell/cmd commands under your permission rules.