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

# generateCode (Deprecated)

> Generates code using the configured AI agent (Codex or Claude) with optional streaming callbacks and conversation history.

<Warning>
  **⚠️ DEPRECATED**: The `generateCode` method is deprecated and will be removed in a future version. Please migrate to [`executeCommand`](/api-reference/execute-command) for better flexibility and control.

  [See migration guide below](#migration-to-executecommand) for how to update your code.
</Warning>

## Method signature

```typescript theme={"dark"}
async generateCode({
  prompt,
  mode,
  branch,
  history,
  callbacks,
}: {
  prompt: string;
  mode: "ask" | "code";
  branch?: string;
  history?: Conversation[];
  callbacks?: VibeKitStreamCallbacks;
}): Promise<AgentResponse>
```

## Parameters

| Parameter   | Type                     | Required | Default | Description                                                         |
| ----------- | ------------------------ | -------- | ------- | ------------------------------------------------------------------- |
| `prompt`    | `string`                 | Yes      | -       | The text prompt describing what code to generate or question to ask |
| `mode`      | `"ask" \| "code"`        | Yes      | -       | Interactive Q\&A mode (`"ask"`) or code generation mode (`"code"`)  |
| `branch`    | `string`                 | No       | -       | Branch identifier for version control or environment context        |
| `history`   | `Conversation[]`         | No       | -       | Previous conversation history to provide context for the generation |
| `callbacks` | `VibeKitStreamCallbacks` | No       | -       | Streaming callbacks for real-time updates                           |

### VibeKitStreamCallbacks Interface

| Property   | Type                        | Required | Description                   |
| ---------- | --------------------------- | -------- | ----------------------------- |
| `onUpdate` | `(message: string) => void` | No       | Called with streaming updates |
| `onError`  | `(error: string) => void`   | No       | Called when errors occur      |

## Return value

| Type                     | Description                                                                                         |
| ------------------------ | --------------------------------------------------------------------------------------------------- |
| `Promise<AgentResponse>` | Promise that resolves to either a CodexResponse or ClaudeResponse depending on the configured agent |

### CodexResponse (for Codex Agent)

| Property    | Type     | Description                                   |
| ----------- | -------- | --------------------------------------------- |
| `sandboxId` | `string` | Unique identifier for the sandbox environment |
| `stdout`    | `string` | Standard output from code execution           |
| `stderr`    | `string` | Standard error from code execution            |
| `exitCode`  | `number` | Exit code from code execution                 |

### ClaudeResponse (for Claude Agent)

| Property | Type     | Description             |
| -------- | -------- | ----------------------- |
| `code`   | `string` | Generated code response |

## Agent-specific behavior

### Codex Agent

* **Streaming Support:** Full streaming support with real-time updates
* **Sandbox Environment:** Executes code in isolated E2B sandbox
* **Mode Support:** Both "ask" and "code" modes fully supported

### Claude Agent

* **Streaming Support:** Limited - provides start/end notifications only
* **Execution:** Direct API calls without sandbox environment
* **Mode Support:** Both modes supported with fallback behavior

## Examples

### Basic Code Generation

```typescript theme={"dark"}
const vibeKit = new VibeKit(config);

const response = await vibeKit.generateCode({
  prompt: "Create a React component for a todo list",
  mode: "code"
});

console.log(response);
```

### With Streaming Callbacks

```typescript theme={"dark"}
const response = await vibeKit.generateCode({
  prompt: "Explain how React hooks work",
  mode: "ask",
  callbacks: {
    onUpdate: (message) => {
      console.log("Update:", message);
    },
    onError: (error) => {
      console.error("Error:", error);
    }
  }
});
```

### With Conversation History and Branch

```typescript theme={"dark"}
const history = [
  {
    role: "user",
    content: "What is React?"
  },
  {
    role: "assistant", 
    content: "React is a JavaScript library..."
  }
];

const response = await vibeKit.generateCode({
  prompt: "Now show me a React component example",
  mode: "code",
  branch: "feature-react-components",
  history
});
```

## Error handling

The method throws errors in the following cases:

* **Agent not initialized:** When the configured agent type doesn't match the initialized agent
* **Agent-specific errors:**
  * Codex: Sandbox creation/execution failures, API errors
  * Claude: API authentication issues, rate limits
* **Configuration errors:** Missing required API keys or invalid setup

```typescript theme={"dark"}
try {
  const response = await vibeKit.generateCode({
    prompt,
    mode: "code"
  });
} catch (error) {
  if (error.message.includes('not initialized')) {
    // Handle initialization error
  } else {
    // Handle generation error
  }
}
```

## Migration to executeCommand

The `generateCode` method has been deprecated in favor of the more flexible `executeCommand` method. Here's how to migrate your code:

### Basic Migration

**Before (generateCode):**

```typescript theme={"dark"}
const response = await vibeKit.generateCode({
  prompt: "Create a React component for a todo list",
  mode: "code"
});
```

**After (executeCommand):**

```typescript theme={"dark"}
const claudeCommand = `echo "Create a React component for a todo list" | claude -p --output-format stream-json --verbose --allowedTools "Edit,Write,MultiEdit,Read,Bash" --model claude-sonnet-4-20250514`;
const response = await vibeKit.executeCommand(claudeCommand);
```

### With Branch Support

**Before (generateCode):**

```typescript theme={"dark"}
const response = await vibeKit.generateCode({
  prompt: "Create a React component",
  mode: "code",
  branch: "feature-react-components"
});
```

**After (executeCommand):**

```typescript theme={"dark"}
const claudeCommand = `echo "Create a React component" | claude -p --output-format stream-json --verbose --allowedTools "Edit,Write,MultiEdit,Read,Bash" --model claude-sonnet-4-20250514`;
const response = await vibeKit.executeCommand(claudeCommand, {
  branch: "feature-react-components"
});
```

### Event Handling Migration

**Before (generateCode with callbacks):**

```typescript theme={"dark"}
const response = await vibeKit.generateCode({
  prompt: "Explain React hooks",
  mode: "ask",
  callbacks: {
    onUpdate: (message) => console.log("Update:", message),
    onError: (error) => console.error("Error:", error)
  }
});
```

**After (executeCommand with events):**

```typescript theme={"dark"}
vibeKit.on('stdout', (message) => console.log("Update:", message));
vibeKit.on('stderr', (error) => console.error("Error:", error));

const claudeCommand = `echo "Explain React hooks" | claude -p --disallowedTools "Edit" "Replace" "Write" --output-format stream-json --verbose --allowedTools "Edit,Write,MultiEdit,Read,Bash" --model claude-sonnet-4-20250514`;
const response = await vibeKit.executeCommand(claudeCommand);
```

### Agent-Specific Commands

For different agents, use these command patterns:

**Claude:**

```typescript theme={"dark"}
const claudeCommand = `echo "${prompt}" | claude -p --output-format stream-json --verbose --allowedTools "Edit,Write,MultiEdit,Read,Bash" --model claude-sonnet-4-20250514`;
```

**Codex:**

```typescript theme={"dark"}
const codexCommand = `codex exec --full-auto --skip-git-repo-check "${prompt}"`;
```

**Gemini:**

```typescript theme={"dark"}
const geminiCommand = `echo "${prompt}" | gemini --model gemini-2.5-pro --yolo`;
```

**OpenCode:**

```typescript theme={"dark"}
const opencodeCommand = `echo "${prompt}" | opencode run`;
```

**Grok:**

```typescript theme={"dark"}
const grokCommand = `echo "${prompt}" | grok --prompt "Help with the following request by providing code or guidance."`;
```

## Benefits of executeCommand

* **More Control:** Direct access to agent CLI commands
* **Branch Support:** Automatic git branch switching
* **Better Events:** Use standard `stdout`/`stderr` events instead of custom callbacks
* **Flexibility:** Execute any shell command in the sandbox environment
* **Consistency:** Single method for all command execution needs

## Notes

* **Required Mode:** The `mode` parameter is now required and must be specified
* **Object Parameters:** All parameters are now passed as a destructured object for better API consistency
* **Branch Support:** The optional `branch` parameter allows for version control or environment context
* **Streaming Differences:** Codex provides real-time streaming, while Claude only provides start/end notifications
* **Environment Support:** Daytona environment is not yet supported and will throw an error
* **Conversation Context:** History is preserved across calls to maintain conversation context
