Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docstrings core update #14871

Merged
merged 3 commits into from
Dec 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions libs/core/langchain_core/beta/runnables/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,17 +128,37 @@ def aconfig_with_context(
config: RunnableConfig,
steps: List[Runnable],
) -> RunnableConfig:
"""Asynchronously patch a runnable config with context getters and setters.

Args:
config: The runnable config.
steps: The runnable steps.

Returns:
The patched runnable config.
"""
return _config_with_context(config, steps, _asetter, _agetter, asyncio.Event)


def config_with_context(
config: RunnableConfig,
steps: List[Runnable],
) -> RunnableConfig:
"""Patch a runnable config with context getters and setters.

Args:
config: The runnable config.
steps: The runnable steps.

Returns:
The patched runnable config.
"""
return _config_with_context(config, steps, _setter, _getter, threading.Event)


class ContextGet(RunnableSerializable):
"""Get a context value."""

prefix: str = ""

key: Union[str, List[str]]
Expand Down Expand Up @@ -197,6 +217,8 @@ def _coerce_set_value(value: SetValue) -> Runnable[Input, Output]:


class ContextSet(RunnableSerializable):
"""Set a context value."""

prefix: str = ""

keys: Mapping[str, Optional[Runnable]]
Expand Down Expand Up @@ -276,8 +298,18 @@ async def ainvoke(


class Context:
"""Context for a runnable."""

@staticmethod
def create_scope(scope: str, /) -> "PrefixContext":
"""Create a context scope.

Args:
scope: The scope.

Returns:
The context scope.
"""
return PrefixContext(prefix=scope)

@staticmethod
Expand All @@ -295,6 +327,8 @@ def setter(


class PrefixContext:
"""Context for a runnable with a prefix."""

prefix: str = ""

def __init__(self, prefix: str = ""):
Expand Down
4 changes: 4 additions & 0 deletions libs/core/langchain_core/language_models/chat_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ def _get_verbosity() -> bool:


def generate_from_stream(stream: Iterator[ChatGenerationChunk]) -> ChatResult:
"""Generate from a stream."""

generation: Optional[ChatGenerationChunk] = None
for chunk in stream:
if generation is None:
Expand All @@ -77,6 +79,8 @@ def generate_from_stream(stream: Iterator[ChatGenerationChunk]) -> ChatResult:
async def agenerate_from_stream(
stream: AsyncIterator[ChatGenerationChunk],
) -> ChatResult:
"""Async generate from a stream."""

generation: Optional[ChatGenerationChunk] = None
async for chunk in stream:
if generation is None:
Expand Down
10 changes: 10 additions & 0 deletions libs/core/langchain_core/load/serializable.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ class SerializedNotImplemented(BaseSerialized):


def try_neq_default(value: Any, key: str, model: BaseModel) -> bool:
"""Try to determine if a value is different from the default.

Args:
value: The value.
key: The key.
model: The model.

Returns:
Whether the value is different from the default.
"""
try:
return model.__fields__[key].get_default() != value
except Exception:
Expand Down
17 changes: 17 additions & 0 deletions libs/core/langchain_core/messages/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@ def merge_content(
first_content: Union[str, List[Union[str, Dict]]],
second_content: Union[str, List[Union[str, Dict]]],
) -> Union[str, List[Union[str, Dict]]]:
"""Merge two message contents.

Args:
first_content: The first content.
second_content: The second content.

Returns:
The merged content.
"""
# If first chunk is a string
if isinstance(first_content, str):
# If the second chunk is also a string, then merge them naively
Expand Down Expand Up @@ -146,6 +155,14 @@ def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore


def message_to_dict(message: BaseMessage) -> dict:
"""Convert a Message to a dictionary.

Args:
message: Message to convert.

Returns:
Message as a dict.
"""
return {"type": message.type, "data": message.dict()}


Expand Down
12 changes: 12 additions & 0 deletions libs/core/langchain_core/runnables/configurable.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,18 @@ def _strremoveprefix(s: str, prefix: str) -> str:
def prefix_config_spec(
spec: ConfigurableFieldSpec, prefix: str
) -> ConfigurableFieldSpec:
"""Prefix the id of a ConfigurableFieldSpec.

This is useful when a RunnableConfigurableAlternatives is used as a
ConfigurableField of another RunnableConfigurableAlternatives.

Args:
spec: The ConfigurableFieldSpec to prefix.
prefix: The prefix to add.

Returns:

"""
return (
ConfigurableFieldSpec(
id=f"{prefix}/{spec.id}",
Expand Down
13 changes: 13 additions & 0 deletions libs/core/langchain_core/tracers/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,19 @@ def register_configure_hook(
handle_class: Optional[Type[BaseCallbackHandler]] = None,
env_var: Optional[str] = None,
) -> None:
"""Register a configure hook.

Args:
context_var (ContextVar[Optional[Any]]): The context variable.
inheritable (bool): Whether the context variable is inheritable.
handle_class (Optional[Type[BaseCallbackHandler]], optional):
The callback handler class. Defaults to None.
env_var (Optional[str], optional): The environment variable. Defaults to None.

Raises:
ValueError: If env_var is set, handle_class must also be set
to a non-None value.
"""
if env_var is not None and handle_class is None:
raise ValueError(
"If env_var is set, handle_class must also be set to a non-None value."
Expand Down
2 changes: 2 additions & 0 deletions libs/core/langchain_core/tracers/root_listeners.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@


class RootListenersTracer(BaseTracer):
"""A tracer that calls listeners on run start, end, and error."""

def __init__(
self,
*,
Expand Down
Loading