Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
@singlestore/elegance-sdk
Advanced tools
The SingleStore Elegance SDK is a library for building full-stack AI-powered applications with SingleStoreDB and OpenAI API.
The SingleStore Elegance SDK is a library for building full-stack AI-powered applications with SingleStoreDB and OpenAI API.
npm install @singlestore/elegance-sdk
This guide will show you how to use the SDK in Express.js and React.js.
eleganceServerClient.ts
filecreateEleganceServerClient
function from @singlestore/elegance-sdk/server
// ./server/services/eleganceServerClient.ts
import { createEleganceServerClient } from "@singlestore/elegance-sdk/server";
export const eleganceServerClient = createEleganceServerClient("mysql", {
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
},
openai: {
apiKey: process.env.OPENAI_API_KEY
}
});
elegance/:route
(using Express.js as an example).// ./server/routes/elegance.ts
import express from "express";
import type { Routes } from "@singlestore/elegance-sdk/server";
import { eleganceServerClient } from "@/services/eleganceServerClient";
export const eleganceRouter = express.Router();
eleganceRouter.post("/elegance/:route", async (req, res) => {
try {
const route = req.params.route as Routes;
const result = await eleganceServerClient.handleRoute(route, req.body);
return res.status(200).json(result);
} catch (error: any) {
return res.status(error.status).json(error);
}
});
./server/index.ts
// ./server/index.ts
import express from "express";
import { eleganceRouter } from "./routes/elegance";
const app = express();
app.use(eleganceRouter);
app.listen(4000, () => {
console.log(`Server started on port: ${4000}`);
});
eleganceClient.ts
filecreateEleganceClient
function from @singlestore/elegance-sdk
// ./client/services/eleganceClient.ts
import { createEleganceClient } from "@singlestore/elegance-sdk";
export const eleganceClient = createEleganceClient("mysql", {
baseURL: "http://localhost:4000"
});
eleganceClient
to your component// ./client/components/ExampleComponent.tsx
import { useEffect } from "react";
import { eleganceClient } from "@/services/eleganceClient";
export function ExampleComponent() {
const query = eleganceClient.hooks.useQuery<{ name: string }[]>({ initialValue: [], initialIsLoading: true });
const { execute: executeQuery } = query;
useEffect(() => {
executeQuery({ query: "SELECT name FROM table LIMIT 3" });
}, [executeQuery]);
if (query.isLoading) return "Loading...";
return (
<div>
{query.value.map(item => (
<h4 key={item.name}>{item.name}</h4>
))}
</div>
);
}
You can find templates using the Elegance SDK here:
You can find example apps using the Elegance SDK here:
Creates an EleganceServerClient instance for a server.
Parameters:
connectionType: "kai" | "mysql"
config: {
connection: KaiConnectionConfig | MySQLConnectionConfig;
openai: OpenAIConfig;
}
Returns: eleganceServerClient
Server client that includes a database connection, controllers and OpenAI client. It's used on the server to handle requests from the client and execute logic.
MySQL or MongoDB connection to interact with a database
Accepts a route and executes the controller for that route.
Parameters:
route: string
- controller route namebody: object
- controller bodyInserts one record.
Parameters:
body: {
collection: string; // Collection name
generateId?: boolean; // Generates the `id` string field
value: MongoOptionalUnlessRequiredId<T>; // Value to insert
options?: MongoInsertOneOptions;
} | {
table: string; // Table name
generateId?: boolean;
value: T;
}
Returns: T
Inserts many records.
Parameters:
body: {
collection: string; // Collection name
values: Array<MongoOptionalUnlessRequiredId<T[number]>>; // Values to insert
generateId?: boolean; // Generates the `id` string field
options?: MongoBulkWriteOptions;
} | {
table: string; // Table name
generateId?: boolean;
values: Array<T>;
}
Returns: Array<T>
Updates many records.
Parameters:
body: {
collection: string; // Collection name
filter: MongoFilter<T[number]>; // Filter to find records to update
update: MongoUpdateFilter<T[number]>;
options?: MongoUpdateOptions;
updatedFilter?: MongoFilter<T[number]>; // Filter to find updated records
} | {
table: string; // Table name
where: MySQLWhere; // MySQL WHERE string value to find records to update
set: MySQLSet; // MySQL SET string value
updatedWhere: MySQLWhere; // MySQL WHERE string value to find updated records
}
Returns: Array<T>
Deletes many records.
Parameters:
body: {
collection: string; // Collection name
filter: MongoFilter<T>; // Filter to find records to delete
options?: MongoDeleteOptions;
} | {
table: string; // Table name
where: MySQLWhere; // MySQL WHERE string value to find records to delete
}
Returns: { message: string }
Gets one record.
Parameters:
body: {
collection: string; // Collection name
filter?: MongoFilter<T>; // Filter to find a record
options?: MongoFindOptions;
} | {
table: string; // Table name
columns?: string[]; // Columns to get by default *
where?: MySQLWhere; // MySQL WHERE string value to find a record
}
Returns: T
Gets many records.
Parameters:
body: {
collection: string; // Collection name
filter?: MongoFilter<T[number]>; // Filter to find records
options?: MongoFindOptions;
} | {
table: string; // Table name
columns?: string[]; // Columns to get by default *
where?: MySQLWhere; // MySQL WHERE string value to find records
skip?: number;
limit?: number;
}
Returns: Array<object>
Executes MySQL or aggregate query.
Parameters:
body: {
collection: string; // Collection name
pipeline: object[]; // Aggregate pipeline
options?: MongoAggregateOptions;
} | {
query: string; // MySQL query
}
Returns: Array<T>
Creates embedding.
Parameters:
body: {
input: string | string[] | object | object[];
}
Returns: Array<number>
Performs vector search in the collection based on the query.
Parameters:
body: {
collection: string; // Collection name
embeddingField: string; // Field name with the embedding by which to perform the search
query: string; // Search query
limit?: number; // Number of records to get
} | {
table: string; // Table name
embeddingField: string;
query: string;
limit?: number;
}
Returns: Array<object>
Accepts a prompt, performs vector search, and creates chat completion for the found records.
Parameters:
body: {
collection: string; // Collection name
prompt: string; // Prompt text
model?: string;
textField?: string; // Field name by which to create a chat completion
embeddingField?: string; // Field name with the embedding by which to perform the search
minSimilarity?: number; // Minimum similarity number to filter search results, used to create a chat completion.
systemRole?: string; // Initial system role
messages?: CreateChatCompletionBody["messages"]; // Additional messages after the prompt message
maxTokens?: CreateChatCompletionBody["max_tokens"];
maxContextLength?: number;
temperature?: CreateChatCompletionBody["temperature"];
} | {
table: string; // Table name
prompt: string;
model?: string;
textField?: string;
embeddingField?: string;
minSimilarity?: number;
systemRole?: string;
messages?: CreateChatCompletionBody["messages"];
maxTokens?: CreateChatCompletionBody["max_tokens"];
maxContextLength?: number;
temperature?: CreateChatCompletionBody["temperature"];
}
Returns:
{
content: string;
context: string;
}
Accepts a CSV or PDF file as a DataURL, splits it into chunks and creates embeddings.
Parameters:
body: {
dataURL: string; // CSV or PDF file DataURL
textField?: string; // Field name in which to save a chunk text
embeddingField?: string; // Field name in which to save an embedding
chunkSize?: number;
}
Returns: Array<{ text: string; embedding: number[]; }>
Accepts a CSV or PDF file as a DataURL, splits it into chunks, creates embeddings, and inserts them into a database.
Parameters:
body: {
collection: string; // Collection name
dataURL: string; // CSV or PDF file DataURL
textField?: string; // Field name in which to save a chunk text
embeddingField?: string; // Field name in which to save an embedding
chunkSize?: number;
} | {
table: string; // Table name
dataURL: string;
textField?: string;
embeddingField?: string;
chunkSize?: number;
}
Returns: Array<{ text: string; embedding: number[]; }>
Default OpenAI client + helpers
Creates embedding using the OpenAI Embeddings API
Parameters:
input: string | Array<string> | object | Array<object>
- input valueReturns: Array<number>
Converts an embedding into a buffer that is then inserted into the database.
Parameters:
embedding: Array<number>
Returns: Buffer
Converts a DataURL (csv, pdf) into an embedding by splitting the text into chunks.
Parameters:
dataURL: string
options?: {
chunkSize?: number;
textField?: string; // Field name in which to save a chunk text
embeddingField?: string; // Field name in which to save an embedding
}
Returns: Array<{ text: string; embedding: number[] }>
Generates a chat completion using the OpenAI ChatCompletion API.
Parameters:
options: ChatCompletionCreateParamsBase
Returns: string
Creates an EleganceClient instance for a client.
Parameters:
connectionType: "kai" | "mysql"
config: {
baseURL: string; // Server URL with the '/elegance/:route' route handler.
}
Returns: eleganceServerClient
Client that includes requests and hooks. It is used to make requests to the server.
Clean functions to make requests to the server. They can be used anywhere within a project and are handled like typical async functions. The parameters for each request correspond to the controller parameters by name. To familiarize with the parameters, refer to the eleganceServerClient.controllers.<requestName>.execute
section.
Ready-to-use React.js hooks with state handlers that use requests. Each hook has the following type:
<R = any,>(options?: { initialValue?: R; initialIsLoading?: boolean; onError?: (error: DefaultError) => void }) => {
value: R | undefined;
error: DefaultError | undefined;
isLoading: boolean;
setValue: react.Dispatch<react.SetStateAction<Awaited<R> | undefined>>;
setError: react.Dispatch<react.SetStateAction<DefaultError | undefined>>;
setIsLoading: react.Dispatch<react.SetStateAction<boolean>>;
execute: (body: object) => Promise<Awaited<R> | undefined>; // Function that executes a request from the eleganceClient.requests by name
};
© 2023 SingleStore
FAQs
The Elegance SDK is an SDK for quickly building real-time AI full-stack JavaScript applications using SingleStoreDB with support for MySQL and Kai (support for Mongo APIs) connection types and the OpenAI API. It provides a set of ready-made tools for impl
The npm package @singlestore/elegance-sdk receives a total of 7 weekly downloads. As such, @singlestore/elegance-sdk popularity was classified as not popular.
We found that @singlestore/elegance-sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.