# Snowflake Cortex Client

Interact with Snowflake Cortex AI/ML inference endpoints for text generation, embeddings, and other AI capabilities.

## Methods

| Method                                   | Description                                                  |
| ---------------------------------------- | ------------------------------------------------------------ |
| `apiRequest(options, schema, metadata?)` | Make any Snowflake Cortex API request with schema validation |

## Usage

### Text Completion

```typescript
import { api, z, snowflakeCortex } from "@superblocksteam/sdk-api";

// Integration ID from the integrations panel
const CORTEX = "a1b2c3d4-5678-90ab-cdef-111111111111";

const CompletionResponseSchema = z
  .object({
    choices: z
      .array(
        z
          .object({
            message: z
              .object({
                content: z.string().optional(),
              })
              .passthrough()
              .optional(),
          })
          .passthrough(),
      )
      .optional(),
  })
  .passthrough();

export default api({
  name: "CortexCompletion",
  integrations: {
    cortex: snowflakeCortex(CORTEX),
  },
  input: z.object({
    prompt: z.string(),
  }),
  output: z.object({
    response: z.string(),
  }),
  async run(ctx, { prompt }) {
    const result = await ctx.integrations.cortex.apiRequest(
      {
        method: "POST",
        path: "/api/v2/cortex/inference:complete",
        body: {
          model: "llama3.1-8b",
          messages: [{ role: "user", content: prompt }],
          stream: false,
        },
      },
      {
        body: z.object({
          model: z.string(),
          messages: z.array(
            z.object({ role: z.string(), content: z.string() }),
          ),
          stream: z.boolean(),
        }),
        response: CompletionResponseSchema,
      },
    );

    return {
      response: result.choices?.[0]?.message?.content ?? "",
    };
  },
});
```

### Text Embedding

```typescript
const EmbeddingResponseSchema = z.object({
  data: z.array(
    z.object({
      embedding: z.array(z.number()),
    }),
  ),
});

const embeddings = await ctx.integrations.cortex.apiRequest(
  {
    method: "POST",
    path: "/api/v2/cortex/inference:embed",
    body: {
      model: "e5-base-v2",
      input: ["Hello world", "How are you?"],
    },
  },
  { response: EmbeddingResponseSchema },
);
```

## Trace Metadata

All methods accept an optional `metadata` parameter as the last argument for diagnostics labeling. See the [root SDK README](../../../README.md#trace-metadata) for details.

## Common Pitfalls

### Streaming Is Not Supported

`apiRequest()` does not support streaming or Server-Sent Events. Always set
`stream: false` in Cortex request bodies (as the examples do) — a streaming
response fails schema validation. Every call returns the complete response;
if a UI needs real-time token streaming, handle it at the frontend layer,
not through the SDK.

### No Specialized Methods

The Snowflake Cortex client only provides `apiRequest()`. There are no other specialized methods:

```typescript
// WRONG - These methods do not exist
await cortex.complete({ ... });
await cortex.embed({ ... });

// CORRECT - Use apiRequest for all operations
await ctx.integrations.cortex.apiRequest(
  { method: "POST", path: "/api/v2/cortex/inference:complete", body: { ... } },
  { response: ResponseSchema }
);
```

### Response Schema is Required

You must always provide a schema object with at least a `response` schema. The `body` schema is optional but recommended for request validation:

```typescript
// WRONG - Missing schema object entirely
const result = await ctx.integrations.cortex.apiRequest({
  method: "POST",
  path: "/api/v2/cortex/inference:complete",
  body: { ... },
});

// CORRECT - Include at least a response schema
const result = await ctx.integrations.cortex.apiRequest(
  { method: "POST", path: "/api/v2/cortex/inference:complete", body: { ... } },
  { response: CompletionResponseSchema }
);
```

## Error Handling

```typescript
import { RestApiValidationError } from "@superblocksteam/sdk-api";

try {
  const result = await ctx.integrations.cortex.apiRequest(
    { method: "POST", path: "/api/v2/cortex/inference:complete", body: { ... } },
    { response: CompletionResponseSchema }
  );
} catch (error) {
  if (error instanceof RestApiValidationError) {
    console.error("Validation failed:", error.details.zodError);
    console.error("Actual response:", error.details.data);
  }
}
```

## API Reference

- [Snowflake Cortex Documentation](https://docs.snowflake.com/en/user-guide/snowflake-cortex/overview)
- [Cortex LLM Functions](https://docs.snowflake.com/en/user-guide/snowflake-cortex/llm-functions)
