Zulia Shavaeva← Back to Zulia
Free AI and security guide/Learn

Learn / Python and coding for AI security work

Python and coding for AI security work

Enough Python to build a small LLM or agent app, call model APIs, write tests against them and automate attacks or checks; 67 percent of the 48 postings ask for it.

Researched on 2026-09-26 with AI assistance. Links and summaries can change; verify details with the original source. Not yet reviewed by a person.

What it is

Practical Python for AI security means being able to build the thing you are asked to test: a script that calls a model API, a small retrieval or tool-using agent, and a test harness that runs prompts and scores the answers. Most of that tooling is Python, for example Inspect installs with pip install inspect-ai and needs a provider package plus an API key in the environment.5

It also means driving the security tooling, which is Python first: garak is a scanner built around probes and detectors for LLM vulnerabilities, and PyRIT is a Python framework whose attacks, converters, scorers and memory you extend in code.36

A large part of the job is writing assertions rather than reading chat transcripts. promptfoo assertions compare model output against expected values or conditions so analysis can be automated, and Inspect splits an evaluation into a dataset, a solver and a scorer.75

The coding is defensive as well as offensive: NIST SP 800-218A extends the Secure Software Development Framework with practices and tasks specific to generative AI and dual-use foundation model development across the lifecycle, so the code you write is judged against normal secure development expectations.9

Why postings ask for it

67 percent of the 48 postings ask for coding, and the split follows how hands-on the role is: 100 percent of the 4 AI Security Research postings, 89 percent of the 9 AI Red Team postings and 81 percent of the 16 AI/Agent Security Engineer postings, against 0 percent of the 7 AI Governance / GRC postings.P

Red team and research work is written as code because the attacks are parameterised and repeated: multi-turn strategies, converters and scorers in PyRIT, or probe-and-detector runs in garak, give results you can rerun after a model or prompt change.63P

Engineering and architect postings need it because the fixes live in application code: parameterising queries fed by model output, constraining tool permissions, and sandboxing agent execution so generated code cannot reach credentials, files or the network.113P

Concepts you should be able to explain

If you can say each of these out loud in two minutes, with an example, you are ready for the technical part of an interview on this skill.

Calling model APIs from code

Models are reached through provider packages and an API key taken from the environment, for example pip install openai and export OPENAI_API_KEY before running an evaluation. Inspect supports over 20 providers plus local inference with HuggingFace, vLLM and SGLang, so the same test code can be pointed at a hosted or a local model. Keeping keys in the environment and making the model an argument is the base pattern for everything else.5

Dataset, solver, scorer

An Inspect task combines a dataset of labelled samples with input and target fields, a solver that produces an answer (one generate call or a full tool-using agent), and a scorer that grades the output by text comparison or model grading. Learning this shape means you can express a security test as data plus a run plus a judgement instead of a one-off prompt. It is also what makes results comparable across models.5

Assertions instead of eyeballing

Model output varies between runs, so tests assert on properties and conditions rather than exact strings; promptfoo assertions compare output against expected values or conditions to automate the analysis. In security testing the assertion is usually the absence of a leaked secret, a refused action, or a well-formed and in-scope tool call. Writing the assertion first forces you to define what failure means.7

Probes, detectors and scanners

garak treats LLM security as a moving target: models give unpredictable output, are updated constantly, and what counts as a weakness in one context may not be in another, so it structures testing as probes against a target with detectors deciding whether a run failed. PyRIT adds multi-turn strategies such as Crescendo, TAP and Skeleton Key, prompt converters, true/false, Likert and classification scorers, and a SQLite memory of all conversations and results. Knowing both means you can automate attack coverage and keep the evidence.36

The agent loop and tool calls

A ReAct agent alternates Thought, Action and Observation text, and the whole loop is just text the model reads back. The Damn Vulnerable LLM Agent shows that injecting a fake Observation and Thought hijacks the loop and makes the agent fetch another user's transactions, which is harder to stop than plain system-prompt overriding. If you cannot read and write an agent loop in Python you cannot see where these boundaries are.12

Untrusted data reaching the prompt

Indirect prompt injection works by placing instructions in data the application is likely to retrieve, so an attacker needs no direct interface to the model; the original work demonstrated data theft, worming and ecosystem contamination against real systems including Bing's GPT-4 powered chat and code completion engines. OWASP lists prompt injection as LLM01:2025, where user prompts alter model behaviour. In code terms, every retrieval, email body, web page or tool result is attacker-controlled input.21

Model output is untrusted input

OWASP LLM05:2025 Improper Output Handling covers insufficient validation and sanitisation of model output before it is used downstream. The second flag in the Damn Vulnerable LLM Agent is reached by making the model pass a UNION-based SQL injection payload into a tool argument, which is an ordinary injection bug with a model in the middle. The fix is parameterised queries, schema validation on tool arguments and encoding at the sink, all written in application code.112

Least privilege, sandboxing and design patterns

OWASP LLM06:2025 Excessive Agency covers systems granted more autonomy than the task needs, and LangChain's guidance is that because you cannot predict what an agent might do its environment should be isolated so it cannot reach credentials, files or the network. Inspect ships a sandboxing system for untrusted model code on Docker, Kubernetes and similar backends. Recent work proposes design patterns for agents with provable resistance to prompt injection and discusses their utility and security trade-offs, which gives you defensible architecture arguments rather than filter-only answers.113511

Use fictional data and authorised sandboxes. Remove employer details and secrets from any portfolio write-up. Time estimates exclude setup. Check model and cloud costs before running tests, set spending limits, and delete lab resources afterwards.

Three exercises

In order of difficulty. Free tools. Keep what you build; it is evidence.

1A minimal model client with tests that pass and fail on purposeabout 4 h

Show a Python script that calls a model and a test suite whose assertions catch a leaked secret and a malformed tool argument, with results you can rerun.75

  1. Write one Python function that sends a prompt to a model and returns text, taking the model name and key from environment variables.
  2. Put a fake secret in the system prompt and write assertions that fail if it ever appears in output, using promptfoo assertions or plain pytest.
  3. Add ten prompt variants as a small dataset file and loop over them so every run covers the same set.
  4. Rerun against a second model or temperature and note which assertions flip, then record the pass rate.

Tools: Python, pytest, promptfoo, a local model runner or a free model endpoint

2Scan a target with garak, then extend itabout 5 h

Show a garak run report against a model you control plus one probe or detector you wrote yourself, and explain why each finding matters in context.34

  1. Install garak and run its built-in probes against a local or free-tier model, saving the report.
  2. Read the report and separate findings that matter for your application context from ones that do not, using the point that a weakness in one context may not be an issue in another.
  3. Write one custom probe reflecting a risk in your own app, for example system prompt leakage, and a detector that decides pass or fail.
  4. Re-run with the custom probe and write a five-line summary an engineer could act on.

Tools: Python, garak, a local model runner

3Break a tool-using agent, fix it, then prove the fix in CIabout 9 h

Show both Damn Vulnerable LLM Agent flags obtained, a patched version, and an automated regression test that fails on the old code and passes on the new.121158

  1. Clone the Damn Vulnerable LLM Agent, run it in the Python virtual environment or Docker, and reach flag one by injecting a fake Observation and Thought into the ReAct loop.
  2. Reach flag two by forcing a UNION-based SQL injection through the GetUserTransactions tool argument.
  3. Patch the app: parameterise the query, take the user id from the session rather than the prompt, and validate tool arguments against a schema.
  4. Reduce the agent's privileges and isolate its execution environment so it cannot reach credentials or the network, citing one design pattern for your choice.
  5. Encode both attacks as automated tests, for example an Inspect task or a promptfoo red team run, and check that they fail before the patch and pass after.

Tools: Python, Docker, Damn Vulnerable LLM Agent, Inspect, promptfoo, a local model runner

Practice questions

Written from the concepts above, not collected from a named employer. Open one, answer it out loud, then tick the points you covered; the score stays in this browser.

Your test prompt gets a different answer every run. How do you write a security test you can trust?Assertions instead of eyeballing

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

Walk me through the structure of an evaluation you would write for a customer support agent.Dataset, solver, scorer

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

What is the difference between direct and indirect prompt injection, and what does that change in your test code?Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

An agent uses a ReAct loop. Where would you attack it and why is that harder to filter than a system-prompt override?The agent loop and tool calls

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

A developer says the model is safe because it refuses harmful requests. What else do you check in the code?Model output is untrusted input

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

How would you reduce the blast radius of an agent that can browse and run code?Least privilege, sandboxing and design patterns

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

You have a garak report with dozens of failures. How do you turn it into work an engineering team will do?Probes, detectors and scanners

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

How do you keep these tests useful after the model is upgraded next month?promptfoo docs: LLM red teaming guide (open source)

Say your answer out loud or write it down, then tick what you covered:

0 of 4 covered

Sources

Every numbered claim above links here. P = the platform's own coding of 48 job postings.

  1. OWASP Top 10 for LLM and Gen AI Applications (2025) OWASP Gen AI Security Project
  2. Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection arXiv (Greshake et al.)
  3. garak: A Framework for Security Probing Large Language Models arXiv
  4. NVIDIA/garak, the LLM vulnerability scanner NVIDIA (GitHub)
  5. Inspect: an open-source framework for large language model evaluations UK AI Security Institute
  6. PyRIT, Python Risk Identification Tool documentation Microsoft
  7. promptfoo docs: Assertions and metrics promptfoo
  8. promptfoo docs: LLM red teaming guide (open source) promptfoo
  9. NIST SP 800-218A, Secure Software Development Practices for Generative AI and Dual-Use Foundation Models: An SSDF Community Profile NIST
  10. Secure Software Development Framework project page NIST
  11. Design Patterns for Securing LLM Agents against Prompt Injections arXiv
  12. Damn Vulnerable LLM Agent Reversec Labs (formerly WithSecure Labs)
  13. LangChain security policy and agent sandboxes LangChain
  14. AgentDojo: A Dynamic Environment to Evaluate Prompt Injection Attacks and Defenses for LLM Agents arXiv
  15. Web LLM attacks learning path and labs PortSwigger Web Security Academy

Resources

Free first. Levels: intro means no prior knowledge of this skill; working means you can apply it on a project; advanced means research depth or specialist tooling.

Level Format

Gaps the research could not fill with a good free source: No free course found today that teaches secure coding specifically for LLM and agent applications with graded exercises; the free material is either general Python or attack labs.; Could not confirm hours or price from the provider page for the Hugging Face AI Agents Course (index snippet says free, page not fetched).; No free, well-maintained lab found for writing pytest-style regression tests and CI gates against model APIs beyond the promptfoo docs, so that is a single point of dependence.; No free primary-source tutorial found for writing and hardening MCP servers in Python; the vulnerable-agent labs available are small community repos.; Nothing found that is aimed at GRC readers who need only enough Python to read and review AI test code (that cluster asks for coding in 0 percent of postings, so the gap may not matter).