
 const omnis_calls = await globalThis.loadModule("omnis_calls");
 import OpenAI_Conversation from "./OpenAI_Conversation.mjs";
 
 const mConversations = [];

 /**
	* Implement all of your publicly accessible methods in methodMap.
	*/
 const methodMap = {
 
	beginConversation: function(param, response) {

		const {model, apiKey, systemPrompt} = param;
		
		const conversation = new OpenAI_Conversation(apiKey, systemPrompt, model);
		mConversations.push(conversation);

		return conversation.ident;
	},

	sendPrompt: async function(param, response) {
		const {conversationID, prompt, throttleTime} = param;

		const conversation = mConversations.find( (it) => it.ident === conversationID);
		if (!conversation) 
			throw new Error(`No conversation with ID ${conversationID}`);

		let buffer = "";
		let timeout = null;
		let finished = false;
		const result = await conversation.sendPrompt(prompt, (content) => {
			buffer += content;
			if (!timeout) {
				timeout = setTimeout( () => {
					omnis_calls.sendEvent(buffer, response);
					buffer = "";
					timeout = null;
				}, throttleTime || 100);
			}
		});

		if (timeout) {
			clearTimeout(timeout);
			timeout = null;
		}
		
		// if there's leftover buffer after the stream ends, flush it immediately
		if (buffer) {
			omnis_calls.sendEvent(buffer, response);
			buffer = "";
		}

		omnis_calls.sendResponse(result, response);
	},

	endConversation: function(param) {
		const {conversationID} = param;

		const index = mConversations.findIndex( (it) => it.ident === conversationID);
		if (index === -1) 
			throw new Error(`No conversation with ID ${conversationID}`);

		mConversations.splice(index, 1);
	}

 };
 
 // omnis_calls.omnisModuleDefaultExport returns an object suitable for your default export.
 // You must pass it your methodMap object.
 export default omnis_calls.omnisModuleDefaultExport(methodMap);