Skip to content

Commit

Permalink
langchain[patch]: add aprep_output method to `langchain/chains/base…
Browse files Browse the repository at this point in the history
….py` (#20748)

## Description

Add `aprep_output` method to `langchain/chains/base.py`. Some downstream
`ChatMessageHistory` objects that use async connections require an async
way to append to the context.

It turned out that `ainvoke()` was calling `prep_output` which is
synchronous.

---------

Co-authored-by: Bagatur <[email protected]>
  • Loading branch information
hslee16 and baskaryan authored Apr 24, 2024
1 parent 43c041c commit 243ba71
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion libs/langchain/langchain/chains/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ async def ainvoke(
if new_arg_supported
else await self._acall(inputs)
)
final_outputs: Dict[str, Any] = self.prep_outputs(
final_outputs: Dict[str, Any] = await self.aprep_outputs(
inputs, outputs, return_only_outputs
)
except BaseException as e:
Expand Down Expand Up @@ -458,6 +458,32 @@ def prep_outputs(
else:
return {**inputs, **outputs}

async def aprep_outputs(
self,
inputs: Dict[str, str],
outputs: Dict[str, str],
return_only_outputs: bool = False,
) -> Dict[str, str]:
"""Validate and prepare chain outputs, and save info about this run to memory.
Args:
inputs: Dictionary of chain inputs, including any inputs added by chain
memory.
outputs: Dictionary of initial chain outputs.
return_only_outputs: Whether to only return the chain outputs. If False,
inputs are also added to the final outputs.
Returns:
A dict of the final chain outputs.
"""
self._validate_outputs(outputs)
if self.memory is not None:
await self.memory.asave_context(inputs, outputs)
if return_only_outputs:
return outputs
else:
return {**inputs, **outputs}

def prep_inputs(self, inputs: Union[Dict[str, Any], Any]) -> Dict[str, str]:
"""Prepare chain inputs, including adding inputs from memory.
Expand Down

0 comments on commit 243ba71

Please sign in to comment.