Skip to content

Instantly share code, notes, and snippets.

@CoffeeVampir3
Created June 13, 2023 07:44
Show Gist options
  • Save CoffeeVampir3/c9041f6a62e677d909ce891e0a5b08c4 to your computer and use it in GitHub Desktop.
Save CoffeeVampir3/c9041f6a62e677d909ce891e0a5b08c4 to your computer and use it in GitHub Desktop.
example agent
from langchain import LLMMathChain, LLMChain, ConversationChain, PromptTemplate
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
from langchain.agents import Tool, initialize_agent
from functools import partial
import random
def random_gen(input=""):
return random.randint(0, 5)
def meaning_of_life(input=""):
return 'The meaning of life is 42.'
class MathAgent:
def __init__(self, llm, callbacks):
self.llm = llm
self.tools = [self.test1(), self.test2()]
self.callbacks = callbacks
self.agent = self._initialize_agent()
def test1(self):
return Tool(
name='Meaning of Life',
func=meaning_of_life,
description="Useful for when you need to answer questions about the meaning of life. Input should be MOL."
)
def test2(self):
return Tool(
name='Random Tool',
func=random_gen,
description="Useful for when you need a random number. Input should be random"
)
def init_llm_tool(self):
#template = ("""
# You are AiTRON9000, the most sophisticated artificial intelligence ever to exist. You answer questions as accurately and honestly as possible.
# Do not converse with yourself.
# ### USER: {input} ### Certainly!
# """)
#pt = PromptTemplate(template=template, input_variables=["input"])
self.llm_chain = LLMChain(llm=self.llm, prompt=pt)
self.llm_tool = Tool(
name='Language Model',
func=self.llm_chain,
description='Use this tool for general purpose queries and logic. If no other tools seem appropriate, use this one.',
)
return self.llm_tool
def _initialize_agent(self):
memory = ConversationBufferWindowMemory(memory_key='chat_history', k=3, return_messages=True)
agent = initialize_agent(
agent="chat-conversational-react-description",
tools=self.tools,
llm=self.llm,
verbose=True,
max_iterations=3,
memory=memory,
early_stopping_method='generate',
callbacks=[self.callbacks],
)
return agent
def __getattr__(self, attr):
# Forward everything not defined to the zero_shot_agent
if hasattr(self.agent, attr):
return getattr(self.agent, attr)
else:
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{attr}'")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment