|
| 1 | +const { PassThrough } = require("stream"); |
| 2 | +const BaseService = require("../../services/BaseService"); |
| 3 | +const { TypedValue } = require("../../services/drivers/meta/Runtime"); |
| 4 | +const { nou } = require("../../util/langutil"); |
| 5 | + |
| 6 | +class TogetherAIService extends BaseService { |
| 7 | + static MODULES = { |
| 8 | + ['together-ai']: require('together-ai'), |
| 9 | + kv: globalThis.kv, |
| 10 | + uuidv4: require('uuid').v4, |
| 11 | + } |
| 12 | + |
| 13 | + async _init () { |
| 14 | + const require = this.require; |
| 15 | + const Together = require('together-ai'); |
| 16 | + this.together = new Together({ |
| 17 | + apiKey: this.config.apiKey |
| 18 | + }); |
| 19 | + this.kvkey = this.modules.uuidv4(); |
| 20 | + debugger; |
| 21 | + } |
| 22 | + |
| 23 | + static IMPLEMENTS = { |
| 24 | + ['puter-chat-completion']: { |
| 25 | + async complete ({ messages, stream, model }) { |
| 26 | + console.log('model?', model); |
| 27 | + const completion = await this.together.chat.completions.create({ |
| 28 | + model: model ?? |
| 29 | + 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo', |
| 30 | + messages: messages, |
| 31 | + stream, |
| 32 | + }); |
| 33 | + |
| 34 | + if ( stream ) { |
| 35 | + const stream = new PassThrough(); |
| 36 | + const retval = new TypedValue({ |
| 37 | + $: 'stream', |
| 38 | + content_type: 'application/x-ndjson', |
| 39 | + chunked: true, |
| 40 | + }, stream); |
| 41 | + (async () => { |
| 42 | + for await ( const chunk of completion ) { |
| 43 | + console.log('IT IS THIS STRING', chunk); |
| 44 | + if ( chunk.choices.length < 1 ) continue; |
| 45 | + if ( chunk.choices[0].finish_reason ) { |
| 46 | + stream.end(); |
| 47 | + break; |
| 48 | + } |
| 49 | + if ( nou(chunk.choices[0].delta.content) ) continue; |
| 50 | + const str = JSON.stringify({ |
| 51 | + text: chunk.choices[0].delta.content |
| 52 | + }); |
| 53 | + stream.write(str + '\n'); |
| 54 | + } |
| 55 | + })(); |
| 56 | + return retval; |
| 57 | + } |
| 58 | + |
| 59 | + return completion.choices[0]; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +module.exports = { |
| 66 | + TogetherAIService, |
| 67 | +}; |
0 commit comments