@aigur/client
Advanced tools
Comparing version 0.30.0 to 0.30.1
@@ -1,812 +0,7 @@ | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
// src/index.ts | ||
var src_exports = {}; | ||
__export(src_exports, { | ||
createClient: () => createClient | ||
}); | ||
module.exports = __toCommonJS(src_exports); | ||
// src/makeid.ts | ||
function makeid(length = 16) { | ||
let result = ""; | ||
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; | ||
const charactersLength = characters.length; | ||
for (let i = 0; i < length; i++) { | ||
result += characters.charAt(Math.floor(Math.random() * charactersLength)); | ||
} | ||
return result; | ||
} | ||
// src/getInputByContext.ts | ||
function getInputByContext(inputPlaceholders, values) { | ||
if (typeof inputPlaceholders === "string") { | ||
return handleSingleValue(inputPlaceholders); | ||
} | ||
const input = { ...inputPlaceholders }; | ||
return getInputContextInner(input); | ||
function getInputContextInner(input2) { | ||
for (const key in input2) { | ||
input2[key] = handleSingleValue(input2[key]); | ||
} | ||
return input2; | ||
} | ||
function handleSingleValue(value) { | ||
if (Array.isArray(value)) { | ||
return value.map((item) => getInputContextInner(item)); | ||
} | ||
if (typeof value === "object" && value !== null) { | ||
return getInputContextInner(value); | ||
} | ||
let newValue = value; | ||
const contextReferences = getContextReferences(value); | ||
for (let ref of contextReferences) { | ||
const contextValue = values[ref.nodeId]; | ||
const propertyValue = contextValue[ref.property]; | ||
if (propertyValue instanceof ArrayBuffer) { | ||
newValue = propertyValue; | ||
continue; | ||
} | ||
newValue = newValue?.replace(new RegExp(escapeRegExp(ref.value)), propertyValue); | ||
if (newValue === "undefined") { | ||
newValue = void 0; | ||
} else if (newValue !== propertyValue && newValue === propertyValue.toString()) { | ||
newValue = propertyValue; | ||
} | ||
} | ||
return newValue; | ||
} | ||
function getContextReferences(value) { | ||
if (typeof value !== "string") | ||
return []; | ||
const contextRegex = /\$context\.(\d+|input)\.(\w+)\$/g; | ||
const matches = value.matchAll(contextRegex); | ||
const references = []; | ||
for (let match of matches) { | ||
references.push({ | ||
value: match[0], | ||
nodeId: match[1], | ||
property: match[2] | ||
}); | ||
} | ||
return references; | ||
} | ||
function escapeRegExp(string) { | ||
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); | ||
} | ||
} | ||
// src/delay.ts | ||
function delay(time) { | ||
return new Promise((resolve) => setTimeout(resolve, time)); | ||
} | ||
// src/Pipeline.ts | ||
var DEFAULT_RETRIES = 2; | ||
var RETRY_DELAY_IN_MS = 350; | ||
var Pipeline = class { | ||
constructor(conf, flow, apiKeys) { | ||
this.conf = conf; | ||
this.flow = flow; | ||
this.apiKeys = apiKeys; | ||
this.onProgressListeners = /* @__PURE__ */ new Map(); | ||
this.onStartListeners = /* @__PURE__ */ new Map(); | ||
this.onFinishListeners = /* @__PURE__ */ new Map(); | ||
this.vercel = { | ||
invoke: (input) => { | ||
return this.invokeRemote(`/api/pipelines/${this.conf.id}`, input); | ||
}, | ||
invokeStream: (input, cb) => { | ||
return this.invokeStream(`/api/pipelines/${this.conf.id}`, input, cb); | ||
} | ||
}; | ||
this.listenToEvents(); | ||
} | ||
invoke(input) { | ||
return this.processPipeline(this.conf, input); | ||
} | ||
invokeRemote(endpoint2, input) { | ||
return fetch(endpoint2, { | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/json" | ||
}, | ||
body: JSON.stringify(input) | ||
}).then((res) => res.json()); | ||
} | ||
async invokeStream(endpoint2, input, cb) { | ||
const response = await fetch(endpoint2, { | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/json" | ||
}, | ||
body: JSON.stringify(input) | ||
}); | ||
if (!response.ok) { | ||
throw new Error(response.statusText); | ||
} | ||
const data = response.body; | ||
if (!data) { | ||
return; | ||
} | ||
const reader = data.getReader(); | ||
const decoder = new TextDecoder(); | ||
let done = false; | ||
while (!done) { | ||
const { value, done: doneReading } = await reader.read(); | ||
done = doneReading; | ||
const chunkValue = decoder.decode(value); | ||
cb(chunkValue); | ||
} | ||
} | ||
onProgress(cb) { | ||
const id = makeid(); | ||
this.onProgressListeners.set(id, cb); | ||
return () => { | ||
this.onProgressListeners.delete(id); | ||
}; | ||
} | ||
onStart(cb) { | ||
const id = makeid(); | ||
this.onStartListeners.set(id, cb); | ||
return () => { | ||
this.onStartListeners.delete(id); | ||
}; | ||
} | ||
onFinish(cb) { | ||
const id = makeid(); | ||
this.onFinishListeners.set(id, cb); | ||
return () => { | ||
this.onFinishListeners.delete(id); | ||
}; | ||
} | ||
listenToEvents() { | ||
if (!this.conf.updateProgress || typeof window === "undefined" || !this.apiKeys?.ablySubscribe) { | ||
return; | ||
} | ||
const dataEndpoint = `https://realtime.ably.io/event-stream?channels=aigur-client&v=1.2&key=${this.apiKeys.ablySubscribe}&enveloped=false`; | ||
const eventSource = new EventSource(dataEndpoint); | ||
eventSource.onmessage = (event) => { | ||
const e = JSON.parse(event.data); | ||
if (e.type === "pipeline:start") { | ||
this.triggerListeners(this.onStartListeners); | ||
} else if (e.type === "pipeline:finish") { | ||
this.triggerListeners(this.onFinishListeners); | ||
} else if (e.type === "node:start" || e.type === "node:finish") { | ||
this.triggerListeners(this.onProgressListeners, { ...e.data, type: e.type }); | ||
} | ||
}; | ||
} | ||
triggerListeners(listeners, ...args) { | ||
for (let listener of listeners.values()) { | ||
listener(...args); | ||
} | ||
} | ||
async processPipeline(pipeline, input) { | ||
const retriesCount = this.conf.retries ?? DEFAULT_RETRIES; | ||
try { | ||
await this.notifyEvent("pipeline:start"); | ||
pipeline.input.parse(input); | ||
const values = { input }; | ||
let output = {}; | ||
const nodes = this.flow.getNodes(); | ||
let startProgressPromise; | ||
for (let i = 0; i < nodes.length; i++) { | ||
startProgressPromise = this.notifyEvent("node:start", { node: nodes[i], index: i }); | ||
let attemptCount = 0; | ||
let isSuccess = false; | ||
do { | ||
attemptCount++; | ||
try { | ||
output = await this.executeAction(nodes, i, values); | ||
values[i] = output; | ||
isSuccess = true; | ||
} catch (e) { | ||
if (attemptCount > retriesCount) { | ||
throw e; | ||
} | ||
await delay((this.conf.retryDelayInMs ?? RETRY_DELAY_IN_MS) * attemptCount); | ||
} | ||
} while (!isSuccess && attemptCount <= retriesCount); | ||
await startProgressPromise; | ||
await this.notifyEvent("node:finish", { node: nodes[i], index: i }); | ||
} | ||
await this.notifyEvent("pipeline:finish"); | ||
return output; | ||
} catch (e) { | ||
console.error(e); | ||
throw e; | ||
} | ||
} | ||
async executeAction(nodes, index, values) { | ||
const { action: action10, schema, input } = nodes[index]; | ||
const inputByContext = getInputByContext(input, values); | ||
return action10(inputByContext, this.apiKeys); | ||
} | ||
notifyEvent(type, data) { | ||
if (!this.conf.updateProgress || !this.apiKeys.ablyPublish) { | ||
return; | ||
} | ||
return fetch("https://rest.ably.io/channels/aigur-client/messages?enveloped=false ", { | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/json", | ||
Authorization: `Basic ${btoa(this.apiKeys.ablyPublish)}` | ||
}, | ||
body: JSON.stringify({ | ||
type, | ||
data | ||
}) | ||
}); | ||
} | ||
}; | ||
// src/nodes/text/prediction/gpt3.stream.ts | ||
var import_zod2 = require("zod"); | ||
var import_eventsource_parser = require("eventsource-parser"); | ||
// src/nodes/text/prediction/gpt3.ts | ||
var import_zod = require("zod"); | ||
var inputSchema = import_zod.z.object({ | ||
prompt: import_zod.z.string(), | ||
model: import_zod.z.string().default("text-davinci-003"), | ||
temperature: import_zod.z.number().default(0.7), | ||
top_p: import_zod.z.number().default(1), | ||
frequency_penalty: import_zod.z.number().default(0), | ||
presence_penalty: import_zod.z.number().default(0), | ||
max_tokens: import_zod.z.number().default(200), | ||
n: import_zod.z.number().default(1) | ||
}); | ||
var outputSchema = import_zod.z.object({ | ||
text: import_zod.z.string() | ||
}); | ||
async function action(input, apiKeys) { | ||
const payload = inputSchema.parse(input); | ||
const response = await fetch("https://api.openai.com/v1/completions", { | ||
headers: { | ||
"Content-Type": "application/json", | ||
Authorization: `Bearer ${apiKeys.openai}` | ||
}, | ||
method: "POST", | ||
body: JSON.stringify(payload) | ||
}); | ||
const output = await response.json(); | ||
return { text: output.choices[0]?.text.replace(/^(?:\n)+/gm, "") }; | ||
} | ||
var gpt3PredictionNode = { | ||
id: "text.prediction.gpt3", | ||
schema: { | ||
input: inputSchema, | ||
output: outputSchema | ||
}, | ||
action | ||
}; | ||
// src/nodes/text/prediction/gpt3.stream.ts | ||
var inputSchema2 = inputSchema.merge( | ||
import_zod2.z.object({ | ||
stream: import_zod2.z.literal(true).optional().default(true) | ||
}) | ||
); | ||
var outputSchema2 = import_zod2.z.object({ stream: import_zod2.z.instanceof(globalThis.ReadableStream ?? Object) }); | ||
async function action2(input, apiKeys) { | ||
const payload = inputSchema2.parse(input); | ||
const response = await fetch("https://api.openai.com/v1/completions", { | ||
headers: { | ||
"Content-Type": "application/json", | ||
Authorization: `Bearer ${apiKeys.openai}` | ||
}, | ||
method: "POST", | ||
body: JSON.stringify(payload) | ||
}); | ||
const stream = await OpenAIStream(response); | ||
return { stream }; | ||
} | ||
var gpt3PredictionStreamNode = { | ||
id: "text.prediction.gpt3.stream", | ||
schema: { | ||
input: inputSchema2, | ||
output: outputSchema2 | ||
}, | ||
action: action2 | ||
}; | ||
async function OpenAIStream(response) { | ||
const encoder = new TextEncoder(); | ||
const decoder = new TextDecoder(); | ||
let counter = 0; | ||
const stream = new ReadableStream({ | ||
async start(controller) { | ||
function onParse(event) { | ||
if (event.type === "event") { | ||
const data = event.data; | ||
if (data === "[DONE]") { | ||
controller.close(); | ||
return; | ||
} | ||
try { | ||
const json = JSON.parse(data); | ||
const text = json.choices[0].text; | ||
if (counter < 2 && (text.match(/\n/) || []).length) { | ||
return; | ||
} | ||
const queue = encoder.encode(text); | ||
controller.enqueue(queue); | ||
counter++; | ||
} catch (e) { | ||
controller.error(e); | ||
} | ||
} | ||
} | ||
const parser = (0, import_eventsource_parser.createParser)(onParse); | ||
for await (const chunk of response.body) { | ||
parser.feed(decoder.decode(chunk)); | ||
} | ||
} | ||
}); | ||
return stream; | ||
} | ||
// src/nodes/output/output.ts | ||
var import_zod3 = require("zod"); | ||
var outputNode = () => ({ | ||
id: "output", | ||
schema: { | ||
input: import_zod3.z.object({}), | ||
output: import_zod3.z.object({}) | ||
}, | ||
async action(input) { | ||
return input; | ||
} | ||
}); | ||
// src/nodes/image/labeling/googleVision.ts | ||
var import_zod4 = require("zod"); | ||
var inputSchema3 = import_zod4.z.object({ | ||
image: import_zod4.z.string() | ||
// base64 | ||
}); | ||
var outputSchema3 = import_zod4.z.object({ | ||
labels: import_zod4.z.array(import_zod4.z.string()) | ||
}); | ||
async function action3(input, apiKeys) { | ||
const payload = inputSchema3.parse(input); | ||
const endpoint2 = `https://vision.googleapis.com/v1/images:annotate?key=${apiKeys.googleapis}`; | ||
const request = { | ||
requests: [ | ||
{ | ||
image: { | ||
content: payload.image | ||
}, | ||
features: [ | ||
{ | ||
type: "LABEL_DETECTION" | ||
} | ||
] | ||
} | ||
] | ||
}; | ||
const response = await fetch(endpoint2, { | ||
method: "POST", | ||
body: JSON.stringify(request) | ||
}); | ||
const data = await response.json(); | ||
return { | ||
labels: data.responses[0].labelAnnotations.map((label) => label.description) | ||
}; | ||
} | ||
var googleVisionNode = { | ||
id: "image.labeling.googleVision", | ||
schema: { | ||
input: inputSchema3, | ||
output: outputSchema3 | ||
}, | ||
action: action3 | ||
}; | ||
// src/nodes/image/textToImage/stability.ts | ||
var import_zod5 = require("zod"); | ||
var inputSchema4 = import_zod5.z.object({ | ||
text_prompts: import_zod5.z.array( | ||
import_zod5.z.object({ | ||
text: import_zod5.z.string(), | ||
weight: import_zod5.z.number().min(-1).max(1).optional().default(1) | ||
}) | ||
).refine((val) => val.length > 0, "Must have at least one text prompt"), | ||
model: import_zod5.z.enum(["stable-diffusion-v1-5", "stable-diffusion-512-v2-1", "stable-diffusion-768-v2-1"]).optional().default("stable-diffusion-v1-5"), | ||
clip_guidance_preset: import_zod5.z.enum(["NONE", "FAST_BLUE", "FAST_GREEN", "SIMPLE", "SLOW", "SLOWER", "SLOWEST"]).optional(), | ||
steps: import_zod5.z.number().optional(), | ||
sampler: import_zod5.z.enum(["one", "two"]).optional(), | ||
samples: import_zod5.z.number().optional(), | ||
cfg_scale: import_zod5.z.number().optional(), | ||
seed: import_zod5.z.number().optional(), | ||
height: import_zod5.z.number().min(128).optional().refine( | ||
(val) => typeof val !== "undefined" ? val % 64 === 0 : true, | ||
"Must be a multiple of 64" | ||
), | ||
width: import_zod5.z.number().min(128).optional().refine( | ||
(val) => typeof val !== "undefined" ? val % 64 === 0 : true, | ||
"Must be a multiple of 64" | ||
) | ||
}); | ||
var outputSchema4 = import_zod5.z.object({ | ||
result: import_zod5.z.instanceof(ArrayBuffer) | ||
}); | ||
async function action4(input, apiKeys) { | ||
const payload = inputSchema4.parse(input); | ||
const endpoint2 = `https://api.stability.ai/v1beta/generation/${payload.model}/text-to-image`; | ||
const response = await fetch(endpoint2, { | ||
headers: { | ||
"Content-Type": "application/json", | ||
Accept: "image/png", | ||
Authorization: apiKeys.stability | ||
}, | ||
method: "POST", | ||
body: JSON.stringify(payload) | ||
}); | ||
const image = await response.arrayBuffer(); | ||
return { | ||
result: image | ||
}; | ||
} | ||
var stabilityTextToImageNode = { | ||
id: "image.textToImage.stableDiffusion.stability", | ||
schema: { | ||
input: inputSchema4, | ||
output: outputSchema4 | ||
}, | ||
action: action4 | ||
}; | ||
// src/nodes/text/modify/enhanceWithKeywords.ts | ||
var import_zod6 = require("zod"); | ||
var inputSchema5 = import_zod6.z.object({ | ||
text: import_zod6.z.string(), | ||
amount: import_zod6.z.number().optional().default(8) | ||
}); | ||
var outputSchema5 = import_zod6.z.object({ | ||
text: import_zod6.z.string() | ||
}); | ||
var examples = { | ||
"Colonial-style home": "Colonial, traditional, classic, historical, timeless, elegant, regal, grand, spacious, architectural, wood-framed, brick-exterior, symmetrical, gabled roof, columns, portico, fireplace, formal, ornate, landscaped".split( | ||
", " | ||
), | ||
"High-end penthouse apartment": "Luxury, high-end, penthouse, apartment, upscale, contemporary, modern, stylish, designer, elite, high-rise, rooftop, panoramic, views, spacious, open-plan, top-floor, amenities, concierge, service, exclusive".split( | ||
", " | ||
) | ||
}; | ||
function getExamples(amountOfKeys) { | ||
return Object.entries(examples).map( | ||
([key, value]) => `Title: ${key} | ||
Description: ${value.slice(0, amountOfKeys).join(", ")} | ||
` | ||
).join("\n"); | ||
} | ||
async function action5(input) { | ||
const payload = inputSchema5.parse(input); | ||
const enhancedText = `Write a maximum of ${payload.amount} keywords in a csv list that describes the following | ||
${getExamples(payload.amount)} | ||
Title: ${payload.text} | ||
Description:`; | ||
return { | ||
text: enhancedText | ||
}; | ||
} | ||
var enhanceWithKeywordsNode = { | ||
id: "text.modify.enhanceWithKeywords", | ||
schema: { | ||
input: inputSchema5, | ||
output: outputSchema5 | ||
}, | ||
action: action5 | ||
}; | ||
// src/nodes/text/modify/simple.ts | ||
var import_zod7 = require("zod"); | ||
var inputSchema6 = import_zod7.z.object({ | ||
text: import_zod7.z.string().or(import_zod7.z.array(import_zod7.z.string())), | ||
modifier: import_zod7.z.string() | ||
}); | ||
var outputSchema6 = import_zod7.z.object({ | ||
text: import_zod7.z.string() | ||
}); | ||
async function action6(input) { | ||
const payload = inputSchema6.parse(input); | ||
return { | ||
text: payload.modifier.replace( | ||
/\$\(text\)\$/gm, | ||
Array.isArray(payload.text) ? payload.text.join(", ") : payload.text | ||
) | ||
}; | ||
} | ||
var simpleModificationNode = { | ||
id: "text.modify.simple", | ||
schema: { | ||
input: inputSchema6, | ||
output: outputSchema6 | ||
}, | ||
action: action6 | ||
}; | ||
// src/nodes/voice/transcribe/whisper/whisperapi.ts | ||
var import_zod8 = require("zod"); | ||
var endpoint = "https://transcribe.whisperapi.com"; | ||
var inputSchema7 = import_zod8.z.object({ | ||
audioUrl: import_zod8.z.string().url() | ||
}); | ||
var outputSchema7 = import_zod8.z.object({ | ||
text: import_zod8.z.string() | ||
}); | ||
async function action7(input, apiKeys) { | ||
const payload = inputSchema7.parse(input); | ||
const form = new FormData(); | ||
form.append("url", payload.audioUrl); | ||
form.append("language", "en"); | ||
form.append("fileType", "mp3"); | ||
form.append("task", "transcribe"); | ||
const result = await fetch(endpoint, { | ||
method: "POST", | ||
headers: { | ||
contentType: "application/json", | ||
Authorization: "Bearer " + apiKeys.whisperapi | ||
}, | ||
body: form | ||
}); | ||
if (!result.ok) { | ||
throw new Error(result.statusText); | ||
} | ||
const data = await result.json(); | ||
return { text: data.text.trim() }; | ||
} | ||
var whisperApiNode = { | ||
id: "voice.transcribe.whisper.whisperapi", | ||
schema: { | ||
input: inputSchema7, | ||
output: outputSchema7 | ||
}, | ||
action: action7 | ||
}; | ||
// src/nodes/transformation/stringToArrayBuffer.ts | ||
var import_zod9 = require("zod"); | ||
var inputSchema8 = import_zod9.z.object({ | ||
string: import_zod9.z.string() | ||
}); | ||
var outputSchema8 = import_zod9.z.object({ | ||
arrayBuffer: import_zod9.z.instanceof(ArrayBuffer) | ||
}); | ||
async function action8(input) { | ||
const payload = inputSchema8.parse(input); | ||
const typedArray = Uint8Array.from(atob(payload.string), (c) => c.charCodeAt(0)); | ||
return { | ||
arrayBuffer: typedArray.buffer | ||
}; | ||
} | ||
var stringToArrayBufferNode = { | ||
id: "text.transformation.stringToArrayBuffer", | ||
schema: { | ||
input: inputSchema8, | ||
output: outputSchema8 | ||
}, | ||
action: action8 | ||
}; | ||
// src/nodes/voice/textToSpeech/googleTextToSpeech.ts | ||
var import_zod10 = require("zod"); | ||
var inputSchema9 = import_zod10.z.object({ | ||
text: import_zod10.z.string(), | ||
speakingRate: import_zod10.z.number().min(0.25).max(4).optional().default(1), | ||
pitch: import_zod10.z.number().min(-20).max(20).optional().default(0), | ||
encoding: import_zod10.z.enum([ | ||
"MP3", | ||
"FLAC", | ||
"LINEAR16", | ||
"MULAW", | ||
"AMR", | ||
"AMR_WB", | ||
"OGG_OPUS", | ||
"SPEEX_WITH_HEADER_BYTE", | ||
"WEBM_OPUS" | ||
]).optional().default("MP3"), | ||
voice: import_zod10.z.object({ | ||
language: import_zod10.z.string().optional().default("en-US"), | ||
name: import_zod10.z.enum([ | ||
"en-US-Standard-A", | ||
"en-US-Standard-C", | ||
"en-US-Standard-D", | ||
"en-US-Standard-E", | ||
"en-US-Standard-F", | ||
"en-US-Standard-G", | ||
"en-US-Standard-H", | ||
"en-US-Standard-I", | ||
"en-US-Standard-J", | ||
"en-US-Studio-M", | ||
"en-US-Studio-O", | ||
"en-US-Wavenet-A", | ||
"en-US-Wavenet-B", | ||
"en-US-Wavenet-C", | ||
"en-US-Wavenet-D", | ||
"en-US-Wavenet-E", | ||
"en-US-Wavenet-F", | ||
"en-US-Wavenet-G", | ||
"en-US-Wavenet-H", | ||
"en-US-Wavenet-I", | ||
"en-US-Wavenet-J", | ||
"en-US-News-K", | ||
"en-US-News-L", | ||
"en-US-News-M", | ||
"en-US-News-N", | ||
"en-US-Standard-A", | ||
"en-US-Standard-B", | ||
"en-US-Standard-C", | ||
"en-US-Standard-D", | ||
"en-US-Standard-E", | ||
"en-US-Standard-F", | ||
"en-US-Standard-G", | ||
"en-US-Standard-H", | ||
"en-US-Standard-I", | ||
"en-US-Standard-J" | ||
]).or(import_zod10.z.string()).optional().default("en-US-Neural2-C") | ||
}).optional().default({ | ||
language: "en-US", | ||
name: "en-US-Neural2-C" | ||
}) | ||
}); | ||
var outputSchema9 = import_zod10.z.object({ | ||
audio: import_zod10.z.string() | ||
// base64 | ||
}); | ||
async function action9(input, apiKeys) { | ||
const parsedInput = inputSchema9.parse(input); | ||
const endpoint2 = `https://us-central1-texttospeech.googleapis.com/v1beta1/text:synthesize?key=${apiKeys.googleapis}`; | ||
const payload = { | ||
input: { | ||
text: parsedInput.text | ||
}, | ||
voice: { | ||
languageCode: parsedInput.voice.language, | ||
name: parsedInput.voice.name | ||
}, | ||
audioConfig: { | ||
audioEncoding: parsedInput.encoding, | ||
speakingRate: parsedInput.speakingRate, | ||
pitch: parsedInput.pitch | ||
} | ||
}; | ||
const result = await fetch(endpoint2, { | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/json" | ||
}, | ||
body: JSON.stringify(payload) | ||
}); | ||
const data = await result.json(); | ||
return { | ||
audio: data.audioContent | ||
}; | ||
} | ||
var googleTextToSpeechNode = { | ||
id: "voice.textToSpeech.google", | ||
schema: { | ||
input: inputSchema9, | ||
output: outputSchema9 | ||
}, | ||
action: action9 | ||
}; | ||
// src/builder.ts | ||
var Builder = class { | ||
constructor(input, nodes) { | ||
this.input = input; | ||
this.nodes = nodes; | ||
this.voice = { | ||
textToSpeech: { | ||
google: this.nodeFactory(googleTextToSpeechNode) | ||
}, | ||
transcribe: { | ||
whisper: { | ||
whisperapi: this.nodeFactory(whisperApiNode) | ||
} | ||
} | ||
}; | ||
this.text = { | ||
modify: { | ||
enhanceWithKeywords: this.nodeFactory(enhanceWithKeywordsNode), | ||
simple: this.nodeFactory(simpleModificationNode) | ||
}, | ||
prediction: { | ||
gpt3: this.nodeFactory(gpt3PredictionNode), | ||
gpt3Stream: this.nodeFactory(gpt3PredictionStreamNode) | ||
} | ||
}; | ||
this.image = { | ||
textToImage: { | ||
stableDiffusion: { | ||
stability: this.nodeFactory(stabilityTextToImageNode) | ||
} | ||
}, | ||
labeling: { | ||
googleVision: this.nodeFactory(googleVisionNode) | ||
} | ||
}; | ||
this.output = this.nodeFactory(outputNode()); | ||
this.transformation = { | ||
stringToArrayBuffer: this.nodeFactory(stringToArrayBufferNode) | ||
}; | ||
} | ||
static create(input) { | ||
return new Builder(input, []); | ||
} | ||
nodeFactory(nodeDefinition) { | ||
return (getUserInput) => { | ||
const input = this.setPlaceholderValues(this.input.keyof().options, "input"); | ||
const prev = this.nodes.length > 0 ? this.nodes[this.nodes.length - 1] : input; | ||
const node = { | ||
...nodeDefinition, | ||
input: getUserInput({ | ||
nodes: this.nodes, | ||
prev: prev.output, | ||
input | ||
}), | ||
output: nodeDefinition.schema.output.keyof ? this.setPlaceholderValues( | ||
nodeDefinition.schema.output.keyof().options, | ||
this.nodes.length | ||
) : nodeDefinition.schema.output | ||
}; | ||
this.nodes.push(node); | ||
return this; | ||
}; | ||
} | ||
setPlaceholderValues(outputKeys, index) { | ||
const placeholderedOutput = {}; | ||
for (let key of outputKeys) { | ||
placeholderedOutput[key] = `$context.${index}.${key}$`; | ||
} | ||
return placeholderedOutput; | ||
} | ||
custom(node) { | ||
return this.nodeFactory(node); | ||
} | ||
getNodes() { | ||
return this.nodes; | ||
} | ||
}; | ||
// src/Aigur.ts | ||
var DEFAULT_RETRIES2 = 2; | ||
var RETRY_DELAY_IN_MS2 = 350; | ||
var createClient = (opts) => { | ||
const { apiKeys } = opts; | ||
return { | ||
pipeline: { | ||
create: (conf) => { | ||
const pipelineConf = { | ||
...conf, | ||
retries: conf.retries ?? DEFAULT_RETRIES2, | ||
retryDelayInMs: conf.retryDelayInMs ?? RETRY_DELAY_IN_MS2 | ||
}; | ||
const flow = conf.flow(new Builder(conf.input, [])); | ||
return new Pipeline(pipelineConf, flow, apiKeys); | ||
} | ||
} | ||
}; | ||
}; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
createClient | ||
}); | ||
var A=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var X=(n,e)=>{for(var t in e)A(n,t,{get:e[t],enumerable:!0})},Q=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of q(e))!Y.call(n,i)&&i!==t&&A(n,i,{get:()=>e[i],enumerable:!(o=H(e,i))||o.enumerable});return n};var ee=n=>Q(A({},"__esModule",{value:!0}),n);var Oe={};X(Oe,{createClient:()=>Te});module.exports=ee(Oe);function P(n=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",o=t.length;for(let i=0;i<n;i++)e+=t.charAt(Math.floor(Math.random()*o));return e}function k(n,e){if(typeof n=="string")return i(n);let t={...n};return o(t);function o(a){for(let r in a)a[r]=i(a[r]);return a}function i(a){if(Array.isArray(a))return a.map(u=>o(u));if(typeof a=="object"&&a!==null)return o(a);let r=a,d=s(a);for(let u of d){let y=e[u.nodeId][u.property];if(y instanceof ArrayBuffer){r=y;continue}r=r?.replace(new RegExp(c(u.value)),y),r==="undefined"?r=void 0:r!==y&&r===y.toString()&&(r=y)}return r}function s(a){if(typeof a!="string")return[];let r=/\$context\.(\d+|input)\.(\w+)\$/g,d=a.matchAll(r),u=[];for(let f of d)u.push({value:f[0],nodeId:f[1],property:f[2]});return u}function c(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}function D(n){return new Promise(e=>setTimeout(e,n))}var te=2,ne=350,w=class{constructor(e,t,o){this.conf=e;this.flow=t;this.apiKeys=o;this.onProgressListeners=new Map;this.onStartListeners=new Map;this.onFinishListeners=new Map;this.vercel={invoke:e=>this.invokeRemote(`/api/pipelines/${this.conf.id}`,e),invokeStream:(e,t)=>this.invokeStream(`/api/pipelines/${this.conf.id}`,e,t)};this.listenToEvents()}invoke(e){return this.processPipeline(this.conf,e)}invokeRemote(e,t){return fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}).then(o=>o.json())}async invokeStream(e,t,o){let i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok)throw new Error(i.statusText);let s=i.body;if(!s)return;let c=s.getReader(),a=new TextDecoder,r=!1;for(;!r;){let{value:d,done:u}=await c.read();r=u;let f=a.decode(d);o(f)}}onProgress(e){let t=P();return this.onProgressListeners.set(t,e),()=>{this.onProgressListeners.delete(t)}}onStart(e){let t=P();return this.onStartListeners.set(t,e),()=>{this.onStartListeners.delete(t)}}onFinish(e){let t=P();return this.onFinishListeners.set(t,e),()=>{this.onFinishListeners.delete(t)}}listenToEvents(){if(!this.conf.updateProgress||typeof window>"u"||!this.apiKeys?.ablySubscribe)return;let e=`https://realtime.ably.io/event-stream?channels=aigur-client&v=1.2&key=${this.apiKeys.ablySubscribe}&enveloped=false`,t=new EventSource(e);t.onmessage=o=>{let i=JSON.parse(o.data);i.type==="pipeline:start"?this.triggerListeners(this.onStartListeners):i.type==="pipeline:finish"?this.triggerListeners(this.onFinishListeners):(i.type==="node:start"||i.type==="node:finish")&&this.triggerListeners(this.onProgressListeners,{...i.data,type:i.type})}}triggerListeners(e,...t){for(let o of e.values())o(...t)}async processPipeline(e,t){let o=this.conf.retries??te;try{await this.notifyEvent("pipeline:start"),e.input.parse(t);let i={input:t},s={},c=this.flow.getNodes(),a;for(let r=0;r<c.length;r++){a=this.notifyEvent("node:start",{node:c[r],index:r});let d=0,u=!1;do{d++;try{s=await this.executeAction(c,r,i),i[r]=s,u=!0}catch(f){if(d>o)throw f;await D((this.conf.retryDelayInMs??ne)*d)}}while(!u&&d<=o);await a,await this.notifyEvent("node:finish",{node:c[r],index:r})}return await this.notifyEvent("pipeline:finish"),s}catch(i){throw console.error(i),i}}async executeAction(e,t,o){let{action:i,schema:s,input:c}=e[t],a=k(c,o);return i(a,this.apiKeys)}notifyEvent(e,t){if(!(!this.conf.updateProgress||!this.apiKeys.ablyPublish))return fetch("https://rest.ably.io/channels/aigur-client/messages?enveloped=false ",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Basic ${btoa(this.apiKeys.ablyPublish)}`},body:JSON.stringify({type:e,data:t})})}};var x=require("zod"),K=require("eventsource-parser");var m=require("zod"),I=m.z.object({prompt:m.z.string(),model:m.z.string().default("text-davinci-003"),temperature:m.z.number().default(.7),top_p:m.z.number().default(1),frequency_penalty:m.z.number().default(0),presence_penalty:m.z.number().default(0),max_tokens:m.z.number().default(200),n:m.z.number().default(1)}),oe=m.z.object({text:m.z.string()});async function ie(n,e){let t=I.parse(n);return{text:(await(await fetch("https://api.openai.com/v1/completions",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.openai}`},method:"POST",body:JSON.stringify(t)})).json()).choices[0]?.text.replace(/^(?:\n)+/gm,"")}}var T={id:"text.prediction.gpt3",schema:{input:I,output:oe},action:ie};var B=I.merge(x.z.object({stream:x.z.literal(!0).optional().default(!0)})),re=x.z.object({stream:x.z.instanceof(globalThis.ReadableStream??Object)});async function ae(n,e){let t=B.parse(n),o=await fetch("https://api.openai.com/v1/completions",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.openai}`},method:"POST",body:JSON.stringify(t)});return{stream:await se(o)}}var M={id:"text.prediction.gpt3.stream",schema:{input:B,output:re},action:ae};async function se(n){let e=new TextEncoder,t=new TextDecoder,o=0;return new ReadableStream({async start(s){function c(r){if(r.type==="event"){let d=r.data;if(d==="[DONE]"){s.close();return}try{let f=JSON.parse(d).choices[0].text;if(o<2&&(f.match(/\n/)||[]).length)return;let y=e.encode(f);s.enqueue(y),o++}catch(u){s.error(u)}}}let a=(0,K.createParser)(c);for await(let r of n.body)a.feed(t.decode(r))}})}var O=require("zod"),F=()=>({id:"output",schema:{input:O.z.object({}),output:O.z.object({})},async action(n){return n}});var g=require("zod"),W=g.z.object({image:g.z.string()}),pe=g.z.object({labels:g.z.array(g.z.string())});async function ue(n,e){let t=W.parse(n),o=`https://vision.googleapis.com/v1/images:annotate?key=${e.googleapis}`,i={requests:[{image:{content:t.image},features:[{type:"LABEL_DETECTION"}]}]};return{labels:(await(await fetch(o,{method:"POST",body:JSON.stringify(i)})).json()).responses[0].labelAnnotations.map(a=>a.description)}}var z={id:"image.labeling.googleVision",schema:{input:W,output:pe},action:ue};var p=require("zod"),Z=p.z.object({text_prompts:p.z.array(p.z.object({text:p.z.string(),weight:p.z.number().min(-1).max(1).optional().default(1)})).refine(n=>n.length>0,"Must have at least one text prompt"),model:p.z.enum(["stable-diffusion-v1-5","stable-diffusion-512-v2-1","stable-diffusion-768-v2-1"]).optional().default("stable-diffusion-v1-5"),clip_guidance_preset:p.z.enum(["NONE","FAST_BLUE","FAST_GREEN","SIMPLE","SLOW","SLOWER","SLOWEST"]).optional(),steps:p.z.number().optional(),sampler:p.z.enum(["one","two"]).optional(),samples:p.z.number().optional(),cfg_scale:p.z.number().optional(),seed:p.z.number().optional(),height:p.z.number().min(128).optional().refine(n=>typeof n<"u"?n%64===0:!0,"Must be a multiple of 64"),width:p.z.number().min(128).optional().refine(n=>typeof n<"u"?n%64===0:!0,"Must be a multiple of 64")}),ce=p.z.object({result:p.z.instanceof(ArrayBuffer)});async function de(n,e){let t=Z.parse(n),o=`https://api.stability.ai/v1beta/generation/${t.model}/text-to-image`;return{result:await(await fetch(o,{headers:{"Content-Type":"application/json",Accept:"image/png",Authorization:e.stability},method:"POST",body:JSON.stringify(t)})).arrayBuffer()}}var j={id:"image.textToImage.stableDiffusion.stability",schema:{input:Z,output:ce},action:de};var S=require("zod"),_=S.z.object({text:S.z.string(),amount:S.z.number().optional().default(8)}),me=S.z.object({text:S.z.string()}),le={"Colonial-style home":"Colonial, traditional, classic, historical, timeless, elegant, regal, grand, spacious, architectural, wood-framed, brick-exterior, symmetrical, gabled roof, columns, portico, fireplace, formal, ornate, landscaped".split(", "),"High-end penthouse apartment":"Luxury, high-end, penthouse, apartment, upscale, contemporary, modern, stylish, designer, elite, high-rise, rooftop, panoramic, views, spacious, open-plan, top-floor, amenities, concierge, service, exclusive".split(", ")};function fe(n){return Object.entries(le).map(([e,t])=>`Title: ${e} | ||
Description: ${t.slice(0,n).join(", ")} | ||
`).join(` | ||
`)}async function ye(n){let e=_.parse(n);return{text:`Write a maximum of ${e.amount} keywords in a csv list that describes the following | ||
${fe(e.amount)} | ||
Title: ${e.text} | ||
Description:`}}var E={id:"text.modify.enhanceWithKeywords",schema:{input:_,output:me},action:ye};var h=require("zod"),$=h.z.object({text:h.z.string().or(h.z.array(h.z.string())),modifier:h.z.string()}),he=h.z.object({text:h.z.string()});async function ge(n){let e=$.parse(n);return{text:e.modifier.replace(/\$\(text\)\$/gm,Array.isArray(e.text)?e.text.join(", "):e.text)}}var C={id:"text.modify.simple",schema:{input:$,output:he},action:ge};var N=require("zod"),Se="https://transcribe.whisperapi.com",V=N.z.object({audioUrl:N.z.string().url()}),be=N.z.object({text:N.z.string()});async function xe(n,e){let t=V.parse(n),o=new FormData;o.append("url",t.audioUrl),o.append("language","en"),o.append("fileType","mp3"),o.append("task","transcribe");let i=await fetch(Se,{method:"POST",headers:{contentType:"application/json",Authorization:"Bearer "+e.whisperapi},body:o});if(!i.ok)throw new Error(i.statusText);return{text:(await i.json()).text.trim()}}var U={id:"voice.transcribe.whisper.whisperapi",schema:{input:V,output:be},action:xe};var v=require("zod"),J=v.z.object({string:v.z.string()}),Ne=v.z.object({arrayBuffer:v.z.instanceof(ArrayBuffer)});async function ve(n){let e=J.parse(n);return{arrayBuffer:Uint8Array.from(atob(e.string),o=>o.charCodeAt(0)).buffer}}var R={id:"text.transformation.stringToArrayBuffer",schema:{input:J,output:Ne},action:ve};var l=require("zod"),G=l.z.object({text:l.z.string(),speakingRate:l.z.number().min(.25).max(4).optional().default(1),pitch:l.z.number().min(-20).max(20).optional().default(0),encoding:l.z.enum(["MP3","FLAC","LINEAR16","MULAW","AMR","AMR_WB","OGG_OPUS","SPEEX_WITH_HEADER_BYTE","WEBM_OPUS"]).optional().default("MP3"),voice:l.z.object({language:l.z.string().optional().default("en-US"),name:l.z.enum(["en-US-Standard-A","en-US-Standard-C","en-US-Standard-D","en-US-Standard-E","en-US-Standard-F","en-US-Standard-G","en-US-Standard-H","en-US-Standard-I","en-US-Standard-J","en-US-Studio-M","en-US-Studio-O","en-US-Wavenet-A","en-US-Wavenet-B","en-US-Wavenet-C","en-US-Wavenet-D","en-US-Wavenet-E","en-US-Wavenet-F","en-US-Wavenet-G","en-US-Wavenet-H","en-US-Wavenet-I","en-US-Wavenet-J","en-US-News-K","en-US-News-L","en-US-News-M","en-US-News-N","en-US-Standard-A","en-US-Standard-B","en-US-Standard-C","en-US-Standard-D","en-US-Standard-E","en-US-Standard-F","en-US-Standard-G","en-US-Standard-H","en-US-Standard-I","en-US-Standard-J"]).or(l.z.string()).optional().default("en-US-Neural2-C")}).optional().default({language:"en-US",name:"en-US-Neural2-C"})}),Pe=l.z.object({audio:l.z.string()});async function we(n,e){let t=G.parse(n),o=`https://us-central1-texttospeech.googleapis.com/v1beta1/text:synthesize?key=${e.googleapis}`,i={input:{text:t.text},voice:{languageCode:t.voice.language,name:t.voice.name},audioConfig:{audioEncoding:t.encoding,speakingRate:t.speakingRate,pitch:t.pitch}};return{audio:(await(await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})).json()).audioContent}}var L={id:"voice.textToSpeech.google",schema:{input:G,output:Pe},action:we};var b=class{constructor(e,t){this.input=e;this.nodes=t;this.voice={textToSpeech:{google:this.nodeFactory(L)},transcribe:{whisper:{whisperapi:this.nodeFactory(U)}}};this.text={modify:{enhanceWithKeywords:this.nodeFactory(E),simple:this.nodeFactory(C)},prediction:{gpt3:this.nodeFactory(T),gpt3Stream:this.nodeFactory(M)}};this.image={textToImage:{stableDiffusion:{stability:this.nodeFactory(j)}},labeling:{googleVision:this.nodeFactory(z)}};this.output=this.nodeFactory(F());this.transformation={stringToArrayBuffer:this.nodeFactory(R)}}static create(e){return new b(e,[])}nodeFactory(e){return t=>{let o=this.setPlaceholderValues(this.input.keyof().options,"input"),i=this.nodes.length>0?this.nodes[this.nodes.length-1]:o,s={...e,input:t({nodes:this.nodes,prev:i.output,input:o}),output:e.schema.output.keyof?this.setPlaceholderValues(e.schema.output.keyof().options,this.nodes.length):e.schema.output};return this.nodes.push(s),this}}setPlaceholderValues(e,t){let o={};for(let i of e)o[i]=`$context.${t}.${i}$`;return o}custom(e){return this.nodeFactory(e)}getNodes(){return this.nodes}};var Ie=2,Ae=350,Te=n=>{let{apiKeys:e}=n;return{pipeline:{create:t=>{let o={...t,retries:t.retries??Ie,retryDelayInMs:t.retryDelayInMs??Ae},i=t.flow(new b(t.input,[]));return new w(o,i,e)}}}};0&&(module.exports={createClient}); |
{ | ||
"name": "@aigur/client", | ||
"version": "0.30.0", | ||
"version": "0.30.1", | ||
"description": "", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
60938
1405
3