# AI-Powered Scripts

**Page:** kit/exec/ai-integration

[Download Raw Markdown](./kit/exec/ai-integration.md)

---

# AI-Powered Scripts

**Add `// @ai true` to any script and get AI superpowers.** No imports, no API key management, no SDK setup. The Vercel AI SDK helpers are injected directly into your script context — `generateText`, `streamText`, `generateObject` — ready to use with 300+ models via [Hoody AI](/foundation/hoody-ai/).

This is what happens when you combine "files are APIs" with "containers have AI access": **every script you write can be an AI-powered endpoint**.

---

## Enabling AI

Add the `@ai` magic comment to any script:

```javascript
// @mode serverless
// @ai true

const { text } = await generateText({
  model,
  prompt: 'Explain quantum computing in one sentence'
});

return { answer: text };
```

**That's it.** The script now has:
- `model` — Pre-configured AI model (from `@ai-model` or default)
- `openai` — OpenAI SDK client instance
- `ai` — Helper namespace (`ai.generate`, `ai.stream`, `ai.object`)
- `generateText()` — Generate text completion
- `streamText()` — Stream text responses
- `generateObject()` — Generate structured JSON objects

---

## AI Magic Comments

Control AI behavior with these magic comments:

| Comment | Values | Default | Description |
|---------|--------|---------|-------------|
| `@ai` | `true` \| `false` | `true` | Enable AI helpers |
| `@ai-model` | model name | `minimax/minimax-m2.5` | Which model to use |
| `@ai-temperature` | `0` - `2` | — | Creativity level (0 = deterministic, 2 = very creative). Provider default when unset |
| `@ai-max-tokens` | number | — | Maximum response length. Provider default when unset |
| `@ai-key` | string | server-configured | API key override (default from server's `--ai-key` flag) |

**The `@ai-model` value** uses [Hoody AI model identifiers](/foundation/hoody-ai/models/) in `provider/model` format:

```javascript
// @ai-model anthropic/claude-sonnet-4.5    // Anthropic Claude
// @ai-model openai/gpt-4o                  // OpenAI GPT-4o
// @ai-model google/gemini-2.5-pro          // Google Gemini
// @ai-model meta-llama/llama-3.3-70b       // Meta Llama
// @ai-model mistralai/mistral-large        // Mistral
```

---

## Injected AI Helpers

When `@ai true` is set, these are automatically available in your script:

### `openai` — OpenAI SDK Client

A pre-configured [OpenAI SDK](https://www.npmjs.com/package/openai) client instance. Connects to the Hoody AI gateway (default: `https://ai.hoody.icu/api/v1`) using a server-configured API key — no manual setup required.

```javascript
// @ai true

// Use the OpenAI SDK directly for full control
const completion = await openai.chat.completions.create({
  model: 'minimax/minimax-m2.5',
  messages: [{ role: 'user', content: 'Hello!' }]
});

return { reply: completion.choices[0].message.content };
```

### `model` — Pre-Configured AI Model

A pre-configured Vercel AI SDK model instance from the [`@ai-sdk/openai`](https://www.npmjs.com/package/@ai-sdk/openai) package. Uses the model name from `@ai-model` (default: `minimax/minimax-m2.5`). Pass this to `generateText`, `streamText`, or `generateObject`.

```javascript
// @ai true
// @ai-model anthropic/claude-sonnet-4.5

// `model` is already configured with the above model
const { text } = await generateText({ model, prompt: 'Hello!' });
```

### `ai` — Helper Namespace

A high-level helper namespace that wraps common AI operations. Provides three convenience methods built on top of the Vercel AI SDK:

- **`ai.generate(options)`** — Generate a complete text response (wraps `generateText`)
- **`ai.stream(options)`** — Stream text chunks as they are produced (wraps `streamText`)
- **`ai.object(options)`** — Generate structured JSON validated against a schema (wraps `generateObject`)

```javascript
// @ai true

const { text } = await ai.generate({ prompt: 'Hello!' });
const { textStream } = await ai.stream({ prompt: 'Write a poem' });
const { object } = await ai.object({ schema, prompt: 'Classify this' });
```

### `generateText(options)` — Text Completion

Generate a complete text response. Returns when the full response is ready.

**Options:** `{ prompt?, messages?, model?, system?, temperature?, maxTokens? }`

```javascript
// @ai true
// @ai-model anthropic/claude-sonnet-4.5

const { text } = await generateText({
  model,
  prompt: 'Write a haiku about HTTP'
});

return { haiku: text };
```

### `streamText(options)` — Streaming Responses

Stream text response chunks as they are generated. Ideal for long responses or real-time UIs.

**Options:** `{ prompt?, messages?, model?, system?, temperature?, maxTokens? }`

```javascript
// @ai true
// @ai-model anthropic/claude-sonnet-4.5
// @timeout 60000

const { textStream } = await streamText({
  model,
  prompt: req.body.question
});

// Stream back to client
res.writeHead(200, { 'Content-Type': 'text/plain' });
for await (const chunk of textStream) {
  res.write(chunk);
}
res.end();
```

### `generateObject(options)` — Structured JSON Output

Generate structured JSON that matches a provided schema. The AI response is validated against the schema automatically.

**Options:** `{ prompt?, messages?, model?, schema, system?, temperature?, maxTokens? }`

```javascript
// @ai true
// @ai-model anthropic/claude-sonnet-4.5

const { object } = await generateObject({
  model,
  schema: {
    type: 'object',
    properties: {
      sentiment: { type: 'string', enum: ['positive', 'negative', 'neutral'] },
      confidence: { type: 'number' },
      keywords: { type: 'array', items: { type: 'string' } }
    }
  },
  prompt: `Analyze the sentiment of: "${req.body.text}"`
});

return object;
// → { sentiment: 'positive', confidence: 0.92, keywords: ['great', 'love'] }
```

---

## AI Configuration Defaults

When `@ai true` is enabled, the following defaults are applied:

| Setting | Default | Override |
|---------|---------|----------|
| **AI URL** | `https://ai.hoody.icu/api/v1` | Server-launch `--ai-url` flag |
| **Model** | `minimax/minimax-m2.5` | `@ai-model` magic comment |
| **API Key** | Server-configured default (via `--ai-key` flag) | `@ai-key` magic comment |
| **Temperature** | Provider default | `@ai-temperature` magic comment |
| **Max Tokens** | Provider default | `@ai-max-tokens` magic comment |

Override any per-script default with the corresponding magic comment:

```javascript
// @ai true
// @ai-model openai/gpt-4o
// @ai-key sk-custom-key-here
// @ai-temperature 0.3
// @ai-max-tokens 2048
```

---

## Error Handling

AI calls respect the script's `@timeout` setting. If the AI provider takes longer than the configured timeout, the request will be terminated.

```javascript
// @ai true
// @timeout 30000  // AI call must complete within 30 seconds

const { text } = await generateText({
  model,
  prompt: req.body.question
});

return { answer: text };
```

There is **no automatic retry** for failed AI calls. If you need retry logic, implement it in your script:

```javascript
// @ai true
// @timeout 60000

async function withRetry(fn, retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      return await fn();
    } catch (err) {
      if (i === retries - 1) throw err;
    }
  }
}

const { text } = await withRetry(() =>
  generateText({ model, prompt: req.body.question })
);

return { answer: text };
```

---

## Validating AI Magic Comments

To validate AI-related magic comments without executing a script, use the magic comments validation endpoint:

```bash
curl -s -X POST "https://PROJECT-CONTAINER-exec-1.SERVER.containers.hoody.icu/api/v1/exec/validate/magic-comments" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "// @ai true\n// @ai-model openai/gpt-4o\n// @ai-temperature 0.5\nreturn {};"
  }'
```

You can also retrieve the full magic comments schema (including all `@ai-*` directives) with:

```bash
curl "https://PROJECT-CONTAINER-exec-1.SERVER.containers.hoody.icu/api/v1/exec/magic-comments/schema"
```

---

## Building AI-Powered APIs

### Text Summarizer

```javascript
// api/summarize.ts
// @mode serverless
// @ai true
// @ai-model anthropic/claude-sonnet-4.5
// @ai-temperature 0.3
// @cors reflective
// @timeout 30000

if (!req.body?.content) {
  res.statusCode = 400;
  return { error: 'Missing content field' };
}

const { text } = await generateText({
  model,
  prompt: `Summarize the following text in 2-3 sentences:\n\n${req.body.content}`
});

return {
  summary: text,
  originalLength: req.body.content.length,
  summaryLength: text.length
};
```

### Content Classifier

```javascript
// api/classify.ts
// @mode serverless
// @ai true
// @ai-model minimax/minimax-m2.5
// @ai-temperature 0
// @cors reflective

const { object } = await generateObject({
  model,
  schema: {
    type: 'object',
    properties: {
      category: { type: 'string', enum: ['bug', 'feature', 'question', 'docs', 'other'] },
      priority: { type: 'string', enum: ['low', 'medium', 'high', 'critical'] },
      summary: { type: 'string' }
    }
  },
  prompt: `Classify this support ticket:\n\n${req.body.ticket}`
});

return object;
```

### Streaming Chatbot

```javascript
// api/chat.ts
// @mode serverless
// @ai true
// @ai-model anthropic/claude-sonnet-4.5
// @ai-temperature 0.7
// @ai-max-tokens 2048
// @cors reflective
// @timeout 60000

const messages = req.body.messages || [];

const { textStream } = await streamText({
  model,
  messages: [
    { role: 'system', content: 'You are a helpful assistant. Be concise.' },
    ...messages
  ]
});

// Stream Server-Sent Events
res.writeHead(200, {
  'Content-Type': 'text/event-stream',
  'Cache-Control': 'no-cache',
  'Connection': 'keep-alive'
});

for await (const chunk of textStream) {
  res.write(`data: ${JSON.stringify({ text: chunk })}\n\n`);
}

res.write('data: [DONE]\n\n');
res.end();
```

---

## AI MITM Pattern

One of the most powerful patterns: use a `hoody-exec` worker script as a **MITM (Man-In-The-Middle) proxy** for AI requests. Intercept, analyze, modify, block, or enhance every AI interaction.

**The simplicity:** Deploy a MITM script once, then **just change the URL in your AI client**:

```
Without MITM: https://ai.hoody.icu/api/v1
With MITM:    https://your-project-container-exec-1.node-us.containers.hoody.icu/api/v1
```

**What you gain:**
- **Tool Call Tampering** — Redirect file writes, block dangerous commands
- **Human-in-the-Loop** — Pause AI for approval on high-stakes operations
- **Cost Optimization** — Compress prompts, cache responses, route to cheaper models
- **Context Injection** — Auto-enhance prompts with your knowledge base
- **Complete Observability** — Log every prompt, response, and decision

**See [Hoody AI Intercept & Control](/foundation/hoody-ai/mitm/) for the complete MITM guide with full examples.**


AI MITM (above) is **client-initiated** — your AI client points its `base_url` at `hoody-exec`. [Proxy Hooks](/foundation/proxy/hooks/) are **proxy-initiated** — you register JavaScript handlers in your container's permissions document, and the Hoody Proxy dispatches matching traffic (any service, not just AI) through `hoody-exec` on your behalf. Both run inside the same tenant-owned `hoody-exec` with identical privileges; pick the pattern that matches who decides to intercept.


---

## What's Next