extends VBoxContainer


# Agent for hosting commands
var agent:Agent 

# The output stream for the agent
var currentOutput:RichTextLabel

# Called when the node enters the scene tree for the first time.
func _ready():
	print("starting")
	agent = (get_parent().model as GodotRWKV).createAgent() as Agent
	
	# system prompt
	var systemprompt = "Message to Assistant:\nYou are a chatbot designed to irritate the user even when being helpful."
	
	# Insert the system prompt into agent memory
	agent.add_context(systemprompt)
	
	# Set stop sequences, agent will stop generating if it sees any of these as outputs
	agent.set_stop_sequences(["\n\n", "User:"])
	
	# create visual indicator of chat record
	var message = RichTextLabel.new()
	message.add_text(systemprompt)
	message.fit_content = true
	
	# add system prompt to chat log
	$ChatLogContainer/ChatLog.add_child(message)
	
	# Initialize agent output
	currentOutput = RichTextLabel.new()
	currentOutput.fit_content = true
	
	# add output stream to chatlog
	$ChatLogContainer/ChatLog.add_child(currentOutput)
	
	
	# add 
	
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	
	# set the output stream to agent current memory
	currentOutput.text = agent.get_context()
	
	# see if generation finished
	if agent.get_max_queued_tokens() == 0:
		$InputFields/Input.visible=true
		if Input.is_action_just_pressed("ui_text_newline"):
			# get raw user input
			var rawinput = $InputFields/Input.text
			
			# Create user input chat log
			var userlog =  RichTextLabel.new()
			userlog.fit_content = true
			
			# Set userlog text
			userlog.text = rawinput
			
			# add to chat log
			$ChatLogContainer/ChatLog.add_child(userlog)
			
			# Initialize a new agent output
			currentOutput = RichTextLabel.new()
			currentOutput.fit_content = true
			
			# add output stream to chatlog
			$ChatLogContainer/ChatLog.add_child(currentOutput)
			
			# format the user input
			var input = "\n\nUser:\n"+rawinput+"\n\nAssistant:\n"
			
			# Add it to agent memory
			agent.add_context(input)
			
			# set the max amount of tokens to generate
			agent.generate(100)
			
	else:
		# if input not allowed, hide the input field to empty and hide it
		$InputFields/Input.visible=false
		$InputFields/Input.text = ""
