Skip to content

feat: fixes codegen run and codegen create #107

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Jan 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 46 additions & 14 deletions docs/blog/act-via-code.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,22 @@
title: "Act via Code"
icon: "code"
iconType: "solid"
description: "The path to advanced code manipulation agents"
description: "The path to fully-automated software engineering"
---

<Frame caption="Voyager (2023) solved agentic tasks with code execution">
<img src="/images/nether-portal.png" />
<img src="/images/mine-amethyst.png" />
</Frame>


Two and a half years since the launch of the GPT-3 API, code assistants have emerged as potentially the premier use case of LLMs. The rapid adoption of AI-powered IDEs and prototype builders isn't surprising — code is structured, deterministic, and rich with patterns, making it an ideal domain for machine learning. Experienced developers working with tools like Cursor (myself included) can tell that the field of software engineering is about to go through rapid change.
Two and a half years since the launch of the GPT-3 API, code assistants have emerged as potentially the premier use case of LLMs. The rapid adoption of AI-powered IDEs and prototype builders isn't surprising — code is structured, deterministic, and rich with patterns, making it an ideal domain for machine learning. Developers actively working with tools like Cursor (myself included) have an exhiliarating yet uncertain sense that the field of software engineering is approaching an inflection point.

Yet there's a striking gap between understanding and action. Today's AI agents can analyze enterprise codebases and propose sophisticated improvements—eliminating tech debt, untangling dependencies, improving modularity. But ask them to actually implement these changes across millions of lines of code, and they hit a wall. Their ceiling isn't intelligence—it's the ability to safely and reliably execute large-scale modifications on real, enterprise codebases.
Yet there's a striking gap between understanding and action for today's code assistants. When provided proper context, frontier LLMs can analyze massive enterprise codebases and propose practical paths towards sophisticated, large-scale improvements. But implementing changes that impact more than a small set of files with modern AI assistants is fundamentally infeasible. The good news is that for focused, file-level changes, we've found real success: AI-powered IDEs ([Windsurf](https://codeium.com/windsurf), [Cursor](https://www.cursor.com/)) are transforming how developers write and review code, while chat-based assistants are revolutionizing how we bootstrap and prototype new applications (via tools like [v0](https://v0.dev/), [lovable.dev](https://lovable.dev/), and [bolt.new](https://bolt.new/)).

The bottleneck isn't intelligence — it's tooling. By giving AI models the ability to write and execute code that modifies code, we're about to unlock an entire class of tasks that agents already understand but can't yet perform. Code execution environments represent the most expressive tool we could offer an agent—enabling composition, abstraction, and systematic manipulation of complex systems. When paired with ever-improving language models, this will unlock another step function improvement in AI capabilities.
However, there's a whole class of critical engineering tasks that remain out of reach - tasks that are fundamentally programmatic and deal with codebase structure at scale. A significant amount of effort on modern engineering teams is directed towards eliminating tech debt, managing large-scale migrations, analyzing dependency graphs, enforcing type coverage across the codebase, and similar tasks that require a global view of a codebase. Today's AI assistants can fully understand these challenges and even propose solutions, but they lack the mechanisms to actually implement them. The intelligence is there, but it's trapped in your IDE's text completion window.


The bottleneck isn't intelligence — it's tooling. The solution requires letting AI systems programmatically interact with codebases and software systems through code execution environments. Code execution environments represent the most expressive tool we could offer an agent—enabling composition, abstraction, and systematic manipulation of complex systems. By combining code execution environments with custom APIs that correspond to powerful large-scale operations, we can unlock a new set of tasks in which agents can be significant contributors. When paired with ever-improving foundation models, this will lead to a step function improvement for code assistants, enabling their application in an entirely new set of valuable tasks.

## Beating Minecraft with Code Execution

Expand Down Expand Up @@ -44,7 +47,7 @@ async function chopSpruceLogs(bot) {
}
```

This approach transformed the agent's capabilities. Rather than being constrained to atomic actions like `equipItem(...)`, it could create higher-level operations like [`craftShieldWithFurnace()`](https://github.com/MineDojo/Voyager/blob/main/skill_library/trial2/skill/code/craftShieldWithFurnace.js) through composing JS APIs. Furthermore, Wang et al. implemented a memory mechanism, in which successful "action programs" could later be recalled, copied, and built upon, effectively enabling the agent to accumulate experience.
This approach transformed the agent's capabilities. Rather than being constrained to atomic actions like `equipItem(...)` (this would be typical of "traditional" agent algorithms, such as ReAct), it could create higher-level operations like [craftShieldWithFurnace()](https://github.com/MineDojo/Voyager/blob/main/skill_library/trial2/skill/code/craftShieldWithFurnace.js) through composing the atomic APIs. Furthermore, Wang et al. implemented a memory mechanism, in which these successful "action programs" could later be recalled, copied, and built upon, effectively enabling the agent to accumulate experience.

<Frame>
<img src="/images/voyager-retrieval.png" />
Expand All @@ -56,9 +59,26 @@ As the Voyager authors noted:

## Code is an Ideal Action Space

The implications of code as an action space extend far beyond gaming. This architectural insight — letting AI act through code rather than atomic commands — will lead to a step change in the capabilities of AI systems. Nowhere is this more apparent than in software engineering, where agents already understand complex transformations but lack the tools to execute them effectively.
What these authors demonstrated is a fundamental insight that extends far beyond gaming. Letting AI act through code rather than atomic commands will lead to a step change in the capabilities of AI systems. Nowhere is this more apparent than in software engineering, where agents already understand complex transformations but lack the tools to execute them effectively.

Today's productionized code assistants operate though an interface where they can directly read/write to text files and perform other bespoke activities, like searching through file embeddings or running terminal commands.

In the act via code paradigm, all of these actions are expressed through writing and executing code, like the below:

```python
# Implement `grep` via for loops and if statements
for function in codebase.functions:
if 'Page' in function.name:

# Implement systematic actions, like moving things around, through an API
function.move_to_file('/pages/' + function.name + '.tsx')
```

Provided a sufficiently comprehensive set of APIs, this paradigm has many clear advantages:

When an agent writes code, it gains several critical advantages over traditional atomic tools:
- **API-Driven Extensibility**: Any operation that can be expressed through an API becomes accessible to the agent. This means the scope of tasks an agent can handle grows with our ability to create clean APIs for complex operations.

- **Programmatic Efficiency**: Many agent tasks involve systematic operations across large codebases. Expressing these as programs rather than individual commands dramatically reduces computational overhead and allows for batch operations.

- **Composability**: Agents can build their own tools by combining simpler operations. This aligns perfectly with LLMs' demonstrated ability to compose and interpolate between examples to create novel solutions.

Expand All @@ -68,17 +88,29 @@ When an agent writes code, it gains several critical advantages over traditional

- **Natural Collaboration**: Programs are a shared language between humans and agents. Code explicitly encodes reasoning in a reviewable format, making actions transparent, debuggable, and easily re-runnable.

## For Software Engineering
## Code Manipulation Programs

Software engineering tasks are inherently programmatic and graph-based — dependency analysis, refactors, control flow analysis, etc. Yet today's AI agents interface with code primarily through string manipulation, missing the rich structure that developers and their tools rely on. By giving agents APIs that operate on the codebase's underlying graph structure rather than raw text, we can unlock a new tier of capabilities. Imagine agents that can rapidly traverse dependency trees, analyze control flow, and perform complex refactors while maintaining perfect awareness of the codebase's structure.
For software engineering, we believe the path forward is clear: agents need a framework that matches how developers think about and manipulate code. While decades of static analysis work gives us a strong foundation, traditional code modification frameworks weren't designed with AI-human collaboration in mind - they expose low-level APIs that don't match how developers (or AI systems) think about code changes.

Consider how a developer thinks about refactoring: it's rarely about direct text manipulation. Instead, we think in terms of high-level operations: "move this function," "rename this variable everywhere," "split this module." These operations can be encoded into a powerful Python API:
We're building a framework with high-level APIs that correspond to how engineers actually think about code modifications. The APIs are clean and intuitive, following clear [principles](/docs/principles) that eliminate sharp edges and handle edge cases automatically. Most importantly, the framework encodes rich structural understanding of code. Consider this example:

```python
# simple access to high-level code constructs
# Access to high-level semantic operations
for component in codebase.jsx_components:
# access detailed code structure and relations
# Rich structural analysis built-in
if len(component.usages) == 0:
# powerful edit APIs that handle edge cases
# Systematic operations across the codebase
component.rename(component.name + 'Page')
```

This isn't just string manipulation - the framework understands React component relationships, tracks usage patterns, and can perform complex refactors while maintaining correctness. By keeping the codebase representation in memory, we can provide lightning-fast operations for both analysis and systematic edits.

The documentation for such a framework isn't just API reference - it's education for advanced intelligence about how to successfully manipulate code at scale. We're building for a future where AI systems are significant contributors to codebases, and they need to understand not just the "how" but the "why" behind code manipulation patterns.

Crucially, we believe these APIs will extend beyond the codebase itself into the broader software engineering ecosystem. When agents can seamlessly interact with tools like Datadog, AWS, and other development platforms through the same clean interfaces, we'll take a major step toward [autonomous software engineering](/about#our-mission). The highest leverage move isn't just giving agents the ability to modify code - it's giving them programmatic access to the entire software development lifecycle.

## Codegen is now OSS

We're excited to release [Codegen](https://github.com/codegen-sh/codegen-sdk) as open source [Apache 2.0](https://github.com/codegen-sh/codegen-sdk?tab=Apache-2.0-1-ov-file) and build out this vision with the broader developer community. [Get started with Codegen](/introduction/getting-started) today or please join us in our [Slack community](https://community.codegen.com) if you have feedback or questions about a use case!

Jay Hack, Founder
4 changes: 2 additions & 2 deletions docs/blog/posts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ iconType: "solid"
Why code as an action space will lead to a step function improvement in agent capabilities.

<Card
img="/images/nether-portal.png"
title="Act via Code"
img="/images/mine-amethyst.png"
title="Voyager (2023) solved Minecraft with code execution"
href="/blog/act-via-code"
/>

Expand Down
114 changes: 114 additions & 0 deletions docs/building-with-codegen/dot-codegen.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
---
title: "The .codegen Directory"
sidebarTitle: ".codegen Directory"
icon: "folder"
iconType: "solid"
---

The `.codegen` directory contains your project's Codegen configuration, codemods, and supporting files. It's automatically created when you run `codegen init`.

## Directory Structure

```bash
.codegen/
├── config.toml # Project configuration
├── codemods/ # Your codemod implementations
├── jupyter/ # Jupyter notebooks for exploration
├── docs/ # API documentation
├── examples/ # Example code
└── prompts/ # AI system prompts
```

## Initialization

The directory is created and managed using the `codegen init` command:

```bash
codegen init [--fetch-docs] [--repo-name NAME] [--organization-name ORG]
```

<Note>
The `--fetch-docs` flag downloads API documentation and examples specific to your project's programming language.
</Note>

### Configuration

The `config.toml` file stores your project settings:

```toml
organization_name = "your-org"
repo_name = "your-repo"
programming_language = "python" # or other supported language
```

This configuration is used by Codegen to provide language-specific features and proper repository context.

## Git Integration

Codegen automatically adds appropriate entries to your `.gitignore`:

```gitignore
# Codegen
.codegen/prompts/
.codegen/docs/
.codegen/examples/
```

<Info>
While prompts, docs, and examples are ignored, your codemods in `.codegen/codemods/` are tracked in Git.
</Info>

## Working with Codemods

The `codemods/` directory is where your transformation functions live. You can create new codemods using:

```bash
codegen create my-codemod [--description "what it does"]
```

This will:
1. Create a new file in `.codegen/codemods/`
2. Generate a system prompt in `.codegen/prompts/` (if using `--description`)
3. Set up the necessary imports and decorators

<Tip>
Use `codegen list` to see all codemods in your project.
</Tip>

## Jupyter Integration

The `jupyter/` directory contains notebooks for interactive development:

```python
from codegen import Codebase

# Initialize codebase
codebase = Codebase('../../')

# Print stats
print(f"📚 Total Files: {len(codebase.files)}")
print(f"⚡ Total Functions: {len(codebase.functions)}")
```

<Note>
A default notebook is created during initialization to help you explore your codebase.
</Note>

## Next Steps

After initializing your `.codegen` directory:

1. Create your first codemod:
```bash
codegen create my-codemod -d "describe what you want to do"
```

2. Run it:
```bash
codegen run my-codemod --apply-local
```

3. Deploy it for team use:
```bash
codegen deploy my-codemod
```
30 changes: 15 additions & 15 deletions docs/building-with-codegen/files-and-directories.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@ iconType: "solid"

Codegen provides two primary abstractions for working with your codebase's file structure:

- [`File`](../api-reference/core/File)
- [`Directory`](../api-reference/core/Directory)
- [File](/api-reference/core/File)
- [Directory](/api-reference/core/Directory)

Both of these expose a rich API for accessing and manipulating their contents.

This guide explains how to effectively use these classes to manage your codebase.

## Accessing Files and Directories

You typically access files from the [`Codebase`](/api-reference/core/Codebase) object with two APIs:
You typically access files from the [codebase](/api-reference/core/Codebase) object with two APIs:

- [`Codebase.get_file(...)`](../api-reference/core/Codebase#get_file) - Get a file by its path
- [`Codebase.files`](../api-reference/core/Codebase#files) - Enables iteration over all files in the codebase
- [codebase.get_file(...)](/api-reference/core/Codebase#get_file) - Get a file by its path
- [codebase.files](/api-reference/core/Codebase#files) - Enables iteration over all files in the codebase

```python
# Get a file from the codebase
Expand All @@ -33,7 +33,7 @@ for file in codebase.files:
exists = codebase.has_file("path/to/file.py")
```

These APIs are similar for [`Directory`](../api-reference/core/Directory), which provides similar methods for accessing files and subdirectories.
These APIs are similar for [Directory](/api-reference/core/Directory), which provides similar methods for accessing files and subdirectories.

```python
# Get a directory
Expand Down Expand Up @@ -74,7 +74,7 @@ docs = codebase.files(extensions=[".md", ".mdx"])
config_files = codebase.files(extensions=[".json", ".yaml", ".toml"])
```

These APIs are similar for [`Directory`](../api-reference/core/Directory), which provides similar methods for accessing files and subdirectories.
These APIs are similar for [Directory](/api-reference/core/Directory), which provides similar methods for accessing files and subdirectories.

## Raw Content and Metadata

Expand Down Expand Up @@ -102,10 +102,10 @@ Files and Directories provide several APIs for accessing and iterating over thei

See, for example:

- `.functions` ([`File`](../api-reference/core/File#functions) / [`Directory`](../api-reference/core/Directory#functions)) - All [`Functions`](../api-reference/core/Function) in the file/directory
- `.classes` ([`File`](../api-reference/core/File#classes) / [`Directory`](../api-reference/core/Directory#classes)) - All [`Classes`](../api-reference/core/Class) in the file/directory
- `.imports` ([`File`](../api-reference/core/File#imports) / [`Directory`](../api-reference/core/Directory#imports)) - All [`Imports`](../api-reference/core/Import) in the file/directory
- [`File.code_block`](../api-reference/core/File#code-block) - The top-level [`CodeBlock`](../api-reference/core/CodeBlock) containing the file's statements
- `.functions` ([File](/api-reference/core/File#functions) / [Directory](/api-reference/core/Directory#functions)) - All [Functions](../api-reference/core/Function) in the file/directory
- `.classes` ([File](/api-reference/core/File#classes) / [Directory](/api-reference/core/Directory#classes)) - All [Classes](../api-reference/core/Class) in the file/directory
- `.imports` ([File](/api-reference/core/File#imports) / [Directory](/api-reference/core/Directory#imports)) - All [Imports](../api-reference/core/Import) in the file/directory


```python
# Get all functions in a file
Expand All @@ -120,10 +120,10 @@ for cls in file.classes:
print(f"Methods: {[m.name for m in cls.methods]}")
print(f"Attributes: {[a.name for a in cls.attributes]}")

# Get imports
for import_stmt in file.import_statements:
print(f"Import from: {import_stmt.module}")
print(f"Imported symbols: {[s.name for s in import_stmt.symbols]}")
# Get imports (can also do `file.import_statements`)
for imp in file.imports:
print(f"Import from: {imp.module}")
print(f"Imported symbol: {[s.name for s in imp.imported_symbol]}")

# Get specific symbols
main_function = file.get_function("main")
Expand Down
2 changes: 1 addition & 1 deletion docs/building-with-codegen/parsing-codebases.mdx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: "Parsing Codebases"
sidebarTitle: "Initialization"
sidebarTitle: "Parsing Codebases"
icon: "power-off"
iconType: "solid"
---
Expand Down
Loading
Loading