Set Up Your Agent Development Lab

One afternoon of setup saves weeks of confusing errors and the occasional surprise bill.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

A good agent lab has five things: an isolated environment per project, pinned versions, secrets kept out of code, a spending limit before the first model call, and a way to test without a model. You can start with Python and a text editor and add local models, containers and tracing later.

What you will learn: how to create a project environment on Windows, macOS or Linux, protect keys, control spending, choose between hosted and local models, and check that everything works.
Prerequisites: you can open a terminal and edit a file.

Beginner A clean, safe starting point

What you are building

Your projectAgent code, tools, tests, prompts
Isolated environmentThis project's packages and versions
Configuration and secretsEnvironment variables, never in code
Model accessScripted stand-in, hosted API or local server

What to install

ItemNeededNotes
PythonNowUse a release that still receives support. The newest release may arrive before some libraries support it.
GitNowHistory for code, prompts and test cases
Code editorNowAny editor with Python support
Node.jsLaterFor TypeScript agents or tool servers; choose a long-term support release
Container toolLaterTo isolate code execution and mirror deployment
Local model serverOptionalNeeds suitable memory and, for larger models, a graphics processor

Download installers from the official project sites or your operating system's package manager. On a work computer, follow your organization's rules on software installation.

Set up a Python environment

A virtual environment is a private folder of packages for one project. It stops one project's upgrade from breaking another. Python includes the venv module for this.

macOS and Linux

mkdir agent-lab
cd agent-lab
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip

Windows PowerShell

mkdir agent-lab
cd agent-lab
py -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip

If PowerShell refuses to run the activation script, read the message and your organization's policy before changing execution settings. You can also call the interpreter directly with .venv\Scripts\python.exe without activating.

Install and record packages

python -m pip install python-dotenv
python -m pip freeze > requirements.txt

The frozen file records exact versions so that you, or a colleague, can rebuild the same environment with python -m pip install -r requirements.txt. Install only packages you need, check the spelling of each name and prefer well-known projects. A mistyped package name can install something hostile.

An alternative: uv

uv is a separate tool that manages environments, dependencies and a lock file together.

uv init agent-lab
cd agent-lab
uv add python-dotenv
uv run python -c "print('ready')"

Use one approach per project and commit its lock or requirements file. Mixing tools in the same folder leads to confusion about which versions are active.

A project layout that scales

agent-lab/
  .env              secrets for this machine, never committed
  .env.example      names of the settings, no values
  .gitignore
  requirements.txt
  src/
    agent.py        the loop
    tools.py        functions the agent may call
    config.py       limits and model settings
  prompts/          instructions, kept as text files
  tests/            offline tests with a scripted model
  evals/            test cases and scores
  runs/             logs and traces, not committed

Separating tools, prompts and limits from the loop makes each one reviewable. It also means a change to instructions shows up clearly in history.

Intermediate Secrets, spending and model access

Keep secrets out of code

An API key is a password that spends money. Put it in an environment variable, or in a local .env file that Git ignores.

# .gitignore
.venv/
.env
runs/
__pycache__/
# .env.example  (commit this one)
MODEL_API_KEY=
MODEL_NAME=
MAX_USD_PER_RUN=0.50
If a key leaks

Deleting the file or the commit is not enough, because copies may already exist. Revoke the key in the provider's console, create a new one and check usage records.

  • Create a separate key for experiments, with the narrowest permissions offered.
  • Never paste a key into a prompt, a log, a screenshot or a support request.
  • Do not give an agent that runs commands access to the folder holding your personal credentials.
  • For shared or deployed systems, use a secret manager rather than files. See Agent Identity, Authorization and Secrets.

Check your setup

This script uses only the standard library. It checks the version, a few modules, your key setting and your ignore rules, and it never prints a secret. It runs here against a temporary folder, first incomplete and then fixed.

"""Check an agent development setup. Standard library only. Prints no secrets."""
import importlib.util
import sys
from pathlib import Path

NEEDED = ["venv", "json", "sqlite3", "asyncio"]
REQUIRED_KEY = "MODEL_API_KEY"

def read_env_file(text):
    """Read KEY=value lines; ignore blanks and comments."""
    values = {}
    for line in text.splitlines():
        line = line.strip()
        if line and not line.startswith("#") and "=" in line:
            key, value = line.split("=", 1)
            values[key.strip()] = value.strip().strip("\"'")
    return values

def check(project, version=sys.version_info):
    results = []
    results.append(("Python 3.11 or newer", version >= (3, 11)))
    for name in NEEDED:
        found = importlib.util.find_spec(name) is not None
        results.append((f"module {name}", found))
    env_file = project / ".env"
    env = read_env_file(env_file.read_text()) if env_file.exists() else {}
    results.append((f"{REQUIRED_KEY} present in .env", bool(env.get(REQUIRED_KEY))))
    ignore = project / ".gitignore"
    ignored = ignore.read_text().split() if ignore.exists() else []
    results.append((".env listed in .gitignore", ".env" in ignored))
    results.append(("lock or requirements file", any(
        (project / f).exists() for f in ("uv.lock", "requirements.txt"))))
    return results

def report(title, project):
    print(title)
    results = check(project)
    for label, ok in results:
        print(f"  {'ok  ' if ok else 'FIX '} {label}")
    print(f"  {sum(ok for _, ok in results)} of {len(results)} checks passed")

if __name__ == "__main__":
    import tempfile
    with tempfile.TemporaryDirectory() as folder:
        project = Path(folder)
        (project / ".env").write_text("# local only\nMODEL_API_KEY=\n")
        report("New project:", project)
        (project / ".env").write_text("MODEL_API_KEY=test-not-a-real-key\n")
        (project / ".gitignore").write_text(".venv\n.env\n")
        (project / "requirements.txt").write_text("python-dotenv\n")
        report("After the fixes:", project)

Output:

New project:
  ok   Python 3.11 or newer
  ok   module venv
  ok   module json
  ok   module sqlite3
  ok   module asyncio
  FIX  MODEL_API_KEY present in .env
  FIX  .env listed in .gitignore
  FIX  lock or requirements file
  5 of 8 checks passed
After the fixes:
  ok   Python 3.11 or newer
  ok   module venv
  ok   module json
  ok   module sqlite3
  ok   module asyncio
  ok   MODEL_API_KEY present in .env
  ok   .env listed in .gitignore
  ok   lock or requirements file
  8 of 8 checks passed

To check your own project, call report("My lab:", Path(".")). The ignore check is deliberately simple. Git's own command git check-ignore -v .env gives the authoritative answer.

Choose how to reach a model

OptionStrengthsLimitsGood for
Scripted stand-inFree, instant, repeatableNo real language abilityLoop, tool and error tests
Hosted APICapable models, little setupCost per use; data leaves your machineRealistic behavior and evaluation
Local serverData stays on your hardware; no per-token feeHardware limits model size and speedPrivate experiments, offline work

Several local servers, including vLLM and Ollama, offer an endpoint that follows the widely used OpenAI API shape, so the same client code can point to a different address. Compatibility is rarely complete: test tool calling and structured output, which differ most. If you run a server on a network, secure it; vLLM's documentation, for instance, warns that its API-key option does not protect every endpoint.

Keep the choice in one place. A function such as get_model() that reads MODEL_NAME lets you swap providers without editing the loop. Choosing Models: Reasoning, Open-Weight and Hosted explains how to compare them.

Put the model behind one function

Before using any provider, decide what the rest of your program expects from a model: a list of messages and tool descriptions go in; text or tool requests and a token count come out. Write that as a small function or class of your own. Then provide two versions.

VersionBehaviorUsed by
ScriptedReturns replies you prepared, in orderUnit tests and demonstrations
RealCalls the provider, with timeout, retry and usage recordingEvaluation runs and users

This boundary has three benefits. Tests become fast and free. Changing provider touches one file. And every call passes through one place where you can apply limits, redact logs and record usage. Keep the interface small. A boundary that tries to expose every provider feature becomes a second, poorly documented API that nobody wants to maintain.

A good first real call

Ask for a short reply, set a low maximum output, print the usage figures and compare them with the provider's console a little later. You will learn what your account actually measures before a loop multiplies it.

Limit spending before the first call

An agent in a loop sends a growing history again on each step, so cost can rise faster than you expect. Use the provider's spending controls where they exist, and add a guard of your own. The prices in this example are invented.

"""Stop an experiment before it spends more than you intended."""

class BudgetExceeded(Exception):
    pass

class BudgetGuard:
    def __init__(self, limit_usd, in_price, out_price, max_calls=50):
        self.limit = limit_usd
        self.in_price = in_price / 1_000_000    # prices are per million tokens
        self.out_price = out_price / 1_000_000
        self.max_calls = max_calls
        self.spent = 0.0
        self.calls = 0

    def before_call(self, input_tokens, max_output_tokens):
        """Refuse a call whose worst case would break a limit."""
        worst = input_tokens * self.in_price + max_output_tokens * self.out_price
        if self.calls >= self.max_calls:
            raise BudgetExceeded(f"call limit {self.max_calls} reached")
        if self.spent + worst > self.limit:
            raise BudgetExceeded(
                f"next call could reach ${self.spent + worst:.4f}, "
                f"limit is ${self.limit:.2f}")

    def after_call(self, input_tokens, output_tokens):
        self.calls += 1
        self.spent += (input_tokens * self.in_price
                       + output_tokens * self.out_price)

if __name__ == "__main__":
    # Example prices only. Use the current prices of your provider.
    guard = BudgetGuard(limit_usd=0.05, in_price=1.00, out_price=5.00)
    history = 2_000
    try:
        for step in range(1, 100):
            guard.before_call(history, max_output_tokens=1_000)
            guard.after_call(history, output_tokens=400)
            print(f"step {step}: input {history:>6} tokens, spent ${guard.spent:.4f}")
            history += 1_500          # a loop resends a growing history
    except BudgetExceeded as stop:
        print("stopped:", stop)

Output:

step 1: input   2000 tokens, spent $0.0040
step 2: input   3500 tokens, spent $0.0095
step 3: input   5000 tokens, spent $0.0165
step 4: input   6500 tokens, spent $0.0250
step 5: input   8000 tokens, spent $0.0350
step 6: input   9500 tokens, spent $0.0465
stopped: next call could reach $0.0625, limit is $0.05

The guard checks the worst case of the next call before making it. Checking only afterward would let one large call pass the limit. Real bills may also include cached tokens, reasoning tokens, tool fees and retries, so read the usage fields your provider returns.

A TypeScript lab, if you need one

The same principles apply with Node.js. Create one folder per project, initialize it, install what you need and commit the lock file that your package manager writes.

mkdir agent-lab-ts
cd agent-lab-ts
npm init -y
npm install --save-dev typescript @types/node
npx tsc --init

Use npm ci on build machines so that they install exactly what the lock file records. Review packages before adding them, and be cautious with packages that run scripts during installation. TypeScript: Mastra and Vercel AI SDK covers library choices.

A daily working routine

  1. Pull the latest code and activate the environment.
  2. Run the offline tests. Start from a passing state.
  3. Make one change: code, prompt or tool description, not all three.
  4. Add or update a test that shows why the change was needed.
  5. Run a small model-backed check with the spending guard on.
  6. Read at least one full trace, including a successful one.
  7. Commit with a message that says what behavior changed.

Changing one thing at a time matters more with agents than with ordinary programs. Output varies between runs, so two simultaneous changes leave you unable to say which one helped. Repeat a model-backed check several times before believing a small difference.

Expert Isolation, reproducibility and teams

Isolate anything that executes

A virtual environment separates packages. It is not a security boundary: code inside it can read your files and use your network. If an agent writes or runs code, give it a container or virtual machine with its own folder, no personal credentials, restricted network access and limits on memory and time. See Code Execution and Sandboxing.

RiskLab control
Agent deletes or overwrites filesWork on a copy in a dedicated folder
Agent sends data outwardBlock network access except the hosts needed
Hostile instructions in downloaded contentNo credentials within reach; approve actions
Runaway processTime, memory and cost limits
Malicious packagePinned versions, review before upgrading

Make runs reproducible

You cannot make a hosted model fully repeatable, but you can record enough to understand any run:

  • code commit, prompt version and tool definitions;
  • model identifier and settings;
  • package lock file;
  • inputs, tool results, outputs, token counts and duration;
  • the test-set version used for scoring.

Store test data you are allowed to keep, and strip personal information from logs. For continuous checks, run offline tests on every change and model-backed evaluations on a schedule or before release, with their own budget. Lab: Evaluation Harness and Tracing extends the lab with tracing.

Setting up for a team

Give newcomers one command that prepares the environment and one that runs the offline tests. Commit the example settings file, not real values. Issue individual keys so that usage can be attributed and revoked. Write down which data may be used in development, and provide invented sample data so that nobody is tempted to copy production records.

Common setup problems

SymptomLikely causeWhat to check
"Module not found" after installingInstalled into a different interpreterRun python -m pip inside the active environment
Key reported missingThe .env file was not loadedWorking folder and loading code
Authentication errorWrong, expired or revoked keyProvider console; stray spaces or quotes
Rate-limit errorsToo many requests or tokensBack off and respect the reply's retry guidance
Certificate errors at workA company network proxyAsk IT for the approved certificate setup; do not disable verification
Local model very slowModel too large for the hardwareTry a smaller model or reduced precision

Lab checklist

  • The project has its own environment and a committed lock or requirements file.
  • .env is ignored by Git and an example file lists the setting names.
  • A spending limit is set at the provider and in code.
  • Tests run without a model or a network.
  • Code execution happens in an isolated place without personal credentials.

Frequently asked questions

Do I need a graphics processor?

Not for hosted APIs or offline tests. Local models benefit greatly from one, and small models can run on ordinary computers at lower speed.

Should I learn containers first?

No. Add them when an agent needs to execute code, or when you prepare to deploy.

Can I use a hosted notebook?

Yes for learning. Check where files and keys are stored, who can open the notebook and whether saved output contains secrets.

How often should I upgrade packages?

On a regular schedule and for security fixes. Upgrade in a branch, run tests and evaluations, then merge.

References and further reading

Next steps