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

# Code Generation

> Generate reproducible Kumo SDK Python code from existing Kumo entities

The `kumoai.codegen` module can generate Python SDK code for supported connectors, tables, graphs, and predictive queries. Use it to turn a supported saved entity into a reproducible script that can be reviewed, versioned, and rerun.

<Warning>
  Code generation is intended for SDK objects that the codegen module supports in your installed SDK version. If a loaded object has no registered codegen handler, `generate_code()` raises `UnsupportedEntityError`. Invalid or unsupported ID/entity-class inputs can raise `ValueError`.
</Warning>

## Generate code by ID

Initialize the SDK, then call `generate_code()` with an entity ID. When the entity class is ambiguous, include `entity_class`.

```python theme={null}
import os
import kumoai as kumo
from kumoai.codegen import generate_code

kumo.init(
    url=os.environ["KUMO_API_ENDPOINT"],
    api_key=os.environ["KUMO_API_KEY"],
)

code = generate_code({
    "id": "myconnector",
    "entity_class": "S3Connector",
})

print(code)
```

The generated script includes Kumo initialization boilerplate and the imports required to recreate the entity and its dependencies.

## Write generated code to a file

Pass `output_path` to write the generated script directly.

```python theme={null}
generate_code(
    {"id": "my-predictive-query", "entity_class": "PredictiveQuery"},
    output_path="recreate_predictive_query.py",
)
```

Review the generated file before running it in production, especially if it will create or update objects in a shared workspace.

## Generate code from an in-memory object

For advanced workflows, pass an SDK object directly with the `object` input mode.

```python theme={null}
code = generate_code({"object": graph})
print(code)
```

This is useful in notebooks when you have modified an object interactively and want to export the equivalent Python code.

## Command-line usage

The SDK includes a CLI module. Invoke it directly with `python -m`:

```bash theme={null}
python -m kumoai.codegen.cli --id myconnector --entity-class S3Connector -o connector.py
python -m kumoai.codegen.cli --id my-predictive-query --entity-class PredictiveQuery
```

If your environment exposes the optional `kumo-codegen` entry point, the equivalent command is:

```bash theme={null}
kumo-codegen --id myconnector --entity-class S3Connector --output connector.py
```

Use `--verbose` to print additional diagnostics.

## Supported input modes

| Input mode | Example                                                | Notes                                                                   |
| ---------- | ------------------------------------------------------ | ----------------------------------------------------------------------- |
| ID         | `{"id": "myconnector", "entity_class": "S3Connector"}` | Loads the entity from Kumo. Requires SDK authentication.                |
| Object     | `{"object": graph}`                                    | Generates from an in-memory SDK object. Useful in notebooks and tests.  |
| JSON       | `{"json": ...}`                                        | Reserved by the CLI interface; not implemented in current SDK versions. |

## How dependency generation works

When you generate code for an entity with dependencies, codegen emits parent objects first. For example, generating a predictive query can emit the connector, source tables, Kumo tables, and graph needed by that query.

The generator deduplicates equivalent supported connector configurations; other entities are reused only when the same object instance is encountered.

## Error handling

Catch codegen-specific exceptions when building automation around generated scripts.

```python theme={null}
from kumoai.codegen import (
    CyclicDependencyError,
    UnsupportedEntityError,
    generate_code,
)

try:
    code = generate_code({"id": entity_id, "entity_class": entity_class})
except UnsupportedEntityError as exc:
    print("This entity type is not supported by codegen:", exc)
except CyclicDependencyError as exc:
    print("The entity graph contains a cycle:", exc)
except ValueError as exc:
    print("The ID or entity class is invalid or unsupported:", exc)
```

## Best practices

* Commit generated scripts alongside the analysis or pipeline that depends on them.
* Treat generated code as a starting point; rename variables and add comments before production use.
* Prefer environment variables for `KUMO_API_ENDPOINT` and `KUMO_API_KEY` so generated scripts do not contain secrets.
* Regenerate code after substantial UI or notebook changes, then review the diff before replacing a production script.
