Text Vision Self-Awareness Module LLM Utility Synthetic Text Data Generator

I saw this youtube video so I’m writing this module that does something similar to what this programmer is doing in this video. I want to post it here to provide inspiration and resources to other developers. I have updated it on 8/20/2023,8/21/2023,8/28/2023,11/30/2023
This is the newest version!! The code below is the old version
(1) AwarenessV2 - Roblox

local aware = {}
local chatmodule=require(script.Parent.ChatModule)
local personalities=require(script.Parent.Personalities)
local interchangephrase={{"and their are","and their is"},}
syntheticdatasynonms={
	{"very close","quite close","extremely close"},
	{"close","near","not far"},
	{"kind of close","pretty near","somewhat near"},

	{" tiny "," mini "," minuscule "},
	{" small "," little "," petite "},

	{" large "," big ","huge"},
	{"gigantic","colossal","massive"},

	{"a few","some","a couple"},
	{"many","numerous","several"},
	{"lots of","tons of","a good number of"},

	{"There is","Over there is"},
	{"I see","I can see"},
	{"Nearby is","Close by is"},

	{"Additionally","Furthermore","Moreover"},
	{"Also","In addition","Plus"},
	{"However","But","Though"},

	{"to the north","northward","to the northern side."},
	{"to the south","southward","to the southern area"},
	{"to the east","eastward","to the eastern side"},

	{"to the west","westward","to the western side"},
	
		{"and their is"
		,"and their exists","and their lies","and their stands","and their remains","and their reside","and their resides"},
	{"Their is"
		,"Their exists","Their lies","Their stands","Their remains","Their reside","Their resides"},
	{"to the current position"}
	



}

ticktime=workspace.GlobalSpells.Tick

local function tablehandler(location)
	-- Get the folder from the workspace
	local tableobj={}
	local mapObjectsFolder = location
	local result=mapObjectsFolder:GetChildren()
	
	return result
end

-- Call the function and assign it to a variable
--ticks=.6 seconds 100 ticks=60seconds 100ticks =1min
tablekeys={

["mapobject"]={{["datatable"]=nil, ["writetime"]=ticktime.Value, ["refreshrate"]=200}, workspace.MapObjects},

["plants"]={{["datatable"]=nil, ["writetime"]=ticktime.Value, ["refreshrate"]=300}, workspace.Plants},

["enemys"]={{["datatable"]=nil, ["writetime0]"]=ticktime.Value, ["refreshrate"]=100}, workspace.Enemys},

["rubble"]={{["datatable"]=nil, ["writetime"]=ticktime.Value, ["refreshrate"]=200}, workspace.Rubble},

["trees"]={{["datatable"]=nil, ["writetime"]=ticktime.Value, ["refreshrate"]=600}, workspace.Trees},

["chests"]={{["datatable"]=nil, ["writetime"]=ticktime.Value, ["refreshrate"]=300}, workspace.Chests},

["grounditems"]={{["datatable"]=nil, ["writetime"]=ticktime.Value, ["refreshrate"]=100}, workspace.GroundItems},

["houses"]={{["datatable"]=nil, ["writetime"]=ticktime.Value, ["refreshrate"]=500}, workspace.Houses},

["players"]={{["datatable"]=nil, ["writetime"]=ticktime.Value, ["refreshrate"]=100}, game.Players},

["dungeons"]={{["datatable"]=nil,["writetime"]=ticktime.Value, ["refreshrate"]=100}, workspace.AmbientAreas},

["npcs"]={{["datatable"]=nil, ["writetime"]=ticktime.Value,["refreshrate"]=100}, workspace.NPCS}

}
--aware.Gettable(Key)

function aware.Gettable(Key)
	if tablekeys[Key] then
		local results,location=tablekeys[Key][1],tablekeys[Key][2]	
		local timer=results["writetime"]
		local refresh=results["refreshrate"]
		local data=results["datatable"]
		if timer+refresh<ticktime.Value and data~=nil then
			return results["datatable"]
		else 
			tablekeys[Key]={{["datatable"]=tablehandler(location), ["writetime"]=ticktime.Value,["refreshrate"]=refresh},location}
			return tablekeys[Key][1]["datatable"]
		end	
	else 
		return nil
	end	
end


function getnearest(list,root,dist,getone,mode)
	local list=list
	local pos=root.Position
	local torso = nil
	local dist = 30
	local temp = nil
	local human = nil
	local temp2 = nil
	local amnt=0
	local scope=nil
	local list=list	
	if list~=nil then
		for x = 1, #list do
			temp2 = list[x]
			if temp2==root.Parent then
				temp=nil
			elseif temp2:IsA("BasePart") then
				temp = temp2
			elseif temp2:IsA("Model") then
				if temp2.PrimaryPart~=nil then
					temp=temp2.PrimaryPart
				else 
					temp=temp2:FindFirstChildOfClass("BasePart")	
				end	
			elseif temp2:IsA("Player") then
				temp=temp2.Character:FindFirstChild("HumanoidRootPart")
			elseif temp2:IsA("Folder") then
				local m=temp2:FindFirstChildOfClass("Model")
				if m then
					temp=m:FindFirstChildOfClass("BasePart")
				end	
				end
			if (temp ~= nil and root~=temp)  then
				if (temp.Position - pos).magnitude < dist then
					amnt=amnt+1
					if mode then torso=temp else torso = temp2 end
					dist = (temp.Position - pos).magnitude
					scope = temp.Size
					if getone==true then
						return torso,scope
					end
				end
			end
		end
	end
	return torso,amnt,scope
end
function aware.nearrubble(root,dist,getone)
	rubble = aware.Gettable("rubble") 
	return getnearest(rubble,root,dist,getone,true)
end
function aware.nearplant(root,dist,getone)
	plants = aware.Gettable("plants")	
	return getnearest(plants,root,dist,getone,true)
end
function aware.neartree(root,dist,getone)
	trees = aware.Gettable("trees")	
	return getnearest(trees,root,dist,getone,true)
end
function aware.nearhouse(root,dist,getone)
	houses = aware.Gettable("houses")	
	return getnearest(houses,root,dist,getone,true)
end
function aware.neardungeons(root,dist,getone)
	dungeons = aware.Gettable("dungeons")
	return getnearest(dungeons,root,dist,getone,true)
end
function aware.nearchest(root,dist,getone)
	chests = aware.Gettable("chests")
	return getnearest(chests,root,dist,getone,true)
end
function aware.nearmapobj(root,dist,getone)
	mapObjects = aware.Gettable("mapobject")	
	return getnearest(mapObjects,root,dist,getone,true)
end
function aware.nearloot(root,dist,getone)
	grounditems = aware.Gettable("grounditems")	
	return getnearest(grounditems,root,dist,getone,true)
end
function aware.nearNPC(root,dist,getone)
	npcs = aware.Gettable("npcs")	
	return getnearest(npcs,root,dist,getone,true)
end
function aware.nearEnemy(root,dist,getone)
	enemys = aware.Gettable("enemys")
	return getnearest(enemys,root,dist,getone,true)
end
function aware.nearplayer(root,dist,getone)
	playerstable = aware.Gettable("players")
	return getnearest(playerstable,root,dist,getone,true)
end

function aware.judgedistance(position, position2, maxDist)

	local distVector = (position - position2).Magnitude

	local judgedDist = {0.2, 0.4, 0.6, 0.8, 1, 1.5, 2} 
	local judgeStrings = {{"very close"}, {"close"}, {"kind of close"},{"not far"}, {"kinda far"}, {"far"}, {"very far"}}

	local index = 1
	local distanceJudge = ""
	repeat
		if distVector <= maxDist * judgedDist[index] then
			if distVector>1 then
				distanceJudge = judgeStrings[index][1]
			else 
				distanceJudge="right here"
			end	
			break
		end
		index = index + 1
	until index > #judgedDist

	-- Get direction
	local dirVector = (position2 - position).Unit -- Unit vector pointing to position2
	local angle = math.atan2(dirVector.Z, dirVector.X) -- Angle in radians
	local dirName = ""
	if distanceJudge~="right here" then
	if angle > math.rad(157.5) or angle < math.rad(-157.5) then
		dirName = "south"
	elseif angle > math.rad(112.5) then 
		dirName = "southwest"
	elseif angle > math.rad(67.5) then
		dirName = "west"
	elseif angle > math.rad(22.5) then
		dirName = "northwest"
	elseif angle > math.rad(-22.5) then
		dirName = "north"
	elseif angle > math.rad(-67.5) then
		dirName = "northeast"
	elseif angle > math.rad(-112.5) then
		dirName = "east"
	else
		dirName = "southeast"
	end
	else dirName = "current position."	
	end
	return distanceJudge,dirName
end

function aware.judgeamnt(amnt,judgestrings)
	local judgedistribution={1,2,3,4,5,6,8}
	local judgestrings={{"a single"},{"a couple"},{"a few"},{"a quartet"},{"several"},{"a bunch"},{"a lot"}}
	local index=1

	repeat
		local distvector=amnt
		if distvector<=judgedistribution[index] then
			return judgestrings[index][1]
		end	
	until index>=#judgedistribution	
end

function aware.judgething(size, bigSize,judgeSizes,judgeStrings)
	local index = 1
	local sizeJudge = ""
	if typeof(size)=="Vector3" then
	for i, judge in ipairs(judgeSizes) do
		if size <= bigSize * judge then
			local sizeJudge2 = judgeStrings[i]
			sizeJudge=sizeJudge2[math.random(1,#sizeJudge)]
			break
		end
		end
	end	
	return sizeJudge
end



function aware.getsurroundingobjects(root,player)
	local closestPlant, numPlants,plantsize = getnearest(plants, root, 40)
	local closestTree, numTrees = getnearest(trees, root, 80) 
	local closestStructure, numStructures,structuresize = getnearest(mapObjects, root, 160)
	local closestEnemy, numEnemies = getnearest(enemys, root, 60)
	local closestNPC, numNPCs = getnearest(npcs, root, 60)
	local closestPlayer, numPlayers = getnearest(playerstable, root, 80)
	local closestRubble, numRubble = getnearest(rubble, root, 20) 
	local closestChest, numChests = getnearest(chests, root, 30)
	local closestGroundItem, numGroundItems = getnearest(grounditems, root, 40)
	local closestHouse, numHouses,housesize = getnearest(houses, root, 100)
	local closestDungeon, numDungeons,dungsize = getnearest(dungeons, root, 200)
	local pos=root.Position
	
	local function describeTrees()
		if numTrees > 1 then
			local treeText
			treeText= aware.judgeamnt(numTrees).." of trees surround the area"
			return treeText			
		end
	end

	local function describePlants()
		if numPlants > 1 then  
			local plantText = aware.judgeamnt(numPlants).." of plants are scattered around"
			return plantText
		end
	end

	local function describeRubble()
		if numRubble > 1 then
			local rubbleText = aware.judgeamnt(numRubble).." of pieces of rubble lay on the ground" 
			return rubbleText
		end
	end

	local function describeEnemies()
		if numEnemies > 1 then
			local enemyText = aware.judgeamnt(numEnemies).." of enemies are lurking nearby"
			return enemyText
		end
	end

	local function describeNPCs()
		if numNPCs > 1 then
			local npcText = aware.judgeamnt(numNPCs).." of strangers are in the area"
			return npcText
		end
	end

	local function describePlayers()
		if numPlayers > 1 then
			local playerText = aware.judgeamnt(numPlayers).." of players are nearby" 
			return playerText
		end
	end

	local function describeChests()
		if numChests > 1 then
			local chestText = aware.judgeamnt(numChests).." of chests are scattered around"
			return chestText
		end
	end

	local function describeGroundItems()
		if numGroundItems > 1 then
			local groundItemText = aware.judgeamnt(numGroundItems).." of items lay on the ground"
			return groundItemText
		end
	end 

	local function describeHouses()
		if numHouses > 1 then
			local houseText = aware.judgeamnt(numHouses).." of houses stand nearby"
			return houseText
		end
	end

	local function describeDungeons()
		local dungeonText = ""
		if numDungeons > 1 then
			local dungeonText = aware.judgeamnt(numDungeons).." of areas around here."
			return dungeonText
		end
	end
	local function describestructures()
		if numStructures > 1 then
			local structureText = aware.judgeamnt(numDungeons).." of interesting places to check out around here."
			return structureText
		end
	end

	local function describeSurroundings(pos)

		
		local descStrings = {}
local opener={"Their are ","I see ","Surrounding us are "}
		local descTrees = describeTrees()
		local descPlants = describePlants()
		local descRubble = describeRubble()
		local descEnemies = describeEnemies()
		local descNPCs = describeNPCs()
		local descPlayers = describePlayers()
		local descChests = describeChests()
		local descGroundItems = describeGroundItems()
		local descHouses = describeHouses()
		local descDungeons = describeDungeons()

		if descTrees then
			table.insert(descStrings, ""..descTrees)
		end
		if descPlants then
			table.insert(descStrings, ""..descPlants)
		end
		if descRubble then
			table.insert(descStrings, ""..descRubble)
		end
		if descEnemies then
			table.insert(descStrings, ""..descEnemies)
		end
		if descNPCs then
			table.insert(descStrings, ""..descNPCs)
		end
		if descPlayers then
			table.insert(descStrings, ""..descPlayers)
		end
		if descChests then
			table.insert(descStrings, ""..descChests)
		end
		if descGroundItems then
			table.insert(descStrings, ""..descGroundItems)
		end
		if descHouses then
			table.insert(descStrings, ""..descHouses)
		end
		if descDungeons then
			table.insert(descStrings, ""..descDungeons)
		end

		-- Remove any nil values
		local finalStrings = {}
		local paragraphstring=""
		for i,str in ipairs(descStrings) do
			if str ~= "" then
				--table.insert(finalStrings, opener[math.random(1,#opener)]..str..".") 
				paragraphstring=paragraphstring..str..", "
			end
		end
		if paragraphstring~="" then
			paragraphstring=opener[math.random(1,#opener)]..paragraphstring.."."
			table.insert(finalStrings,paragraphstring)
		end
		-- Join the strings together

		return finalStrings

	end
	local function describeSurroundings2(pos)
	
		local function describeRubble2(context)

			local rubbleText = ""

			if closestRubble then
				if closestRubble:IsA("BasePart") then
				local dist, dir = aware.judgedistance(pos, closestRubble.Position, 20)
				local size = aware.judgesize(closestRubble.Size,Vector3.new(40,40,40))
					rubbleText = "piece of " ..size.. " rubble is " ..dist.. " to the " ..dir
				end	
			end

			if numRubble > 1 then
				if context==nil then
					return rubbleText,aware.judgeamnt(numRubble).. " of pieces of rubble lay on the ground" 	
				else
					rubbleText = rubbleText .. context.. aware.judgeamnt(numRubble).. " of pieces of rubble lay on the ground"
				end	
			end

			return rubbleText

		end


		local function describeChests2(context)

			local chestText = ""

			if closestChest then
				local dist, dir = aware.judgedistance(pos, closestChest.PrimaryPart.Position, 30)
				--local size = aware.judgesize(closestChest.Size)
				chestText = "chest is " ..dist.. " to the " ..dir
			end

			if numChests > 1 then
				if context==nil then
					return chestText,aware.judgeamnt(numChests).." of chests are scattered around" 	
				else
					chestText = chestText .. context .. aware.judgeamnt(numChests).." of chests are scattered around" 
				end
			end	

			return chestText

		end


		local function describeGroundItems2(context)

			local groundItemText = ""

			if closestGroundItem then
				local dist, dir = aware.judgedistance(pos, closestGroundItem.Item:FindFirstChildOfClass("BasePart").Position, 40)
			--	local size = aware.judgesize(closestGroundItem.Size,Vector3.new(40,40,40))
				groundItemText = aware.judgeobject(closestGroundItem)" is " ..dist.. " to the " ..dir
			end

			if numGroundItems > 1 then
				if context==nil then
					return groundItemText,aware.judgeamnt(numGroundItems).." of items lay on the ground"	
				else
					groundItemText = groundItemText .. context .. aware.judgeamnt(numGroundItems).." of items lay on the ground"
				end	
			end

			return groundItemText

		end


		local function describeHouses2(context)

			local houseText = ""

			if closestHouse then
				local dist, dir = aware.judgedistance(pos, closestHouse.Position, 100)
				local size = aware.judgesize(closestHouse.PrimaryPart.Size,Vector3.new(100,100,100))
				houseText = "" ..size.. " house is " ..dist.. " to the " ..dir
			end

			if numHouses > 1 then
				if context==nil then
					return houseText,aware.judgeamnt(numHouses).." of other houses stand nearby"	
				else
					houseText = houseText .. context .. aware.judgeamnt(numHouses).." of other houses stand nearby"
				end
			end	

			return houseText

		end

		local function describestructures2(context)
		
			local dungeonText=""
			if closestStructure then
				local dist, dir = aware.judgedistance(pos, closestStructure.PrimaryPart.Position, 200)
				local size = aware.judgesize(closestStructure.PrimaryPart.Size,Vector3.new(200,100,200))
				dungeonText = aware.judgeobject(closestStructure).." is "..dist.. " to the " ..dir
			end

			if numStructures > 1 then
				if context==nil then
					return dungeonText,aware.judgeamnt(numStructures)" of interesting places to check out around here" 	
				else
					dungeonText = dungeonText .. context..aware.judgeamnt(numStructures)" of interesting places to check out around here" 
				end	
			end
			return dungeonText
		end

		local function describeDungeons2(context)

			local dungeonText = ""

			if closestDungeon then
				local dist, dir = aware.judgedistance(pos, closestDungeon:FindFirstChildOfClass("BasePart").Position, 200)
				local size = aware.judgesize(closestDungeon:FindFirstChildOfClass("BasePart").Size,Vector3.new(360,20,360))
				dungeonText = aware.judgeobject(closestDungeon).." is "..dist.. " to the " ..dir
			end

			if numDungeons > 1 then
				if context==nil then
					return dungeonText,aware.judgeamnt(numDungeons)" of areas around here" 	
				else
					dungeonText = dungeonText .. context..aware.judgeamnt(numDungeons)" of areas around here" 
				end	
			end

			return dungeonText

		end
		local function describeTrees2(context)

			local treeText = ""

			if closestTree then
				local dist, dir = aware.judgedistance(pos, closestTree.PrimaryPart.Position, 160) 
				treeText = aware.judgeobject(closestTree).." is " ..dist.. " to the " ..dir
			end

			if numTrees > 1 then
				if context==nil then
					return treeText, aware.judgeamnt(numTrees).." of other trees surround the area" 	
				else
					treeText = treeText ..context.. aware.judgeamnt(numTrees).." of other trees surround the area"
				end	
			end

			return treeText

		end


		local function describePlants2(context)

			local plantText = ""

			if closestPlant then
				local dist, dir = aware.judgedistance(pos, closestPlant.Position, 40)
				local size = aware.judgesize(closestPlant.Size,Vector3.new(6,10,6))
				plantText =size.. " "..aware.judgeobject(closestPlant).." is " ..dist.. " to the " ..dir
			end

			if numPlants > 1 then
				if context==nil then
					return plantText,  aware.judgeamnt(numPlants).." of other plants are scattered around"	
				else
					plantText = plantText ..context.. aware.judgeamnt(numPlants).." of other plants are scattered around"
				end	
			end

			return plantText

		end


		local function describeEnemies2(context)

			local enemyText = ""

			if closestEnemy then
				local dist, dir = aware.judgedistance(pos, closestEnemy.HumanoidRootPart.Position, 60)
				enemyText = aware.judgeobject(closestEnemy,root.Parent).. " is " ..dist.. " to the " ..dir
			end

			if numEnemies > 1 then
				if context==nil then
					return enemyText,aware.judgeamnt(numEnemies).." enemies are lurking nearby"
				else
					enemyText = enemyText ..context.. aware.judgeamnt(numEnemies).." enemies are lurking nearby"
				end
			end	

			return enemyText

		end

		local function describePlayers2(context)

			local enemyText = ""

			if closestPlayer and closestPlayer~=player then
				local dist, dir = aware.judgedistance(pos, closestPlayer.Character.HumanoidRootPart.Position, 80)
				enemyText = aware.judgeobject(closestPlayer,game.Players:GetPlayerFromCharacter(root.Parent)).. " is " ..dist.. " to the " ..dir
			elseif closestPlayer~=nil and closestPlayer==player then enemyText="I can see you right here"	
			end

			if numPlayers > 1 then
				if context==nil then
					return enemyText,aware.judgeamnt(numPlayers).." of players are nearby" 	
				else
					enemyText = enemyText ..context.. aware.judgeamnt(numPlayers).." of players are nearby" 
				end	
			end

			return enemyText

		end
		local function describeNPCs2(context)

			local npcText = ""

			if closestNPC then
				local dist, dir = aware.judgedistance(pos, closestNPC.HumanoidRootPart.Position, 80)
				npcText = aware.judgeobject(closestNPC,root.Parent)..
					" is " ..dist.. " to the " 
						..dir
			end

			if numNPCs > 1 then
				if context==nil then
					return npcText,aware.judgeamnt(numNPCs).." of strangers are in the area"	
				else
					npcText = npcText ..context.. aware.judgeamnt(numNPCs).." strangers are in the area"
				end	
			end

			return npcText

		end
		local descStrings = {}
		local opener={"I can see that, ","I notice that, ","I observe that, ","It is apparent that, "}
		local descTrees2 = describeTrees2(", and their are ")
		local descPlants2 = describePlants2(", and their are ")
		local descRubble2 = describeRubble2(", and their are ")
		local descEnemies2 = describeEnemies2(", and their are ")
		local descNPCs2 = describeNPCs2(", and their are ")
		local descPlayers2 = describePlayers2(", and their are ")
		local descChests2 = describeChests2(", and their are ")
		local descGroundItems2 = describeGroundItems2(", and their are ")
		local descHouses2 = describeHouses2(", and their are ")
		local descDungeons2 = describeDungeons2(", and their are ")
		if root.Parent:FindFirstChild("Humanoid") then
			local Person=root.Parent.Humanoid.DisplayName
			local selfrecognition= "I am "..Person.."."
			local Greetings=personalities.CallPersonality(Person)
			
			table.insert(descStrings, selfrecognition)	
		end	
		if descTrees2~="" then
			table.insert(descStrings, ""..descTrees2)
		end
		if descPlants2~="" then
			table.insert(descStrings, ""..descPlants2)
		end
		if descRubble2~="" then
			table.insert(descStrings, ""..descRubble2)
		end
		if descEnemies2~="" then
			table.insert(descStrings, ""..descEnemies2)
		end
		if descNPCs2~="" then
			table.insert(descStrings, ""..descNPCs2)
		end
		if descPlayers2~="" then
			table.insert(descStrings, ""..descPlayers2)
		end
		if descChests2~="" then
			table.insert(descStrings, ""..descChests2)
		end
		if descGroundItems2~="" then
			table.insert(descStrings, ""..descGroundItems2)
		end
		if descHouses2~="" then
			table.insert(descStrings, ""..descHouses2)
		end
		if descDungeons2~="" then
			table.insert(descStrings, ""..descDungeons2)
		end


		local descStrings2 = {}
		local tre,tree2=describeTrees2()
		local plan,plan2=describePlants2()
		local rub,rub2=describeRubble2()
		local enem,enem2=describeEnemies2()
		local npc1,npc2=describeNPCs2()
		local plr1,plr2=describePlayers2()
		local chest,ches2=describeChests2()
		local g1,g2=describeGroundItems2()
		local hous,house=describeHouses2()
		local dung,dungeon=describeDungeons2()
		local struc,struc2=describestructures2()

		local function DetermineGoal()
			local interest=""
			
			if closestPlayer~="" then
				if player~=plr1 then
					
					interest=interest.." I can see that "..plr1..""	
				elseif player~=nil then
					local plrinter={
						"I see you before me now,",
						"I'm aware of your presence,",
						"You stand before me,",
						"I see you now,",
						"You are in my sight,",
						"I have you in my view,",
						"You are here with me,",
						"I can sense you,",
						"I can spot you "..player.Name..",",
							""..player.Name.." is that your name?",
							"I can see you "..player.Name..",",
							""..player.Name..", I know who you are.",
							"I can sense you "..player.Name..",",
							""..player.Name..", do you know who I am?",
							"I can observe you "..player.Name..",",
							""..player.Name..", what are you doing here?",
							"I can notice you "..player.Name..",",
							""..player.Name..", do you have a purpose here?"
					}

					interest=interest..plrinter[chatmodule.mathrandom(1,#plrinter)]
				end	
			end
			if enem~="" then
				local enemt={" Watch out, there is "..enem.."",
					""..enem.."",
					" There is "..enem.."",
					" I notice "..enem.."",
					" I believe there is "..enem.."",
					" Be careful, "..enem.."",
					" I see "..enem.."",
					" I suspect there is "..enem.."",
					" Beware of "..enem.."."
				}

				interest=interest..enemt[chatmodule.mathrandom(1,#enemt)]		
			end
			if npc1~="" then
				if closestPlayer and interest~="" then
					interest=interest..", and"
				end 
				local npct={" I'm aware of my peer, "..aware.judgeobject(closestNPC)..",",
					" "..npc1.."",
					" I notice that "..npc1.."",
					" I can see my colleague, "..aware.judgeobject(closestNPC)..",",
					" "..npc1.." is in my view.",
					" I observe that "..npc1.."",
					" I can sense my ally, "..aware.judgeobject(closestNPC)..",",
					" "..npc1.." is within my range.",
					" I detect that "..npc1.."",
					" I can spot another adventurer, "..aware.judgeobject(closestNPC)..","
				}

				
				interest=interest..npct[chatmodule.mathrandom(1,#npct)]
			end
			if closestDungeon then
				--if not npc1 and interest~="" then
				--	interest=interest..", we "
				--else 
				--	interest=interest.." We "
				--end
				if interest~="" then
					interest=interest.."."
				end
				local strut={" We are in a place called "..aware.judgeobject(closestDungeon).."",
					"I believe, we are in an area called "..aware.judgeobject(closestDungeon).."",
					""..aware.judgeobject(closestDungeon).."... I believe that's what this place is called",
					"This area is called "..aware.judgeobject(closestDungeon).."",
					"If I recall correctly this place is known as "..aware.judgeobject(closestDungeon).."",
					"If my navigation skills are correct, this area is called "..aware.judgeobject(closestDungeon).."",
					"This place is known as "..aware.judgeobject(closestDungeon).."",
					""..aware.judgeobject(closestDungeon).." is the name of this land.",
					"According to my map, this place is called "..aware.judgeobject(closestDungeon).."",
					"I have heard that this place is called "..aware.judgeobject(closestDungeon).."",
					""..aware.judgeobject(closestDungeon)..", that's the name of this place.",
					"This location is called "..aware.judgeobject(closestDungeon).."",
					"From what I know, this place is known as "..aware.judgeobject(closestDungeon).."",
					"My compass tells me that this area is called "..aware.judgeobject(closestDungeon).."",
					"I have learned that this place is called "..aware.judgeobject(closestDungeon).."",
					""..aware.judgeobject(closestDungeon)..", that's the name of this area.",
					"This spot is called "..aware.judgeobject(closestDungeon).."",
					"Based on my information, this place is known as "..aware.judgeobject(closestDungeon).."",
					"My guidebook says that this area is called "..aware.judgeobject(closestDungeon).."",
					"I have been told that this place is called "..aware.judgeobject(closestDungeon)..""}

				interest=interest..strut[chatmodule.mathrandom(1,#strut)]
				
			end
			if struc~="" then
				if interest~="" then
					interest=interest.."."
				end
				interest=interest.." Their is a "..struc
			end
			if chest~="" then
				if interest~="" then
					interest=interest.."."
				end
				interest=interest.." I notice a "..chest..""
			end
			if g1~="" then
				if interest~="" then
					interest=interest..","
				end
				interest=interest..g1
			end
			if hous~="" then
				if struc and interest~="" then
					interest=interest.."."
				end
				interest=interest.." I can see a "..hous..""
			end
			if tree2 then
				if interest~="" then
					interest=chatmodule.randomizeString(interest..". Additionally, t")
				else 
					interest=interest.."T"
				end
				interest=interest.."heir are "..tree2
			end
			if plan2 then
				if interest~="" then
					interest=interest..","
				else
					interest=interest.." Their are "
				end
				interest=interest..""..plan2..""
			end
			if interest~="" then
				interest=interest.."."	
			end
			return interest
		end
		--example 	enemyText = aware.judgeobject(closestEnemy.Parent).. " is " ..dist.. " to the " ..dir
		--return enemyText,aware.judgeamnt(numPlayers).." of players are nearby" 	
		--	enemyText = enemyText ..context.. aware.judgeamnt(numPlayers).." of players are nearby" 

		-- Remove any nil values
		local finalStrings = {}
		local paragraphstring=""
		for i,str in ipairs(descStrings) do
			if str ~= "" then
				table.insert(finalStrings, opener[math.random(1,#opener)]..str..".") 
				if i~=#descStrings then
					paragraphstring=paragraphstring..str..", "
				else 
					paragraphstring=paragraphstring..str..". "
				end	
			end
		end
		table.insert(finalStrings,DetermineGoal())
		if paragraphstring~="" then
			paragraphstring=paragraphstring.."."
			table.insert(finalStrings,paragraphstring)
		end
		-- Join the strings together

		return finalStrings

	end
	local d1=describeSurroundings(pos)
	local d2=describeSurroundings2(pos)
	local syntheticdata= function()
		for i,str in ipairs(d1) do
		if str ~= "" then
				table.insert(d2, str) 
			--paragraphstring=paragraphstring..str..", "
		end
		end
		for i,str in ipairs(d2) do
			if str ~= "" then
				d2[i]=chatmodule.randomizeStringLight(str,syntheticdatasynonms)
				--paragraphstring=paragraphstring..str..", "
			end
		end
		
		return d2
	end
	
	return syntheticdata(),closestEnemy
	
	--,
	--{
	--	closestPlant = closestPlant,  
	--	numPlants = numPlants,
	--	plantsize = plantsize,

	--	closestTree = closestTree,
	--	numTrees = numTrees,

	--	closestStructure = closestStructure,
	--	numStructures = numStructures,
	--	structuresize = structuresize,

	--	closestEnemy = closestEnemy,
	--	numEnemies = numEnemies, 

	--	closestNPC = closestNPC,
	--	numNPCs = numNPCs,

	--	closestPlayer = closestPlayer,
	--	numPlayers = numPlayers,

	--	closestRubble = closestRubble,
	--	numRubble = numRubble,

	--	closestChest = closestChest,
	--	numChests = numChests,

	--	closestGroundItem = closestGroundItem, 
	--	numGroundItems = numGroundItems,

	--	closestHouse = closestHouse,
	--	numHouses = numHouses,
	--	housesize,

	--	closestDungeon = closestDungeon,
	--	numDungeons = numDungeons,
	--	dungsize = dungsize
	--}
end

return aware










Also, this is the video that inspired this!
This is a old video of my AI in Action!

I’m currently using this with Zephyr 7b with a experiment to inject the system message with the awareness! It’s been very successful!

Some updates to this library is that it is very optimized and can be very useful for tracking objects in your game! I personally use this as a easy module for getting nearest objects and to describe the surroundings to inject into the system message of a LLM
Here’s an example of code used to inject AI with the awareness

function cm.ZephyrStory(person,personal,Playername,quer)
-- Define the API URL and the authorization header
local API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
local headers = {Authorization = bearer}

-- Define the HttpService
local HttpService = game:GetService("HttpService")

-- Define a function that takes an input and queries the model
local function queryModel(input)
    -- Create a payload table with the input
    local payload = {inputs = input}
    -- Encode the payload table into a JSON string
    local payloadJSON = HttpService:JSONEncode(payload)
    -- Send a POST request to the API URL with the header and the payload
    local response = HttpService:PostAsync(API_URL, payloadJSON, Enum.HttpContentType.ApplicationJson, false, headers)
    -- Decode the response into a table
    print(response)
 --  local responseTable = HttpService:JSONDecode(response)
    -- Return the response table
    return response --Get JSON res[pmse]
end
local personality=personal[1]
local awarobserve=personal[2]
-- Test the function with an example input
local input = "<|system|>\n You are a roleplaying as a "..personality..", you are charismatic and friendly, your name is "..person..". You have a avatar and you are the brain. "..awarobserve.."</s>\n<|"..Playername.."|>\n"..quer.."</s>\n<|assistant|>"
local output = queryModel(input)
print(output)

--local str=format_response(output[1].generated_text)
--print(str)
--local outputtabl=cm.extractDialogue(str)
-- Print the output

return output --parseConversation(str)
end
42 Likes

That’s not even a neural network, let alone an AI. It’s just a bunch of if-else statements.

23 Likes

This is pretty interesting, but I don’t see myself using it anytime soon.

9 Likes

Lmao This is not an AI this is a algorithm that tells the AI what it sees by constructing strings. This information could be passed to an AI. like it was in the youtube video I’ve shown . This allows the NPC to make observations of its surroundings. I’m using it for my luau chatbot that also uses AI. It’s just a method template and the code is not complete. But it’s a good start for anyone wishing to pursue a similar project.

7 Likes

Self-aware AI means conscious & sentient intelligence. As of now, this ability is only reserved to humans.

This script isn’t self-aware, nor is it AI. It can’t do anything than fulfilling the existing tasks. Want to describe something in the environment that’s not covered by the if-statements (while perceived by the ‘senses’ of the NPC)? This script can’t.

9 Likes

Did you know that monkeys can be self aware they pass the test.

7 Likes

Well, that’s an insane amount of if statements and variable declarations to a point that practically nobody will ever bother to read the code. Can’t judge because I aint reading that pain.

6 Likes

you guys are soo naive. We are talking about giving a ROBLOX AI the ability to have a text input of it’s surroundings. This is how the guy in the youtube video provided input to the AI. If you are not working on an AI project you wouldn’t have a clue what to do with this perhaps. You can criticize but I doubt you could conceptualize an algorithm that turns data of a objects surroundings into text data. The thing is nobody asked you for your negative opinion. You may be clueless on the subject but you are foolish to come at me like that.
I don’t even care if you use this or not. It’s for my AI project and I’m just sharing resources. Someone searching how to make an AI self aware will find this post in the future perhaps and find this as a useful framework in providing the logical framework to turn surroundings into a descriptive string.
For example you could use a module like this to provide the player with text based hints. An output for the enemies would be. “Their is a weak Darkness Juggernaut lurking to the northwest, and a lot of other enemies are lurking around” or “We are on the huge Island of Athens, their is a small Staff Shop to the northwest.” So the possibilities are pretty expansive. The simple trick would be to determine the points of interest to get a string describing a variety of scenarios.
Lol so if you don’t see how cool that is you can be off with yourself and take your attitude elsewhere. This is just a resource not something to be criticized by the loud minority concerning whatever nonsense you said.

6 Likes

To be self aware an AI must be aware of its surroundings. You show me your AI project and how it works then you let me know what you think of this module. Because I think it’s funny how you know nothing yet decide to tout your opinion this is literally the type of string constructing algorithm to describe to a large language model what it sees. I would like to reiterate I do not care for your negative opinions, you are likely clueless and do not really know what you are talking about.

My responses coming off condescending because the only ones who decided to say anything where the negative people and they are not even making good arguments. Research the topic and provide informed input. This is how you would send surroundings information to an AI model. You can ask it to find a point of interest from the surroundings and make decisions based on that. My chatbot has the abilities to perform action commands from strings. So I could interpret the output to make the AI chatbot self aware by giving it the ability to make autonomous decisions based on its environment.

For example perhaps the AI decides to pick up an apple on the ground because it has some arbitrary hunger or thirst stat. The AIs decisions could also be influenced by survival and input from its surroundings. This is not a common implementation of a large language model but it would be very interesting to give the AI human goals. Like what literal universities have published on Automonous agents.This script is a strong concept for other developers as it provides a structured way to construct a description of the chatbots surroundings.
You could use raycasting and project a ray from only the front of the AI if you wish to only get what it would see in front of it.

For example if you were making a AI character who was a reactive NPC that made dialogue. You could send a message to the model describing the surroundings. Then the model can respond to that input of the world with their character like in that youtube video but within the confines of ROBLOX studio.

self-a·ware·ness

[ˌselfəˈwernəs]

NOUN

  1. conscious knowledge of one’s own character, feelings, motives, and desires:

“the process can be painful but it leads to greater self-awareness”

Also, I updated the code I shared to not include the NPC description algorithm because it is too lengthy and tailored to my custom NPC combat algorithm
But I will post it here just because.

function aware.DescribeNPC(Char)
	local MagicID=Char:FindFirstChild("MagicID")
	if MagicID~=nil then
		local fly=""
		local Aggression=""
		local AttackVector=""
		local Barrier=""
		local Buffs=""
		local BaseHealth=""
		local BaseMagicDMG=""
		local BaseRangeDMG=""
		local BaseMeleeDMG=""
		local CanBeFrozen=""
		local ChangeStyles=""
		local Cooldown=""
		local Cost=""
		local CostMax=""
		local Cure=""
		local Description=""
		local Dodge=""
		local Element=""
		local Element2=""
		local Element3=""
		local Hide=""
		local Level=""
		local MainStyle=""
		local Multiply=""
		local Paralyze=""
		local Poison=""
		local Power=""
		local Prayer=""
		local ProtectFromStyle=""
		local Recoil=""
		local Range=""
		local Parasite=""
		local Species=""
		local Teleport=""
		local Transform=""
		local Weakness=""
		local rating=0
		--construct a long combined string of the above local strings.

		if MagicID:GetAttribute("Aggression")==1 then
			Aggression="aggressive, "
			rating=rating+1
		end
		if MagicID:GetAttribute("Fly")==true then
			fly="can Fly, "
			rating=rating+1
		end
		if MagicID:GetAttribute("Barrier")==true then
			Barrier="uses Barrier, "
			rating=rating+1
		end
		if MagicID:GetAttribute("Buffs")==true then
			Buffs="uses Buffs, "
			rating=rating+1
		end
		if MagicID:GetAttribute("Multiply")==true then
			Buffs="uses Multiply, "
			rating=rating+1
		end
		if MagicID:GetAttribute("ChangeStyle")==true then
			ChangeStyles="melee and magic user, "
			rating=rating+1
			BaseMagicDMG="base Magic damage is"..tostring(MagicID:GetAttribute("BaseMagicDMG"))..", "
			BaseMagicDMG="base Melee damage is"..tostring(MagicID:GetAttribute("BaseMeleeDMG"))..", "
			if MagicID:GetAttribute("AttackVector3")~=nil then
				AttackVector="melee range is"..tostring(MagicID:GetAttribute("AttackVector3"))..", "
			end	
		elseif MagicID:GetAttribute("ChangeStyle")==false then
			if	MagicID:GetAttribute("MainStyles")~=nil then
				if MagicID:GetAttribute("MainStyles")==1 then
					MainStyle="uses Melee only, "
					if MagicID:GetAttribute("AttackVector3")~=nil then
						AttackVector="melee range:"..tostring(MagicID:GetAttribute("AttackVector3"))..", "
					end	
				elseif MagicID:GetAttribute("MainStyles")==2 then
					MainStyle="uses Magic only, "
				elseif MagicID:GetAttribute("MainStyles")==3 then
					MainStyle="uses Range only, "
				end
			end
		end	

		if MagicID:GetAttribute("BaseHealth")~=nil then
			local hpr=Char.Humanoid.MaxHealth/100
			rating=rating+hpr
			BaseHealth="base health "..tostring(MagicID:GetAttribute("BaseHealth"))..", "
		end
		--write code to complete above context
		if MagicID:GetAttribute("CanBeFrozen")==false then
			CanBeFrozen="cannot be frozen, "
			rating=rating+1
		end
		if MagicID:GetAttribute("Cooldown")~=nil then
			Cooldown="it's cooldown is "..tostring(MagicID:GetAttribute("Cooldown"))..", "
			rating=rating+(5-MagicID:GetAttribute("Cooldown"))
		end
		if MagicID:GetAttribute("Cost")~=nil then
			Cost="it's action cost is "..tostring(MagicID:GetAttribute("Cost"))..", "
			rating=rating+1
		end
		if MagicID:GetAttribute("CostMax")~=nil then
			CostMax="It's max power is"..tostring(MagicID:GetAttribute("CostMax"))..", "
		end
		if MagicID:GetAttribute("Cure")==true then
			Cure="can Heal, "
			rating=rating+1
		end
		if MagicID:GetAttribute("Description")~=nil then
			Description=MagicID:GetAttribute("Description")..""
		end
		if MagicID:GetAttribute("Dodge")==true then
			Dodge="can Dodge, "
			rating=rating+1
		end
		if MagicID:GetAttribute("Teleport")==true then
			Teleport="can Teleport, "
			rating=rating+1
		end
		if MagicID:GetAttribute("Transform")==true then
			Transform="can Transform, "
			rating=rating+1
		end

		if MagicID:GetAttribute("Element")~=nil and MagicID:GetAttribute("Element")~="" then
			Element="uses "..MagicID:GetAttribute("Element")
			rating=rating+1
			if MagicID:GetAttribute("Element2")~="" and MagicID:GetAttribute("Element2")~=nil then
				Element2=","..MagicID:GetAttribute("Element2")
				rating=rating+1
			end
			if MagicID:GetAttribute("Element3")~="" and MagicID:GetAttribute("Element2")~=nil then
				Element3="and "..MagicID:GetAttribute("Element3")
				rating=rating+1
			end	
		end
		if MagicID:GetAttribute("Parasite")==true then
			Parasite=", it's parasitic"
			rating=rating+1
		end
		if MagicID:GetAttribute("Poison")==true then
			Poison=", it's poisonous"
			rating=rating+1
		end

		if MagicID:GetAttribute("Prayer")==true then
			Prayer="uses Prayers"
			rating=rating+1
		elseif 	MagicID:GetAttribute("ProtectFromStyle")==1 then
			rating=rating+1
			ProtectFromStyle=", strong against Melee"
		elseif		MagicID:GetAttribute("ProtectFromStyle")==2 then
			rating=rating+1
			ProtectFromStyle=", strong against Magic"
		elseif		MagicID:GetAttribute("ProtectFromStyle")==3 then
			rating=rating+1
			ProtectFromStyle=", strong against Range"
		end
		--Power="Power Multiplier:" MagicID:GetAttribute("Power")
		--Range=""
		if MagicID:GetAttribute("Recoil")==true then
			rating=rating+1
			Recoil="hurts to touch, "
		end
		rating=rating+tonumber(Level)
		--write rest of code for above context	
		return Description..Element..Element2..
			Element3.." magic. It's "..Level.." "..ChangeStyles..MainStyle..Cooldown..fly..Aggression..Barrier..Buffs..BaseHealth..
			BaseMagicDMG..BaseRangeDMG..BaseMeleeDMG..AttackVector..CanBeFrozen..
			Cost..CostMax..Cure..Dodge..
			Hide..Multiply..Paralyze..Poison..Power..
			Prayer..ProtectFromStyle..".",aware.judgepower(rating,25)
	else return "",nil	
	end
end
8 Likes

This topic is related to my main topic! Which has a module that you can input search queries based on a database.
For example if you are looking for an Apple. You can search a list of strings and return a string describing an Apple.
This is a part of a multi-model AI-chatbot Agent I’m working on. When it’s done I will be releasing some sort of open-source version that has a simple framework to work from for other developers.
I have recently released a new ChatModule which is the most recent version of the main algorithms that powers the bots ability to compare input robustly with a database of strings and provide output. It also can solve basic geometry for example “What is the circumference of a circle with a radius of 4?” and worded algebra problems “If I have 4 groups of 5 how many do I have in total?” output= “4*5=20”.

The way it’s designed is to answer questions with the chatbot using my specific database for my games lore and hints when it can. Then, if it does not know the answer it gets the answer from a variety of APIs including wikipedia, How to wiki, conversational AIs that think they are the input personality, and GPT2. It uses zero-shot classification to determine which model to use. It saved all of the data it recieves from the AIs and APIs for that database or specific character. I’m also incorporating more APIs and premium AI models in the future. It’s important to have levels to things like this. It can be visualized like this Chatbot determines the intent based on rules and algorithms if conditions are met then->zero-shot-classification AI to determine the inputs intent->APICall to AI Model or wiki.
Premium architecture would be just be Chatbot Input if any->APICall to AI with specified character and context with user query
Artificially Intelligent Chatbot LUAU Algorithm [Open Source] - Resources / Community Resources - Developer Forum | Roblox

image

6 Likes

image_2023-08-19_133422802

  1. It’s not “Self Aware”, it’s only capable of what it’s allowed to do, true sentience is impossible, you can only simulate it

  2. You literally said it’s an AI

5 Likes

I like the idea. However, it is a bit messy.

4 Likes
  1. Literally didn’t. Title is creating self aware AI. Which you would need a module to tell the AI what it sees.
  2. This constructs a paragraph and database of observations based on space position and time.
    Creating a Self aware AI must include observations of the environment. If the AI were given decisions to make inputing data into language that it can understand is important. Giving the response in string format allows the AI to maintain the context that it is that character and is currently in that point in space surrounded by the environment with the observations.
    3.Based on this information and additional parameters a goal can be derived from the observations.
    for example: Sees a NPC, decide to approach the NPC and interact with other NPC
    see a structure appraoch the structure.
    Be in a specific zone create character input based on the information for example a output string would be “I see the huge Pyramid of Kufu.”

In conclusion this is part of the architecture of creating a simulated self aware AI. Which of course self aware is within the context of the AI in question.
But awareness is knowing what your surroundings are. With current large language models they have been shown to benefit in a story driven or RPG environment when they can make informed decisions based on their surroundings.

6 Likes

Why is everyone mad?
OP did make a self aware AI but not in the way that pleases your definition of what it means to be self aware.
Make this simple for yourselves and avoid explaining your definition of the word AI, as I’m very sure OP meant to call it NPC. It’s just a small miss direction. Honest mistakes can be made.

4 Likes

This is part of my AI project. Which includes artificial intelligence models. If you have a AI that has no information about its surroundings then it cannot make relevant observations of its surroundings.
This algorithm creates artificial data to give AI context about its surroundings. If you were involved in working with Language Models this concept is easy to grasp and quite important within the restrictions of ROBLOx’s coding environment.

3 Likes

I’ll take ur words for it.
I’d like to suggest that it may seem better to add an API example and write a showcase for others to glance at. It may help them avoid looking at your work and discard it like the people above.

2 Likes

This is a module not an API. But if you are interested in how to make API calls to different AI models you can check out huggingface also here is a link and code example of a GPT2 API call. GPT2 can be used to complete a sentence. For example say you input “I see the huge Island of Sparta” GPT2 would finish the sentence.

function GPT2(inputText)
-- Import the HttpService


-- Define the API URL
--local API_URL = "https://api-inference.huggingface.co/models/gpt2"
	local API_URL ="https://api-inference.huggingface.co/models/gpt2-large"
-- Define the headers with your authorization key
local headers = {
	["Authorization"] = Bearerkey
}

-- Define a function to query the API with a payload
local function query(payload)
	-- Encode the payload as a JSON string
	local jsonPayload = HttpService:JSONEncode(payload)
	-- Send a POST request to the API URL with the headers and the payload
	local response = HttpService:PostAsync(API_URL, jsonPayload, Enum.HttpContentType.ApplicationJson, false, headers)
	-- Decode the response as a JSON table
	local jsonResponse = HttpService:JSONDecode(response)
	-- Return the JSON table
	return jsonResponse
end
	
-- Define your input text
	
-- Query the API with your input text as the inputs field
	local output = query({
		["inputs"] = inputText,
		["max_length"] = 200, -- This will limit the output to 150 tokens
		["num_return_sequences"] =1, -- This will generate only one output
		["temperature"] = 2-- This will increase the randomness of the output
	})
	
	-- or
	local generatedText = output[1]["generated_text"]
print(output)
	-- Print the string
	return generatedText
-- Print the output

end

Also here is an example of using a model that includes context and its previous responses.

function conversationaldialogue(str,context,responses,model)
	local model=model
	local API_URL
	if model==nil then
		model=math.random(1,2)
	end
	if model==1 then
	 API_URL = "https://api-inference.huggingface.co/models/microsoft/GODEL-v1_1-base-seq2seq"
	else
	-- Define the URL and the headers for the request
	 API_URL = "https://api-inference.huggingface.co/models/facebook/blenderbot-400M-distill"
	end
	
	local headers = {
		["Authorization"] = Bearerkey,
		--["Content-Type"] = "application/json"
	}
table.insert(context,str)
	-- Define the payload for the request
	local payload = {
		inputs = {
			past_user_inputs = context,
			generated_responses = responses
		}
	}

	-- Encode the payload as a JSON string
	local payloadJSON = HttpService:JSONEncode(payload)

	-- Send the request and get the response
	local success, response = pcall(function()
		return HttpService:RequestAsync({
			Url = API_URL,
			Method = "POST",
			Headers = headers,
			Body = payloadJSON
		})
	end)

	-- Check if the request was successful
	if success then
		-- Decode the response as a JSON table
		local responseJSON = HttpService:JSONDecode(response.Body)

		-- Check if the response has a generated_text
		if responseJSON.generated_text then
			-- Print the generated_text
			return	(responseJSON.generated_text)
		else
			-- Print an error message
			print(response)
			return nil
		end
	else
		-- Print an error message
		print("Request failed: " .. response)
		return nil
	end

end

If you are interested in learning more about implementing language models to your project their are various amounts of information about this.

I’m not afraid to share my documentation about how I structure my API call function. I organized them all into functions and use zero-shot-classification to determin which api to use.

local ChatAPI={
	--inputstring
	["Gpt2"]=ac["Gpt2"],--Call with strings
	["GptS"]=ac["GptS"],--
	["Gps2"]=ac["Gps2"],--
	["Inst"]=ac["Inst"],--Callwithstrings
	["Philo"]=ac["Philo"],--use keyword
	--inputstring
	--
	["Conv"]=ac["Conv"],--Call with str, npcstr and character
	["Conv2"]=ac["Conv2"],--Call with str and npcstr
	["Conv3"]=ac["Conv3"],--call with str,npcstr and context
}
local EduAPI = {
	["Wik"] = ac["Wik"], -- Call with phrase/word
	["Wik2"] = ac["Wik2"], -- Call with phrase/word
	["Sbok"] = ac["Sbok"], -- Call with title
}
local UtilAPI = {
	["KeyP"] = ac["KeyP"], -- KeyTerms for Query
	["Classify"] = ac["Classify"], -- (str,labels)
	["CompSen"] = ac["CompSen"], -- call with string
	["Paraphrase"] = ac["Paraphrase"], -- Rephrase sentence string
	["CorPunct"] = ac["CorPunct"], -- call with string
	["Summary"] = ac["Summary"], -- call with string
}
local Utilfunc={
	["len"]=checklength,
	["getsent"]=get_sentences,
	["countsent"]=countsentences,
	["RDS"]=removeDuplicateSentences,
	["RRDS"]=removerandomizeDuplicateSentences,
	["checkdupl"]=check_duplicate--string,pattern
}
local ac={
	--Conversational
	["Gpt2"]=GPT2,--Call with strings
	["GptS"]=AddFlair,--
	["Gps2"]=CreatorFlair,--
	["Conv"]=conversationaldialogue,--
	["Inst"]=Instruct,--Callwithstrings
	["Philo"]=buildquotes,--use keyword
	--Conversational
	--Educational
	["Wik"]=SearchWikipedia,--Call with phrase/word
	["Wik2"]=SearchWikipedia2,
	["Sbok"]=search_book,
	--Educational
	--Utility
	["KeyP"]=extract_keyphrases,--KeyTerms for Query
	["Classify"]=zero_shot_classification,--(str,labels)
	["CompSen"]=check_and_generate_punctuation,--call with string
	["Paraphrase"]=ExtractCoreInformation,--Rephrase sentence string,
	["CorPunct"]=CorrectPunctuationCapitalization,--call with string	
	["Summary"]=summarrization,--call with string,
	--Utility
	["NorrisJoke"]=ExtractjokeTable,--returns joke	
}
local Labelfuncs={
	["search query"]=ac["Wik2"],	
	["philosophical question"]=ac["Philo"],
	["loving"]=LovelyResponse,
	["greetings"]=ExpandResponse,
	["adventurerous"]=StoryResponse,
	["personal question"]=ChatwithAIInit,--str,context,responses,model)
	["asking for instructions"]=ChatwithAICont,
}

local Labeldb={
	["search query"]=wikidb,
	["philosophical question"]=script.Parent.Parent.ChatModule.Philosophy,
	["loving"]=nil,
	["greetings"]=nil,
	["adventurerous"]=nil,
	["personal question"]=nil,--str,context,responses,model)
	["asking for instructions"]=nil,
}


local labels = {"philosophical question","adventurous","loving","greetings","personal question","asking for instructions","search query"}
function onRemote(player,str,apicall,context,responses,person,NPCstr)
	
	if apicall=="Follow" then
		dfg.FollowMe(str,player.Character.HumanoidRootPart)
	elseif apicall=="savedata" then
		SaveNPCData(str)	
	elseif apicall=="deletedata" then
		DeleteNPCData(str)
	elseif apicall=="go away" then
		dfg.GoAway(str,player.Character.HumanoidRootPart)	
	elseif apicall=="search" then	
	if str~=nil then
	if wikidb:FindFirstChild(str)==nil and str~=nil and apicall=="search" then
				CallWikiApi(str)
				datachanged=true
--	elseif apicall=="joke" then
	--	token.Value=CreateJokeTable()	
			end	
		end
	elseif apicall=="question" and str~=nil and instrucdb:FindFirstChild(str)==nil then
		CallHowToApi(str)
		datachanged=true
	elseif apicall=="classify" and str~=nil and str:match("[%a]")~=nil then
		local highest_score, classify = get_highest_classifier_value (str, labels)
		local response=nil	
		local dir=nil
		if classify=="search query" then
			dir=wikidb
			--response= Labelfuncs[classify](str)	
		elseif classify=="philosophical question" then 
			dir=script.Parent.Chat:FindFirstChild(person)
			if NPCstr==nil then
				NPCstr=person
			end
			--response= Labelfuncs[classify](NPCstr)	
		else
			if NPCstr~=nil then
				table.insert(responses,NPCstr)
			end	
			
			dir=script.Parent.Chat:FindFirstChild(person)
			
			--response=Labelfuncs[classify](str,context,responses)	
		end	
		print(dir)
		print(classify)
		if dir~=nil then
		response=CheckToken(str,dir)
		if response==nil then
		if classify=="search query" then
		response= Labelfuncs[classify](str)	
		elseif classify=="philosophical question" then 
		response= Labelfuncs[classify](NPCstr)	
		else
		response=Labelfuncs[classify](str,context,responses)	
			end	
		else print("Token already exists, check stack for erorr.")	
		end	
		if response~=nil and dir~=nil then
			player.PlayerGui.Chatbot.ServerString.Value=response
			CreateToken(str,response,dir)
			end
		else 
			print("directory is nil "..NPCstr)
			player.PlayerGui.Chatbot.ServerString.Value=""
		end	
	end	
	
end

Here is the zero shot classification API. You input classfication labels and its returns a table of probabilities based on the input string.

function zero_shot_classification (input, labels)
	-- Get the HttpService


	-- Define the URL and the headers for the request
	local API_URL = "https://api-inference.huggingface.co/models/sileod/deberta-v3-base-tasksource-nli"
	local headers = {
		["Authorization"] = Bearerkey, -- Your Hugging Face token
		--["Content-Type"] = "application/json" -- The content type of the request
	}

	-- Define the payload for the request
	local payload = {
		inputs = input, -- The input text to classify
		parameters = {
			candidate_labels = labels -- The candidate labels to choose from
		}
	}

	-- Encode the payload as a JSON string
	local payloadJSON = HttpService:JSONEncode(payload)

	-- Send the request and get the response
	local success, response = pcall(function()
		return HttpService:PostAsync(API_URL, payloadJSON, Enum.HttpContentType.ApplicationJson, false, headers) -- Post the JSON payload to the API URL with the headers
	end)

	-- Check if the request was successful
	if success then
		-- Decode the response as a JSON table
		local responseJSON = HttpService:JSONDecode(response)

		-- Print the scores and labels of the classification
		print("Scores: " .. table.concat(responseJSON.scores, ", "))
		print("Labels: " .. table.concat(responseJSON.labels, ", "))
		return responseJSON.scores,responseJSON.labels
	else
		-- Print an error message
		print("Request failed: " .. response)
	end
end

function get_highest_classifier_value (input, labels)
	-- Call the zero_shot_classification function to get the scores and labels
	local scores, labels = zero_shot_classification (input, labels)

	-- Initialize the variables to store the highest score and label
	local highest_score = -math.huge -- A very small number
	local highest_label = ""

	-- Loop through the scores and labels arrays
	for i = 1, #scores do
		-- Check if the current score is higher than the highest score
		if scores[i] > highest_score then
			-- Update the highest score and label
			highest_score = scores[i]
			highest_label = labels[i]
		end
	end

	-- Return the highest score and label
	return highest_score, highest_label
end
3 Likes

Self-aware can be defined as a character that can think by itself, interact with its surroundings by itself, react or express emotions. All I see in your code is just what you limited it to do. You cannot train it, it is not self aware, and less an AI.

That aside, this is one of the most unformatted and ridiculous code I’ve seen in all of DevForum. Even worse - it looks like that most of this was written by ChatGPT. The source code is straight up unreadable, let alone anyone being able to do anything with it.

Unnecessary functions, unnecessary variable definitions, insane amount of if statements that could’ve been simplified in other methods. Instead of using functions for actual uses you still went with the copy-paste method. Half of your code has ChatGPT comments, the rest is straight up Ctrl+C Ctrl+V. We can do better, let’s say:

  • First, there’s zero need to define insane amounts of variables at the start, just use a table for it. The benefit of using tables is that we can also loop through them, so we don’t create a clutter in the code.
  • Then, you don’t need to define say local element3629 in the start. Just declare it when it exists. Simple!
  • I’m also not sure why you’re using Attributes. Just place all of this in the code. Plus, there’s no need to define your values as “value x is y”, why do you need that??? Like, instead of value = "cannot heal" you’re just wasting a Variable because canHeal = false already implies that the character cannot heal.
  • Also I’m very sure Vector3.magnitude does not exist. It’s Magnitude. Did you even test this?

All it does is check for distances, instances, orientation and objects near it. You cannot call this “self aware”. This is ridiculous. I remind you, AI has the ability to learn by itself, hence why artificial intelligence. We living beings are able to think and process what we perceive, and so does AI, since it’s also an intelligence, albeit not natural. If it can’t learn and put it to use - it’s not AI.

2 Likes

That’s a bit derailed from what I suggested, I’m partly to blame here lol since I called it API.
What I mean is a code example that uses your module in a showcase format. It would be nice to list all the functions one would use in the module. Just to help give an idea to those who come across your work.

But you have said that this is a work in progress, so it’s fair.

Try saying:

This could be better if you do X,Y,Z

Instead of saying:

This is bad because you suck lol