saicharantej commited on
Commit
0161628
·
verified ·
1 Parent(s): 78ca3ce

Update app.py

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