Pular para o conteúdo principal

Smart Tables SDK

O SmartTablesSDK fornece uma solução completa para gerenciar tabelas de dados estruturados com capacidades avançadas de consulta, filtragem, ordenação e manipulação de dados. Construa poderosos aplicativos de gerenciamento de dados com facilidade, com suporte a visualizações personalizadas, importação/exportação de dados e processamento de dados por IA.

Instalação​

npm install @odin-ai-staging/sdk

Início Rápido​

Neste exemplo, você aprenderá como usar o SmartTablesSDK para criar e gerenciar programaticamente tabelas de dados estruturados por meio da API do EKB. Você começa inicializando o SDK com suas credenciais de API (URL base, ID do projeto, chave de API e secret), em seguida segue um fluxo de trabalho direto para construir um banco de dados funcional: primeiro, você cria uma nova tabela com createTable() fornecendo um nome e descrição (neste caso, "Banco de Dados de Clientes"), depois define a estrutura da tabela adicionando colunas com addColumn(), especificando o nome, o tipo de dados (como 'text' ou 'email') e a descrição de cada coluna. Uma vez que a estrutura da tabela esteja configurada, você pode populá-la com dados usando addRow() para inserir registros como pares de chave-valor e, finalmente, consultar seus dados com queryTable(), que suporta filtragem (usando operadores como 'contains'), paginação e outros parâmetros de consulta para recuperar exatamente os dados que você precisa. Isso fornece uma solução programática completa para criar estruturas semelhantes a bancos de dados com capacidades de IA, perfeita para construir sistemas dinâmicos de gerenciamento de dados, ferramentas de CRM ou qualquer aplicativo onde você precise armazenar, organizar e consultar informações estruturadas por meio de uma API — tudo sem gerenciar infraestrutura de banco de dados tradicional.

import { SmartTablesSDK } from '@odin-ai-staging/sdk';

// Initialize the SDK
const smartTablesSDK = new SmartTablesSDK({
baseUrl: 'https://your-api-endpoint.com/',
projectId: 'your-project-id',
apiKey: 'your-api-key',
apiSecret: 'your-api-secret'
});

// Quick example: Create table and add data
async function quickExample() {
// Create a new table
const table = await smartTablesSDK.createTable(
'Customer Database',
'Manage customer information'
);

// Add columns
await smartTablesSDK.addColumn(table.id, {
name: 'name',
type: 'text',
description: 'Customer name'
});

await smartTablesSDK.addColumn(table.id, {
name: 'email',
type: 'email',
description: 'Customer email address'
});

// Add data
await smartTablesSDK.addRow(table.id, {
name: 'John Doe',
email: 'john@example.com'
});

// Query data
const results = await smartTablesSDK.queryTable(table.id, {
filters: [{ column: 'name', operator: 'contains', value: 'John' }],
pagination: { limit: 10, page: 1 }
});

console.log('Query results:', results.data);
}

Configuração​

Interface SmartTablesSDKConfig​

interface SmartTablesSDKConfig {
baseUrl: string; // API endpoint URL
projectId: string; // Your project identifier
apiKey?: string; // API key for authentication
apiSecret?: string; // API secret for authentication
accessToken?: string; // Access token for web app usage
}

O SmartTablesSDK usa a mesma configuração que outros componentes do SDK, estendendo o BaseClientConfig.

Conceitos Principais​

SmartTable​

Uma SmartTable representa uma tabela de dados estruturados com esquema, metadados e capacidades de gerenciamento de dados.

interface SmartTable {
id: string; // Unique table identifier
project_id: string; // Project this table belongs to
title: string; // Display name of the table
description: string; // Table description
schema: SmartTableColumn[]; // Column definitions
table_name: string; // Internal table name
created_at?: number; // Creation timestamp
updated_at?: number; // Last update timestamp
}

SmartTableColumn​

Define a estrutura e as propriedades das colunas da tabela.

interface SmartTableColumn {
name: string; // Column name
type: ColumnType; // Data type
description?: string; // Column description
notNull?: boolean; // Required field
unique?: boolean; // Unique constraint
defaultValue?: string | number | boolean | null; // Default value
options?: Record<string, unknown>; // Additional options
}

type ColumnType = 'text' | 'number' | 'boolean' | 'date' | 'email' | 'url' | 'json';

Filtragem e Consulta​

Sistema avançado de filtragem com múltiplos operadores e opções de ordenação.

interface TableFilter {
column: string;
operator: FilterOperator;
value: string | number | boolean | null;
}

type FilterOperator = 'eq' | 'ne' | 'gt' | 'lt' | 'gte' | 'lte' | 'contains' | 'startswith' | 'endswith';

interface TableSort {
column: string;
direction: 'asc' | 'desc';
}

interface TablePagination {
page?: number;
limit?: number;
search?: string;
}

Gerenciamento de Tabelas​

getAllTables()​

Recupere todas as tabelas no projeto.

async getAllTables(): Promise<SmartTable[]>

Exemplo:

const tables = await smartTablesSDK.getAllTables();
tables.forEach(table => {
console.log(`Table: ${table.title} (${table.id})`);
console.log(`Columns: ${table.schema.length}`);
});

getTable(tableId)​

Obtenha uma tabela específica pelo ID.

async getTable(tableId: string): Promise<SmartTable>

Exemplo:

const table = await smartTablesSDK.getTable('table_123');
console.log('Table schema:', table.schema);

createTable(title, description, metadata?)​

Crie uma nova tabela.

async createTable(
title: string,
description: string,
metadata?: Record<string, unknown>
): Promise<SmartTable>

Exemplo:

const table = await smartTablesSDK.createTable(
'Product Catalog',
'Manage product information and inventory',
{ category: 'inventory', owner: 'admin' }
);

updateTable(tableId, title, description?, metadata?)​

Atualize os metadados da tabela.

async updateTable(
tableId: string,
title: string,
description?: string,
metadata?: Record<string, unknown>
): Promise<void>

Exemplo:

await smartTablesSDK.updateTable(
'table_123',
'Updated Product Catalog',
'Enhanced product management system',
{ version: '2.0' }
);

deleteTable(tableId)​

Exclua uma tabela e todos os seus dados permanentemente.

async deleteTable(tableId: string): Promise<void>

Exemplo:

await smartTablesSDK.deleteTable('table_123');

Operações de Coluna​

addColumn(tableId, column)​

Adicione uma nova coluna à tabela.

async addColumn(tableId: string, column: SmartTableColumn): Promise<void>

Exemplo:

// Add a text column
await smartTablesSDK.addColumn('table_123', {
name: 'product_name',
type: 'text',
description: 'Name of the product',
notNull: true
});

// Add a number column with default value
await smartTablesSDK.addColumn('table_123', {
name: 'price',
type: 'number',
description: 'Product price in USD',
defaultValue: 0,
notNull: true
});

// Add an email column with validation
await smartTablesSDK.addColumn('table_123', {
name: 'supplier_email',
type: 'email',
description: 'Supplier contact email',
unique: true
});

updateColumn(tableId, columnName, updates)​

Atualize as propriedades de uma coluna.

async updateColumn(
tableId: string,
columnName: string,
updates: Partial<SmartTableColumn>
): Promise<void>

Exemplo:

await smartTablesSDK.updateColumn('table_123', 'product_name', {
description: 'Updated product name field',
notNull: true,
unique: true
});

deleteColumn(tableId, columnName)​

Remova uma coluna da tabela.

async deleteColumn(tableId: string, columnName: string): Promise<void>

Exemplo:

await smartTablesSDK.deleteColumn('table_123', 'obsolete_column');

Operações de Dados​

addRow(tableId, data)​

Adicione uma nova linha à tabela.

async addRow(tableId: string, data: Record<string, any>): Promise<any>

Exemplo:

const newRow = await smartTablesSDK.addRow('table_123', {
product_name: 'Wireless Headphones',
price: 99.99,
supplier_email: 'supplier@example.com',
in_stock: true
});

console.log('New row ID:', newRow.id);

updateRow(tableId, rowId, columnName, newValue)​

Atualize uma célula específica na tabela.

async updateRow(
tableId: string,
rowId: string,
columnName: string,
newValue: any
): Promise<void>

Exemplo:

// Update product price
await smartTablesSDK.updateRow(
'table_123',
'row_456',
'price',
89.99
);

// Update stock status
await smartTablesSDK.updateRow(
'table_123',
'row_456',
'in_stock',
false
);

deleteRow(tableId, rowId)​

Exclua uma linha da tabela.

async deleteRow(tableId: string, rowId: string): Promise<void>

Exemplo:

await smartTablesSDK.deleteRow('table_123', 'row_456');

Consulta e Filtragem​

queryTable(tableId, options?)​

Consulte dados da tabela com filtragem, ordenação e paginação avançadas.

async queryTable(
tableId: string,
options?: TableQueryOptions
): Promise<TableQueryResponse>

TableQueryOptions:

interface TableQueryOptions {
filters?: TableFilter[]; // Filter conditions
sort?: TableSort[]; // Sort configurations
pagination?: TablePagination; // Pagination settings
}

Exemplos:

Consulta Básica​

const results = await smartTablesSDK.queryTable('table_123');
console.log('All data:', results.data);

Consulta com Filtros​

const results = await smartTablesSDK.queryTable('table_123', {
filters: [
{ column: 'price', operator: 'gte', value: 50 },
{ column: 'in_stock', operator: 'eq', value: true },
{ column: 'product_name', operator: 'contains', value: 'headphones' }
]
});

Consulta com Ordenação e Paginação​

const results = await smartTablesSDK.queryTable('table_123', {
sort: [
{ column: 'price', direction: 'desc' },
{ column: 'product_name', direction: 'asc' }
],
pagination: {
page: 2,
limit: 20,
search: 'wireless'
}
});

console.log(`Found ${results.total} items`);
console.log(`Page ${results.page} of ${Math.ceil(results.total / results.limit)}`);

Importação/Exportação de Dados​

importTable(title, description, columnMappings, file)​

Importe dados de arquivos CSV ou Excel.

async importTable(
title: string,
description: string,
columnMappings: ColumnMapping[],
file: File
): Promise<ImportResult>

Interface ColumnMapping:

interface ColumnMapping {
sourceColumn: string; // Column name in source file
targetColumn: string; // Column name in target table
dataType: string; // Target data type
}

Exemplo:

const fileInput = document.getElementById('csvFile') as HTMLInputElement;
const file = fileInput.files[0];

const columnMappings: ColumnMapping[] = [
{ sourceColumn: 'Name', targetColumn: 'product_name', dataType: 'text' },
{ sourceColumn: 'Price', targetColumn: 'price', dataType: 'number' },
{ sourceColumn: 'Email', targetColumn: 'supplier_email', dataType: 'email' }
];

const result = await smartTablesSDK.importTable(
'Imported Products',
'Products imported from CSV',
columnMappings,
file
);

console.log(`Imported ${result.rows_imported} rows`);
console.log(`Table ID: ${result.data_type_id}`);

Recursos com IA​

computeRowColumns(dataTypeId, rowId, columnNames?)​

Acione o cálculo por IA para colunas específicas de uma linha.

async computeRowColumns(
dataTypeId: string,
rowId: string,
columnNames?: string[]
): Promise<void>

Exemplo:

// Compute specific columns for a row
await smartTablesSDK.computeRowColumns(
'table_123',
'row_456',
['ai_summary', 'sentiment_score']
);

computeAllRows(dataTypeId)​

Acione o cálculo por IA para todas as linhas da tabela.

async computeAllRows(dataTypeId: string): Promise<{
message: string;
total_rows_processed: number;
total_columns_updated: number;
updated_columns: string[];
failed_rows: number[];
stopped_due_to_failures: boolean;
retry_attempts: Record<number, number>;
computation_id?: string;
history_table?: string;
}>

Exemplo:

const result = await smartTablesSDK.computeAllRows('table_123');
console.log(`Processed ${result.total_rows_processed} rows`);
console.log(`Updated ${result.total_columns_updated} columns`);
console.log(`Updated columns: ${result.updated_columns.join(', ')}`);

if (result.failed_rows.length > 0) {
console.log(`Failed rows: ${result.failed_rows.join(', ')}`);
}

Tratamento de Erros​

O SmartTablesSDK usa o mesmo tratamento de erros que outros componentes do SDK:

try {
const table = await smartTablesSDK.createTable('My Table', 'Description');
} catch (error) {
if (error instanceof APIError) {
console.error(`API Error ${error.status}: ${error.message}`);
if (error.detail) {
console.error('Details:', error.detail);
}
} else {
console.error('Unexpected error:', error);
}
}

Exemplos​

Aplicativo Completo de Gerenciamento de Dados​

Neste exemplo, você aprenderá como construir um sistema completo de gerenciamento de produtos usando o SmartTablesSDK com uma classe bem estruturada que lida com informações de estoque e produtos. A classe ProductManager inicializa o SDK com variáveis de ambiente e fornece um fluxo de trabalho completo para gerenciar um catálogo de produtos: o método initializeTable() cria uma nova tabela "Product Catalog" e configura um esquema abrangente com oito colunas incluindo vários tipos de dados (text, number, boolean, email, url e date), juntamente com restrições como notNull para campos obrigatórios e defaultValue para disponibilidade de estoque. Uma vez inicializada, você pode adicionar produtos usando addProduct(), que insere novas linhas e registra automaticamente a data atual em cada entrada, e realizar buscas sofisticadas com searchProducts(), que permite filtrar produtos por categoria, faixa de preço (usando operadores 'gte' e 'lte' para comparações de maior-ou-igual e menor-ou-igual), aplicar busca por texto em toda a tabela e ordenar resultados alfabeticamente por nome do produto. Isso fornece um padrão pronto para produção para construir sistemas de estoque de e-commerce, bancos de dados de produtos ou qualquer aplicativo que requer gerenciamento de dados estruturados com capacidades avançadas de consulta — demonstrando como combinar múltiplas condições de filtro, paginação, ordenação e funcionalidade de busca em uma solução coesa de gerenciamento de dados.

import { SmartTablesSDK } from '@odin-ai-staging/sdk';

class ProductManager {
private sdk: SmartTablesSDK;
private tableId?: string;

constructor() {
this.sdk = new SmartTablesSDK({
baseUrl: process.env.API_BASE_URL,
projectId: process.env.PROJECT_ID,
apiKey: process.env.API_KEY,
apiSecret: process.env.API_SECRET
});
}

async initializeTable() {
try {
// Create table
const table = await this.sdk.createTable(
'Product Catalog',
'Manage product inventory and information'
);
this.tableId = table.id;

// Add columns
await this.addColumns();

console.log('Table initialized:', this.tableId);
return table;
} catch (error) {
console.error('Failed to initialize table:', error);
throw error;
}
}

private async addColumns() {
const columns = [
{ name: 'name', type: 'text', description: 'Product name', notNull: true },
{ name: 'description', type: 'text', description: 'Product description' },
{ name: 'price', type: 'number', description: 'Price in USD', notNull: true },
{ name: 'category', type: 'text', description: 'Product category' },
{ name: 'in_stock', type: 'boolean', description: 'Stock availability', defaultValue: true },
{ name: 'supplier_email', type: 'email', description: 'Supplier contact' },
{ name: 'website', type: 'url', description: 'Product website' },
{ name: 'created_at', type: 'date', description: 'Creation date' }
];

for (const column of columns) {
await this.sdk.addColumn(this.tableId!, column);
}
}

async addProduct(productData: any) {
if (!this.tableId) throw new Error('Table not initialized');

try {
const result = await this.sdk.addRow(this.tableId, {
...productData,
created_at: new Date().toISOString()
});

console.log('Product added:', result);
return result;
} catch (error) {
console.error('Failed to add product:', error);
throw error;
}
}

async searchProducts(searchTerm: string, category?: string, minPrice?: number, maxPrice?: number) {
if (!this.tableId) throw new Error('Table not initialized');

const filters = [];

if (category) {
filters.push({ column: 'category', operator: 'eq', value: category });
}

if (minPrice !== undefined) {
filters.push({ column: 'price', operator: 'gte', value: minPrice });
}

if (maxPrice !== undefined) {
filters.push({ column: 'price', operator: 'lte', value: maxPrice });
}

try {
const results = await this.sdk.queryTable(this.tableId, {
filters,
pagination: {
search: searchTerm,
limit: 50
},
sort: [
{ column: 'name', direction: 'asc' }
]
});

return results;
} catch (error) {
console.error('Search failed:', error);
throw error;
}
}
}

// Usage
const productManager = new ProductManager();
await productManager.initializeTable();
await productManager.addProduct({
name: 'Wireless Headphones',
price: 199.99,
category: 'Electronics'
});

Práticas Recomendadas​

Consultas Eficientes​

  • Use paginação para conjuntos de dados grandes
  • Aplique filtros para reduzir a transferência de dados
  • Combine múltiplas operações quando possível
// Good: Efficient query with filters and pagination
const results = await smartTablesSDK.queryTable(tableId, {
filters: [{ column: 'status', operator: 'eq', value: 'active' }],
pagination: { limit: 50, page: 1 },
sort: [{ column: 'created_at', direction: 'desc' }]
});

// Bad: Fetching all data without filters
const allResults = await smartTablesSDK.queryTable(tableId);

Design de Esquema​

  • Defina tipos de coluna apropriados
  • Use restrições (notNull, unique) de forma adequada
  • Forneça descrições significativas
// Good: Well-defined column schema
await smartTablesSDK.addColumn(tableId, {
name: 'email',
type: 'email',
description: 'Customer email address',
notNull: true,
unique: true
});

// Bad: Vague column definition
await smartTablesSDK.addColumn(tableId, {
name: 'data',
type: 'text'
});

Tratamento de Erros e Validação​

  • Sempre trate erros de forma adequada
  • Valide dados antes das operações
  • Use transações para operações relacionadas
async function safeTableOperation(tableId: string, data: any) {
try {
// Validate data first
if (!data.email || !data.email.includes('@')) {
throw new Error('Invalid email format');
}

// Perform operation
const result = await smartTablesSDK.addRow(tableId, data);
return result;
} catch (error) {
console.error('Operation failed:', error);
// Handle specific error types
if (error.message.includes('unique constraint')) {
throw new Error('Email already exists');
}
throw error;
}
}