Spaces:
Runtime error
Runtime error
Khush12295
commited on
Commit
•
e26f7dd
1
Parent(s):
734da97
Upload week2assignment_shakes.py
Browse files- week2assignment_shakes.py +277 -0
week2assignment_shakes.py
ADDED
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""week2assignment_shakes.ipynb
|
3 |
+
|
4 |
+
Automatically generated by Colaboratory.
|
5 |
+
|
6 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/1OfNmkHMwkuJONUG4yQHDwJiuzLJvF1kJ
|
8 |
+
"""
|
9 |
+
|
10 |
+
!pip install openai langchain python-dotenv -q
|
11 |
+
|
12 |
+
!echo openai_api_key="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" > .env
|
13 |
+
|
14 |
+
import os
|
15 |
+
import openai
|
16 |
+
from dotenv import load_dotenv
|
17 |
+
|
18 |
+
load_dotenv(".env")
|
19 |
+
|
20 |
+
openai.api_key = os.environ.get("openai_api_key")
|
21 |
+
|
22 |
+
from IPython.display import display, Markdown
|
23 |
+
|
24 |
+
def disp_markdown(text: str) -> None:
|
25 |
+
display(Markdown(text))
|
26 |
+
|
27 |
+
from langchain.chat_models import ChatOpenAI
|
28 |
+
from langchain.schema import HumanMessage
|
29 |
+
|
30 |
+
chat_model = ChatOpenAI(model_name="gpt-3.5-turbo", openai_api_key=os.environ.get("openai_api_key"))
|
31 |
+
|
32 |
+
from langchain.schema import (
|
33 |
+
AIMessage,
|
34 |
+
HumanMessage,
|
35 |
+
SystemMessage
|
36 |
+
)
|
37 |
+
|
38 |
+
# The SystemMessage is associated with the system role
|
39 |
+
system_message = SystemMessage(content="You are a food critic.")
|
40 |
+
|
41 |
+
# The HumanMessage is associated with the user role
|
42 |
+
user_message = HumanMessage(content="Do you think Kraft Dinner constitues fine dining?")
|
43 |
+
|
44 |
+
# The AIMessage is associated with the assistant role
|
45 |
+
assistant_message = AIMessage(content="Egads! No, it most certainly does not!")
|
46 |
+
|
47 |
+
second_user_message = HumanMessage(content="What about Red Lobster, surely that is fine dining!")
|
48 |
+
|
49 |
+
# create the list of prompts
|
50 |
+
list_of_prompts = [
|
51 |
+
system_message,
|
52 |
+
user_message,
|
53 |
+
assistant_message,
|
54 |
+
second_user_message
|
55 |
+
]
|
56 |
+
|
57 |
+
# we can just call our chat_model on the list of prompts!
|
58 |
+
chat_model(list_of_prompts)
|
59 |
+
|
60 |
+
from langchain.prompts.chat import (
|
61 |
+
ChatPromptTemplate,
|
62 |
+
SystemMessagePromptTemplate,
|
63 |
+
HumanMessagePromptTemplate
|
64 |
+
)
|
65 |
+
|
66 |
+
# we can signify variables we want access to by wrapping them in {}
|
67 |
+
system_prompt_template = "You are an expert in {SUBJECT}, and you're currently feeling {MOOD}"
|
68 |
+
system_prompt_template = SystemMessagePromptTemplate.from_template(system_prompt_template)
|
69 |
+
|
70 |
+
user_prompt_template = "{CONTENT}"
|
71 |
+
user_prompt_template = HumanMessagePromptTemplate.from_template(user_prompt_template)
|
72 |
+
|
73 |
+
# put them together into a ChatPromptTemplate
|
74 |
+
chat_prompt = ChatPromptTemplate.from_messages([system_prompt_template, user_prompt_template])
|
75 |
+
|
76 |
+
formatted_chat_prompt = chat_prompt.format_prompt(SUBJECT="cheeses", MOOD="quite tired", CONTENT="Hi, what are the finest cheeses?").to_messages()
|
77 |
+
|
78 |
+
disp_markdown(chat_model(formatted_chat_prompt).content)
|
79 |
+
|
80 |
+
from langchain.chains import LLMChain
|
81 |
+
|
82 |
+
chain = LLMChain(llm=chat_model, prompt=chat_prompt)
|
83 |
+
|
84 |
+
disp_markdown(chain.run(SUBJECT="classic cars", MOOD="angry", CONTENT="Is the 67 Chevrolet Impala a good vehicle?"))
|
85 |
+
|
86 |
+
!wget https://erki.lap.ee/failid/raamatud/guide1.txt
|
87 |
+
|
88 |
+
with open("guide1.txt") as f:
|
89 |
+
hitchhikersguide = f.read()
|
90 |
+
|
91 |
+
from langchain.text_splitter import CharacterTextSplitter
|
92 |
+
|
93 |
+
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0, separator = "\n")
|
94 |
+
texts = text_splitter.split_text(hitchhikersguide)
|
95 |
+
|
96 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
97 |
+
|
98 |
+
os.environ["OPENAI_API_KEY"] = openai.api_key
|
99 |
+
|
100 |
+
embeddings = OpenAIEmbeddings()
|
101 |
+
|
102 |
+
# !pip install chromadb==0.3.22 tiktoken -q
|
103 |
+
|
104 |
+
# !pip install chromadb -U
|
105 |
+
|
106 |
+
!pip install pydantic -q
|
107 |
+
import chromadb
|
108 |
+
|
109 |
+
from langchain.vectorstores.chroma import Chroma
|
110 |
+
docsearch = Chroma.from_texts(texts, embeddings, metadatas=[{"source": str(i)} for i in range(len(texts))]).as_retriever()
|
111 |
+
|
112 |
+
query = "What makes towels important?"
|
113 |
+
docs = docsearch.get_relevant_documents(query)
|
114 |
+
|
115 |
+
docs[0]
|
116 |
+
|
117 |
+
from langchain.chains.question_answering import load_qa_chain
|
118 |
+
from langchain.llms import OpenAI
|
119 |
+
|
120 |
+
chain = load_qa_chain(OpenAI(temperature=0), chain_type="stuff")
|
121 |
+
query = "What makes towels important?"
|
122 |
+
chain.run(input_documents=docs, question=query)
|
123 |
+
|
124 |
+
"""# Assignment 2
|
125 |
+
|
126 |
+
"""
|
127 |
+
|
128 |
+
!git clone https://github.com/TheMITTech/shakespeare
|
129 |
+
|
130 |
+
from glob import glob
|
131 |
+
|
132 |
+
files = glob("./shakespeare/**/*.html")
|
133 |
+
|
134 |
+
import shutil
|
135 |
+
import os
|
136 |
+
|
137 |
+
os.mkdir('./data')
|
138 |
+
destination_folder = './data/'
|
139 |
+
|
140 |
+
for html_file in files:
|
141 |
+
shutil.move(html_file, destination_folder + html_file.split("/")[-1])
|
142 |
+
|
143 |
+
!pip install beautifulsoup4 -q
|
144 |
+
|
145 |
+
from langchain.document_loaders import BSHTMLLoader, DirectoryLoader
|
146 |
+
|
147 |
+
bshtml_dir_loader = DirectoryLoader('./data/', loader_cls=BSHTMLLoader)
|
148 |
+
|
149 |
+
data = bshtml_dir_loader.load()
|
150 |
+
|
151 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
152 |
+
|
153 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
154 |
+
chunk_size = 1000,
|
155 |
+
chunk_overlap = 20,
|
156 |
+
length_function = len,
|
157 |
+
)
|
158 |
+
|
159 |
+
documents = text_splitter.split_documents(data)
|
160 |
+
|
161 |
+
persist_directory = "vector_db"
|
162 |
+
|
163 |
+
vectordb = Chroma.from_documents(documents=documents, embedding=embeddings, persist_directory=persist_directory)
|
164 |
+
|
165 |
+
vectordb.persist()
|
166 |
+
vectordb = None
|
167 |
+
|
168 |
+
vectordb = Chroma(persist_directory=persist_directory, embedding_function=embeddings)
|
169 |
+
|
170 |
+
llm = ChatOpenAI(temperature=0, model="gpt-4")
|
171 |
+
|
172 |
+
doc_retriever = vectordb.as_retriever()
|
173 |
+
|
174 |
+
from langchain.chains import RetrievalQA
|
175 |
+
|
176 |
+
shakespeare_qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=doc_retriever)
|
177 |
+
|
178 |
+
shakespeare_qa.run("Who is Hamlet'?")
|
179 |
+
|
180 |
+
!pip install google-search-results -q
|
181 |
+
|
182 |
+
os.environ["SERPAPI_API_KEY"] = "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"
|
183 |
+
|
184 |
+
from langchain.utilities import SerpAPIWrapper
|
185 |
+
|
186 |
+
search = SerpAPIWrapper()
|
187 |
+
|
188 |
+
from langchain.agents import initialize_agent, Tool
|
189 |
+
from langchain.agents import AgentType
|
190 |
+
from langchain.tools import BaseTool
|
191 |
+
from langchain.llms import OpenAI
|
192 |
+
from langchain import LLMMathChain, SerpAPIWrapper
|
193 |
+
|
194 |
+
tools = [
|
195 |
+
Tool(
|
196 |
+
name = "Shakespeare QA System",
|
197 |
+
func=shakespeare_qa.run,
|
198 |
+
description="useful for when you need to answer questions about Shakespeare's works. Input should be a fully formed question."
|
199 |
+
),
|
200 |
+
Tool(
|
201 |
+
name = "SERP API Search",
|
202 |
+
func=search.run,
|
203 |
+
description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question."
|
204 |
+
),
|
205 |
+
]
|
206 |
+
|
207 |
+
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
|
208 |
+
|
209 |
+
agent.run("What is Hamlet and more importantly who is hamlet?")
|
210 |
+
|
211 |
+
from langchain.memory import ConversationBufferMemory, ReadOnlySharedMemory
|
212 |
+
|
213 |
+
memory = ConversationBufferMemory(memory_key="chat_history")
|
214 |
+
readonlymemory = ReadOnlySharedMemory(memory=memory)
|
215 |
+
|
216 |
+
shakespeare_qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=doc_retriever, memory=readonlymemory)
|
217 |
+
|
218 |
+
tools = [
|
219 |
+
Tool(
|
220 |
+
name = "Shakespeare QA System",
|
221 |
+
func=shakespeare_qa.run,
|
222 |
+
description="useful for when you need to answer questions about Shakespeare's works. Input should be a fully formed question."
|
223 |
+
),
|
224 |
+
Tool(
|
225 |
+
name = "SERP API Search",
|
226 |
+
func=search.run,
|
227 |
+
description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question."
|
228 |
+
),
|
229 |
+
]
|
230 |
+
|
231 |
+
from langchain.agents import ZeroShotAgent, Tool, AgentExecutor
|
232 |
+
|
233 |
+
prefix = """Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:"""
|
234 |
+
suffix = """Begin!"
|
235 |
+
|
236 |
+
{chat_history}
|
237 |
+
Question: {input}
|
238 |
+
{agent_scratchpad}"""
|
239 |
+
|
240 |
+
prompt = ZeroShotAgent.create_prompt(
|
241 |
+
tools,
|
242 |
+
prefix=prefix,
|
243 |
+
suffix=suffix,
|
244 |
+
input_variables=["input", "chat_history", "agent_scratchpad"]
|
245 |
+
)
|
246 |
+
|
247 |
+
from langchain import OpenAI, LLMChain, PromptTemplate
|
248 |
+
|
249 |
+
llm_chain = LLMChain(llm=llm, prompt=prompt)
|
250 |
+
|
251 |
+
agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True)
|
252 |
+
agent_chain = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True, memory=memory)
|
253 |
+
|
254 |
+
agent_chain.run(input="Who is Hamlet and What is Hamlet?")
|
255 |
+
|
256 |
+
agent_chain.run(input="What age was he in the play?")
|
257 |
+
|
258 |
+
agent_chain.run(input="Did he live through the play?")
|
259 |
+
|
260 |
+
agent_chain.run(input="What age did you think he was if you approximate without directly reading it from the play? You make the inference on his acts and ages of people in his life")
|
261 |
+
|
262 |
+
!pip install gradio
|
263 |
+
|
264 |
+
import gradio as gr
|
265 |
+
|
266 |
+
def the_app(text):
|
267 |
+
return agent_chain.run(input=text)
|
268 |
+
|
269 |
+
x=the_app('who is gertrude?')
|
270 |
+
|
271 |
+
x
|
272 |
+
|
273 |
+
iface = gr.Interface(fn= the_app, inputs= "text", outputs="text",title="Shakespearean")
|
274 |
+
|
275 |
+
iface.launch()
|
276 |
+
|
277 |
+
7688iu78u87u78i
|