# AI Operations

The Prismon AI Client Method provides a simple interface for interacting with AI models through the Prismon platform. This documentation covers the `invokeAI` and `registerModel` methods for executing AI inferences and managing AI model configurations.

### Initialization

Create an AI client instance with your configuration:

```typescript
import { createPrismonClient } from '@prismon/sdk';

const client = createPrismonClient({
  apiKey: 'your-api-key-here',        // Your Prismon API key
  appId: 'your-app-id',               // Your application ID
  logger: boolean,                    // Logger implementation
});
```

### Core Methods

#### 1. `invokeAI` - Execute AI Inference

**Method Signature**

```typescript
invokeAI(params: AIInvokeParams): Promise<ApiResponse<AIInvokeResponse>>
```

**Parameters**

| Parameter                 | Type                          | Description                                                          |
| ------------------------- | ----------------------------- | -------------------------------------------------------------------- |
| `userId`                  | `string`                      | Unique identifier for the user making the request                    |
| `modelId`                 | `string`                      | ID of the model to invoke                                            |
| `inputType`               | `"Text" \| "Image" \| "Json"` | Type of input data                                                   |
| `inputData`               | `string`                      | The input data for the AI model (text, base64 image, or JSON string) |
| `mcpTransport` (optional) | `'StreamableHTTP'`            | Transport method for MCP models                                      |
| `modelName` (optional)    | `string`                      | Name override for the model                                          |

Response

```typescript
interface ApiResponse<T> {
  success: boolean;    // Whether the API call succeeded
  data: T;            // Response data
  error?: string;      // Error message if unsuccessful
}

interface AIInvokeResponse {
  succeeded: boolean;  // Whether the AI operation succeeded
  message: string;     // Status message from the AI
  output: string;      // The AI-generated output
  modelId:  string;    // Registered model id
}
```

**Usage Examples**

**Text Input Example:**

```typescript
const response = await client.ai.invokeAI({
  userId: 'user-123',
  modelId: 'text-generator-001',
  inputType: 'Text',
  inputData: 'Write a poem about blockchain technology'
});

if (response.success && response.data.succeeded) {
  console.log('AI Response:', response.data.output);
}
```

**Image Input Example:**

```typescript
// Convert image to base64
const imageBase64 = await convertImageToBase64('image.png');

const response = await client.ai.invokeAI({
  userId: 'user-123',
  modelId: 'image-classifier-001',
  inputType: 'Image',
  inputData: imageBase64
});
```

**JSON Input Example:**

```typescript
const response = await aiClient.invokeAI({
  userId: 'user-123',
  modelId: 'data-processor-001',
  inputType: 'Json',
  inputData: JSON.stringify({ /* your structured data */ })
});
```

#### 2. `registerModel` - Register a New AI Model

**Method Signature**

```typescript
registerModel(modelConfig: AIModelConfig): Promise<ApiResponse<{ message: string }>>
```

Parameters

```typescript
interface AIModelConfig {
  name: string;                     // Display name for the model
  type: 'LocalML' | 'ExternalAPI' | 'MCP';  // Model type
  filePath?: string;                // Path to model file (for LocalML)
  externalApiUrl?: string;          // API endpoint (for ExternalAPI)
  externalApiKey?: string;          // API key (for ExternalAPI)
  inputType: 'Text' | 'Image' | 'Json';  // Supported input type
  outputType: 'Text' | 'Json';      // Expected output type
  modelName?: string;               // Technical model name/identifier
}
```

Response

```typescript
interface ApiResponse<{ message: string }> {
  success: boolean;
  data: { message: string };
  error?: string;
}
```

**Usage Examples**

**Registering a Local ML Model:**

```typescript
const response = await client.ai.registerModel({
  name: 'Sentiment Analyzer',
  type: 'LocalML',
  filePath: '/models/sentiment.onnx',
  inputType: 'Text',
  outputType: 'Json'
});

if (response.success) {
  console.log('Model registered:', response.data.message);
}
```

**Registering an External API Model:**

```typescript
const response = await aiClient.registerModel({
  name: 'OpenAI GPT-3',
  type: 'ExternalAPI',
  externalApiUrl: 'https://api.openai.com/v1/completions',
  externalApiKey: 'sk-your-openai-key',
  inputType: 'Text',
  outputType: 'Text',
  modelName: 'text-davinci-003'
});
```

### Advanced Usage

#### Error Handling

```typescript
try {
  const response = await client.ai.invokeAI(/* params */);
  
  if (!response.success) {
    console.error('API Error:', response.error);
    return;
  }
  
  if (!response.data.succeeded) {
    console.error('AI Processing Error:', response.data.message);
    return;
  }
  
  // Process successful response
  console.log(response.data.output);
} catch (error) {
  console.error('Unexpected error:', error);
}
```

#### TypeScript Support

The SDK provides complete TypeScript types for all methods and responses. You can import the interfaces for type safety:

```typescript
import { AIInvokeParams, AIInvokeResponse, AIModelConfig } from 'prismon-sdk';
```

### Best Practices

1. **Validate Inputs**: Ensure input data matches the model's expected `inputType`
2. **Handle Errors Gracefully**: Check both `response.success` and `response.data.succeeded`
3. **Secure API Keys**: Never hardcode keys - use environment variables
4. **Type Safety**: Leverage TypeScript interfaces for better code quality
5. **Monitor Usage**: Track model invocations and performance
6. **Batch Requests**: For multiple inferences, consider batching at application level


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lucky-israel.gitbook.io/prismon-docs/features/interactive-blocks.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
