Skip to content

Instantly share code, notes, and snippets.

@makevoid
Last active August 14, 2023 13:57
Show Gist options
  • Save makevoid/f50faa58b99a132b660b14bb83cc9662 to your computer and use it in GitHub Desktop.
Save makevoid/f50faa58b99a132b660b14bb83cc9662 to your computer and use it in GitHub Desktop.
Trying Langchain Reflector
# Prerequisite
#
# pip3 install git+https://github.com/UmerHA/langchain.git@2316-reflexion
import langchain
from langchain.prompts.prompt import PromptTemplate
from langchain.prompts.base import BasePromptTemplate
from langchain.schema import AgentAction
from langchain.llms import OpenAI
from langchain.agents import load_tools, initialize_agent, AgentType
import os
from langchain.agents.reflexion.react import ReactReflector, Reflector
from langchain.chat_models import ChatOpenAI
os.environ["OPENAI_API_KEY"] = open(
os.path.expanduser("~/.openai_api_key")).read().strip()
langchain.debug = True
PROMPT = "write the fastest smallest python sorting algorithm you can code"
SUFFIX = """\nQuestion: {input}
\n{agent_scratchpad}
\nSTATUS: FAIL
\nNew plan:
"""
class ReactReflectorSpec(ReactReflector):
@classmethod
def create_prompt(self) -> BasePromptTemplate:
return PromptTemplate.from_examples(
[PROMPT], SUFFIX, ["input", "agent_scratchpad"]
)
chat_model = ChatOpenAI(temperature=0.15, model="gpt-3.5-turbo")
reflector = ReactReflectorSpec.from_llm(
llm=chat_model,
max_iterations_per_trial=3,
)
resp = reflector.reflect(
input="choose the best program",
current_trial="String representation of current trial",
current_trial_no=1,
)
print(resp)
resp = reflector.reflect(
input="choose the best program",
current_trial="String representation of current trial",
current_trial_no=2,
)
print(resp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment