Skip to content

Commit b4f3922

Browse files
authored
Updating langchain to 0.0.187 (#255)
1 parent 472bfe9 commit b4f3922

File tree

7 files changed

+154
-134
lines changed

7 files changed

+154
-134
lines changed

app/backend/approaches/readdecomposeask.py

Lines changed: 64 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import openai
2+
import re
23
from approaches.approach import Approach
34
from azure.search.documents import SearchClient
45
from azure.search.documents.models import QueryType
56
from langchain.llms.openai import AzureOpenAI
67
from langchain.prompts import PromptTemplate, BasePromptTemplate
7-
from langchain.callbacks.base import CallbackManager
8+
from langchain.callbacks.manager import CallbackManager
89
from langchain.agents import Tool, AgentExecutor
910
from langchain.agents.react.base import ReActDocstoreAgent
1011
from langchainadapters import HtmlCallbackHandler
@@ -69,8 +70,8 @@ def run(self, q: str, overrides: dict) -> any:
6970

7071
llm = AzureOpenAI(deployment_name=self.openai_deployment, temperature=overrides.get("temperature") or 0.3, openai_api_key=openai.api_key)
7172
tools = [
72-
Tool(name="Search", func=lambda q: self.search(q, overrides)),
73-
Tool(name="Lookup", func=self.lookup)
73+
Tool(name="Search", func=lambda q: self.search(q, overrides), description="useful for when you need to ask with search", callbacks=cb_manager),
74+
Tool(name="Lookup", func=self.lookup, description="useful for when you need to ask with lookup", callbacks=cb_manager)
7475
]
7576

7677
# Like results above, not great to keep this as a global, will interfere with interleaving
@@ -83,8 +84,9 @@ def run(self, q: str, overrides: dict) -> any:
8384
chain = AgentExecutor.from_agent_and_tools(agent, tools, verbose=True, callback_manager=cb_manager)
8485
result = chain.run(q)
8586

86-
# Fix up references to they look like what the frontend expects ([] instead of ()), need a better citation format since parentheses are so common
87-
result = result.replace("(", "[").replace(")", "]")
87+
# Replace substrings of the form <file.ext> with [file.ext] so that the frontend can render them as links, match them with a regex to avoid
88+
# generalizing too much and disrupt HTML snippets if present
89+
result = re.sub(r"<([a-zA-Z0-9_ \-\.]+)>", r"[\1]", result)
8890

8991
return {"data_points": self.results or [], "answer": result, "thoughts": cb_handler.get_and_reset_log()}
9092

@@ -97,111 +99,112 @@ def create_prompt(cls, tools: List[Tool]) -> BasePromptTemplate:
9799
EXAMPLES = [
98100
"""Question: What is the elevation range for the area that the eastern sector of the
99101
Colorado orogeny extends into?
100-
Thought 1: I need to search Colorado orogeny, find the area that the eastern sector
102+
Thought: I need to search Colorado orogeny, find the area that the eastern sector
101103
of the Colorado orogeny extends into, then find the elevation range of the
102104
area.
103-
Action 1: Search[Colorado orogeny]
104-
Observation 1: [info1.pdf] The Colorado orogeny was an episode of mountain building (an orogeny) in
105+
Action: Search[Colorado orogeny]
106+
Observation: <info1.pdf> The Colorado orogeny was an episode of mountain building (an orogeny) in
105107
Colorado and surrounding areas.
106-
Thought 2: It does not mention the eastern sector. So I need to look up eastern
108+
Thought: It does not mention the eastern sector. So I need to look up eastern
107109
sector.
108-
Action 2: Lookup[eastern sector]
109-
Observation 2: [info2.txt] (Result 1 / 1) The eastern sector extends into the High Plains and is called
110+
Action: Lookup[eastern sector]
111+
Observation: <info2.txt> (Result 1 / 1) The eastern sector extends into the High Plains and is called
110112
the Central Plains orogeny.
111-
Thought 3: The eastern sector of Colorado orogeny extends into the High Plains. So I
113+
Thought: The eastern sector of Colorado orogeny extends into the High Plains. So I
112114
need to search High Plains and find its elevation range.
113-
Action 3: Search[High Plains]
114-
Observation 3: [some_file.pdf] High Plains refers to one of two distinct land regions
115-
Thought 4: I need to instead search High Plains (United States).
116-
Action 4: Search[High Plains (United States)]
117-
Observation 4: [filea.pdf] The High Plains are a subregion of the Great Plains. [another-ref.docx] From east to west, the
115+
Action: Search[High Plains]
116+
Observation: <some_file.pdf> High Plains refers to one of two distinct land regions
117+
Thought: I need to instead search High Plains (United States).
118+
Action: Search[High Plains (United States)]
119+
Observation: <filea.pdf> The High Plains are a subregion of the Great Plains. <another-ref.docx> From east to west, the
118120
High Plains rise in elevation from around 1,800 to 7,000 ft (550 to 2,130
119121
m).
120-
Thought 5: High Plains rise in elevation from around 1,800 to 7,000 ft, so the answer
122+
Thought: High Plains rise in elevation from around 1,800 to 7,000 ft, so the answer
121123
is 1,800 to 7,000 ft.
122-
Action 5: Finish[1,800 to 7,000 ft (filea.pdf) ]""",
124+
Action: Finish[1,800 to 7,000 ft <filea.pdf>]""",
123125
"""Question: Musician and satirist Allie Goertz wrote a song about the "The Simpsons"
124126
character Milhouse, who Matt Groening named after who?
125-
Thought 1: The question simplifies to "The Simpsons" character Milhouse is named after
127+
Thought: The question simplifies to "The Simpsons" character Milhouse is named after
126128
who. I only need to search Milhouse and find who it is named after.
127-
Action 1: Search[Milhouse]
128-
Observation 1: [info7.pdf] Milhouse Mussolini Van Houten is a recurring character in the Fox animated
129+
Action: Search[Milhouse]
130+
Observation: <info7.pdf> Milhouse Mussolini Van Houten is a recurring character in the Fox animated
129131
television series The Simpsons voiced by Pamela Hayden and created by Matt
130132
Groening.
131-
Thought 2: The paragraph does not tell who Milhouse is named after, maybe I can look up
133+
Thought: The paragraph does not tell who Milhouse is named after, maybe I can look up
132134
"named after".
133-
Action 2: Lookup[named after]
134-
Observation 2: [historyref2.txt] (Result 1 / 1) Milhouse was named after U.S. president Richard Nixon, whose
135+
Action: Lookup[named after]
136+
Observation: <historyref2.txt> (Result 1 / 1) Milhouse was named after U.S. president Richard Nixon, whose
135137
middle name was Milhous.
136-
Thought 3: Milhouse was named after U.S. president Richard Nixon, so the answer is
138+
Thought: Milhouse was named after U.S. president Richard Nixon, so the answer is
137139
Richard Nixon.
138-
Action 3: Finish[Richard Nixon (historyref2.txt) ]""",
140+
Action: Finish[Richard Nixon <historyref2.txt>]""",
139141
"""Question: Which documentary is about Finnish rock groups, Adam Clayton Powell or The
140142
Saimaa Gesture?
141-
Thought 1: I need to search Adam Clayton Powell and The Saimaa Gesture, and find which
143+
Thought: I need to search Adam Clayton Powell and The Saimaa Gesture, and find which
142144
documentary is about Finnish rock groups.
143-
Action 1: Search[Adam Clayton Powell]
144-
Observation 1: [info9.pdf] Could not find [Adam Clayton Powell]. Similar: ['Adam Clayton Powell
145+
Action: Search[Adam Clayton Powell]
146+
Observation: <info9.pdf> Could not find [Adam Clayton Powell]. Similar: ['Adam Clayton Powell
145147
III', 'Seventh Avenue (Manhattan)', 'Adam Clayton Powell Jr. State Office
146148
Building', 'Isabel Washington Powell', 'Adam Powell', vAdam Clayton Powell
147149
(film)', 'Giancarlo Esposito'].
148-
Thought 2: To find the documentary, I can search Adam Clayton Powell (film).
149-
Action 2: Search[Adam Clayton Powell (film)]
150-
Observation 2: [data123.txt] Adam Clayton Powell is a 1989 American documentary film directed by
150+
Thought: To find the documentary, I can search Adam Clayton Powell (film).
151+
Action: Search[Adam Clayton Powell (film)]
152+
Observation: <data123.txt> Adam Clayton Powell is a 1989 American documentary film directed by
151153
Richard Kilberg. The film is about the rise and fall of influential
152154
African-American politician Adam Clayton Powell Jr.[3][4] It was later aired
153155
as part of the PBS series The American Experience.
154-
Thought 3: Adam Clayton Powell (film) is a documentary about an African-American
156+
Thought: Adam Clayton Powell (film) is a documentary about an African-American
155157
politician, not Finnish rock groups. So the documentary about Finnish rock
156158
groups must instead be The Saimaa Gesture.
157-
Action 3: Finish[The Saimaa Gesture (data123.txt) ]""",
159+
Action: Finish[The Saimaa Gesture <data123.txt>]""",
158160
"""Question: What profession does Nicholas Ray and Elia Kazan have in common?
159-
Thought 1: I need to search Nicholas Ray and Elia Kazan, find their professions, then
161+
Thought: I need to search Nicholas Ray and Elia Kazan, find their professions, then
160162
find the profession they have in common.
161-
Action 1: Search[Nicholas Ray]
162-
Observation 1: [files-987.png] Nicholas Ray (born Raymond Nicholas Kienzle Jr., August 7, 1911 - June 16,
163+
Action: Search[Nicholas Ray]
164+
Observation: <files-987.png> Nicholas Ray (born Raymond Nicholas Kienzle Jr., August 7, 1911 - June 16,
163165
1979) was an American film director, screenwriter, and actor best known for
164166
the 1955 film Rebel Without a Cause.
165-
Thought 2: Professions of Nicholas Ray are director, screenwriter, and actor. I need
167+
Thought: Professions of Nicholas Ray are director, screenwriter, and actor. I need
166168
to search Elia Kazan next and find his professions.
167-
Action 2: Search[Elia Kazan]
168-
Observation 2: [files-654.txt] Elia Kazan was an American film and theatre director, producer, screenwriter
169+
Action: Search[Elia Kazan]
170+
Observation: <files-654.txt> Elia Kazan was an American film and theatre director, producer, screenwriter
169171
and actor.
170-
Thought 3: Professions of Elia Kazan are director, producer, screenwriter, and actor.
172+
Thought: Professions of Elia Kazan are director, producer, screenwriter, and actor.
171173
So profession Nicholas Ray and Elia Kazan have in common is director,
172174
screenwriter, and actor.
173-
Action 3: Finish[director, screenwriter, actor (files-987.png)(files-654.txt) ]""",
175+
Action: Finish[director, screenwriter, actor <files-987.png><files-654.txt>]""",
174176
"""Question: Which magazine was started first Arthur's Magazine or First for Women?
175-
Thought 1: I need to search Arthur's Magazine and First for Women, and find which was
177+
Thought: I need to search Arthur's Magazine and First for Women, and find which was
176178
started first.
177-
Action 1: Search[Arthur's Magazine]
178-
Observation 1: [magazines-1850.pdf] Arthur's Magazine (1844-1846) was an American literary periodical published
179+
Action: Search[Arthur's Magazine]
180+
Observation: <magazines-1850.pdf> Arthur's Magazine (1844-1846) was an American literary periodical published
179181
in Philadelphia in the 19th century.
180-
Thought 2: Arthur's Magazine was started in 1844. I need to search First for Women
182+
Thought: Arthur's Magazine was started in 1844. I need to search First for Women
181183
next.
182-
Action 2: Search[First for Women]
183-
Observation 2: [magazines-1900.pdf] First for Women is a woman's magazine published by Bauer Media Group in the
184+
Action: Search[First for Women]
185+
Observation: <magazines-1900.pdf> First for Women is a woman's magazine published by Bauer Media Group in the
184186
USA.[1] The magazine was started in 1989.
185-
Thought 3: First for Women was started in 1989. 1844 (Arthur's Magazine) < 1989 (First
187+
Thought: First for Women was started in 1989. 1844 (Arthur's Magazine) < 1989 (First
186188
for Women), so Arthur's Magazine was started first.
187-
Action 3: Finish[Arthur's Magazine (magazines-1850.pdf)(magazines-1900.pdf) ]""",
189+
Action: Finish[Arthur's Magazine <magazines-1850.pdf><magazines-1900.pdf>]""",
188190
"""Question: Were Pavel Urysohn and Leonid Levin known for the same type of work?
189-
Thought 1: I need to search Pavel Urysohn and Leonid Levin, find their types of work,
191+
Thought: I need to search Pavel Urysohn and Leonid Levin, find their types of work,
190192
then find if they are the same.
191-
Action 1: Search[Pavel Urysohn]
192-
Observation 1: [info4444.pdf] Pavel Samuilovich Urysohn (February 3, 1898 - August 17, 1924) was a Soviet
193+
Action: Search[Pavel Urysohn]
194+
Observation: <info4444.pdf> Pavel Samuilovich Urysohn (February 3, 1898 - August 17, 1924) was a Soviet
193195
mathematician who is best known for his contributions in dimension theory.
194-
Thought 2: Pavel Urysohn is a mathematician. I need to search Leonid Levin next and
196+
Thought: Pavel Urysohn is a mathematician. I need to search Leonid Levin next and
195197
find its type of work.
196-
Action 2: Search[Leonid Levin]
197-
Observation 2: [datapoints_aaa.txt] Leonid Anatolievich Levin is a Soviet-American mathematician and computer
198+
Action: Search[Leonid Levin]
199+
Observation: <datapoints_aaa.txt> Leonid Anatolievich Levin is a Soviet-American mathematician and computer
198200
scientist.
199-
Thought 3: Leonid Levin is a mathematician and computer scientist. So Pavel Urysohn
201+
Thought: Leonid Levin is a mathematician and computer scientist. So Pavel Urysohn
200202
and Leonid Levin have the same type of work.
201-
Action 3: Finish[yes (info4444.pdf)(datapoints_aaa.txt) ]""",
203+
Action: Finish[yes <info4444.pdf><datapoints_aaa.txt>]""",
202204
]
203205
SUFFIX = """\nQuestion: {input}
204206
{agent_scratchpad}"""
205207
PREFIX = "Answer questions as shown in the following examples, by splitting the question into individual search or lookup actions to find facts until you can answer the question. " \
206-
"Observations are prefixed by their source name in square brackets, source names MUST be included with the actions in the answers." \
207-
"Only answer the questions using the information from observations, do not speculate."
208+
"Observations are prefixed by their source name in angled brackets, source names MUST be included with the actions in the answers." \
209+
"All questions must be answered from the results from search or look up actions, only facts resulting from those can be used in an answer. "
210+
"Answer questions as truthfully as possible, and ONLY answer the questions using the information from observations, do not speculate or your own knowledge."

app/backend/approaches/readretrieveread.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from azure.search.documents import SearchClient
44
from azure.search.documents.models import QueryType
55
from langchain.llms.openai import AzureOpenAI
6-
from langchain.callbacks.base import CallbackManager
6+
from langchain.callbacks.manager import CallbackManager, Callbacks
77
from langchain.chains import LLMChain
88
from langchain.agents import Tool, ZeroShotAgent, AgentExecutor
99
from langchain.llms.openai import AzureOpenAI
@@ -77,8 +77,11 @@ def run(self, q: str, overrides: dict) -> any:
7777
cb_handler = HtmlCallbackHandler()
7878
cb_manager = CallbackManager(handlers=[cb_handler])
7979

80-
acs_tool = Tool(name = "CognitiveSearch", func = lambda q: self.retrieve(q, overrides), description = self.CognitiveSearchToolDescription)
81-
employee_tool = EmployeeInfoTool("Employee1")
80+
acs_tool = Tool(name="CognitiveSearch",
81+
func=lambda q: self.retrieve(q, overrides),
82+
description=self.CognitiveSearchToolDescription,
83+
callbacks=cb_manager)
84+
employee_tool = EmployeeInfoTool("Employee1", callbacks=cb_manager)
8285
tools = [acs_tool, employee_tool]
8386

8487
prompt = ZeroShotAgent.create_prompt(
@@ -103,8 +106,12 @@ def run(self, q: str, overrides: dict) -> any:
103106
class EmployeeInfoTool(CsvLookupTool):
104107
employee_name: str = ""
105108

106-
def __init__(self, employee_name: str):
107-
super().__init__(filename = "data/employeeinfo.csv", key_field = "name", name = "Employee", description = "useful for answering questions about the employee, their benefits and other personal information")
109+
def __init__(self, employee_name: str, callbacks: Callbacks = None):
110+
super().__init__(filename="data/employeeinfo.csv",
111+
key_field="name",
112+
name="Employee",
113+
description="useful for answering questions about the employee, their benefits and other personal information",
114+
callbacks=callbacks)
108115
self.func = self.employee_info
109116
self.employee_name = employee_name
110117

app/backend/langchainadapters.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,12 @@ def on_chain_error(self, error: Exception, **kwargs: Any) -> None:
4444
def on_tool_start(
4545
self,
4646
serialized: Dict[str, Any],
47-
action: AgentAction,
47+
input_str: str,
4848
color: Optional[str] = None,
4949
**kwargs: Any,
5050
) -> None:
5151
"""Print out the log in specified color."""
52-
self.html += f"<span style='color:{color}'>{ch(action.log)}</span><br>"
52+
pass
5353

5454
def on_tool_end(
5555
self,
@@ -69,12 +69,18 @@ def on_text(
6969
self,
7070
text: str,
7171
color: Optional[str] = None,
72-
end: str = "",
7372
**kwargs: Optional[str],
7473
) -> None:
7574
"""Run when agent ends."""
7675
self.html += f"<span style='color:{color}'>{ch(text)}</span><br>"
7776

77+
def on_agent_action(
78+
self,
79+
action: AgentAction,
80+
color: Optional[str] = None,
81+
**kwargs: Any) -> Any:
82+
self.html += f"<span style='color:{color}'>{ch(action.log)}</span><br>"
83+
7884
def on_agent_finish(
7985
self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any
8086
) -> None:

app/backend/lookuptool.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
from os import path
22
import csv
33
from langchain.agents import Tool
4+
from langchain.callbacks.manager import Callbacks
45
from typing import Optional
56

67
class CsvLookupTool(Tool):
7-
def __init__(self, filename: path, key_field: str, name: str = "lookup", description: str = "useful to look up details given an input key as opposite to searching data with an unstructured question"):
8-
super().__init__(name, self.lookup, description)
9-
self.data = {}
8+
data: dict[str, str] = {}
9+
10+
def __init__(self, filename: path, key_field: str, name: str = "lookup",
11+
description: str = "useful to look up details given an input key as opposite to searching data with an unstructured question",
12+
callbacks: Callbacks = None):
13+
super().__init__(name, self.lookup, description, callbacks=callbacks)
1014
with open(filename, newline='') as csvfile:
1115
reader = csv.DictReader(csvfile)
1216
for row in reader:

app/backend/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
azure-identity==1.13.0b3
22
Flask==2.2.2
3-
langchain==0.0.78
3+
langchain==0.0.187
44
openai==0.26.4
55
azure-search-documents==11.4.0b3
66
azure-storage-blob==12.14.1

0 commit comments

Comments
 (0)