Package: llmstatemachine
Large Language Model State Machine (llmstatemachine)Introductionllmstatemachine is a library for creating agents with GPT-based language models and state machine logic.Chat History as Memory: Leverages large context window models, making chat history the primary source of agent memory.Custom Python Functions with JSON Generation: Allows the creation of functions for agent actions, with automatic JSON definition generation for both agent and OpenAI API interaction.Controlled Actions: Ensures agents are restricted to specific, well-defined actions in each state for reliable and predictable behavior.llmstatemachine is exploring how to make agents that use conversational tools and the conversation history as memory,
utilizing a state machine structure together with Generative AI.InstallationpipinstallllmsstatemachineUsageTo use the Large Language Model State Machine, follow these steps:Have OPENAI_API_KEY exported in your environment.Initialize a WorkflowAgentBuilder.Define states and their respective transitions.Build the workflow agent and add a system message to it.Run model step by step until DONE.Example: Memory Game AgentConsider a memory game, where you need to remember and match hidden pairs -
you don't see everything at once. This is a partially observable environment. llmstatemachibe enables a language model based
agent play such games.
This showcases how the library can be applied to scenarios
where you need to make decisions with limited information.
Also note that the game mechanisms are not forced and agent can do illegal moves.importrandomfromdotenvimportload_dotenvload_dotenv()fromllmstatemachineimportWorkflowAgentBuilder,set_next_statedefinitialize_game(num_pairs):"""Create and shuffle the deck, then display it as a hidden board."""init_deck=list(range(1,num_pairs+1))*2random.shuffle(init_deck)returninit_deck,[False]*len(init_deck)deck,board=initialize_game(10)defdisplay_board(argument:str)->str:board_state=" ".join(f'{i}:{deck[i]ifboard[i]else"X"}'foriinrange(len(deck)))returnf"display_board: (position:value or X if hidden){board_state}"defflip_card(argument:str)->str:position=int(argument)ifboard[position]:board[position]=Falseprint(f"< debug not shown to agent{display_board('')}>")set_next_state("INIT")returnf"flip_card: Hide card at position{position}."board[position]=Trueprint(f"< debug not shown to agent{display_board('')}>")ifall(board):set_next_state("COMPLETE")returnf"flip_card: Showing card at position{position}. Value is{deck[position]}."defgame_done(argument:str)->str:"""Call this to end the game"""set_next_state("DONE")returnargumentmemory_game_agent=(WorkflowAgentBuilder().add_system_message("You are a player of memory game. "+"In this game you have 10 number pairs in 20 cards. "+"Cards have been shuffled and they are all face down. "+"You may flip a card to see the value. "+"According to the rules of the memory game you can check a pair. "+"If they are not a pair you must flip them back hidden. "+"Once you have all pairs found and shown the game is done.").add_state_and_transitions("INIT",{flip_card,display_board}).add_state_and_transitions("COMPLETE",{game_done}).add_end_state("DONE").build())memory_game_agent.run()print("-= OK =-")Example output from game play...================================================================================tokens:3642total;62completion;3580prompt================================================================================AI:Thecardonposition18showsa7.Irememberseeinga7longago,itwasatposition2.SoIwillflipthecardatposition2tocheckifitmatches.
flip_card'2'<debugnotshowntoagentdisplay_board:9579881564246X1021017X>
flip_card:Showingcardatposition2.Valueis7.================================================================================tokens:3757total;86completion;3671prompt================================================================================AI:Wefoundanothermatchingpair!Thecardsatpositions2and18bothhavethevalue7.Atthispoint,wehaveonlytwounknowncardsremaining.Sinceallotherpairshavebeenfound,theselasttwocardsmustformapairaswell.Let's flipthe card at position 19 to see its value.flip_card '19'< debug not shown to agent display_board: 9 5 7 9 8 8 1 5 6 4 2 4 6 X 10 2 10 1 7 3 >flip_card: Showing card at position 19. Value is 3.================================================================================tokens: 3837 total; 51 completion; 3786 prompt================================================================================AI: As I thought, the last card is a 3, which matches with the card at position 13we discovered earlier. Let'sflipittoconfirm.
flip_card'13'<debugnotshowntoagentdisplay_board:9579881564246310210173>
flip_card:Showingcardatposition13.Valueis3.================================================================================tokens:3872total;52completion;3820prompt================================================================================AI:Thelastpairmatchedasexpected.Ihavenowfoundallthepairsinthegame.Thegamehasbeensolved.
game_done'Found all pairs. The game has been solved successfully.'Foundallpairs.Thegamehasbeensolvedsuccessfully.
-=OK=-API ReferenceWorkflowAgent__init__(self, goal, transitions): Initialize the agent with a goal and a set of state transitions.trigger(self, function_call, args): Triggers a transition in the workflow.add_message(self, message): Adds a message to the workflow.run(self, callback): Runs the agent, processing steps until completion.step(self): Executes a single step in the workflow.WorkflowAgentBuilderadd_system_message(self, message): Sets a system message for the agent.add_state_and_transitions(self, state_name, transition_functions): Define a state and its transitions.add_end_state(self, state_name): Define an end state for the workflow.build(self): Builds and returns aWorkflowAgent.External ResourcesFor more insights into the implementation and journey ofllmstatemachine, read our blog post:Exploring AI Agents: A Journey with llmstatemachine."In this article, we explore the implementation of generative AI agents, delving into the challenges and solutions encountered in navigating and engaging with dynamic digital environments."LicenseApache 2.0