> ## Documentation Index
> Fetch the complete documentation index at: https://docs.trykode.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# kode generate — LLM-Powered Structured Code Patches

> kode generate sends a task prompt to an LLM and returns structured JSON hunks. Use --apply to also verify and apply the patches to your codebase.

`kode generate` is the core generation command. It takes a task description, builds a prompt from it (optionally augmented with a context packet from `kode plan`), sends it to your configured LLM, and returns structured JSON hunks — each one a targeted replacement scoped to a specific symbol or anchor in a single file. By default the output goes to stdout so you can inspect, store, or pipe it. Add `--apply` and Kode will also verify the hunks and write passing ones to disk.

## Synopsis

```bash theme={null}
kode generate <prompt>
```

## What it does

1. Reads the model and API endpoint from `.kode/kode.json` (or environment variables).
2. Optionally loads a context packet from `--context-file` to enrich the prompt with relevant code symbols.
3. Sends the prompt to the LLM and receives a structured response.
4. Parses the response into an array of `StructuredHunk` objects.
5. Without `--apply`: prints the hunk array as indented JSON to stdout and exits.
6. With `--apply`: passes the hunks through `kode verify`'s pipeline and writes passing hunks to disk, then prints an execution summary to stdout.

## Flags

<ParamField path="--model" type="string">
  Override the LLM model for this run. Accepts `provider/model` format. When omitted, Kode reads the model from `.kode/kode.json` (`model` field), then falls back to the `KODE_LLM_MODEL` environment variable, and finally `gpt-4o`.

  ```bash theme={null}
  kode generate --model anthropic/claude-sonnet-4-6 "refactor auth"
  ```
</ParamField>

<ParamField path="--context-file" type="string">
  Path to a context packet JSON file produced by `kode plan --packet`. The packet is injected into the LLM prompt as structured context, improving patch quality and reducing hallucinated file paths.

  ```bash theme={null}
  kode generate --context-file ctx.json "add rate limiting"
  ```
</ParamField>

<ParamField path="--apply" default="false" type="boolean">
  Verify and apply hunks to disk after generation. Kode runs each hunk through the 9-gate pipeline and writes patches that pass all gates. Equivalent to running `kode run`.

  ```bash theme={null}
  kode generate --apply "add input validation"
  ```
</ParamField>

<ParamField path="--project-dir" default="cwd" type="string">
  Project root directory. Kode resolves all file paths relative to this directory. Defaults to the current working directory.
</ParamField>

## Environment variables

| Variable            | Description                                                |
| ------------------- | ---------------------------------------------------------- |
| `KODE_LLM_API_KEY`  | API key for the LLM provider (required)                    |
| `OPENAI_API_KEY`    | Fallback API key when `KODE_LLM_API_KEY` is not set        |
| `KODE_LLM_ENDPOINT` | Custom API base URL (default: `https://api.openai.com/v1`) |
| `KODE_LLM_MODEL`    | Default model (default: `gpt-4o`)                          |

## Examples

<CodeGroup>
  ```bash Generate only theme={null}
  # Generate hunks and print JSON to stdout (nothing is written to disk)
  kode generate "add rate limiting to the API handler" > patches.json
  ```

  ```bash Generate and apply theme={null}
  # Generate, verify, and write passing hunks to disk
  kode generate --apply "add input validation to CreateUser"
  ```

  ```bash With context file theme={null}
  # Equivalent to kode run --context-file
  kode generate --apply --context-file ctx.json "fix the auth bug"
  ```

  ```bash Custom model theme={null}
  # Override the model for this generation
  kode generate --model anthropic/claude-sonnet-4-6 "simplify the retry logic"
  ```
</CodeGroup>

## JSON hunk format

When run without `--apply`, `kode generate` prints a JSON array to stdout:

```json theme={null}
[
  {
    "id": "hunk-1",
    "file_path": "internal/api/handler.go",
    "action": "MODIFY",
    "target_symbol": "CreateUser",
    "anchor_text": "func CreateUser(w http.ResponseWriter, r *http.Request) {",
    "new_text": "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tif r.Body == nil {\n\t\thttp.Error(w, \"empty body\", http.StatusBadRequest)\n\t\treturn\n\t}",
    "explanation": "Guard against nil request body"
  },
  {
    "id": "hunk-2",
    "file_path": "internal/api/handler_test.go",
    "action": "INSERT",
    "anchor_text": "",
    "new_text": "func TestCreateUser_NilBody(t *testing.T) {\n\t// ...\n}",
    "explanation": "Add test for nil body case"
  }
]
```

Save this output and verify it independently by wrapping the array in a `hunks` envelope:

```bash theme={null}
kode generate "add null check" > hunks.json
# Wrap in the verify input envelope
echo "{\"hunks\": $(cat hunks.json), \"original_files\": {}}" > patches.json
kode verify --input patches.json
```

## Relationship to other commands

`kode generate --apply` and `kode run` are identical. Use `kode generate` (without `--apply`) when you want to inspect or version-control the raw hunks before applying them.

| Command                 | Generates | Verifies | Applies | Runs tests |
| ----------------------- | --------- | -------- | ------- | ---------- |
| `kode generate`         | ✓         | —        | —       | —          |
| `kode generate --apply` | ✓         | ✓        | ✓       | —          |
| `kode run`              | ✓         | ✓        | ✓       | —          |
| `kode loop`             | ✓         | ✓        | ✓       | ✓          |

<Tip>
  Inspect the JSON output of `kode generate` before committing by piping it into `kode verify --input`. This gives you a dry-run view of exactly which gates each hunk passes or fails before anything touches disk.
</Tip>
