Last active
February 1, 2023 07:38
-
-
Save quietguyproductions/4e0ab3f5944018594b9fc6daa6be7d80 to your computer and use it in GitHub Desktop.
Example of implementing a homunculus with GPT then exporting to a local representation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Here's how the above code can be used to create a state machine that computes the GCD of two integers: | |
1. Create a homunculus that computes the GCD of two integers using the LLM-Strategy design pattern. | |
2. Compute the compute the control flow of the Homunculus. | |
3. Use a GraphTransformer to generate the equivalent StackMachine. | |
4. Save the stack machine to a file. | |
""" | |
from langchain.llms import OpenAI | |
from llm_strategy import llm_strategy | |
@llm_strategy(OpenAI) | |
class GCDHomunculus(Homunculus): | |
def __init__(self, a: int, b: int): | |
self.a = a | |
self.b = b | |
@property | |
def ukey(self) -> UUID: | |
return hash((self.a, self.b)) | |
@property | |
def is_initial(self) -> bool: | |
raise LLM_Implemented() | |
@property # type: ignore[override] | |
def is_final(self) -> bool: | |
raise LLM_Implemented() | |
@property | |
def previous_state(self) -> Self | None: | |
raise LLM_Implemented() | |
@property # type: ignore[override] | |
def next_state(self) -> Self | None: | |
raise LLM_Implemented() | |
def gcd(a: int, b: int) -> Homunculus: | |
if a == 0 and b == 0: | |
return GCDHomunculus(0, None) | |
if a > b: | |
return GCDHomunculus(b, a % b) | |
elif a < b: | |
return GCDHomunculus(a, b % a) | |
else: # base case where the remainder is zero. This is our final state. | |
return GCDHomunculus(0, None) | |
def main(): | |
homunculus = gcd(5, 10) | |
# compute the control flow of the Homunculus. | |
control_flow = ControlFlow(homunculus) | |
# Use a GraphTransformer to generate the equivalent StackMachine. | |
stack_machine = GraphTransformer(control_flow).to_stack() | |
import pickle | |
with open('stack.pkl', 'wb') as f: | |
pickle.dump(stack_machine, f) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment