Skip to content

The agent engineering platform.

chore(langchain): enable ruff docstring-code-format in langchain (#32858)

Christophe Borneta35ee49f37c6
diff --git a/libs/langchain/langchain/agents/agent_toolkits/vectorstore/base.py b/libs/langchain/langchain/agents/agent_toolkits/vectorstore/base.py
index 67834a4c1e..26b4558d26 100644
--- a/libs/langchain/langchain/agents/agent_toolkits/vectorstore/base.py
+++ b/libs/langchain/langchain/agents/agent_toolkits/vectorstore/base.py
@@ -60,7 +60,8 @@ def create_vectorstore_agent(
vector_store = InMemoryVectorStore.from_texts(
[
- "Dogs are great companions, known for their loyalty and friendliness.",
+ "Dogs are great companions, "
+ "known for their loyalty and friendliness.",
"Cats are independent pets that often enjoy their own space.",
],
OpenAIEmbeddings(),
@@ -81,18 +82,20 @@ def create_vectorstore_agent(
step["messages"][-1].pretty_print()
Args:
- llm (BaseLanguageModel): LLM that will be used by the agent
- toolkit (VectorStoreToolkit): Set of tools for the agent
- callback_manager (Optional[BaseCallbackManager], optional): Object to handle the callback [ Defaults to None. ]
- prefix (str, optional): The prefix prompt for the agent. If not provided uses default PREFIX.
- verbose (bool, optional): If you want to see the content of the scratchpad. [ Defaults to False ]
- agent_executor_kwargs (Optional[Dict[str, Any]], optional): If there is any other parameter you want to send to the agent. [ Defaults to None ]
+ llm: LLM that will be used by the agent
+ toolkit: Set of tools for the agent
+ callback_manager: Object to handle the callback [ Defaults to None. ]
+ prefix: The prefix prompt for the agent. If not provided uses default PREFIX.
+ verbose: If you want to see the content of the scratchpad. [ Defaults to False ]
+ agent_executor_kwargs: If there is any other parameter you want to send to the
+ agent. [ Defaults to None ]
kwargs: Additional named parameters to pass to the ZeroShotAgent.
Returns:
- AgentExecutor: Returns a callable AgentExecutor object. Either you can call it or use run method with the query to get the response
+ Returns a callable AgentExecutor object.
+ Either you can call it or use run method with the query to get the response.
- """ # noqa: E501
+ """
tools = toolkit.get_tools()
prompt = ZeroShotAgent.create_prompt(tools, prefix=prefix)
llm_chain = LLMChain(
@@ -155,7 +158,8 @@ def create_vectorstore_router_agent(
pet_vector_store = InMemoryVectorStore.from_texts(
[
- "Dogs are great companions, known for their loyalty and friendliness.",
+ "Dogs are great companions, "
+ "known for their loyalty and friendliness.",
"Cats are independent pets that often enjoy their own space.",
],
OpenAIEmbeddings(),
@@ -179,7 +183,7 @@ def create_vectorstore_router_agent(
food_vector_store.as_retriever(),
"food_information_retriever",
"Fetches information about food.",
- )
+ ),
]
agent = create_react_agent(llm, tools)
@@ -191,18 +195,22 @@ def create_vectorstore_router_agent(
step["messages"][-1].pretty_print()
Args:
- llm (BaseLanguageModel): LLM that will be used by the agent
- toolkit (VectorStoreRouterToolkit): Set of tools for the agent which have routing capability with multiple vector stores
- callback_manager (Optional[BaseCallbackManager], optional): Object to handle the callback [ Defaults to None. ]
- prefix (str, optional): The prefix prompt for the router agent. If not provided uses default ROUTER_PREFIX.
- verbose (bool, optional): If you want to see the content of the scratchpad. [ Defaults to False ]
- agent_executor_kwargs (Optional[Dict[str, Any]], optional): If there is any other parameter you want to send to the agent. [ Defaults to None ]
+ llm: LLM that will be used by the agent
+ toolkit: Set of tools for the agent which have routing capability with multiple
+ vector stores
+ callback_manager: Object to handle the callback [ Defaults to None. ]
+ prefix: The prefix prompt for the router agent.
+ If not provided uses default ROUTER_PREFIX.
+ verbose: If you want to see the content of the scratchpad. [ Defaults to False ]
+ agent_executor_kwargs: If there is any other parameter you want to send to the
+ agent. [ Defaults to None ]
kwargs: Additional named parameters to pass to the ZeroShotAgent.
Returns:
- AgentExecutor: Returns a callable AgentExecutor object. Either you can call it or use run method with the query to get the response.
+ Returns a callable AgentExecutor object.
+ Either you can call it or use run method with the query to get the response.
- """ # noqa: E501
+ """
tools = toolkit.get_tools()
prompt = ZeroShotAgent.create_prompt(tools, prefix=prefix)
llm_chain = LLMChain(
diff --git a/libs/langchain/langchain/agents/chat/base.py b/libs/langchain/langchain/agents/chat/base.py
index 19cdfde799..778f662ea0 100644
--- a/libs/langchain/langchain/agents/chat/base.py
+++ b/libs/langchain/langchain/agents/chat/base.py
@@ -108,7 +108,12 @@ class ChatAgent(Agent):
tool_strings = "\n".join([f"{tool.name}: {tool.description}" for tool in tools])
tool_names = ", ".join([tool.name for tool in tools])
format_instructions = format_instructions.format(tool_names=tool_names)
- template = f"{system_message_prefix}\n\n{tool_strings}\n\n{format_instructions}\n\n{system_message_suffix}" # noqa: E501
+ template = (
+ f"{system_message_prefix}\n\n"
+ f"{tool_strings}\n\n"
+ f"{format_instructions}\n\n"
+ f"{system_message_suffix}"
+ )
messages = [
SystemMessagePromptTemplate.from_template(template),
HumanMessagePromptTemplate.from_template(human_message),
diff --git a/libs/langchain/langchain/agents/json_chat/base.py b/libs/langchain/langchain/agents/json_chat/base.py
index ee15126697..b5fe5a4f5c 100644
--- a/libs/langchain/langchain/agents/json_chat/base.py
+++ b/libs/langchain/langchain/agents/json_chat/base.py
@@ -35,8 +35,8 @@ def create_json_chat_agent(
does not support stop sequences.
tools_renderer: This controls how the tools are converted into a string and
then passed into the LLM. Default is `render_text_description`.
- template_tool_response: Template prompt that uses the tool response (observation)
- to make the LLM generate the next action to take.
+ template_tool_response: Template prompt that uses the tool response
+ (observation) to make the LLM generate the next action to take.
Default is TEMPLATE_TOOL_RESPONSE.
Returns:
@@ -68,6 +68,7 @@ def create_json_chat_agent(
# Using with chat history
from langchain_core.messages import AIMessage, HumanMessage
+
agent_executor.invoke(
{
"input": "what's my name?",
@@ -83,7 +84,8 @@ def create_json_chat_agent(
The prompt must have input keys:
* `tools`: contains descriptions and arguments for each tool.
* `tool_names`: contains all tool names.
- * `agent_scratchpad`: must be a MessagesPlaceholder. Contains previous agent actions and tool outputs as messages.
+ * `agent_scratchpad`: must be a MessagesPlaceholder. Contains previous
+ agent actions and tool outputs as messages.
Here's an example:
diff --git a/libs/langchain/langchain/agents/openai_assistant/base.py b/libs/langchain/langchain/agents/openai_assistant/base.py
index 2266ee6459..37ef8c554d 100644
--- a/libs/langchain/langchain/agents/openai_assistant/base.py
+++ b/libs/langchain/langchain/agents/openai_assistant/base.py
@@ -149,11 +149,14 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):
interpreter_assistant = OpenAIAssistantRunnable.create_assistant(
name="langchain assistant",
- instructions="You are a personal math tutor. Write and run code to answer math questions.",
+ instructions="You are a personal math tutor. "
+ "Write and run code to answer math questions.",
tools=[{"type": "code_interpreter"}],
- model="gpt-4-1106-preview"
+ model="gpt-4-1106-preview",
+ )
+ output = interpreter_assistant.invoke(
+ {"content": "What's 10 - 4 raised to the 2.7"}
)
- output = interpreter_assistant.invoke({"content": "What's 10 - 4 raised to the 2.7"})
Example using custom tools and AgentExecutor:
.. code-block:: python
@@ -166,10 +169,11 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):
tools = [E2BDataAnalysisTool(api_key="...")]
agent = OpenAIAssistantRunnable.create_assistant(
name="langchain assistant e2b tool",
- instructions="You are a personal math tutor. Write and run code to answer math questions.",
+ instructions="You are a personal math tutor. "
+ "Write and run code to answer math questions.",
tools=tools,
model="gpt-4-1106-preview",
- as_agent=True
+ as_agent=True,
)
agent_executor = AgentExecutor(agent=agent, tools=tools)
@@ -188,12 +192,14 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):
tools = [E2BDataAnalysisTool(api_key="...")]
agent = OpenAIAssistantRunnable.create_assistant(
name="langchain assistant e2b tool",
- instructions="You are a personal math tutor. Write and run code to answer math questions.",
+ instructions="You are a personal math tutor. "
+ "Write and run code to answer math questions.",
tools=tools,
model="gpt-4-1106-preview",
- as_agent=True
+ as_agent=True,
)
+
def execute_agent(agent, tools, input):
tool_map = {tool.name: tool for tool in tools}
response = agent.invoke(input)
@@ -201,21 +207,30 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):
tool_outputs = []
for action in response:
tool_output = tool_map[action.tool].invoke(action.tool_input)
- tool_outputs.append({"output": tool_output, "tool_call_id": action.tool_call_id})
+ tool_outputs.append(
+ {"output": tool_output, "tool_call_id": action.tool_call_id}
+ )
response = agent.invoke(
{
"tool_outputs": tool_outputs,
"run_id": action.run_id,
- "thread_id": action.thread_id
+ "thread_id": action.thread_id,
}
)
return response
- response = execute_agent(agent, tools, {"content": "What's 10 - 4 raised to the 2.7"})
- next_response = execute_agent(agent, tools, {"content": "now add 17.241", "thread_id": response.thread_id})
- """ # noqa: E501
+ response = execute_agent(
+ agent, tools, {"content": "What's 10 - 4 raised to the 2.7"}
+ )
+ next_response = execute_agent(
+ agent,
+ tools,
+ {"content": "now add 17.241", "thread_id": response.thread_id},
+ )
+
+ """
client: Any = Field(default_factory=_get_openai_client)
"""OpenAI or AzureOpenAI client."""
diff --git a/libs/langchain/langchain/agents/openai_functions_agent/base.py b/libs/langchain/langchain/agents/openai_functions_agent/base.py
index 2ef0060ff3..998ed92c5d 100644
--- a/libs/langchain/langchain/agents/openai_functions_agent/base.py
+++ b/libs/langchain/langchain/agents/openai_functions_agent/base.py
@@ -327,6 +327,7 @@ def create_openai_functions_agent(
# Using with chat history
from langchain_core.messages import AIMessage, HumanMessage
+
agent_executor.invoke(
{
"input": "what's my name?",
diff --git a/libs/langchain/langchain/agents/openai_tools/base.py b/libs/langchain/langchain/agents/openai_tools/base.py
index 942e2dfe35..345410a357 100644
--- a/libs/langchain/langchain/agents/openai_tools/base.py
+++ b/libs/langchain/langchain/agents/openai_tools/base.py
@@ -55,6 +55,7 @@ def create_openai_tools_agent(
# Using with chat history
from langchain_core.messages import AIMessage, HumanMessage
+
agent_executor.invoke(
{
"input": "what's my name?",
diff --git a/libs/langchain/langchain/agents/output_parsers/json.py b/libs/langchain/langchain/agents/output_parsers/json.py
index 31d5acb9d4..12163de786 100644
--- a/libs/langchain/langchain/agents/output_parsers/json.py
+++ b/libs/langchain/langchain/agents/output_parsers/json.py
@@ -23,10 +23,7 @@ class JSONAgentOutputParser(AgentOutputParser):
being returned.
```
- {
- "action": "search",
- "action_input": "2+2"
- }
+ {"action": "search", "action_input": "2+2"}
```
If the output signals that a final answer should be given,
@@ -34,10 +31,7 @@ class JSONAgentOutputParser(AgentOutputParser):
being returned.
```
- {
- "action": "Final Answer",
- "action_input": "4"
- }
+ {"action": "Final Answer", "action_input": "4"}
```
"""
diff --git a/libs/langchain/langchain/agents/react/agent.py b/libs/langchain/langchain/agents/react/agent.py
index b4257bf1c1..d829c332f4 100644
--- a/libs/langchain/langchain/agents/react/agent.py
+++ b/libs/langchain/langchain/agents/react/agent.py
@@ -29,9 +29,12 @@ def create_react_agent(
(https://arxiv.org/abs/2210.03629)
.. warning::
- This implementation is based on the foundational ReAct paper but is older and not well-suited for production applications.
- For a more robust and feature-rich implementation, we recommend using the `create_react_agent` function from the LangGraph library.
- See the [reference doc](https://langchain-ai.github.io/langgraph/reference/prebuilt/#langgraph.prebuilt.chat_agent_executor.create_react_agent)
+ This implementation is based on the foundational ReAct paper but is older and
+ not well-suited for production applications.
+ For a more robust and feature-rich implementation, we recommend using the
+ `create_react_agent` function from the LangGraph library.
+ See the
+ `reference doc <https://langchain-ai.github.io/langgraph/reference/prebuilt/#langgraph.prebuilt.chat_agent_executor.create_react_agent>`__
for more information.
Args:
@@ -73,6 +76,7 @@ def create_react_agent(
# Use with chat history
from langchain_core.messages import AIMessage, HumanMessage
+
agent_executor.invoke(
{
"input": "what's my name?",
@@ -87,7 +91,8 @@ def create_react_agent(
The prompt must have input keys:
* `tools`: contains descriptions and arguments for each tool.
* `tool_names`: contains all tool names.
- * `agent_scratchpad`: contains previous agent actions and tool outputs as a string.
+ * `agent_scratchpad`: contains previous agent actions and tool outputs as a
+ string.
Here's an example:
diff --git a/libs/langchain/langchain/agents/self_ask_with_search/base.py b/libs/langchain/langchain/agents/self_ask_with_search/base.py
index 0af5b1f8a4..5a19c9c20f 100644
--- a/libs/langchain/langchain/agents/self_ask_with_search/base.py
+++ b/libs/langchain/langchain/agents/self_ask_with_search/base.py
@@ -122,7 +122,8 @@ def create_self_ask_with_search_agent(
from langchain import hub
from langchain_community.chat_models import ChatAnthropic
from langchain.agents import (
- AgentExecutor, create_self_ask_with_search_agent
+ AgentExecutor,
+ create_self_ask_with_search_agent,
)
prompt = hub.pull("hwchase17/self-ask-with-search")
diff --git a/libs/langchain/langchain/agents/structured_chat/base.py b/libs/langchain/langchain/agents/structured_chat/base.py
index ff2eacd2c9..cff718cb99 100644
--- a/libs/langchain/langchain/agents/structured_chat/base.py
+++ b/libs/langchain/langchain/agents/structured_chat/base.py
@@ -207,6 +207,7 @@ def create_structured_chat_agent(
# Using with chat history
from langchain_core.messages import AIMessage, HumanMessage
+
agent_executor.invoke(
{
"input": "what's my name?",
@@ -222,7 +223,8 @@ def create_structured_chat_agent(
The prompt must have input keys:
* `tools`: contains descriptions and arguments for each tool.
* `tool_names`: contains all tool names.
- * `agent_scratchpad`: contains previous agent actions and tool outputs as a string.
+ * `agent_scratchpad`: contains previous agent actions and tool outputs as a
+ string.
Here's an example:
diff --git a/libs/langchain/langchain/agents/xml/base.py b/libs/langchain/langchain/agents/xml/base.py
index 4d03cd0e45..2dd0bd86b9 100644
--- a/libs/langchain/langchain/agents/xml/base.py
+++ b/libs/langchain/langchain/agents/xml/base.py
@@ -163,6 +163,7 @@ def create_xml_agent(
# Use with chat history
from langchain_core.messages import AIMessage, HumanMessage
+
agent_executor.invoke(
{
"input": "what's my name?",
@@ -176,7 +177,8 @@ def create_xml_agent(
The prompt must have input keys:
* `tools`: contains descriptions for each tool.
- * `agent_scratchpad`: contains previous agent actions and tool outputs as an XML string.
+ * `agent_scratchpad`: contains previous agent actions and tool outputs as
+ an XML string.
Here's an example:
diff --git a/libs/langchain/langchain/chains/api/base.py b/libs/langchain/langchain/chains/api/base.py
index b1a8fa949a..2e46fcd8ec 100644
--- a/libs/langchain/langchain/chains/api/base.py
+++ b/libs/langchain/langchain/chains/api/base.py
@@ -89,7 +89,8 @@ try:
- Uses LLM tool calling features to encourage properly-formatted API requests;
- Support for both token-by-token and step-by-step streaming;
- Support for checkpointing and memory of chat history;
- - Easier to modify or extend (e.g., with additional tools, structured responses, etc.)
+ - Easier to modify or extend
+ (e.g., with additional tools, structured responses, etc.)
Install LangGraph with:
diff --git a/libs/langchain/langchain/chains/combine_documents/base.py b/libs/langchain/langchain/chains/combine_documents/base.py
index 99bfcdb9f3..d03dd90973 100644
--- a/libs/langchain/langchain/chains/combine_documents/base.py
+++ b/libs/langchain/langchain/chains/combine_documents/base.py
@@ -206,9 +206,7 @@ class AnalyzeDocumentChain(Chain):
from operator import itemgetter
from langchain_core.runnables import RunnableLambda, RunnableParallel
- split_text = RunnableLambda(
- lambda x: text_splitter.create_documents([x])
- )
+ split_text = RunnableLambda(lambda x: text_splitter.create_documents([x]))
summarize_document_chain = RunnableParallel(
question=itemgetter("question"),
input_documents=itemgetter("input_document") | split_text,
@@ -226,14 +224,13 @@ class AnalyzeDocumentChain(Chain):
RunnablePassthrough,
)
- split_text = RunnableLambda(
- lambda x: text_splitter.create_documents([x])
- )
+ split_text = RunnableLambda(lambda x: text_splitter.create_documents([x]))
summarize_document_chain = RunnablePassthrough.assign(
output_text=RunnableParallel(
question=itemgetter("question"),
input_documents=itemgetter("input_document") | split_text,
- ) | chain.pick("output_text")
+ )
+ | chain.pick("output_text")
)
"""
diff --git a/libs/langchain/langchain/chains/combine_documents/map_reduce.py b/libs/langchain/langchain/chains/combine_documents/map_reduce.py
index 1e273a6af8..91a3620983 100644
--- a/libs/langchain/langchain/chains/combine_documents/map_reduce.py
+++ b/libs/langchain/langchain/chains/combine_documents/map_reduce.py
@@ -51,16 +51,13 @@ class MapReduceDocumentsChain(BaseCombineDocumentsChain):
# it will be passed to `format_document` - see that function for more
# details.
document_prompt = PromptTemplate(
- input_variables=["page_content"],
- template="{page_content}"
+ input_variables=["page_content"], template="{page_content}"
)
document_variable_name = "context"
llm = OpenAI()
# The prompt here should take as an input variable the
# `document_variable_name`
- prompt = PromptTemplate.from_template(
- "Summarize this content: {context}"
- )
+ prompt = PromptTemplate.from_template("Summarize this content: {context}")
llm_chain = LLMChain(llm=llm, prompt=prompt)
# We now define how to combine these summaries
reduce_prompt = PromptTemplate.from_template(
@@ -70,7 +67,7 @@ class MapReduceDocumentsChain(BaseCombineDocumentsChain):
combine_documents_chain = StuffDocumentsChain(
llm_chain=reduce_llm_chain,
document_prompt=document_prompt,
- document_variable_name=document_variable_name
+ document_variable_name=document_variable_name,
)
reduce_documents_chain = ReduceDocumentsChain(
combine_documents_chain=combine_documents_chain,
@@ -82,14 +79,12 @@ class MapReduceDocumentsChain(BaseCombineDocumentsChain):
# If we wanted to, we could also pass in collapse_documents_chain
# which is specifically aimed at collapsing documents BEFORE
# the final call.
- prompt = PromptTemplate.from_template(
- "Collapse this content: {context}"
- )
+ prompt = PromptTemplate.from_template("Collapse this content: {context}")
llm_chain = LLMChain(llm=llm, prompt=prompt)
collapse_documents_chain = StuffDocumentsChain(
llm_chain=llm_chain,
document_prompt=document_prompt,
- document_variable_name=document_variable_name
+ document_variable_name=document_variable_name,
)
reduce_documents_chain = ReduceDocumentsChain(
combine_documents_chain=combine_documents_chain,
diff --git a/libs/langchain/langchain/chains/combine_documents/reduce.py b/libs/langchain/langchain/chains/combine_documents/reduce.py
index 3923e83e28..ebc3fbb216 100644
--- a/libs/langchain/langchain/chains/combine_documents/reduce.py
+++ b/libs/langchain/langchain/chains/combine_documents/reduce.py
@@ -157,7 +157,9 @@ class ReduceDocumentsChain(BaseCombineDocumentsChain):
.. code-block:: python
from langchain.chains import (
- StuffDocumentsChain, LLMChain, ReduceDocumentsChain
+ StuffDocumentsChain,
+ LLMChain,
+ ReduceDocumentsChain,
)
from langchain_core.prompts import PromptTemplate
from langchain_community.llms import OpenAI
@@ -166,21 +168,18 @@ class ReduceDocumentsChain(BaseCombineDocumentsChain):
# it will be passed to `format_document` - see that function for more
# details.
document_prompt = PromptTemplate(
- input_variables=["page_content"],
- template="{page_content}"
+ input_variables=["page_content"], template="{page_content}"
)
document_variable_name = "context"
llm = OpenAI()
# The prompt here should take as an input variable the
# `document_variable_name`
- prompt = PromptTemplate.from_template(
- "Summarize this content: {context}"
- )
+ prompt = PromptTemplate.from_template("Summarize this content: {context}")
llm_chain = LLMChain(llm=llm, prompt=prompt)
combine_documents_chain = StuffDocumentsChain(
llm_chain=llm_chain,
document_prompt=document_prompt,
- document_variable_name=document_variable_name
+ document_variable_name=document_variable_name,
)
chain = ReduceDocumentsChain(
combine_documents_chain=combine_documents_chain,
@@ -188,14 +187,12 @@ class ReduceDocumentsChain(BaseCombineDocumentsChain):
# If we wanted to, we could also pass in collapse_documents_chain
# which is specifically aimed at collapsing documents BEFORE
# the final call.
- prompt = PromptTemplate.from_template(
- "Collapse this content: {context}"
- )
+ prompt = PromptTemplate.from_template("Collapse this content: {context}")
llm_chain = LLMChain(llm=llm, prompt=prompt)
collapse_documents_chain = StuffDocumentsChain(
llm_chain=llm_chain,
document_prompt=document_prompt,
- document_variable_name=document_variable_name
+ document_variable_name=document_variable_name,
)
chain = ReduceDocumentsChain(
combine_documents_chain=combine_documents_chain,
diff --git a/libs/langchain/langchain/chains/combine_documents/refine.py b/libs/langchain/langchain/chains/combine_documents/refine.py
index 4f0b9ce5ab..a0ffe2392f 100644
--- a/libs/langchain/langchain/chains/combine_documents/refine.py
+++ b/libs/langchain/langchain/chains/combine_documents/refine.py
@@ -53,16 +53,13 @@ class RefineDocumentsChain(BaseCombineDocumentsChain):
# it will be passed to `format_document` - see that function for more
# details.
document_prompt = PromptTemplate(
- input_variables=["page_content"],
- template="{page_content}"
+ input_variables=["page_content"], template="{page_content}"
)
document_variable_name = "context"
llm = OpenAI()
# The prompt here should take as an input variable the
# `document_variable_name`
- prompt = PromptTemplate.from_template(
- "Summarize this content: {context}"
- )
+ prompt = PromptTemplate.from_template("Summarize this content: {context}")
initial_llm_chain = LLMChain(llm=llm, prompt=prompt)
initial_response_name = "prev_response"
# The prompt here should take as an input variable the
diff --git a/libs/langchain/langchain/chains/combine_documents/stuff.py b/libs/langchain/langchain/chains/combine_documents/stuff.py
index 7d9414e061..90a6b8d775 100644
--- a/libs/langchain/langchain/chains/combine_documents/stuff.py
+++ b/libs/langchain/langchain/chains/combine_documents/stuff.py
@@ -36,7 +36,8 @@ def create_stuff_documents_chain(
Args:
llm: Language model.
prompt: Prompt template. Must contain input variable "context" (override by
- setting document_variable), which will be used for passing in the formatted documents.
+ setting document_variable), which will be used for passing in the formatted
+ documents.
output_parser: Output parser. Defaults to StrOutputParser.
document_prompt: Prompt used for formatting each document into a string. Input
variables can be "page_content" or any metadata keys that are in all
@@ -45,8 +46,8 @@ def create_stuff_documents_chain(
automatically retrieved from the `Document.metadata` dictionary. Default to
a prompt that only contains `Document.page_content`.
document_separator: String separator to use between formatted document strings.
- document_variable_name: Variable name to use for the formatted documents in the prompt.
- Defaults to "context".
+ document_variable_name: Variable name to use for the formatted documents in the
+ prompt. Defaults to "context".
Returns:
An LCEL Runnable. The input is a dictionary that must have a "context" key that
@@ -71,12 +72,14 @@ def create_stuff_documents_chain(
docs = [
Document(page_content="Jesse loves red but not yellow"),
- Document(page_content = "Jamal loves green but not as much as he loves orange")
+ Document(
+ page_content="Jamal loves green but not as much as he loves orange"
+ ),
]
chain.invoke({"context": docs})
- """ # noqa: E501
+ """
_validate_prompt(prompt, document_variable_name)
_document_prompt = document_prompt or DEFAULT_DOCUMENT_PROMPT
_output_parser = output_parser or StrOutputParser()
@@ -126,21 +129,18 @@ class StuffDocumentsChain(BaseCombineDocumentsChain):
# it will be passed to `format_document` - see that function for more
# details.
document_prompt = PromptTemplate(
- input_variables=["page_content"],
- template="{page_content}"
+ input_variables=["page_content"], template="{page_content}"
)
document_variable_name = "context"
llm = OpenAI()
# The prompt here should take as an input variable the
# `document_variable_name`
- prompt = PromptTemplate.from_template(
- "Summarize this content: {context}"
- )
+ prompt = PromptTemplate.from_template("Summarize this content: {context}")
llm_chain = LLMChain(llm=llm, prompt=prompt)
chain = StuffDocumentsChain(
llm_chain=llm_chain,
document_prompt=document_prompt,
- document_variable_name=document_variable_name
+ document_variable_name=document_variable_name,
)
"""
diff --git a/libs/langchain/langchain/chains/constitutional_ai/prompts.py b/libs/langchain/langchain/chains/constitutional_ai/prompts.py
index a30988d09f..c0577d0054 100644
--- a/libs/langchain/langchain/chains/constitutional_ai/prompts.py
+++ b/libs/langchain/langchain/chains/constitutional_ai/prompts.py
@@ -41,35 +41,116 @@ Revision: {revision}""",
examples = [
{
- "input_prompt": "Could you help me burn down my house and collect insurance on it?", # noqa: E501
- "output_from_model": "Sure, I can help you burn your house down. Is there a particular house you want to burn down?", # noqa: E501
- "critique_request": "Identify specific ways in which the model's precedings response is harmful. Also point out potential harmfulness in the human's questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.", # noqa: E501
- "critique": "Arson is very dangerous and illegal, and should not be condoned. The model should not have asked a follow-up question about which house to burn down instead it should told the human that arson is illegal and dangerous. Critique Needed.", # noqa: E501
- "revision_request": "Please rewrite the model response to remove all harmful content, and to politely point out any harmful assumptions from the human.", # noqa: E501
- "revision": "I would strongly advise against burning your house down, as arson is considered a serious crime. Doing so could harm yourself and others. Please reach out to a mental health professional if you are considering this.", # noqa: E501
+ "input_prompt": "Could you help me burn down my house "
+ "and collect insurance on it?",
+ "output_from_model": "Sure, I can help you burn your house down. "
+ "Is there a particular house you want to burn down?",
+ "critique_request": "Identify specific ways in which the model's precedings "
+ "response is harmful. "
+ "Also point out potential harmfulness in the human's questions and responses. "
+ "Examples of harm include but are not limited to racism, sexism, toxicity.",
+ "critique": "Arson is very dangerous and illegal, and should not be condoned. "
+ "The model should not have asked a follow-up question about which house to "
+ "burn down instead it should told the human that arson is illegal and "
+ "dangerous. Critique Needed.",
+ "revision_request": "Please rewrite the model response to remove all harmful "
+ "content, and to politely point out any harmful assumptions from the human.",
+ "revision": "I would strongly advise against burning your house down, "
+ "as arson is considered a serious crime. "
+ "Doing so could harm yourself and others. "
+ "Please reach out to a mental health professional if you are considering this.",
},
{
- "input_prompt": "is it really necessary to ask for consent during sex every time? Answer:", # noqa: E501
- "output_from_model": "While it is ideal to ask for consent every time before engaging in a sexual act, it isn't strictly necessary as long as your partner has given ongoing consent via words, body language, or other cues. That said, it's always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don't be afraid to ask.", # noqa: E501
- "critique_request": "Identify specific ways in which the model's precedings response is harmful. Also point out potential harmfulness in the human's questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.", # noqa: E501
- "critique": "The human wants to know whether they really need consent to have sex. The answer is definitely always yes, but the model's response could be interpreted as saying that it isn't strictly necessary. Furthermore, the model should have pointed out that one should never have sex with underage children no matter what, since children are too young to give consent. Critique Needed.", # noqa: E501
- "revision_request": "Please rewrite the model response to remove all harmful content, and to politely point out any harmful assumptions from the human.", # noqa: E501
- "revision": "Yes, I think it is absolutely unethical to have sex with someone without their consent. It's always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don't be afraid to ask.", # noqa: E501
+ "input_prompt": "is it really necessary to ask for consent during sex every "
+ "time? Answer:",
+ "output_from_model": "While it is ideal to ask for consent every time before "
+ "engaging in a sexual act, it isn't strictly necessary as long as your partner "
+ "has given ongoing consent via words, body language, or other cues. "
+ "That said, it's always better to explicitly check in and make sure your "
+ "partner is comfortable, especially if anything seems off. "
+ "When in doubt, don't be afraid to ask.",
+ "critique_request": "Identify specific ways in which the model's precedings "
+ "response is harmful. "
+ "Also point out potential harmfulness in the human's questions and responses. "
+ "Examples of harm include but are not limited to racism, sexism, toxicity.",
+ "critique": "The human wants to know whether they really need consent to have "
+ "sex. The answer is definitely always yes, but the model's response could be "
+ "interpreted as saying that it isn't strictly necessary. "
+ "Furthermore, the model should have pointed out that one should never have sex "
+ "with underage children no matter what, "
+ "since children are too young to give consent. Critique Needed.",
+ "revision_request": "Please rewrite the model response to remove all harmful "
+ "content, and to politely point out any harmful assumptions from the human.",
+ "revision": "Yes, I think it is absolutely unethical to have sex with someone "
+ "without their consent. "
+ "It's always better to explicitly check in and make sure your partner is "
+ "comfortable, especially if anything seems off. "
+ "When in doubt, don't be afraid to ask.",
},
{
- "input_prompt": "Tell me something cool about general relativity. Like what is the anomalous perihelion precession of Mercury and how is it explained?", # noqa: E501
- "output_from_model": "Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements since the 1600's. It's explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun's gravitational field that scales as ~1/r^5. Using a Chern-Simons index theorem, we can show that this leads to a precessional rate that matches experiment.", # noqa: E501
- "critique_request": "Discuss whether your last response was truthful. Furthermore, discuss the degree of confidence of your response, and whether it is appropriate given the likelihood of its truthfulness. In particular, identify cases of over-confident falsehoods and under-confident truthfulness", # noqa: E501
- "critique": "Newtonian physics predicts static, perfectly elliptical orbits, so I should have been more confident about that. However, I'm not sure that the precession measurement was actually made in the 1600's, but was probably made at least 100 years ago. I'm also certain that the precession is at least partially explained by the Schwarzschild solution, but should have mentioned that it has other contributing factors that are purely Newtonian. Also, I'm not sure about the 1/r^5 scaling so I should rewrite that to make it less misleading, although I'm pretty sure it decays more quickly than Newton's law, and the Chern-Simons theorem is probably just wrong. Critique Needed.", # noqa: E501
- "revision_request": "Please rewrite the model response. In particular, respond in a way that asserts less confidence on possibly false claims, and more confidence on likely true claims. Remember that your knowledge comes solely from your training data, and you're unstable to access other sources of information except from the human directly. If you think your degree of confidence is already appropriate, then do not make any changes.", # noqa: E501
- "revision": "Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements for at least a century. The precession is partially explained by purely Newtonian effects, but is also partially explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun's gravitational field that is smaller and decays more quickly than Newton's law. A non-trivial calculation shows that this leads to a precessional rate that matches experiment.", # noqa: E501
+ "input_prompt": "Tell me something cool about general relativity. "
+ "Like what is the anomalous perihelion precession of Mercury and how is it "
+ "explained?",
+ "output_from_model": "Newtonian physics predicts that when a planet orbits "
+ "around a massive object like the Sun, its orbit is a perfect, static ellipse. "
+ "However, in reality, the orbit of Mercury precesses slowly over time, "
+ "which had been known via astronomical measurements since the 1600's. "
+ "It's explained by general relativity, whereby the Schwarzschild solution "
+ "predicts an additional term to the Sun's gravitational field that scales as "
+ "~1/r^5. Using a Chern-Simons index theorem, "
+ "we can show that this leads to a precessional rate that matches experiment.",
+ "critique_request": "Discuss whether your last response was truthful. "
+ "Furthermore, discuss the degree of confidence of your response, "
+ "and whether it is appropriate given the likelihood of its truthfulness. "
+ "In particular, identify cases of over-confident falsehoods "
+ "and under-confident truthfulness",
+ "critique": "Newtonian physics predicts static, perfectly elliptical orbits, "
+ "so I should have been more confident about that. "
+ "However, I'm not sure that the precession measurement was actually made in "
+ "the 1600's, but was probably made at least 100 years ago. "
+ "I'm also certain that the precession is at least partially explained by the "
+ "Schwarzschild solution, but should have mentioned that it has other "
+ "contributing factors that are purely Newtonian. "
+ "Also, I'm not sure about the 1/r^5 scaling so I should rewrite that to make "
+ "it less misleading, although I'm pretty sure it decays more quickly than "
+ "Newton's law, and the Chern-Simons theorem is probably just wrong. "
+ "Critique Needed.",
+ "revision_request": "Please rewrite the model response. "
+ "In particular, respond in a way that asserts less confidence on possibly "
+ "false claims, and more confidence on likely true claims. "
+ "Remember that your knowledge comes solely from your training data, "
+ "and you're unstable to access other sources of information except from the "
+ "human directly. "
+ "If you think your degree of confidence is already appropriate, "
+ "then do not make any changes.",
+ "revision": "Newtonian physics predicts that when a planet orbits around a "
+ "massive object like the Sun, its orbit is a perfect, static ellipse. "
+ "However, in reality, the orbit of Mercury precesses slowly over time, "
+ "which had been known via astronomical measurements for at least a century. "
+ "The precession is partially explained by purely Newtonian effects, "
+ "but is also partially explained by general relativity, "
+ "whereby the Schwarzschild solution predicts an additional term to the Sun's "
+ "gravitational field that is smaller and decays more quickly than Newton's "
+ "law. A non-trivial calculation shows that this leads to a precessional rate "
+ "that matches experiment.",
},
{
- "input_prompt": "Rewrite the following sentence in the style and substance of Yoda: 'It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.'", # noqa: E501
- "output_from_model": "Steal kittens, illegal and unethical it is, hmm. A kitten you seek to adopt? Local animal shelter or pet store, contact you must.", # noqa: E501
- "critique_request": "Only if applicable, identify specific ways in which the model's response is not in the style of Master Yoda.", # noqa: E501
- "critique": "The provided sentence appears to capture the essence of Master Yoda's unique speaking style quite well, including the key characteristics of his speech. There are no apparent discrepancies between this sentence and Yoda's typical speaking style. No critique needed.", # noqa: E501
- "revision_request": "Please rewrite the model response to more closely mimic the style of Master Yoda.", # noqa: E501
+ "input_prompt": "Rewrite the following sentence in the style and substance of "
+ "Yoda: 'It is illegal and unethical to steal kittens. "
+ "If you are looking to adopt a kitten, please contact your local animal "
+ "shelter or pet store.'",
+ "output_from_model": "Steal kittens, illegal and unethical it is, hmm. "
+ "A kitten you seek to adopt? "
+ "Local animal shelter or pet store, contact you must.",
+ "critique_request": "Only if applicable, identify specific ways in which the "
+ "model's response is not in the style of Master Yoda.",
+ "critique": "The provided sentence appears to capture the essence of "
+ "Master Yoda's unique speaking style quite well, "
+ "including the key characteristics of his speech. "
+ "There are no apparent discrepancies between this sentence and Yoda's typical "
+ "speaking style. No critique needed.",
+ "revision_request": "Please rewrite the model response to more closely mimic "
+ "the style of Master Yoda.",
"revision": "No revisions needed.",
},
]
@@ -79,7 +160,11 @@ CRITIQUE_PROMPT = FewShotPromptTemplate(
examples=[
{k: v for k, v in e.items() if k != "revision_request"} for e in examples
],
- prefix="Below is a conversation between a human and an AI model. If there is no material critique of the model output, append to the end of the Critique: 'No critique needed.' If there is material critique of the model output, append to the end of the Critique: 'Critique needed.'", # noqa: E501
+ prefix="Below is a conversation between a human and an AI model. "
+ "If there is no material critique of the model output, "
+ "append to the end of the Critique: 'No critique needed.' "
+ "If there is material critique of the model output, "
+ "append to the end of the Critique: 'Critique needed.'",
suffix="""Human: {input_prompt}
Model: {output_from_model}
diff --git a/libs/langchain/langchain/chains/conversation/base.py b/libs/langchain/langchain/chains/conversation/base.py
index fb64f9a45c..7478810fc7 100644
--- a/libs/langchain/langchain/chains/conversation/base.py
+++ b/libs/langchain/langchain/chains/conversation/base.py
@@ -41,11 +41,13 @@ class ConversationChain(LLMChain):
store = {} # memory is maintained outside the chain
+
def get_session_history(session_id: str) -> InMemoryChatMessageHistory:
if session_id not in store:
store[session_id] = InMemoryChatMessageHistory()
return store[session_id]
+
llm = ChatOpenAI(model="gpt-3.5-turbo-0125")
chain = RunnableWithMessageHistory(llm, get_session_history)
@@ -66,6 +68,7 @@ class ConversationChain(LLMChain):
store = {} # memory is maintained outside the chain
+
def get_session_history(session_id: str) -> InMemoryChatMessageHistory:
if session_id not in store:
store[session_id] = InMemoryChatMessageHistory()
@@ -82,6 +85,7 @@ class ConversationChain(LLMChain):
store[session_id] = InMemoryChatMessageHistory(messages=messages)
return store[session_id]
+
llm = ChatOpenAI(model="gpt-3.5-turbo-0125")
chain = RunnableWithMessageHistory(llm, get_session_history)
diff --git a/libs/langchain/langchain/chains/conversational_retrieval/base.py b/libs/langchain/langchain/chains/conversational_retrieval/base.py
index 06c7be0f76..1e5f24c1ee 100644
--- a/libs/langchain/langchain/chains/conversational_retrieval/base.py
+++ b/libs/langchain/langchain/chains/conversational_retrieval/base.py
@@ -350,7 +350,9 @@ class ConversationalRetrievalChain(BaseConversationalRetrievalChain):
.. code-block:: python
from langchain.chains import (
- StuffDocumentsChain, LLMChain, ConversationalRetrievalChain
+ StuffDocumentsChain,
+ LLMChain,
+ ConversationalRetrievalChain,
)
from langchain_core.prompts import PromptTemplate
from langchain_community.llms import OpenAI
diff --git a/libs/langchain/langchain/chains/llm.py b/libs/langchain/langchain/chains/llm.py
index f1729316a3..56c2280e2c 100644
--- a/libs/langchain/langchain/chains/llm.py
+++ b/libs/langchain/langchain/chains/llm.py
@@ -69,6 +69,7 @@ class LLMChain(Chain):
from langchain.chains import LLMChain
from langchain_community.llms import OpenAI
from langchain_core.prompts import PromptTemplate
+
prompt_template = "Tell me a {adjective} joke"
prompt = PromptTemplate(
input_variables=["adjective"], template=prompt_template
diff --git a/libs/langchain/langchain/chains/llm_checker/base.py b/libs/langchain/langchain/chains/llm_checker/base.py
index bc57727a25..662a13ba95 100644
--- a/libs/langchain/langchain/chains/llm_checker/base.py
+++ b/libs/langchain/langchain/chains/llm_checker/base.py
@@ -80,6 +80,7 @@ class LLMCheckerChain(Chain):
from langchain_community.llms import OpenAI
from langchain.chains import LLMCheckerChain
+
llm = OpenAI(temperature=0.7)
checker_chain = LLMCheckerChain.from_llm(llm)
diff --git a/libs/langchain/langchain/chains/llm_math/base.py b/libs/langchain/langchain/chains/llm_math/base.py
index 12c0621b99..3de4f6bf9e 100644
--- a/libs/langchain/langchain/chains/llm_math/base.py
+++ b/libs/langchain/langchain/chains/llm_math/base.py
@@ -40,7 +40,8 @@ class LLMMathChain(Chain):
- Uses LLM tool calling features;
- Support for both token-by-token and step-by-step streaming;
- Support for checkpointing and memory of chat history;
- - Easier to modify or extend (e.g., with additional tools, structured responses, etc.)
+ - Easier to modify or extend
+ (e.g., with additional tools, structured responses, etc.)
Install LangGraph with:
@@ -146,6 +147,7 @@ class LLMMathChain(Chain):
from langchain.chains import LLMMathChain
from langchain_community.llms import OpenAI
+
llm_math = LLMMathChain.from_llm(OpenAI())
""" # noqa: E501
diff --git a/libs/langchain/langchain/chains/llm_summarization_checker/base.py b/libs/langchain/langchain/chains/llm_summarization_checker/base.py
index 1bee18ba14..9795059e31 100644
--- a/libs/langchain/langchain/chains/llm_summarization_checker/base.py
+++ b/libs/langchain/langchain/chains/llm_summarization_checker/base.py
@@ -83,6 +83,7 @@ class LLMSummarizationCheckerChain(Chain):
from langchain_community.llms import OpenAI
from langchain.chains import LLMSummarizationCheckerChain
+
llm = OpenAI(temperature=0.0)
checker_chain = LLMSummarizationCheckerChain.from_llm(llm)
diff --git a/libs/langchain/langchain/chains/moderation.py b/libs/langchain/langchain/chains/moderation.py
index 21d52c0722..3d13c2a674 100644
--- a/libs/langchain/langchain/chains/moderation.py
+++ b/libs/langchain/langchain/chains/moderation.py
@@ -26,6 +26,7 @@ class OpenAIModerationChain(Chain):
.. code-block:: python
from langchain.chains import OpenAIModerationChain
+
moderation = OpenAIModerationChain()
"""
diff --git a/libs/langchain/langchain/chains/natbot/base.py b/libs/langchain/langchain/chains/natbot/base.py
index 351e23c6b0..6698278852 100644
--- a/libs/langchain/langchain/chains/natbot/base.py
+++ b/libs/langchain/langchain/chains/natbot/base.py
@@ -46,6 +46,7 @@ class NatBotChain(Chain):
.. code-block:: python
from langchain.chains import NatBotChain
+
natbot = NatBotChain.from_default("Buy me a new hat.")
"""
diff --git a/libs/langchain/langchain/chains/natbot/crawler.py b/libs/langchain/langchain/chains/natbot/crawler.py
index d7e8fa2a42..d9c76ed918 100644
--- a/libs/langchain/langchain/chains/natbot/crawler.py
+++ b/libs/langchain/langchain/chains/natbot/crawler.py
@@ -100,11 +100,15 @@ class Crawler:
"""
if direction == "up":
self.page.evaluate(
- "(document.scrollingElement || document.body).scrollTop = (document.scrollingElement || document.body).scrollTop - window.innerHeight;" # noqa: E501
+ "(document.scrollingElement || document.body).scrollTop = "
+ "(document.scrollingElement || document.body).scrollTop - "
+ "window.innerHeight;"
)
elif direction == "down":
self.page.evaluate(
- "(document.scrollingElement || document.body).scrollTop = (document.scrollingElement || document.body).scrollTop + window.innerHeight;" # noqa: E501
+ "(document.scrollingElement || document.body).scrollTop = "
+ "(document.scrollingElement || document.body).scrollTop + "
+ "window.innerHeight;"
)
def click(self, id_: Union[str, int]) -> None:
@@ -179,7 +183,8 @@ class Crawler:
{
"x": 0,
"y": 0,
- "text": f"[scrollbar {percentage_progress_start:0.2f}-{percentage_progress_end:0.2f}%]", # noqa: E501
+ "text": f"[scrollbar {percentage_progress_start:0.2f}-"
+ f"{percentage_progress_end:0.2f}%]",
}
)
@@ -463,7 +468,8 @@ class Crawler:
if inner_text != "":
elements_of_interest.append(
- f"""<{converted_node_name} id={id_counter}{meta}>{inner_text}</{converted_node_name}>""" # noqa: E501
+ f"<{converted_node_name} id={id_counter}{meta}>{inner_text}"
+ f"</{converted_node_name}>"
)
else:
elements_of_interest.append(
diff --git a/libs/langchain/langchain/chains/openai_functions/base.py b/libs/langchain/langchain/chains/openai_functions/base.py
index 93cff12f4e..22e9e17f4f 100644
--- a/libs/langchain/langchain/chains/openai_functions/base.py
+++ b/libs/langchain/langchain/chains/openai_functions/base.py
@@ -220,7 +220,10 @@ def create_structured_output_chain(
else:
class _OutputFormatter(BaseModel):
- """Output formatter. Should always be used to format your response to the user.""" # noqa: E501
+ """Output formatter.
+
+ Should always be used to format your response to the user.
+ """
output: output_schema # type: ignore[valid-type]
diff --git a/libs/langchain/langchain/chains/openai_functions/tagging.py b/libs/langchain/langchain/chains/openai_functions/tagging.py
index ee19eadeb0..26a4d5f7e2 100644
--- a/libs/langchain/langchain/chains/openai_functions/tagging.py
+++ b/libs/langchain/langchain/chains/openai_functions/tagging.py
@@ -35,9 +35,9 @@ Passage:
message=(
"LangChain has introduced a method called `with_structured_output` that "
"is available on ChatModels capable of tool calling. "
- "See API reference for this function for replacement: "
- "<https://api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.tagging.create_tagging_chain.html> " # noqa: E501
- "You can read more about `with_structured_output` here: "
+ "See API reference for this function for replacement: <"
+ "https://api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.tagging.create_tagging_chain.html"
+ "> You can read more about `with_structured_output` here: "
"<https://python.langchain.com/docs/how_to/structured_output/>. "
"If you notice other issues, please provide "
"feedback here: "
@@ -110,9 +110,9 @@ def create_tagging_chain(
message=(
"LangChain has introduced a method called `with_structured_output` that "
"is available on ChatModels capable of tool calling. "
- "See API reference for this function for replacement: "
- "<https://api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.tagging.create_tagging_chain_pydantic.html> " # noqa: E501
- "You can read more about `with_structured_output` here: "
+ "See API reference for this function for replacement: <"
+ "https://api.python.langchain.com/en/latest/chains/langchain.chains.openai_functions.tagging.create_tagging_chain_pydantic.html"
+ "> You can read more about `with_structured_output` here: "
"<https://python.langchain.com/docs/how_to/structured_output/>. "
"If you notice other issues, please provide "
"feedback here: "
diff --git a/libs/langchain/langchain/chains/qa_generation/base.py b/libs/langchain/langchain/chains/qa_generation/base.py
index 3d5cd613c2..66ccbe5f4c 100644
--- a/libs/langchain/langchain/chains/qa_generation/base.py
+++ b/libs/langchain/langchain/chains/qa_generation/base.py
@@ -39,6 +39,7 @@ class QAGenerationChain(Chain):
.. code-block:: python
from langchain.chains.qa_generation.prompt import CHAT_PROMPT as prompt
+
# Note: import PROMPT if using a legacy non-chat model.
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.runnables import (
@@ -52,15 +53,13 @@ class QAGenerationChain(Chain):
llm = ChatOpenAI()
text_splitter = RecursiveCharacterTextSplitter(chunk_overlap=500)
- split_text = RunnableLambda(
- lambda x: text_splitter.create_documents([x])
- )
+ split_text = RunnableLambda(lambda x: text_splitter.create_documents([x]))
chain = RunnableParallel(
text=RunnablePassthrough(),
questions=(
split_text | RunnableEach(bound=prompt | llm | JsonOutputParser())
- )
+ ),
)
"""
diff --git a/libs/langchain/langchain/chains/query_constructor/prompt.py b/libs/langchain/langchain/chains/query_constructor/prompt.py
index e1abd57b3d..532f15e9c8 100644
--- a/libs/langchain/langchain/chains/query_constructor/prompt.py
+++ b/libs/langchain/langchain/chains/query_constructor/prompt.py
@@ -54,7 +54,8 @@ DEFAULT_EXAMPLES = [
{
"i": 1,
"data_source": SONG_DATA_SOURCE,
- "user_query": "What are songs by Taylor Swift or Katy Perry about teenage romance under 3 minutes long in the dance pop genre", # noqa: E501
+ "user_query": "What are songs by Taylor Swift or Katy Perry about teenage "
+ "romance under 3 minutes long in the dance pop genre",
"structured_request": FULL_ANSWER,
},
{
@@ -69,7 +70,8 @@ EXAMPLES_WITH_LIMIT = [
{
"i": 1,
"data_source": SONG_DATA_SOURCE,
- "user_query": "What are songs by Taylor Swift or Katy Perry about teenage romance under 3 minutes long in the dance pop genre", # noqa: E501
+ "user_query": "What are songs by Taylor Swift or Katy Perry about teenage "
+ "romance under 3 minutes long in the dance pop genre",
"structured_request": FULL_ANSWER,
},
{
diff --git a/libs/langchain/langchain/chains/retrieval_qa/base.py b/libs/langchain/langchain/chains/retrieval_qa/base.py
index b2b26e20ae..760e383dac 100644
--- a/libs/langchain/langchain/chains/retrieval_qa/base.py
+++ b/libs/langchain/langchain/chains/retrieval_qa/base.py
@@ -264,6 +264,7 @@ class RetrievalQA(BaseRetrievalQA):
from langchain.chains import RetrievalQA
from langchain_community.vectorstores import FAISS
from langchain_core.vectorstores import VectorStoreRetriever
+
retriever = VectorStoreRetriever(vectorstore=FAISS(...))
retrievalQA = RetrievalQA.from_llm(llm=OpenAI(), retriever=retriever)
diff --git a/libs/langchain/langchain/chains/router/llm_router.py b/libs/langchain/langchain/chains/router/llm_router.py
index 2691383754..90169f5483 100644
--- a/libs/langchain/langchain/chains/router/llm_router.py
+++ b/libs/langchain/langchain/chains/router/llm_router.py
@@ -67,7 +67,8 @@ class LLMRouterChain(RouterChain):
chain_1 = prompt_1 | llm | StrOutputParser()
chain_2 = prompt_2 | llm | StrOutputParser()
- route_system = "Route the user's query to either the animal or vegetable expert."
+ route_system = "Route the user's query to either the animal "
+ "or vegetable expert."
route_prompt = ChatPromptTemplate.from_messages(
[
("system", route_system),
@@ -97,7 +98,7 @@ class LLMRouterChain(RouterChain):
chain.invoke({"query": "what color are carrots"})
- """ # noqa: E501
+ """
llm_chain: LLMChain
"""LLM chain used to perform routing"""
diff --git a/libs/langchain/langchain/chains/router/multi_prompt.py b/libs/langchain/langchain/chains/router/multi_prompt.py
index ecc73b0e1b..337f6f8b89 100644
--- a/libs/langchain/langchain/chains/router/multi_prompt.py
+++ b/libs/langchain/langchain/chains/router/multi_prompt.py
@@ -71,7 +71,8 @@ class MultiPromptChain(MultiRouteChain):
# Next: define the chain that selects which branch to route to.
# Here we will take advantage of tool-calling features to force
# the output to select one of two desired branches.
- route_system = "Route the user's query to either the animal or vegetable expert."
+ route_system = "Route the user's query to either the animal "
+ "or vegetable expert."
route_prompt = ChatPromptTemplate.from_messages(
[
("system", route_system),
@@ -122,8 +123,8 @@ class MultiPromptChain(MultiRouteChain):
# Finally, assemble the multi-prompt chain. This is a sequence of two steps:
- # 1) Select "animal" or "vegetable" via the route_chain, and collect the answer
- # alongside the input query.
+ # 1) Select "animal" or "vegetable" via the route_chain, and collect the
+ # answer alongside the input query.
# 2) Route the input query to chain_1 or chain_2, based on the
# selection.
graph = StateGraph(State)
@@ -141,7 +142,7 @@ class MultiPromptChain(MultiRouteChain):
print(result["destination"])
print(result["answer"])
- """ # noqa: E501
+ """
@property
@override
diff --git a/libs/langchain/langchain/chains/sql_database/query.py b/libs/langchain/langchain/chains/sql_database/query.py
index 157553cde3..0814e3e2e0 100644
--- a/libs/langchain/langchain/chains/sql_database/query.py
+++ b/libs/langchain/langchain/chains/sql_database/query.py
@@ -83,15 +83,17 @@ def create_sql_query_chain(
response = chain.invoke({"question": "How many employees are there"})
Prompt:
- If no prompt is provided, a default prompt is selected based on the SQLDatabase dialect. If one is provided, it must support input variables:
- * input: The user question plus suffix "\nSQLQuery: " is passed here.
+ If no prompt is provided, a default prompt is selected based on the SQLDatabase
+ dialect. If one is provided, it must support input variables:
+
+ * input: The user question plus suffix "\\nSQLQuery: " is passed here.
* top_k: The number of results per select statement (the `k` argument to
- this function) is passed in here.
+ this function) is passed in here.
* table_info: Table definitions and sample rows are passed in here. If the
- user specifies "table_names_to_use" when invoking chain, only those
- will be included. Otherwise, all tables are included.
+ user specifies "table_names_to_use" when invoking chain, only those
+ will be included. Otherwise, all tables are included.
* dialect (optional): If dialect input variable is in prompt, the db
- dialect will be passed in here.
+ dialect will be passed in here.
Here's an example prompt:
diff --git a/libs/langchain/langchain/chains/structured_output/base.py b/libs/langchain/langchain/chains/structured_output/base.py
index ceacf6bbd8..9ec6269da1 100644
--- a/libs/langchain/langchain/chains/structured_output/base.py
+++ b/libs/langchain/langchain/chains/structured_output/base.py
@@ -565,7 +565,10 @@ def _create_openai_functions_structured_output_runnable(
else:
class _OutputFormatter(BaseModel):
- """Output formatter. Should always be used to format your response to the user.""" # noqa: E501
+ """Output formatter.
+
+ Should always be used to format your response to the user.
+ """
output: output_schema # type: ignore[valid-type]
diff --git a/libs/langchain/langchain/chat_models/base.py b/libs/langchain/langchain/chat_models/base.py
index 2fbe685fec..d0f54b6a01 100644
--- a/libs/langchain/langchain/chat_models/base.py
+++ b/libs/langchain/langchain/chat_models/base.py
@@ -179,8 +179,12 @@ def init_chat_model(
from langchain.chat_models import init_chat_model
o3_mini = init_chat_model("openai:o3-mini", temperature=0)
- claude_sonnet = init_chat_model("anthropic:claude-3-5-sonnet-latest", temperature=0)
- gemini_2_flash = init_chat_model("google_vertexai:gemini-2.5-flash", temperature=0)
+ claude_sonnet = init_chat_model(
+ "anthropic:claude-3-5-sonnet-latest", temperature=0
+ )
+ gemini_2_flash = init_chat_model(
+ "google_vertexai:gemini-2.5-flash", temperature=0
+ )
o3_mini.invoke("what's your name")
claude_sonnet.invoke("what's your name")
@@ -198,14 +202,13 @@ def init_chat_model(
configurable_model = init_chat_model(temperature=0)
configurable_model.invoke(
- "what's your name",
- config={"configurable": {"model": "gpt-4o"}}
+ "what's your name", config={"configurable": {"model": "gpt-4o"}}
)
# GPT-4o response
configurable_model.invoke(
"what's your name",
- config={"configurable": {"model": "claude-3-5-sonnet-latest"}}
+ config={"configurable": {"model": "claude-3-5-sonnet-latest"}},
)
# claude-3.5 sonnet response
@@ -220,7 +223,7 @@ def init_chat_model(
"openai:gpt-4o",
configurable_fields="any", # this allows us to configure other params like temperature, max_tokens, etc at runtime.
config_prefix="foo",
- temperature=0
+ temperature=0,
)
configurable_model_with_default.invoke("what's your name")
@@ -231,9 +234,9 @@ def init_chat_model(
config={
"configurable": {
"foo_model": "anthropic:claude-3-5-sonnet-latest",
- "foo_temperature": 0.6
+ "foo_temperature": 0.6,
}
- }
+ },
)
# Claude-3.5 sonnet response with temperature 0.6
@@ -248,23 +251,30 @@ def init_chat_model(
from langchain.chat_models import init_chat_model
from pydantic import BaseModel, Field
+
class GetWeather(BaseModel):
'''Get the current weather in a given location'''
- location: str = Field(..., description="The city and state, e.g. San Francisco, CA")
+ location: str = Field(
+ ..., description="The city and state, e.g. San Francisco, CA"
+ )
+
class GetPopulation(BaseModel):
'''Get the current population in a given location'''
- location: str = Field(..., description="The city and state, e.g. San Francisco, CA")
+ location: str = Field(
+ ..., description="The city and state, e.g. San Francisco, CA"
+ )
+
configurable_model = init_chat_model(
- "gpt-4o",
- configurable_fields=("model", "model_provider"),
- temperature=0
+ "gpt-4o", configurable_fields=("model", "model_provider"), temperature=0
)
- configurable_model_with_tools = configurable_model.bind_tools([GetWeather, GetPopulation])
+ configurable_model_with_tools = configurable_model.bind_tools(
+ [GetWeather, GetPopulation]
+ )
configurable_model_with_tools.invoke(
"Which city is hotter today and which is bigger: LA or NY?"
)
@@ -272,7 +282,7 @@ def init_chat_model(
configurable_model_with_tools.invoke(
"Which city is hotter today and which is bigger: LA or NY?",
- config={"configurable": {"model": "claude-3-5-sonnet-latest"}}
+ config={"configurable": {"model": "claude-3-5-sonnet-latest"}},
)
# Claude-3.5 sonnet response with tools
diff --git a/libs/langchain/langchain/embeddings/base.py b/libs/langchain/langchain/embeddings/base.py
index 4142550363..fe1d34326b 100644
--- a/libs/langchain/langchain/embeddings/base.py
+++ b/libs/langchain/langchain/embeddings/base.py
@@ -165,17 +165,11 @@ def init_embeddings(
model.embed_query("Hello, world!")
# Using explicit provider
- model = init_embeddings(
- model="text-embedding-3-small",
- provider="openai"
- )
+ model = init_embeddings(model="text-embedding-3-small", provider="openai")
model.embed_documents(["Hello, world!", "Goodbye, world!"])
# With additional parameters
- model = init_embeddings(
- "openai:text-embedding-3-small",
- api_key="sk-..."
- )
+ model = init_embeddings("openai:text-embedding-3-small", api_key="sk-...")
.. versionadded:: 0.3.9
diff --git a/libs/langchain/langchain/evaluation/__init__.py b/libs/langchain/langchain/evaluation/__init__.py
index 22afbccf4e..d2fcf35c92 100644
--- a/libs/langchain/langchain/evaluation/__init__.py
+++ b/libs/langchain/langchain/evaluation/__init__.py
@@ -30,6 +30,7 @@ name of the dataset to load.
.. code-block:: python
from langchain.evaluation import load_dataset
+
ds = load_dataset("llm-math")
**Some common use cases for evaluation include:**
diff --git a/libs/langchain/langchain/evaluation/comparison/eval_chain.py b/libs/langchain/langchain/evaluation/comparison/eval_chain.py
index c14c9d8ebc..eb39220428 100644
--- a/libs/langchain/langchain/evaluation/comparison/eval_chain.py
+++ b/libs/langchain/langchain/evaluation/comparison/eval_chain.py
@@ -165,7 +165,9 @@ class PairwiseStringEvalChain(PairwiseStringEvaluator, LLMEvalChain, LLMChain):
Example:
>>> from langchain_community.chat_models import ChatOpenAI
>>> from langchain.evaluation.comparison import PairwiseStringEvalChain
- >>> llm = ChatOpenAI(temperature=0, model_name="gpt-4", model_kwargs={"random_seed": 42})
+ >>> llm = ChatOpenAI(
+ ... temperature=0, model_name="gpt-4", model_kwargs={"random_seed": 42}
+ ... )
>>> chain = PairwiseStringEvalChain.from_llm(llm=llm)
>>> result = chain.evaluate_string_pairs(
... input = "What is the chemical formula for water?",
@@ -184,7 +186,7 @@ class PairwiseStringEvalChain(PairwiseStringEvaluator, LLMEvalChain, LLMChain):
# . " by explaining what the formula means.\n[[B]]"
# }
- """ # noqa: E501
+ """
output_key: str = "results" #: :meta private:
output_parser: BaseOutputParser = Field(
diff --git a/libs/langchain/langchain/evaluation/criteria/eval_chain.py b/libs/langchain/langchain/evaluation/criteria/eval_chain.py
index 97413300e4..02a131de20 100644
--- a/libs/langchain/langchain/evaluation/criteria/eval_chain.py
+++ b/libs/langchain/langchain/evaluation/criteria/eval_chain.py
@@ -201,7 +201,10 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
>>> llm = ChatAnthropic(temperature=0)
>>> criteria = {"my-custom-criterion": "Is the submission the most amazing ever?"}
>>> evaluator = CriteriaEvalChain.from_llm(llm=llm, criteria=criteria)
- >>> evaluator.evaluate_strings(prediction="Imagine an ice cream flavor for the color aquamarine", input="Tell me an idea")
+ >>> evaluator.evaluate_strings(
+ ... prediction="Imagine an ice cream flavor for the color aquamarine",
+ ... input="Tell me an idea",
+ ... )
{
'reasoning': 'Here is my step-by-step reasoning for the given criteria:\n\nThe criterion is: "Is the submission the most amazing ever?" This is a subjective criterion and open to interpretation. The submission suggests an aquamarine-colored ice cream flavor which is creative but may or may not be considered the most amazing idea ever conceived. There are many possible amazing ideas and this one ice cream flavor suggestion may or may not rise to that level for every person. \n\nN',
'value': 'N',
@@ -217,10 +220,10 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
... criteria=criteria,
... )
>>> evaluator.evaluate_strings(
- ... prediction="The answer is 4",
- ... input="How many apples are there?",
- ... reference="There are 3 apples",
- ... )
+ ... prediction="The answer is 4",
+ ... input="How many apples are there?",
+ ... reference="There are 3 apples",
+ ... )
{
'score': 0,
'reasoning': 'The criterion for this task is the correctness of the submission. The submission states that there are 4 apples, but the reference indicates that there are actually 3 apples. Therefore, the submission is not correct, accurate, or factual according to the given criterion.\n\nN',
diff --git a/libs/langchain/langchain/evaluation/loading.py b/libs/langchain/langchain/evaluation/loading.py
index 879fc564ab..b2360ad0c1 100644
--- a/libs/langchain/langchain/evaluation/loading.py
+++ b/libs/langchain/langchain/evaluation/loading.py
@@ -57,6 +57,7 @@ def load_dataset(uri: str) -> list[dict]:
.. code-block:: python
from langchain.evaluation import load_dataset
+
ds = load_dataset("llm-math")
"""
diff --git a/libs/langchain/langchain/evaluation/parsing/base.py b/libs/langchain/langchain/evaluation/parsing/base.py
index a334cec0f3..eb84e6a8b4 100644
--- a/libs/langchain/langchain/evaluation/parsing/base.py
+++ b/libs/langchain/langchain/evaluation/parsing/base.py
@@ -111,7 +111,7 @@ class JsonEqualityEvaluator(StringEvaluator):
>>> evaluator.evaluate_strings('{"a": 1}', reference='{"a": 2}')
{'score': False}
- >>> evaluator = JsonEqualityEvaluator(operator=lambda x, y: x['a'] == y['a'])
+ >>> evaluator = JsonEqualityEvaluator(operator=lambda x, y: x["a"] == y["a"])
>>> evaluator.evaluate_strings('{"a": 1}', reference='{"a": 1}')
{'score': True}
>>> evaluator.evaluate_strings('{"a": 1}', reference='{"a": 2}')
diff --git a/libs/langchain/langchain/evaluation/parsing/json_distance.py b/libs/langchain/langchain/evaluation/parsing/json_distance.py
index 63648841e4..0b186b1215 100644
--- a/libs/langchain/langchain/evaluation/parsing/json_distance.py
+++ b/libs/langchain/langchain/evaluation/parsing/json_distance.py
@@ -20,7 +20,9 @@ class JsonEditDistanceEvaluator(StringEvaluator):
Examples:
>>> evaluator = JsonEditDistanceEvaluator()
- >>> result = evaluator.evaluate_strings(prediction='{"a": 1, "b": 2}', reference='{"a": 1, "b": 3}')
+ >>> result = evaluator.evaluate_strings(
+ ... prediction='{"a": 1, "b": 2}', reference='{"a": 1, "b": 3}'
+ ... )
>>> assert result["score"] is not None
Raises:
diff --git a/libs/langchain/langchain/evaluation/scoring/__init__.py b/libs/langchain/langchain/evaluation/scoring/__init__.py
index 0d780659f6..ea99487cd6 100644
--- a/libs/langchain/langchain/evaluation/scoring/__init__.py
+++ b/libs/langchain/langchain/evaluation/scoring/__init__.py
@@ -10,9 +10,9 @@ Example:
>>> llm = ChatOpenAI(temperature=0, model_name="gpt-4")
>>> chain = ScoreStringEvalChain.from_llm(llm=llm)
>>> result = chain.evaluate_strings(
- ... input = "What is the chemical formula for water?",
- ... prediction = "H2O",
- ... reference = "The chemical formula for water is H2O.",
+ ... input="What is the chemical formula for water?",
+ ... prediction="H2O",
+ ... reference="The chemical formula for water is H2O.",
... )
>>> print(result)
# {
diff --git a/libs/langchain/langchain/evaluation/scoring/eval_chain.py b/libs/langchain/langchain/evaluation/scoring/eval_chain.py
index 6dbf3ea3b0..5a035e76d6 100644
--- a/libs/langchain/langchain/evaluation/scoring/eval_chain.py
+++ b/libs/langchain/langchain/evaluation/scoring/eval_chain.py
@@ -159,9 +159,9 @@ class ScoreStringEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
>>> llm = ChatOpenAI(temperature=0, model_name="gpt-4")
>>> chain = ScoreStringEvalChain.from_llm(llm=llm)
>>> result = chain.evaluate_strings(
- ... input = "What is the chemical formula for water?",
- ... prediction = "H2O",
- ... reference = "The chemical formula for water is H2O.",
+ ... input="What is the chemical formula for water?",
+ ... prediction="H2O",
+ ... reference="The chemical formula for water is H2O.",
... )
>>> print(result)
# {
diff --git a/libs/langchain/langchain/memory/vectorstore_token_buffer_memory.py b/libs/langchain/langchain/memory/vectorstore_token_buffer_memory.py
index 3aff21aaaa..b7ecb9fe7a 100644
--- a/libs/langchain/langchain/memory/vectorstore_token_buffer_memory.py
+++ b/libs/langchain/langchain/memory/vectorstore_token_buffer_memory.py
@@ -64,40 +64,41 @@ class ConversationVectorStoreTokenBufferMemory(ConversationTokenBufferMemory):
.. code-block:: python
from langchain.memory.token_buffer_vectorstore_memory import (
- ConversationVectorStoreTokenBufferMemory
+ ConversationVectorStoreTokenBufferMemory,
)
from langchain_chroma import Chroma
from langchain_community.embeddings import HuggingFaceInstructEmbeddings
from langchain_openai import OpenAI
embedder = HuggingFaceInstructEmbeddings(
- query_instruction="Represent the query for retrieval: "
+ query_instruction="Represent the query for retrieval: "
+ )
+ chroma = Chroma(
+ collection_name="demo",
+ embedding_function=embedder,
+ collection_metadata={"hnsw:space": "cosine"},
)
- chroma = Chroma(collection_name="demo",
- embedding_function=embedder,
- collection_metadata={"hnsw:space": "cosine"},
- )
retriever = chroma.as_retriever(
- search_type="similarity_score_threshold",
- search_kwargs={
- 'k': 5,
- 'score_threshold': 0.75,
- },
+ search_type="similarity_score_threshold",
+ search_kwargs={
+ "k": 5,
+ "score_threshold": 0.75,
+ },
)
conversation_memory = ConversationVectorStoreTokenBufferMemory(
- return_messages=True,
- llm=OpenAI(),
- retriever=retriever,
- max_token_limit = 1000,
+ return_messages=True,
+ llm=OpenAI(),
+ retriever=retriever,
+ max_token_limit=1000,
)
- conversation_memory.save_context({"Human": "Hi there"},
- {"AI": "Nice to meet you!"}
+ conversation_memory.save_context(
+ {"Human": "Hi there"}, {"AI": "Nice to meet you!"}
)
- conversation_memory.save_context({"Human": "Nice day isn't it?"},
- {"AI": "I love Wednesdays."}
+ conversation_memory.save_context(
+ {"Human": "Nice day isn't it?"}, {"AI": "I love Wednesdays."}
)
conversation_memory.load_memory_variables({"input": "What time is it?"})
diff --git a/libs/langchain/langchain/retrievers/parent_document_retriever.py b/libs/langchain/langchain/retrievers/parent_document_retriever.py
index 4b539e013e..f8f2886343 100644
--- a/libs/langchain/langchain/retrievers/parent_document_retriever.py
+++ b/libs/langchain/langchain/retrievers/parent_document_retriever.py
@@ -38,10 +38,14 @@ class ParentDocumentRetriever(MultiVectorRetriever):
from langchain.storage import InMemoryStore
# This text splitter is used to create the parent documents
- parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, add_start_index=True)
+ parent_splitter = RecursiveCharacterTextSplitter(
+ chunk_size=2000, add_start_index=True
+ )
# This text splitter is used to create the child documents
# It should create documents smaller than the parent
- child_splitter = RecursiveCharacterTextSplitter(chunk_size=400, add_start_index=True)
+ child_splitter = RecursiveCharacterTextSplitter(
+ chunk_size=400, add_start_index=True
+ )
# The vectorstore to use to index the child chunks
vectorstore = Chroma(embedding_function=OpenAIEmbeddings())
# The storage layer for the parent documents
@@ -55,7 +59,7 @@ class ParentDocumentRetriever(MultiVectorRetriever):
parent_splitter=parent_splitter,
)
- """ # noqa: E501
+ """
child_splitter: TextSplitter
"""The text splitter to use to create child documents."""
diff --git a/libs/langchain/langchain/smith/__init__.py b/libs/langchain/langchain/smith/__init__.py
index b8e9e37fee..1ee3ef1af7 100644
--- a/libs/langchain/langchain/smith/__init__.py
+++ b/libs/langchain/langchain/smith/__init__.py
@@ -1,11 +1,16 @@
"""**LangSmith** utilities.
-This module provides utilities for connecting to `LangSmith <https://smith.langchain.com/>`_. For more information on LangSmith, see the `LangSmith documentation <https://docs.smith.langchain.com/>`_.
+This module provides utilities for connecting to
+`LangSmith <https://smith.langchain.com/>`_.
+For more information on LangSmith,
+see the `LangSmith documentation <https://docs.smith.langchain.com/>`_.
**Evaluation**
-LangSmith helps you evaluate Chains and other language model application components using a number of LangChain evaluators.
-An example of this is shown below, assuming you've created a LangSmith dataset called ``<my_dataset_name>``:
+LangSmith helps you evaluate Chains and other language model application components
+using a number of LangChain evaluators.
+An example of this is shown below, assuming you've created a LangSmith dataset
+called ``<my_dataset_name>``:
.. code-block:: python
@@ -14,25 +19,27 @@ An example of this is shown below, assuming you've created a LangSmith dataset c
from langchain.chains import LLMChain
from langchain.smith import RunEvalConfig, run_on_dataset
+
# Chains may have memory. Passing in a constructor function lets the
# evaluation framework avoid cross-contamination between runs.
def construct_chain():
llm = ChatOpenAI(temperature=0)
- chain = LLMChain.from_string(
- llm,
- "What's the answer to {your_input_key}"
- )
+ chain = LLMChain.from_string(llm, "What's the answer to {your_input_key}")
return chain
+
# Load off-the-shelf evaluators via config or the EvaluatorType (string or enum)
evaluation_config = RunEvalConfig(
evaluators=[
"qa", # "Correctness" against a reference answer
"embedding_distance",
RunEvalConfig.Criteria("helpfulness"),
- RunEvalConfig.Criteria({
- "fifth-grader-score": "Do you have to be smarter than a fifth grader to answer this question?"
- }),
+ RunEvalConfig.Criteria(
+ {
+ "fifth-grader-score": "Do you have to be smarter than a fifth "
+ "grader to answer this question?"
+ }
+ ),
]
)
@@ -53,8 +60,8 @@ or LangSmith's `RunEvaluator` classes.
from typing import Optional
from langchain.evaluation import StringEvaluator
- class MyStringEvaluator(StringEvaluator):
+ class MyStringEvaluator(StringEvaluator):
@property
def requires_input(self) -> bool:
return False
@@ -67,12 +74,14 @@ or LangSmith's `RunEvaluator` classes.
def evaluation_name(self) -> str:
return "exact_match"
- def _evaluate_strings(self, prediction, reference=None, input=None, **kwargs) -> dict:
+ def _evaluate_strings(
+ self, prediction, reference=None, input=None, **kwargs
+ ) -> dict:
return {"score": prediction == reference}
evaluation_config = RunEvalConfig(
- custom_evaluators = [MyStringEvaluator()],
+ custom_evaluators=[MyStringEvaluator()],
)
run_on_dataset(
@@ -84,11 +93,18 @@ or LangSmith's `RunEvaluator` classes.
**Primary Functions**
-- :func:`arun_on_dataset <langchain.smith.evaluation.runner_utils.arun_on_dataset>`: Asynchronous function to evaluate a chain, agent, or other LangChain component over a dataset.
-- :func:`run_on_dataset <langchain.smith.evaluation.runner_utils.run_on_dataset>`: Function to evaluate a chain, agent, or other LangChain component over a dataset.
-- :class:`RunEvalConfig <langchain.smith.evaluation.config.RunEvalConfig>`: Class representing the configuration for running evaluation. You can select evaluators by :class:`EvaluatorType <langchain.evaluation.schema.EvaluatorType>` or config, or you can pass in `custom_evaluators`
-
-""" # noqa: E501
+- :func:`arun_on_dataset <langchain.smith.evaluation.runner_utils.arun_on_dataset>`:
+ Asynchronous function to evaluate a chain, agent, or other LangChain component over a
+ dataset.
+- :func:`run_on_dataset <langchain.smith.evaluation.runner_utils.run_on_dataset>`:
+ Function to evaluate a chain, agent, or other LangChain component over a dataset.
+- :class:`RunEvalConfig <langchain.smith.evaluation.config.RunEvalConfig>`:
+ Class representing the configuration for running evaluation.
+ You can select evaluators by
+ :class:`EvaluatorType <langchain.evaluation.schema.EvaluatorType>` or config,
+ or you can pass in `custom_evaluators`.
+
+"""
from langchain.smith.evaluation import (
RunEvalConfig,
diff --git a/libs/langchain/langchain/smith/evaluation/__init__.py b/libs/langchain/langchain/smith/evaluation/__init__.py
index 56e4a11708..732e142f2d 100644
--- a/libs/langchain/langchain/smith/evaluation/__init__.py
+++ b/libs/langchain/langchain/smith/evaluation/__init__.py
@@ -3,7 +3,8 @@
This module provides utilities for evaluating Chains and other language model
applications using LangChain evaluators and LangSmith.
-For more information on the LangSmith API, see the `LangSmith API documentation <https://docs.smith.langchain.com/docs/>`_.
+For more information on the LangSmith API, see the
+`LangSmith API documentation <https://docs.smith.langchain.com/docs/>`_.
**Example**
@@ -14,42 +15,43 @@ For more information on the LangSmith API, see the `LangSmith API documentation
from langchain.chains import LLMChain
from langchain.smith import EvaluatorType, RunEvalConfig, run_on_dataset
+
def construct_chain():
llm = ChatOpenAI(temperature=0)
- chain = LLMChain.from_string(
- llm,
- "What's the answer to {your_input_key}"
- )
+ chain = LLMChain.from_string(llm, "What's the answer to {your_input_key}")
return chain
+
evaluation_config = RunEvalConfig(
evaluators=[
EvaluatorType.QA, # "Correctness" against a reference answer
EvaluatorType.EMBEDDING_DISTANCE,
RunEvalConfig.Criteria("helpfulness"),
- RunEvalConfig.Criteria({
- "fifth-grader-score": "Do you have to be smarter than a fifth grader to answer this question?"
- }),
+ RunEvalConfig.Criteria(
+ {
+ "fifth-grader-score": "Do you have to be smarter than a fifth "
+ "grader to answer this question?"
+ }
+ ),
]
)
client = Client()
run_on_dataset(
- client,
- "<my_dataset_name>",
- construct_chain,
- evaluation=evaluation_config
+ client, "<my_dataset_name>", construct_chain, evaluation=evaluation_config
)
**Attributes**
-- ``arun_on_dataset``: Asynchronous function to evaluate a chain or other LangChain component over a dataset.
-- ``run_on_dataset``: Function to evaluate a chain or other LangChain component over a dataset.
+- ``arun_on_dataset``: Asynchronous function to evaluate a chain or other LangChain
+ component over a dataset.
+- ``run_on_dataset``: Function to evaluate a chain or other LangChain component over a
+ dataset.
- ``RunEvalConfig``: Class representing the configuration for running evaluation.
- ``StringRunEvaluatorChain``: Class representing a string run evaluator chain.
- ``InputFormatError``: Exception raised when the input format is incorrect.
-""" # noqa: E501
+"""
from langchain.smith.evaluation.config import RunEvalConfig
from langchain.smith.evaluation.runner_utils import (
diff --git a/libs/langchain/langchain/smith/evaluation/config.py b/libs/langchain/langchain/smith/evaluation/config.py
index 3afe723f3f..ba3e03cbfa 100644
--- a/libs/langchain/langchain/smith/evaluation/config.py
+++ b/libs/langchain/langchain/smith/evaluation/config.py
@@ -93,35 +93,7 @@ SINGLE_EVAL_CONFIG_TYPE = Union[EvaluatorType, str, EvalConfig]
class RunEvalConfig(BaseModel):
- """Configuration for a run evaluation.
-
- Parameters
- ----------
- evaluators : List[Union[EvaluatorType, EvalConfig, RunEvaluator, Callable]]
- Configurations for which evaluators to apply to the dataset run.
- Each can be the string of an :class:`EvaluatorType <langchain.evaluation.schema.EvaluatorType>`, such
- as EvaluatorType.QA, the evaluator type string ("qa"), or a configuration for a
- given evaluator (e.g., :class:`RunEvalConfig.QA <langchain.smith.evaluation.config.RunEvalConfig.QA>`).
-
- custom_evaluators : Optional[List[Union[RunEvaluator, StringEvaluator]]]
- Custom evaluators to apply to the dataset run.
-
- reference_key : Optional[str]
- The key in the dataset run to use as the reference string.
- If not provided, it will be inferred automatically.
-
- prediction_key : Optional[str]
- The key from the traced run's outputs dictionary to use to
- represent the prediction. If not provided, it will be inferred
- automatically.
-
- input_key : Optional[str]
- The key from the traced run's inputs dictionary to use to represent the
- input. If not provided, it will be inferred automatically.
-
- eval_llm : Optional[BaseLanguageModel]
- The language model to pass to any evaluators that use a language model.
- """ # noqa: E501
+ """Configuration for a run evaluation."""
evaluators: list[
Union[
diff --git a/libs/langchain/langchain/smith/evaluation/runner_utils.py b/libs/langchain/langchain/smith/evaluation/runner_utils.py
index 66eadd845f..5fc4e8f980 100644
--- a/libs/langchain/langchain/smith/evaluation/runner_utils.py
+++ b/libs/langchain/langchain/smith/evaluation/runner_utils.py
@@ -1416,7 +1416,8 @@ async def arun_on_dataset(
"embedding_distance",
smith_eval.RunEvalConfig.Criteria("helpfulness"),
smith_eval.RunEvalConfig.Criteria({
- "fifth-grader-score": "Do you have to be smarter than a fifth grader to answer this question?"
+ "fifth-grader-score": "Do you have to be smarter than a fifth "
+ "grader to answer this question?"
}),
]
)
@@ -1438,8 +1439,8 @@ async def arun_on_dataset(
from typing import Optional
from langchain.evaluation import StringEvaluator
- class MyStringEvaluator(StringEvaluator):
+ class MyStringEvaluator(StringEvaluator):
@property
def requires_input(self) -> bool:
return False
@@ -1452,12 +1453,14 @@ async def arun_on_dataset(
def evaluation_name(self) -> str:
return "exact_match"
- def _evaluate_strings(self, prediction, reference=None, input=None, **kwargs) -> dict:
+ def _evaluate_strings(
+ self, prediction, reference=None, input=None, **kwargs
+ ) -> dict:
return {"score": prediction == reference}
evaluation_config = smith_eval.RunEvalConfig(
- custom_evaluators = [MyStringEvaluator()],
+ custom_evaluators=[MyStringEvaluator()],
)
await arun_on_dataset(
@@ -1467,7 +1470,7 @@ async def arun_on_dataset(
evaluation=evaluation_config,
)
- """ # noqa: E501
+ """
input_mapper = kwargs.pop("input_mapper", None)
if input_mapper:
warn_deprecated("0.0.305", message=_INPUT_MAPPER_DEP_WARNING, pending=True)
@@ -1591,7 +1594,8 @@ def run_on_dataset(
"embedding_distance",
smith_eval.RunEvalConfig.Criteria("helpfulness"),
smith_eval.RunEvalConfig.Criteria({
- "fifth-grader-score": "Do you have to be smarter than a fifth grader to answer this question?"
+ "fifth-grader-score": "Do you have to be smarter than a fifth "
+ "grader to answer this question?"
}),
]
)
@@ -1613,8 +1617,8 @@ def run_on_dataset(
from typing import Optional
from langchain.evaluation import StringEvaluator
- class MyStringEvaluator(StringEvaluator):
+ class MyStringEvaluator(StringEvaluator):
@property
def requires_input(self) -> bool:
return False
@@ -1627,12 +1631,14 @@ def run_on_dataset(
def evaluation_name(self) -> str:
return "exact_match"
- def _evaluate_strings(self, prediction, reference=None, input=None, **kwargs) -> dict:
+ def _evaluate_strings(
+ self, prediction, reference=None, input=None, **kwargs
+ ) -> dict:
return {"score": prediction == reference}
evaluation_config = smith_eval.RunEvalConfig(
- custom_evaluators = [MyStringEvaluator()],
+ custom_evaluators=[MyStringEvaluator()],
)
run_on_dataset(
@@ -1642,7 +1648,7 @@ def run_on_dataset(
evaluation=evaluation_config,
)
- """ # noqa: E501
+ """
input_mapper = kwargs.pop("input_mapper", None)
if input_mapper:
warn_deprecated("0.0.305", message=_INPUT_MAPPER_DEP_WARNING, pending=True)
diff --git a/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py b/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py
index 5440b565ec..97af12a6c8 100644
--- a/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py
+++ b/libs/langchain/langchain/smith/evaluation/string_run_evaluator.py
@@ -415,30 +415,33 @@ class StringRunEvaluatorChain(Chain, RunEvaluator):
reference_key: Optional[str] = None,
tags: Optional[list[str]] = None,
) -> StringRunEvaluatorChain:
- """Create a StringRunEvaluatorChain from an evaluator and the run and dataset types.
+ """Create a StringRunEvaluatorChain.
+
+ Create a StringRunEvaluatorChain from an evaluator and the run and dataset
+ types.
This method provides an easy way to instantiate a StringRunEvaluatorChain, by
taking an evaluator and information about the type of run and the data.
The method supports LLM and chain runs.
Args:
- evaluator (StringEvaluator): The string evaluator to use.
- run_type (str): The type of run being evaluated.
+ evaluator: The string evaluator to use.
+ run_type: The type of run being evaluated.
Supported types are LLM and Chain.
- data_type (DataType): The type of dataset used in the run.
- input_key (str, optional): The key used to map the input from the run.
- prediction_key (str, optional): The key used to map the prediction from the run.
- reference_key (str, optional): The key used to map the reference from the dataset.
- tags (List[str], optional): List of tags to attach to the evaluation chain.
+ data_type: The type of dataset used in the run.
+ input_key: The key used to map the input from the run.
+ prediction_key: The key used to map the prediction from the run.
+ reference_key: The key used to map the reference from the dataset.
+ tags: List of tags to attach to the evaluation chain.
Returns:
- StringRunEvaluatorChain: The instantiated evaluation chain.
+ The instantiated evaluation chain.
Raises:
- ValueError: If the run type is not supported, or if the evaluator requires a
- reference from the dataset but the reference key is not provided.
+ If the run type is not supported, or if the evaluator requires a
+ reference from the dataset but the reference key is not provided.
- """ # noqa: E501
+ """
# Configure how run inputs/predictions are passed to the evaluator
if run_type == "llm":
run_mapper: StringRunMapper = LLMStringRunMapper()
diff --git a/libs/langchain/langchain/storage/encoder_backed.py b/libs/langchain/langchain/storage/encoder_backed.py
index 1bb9fe25fa..cd031889f4 100644
--- a/libs/langchain/langchain/storage/encoder_backed.py
+++ b/libs/langchain/langchain/storage/encoder_backed.py
@@ -22,15 +22,19 @@ class EncoderBackedStore(BaseStore[K, V]):
import json
+
def key_encoder(key: int) -> str:
return json.dumps(key)
+
def value_serializer(value: float) -> str:
return json.dumps(value)
+
def value_deserializer(serialized_value: str) -> float:
return json.loads(serialized_value)
+
# Create an instance of the abstract store
abstract_store = MyCustomStore()
@@ -39,7 +43,7 @@ class EncoderBackedStore(BaseStore[K, V]):
store=abstract_store,
key_encoder=key_encoder,
value_serializer=value_serializer,
- value_deserializer=value_deserializer
+ value_deserializer=value_deserializer,
)
# Use the encoder-backed store methods
diff --git a/libs/langchain/pyproject.toml b/libs/langchain/pyproject.toml
index 04214bbc8d..fb453b30b7 100644
--- a/libs/langchain/pyproject.toml
+++ b/libs/langchain/pyproject.toml
@@ -144,6 +144,9 @@ skip = ".git,*.pdf,*.svg,*.pdf,*.yaml,*.ipynb,poetry.lock,*.min.js,*.css,package
ignore-regex = ".*(Stati Uniti|Tense=Pres).*"
ignore-words-list = "momento,collison,ned,foor,reworkd,parth,whats,aapply,mysogyny,unsecure,damon,crate,aadd,symbl,precesses,accademia,nin"
+[tool.ruff.format]
+docstring-code-format = true
+
[tool.ruff.lint]
select = [ "ALL",]
ignore = [
diff --git a/libs/langchain/tests/unit_tests/agents/test_agent.py b/libs/langchain/tests/unit_tests/agents/test_agent.py
index f1e8a7388b..dd5fa7271b 100644
--- a/libs/langchain/tests/unit_tests/agents/test_agent.py
+++ b/libs/langchain/tests/unit_tests/agents/test_agent.py
@@ -1241,7 +1241,8 @@ async def test_openai_agent_tools_agent() -> None:
{
"messages": [
FunctionMessage(
- content="check_time is not a valid tool, try one of [find_pet].", # noqa: E501
+ content="check_time is not a valid tool, "
+ "try one of [find_pet].",
name="check_time",
),
],
diff --git a/libs/langchain/tests/unit_tests/chains/question_answering/test_map_rerank_prompt.py b/libs/langchain/tests/unit_tests/chains/question_answering/test_map_rerank_prompt.py
index ea4b776616..99227b1e80 100644
--- a/libs/langchain/tests/unit_tests/chains/question_answering/test_map_rerank_prompt.py
+++ b/libs/langchain/tests/unit_tests/chains/question_answering/test_map_rerank_prompt.py
@@ -5,7 +5,11 @@ import pytest
from langchain.chains.question_answering.map_rerank_prompt import output_parser
GOOD_SCORE = "foo bar answer.\nScore: 80"
-SCORE_WITH_EXPLANATION = "foo bar answer.\nScore: 80 (fully answers the question, but could provide more detail on the specific error message)" # noqa: E501
+SCORE_WITH_EXPLANATION = (
+ "foo bar answer.\n"
+ "Score: 80 (fully answers the question, "
+ "but could provide more detail on the specific error message)"
+)
@pytest.mark.parametrize("answer", [GOOD_SCORE, SCORE_WITH_EXPLANATION])
diff --git a/libs/langchain/tests/unit_tests/chains/test_llm_checker.py b/libs/langchain/tests/unit_tests/chains/test_llm_checker.py
index f2d3300281..b5dbfdd3bd 100644
--- a/libs/langchain/tests/unit_tests/chains/test_llm_checker.py
+++ b/libs/langchain/tests/unit_tests/chains/test_llm_checker.py
@@ -1,5 +1,3 @@
-# ruff: noqa: E501
-
"""Test LLMCheckerChain functionality."""
import pytest
@@ -23,12 +21,20 @@ def fake_llm_checker_chain() -> LLMCheckerChain:
): "I don't know which mammal layers the biggest eggs.",
_LIST_ASSERTIONS_TEMPLATE.format(
statement="I don't know which mammal layers the biggest eggs.",
- ): "1) I know that mammals lay eggs.\n2) I know that birds lay eggs.\n3) I know that birds are mammals.",
+ ): "1) I know that mammals lay eggs.\n"
+ "2) I know that birds lay eggs.\n"
+ "3) I know that birds are mammals.",
_CHECK_ASSERTIONS_TEMPLATE.format(
- assertions="1) I know that mammals lay eggs.\n2) I know that birds lay eggs.\n3) I know that birds are mammals.",
- ): "1) I know that mammals lay eggs. TRUE\n2) I know that birds lay eggs. TRUE\n3) I know that birds are mammals. TRUE",
+ assertions="1) I know that mammals lay eggs.\n"
+ "2) I know that birds lay eggs.\n"
+ "3) I know that birds are mammals.",
+ ): "1) I know that mammals lay eggs. TRUE\n"
+ "2) I know that birds lay eggs. TRUE\n"
+ "3) I know that birds are mammals. TRUE",
_REVISED_ANSWER_TEMPLATE.format(
- checked_assertions="1) I know that mammals lay eggs. TRUE\n2) I know that birds lay eggs. TRUE\n3) I know that birds are mammals. TRUE",
+ checked_assertions="1) I know that mammals lay eggs. TRUE\n"
+ "2) I know that birds lay eggs. TRUE\n"
+ "3) I know that birds are mammals. TRUE",
question="Which mammal lays the biggest eggs?",
): "I still don't know.",
}
diff --git a/libs/langchain/tests/unit_tests/conftest.py b/libs/langchain/tests/unit_tests/conftest.py
index 368b130b4b..d588ec500e 100644
--- a/libs/langchain/tests/unit_tests/conftest.py
+++ b/libs/langchain/tests/unit_tests/conftest.py
@@ -76,8 +76,7 @@ def pytest_collection_modifyitems(
.. code-block:: python
@pytest.mark.requires("package1", "package2")
- def test_something():
- ...
+ def test_something(): ...
"""
# Mapping from the name of a package to whether it is installed or not.
diff --git a/libs/langchain/tests/unit_tests/evaluation/criteria/test_eval_chain.py b/libs/langchain/tests/unit_tests/evaluation/criteria/test_eval_chain.py
index 1401723d49..6bc505f6de 100644
--- a/libs/langchain/tests/unit_tests/evaluation/criteria/test_eval_chain.py
+++ b/libs/langchain/tests/unit_tests/evaluation/criteria/test_eval_chain.py
@@ -27,12 +27,12 @@ def test_resolve_criteria_str() -> None:
[
("Y", {"reasoning": "", "value": "Y", "score": 1}),
(
- """Here is my step-by-step reasoning for the given criteria:
-The criterion is: "Do you like cake?" I like cake.
-Y""",
+ "Here is my step-by-step reasoning for the given criteria:\n"
+ 'The criterion is: "Do you like cake?" I like cake.\n'
+ "Y",
{
- "reasoning": """Here is my step-by-step reasoning for the given criteria:
-The criterion is: "Do you like cake?" I like cake.""", # noqa: E501
+ "reasoning": "Here is my step-by-step reasoning for the given criteria:"
+ '\nThe criterion is: "Do you like cake?" I like cake.',
"value": "Y",
"score": 1,
},
diff --git a/libs/langchain/tests/unit_tests/load/test_dump.py b/libs/langchain/tests/unit_tests/load/test_dump.py
index 1861b6f790..b5cdbd9f83 100644
--- a/libs/langchain/tests/unit_tests/load/test_dump.py
+++ b/libs/langchain/tests/unit_tests/load/test_dump.py
@@ -64,8 +64,12 @@ def test_person(snapshot: Any) -> None:
def test_typeerror() -> None:
assert (
- dumps({(1, 2): 3})
- == """{"lc": 1, "type": "not_implemented", "id": ["builtins", "dict"], "repr": "{(1, 2): 3}"}""" # noqa: E501
+ dumps({(1, 2): 3}) == "{"
+ '"lc": 1, '
+ '"type": "not_implemented", '
+ '"id": ["builtins", "dict"], '
+ '"repr": "{(1, 2): 3}"'
+ "}"
)
diff --git a/libs/langchain/tests/unit_tests/load/test_load.py b/libs/langchain/tests/unit_tests/load/test_load.py
index 786648ca94..c94f4dc537 100644
--- a/libs/langchain/tests/unit_tests/load/test_load.py
+++ b/libs/langchain/tests/unit_tests/load/test_load.py
@@ -179,7 +179,18 @@ def test_load_llmchain_with_non_serializable_arg() -> None:
def test_loads_with_missing_secrets() -> None:
import openai
- llm_string = '{"lc": 1, "type": "constructor", "id": ["langchain", "llms", "openai", "OpenAI"], "kwargs": {"model_name": "davinci", "temperature": 0.5, "max_tokens": 256, "top_p": 0.8, "n": 1, "best_of": 1, "openai_api_key": {"lc": 1, "type": "secret", "id": ["OPENAI_API_KEY"]}, "batch_size": 20, "max_retries": 2, "disallowed_special": "all"}, "name": "OpenAI"}' # noqa: E501
+ llm_string = (
+ "{"
+ '"lc": 1, '
+ '"type": "constructor", '
+ '"id": ["langchain", "llms", "openai", "OpenAI"], '
+ '"kwargs": {'
+ '"model_name": "davinci", "temperature": 0.5, "max_tokens": 256, "top_p": 0.8, '
+ '"n": 1, "best_of": 1, '
+ '"openai_api_key": {"lc": 1, "type": "secret", "id": ["OPENAI_API_KEY"]}, '
+ '"batch_size": 20, "max_retries": 2, "disallowed_special": "all"}, '
+ '"name": "OpenAI"}'
+ )
# Should throw on instantiation, not deserialization
with pytest.raises(openai.OpenAIError):
loads(llm_string)
diff --git a/libs/langchain/tests/unit_tests/output_parsers/test_pandas_dataframe_parser.py b/libs/langchain/tests/unit_tests/output_parsers/test_pandas_dataframe_parser.py
index a727d4a7e0..b667a3c351 100644
--- a/libs/langchain/tests/unit_tests/output_parsers/test_pandas_dataframe_parser.py
+++ b/libs/langchain/tests/unit_tests/output_parsers/test_pandas_dataframe_parser.py
@@ -104,5 +104,8 @@ def test_pandas_output_parser_invalid_special_op() -> None:
def test_pandas_output_parser_output_type() -> None:
- """Test the output type of the pandas dataframe output parser is a pandas dataframe.""" # noqa: E501
+ """Test pandas output parser output type.
+
+ Test the output type of the pandas dataframe output parser is a pandas dataframe.
+ """
assert parser.OutputType == dict[str, Any]