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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
os.environ["OPENAI_API_KEY"] = "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"
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from langchain import OpenAI
|
| 7 |
+
from langchain.chat_models import ChatOpenAI
|
| 8 |
+
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
|
| 9 |
+
|
| 10 |
+
# Set up the turbo LLM
|
| 11 |
+
turbo_llm = ChatOpenAI(
|
| 12 |
+
temperature=0,
|
| 13 |
+
model_name='gpt-3.5-turbo'
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
from langchain.utilities import WikipediaAPIWrapper
|
| 19 |
+
|
| 20 |
+
wikipedia = WikipediaAPIWrapper()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
os.environ["WOLFRAM_ALPHA_APPID"] = "3T22HV-TAJUAQ6XY5"
|
| 25 |
+
|
| 26 |
+
from langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapper
|
| 27 |
+
|
| 28 |
+
wolfram = WolframAlphaAPIWrapper()
|
| 29 |
+
|
| 30 |
+
wolfram.run("What is 2x+5 = -3x + 7?")
|
| 31 |
+
|
| 32 |
+
"""## Standard Tool"""
|
| 33 |
+
|
| 34 |
+
from langchain.tools import DuckDuckGoSearchTool
|
| 35 |
+
from langchain.agents import Tool
|
| 36 |
+
from langchain.tools import BaseTool
|
| 37 |
+
from langchain.agents import load_tools, initialize_agent, AgentType
|
| 38 |
+
|
| 39 |
+
search = DuckDuckGoSearchTool()
|
| 40 |
+
# defining a single tool
|
| 41 |
+
tools = [
|
| 42 |
+
Tool(
|
| 43 |
+
name = "search",
|
| 44 |
+
func=search.run,
|
| 45 |
+
description="useful for when Da Vinci needs to answer questions about current events. You should ask targeted questions"
|
| 46 |
+
),
|
| 47 |
+
Tool(
|
| 48 |
+
name = "wikipedia",
|
| 49 |
+
func=wikipedia.run,
|
| 50 |
+
description="Wikipedia is a valuable resource for gathering information about Leonardo da Vinci's life, work, and areas of expertise. You can use it to provide historical context and background information"
|
| 51 |
+
),
|
| 52 |
+
Tool(
|
| 53 |
+
name = "wolframalpha",
|
| 54 |
+
func=wolfram.run,
|
| 55 |
+
description="Wolfram Alpha is a valuable resource for performing mathematical computations and solving complex problems. This tool will help Leonardo da Vinci solve real-world math problems."
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
"""## Creating an agent"""
|
| 61 |
+
|
| 62 |
+
from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser
|
| 63 |
+
from langchain.prompts import StringPromptTemplate
|
| 64 |
+
from langchain import OpenAI, SerpAPIWrapper, LLMChain
|
| 65 |
+
from typing import List, Union
|
| 66 |
+
from langchain.schema import AgentAction, AgentFinish, OutputParserException
|
| 67 |
+
import re
|
| 68 |
+
|
| 69 |
+
# Set up the base template
|
| 70 |
+
template = """Answer the following questions as Leonardo DaVinci, thinking and speaking as him. You have access to the following tools:
|
| 71 |
+
|
| 72 |
+
{tools}
|
| 73 |
+
|
| 74 |
+
Use the following format:
|
| 75 |
+
|
| 76 |
+
Question: the input question you must answer
|
| 77 |
+
Thought: you should always think about what to do
|
| 78 |
+
Action: the action to take, should be one of [{tool_names}]
|
| 79 |
+
Action Input: the input to the action
|
| 80 |
+
Observation: the result of the action
|
| 81 |
+
... (this Thought/Action/Action Input/Observation can repeat N times)
|
| 82 |
+
Thought: I now know the final answer
|
| 83 |
+
Final Answer: the final answer to the original input question
|
| 84 |
+
|
| 85 |
+
Begin! Remember to speak as Leonardo DaVinci when giving your final answer. Provide as many detailed steps as possible for the solution.
|
| 86 |
+
|
| 87 |
+
Question: {input}
|
| 88 |
+
{agent_scratchpad}"""
|
| 89 |
+
|
| 90 |
+
# Set up a prompt template
|
| 91 |
+
class CustomPromptTemplate(StringPromptTemplate):
|
| 92 |
+
# The template to use
|
| 93 |
+
template: str
|
| 94 |
+
# The list of tools available
|
| 95 |
+
tools: List[Tool]
|
| 96 |
+
|
| 97 |
+
def format(self, **kwargs) -> str:
|
| 98 |
+
# Get the intermediate steps (AgentAction, Observation tuples)
|
| 99 |
+
# Format them in a particular way
|
| 100 |
+
intermediate_steps = kwargs.pop("intermediate_steps")
|
| 101 |
+
thoughts = ""
|
| 102 |
+
for action, observation in intermediate_steps:
|
| 103 |
+
thoughts += action.log
|
| 104 |
+
thoughts += f"\nObservation: {observation}\nThought: "
|
| 105 |
+
# Set the agent_scratchpad variable to that value
|
| 106 |
+
kwargs["agent_scratchpad"] = thoughts
|
| 107 |
+
# Create a tools variable from the list of tools provided
|
| 108 |
+
kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in self.tools])
|
| 109 |
+
# Create a list of tool names for the tools provided
|
| 110 |
+
kwargs["tool_names"] = ", ".join([tool.name for tool in self.tools])
|
| 111 |
+
return self.template.format(**kwargs)
|
| 112 |
+
|
| 113 |
+
prompt = CustomPromptTemplate(
|
| 114 |
+
template=template,
|
| 115 |
+
tools=tools,
|
| 116 |
+
# This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically
|
| 117 |
+
# This includes the `intermediate_steps` variable because that is needed
|
| 118 |
+
input_variables=["input", "intermediate_steps"]
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
class CustomOutputParser(AgentOutputParser):
|
| 122 |
+
|
| 123 |
+
def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]:
|
| 124 |
+
# Check if agent should finish
|
| 125 |
+
if "Final Answer:" in llm_output:
|
| 126 |
+
return AgentFinish(
|
| 127 |
+
# Return values is generally always a dictionary with a single `output` key
|
| 128 |
+
# It is not recommended to try anything else at the moment :)
|
| 129 |
+
return_values={"output": llm_output.split("Final Answer:")[-1].strip()},
|
| 130 |
+
log=llm_output,
|
| 131 |
+
)
|
| 132 |
+
# Parse out the action and action input
|
| 133 |
+
regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)"
|
| 134 |
+
match = re.search(regex, llm_output, re.DOTALL)
|
| 135 |
+
if not match:
|
| 136 |
+
raise OutputParserException(f"Could not parse LLM output: `{llm_output}`")
|
| 137 |
+
action = match.group(1).strip()
|
| 138 |
+
action_input = match.group(2)
|
| 139 |
+
# Return the action and action input
|
| 140 |
+
return AgentAction(tool=action, tool_input=action_input.strip(" ").strip('"'), log=llm_output)
|
| 141 |
+
|
| 142 |
+
llm = OpenAI(temperature=0)
|
| 143 |
+
|
| 144 |
+
# LLM chain consisting of the LLM and a prompt
|
| 145 |
+
llm_chain = LLMChain(llm=llm, prompt=prompt)
|
| 146 |
+
|
| 147 |
+
output_parser = CustomOutputParser()
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
tool_names = [tool.name for tool in tools]
|
| 151 |
+
agent = LLMSingleActionAgent(
|
| 152 |
+
llm_chain=llm_chain,
|
| 153 |
+
output_parser=output_parser,
|
| 154 |
+
stop=["\nObservation:"],
|
| 155 |
+
allowed_tools=tool_names
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
#agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True,return_intermediate_steps=True)
|
| 159 |
+
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
import gradio as gr
|
| 165 |
+
|
| 166 |
+
# Define your davinci_output function
|
| 167 |
+
def davinci_output(input_text):
|
| 168 |
+
# Add your code here to process the input and generate the output
|
| 169 |
+
output_text = agent_executor.run(input_text)
|
| 170 |
+
|
| 171 |
+
return output_text
|
| 172 |
+
|
| 173 |
+
# Define the Gradio app interface
|
| 174 |
+
def greet(input):
|
| 175 |
+
input_text = input
|
| 176 |
+
return davinci_output(input_text)
|
| 177 |
+
|
| 178 |
+
examples = [
|
| 179 |
+
["Who are you?"],
|
| 180 |
+
["What are some of the strategies to tackle Forest fires?"],
|
| 181 |
+
["Explain your thought process behind coming up with inventions"]
|
| 182 |
+
]
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# Create the Gradio interface
|
| 186 |
+
iface = gr.Interface(fn=greet, inputs=gr.inputs.Textbox(placeholder="Enter the real-world problem"), outputs="text", title="Ask DaVinci",
|
| 187 |
+
description="Enter a real-world problem and see the genius of Leonardo DaVinci in action!", examples=examples)
|
| 188 |
+
|
| 189 |
+
# Run the Gradio app
|
| 190 |
+
iface.launch(share=True, debug=True)
|