GUARDLABS
GuardLabs · Technical note

Finding Vulnerabilities in Python Code with AI Agents

AI agents enhance traditional Static Application Security Testing (SAST) by analyzing code semantics rather than relying solely on rigid pattern matching. By combining Python's native Abstract Syntax Tree (AST) parsing with Large Language Models (LLMs), security teams can automate complex code audits, detect subtle business logic flaws, and reduce false positives.

Architecture of an AI Security Agent

An effective vulnerability scanning agent operates in four distinct phases:

  • Parsing & Extraction: Reads source files and breaks them into functional blocks or AST nodes.
  • Context Enrichment: Maps imports, variable scopes, and data flow across function boundaries.
  • LLM Analysis: Evaluates code chunks against common vulnerability patterns (e.g., OWASP Top 10, unsafe deserialization, command injection).
  • Structured Triage: Outputs findings in a standardized format (such as SARIF or JSON) containing severity ratings and remediation guidance.

Implementing a Python Vulnerability Scanning Script

The following implementation demonstrates how to construct a lightweight AI agent that extracts functions from a target Python file and queries an LLM to identify potential security vulnerabilities using structured JSON output.

import ast
import json
import openai

def extract_functions(file_path):
    """Parses a Python file and returns source code for each function definition."""
    with open(file_path, "r", encoding="utf-8") as f:
        tree = ast.parse(f.read(), filename=file_path)
    
    functions = []
    for node in ast.walk(tree):
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
            functions.append(ast.unparse(node))
    return functions

def analyze_function(function_code):
    """Sends function source code to an LLM for security audit."""
    prompt = f"""
Analyze the following Python function for security vulnerabilities (e.g., SQL injection, command injection, hardcoded secrets, unsafe deserialization).

Return ONLY a JSON object with this schema:
{{
  "vulnerable": boolean,
  "issue_type": "string",
  "severity": "Low|Medium|High|Critical",
  "explanation": "string",
  "remediation": "string"
}}

Function code:
```python
{function_code}
```
"""
    response = openai.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": prompt}],
        response_format={"type": "json_object"}
    )
    return json.loads(response.choices[0].message.content)

def audit_file(file_path):
    """Audits all functions within a target Python file."""
    functions = extract_functions(file_path)
    results = []
    for fn in functions:
        analysis = analyze_function(fn)
        if analysis.get("vulnerable"):
            results.append(analysis)
    return results

Hybrid Workflows: Combining Deterministic Tools with AI

Deploying standalone LLMs for code analysis can lead to high API costs and hallucinated findings. A hybrid approach yields optimal results:

  • Pre-filtering with Deterministic SAST: Run static analyzers like bandit or semgrep first to identify suspicious code regions.
  • AI Agent Triage: Pass flagged findings to the AI agent to evaluate semantic context, filter false positives, and draft precise patches.
  • CI/CD Integration: Execute the hybrid pipeline on pull requests to enforce security gates automatically.

Key Operational Considerations

When implementing AI agents for code security, maintain these boundaries:

  • Context Windows: Large repositories cannot be passed whole; modular AST chunking or graph-based retrieval is mandatory.
  • Data Governance: Ensure source code transmission complies with enterprise privacy policies and API data-retention terms.
  • Human Oversight: Treat agent outputs as security recommendations requiring validation by an engineer prior to merging fixes.

Need this done? We handle this hands-on at GuardLabs — get in touch for a quote.

Published 2026-07-27 2 min read All articles
Need help with this?

I take on freelance fixes and builds in this area.