Skip to content

Commit a35ee49

Browse files
authored
chore(langchain): enable ruff docstring-code-format in langchain (#32858)
1 parent 352ff36 commit a35ee49

File tree

63 files changed

+506
-315
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+506
-315
lines changed

libs/langchain/langchain/agents/agent_toolkits/vectorstore/base.py

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ def create_vectorstore_agent(
6060
6161
vector_store = InMemoryVectorStore.from_texts(
6262
[
63-
"Dogs are great companions, known for their loyalty and friendliness.",
63+
"Dogs are great companions, "
64+
"known for their loyalty and friendliness.",
6465
"Cats are independent pets that often enjoy their own space.",
6566
],
6667
OpenAIEmbeddings(),
@@ -81,18 +82,20 @@ def create_vectorstore_agent(
8182
step["messages"][-1].pretty_print()
8283
8384
Args:
84-
llm (BaseLanguageModel): LLM that will be used by the agent
85-
toolkit (VectorStoreToolkit): Set of tools for the agent
86-
callback_manager (Optional[BaseCallbackManager], optional): Object to handle the callback [ Defaults to None. ]
87-
prefix (str, optional): The prefix prompt for the agent. If not provided uses default PREFIX.
88-
verbose (bool, optional): If you want to see the content of the scratchpad. [ Defaults to False ]
89-
agent_executor_kwargs (Optional[Dict[str, Any]], optional): If there is any other parameter you want to send to the agent. [ Defaults to None ]
85+
llm: LLM that will be used by the agent
86+
toolkit: Set of tools for the agent
87+
callback_manager: Object to handle the callback [ Defaults to None. ]
88+
prefix: The prefix prompt for the agent. If not provided uses default PREFIX.
89+
verbose: If you want to see the content of the scratchpad. [ Defaults to False ]
90+
agent_executor_kwargs: If there is any other parameter you want to send to the
91+
agent. [ Defaults to None ]
9092
kwargs: Additional named parameters to pass to the ZeroShotAgent.
9193
9294
Returns:
93-
AgentExecutor: Returns a callable AgentExecutor object. Either you can call it or use run method with the query to get the response
95+
Returns a callable AgentExecutor object.
96+
Either you can call it or use run method with the query to get the response.
9497
95-
""" # noqa: E501
98+
"""
9699
tools = toolkit.get_tools()
97100
prompt = ZeroShotAgent.create_prompt(tools, prefix=prefix)
98101
llm_chain = LLMChain(
@@ -155,7 +158,8 @@ def create_vectorstore_router_agent(
155158
156159
pet_vector_store = InMemoryVectorStore.from_texts(
157160
[
158-
"Dogs are great companions, known for their loyalty and friendliness.",
161+
"Dogs are great companions, "
162+
"known for their loyalty and friendliness.",
159163
"Cats are independent pets that often enjoy their own space.",
160164
],
161165
OpenAIEmbeddings(),
@@ -179,7 +183,7 @@ def create_vectorstore_router_agent(
179183
food_vector_store.as_retriever(),
180184
"food_information_retriever",
181185
"Fetches information about food.",
182-
)
186+
),
183187
]
184188
185189
agent = create_react_agent(llm, tools)
@@ -191,18 +195,22 @@ def create_vectorstore_router_agent(
191195
step["messages"][-1].pretty_print()
192196
193197
Args:
194-
llm (BaseLanguageModel): LLM that will be used by the agent
195-
toolkit (VectorStoreRouterToolkit): Set of tools for the agent which have routing capability with multiple vector stores
196-
callback_manager (Optional[BaseCallbackManager], optional): Object to handle the callback [ Defaults to None. ]
197-
prefix (str, optional): The prefix prompt for the router agent. If not provided uses default ROUTER_PREFIX.
198-
verbose (bool, optional): If you want to see the content of the scratchpad. [ Defaults to False ]
199-
agent_executor_kwargs (Optional[Dict[str, Any]], optional): If there is any other parameter you want to send to the agent. [ Defaults to None ]
198+
llm: LLM that will be used by the agent
199+
toolkit: Set of tools for the agent which have routing capability with multiple
200+
vector stores
201+
callback_manager: Object to handle the callback [ Defaults to None. ]
202+
prefix: The prefix prompt for the router agent.
203+
If not provided uses default ROUTER_PREFIX.
204+
verbose: If you want to see the content of the scratchpad. [ Defaults to False ]
205+
agent_executor_kwargs: If there is any other parameter you want to send to the
206+
agent. [ Defaults to None ]
200207
kwargs: Additional named parameters to pass to the ZeroShotAgent.
201208
202209
Returns:
203-
AgentExecutor: Returns a callable AgentExecutor object. Either you can call it or use run method with the query to get the response.
210+
Returns a callable AgentExecutor object.
211+
Either you can call it or use run method with the query to get the response.
204212
205-
""" # noqa: E501
213+
"""
206214
tools = toolkit.get_tools()
207215
prompt = ZeroShotAgent.create_prompt(tools, prefix=prefix)
208216
llm_chain = LLMChain(

libs/langchain/langchain/agents/chat/base.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,12 @@ def create_prompt(
108108
tool_strings = "\n".join([f"{tool.name}: {tool.description}" for tool in tools])
109109
tool_names = ", ".join([tool.name for tool in tools])
110110
format_instructions = format_instructions.format(tool_names=tool_names)
111-
template = f"{system_message_prefix}\n\n{tool_strings}\n\n{format_instructions}\n\n{system_message_suffix}" # noqa: E501
111+
template = (
112+
f"{system_message_prefix}\n\n"
113+
f"{tool_strings}\n\n"
114+
f"{format_instructions}\n\n"
115+
f"{system_message_suffix}"
116+
)
112117
messages = [
113118
SystemMessagePromptTemplate.from_template(template),
114119
HumanMessagePromptTemplate.from_template(human_message),

libs/langchain/langchain/agents/json_chat/base.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ def create_json_chat_agent(
3535
does not support stop sequences.
3636
tools_renderer: This controls how the tools are converted into a string and
3737
then passed into the LLM. Default is `render_text_description`.
38-
template_tool_response: Template prompt that uses the tool response (observation)
39-
to make the LLM generate the next action to take.
38+
template_tool_response: Template prompt that uses the tool response
39+
(observation) to make the LLM generate the next action to take.
4040
Default is TEMPLATE_TOOL_RESPONSE.
4141
4242
Returns:
@@ -68,6 +68,7 @@ def create_json_chat_agent(
6868
6969
# Using with chat history
7070
from langchain_core.messages import AIMessage, HumanMessage
71+
7172
agent_executor.invoke(
7273
{
7374
"input": "what's my name?",
@@ -83,7 +84,8 @@ def create_json_chat_agent(
8384
The prompt must have input keys:
8485
* `tools`: contains descriptions and arguments for each tool.
8586
* `tool_names`: contains all tool names.
86-
* `agent_scratchpad`: must be a MessagesPlaceholder. Contains previous agent actions and tool outputs as messages.
87+
* `agent_scratchpad`: must be a MessagesPlaceholder. Contains previous
88+
agent actions and tool outputs as messages.
8789
8890
Here's an example:
8991

libs/langchain/langchain/agents/openai_assistant/base.py

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -149,11 +149,14 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):
149149
150150
interpreter_assistant = OpenAIAssistantRunnable.create_assistant(
151151
name="langchain assistant",
152-
instructions="You are a personal math tutor. Write and run code to answer math questions.",
152+
instructions="You are a personal math tutor. "
153+
"Write and run code to answer math questions.",
153154
tools=[{"type": "code_interpreter"}],
154-
model="gpt-4-1106-preview"
155+
model="gpt-4-1106-preview",
156+
)
157+
output = interpreter_assistant.invoke(
158+
{"content": "What's 10 - 4 raised to the 2.7"}
155159
)
156-
output = interpreter_assistant.invoke({"content": "What's 10 - 4 raised to the 2.7"})
157160
158161
Example using custom tools and AgentExecutor:
159162
.. code-block:: python
@@ -166,10 +169,11 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):
166169
tools = [E2BDataAnalysisTool(api_key="...")]
167170
agent = OpenAIAssistantRunnable.create_assistant(
168171
name="langchain assistant e2b tool",
169-
instructions="You are a personal math tutor. Write and run code to answer math questions.",
172+
instructions="You are a personal math tutor. "
173+
"Write and run code to answer math questions.",
170174
tools=tools,
171175
model="gpt-4-1106-preview",
172-
as_agent=True
176+
as_agent=True,
173177
)
174178
175179
agent_executor = AgentExecutor(agent=agent, tools=tools)
@@ -188,34 +192,45 @@ class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):
188192
tools = [E2BDataAnalysisTool(api_key="...")]
189193
agent = OpenAIAssistantRunnable.create_assistant(
190194
name="langchain assistant e2b tool",
191-
instructions="You are a personal math tutor. Write and run code to answer math questions.",
195+
instructions="You are a personal math tutor. "
196+
"Write and run code to answer math questions.",
192197
tools=tools,
193198
model="gpt-4-1106-preview",
194-
as_agent=True
199+
as_agent=True,
195200
)
196201
202+
197203
def execute_agent(agent, tools, input):
198204
tool_map = {tool.name: tool for tool in tools}
199205
response = agent.invoke(input)
200206
while not isinstance(response, AgentFinish):
201207
tool_outputs = []
202208
for action in response:
203209
tool_output = tool_map[action.tool].invoke(action.tool_input)
204-
tool_outputs.append({"output": tool_output, "tool_call_id": action.tool_call_id})
210+
tool_outputs.append(
211+
{"output": tool_output, "tool_call_id": action.tool_call_id}
212+
)
205213
response = agent.invoke(
206214
{
207215
"tool_outputs": tool_outputs,
208216
"run_id": action.run_id,
209-
"thread_id": action.thread_id
217+
"thread_id": action.thread_id,
210218
}
211219
)
212220
213221
return response
214222
215-
response = execute_agent(agent, tools, {"content": "What's 10 - 4 raised to the 2.7"})
216-
next_response = execute_agent(agent, tools, {"content": "now add 17.241", "thread_id": response.thread_id})
217223
218-
""" # noqa: E501
224+
response = execute_agent(
225+
agent, tools, {"content": "What's 10 - 4 raised to the 2.7"}
226+
)
227+
next_response = execute_agent(
228+
agent,
229+
tools,
230+
{"content": "now add 17.241", "thread_id": response.thread_id},
231+
)
232+
233+
"""
219234

220235
client: Any = Field(default_factory=_get_openai_client)
221236
"""OpenAI or AzureOpenAI client."""

libs/langchain/langchain/agents/openai_functions_agent/base.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,7 @@ def create_openai_functions_agent(
327327
328328
# Using with chat history
329329
from langchain_core.messages import AIMessage, HumanMessage
330+
330331
agent_executor.invoke(
331332
{
332333
"input": "what's my name?",

libs/langchain/langchain/agents/openai_tools/base.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ def create_openai_tools_agent(
5555
5656
# Using with chat history
5757
from langchain_core.messages import AIMessage, HumanMessage
58+
5859
agent_executor.invoke(
5960
{
6061
"input": "what's my name?",

libs/langchain/langchain/agents/output_parsers/json.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,21 +23,15 @@ class JSONAgentOutputParser(AgentOutputParser):
2323
being returned.
2424
2525
```
26-
{
27-
"action": "search",
28-
"action_input": "2+2"
29-
}
26+
{"action": "search", "action_input": "2+2"}
3027
```
3128
3229
If the output signals that a final answer should be given,
3330
should be in the below format. This will result in an AgentFinish
3431
being returned.
3532
3633
```
37-
{
38-
"action": "Final Answer",
39-
"action_input": "4"
40-
}
34+
{"action": "Final Answer", "action_input": "4"}
4135
```
4236
"""
4337

libs/langchain/langchain/agents/react/agent.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,12 @@ def create_react_agent(
2929
(https://arxiv.org/abs/2210.03629)
3030
3131
.. warning::
32-
This implementation is based on the foundational ReAct paper but is older and not well-suited for production applications.
33-
For a more robust and feature-rich implementation, we recommend using the `create_react_agent` function from the LangGraph library.
34-
See the [reference doc](https://langchain-ai.github.io/langgraph/reference/prebuilt/#langgraph.prebuilt.chat_agent_executor.create_react_agent)
32+
This implementation is based on the foundational ReAct paper but is older and
33+
not well-suited for production applications.
34+
For a more robust and feature-rich implementation, we recommend using the
35+
`create_react_agent` function from the LangGraph library.
36+
See the
37+
`reference doc <https://langchain-ai.github.io/langgraph/reference/prebuilt/#langgraph.prebuilt.chat_agent_executor.create_react_agent>`__
3538
for more information.
3639
3740
Args:
@@ -73,6 +76,7 @@ def create_react_agent(
7376
7477
# Use with chat history
7578
from langchain_core.messages import AIMessage, HumanMessage
79+
7680
agent_executor.invoke(
7781
{
7882
"input": "what's my name?",
@@ -87,7 +91,8 @@ def create_react_agent(
8791
The prompt must have input keys:
8892
* `tools`: contains descriptions and arguments for each tool.
8993
* `tool_names`: contains all tool names.
90-
* `agent_scratchpad`: contains previous agent actions and tool outputs as a string.
94+
* `agent_scratchpad`: contains previous agent actions and tool outputs as a
95+
string.
9196
9297
Here's an example:
9398

libs/langchain/langchain/agents/self_ask_with_search/base.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,8 @@ def create_self_ask_with_search_agent(
122122
from langchain import hub
123123
from langchain_community.chat_models import ChatAnthropic
124124
from langchain.agents import (
125-
AgentExecutor, create_self_ask_with_search_agent
125+
AgentExecutor,
126+
create_self_ask_with_search_agent,
126127
)
127128
128129
prompt = hub.pull("hwchase17/self-ask-with-search")

libs/langchain/langchain/agents/structured_chat/base.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,7 @@ def create_structured_chat_agent(
207207
208208
# Using with chat history
209209
from langchain_core.messages import AIMessage, HumanMessage
210+
210211
agent_executor.invoke(
211212
{
212213
"input": "what's my name?",
@@ -222,7 +223,8 @@ def create_structured_chat_agent(
222223
The prompt must have input keys:
223224
* `tools`: contains descriptions and arguments for each tool.
224225
* `tool_names`: contains all tool names.
225-
* `agent_scratchpad`: contains previous agent actions and tool outputs as a string.
226+
* `agent_scratchpad`: contains previous agent actions and tool outputs as a
227+
string.
226228
227229
Here's an example:
228230

0 commit comments

Comments
 (0)