tune-sdk 0.1.13 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/rpc.js CHANGED
@@ -35,8 +35,9 @@ function jsonrpc(params, exports) {
35
35
  }
36
36
  jsonrpc;
37
37
 
38
- function concatU8A(u8arrays) {
39
- var totalLen, res, offset, arr, _i, _ref, _len;
38
+ function concatU8A() {
39
+ var totalLen, res, offset, arr, _i, _i0, _ref, _len;
40
+ var u8arrays = 1 <= arguments.length ? [].slice.call(arguments, 0, _i = arguments.length - 0) : (_i = 0, []);
40
41
  var totalLen;
41
42
  var res;
42
43
  var offset;
@@ -46,8 +47,8 @@ function concatU8A(u8arrays) {
46
47
  res = new Uint8Array(totalLen);
47
48
  offset = 0;
48
49
  _ref = u8arrays;
49
- for (_i = 0, _len = _ref.length; _i < _len; ++_i) {
50
- arr = _ref[_i];
50
+ for (_i0 = 0, _len = _ref.length; _i0 < _len; ++_i0) {
51
+ arr = _ref[_i0];
51
52
  res.set(arr, offset);
52
53
  offset = offset + arr.length;
53
54
  }
@@ -55,11 +56,37 @@ function concatU8A(u8arrays) {
55
56
  }
56
57
  concatU8A;
57
58
 
59
+ function assert(cond, msg) {
60
+ var _ref;
61
+ if (!cond) {
62
+ _ref = undefined;
63
+ throw Error, msg;
64
+ } else {
65
+ _ref = undefined;
66
+ }
67
+ return _ref;
68
+ }
69
+ assert;
70
+
58
71
  function JSONRPC(params, exports) {
59
- var self;
72
+ var debugWriter, self, _ref;
73
+ var debugWriter;
74
+ debugWriter;
60
75
  this.msgId = 1;
61
- this.chunks = [];
62
- this.debug = params.debug;
76
+ if (!params.debug) {
77
+ _ref = (function() {});
78
+ } else if (typeof params.debug === "boolean") {
79
+ _ref = (function() {
80
+ var _i;
81
+ var args = 1 <= arguments.length ? [].slice.call(arguments, 0, _i = arguments.length - 0) : (_i = 0, []);
82
+ return console.error.apply(console, [].concat(args));
83
+ });
84
+ } else if (typeof params.debug === "function") {
85
+ _ref = params.debug;
86
+ } else {
87
+ _ref = undefined;
88
+ }
89
+ this.debug = _ref;
63
90
  this.name = params.name;
64
91
  this.exports = exports || params.exports || {}
65
92
  this.callbacks = {};
@@ -67,35 +94,34 @@ function JSONRPC(params, exports) {
67
94
  this.reader = params.inStream.getReader();
68
95
  this.writer = params.outStream.getWriter();
69
96
  self = this;
70
- this.decoder = new TextDecoder();
71
- assert.ok(params.inStream, "inStream has to be defined and be a ReadableStream");
72
- assert.ok(params.outStream, "outStream has to be defined and be a WritableStream");
97
+ assert(params.inStream, "inStream has to be defined and be a ReadableStream");
98
+ assert(params.outStream, "outStream has to be defined and be a WritableStream");
73
99
  async function pump() {
74
- var res, value, done, buf, newlineIdx, line, msg, cb, iter, err, m, r, chunk, _res, _ref, _ref0;
100
+ var res, value, done, newlineIdx, line, msg, cb, iter, err, _ref0, _err;
75
101
  var res;
76
- res = await self.reader.read();
77
102
  var value;
78
103
  var done;
104
+ res = await self.reader.read();
79
105
  value = res.value;
80
106
  done = res.done;
81
107
  if (done) return;
82
- self.chunks.push(value);
83
- var buf;
84
108
  var newlineIdx;
85
- buf = concatU8A(self.chunks);
86
109
  newlineIdx = 0;
87
- while (-1 !== (newlineIdx = buf.indexOf(10))) {
110
+ self.buf = (self.buf ? concatU8A(self.buf, value) : value);
111
+ while (-1 !== (newlineIdx = self.buf.indexOf(10))) {
88
112
  var line;
89
- line = self.decoder.decode(buf.subarray(0, newlineIdx));
90
- buf = buf.subarray(newlineIdx + 1);
91
- self.chunks = [buf];
92
- if (self.debug) console.log(self.name, line);
113
+ line = new TextDecoder().decode(self.buf.subarray(0, newlineIdx));
114
+ self.buf = self.buf.subarray(newlineIdx + 1);
115
+ self.debug(self.name, "<==", line);
93
116
  var msg;
94
- msg = JSON.parse(line);
95
- if (!msg.id) {
96
- console.log("message has no id, skipping", msg);
97
- continue;
117
+ try {
118
+ _ref0 = JSON.parse(line);
119
+ } catch (_err) {
120
+ self.debug(self.name, " cant parse json: ", line);
121
+ _ref0 = {}
98
122
  }
123
+ msg = _ref0;
124
+ if (!msg.id) continue;
99
125
  var cb;
100
126
  var iter;
101
127
  cb = self.callbacks[msg.id];
@@ -125,30 +151,33 @@ function JSONRPC(params, exports) {
125
151
  if (!self.exports[msg.method]) {
126
152
  self._error(msg.id, "method not found: " + msg.method);
127
153
  continue;
128
- }
129
- var m;
130
- var r;
131
- var chunk;
132
- m = msg;
133
- r = undefined;
134
- chunk = {};
135
- try {
136
- r = await self.exports[m.method](msg.params, msg.stream);
137
- if (((typeof r !== 'undefined') && !!r[Symbol.asyncIterator])) {
138
- _res = [];
139
- while (!chunk.done) {
140
- chunk = await r.next();
141
- if (chunk.err) throw chunk.err;
142
- if (typeof(_ref = !!chunk.value ? self._result(m.id, chunk.value, chunk.done) : undefined) !== 'undefined') _res.push(_ref);
143
- }
144
- _ref0 = _res;
145
- } else {
146
- _ref0 = self._result(m.id, r, true);
154
+ }(function(m, r, chunk) {
155
+ var _ref1;
156
+ try {
157
+ _ref1 = self.exports[m.method](msg.params, msg.stream)
158
+ .then((async function(r) {
159
+ var _res, _ref1, _ref2;
160
+ if (((typeof r !== 'undefined') && !!r[Symbol.asyncIterator])) {
161
+ _res = [];
162
+ while (!chunk.done) {
163
+ chunk = await r.next();
164
+ if (chunk.err) throw chunk.err;
165
+ if (typeof(_ref1 = (!!chunk.value ? self._result(m.id, chunk.value, chunk.done) : undefined)) !== 'undefined') _res.push(_ref1);
166
+ }
167
+ _ref2 = _res;
168
+ } else {
169
+ _ref2 = self._result(m.id, r, true);
170
+ }
171
+ return _ref2;
172
+ }))
173
+ .catch((function(e) {
174
+ return self._error(m.id, e.message, e.stack);
175
+ }));
176
+ } catch (e) {
177
+ _ref1 = self._error(m.id, e.message, e.stack);
147
178
  }
148
- _ref0;
149
- } catch (e) {
150
- self._error(m.id, e.message, e.stack);
151
- }
179
+ return _ref1;
180
+ })(msg, undefined, {});
152
181
  }
153
182
  }
154
183
  return pump();
@@ -164,6 +193,7 @@ JSONRPC.prototype._write = (async function(payload) {
164
193
  var data;
165
194
  encoder = new TextEncoder();
166
195
  data = encoder.encode(JSON.stringify(payload) + "\n");
196
+ this.debug(this.name, "==>", JSON.stringify(payload));
167
197
  return await this.writer.write(data);
168
198
  });
169
199
  JSONRPC.prototype._error = (function(msgId, message, stack) {
@@ -208,4 +238,21 @@ JSONRPC.prototype._call = (async function(method, params, stream) {
208
238
  }));
209
239
  return (self.iterators[msgId] = new AsyncIter());
210
240
  });
241
+
242
+ function _once(cond, body) {
243
+ return new Promise((function(resolve, reject) {
244
+ function handler() {
245
+ var _ref;
246
+ try {
247
+ _ref = cond() ? resolve(body()) : setTimeout(handler, 10);
248
+ } catch (err) {
249
+ _ref = reject(err);
250
+ }
251
+ return _ref;
252
+ }
253
+ setTimeout(handler, 10);
254
+ return "";
255
+ }));
256
+ }
257
+ _once;
211
258
  exports.jsonrpc = jsonrpc;
package/dist/tune.js CHANGED
@@ -1057,11 +1057,19 @@ Context.prototype.clone = (function() {
1057
1057
  return res;
1058
1058
  });
1059
1059
  Context.prototype.use = (function(middleware) {
1060
- return ((middleware.name === "write") ? this.ws.push(middleware) : this.ms.push(middleware));
1060
+ var _ref;
1061
+ if ((typeof middleware !== "function")) {
1062
+ _ref = undefined;
1063
+ throw Error(tpl("middleware {} is not a function", util.inspect(middleware)));
1064
+ } else {
1065
+ _ref = ((middleware.name === "write") ? this.ws.push(middleware) : this.ms.push(middleware));
1066
+ }
1067
+ return _ref;
1061
1068
  });
1062
- Context.prototype.resolve = (async function(name, args) {
1069
+ async function resolve(ctx, name, args, middlewares) {
1063
1070
  var i, output, match, type, result, res, md;
1064
- if (!this.ms.length) return;
1071
+ middlewares = middlewares || ctx.ms;
1072
+ if (!middlewares.length) return;
1065
1073
  var i;
1066
1074
  var output;
1067
1075
  var match;
@@ -1074,10 +1082,10 @@ Context.prototype.resolve = (async function(name, args) {
1074
1082
  type = (((typeof args !== "undefined") && (args !== null) && !Number.isNaN(args) && (typeof args.type !== "undefined") && (args.type !== null) && !Number.isNaN(args.type)) ? args.type : (((typeof "any" !== "undefined") && ("any" !== null) && !Number.isNaN("any")) ? "any" : undefined));
1075
1083
  result = ((output === "all") ? [] : undefined);
1076
1084
  res = undefined;
1077
- while (i < this.ms.length) {
1085
+ while (i < middlewares.length) {
1078
1086
  var md;
1079
- md = this.ms[i];
1080
- res = await md.call(this, name, {
1087
+ md = middlewares[i];
1088
+ res = await md.call(ctx, name, {
1081
1089
  output: output,
1082
1090
  match: match,
1083
1091
  type: type
@@ -1106,6 +1114,10 @@ Context.prototype.resolve = (async function(name, args) {
1106
1114
  i++;
1107
1115
  }
1108
1116
  return result;
1117
+ }
1118
+ resolve;
1119
+ Context.prototype.resolve = (async function(name, args) {
1120
+ return resolve(this, name, args);
1109
1121
  });
1110
1122
  Context.prototype.text2run = (function(text, opts) {
1111
1123
  return text2run(text, this, opts);
@@ -1760,7 +1772,7 @@ function ast2payload(ast) {
1760
1772
  }))
1761
1773
  .map((function(item) {
1762
1774
  item.content = item.nodes.reduce((function(memo, node) {
1763
- var lastNode, _ref;
1775
+ var lastStack, lastNode, _ref;
1764
1776
  if ((node.type === "image")) {
1765
1777
  if ((typeof memo === "string")) memo = Array({
1766
1778
  type: "text",
@@ -1808,6 +1820,10 @@ function ast2payload(ast) {
1808
1820
  text: node.value
1809
1821
  });
1810
1822
  }
1823
+ } else {
1824
+ var lastStack;
1825
+ lastStack = node.stack["slice"](-1)[0];
1826
+ throw new TuneError(tpl("unknown node type '{type}' for '{name}'", node), (((typeof lastStack !== "undefined") && (lastStack !== null) && !Number.isNaN(lastStack) && (typeof lastStack.filename !== "undefined") && (lastStack.filename !== null) && !Number.isNaN(lastStack.filename)) ? lastStack.filename : undefined), (((typeof lastStack !== "undefined") && (lastStack !== null) && !Number.isNaN(lastStack) && (typeof lastStack.row !== "undefined") && (lastStack.row !== null) && !Number.isNaN(lastStack.row)) ? lastStack.row : undefined), (((typeof lastStack !== "undefined") && (lastStack !== null) && !Number.isNaN(lastStack) && (typeof lastStack.col !== "undefined") && (lastStack.col !== null) && !Number.isNaN(lastStack.col)) ? lastStack.col : undefined), node.stack);
1811
1827
  }
1812
1828
  return memo;
1813
1829
  }), "");
@@ -2099,45 +2115,95 @@ function text2run(text, ctx, opts) {
2099
2115
  }
2100
2116
  text2run;
2101
2117
  async function file2run(args, params, ctx) {
2102
- var lctx, uext, node, text, res, longFormatRegex, response, _ref;
2118
+ var lctx, text, stop, node, response, res, r, chunk, itergeDPeG9, _ref;
2103
2119
  var lctx;
2104
2120
  lctx = ctx.clone();
2105
2121
  lctx.ms.unshift(envmd(params));
2106
- var uext;
2107
- uext = "";
2122
+ var text;
2123
+ var stop;
2124
+ text = args.text;
2125
+ stop = (((typeof args !== "undefined") && (args !== null) && !Number.isNaN(args) && (typeof args.stop !== "undefined") && (args.stop !== null) && !Number.isNaN(args.stop)) ? args.stop : (((typeof "assistant" !== "undefined") && ("assistant" !== null) && !Number.isNaN("assistant")) ? "assistant" : undefined));
2108
2126
  if (args.filename) {
2109
2127
  node = await ctx.resolve(args.filename);
2110
- if (node) {
2111
- lctx.stack.push(node);
2112
- text = await node.read();
2113
- }
2128
+ if (node) lctx.stack.push(node);
2129
+ if ((node && !text)) text = await node.read();
2130
+ if ((!node && !text)) throw new TuneError(tpl("'{}' not found", args.filename));
2114
2131
  }
2115
2132
  if ((!text && args.system)) text = tpl("system:\n{system}", args);
2116
2133
  if (args.user) text += tpl("\nuser:\n{user}", args);
2117
- var res;
2118
- res = await lctx.text2run(text, {
2119
- stop: (((typeof args !== "undefined") && (args !== null) && !Number.isNaN(args) && (typeof args.stop !== "undefined") && (args.stop !== null) && !Number.isNaN(args.stop)) ? args.stop : (((typeof "assistant" !== "undefined") && ("assistant" !== null) && !Number.isNaN("assistant")) ? "assistant" : undefined))
2120
- });
2121
- if ((args.filename && (((typeof args !== "undefined") && (args !== null) && !Number.isNaN(args) && (typeof args.save !== "undefined") && (args.save !== null) && !Number.isNaN(args.save)) ? args.save : undefined))) {
2122
- var longFormatRegex;
2123
- longFormatRegex = /^(system|user|tool_call|tool_result|assistant|error):/;
2124
- await ctx.write(args.filename, text + "\n" + msg2text(res, longFormatRegex.test(text)));
2125
- }
2126
2134
  var response;
2127
2135
  response = (((typeof args !== "undefined") && (args !== null) && !Number.isNaN(args) && (typeof args.response !== "undefined") && (args.response !== null) && !Number.isNaN(args.response)) ? args.response : (((typeof "content" !== "undefined") && ("content" !== null) && !Number.isNaN("content")) ? "content" : undefined));
2128
- switch (response) {
2129
- case "content":
2130
- _ref = res["slice"](-1)[0].content;
2131
- break;
2132
- case "json":
2133
- _ref = JSON.parse(res["slice"](-1)[0].content);
2134
- break;
2135
- case "messages":
2136
- _ref = res;
2137
- break;
2138
- default:
2136
+
2137
+ function transformOutput(res) {
2138
+ var _ref;
2139
+ switch (response) {
2140
+ case "content":
2141
+ _ref = res["slice"](-1)[0].content;
2142
+ break;
2143
+ case "json":
2144
+ _ref = JSON.parse(res["slice"](-1)[0].content);
2145
+ break;
2146
+ case "messages":
2147
+ _ref = res;
2148
+ break;
2149
+ case "chat":
2150
+ _ref = msg2text(res, true);
2151
+ break;
2152
+ default:
2153
+ _ref = undefined;
2154
+ throw new TuneError(tpl("Invalid response type '{}'", response));
2155
+ }
2156
+ return _ref;
2157
+ }
2158
+ transformOutput;
2159
+ async function save() {
2160
+ var longFormatRegex, _ref;
2161
+ if ((args.filename && (((typeof args !== "undefined") && (args !== null) && !Number.isNaN(args) && (typeof args.save !== "undefined") && (args.save !== null) && !Number.isNaN(args.save)) ? args.save : undefined))) {
2162
+ var longFormatRegex;
2163
+ longFormatRegex = /^(system|user|tool_call|tool_result|assistant|error):/;
2164
+ _ref = await ctx.write(args.filename, text + "\n" + msg2text(res, longFormatRegex.test(text)));
2165
+ } else {
2139
2166
  _ref = undefined;
2140
- throw new TuneError(tpl("Invalid response type '{}'", response));
2167
+ }
2168
+ return _ref;
2169
+ }
2170
+ save;
2171
+ if (!args.stream) {
2172
+ var res;
2173
+ res = await lctx.text2run(text, {
2174
+ stop: stop
2175
+ });
2176
+ await save();
2177
+ _ref = transformOutput(res);
2178
+ } else {
2179
+ r = await lctx.text2run(text, {
2180
+ stop: stop,
2181
+ stream: true
2182
+ });
2183
+ chunk = {};
2184
+ itergeDPeG9 = new AsyncIter();
2185
+ (async function($lastRes) {
2186
+ var _ref;
2187
+ try {
2188
+ while (!chunk.done) {
2189
+ chunk = await r.next();
2190
+ res = (chunk.value || "");
2191
+ if (chunk.done) await save();
2192
+ $lastRes = transformOutput(res) || $lastRes;
2193
+ itergeDPeG9.result = {
2194
+ value: $lastRes
2195
+ }
2196
+ }
2197
+ _ref = itergeDPeG9.result = {
2198
+ value: $lastRes,
2199
+ done: true
2200
+ }
2201
+ } catch (e) {
2202
+ _ref = (itergeDPeG9.err = e);
2203
+ }
2204
+ return _ref;
2205
+ })();
2206
+ _ref = itergeDPeG9;
2141
2207
  }
2142
2208
  return _ref;
2143
2209
  }
@@ -2414,4 +2480,5 @@ exports.text2payload = text2payload;
2414
2480
  exports.payload2http = payload2http;
2415
2481
  exports.envmd = envmd;
2416
2482
  exports.unescape = unescape;
2417
- exports.escape = escape;
2483
+ exports.escape = escape;
2484
+ exports.resolve = resolve;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tune-sdk",
3
- "version": "0.1.13",
4
- "description": "tune - your everyday LLM toolkit.",
3
+ "version": "0.2.2",
4
+ "description": "tune - LLM chat in text file",
5
5
  "main": "dist/tune.js",
6
6
  "module": "dist/tune.mjs",
7
7
  "bin": "bin/cli.js",
@@ -12,6 +12,12 @@
12
12
  },
13
13
  "./fsctx": {
14
14
  "require": "./dist/fsctx.js"
15
+ },
16
+ "./cli": {
17
+ "require": "./dist/cli.js"
18
+ },
19
+ "./rpc": {
20
+ "require": "./dist/rpc.js"
15
21
  }
16
22
  },
17
23
  "keywords": [
@@ -1,6 +1,9 @@
1
1
  import path from 'path';
2
2
 
3
3
  export default async function json_format(node, args, ctx) {
4
+ if (!node) {
5
+ return
6
+ }
4
7
  let response_format = { "type": "json_object" }
5
8
  if (args.trim()) {
6
9
 
package/tools/log.proc.js CHANGED
@@ -1,12 +1,15 @@
1
1
  const fs = require("fs")
2
- module.exports = async (node, args, ctx) => {
3
- const newNode = Object.assign({}, node);
4
- newNode.exec = async function(payload, ctx) {
2
+ const path = require("path")
3
+
4
+ module.exports = async (node, args, ctx) => ({
5
+ ...node,
6
+ exec: async function(payload, ctx) {
5
7
  const res = await node.exec(payload, ctx)
6
8
  const body = JSON.parse(res.body)
7
9
  payload = {...res, body};
8
- fs.writeFileSync(args.trim() || "log.json", JSON.stringify(payload, null, " "));
10
+ const filename = args.trim() || "log.json"
11
+ const content = path.extname(filename) == ".chat" ? ctx.msg2text(payload.body.messages, true) : JSON.stringify(payload, null, " ")
12
+ fs.writeFileSync(filename, content);
9
13
  return res
10
14
  }
11
- return newNode
12
- }
15
+ })
@@ -1,5 +1,5 @@
1
1
  {
2
- "description": "Process and generate messages based on input parameters and file context",
2
+ "description": "this tool sends a message to another ai chat as 'user' role, result of the tool is an 'assistant' reply",
3
3
  "parameters": {
4
4
  "type": "object",
5
5
  "properties": {
@@ -9,11 +9,11 @@
9
9
  },
10
10
  "system": {
11
11
  "type": "string",
12
- "description": "Filename that contains system prompt, used once when filename is empty"
12
+ "description": "Filename that contains system prompt, required once at the beginning of simulation"
13
13
  },
14
14
  "text": {
15
15
  "type": "string",
16
- "description": "User input message to process"
16
+ "description": "User message to send"
17
17
  }
18
18
  },
19
19
  "required": ["filename", "text"]
@@ -0,0 +1,13 @@
1
+ {
2
+ "description": "Execute a nushell command",
3
+ "parameters": {
4
+ "type": "object",
5
+ "properties": {
6
+ "text": {
7
+ "type": "string",
8
+ "description": "The nushell command to execute"
9
+ }
10
+ },
11
+ "required": ["text"]
12
+ }
13
+ }
@@ -0,0 +1,14 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import util from 'node:util'
3
+
4
+ export default async function nu({ text }) {
5
+ let result = ""
6
+ try {
7
+ result = spawnSync("nu",
8
+ ["-c", text, "--error-style", "plain"],
9
+ { encoding: "utf8", shell: false })
10
+ } catch (e) {
11
+ result = e.stderr + e.stdout
12
+ }
13
+ return (result.stdout || result.stderr || "").replaceAll("@", "\\@");
14
+ }
@@ -0,0 +1,41 @@
1
+ {
2
+ "description": "Fetch audio from Yandex's TTS",
3
+ "parameters": {
4
+ "type": "object",
5
+ "properties": {
6
+ "text": {
7
+ "type": "string",
8
+ "description": "Text input to convert to speech. + Set stress/accent e.g. 'h+ello'\nSpecify context-dependent pause: <[small]>, allowed: tiny, small, medium, large, huge\nHighlight emcented]> or **emphasized word**"
9
+ },
10
+ "voice": {
11
+ "type": "string",
12
+ "enum": [ "alena-neutral", "alena-good",
13
+ "filipp",
14
+ "ermil-neutral", "ermil-good",
15
+ "jane-neutral", "jane-good", "jane-evil",
16
+ "omazh-neutral", "omazh-evil",
17
+ "zahar-neutral", "zahar-good",
18
+ "dasha-neutral", "dasha-good", "dasha-friendly",
19
+ "julia-neutral", "julia-strict",
20
+ "lera-neutral", "lera-friendly",
21
+ "masha-good", "masha-strict", "masha-friendly",
22
+ "marina-neutral", "marina-whisper", "marina-friendly",
23
+ "alexander-neutral", "alexander-good",
24
+ "kirill-neutral", "kirill-strict", "kirill-good",
25
+ "anton-neutral", "anton-good",
26
+ "madi_ru",
27
+ "saule_ru-neutral", "saule_ru-strict", "saule_ru-whisper",
28
+ "zamira_ru-neutral", "zamira_ru-strict", "zamira_ru-friendly",
29
+ "zhanar_ru-neutral", "zhanar_ru-strict", "zhanar_ru-friendly",
30
+ "yulduz_ru-neutral", "yulduz_ru-strict", "yulduz_ru-friendly", "yulduz_ru-whisper"
31
+ ],
32
+ "description": "Voice type to use for TTS"
33
+ },
34
+ "filename": {
35
+ "type": "string",
36
+ "description": "wav filename to save the audio to"
37
+ }
38
+ },
39
+ "required": ["text", "voice", "filename"]
40
+ }
41
+ }
@@ -0,0 +1,31 @@
1
+ import fs from 'fs';
2
+ export default async function yandexTTS({ text, voice, filename }, ctx) {
3
+ const key = await ctx.read("YC_TOKEN");
4
+ const folderId = await ctx.read("YC_FOLDER_ID")
5
+ const [v, r] = voice.split("-")
6
+ const hints = [{ voice: v}]
7
+ if (r) {
8
+ hints.push({ role: r})
9
+ }
10
+ const response = await fetch("https://tts.api.cloud.yandex.net/tts/v3/utteranceSynthesis", {
11
+ method: "POST",
12
+ headers: {
13
+ "Authorization": `Bearer ${key}`,
14
+ "x-folder-id": folderId,
15
+ "Content-Type": "application/json",
16
+ },
17
+ body: JSON.stringify({
18
+ text,
19
+ hints
20
+ }),
21
+ });
22
+
23
+
24
+ if (!response.ok) {
25
+ const { error } = await response.json()
26
+ throw new Error(`Error: ${response.status} ${response.statusText}\n${error.message}`);
27
+ }
28
+ const result = await response.json()
29
+ await ctx.write(filename, Buffer.from(result.result.audioChunk.data, 'base64'));
30
+ return "speech generated"
31
+ }
@@ -1,34 +0,0 @@
1
- const { createProviderContext } = require("./llm-utils");
2
-
3
- async function fetchAnthropicModels(apiKey) {
4
- const res = await fetch("https://api.anthropic.com/v1/models", {
5
- headers: {
6
- "x-api-key": apiKey,
7
- "anthropic-version": "2023-06-01"
8
- }
9
- });
10
-
11
- if (!res.ok) throw new Error(`Error: ${res.status} ${res.statusText}`);
12
-
13
- const content = await res.json();
14
- return content.data;
15
- }
16
-
17
- module.exports = createProviderContext("anthropic", {
18
- apiKeyEnv: "ANTHROPIC_KEY",
19
- apiModelFetcher: fetchAnthropicModels,
20
- createExecFunction: (model, payload, key) => {
21
- return {
22
- url: "https://api.anthropic.com/v1/chat/completions",
23
- method: "POST",
24
- headers: {
25
- "content-type": "application/json",
26
- authorization: `Bearer ${key}`,
27
- },
28
- body: JSON.stringify({
29
- model: model.id,
30
- ...payload,
31
- }),
32
- };
33
- }
34
- });
@@ -1,49 +0,0 @@
1
- const { createProviderContext } = require("./llm-utils");
2
-
3
- async function fetchGeminiModels(apiKey) {
4
- const res = await fetch(
5
- `https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}&pageSize=200`,
6
- );
7
-
8
- if (!res.ok) throw new Error(`Error: ${res.status} ${res.statusText}`);
9
-
10
- const content = await res.json();
11
- content.models.forEach(model => {
12
- model.id = model.name.split("/")[1]
13
- })
14
- return content.models;
15
- }
16
-
17
- module.exports = createProviderContext("gemini", {
18
- apiKeyEnv: "GEMINI_KEY",
19
- apiModelFetcher: fetchGeminiModels,
20
- //modelMatcher: (name) => name.indexOf("google/") === 0,
21
- // modelFilter: (models, name, args) => {
22
- // const shortName = name.split("/")[1];
23
- // return models
24
- // .map((item) => ({ ...item, shortName: item.name.split("/")[1] }))
25
- // .filter((item) => item.shortName === shortName);
26
- // },
27
- createExecFunction: (model, payload, key) => {
28
- // google does not like content to be null
29
- payload.messages.forEach((message) => {
30
- if (message.content === null) {
31
- message.content = [];
32
- }
33
- });
34
-
35
- return {
36
- url: "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
37
- method: "POST",
38
- headers: {
39
- "content-type": "application/json",
40
- authorization: `Bearer ${key}`,
41
- },
42
- body: JSON.stringify({
43
- model: model.shortName || model.name.split("/")[1],
44
- ...payload,
45
- messages: payload.messages.filter(msg => msg.role !== 'comment'),
46
- }),
47
- };
48
- }
49
- });