diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/adapters/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/adapters/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3834e1853e4a4f7255006f6ce6b1ea25a12b236c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/adapters/__init__.py
@@ -0,0 +1,8 @@
+"""**Adapters** are used to adapt LangChain models to other APIs.
+
+LangChain integrates with many model providers.
+While LangChain has its own message and model APIs,
+LangChain has also made it as easy as
+possible to explore other models by exposing an **adapter** to adapt LangChain
+models to the other APIs, as to the OpenAI API.
+"""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/adapters/openai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/adapters/openai.py
new file mode 100644
index 0000000000000000000000000000000000000000..09b0f5d1d51fa89e2c771b615b4aed546b8db1e0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/adapters/openai.py
@@ -0,0 +1,421 @@
+from __future__ import annotations
+
+import importlib
+from typing import (
+ Any,
+ AsyncIterator,
+ Dict,
+ Iterable,
+ List,
+ Mapping,
+ Sequence,
+ Union,
+ overload,
+)
+
+from langchain_core.chat_sessions import ChatSession
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ FunctionMessage,
+ HumanMessage,
+ SystemMessage,
+ ToolMessage,
+)
+from pydantic import BaseModel
+from typing_extensions import Literal
+
+
+async def aenumerate(
+ iterable: AsyncIterator[Any], start: int = 0
+) -> AsyncIterator[tuple[int, Any]]:
+ """Async version of enumerate function."""
+ i = start
+ async for x in iterable:
+ yield i, x
+ i += 1
+
+
+class IndexableBaseModel(BaseModel):
+ """Allows a BaseModel to return its fields by string variable indexing."""
+
+ def __getitem__(self, item: str) -> Any:
+ return getattr(self, item)
+
+
+class Choice(IndexableBaseModel):
+ """Choice."""
+
+ message: dict
+
+
+class ChatCompletions(IndexableBaseModel):
+ """Chat completions."""
+
+ choices: List[Choice]
+
+
+class ChoiceChunk(IndexableBaseModel):
+ """Choice chunk."""
+
+ delta: dict
+
+
+class ChatCompletionChunk(IndexableBaseModel):
+ """Chat completion chunk."""
+
+ choices: List[ChoiceChunk]
+
+
+def convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ """Convert a dictionary to a LangChain message.
+
+ Args:
+ _dict: The dictionary.
+
+ Returns:
+ The LangChain message.
+ """
+ role = _dict.get("role")
+ if role == "user":
+ return HumanMessage(content=_dict.get("content", ""))
+ elif role == "assistant":
+ # Fix for azure
+ # Also OpenAI returns None for tool invocations
+ content = _dict.get("content", "") or ""
+ additional_kwargs: Dict = {}
+ if function_call := _dict.get("function_call"):
+ additional_kwargs["function_call"] = dict(function_call)
+ if tool_calls := _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = tool_calls
+ if context := _dict.get("context"):
+ additional_kwargs["context"] = context
+ return AIMessage(content=content, additional_kwargs=additional_kwargs)
+ elif role == "system":
+ return SystemMessage(content=_dict.get("content", ""))
+ elif role == "function":
+ return FunctionMessage(content=_dict.get("content", ""), name=_dict.get("name")) # type: ignore[arg-type]
+ elif role == "tool":
+ additional_kwargs = {}
+ if "name" in _dict:
+ additional_kwargs["name"] = _dict["name"]
+ return ToolMessage(
+ content=_dict.get("content", ""),
+ tool_call_id=_dict.get("tool_call_id"),
+ additional_kwargs=additional_kwargs,
+ )
+ else:
+ return ChatMessage(content=_dict.get("content", ""), role=role) # type: ignore[arg-type]
+
+
+def convert_message_to_dict(message: BaseMessage) -> dict:
+ """Convert a LangChain message to a dictionary.
+
+ Args:
+ message: The LangChain message.
+
+ Returns:
+ The dictionary.
+ """
+ message_dict: Dict[str, Any]
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ if "function_call" in message.additional_kwargs:
+ message_dict["function_call"] = message.additional_kwargs["function_call"]
+ # If function call only, content is None not empty string
+ if message_dict["content"] == "":
+ message_dict["content"] = None
+ if "tool_calls" in message.additional_kwargs:
+ message_dict["tool_calls"] = message.additional_kwargs["tool_calls"]
+ # If tool calls only, content is None not empty string
+ if message_dict["content"] == "":
+ message_dict["content"] = None
+ if "context" in message.additional_kwargs:
+ message_dict["context"] = message.additional_kwargs["context"]
+ # If context only, content is None not empty string
+ if message_dict["content"] == "":
+ message_dict["content"] = None
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, FunctionMessage):
+ message_dict = {
+ "role": "function",
+ "content": message.content,
+ "name": message.name,
+ }
+ elif isinstance(message, ToolMessage):
+ message_dict = {
+ "role": "tool",
+ "content": message.content,
+ "tool_call_id": message.tool_call_id,
+ }
+ else:
+ raise TypeError(f"Got unknown type {message}")
+ if "name" in message.additional_kwargs:
+ message_dict["name"] = message.additional_kwargs["name"]
+ return message_dict
+
+
+def convert_openai_messages(messages: Sequence[Dict[str, Any]]) -> List[BaseMessage]:
+ """Convert dictionaries representing OpenAI messages to LangChain format.
+
+ Args:
+ messages: List of dictionaries representing OpenAI messages
+
+ Returns:
+ List of LangChain BaseMessage objects.
+ """
+ return [convert_dict_to_message(m) for m in messages]
+
+
+def _convert_message_chunk(chunk: BaseMessageChunk, i: int) -> dict:
+ _dict: Dict[str, Any] = {}
+ if isinstance(chunk, AIMessageChunk):
+ if i == 0:
+ # Only shows up in the first chunk
+ _dict["role"] = "assistant"
+ if "function_call" in chunk.additional_kwargs:
+ _dict["function_call"] = chunk.additional_kwargs["function_call"]
+ # If the first chunk is a function call, the content is not empty string,
+ # not missing, but None.
+ if i == 0:
+ _dict["content"] = None
+ if "tool_calls" in chunk.additional_kwargs:
+ _dict["tool_calls"] = chunk.additional_kwargs["tool_calls"]
+ # If the first chunk is tool calls, the content is not empty string,
+ # not missing, but None.
+ if i == 0:
+ _dict["content"] = None
+ else:
+ _dict["content"] = chunk.content
+ else:
+ raise ValueError(f"Got unexpected streaming chunk type: {type(chunk)}")
+ # This only happens at the end of streams, and OpenAI returns as empty dict
+ if _dict == {"content": ""}:
+ _dict = {}
+ return _dict
+
+
+def _convert_message_chunk_to_delta(chunk: BaseMessageChunk, i: int) -> Dict[str, Any]:
+ _dict = _convert_message_chunk(chunk, i)
+ return {"choices": [{"delta": _dict}]}
+
+
+class ChatCompletion:
+ """Chat completion."""
+
+ @overload
+ @staticmethod
+ def create(
+ messages: Sequence[Dict[str, Any]],
+ *,
+ provider: str = "ChatOpenAI",
+ stream: Literal[False] = False,
+ **kwargs: Any,
+ ) -> dict: ...
+
+ @overload
+ @staticmethod
+ def create(
+ messages: Sequence[Dict[str, Any]],
+ *,
+ provider: str = "ChatOpenAI",
+ stream: Literal[True],
+ **kwargs: Any,
+ ) -> Iterable: ...
+
+ @staticmethod
+ def create(
+ messages: Sequence[Dict[str, Any]],
+ *,
+ provider: str = "ChatOpenAI",
+ stream: bool = False,
+ **kwargs: Any,
+ ) -> Union[dict, Iterable]:
+ models = importlib.import_module("langchain.chat_models")
+ model_cls = getattr(models, provider)
+ model_config = model_cls(**kwargs)
+ converted_messages = convert_openai_messages(messages)
+ if not stream:
+ result = model_config.invoke(converted_messages)
+ return {"choices": [{"message": convert_message_to_dict(result)}]}
+ else:
+ return (
+ _convert_message_chunk_to_delta(c, i)
+ for i, c in enumerate(model_config.stream(converted_messages))
+ )
+
+ @overload
+ @staticmethod
+ async def acreate(
+ messages: Sequence[Dict[str, Any]],
+ *,
+ provider: str = "ChatOpenAI",
+ stream: Literal[False] = False,
+ **kwargs: Any,
+ ) -> dict: ...
+
+ @overload
+ @staticmethod
+ async def acreate(
+ messages: Sequence[Dict[str, Any]],
+ *,
+ provider: str = "ChatOpenAI",
+ stream: Literal[True],
+ **kwargs: Any,
+ ) -> AsyncIterator: ...
+
+ @staticmethod
+ async def acreate(
+ messages: Sequence[Dict[str, Any]],
+ *,
+ provider: str = "ChatOpenAI",
+ stream: bool = False,
+ **kwargs: Any,
+ ) -> Union[dict, AsyncIterator]:
+ models = importlib.import_module("langchain.chat_models")
+ model_cls = getattr(models, provider)
+ model_config = model_cls(**kwargs)
+ converted_messages = convert_openai_messages(messages)
+ if not stream:
+ result = await model_config.ainvoke(converted_messages)
+ return {"choices": [{"message": convert_message_to_dict(result)}]}
+ else:
+ return (
+ _convert_message_chunk_to_delta(c, i)
+ async for i, c in aenumerate(model_config.astream(converted_messages))
+ )
+
+
+def _has_assistant_message(session: ChatSession) -> bool:
+ """Check if chat session has an assistant message."""
+ return any([isinstance(m, AIMessage) for m in session["messages"]])
+
+
+def convert_messages_for_finetuning(
+ sessions: Iterable[ChatSession],
+) -> List[List[dict]]:
+ """Convert messages to a list of lists of dictionaries for fine-tuning.
+
+ Args:
+ sessions: The chat sessions.
+
+ Returns:
+ The list of lists of dictionaries.
+ """
+ return [
+ [convert_message_to_dict(s) for s in session["messages"]]
+ for session in sessions
+ if _has_assistant_message(session)
+ ]
+
+
+class Completions:
+ """Completions."""
+
+ @overload
+ @staticmethod
+ def create(
+ messages: Sequence[Dict[str, Any]],
+ *,
+ provider: str = "ChatOpenAI",
+ stream: Literal[False] = False,
+ **kwargs: Any,
+ ) -> ChatCompletions: ...
+
+ @overload
+ @staticmethod
+ def create(
+ messages: Sequence[Dict[str, Any]],
+ *,
+ provider: str = "ChatOpenAI",
+ stream: Literal[True],
+ **kwargs: Any,
+ ) -> Iterable: ...
+
+ @staticmethod
+ def create(
+ messages: Sequence[Dict[str, Any]],
+ *,
+ provider: str = "ChatOpenAI",
+ stream: bool = False,
+ **kwargs: Any,
+ ) -> Union[ChatCompletions, Iterable]:
+ models = importlib.import_module("langchain.chat_models")
+ model_cls = getattr(models, provider)
+ model_config = model_cls(**kwargs)
+ converted_messages = convert_openai_messages(messages)
+ if not stream:
+ result = model_config.invoke(converted_messages)
+ return ChatCompletions(
+ choices=[Choice(message=convert_message_to_dict(result))]
+ )
+ else:
+ return (
+ ChatCompletionChunk(
+ choices=[ChoiceChunk(delta=_convert_message_chunk(c, i))]
+ )
+ for i, c in enumerate(model_config.stream(converted_messages))
+ )
+
+ @overload
+ @staticmethod
+ async def acreate(
+ messages: Sequence[Dict[str, Any]],
+ *,
+ provider: str = "ChatOpenAI",
+ stream: Literal[False] = False,
+ **kwargs: Any,
+ ) -> ChatCompletions: ...
+
+ @overload
+ @staticmethod
+ async def acreate(
+ messages: Sequence[Dict[str, Any]],
+ *,
+ provider: str = "ChatOpenAI",
+ stream: Literal[True],
+ **kwargs: Any,
+ ) -> AsyncIterator: ...
+
+ @staticmethod
+ async def acreate(
+ messages: Sequence[Dict[str, Any]],
+ *,
+ provider: str = "ChatOpenAI",
+ stream: bool = False,
+ **kwargs: Any,
+ ) -> Union[ChatCompletions, AsyncIterator]:
+ models = importlib.import_module("langchain.chat_models")
+ model_cls = getattr(models, provider)
+ model_config = model_cls(**kwargs)
+ converted_messages = convert_openai_messages(messages)
+ if not stream:
+ result = await model_config.ainvoke(converted_messages)
+ return ChatCompletions(
+ choices=[Choice(message=convert_message_to_dict(result))]
+ )
+ else:
+ return (
+ ChatCompletionChunk(
+ choices=[ChoiceChunk(delta=_convert_message_chunk(c, i))]
+ )
+ async for i, c in aenumerate(model_config.astream(converted_messages))
+ )
+
+
+class Chat:
+ """Chat."""
+
+ def __init__(self) -> None:
+ self.completions = Completions()
+
+
+chat = Chat()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0e67479ffd89d101972ce80f73516fef2c0a73d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/__init__.py
@@ -0,0 +1,170 @@
+"""**Toolkits** are sets of tools that can be used to interact with
+various services and APIs.
+"""
+
+import importlib
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langchain_community.agent_toolkits.ainetwork.toolkit import (
+ AINetworkToolkit,
+ )
+ from langchain_community.agent_toolkits.amadeus.toolkit import (
+ AmadeusToolkit,
+ )
+ from langchain_community.agent_toolkits.azure_ai_services import (
+ AzureAiServicesToolkit,
+ )
+ from langchain_community.agent_toolkits.azure_cognitive_services import (
+ AzureCognitiveServicesToolkit,
+ )
+ from langchain_community.agent_toolkits.cassandra_database.toolkit import (
+ CassandraDatabaseToolkit, # noqa: F401
+ )
+ from langchain_community.agent_toolkits.cogniswitch.toolkit import (
+ CogniswitchToolkit,
+ )
+ from langchain_community.agent_toolkits.connery import (
+ ConneryToolkit,
+ )
+ from langchain_community.agent_toolkits.file_management.toolkit import (
+ FileManagementToolkit,
+ )
+ from langchain_community.agent_toolkits.gmail.toolkit import (
+ GmailToolkit,
+ )
+ from langchain_community.agent_toolkits.jira.toolkit import (
+ JiraToolkit,
+ )
+ from langchain_community.agent_toolkits.json.base import (
+ create_json_agent,
+ )
+ from langchain_community.agent_toolkits.json.toolkit import (
+ JsonToolkit,
+ )
+ from langchain_community.agent_toolkits.multion.toolkit import (
+ MultionToolkit,
+ )
+ from langchain_community.agent_toolkits.nasa.toolkit import (
+ NasaToolkit,
+ )
+ from langchain_community.agent_toolkits.nla.toolkit import (
+ NLAToolkit,
+ )
+ from langchain_community.agent_toolkits.office365.toolkit import (
+ O365Toolkit,
+ )
+ from langchain_community.agent_toolkits.openapi.base import (
+ create_openapi_agent,
+ )
+ from langchain_community.agent_toolkits.openapi.toolkit import (
+ OpenAPIToolkit,
+ )
+ from langchain_community.agent_toolkits.playwright.toolkit import (
+ PlayWrightBrowserToolkit,
+ )
+ from langchain_community.agent_toolkits.polygon.toolkit import (
+ PolygonToolkit,
+ )
+ from langchain_community.agent_toolkits.powerbi.base import (
+ create_pbi_agent,
+ )
+ from langchain_community.agent_toolkits.powerbi.chat_base import (
+ create_pbi_chat_agent,
+ )
+ from langchain_community.agent_toolkits.powerbi.toolkit import (
+ PowerBIToolkit,
+ )
+ from langchain_community.agent_toolkits.slack.toolkit import (
+ SlackToolkit,
+ )
+ from langchain_community.agent_toolkits.spark_sql.base import (
+ create_spark_sql_agent,
+ )
+ from langchain_community.agent_toolkits.spark_sql.toolkit import (
+ SparkSQLToolkit,
+ )
+ from langchain_community.agent_toolkits.sql.base import (
+ create_sql_agent,
+ )
+ from langchain_community.agent_toolkits.sql.toolkit import (
+ SQLDatabaseToolkit,
+ )
+ from langchain_community.agent_toolkits.steam.toolkit import (
+ SteamToolkit,
+ )
+ from langchain_community.agent_toolkits.zapier.toolkit import (
+ ZapierToolkit,
+ )
+
+__all__ = [
+ "AINetworkToolkit",
+ "AmadeusToolkit",
+ "AzureAiServicesToolkit",
+ "AzureCognitiveServicesToolkit",
+ "CogniswitchToolkit",
+ "ConneryToolkit",
+ "FileManagementToolkit",
+ "GmailToolkit",
+ "JiraToolkit",
+ "JsonToolkit",
+ "MultionToolkit",
+ "NLAToolkit",
+ "NasaToolkit",
+ "O365Toolkit",
+ "OpenAPIToolkit",
+ "PlayWrightBrowserToolkit",
+ "PolygonToolkit",
+ "PowerBIToolkit",
+ "SQLDatabaseToolkit",
+ "SlackToolkit",
+ "SparkSQLToolkit",
+ "SteamToolkit",
+ "ZapierToolkit",
+ "create_json_agent",
+ "create_openapi_agent",
+ "create_pbi_agent",
+ "create_pbi_chat_agent",
+ "create_spark_sql_agent",
+ "create_sql_agent",
+]
+
+
+_module_lookup = {
+ "AINetworkToolkit": "langchain_community.agent_toolkits.ainetwork.toolkit",
+ "AmadeusToolkit": "langchain_community.agent_toolkits.amadeus.toolkit",
+ "AzureAiServicesToolkit": "langchain_community.agent_toolkits.azure_ai_services",
+ "AzureCognitiveServicesToolkit": "langchain_community.agent_toolkits.azure_cognitive_services", # noqa: E501
+ "CogniswitchToolkit": "langchain_community.agent_toolkits.cogniswitch.toolkit",
+ "ConneryToolkit": "langchain_community.agent_toolkits.connery",
+ "FileManagementToolkit": "langchain_community.agent_toolkits.file_management.toolkit", # noqa: E501
+ "GmailToolkit": "langchain_community.agent_toolkits.gmail.toolkit",
+ "JiraToolkit": "langchain_community.agent_toolkits.jira.toolkit",
+ "JsonToolkit": "langchain_community.agent_toolkits.json.toolkit",
+ "MultionToolkit": "langchain_community.agent_toolkits.multion.toolkit",
+ "NLAToolkit": "langchain_community.agent_toolkits.nla.toolkit",
+ "NasaToolkit": "langchain_community.agent_toolkits.nasa.toolkit",
+ "O365Toolkit": "langchain_community.agent_toolkits.office365.toolkit",
+ "OpenAPIToolkit": "langchain_community.agent_toolkits.openapi.toolkit",
+ "PlayWrightBrowserToolkit": "langchain_community.agent_toolkits.playwright.toolkit",
+ "PolygonToolkit": "langchain_community.agent_toolkits.polygon.toolkit",
+ "PowerBIToolkit": "langchain_community.agent_toolkits.powerbi.toolkit",
+ "SQLDatabaseToolkit": "langchain_community.agent_toolkits.sql.toolkit",
+ "SlackToolkit": "langchain_community.agent_toolkits.slack.toolkit",
+ "SparkSQLToolkit": "langchain_community.agent_toolkits.spark_sql.toolkit",
+ "SteamToolkit": "langchain_community.agent_toolkits.steam.toolkit",
+ "ZapierToolkit": "langchain_community.agent_toolkits.zapier.toolkit",
+ "create_json_agent": "langchain_community.agent_toolkits.json.base",
+ "create_openapi_agent": "langchain_community.agent_toolkits.openapi.base",
+ "create_pbi_agent": "langchain_community.agent_toolkits.powerbi.base",
+ "create_pbi_chat_agent": "langchain_community.agent_toolkits.powerbi.chat_base",
+ "create_spark_sql_agent": "langchain_community.agent_toolkits.spark_sql.base",
+ "create_sql_agent": "langchain_community.agent_toolkits.sql.base",
+}
+
+
+def __getattr__(name: str) -> Any:
+ if name in _module_lookup:
+ module = importlib.import_module(_module_lookup[name])
+ return getattr(module, name)
+ raise AttributeError(f"module {__name__} has no attribute {name}")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/azure_ai_services.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/azure_ai_services.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a69fa7c5bd315f00e2c7e56e1e262979a3ede2b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/azure_ai_services.py
@@ -0,0 +1,31 @@
+from __future__ import annotations
+
+from typing import List
+
+from langchain_core.tools import BaseTool
+from langchain_core.tools.base import BaseToolkit
+
+from langchain_community.tools.azure_ai_services import (
+ AzureAiServicesDocumentIntelligenceTool,
+ AzureAiServicesImageAnalysisTool,
+ AzureAiServicesSpeechToTextTool,
+ AzureAiServicesTextAnalyticsForHealthTool,
+ AzureAiServicesTextToSpeechTool,
+)
+
+
+class AzureAiServicesToolkit(BaseToolkit):
+ """Toolkit for Azure AI Services."""
+
+ def get_tools(self) -> List[BaseTool]:
+ """Get the tools in the toolkit."""
+
+ tools: List[BaseTool] = [
+ AzureAiServicesDocumentIntelligenceTool(), # type: ignore[call-arg]
+ AzureAiServicesImageAnalysisTool(),
+ AzureAiServicesSpeechToTextTool(), # type: ignore[call-arg]
+ AzureAiServicesTextToSpeechTool(), # type: ignore[call-arg]
+ AzureAiServicesTextAnalyticsForHealthTool(), # type: ignore[call-arg]
+ ]
+
+ return tools
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/azure_cognitive_services.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/azure_cognitive_services.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f9b27bf481453d8a524be2ef48b9924ec8ae1ce
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/azure_cognitive_services.py
@@ -0,0 +1,34 @@
+from __future__ import annotations
+
+import sys
+from typing import List
+
+from langchain_core.tools import BaseTool
+from langchain_core.tools.base import BaseToolkit
+
+from langchain_community.tools.azure_cognitive_services import (
+ AzureCogsFormRecognizerTool,
+ AzureCogsImageAnalysisTool,
+ AzureCogsSpeech2TextTool,
+ AzureCogsText2SpeechTool,
+ AzureCogsTextAnalyticsHealthTool,
+)
+
+
+class AzureCognitiveServicesToolkit(BaseToolkit):
+ """Toolkit for Azure Cognitive Services."""
+
+ def get_tools(self) -> List[BaseTool]:
+ """Get the tools in the toolkit."""
+
+ tools: List[BaseTool] = [
+ AzureCogsFormRecognizerTool(), # type: ignore[call-arg]
+ AzureCogsSpeech2TextTool(), # type: ignore[call-arg]
+ AzureCogsText2SpeechTool(), # type: ignore[call-arg]
+ AzureCogsTextAnalyticsHealthTool(), # type: ignore[call-arg]
+ ]
+
+ # TODO: Remove check once azure-ai-vision supports MacOS.
+ if sys.platform.startswith("linux") or sys.platform.startswith("win"):
+ tools.append(AzureCogsImageAnalysisTool()) # type: ignore[call-arg]
+ return tools
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a2ad9cdb9738050ae163951bb9e15bd76566da5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/base.py
@@ -0,0 +1,5 @@
+"""Toolkits for agents."""
+
+from langchain_core.tools.base import BaseToolkit
+
+__all__ = ["BaseToolkit"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/load_tools.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/load_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..510ee7fe69796ef19f94ed798b3e5330afca756f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agent_toolkits/load_tools.py
@@ -0,0 +1,771 @@
+# flake8: noqa
+"""Tools provide access to various resources and services.
+
+LangChain has a large ecosystem of integrations with various external resources
+like local and remote file systems, APIs and databases.
+
+These integrations allow developers to create versatile applications that combine the
+power of LLMs with the ability to access, interact with and manipulate external
+resources.
+
+When developing an application, developers should inspect the capabilities and
+permissions of the tools that underlie the given agent toolkit, and determine
+whether permissions of the given toolkit are appropriate for the application.
+
+See [Security](https://python.langchain.com/docs/security) for more information.
+"""
+
+import warnings
+from typing import Any, Dict, List, Optional, Callable, Tuple
+
+from mypy_extensions import Arg, KwArg
+
+from langchain_community.tools.arxiv.tool import ArxivQueryRun
+from langchain_community.tools.bing_search.tool import BingSearchRun
+from langchain_community.tools.dataforseo_api_search import DataForSeoAPISearchResults
+from langchain_community.tools.dataforseo_api_search import DataForSeoAPISearchRun
+from langchain_community.tools.ddg_search.tool import DuckDuckGoSearchRun
+from langchain_community.tools.eleven_labs.text2speech import ElevenLabsText2SpeechTool
+from langchain_community.tools.file_management import ReadFileTool
+from langchain_community.tools.golden_query.tool import GoldenQueryRun
+from langchain_community.tools.google_cloud.texttospeech import (
+ GoogleCloudTextToSpeechTool,
+)
+from langchain_community.tools.google_finance.tool import GoogleFinanceQueryRun
+from langchain_community.tools.google_jobs.tool import GoogleJobsQueryRun
+from langchain_community.tools.google_lens.tool import GoogleLensQueryRun
+from langchain_community.tools.google_scholar.tool import GoogleScholarQueryRun
+from langchain_community.tools.google_search.tool import (
+ GoogleSearchResults,
+ GoogleSearchRun,
+)
+from langchain_community.tools.google_serper.tool import (
+ GoogleSerperResults,
+ GoogleSerperRun,
+)
+from langchain_community.tools.google_trends.tool import GoogleTrendsQueryRun
+from langchain_community.tools.graphql.tool import BaseGraphQLTool
+from langchain_community.tools.human.tool import HumanInputRun
+from langchain_community.tools.memorize.tool import Memorize
+from langchain_community.tools.merriam_webster.tool import MerriamWebsterQueryRun
+from langchain_community.tools.metaphor_search.tool import MetaphorSearchResults
+from langchain_community.tools.openweathermap.tool import OpenWeatherMapQueryRun
+from langchain_community.tools.pubmed.tool import PubmedQueryRun
+from langchain_community.tools.reddit_search.tool import RedditSearchRun
+from langchain_community.tools.requests.tool import (
+ RequestsDeleteTool,
+ RequestsGetTool,
+ RequestsPatchTool,
+ RequestsPostTool,
+ RequestsPutTool,
+)
+from langchain_community.tools.scenexplain.tool import SceneXplainTool
+from langchain_community.tools.searchapi.tool import SearchAPIResults, SearchAPIRun
+from langchain_community.tools.searx_search.tool import (
+ SearxSearchResults,
+ SearxSearchRun,
+)
+from langchain_community.tools.shell.tool import ShellTool
+from langchain_community.tools.sleep.tool import SleepTool
+from langchain_community.tools.stackexchange.tool import StackExchangeTool
+from langchain_community.tools.wikipedia.tool import WikipediaQueryRun
+from langchain_community.tools.wolfram_alpha.tool import WolframAlphaQueryRun
+from langchain_community.utilities.arxiv import ArxivAPIWrapper
+from langchain_community.utilities.awslambda import LambdaWrapper
+from langchain_community.utilities.bing_search import BingSearchAPIWrapper
+from langchain_community.utilities.dalle_image_generator import DallEAPIWrapper
+from langchain_community.utilities.dataforseo_api_search import DataForSeoAPIWrapper
+from langchain_community.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper
+from langchain_community.utilities.golden_query import GoldenQueryAPIWrapper
+from langchain_community.utilities.google_books import GoogleBooksAPIWrapper
+from langchain_community.utilities.google_finance import GoogleFinanceAPIWrapper
+from langchain_community.utilities.google_jobs import GoogleJobsAPIWrapper
+from langchain_community.utilities.google_lens import GoogleLensAPIWrapper
+from langchain_community.utilities.google_scholar import GoogleScholarAPIWrapper
+from langchain_community.utilities.google_search import GoogleSearchAPIWrapper
+from langchain_community.utilities.google_serper import GoogleSerperAPIWrapper
+from langchain_community.utilities.google_trends import GoogleTrendsAPIWrapper
+from langchain_community.utilities.graphql import GraphQLAPIWrapper
+from langchain_community.utilities.merriam_webster import MerriamWebsterAPIWrapper
+from langchain_community.utilities.metaphor_search import MetaphorSearchAPIWrapper
+from langchain_community.utilities.openweathermap import OpenWeatherMapAPIWrapper
+from langchain_community.utilities.pubmed import PubMedAPIWrapper
+from langchain_community.utilities.reddit_search import RedditSearchAPIWrapper
+from langchain_community.utilities.requests import TextRequestsWrapper
+from langchain_community.utilities.searchapi import SearchApiAPIWrapper
+from langchain_community.utilities.searx_search import SearxSearchWrapper
+from langchain_community.utilities.serpapi import SerpAPIWrapper
+from langchain_community.utilities.stackexchange import StackExchangeAPIWrapper
+from langchain_community.utilities.twilio import TwilioAPIWrapper
+from langchain_community.utilities.wikipedia import WikipediaAPIWrapper
+from langchain_community.utilities.wolfram_alpha import WolframAlphaAPIWrapper
+from langchain_core.callbacks import BaseCallbackManager
+from langchain_core.callbacks import Callbacks
+from langchain_core.language_models import BaseLanguageModel
+from langchain_core.tools import BaseTool, Tool
+
+
+def _get_tools_requests_get() -> BaseTool:
+ # Dangerous requests are allowed here, because there's another flag that the user
+ # has to provide in order to actually opt in.
+ # This is a private function and should not be used directly.
+ return RequestsGetTool(
+ requests_wrapper=TextRequestsWrapper(), allow_dangerous_requests=True
+ )
+
+
+def _get_tools_requests_post() -> BaseTool:
+ # Dangerous requests are allowed here, because there's another flag that the user
+ # has to provide in order to actually opt in.
+ # This is a private function and should not be used directly.
+ return RequestsPostTool(
+ requests_wrapper=TextRequestsWrapper(), allow_dangerous_requests=True
+ )
+
+
+def _get_tools_requests_patch() -> BaseTool:
+ # Dangerous requests are allowed here, because there's another flag that the user
+ # has to provide in order to actually opt in.
+ # This is a private function and should not be used directly.
+ return RequestsPatchTool(
+ requests_wrapper=TextRequestsWrapper(), allow_dangerous_requests=True
+ )
+
+
+def _get_tools_requests_put() -> BaseTool:
+ # Dangerous requests are allowed here, because there's another flag that the user
+ # has to provide in order to actually opt in.
+ # This is a private function and should not be used directly.
+ return RequestsPutTool(
+ requests_wrapper=TextRequestsWrapper(), allow_dangerous_requests=True
+ )
+
+
+def _get_tools_requests_delete() -> BaseTool:
+ # Dangerous requests are allowed here, because there's another flag that the user
+ # has to provide in order to actually opt in.
+ # This is a private function and should not be used directly.
+ return RequestsDeleteTool(
+ requests_wrapper=TextRequestsWrapper(), allow_dangerous_requests=True
+ )
+
+
+def _get_terminal() -> BaseTool:
+ return ShellTool()
+
+
+def _get_sleep() -> BaseTool:
+ return SleepTool()
+
+
+_BASE_TOOLS: Dict[str, Callable[[], BaseTool]] = {
+ "sleep": _get_sleep,
+}
+
+DANGEROUS_TOOLS = {
+ # Tools that contain some level of risk.
+ # Please use with caution and read the documentation of these tools
+ # to understand the risks and how to mitigate them.
+ # Refer to https://python.langchain.com/docs/security
+ # for more information.
+ "requests": _get_tools_requests_get, # preserved for backwards compatibility
+ "requests_get": _get_tools_requests_get,
+ "requests_post": _get_tools_requests_post,
+ "requests_patch": _get_tools_requests_patch,
+ "requests_put": _get_tools_requests_put,
+ "requests_delete": _get_tools_requests_delete,
+ "terminal": _get_terminal,
+}
+
+
+def _get_llm_math(llm: BaseLanguageModel) -> BaseTool:
+ try:
+ from langchain_classic.chains.llm_math.base import LLMMathChain
+ except ImportError:
+ raise ImportError(
+ "LLM Math tools require the library `langchain` to be installed."
+ " Please install it with `pip install langchain`."
+ )
+ return Tool(
+ name="Calculator",
+ description="Useful for when you need to answer questions about math.",
+ func=LLMMathChain.from_llm(llm=llm).run,
+ coroutine=LLMMathChain.from_llm(llm=llm).arun,
+ )
+
+
+def _get_open_meteo_api(llm: BaseLanguageModel) -> BaseTool:
+ try:
+ from langchain_classic.chains.api.base import APIChain
+ from langchain_classic.chains.api import (
+ open_meteo_docs,
+ )
+ except ImportError:
+ raise ImportError(
+ "API tools require the library `langchain` to be installed."
+ " Please install it with `pip install langchain`."
+ )
+ chain = APIChain.from_llm_and_api_docs(
+ llm,
+ open_meteo_docs.OPEN_METEO_DOCS,
+ limit_to_domains=["https://api.open-meteo.com/"],
+ )
+ return Tool(
+ name="Open-Meteo-API",
+ description="Useful for when you want to get weather information from the OpenMeteo API. The input should be a question in natural language that this API can answer.",
+ func=chain.run,
+ )
+
+
+_LLM_TOOLS: Dict[str, Callable[[BaseLanguageModel], BaseTool]] = {
+ "llm-math": _get_llm_math,
+ "open-meteo-api": _get_open_meteo_api,
+}
+
+
+def _get_news_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:
+ news_api_key = kwargs["news_api_key"]
+ try:
+ from langchain_classic.chains.api.base import APIChain
+ from langchain_classic.chains.api import (
+ news_docs,
+ )
+ except ImportError:
+ raise ImportError(
+ "API tools require the library `langchain` to be installed."
+ " Please install it with `pip install langchain`."
+ )
+ chain = APIChain.from_llm_and_api_docs(
+ llm,
+ news_docs.NEWS_DOCS,
+ headers={"X-Api-Key": news_api_key},
+ limit_to_domains=["https://newsapi.org/"],
+ )
+ return Tool(
+ name="News-API",
+ description="Use this when you want to get information about the top headlines of current news stories. The input should be a question in natural language that this API can answer.",
+ func=chain.run,
+ )
+
+
+def _get_tmdb_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:
+ tmdb_bearer_token = kwargs["tmdb_bearer_token"]
+ try:
+ from langchain_classic.chains.api.base import APIChain
+ from langchain_classic.chains.api import (
+ tmdb_docs,
+ )
+ except ImportError:
+ raise ImportError(
+ "API tools require the library `langchain` to be installed."
+ " Please install it with `pip install langchain`."
+ )
+ chain = APIChain.from_llm_and_api_docs(
+ llm,
+ tmdb_docs.TMDB_DOCS,
+ headers={"Authorization": f"Bearer {tmdb_bearer_token}"},
+ limit_to_domains=["https://api.themoviedb.org/"],
+ )
+ return Tool(
+ name="TMDB-API",
+ description="Useful for when you want to get information from The Movie Database. The input should be a question in natural language that this API can answer.",
+ func=chain.run,
+ )
+
+
+def _get_podcast_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:
+ listen_api_key = kwargs["listen_api_key"]
+ try:
+ from langchain_classic.chains.api.base import APIChain
+ from langchain_classic.chains.api import (
+ podcast_docs,
+ )
+ except ImportError:
+ raise ImportError(
+ "API tools require the library `langchain` to be installed."
+ " Please install it with `pip install langchain`."
+ )
+ chain = APIChain.from_llm_and_api_docs(
+ llm,
+ podcast_docs.PODCAST_DOCS,
+ headers={"X-ListenAPI-Key": listen_api_key},
+ limit_to_domains=["https://listen-api.listennotes.com/"],
+ )
+ return Tool(
+ name="Podcast-API",
+ description="Use the Listen Notes Podcast API to search all podcasts or episodes. The input should be a question in natural language that this API can answer.",
+ func=chain.run,
+ )
+
+
+def _get_lambda_api(**kwargs: Any) -> BaseTool:
+ return Tool(
+ name=kwargs["awslambda_tool_name"],
+ description=kwargs["awslambda_tool_description"],
+ func=LambdaWrapper(**kwargs).run,
+ )
+
+
+def _get_wolfram_alpha(**kwargs: Any) -> BaseTool:
+ return WolframAlphaQueryRun(api_wrapper=WolframAlphaAPIWrapper(**kwargs))
+
+
+def _get_google_search(**kwargs: Any) -> BaseTool:
+ return GoogleSearchRun(api_wrapper=GoogleSearchAPIWrapper(**kwargs))
+
+
+def _get_merriam_webster(**kwargs: Any) -> BaseTool:
+ return MerriamWebsterQueryRun(api_wrapper=MerriamWebsterAPIWrapper(**kwargs))
+
+
+def _get_wikipedia(**kwargs: Any) -> BaseTool:
+ return WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(**kwargs))
+
+
+def _get_arxiv(**kwargs: Any) -> BaseTool:
+ return ArxivQueryRun(api_wrapper=ArxivAPIWrapper(**kwargs))
+
+
+def _get_golden_query(**kwargs: Any) -> BaseTool:
+ return GoldenQueryRun(api_wrapper=GoldenQueryAPIWrapper(**kwargs))
+
+
+def _get_pubmed(**kwargs: Any) -> BaseTool:
+ return PubmedQueryRun(api_wrapper=PubMedAPIWrapper(**kwargs))
+
+
+def _get_google_books(**kwargs: Any) -> BaseTool:
+ from langchain_community.tools.google_books import GoogleBooksQueryRun
+
+ return GoogleBooksQueryRun(api_wrapper=GoogleBooksAPIWrapper(**kwargs))
+
+
+def _get_google_jobs(**kwargs: Any) -> BaseTool:
+ return GoogleJobsQueryRun(api_wrapper=GoogleJobsAPIWrapper(**kwargs))
+
+
+def _get_google_lens(**kwargs: Any) -> BaseTool:
+ return GoogleLensQueryRun(api_wrapper=GoogleLensAPIWrapper(**kwargs))
+
+
+def _get_google_serper(**kwargs: Any) -> BaseTool:
+ return GoogleSerperRun(api_wrapper=GoogleSerperAPIWrapper(**kwargs))
+
+
+def _get_google_scholar(**kwargs: Any) -> BaseTool:
+ return GoogleScholarQueryRun(api_wrapper=GoogleScholarAPIWrapper(**kwargs))
+
+
+def _get_google_finance(**kwargs: Any) -> BaseTool:
+ return GoogleFinanceQueryRun(api_wrapper=GoogleFinanceAPIWrapper(**kwargs))
+
+
+def _get_google_trends(**kwargs: Any) -> BaseTool:
+ return GoogleTrendsQueryRun(api_wrapper=GoogleTrendsAPIWrapper(**kwargs))
+
+
+def _get_google_serper_results_json(**kwargs: Any) -> BaseTool:
+ return GoogleSerperResults(api_wrapper=GoogleSerperAPIWrapper(**kwargs))
+
+
+def _get_google_search_results_json(**kwargs: Any) -> BaseTool:
+ return GoogleSearchResults(api_wrapper=GoogleSearchAPIWrapper(**kwargs))
+
+
+def _get_searchapi(**kwargs: Any) -> BaseTool:
+ return SearchAPIRun(api_wrapper=SearchApiAPIWrapper(**kwargs))
+
+
+def _get_searchapi_results_json(**kwargs: Any) -> BaseTool:
+ return SearchAPIResults(api_wrapper=SearchApiAPIWrapper(**kwargs))
+
+
+def _get_serpapi(**kwargs: Any) -> BaseTool:
+ return Tool(
+ name="Search",
+ description="A search engine. Useful for when you need to answer questions about current events. Input should be a search query.",
+ func=SerpAPIWrapper(**kwargs).run,
+ coroutine=SerpAPIWrapper(**kwargs).arun,
+ )
+
+
+def _get_stackexchange(**kwargs: Any) -> BaseTool:
+ return StackExchangeTool(api_wrapper=StackExchangeAPIWrapper(**kwargs))
+
+
+def _get_dalle_image_generator(**kwargs: Any) -> Tool:
+ return Tool(
+ "Dall-E-Image-Generator",
+ DallEAPIWrapper(**kwargs).run,
+ "A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description.",
+ )
+
+
+def _get_twilio(**kwargs: Any) -> BaseTool:
+ return Tool(
+ name="Text-Message",
+ description="Useful for when you need to send a text message to a provided phone number.",
+ func=TwilioAPIWrapper(**kwargs).run,
+ )
+
+
+def _get_searx_search(**kwargs: Any) -> BaseTool:
+ return SearxSearchRun(wrapper=SearxSearchWrapper(**kwargs))
+
+
+def _get_searx_search_results_json(**kwargs: Any) -> BaseTool:
+ wrapper_kwargs = {k: v for k, v in kwargs.items() if k != "num_results"}
+ return SearxSearchResults(wrapper=SearxSearchWrapper(**wrapper_kwargs), **kwargs)
+
+
+def _get_bing_search(**kwargs: Any) -> BaseTool:
+ return BingSearchRun(api_wrapper=BingSearchAPIWrapper(**kwargs))
+
+
+def _get_metaphor_search(**kwargs: Any) -> BaseTool:
+ return MetaphorSearchResults(api_wrapper=MetaphorSearchAPIWrapper(**kwargs))
+
+
+def _get_ddg_search(**kwargs: Any) -> BaseTool:
+ return DuckDuckGoSearchRun(api_wrapper=DuckDuckGoSearchAPIWrapper(**kwargs))
+
+
+def _get_human_tool(**kwargs: Any) -> BaseTool:
+ return HumanInputRun(**kwargs)
+
+
+def _get_scenexplain(**kwargs: Any) -> BaseTool:
+ return SceneXplainTool(**kwargs)
+
+
+def _get_graphql_tool(**kwargs: Any) -> BaseTool:
+ return BaseGraphQLTool(graphql_wrapper=GraphQLAPIWrapper(**kwargs))
+
+
+def _get_openweathermap(**kwargs: Any) -> BaseTool:
+ return OpenWeatherMapQueryRun(api_wrapper=OpenWeatherMapAPIWrapper(**kwargs))
+
+
+def _get_dataforseo_api_search(**kwargs: Any) -> BaseTool:
+ return DataForSeoAPISearchRun(api_wrapper=DataForSeoAPIWrapper(**kwargs))
+
+
+def _get_dataforseo_api_search_json(**kwargs: Any) -> BaseTool:
+ return DataForSeoAPISearchResults(api_wrapper=DataForSeoAPIWrapper(**kwargs))
+
+
+def _get_eleven_labs_text2speech(**kwargs: Any) -> BaseTool:
+ return ElevenLabsText2SpeechTool(**kwargs)
+
+
+def _get_memorize(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:
+ return Memorize(llm=llm) # type: ignore[arg-type]
+
+
+def _get_google_cloud_texttospeech(**kwargs: Any) -> BaseTool:
+ return GoogleCloudTextToSpeechTool(**kwargs)
+
+
+def _get_file_management_tool(**kwargs: Any) -> BaseTool:
+ return ReadFileTool(**kwargs)
+
+
+def _get_reddit_search(**kwargs: Any) -> BaseTool:
+ return RedditSearchRun(api_wrapper=RedditSearchAPIWrapper(**kwargs))
+
+
+_EXTRA_LLM_TOOLS: Dict[
+ str,
+ Tuple[Callable[[Arg(BaseLanguageModel, "llm"), KwArg(Any)], BaseTool], List[str]],
+] = {
+ "news-api": (_get_news_api, ["news_api_key"]),
+ "tmdb-api": (_get_tmdb_api, ["tmdb_bearer_token"]),
+ "podcast-api": (_get_podcast_api, ["listen_api_key"]),
+ "memorize": (_get_memorize, []),
+}
+_EXTRA_OPTIONAL_TOOLS: Dict[str, Tuple[Callable[[KwArg(Any)], BaseTool], List[str]]] = {
+ "wolfram-alpha": (_get_wolfram_alpha, ["wolfram_alpha_appid"]),
+ "google-search": (_get_google_search, ["google_api_key", "google_cse_id"]),
+ "google-search-results-json": (
+ _get_google_search_results_json,
+ ["google_api_key", "google_cse_id", "num_results"],
+ ),
+ "searx-search-results-json": (
+ _get_searx_search_results_json,
+ ["searx_host", "engines", "num_results", "aiosession"],
+ ),
+ "bing-search": (_get_bing_search, ["bing_subscription_key", "bing_search_url"]),
+ "metaphor-search": (_get_metaphor_search, ["metaphor_api_key"]),
+ "ddg-search": (_get_ddg_search, []),
+ "google-books": (_get_google_books, ["google_books_api_key"]),
+ "google-lens": (_get_google_lens, ["serp_api_key"]),
+ "google-serper": (_get_google_serper, ["serper_api_key", "aiosession"]),
+ "google-scholar": (
+ _get_google_scholar,
+ ["top_k_results", "hl", "lr", "serp_api_key"],
+ ),
+ "google-finance": (
+ _get_google_finance,
+ ["serp_api_key"],
+ ),
+ "google-trends": (
+ _get_google_trends,
+ ["serp_api_key"],
+ ),
+ "google-jobs": (
+ _get_google_jobs,
+ ["serp_api_key"],
+ ),
+ "google-serper-results-json": (
+ _get_google_serper_results_json,
+ ["serper_api_key", "aiosession"],
+ ),
+ "searchapi": (_get_searchapi, ["searchapi_api_key", "aiosession"]),
+ "searchapi-results-json": (
+ _get_searchapi_results_json,
+ ["searchapi_api_key", "aiosession"],
+ ),
+ "serpapi": (_get_serpapi, ["serpapi_api_key", "aiosession"]),
+ "dalle-image-generator": (_get_dalle_image_generator, ["openai_api_key"]),
+ "twilio": (_get_twilio, ["account_sid", "auth_token", "from_number"]),
+ "searx-search": (_get_searx_search, ["searx_host", "engines", "aiosession"]),
+ "merriam-webster": (_get_merriam_webster, ["merriam_webster_api_key"]),
+ "wikipedia": (_get_wikipedia, ["top_k_results", "lang"]),
+ "arxiv": (
+ _get_arxiv,
+ ["top_k_results", "load_max_docs", "load_all_available_meta"],
+ ),
+ "golden-query": (_get_golden_query, ["golden_api_key"]),
+ "pubmed": (_get_pubmed, ["top_k_results"]),
+ "human": (_get_human_tool, ["prompt_func", "input_func"]),
+ "awslambda": (
+ _get_lambda_api,
+ ["awslambda_tool_name", "awslambda_tool_description", "function_name"],
+ ),
+ "stackexchange": (_get_stackexchange, []),
+ "sceneXplain": (_get_scenexplain, []),
+ "graphql": (
+ _get_graphql_tool,
+ ["graphql_endpoint", "custom_headers", "fetch_schema_from_transport"],
+ ),
+ "openweathermap-api": (_get_openweathermap, ["openweathermap_api_key"]),
+ "dataforseo-api-search": (
+ _get_dataforseo_api_search,
+ ["api_login", "api_password", "aiosession"],
+ ),
+ "dataforseo-api-search-json": (
+ _get_dataforseo_api_search_json,
+ ["api_login", "api_password", "aiosession"],
+ ),
+ "eleven_labs_text2speech": (_get_eleven_labs_text2speech, ["elevenlabs_api_key"]),
+ "google_cloud_texttospeech": (_get_google_cloud_texttospeech, []),
+ "read_file": (_get_file_management_tool, []),
+ "reddit_search": (
+ _get_reddit_search,
+ ["reddit_client_id", "reddit_client_secret", "reddit_user_agent"],
+ ),
+}
+
+
+def _handle_callbacks(
+ callback_manager: Optional[BaseCallbackManager], callbacks: Callbacks
+) -> Callbacks:
+ if callback_manager is not None:
+ warnings.warn(
+ "callback_manager is deprecated. Please use callbacks instead.",
+ DeprecationWarning,
+ )
+ if callbacks is not None:
+ raise ValueError(
+ "Cannot specify both callback_manager and callbacks arguments."
+ )
+ return callback_manager
+ return callbacks
+
+
+def load_huggingface_tool(
+ task_or_repo_id: str,
+ model_repo_id: Optional[str] = None,
+ token: Optional[str] = None,
+ remote: bool = False,
+ **kwargs: Any,
+) -> BaseTool:
+ """Loads a tool from the HuggingFace Hub.
+
+ Args:
+ task_or_repo_id: Task or model repo id.
+ model_repo_id: Optional model repo id. Defaults to None.
+ token: Optional token. Defaults to None.
+ remote: Optional remote. Defaults to False.
+ kwargs: Additional keyword arguments.
+
+ Returns:
+ A tool.
+
+ Raises:
+ ImportError: If the required libraries are not installed.
+ NotImplementedError: If multimodal outputs or inputs are not supported.
+ """
+ try:
+ from transformers import load_tool
+ except ImportError:
+ raise ImportError(
+ "HuggingFace tools require the libraries `transformers>=4.29.0`"
+ " and `huggingface_hub>=0.14.1` to be installed."
+ " Please install it with"
+ " `pip install --upgrade transformers huggingface_hub`."
+ )
+ hf_tool = load_tool(
+ task_or_repo_id,
+ model_repo_id=model_repo_id,
+ token=token,
+ remote=remote,
+ **kwargs,
+ )
+ outputs = hf_tool.outputs
+ if set(outputs) != {"text"}:
+ raise NotImplementedError("Multimodal outputs not supported yet.")
+ inputs = hf_tool.inputs
+ if set(inputs) != {"text"}:
+ raise NotImplementedError("Multimodal inputs not supported yet.")
+ return Tool.from_function(
+ hf_tool.__call__, name=hf_tool.name, description=hf_tool.description
+ )
+
+
+def raise_dangerous_tools_exception(name: str) -> None:
+ raise ValueError(
+ f"{name} is a dangerous tool. You cannot use it without opting in "
+ "by setting allow_dangerous_tools to True. "
+ "Most tools have some inherit risk to them merely because they are "
+ 'allowed to interact with the "real world".'
+ "Please refer to LangChain security guidelines "
+ "to https://python.langchain.com/docs/security."
+ "Some tools have been designated as dangerous because they pose "
+ "risk that is not intuitively obvious. For example, a tool that "
+ "allows an agent to make requests to the web, can also be used "
+ "to make requests to a server that is only accessible from the "
+ "server hosting the code."
+ "Again, all tools carry some risk, and it's your responsibility to "
+ "understand which tools you're using and the risks associated with "
+ "them."
+ )
+
+
+def load_tools(
+ tool_names: List[str],
+ llm: Optional[BaseLanguageModel] = None,
+ callbacks: Callbacks = None,
+ allow_dangerous_tools: bool = False,
+ **kwargs: Any,
+) -> List[BaseTool]:
+ """Load tools based on their name.
+
+ Tools allow agents to interact with various resources and services like
+ APIs, databases, file systems, etc.
+
+ Please scope the permissions of each tools to the minimum required for the
+ application.
+
+ For example, if an application only needs to read from a database,
+ the database tool should not be given write permissions. Moreover
+ consider scoping the permissions to only allow accessing specific
+ tables and impose user-level quota for limiting resource usage.
+
+ Please read the APIs of the individual tools to determine which configuration
+ they support.
+
+ See [Security](https://python.langchain.com/docs/security) for more information.
+
+ Args:
+ tool_names: name of tools to load.
+ llm: An optional language model may be needed to initialize certain tools.
+ Defaults to None.
+ callbacks: Optional callback manager or list of callback handlers.
+ If not provided, default global callback manager will be used.
+ allow_dangerous_tools: Optional flag to allow dangerous tools.
+ Tools that contain some level of risk.
+ Please use with caution and read the documentation of these tools
+ to understand the risks and how to mitigate them.
+ Refer to https://python.langchain.com/docs/security
+ for more information.
+ Please note that this list may not be fully exhaustive.
+ It is your responsibility to understand which tools
+ you're using and the risks associated with them.
+ Defaults to False.
+ kwargs: Additional keyword arguments.
+
+ Returns:
+ List of tools.
+
+ Raises:
+ ValueError: If the tool name is unknown.
+ ValueError: If the tool requires an LLM to be provided.
+ ValueError: If the tool requires some parameters that were not provided.
+ ValueError: If the tool is a dangerous tool and allow_dangerous_tools is False.
+ """
+ tools = []
+ callbacks = _handle_callbacks(
+ callback_manager=kwargs.get("callback_manager"), callbacks=callbacks
+ )
+ for name in tool_names:
+ if name in DANGEROUS_TOOLS and not allow_dangerous_tools:
+ raise_dangerous_tools_exception(name)
+
+ if name in {"requests"}:
+ warnings.warn(
+ "tool name `requests` is deprecated - "
+ "please use `requests_all` or specify the requests method"
+ )
+ if name == "requests_all":
+ # expand requests into various methods
+ if not allow_dangerous_tools:
+ raise_dangerous_tools_exception(name)
+ requests_method_tools = [
+ _tool for _tool in DANGEROUS_TOOLS if _tool.startswith("requests_")
+ ]
+ tool_names.extend(requests_method_tools)
+ elif name in _BASE_TOOLS:
+ tools.append(_BASE_TOOLS[name]())
+ elif name in DANGEROUS_TOOLS:
+ tools.append(DANGEROUS_TOOLS[name]())
+ elif name in _LLM_TOOLS:
+ if llm is None:
+ raise ValueError(f"Tool {name} requires an LLM to be provided")
+ tool = _LLM_TOOLS[name](llm)
+ tools.append(tool)
+ elif name in _EXTRA_LLM_TOOLS:
+ if llm is None:
+ raise ValueError(f"Tool {name} requires an LLM to be provided")
+ _get_llm_tool_func, extra_keys = _EXTRA_LLM_TOOLS[name]
+ missing_keys = set(extra_keys).difference(kwargs)
+ if missing_keys:
+ raise ValueError(
+ f"Tool {name} requires some parameters that were not "
+ f"provided: {missing_keys}"
+ )
+ sub_kwargs = {k: kwargs[k] for k in extra_keys}
+ tool = _get_llm_tool_func(llm=llm, **sub_kwargs)
+ tools.append(tool)
+ elif name in _EXTRA_OPTIONAL_TOOLS:
+ _get_tool_func, extra_keys = _EXTRA_OPTIONAL_TOOLS[name]
+ sub_kwargs = {k: kwargs[k] for k in extra_keys if k in kwargs}
+ tool = _get_tool_func(**sub_kwargs)
+ tools.append(tool)
+ else:
+ raise ValueError(f"Got unknown tool {name}")
+ if callbacks is not None:
+ for tool in tools:
+ tool.callbacks = callbacks
+ return tools
+
+
+def get_all_tool_names() -> List[str]:
+ """Get a list of all possible tool names."""
+ return (
+ list(_BASE_TOOLS)
+ + list(_EXTRA_OPTIONAL_TOOLS)
+ + list(_EXTRA_LLM_TOOLS)
+ + list(_LLM_TOOLS)
+ + list(DANGEROUS_TOOLS)
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agents/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/agents/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d36b91f4b1d946906c1eddcde9b968a075f3228
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/__init__.py
@@ -0,0 +1,157 @@
+"""**Callback handlers** allow listening to events in LangChain.
+
+**Class hierarchy:**
+
+.. code-block::
+
+ BaseCallbackHandler --> CallbackHandler # Example: AimCallbackHandler
+"""
+
+import importlib
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langchain_community.callbacks.aim_callback import (
+ AimCallbackHandler,
+ )
+ from langchain_community.callbacks.argilla_callback import (
+ ArgillaCallbackHandler,
+ )
+ from langchain_community.callbacks.arize_callback import (
+ ArizeCallbackHandler,
+ )
+ from langchain_community.callbacks.arthur_callback import (
+ ArthurCallbackHandler,
+ )
+ from langchain_community.callbacks.clearml_callback import (
+ ClearMLCallbackHandler,
+ )
+ from langchain_community.callbacks.comet_ml_callback import (
+ CometCallbackHandler,
+ )
+ from langchain_community.callbacks.context_callback import (
+ ContextCallbackHandler,
+ )
+ from langchain_community.callbacks.fiddler_callback import (
+ FiddlerCallbackHandler,
+ )
+ from langchain_community.callbacks.flyte_callback import (
+ FlyteCallbackHandler,
+ )
+ from langchain_community.callbacks.human import (
+ HumanApprovalCallbackHandler,
+ )
+ from langchain_community.callbacks.infino_callback import (
+ InfinoCallbackHandler,
+ )
+ from langchain_community.callbacks.labelstudio_callback import (
+ LabelStudioCallbackHandler,
+ )
+ from langchain_community.callbacks.llmonitor_callback import (
+ LLMonitorCallbackHandler,
+ )
+ from langchain_community.callbacks.manager import (
+ get_openai_callback,
+ wandb_tracing_enabled,
+ )
+ from langchain_community.callbacks.mlflow_callback import (
+ MlflowCallbackHandler,
+ )
+ from langchain_community.callbacks.openai_info import (
+ OpenAICallbackHandler,
+ )
+ from langchain_community.callbacks.promptlayer_callback import (
+ PromptLayerCallbackHandler,
+ )
+ from langchain_community.callbacks.sagemaker_callback import (
+ SageMakerCallbackHandler,
+ )
+ from langchain_community.callbacks.streamlit import (
+ LLMThoughtLabeler,
+ StreamlitCallbackHandler,
+ )
+ from langchain_community.callbacks.trubrics_callback import (
+ TrubricsCallbackHandler,
+ )
+ from langchain_community.callbacks.upstash_ratelimit_callback import (
+ UpstashRatelimitError,
+ UpstashRatelimitHandler, # noqa: F401
+ )
+ from langchain_community.callbacks.uptrain_callback import (
+ UpTrainCallbackHandler,
+ )
+ from langchain_community.callbacks.wandb_callback import (
+ WandbCallbackHandler,
+ )
+ from langchain_community.callbacks.whylabs_callback import (
+ WhyLabsCallbackHandler,
+ )
+
+
+_module_lookup = {
+ "AimCallbackHandler": "langchain_community.callbacks.aim_callback",
+ "ArgillaCallbackHandler": "langchain_community.callbacks.argilla_callback",
+ "ArizeCallbackHandler": "langchain_community.callbacks.arize_callback",
+ "ArthurCallbackHandler": "langchain_community.callbacks.arthur_callback",
+ "ClearMLCallbackHandler": "langchain_community.callbacks.clearml_callback",
+ "CometCallbackHandler": "langchain_community.callbacks.comet_ml_callback",
+ "ContextCallbackHandler": "langchain_community.callbacks.context_callback",
+ "FiddlerCallbackHandler": "langchain_community.callbacks.fiddler_callback",
+ "FlyteCallbackHandler": "langchain_community.callbacks.flyte_callback",
+ "HumanApprovalCallbackHandler": "langchain_community.callbacks.human",
+ "InfinoCallbackHandler": "langchain_community.callbacks.infino_callback",
+ "LLMThoughtLabeler": "langchain_community.callbacks.streamlit",
+ "LLMonitorCallbackHandler": "langchain_community.callbacks.llmonitor_callback",
+ "LabelStudioCallbackHandler": "langchain_community.callbacks.labelstudio_callback",
+ "MlflowCallbackHandler": "langchain_community.callbacks.mlflow_callback",
+ "OpenAICallbackHandler": "langchain_community.callbacks.openai_info",
+ "PromptLayerCallbackHandler": "langchain_community.callbacks.promptlayer_callback",
+ "SageMakerCallbackHandler": "langchain_community.callbacks.sagemaker_callback",
+ "StreamlitCallbackHandler": "langchain_community.callbacks.streamlit",
+ "TrubricsCallbackHandler": "langchain_community.callbacks.trubrics_callback",
+ "UpstashRatelimitError": "langchain_community.callbacks.upstash_ratelimit_callback",
+ "UpstashRatelimitHandler": "langchain_community.callbacks.upstash_ratelimit_callback", # noqa
+ "UpTrainCallbackHandler": "langchain_community.callbacks.uptrain_callback",
+ "WandbCallbackHandler": "langchain_community.callbacks.wandb_callback",
+ "WhyLabsCallbackHandler": "langchain_community.callbacks.whylabs_callback",
+ "get_openai_callback": "langchain_community.callbacks.manager",
+ "wandb_tracing_enabled": "langchain_community.callbacks.manager",
+}
+
+
+def __getattr__(name: str) -> Any:
+ if name in _module_lookup:
+ module = importlib.import_module(_module_lookup[name])
+ return getattr(module, name)
+ raise AttributeError(f"module {__name__} has no attribute {name}")
+
+
+__all__ = [
+ "AimCallbackHandler",
+ "ArgillaCallbackHandler",
+ "ArizeCallbackHandler",
+ "ArthurCallbackHandler",
+ "ClearMLCallbackHandler",
+ "CometCallbackHandler",
+ "ContextCallbackHandler",
+ "FiddlerCallbackHandler",
+ "FlyteCallbackHandler",
+ "HumanApprovalCallbackHandler",
+ "InfinoCallbackHandler",
+ "LLMThoughtLabeler",
+ "LLMonitorCallbackHandler",
+ "LabelStudioCallbackHandler",
+ "MlflowCallbackHandler",
+ "OpenAICallbackHandler",
+ "PromptLayerCallbackHandler",
+ "SageMakerCallbackHandler",
+ "StreamlitCallbackHandler",
+ "TrubricsCallbackHandler",
+ "UpstashRatelimitError",
+ "UpstashRatelimitHandler",
+ "UpTrainCallbackHandler",
+ "WandbCallbackHandler",
+ "WhyLabsCallbackHandler",
+ "get_openai_callback",
+ "wandb_tracing_enabled",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/aim_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/aim_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5d1aa50fec3fcae6a7cddbf7d0568555530050c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/aim_callback.py
@@ -0,0 +1,434 @@
+from copy import deepcopy
+from typing import Any, Dict, List, Optional
+
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.outputs import LLMResult
+from langchain_core.utils import guard_import
+
+
+def import_aim() -> Any:
+ """Import the aim python package and raise an error if it is not installed."""
+ return guard_import("aim")
+
+
+class BaseMetadataCallbackHandler:
+ """Callback handler for the metadata and associated function states for callbacks.
+
+ Attributes:
+ step (int): The current step.
+ starts (int): The number of times the start method has been called.
+ ends (int): The number of times the end method has been called.
+ errors (int): The number of times the error method has been called.
+ text_ctr (int): The number of times the text method has been called.
+ ignore_llm_ (bool): Whether to ignore llm callbacks.
+ ignore_chain_ (bool): Whether to ignore chain callbacks.
+ ignore_agent_ (bool): Whether to ignore agent callbacks.
+ ignore_retriever_ (bool): Whether to ignore retriever callbacks.
+ always_verbose_ (bool): Whether to always be verbose.
+ chain_starts (int): The number of times the chain start method has been called.
+ chain_ends (int): The number of times the chain end method has been called.
+ llm_starts (int): The number of times the llm start method has been called.
+ llm_ends (int): The number of times the llm end method has been called.
+ llm_streams (int): The number of times the text method has been called.
+ tool_starts (int): The number of times the tool start method has been called.
+ tool_ends (int): The number of times the tool end method has been called.
+ agent_ends (int): The number of times the agent end method has been called.
+ """
+
+ def __init__(self) -> None:
+ self.step = 0
+
+ self.starts = 0
+ self.ends = 0
+ self.errors = 0
+ self.text_ctr = 0
+
+ self.ignore_llm_ = False
+ self.ignore_chain_ = False
+ self.ignore_agent_ = False
+ self.ignore_retriever_ = False
+ self.always_verbose_ = False
+
+ self.chain_starts = 0
+ self.chain_ends = 0
+
+ self.llm_starts = 0
+ self.llm_ends = 0
+ self.llm_streams = 0
+
+ self.tool_starts = 0
+ self.tool_ends = 0
+
+ self.agent_ends = 0
+
+ @property
+ def always_verbose(self) -> bool:
+ """Whether to call verbose callbacks even if verbose is False."""
+ return self.always_verbose_
+
+ @property
+ def ignore_llm(self) -> bool:
+ """Whether to ignore LLM callbacks."""
+ return self.ignore_llm_
+
+ @property
+ def ignore_chain(self) -> bool:
+ """Whether to ignore chain callbacks."""
+ return self.ignore_chain_
+
+ @property
+ def ignore_agent(self) -> bool:
+ """Whether to ignore agent callbacks."""
+ return self.ignore_agent_
+
+ @property
+ def ignore_retriever(self) -> bool:
+ """Whether to ignore retriever callbacks."""
+ return self.ignore_retriever_
+
+ def get_custom_callback_meta(self) -> Dict[str, Any]:
+ return {
+ "step": self.step,
+ "starts": self.starts,
+ "ends": self.ends,
+ "errors": self.errors,
+ "text_ctr": self.text_ctr,
+ "chain_starts": self.chain_starts,
+ "chain_ends": self.chain_ends,
+ "llm_starts": self.llm_starts,
+ "llm_ends": self.llm_ends,
+ "llm_streams": self.llm_streams,
+ "tool_starts": self.tool_starts,
+ "tool_ends": self.tool_ends,
+ "agent_ends": self.agent_ends,
+ }
+
+ def reset_callback_meta(self) -> None:
+ """Reset the callback metadata."""
+ self.step = 0
+
+ self.starts = 0
+ self.ends = 0
+ self.errors = 0
+ self.text_ctr = 0
+
+ self.ignore_llm_ = False
+ self.ignore_chain_ = False
+ self.ignore_agent_ = False
+ self.always_verbose_ = False
+
+ self.chain_starts = 0
+ self.chain_ends = 0
+
+ self.llm_starts = 0
+ self.llm_ends = 0
+ self.llm_streams = 0
+
+ self.tool_starts = 0
+ self.tool_ends = 0
+
+ self.agent_ends = 0
+
+ return None
+
+
+class AimCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
+ """Callback Handler that logs to Aim.
+
+ Parameters:
+ repo (:obj:`str`, optional): Aim repository path or Repo object to which
+ Run object is bound. If skipped, default Repo is used.
+ experiment_name (:obj:`str`, optional): Sets Run's `experiment` property.
+ 'default' if not specified. Can be used later to query runs/sequences.
+ system_tracking_interval (:obj:`int`, optional): Sets the tracking interval
+ in seconds for system usage metrics (CPU, Memory, etc.). Set to `None`
+ to disable system metrics tracking.
+ log_system_params (:obj:`bool`, optional): Enable/Disable logging of system
+ params such as installed packages, git info, environment variables, etc.
+
+ This handler will utilize the associated callback method called and formats
+ the input of each callback function with metadata regarding the state of LLM run
+ and then logs the response to Aim.
+ """
+
+ def __init__(
+ self,
+ repo: Optional[str] = None,
+ experiment_name: Optional[str] = None,
+ system_tracking_interval: Optional[int] = 10,
+ log_system_params: bool = True,
+ ) -> None:
+ """Initialize callback handler."""
+
+ super().__init__()
+
+ aim = import_aim()
+ self.repo = repo
+ self.experiment_name = experiment_name
+ self.system_tracking_interval = system_tracking_interval
+ self.log_system_params = log_system_params
+ self._run = aim.Run(
+ repo=self.repo,
+ experiment=self.experiment_name,
+ system_tracking_interval=self.system_tracking_interval,
+ log_system_params=self.log_system_params,
+ )
+ self._run_hash = self._run.hash
+ self.action_records: list = []
+
+ def setup(self, **kwargs: Any) -> None:
+ aim = import_aim()
+
+ if not self._run:
+ if self._run_hash:
+ self._run = aim.Run(
+ self._run_hash,
+ repo=self.repo,
+ system_tracking_interval=self.system_tracking_interval,
+ )
+ else:
+ self._run = aim.Run(
+ repo=self.repo,
+ experiment=self.experiment_name,
+ system_tracking_interval=self.system_tracking_interval,
+ log_system_params=self.log_system_params,
+ )
+ self._run_hash = self._run.hash
+
+ if kwargs:
+ for key, value in kwargs.items():
+ self._run.set(key, value, strict=False)
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Run when LLM starts."""
+ aim = import_aim()
+
+ self.step += 1
+ self.llm_starts += 1
+ self.starts += 1
+
+ resp = {"action": "on_llm_start"}
+ resp.update(self.get_custom_callback_meta())
+
+ prompts_res = deepcopy(prompts)
+
+ self._run.track(
+ [aim.Text(prompt) for prompt in prompts_res],
+ name="on_llm_start",
+ context=resp,
+ )
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running."""
+ aim = import_aim()
+ self.step += 1
+ self.llm_ends += 1
+ self.ends += 1
+
+ resp = {"action": "on_llm_end"}
+ resp.update(self.get_custom_callback_meta())
+
+ response_res = deepcopy(response)
+
+ generated = [
+ aim.Text(generation.text)
+ for generations in response_res.generations
+ for generation in generations
+ ]
+ self._run.track(
+ generated,
+ name="on_llm_end",
+ context=resp,
+ )
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Run when LLM generates a new token."""
+ self.step += 1
+ self.llm_streams += 1
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when LLM errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Run when chain starts running."""
+ aim = import_aim()
+ self.step += 1
+ self.chain_starts += 1
+ self.starts += 1
+
+ resp = {"action": "on_chain_start"}
+ resp.update(self.get_custom_callback_meta())
+
+ inputs_res = deepcopy(inputs)
+
+ self._run.track(
+ aim.Text(inputs_res["input"]), name="on_chain_start", context=resp
+ )
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Run when chain ends running."""
+ aim = import_aim()
+ self.step += 1
+ self.chain_ends += 1
+ self.ends += 1
+
+ resp = {"action": "on_chain_end"}
+ resp.update(self.get_custom_callback_meta())
+
+ outputs_res = deepcopy(outputs)
+
+ self._run.track(
+ aim.Text(outputs_res["output"]), name="on_chain_end", context=resp
+ )
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when chain errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_tool_start(
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
+ ) -> None:
+ """Run when tool starts running."""
+ aim = import_aim()
+ self.step += 1
+ self.tool_starts += 1
+ self.starts += 1
+
+ resp = {"action": "on_tool_start"}
+ resp.update(self.get_custom_callback_meta())
+
+ self._run.track(aim.Text(input_str), name="on_tool_start", context=resp)
+
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
+ """Run when tool ends running."""
+ output = str(output)
+ aim = import_aim()
+ self.step += 1
+ self.tool_ends += 1
+ self.ends += 1
+
+ resp = {"action": "on_tool_end"}
+ resp.update(self.get_custom_callback_meta())
+
+ self._run.track(aim.Text(output), name="on_tool_end", context=resp)
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when tool errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """
+ Run when agent is ending.
+ """
+ self.step += 1
+ self.text_ctr += 1
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run when agent ends running."""
+ aim = import_aim()
+ self.step += 1
+ self.agent_ends += 1
+ self.ends += 1
+
+ resp = {"action": "on_agent_finish"}
+ resp.update(self.get_custom_callback_meta())
+
+ finish_res = deepcopy(finish)
+
+ text = "OUTPUT:\n{}\n\nLOG:\n{}".format(
+ finish_res.return_values["output"], finish_res.log
+ )
+ self._run.track(aim.Text(text), name="on_agent_finish", context=resp)
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Run on agent action."""
+ aim = import_aim()
+ self.step += 1
+ self.tool_starts += 1
+ self.starts += 1
+
+ resp = {
+ "action": "on_agent_action",
+ "tool": action.tool,
+ }
+ resp.update(self.get_custom_callback_meta())
+
+ action_res = deepcopy(action)
+
+ text = "TOOL INPUT:\n{}\n\nLOG:\n{}".format(
+ action_res.tool_input, action_res.log
+ )
+ self._run.track(aim.Text(text), name="on_agent_action", context=resp)
+
+ def flush_tracker(
+ self,
+ repo: Optional[str] = None,
+ experiment_name: Optional[str] = None,
+ system_tracking_interval: Optional[int] = 10,
+ log_system_params: bool = True,
+ langchain_asset: Any = None,
+ reset: bool = True,
+ finish: bool = False,
+ ) -> None:
+ """Flush the tracker and reset the session.
+
+ Args:
+ repo (:obj:`str`, optional): Aim repository path or Repo object to which
+ Run object is bound. If skipped, default Repo is used.
+ experiment_name (:obj:`str`, optional): Sets Run's `experiment` property.
+ 'default' if not specified. Can be used later to query runs/sequences.
+ system_tracking_interval (:obj:`int`, optional): Sets the tracking interval
+ in seconds for system usage metrics (CPU, Memory, etc.). Set to `None`
+ to disable system metrics tracking.
+ log_system_params (:obj:`bool`, optional): Enable/Disable logging of system
+ params such as installed packages, git info, environment variables, etc.
+ langchain_asset: The langchain asset to save.
+ reset: Whether to reset the session.
+ finish: Whether to finish the run.
+
+ Returns:
+ None
+ """
+
+ if langchain_asset:
+ try:
+ for key, value in langchain_asset.dict().items():
+ self._run.set(key, value, strict=False)
+ except Exception:
+ pass
+
+ if finish or reset:
+ self._run.close()
+ self.reset_callback_meta()
+ if reset:
+ aim = import_aim()
+ self.repo = repo if repo else self.repo
+ self.experiment_name = (
+ experiment_name if experiment_name else self.experiment_name
+ )
+ self.system_tracking_interval = (
+ system_tracking_interval
+ if system_tracking_interval
+ else self.system_tracking_interval
+ )
+ self.log_system_params = (
+ log_system_params if log_system_params else self.log_system_params
+ )
+
+ self._run = aim.Run(
+ repo=self.repo,
+ experiment=self.experiment_name,
+ system_tracking_interval=self.system_tracking_interval,
+ log_system_params=self.log_system_params,
+ )
+ self._run_hash = self._run.hash
+ self.action_records = []
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/argilla_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/argilla_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cd005c5cb15255866abde9f0568c77baddbeaeb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/argilla_callback.py
@@ -0,0 +1,349 @@
+import os
+import warnings
+from typing import Any, Dict, List, Optional, cast
+
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.outputs import LLMResult
+from packaging.version import parse
+
+
+class ArgillaCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that logs into Argilla.
+
+ Args:
+ dataset_name: name of the `FeedbackDataset` in Argilla. Note that it must
+ exist in advance. If you need help on how to create a `FeedbackDataset` in
+ Argilla, please visit
+ https://docs.argilla.io/en/latest/tutorials_and_integrations/integrations/use_argilla_callback_in_langchain.html.
+ workspace_name: name of the workspace in Argilla where the specified
+ `FeedbackDataset` lives in. Defaults to `None`, which means that the
+ default workspace will be used.
+ api_url: URL of the Argilla Server that we want to use, and where the
+ `FeedbackDataset` lives in. Defaults to `None`, which means that either
+ `ARGILLA_API_URL` environment variable or the default will be used.
+ api_key: API Key to connect to the Argilla Server. Defaults to `None`, which
+ means that either `ARGILLA_API_KEY` environment variable or the default
+ will be used.
+
+ Raises:
+ ImportError: if the `argilla` package is not installed.
+ ConnectionError: if the connection to Argilla fails.
+ FileNotFoundError: if the `FeedbackDataset` retrieval from Argilla fails.
+
+ Examples:
+ >>> from langchain_community.llms import OpenAI
+ >>> from langchain_community.callbacks import ArgillaCallbackHandler
+ >>> argilla_callback = ArgillaCallbackHandler(
+ ... dataset_name="my-dataset",
+ ... workspace_name="my-workspace",
+ ... api_url="http://localhost:6900",
+ ... api_key="argilla.apikey",
+ ... )
+ >>> llm = OpenAI(
+ ... temperature=0,
+ ... callbacks=[argilla_callback],
+ ... verbose=True,
+ ... openai_api_key="API_KEY_HERE",
+ ... )
+ >>> llm.generate([
+ ... "What is the best NLP-annotation tool out there? (no bias at all)",
+ ... ])
+ "Argilla, no doubt about it."
+ """
+
+ REPO_URL: str = "https://github.com/argilla-io/argilla"
+ ISSUES_URL: str = f"{REPO_URL}/issues"
+ BLOG_URL: str = "https://docs.argilla.io/en/latest/tutorials_and_integrations/integrations/use_argilla_callback_in_langchain.html"
+
+ DEFAULT_API_URL: str = "http://localhost:6900"
+
+ def __init__(
+ self,
+ dataset_name: str,
+ workspace_name: Optional[str] = None,
+ api_url: Optional[str] = None,
+ api_key: Optional[str] = None,
+ ) -> None:
+ """Initializes the `ArgillaCallbackHandler`.
+
+ Args:
+ dataset_name: name of the `FeedbackDataset` in Argilla. Note that it must
+ exist in advance. If you need help on how to create a `FeedbackDataset`
+ in Argilla, please visit
+ https://docs.argilla.io/en/latest/tutorials_and_integrations/integrations/use_argilla_callback_in_langchain.html.
+ workspace_name: name of the workspace in Argilla where the specified
+ `FeedbackDataset` lives in. Defaults to `None`, which means that the
+ default workspace will be used.
+ api_url: URL of the Argilla Server that we want to use, and where the
+ `FeedbackDataset` lives in. Defaults to `None`, which means that either
+ `ARGILLA_API_URL` environment variable or the default will be used.
+ api_key: API Key to connect to the Argilla Server. Defaults to `None`, which
+ means that either `ARGILLA_API_KEY` environment variable or the default
+ will be used.
+
+ Raises:
+ ImportError: if the `argilla` package is not installed.
+ ConnectionError: if the connection to Argilla fails.
+ FileNotFoundError: if the `FeedbackDataset` retrieval from Argilla fails.
+ """
+
+ super().__init__()
+
+ # Import Argilla (not via `import_argilla` to keep hints in IDEs)
+ try:
+ import argilla as rg
+
+ self.ARGILLA_VERSION = rg.__version__
+ except ImportError:
+ raise ImportError(
+ "To use the Argilla callback manager you need to have the `argilla` "
+ "Python package installed. Please install it with `pip install argilla`"
+ )
+
+ # Check whether the Argilla version is compatible
+ if parse(self.ARGILLA_VERSION) < parse("1.8.0"):
+ raise ImportError(
+ f"The installed `argilla` version is {self.ARGILLA_VERSION} but "
+ "`ArgillaCallbackHandler` requires at least version 1.8.0. Please "
+ "upgrade `argilla` with `pip install --upgrade argilla`."
+ )
+
+ # Show a warning message if Argilla will assume the default values will be used
+ if api_url is None and os.getenv("ARGILLA_API_URL") is None:
+ warnings.warn(
+ (
+ "Since `api_url` is None, and the env var `ARGILLA_API_URL` is not"
+ f" set, it will default to `{self.DEFAULT_API_URL}`, which is the"
+ " default API URL in Argilla Quickstart."
+ ),
+ )
+ api_url = self.DEFAULT_API_URL
+
+ if api_key is None and os.getenv("ARGILLA_API_KEY") is None:
+ self.DEFAULT_API_KEY = (
+ "admin.apikey"
+ if parse(self.ARGILLA_VERSION) < parse("1.11.0")
+ else "owner.apikey"
+ )
+
+ warnings.warn(
+ (
+ "Since `api_key` is None, and the env var `ARGILLA_API_KEY` is not"
+ f" set, it will default to `{self.DEFAULT_API_KEY}`, which is the"
+ " default API key in Argilla Quickstart."
+ ),
+ )
+ api_key = self.DEFAULT_API_KEY
+
+ # Connect to Argilla with the provided credentials, if applicable
+ try:
+ rg.init(api_key=api_key, api_url=api_url)
+ except Exception as e:
+ raise ConnectionError(
+ f"Could not connect to Argilla with exception: '{e}'.\n"
+ "Please check your `api_key` and `api_url`, and make sure that "
+ "the Argilla server is up and running. If the problem persists "
+ f"please report it to {self.ISSUES_URL} as an `integration` issue."
+ ) from e
+
+ # Set the Argilla variables
+ self.dataset_name = dataset_name
+ self.workspace_name = workspace_name or rg.get_workspace()
+
+ # Retrieve the `FeedbackDataset` from Argilla (without existing records)
+ try:
+ extra_args = {}
+ if parse(self.ARGILLA_VERSION) < parse("1.14.0"):
+ warnings.warn(
+ f"You have Argilla {self.ARGILLA_VERSION}, but Argilla 1.14.0 or"
+ " higher is recommended.",
+ UserWarning,
+ )
+ extra_args = {"with_records": False}
+ self.dataset = rg.FeedbackDataset.from_argilla(
+ name=self.dataset_name,
+ workspace=self.workspace_name,
+ **extra_args,
+ )
+ except Exception as e:
+ raise FileNotFoundError(
+ f"`FeedbackDataset` retrieval from Argilla failed with exception `{e}`."
+ f"\nPlease check that the dataset with name={self.dataset_name} in the"
+ f" workspace={self.workspace_name} exists in advance. If you need help"
+ " on how to create a `langchain`-compatible `FeedbackDataset` in"
+ f" Argilla, please visit {self.BLOG_URL}. If the problem persists"
+ f" please report it to {self.ISSUES_URL} as an `integration` issue."
+ ) from e
+
+ supported_fields = ["prompt", "response"]
+ if supported_fields != [field.name for field in self.dataset.fields]:
+ raise ValueError(
+ f"`FeedbackDataset` with name={self.dataset_name} in the workspace="
+ f"{self.workspace_name} had fields that are not supported yet for the"
+ f"`langchain` integration. Supported fields are: {supported_fields},"
+ f" and the current `FeedbackDataset` fields are {[field.name for field in self.dataset.fields]}." # noqa: E501
+ " For more information on how to create a `langchain`-compatible"
+ f" `FeedbackDataset` in Argilla, please visit {self.BLOG_URL}."
+ )
+
+ self.prompts: Dict[str, List[str]] = {}
+
+ warnings.warn(
+ (
+ "The `ArgillaCallbackHandler` is currently in beta and is subject to"
+ " change based on updates to `langchain`. Please report any issues to"
+ f" {self.ISSUES_URL} as an `integration` issue."
+ ),
+ )
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Save the prompts in memory when an LLM starts."""
+ self.prompts.update({str(kwargs["parent_run_id"] or kwargs["run_id"]): prompts})
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Do nothing when a new token is generated."""
+ pass
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Log records to Argilla when an LLM ends."""
+ # Do nothing if there's a parent_run_id, since we will log the records when
+ # the chain ends
+ if kwargs["parent_run_id"]:
+ return
+
+ # Creates the records and adds them to the `FeedbackDataset`
+ prompts = self.prompts[str(kwargs["run_id"])]
+ for prompt, generations in zip(prompts, response.generations):
+ self.dataset.add_records(
+ records=[
+ {
+ "fields": {
+ "prompt": prompt,
+ "response": generation.text.strip(),
+ },
+ }
+ for generation in generations
+ ]
+ )
+
+ # Pop current run from `self.runs`
+ self.prompts.pop(str(kwargs["run_id"]))
+
+ if parse(self.ARGILLA_VERSION) < parse("1.14.0"):
+ # Push the records to Argilla
+ self.dataset.push_to_argilla()
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when LLM outputs an error."""
+ pass
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """If the key `input` is in `inputs`, then save it in `self.prompts` using
+ either the `parent_run_id` or the `run_id` as the key. This is done so that
+ we don't log the same input prompt twice, once when the LLM starts and once
+ when the chain starts.
+ """
+ if "input" in inputs:
+ self.prompts.update(
+ {
+ str(kwargs["parent_run_id"] or kwargs["run_id"]): (
+ inputs["input"]
+ if isinstance(inputs["input"], list)
+ else [inputs["input"]]
+ )
+ }
+ )
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """If either the `parent_run_id` or the `run_id` is in `self.prompts`, then
+ log the outputs to Argilla, and pop the run from `self.prompts`. The behavior
+ differs if the output is a list or not.
+ """
+ if not any(
+ key in self.prompts
+ for key in [str(kwargs["parent_run_id"]), str(kwargs["run_id"])]
+ ):
+ return
+ prompts: List = self.prompts.get(str(kwargs["parent_run_id"])) or cast(
+ List, self.prompts.get(str(kwargs["run_id"]), [])
+ )
+ for chain_output_key, chain_output_val in outputs.items():
+ if isinstance(chain_output_val, list):
+ # Creates the records and adds them to the `FeedbackDataset`
+ self.dataset.add_records(
+ records=[
+ {
+ "fields": {
+ "prompt": prompt,
+ "response": output["text"].strip(),
+ },
+ }
+ for prompt, output in zip(prompts, chain_output_val)
+ ]
+ )
+ else:
+ # Creates the records and adds them to the `FeedbackDataset`
+ self.dataset.add_records(
+ records=[
+ {
+ "fields": {
+ "prompt": " ".join(prompts),
+ "response": chain_output_val.strip(),
+ },
+ }
+ ]
+ )
+
+ # Pop current run from `self.runs`
+ if str(kwargs["parent_run_id"]) in self.prompts:
+ self.prompts.pop(str(kwargs["parent_run_id"]))
+ if str(kwargs["run_id"]) in self.prompts:
+ self.prompts.pop(str(kwargs["run_id"]))
+
+ if parse(self.ARGILLA_VERSION) < parse("1.14.0"):
+ # Push the records to Argilla
+ self.dataset.push_to_argilla()
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when LLM chain outputs an error."""
+ pass
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing when tool starts."""
+ pass
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Do nothing when agent takes a specific action."""
+ pass
+
+ def on_tool_end(
+ self,
+ output: Any,
+ observation_prefix: Optional[str] = None,
+ llm_prefix: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing when tool ends."""
+ pass
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when tool outputs an error."""
+ pass
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """Do nothing"""
+ pass
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Do nothing"""
+ pass
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/arize_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/arize_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..45a6a39d66aaaab27fc7cf9c529d8e2c79d08220
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/arize_callback.py
@@ -0,0 +1,213 @@
+from datetime import datetime
+from typing import Any, Dict, List, Optional
+
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.outputs import LLMResult
+
+from langchain_community.callbacks.utils import import_pandas
+
+
+class ArizeCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that logs to Arize."""
+
+ def __init__(
+ self,
+ model_id: Optional[str] = None,
+ model_version: Optional[str] = None,
+ SPACE_KEY: Optional[str] = None,
+ API_KEY: Optional[str] = None,
+ ) -> None:
+ """Initialize callback handler."""
+
+ super().__init__()
+ self.model_id = model_id
+ self.model_version = model_version
+ self.space_key = SPACE_KEY
+ self.api_key = API_KEY
+ self.prompt_records: List[str] = []
+ self.response_records: List[str] = []
+ self.prediction_ids: List[str] = []
+ self.pred_timestamps: List[int] = []
+ self.response_embeddings: List[float] = []
+ self.prompt_embeddings: List[float] = []
+ self.prompt_tokens = 0
+ self.completion_tokens = 0
+ self.total_tokens = 0
+ self.step = 0
+
+ from arize.pandas.embeddings import EmbeddingGenerator, UseCases
+ from arize.pandas.logger import Client
+
+ self.generator = EmbeddingGenerator.from_use_case(
+ use_case=UseCases.NLP.SEQUENCE_CLASSIFICATION,
+ model_name="distilbert-base-uncased",
+ tokenizer_max_length=512,
+ batch_size=256,
+ )
+ self.arize_client = Client(space_key=SPACE_KEY, api_key=API_KEY)
+ if SPACE_KEY == "SPACE_KEY" or API_KEY == "API_KEY":
+ raise ValueError("❌ CHANGE SPACE AND API KEYS")
+ else:
+ print("✅ Arize client setup done! Now you can start using Arize!") # noqa: T201
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ for prompt in prompts:
+ self.prompt_records.append(prompt.replace("\n", ""))
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Do nothing."""
+ pass
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ pd = import_pandas()
+ from arize.utils.types import (
+ EmbeddingColumnNames,
+ Environments,
+ ModelTypes,
+ Schema,
+ )
+
+ # Safe check if 'llm_output' and 'token_usage' exist
+ if response.llm_output and "token_usage" in response.llm_output:
+ self.prompt_tokens = response.llm_output["token_usage"].get(
+ "prompt_tokens", 0
+ )
+ self.total_tokens = response.llm_output["token_usage"].get(
+ "total_tokens", 0
+ )
+ self.completion_tokens = response.llm_output["token_usage"].get(
+ "completion_tokens", 0
+ )
+ else:
+ self.prompt_tokens = self.total_tokens = self.completion_tokens = (
+ 0 # assign default value
+ )
+
+ for generations in response.generations:
+ for generation in generations:
+ prompt = self.prompt_records[self.step]
+ self.step = self.step + 1
+ prompt_embedding = pd.Series(
+ self.generator.generate_embeddings(
+ text_col=pd.Series(prompt.replace("\n", " "))
+ ).reset_index(drop=True)
+ )
+
+ # Assigning text to response_text instead of response
+ response_text = generation.text.replace("\n", " ")
+ response_embedding = pd.Series(
+ self.generator.generate_embeddings(
+ text_col=pd.Series(generation.text.replace("\n", " "))
+ ).reset_index(drop=True)
+ )
+ pred_timestamp = datetime.now().timestamp()
+
+ # Define the columns and data
+ columns = [
+ "prediction_ts",
+ "response",
+ "prompt",
+ "response_vector",
+ "prompt_vector",
+ "prompt_token",
+ "completion_token",
+ "total_token",
+ ]
+ data = [
+ [
+ pred_timestamp,
+ response_text,
+ prompt,
+ response_embedding[0],
+ prompt_embedding[0],
+ self.prompt_tokens,
+ self.total_tokens,
+ self.completion_tokens,
+ ]
+ ]
+
+ # Create the DataFrame
+ df = pd.DataFrame(data, columns=columns)
+
+ # Declare prompt and response columns
+ prompt_columns = EmbeddingColumnNames(
+ vector_column_name="prompt_vector", data_column_name="prompt"
+ )
+
+ response_columns = EmbeddingColumnNames(
+ vector_column_name="response_vector", data_column_name="response"
+ )
+
+ schema = Schema(
+ timestamp_column_name="prediction_ts",
+ tag_column_names=[
+ "prompt_token",
+ "completion_token",
+ "total_token",
+ ],
+ prompt_column_names=prompt_columns,
+ response_column_names=response_columns,
+ )
+
+ response_from_arize = self.arize_client.log(
+ dataframe=df,
+ schema=schema,
+ model_id=self.model_id,
+ model_version=self.model_version,
+ model_type=ModelTypes.GENERATIVE_LLM,
+ environment=Environments.PRODUCTION,
+ )
+ if response_from_arize.status_code == 200:
+ print("✅ Successfully logged data to Arize!") # noqa: T201
+ else:
+ print(f'❌ Logging failed "{response_from_arize.text}"') # noqa: T201
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing."""
+ pass
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ pass
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Do nothing."""
+ pass
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing."""
+ pass
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ **kwargs: Any,
+ ) -> None:
+ pass
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Do nothing."""
+ pass
+
+ def on_tool_end(
+ self,
+ output: Any,
+ observation_prefix: Optional[str] = None,
+ llm_prefix: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ pass
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ pass
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ pass
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ pass
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/arthur_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/arthur_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..6aa911fd739ebdd0bde3b4612aa598b26de58dc1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/arthur_callback.py
@@ -0,0 +1,297 @@
+"""ArthurAI's Callback Handler."""
+
+from __future__ import annotations
+
+import os
+import uuid
+from collections import defaultdict
+from datetime import datetime
+from time import time
+from typing import TYPE_CHECKING, Any, DefaultDict, Dict, List, Optional
+
+import numpy as np
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.outputs import LLMResult
+
+if TYPE_CHECKING:
+ import arthurai
+ from arthurai.core.models import ArthurModel
+
+PROMPT_TOKENS = "prompt_tokens"
+COMPLETION_TOKENS = "completion_tokens"
+TOKEN_USAGE = "token_usage"
+FINISH_REASON = "finish_reason"
+DURATION = "duration"
+
+
+def _lazy_load_arthur() -> arthurai:
+ """Lazy load Arthur."""
+ try:
+ import arthurai
+ except ImportError as e:
+ raise ImportError(
+ "To use the ArthurCallbackHandler you need the"
+ " `arthurai` package. Please install it with"
+ " `pip install arthurai`.",
+ e,
+ )
+
+ return arthurai
+
+
+class ArthurCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that logs to Arthur platform.
+
+ Arthur helps enterprise teams optimize model operations
+ and performance at scale. The Arthur API tracks model
+ performance, explainability, and fairness across tabular,
+ NLP, and CV models. Our API is model- and platform-agnostic,
+ and continuously scales with complex and dynamic enterprise needs.
+ To learn more about Arthur, visit our website at
+ https://www.arthur.ai/ or read the Arthur docs at
+ https://docs.arthur.ai/
+ """
+
+ def __init__(
+ self,
+ arthur_model: ArthurModel,
+ ) -> None:
+ """Initialize callback handler."""
+ super().__init__()
+ arthurai = _lazy_load_arthur()
+ Stage = arthurai.common.constants.Stage
+ ValueType = arthurai.common.constants.ValueType
+ self.arthur_model = arthur_model
+ # save the attributes of this model to be used when preparing
+ # inferences to log to Arthur in on_llm_end()
+ self.attr_names = set([a.name for a in self.arthur_model.get_attributes()])
+ self.input_attr = [
+ x
+ for x in self.arthur_model.get_attributes()
+ if x.stage == Stage.ModelPipelineInput
+ and x.value_type == ValueType.Unstructured_Text
+ ][0].name
+ self.output_attr = [
+ x
+ for x in self.arthur_model.get_attributes()
+ if x.stage == Stage.PredictedValue
+ and x.value_type == ValueType.Unstructured_Text
+ ][0].name
+ self.token_likelihood_attr = None
+ if (
+ len(
+ [
+ x
+ for x in self.arthur_model.get_attributes()
+ if x.value_type == ValueType.TokenLikelihoods
+ ]
+ )
+ > 0
+ ):
+ self.token_likelihood_attr = [
+ x
+ for x in self.arthur_model.get_attributes()
+ if x.value_type == ValueType.TokenLikelihoods
+ ][0].name
+
+ self.run_map: DefaultDict[str, Any] = defaultdict(dict)
+
+ @classmethod
+ def from_credentials(
+ cls,
+ model_id: str,
+ arthur_url: Optional[str] = "https://app.arthur.ai",
+ arthur_login: Optional[str] = None,
+ arthur_password: Optional[str] = None,
+ ) -> ArthurCallbackHandler:
+ """Initialize callback handler from Arthur credentials.
+
+ Args:
+ model_id (str): The ID of the arthur model to log to.
+ arthur_url (str, optional): The URL of the Arthur instance to log to.
+ Defaults to "https://app.arthur.ai".
+ arthur_login (str, optional): The login to use to connect to Arthur.
+ Defaults to None.
+ arthur_password (str, optional): The password to use to connect to
+ Arthur. Defaults to None.
+
+ Returns:
+ ArthurCallbackHandler: The initialized callback handler.
+ """
+ arthurai = _lazy_load_arthur()
+ ArthurAI = arthurai.ArthurAI
+ ResponseClientError = arthurai.common.exceptions.ResponseClientError
+
+ # connect to Arthur
+ if arthur_login is None:
+ try:
+ arthur_api_key = os.environ["ARTHUR_API_KEY"]
+ except KeyError:
+ raise ValueError(
+ "No Arthur authentication provided. Either give"
+ " a login to the ArthurCallbackHandler"
+ " or set an ARTHUR_API_KEY as an environment variable."
+ )
+ arthur = ArthurAI(url=arthur_url, access_key=arthur_api_key)
+ else:
+ if arthur_password is None:
+ arthur = ArthurAI(url=arthur_url, login=arthur_login)
+ else:
+ arthur = ArthurAI(
+ url=arthur_url, login=arthur_login, password=arthur_password
+ )
+ # get model from Arthur by the provided model ID
+ try:
+ arthur_model = arthur.get_model(model_id)
+ except ResponseClientError:
+ raise ValueError(
+ f"Was unable to retrieve model with id {model_id} from Arthur."
+ " Make sure the ID corresponds to a model that is currently"
+ " registered with your Arthur account."
+ )
+ return cls(arthur_model)
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """On LLM start, save the input prompts"""
+ run_id = kwargs["run_id"]
+ self.run_map[run_id]["input_texts"] = prompts
+ self.run_map[run_id]["start_time"] = time()
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """On LLM end, send data to Arthur."""
+ try:
+ import pytz
+ except ImportError as e:
+ raise ImportError(
+ "Could not import pytz. Please install it with 'pip install pytz'."
+ ) from e
+
+ run_id = kwargs["run_id"]
+
+ # get the run params from this run ID,
+ # or raise an error if this run ID has no corresponding metadata in self.run_map
+ try:
+ run_map_data = self.run_map[run_id]
+ except KeyError as e:
+ raise KeyError(
+ "This function has been called with a run_id"
+ " that was never registered in on_llm_start()."
+ " Restart and try running the LLM again"
+ ) from e
+
+ # mark the duration time between on_llm_start() and on_llm_end()
+ time_from_start_to_end = time() - run_map_data["start_time"]
+
+ # create inferences to log to Arthur
+ inferences = []
+ for i, generations in enumerate(response.generations):
+ for generation in generations:
+ inference = {
+ "partner_inference_id": str(uuid.uuid4()),
+ "inference_timestamp": datetime.now(tz=pytz.UTC),
+ self.input_attr: run_map_data["input_texts"][i],
+ self.output_attr: generation.text,
+ }
+
+ if generation.generation_info is not None:
+ # add finish reason to the inference
+ # if generation info contains a finish reason and
+ # if the ArthurModel was registered to monitor finish_reason
+ if (
+ FINISH_REASON in generation.generation_info
+ and FINISH_REASON in self.attr_names
+ ):
+ inference[FINISH_REASON] = generation.generation_info[
+ FINISH_REASON
+ ]
+
+ # add token likelihoods data to the inference if the ArthurModel
+ # was registered to monitor token likelihoods
+ logprobs_data = generation.generation_info["logprobs"]
+ if (
+ logprobs_data is not None
+ and self.token_likelihood_attr is not None
+ ):
+ logprobs = logprobs_data["top_logprobs"]
+ likelihoods = [
+ {k: np.exp(v) for k, v in logprobs[i].items()}
+ for i in range(len(logprobs))
+ ]
+ inference[self.token_likelihood_attr] = likelihoods
+
+ # add token usage counts to the inference if the
+ # ArthurModel was registered to monitor token usage
+ if (
+ isinstance(response.llm_output, dict)
+ and TOKEN_USAGE in response.llm_output
+ ):
+ token_usage = response.llm_output[TOKEN_USAGE]
+ if (
+ PROMPT_TOKENS in token_usage
+ and PROMPT_TOKENS in self.attr_names
+ ):
+ inference[PROMPT_TOKENS] = token_usage[PROMPT_TOKENS]
+ if (
+ COMPLETION_TOKENS in token_usage
+ and COMPLETION_TOKENS in self.attr_names
+ ):
+ inference[COMPLETION_TOKENS] = token_usage[COMPLETION_TOKENS]
+
+ # add inference duration to the inference if the ArthurModel
+ # was registered to monitor inference duration
+ if DURATION in self.attr_names:
+ inference[DURATION] = time_from_start_to_end
+
+ inferences.append(inference)
+
+ # send inferences to arthur
+ self.arthur_model.send_inferences(inferences)
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """On chain start, do nothing."""
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """On chain end, do nothing."""
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when LLM outputs an error."""
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """On new token, pass."""
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when LLM chain outputs an error."""
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing when tool starts."""
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Do nothing when agent takes a specific action."""
+
+ def on_tool_end(
+ self,
+ output: Any,
+ observation_prefix: Optional[str] = None,
+ llm_prefix: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing when tool ends."""
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when tool outputs an error."""
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """Do nothing"""
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Do nothing"""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/bedrock_anthropic_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/bedrock_anthropic_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..02b1d3ed4b686a9b15f422bf831b986a16cc04fb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/bedrock_anthropic_callback.py
@@ -0,0 +1,135 @@
+import threading
+from typing import Any, Dict, List, Union
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.outputs import LLMResult
+
+MODEL_COST_PER_1K_INPUT_TOKENS = {
+ "anthropic.claude-instant-v1": 0.0008,
+ "anthropic.claude-v2": 0.008,
+ "anthropic.claude-v2:1": 0.008,
+ "anthropic.claude-3-sonnet-20240229-v1:0": 0.003,
+ "anthropic.claude-3-5-sonnet-20240620-v1:0": 0.003,
+ "anthropic.claude-3-5-sonnet-20241022-v2:0": 0.003,
+ "anthropic.claude-3-7-sonnet-20250219-v1:0": 0.003,
+ "anthropic.claude-sonnet-4-20250514-v1:0": 0.003,
+ "anthropic.claude-3-haiku-20240307-v1:0": 0.00025,
+ "anthropic.claude-3-opus-20240229-v1:0": 0.015,
+ "anthropic.claude-opus-4-20250514-v1:0": 0.015,
+ "anthropic.claude-3-5-haiku-20241022-v1:0": 0.0008,
+}
+
+MODEL_COST_PER_1K_OUTPUT_TOKENS = {
+ "anthropic.claude-instant-v1": 0.0024,
+ "anthropic.claude-v2": 0.024,
+ "anthropic.claude-v2:1": 0.024,
+ "anthropic.claude-3-sonnet-20240229-v1:0": 0.015,
+ "anthropic.claude-3-5-sonnet-20240620-v1:0": 0.015,
+ "anthropic.claude-3-5-sonnet-20241022-v2:0": 0.015,
+ "anthropic.claude-3-7-sonnet-20250219-v1:0": 0.015,
+ "anthropic.claude-sonnet-4-20250514-v1:0": 0.015,
+ "anthropic.claude-3-haiku-20240307-v1:0": 0.00125,
+ "anthropic.claude-3-opus-20240229-v1:0": 0.075,
+ "anthropic.claude-opus-4-20250514-v1:0": 0.075,
+ "anthropic.claude-3-5-haiku-20241022-v1:0": 0.004,
+}
+
+
+def _get_anthropic_claude_token_cost(
+ prompt_tokens: int, completion_tokens: int, model_id: Union[str, None]
+) -> float:
+ if model_id:
+ # The model ID can be a cross-region (system-defined) inference profile ID,
+ # which has a prefix indicating the region (e.g., 'us', 'eu') but
+ # shares the same token costs as the "base model".
+ # By extracting the "base model ID", by taking the last two segments
+ # of the model ID, we can map cross-region inference profile IDs to
+ # their corresponding cost entries.
+ base_model_id = model_id.split(".")[-2] + "." + model_id.split(".")[-1]
+ else:
+ base_model_id = None
+ """Get the cost of tokens for the Claude model."""
+ if base_model_id not in MODEL_COST_PER_1K_INPUT_TOKENS:
+ raise ValueError(
+ f"Unknown model: {model_id}. Please provide a valid Anthropic model name."
+ "Known models are: " + ", ".join(MODEL_COST_PER_1K_INPUT_TOKENS.keys())
+ )
+ return (prompt_tokens / 1000) * MODEL_COST_PER_1K_INPUT_TOKENS[base_model_id] + (
+ completion_tokens / 1000
+ ) * MODEL_COST_PER_1K_OUTPUT_TOKENS[base_model_id]
+
+
+class BedrockAnthropicTokenUsageCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that tracks bedrock anthropic info."""
+
+ total_tokens: int = 0
+ prompt_tokens: int = 0
+ completion_tokens: int = 0
+ successful_requests: int = 0
+ total_cost: float = 0.0
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._lock = threading.Lock()
+
+ def __repr__(self) -> str:
+ return (
+ f"Tokens Used: {self.total_tokens}\n"
+ f"\tPrompt Tokens: {self.prompt_tokens}\n"
+ f"\tCompletion Tokens: {self.completion_tokens}\n"
+ f"Successful Requests: {self.successful_requests}\n"
+ f"Total Cost (USD): ${self.total_cost}"
+ )
+
+ @property
+ def always_verbose(self) -> bool:
+ """Whether to call verbose callbacks even if verbose is False."""
+ return True
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Print out the prompts."""
+ pass
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Print out the token."""
+ pass
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Collect token usage."""
+ if response.llm_output is None:
+ return None
+
+ if "usage" not in response.llm_output:
+ with self._lock:
+ self.successful_requests += 1
+ return None
+
+ # compute tokens and cost for this request
+ token_usage = response.llm_output["usage"]
+ completion_tokens = token_usage.get("completion_tokens", 0)
+ prompt_tokens = token_usage.get("prompt_tokens", 0)
+ total_tokens = token_usage.get("total_tokens", 0)
+ model_id = response.llm_output.get("model_id", None)
+ total_cost = _get_anthropic_claude_token_cost(
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ model_id=model_id,
+ )
+
+ # update shared state behind lock
+ with self._lock:
+ self.total_cost += total_cost
+ self.total_tokens += total_tokens
+ self.prompt_tokens += prompt_tokens
+ self.completion_tokens += completion_tokens
+ self.successful_requests += 1
+
+ def __copy__(self) -> "BedrockAnthropicTokenUsageCallbackHandler":
+ """Return a copy of the callback handler."""
+ return self
+
+ def __deepcopy__(self, memo: Any) -> "BedrockAnthropicTokenUsageCallbackHandler":
+ """Return a deep copy of the callback handler."""
+ return self
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/clearml_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/clearml_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..8149c1cd5cbb65a4e76bb22689c3de2c3fdc7dad
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/clearml_callback.py
@@ -0,0 +1,518 @@
+from __future__ import annotations
+
+import tempfile
+from copy import deepcopy
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence
+
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.outputs import LLMResult
+from langchain_core.utils import guard_import
+
+from langchain_community.callbacks.utils import (
+ BaseMetadataCallbackHandler,
+ flatten_dict,
+ hash_string,
+ import_pandas,
+ import_spacy,
+ import_textstat,
+ load_json,
+)
+
+if TYPE_CHECKING:
+ import pandas as pd
+
+
+def import_clearml() -> Any:
+ """Import the clearml python package and raise an error if it is not installed."""
+ return guard_import("clearml")
+
+
+class ClearMLCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
+ """Callback Handler that logs to ClearML.
+
+ Parameters:
+ job_type (str): The type of clearml task such as "inference", "testing" or "qc"
+ project_name (str): The clearml project name
+ tags (list): Tags to add to the task
+ task_name (str): Name of the clearml task
+ visualize (bool): Whether to visualize the run.
+ complexity_metrics (bool): Whether to log complexity metrics
+ stream_logs (bool): Whether to stream callback actions to ClearML
+
+ This handler will utilize the associated callback method and formats
+ the input of each callback function with metadata regarding the state of LLM run,
+ and adds the response to the list of records for both the {method}_records and
+ action. It then logs the response to the ClearML console.
+ """
+
+ def __init__(
+ self,
+ task_type: Optional[str] = "inference",
+ project_name: Optional[str] = "langchain_callback_demo",
+ tags: Optional[Sequence] = None,
+ task_name: Optional[str] = None,
+ visualize: bool = False,
+ complexity_metrics: bool = False,
+ stream_logs: bool = False,
+ ) -> None:
+ """Initialize callback handler."""
+
+ clearml = import_clearml()
+ spacy = import_spacy()
+ super().__init__()
+
+ self.task_type = task_type
+ self.project_name = project_name
+ self.tags = tags
+ self.task_name = task_name
+ self.visualize = visualize
+ self.complexity_metrics = complexity_metrics
+ self.stream_logs = stream_logs
+
+ self.temp_dir = tempfile.TemporaryDirectory()
+
+ # Check if ClearML task already exists (e.g. in pipeline)
+ if clearml.Task.current_task():
+ self.task = clearml.Task.current_task()
+ else:
+ self.task = clearml.Task.init(
+ task_type=self.task_type,
+ project_name=self.project_name,
+ tags=self.tags,
+ task_name=self.task_name,
+ output_uri=True,
+ )
+ self.logger = self.task.get_logger()
+ warning = (
+ "The clearml callback is currently in beta and is subject to change "
+ "based on updates to `langchain`. Please report any issues to "
+ "https://github.com/allegroai/clearml/issues with the tag `langchain`."
+ )
+ self.logger.report_text(warning, level=30, print_console=True)
+ self.callback_columns: list = []
+ self.action_records: list = []
+ self.complexity_metrics = complexity_metrics
+ self.visualize = visualize
+ self.nlp = spacy.load("en_core_web_sm")
+
+ def _init_resp(self) -> Dict:
+ return {k: None for k in self.callback_columns}
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Run when LLM starts."""
+ self.step += 1
+ self.llm_starts += 1
+ self.starts += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_llm_start"})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.get_custom_callback_meta())
+
+ for prompt in prompts:
+ prompt_resp = deepcopy(resp)
+ prompt_resp["prompts"] = prompt
+ self.on_llm_start_records.append(prompt_resp)
+ self.action_records.append(prompt_resp)
+ if self.stream_logs:
+ self.logger.report_text(prompt_resp)
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Run when LLM generates a new token."""
+ self.step += 1
+ self.llm_streams += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_llm_new_token", "token": token})
+ resp.update(self.get_custom_callback_meta())
+
+ self.on_llm_token_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.logger.report_text(resp)
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running."""
+ self.step += 1
+ self.llm_ends += 1
+ self.ends += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_llm_end"})
+ resp.update(flatten_dict(response.llm_output or {}))
+ resp.update(self.get_custom_callback_meta())
+
+ for generations in response.generations:
+ for generation in generations:
+ generation_resp = deepcopy(resp)
+ generation_resp.update(flatten_dict(generation.dict()))
+ generation_resp.update(self.analyze_text(generation.text))
+ self.on_llm_end_records.append(generation_resp)
+ self.action_records.append(generation_resp)
+ if self.stream_logs:
+ self.logger.report_text(generation_resp)
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when LLM errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Run when chain starts running."""
+ self.step += 1
+ self.chain_starts += 1
+ self.starts += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_chain_start"})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.get_custom_callback_meta())
+
+ chain_input = inputs.get("input", inputs.get("human_input"))
+
+ if isinstance(chain_input, str):
+ input_resp = deepcopy(resp)
+ input_resp["input"] = chain_input
+ self.on_chain_start_records.append(input_resp)
+ self.action_records.append(input_resp)
+ if self.stream_logs:
+ self.logger.report_text(input_resp)
+ elif isinstance(chain_input, list):
+ for inp in chain_input:
+ input_resp = deepcopy(resp)
+ input_resp.update(inp)
+ self.on_chain_start_records.append(input_resp)
+ self.action_records.append(input_resp)
+ if self.stream_logs:
+ self.logger.report_text(input_resp)
+ else:
+ raise ValueError("Unexpected data format provided!")
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Run when chain ends running."""
+ self.step += 1
+ self.chain_ends += 1
+ self.ends += 1
+
+ resp = self._init_resp()
+ resp.update(
+ {
+ "action": "on_chain_end",
+ "outputs": outputs.get("output", outputs.get("text")),
+ }
+ )
+ resp.update(self.get_custom_callback_meta())
+
+ self.on_chain_end_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.logger.report_text(resp)
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when chain errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_tool_start(
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
+ ) -> None:
+ """Run when tool starts running."""
+ self.step += 1
+ self.tool_starts += 1
+ self.starts += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_tool_start", "input_str": input_str})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.get_custom_callback_meta())
+
+ self.on_tool_start_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.logger.report_text(resp)
+
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
+ """Run when tool ends running."""
+ output = str(output)
+ self.step += 1
+ self.tool_ends += 1
+ self.ends += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_tool_end", "output": output})
+ resp.update(self.get_custom_callback_meta())
+
+ self.on_tool_end_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.logger.report_text(resp)
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when tool errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """
+ Run when agent is ending.
+ """
+ self.step += 1
+ self.text_ctr += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_text", "text": text})
+ resp.update(self.get_custom_callback_meta())
+
+ self.on_text_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.logger.report_text(resp)
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run when agent ends running."""
+ self.step += 1
+ self.agent_ends += 1
+ self.ends += 1
+
+ resp = self._init_resp()
+ resp.update(
+ {
+ "action": "on_agent_finish",
+ "output": finish.return_values["output"],
+ "log": finish.log,
+ }
+ )
+ resp.update(self.get_custom_callback_meta())
+
+ self.on_agent_finish_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.logger.report_text(resp)
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Run on agent action."""
+ self.step += 1
+ self.tool_starts += 1
+ self.starts += 1
+
+ resp = self._init_resp()
+ resp.update(
+ {
+ "action": "on_agent_action",
+ "tool": action.tool,
+ "tool_input": action.tool_input,
+ "log": action.log,
+ }
+ )
+ resp.update(self.get_custom_callback_meta())
+ self.on_agent_action_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.logger.report_text(resp)
+
+ def analyze_text(self, text: str) -> dict:
+ """Analyze text using textstat and spacy.
+
+ Parameters:
+ text (str): The text to analyze.
+
+ Returns:
+ `dict` containing the complexity metrics.
+ """
+ resp = {}
+ textstat = import_textstat()
+ spacy = import_spacy()
+ if self.complexity_metrics:
+ text_complexity_metrics = {
+ "flesch_reading_ease": textstat.flesch_reading_ease(text),
+ "flesch_kincaid_grade": textstat.flesch_kincaid_grade(text),
+ "smog_index": textstat.smog_index(text),
+ "coleman_liau_index": textstat.coleman_liau_index(text),
+ "automated_readability_index": textstat.automated_readability_index(
+ text
+ ),
+ "dale_chall_readability_score": textstat.dale_chall_readability_score(
+ text
+ ),
+ "difficult_words": textstat.difficult_words(text),
+ "linsear_write_formula": textstat.linsear_write_formula(text),
+ "gunning_fog": textstat.gunning_fog(text),
+ "text_standard": textstat.text_standard(text),
+ "fernandez_huerta": textstat.fernandez_huerta(text),
+ "szigriszt_pazos": textstat.szigriszt_pazos(text),
+ "gutierrez_polini": textstat.gutierrez_polini(text),
+ "crawford": textstat.crawford(text),
+ "gulpease_index": textstat.gulpease_index(text),
+ "osman": textstat.osman(text),
+ }
+ resp.update(text_complexity_metrics)
+
+ if self.visualize and self.nlp and self.temp_dir.name is not None:
+ doc = self.nlp(text)
+
+ dep_out = spacy.displacy.render(doc, style="dep", jupyter=False, page=True)
+ dep_output_path = Path(
+ self.temp_dir.name, hash_string(f"dep-{text}") + ".html"
+ )
+ dep_output_path.open("w", encoding="utf-8").write(dep_out)
+
+ ent_out = spacy.displacy.render(doc, style="ent", jupyter=False, page=True)
+ ent_output_path = Path(
+ self.temp_dir.name, hash_string(f"ent-{text}") + ".html"
+ )
+ ent_output_path.open("w", encoding="utf-8").write(ent_out)
+
+ self.logger.report_media(
+ "Dependencies Plot", text, local_path=dep_output_path
+ )
+ self.logger.report_media("Entities Plot", text, local_path=ent_output_path)
+
+ return resp
+
+ @staticmethod
+ def _build_llm_df(
+ base_df: pd.DataFrame, base_df_fields: Sequence, rename_map: Mapping
+ ) -> pd.DataFrame:
+ base_df_fields = [field for field in base_df_fields if field in base_df]
+ rename_map = {
+ map_entry_k: map_entry_v
+ for map_entry_k, map_entry_v in rename_map.items()
+ if map_entry_k in base_df_fields
+ }
+ llm_df = base_df[base_df_fields].dropna(axis=1)
+ if rename_map:
+ llm_df = llm_df.rename(rename_map, axis=1)
+ return llm_df
+
+ def _create_session_analysis_df(self) -> Any:
+ """Create a dataframe with all the information from the session."""
+ pd = import_pandas()
+ on_llm_end_records_df = pd.DataFrame(self.on_llm_end_records)
+
+ llm_input_prompts_df = ClearMLCallbackHandler._build_llm_df(
+ base_df=on_llm_end_records_df,
+ base_df_fields=["step", "prompts"]
+ + (["name"] if "name" in on_llm_end_records_df else ["id"]),
+ rename_map={"step": "prompt_step"},
+ )
+ complexity_metrics_columns = []
+ visualizations_columns: List = []
+
+ if self.complexity_metrics:
+ complexity_metrics_columns = [
+ "flesch_reading_ease",
+ "flesch_kincaid_grade",
+ "smog_index",
+ "coleman_liau_index",
+ "automated_readability_index",
+ "dale_chall_readability_score",
+ "difficult_words",
+ "linsear_write_formula",
+ "gunning_fog",
+ "text_standard",
+ "fernandez_huerta",
+ "szigriszt_pazos",
+ "gutierrez_polini",
+ "crawford",
+ "gulpease_index",
+ "osman",
+ ]
+
+ llm_outputs_df = ClearMLCallbackHandler._build_llm_df(
+ on_llm_end_records_df,
+ [
+ "step",
+ "text",
+ "token_usage_total_tokens",
+ "token_usage_prompt_tokens",
+ "token_usage_completion_tokens",
+ ]
+ + complexity_metrics_columns
+ + visualizations_columns,
+ {"step": "output_step", "text": "output"},
+ )
+ session_analysis_df = pd.concat([llm_input_prompts_df, llm_outputs_df], axis=1)
+ return session_analysis_df
+
+ def flush_tracker(
+ self,
+ name: Optional[str] = None,
+ langchain_asset: Any = None,
+ finish: bool = False,
+ ) -> None:
+ """Flush the tracker and setup the session.
+
+ Everything after this will be a new table.
+
+ Args:
+ name: Name of the performed session so far so it is identifiable
+ langchain_asset: The langchain asset to save.
+ finish: Whether to finish the run.
+
+ Returns:
+ None
+ """
+ pd = import_pandas()
+ clearml = import_clearml()
+
+ # Log the action records
+ self.logger.report_table(
+ "Action Records", name, table_plot=pd.DataFrame(self.action_records)
+ )
+
+ # Session analysis
+ session_analysis_df = self._create_session_analysis_df()
+ self.logger.report_table(
+ "Session Analysis", name, table_plot=session_analysis_df
+ )
+
+ if self.stream_logs:
+ self.logger.report_text(
+ {
+ "action_records": pd.DataFrame(self.action_records),
+ "session_analysis": session_analysis_df,
+ }
+ )
+
+ if langchain_asset:
+ langchain_asset_path = Path(self.temp_dir.name, "model.json")
+ try:
+ langchain_asset.save(langchain_asset_path)
+ # Create output model and connect it to the task
+ output_model = clearml.OutputModel(
+ task=self.task, config_text=load_json(langchain_asset_path)
+ )
+ output_model.update_weights(
+ weights_filename=str(langchain_asset_path),
+ auto_delete_file=False,
+ target_filename=name,
+ )
+ except ValueError:
+ langchain_asset.save_agent(langchain_asset_path)
+ output_model = clearml.OutputModel(
+ task=self.task, config_text=load_json(langchain_asset_path)
+ )
+ output_model.update_weights(
+ weights_filename=str(langchain_asset_path),
+ auto_delete_file=False,
+ target_filename=name,
+ )
+ except NotImplementedError as e:
+ print("Could not save model.") # noqa: T201
+ print(repr(e)) # noqa: T201
+ pass
+
+ # Cleanup after adding everything to ClearML
+ self.task.flush(wait_for_uploads=True)
+ self.temp_dir.cleanup()
+ self.temp_dir = tempfile.TemporaryDirectory()
+ self.reset_callback_meta()
+
+ if finish:
+ self.task.close()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/comet_ml_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/comet_ml_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d682c9a05f898bb757b44cb75fcfe37500efb64
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/comet_ml_callback.py
@@ -0,0 +1,639 @@
+import tempfile
+from copy import deepcopy
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Optional, Sequence
+
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.outputs import Generation, LLMResult
+from langchain_core.utils import guard_import
+
+import langchain_community
+from langchain_community.callbacks.utils import (
+ BaseMetadataCallbackHandler,
+ flatten_dict,
+ import_pandas,
+ import_spacy,
+ import_textstat,
+)
+
+LANGCHAIN_MODEL_NAME = "langchain-model"
+
+
+def import_comet_ml() -> Any:
+ """Import comet_ml and raise an error if it is not installed."""
+ return guard_import("comet_ml")
+
+
+def _get_experiment(
+ workspace: Optional[str] = None, project_name: Optional[str] = None
+) -> Any:
+ comet_ml = import_comet_ml()
+
+ experiment = comet_ml.Experiment(
+ workspace=workspace,
+ project_name=project_name,
+ )
+
+ return experiment
+
+
+def _fetch_text_complexity_metrics(text: str) -> dict:
+ textstat = import_textstat()
+ text_complexity_metrics = {
+ "flesch_reading_ease": textstat.flesch_reading_ease(text),
+ "flesch_kincaid_grade": textstat.flesch_kincaid_grade(text),
+ "smog_index": textstat.smog_index(text),
+ "coleman_liau_index": textstat.coleman_liau_index(text),
+ "automated_readability_index": textstat.automated_readability_index(text),
+ "dale_chall_readability_score": textstat.dale_chall_readability_score(text),
+ "difficult_words": textstat.difficult_words(text),
+ "linsear_write_formula": textstat.linsear_write_formula(text),
+ "gunning_fog": textstat.gunning_fog(text),
+ "text_standard": textstat.text_standard(text),
+ "fernandez_huerta": textstat.fernandez_huerta(text),
+ "szigriszt_pazos": textstat.szigriszt_pazos(text),
+ "gutierrez_polini": textstat.gutierrez_polini(text),
+ "crawford": textstat.crawford(text),
+ "gulpease_index": textstat.gulpease_index(text),
+ "osman": textstat.osman(text),
+ }
+ return text_complexity_metrics
+
+
+def _summarize_metrics_for_generated_outputs(metrics: Sequence) -> dict:
+ pd = import_pandas()
+ metrics_df = pd.DataFrame(metrics)
+ metrics_summary = metrics_df.describe()
+
+ return metrics_summary.to_dict()
+
+
+class CometCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
+ """Callback Handler that logs to Comet.
+
+ Parameters:
+ job_type (str): The type of comet_ml task such as "inference",
+ "testing" or "qc"
+ project_name (str): The comet_ml project name
+ tags (list): Tags to add to the task
+ task_name (str): Name of the comet_ml task
+ visualize (bool): Whether to visualize the run.
+ complexity_metrics (bool): Whether to log complexity metrics
+ stream_logs (bool): Whether to stream callback actions to Comet
+
+ This handler will utilize the associated callback method and formats
+ the input of each callback function with metadata regarding the state of LLM run,
+ and adds the response to the list of records for both the {method}_records and
+ action. It then logs the response to Comet.
+ """
+
+ def __init__(
+ self,
+ task_type: Optional[str] = "inference",
+ workspace: Optional[str] = None,
+ project_name: Optional[str] = None,
+ tags: Optional[Sequence] = None,
+ name: Optional[str] = None,
+ visualizations: Optional[List[str]] = None,
+ complexity_metrics: bool = False,
+ custom_metrics: Optional[Callable] = None,
+ stream_logs: bool = True,
+ ) -> None:
+ """Initialize callback handler."""
+
+ self.comet_ml = import_comet_ml()
+ super().__init__()
+
+ self.task_type = task_type
+ self.workspace = workspace
+ self.project_name = project_name
+ self.tags = tags
+ self.visualizations = visualizations
+ self.complexity_metrics = complexity_metrics
+ self.custom_metrics = custom_metrics
+ self.stream_logs = stream_logs
+ self.temp_dir = tempfile.TemporaryDirectory()
+
+ self.experiment = _get_experiment(workspace, project_name)
+ self.experiment.log_other("Created from", "langchain")
+ if tags:
+ self.experiment.add_tags(tags)
+ self.name = name
+ if self.name:
+ self.experiment.set_name(self.name)
+
+ warning = (
+ "The comet_ml callback is currently in beta and is subject to change "
+ "based on updates to `langchain`. Please report any issues to "
+ "https://github.com/comet-ml/issue-tracking/issues with the tag "
+ "`langchain`."
+ )
+ self.comet_ml.LOGGER.warning(warning)
+
+ self.callback_columns: list = []
+ self.action_records: list = []
+ self.complexity_metrics = complexity_metrics
+ if self.visualizations:
+ spacy = import_spacy()
+ self.nlp = spacy.load("en_core_web_sm")
+ else:
+ self.nlp = None
+
+ def _init_resp(self) -> Dict:
+ return {k: None for k in self.callback_columns}
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Run when LLM starts."""
+ self.step += 1
+ self.llm_starts += 1
+ self.starts += 1
+
+ metadata = self._init_resp()
+ metadata.update({"action": "on_llm_start"})
+ metadata.update(flatten_dict(serialized))
+ metadata.update(self.get_custom_callback_meta())
+
+ for prompt in prompts:
+ prompt_resp = deepcopy(metadata)
+ prompt_resp["prompts"] = prompt
+ self.on_llm_start_records.append(prompt_resp)
+ self.action_records.append(prompt_resp)
+
+ if self.stream_logs:
+ self._log_stream(prompt, metadata, self.step)
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Run when LLM generates a new token."""
+ self.step += 1
+ self.llm_streams += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_llm_new_token", "token": token})
+ resp.update(self.get_custom_callback_meta())
+
+ self.action_records.append(resp)
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running."""
+ self.step += 1
+ self.llm_ends += 1
+ self.ends += 1
+
+ metadata = self._init_resp()
+ metadata.update({"action": "on_llm_end"})
+ metadata.update(flatten_dict(response.llm_output or {}))
+ metadata.update(self.get_custom_callback_meta())
+
+ output_complexity_metrics = []
+ output_custom_metrics = []
+
+ for prompt_idx, generations in enumerate(response.generations):
+ for gen_idx, generation in enumerate(generations):
+ text = generation.text
+
+ generation_resp = deepcopy(metadata)
+ generation_resp.update(flatten_dict(generation.dict()))
+
+ complexity_metrics = self._get_complexity_metrics(text)
+ if complexity_metrics:
+ output_complexity_metrics.append(complexity_metrics)
+ generation_resp.update(complexity_metrics)
+
+ custom_metrics = self._get_custom_metrics(
+ generation, prompt_idx, gen_idx
+ )
+ if custom_metrics:
+ output_custom_metrics.append(custom_metrics)
+ generation_resp.update(custom_metrics)
+
+ if self.stream_logs:
+ self._log_stream(text, metadata, self.step)
+
+ self.action_records.append(generation_resp)
+ self.on_llm_end_records.append(generation_resp)
+
+ self._log_text_metrics(output_complexity_metrics, step=self.step)
+ self._log_text_metrics(output_custom_metrics, step=self.step)
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when LLM errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Run when chain starts running."""
+ self.step += 1
+ self.chain_starts += 1
+ self.starts += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_chain_start"})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.get_custom_callback_meta())
+
+ for chain_input_key, chain_input_val in inputs.items():
+ if isinstance(chain_input_val, str):
+ input_resp = deepcopy(resp)
+ if self.stream_logs:
+ self._log_stream(chain_input_val, resp, self.step)
+ input_resp.update({chain_input_key: chain_input_val})
+ self.action_records.append(input_resp)
+
+ else:
+ self.comet_ml.LOGGER.warning(
+ f"Unexpected data format provided! "
+ f"Input Value for {chain_input_key} will not be logged"
+ )
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Run when chain ends running."""
+ self.step += 1
+ self.chain_ends += 1
+ self.ends += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_chain_end"})
+ resp.update(self.get_custom_callback_meta())
+
+ for chain_output_key, chain_output_val in outputs.items():
+ if isinstance(chain_output_val, str):
+ output_resp = deepcopy(resp)
+ if self.stream_logs:
+ self._log_stream(chain_output_val, resp, self.step)
+ output_resp.update({chain_output_key: chain_output_val})
+ self.action_records.append(output_resp)
+ else:
+ self.comet_ml.LOGGER.warning(
+ f"Unexpected data format provided! "
+ f"Output Value for {chain_output_key} will not be logged"
+ )
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when chain errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_tool_start(
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
+ ) -> None:
+ """Run when tool starts running."""
+ self.step += 1
+ self.tool_starts += 1
+ self.starts += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_tool_start"})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.get_custom_callback_meta())
+ if self.stream_logs:
+ self._log_stream(input_str, resp, self.step)
+
+ resp.update({"input_str": input_str})
+ self.action_records.append(resp)
+
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
+ """Run when tool ends running."""
+ output = str(output)
+ self.step += 1
+ self.tool_ends += 1
+ self.ends += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_tool_end"})
+ resp.update(self.get_custom_callback_meta())
+ if self.stream_logs:
+ self._log_stream(output, resp, self.step)
+
+ resp.update({"output": output})
+ self.action_records.append(resp)
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when tool errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """
+ Run when agent is ending.
+ """
+ self.step += 1
+ self.text_ctr += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_text"})
+ resp.update(self.get_custom_callback_meta())
+ if self.stream_logs:
+ self._log_stream(text, resp, self.step)
+
+ resp.update({"text": text})
+ self.action_records.append(resp)
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run when agent ends running."""
+ self.step += 1
+ self.agent_ends += 1
+ self.ends += 1
+
+ resp = self._init_resp()
+ output = finish.return_values["output"]
+ log = finish.log
+
+ resp.update({"action": "on_agent_finish", "log": log})
+ resp.update(self.get_custom_callback_meta())
+ if self.stream_logs:
+ self._log_stream(output, resp, self.step)
+
+ resp.update({"output": output})
+ self.action_records.append(resp)
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Run on agent action."""
+ self.step += 1
+ self.tool_starts += 1
+ self.starts += 1
+
+ tool = action.tool
+ tool_input = str(action.tool_input)
+ log = action.log
+
+ resp = self._init_resp()
+ resp.update({"action": "on_agent_action", "log": log, "tool": tool})
+ resp.update(self.get_custom_callback_meta())
+ if self.stream_logs:
+ self._log_stream(tool_input, resp, self.step)
+
+ resp.update({"tool_input": tool_input})
+ self.action_records.append(resp)
+
+ def _get_complexity_metrics(self, text: str) -> dict:
+ """Compute text complexity metrics using textstat.
+
+ Parameters:
+ text (str): The text to analyze.
+
+ Returns:
+ `dict` containing the complexity metrics.
+ """
+ resp = {}
+ if self.complexity_metrics:
+ text_complexity_metrics = _fetch_text_complexity_metrics(text)
+ resp.update(text_complexity_metrics)
+
+ return resp
+
+ def _get_custom_metrics(
+ self, generation: Generation, prompt_idx: int, gen_idx: int
+ ) -> dict:
+ """Compute Custom Metrics for an LLM Generated Output
+
+ Args:
+ generation (LLMResult): Output generation from an LLM
+ prompt_idx (int): List index of the input prompt
+ gen_idx (int): List index of the generated output
+
+ Returns:
+ dict: `dict` containing the custom metrics.
+ """
+
+ resp = {}
+ if self.custom_metrics:
+ custom_metrics = self.custom_metrics(generation, prompt_idx, gen_idx)
+ resp.update(custom_metrics)
+
+ return resp
+
+ def flush_tracker(
+ self,
+ langchain_asset: Any = None,
+ task_type: Optional[str] = "inference",
+ workspace: Optional[str] = None,
+ project_name: Optional[str] = "comet-langchain-demo",
+ tags: Optional[Sequence] = None,
+ name: Optional[str] = None,
+ visualizations: Optional[List[str]] = None,
+ complexity_metrics: bool = False,
+ custom_metrics: Optional[Callable] = None,
+ finish: bool = False,
+ reset: bool = False,
+ ) -> None:
+ """Flush the tracker and setup the session.
+
+ Everything after this will be a new table.
+
+ Args:
+ name: Name of the performed session so far so it is identifiable
+ langchain_asset: The langchain asset to save.
+ finish: Whether to finish the run.
+
+ Returns:
+ None
+ """
+ self._log_session(langchain_asset)
+
+ if langchain_asset:
+ try:
+ self._log_model(langchain_asset)
+ except Exception:
+ self.comet_ml.LOGGER.error(
+ "Failed to export agent or LLM to Comet",
+ exc_info=True,
+ extra={"show_traceback": True},
+ )
+
+ if finish:
+ self.experiment.end()
+
+ if reset:
+ self._reset(
+ task_type,
+ workspace,
+ project_name,
+ tags,
+ name,
+ visualizations,
+ complexity_metrics,
+ custom_metrics,
+ )
+
+ def _log_stream(self, prompt: str, metadata: dict, step: int) -> None:
+ self.experiment.log_text(prompt, metadata=metadata, step=step)
+
+ def _log_model(self, langchain_asset: Any) -> None:
+ model_parameters = self._get_llm_parameters(langchain_asset)
+ self.experiment.log_parameters(model_parameters, prefix="model")
+
+ langchain_asset_path = Path(self.temp_dir.name, "model.json")
+ model_name = self.name if self.name else LANGCHAIN_MODEL_NAME
+
+ try:
+ if hasattr(langchain_asset, "save"):
+ langchain_asset.save(langchain_asset_path)
+ self.experiment.log_model(model_name, str(langchain_asset_path))
+ except (ValueError, AttributeError, NotImplementedError) as e:
+ if hasattr(langchain_asset, "save_agent"):
+ langchain_asset.save_agent(langchain_asset_path)
+ self.experiment.log_model(model_name, str(langchain_asset_path))
+ else:
+ self.comet_ml.LOGGER.error(
+ f"{e}"
+ " Could not save Langchain Asset "
+ f"for {langchain_asset.__class__.__name__}"
+ )
+
+ def _log_session(self, langchain_asset: Optional[Any] = None) -> None:
+ try:
+ llm_session_df = self._create_session_analysis_dataframe(langchain_asset)
+ # Log the cleaned dataframe as a table
+ self.experiment.log_table("langchain-llm-session.csv", llm_session_df)
+ except Exception:
+ self.comet_ml.LOGGER.warning(
+ "Failed to log session data to Comet",
+ exc_info=True,
+ extra={"show_traceback": True},
+ )
+
+ try:
+ metadata = {"langchain_version": str(langchain_community.__version__)}
+ # Log the langchain low-level records as a JSON file directly
+ self.experiment.log_asset_data(
+ self.action_records, "langchain-action_records.json", metadata=metadata
+ )
+ except Exception:
+ self.comet_ml.LOGGER.warning(
+ "Failed to log session data to Comet",
+ exc_info=True,
+ extra={"show_traceback": True},
+ )
+
+ try:
+ self._log_visualizations(llm_session_df)
+ except Exception:
+ self.comet_ml.LOGGER.warning(
+ "Failed to log visualizations to Comet",
+ exc_info=True,
+ extra={"show_traceback": True},
+ )
+
+ def _log_text_metrics(self, metrics: Sequence[dict], step: int) -> None:
+ if not metrics:
+ return
+
+ metrics_summary = _summarize_metrics_for_generated_outputs(metrics)
+ for key, value in metrics_summary.items():
+ self.experiment.log_metrics(value, prefix=key, step=step)
+
+ def _log_visualizations(self, session_df: Any) -> None:
+ if not (self.visualizations and self.nlp):
+ return
+
+ spacy = import_spacy()
+
+ prompts = session_df["prompts"].tolist()
+ outputs = session_df["text"].tolist()
+
+ for idx, (prompt, output) in enumerate(zip(prompts, outputs)):
+ doc = self.nlp(output)
+ sentence_spans = list(doc.sents)
+
+ for visualization in self.visualizations:
+ try:
+ html = spacy.displacy.render(
+ sentence_spans,
+ style=visualization,
+ options={"compact": True},
+ jupyter=False,
+ page=True,
+ )
+ self.experiment.log_asset_data(
+ html,
+ name=f"langchain-viz-{visualization}-{idx}.html",
+ metadata={"prompt": prompt},
+ step=idx,
+ )
+ except Exception as e:
+ self.comet_ml.LOGGER.warning(
+ e, exc_info=True, extra={"show_traceback": True}
+ )
+
+ return
+
+ def _reset(
+ self,
+ task_type: Optional[str] = None,
+ workspace: Optional[str] = None,
+ project_name: Optional[str] = None,
+ tags: Optional[Sequence] = None,
+ name: Optional[str] = None,
+ visualizations: Optional[List[str]] = None,
+ complexity_metrics: bool = False,
+ custom_metrics: Optional[Callable] = None,
+ ) -> None:
+ _task_type = task_type if task_type else self.task_type
+ _workspace = workspace if workspace else self.workspace
+ _project_name = project_name if project_name else self.project_name
+ _tags = tags if tags else self.tags
+ _name = name if name else self.name
+ _visualizations = visualizations if visualizations else self.visualizations
+ _complexity_metrics = (
+ complexity_metrics if complexity_metrics else self.complexity_metrics
+ )
+ _custom_metrics = custom_metrics if custom_metrics else self.custom_metrics
+
+ self.__init__( # type: ignore[misc]
+ task_type=_task_type,
+ workspace=_workspace,
+ project_name=_project_name,
+ tags=_tags,
+ name=_name,
+ visualizations=_visualizations,
+ complexity_metrics=_complexity_metrics,
+ custom_metrics=_custom_metrics,
+ )
+
+ self.reset_callback_meta()
+ self.temp_dir = tempfile.TemporaryDirectory()
+
+ def _create_session_analysis_dataframe(self, langchain_asset: Any = None) -> dict:
+ pd = import_pandas()
+
+ llm_parameters = self._get_llm_parameters(langchain_asset)
+ num_generations_per_prompt = llm_parameters.get("n", 1)
+
+ llm_start_records_df = pd.DataFrame(self.on_llm_start_records)
+ # Repeat each input row based on the number of outputs generated per prompt
+ llm_start_records_df = llm_start_records_df.loc[
+ llm_start_records_df.index.repeat(num_generations_per_prompt)
+ ].reset_index(drop=True)
+ llm_end_records_df = pd.DataFrame(self.on_llm_end_records)
+
+ llm_session_df = pd.merge(
+ llm_start_records_df,
+ llm_end_records_df,
+ left_index=True,
+ right_index=True,
+ suffixes=["_llm_start", "_llm_end"],
+ )
+
+ return llm_session_df
+
+ def _get_llm_parameters(self, langchain_asset: Any = None) -> dict:
+ if not langchain_asset:
+ return {}
+ try:
+ if hasattr(langchain_asset, "agent"):
+ llm_parameters = langchain_asset.agent.llm_chain.llm.dict()
+ elif hasattr(langchain_asset, "llm_chain"):
+ llm_parameters = langchain_asset.llm_chain.llm.dict()
+ elif hasattr(langchain_asset, "llm"):
+ llm_parameters = langchain_asset.llm.dict()
+ else:
+ llm_parameters = langchain_asset.dict()
+ except Exception:
+ return {}
+
+ return llm_parameters
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/confident_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/confident_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..b078abf45074c3912625389d374ae325fa0c68d0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/confident_callback.py
@@ -0,0 +1,183 @@
+# flake8: noqa
+import os
+import warnings
+from typing import Any, Dict, List, Optional, Union
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.outputs import LLMResult
+
+
+class DeepEvalCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that logs into deepeval.
+
+ Args:
+ implementation_name: name of the `implementation` in deepeval
+ metrics: A list of metrics
+
+ Raises:
+ ImportError: if the `deepeval` package is not installed.
+
+ Examples:
+ >>> from langchain_community.llms import OpenAI
+ >>> from langchain_community.callbacks import DeepEvalCallbackHandler
+ >>> from deepeval.metrics import AnswerRelevancy
+ >>> metric = AnswerRelevancy(minimum_score=0.3)
+ >>> deepeval_callback = DeepEvalCallbackHandler(
+ ... implementation_name="exampleImplementation",
+ ... metrics=[metric],
+ ... )
+ >>> llm = OpenAI(
+ ... temperature=0,
+ ... callbacks=[deepeval_callback],
+ ... verbose=True,
+ ... openai_api_key="API_KEY_HERE",
+ ... )
+ >>> llm.generate([
+ ... "What is the best evaluation tool out there? (no bias at all)",
+ ... ])
+ "Deepeval, no doubt about it."
+ """
+
+ REPO_URL: str = "https://github.com/confident-ai/deepeval"
+ ISSUES_URL: str = f"{REPO_URL}/issues"
+ BLOG_URL: str = "https://docs.confident-ai.com" # noqa: E501
+
+ def __init__(
+ self,
+ metrics: List[Any],
+ implementation_name: Optional[str] = None,
+ ) -> None:
+ """Initializes the `deepevalCallbackHandler`.
+
+ Args:
+ implementation_name: Name of the implementation you want.
+ metrics: What metrics do you want to track?
+
+ Raises:
+ ImportError: if the `deepeval` package is not installed.
+ ConnectionError: if the connection to deepeval fails.
+ """
+
+ super().__init__()
+
+ # Import deepeval (not via `import_deepeval` to keep hints in IDEs)
+ try:
+ import deepeval # ignore: F401,I001
+ except ImportError:
+ raise ImportError(
+ """To use the deepeval callback manager you need to have the
+ `deepeval` Python package installed. Please install it with
+ `pip install deepeval`"""
+ )
+
+ if os.path.exists(".deepeval"):
+ warnings.warn(
+ """You are currently not logging anything to the dashboard, we
+ recommend using `deepeval login`."""
+ )
+
+ # Set the deepeval variables
+ self.implementation_name = implementation_name
+ self.metrics = metrics
+
+ warnings.warn(
+ (
+ "The `DeepEvalCallbackHandler` is currently in beta and is subject to"
+ " change based on updates to `langchain`. Please report any issues to"
+ f" {self.ISSUES_URL} as an `integration` issue."
+ ),
+ )
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Store the prompts"""
+ self.prompts = prompts
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Do nothing when a new token is generated."""
+ pass
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Log records to deepeval when an LLM ends."""
+ from deepeval.metrics.answer_relevancy import AnswerRelevancy
+ from deepeval.metrics.bias_classifier import UnBiasedMetric
+ from deepeval.metrics.metric import Metric
+ from deepeval.metrics.toxic_classifier import NonToxicMetric
+
+ for metric in self.metrics:
+ for i, generation in enumerate(response.generations):
+ # Here, we only measure the first generation's output
+ output = generation[0].text
+ query = self.prompts[i]
+ if isinstance(metric, AnswerRelevancy):
+ result = metric.measure(
+ output=output,
+ query=query,
+ )
+ print(f"Answer Relevancy: {result}") # noqa: T201
+ elif isinstance(metric, UnBiasedMetric):
+ score = metric.measure(output)
+ print(f"Bias Score: {score}") # noqa: T201
+ elif isinstance(metric, NonToxicMetric):
+ score = metric.measure(output)
+ print(f"Toxic Score: {score}") # noqa: T201
+ else:
+ raise ValueError(
+ f"""Metric {metric.__name__} is not supported by deepeval
+ callbacks."""
+ )
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when LLM outputs an error."""
+ pass
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Do nothing when chain starts"""
+ pass
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Do nothing when chain ends."""
+ pass
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when LLM chain outputs an error."""
+ pass
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing when tool starts."""
+ pass
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Do nothing when agent takes a specific action."""
+ pass
+
+ def on_tool_end(
+ self,
+ output: Any,
+ observation_prefix: Optional[str] = None,
+ llm_prefix: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing when tool ends."""
+ pass
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when tool outputs an error."""
+ pass
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """Do nothing"""
+ pass
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Do nothing"""
+ pass
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/context_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/context_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d4d2b6d1e3e26511a784b8c30f8dafd52e8b9a2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/context_callback.py
@@ -0,0 +1,192 @@
+"""Callback handler for Context AI"""
+
+import os
+from typing import Any, Dict, List
+from uuid import UUID
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.messages import BaseMessage
+from langchain_core.outputs import LLMResult
+from langchain_core.utils import guard_import
+
+
+def import_context() -> Any:
+ """Import the `getcontext` package."""
+ return (
+ guard_import("getcontext", pip_name="python-context"),
+ guard_import("getcontext.token", pip_name="python-context").Credential,
+ guard_import(
+ "getcontext.generated.models", pip_name="python-context"
+ ).Conversation,
+ guard_import("getcontext.generated.models", pip_name="python-context").Message,
+ guard_import(
+ "getcontext.generated.models", pip_name="python-context"
+ ).MessageRole,
+ guard_import("getcontext.generated.models", pip_name="python-context").Rating,
+ )
+
+
+class ContextCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that records transcripts to the Context service.
+
+ (https://context.ai).
+
+ Keyword Args:
+ token (optional): The token with which to authenticate requests to Context.
+ Visit https://with.context.ai/settings to generate a token.
+ If not provided, the value of the `CONTEXT_TOKEN` environment
+ variable will be used.
+
+ Raises:
+ ImportError: if the `context-python` package is not installed.
+
+ Chat Example:
+ >>> from langchain_community.llms import ChatOpenAI
+ >>> from langchain_community.callbacks import ContextCallbackHandler
+ >>> context_callback = ContextCallbackHandler(
+ ... token="",
+ ... )
+ >>> chat = ChatOpenAI(
+ ... temperature=0,
+ ... headers={"user_id": "123"},
+ ... callbacks=[context_callback],
+ ... openai_api_key="API_KEY_HERE",
+ ... )
+ >>> messages = [
+ ... SystemMessage(content="You translate English to French."),
+ ... HumanMessage(content="I love programming with LangChain."),
+ ... ]
+ >>> chat.invoke(messages)
+
+ Chain Example:
+ >>> from langchain_classic.chains import LLMChain
+ >>> from langchain_community.chat_models import ChatOpenAI
+ >>> from langchain_community.callbacks import ContextCallbackHandler
+ >>> context_callback = ContextCallbackHandler(
+ ... token="",
+ ... )
+ >>> human_message_prompt = HumanMessagePromptTemplate(
+ ... prompt=PromptTemplate(
+ ... template="What is a good name for a company that makes {product}?",
+ ... input_variables=["product"],
+ ... ),
+ ... )
+ >>> chat_prompt_template = ChatPromptTemplate.from_messages(
+ ... [human_message_prompt]
+ ... )
+ >>> callback = ContextCallbackHandler(token)
+ >>> # Note: the same callback object must be shared between the
+ ... LLM and the chain.
+ >>> chat = ChatOpenAI(temperature=0.9, callbacks=[callback])
+ >>> chain = LLMChain(
+ ... llm=chat,
+ ... prompt=chat_prompt_template,
+ ... callbacks=[callback]
+ ... )
+ >>> chain.run("colorful socks")
+ """
+
+ def __init__(self, token: str = "", verbose: bool = False, **kwargs: Any) -> None:
+ (
+ self.context,
+ self.credential,
+ self.conversation_model,
+ self.message_model,
+ self.message_role_model,
+ self.rating_model,
+ ) = import_context()
+
+ token = token or os.environ.get("CONTEXT_TOKEN") or ""
+
+ self.client = self.context.ContextAPI(credential=self.credential(token))
+
+ self.chain_run_id = None
+
+ self.llm_model = None
+
+ self.messages: List[Any] = []
+ self.metadata: Dict[str, str] = {}
+
+ def on_chat_model_start(
+ self,
+ serialized: Dict[str, Any],
+ messages: List[List[BaseMessage]],
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when the chat model is started."""
+ llm_model = kwargs.get("invocation_params", {}).get("model", None)
+ if llm_model is not None:
+ self.metadata["model"] = llm_model
+
+ if len(messages) == 0:
+ return
+
+ for message in messages[0]:
+ role = self.message_role_model.SYSTEM
+ if message.type == "human":
+ role = self.message_role_model.USER
+ elif message.type == "system":
+ role = self.message_role_model.SYSTEM
+ elif message.type == "ai":
+ role = self.message_role_model.ASSISTANT
+
+ self.messages.append(
+ self.message_model(
+ message=message.content,
+ role=role,
+ )
+ )
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends."""
+ if len(response.generations) == 0 or len(response.generations[0]) == 0:
+ return
+
+ if not self.chain_run_id:
+ generation = response.generations[0][0]
+ self.messages.append(
+ self.message_model(
+ message=generation.text,
+ role=self.message_role_model.ASSISTANT,
+ )
+ )
+
+ self._log_conversation()
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Run when chain starts."""
+ self.chain_run_id = kwargs.get("run_id", None)
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Run when chain ends."""
+ self.messages.append(
+ self.message_model(
+ message=outputs["text"],
+ role=self.message_role_model.ASSISTANT,
+ )
+ )
+
+ self._log_conversation()
+
+ self.chain_run_id = None
+
+ def _log_conversation(self) -> None:
+ """Log the conversation to the context API."""
+ if len(self.messages) == 0:
+ return
+
+ self.client.log.conversation_upsert(
+ body={
+ "conversation": self.conversation_model(
+ messages=self.messages,
+ metadata=self.metadata,
+ )
+ }
+ )
+
+ self.messages = []
+ self.metadata = {}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/fiddler_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/fiddler_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ff6ed894d0b659573490c13a9ebbc3eecb675ff
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/fiddler_callback.py
@@ -0,0 +1,335 @@
+import time
+from typing import Any, Dict, List, Optional
+from uuid import UUID
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.outputs import LLMResult
+from langchain_core.utils import guard_import
+
+from langchain_community.callbacks.utils import import_pandas
+
+# Define constants
+
+# LLMResult keys
+TOKEN_USAGE = "token_usage"
+TOTAL_TOKENS = "total_tokens"
+PROMPT_TOKENS = "prompt_tokens"
+COMPLETION_TOKENS = "completion_tokens"
+RUN_ID = "run_id"
+MODEL_NAME = "model_name"
+GOOD = "good"
+BAD = "bad"
+NEUTRAL = "neutral"
+SUCCESS = "success"
+FAILURE = "failure"
+
+# Default values
+DEFAULT_MAX_TOKEN = 65536
+DEFAULT_MAX_DURATION = 120000
+
+# Fiddler specific constants
+PROMPT = "prompt"
+RESPONSE = "response"
+CONTEXT = "context"
+DURATION = "duration"
+FEEDBACK = "feedback"
+LLM_STATUS = "llm_status"
+
+FEEDBACK_POSSIBLE_VALUES = [GOOD, BAD, NEUTRAL]
+
+# Define a dataset dictionary
+_dataset_dict = {
+ PROMPT: ["fiddler"] * 10,
+ RESPONSE: ["fiddler"] * 10,
+ CONTEXT: ["fiddler"] * 10,
+ FEEDBACK: ["good"] * 10,
+ LLM_STATUS: ["success"] * 10,
+ MODEL_NAME: ["fiddler"] * 10,
+ RUN_ID: ["123e4567-e89b-12d3-a456-426614174000"] * 10,
+ TOTAL_TOKENS: [0, DEFAULT_MAX_TOKEN] * 5,
+ PROMPT_TOKENS: [0, DEFAULT_MAX_TOKEN] * 5,
+ COMPLETION_TOKENS: [0, DEFAULT_MAX_TOKEN] * 5,
+ DURATION: [1, DEFAULT_MAX_DURATION] * 5,
+}
+
+
+def import_fiddler() -> Any:
+ """Import the fiddler python package and raise an error if it is not installed."""
+ return guard_import("fiddler", pip_name="fiddler-client")
+
+
+# First, define custom callback handler implementations
+class FiddlerCallbackHandler(BaseCallbackHandler):
+ def __init__(
+ self,
+ url: str,
+ org: str,
+ project: str,
+ model: str,
+ api_key: str,
+ ) -> None:
+ """
+ Initialize Fiddler callback handler.
+
+ Args:
+ url: Fiddler URL (e.g. https://demo.fiddler.ai).
+ Make sure to include the protocol (http/https).
+ org: Fiddler organization id
+ project: Fiddler project name to publish events to
+ model: Fiddler model name to publish events to
+ api_key: Fiddler authentication token
+ """
+ super().__init__()
+ # Initialize Fiddler client and other necessary properties
+ self.fdl = import_fiddler()
+ self.pd = import_pandas()
+
+ self.url = url
+ self.org = org
+ self.project = project
+ self.model = model
+ self.api_key = api_key
+ self._df = self.pd.DataFrame(_dataset_dict)
+
+ self.run_id_prompts: Dict[UUID, List[str]] = {}
+ self.run_id_response: Dict[UUID, List[str]] = {}
+ self.run_id_starttime: Dict[UUID, int] = {}
+
+ # Initialize Fiddler client here
+ self.fiddler_client = self.fdl.FiddlerApi(url, org_id=org, auth_token=api_key)
+
+ if self.project not in self.fiddler_client.get_project_names():
+ print( # noqa: T201
+ f"adding project {self.project}.This only has to be done once."
+ )
+ try:
+ self.fiddler_client.add_project(self.project)
+ except Exception as e:
+ print( # noqa: T201
+ f"Error adding project {self.project}:"
+ "{e}. Fiddler integration will not work."
+ )
+ raise e
+
+ dataset_info = self.fdl.DatasetInfo.from_dataframe(
+ self._df, max_inferred_cardinality=0
+ )
+
+ # Set feedback column to categorical
+ for i in range(len(dataset_info.columns)):
+ if dataset_info.columns[i].name == FEEDBACK:
+ dataset_info.columns[i].data_type = self.fdl.DataType.CATEGORY
+ dataset_info.columns[i].possible_values = FEEDBACK_POSSIBLE_VALUES
+
+ elif dataset_info.columns[i].name == LLM_STATUS:
+ dataset_info.columns[i].data_type = self.fdl.DataType.CATEGORY
+ dataset_info.columns[i].possible_values = [SUCCESS, FAILURE]
+
+ if self.model not in self.fiddler_client.get_model_names(self.project):
+ if self.model not in self.fiddler_client.get_dataset_names(self.project):
+ print( # noqa: T201
+ f"adding dataset {self.model} to project {self.project}."
+ "This only has to be done once."
+ )
+ try:
+ self.fiddler_client.upload_dataset(
+ project_id=self.project,
+ dataset_id=self.model,
+ dataset={"train": self._df},
+ info=dataset_info,
+ )
+ except Exception as e:
+ print( # noqa: T201
+ f"Error adding dataset {self.model}: {e}."
+ "Fiddler integration will not work."
+ )
+ raise e
+
+ model_info = self.fdl.ModelInfo.from_dataset_info(
+ dataset_info=dataset_info,
+ dataset_id="train",
+ model_task=self.fdl.ModelTask.LLM,
+ features=[PROMPT, CONTEXT, RESPONSE],
+ target=FEEDBACK,
+ metadata_cols=[
+ RUN_ID,
+ TOTAL_TOKENS,
+ PROMPT_TOKENS,
+ COMPLETION_TOKENS,
+ MODEL_NAME,
+ DURATION,
+ ],
+ custom_features=self.custom_features,
+ )
+ print( # noqa: T201
+ f"adding model {self.model} to project {self.project}."
+ "This only has to be done once."
+ )
+ try:
+ self.fiddler_client.add_model(
+ project_id=self.project,
+ dataset_id=self.model,
+ model_id=self.model,
+ model_info=model_info,
+ )
+ except Exception as e:
+ print( # noqa: T201
+ f"Error adding model {self.model}: {e}."
+ "Fiddler integration will not work."
+ )
+ raise e
+
+ @property
+ def custom_features(self) -> list:
+ """
+ Define custom features for the model to automatically enrich the data with.
+ Here, we enable the following enrichments:
+ - Automatic Embedding generation for prompt and response
+ - Text Statistics such as:
+ - Automated Readability Index
+ - Coleman Liau Index
+ - Dale Chall Readability Score
+ - Difficult Words
+ - Flesch Reading Ease
+ - Flesch Kincaid Grade
+ - Gunning Fog
+ - Linsear Write Formula
+ - PII - Personal Identifiable Information
+ - Sentiment Analysis
+
+ """
+
+ return [
+ self.fdl.Enrichment(
+ name="Prompt Embedding",
+ enrichment="embedding",
+ columns=[PROMPT],
+ ),
+ self.fdl.TextEmbedding(
+ name="Prompt CF",
+ source_column=PROMPT,
+ column="Prompt Embedding",
+ ),
+ self.fdl.Enrichment(
+ name="Response Embedding",
+ enrichment="embedding",
+ columns=[RESPONSE],
+ ),
+ self.fdl.TextEmbedding(
+ name="Response CF",
+ source_column=RESPONSE,
+ column="Response Embedding",
+ ),
+ self.fdl.Enrichment(
+ name="Text Statistics",
+ enrichment="textstat",
+ columns=[PROMPT, RESPONSE],
+ config={
+ "statistics": [
+ "automated_readability_index",
+ "coleman_liau_index",
+ "dale_chall_readability_score",
+ "difficult_words",
+ "flesch_reading_ease",
+ "flesch_kincaid_grade",
+ "gunning_fog",
+ "linsear_write_formula",
+ ]
+ },
+ ),
+ self.fdl.Enrichment(
+ name="PII",
+ enrichment="pii",
+ columns=[PROMPT, RESPONSE],
+ ),
+ self.fdl.Enrichment(
+ name="Sentiment",
+ enrichment="sentiment",
+ columns=[PROMPT, RESPONSE],
+ ),
+ ]
+
+ def _publish_events(
+ self,
+ run_id: UUID,
+ prompt_responses: List[str],
+ duration: int,
+ llm_status: str,
+ model_name: Optional[str] = "",
+ token_usage_dict: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ """
+ Publish events to fiddler
+ """
+
+ prompt_count = len(self.run_id_prompts[run_id])
+ df = self.pd.DataFrame(
+ {
+ PROMPT: self.run_id_prompts[run_id],
+ RESPONSE: prompt_responses,
+ RUN_ID: [str(run_id)] * prompt_count,
+ DURATION: [duration] * prompt_count,
+ LLM_STATUS: [llm_status] * prompt_count,
+ MODEL_NAME: [model_name] * prompt_count,
+ }
+ )
+
+ if token_usage_dict:
+ for key, value in token_usage_dict.items():
+ df[key] = [value] * prompt_count if isinstance(value, int) else value
+
+ try:
+ if df.shape[0] > 1:
+ self.fiddler_client.publish_events_batch(self.project, self.model, df)
+ else:
+ df_dict = df.to_dict(orient="records")
+ self.fiddler_client.publish_event(
+ self.project, self.model, event=df_dict[0]
+ )
+ except Exception as e:
+ print( # noqa: T201
+ f"Error publishing events to fiddler: {e}. continuing..."
+ )
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> Any:
+ run_id = kwargs[RUN_ID]
+ self.run_id_prompts[run_id] = prompts
+ self.run_id_starttime[run_id] = int(time.time() * 1000)
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ flattened_llmresult = response.flatten()
+ run_id = kwargs[RUN_ID]
+ run_duration = int(time.time() * 1000) - self.run_id_starttime[run_id]
+ model_name = ""
+ token_usage_dict = {}
+
+ if isinstance(response.llm_output, dict):
+ token_usage_dict = {
+ k: v
+ for k, v in response.llm_output.items()
+ if k in [TOTAL_TOKENS, PROMPT_TOKENS, COMPLETION_TOKENS]
+ }
+ model_name = response.llm_output.get(MODEL_NAME, "")
+
+ prompt_responses = [
+ llmresult.generations[0][0].text for llmresult in flattened_llmresult
+ ]
+
+ self._publish_events(
+ run_id,
+ prompt_responses,
+ run_duration,
+ SUCCESS,
+ model_name,
+ token_usage_dict,
+ )
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ run_id = kwargs[RUN_ID]
+ duration = int(time.time() * 1000) - self.run_id_starttime[run_id]
+
+ self._publish_events(
+ run_id, [""] * len(self.run_id_prompts[run_id]), duration, FAILURE
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/flyte_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/flyte_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..e108d13cbeeb62b3ac64098cd347860d01e20924
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/flyte_callback.py
@@ -0,0 +1,364 @@
+"""FlyteKit callback handler."""
+
+from __future__ import annotations
+
+import logging
+from copy import deepcopy
+from typing import TYPE_CHECKING, Any, Dict, List, Tuple
+
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.outputs import LLMResult
+from langchain_core.utils import guard_import
+
+from langchain_community.callbacks.utils import (
+ BaseMetadataCallbackHandler,
+ flatten_dict,
+ import_pandas,
+ import_spacy,
+ import_textstat,
+)
+
+if TYPE_CHECKING:
+ import flytekit
+ from flytekitplugins.deck import renderer
+
+logger = logging.getLogger(__name__)
+
+
+def import_flytekit() -> Tuple[flytekit, renderer]:
+ """Import flytekit and flytekitplugins-deck-standard."""
+ return (
+ guard_import("flytekit"),
+ guard_import(
+ "flytekitplugins.deck", pip_name="flytekitplugins-deck-standard"
+ ).renderer,
+ )
+
+
+def analyze_text(
+ text: str,
+ nlp: Any = None,
+ textstat: Any = None,
+) -> dict:
+ """Analyze text using textstat and spacy.
+
+ Parameters:
+ text (str): The text to analyze.
+ nlp (spacy.lang): The spacy language model to use for visualization.
+
+ Returns:
+ `dict` containing the complexity metrics and visualization
+ files serialized to HTML string.
+ """
+ resp: Dict[str, Any] = {}
+ if textstat is not None:
+ text_complexity_metrics = {
+ "flesch_reading_ease": textstat.flesch_reading_ease(text),
+ "flesch_kincaid_grade": textstat.flesch_kincaid_grade(text),
+ "smog_index": textstat.smog_index(text),
+ "coleman_liau_index": textstat.coleman_liau_index(text),
+ "automated_readability_index": textstat.automated_readability_index(text),
+ "dale_chall_readability_score": textstat.dale_chall_readability_score(text),
+ "difficult_words": textstat.difficult_words(text),
+ "linsear_write_formula": textstat.linsear_write_formula(text),
+ "gunning_fog": textstat.gunning_fog(text),
+ "fernandez_huerta": textstat.fernandez_huerta(text),
+ "szigriszt_pazos": textstat.szigriszt_pazos(text),
+ "gutierrez_polini": textstat.gutierrez_polini(text),
+ "crawford": textstat.crawford(text),
+ "gulpease_index": textstat.gulpease_index(text),
+ "osman": textstat.osman(text),
+ }
+ resp.update({"text_complexity_metrics": text_complexity_metrics})
+ resp.update(text_complexity_metrics)
+
+ if nlp is not None:
+ spacy = import_spacy()
+ doc = nlp(text)
+ dep_out = spacy.displacy.render(doc, style="dep", jupyter=False, page=True)
+ ent_out = spacy.displacy.render(doc, style="ent", jupyter=False, page=True)
+ text_visualizations = {
+ "dependency_tree": dep_out,
+ "entities": ent_out,
+ }
+ resp.update(text_visualizations)
+
+ return resp
+
+
+class FlyteCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
+ """Callback handler that is used within a Flyte task."""
+
+ def __init__(self) -> None:
+ """Initialize callback handler."""
+ flytekit, renderer = import_flytekit()
+ self.pandas = import_pandas()
+
+ self.textstat = None
+ try:
+ self.textstat = import_textstat()
+ except ImportError:
+ logger.warning(
+ "Textstat library is not installed. \
+ It may result in the inability to log \
+ certain metrics that can be captured with Textstat."
+ )
+
+ spacy = None
+ try:
+ spacy = import_spacy()
+ except ImportError:
+ logger.warning(
+ "Spacy library is not installed. \
+ It may result in the inability to log \
+ certain metrics that can be captured with Spacy."
+ )
+
+ super().__init__()
+
+ self.nlp = None
+ if spacy:
+ try:
+ self.nlp = spacy.load("en_core_web_sm")
+ except OSError:
+ logger.warning(
+ "FlyteCallbackHandler uses spacy's en_core_web_sm model"
+ " for certain metrics. To download,"
+ " run the following command in your terminal:"
+ " `python -m spacy download en_core_web_sm`"
+ )
+
+ self.table_renderer = renderer.TableRenderer
+ self.markdown_renderer = renderer.MarkdownRenderer
+
+ self.deck = flytekit.Deck(
+ "LangChain Metrics",
+ self.markdown_renderer().to_html("## LangChain Metrics"),
+ )
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Run when LLM starts."""
+
+ self.step += 1
+ self.llm_starts += 1
+ self.starts += 1
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_llm_start"})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.get_custom_callback_meta())
+
+ prompt_responses = []
+ for prompt in prompts:
+ prompt_responses.append(prompt)
+
+ resp.update({"prompts": prompt_responses})
+
+ self.deck.append(self.markdown_renderer().to_html("### LLM Start"))
+ self.deck.append(
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
+ )
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Run when LLM generates a new token."""
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running."""
+ self.step += 1
+ self.llm_ends += 1
+ self.ends += 1
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_llm_end"})
+ resp.update(flatten_dict(response.llm_output or {}))
+ resp.update(self.get_custom_callback_meta())
+
+ self.deck.append(self.markdown_renderer().to_html("### LLM End"))
+ self.deck.append(self.table_renderer().to_html(self.pandas.DataFrame([resp])))
+
+ for generations in response.generations:
+ for generation in generations:
+ generation_resp = deepcopy(resp)
+ generation_resp.update(flatten_dict(generation.dict()))
+ if self.nlp or self.textstat:
+ generation_resp.update(
+ analyze_text(
+ generation.text, nlp=self.nlp, textstat=self.textstat
+ )
+ )
+
+ complexity_metrics: Dict[str, float] = generation_resp.pop(
+ "text_complexity_metrics"
+ )
+ self.deck.append(
+ self.markdown_renderer().to_html("#### Text Complexity Metrics")
+ )
+ self.deck.append(
+ self.table_renderer().to_html(
+ self.pandas.DataFrame([complexity_metrics])
+ )
+ + "\n"
+ )
+
+ dependency_tree = generation_resp["dependency_tree"]
+ self.deck.append(
+ self.markdown_renderer().to_html("#### Dependency Tree")
+ )
+ self.deck.append(dependency_tree)
+
+ entities = generation_resp["entities"]
+ self.deck.append(self.markdown_renderer().to_html("#### Entities"))
+ self.deck.append(entities)
+ else:
+ self.deck.append(
+ self.markdown_renderer().to_html("#### Generated Response")
+ )
+ self.deck.append(self.markdown_renderer().to_html(generation.text))
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when LLM errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Run when chain starts running."""
+ self.step += 1
+ self.chain_starts += 1
+ self.starts += 1
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_chain_start"})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.get_custom_callback_meta())
+
+ chain_input = ",".join([f"{k}={v}" for k, v in inputs.items()])
+ input_resp = deepcopy(resp)
+ input_resp["inputs"] = chain_input
+
+ self.deck.append(self.markdown_renderer().to_html("### Chain Start"))
+ self.deck.append(
+ self.table_renderer().to_html(self.pandas.DataFrame([input_resp])) + "\n"
+ )
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Run when chain ends running."""
+ self.step += 1
+ self.chain_ends += 1
+ self.ends += 1
+
+ resp: Dict[str, Any] = {}
+ chain_output = ",".join([f"{k}={v}" for k, v in outputs.items()])
+ resp.update({"action": "on_chain_end", "outputs": chain_output})
+ resp.update(self.get_custom_callback_meta())
+
+ self.deck.append(self.markdown_renderer().to_html("### Chain End"))
+ self.deck.append(
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
+ )
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when chain errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_tool_start(
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
+ ) -> None:
+ """Run when tool starts running."""
+ self.step += 1
+ self.tool_starts += 1
+ self.starts += 1
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_tool_start", "input_str": input_str})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.get_custom_callback_meta())
+
+ self.deck.append(self.markdown_renderer().to_html("### Tool Start"))
+ self.deck.append(
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
+ )
+
+ def on_tool_end(self, output: str, **kwargs: Any) -> None:
+ """Run when tool ends running."""
+ self.step += 1
+ self.tool_ends += 1
+ self.ends += 1
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_tool_end", "output": output})
+ resp.update(self.get_custom_callback_meta())
+
+ self.deck.append(self.markdown_renderer().to_html("### Tool End"))
+ self.deck.append(
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
+ )
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when tool errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """
+ Run when agent is ending.
+ """
+ self.step += 1
+ self.text_ctr += 1
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_text", "text": text})
+ resp.update(self.get_custom_callback_meta())
+
+ self.deck.append(self.markdown_renderer().to_html("### On Text"))
+ self.deck.append(
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
+ )
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run when agent ends running."""
+ self.step += 1
+ self.agent_ends += 1
+ self.ends += 1
+
+ resp: Dict[str, Any] = {}
+ resp.update(
+ {
+ "action": "on_agent_finish",
+ "output": finish.return_values["output"],
+ "log": finish.log,
+ }
+ )
+ resp.update(self.get_custom_callback_meta())
+
+ self.deck.append(self.markdown_renderer().to_html("### Agent Finish"))
+ self.deck.append(
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
+ )
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Run on agent action."""
+ self.step += 1
+ self.tool_starts += 1
+ self.starts += 1
+
+ resp: Dict[str, Any] = {}
+ resp.update(
+ {
+ "action": "on_agent_action",
+ "tool": action.tool,
+ "tool_input": action.tool_input,
+ "log": action.log,
+ }
+ )
+ resp.update(self.get_custom_callback_meta())
+
+ self.deck.append(self.markdown_renderer().to_html("### Agent Action"))
+ self.deck.append(
+ self.table_renderer().to_html(self.pandas.DataFrame([resp])) + "\n"
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/human.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/human.py
new file mode 100644
index 0000000000000000000000000000000000000000..64ea01f99f524fca14ffbabb6bc2560341a10415
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/human.py
@@ -0,0 +1,88 @@
+from typing import Any, Awaitable, Callable, Dict, Optional
+from uuid import UUID
+
+from langchain_core.callbacks import AsyncCallbackHandler, BaseCallbackHandler
+
+
+def _default_approve(_input: str) -> bool:
+ msg = (
+ "Do you approve of the following input? "
+ "Anything except 'Y'/'Yes' (case-insensitive) will be treated as a no."
+ )
+ msg += "\n\n" + _input + "\n"
+ resp = input(msg)
+ return resp.lower() in ("yes", "y")
+
+
+async def _adefault_approve(_input: str) -> bool:
+ msg = (
+ "Do you approve of the following input? "
+ "Anything except 'Y'/'Yes' (case-insensitive) will be treated as a no."
+ )
+ msg += "\n\n" + _input + "\n"
+ resp = input(msg)
+ return resp.lower() in ("yes", "y")
+
+
+def _default_true(_: Dict[str, Any]) -> bool:
+ return True
+
+
+class HumanRejectedException(Exception):
+ """Exception to raise when a person manually review and rejects a value."""
+
+
+class HumanApprovalCallbackHandler(BaseCallbackHandler):
+ """Callback for manually validating values."""
+
+ raise_error: bool = True
+
+ def __init__(
+ self,
+ approve: Callable[[Any], bool] = _default_approve,
+ should_check: Callable[[Dict[str, Any]], bool] = _default_true,
+ ):
+ self._approve = approve
+ self._should_check = should_check
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ parent_run_id: Optional[UUID] = None,
+ **kwargs: Any,
+ ) -> Any:
+ if self._should_check(serialized) and not self._approve(input_str):
+ raise HumanRejectedException(
+ f"Inputs {input_str} to tool {serialized} were rejected."
+ )
+
+
+class AsyncHumanApprovalCallbackHandler(AsyncCallbackHandler):
+ """Asynchronous callback for manually validating values."""
+
+ raise_error: bool = True
+
+ def __init__(
+ self,
+ approve: Callable[[Any], Awaitable[bool]] = _adefault_approve,
+ should_check: Callable[[Dict[str, Any]], bool] = _default_true,
+ ):
+ self._approve = approve
+ self._should_check = should_check
+
+ async def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ parent_run_id: Optional[UUID] = None,
+ **kwargs: Any,
+ ) -> Any:
+ if self._should_check(serialized) and not await self._approve(input_str):
+ raise HumanRejectedException(
+ f"Inputs {input_str} to tool {serialized} were rejected."
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/infino_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/infino_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..3205737409306afecc0a91ab235273f548fabc99
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/infino_callback.py
@@ -0,0 +1,251 @@
+import time
+from typing import Any, Dict, List, Optional, cast
+
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.messages import BaseMessage
+from langchain_core.outputs import ChatGeneration, LLMResult
+from langchain_core.utils import guard_import
+
+
+def import_infino() -> Any:
+ """Import the infino client."""
+ return guard_import("infinopy").InfinoClient()
+
+
+def import_tiktoken() -> Any:
+ """Import tiktoken for counting tokens for OpenAI models."""
+ return guard_import("tiktoken")
+
+
+def get_num_tokens(string: str, openai_model_name: str) -> int:
+ """Calculate num tokens for OpenAI with tiktoken package.
+
+ Official documentation: https://github.com/openai/openai-cookbook/blob/main
+ /examples/How_to_count_tokens_with_tiktoken.ipynb
+ """
+ tiktoken = import_tiktoken()
+
+ encoding = tiktoken.encoding_for_model(openai_model_name)
+ num_tokens = len(encoding.encode(string))
+ return num_tokens
+
+
+class InfinoCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that logs to Infino."""
+
+ def __init__(
+ self,
+ model_id: Optional[str] = None,
+ model_version: Optional[str] = None,
+ verbose: bool = False,
+ ) -> None:
+ # Set Infino client
+ self.client = import_infino()
+ self.model_id = model_id
+ self.model_version = model_version
+ self.verbose = verbose
+ self.is_chat_openai_model = False
+ self.chat_openai_model_name = "gpt-3.5-turbo"
+
+ def _send_to_infino(
+ self,
+ key: str,
+ value: Any,
+ is_ts: bool = True,
+ ) -> None:
+ """Send the key-value to Infino.
+
+ Parameters:
+ key (str): the key to send to Infino.
+ value (Any): the value to send to Infino.
+ is_ts (bool): if True, the value is part of a time series, else it
+ is sent as a log message.
+ """
+ payload = {
+ "date": int(time.time()),
+ key: value,
+ "labels": {
+ "model_id": self.model_id,
+ "model_version": self.model_version,
+ },
+ }
+ if self.verbose:
+ print(f"Tracking {key} with Infino: {payload}") # noqa: T201
+
+ # Append to Infino time series only if is_ts is True, otherwise
+ # append to Infino log.
+ if is_ts:
+ self.client.append_ts(payload)
+ else:
+ self.client.append_log(payload)
+
+ def on_llm_start(
+ self,
+ serialized: Dict[str, Any],
+ prompts: List[str],
+ **kwargs: Any,
+ ) -> None:
+ """Log the prompts to Infino, and set start time and error flag."""
+ for prompt in prompts:
+ self._send_to_infino("prompt", prompt, is_ts=False)
+
+ # Set the error flag to indicate no error (this will get overridden
+ # in on_llm_error if an error occurs).
+ self.error = 0
+
+ # Set the start time (so that we can calculate the request
+ # duration in on_llm_end).
+ self.start_time = time.time()
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Do nothing when a new token is generated."""
+ pass
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Log the latency, error, token usage, and response to Infino."""
+ # Calculate and track the request latency.
+ self.end_time = time.time()
+ duration = self.end_time - self.start_time
+ self._send_to_infino("latency", duration)
+
+ # Track success or error flag.
+ self._send_to_infino("error", self.error)
+
+ # Track prompt response.
+ for generations in response.generations:
+ for generation in generations:
+ self._send_to_infino("prompt_response", generation.text, is_ts=False)
+
+ # Track token usage (for non-chat models).
+ if (response.llm_output is not None) and isinstance(response.llm_output, Dict):
+ token_usage = response.llm_output["token_usage"]
+ if token_usage is not None:
+ prompt_tokens = token_usage["prompt_tokens"]
+ total_tokens = token_usage["total_tokens"]
+ completion_tokens = token_usage["completion_tokens"]
+ self._send_to_infino("prompt_tokens", prompt_tokens)
+ self._send_to_infino("total_tokens", total_tokens)
+ self._send_to_infino("completion_tokens", completion_tokens)
+
+ # Track completion token usage (for openai chat models).
+ if self.is_chat_openai_model:
+ messages = " ".join(
+ cast(str, cast(ChatGeneration, generation).message.content)
+ for generation in generations
+ )
+ completion_tokens = get_num_tokens(
+ messages, openai_model_name=self.chat_openai_model_name
+ )
+ self._send_to_infino("completion_tokens", completion_tokens)
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Set the error flag."""
+ self.error = 1
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Do nothing when LLM chain starts."""
+ pass
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Do nothing when LLM chain ends."""
+ pass
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Need to log the error."""
+ pass
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing when tool starts."""
+ pass
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Do nothing when agent takes a specific action."""
+ pass
+
+ def on_tool_end(
+ self,
+ output: str,
+ observation_prefix: Optional[str] = None,
+ llm_prefix: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing when tool ends."""
+ pass
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when tool outputs an error."""
+ pass
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """Do nothing."""
+ pass
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Do nothing."""
+ pass
+
+ def on_chat_model_start(
+ self,
+ serialized: Dict[str, Any],
+ messages: List[List[BaseMessage]],
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM starts running."""
+
+ # Currently, for chat models, we only support input prompts for ChatOpenAI.
+ # Check if this model is a ChatOpenAI model.
+ values = serialized.get("id")
+ if values:
+ for value in values:
+ if value == "ChatOpenAI":
+ self.is_chat_openai_model = True
+ break
+
+ # Track prompt tokens for ChatOpenAI model.
+ if self.is_chat_openai_model:
+ invocation_params = kwargs.get("invocation_params")
+ if invocation_params:
+ model_name = invocation_params.get("model_name")
+ if model_name:
+ self.chat_openai_model_name = model_name
+ prompt_tokens = 0
+ for message_list in messages:
+ message_string = " ".join(
+ cast(str, msg.content) for msg in message_list
+ )
+ num_tokens = get_num_tokens(
+ message_string,
+ openai_model_name=self.chat_openai_model_name,
+ )
+ prompt_tokens += num_tokens
+
+ self._send_to_infino("prompt_tokens", prompt_tokens)
+
+ if self.verbose:
+ print( # noqa: T201
+ f"on_chat_model_start: is_chat_openai_model= \
+ {self.is_chat_openai_model}, \
+ chat_openai_model_name={self.chat_openai_model_name}"
+ )
+
+ # Send the prompt to infino
+ prompt = " ".join(
+ cast(str, msg.content) for sublist in messages for msg in sublist
+ )
+ self._send_to_infino("prompt", prompt, is_ts=False)
+
+ # Set the error flag to indicate no error (this will get overridden
+ # in on_llm_error if an error occurs).
+ self.error = 0
+
+ # Set the start time (so that we can calculate the request
+ # duration in on_llm_end).
+ self.start_time = time.time()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/labelstudio_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/labelstudio_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..0eb35af10171854afdce0860a706ee1234603e81
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/labelstudio_callback.py
@@ -0,0 +1,390 @@
+import os
+import warnings
+from datetime import datetime
+from enum import Enum
+from typing import Any, Dict, List, Optional, Tuple, Union
+from uuid import UUID
+
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.messages import BaseMessage, ChatMessage
+from langchain_core.outputs import Generation, LLMResult
+
+
+class LabelStudioMode(Enum):
+ """Label Studio mode enumerator."""
+
+ PROMPT = "prompt"
+ CHAT = "chat"
+
+
+def get_default_label_configs(
+ mode: Union[str, LabelStudioMode],
+) -> Tuple[str, LabelStudioMode]:
+ """Get default Label Studio configs for the given mode.
+
+ Parameters:
+ mode: Label Studio mode ("prompt" or "chat")
+
+ Returns: Tuple of Label Studio config and mode
+ """
+ _default_label_configs = {
+ LabelStudioMode.PROMPT.value: """
+
+
+
+
+
+
+
+
+
+
+""",
+ LabelStudioMode.CHAT.value: """
+
+
+
+
+
+
+
+
+""",
+ }
+
+ if isinstance(mode, str):
+ mode = LabelStudioMode(mode)
+
+ return _default_label_configs[mode.value], mode
+
+
+class LabelStudioCallbackHandler(BaseCallbackHandler):
+ """Label Studio callback handler.
+ Provides the ability to send predictions to Label Studio
+ for human evaluation, feedback and annotation.
+
+ Parameters:
+ api_key: Label Studio API key
+ url: Label Studio URL
+ project_id: Label Studio project ID
+ project_name: Label Studio project name
+ project_config: Label Studio project config (XML)
+ mode: Label Studio mode ("prompt" or "chat")
+
+ Examples:
+ >>> from langchain_community.llms import OpenAI
+ >>> from langchain_community.callbacks import LabelStudioCallbackHandler
+ >>> handler = LabelStudioCallbackHandler(
+ ... api_key='',
+ ... url='http://localhost:8080',
+ ... project_name='LangChain-%Y-%m-%d',
+ ... mode='prompt'
+ ... )
+ >>> llm = OpenAI(callbacks=[handler])
+ >>> llm.invoke('Tell me a story about a dog.')
+ """
+
+ DEFAULT_PROJECT_NAME: str = "LangChain-%Y-%m-%d"
+
+ def __init__(
+ self,
+ api_key: Optional[str] = None,
+ url: Optional[str] = None,
+ project_id: Optional[int] = None,
+ project_name: str = DEFAULT_PROJECT_NAME,
+ project_config: Optional[str] = None,
+ mode: Union[str, LabelStudioMode] = LabelStudioMode.PROMPT,
+ ):
+ super().__init__()
+
+ # Import LabelStudio SDK
+ try:
+ import label_studio_sdk as ls
+ except ImportError:
+ raise ImportError(
+ f"You're using {self.__class__.__name__} in your code,"
+ f" but you don't have the LabelStudio SDK "
+ f"Python package installed or upgraded to the latest version. "
+ f"Please run `pip install -U label-studio-sdk`"
+ f" before using this callback."
+ )
+
+ # Check if Label Studio API key is provided
+ if not api_key:
+ if os.getenv("LABEL_STUDIO_API_KEY"):
+ api_key = str(os.getenv("LABEL_STUDIO_API_KEY"))
+ else:
+ raise ValueError(
+ f"You're using {self.__class__.__name__} in your code,"
+ f" Label Studio API key is not provided. "
+ f"Please provide Label Studio API key: "
+ f"go to the Label Studio instance, navigate to "
+ f"Account & Settings -> Access Token and copy the key. "
+ f"Use the key as a parameter for the callback: "
+ f"{self.__class__.__name__}"
+ f"(label_studio_api_key='', ...) or "
+ f"set the environment variable LABEL_STUDIO_API_KEY="
+ )
+ self.api_key = api_key
+
+ if not url:
+ if os.getenv("LABEL_STUDIO_URL"):
+ url = os.getenv("LABEL_STUDIO_URL")
+ else:
+ warnings.warn(
+ f"Label Studio URL is not provided, "
+ f"using default URL: {ls.LABEL_STUDIO_DEFAULT_URL}"
+ f"If you want to provide your own URL, use the parameter: "
+ f"{self.__class__.__name__}"
+ f"(label_studio_url='', ...) "
+ f"or set the environment variable LABEL_STUDIO_URL="
+ )
+ url = ls.LABEL_STUDIO_DEFAULT_URL
+ self.url = url
+
+ # Maps run_id to prompts
+ self.payload: Dict[str, Dict] = {}
+
+ self.ls_client = ls.Client(url=self.url, api_key=self.api_key)
+ self.project_name = project_name
+ if project_config:
+ self.project_config = project_config
+ self.mode = None
+ else:
+ self.project_config, self.mode = get_default_label_configs(mode)
+
+ self.project_id = project_id or os.getenv("LABEL_STUDIO_PROJECT_ID")
+ if self.project_id is not None:
+ self.ls_project = self.ls_client.get_project(int(self.project_id))
+ else:
+ project_title = datetime.today().strftime(self.project_name)
+ existing_projects = self.ls_client.get_projects(title=project_title)
+ if existing_projects:
+ self.ls_project = existing_projects[0]
+ self.project_id = self.ls_project.id
+ else:
+ self.ls_project = self.ls_client.create_project(
+ title=project_title, label_config=self.project_config
+ )
+ self.project_id = self.ls_project.id
+ self.parsed_label_config = self.ls_project.parsed_label_config
+
+ # Find the first TextArea tag
+ # "from_name", "to_name", "value" will be used to create predictions
+ self.from_name, self.to_name, self.value, self.input_type = (
+ None,
+ None,
+ None,
+ None,
+ )
+ for tag_name, tag_info in self.parsed_label_config.items():
+ if tag_info["type"] == "TextArea":
+ self.from_name = tag_name
+ self.to_name = tag_info["to_name"][0]
+ self.value = tag_info["inputs"][0]["value"]
+ self.input_type = tag_info["inputs"][0]["type"]
+ break
+ if not self.from_name:
+ error_message = (
+ f'Label Studio project "{self.project_name}" '
+ f"does not have a TextArea tag. "
+ f"Please add a TextArea tag to the project."
+ )
+ if self.mode == LabelStudioMode.PROMPT:
+ error_message += (
+ "\nHINT: go to project Settings -> "
+ "Labeling Interface -> Browse Templates"
+ ' and select "Generative AI -> '
+ 'Supervised Language Model Fine-tuning" template.'
+ )
+ else:
+ error_message += (
+ "\nHINT: go to project Settings -> "
+ "Labeling Interface -> Browse Templates"
+ " and check available templates under "
+ '"Generative AI" section.'
+ )
+ raise ValueError(error_message)
+
+ def add_prompts_generations(
+ self, run_id: str, generations: List[List[Generation]]
+ ) -> None:
+ # Create tasks in Label Studio
+ tasks = []
+ prompts = self.payload[run_id]["prompts"]
+ model_version = (
+ self.payload[run_id]["kwargs"]
+ .get("invocation_params", {})
+ .get("model_name")
+ )
+ for prompt, generation in zip(prompts, generations):
+ tasks.append(
+ {
+ "data": {
+ self.value: prompt,
+ "run_id": run_id,
+ },
+ "predictions": [
+ {
+ "result": [
+ {
+ "from_name": self.from_name,
+ "to_name": self.to_name,
+ "type": "textarea",
+ "value": {"text": [g.text for g in generation]},
+ }
+ ],
+ "model_version": model_version,
+ }
+ ],
+ }
+ )
+ self.ls_project.import_tasks(tasks)
+
+ def on_llm_start(
+ self,
+ serialized: Dict[str, Any],
+ prompts: List[str],
+ **kwargs: Any,
+ ) -> None:
+ """Save the prompts in memory when an LLM starts."""
+ if self.input_type != "Text":
+ raise ValueError(
+ f'\nLabel Studio project "{self.project_name}" '
+ f"has an input type <{self.input_type}>. "
+ f'To make it work with the mode="chat", '
+ f"the input type should be .\n"
+ f"Read more here https://labelstud.io/tags/text"
+ )
+ run_id = str(kwargs["run_id"])
+ self.payload[run_id] = {"prompts": prompts, "kwargs": kwargs}
+
+ def _get_message_role(self, message: BaseMessage) -> str:
+ """Get the role of the message."""
+ if isinstance(message, ChatMessage):
+ return message.role
+ else:
+ return message.__class__.__name__
+
+ def on_chat_model_start(
+ self,
+ serialized: Dict[str, Any],
+ messages: List[List[BaseMessage]],
+ *,
+ run_id: UUID,
+ parent_run_id: Optional[UUID] = None,
+ tags: Optional[List[str]] = None,
+ metadata: Optional[Dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Save the prompts in memory when an LLM starts."""
+ if self.input_type != "Paragraphs":
+ raise ValueError(
+ f'\nLabel Studio project "{self.project_name}" '
+ f"has an input type <{self.input_type}>. "
+ f'To make it work with the mode="chat", '
+ f"the input type should be .\n"
+ f"Read more here https://labelstud.io/tags/paragraphs"
+ )
+
+ prompts = []
+ for message_list in messages:
+ dialog = []
+ for message in message_list:
+ dialog.append(
+ {
+ "role": self._get_message_role(message),
+ "content": message.content,
+ }
+ )
+ prompts.append(dialog)
+ self.payload[str(run_id)] = {
+ "prompts": prompts,
+ "tags": tags,
+ "metadata": metadata,
+ "run_id": run_id,
+ "parent_run_id": parent_run_id,
+ "kwargs": kwargs,
+ }
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Do nothing when a new token is generated."""
+ pass
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Create a new Label Studio task for each prompt and generation."""
+ run_id = str(kwargs["run_id"])
+
+ # Submit results to Label Studio
+ self.add_prompts_generations(run_id, response.generations)
+
+ # Pop current run from `self.runs`
+ self.payload.pop(run_id)
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when LLM outputs an error."""
+ pass
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ pass
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ pass
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when LLM chain outputs an error."""
+ pass
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing when tool starts."""
+ pass
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Do nothing when agent takes a specific action."""
+ pass
+
+ def on_tool_end(
+ self,
+ output: str,
+ observation_prefix: Optional[str] = None,
+ llm_prefix: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing when tool ends."""
+ pass
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Do nothing when tool outputs an error."""
+ pass
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """Do nothing"""
+ pass
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Do nothing"""
+ pass
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/llmonitor_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/llmonitor_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc7bbbfb9b092459e56ee8a814a5a8a14a16855a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/llmonitor_callback.py
@@ -0,0 +1,681 @@
+import importlib.metadata
+import logging
+import os
+import traceback
+import warnings
+from contextvars import ContextVar
+from typing import Any, Dict, List, Union, cast
+from uuid import UUID
+
+import requests
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.messages import BaseMessage
+from langchain_core.outputs import LLMResult
+from packaging.version import parse
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_API_URL = "https://app.llmonitor.com"
+
+user_ctx = ContextVar[Union[str, None]]("user_ctx", default=None)
+user_props_ctx = ContextVar[Union[str, None]]("user_props_ctx", default=None)
+
+PARAMS_TO_CAPTURE = [
+ "temperature",
+ "top_p",
+ "top_k",
+ "stop",
+ "presence_penalty",
+ "frequence_penalty",
+ "seed",
+ "function_call",
+ "functions",
+ "tools",
+ "tool_choice",
+ "response_format",
+ "max_tokens",
+ "logit_bias",
+]
+
+
+class UserContextManager:
+ """Context manager for LLMonitor user context."""
+
+ def __init__(self, user_id: str, user_props: Any = None) -> None:
+ user_ctx.set(user_id)
+ user_props_ctx.set(user_props)
+
+ def __enter__(self) -> Any:
+ pass
+
+ def __exit__(self, exc_type: Any, exc_value: Any, exc_tb: Any) -> Any:
+ user_ctx.set(None)
+ user_props_ctx.set(None)
+
+
+def identify(user_id: str, user_props: Any = None) -> UserContextManager:
+ """Builds an LLMonitor UserContextManager
+
+ Parameters:
+ - `user_id`: The user id.
+ - `user_props`: The user properties.
+
+ Returns:
+ A context manager that sets the user context.
+ """
+ return UserContextManager(user_id, user_props)
+
+
+def _serialize(obj: Any) -> Union[Dict[str, Any], List[Any], Any]:
+ if hasattr(obj, "to_json"):
+ return obj.to_json()
+
+ if isinstance(obj, dict):
+ return {key: _serialize(value) for key, value in obj.items()}
+
+ if isinstance(obj, list):
+ return [_serialize(element) for element in obj]
+
+ return obj
+
+
+def _parse_input(raw_input: Any) -> Any:
+ if not raw_input:
+ return None
+
+ # if it's an array of 1, just parse the first element
+ if isinstance(raw_input, list) and len(raw_input) == 1:
+ return _parse_input(raw_input[0])
+
+ if not isinstance(raw_input, dict):
+ return _serialize(raw_input)
+
+ input_value = raw_input.get("input")
+ inputs_value = raw_input.get("inputs")
+ question_value = raw_input.get("question")
+ query_value = raw_input.get("query")
+
+ if input_value:
+ return input_value
+ if inputs_value:
+ return inputs_value
+ if question_value:
+ return question_value
+ if query_value:
+ return query_value
+
+ return _serialize(raw_input)
+
+
+def _parse_output(raw_output: dict) -> Any:
+ if not raw_output:
+ return None
+
+ if not isinstance(raw_output, dict):
+ return _serialize(raw_output)
+
+ text_value = raw_output.get("text")
+ output_value = raw_output.get("output")
+ output_text_value = raw_output.get("output_text")
+ answer_value = raw_output.get("answer")
+ result_value = raw_output.get("result")
+
+ if text_value:
+ return text_value
+ if answer_value:
+ return answer_value
+ if output_value:
+ return output_value
+ if output_text_value:
+ return output_text_value
+ if result_value:
+ return result_value
+
+ return _serialize(raw_output)
+
+
+def _parse_lc_role(
+ role: str,
+) -> str:
+ if role == "human":
+ return "user"
+ else:
+ return role
+
+
+def _get_user_id(metadata: Any) -> Any:
+ if user_ctx.get() is not None:
+ return user_ctx.get()
+
+ metadata = metadata or {}
+ user_id = metadata.get("user_id")
+ if user_id is None:
+ user_id = metadata.get("userId") # legacy, to delete in the future
+ return user_id
+
+
+def _get_user_props(metadata: Any) -> Any:
+ if user_props_ctx.get() is not None:
+ return user_props_ctx.get()
+
+ metadata = metadata or {}
+ return metadata.get("user_props", None)
+
+
+def _parse_lc_message(message: BaseMessage) -> Dict[str, Any]:
+ keys = ["function_call", "tool_calls", "tool_call_id", "name"]
+ parsed = {"text": message.content, "role": _parse_lc_role(message.type)}
+ parsed.update(
+ {
+ key: cast(Any, message.additional_kwargs.get(key))
+ for key in keys
+ if message.additional_kwargs.get(key) is not None
+ }
+ )
+ return parsed
+
+
+def _parse_lc_messages(messages: Union[List[BaseMessage], Any]) -> List[Dict[str, Any]]:
+ return [_parse_lc_message(message) for message in messages]
+
+
+class LLMonitorCallbackHandler(BaseCallbackHandler):
+ """Callback Handler for LLMonitor`.
+
+ #### Parameters:
+ - `app_id`: The app id of the app you want to report to. Defaults to
+ `None`, which means that `LLMONITOR_APP_ID` will be used.
+ - `api_url`: The url of the LLMonitor API. Defaults to `None`,
+ which means that either `LLMONITOR_API_URL` environment variable
+ or `https://app.llmonitor.com` will be used.
+
+ #### Raises:
+ - `ValueError`: if `app_id` is not provided either as an
+ argument or as an environment variable.
+ - `ConnectionError`: if the connection to the API fails.
+
+
+ #### Example:
+ ```python
+ from langchain_community.llms import OpenAI
+ from langchain_community.callbacks import LLMonitorCallbackHandler
+
+ llmonitor_callback = LLMonitorCallbackHandler()
+ llm = OpenAI(callbacks=[llmonitor_callback],
+ metadata={"userId": "user-123"})
+ llm.invoke("Hello, how are you?")
+ ```
+ """
+
+ __api_url: str
+ __app_id: str
+ __verbose: bool
+ __llmonitor_version: str
+ __has_valid_config: bool
+
+ def __init__(
+ self,
+ app_id: Union[str, None] = None,
+ api_url: Union[str, None] = None,
+ verbose: bool = False,
+ ) -> None:
+ super().__init__()
+
+ self.__has_valid_config = True
+
+ try:
+ import llmonitor
+
+ self.__llmonitor_version = importlib.metadata.version("llmonitor")
+ self.__track_event = llmonitor.track_event
+
+ except ImportError:
+ logger.warning(
+ """[LLMonitor] To use the LLMonitor callback handler you need to
+ have the `llmonitor` Python package installed. Please install it
+ with `pip install llmonitor`"""
+ )
+ self.__has_valid_config = False
+ return
+
+ if parse(self.__llmonitor_version) < parse("0.0.32"):
+ logger.warning(
+ f"""[LLMonitor] The installed `llmonitor` version is
+ {self.__llmonitor_version}
+ but `LLMonitorCallbackHandler` requires at least version 0.0.32
+ upgrade `llmonitor` with `pip install --upgrade llmonitor`"""
+ )
+ self.__has_valid_config = False
+
+ self.__has_valid_config = True
+
+ self.__api_url = api_url or os.getenv("LLMONITOR_API_URL") or DEFAULT_API_URL
+ self.__verbose = verbose or bool(os.getenv("LLMONITOR_VERBOSE"))
+
+ _app_id = app_id or os.getenv("LLMONITOR_APP_ID")
+ if _app_id is None:
+ logger.warning(
+ """[LLMonitor] app_id must be provided either as an argument or
+ as an environment variable"""
+ )
+ self.__has_valid_config = False
+ else:
+ self.__app_id = _app_id
+
+ if self.__has_valid_config is False:
+ return None
+
+ try:
+ res = requests.get(f"{self.__api_url}/api/app/{self.__app_id}")
+ if not res.ok:
+ raise ConnectionError()
+ except Exception:
+ logger.warning(
+ f"""[LLMonitor] Could not connect to the LLMonitor API at
+ {self.__api_url}"""
+ )
+
+ def on_llm_start(
+ self,
+ serialized: Dict[str, Any],
+ prompts: List[str],
+ *,
+ run_id: UUID,
+ parent_run_id: Union[UUID, None] = None,
+ tags: Union[List[str], None] = None,
+ metadata: Union[Dict[str, Any], None] = None,
+ **kwargs: Any,
+ ) -> None:
+ if self.__has_valid_config is False:
+ return
+ try:
+ user_id = _get_user_id(metadata)
+ user_props = _get_user_props(metadata)
+
+ params = kwargs.get("invocation_params", {})
+ params.update(
+ serialized.get("kwargs", {})
+ ) # Sometimes, for example with ChatAnthropic, `invocation_params` is empty
+
+ name = (
+ params.get("model")
+ or params.get("model_name")
+ or params.get("model_id")
+ )
+
+ if not name and "anthropic" in params.get("_type"):
+ name = "claude-2"
+
+ extra = {
+ param: params.get(param)
+ for param in PARAMS_TO_CAPTURE
+ if params.get(param) is not None
+ }
+
+ input = _parse_input(prompts)
+
+ self.__track_event(
+ "llm",
+ "start",
+ user_id=user_id,
+ run_id=str(run_id),
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
+ name=name,
+ input=input,
+ tags=tags,
+ extra=extra,
+ metadata=metadata,
+ user_props=user_props,
+ app_id=self.__app_id,
+ )
+ except Exception as e:
+ warnings.warn(f"[LLMonitor] An error occurred in on_llm_start: {e}")
+
+ def on_chat_model_start(
+ self,
+ serialized: Dict[str, Any],
+ messages: List[List[BaseMessage]],
+ *,
+ run_id: UUID,
+ parent_run_id: Union[UUID, None] = None,
+ tags: Union[List[str], None] = None,
+ metadata: Union[Dict[str, Any], None] = None,
+ **kwargs: Any,
+ ) -> Any:
+ if self.__has_valid_config is False:
+ return
+
+ try:
+ user_id = _get_user_id(metadata)
+ user_props = _get_user_props(metadata)
+
+ params = kwargs.get("invocation_params", {})
+ params.update(
+ serialized.get("kwargs", {})
+ ) # Sometimes, for example with ChatAnthropic, `invocation_params` is empty
+
+ name = (
+ params.get("model")
+ or params.get("model_name")
+ or params.get("model_id")
+ )
+
+ if not name and "anthropic" in params.get("_type"):
+ name = "claude-2"
+
+ extra = {
+ param: params.get(param)
+ for param in PARAMS_TO_CAPTURE
+ if params.get(param) is not None
+ }
+
+ input = _parse_lc_messages(messages[0])
+
+ self.__track_event(
+ "llm",
+ "start",
+ user_id=user_id,
+ run_id=str(run_id),
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
+ name=name,
+ input=input,
+ tags=tags,
+ extra=extra,
+ metadata=metadata,
+ user_props=user_props,
+ app_id=self.__app_id,
+ )
+ except Exception as e:
+ logger.error(f"[LLMonitor] An error occurred in on_chat_model_start: {e}")
+
+ def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: Union[UUID, None] = None,
+ **kwargs: Any,
+ ) -> None:
+ if self.__has_valid_config is False:
+ return
+
+ try:
+ token_usage = (response.llm_output or {}).get("token_usage", {})
+
+ parsed_output: Any = [
+ _parse_lc_message(generation.message)
+ if hasattr(generation, "message")
+ else generation.text
+ for generation in response.generations[0]
+ ]
+
+ # if it's an array of 1, just parse the first element
+ if len(parsed_output) == 1:
+ parsed_output = parsed_output[0]
+
+ self.__track_event(
+ "llm",
+ "end",
+ run_id=str(run_id),
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
+ output=parsed_output,
+ token_usage={
+ "prompt": token_usage.get("prompt_tokens"),
+ "completion": token_usage.get("completion_tokens"),
+ },
+ app_id=self.__app_id,
+ )
+ except Exception as e:
+ logger.error(f"[LLMonitor] An error occurred in on_llm_end: {e}")
+
+ def on_tool_start(
+ self,
+ serialized: Dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ parent_run_id: Union[UUID, None] = None,
+ tags: Union[List[str], None] = None,
+ metadata: Union[Dict[str, Any], None] = None,
+ **kwargs: Any,
+ ) -> None:
+ if self.__has_valid_config is False:
+ return
+ try:
+ user_id = _get_user_id(metadata)
+ user_props = _get_user_props(metadata)
+ name = serialized.get("name")
+
+ self.__track_event(
+ "tool",
+ "start",
+ user_id=user_id,
+ run_id=str(run_id),
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
+ name=name,
+ input=input_str,
+ tags=tags,
+ metadata=metadata,
+ user_props=user_props,
+ app_id=self.__app_id,
+ )
+ except Exception as e:
+ logger.error(f"[LLMonitor] An error occurred in on_tool_start: {e}")
+
+ def on_tool_end(
+ self,
+ output: Any,
+ *,
+ run_id: UUID,
+ parent_run_id: Union[UUID, None] = None,
+ tags: Union[List[str], None] = None,
+ **kwargs: Any,
+ ) -> None:
+ output = str(output)
+ if self.__has_valid_config is False:
+ return
+ try:
+ self.__track_event(
+ "tool",
+ "end",
+ run_id=str(run_id),
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
+ output=output,
+ app_id=self.__app_id,
+ )
+ except Exception as e:
+ logger.error(f"[LLMonitor] An error occurred in on_tool_end: {e}")
+
+ def on_chain_start(
+ self,
+ serialized: Dict[str, Any],
+ inputs: Dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: Union[UUID, None] = None,
+ tags: Union[List[str], None] = None,
+ metadata: Union[Dict[str, Any], None] = None,
+ **kwargs: Any,
+ ) -> Any:
+ if self.__has_valid_config is False:
+ return
+ try:
+ name = serialized.get("id", [None, None, None, None])[3]
+ type = "chain"
+ metadata = metadata or {}
+
+ agentName = metadata.get("agent_name")
+ if agentName is None:
+ agentName = metadata.get("agentName")
+
+ if name == "AgentExecutor" or name == "PlanAndExecute":
+ type = "agent"
+ if agentName is not None:
+ type = "agent"
+ name = agentName
+ if parent_run_id is not None:
+ type = "chain"
+
+ user_id = _get_user_id(metadata)
+ user_props = _get_user_props(metadata)
+ input = _parse_input(inputs)
+
+ self.__track_event(
+ type,
+ "start",
+ user_id=user_id,
+ run_id=str(run_id),
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
+ name=name,
+ input=input,
+ tags=tags,
+ metadata=metadata,
+ user_props=user_props,
+ app_id=self.__app_id,
+ )
+ except Exception as e:
+ logger.error(f"[LLMonitor] An error occurred in on_chain_start: {e}")
+
+ def on_chain_end(
+ self,
+ outputs: Dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: Union[UUID, None] = None,
+ **kwargs: Any,
+ ) -> Any:
+ if self.__has_valid_config is False:
+ return
+ try:
+ output = _parse_output(outputs)
+
+ self.__track_event(
+ "chain",
+ "end",
+ run_id=str(run_id),
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
+ output=output,
+ app_id=self.__app_id,
+ )
+ except Exception as e:
+ logger.error(f"[LLMonitor] An error occurred in on_chain_end: {e}")
+
+ def on_agent_action(
+ self,
+ action: AgentAction,
+ *,
+ run_id: UUID,
+ parent_run_id: Union[UUID, None] = None,
+ **kwargs: Any,
+ ) -> Any:
+ if self.__has_valid_config is False:
+ return
+ try:
+ name = action.tool
+ input = _parse_input(action.tool_input)
+
+ self.__track_event(
+ "tool",
+ "start",
+ run_id=str(run_id),
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
+ name=name,
+ input=input,
+ app_id=self.__app_id,
+ )
+ except Exception as e:
+ logger.error(f"[LLMonitor] An error occurred in on_agent_action: {e}")
+
+ def on_agent_finish(
+ self,
+ finish: AgentFinish,
+ *,
+ run_id: UUID,
+ parent_run_id: Union[UUID, None] = None,
+ **kwargs: Any,
+ ) -> Any:
+ if self.__has_valid_config is False:
+ return
+ try:
+ output = _parse_output(finish.return_values)
+
+ self.__track_event(
+ "agent",
+ "end",
+ run_id=str(run_id),
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
+ output=output,
+ app_id=self.__app_id,
+ )
+ except Exception as e:
+ logger.error(f"[LLMonitor] An error occurred in on_agent_finish: {e}")
+
+ def on_chain_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: Union[UUID, None] = None,
+ **kwargs: Any,
+ ) -> Any:
+ if self.__has_valid_config is False:
+ return
+ try:
+ self.__track_event(
+ "chain",
+ "error",
+ run_id=str(run_id),
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
+ error={"message": str(error), "stack": traceback.format_exc()},
+ app_id=self.__app_id,
+ )
+ except Exception as e:
+ logger.error(f"[LLMonitor] An error occurred in on_chain_error: {e}")
+
+ def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: Union[UUID, None] = None,
+ **kwargs: Any,
+ ) -> Any:
+ if self.__has_valid_config is False:
+ return
+ try:
+ self.__track_event(
+ "tool",
+ "error",
+ run_id=str(run_id),
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
+ error={"message": str(error), "stack": traceback.format_exc()},
+ app_id=self.__app_id,
+ )
+ except Exception as e:
+ logger.error(f"[LLMonitor] An error occurred in on_tool_error: {e}")
+
+ def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: Union[UUID, None] = None,
+ **kwargs: Any,
+ ) -> Any:
+ if self.__has_valid_config is False:
+ return
+ try:
+ self.__track_event(
+ "llm",
+ "error",
+ run_id=str(run_id),
+ parent_run_id=str(parent_run_id) if parent_run_id else None,
+ error={"message": str(error), "stack": traceback.format_exc()},
+ app_id=self.__app_id,
+ )
+ except Exception as e:
+ logger.error(f"[LLMonitor] An error occurred in on_llm_error: {e}")
+
+
+__all__ = ["LLMonitorCallbackHandler", "identify"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/manager.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e8d052560602046cb95c46e86519753ec9f2770
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/manager.py
@@ -0,0 +1,104 @@
+from __future__ import annotations
+
+import logging
+from contextlib import contextmanager
+from contextvars import ContextVar
+from typing import (
+ Generator,
+ Optional,
+)
+
+from langchain_core.tracers.context import register_configure_hook
+
+from langchain_community.callbacks.bedrock_anthropic_callback import (
+ BedrockAnthropicTokenUsageCallbackHandler,
+)
+from langchain_community.callbacks.openai_info import OpenAICallbackHandler
+from langchain_community.callbacks.tracers.comet import CometTracer
+from langchain_community.callbacks.tracers.wandb import WandbTracer
+
+logger = logging.getLogger(__name__)
+
+openai_callback_var: ContextVar[Optional[OpenAICallbackHandler]] = ContextVar(
+ "openai_callback", default=None
+)
+bedrock_anthropic_callback_var: (ContextVar)[
+ Optional[BedrockAnthropicTokenUsageCallbackHandler]
+] = ContextVar("bedrock_anthropic_callback", default=None)
+wandb_tracing_callback_var: ContextVar[Optional[WandbTracer]] = ContextVar(
+ "tracing_wandb_callback", default=None
+)
+comet_tracing_callback_var: ContextVar[Optional[CometTracer]] = ContextVar(
+ "tracing_comet_callback", default=None
+)
+
+register_configure_hook(openai_callback_var, True)
+register_configure_hook(bedrock_anthropic_callback_var, True)
+register_configure_hook(
+ wandb_tracing_callback_var, True, WandbTracer, "LANGCHAIN_WANDB_TRACING"
+)
+register_configure_hook(
+ comet_tracing_callback_var, True, CometTracer, "LANGCHAIN_COMET_TRACING"
+)
+
+
+@contextmanager
+def get_openai_callback() -> Generator[OpenAICallbackHandler, None, None]:
+ """Get the OpenAI callback handler in a context manager.
+ which conveniently exposes token and cost information.
+
+ Returns:
+ OpenAICallbackHandler: The OpenAI callback handler.
+
+ Example:
+ >>> with get_openai_callback() as cb:
+ ... # Use the OpenAI callback handler
+ """
+ cb = OpenAICallbackHandler()
+ openai_callback_var.set(cb)
+ yield cb
+ openai_callback_var.set(None)
+
+
+@contextmanager
+def get_bedrock_anthropic_callback() -> Generator[
+ BedrockAnthropicTokenUsageCallbackHandler, None, None
+]:
+ """Get the Bedrock anthropic callback handler in a context manager.
+ which conveniently exposes token and cost information.
+
+ Returns:
+ BedrockAnthropicTokenUsageCallbackHandler:
+ The Bedrock anthropic callback handler.
+
+ Example:
+ >>> with get_bedrock_anthropic_callback() as cb:
+ ... # Use the Bedrock anthropic callback handler
+ """
+ cb = BedrockAnthropicTokenUsageCallbackHandler()
+ bedrock_anthropic_callback_var.set(cb)
+ yield cb
+ bedrock_anthropic_callback_var.set(None)
+
+
+@contextmanager
+def wandb_tracing_enabled(
+ session_name: str = "default",
+) -> Generator[None, None, None]:
+ """Get the WandbTracer in a context manager.
+
+ Args:
+ session_name (str, optional): The name of the session.
+ Defaults to "default".
+
+ Returns:
+ None
+
+ Example:
+ >>> with wandb_tracing_enabled() as session:
+ ... # Use the WandbTracer session
+ """
+ cb = WandbTracer()
+ wandb_tracing_callback_var.set(cb)
+ yield None
+ wandb_tracing_callback_var.set(None)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/mlflow_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/mlflow_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..e061405d211850eb17d96b561682d71e52997a29
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/mlflow_callback.py
@@ -0,0 +1,769 @@
+import logging
+import os
+import random
+import string
+import tempfile
+import traceback
+from copy import deepcopy
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Sequence, Union
+
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.documents import Document
+from langchain_core.outputs import LLMResult
+from langchain_core.utils import get_from_dict_or_env, guard_import
+
+from langchain_community.callbacks.utils import (
+ BaseMetadataCallbackHandler,
+ flatten_dict,
+ hash_string,
+ import_pandas,
+ import_spacy,
+ import_textstat,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def import_mlflow() -> Any:
+ """Import the mlflow python package and raise an error if it is not installed."""
+ return guard_import("mlflow")
+
+
+def mlflow_callback_metrics() -> List[str]:
+ """Get the metrics to log to MLFlow."""
+ return [
+ "step",
+ "starts",
+ "ends",
+ "errors",
+ "text_ctr",
+ "chain_starts",
+ "chain_ends",
+ "llm_starts",
+ "llm_ends",
+ "llm_streams",
+ "tool_starts",
+ "tool_ends",
+ "agent_ends",
+ "retriever_starts",
+ "retriever_ends",
+ ]
+
+
+def get_text_complexity_metrics() -> List[str]:
+ """Get the text complexity metrics from textstat."""
+ return [
+ "flesch_reading_ease",
+ "flesch_kincaid_grade",
+ "smog_index",
+ "coleman_liau_index",
+ "automated_readability_index",
+ "dale_chall_readability_score",
+ "difficult_words",
+ "linsear_write_formula",
+ "gunning_fog",
+ # "text_standard"
+ "fernandez_huerta",
+ "szigriszt_pazos",
+ "gutierrez_polini",
+ "crawford",
+ "gulpease_index",
+ "osman",
+ ]
+
+
+def analyze_text(
+ text: str,
+ nlp: Any = None,
+ textstat: Any = None,
+) -> dict:
+ """Analyze text using textstat and spacy.
+
+ Parameters:
+ text (str): The text to analyze.
+ nlp (spacy.lang): The spacy language model to use for visualization.
+ textstat: The textstat library to use for complexity metrics calculation.
+
+ Returns:
+ `dict` containing the complexity metrics and visualization
+ files serialized to HTML string.
+ """
+ resp: Dict[str, Any] = {}
+ if textstat is not None:
+ text_complexity_metrics = {
+ key: getattr(textstat, key)(text) for key in get_text_complexity_metrics()
+ }
+ resp.update({"text_complexity_metrics": text_complexity_metrics})
+ resp.update(text_complexity_metrics)
+
+ if nlp is not None:
+ spacy = import_spacy()
+ doc = nlp(text)
+
+ dep_out = spacy.displacy.render(doc, style="dep", jupyter=False, page=True)
+
+ ent_out = spacy.displacy.render(doc, style="ent", jupyter=False, page=True)
+
+ text_visualizations = {
+ "dependency_tree": dep_out,
+ "entities": ent_out,
+ }
+
+ resp.update(text_visualizations)
+
+ return resp
+
+
+def construct_html_from_prompt_and_generation(prompt: str, generation: str) -> Any:
+ """Construct an html element from a prompt and a generation.
+
+ Parameters:
+ prompt (str): The prompt.
+ generation (str): The generation.
+
+ Returns:
+ (str): The html string."""
+ formatted_prompt = prompt.replace("\n", "
")
+ formatted_generation = generation.replace("\n", "
")
+
+ return f"""
+ {formatted_prompt}:
+
+
+ {formatted_generation}
+
+
+ """
+
+
+class MlflowLogger:
+ """Callback Handler that logs metrics and artifacts to mlflow server.
+
+ Parameters:
+ name (str): Name of the run.
+ experiment (str): Name of the experiment.
+ tags (dict): Tags to be attached for the run.
+ tracking_uri (str): MLflow tracking server uri.
+
+ This handler implements the helper functions to initialize,
+ log metrics and artifacts to the mlflow server.
+ """
+
+ def __init__(self, **kwargs: Any):
+ self.mlflow = import_mlflow()
+ if "DATABRICKS_RUNTIME_VERSION" in os.environ:
+ self.mlflow.set_tracking_uri("databricks")
+ self.mlf_expid = self.mlflow.tracking.fluent._get_experiment_id()
+ self.mlf_exp = self.mlflow.get_experiment(self.mlf_expid)
+ else:
+ tracking_uri = get_from_dict_or_env(
+ kwargs, "tracking_uri", "MLFLOW_TRACKING_URI", ""
+ )
+ self.mlflow.set_tracking_uri(tracking_uri)
+
+ if run_id := kwargs.get("run_id"):
+ self.mlf_expid = self.mlflow.get_run(run_id).info.experiment_id
+ else:
+ # User can set other env variables described here
+ # > https://www.mlflow.org/docs/latest/tracking.html#logging-to-a-tracking-server
+
+ experiment_name = get_from_dict_or_env(
+ kwargs, "experiment_name", "MLFLOW_EXPERIMENT_NAME"
+ )
+ self.mlf_exp = self.mlflow.get_experiment_by_name(experiment_name)
+ if self.mlf_exp is not None:
+ self.mlf_expid = self.mlf_exp.experiment_id
+ else:
+ self.mlf_expid = self.mlflow.create_experiment(experiment_name)
+
+ self.start_run(
+ kwargs["run_name"], kwargs["run_tags"], kwargs.get("run_id", None)
+ )
+ self.dir = kwargs.get("artifacts_dir", "")
+
+ def start_run(
+ self, name: str, tags: Dict[str, str], run_id: Optional[str] = None
+ ) -> None:
+ """
+ If run_id is provided, it will reuse the run with the given run_id.
+ Otherwise, it starts a new run, auto generates the random suffix for name.
+ """
+ if run_id is None:
+ if name.endswith("-%"):
+ rname = "".join(
+ random.choices(string.ascii_uppercase + string.digits, k=7)
+ )
+ name = name[:-1] + rname
+ run = self.mlflow.MlflowClient().create_run(
+ self.mlf_expid, run_name=name, tags=tags
+ )
+ run_id = run.info.run_id
+ self.run_id = run_id
+
+ def finish_run(self) -> None:
+ """To finish the run."""
+ self.mlflow.end_run()
+
+ def metric(self, key: str, value: float) -> None:
+ """To log metric to mlflow server."""
+ self.mlflow.log_metric(key, value, run_id=self.run_id)
+
+ def metrics(
+ self, data: Union[Dict[str, float], Dict[str, int]], step: Optional[int] = 0
+ ) -> None:
+ """To log all metrics in the input dict."""
+ self.mlflow.log_metrics(data, run_id=self.run_id)
+
+ def jsonf(self, data: Dict[str, Any], filename: str) -> None:
+ """To log the input data as json file artifact."""
+ self.mlflow.log_dict(
+ data, os.path.join(self.dir, f"{filename}.json"), run_id=self.run_id
+ )
+
+ def table(self, name: str, dataframe: Any) -> None:
+ """To log the input pandas dataframe as a html table"""
+ self.html(dataframe.to_html(), f"table_{name}")
+
+ def html(self, html: str, filename: str) -> None:
+ """To log the input html string as html file artifact."""
+ self.mlflow.log_text(
+ html, os.path.join(self.dir, f"{filename}.html"), run_id=self.run_id
+ )
+
+ def text(self, text: str, filename: str) -> None:
+ """To log the input text as text file artifact."""
+ self.mlflow.log_text(
+ text, os.path.join(self.dir, f"{filename}.txt"), run_id=self.run_id
+ )
+
+ def artifact(self, path: str) -> None:
+ """To upload the file from given path as artifact."""
+ self.mlflow.log_artifact(path, run_id=self.run_id)
+
+ def langchain_artifact(self, chain: Any) -> None:
+ self.mlflow.langchain.log_model(chain, "langchain-model", run_id=self.run_id)
+
+
+class MlflowCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
+ """Callback Handler that logs metrics and artifacts to mlflow server.
+
+ Parameters:
+ name (str): Name of the run.
+ experiment (str): Name of the experiment.
+ tags (dict): Tags to be attached for the run.
+ tracking_uri (str): MLflow tracking server uri.
+
+ This handler will utilize the associated callback method called and formats
+ the input of each callback function with metadata regarding the state of LLM run,
+ and adds the response to the list of records for both the {method}_records and
+ action. It then logs the response to mlflow server.
+ """
+
+ def __init__(
+ self,
+ name: Optional[str] = "langchainrun-%",
+ experiment: Optional[str] = "langchain",
+ tags: Optional[Dict] = None,
+ tracking_uri: Optional[str] = None,
+ run_id: Optional[str] = None,
+ artifacts_dir: str = "",
+ ) -> None:
+ """Initialize callback handler."""
+ import_pandas()
+ import_mlflow()
+ super().__init__()
+
+ self.name = name
+ self.experiment = experiment
+ self.tags = tags or {}
+ self.tracking_uri = tracking_uri
+ self.run_id = run_id
+ self.artifacts_dir = artifacts_dir
+
+ self.temp_dir = tempfile.TemporaryDirectory()
+
+ self.mlflg = MlflowLogger(
+ tracking_uri=self.tracking_uri,
+ experiment_name=self.experiment,
+ run_name=self.name,
+ run_tags=self.tags,
+ run_id=self.run_id,
+ artifacts_dir=self.artifacts_dir,
+ )
+
+ self.action_records: list = []
+ self.nlp = None
+ try:
+ spacy = import_spacy()
+ except ImportError as e:
+ logger.warning(e.msg)
+ else:
+ try:
+ self.nlp = spacy.load("en_core_web_sm")
+ except OSError:
+ logger.warning(
+ "Run `python -m spacy download en_core_web_sm` "
+ "to download en_core_web_sm model for text visualization."
+ )
+
+ try:
+ self.textstat = import_textstat()
+ except ImportError as e:
+ logger.warning(e.msg)
+ self.textstat = None
+
+ self.metrics = {key: 0 for key in mlflow_callback_metrics()}
+
+ self.records: Dict[str, Any] = {
+ "on_llm_start_records": [],
+ "on_llm_token_records": [],
+ "on_llm_end_records": [],
+ "on_chain_start_records": [],
+ "on_chain_end_records": [],
+ "on_tool_start_records": [],
+ "on_tool_end_records": [],
+ "on_text_records": [],
+ "on_agent_finish_records": [],
+ "on_agent_action_records": [],
+ "on_retriever_start_records": [],
+ "on_retriever_end_records": [],
+ "action_records": [],
+ }
+
+ def _reset(self) -> None:
+ for k, v in self.metrics.items():
+ self.metrics[k] = 0
+ for k, v in self.records.items():
+ self.records[k] = []
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Run when LLM starts."""
+ self.metrics["step"] += 1
+ self.metrics["llm_starts"] += 1
+ self.metrics["starts"] += 1
+
+ llm_starts = self.metrics["llm_starts"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_llm_start"})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.metrics)
+
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
+
+ for idx, prompt in enumerate(prompts):
+ prompt_resp = deepcopy(resp)
+ prompt_resp["prompt"] = prompt
+ self.records["on_llm_start_records"].append(prompt_resp)
+ self.records["action_records"].append(prompt_resp)
+ self.mlflg.jsonf(prompt_resp, f"llm_start_{llm_starts}_prompt_{idx}")
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Run when LLM generates a new token."""
+ self.metrics["step"] += 1
+ self.metrics["llm_streams"] += 1
+
+ llm_streams = self.metrics["llm_streams"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_llm_new_token", "token": token})
+ resp.update(self.metrics)
+
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
+
+ self.records["on_llm_token_records"].append(resp)
+ self.records["action_records"].append(resp)
+ self.mlflg.jsonf(resp, f"llm_new_tokens_{llm_streams}")
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running."""
+ self.metrics["step"] += 1
+ self.metrics["llm_ends"] += 1
+ self.metrics["ends"] += 1
+
+ llm_ends = self.metrics["llm_ends"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_llm_end"})
+ resp.update(flatten_dict(response.llm_output or {}))
+ resp.update(self.metrics)
+
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
+
+ for generations in response.generations:
+ for idx, generation in enumerate(generations):
+ generation_resp = deepcopy(resp)
+ generation_resp.update(flatten_dict(generation.dict()))
+ generation_resp.update(
+ analyze_text(
+ generation.text,
+ nlp=self.nlp,
+ textstat=self.textstat,
+ )
+ )
+ if "text_complexity_metrics" in generation_resp:
+ complexity_metrics: Dict[str, float] = generation_resp.pop(
+ "text_complexity_metrics"
+ )
+ self.mlflg.metrics(
+ complexity_metrics,
+ step=self.metrics["step"],
+ )
+ self.records["on_llm_end_records"].append(generation_resp)
+ self.records["action_records"].append(generation_resp)
+ self.mlflg.jsonf(resp, f"llm_end_{llm_ends}_generation_{idx}")
+ if "dependency_tree" in generation_resp:
+ dependency_tree = generation_resp["dependency_tree"]
+ self.mlflg.html(
+ dependency_tree, "dep-" + hash_string(generation.text)
+ )
+ if "entities" in generation_resp:
+ entities = generation_resp["entities"]
+ self.mlflg.html(entities, "ent-" + hash_string(generation.text))
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when LLM errors."""
+ self.metrics["step"] += 1
+ self.metrics["errors"] += 1
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Run when chain starts running."""
+ self.metrics["step"] += 1
+ self.metrics["chain_starts"] += 1
+ self.metrics["starts"] += 1
+
+ chain_starts = self.metrics["chain_starts"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_chain_start"})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.metrics)
+
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
+
+ if isinstance(inputs, dict):
+ chain_input = ",".join([f"{k}={v}" for k, v in inputs.items()])
+ elif isinstance(inputs, list):
+ chain_input = ",".join([str(input) for input in inputs])
+ else:
+ chain_input = str(inputs)
+ input_resp = deepcopy(resp)
+ input_resp["inputs"] = chain_input
+ self.records["on_chain_start_records"].append(input_resp)
+ self.records["action_records"].append(input_resp)
+ self.mlflg.jsonf(input_resp, f"chain_start_{chain_starts}")
+
+ def on_chain_end(
+ self, outputs: Union[Dict[str, Any], str, List[str]], **kwargs: Any
+ ) -> None:
+ """Run when chain ends running."""
+ self.metrics["step"] += 1
+ self.metrics["chain_ends"] += 1
+ self.metrics["ends"] += 1
+
+ chain_ends = self.metrics["chain_ends"]
+
+ resp: Dict[str, Any] = {}
+ if isinstance(outputs, dict):
+ chain_output = ",".join([f"{k}={v}" for k, v in outputs.items()])
+ elif isinstance(outputs, list):
+ chain_output = ",".join(map(str, outputs))
+ else:
+ chain_output = str(outputs)
+ resp.update({"action": "on_chain_end", "outputs": chain_output})
+ resp.update(self.metrics)
+
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
+
+ self.records["on_chain_end_records"].append(resp)
+ self.records["action_records"].append(resp)
+ self.mlflg.jsonf(resp, f"chain_end_{chain_ends}")
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when chain errors."""
+ self.metrics["step"] += 1
+ self.metrics["errors"] += 1
+
+ def on_tool_start(
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
+ ) -> None:
+ """Run when tool starts running."""
+ self.metrics["step"] += 1
+ self.metrics["tool_starts"] += 1
+ self.metrics["starts"] += 1
+
+ tool_starts = self.metrics["tool_starts"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_tool_start", "input_str": input_str})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.metrics)
+
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
+
+ self.records["on_tool_start_records"].append(resp)
+ self.records["action_records"].append(resp)
+ self.mlflg.jsonf(resp, f"tool_start_{tool_starts}")
+
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
+ """Run when tool ends running."""
+ output = str(output)
+ self.metrics["step"] += 1
+ self.metrics["tool_ends"] += 1
+ self.metrics["ends"] += 1
+
+ tool_ends = self.metrics["tool_ends"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_tool_end", "output": output})
+ resp.update(self.metrics)
+
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
+
+ self.records["on_tool_end_records"].append(resp)
+ self.records["action_records"].append(resp)
+ self.mlflg.jsonf(resp, f"tool_end_{tool_ends}")
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when tool errors."""
+ self.metrics["step"] += 1
+ self.metrics["errors"] += 1
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """
+ Run when text is received.
+ """
+ self.metrics["step"] += 1
+ self.metrics["text_ctr"] += 1
+
+ text_ctr = self.metrics["text_ctr"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_text", "text": text})
+ resp.update(self.metrics)
+
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
+
+ self.records["on_text_records"].append(resp)
+ self.records["action_records"].append(resp)
+ self.mlflg.jsonf(resp, f"on_text_{text_ctr}")
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run when agent ends running."""
+ self.metrics["step"] += 1
+ self.metrics["agent_ends"] += 1
+ self.metrics["ends"] += 1
+
+ agent_ends = self.metrics["agent_ends"]
+ resp: Dict[str, Any] = {}
+ resp.update(
+ {
+ "action": "on_agent_finish",
+ "output": finish.return_values["output"],
+ "log": finish.log,
+ }
+ )
+ resp.update(self.metrics)
+
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
+
+ self.records["on_agent_finish_records"].append(resp)
+ self.records["action_records"].append(resp)
+ self.mlflg.jsonf(resp, f"agent_finish_{agent_ends}")
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Run on agent action."""
+ self.metrics["step"] += 1
+ self.metrics["tool_starts"] += 1
+ self.metrics["starts"] += 1
+
+ tool_starts = self.metrics["tool_starts"]
+ resp: Dict[str, Any] = {}
+ resp.update(
+ {
+ "action": "on_agent_action",
+ "tool": action.tool,
+ "tool_input": action.tool_input,
+ "log": action.log,
+ }
+ )
+ resp.update(self.metrics)
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
+ self.records["on_agent_action_records"].append(resp)
+ self.records["action_records"].append(resp)
+ self.mlflg.jsonf(resp, f"agent_action_{tool_starts}")
+
+ def on_retriever_start(
+ self,
+ serialized: Dict[str, Any],
+ query: str,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when Retriever starts running."""
+ self.metrics["step"] += 1
+ self.metrics["retriever_starts"] += 1
+ self.metrics["starts"] += 1
+
+ retriever_starts = self.metrics["retriever_starts"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_retriever_start", "query": query})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.metrics)
+
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
+
+ self.records["on_retriever_start_records"].append(resp)
+ self.records["action_records"].append(resp)
+ self.mlflg.jsonf(resp, f"retriever_start_{retriever_starts}")
+
+ def on_retriever_end(
+ self,
+ documents: Sequence[Document],
+ **kwargs: Any,
+ ) -> Any:
+ """Run when Retriever ends running."""
+ self.metrics["step"] += 1
+ self.metrics["retriever_ends"] += 1
+ self.metrics["ends"] += 1
+
+ retriever_ends = self.metrics["retriever_ends"]
+
+ resp: Dict[str, Any] = {}
+ retriever_documents = [
+ {
+ "page_content": doc.page_content,
+ "metadata": {
+ k: (
+ str(v)
+ if not isinstance(v, list)
+ else ",".join(str(x) for x in v)
+ )
+ for k, v in doc.metadata.items()
+ },
+ }
+ for doc in documents
+ ]
+ resp.update({"action": "on_retriever_end", "documents": retriever_documents})
+ resp.update(self.metrics)
+
+ self.mlflg.metrics(self.metrics, step=self.metrics["step"])
+
+ self.records["on_retriever_end_records"].append(resp)
+ self.records["action_records"].append(resp)
+ self.mlflg.jsonf(resp, f"retriever_end_{retriever_ends}")
+
+ def on_retriever_error(self, error: BaseException, **kwargs: Any) -> Any:
+ """Run when Retriever errors."""
+ self.metrics["step"] += 1
+ self.metrics["errors"] += 1
+
+ def _create_session_analysis_df(self) -> Any:
+ """Create a dataframe with all the information from the session."""
+ pd = import_pandas()
+ on_llm_start_records_df = pd.DataFrame(self.records["on_llm_start_records"])
+ on_llm_end_records_df = pd.DataFrame(self.records["on_llm_end_records"])
+
+ llm_input_columns = ["step", "prompt"]
+ if "name" in on_llm_start_records_df.columns:
+ llm_input_columns.append("name")
+ elif "id" in on_llm_start_records_df.columns:
+ # id is llm class's full import path. For example:
+ # ["langchain", "llms", "openai", "AzureOpenAI"]
+ on_llm_start_records_df["name"] = on_llm_start_records_df["id"].apply(
+ lambda id_: id_[-1]
+ )
+ llm_input_columns.append("name")
+ llm_input_prompts_df = (
+ on_llm_start_records_df[llm_input_columns]
+ .dropna(axis=1)
+ .rename({"step": "prompt_step"}, axis=1)
+ )
+ complexity_metrics_columns = (
+ get_text_complexity_metrics() if self.textstat is not None else []
+ )
+ visualizations_columns = (
+ ["dependency_tree", "entities"] if self.nlp is not None else []
+ )
+
+ token_usage_columns = [
+ "token_usage_total_tokens",
+ "token_usage_prompt_tokens",
+ "token_usage_completion_tokens",
+ ]
+ token_usage_columns = [
+ x for x in token_usage_columns if x in on_llm_end_records_df.columns
+ ]
+
+ llm_outputs_df = (
+ on_llm_end_records_df[
+ [
+ "step",
+ "text",
+ ]
+ + token_usage_columns
+ + complexity_metrics_columns
+ + visualizations_columns
+ ]
+ .dropna(axis=1)
+ .rename({"step": "output_step", "text": "output"}, axis=1)
+ )
+ session_analysis_df = pd.concat([llm_input_prompts_df, llm_outputs_df], axis=1)
+ session_analysis_df["chat_html"] = session_analysis_df[
+ ["prompt", "output"]
+ ].apply(
+ lambda row: construct_html_from_prompt_and_generation(
+ row["prompt"], row["output"]
+ ),
+ axis=1,
+ )
+ return session_analysis_df
+
+ def _contain_llm_records(self) -> bool:
+ return bool(self.records["on_llm_start_records"])
+
+ def flush_tracker(self, langchain_asset: Any = None, finish: bool = False) -> None:
+ pd = import_pandas()
+ self.mlflg.table("action_records", pd.DataFrame(self.records["action_records"]))
+ if self._contain_llm_records():
+ session_analysis_df = self._create_session_analysis_df()
+ chat_html = session_analysis_df.pop("chat_html")
+ chat_html = chat_html.replace("\n", "", regex=True)
+ self.mlflg.table("session_analysis", pd.DataFrame(session_analysis_df))
+ self.mlflg.html("".join(chat_html.tolist()), "chat_html")
+
+ if langchain_asset:
+ # To avoid circular import error
+ # mlflow only supports LLMChain asset
+ if "langchain.chains.llm.LLMChain" in str(type(langchain_asset)):
+ self.mlflg.langchain_artifact(langchain_asset)
+ else:
+ langchain_asset_path = str(Path(self.temp_dir.name, "model.json"))
+ try:
+ langchain_asset.save(langchain_asset_path)
+ self.mlflg.artifact(langchain_asset_path)
+ except ValueError:
+ try:
+ langchain_asset.save_agent(langchain_asset_path)
+ self.mlflg.artifact(langchain_asset_path)
+ except AttributeError:
+ print("Could not save model.") # noqa: T201
+ traceback.print_exc()
+ pass
+ except NotImplementedError:
+ print("Could not save model.") # noqa: T201
+ traceback.print_exc()
+ pass
+ except NotImplementedError:
+ print("Could not save model.") # noqa: T201
+ traceback.print_exc()
+ pass
+ if finish:
+ self.mlflg.finish_run()
+ self._reset()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/openai_info.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/openai_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..aec6ba28922c282b0b6240733386cfbbf7d99c59
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/openai_info.py
@@ -0,0 +1,555 @@
+"""Callback Handler that prints to std out."""
+
+import threading
+from enum import Enum, auto
+from typing import Any, Dict, List
+
+from langchain_core._api import warn_deprecated
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.messages import AIMessage
+from langchain_core.outputs import ChatGeneration, LLMResult
+
+MODEL_COST_PER_1K_TOKENS = {
+ # GPT-5 input
+ "gpt-5": 0.00125,
+ "gpt-5-cached": 0.000125,
+ "gpt-5-2025-08-07": 0.00125,
+ "gpt-5-2025-08-07-cached": 0.000125,
+ # GPT-5 output
+ "gpt-5-completion": 0.01,
+ "gpt-5-2025-08-07-completion": 0.01,
+ # GPT-5-mini input
+ "gpt-5-mini": 0.00025,
+ "gpt-5-mini-cached": 0.000025,
+ "gpt-5-mini-2025-08-07": 0.00025,
+ "gpt-5-mini-2025-08-07-cached": 0.000025,
+ # GPT-5-mini output
+ "gpt-5-mini-completion": 0.002,
+ "gpt-5-mini-2025-08-07-completion": 0.002,
+ # GPT-5-nano input
+ "gpt-5-nano": 0.00005,
+ "gpt-5-nano-cached": 0.000005,
+ "gpt-5-nano-2025-08-07": 0.00005,
+ "gpt-5-nano-2025-08-07-cached": 0.000005,
+ # GPT-5-nano output
+ "gpt-5-nano-completion": 0.0004,
+ "gpt-5-nano-2025-08-07-completion": 0.0004,
+ # GPT-5-chat-latest input
+ "gpt-5-chat-latest": 0.00125,
+ "gpt-5-chat-latest-cached": 0.000125,
+ "gpt-5-chat-latest-2025-08-07": 0.00125,
+ "gpt-5-chat-latest-2025-08-07-cached": 0.000125,
+ # GPT-5-chat-latest output
+ "gpt-5-chat-latest-completion": 0.01,
+ "gpt-5-chat-latest-2025-08-07-completion": 0.01,
+ # GPT-4.1 input
+ "gpt-4.1": 0.002,
+ "gpt-4.1-2025-04-14": 0.002,
+ "gpt-4.1-cached": 0.0005,
+ "gpt-4.1-2025-04-14-cached": 0.0005,
+ # GPT-4.1 output
+ "gpt-4.1-completion": 0.008,
+ "gpt-4.1-2025-04-14-completion": 0.008,
+ # GPT-4.1-mini input
+ "gpt-4.1-mini": 0.0004,
+ "gpt-4.1-mini-2025-04-14": 0.0004,
+ "gpt-4.1-mini-cached": 0.0001,
+ "gpt-4.1-mini-2025-04-14-cached": 0.0001,
+ # GPT-4.1-mini output
+ "gpt-4.1-mini-completion": 0.0016,
+ "gpt-4.1-mini-2025-04-14-completion": 0.0016,
+ # GPT-4.1-nano input
+ "gpt-4.1-nano": 0.0001,
+ "gpt-4.1-nano-2025-04-14": 0.0001,
+ "gpt-4.1-nano-cached": 0.000025,
+ "gpt-4.1-nano-2025-04-14-cached": 0.000025,
+ # GPT-4.1-nano output
+ "gpt-4.1-nano-completion": 0.0004,
+ "gpt-4.1-nano-2025-04-14-completion": 0.0004,
+ # GPT-4.5-preview input
+ "gpt-4.5-preview": 0.075,
+ "gpt-4.5-preview-2025-02-27": 0.075,
+ "gpt-4.5-preview-cached": 0.0375,
+ "gpt-4.5-preview-2025-02-27-cached": 0.0375,
+ # GPT-4.5-preview output
+ "gpt-4.5-preview-completion": 0.15,
+ "gpt-4.5-preview-2025-02-27-completion": 0.15,
+ # OpenAI o1 input
+ "o1": 0.015,
+ "o1-2024-12-17": 0.015,
+ "o1-cached": 0.0075,
+ "o1-2024-12-17-cached": 0.0075,
+ # OpenAI o1 output
+ "o1-completion": 0.06,
+ "o1-2024-12-17-completion": 0.06,
+ # OpenAI o1-pro input
+ "o1-pro": 0.15,
+ "o1-pro-2025-03-19": 0.15,
+ # OpenAI o1-pro output
+ "o1-pro-completion": 0.6,
+ "o1-pro-2025-03-19-completion": 0.6,
+ # OpenAI o3 input
+ "o3": 0.002,
+ "o3-2025-04-16": 0.002,
+ "o3-cached": 0.0005,
+ "o3-2025-04-16-cached": 0.0005,
+ # OpenAI o3 output
+ "o3-completion": 0.008,
+ "o3-2025-04-16-completion": 0.008,
+ # OpenAI o4-mini input
+ "o4-mini": 0.0011,
+ "o4-mini-2025-04-16": 0.0011,
+ "o4-mini-cached": 0.000275,
+ "o4-mini-2025-04-16-cached": 0.000275,
+ # OpenAI o4-mini output
+ "o4-mini-completion": 0.0044,
+ "o4-mini-2025-04-16-completion": 0.0044,
+ # OpenAI o3-mini input
+ "o3-mini": 0.0011,
+ "o3-mini-2025-01-31": 0.0011,
+ "o3-mini-cached": 0.00055,
+ "o3-mini-2025-01-31-cached": 0.00055,
+ # OpenAI o3-mini output
+ "o3-mini-completion": 0.0044,
+ "o3-mini-2025-01-31-completion": 0.0044,
+ # OpenAI o1-mini input (updated pricing)
+ "o1-mini": 0.0011,
+ "o1-mini-cached": 0.00055,
+ "o1-mini-2024-09-12": 0.0011,
+ "o1-mini-2024-09-12-cached": 0.00055,
+ # OpenAI o1-mini output (updated pricing)
+ "o1-mini-completion": 0.0044,
+ "o1-mini-2024-09-12-completion": 0.0044,
+ # OpenAI o1-preview input
+ "o1-preview": 0.015,
+ "o1-preview-cached": 0.0075,
+ "o1-preview-2024-09-12": 0.015,
+ "o1-preview-2024-09-12-cached": 0.0075,
+ # OpenAI o1-preview output
+ "o1-preview-completion": 0.06,
+ "o1-preview-2024-09-12-completion": 0.06,
+ # GPT-4o input
+ "gpt-4o": 0.0025,
+ "gpt-4o-cached": 0.00125,
+ "gpt-4o-2024-05-13": 0.005,
+ "gpt-4o-2024-08-06": 0.0025,
+ "gpt-4o-2024-08-06-cached": 0.00125,
+ "gpt-4o-2024-11-20": 0.0025,
+ "gpt-4o-2024-11-20-cached": 0.00125,
+ # GPT-4o output
+ "gpt-4o-completion": 0.01,
+ "gpt-4o-2024-05-13-completion": 0.015,
+ "gpt-4o-2024-08-06-completion": 0.01,
+ "gpt-4o-2024-11-20-completion": 0.01,
+ # GPT-4o-audio-preview input
+ "gpt-4o-audio-preview": 0.0025,
+ "gpt-4o-audio-preview-2024-12-17": 0.0025,
+ "gpt-4o-audio-preview-2024-10-01": 0.0025,
+ # GPT-4o-audio-preview output
+ "gpt-4o-audio-preview-completion": 0.01,
+ "gpt-4o-audio-preview-2024-12-17-completion": 0.01,
+ "gpt-4o-audio-preview-2024-10-01-completion": 0.01,
+ # GPT-4o-realtime-preview input
+ "gpt-4o-realtime-preview": 0.005,
+ "gpt-4o-realtime-preview-2024-12-17": 0.005,
+ "gpt-4o-realtime-preview-2024-10-01": 0.005,
+ "gpt-4o-realtime-preview-cached": 0.0025,
+ "gpt-4o-realtime-preview-2024-12-17-cached": 0.0025,
+ "gpt-4o-realtime-preview-2024-10-01-cached": 0.0025,
+ # GPT-4o-realtime-preview output
+ "gpt-4o-realtime-preview-completion": 0.02,
+ "gpt-4o-realtime-preview-2024-12-17-completion": 0.02,
+ "gpt-4o-realtime-preview-2024-10-01-completion": 0.02,
+ # GPT-4o-mini input
+ "gpt-4o-mini": 0.00015,
+ "gpt-4o-mini-cached": 0.000075,
+ "gpt-4o-mini-2024-07-18": 0.00015,
+ "gpt-4o-mini-2024-07-18-cached": 0.000075,
+ # GPT-4o-mini output
+ "gpt-4o-mini-completion": 0.0006,
+ "gpt-4o-mini-2024-07-18-completion": 0.0006,
+ # GPT-4o-mini-audio-preview input
+ "gpt-4o-mini-audio-preview": 0.00015,
+ "gpt-4o-mini-audio-preview-2024-12-17": 0.00015,
+ # GPT-4o-mini-audio-preview output
+ "gpt-4o-mini-audio-preview-completion": 0.0006,
+ "gpt-4o-mini-audio-preview-2024-12-17-completion": 0.0006,
+ # GPT-4o-mini-realtime-preview input
+ "gpt-4o-mini-realtime-preview": 0.0006,
+ "gpt-4o-mini-realtime-preview-2024-12-17": 0.0006,
+ "gpt-4o-mini-realtime-preview-cached": 0.0003,
+ "gpt-4o-mini-realtime-preview-2024-12-17-cached": 0.0003,
+ # GPT-4o-mini-realtime-preview output
+ "gpt-4o-mini-realtime-preview-completion": 0.0024,
+ "gpt-4o-mini-realtime-preview-2024-12-17-completion": 0.0024,
+ # GPT-4o-mini-search-preview input
+ "gpt-4o-mini-search-preview": 0.00015,
+ "gpt-4o-mini-search-preview-2025-03-11": 0.00015,
+ # GPT-4o-mini-search-preview output
+ "gpt-4o-mini-search-preview-completion": 0.0006,
+ "gpt-4o-mini-search-preview-2025-03-11-completion": 0.0006,
+ # GPT-4o-search-preview input
+ "gpt-4o-search-preview": 0.0025,
+ "gpt-4o-search-preview-2025-03-11": 0.0025,
+ # GPT-4o-search-preview output
+ "gpt-4o-search-preview-completion": 0.01,
+ "gpt-4o-search-preview-2025-03-11-completion": 0.01,
+ # Computer-use-preview input
+ "computer-use-preview": 0.003,
+ "computer-use-preview-2025-03-11": 0.003,
+ # Computer-use-preview output
+ "computer-use-preview-completion": 0.012,
+ "computer-use-preview-2025-03-11-completion": 0.012,
+ # GPT-4 input
+ "gpt-4": 0.03,
+ "gpt-4-0314": 0.03,
+ "gpt-4-0613": 0.03,
+ "gpt-4-32k": 0.06,
+ "gpt-4-32k-0314": 0.06,
+ "gpt-4-32k-0613": 0.06,
+ "gpt-4-vision-preview": 0.01,
+ "gpt-4-1106-preview": 0.01,
+ "gpt-4-0125-preview": 0.01,
+ "gpt-4-turbo-preview": 0.01,
+ "gpt-4-turbo": 0.01,
+ "gpt-4-turbo-2024-04-09": 0.01,
+ # GPT-4 output
+ "gpt-4-completion": 0.06,
+ "gpt-4-0314-completion": 0.06,
+ "gpt-4-0613-completion": 0.06,
+ "gpt-4-32k-completion": 0.12,
+ "gpt-4-32k-0314-completion": 0.12,
+ "gpt-4-32k-0613-completion": 0.12,
+ "gpt-4-vision-preview-completion": 0.03,
+ "gpt-4-1106-preview-completion": 0.03,
+ "gpt-4-0125-preview-completion": 0.03,
+ "gpt-4-turbo-preview-completion": 0.03,
+ "gpt-4-turbo-completion": 0.03,
+ "gpt-4-turbo-2024-04-09-completion": 0.03,
+ # GPT-3.5 input
+ # gpt-3.5-turbo points at gpt-3.5-turbo-0613 until Feb 16, 2024.
+ # Switches to gpt-3.5-turbo-0125 after.
+ "gpt-3.5-turbo": 0.0015,
+ "gpt-3.5-turbo-0125": 0.0005,
+ "gpt-3.5-turbo-0301": 0.0015,
+ "gpt-3.5-turbo-0613": 0.0015,
+ "gpt-3.5-turbo-1106": 0.001,
+ "gpt-3.5-turbo-instruct": 0.0015,
+ "gpt-3.5-turbo-16k": 0.003,
+ "gpt-3.5-turbo-16k-0613": 0.003,
+ # GPT-3.5 output
+ # gpt-3.5-turbo points at gpt-3.5-turbo-0613 until Feb 16, 2024.
+ # Switches to gpt-3.5-turbo-0125 after.
+ "gpt-3.5-turbo-completion": 0.002,
+ "gpt-3.5-turbo-0125-completion": 0.0015,
+ "gpt-3.5-turbo-0301-completion": 0.002,
+ "gpt-3.5-turbo-0613-completion": 0.002,
+ "gpt-3.5-turbo-1106-completion": 0.002,
+ "gpt-3.5-turbo-instruct-completion": 0.002,
+ "gpt-3.5-turbo-16k-completion": 0.004,
+ "gpt-3.5-turbo-16k-0613-completion": 0.004,
+ # Azure GPT-35 input
+ "gpt-35-turbo": 0.0015, # Azure OpenAI version of ChatGPT
+ "gpt-35-turbo-0125": 0.0005,
+ "gpt-35-turbo-0301": 0.002, # Azure OpenAI version of ChatGPT
+ "gpt-35-turbo-0613": 0.0015,
+ "gpt-35-turbo-instruct": 0.0015,
+ "gpt-35-turbo-16k": 0.003,
+ "gpt-35-turbo-16k-0613": 0.003,
+ # Azure GPT-35 output
+ "gpt-35-turbo-completion": 0.002, # Azure OpenAI version of ChatGPT
+ "gpt-35-turbo-0125-completion": 0.0015,
+ "gpt-35-turbo-0301-completion": 0.002, # Azure OpenAI version of ChatGPT
+ "gpt-35-turbo-0613-completion": 0.002,
+ "gpt-35-turbo-instruct-completion": 0.002,
+ "gpt-35-turbo-16k-completion": 0.004,
+ "gpt-35-turbo-16k-0613-completion": 0.004,
+ # Others
+ "text-ada-001": 0.0004,
+ "ada": 0.0004,
+ "text-babbage-001": 0.0005,
+ "babbage": 0.0005,
+ "text-curie-001": 0.002,
+ "curie": 0.002,
+ "text-davinci-003": 0.02,
+ "text-davinci-002": 0.02,
+ "code-davinci-002": 0.02,
+ # Fine Tuned input
+ "babbage-002-finetuned": 0.0016,
+ "davinci-002-finetuned": 0.012,
+ "gpt-3.5-turbo-0613-finetuned": 0.003,
+ "gpt-3.5-turbo-1106-finetuned": 0.003,
+ "gpt-3.5-turbo-0125-finetuned": 0.003,
+ "gpt-4o-mini-2024-07-18-finetuned": 0.0003,
+ "gpt-4o-mini-2024-07-18-finetuned-cached": 0.00015,
+ # Fine Tuned output
+ "babbage-002-finetuned-completion": 0.0016,
+ "davinci-002-finetuned-completion": 0.012,
+ "gpt-3.5-turbo-0613-finetuned-completion": 0.006,
+ "gpt-3.5-turbo-1106-finetuned-completion": 0.006,
+ "gpt-3.5-turbo-0125-finetuned-completion": 0.006,
+ "gpt-4o-mini-2024-07-18-finetuned-completion": 0.0012,
+ # Azure Fine Tuned input
+ "babbage-002-azure-finetuned": 0.0004,
+ "davinci-002-azure-finetuned": 0.002,
+ "gpt-35-turbo-0613-azure-finetuned": 0.0015,
+ # Azure Fine Tuned output
+ "babbage-002-azure-finetuned-completion": 0.0004,
+ "davinci-002-azure-finetuned-completion": 0.002,
+ "gpt-35-turbo-0613-azure-finetuned-completion": 0.002,
+ # Legacy fine-tuned models
+ "ada-finetuned-legacy": 0.0016,
+ "babbage-finetuned-legacy": 0.0024,
+ "curie-finetuned-legacy": 0.012,
+ "davinci-finetuned-legacy": 0.12,
+}
+
+
+class TokenType(Enum):
+ """Token type enum."""
+
+ PROMPT = auto()
+ PROMPT_CACHED = auto()
+ COMPLETION = auto()
+
+
+def standardize_model_name(
+ model_name: str,
+ is_completion: bool = False,
+ *,
+ token_type: TokenType = TokenType.PROMPT,
+) -> str:
+ """
+ Standardize the model name to a format that can be used in the OpenAI API.
+
+ Args:
+ model_name: Model name to standardize.
+ is_completion: Whether the model is used for completion or not.
+ Defaults to False. Deprecated in favor of ``token_type``.
+ token_type: Token type. Defaults to ``TokenType.PROMPT``.
+
+ Returns:
+ Standardized model name.
+
+ """
+ if is_completion:
+ warn_deprecated(
+ since="0.3.13",
+ message=(
+ "is_completion is deprecated. Use token_type instead. Example:\n\n"
+ "from langchain_community.callbacks.openai_info import TokenType\n\n"
+ "standardize_model_name('gpt-4o', token_type=TokenType.COMPLETION)\n"
+ ),
+ removal="1.0",
+ )
+ token_type = TokenType.COMPLETION
+ model_name = model_name.lower()
+ if ".ft-" in model_name:
+ model_name = model_name.split(".ft-")[0] + "-azure-finetuned"
+ if ":ft-" in model_name:
+ model_name = model_name.split(":")[0] + "-finetuned-legacy"
+ if "ft:" in model_name:
+ model_name = model_name.split(":")[1] + "-finetuned"
+ if token_type == TokenType.COMPLETION and (
+ model_name.startswith("gpt-5")
+ or model_name.startswith("gpt-4")
+ or model_name.startswith("gpt-3.5")
+ or model_name.startswith("gpt-35")
+ or model_name.startswith("o1-")
+ or model_name.startswith("o3-")
+ or model_name.startswith("o4-")
+ or ("finetuned" in model_name and "legacy" not in model_name)
+ ):
+ return model_name + "-completion"
+ if (
+ token_type == TokenType.PROMPT_CACHED
+ and (
+ model_name.startswith("gpt-5")
+ or model_name.startswith("gpt-4o")
+ or model_name.startswith("gpt-4.1")
+ or model_name.startswith("o1")
+ or model_name.startswith("o3")
+ or model_name.startswith("o4")
+ )
+ and not (model_name.startswith("gpt-4o-2024-05-13"))
+ ):
+ return model_name + "-cached"
+ else:
+ return model_name
+
+
+def get_openai_token_cost_for_model(
+ model_name: str,
+ num_tokens: int,
+ is_completion: bool = False,
+ *,
+ token_type: TokenType = TokenType.PROMPT,
+) -> float:
+ """
+ Get the cost in USD for a given model and number of tokens.
+
+ Args:
+ model_name: Name of the model
+ num_tokens: Number of tokens.
+ is_completion: Whether the model is used for completion or not.
+ Defaults to False. Deprecated in favor of ``token_type``.
+ token_type: Token type. Defaults to ``TokenType.PROMPT``.
+
+ Returns:
+ Cost in USD.
+ """
+ if is_completion:
+ warn_deprecated(
+ since="0.3.13",
+ message=(
+ "is_completion is deprecated. Use token_type instead. Example:\n\n"
+ "from langchain_community.callbacks.openai_info import TokenType\n\n"
+ "get_openai_token_cost_for_model('gpt-4o', 10, token_type=TokenType.COMPLETION)\n" # noqa: E501
+ ),
+ removal="1.0",
+ )
+ token_type = TokenType.COMPLETION
+ model_name = standardize_model_name(model_name, token_type=token_type)
+ if model_name not in MODEL_COST_PER_1K_TOKENS:
+ raise ValueError(
+ f"Unknown model: {model_name}. Please provide a valid OpenAI model name."
+ "Known models are: " + ", ".join(MODEL_COST_PER_1K_TOKENS.keys())
+ )
+ return MODEL_COST_PER_1K_TOKENS[model_name] * (num_tokens / 1000)
+
+
+class OpenAICallbackHandler(BaseCallbackHandler):
+ """Callback Handler that tracks OpenAI info."""
+
+ total_tokens: int = 0
+ prompt_tokens: int = 0
+ prompt_tokens_cached: int = 0
+ completion_tokens: int = 0
+ reasoning_tokens: int = 0
+ successful_requests: int = 0
+ total_cost: float = 0.0
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._lock = threading.Lock()
+
+ def __repr__(self) -> str:
+ return (
+ f"Tokens Used: {self.total_tokens}\n"
+ f"\tPrompt Tokens: {self.prompt_tokens}\n"
+ f"\t\tPrompt Tokens Cached: {self.prompt_tokens_cached}\n"
+ f"\tCompletion Tokens: {self.completion_tokens}\n"
+ f"\t\tReasoning Tokens: {self.reasoning_tokens}\n"
+ f"Successful Requests: {self.successful_requests}\n"
+ f"Total Cost (USD): ${self.total_cost}"
+ )
+
+ @property
+ def always_verbose(self) -> bool:
+ """Whether to call verbose callbacks even if verbose is False."""
+ return True
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Print out the prompts."""
+ pass
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Print out the token."""
+ pass
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Collect token usage."""
+ # Check for usage_metadata (langchain-core >= 0.2.2)
+ try:
+ generation = response.generations[0][0]
+ except IndexError:
+ generation = None
+ if isinstance(generation, ChatGeneration):
+ try:
+ message = generation.message
+ if isinstance(message, AIMessage):
+ usage_metadata = message.usage_metadata
+ response_metadata = message.response_metadata
+ else:
+ usage_metadata = None
+ response_metadata = None
+ except AttributeError:
+ usage_metadata = None
+ response_metadata = None
+ else:
+ usage_metadata = None
+ response_metadata = None
+
+ prompt_tokens_cached = 0
+ reasoning_tokens = 0
+
+ if usage_metadata:
+ token_usage = {"total_tokens": usage_metadata["total_tokens"]}
+ completion_tokens = usage_metadata["output_tokens"]
+ prompt_tokens = usage_metadata["input_tokens"]
+ if response_model_name := (response_metadata or {}).get("model_name"):
+ model_name = standardize_model_name(response_model_name)
+ elif response.llm_output is None:
+ model_name = ""
+ else:
+ model_name = standardize_model_name(
+ response.llm_output.get("model_name", "")
+ )
+ if "cache_read" in usage_metadata.get("input_token_details", {}):
+ prompt_tokens_cached = usage_metadata["input_token_details"][
+ "cache_read"
+ ]
+ if "reasoning" in usage_metadata.get("output_token_details", {}):
+ reasoning_tokens = usage_metadata["output_token_details"]["reasoning"]
+ else:
+ if response.llm_output is None:
+ return None
+
+ if "token_usage" not in response.llm_output:
+ with self._lock:
+ self.successful_requests += 1
+ return None
+
+ # compute tokens and cost for this request
+ token_usage = response.llm_output["token_usage"]
+ completion_tokens = token_usage.get("completion_tokens", 0)
+ prompt_tokens = token_usage.get("prompt_tokens", 0)
+ model_name = standardize_model_name(
+ response.llm_output.get("model_name", "")
+ )
+
+ if model_name in MODEL_COST_PER_1K_TOKENS:
+ uncached_prompt_tokens = prompt_tokens - prompt_tokens_cached
+ uncached_prompt_cost = get_openai_token_cost_for_model(
+ model_name, uncached_prompt_tokens, token_type=TokenType.PROMPT
+ )
+ cached_prompt_cost = get_openai_token_cost_for_model(
+ model_name, prompt_tokens_cached, token_type=TokenType.PROMPT_CACHED
+ )
+ prompt_cost = uncached_prompt_cost + cached_prompt_cost
+ completion_cost = get_openai_token_cost_for_model(
+ model_name, completion_tokens, token_type=TokenType.COMPLETION
+ )
+ else:
+ completion_cost = 0
+ prompt_cost = 0
+
+ # update shared state behind lock
+ with self._lock:
+ self.total_cost += prompt_cost + completion_cost
+ self.total_tokens += token_usage.get("total_tokens", 0)
+ self.prompt_tokens += prompt_tokens
+ self.prompt_tokens_cached += prompt_tokens_cached
+ self.completion_tokens += completion_tokens
+ self.reasoning_tokens += reasoning_tokens
+ self.successful_requests += 1
+
+ def __copy__(self) -> "OpenAICallbackHandler":
+ """Return a copy of the callback handler."""
+ return self
+
+ def __deepcopy__(self, memo: Any) -> "OpenAICallbackHandler":
+ """Return a deep copy of the callback handler."""
+ return self
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/promptlayer_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/promptlayer_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..150cc5e50c252d59b74f6f6bd4be7aad6e7cdd3f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/promptlayer_callback.py
@@ -0,0 +1,163 @@
+"""Callback handler for promptlayer."""
+
+from __future__ import annotations
+
+import datetime
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple
+from uuid import UUID
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import (
+ ChatGeneration,
+ LLMResult,
+)
+
+if TYPE_CHECKING:
+ import promptlayer
+
+
+def _lazy_import_promptlayer() -> promptlayer:
+ """Lazy import promptlayer to avoid circular imports."""
+ try:
+ import promptlayer
+ except ImportError:
+ raise ImportError(
+ "The PromptLayerCallbackHandler requires the promptlayer package. "
+ " Please install it with `pip install promptlayer`."
+ )
+ return promptlayer
+
+
+class PromptLayerCallbackHandler(BaseCallbackHandler):
+ """Callback handler for promptlayer."""
+
+ def __init__(
+ self,
+ pl_id_callback: Optional[Callable[..., Any]] = None,
+ pl_tags: Optional[List[str]] = None,
+ ) -> None:
+ """Initialize the PromptLayerCallbackHandler."""
+ _lazy_import_promptlayer()
+ self.pl_id_callback = pl_id_callback
+ self.pl_tags = pl_tags or []
+ self.runs: Dict[UUID, Dict[str, Any]] = {}
+
+ def on_chat_model_start(
+ self,
+ serialized: Dict[str, Any],
+ messages: List[List[BaseMessage]],
+ *,
+ run_id: UUID,
+ parent_run_id: Optional[UUID] = None,
+ tags: Optional[List[str]] = None,
+ **kwargs: Any,
+ ) -> Any:
+ self.runs[run_id] = {
+ "messages": [self._create_message_dicts(m)[0] for m in messages],
+ "invocation_params": kwargs.get("invocation_params", {}),
+ "name": ".".join(serialized["id"]),
+ "request_start_time": datetime.datetime.now().timestamp(),
+ "tags": tags,
+ }
+
+ def on_llm_start(
+ self,
+ serialized: Dict[str, Any],
+ prompts: List[str],
+ *,
+ run_id: UUID,
+ parent_run_id: Optional[UUID] = None,
+ tags: Optional[List[str]] = None,
+ **kwargs: Any,
+ ) -> Any:
+ self.runs[run_id] = {
+ "prompts": prompts,
+ "invocation_params": kwargs.get("invocation_params", {}),
+ "name": ".".join(serialized["id"]),
+ "request_start_time": datetime.datetime.now().timestamp(),
+ "tags": tags,
+ }
+
+ def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: Optional[UUID] = None,
+ **kwargs: Any,
+ ) -> None:
+ from promptlayer.utils import get_api_key, promptlayer_api_request
+
+ run_info = self.runs.get(run_id, {})
+ if not run_info:
+ return
+ run_info["request_end_time"] = datetime.datetime.now().timestamp()
+ for i in range(len(response.generations)):
+ generation = response.generations[i][0]
+
+ resp = {
+ "text": generation.text,
+ "llm_output": response.llm_output,
+ }
+ model_params = run_info.get("invocation_params", {})
+ is_chat_model = run_info.get("messages", None) is not None
+ model_input = (
+ run_info.get("messages", [])[i]
+ if is_chat_model
+ else [run_info.get("prompts", [])[i]]
+ )
+ model_response = (
+ [self._convert_message_to_dict(generation.message)]
+ if is_chat_model and isinstance(generation, ChatGeneration)
+ else resp
+ )
+
+ pl_request_id = promptlayer_api_request(
+ run_info.get("name"),
+ "langchain",
+ model_input,
+ model_params,
+ self.pl_tags,
+ model_response,
+ run_info.get("request_start_time"),
+ run_info.get("request_end_time"),
+ get_api_key(),
+ return_pl_id=bool(self.pl_id_callback is not None),
+ metadata={
+ "_langchain_run_id": str(run_id),
+ "_langchain_parent_run_id": str(parent_run_id),
+ "_langchain_tags": str(run_info.get("tags", [])),
+ },
+ )
+
+ if self.pl_id_callback:
+ self.pl_id_callback(pl_request_id)
+
+ def _convert_message_to_dict(self, message: BaseMessage) -> Dict[str, Any]:
+ if isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ else:
+ raise ValueError(f"Got unknown type {message}")
+ if "name" in message.additional_kwargs:
+ message_dict["name"] = message.additional_kwargs["name"]
+ return message_dict
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage]
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
+ params: Dict[str, Any] = {}
+ message_dicts = [self._convert_message_to_dict(m) for m in messages]
+ return message_dicts, params
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/sagemaker_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/sagemaker_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..45295a0b5f7e2c8d2b3f7054c62cd1428b3974a9
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/sagemaker_callback.py
@@ -0,0 +1,277 @@
+import json
+import os
+import shutil
+import tempfile
+from copy import deepcopy
+from typing import Any, Dict, List, Optional
+
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.outputs import LLMResult
+
+from langchain_community.callbacks.utils import (
+ flatten_dict,
+)
+
+
+def save_json(data: dict, file_path: str) -> None:
+ """Save dict to local file path.
+
+ Parameters:
+ data (dict): The dictionary to be saved.
+ file_path (str): Local file path.
+ """
+ with open(file_path, "w") as outfile:
+ json.dump(data, outfile)
+
+
+class SageMakerCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that logs prompt artifacts and metrics to SageMaker Experiments.
+
+ Parameters:
+ run (sagemaker.experiments.run.Run): Run object where the experiment is logged.
+ """
+
+ def __init__(self, run: Any) -> None:
+ """Initialize callback handler."""
+ super().__init__()
+
+ self.run = run
+
+ self.metrics = {
+ "step": 0,
+ "starts": 0,
+ "ends": 0,
+ "errors": 0,
+ "text_ctr": 0,
+ "chain_starts": 0,
+ "chain_ends": 0,
+ "llm_starts": 0,
+ "llm_ends": 0,
+ "llm_streams": 0,
+ "tool_starts": 0,
+ "tool_ends": 0,
+ "agent_ends": 0,
+ }
+
+ # Create a temporary directory
+ self.temp_dir = tempfile.mkdtemp()
+
+ def _reset(self) -> None:
+ for k, v in self.metrics.items():
+ self.metrics[k] = 0
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Run when LLM starts."""
+ self.metrics["step"] += 1
+ self.metrics["llm_starts"] += 1
+ self.metrics["starts"] += 1
+
+ llm_starts = self.metrics["llm_starts"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_llm_start"})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.metrics)
+
+ for idx, prompt in enumerate(prompts):
+ prompt_resp = deepcopy(resp)
+ prompt_resp["prompt"] = prompt
+ self.jsonf(
+ prompt_resp,
+ self.temp_dir,
+ f"llm_start_{llm_starts}_prompt_{idx}",
+ )
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Run when LLM generates a new token."""
+ self.metrics["step"] += 1
+ self.metrics["llm_streams"] += 1
+
+ llm_streams = self.metrics["llm_streams"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_llm_new_token", "token": token})
+ resp.update(self.metrics)
+
+ self.jsonf(resp, self.temp_dir, f"llm_new_tokens_{llm_streams}")
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running."""
+ self.metrics["step"] += 1
+ self.metrics["llm_ends"] += 1
+ self.metrics["ends"] += 1
+
+ llm_ends = self.metrics["llm_ends"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_llm_end"})
+ resp.update(flatten_dict(response.llm_output or {}))
+
+ resp.update(self.metrics)
+
+ for generations in response.generations:
+ for idx, generation in enumerate(generations):
+ generation_resp = deepcopy(resp)
+ generation_resp.update(flatten_dict(generation.dict()))
+
+ self.jsonf(
+ resp,
+ self.temp_dir,
+ f"llm_end_{llm_ends}_generation_{idx}",
+ )
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when LLM errors."""
+ self.metrics["step"] += 1
+ self.metrics["errors"] += 1
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Run when chain starts running."""
+ self.metrics["step"] += 1
+ self.metrics["chain_starts"] += 1
+ self.metrics["starts"] += 1
+
+ chain_starts = self.metrics["chain_starts"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_chain_start"})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.metrics)
+
+ chain_input = ",".join([f"{k}={v}" for k, v in inputs.items()])
+ input_resp = deepcopy(resp)
+ input_resp["inputs"] = chain_input
+
+ self.jsonf(input_resp, self.temp_dir, f"chain_start_{chain_starts}")
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Run when chain ends running."""
+ self.metrics["step"] += 1
+ self.metrics["chain_ends"] += 1
+ self.metrics["ends"] += 1
+
+ chain_ends = self.metrics["chain_ends"]
+
+ resp: Dict[str, Any] = {}
+ chain_output = ",".join([f"{k}={v}" for k, v in outputs.items()])
+ resp.update({"action": "on_chain_end", "outputs": chain_output})
+ resp.update(self.metrics)
+
+ self.jsonf(resp, self.temp_dir, f"chain_end_{chain_ends}")
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when chain errors."""
+ self.metrics["step"] += 1
+ self.metrics["errors"] += 1
+
+ def on_tool_start(
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
+ ) -> None:
+ """Run when tool starts running."""
+ self.metrics["step"] += 1
+ self.metrics["tool_starts"] += 1
+ self.metrics["starts"] += 1
+
+ tool_starts = self.metrics["tool_starts"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_tool_start", "input_str": input_str})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.metrics)
+
+ self.jsonf(resp, self.temp_dir, f"tool_start_{tool_starts}")
+
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
+ """Run when tool ends running."""
+ output = str(output)
+ self.metrics["step"] += 1
+ self.metrics["tool_ends"] += 1
+ self.metrics["ends"] += 1
+
+ tool_ends = self.metrics["tool_ends"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_tool_end", "output": output})
+ resp.update(self.metrics)
+
+ self.jsonf(resp, self.temp_dir, f"tool_end_{tool_ends}")
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when tool errors."""
+ self.metrics["step"] += 1
+ self.metrics["errors"] += 1
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """
+ Run when agent is ending.
+ """
+ self.metrics["step"] += 1
+ self.metrics["text_ctr"] += 1
+
+ text_ctr = self.metrics["text_ctr"]
+
+ resp: Dict[str, Any] = {}
+ resp.update({"action": "on_text", "text": text})
+ resp.update(self.metrics)
+
+ self.jsonf(resp, self.temp_dir, f"on_text_{text_ctr}")
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run when agent ends running."""
+ self.metrics["step"] += 1
+ self.metrics["agent_ends"] += 1
+ self.metrics["ends"] += 1
+
+ agent_ends = self.metrics["agent_ends"]
+ resp: Dict[str, Any] = {}
+ resp.update(
+ {
+ "action": "on_agent_finish",
+ "output": finish.return_values["output"],
+ "log": finish.log,
+ }
+ )
+ resp.update(self.metrics)
+
+ self.jsonf(resp, self.temp_dir, f"agent_finish_{agent_ends}")
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Run on agent action."""
+ self.metrics["step"] += 1
+ self.metrics["tool_starts"] += 1
+ self.metrics["starts"] += 1
+
+ tool_starts = self.metrics["tool_starts"]
+ resp: Dict[str, Any] = {}
+ resp.update(
+ {
+ "action": "on_agent_action",
+ "tool": action.tool,
+ "tool_input": action.tool_input,
+ "log": action.log,
+ }
+ )
+ resp.update(self.metrics)
+ self.jsonf(resp, self.temp_dir, f"agent_action_{tool_starts}")
+
+ def jsonf(
+ self,
+ data: Dict[str, Any],
+ data_dir: str,
+ filename: str,
+ is_output: Optional[bool] = True,
+ ) -> None:
+ """To log the input data as json file artifact."""
+ file_path = os.path.join(data_dir, f"{filename}.json")
+ save_json(data, file_path)
+ self.run.log_file(file_path, name=filename, is_output=is_output)
+
+ def flush_tracker(self) -> None:
+ """Reset the steps and delete the temporary local directory."""
+ self._reset()
+ shutil.rmtree(self.temp_dir)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/trubrics_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/trubrics_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa697a756ed1b542b82a8122b7ad8017c88dd79e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/trubrics_callback.py
@@ -0,0 +1,125 @@
+import os
+from typing import Any, Dict, List, Optional
+from uuid import UUID
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ ChatMessage,
+ FunctionMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import LLMResult
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ message_dict: Dict[str, Any]
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ if "function_call" in message.additional_kwargs:
+ message_dict["function_call"] = message.additional_kwargs["function_call"]
+ # If function call only, content is None not empty string
+ if message_dict["content"] == "":
+ message_dict["content"] = None
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, FunctionMessage):
+ message_dict = {
+ "role": "function",
+ "content": message.content,
+ "name": message.name,
+ }
+ else:
+ raise TypeError(f"Got unknown type {message}")
+ if "name" in message.additional_kwargs:
+ message_dict["name"] = message.additional_kwargs["name"]
+ return message_dict
+
+
+class TrubricsCallbackHandler(BaseCallbackHandler):
+ """
+ Callback handler for Trubrics.
+
+ Args:
+ project: a trubrics project, default project is "default"
+ email: a trubrics account email, can equally be set in env variables
+ password: a trubrics account password, can equally be set in env variables
+ **kwargs: all other kwargs are parsed and set to trubrics prompt variables,
+ or added to the `metadata` dict
+ """
+
+ def __init__(
+ self,
+ project: str = "default",
+ email: Optional[str] = None,
+ password: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__()
+ try:
+ from trubrics import Trubrics
+ except ImportError:
+ raise ImportError(
+ "The TrubricsCallbackHandler requires installation of "
+ "the trubrics package. "
+ "Please install it with `pip install trubrics`."
+ )
+
+ self.trubrics = Trubrics(
+ project=project,
+ email=email or os.environ["TRUBRICS_EMAIL"],
+ password=password or os.environ["TRUBRICS_PASSWORD"],
+ )
+ self.config_model: dict = {}
+ self.prompt: Optional[str] = None
+ self.messages: Optional[list] = None
+ self.trubrics_kwargs: Optional[dict] = kwargs if kwargs else None
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ self.prompt = prompts[0]
+
+ def on_chat_model_start(
+ self,
+ serialized: Dict[str, Any],
+ messages: List[List[BaseMessage]],
+ **kwargs: Any,
+ ) -> None:
+ self.messages = [_convert_message_to_dict(message) for message in messages[0]]
+ self.prompt = self.messages[-1]["content"]
+
+ def on_llm_end(self, response: LLMResult, run_id: UUID, **kwargs: Any) -> None:
+ tags = ["langchain"]
+ user_id = None
+ session_id = None
+ metadata: dict = {"langchain_run_id": run_id}
+ if self.messages:
+ metadata["messages"] = self.messages
+ if self.trubrics_kwargs:
+ if self.trubrics_kwargs.get("tags"):
+ tags.append(*self.trubrics_kwargs.pop("tags"))
+ user_id = self.trubrics_kwargs.pop("user_id", None)
+ session_id = self.trubrics_kwargs.pop("session_id", None)
+ metadata.update(self.trubrics_kwargs)
+
+ for generation in response.generations:
+ self.trubrics.log_prompt(
+ config_model={
+ "model": response.llm_output.get("model_name")
+ if response.llm_output
+ else "NA"
+ },
+ prompt=self.prompt,
+ generation=generation[0].text,
+ user_id=user_id,
+ session_id=session_id,
+ tags=tags,
+ metadata=metadata,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/upstash_ratelimit_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/upstash_ratelimit_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..012350aca635a627c06b61ef8460cadbe3539d59
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/upstash_ratelimit_callback.py
@@ -0,0 +1,206 @@
+"""Ratelimiting Handler to limit requests or tokens"""
+
+import logging
+from typing import Any, Dict, List, Literal, Optional
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.outputs import LLMResult
+
+logger = logging.getLogger(__name__)
+try:
+ from upstash_ratelimit import Ratelimit
+except ImportError:
+ Ratelimit = None
+
+
+class UpstashRatelimitError(Exception):
+ """
+ Upstash Ratelimit Error
+
+ Raised when the rate limit is reached in `UpstashRatelimitHandler`
+ """
+
+ def __init__(
+ self,
+ message: str,
+ type: Literal["token", "request"],
+ limit: Optional[int] = None,
+ reset: Optional[float] = None,
+ ):
+ """
+ Args:
+ message (str): error message
+ type (str): The kind of the limit which was reached. One of
+ "token" or "request"
+ limit (Optional[int]): The limit which was reached. Passed when type
+ is request
+ reset (Optional[int]): unix timestamp in milliseconds when the limits
+ are reset. Passed when type is request
+ """
+ # Call the base class constructor with the parameters it needs
+ super().__init__(message)
+ self.type = type
+ self.limit = limit
+ self.reset = reset
+
+
+class UpstashRatelimitHandler(BaseCallbackHandler):
+ """
+ Callback to handle rate limiting based on the number of requests
+ or the number of tokens in the input.
+
+ It uses Upstash Ratelimit to track the ratelimit which utilizes
+ Upstash Redis to track the state.
+
+ Should not be passed to the chain when initialising the chain.
+ This is because the handler has a state which should be fresh
+ every time invoke is called. Instead, initialise and pass a handler
+ every time you invoke.
+ """
+
+ raise_error: bool = True
+ _checked: bool = False
+
+ def __init__(
+ self,
+ identifier: str,
+ *,
+ token_ratelimit: Optional[Ratelimit] = None,
+ request_ratelimit: Optional[Ratelimit] = None,
+ include_output_tokens: bool = False,
+ ):
+ """
+ Creates UpstashRatelimitHandler. Must be passed an identifier to
+ ratelimit like a user id or an ip address.
+
+ Additionally, it must be passed at least one of token_ratelimit
+ or request_ratelimit parameters.
+
+ Args:
+ identifier Union[int, str]: the identifier
+ token_ratelimit Optional[Ratelimit]: Ratelimit to limit the
+ number of tokens. Only works with OpenAI models since only
+ these models provide the number of tokens as information
+ in their output.
+ request_ratelimit Optional[Ratelimit]: Ratelimit to limit the
+ number of requests
+ include_output_tokens bool: Whether to count output tokens when
+ rate limiting based on number of tokens. Only used when
+ `token_ratelimit` is passed. False by default.
+
+ Example:
+ .. code-block:: python
+
+ from upstash_redis import Redis
+ from upstash_ratelimit import Ratelimit, FixedWindow
+
+ redis = Redis.from_env()
+ ratelimit = Ratelimit(
+ redis=redis,
+ # fixed window to allow 10 requests every 10 seconds:
+ limiter=FixedWindow(max_requests=10, window=10),
+ )
+
+ user_id = "foo"
+ handler = UpstashRatelimitHandler(
+ identifier=user_id,
+ request_ratelimit=ratelimit
+ )
+
+ # Initialize a simple runnable to test
+ chain = RunnableLambda(str)
+
+ # pass handler as callback:
+ output = chain.invoke(
+ "input",
+ config={
+ "callbacks": [handler]
+ }
+ )
+
+ """
+ if not any([token_ratelimit, request_ratelimit]):
+ raise ValueError(
+ "You must pass at least one of input_token_ratelimit or"
+ " request_ratelimit parameters for handler to work."
+ )
+
+ self.identifier = identifier
+ self.token_ratelimit = token_ratelimit
+ self.request_ratelimit = request_ratelimit
+ self.include_output_tokens = include_output_tokens
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> Any:
+ """
+ Run when chain starts running.
+
+ on_chain_start runs multiple times during a chain execution. To make
+ sure that it's only called once, we keep a bool state `_checked`. If
+ not `self._checked`, we call limit with `request_ratelimit` and raise
+ `UpstashRatelimitError` if the identifier is rate limited.
+ """
+ if self.request_ratelimit and not self._checked:
+ response = self.request_ratelimit.limit(self.identifier)
+ if not response.allowed:
+ raise UpstashRatelimitError(
+ "Request limit reached!", "request", response.limit, response.reset
+ )
+ self._checked = True
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """
+ Run when LLM starts running
+ """
+ if self.token_ratelimit:
+ remaining = self.token_ratelimit.get_remaining(self.identifier)
+ if remaining <= 0:
+ raise UpstashRatelimitError("Token limit reached!", "token")
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """
+ Run when LLM ends running
+
+ If the `include_output_tokens` is set to True, number of tokens
+ in LLM completion are counted for rate limiting
+ """
+ if self.token_ratelimit:
+ try:
+ llm_output = response.llm_output or {}
+ token_usage = llm_output["token_usage"]
+ token_count = (
+ token_usage["total_tokens"]
+ if self.include_output_tokens
+ else token_usage["prompt_tokens"]
+ )
+ except KeyError:
+ raise ValueError(
+ "LLM response doesn't include"
+ " `token_usage: {total_tokens: int, prompt_tokens: int}`"
+ " field. To use UpstashRatelimitHandler with token_ratelimit,"
+ " either use a model which returns token_usage (like "
+ " OpenAI models) or rate limit only with request_ratelimit."
+ )
+
+ # call limit to add the completion tokens to rate limit
+ # but don't raise exception since we already generated
+ # the tokens and would rather continue execution.
+ self.token_ratelimit.limit(self.identifier, rate=token_count)
+
+ def reset(self, identifier: Optional[str] = None) -> "UpstashRatelimitHandler":
+ """
+ Creates a new UpstashRatelimitHandler object with the same
+ ratelimit configurations but with a new identifier if it's
+ provided.
+
+ Also resets the state of the handler.
+ """
+ return UpstashRatelimitHandler(
+ identifier=identifier or self.identifier,
+ token_ratelimit=self.token_ratelimit,
+ request_ratelimit=self.request_ratelimit,
+ include_output_tokens=self.include_output_tokens,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/uptrain_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/uptrain_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c35bf046593828dc2a501c6d57e4155968cf379
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/uptrain_callback.py
@@ -0,0 +1,384 @@
+"""
+UpTrain Callback Handler
+
+UpTrain is an open-source platform to evaluate and improve LLM applications. It provides
+grades for 20+ preconfigured checks (covering language, code, embedding use cases),
+performs root cause analyses on instances of failure cases and provides guidance for
+resolving them.
+
+This module contains a callback handler for integrating UpTrain seamlessly into your
+pipeline and facilitating diverse evaluations. The callback handler automates various
+evaluations to assess the performance and effectiveness of the components within the
+pipeline.
+
+The evaluations conducted include:
+
+1. RAG:
+ - Context Relevance: Determines the relevance of the context extracted from the query
+ to the response.
+ - Factual Accuracy: Assesses if the Language Model (LLM) is providing accurate
+ information or hallucinating.
+ - Response Completeness: Checks if the response contains all the information
+ requested by the query.
+
+2. Multi Query Generation:
+ MultiQueryRetriever generates multiple variants of a question with similar meanings
+ to the original question. This evaluation includes previous assessments and adds:
+ - Multi Query Accuracy: Ensures that the multi-queries generated convey the same
+ meaning as the original query.
+
+3. Context Compression and Reranking:
+ Re-ranking involves reordering nodes based on relevance to the query and selecting
+ top n nodes.
+ Due to the potential reduction in the number of nodes after re-ranking, the following
+ evaluations
+ are performed in addition to the RAG evaluations:
+ - Context Reranking: Determines if the order of re-ranked nodes is more relevant to
+ the query than the original order.
+ - Context Conciseness: Examines whether the reduced number of nodes still provides
+ all the required information.
+
+These evaluations collectively ensure the robustness and effectiveness of the RAG query
+engine, MultiQueryRetriever, and the re-ranking process within the pipeline.
+
+Useful links:
+Github: https://github.com/uptrain-ai/uptrain
+Website: https://uptrain.ai/
+Docs: https://docs.uptrain.ai/getting-started/introduction
+
+"""
+
+import logging
+import sys
+from collections import defaultdict
+from typing import (
+ Any,
+ DefaultDict,
+ Dict,
+ List,
+ Optional,
+ Sequence,
+ Set,
+)
+from uuid import UUID
+
+from langchain_core.callbacks.base import BaseCallbackHandler
+from langchain_core.documents import Document
+from langchain_core.outputs import LLMResult
+from langchain_core.utils import guard_import
+
+logger = logging.getLogger(__name__)
+handler = logging.StreamHandler(sys.stdout)
+formatter = logging.Formatter("%(message)s")
+handler.setFormatter(formatter)
+logger.addHandler(handler)
+
+
+def import_uptrain() -> Any:
+ """Import the `uptrain` package."""
+ return guard_import("uptrain")
+
+
+class UpTrainDataSchema:
+ """The UpTrain data schema for tracking evaluation results.
+
+ Args:
+ project_name (str): The project name to be shown in UpTrain dashboard.
+
+ Attributes:
+ project_name (str): The project name to be shown in UpTrain dashboard.
+ uptrain_results (DefaultDict[str, Any]): Dictionary to store evaluation results.
+ eval_types (Set[str]): Set to store the types of evaluations.
+ query (str): Query for the RAG evaluation.
+ context (str): Context for the RAG evaluation.
+ response (str): Response for the RAG evaluation.
+ old_context (List[str]): Old context nodes for Context Conciseness evaluation.
+ new_context (List[str]): New context nodes for Context Conciseness evaluation.
+ context_conciseness_run_id (str): Run ID for Context Conciseness evaluation.
+ multi_queries (List[str]): List of multi queries for Multi Query evaluation.
+ multi_query_run_id (str): Run ID for Multi Query evaluation.
+ multi_query_daugher_run_id (str): Run ID for Multi Query daughter evaluation.
+
+ """
+
+ def __init__(self, project_name: str) -> None:
+ """Initialize the UpTrain data schema."""
+ # For tracking project name and results
+ self.project_name: str = project_name
+ self.uptrain_results: DefaultDict[str, Any] = defaultdict(list)
+
+ # For tracking event types
+ self.eval_types: Set[str] = set()
+
+ ## RAG
+ self.query: str = ""
+ self.context: str = ""
+ self.response: str = ""
+
+ ## CONTEXT CONCISENESS
+ self.old_context: List[str] = []
+ self.new_context: List[str] = []
+ self.context_conciseness_run_id: UUID = UUID(int=0)
+
+ # MULTI QUERY
+ self.multi_queries: List[str] = []
+ self.multi_query_run_id: UUID = UUID(int=0)
+ self.multi_query_daugher_run_id: UUID = UUID(int=0)
+
+
+class UpTrainCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that logs evaluation results to uptrain and the console.
+
+ Args:
+ project_name (str): The project name to be shown in UpTrain dashboard.
+ key_type (str): Type of key to use. Must be 'uptrain' or 'openai'.
+ api_key (str): API key for the UpTrain or OpenAI API.
+ (This key is required to perform evaluations using GPT.)
+
+ Raises:
+ ValueError: If the key type is invalid.
+ ImportError: If the `uptrain` package is not installed.
+
+ """
+
+ def __init__(
+ self,
+ *,
+ project_name: str = "langchain",
+ key_type: str = "openai",
+ api_key: str = "sk-****************", # The API key to use for evaluation
+ model: str = "gpt-3.5-turbo", # The model to use for evaluation
+ log_results: bool = True,
+ ) -> None:
+ """Initializes the `UpTrainCallbackHandler`."""
+ super().__init__()
+
+ uptrain = import_uptrain()
+
+ self.log_results = log_results
+
+ # Set uptrain variables
+ self.schema = UpTrainDataSchema(project_name=project_name)
+ self.first_score_printed_flag = False
+
+ if key_type == "uptrain":
+ settings = uptrain.Settings(uptrain_access_token=api_key, model=model)
+ self.uptrain_client = uptrain.APIClient(settings=settings)
+ elif key_type == "openai":
+ settings = uptrain.Settings(
+ openai_api_key=api_key, evaluate_locally=True, model=model
+ )
+ self.uptrain_client = uptrain.EvalLLM(settings=settings)
+ else:
+ raise ValueError("Invalid key type: Must be 'uptrain' or 'openai'")
+
+ def uptrain_evaluate(
+ self,
+ evaluation_name: str,
+ data: List[Dict[str, Any]],
+ checks: List[str],
+ ) -> None:
+ """Run an evaluation on the UpTrain server using UpTrain client."""
+ if self.uptrain_client.__class__.__name__ == "APIClient":
+ uptrain_result = self.uptrain_client.log_and_evaluate(
+ project_name=self.schema.project_name,
+ evaluation_name=evaluation_name,
+ data=data,
+ checks=checks,
+ )
+ else:
+ uptrain_result = self.uptrain_client.evaluate(
+ project_name=self.schema.project_name,
+ evaluation_name=evaluation_name,
+ data=data,
+ checks=checks,
+ )
+ self.schema.uptrain_results[self.schema.project_name].append(uptrain_result)
+
+ score_name_map = {
+ "score_context_relevance": "Context Relevance Score",
+ "score_factual_accuracy": "Factual Accuracy Score",
+ "score_response_completeness": "Response Completeness Score",
+ "score_sub_query_completeness": "Sub Query Completeness Score",
+ "score_context_reranking": "Context Reranking Score",
+ "score_context_conciseness": "Context Conciseness Score",
+ "score_multi_query_accuracy": "Multi Query Accuracy Score",
+ }
+
+ if self.log_results:
+ # Set logger level to INFO to print the evaluation results
+ logger.setLevel(logging.INFO)
+
+ for row in uptrain_result:
+ columns = list(row.keys())
+ for column in columns:
+ if column == "question":
+ logger.info(f"\nQuestion: {row[column]}")
+ self.first_score_printed_flag = False
+ elif column == "response":
+ logger.info(f"Response: {row[column]}")
+ self.first_score_printed_flag = False
+ elif column == "variants":
+ logger.info("Multi Queries:")
+ for variant in row[column]:
+ logger.info(f" - {variant}")
+ self.first_score_printed_flag = False
+ elif column.startswith("score"):
+ if not self.first_score_printed_flag:
+ logger.info("")
+ self.first_score_printed_flag = True
+ if column in score_name_map:
+ logger.info(f"{score_name_map[column]}: {row[column]}")
+ else:
+ logger.info(f"{column}: {row[column]}")
+
+ if self.log_results:
+ # Set logger level back to WARNING
+ # (We are doing this to avoid printing the logs from HTTP requests)
+ logger.setLevel(logging.WARNING)
+
+ def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: Optional[UUID] = None,
+ **kwargs: Any,
+ ) -> None:
+ """Log records to uptrain when an LLM ends."""
+ uptrain = import_uptrain()
+ self.schema.response = response.generations[0][0].text
+ if (
+ "qa_rag" in self.schema.eval_types
+ and parent_run_id != self.schema.multi_query_daugher_run_id
+ ):
+ data = [
+ {
+ "question": self.schema.query,
+ "context": self.schema.context,
+ "response": self.schema.response,
+ }
+ ]
+
+ self.uptrain_evaluate(
+ evaluation_name="rag",
+ data=data,
+ checks=[
+ uptrain.Evals.CONTEXT_RELEVANCE,
+ uptrain.Evals.FACTUAL_ACCURACY,
+ uptrain.Evals.RESPONSE_COMPLETENESS,
+ ],
+ )
+
+ def on_chain_start(
+ self,
+ serialized: Dict[str, Any],
+ inputs: Dict[str, Any],
+ *,
+ run_id: UUID,
+ tags: Optional[List[str]] = None,
+ parent_run_id: Optional[UUID] = None,
+ metadata: Optional[Dict[str, Any]] = None,
+ run_type: Optional[str] = None,
+ name: Optional[str] = None,
+ **kwargs: Any,
+ ) -> None:
+ """Do nothing when chain starts"""
+ if parent_run_id == self.schema.multi_query_run_id:
+ self.schema.multi_query_daugher_run_id = run_id
+ if isinstance(inputs, dict) and set(inputs.keys()) == {"context", "question"}:
+ self.schema.eval_types.add("qa_rag")
+
+ context = ""
+ if isinstance(inputs["context"], Document):
+ context = inputs["context"].page_content
+ elif isinstance(inputs["context"], list):
+ for doc in inputs["context"]:
+ context += doc.page_content + "\n"
+ elif isinstance(inputs["context"], str):
+ context = inputs["context"]
+ self.schema.context = context
+ self.schema.query = inputs["question"]
+ pass
+
+ def on_retriever_start(
+ self,
+ serialized: Dict[str, Any],
+ query: str,
+ *,
+ run_id: UUID,
+ parent_run_id: Optional[UUID] = None,
+ tags: Optional[List[str]] = None,
+ metadata: Optional[Dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> None:
+ if "contextual_compression" in serialized["id"]:
+ self.schema.eval_types.add("contextual_compression")
+ self.schema.query = query
+ self.schema.context_conciseness_run_id = run_id
+
+ if "multi_query" in serialized["id"]:
+ self.schema.eval_types.add("multi_query")
+ self.schema.multi_query_run_id = run_id
+ self.schema.query = query
+ elif "multi_query" in self.schema.eval_types:
+ self.schema.multi_queries.append(query)
+
+ def on_retriever_end(
+ self,
+ documents: Sequence[Document],
+ *,
+ run_id: UUID,
+ parent_run_id: Optional[UUID] = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when Retriever ends running."""
+ uptrain = import_uptrain()
+ if run_id == self.schema.multi_query_run_id:
+ data = [
+ {
+ "question": self.schema.query,
+ "variants": self.schema.multi_queries,
+ }
+ ]
+
+ self.uptrain_evaluate(
+ evaluation_name="multi_query",
+ data=data,
+ checks=[uptrain.Evals.MULTI_QUERY_ACCURACY],
+ )
+ if "contextual_compression" in self.schema.eval_types:
+ if parent_run_id == self.schema.context_conciseness_run_id:
+ for doc in documents:
+ self.schema.old_context.append(doc.page_content)
+ elif run_id == self.schema.context_conciseness_run_id:
+ for doc in documents:
+ self.schema.new_context.append(doc.page_content)
+ context = "\n".join(
+ [
+ f"{index}. {string}"
+ for index, string in enumerate(self.schema.old_context, start=1)
+ ]
+ )
+ reranked_context = "\n".join(
+ [
+ f"{index}. {string}"
+ for index, string in enumerate(self.schema.new_context, start=1)
+ ]
+ )
+ data = [
+ {
+ "question": self.schema.query,
+ "context": context,
+ "concise_context": reranked_context,
+ "reranked_context": reranked_context,
+ }
+ ]
+ self.uptrain_evaluate(
+ evaluation_name="context_reranking",
+ data=data,
+ checks=[
+ uptrain.Evals.CONTEXT_CONCISENESS,
+ uptrain.Evals.CONTEXT_RERANKING,
+ ],
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..db5dd37bf0cd037fc1c459acc6cbd534be46f87c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/utils.py
@@ -0,0 +1,239 @@
+import hashlib
+from pathlib import Path
+from typing import Any, Dict, Iterable, Tuple, Union
+
+from langchain_core.utils import guard_import
+
+
+def import_spacy() -> Any:
+ """Import the spacy python package and raise an error if it is not installed."""
+ return guard_import("spacy")
+
+
+def import_pandas() -> Any:
+ """Import the pandas python package and raise an error if it is not installed."""
+ return guard_import("pandas")
+
+
+def import_textstat() -> Any:
+ """Import the textstat python package and raise an error if it is not installed."""
+ return guard_import("textstat")
+
+
+def _flatten_dict(
+ nested_dict: Dict[str, Any], parent_key: str = "", sep: str = "_"
+) -> Iterable[Tuple[str, Any]]:
+ """
+ Generator that yields flattened items from a nested dictionary for a flat dict.
+
+ Parameters:
+ nested_dict (dict): The nested dictionary to flatten.
+ parent_key (str): The prefix to prepend to the keys of the flattened dict.
+ sep (str): The separator to use between the parent key and the key of the
+ flattened dictionary.
+
+ Yields:
+ (str, any): A key-value pair from the flattened dictionary.
+ """
+ for key, value in nested_dict.items():
+ new_key = parent_key + sep + key if parent_key else key
+ if isinstance(value, dict):
+ yield from _flatten_dict(value, new_key, sep)
+ else:
+ yield new_key, value
+
+
+def flatten_dict(
+ nested_dict: Dict[str, Any], parent_key: str = "", sep: str = "_"
+) -> Dict[str, Any]:
+ """Flatten a nested dictionary into a flat dictionary.
+
+ Parameters:
+ nested_dict (dict): The nested dictionary to flatten.
+ parent_key (str): The prefix to prepend to the keys of the flattened dict.
+ sep (str): The separator to use between the parent key and the key of the
+ flattened dictionary.
+
+ Returns:
+ (dict): A flat dictionary.
+
+ """
+ flat_dict = {k: v for k, v in _flatten_dict(nested_dict, parent_key, sep)}
+ return flat_dict
+
+
+def hash_string(s: str) -> str:
+ """Hash a string using sha1.
+
+ Parameters:
+ s (str): The string to hash.
+
+ Returns:
+ (str): The hashed string.
+ """
+ return hashlib.sha1(s.encode("utf-8")).hexdigest()
+
+
+def load_json(json_path: Union[str, Path]) -> str:
+ """Load json file to a string.
+
+ Parameters:
+ json_path (str): The path to the json file.
+
+ Returns:
+ (str): The string representation of the json file.
+ """
+ with open(json_path, "r") as f:
+ data = f.read()
+ return data
+
+
+class BaseMetadataCallbackHandler:
+ """Handle the metadata and associated function states for callbacks.
+
+ Attributes:
+ step (int): The current step.
+ starts (int): The number of times the start method has been called.
+ ends (int): The number of times the end method has been called.
+ errors (int): The number of times the error method has been called.
+ text_ctr (int): The number of times the text method has been called.
+ ignore_llm_ (bool): Whether to ignore llm callbacks.
+ ignore_chain_ (bool): Whether to ignore chain callbacks.
+ ignore_agent_ (bool): Whether to ignore agent callbacks.
+ ignore_retriever_ (bool): Whether to ignore retriever callbacks.
+ always_verbose_ (bool): Whether to always be verbose.
+ chain_starts (int): The number of times the chain start method has been called.
+ chain_ends (int): The number of times the chain end method has been called.
+ llm_starts (int): The number of times the llm start method has been called.
+ llm_ends (int): The number of times the llm end method has been called.
+ llm_streams (int): The number of times the text method has been called.
+ tool_starts (int): The number of times the tool start method has been called.
+ tool_ends (int): The number of times the tool end method has been called.
+ agent_ends (int): The number of times the agent end method has been called.
+ on_llm_start_records (list): A list of records of the on_llm_start method.
+ on_llm_token_records (list): A list of records of the on_llm_token method.
+ on_llm_end_records (list): A list of records of the on_llm_end method.
+ on_chain_start_records (list): A list of records of the on_chain_start method.
+ on_chain_end_records (list): A list of records of the on_chain_end method.
+ on_tool_start_records (list): A list of records of the on_tool_start method.
+ on_tool_end_records (list): A list of records of the on_tool_end method.
+ on_agent_finish_records (list): A list of records of the on_agent_end method.
+ """
+
+ def __init__(self) -> None:
+ self.step = 0
+
+ self.starts = 0
+ self.ends = 0
+ self.errors = 0
+ self.text_ctr = 0
+
+ self.ignore_llm_ = False
+ self.ignore_chain_ = False
+ self.ignore_agent_ = False
+ self.ignore_retriever_ = False
+ self.always_verbose_ = False
+
+ self.chain_starts = 0
+ self.chain_ends = 0
+
+ self.llm_starts = 0
+ self.llm_ends = 0
+ self.llm_streams = 0
+
+ self.tool_starts = 0
+ self.tool_ends = 0
+
+ self.agent_ends = 0
+
+ self.on_llm_start_records: list = []
+ self.on_llm_token_records: list = []
+ self.on_llm_end_records: list = []
+
+ self.on_chain_start_records: list = []
+ self.on_chain_end_records: list = []
+
+ self.on_tool_start_records: list = []
+ self.on_tool_end_records: list = []
+
+ self.on_text_records: list = []
+ self.on_agent_finish_records: list = []
+ self.on_agent_action_records: list = []
+
+ @property
+ def always_verbose(self) -> bool:
+ """Whether to call verbose callbacks even if verbose is False."""
+ return self.always_verbose_
+
+ @property
+ def ignore_llm(self) -> bool:
+ """Whether to ignore LLM callbacks."""
+ return self.ignore_llm_
+
+ @property
+ def ignore_chain(self) -> bool:
+ """Whether to ignore chain callbacks."""
+ return self.ignore_chain_
+
+ @property
+ def ignore_agent(self) -> bool:
+ """Whether to ignore agent callbacks."""
+ return self.ignore_agent_
+
+ def get_custom_callback_meta(self) -> Dict[str, Any]:
+ return {
+ "step": self.step,
+ "starts": self.starts,
+ "ends": self.ends,
+ "errors": self.errors,
+ "text_ctr": self.text_ctr,
+ "chain_starts": self.chain_starts,
+ "chain_ends": self.chain_ends,
+ "llm_starts": self.llm_starts,
+ "llm_ends": self.llm_ends,
+ "llm_streams": self.llm_streams,
+ "tool_starts": self.tool_starts,
+ "tool_ends": self.tool_ends,
+ "agent_ends": self.agent_ends,
+ }
+
+ def reset_callback_meta(self) -> None:
+ """Reset the callback metadata."""
+ self.step = 0
+
+ self.starts = 0
+ self.ends = 0
+ self.errors = 0
+ self.text_ctr = 0
+
+ self.ignore_llm_ = False
+ self.ignore_chain_ = False
+ self.ignore_agent_ = False
+ self.always_verbose_ = False
+
+ self.chain_starts = 0
+ self.chain_ends = 0
+
+ self.llm_starts = 0
+ self.llm_ends = 0
+ self.llm_streams = 0
+
+ self.tool_starts = 0
+ self.tool_ends = 0
+
+ self.agent_ends = 0
+
+ self.on_llm_start_records = []
+ self.on_llm_token_records = []
+ self.on_llm_end_records = []
+
+ self.on_chain_start_records = []
+ self.on_chain_end_records = []
+
+ self.on_tool_start_records = []
+ self.on_tool_end_records = []
+
+ self.on_text_records = []
+ self.on_agent_finish_records = []
+ self.on_agent_action_records = []
+ return None
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/wandb_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/wandb_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bd6d260baa669e760bc5ea0bfd9ccecb33f142f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/wandb_callback.py
@@ -0,0 +1,597 @@
+import json
+import tempfile
+from copy import deepcopy
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Sequence, Union
+
+from langchain_core._api import warn_deprecated
+from langchain_core.agents import AgentAction, AgentFinish
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.outputs import LLMResult
+from langchain_core.utils import guard_import
+
+from langchain_community.callbacks.utils import (
+ BaseMetadataCallbackHandler,
+ flatten_dict,
+ hash_string,
+ import_pandas,
+ import_spacy,
+ import_textstat,
+)
+
+
+def import_wandb() -> Any:
+ """Import the wandb python package and raise an error if it is not installed."""
+ return guard_import("wandb")
+
+
+def load_json_to_dict(json_path: Union[str, Path]) -> dict:
+ """Load json file to a dictionary.
+
+ Parameters:
+ json_path (str): The path to the json file.
+
+ Returns:
+ (dict): The dictionary representation of the json file.
+ """
+ with open(json_path, "r") as f:
+ data = json.load(f)
+ return data
+
+
+def analyze_text(
+ text: str,
+ complexity_metrics: bool = True,
+ visualize: bool = True,
+ nlp: Any = None,
+ output_dir: Optional[Union[str, Path]] = None,
+) -> dict:
+ """Analyze text using textstat and spacy.
+
+ Parameters:
+ text (str): The text to analyze.
+ complexity_metrics (bool): Whether to compute complexity metrics.
+ visualize (bool): Whether to visualize the text.
+ nlp (spacy.lang): The spacy language model to use for visualization.
+ output_dir (str): The directory to save the visualization files to.
+
+ Returns:
+ `dict` containing the complexity metrics and visualization
+ files serialized in a wandb.Html element.
+ """
+ resp = {}
+ textstat = import_textstat()
+ wandb = import_wandb()
+ spacy = import_spacy()
+ if complexity_metrics:
+ text_complexity_metrics = {
+ "flesch_reading_ease": textstat.flesch_reading_ease(text),
+ "flesch_kincaid_grade": textstat.flesch_kincaid_grade(text),
+ "smog_index": textstat.smog_index(text),
+ "coleman_liau_index": textstat.coleman_liau_index(text),
+ "automated_readability_index": textstat.automated_readability_index(text),
+ "dale_chall_readability_score": textstat.dale_chall_readability_score(text),
+ "difficult_words": textstat.difficult_words(text),
+ "linsear_write_formula": textstat.linsear_write_formula(text),
+ "gunning_fog": textstat.gunning_fog(text),
+ "text_standard": textstat.text_standard(text),
+ "fernandez_huerta": textstat.fernandez_huerta(text),
+ "szigriszt_pazos": textstat.szigriszt_pazos(text),
+ "gutierrez_polini": textstat.gutierrez_polini(text),
+ "crawford": textstat.crawford(text),
+ "gulpease_index": textstat.gulpease_index(text),
+ "osman": textstat.osman(text),
+ }
+ resp.update(text_complexity_metrics)
+
+ if visualize and nlp and output_dir is not None:
+ doc = nlp(text)
+
+ dep_out = spacy.displacy.render(doc, style="dep", jupyter=False, page=True)
+ dep_output_path = Path(output_dir, hash_string(f"dep-{text}") + ".html")
+ dep_output_path.open("w", encoding="utf-8").write(dep_out)
+
+ ent_out = spacy.displacy.render(doc, style="ent", jupyter=False, page=True)
+ ent_output_path = Path(output_dir, hash_string(f"ent-{text}") + ".html")
+ ent_output_path.open("w", encoding="utf-8").write(ent_out)
+
+ text_visualizations = {
+ "dependency_tree": wandb.Html(str(dep_output_path)),
+ "entities": wandb.Html(str(ent_output_path)),
+ }
+ resp.update(text_visualizations)
+
+ return resp
+
+
+def construct_html_from_prompt_and_generation(prompt: str, generation: str) -> Any:
+ """Construct an html element from a prompt and a generation.
+
+ Parameters:
+ prompt (str): The prompt.
+ generation (str): The generation.
+
+ Returns:
+ (wandb.Html): The html element."""
+ wandb = import_wandb()
+ formatted_prompt = prompt.replace("\n", "
")
+ formatted_generation = generation.replace("\n", "
")
+
+ return wandb.Html(
+ f"""
+ {formatted_prompt}:
+
+
+ {formatted_generation}
+
+
+ """,
+ inject=False,
+ )
+
+
+class WandbCallbackHandler(BaseMetadataCallbackHandler, BaseCallbackHandler):
+ """Callback Handler that logs to Weights and Biases.
+
+ Parameters:
+ job_type (str): The type of job.
+ project (str): The project to log to.
+ entity (str): The entity to log to.
+ tags (list): The tags to log.
+ group (str): The group to log to.
+ name (str): The name of the run.
+ notes (str): The notes to log.
+ visualize (bool): Whether to visualize the run.
+ complexity_metrics (bool): Whether to log complexity metrics.
+ stream_logs (bool): Whether to stream callback actions to W&B
+
+ This handler will utilize the associated callback method called and formats
+ the input of each callback function with metadata regarding the state of LLM run,
+ and adds the response to the list of records for both the {method}_records and
+ action. It then logs the response using the run.log() method to Weights and Biases.
+ """
+
+ def __init__(
+ self,
+ job_type: Optional[str] = None,
+ project: Optional[str] = "langchain_callback_demo",
+ entity: Optional[str] = None,
+ tags: Optional[Sequence] = None,
+ group: Optional[str] = None,
+ name: Optional[str] = None,
+ notes: Optional[str] = None,
+ visualize: bool = False,
+ complexity_metrics: bool = False,
+ stream_logs: bool = False,
+ ) -> None:
+ """Initialize callback handler."""
+
+ wandb = import_wandb()
+ import_pandas()
+ import_textstat()
+ spacy = import_spacy()
+ super().__init__()
+
+ self.job_type = job_type
+ self.project = project
+ self.entity = entity
+ self.tags = tags
+ self.group = group
+ self.name = name
+ self.notes = notes
+ self.visualize = visualize
+ self.complexity_metrics = complexity_metrics
+ self.stream_logs = stream_logs
+
+ self.temp_dir = tempfile.TemporaryDirectory()
+ self.run = wandb.init(
+ job_type=self.job_type,
+ project=self.project,
+ entity=self.entity,
+ tags=self.tags,
+ group=self.group,
+ name=self.name,
+ notes=self.notes,
+ )
+ warning = (
+ "DEPRECATION: The `WandbCallbackHandler` will soon be deprecated in favor "
+ "of the `WandbTracer`. Please update your code to use the `WandbTracer` "
+ "instead."
+ )
+ wandb.termwarn(
+ warning,
+ repeat=False,
+ )
+ self.callback_columns: list = []
+ self.action_records: list = []
+ self.complexity_metrics = complexity_metrics
+ self.visualize = visualize
+ self.nlp = spacy.load("en_core_web_sm")
+ warn_deprecated(
+ "0.3.8",
+ pending=False,
+ message=(
+ "Please use the WeaveTracer instead of the WandbCallbackHandler. "
+ "The WeaveTracer is a more flexible and powerful tool for logging "
+ "and tracing your LangChain callables."
+ "Find more information at https://weave-docs.wandb.ai/guides/integrations/langchain"
+ ),
+ alternative=(
+ "Please instantiate the WeaveTracer from "
+ "weave.integrations.langchain import WeaveTracer ."
+ "For autologging simply use weave.init() and log all traces "
+ "from your LangChain callables."
+ ),
+ )
+
+ def _init_resp(self) -> Dict:
+ return {k: None for k in self.callback_columns}
+
+ def on_llm_start(
+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
+ ) -> None:
+ """Run when LLM starts."""
+ self.step += 1
+ self.llm_starts += 1
+ self.starts += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_llm_start"})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.get_custom_callback_meta())
+
+ for prompt in prompts:
+ prompt_resp = deepcopy(resp)
+ prompt_resp["prompts"] = prompt
+ self.on_llm_start_records.append(prompt_resp)
+ self.action_records.append(prompt_resp)
+ if self.stream_logs:
+ self.run.log(prompt_resp)
+
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Run when LLM generates a new token."""
+ self.step += 1
+ self.llm_streams += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_llm_new_token", "token": token})
+ resp.update(self.get_custom_callback_meta())
+
+ self.on_llm_token_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.run.log(resp)
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running."""
+ self.step += 1
+ self.llm_ends += 1
+ self.ends += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_llm_end"})
+ resp.update(flatten_dict(response.llm_output or {}))
+ resp.update(self.get_custom_callback_meta())
+
+ for generations in response.generations:
+ for generation in generations:
+ generation_resp = deepcopy(resp)
+ generation_resp.update(flatten_dict(generation.dict()))
+ generation_resp.update(
+ analyze_text(
+ generation.text,
+ complexity_metrics=self.complexity_metrics,
+ visualize=self.visualize,
+ nlp=self.nlp,
+ output_dir=self.temp_dir.name,
+ )
+ )
+ self.on_llm_end_records.append(generation_resp)
+ self.action_records.append(generation_resp)
+ if self.stream_logs:
+ self.run.log(generation_resp)
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when LLM errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_chain_start(
+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Run when chain starts running."""
+ self.step += 1
+ self.chain_starts += 1
+ self.starts += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_chain_start"})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.get_custom_callback_meta())
+
+ chain_input = inputs["input"]
+
+ if isinstance(chain_input, str):
+ input_resp = deepcopy(resp)
+ input_resp["input"] = chain_input
+ self.on_chain_start_records.append(input_resp)
+ self.action_records.append(input_resp)
+ if self.stream_logs:
+ self.run.log(input_resp)
+ elif isinstance(chain_input, list):
+ for inp in chain_input:
+ input_resp = deepcopy(resp)
+ input_resp.update(inp)
+ self.on_chain_start_records.append(input_resp)
+ self.action_records.append(input_resp)
+ if self.stream_logs:
+ self.run.log(input_resp)
+ else:
+ raise ValueError("Unexpected data format provided!")
+
+ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:
+ """Run when chain ends running."""
+ self.step += 1
+ self.chain_ends += 1
+ self.ends += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_chain_end", "outputs": outputs["output"]})
+ resp.update(self.get_custom_callback_meta())
+
+ self.on_chain_end_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.run.log(resp)
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when chain errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_tool_start(
+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any
+ ) -> None:
+ """Run when tool starts running."""
+ self.step += 1
+ self.tool_starts += 1
+ self.starts += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_tool_start", "input_str": input_str})
+ resp.update(flatten_dict(serialized))
+ resp.update(self.get_custom_callback_meta())
+
+ self.on_tool_start_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.run.log(resp)
+
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
+ """Run when tool ends running."""
+ output = str(output)
+ self.step += 1
+ self.tool_ends += 1
+ self.ends += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_tool_end", "output": output})
+ resp.update(self.get_custom_callback_meta())
+
+ self.on_tool_end_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.run.log(resp)
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when tool errors."""
+ self.step += 1
+ self.errors += 1
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """
+ Run when agent is ending.
+ """
+ self.step += 1
+ self.text_ctr += 1
+
+ resp = self._init_resp()
+ resp.update({"action": "on_text", "text": text})
+ resp.update(self.get_custom_callback_meta())
+
+ self.on_text_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.run.log(resp)
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run when agent ends running."""
+ self.step += 1
+ self.agent_ends += 1
+ self.ends += 1
+
+ resp = self._init_resp()
+ resp.update(
+ {
+ "action": "on_agent_finish",
+ "output": finish.return_values["output"],
+ "log": finish.log,
+ }
+ )
+ resp.update(self.get_custom_callback_meta())
+
+ self.on_agent_finish_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.run.log(resp)
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Run on agent action."""
+ self.step += 1
+ self.tool_starts += 1
+ self.starts += 1
+
+ resp = self._init_resp()
+ resp.update(
+ {
+ "action": "on_agent_action",
+ "tool": action.tool,
+ "tool_input": action.tool_input,
+ "log": action.log,
+ }
+ )
+ resp.update(self.get_custom_callback_meta())
+ self.on_agent_action_records.append(resp)
+ self.action_records.append(resp)
+ if self.stream_logs:
+ self.run.log(resp)
+
+ def _create_session_analysis_df(self) -> Any:
+ """Create a dataframe with all the information from the session."""
+ pd = import_pandas()
+ on_llm_start_records_df = pd.DataFrame(self.on_llm_start_records)
+ on_llm_end_records_df = pd.DataFrame(self.on_llm_end_records)
+
+ llm_input_prompts_df = (
+ on_llm_start_records_df[["step", "prompts", "name"]]
+ .dropna(axis=1)
+ .rename({"step": "prompt_step"}, axis=1)
+ )
+ complexity_metrics_columns = []
+ visualizations_columns = []
+
+ if self.complexity_metrics:
+ complexity_metrics_columns = [
+ "flesch_reading_ease",
+ "flesch_kincaid_grade",
+ "smog_index",
+ "coleman_liau_index",
+ "automated_readability_index",
+ "dale_chall_readability_score",
+ "difficult_words",
+ "linsear_write_formula",
+ "gunning_fog",
+ "text_standard",
+ "fernandez_huerta",
+ "szigriszt_pazos",
+ "gutierrez_polini",
+ "crawford",
+ "gulpease_index",
+ "osman",
+ ]
+
+ if self.visualize:
+ visualizations_columns = ["dependency_tree", "entities"]
+
+ llm_outputs_df = (
+ on_llm_end_records_df[
+ [
+ "step",
+ "text",
+ "token_usage_total_tokens",
+ "token_usage_prompt_tokens",
+ "token_usage_completion_tokens",
+ ]
+ + complexity_metrics_columns
+ + visualizations_columns
+ ]
+ .dropna(axis=1)
+ .rename({"step": "output_step", "text": "output"}, axis=1)
+ )
+ session_analysis_df = pd.concat([llm_input_prompts_df, llm_outputs_df], axis=1)
+ session_analysis_df["chat_html"] = session_analysis_df[
+ ["prompts", "output"]
+ ].apply(
+ lambda row: construct_html_from_prompt_and_generation(
+ row["prompts"], row["output"]
+ ),
+ axis=1,
+ )
+ return session_analysis_df
+
+ def flush_tracker(
+ self,
+ langchain_asset: Any = None,
+ reset: bool = True,
+ finish: bool = False,
+ job_type: Optional[str] = None,
+ project: Optional[str] = None,
+ entity: Optional[str] = None,
+ tags: Optional[Sequence] = None,
+ group: Optional[str] = None,
+ name: Optional[str] = None,
+ notes: Optional[str] = None,
+ visualize: Optional[bool] = None,
+ complexity_metrics: Optional[bool] = None,
+ ) -> None:
+ """Flush the tracker and reset the session.
+
+ Args:
+ langchain_asset: The langchain asset to save.
+ reset: Whether to reset the session.
+ finish: Whether to finish the run.
+ job_type: The job type.
+ project: The project.
+ entity: The entity.
+ tags: The tags.
+ group: The group.
+ name: The name.
+ notes: The notes.
+ visualize: Whether to visualize.
+ complexity_metrics: Whether to compute complexity metrics.
+
+ Returns:
+ None
+ """
+ pd = import_pandas()
+ wandb = import_wandb()
+ action_records_table = wandb.Table(dataframe=pd.DataFrame(self.action_records))
+ session_analysis_table = wandb.Table(
+ dataframe=self._create_session_analysis_df()
+ )
+ self.run.log(
+ {
+ "action_records": action_records_table,
+ "session_analysis": session_analysis_table,
+ }
+ )
+
+ if langchain_asset:
+ langchain_asset_path = Path(self.temp_dir.name, "model.json")
+ model_artifact = wandb.Artifact(name="model", type="model")
+ model_artifact.add(action_records_table, name="action_records")
+ model_artifact.add(session_analysis_table, name="session_analysis")
+ try:
+ langchain_asset.save(langchain_asset_path)
+ model_artifact.add_file(str(langchain_asset_path))
+ model_artifact.metadata = load_json_to_dict(langchain_asset_path)
+ except ValueError:
+ langchain_asset.save_agent(langchain_asset_path)
+ model_artifact.add_file(str(langchain_asset_path))
+ model_artifact.metadata = load_json_to_dict(langchain_asset_path)
+ except NotImplementedError as e:
+ print("Could not save model.") # noqa: T201
+ print(repr(e)) # noqa: T201
+ pass
+ self.run.log_artifact(model_artifact)
+
+ if finish or reset:
+ self.run.finish()
+ self.temp_dir.cleanup()
+ self.reset_callback_meta()
+ if reset:
+ self.__init__( # type: ignore[misc]
+ job_type=job_type if job_type else self.job_type,
+ project=project if project else self.project,
+ entity=entity if entity else self.entity,
+ tags=tags if tags else self.tags,
+ group=group if group else self.group,
+ name=name if name else self.name,
+ notes=notes if notes else self.notes,
+ visualize=visualize if visualize else self.visualize,
+ complexity_metrics=(
+ complexity_metrics
+ if complexity_metrics
+ else self.complexity_metrics
+ ),
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/whylabs_callback.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/whylabs_callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..abf2061857d24773ea387f60d4e3518d2295f0a4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/callbacks/whylabs_callback.py
@@ -0,0 +1,187 @@
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any, Optional
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.utils import get_from_env, guard_import
+
+if TYPE_CHECKING:
+ from whylogs.api.logger.logger import Logger
+
+diagnostic_logger = logging.getLogger(__name__)
+
+
+def import_langkit(
+ sentiment: bool = False,
+ toxicity: bool = False,
+ themes: bool = False,
+) -> Any:
+ """Import the langkit python package and raise an error if it is not installed.
+
+ Args:
+ sentiment: Whether to import the langkit.sentiment module. Defaults to False.
+ toxicity: Whether to import the langkit.toxicity module. Defaults to False.
+ themes: Whether to import the langkit.themes module. Defaults to False.
+
+ Returns:
+ The imported langkit module.
+ """
+ langkit = guard_import("langkit")
+ guard_import("langkit.regexes")
+ guard_import("langkit.textstat")
+ if sentiment:
+ guard_import("langkit.sentiment")
+ if toxicity:
+ guard_import("langkit.toxicity")
+ if themes:
+ guard_import("langkit.themes")
+ return langkit
+
+
+class WhyLabsCallbackHandler(BaseCallbackHandler):
+ """
+ Callback Handler for logging to WhyLabs. This callback handler utilizes
+ `langkit` to extract features from the prompts & responses when interacting with
+ an LLM. These features can be used to guardrail, evaluate, and observe interactions
+ over time to detect issues relating to hallucinations, prompt engineering,
+ or output validation. LangKit is an LLM monitoring toolkit developed by WhyLabs.
+
+ Here are some examples of what can be monitored with LangKit:
+ * Text Quality
+ - readability score
+ - complexity and grade scores
+ * Text Relevance
+ - Similarity scores between prompt/responses
+ - Similarity scores against user-defined themes
+ - Topic classification
+ * Security and Privacy
+ - patterns - count of strings matching a user-defined regex pattern group
+ - jailbreaks - similarity scores with respect to known jailbreak attempts
+ - prompt injection - similarity scores with respect to known prompt attacks
+ - refusals - similarity scores with respect to known LLM refusal responses
+ * Sentiment and Toxicity
+ - sentiment analysis
+ - toxicity analysis
+
+ For more information, see https://docs.whylabs.ai/docs/language-model-monitoring
+ or check out the LangKit repo here: https://github.com/whylabs/langkit
+
+ ---
+ Args:
+ api_key (Optional[str]): WhyLabs API key. Optional because the preferred
+ way to specify the API key is with environment variable
+ WHYLABS_API_KEY.
+ org_id (Optional[str]): WhyLabs organization id to write profiles to.
+ Optional because the preferred way to specify the organization id is
+ with environment variable WHYLABS_DEFAULT_ORG_ID.
+ dataset_id (Optional[str]): WhyLabs dataset id to write profiles to.
+ Optional because the preferred way to specify the dataset id is
+ with environment variable WHYLABS_DEFAULT_DATASET_ID.
+ sentiment (bool): Whether to enable sentiment analysis. Defaults to False.
+ toxicity (bool): Whether to enable toxicity analysis. Defaults to False.
+ themes (bool): Whether to enable theme analysis. Defaults to False.
+ """
+
+ def __init__(self, logger: Logger, handler: Any):
+ """Initiate the rolling logger."""
+ super().__init__()
+ if hasattr(handler, "init"):
+ handler.init(self)
+ if hasattr(handler, "_get_callbacks"):
+ self._callbacks = handler._get_callbacks()
+ else:
+ self._callbacks = dict()
+ diagnostic_logger.warning("initialized handler without callbacks.")
+ self._logger = logger
+
+ def flush(self) -> None:
+ """Explicitly write current profile if using a rolling logger."""
+ if self._logger and hasattr(self._logger, "_do_rollover"):
+ self._logger._do_rollover()
+ diagnostic_logger.info("Flushing WhyLabs logger, writing profile...")
+
+ def close(self) -> None:
+ """Close any loggers to allow writing out of any profiles before exiting."""
+ if self._logger and hasattr(self._logger, "close"):
+ self._logger.close()
+ diagnostic_logger.info("Closing WhyLabs logger, see you next time!")
+
+ def __enter__(self) -> WhyLabsCallbackHandler:
+ return self
+
+ def __exit__(
+ self, exception_type: Any, exception_value: Any, traceback: Any
+ ) -> None:
+ self.close()
+
+ @classmethod
+ def from_params(
+ cls,
+ *,
+ api_key: Optional[str] = None,
+ org_id: Optional[str] = None,
+ dataset_id: Optional[str] = None,
+ sentiment: bool = False,
+ toxicity: bool = False,
+ themes: bool = False,
+ logger: Optional[Logger] = None,
+ ) -> WhyLabsCallbackHandler:
+ """Instantiate whylogs Logger from params.
+
+ Args:
+ api_key (Optional[str]): WhyLabs API key. Optional because the preferred
+ way to specify the API key is with environment variable
+ WHYLABS_API_KEY.
+ org_id (Optional[str]): WhyLabs organization id to write profiles to.
+ If not set must be specified in environment variable
+ WHYLABS_DEFAULT_ORG_ID.
+ dataset_id (Optional[str]): The model or dataset this callback is gathering
+ telemetry for. If not set must be specified in environment variable
+ WHYLABS_DEFAULT_DATASET_ID.
+ sentiment (bool): If True will initialize a model to perform
+ sentiment analysis compound score. Defaults to False and will not gather
+ this metric.
+ toxicity (bool): If True will initialize a model to score
+ toxicity. Defaults to False and will not gather this metric.
+ themes (bool): If True will initialize a model to calculate
+ distance to configured themes. Defaults to None and will not gather this
+ metric.
+ logger (Optional[Logger]): If specified will bind the configured logger as
+ the telemetry gathering agent. Defaults to LangKit schema with periodic
+ WhyLabs writer.
+ """
+ # langkit library will import necessary whylogs libraries
+ import_langkit(sentiment=sentiment, toxicity=toxicity, themes=themes)
+
+ why = guard_import("whylogs")
+ get_callback_instance = guard_import(
+ "langkit.callback_handler"
+ ).get_callback_instance
+ WhyLabsWriter = guard_import("whylogs.api.writer.whylabs").WhyLabsWriter
+ udf_schema = guard_import("whylogs.experimental.core.udf_schema").udf_schema
+
+ if logger is None:
+ api_key = api_key or get_from_env("api_key", "WHYLABS_API_KEY")
+ org_id = org_id or get_from_env("org_id", "WHYLABS_DEFAULT_ORG_ID")
+ dataset_id = dataset_id or get_from_env(
+ "dataset_id", "WHYLABS_DEFAULT_DATASET_ID"
+ )
+ whylabs_writer = WhyLabsWriter(
+ api_key=api_key, org_id=org_id, dataset_id=dataset_id
+ )
+
+ whylabs_logger = why.logger(
+ mode="rolling", interval=5, when="M", schema=udf_schema()
+ )
+
+ whylabs_logger.append_writer(writer=whylabs_writer)
+ else:
+ diagnostic_logger.info("Using passed in whylogs logger {logger}")
+ whylabs_logger = logger
+
+ callback_handler_cls = get_callback_instance(logger=whylabs_logger, impl=cls)
+ diagnostic_logger.info(
+ "Started whylogs Logger with WhyLabsWriter and initialized LangKit. 📝"
+ )
+ return callback_handler_cls
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..37790c9601a45ec1ff71e642530cdb3d9d6d39b8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/__init__.py
@@ -0,0 +1,24 @@
+"""
+Chains module for langchain_community
+
+This module contains the community chains.
+"""
+
+import importlib
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langchain_community.chains.pebblo_retrieval.base import PebbloRetrievalQA
+
+__all__ = ["PebbloRetrievalQA"]
+
+_module_lookup = {
+ "PebbloRetrievalQA": "langchain_community.chains.pebblo_retrieval.base"
+}
+
+
+def __getattr__(name: str) -> Any:
+ if name in _module_lookup:
+ module = importlib.import_module(_module_lookup[name])
+ return getattr(module, name)
+ raise AttributeError(f"module {__name__} has no attribute {name}")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/llm_requests.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/llm_requests.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5bf412d578b3556b1a90475043a480fcdc9c97c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chains/llm_requests.py
@@ -0,0 +1,98 @@
+"""Chain that hits a URL and then uses an LLM to parse results."""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional
+
+from langchain_classic.chains import LLMChain
+from langchain_classic.chains.base import Chain
+from langchain_core.callbacks import CallbackManagerForChainRun
+from pydantic import ConfigDict, Field, model_validator
+
+from langchain_community.utilities.requests import TextRequestsWrapper
+
+DEFAULT_HEADERS = {
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" # noqa: E501
+}
+
+
+class LLMRequestsChain(Chain):
+ """Chain that requests a URL and then uses an LLM to parse results.
+
+ **Security Note**: This chain can make GET requests to arbitrary URLs,
+ including internal URLs.
+
+ Control access to who can run this chain and what network access
+ this chain has.
+
+ See https://python.langchain.com/docs/security for more information.
+ """
+
+ llm_chain: LLMChain
+ requests_wrapper: TextRequestsWrapper = Field(
+ default_factory=lambda: TextRequestsWrapper(headers=DEFAULT_HEADERS),
+ exclude=True,
+ )
+ text_length: int = 8000
+ requests_key: str = "requests_result" #: :meta private:
+ input_key: str = "url" #: :meta private:
+ output_key: str = "output" #: :meta private:
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ @property
+ def input_keys(self) -> List[str]:
+ """Will be whatever keys the prompt expects.
+
+ :meta private:
+ """
+ return [self.input_key]
+
+ @property
+ def output_keys(self) -> List[str]:
+ """Will always return text key.
+
+ :meta private:
+ """
+ return [self.output_key]
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+ try:
+ from bs4 import BeautifulSoup # noqa: F401
+
+ except ImportError:
+ raise ImportError(
+ "Could not import bs4 python package. "
+ "Please install it with `pip install bs4`."
+ )
+ return values
+
+ def _call(
+ self,
+ inputs: Dict[str, Any],
+ run_manager: Optional[CallbackManagerForChainRun] = None,
+ ) -> Dict[str, Any]:
+ from bs4 import BeautifulSoup
+
+ _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
+ # Other keys are assumed to be needed for LLM prediction
+ other_keys = {k: v for k, v in inputs.items() if k != self.input_key}
+ url = inputs[self.input_key]
+ res = self.requests_wrapper.get(url)
+ # extract the text from the html
+ soup = BeautifulSoup(res, "html.parser") # type: ignore[arg-type]
+ other_keys[self.requests_key] = soup.get_text()[: self.text_length]
+ result = self.llm_chain.predict(
+ callbacks=_run_manager.get_child(), **other_keys
+ )
+ return {self.output_key: result}
+
+ @property
+ def _chain_type(self) -> str:
+ return "llm_requests_chain"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..255b9b1598d0ee5f5cfd09e099f71469208de415
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/__init__.py
@@ -0,0 +1,83 @@
+"""**Chat Loaders** load chat messages from common communications platforms.
+
+Load chat messages from various
+communications platforms such as Facebook Messenger, Telegram, and
+WhatsApp. The loaded chat messages can be used for fine-tuning models.
+
+**Class hierarchy:**
+
+.. code-block::
+
+ BaseChatLoader --> ChatLoader # Examples: WhatsAppChatLoader, IMessageChatLoader
+
+**Main helpers:**
+
+.. code-block::
+
+ ChatSession
+
+""" # noqa: E501
+
+import importlib
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langchain_community.chat_loaders.base import (
+ BaseChatLoader,
+ )
+ from langchain_community.chat_loaders.facebook_messenger import (
+ FolderFacebookMessengerChatLoader,
+ SingleFileFacebookMessengerChatLoader,
+ )
+ from langchain_community.chat_loaders.gmail import (
+ GMailLoader,
+ )
+ from langchain_community.chat_loaders.imessage import (
+ IMessageChatLoader,
+ )
+ from langchain_community.chat_loaders.langsmith import (
+ LangSmithDatasetChatLoader,
+ LangSmithRunChatLoader,
+ )
+ from langchain_community.chat_loaders.slack import (
+ SlackChatLoader,
+ )
+ from langchain_community.chat_loaders.telegram import (
+ TelegramChatLoader,
+ )
+ from langchain_community.chat_loaders.whatsapp import (
+ WhatsAppChatLoader,
+ )
+
+__all__ = [
+ "BaseChatLoader",
+ "FolderFacebookMessengerChatLoader",
+ "GMailLoader",
+ "IMessageChatLoader",
+ "LangSmithDatasetChatLoader",
+ "LangSmithRunChatLoader",
+ "SingleFileFacebookMessengerChatLoader",
+ "SlackChatLoader",
+ "TelegramChatLoader",
+ "WhatsAppChatLoader",
+]
+
+_module_lookup = {
+ "BaseChatLoader": "langchain_core.chat_loaders",
+ "FolderFacebookMessengerChatLoader": "langchain_community.chat_loaders.facebook_messenger", # noqa: E501
+ "GMailLoader": "langchain_community.chat_loaders.gmail",
+ "IMessageChatLoader": "langchain_community.chat_loaders.imessage",
+ "LangSmithDatasetChatLoader": "langchain_community.chat_loaders.langsmith",
+ "LangSmithRunChatLoader": "langchain_community.chat_loaders.langsmith",
+ "SingleFileFacebookMessengerChatLoader": "langchain_community.chat_loaders.facebook_messenger", # noqa: E501
+ "SlackChatLoader": "langchain_community.chat_loaders.slack",
+ "TelegramChatLoader": "langchain_community.chat_loaders.telegram",
+ "WhatsAppChatLoader": "langchain_community.chat_loaders.whatsapp",
+}
+
+
+def __getattr__(name: str) -> Any:
+ if name in _module_lookup:
+ module = importlib.import_module(_module_lookup[name])
+ return getattr(module, name)
+ raise AttributeError(f"module {__name__} has no attribute {name}")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5207e6ef4f575cfe24dc1413e1331c3cdb05fee
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/base.py
@@ -0,0 +1,3 @@
+from langchain_core.chat_loaders import BaseChatLoader
+
+__all__ = ["BaseChatLoader"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/facebook_messenger.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/facebook_messenger.py
new file mode 100644
index 0000000000000000000000000000000000000000..44900e0f84eefc4e1212f44b595fe226142fef60
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/facebook_messenger.py
@@ -0,0 +1,78 @@
+import json
+import logging
+from pathlib import Path
+from typing import Iterator, Union
+
+from langchain_core.chat_loaders import BaseChatLoader
+from langchain_core.chat_sessions import ChatSession
+from langchain_core.messages import HumanMessage
+
+logger = logging.getLogger(__file__)
+
+
+class SingleFileFacebookMessengerChatLoader(BaseChatLoader):
+ """Load `Facebook Messenger` chat data from a single file.
+
+ Args:
+ path (Union[Path, str]): The path to the chat file.
+
+ """
+
+ def __init__(self, path: Union[Path, str]) -> None:
+ super().__init__()
+ self.file_path = path if isinstance(path, Path) else Path(path)
+
+ def lazy_load(self) -> Iterator[ChatSession]:
+ """Lazy loads the chat data from the file.
+
+ Yields:
+ ChatSession: A chat session containing the loaded messages.
+
+ """
+ with open(self.file_path) as f:
+ data = json.load(f)
+ sorted_data = sorted(data["messages"], key=lambda x: x["timestamp_ms"])
+ messages = []
+ for index, m in enumerate(sorted_data):
+ if "content" not in m:
+ logger.info(
+ f"""Skipping Message No.
+ {index + 1} as no content is present in the message"""
+ )
+ continue
+ messages.append(
+ HumanMessage(
+ content=m["content"], additional_kwargs={"sender": m["sender_name"]}
+ )
+ )
+ yield ChatSession(messages=messages)
+
+
+class FolderFacebookMessengerChatLoader(BaseChatLoader):
+ """Load `Facebook Messenger` chat data from a folder.
+
+ Args:
+ path (Union[str, Path]): The path to the directory
+ containing the chat files.
+
+ """
+
+ def __init__(self, path: Union[str, Path]) -> None:
+ super().__init__()
+ self.directory_path = Path(path) if isinstance(path, str) else path
+
+ def lazy_load(self) -> Iterator[ChatSession]:
+ """Lazy loads the chat data from the folder.
+
+ Yields:
+ ChatSession: A chat session containing the loaded messages.
+
+ """
+ inbox_path = self.directory_path / "inbox"
+ for _dir in inbox_path.iterdir():
+ if _dir.is_dir():
+ for _file in _dir.iterdir():
+ if _file.suffix.lower() == ".json":
+ file_loader = SingleFileFacebookMessengerChatLoader(path=_file)
+ for result in file_loader.lazy_load():
+ yield result
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/gmail.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/gmail.py
new file mode 100644
index 0000000000000000000000000000000000000000..03dff9c243faced9e0a931a3c5cd080dc3600c92
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/gmail.py
@@ -0,0 +1,117 @@
+import base64
+import re
+from typing import Any, Iterator
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.chat_loaders import BaseChatLoader
+from langchain_core.chat_sessions import ChatSession
+from langchain_core.messages import HumanMessage
+
+
+def _extract_email_content(msg: Any) -> HumanMessage:
+ from_email = None
+ for values in msg["payload"]["headers"]:
+ name = values["name"]
+ if name == "From":
+ from_email = values["value"]
+ if from_email is None:
+ raise ValueError
+ for part in msg["payload"]["parts"]:
+ if part["mimeType"] == "text/plain":
+ data = part["body"]["data"]
+ data = base64.urlsafe_b64decode(data).decode("utf-8")
+ # Regular expression to split the email body at the first
+ # occurrence of a line that starts with "On ... wrote:"
+ pattern = re.compile(r"\r\nOn .+(\r\n)*wrote:\r\n")
+ # Split the email body and extract the first part
+ newest_response = re.split(pattern, data)[0]
+ message = HumanMessage(
+ content=newest_response, additional_kwargs={"sender": from_email}
+ )
+ return message
+ raise ValueError
+
+
+def _get_message_data(service: Any, message: Any) -> ChatSession:
+ msg = service.users().messages().get(userId="me", id=message["id"]).execute()
+ message_content = _extract_email_content(msg)
+ in_reply_to = None
+ email_data = msg["payload"]["headers"]
+ for values in email_data:
+ name = values["name"]
+ if name == "In-Reply-To":
+ in_reply_to = values["value"]
+ if in_reply_to is None:
+ raise ValueError
+
+ thread_id = msg["threadId"]
+
+ thread = service.users().threads().get(userId="me", id=thread_id).execute()
+ messages = thread["messages"]
+
+ response_email = None
+ for message in messages:
+ email_data = message["payload"]["headers"]
+ for values in email_data:
+ if values["name"] == "Message-ID":
+ message_id = values["value"]
+ if message_id == in_reply_to:
+ response_email = message
+ if response_email is None:
+ raise ValueError
+ starter_content = _extract_email_content(response_email)
+ return ChatSession(messages=[starter_content, message_content])
+
+
+@deprecated(
+ since="0.0.32",
+ removal="1.0",
+ alternative_import="langchain_google_community.GMailLoader",
+)
+class GMailLoader(BaseChatLoader):
+ """Load data from `GMail`.
+
+ There are many ways you could want to load data from GMail.
+ This loader is currently fairly opinionated in how to do so.
+ The way it does it is it first looks for all messages that you have sent.
+ It then looks for messages where you are responding to a previous email.
+ It then fetches that previous email, and creates a training example
+ of that email, followed by your email.
+
+ Note that there are clear limitations here. For example,
+ all examples created are only looking at the previous email for context.
+
+ To use:
+
+ - Set up a Google Developer Account:
+ Go to the Google Developer Console, create a project,
+ and enable the Gmail API for that project.
+ This will give you a credentials.json file that you'll need later.
+ """
+
+ def __init__(self, creds: Any, n: int = 100, raise_error: bool = False) -> None:
+ super().__init__()
+ self.creds = creds
+ self.n = n
+ self.raise_error = raise_error
+
+ def lazy_load(self) -> Iterator[ChatSession]:
+ from googleapiclient.discovery import build
+
+ service = build("gmail", "v1", credentials=self.creds)
+ results = (
+ service.users()
+ .messages()
+ .list(userId="me", labelIds=["SENT"], maxResults=self.n)
+ .execute()
+ )
+ messages = results.get("messages", [])
+ for message in messages:
+ try:
+ yield _get_message_data(service, message)
+ except Exception as e:
+ # TODO: handle errors better
+ if self.raise_error:
+ raise e
+ else:
+ pass
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/imessage.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/imessage.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6a1dd00d5f7dc68bc2585def031bb1ff4e7aa92
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/imessage.py
@@ -0,0 +1,221 @@
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from typing import TYPE_CHECKING, Iterator, List, Optional, Union
+
+from langchain_core.chat_loaders import BaseChatLoader
+from langchain_core.chat_sessions import ChatSession
+from langchain_core.messages import HumanMessage
+
+if TYPE_CHECKING:
+ import sqlite3
+
+
+def nanoseconds_from_2001_to_datetime(nanoseconds: int) -> datetime:
+ """Convert nanoseconds since 2001 to a datetime object.
+
+ Args:
+ nanoseconds (int): Nanoseconds since January 1, 2001.
+
+ Returns:
+ datetime: Datetime object.
+ """
+ # Convert nanoseconds to seconds (1 second = 1e9 nanoseconds)
+ timestamp_in_seconds = nanoseconds / 1e9
+
+ # The reference date is January 1, 2001, in Unix time
+ reference_date_seconds = datetime(2001, 1, 1).timestamp()
+
+ # Calculate the actual timestamp by adding the reference date
+ actual_timestamp = reference_date_seconds + timestamp_in_seconds
+
+ # Convert to a datetime object
+ return datetime.fromtimestamp(actual_timestamp)
+
+
+class IMessageChatLoader(BaseChatLoader):
+ """Load chat sessions from the `iMessage` chat.db SQLite file.
+
+ It only works on macOS when you have iMessage enabled and have the chat.db file.
+
+ The chat.db file is likely located at ~/Library/Messages/chat.db. However, your
+ terminal may not have permission to access this file. To resolve this, you can
+ copy the file to a different location, change the permissions of the file, or
+ grant full disk access for your terminal emulator
+ in System Settings > Security and Privacy > Full Disk Access.
+ """
+
+ def __init__(self, path: Optional[Union[str, Path]] = None):
+ """
+ Initialize the IMessageChatLoader.
+
+ Args:
+ path (str or Path, optional): Path to the chat.db SQLite file.
+ Defaults to None, in which case the default path
+ ~/Library/Messages/chat.db will be used.
+ """
+ if path is None:
+ path = Path.home() / "Library" / "Messages" / "chat.db"
+ self.db_path = path if isinstance(path, Path) else Path(path)
+ if not self.db_path.exists():
+ raise FileNotFoundError(f"File {self.db_path} not found")
+ try:
+ import sqlite3 # noqa: F401
+ except ImportError as e:
+ raise ImportError(
+ "The sqlite3 module is required to load iMessage chats.\n"
+ "Please install it with `pip install pysqlite3`"
+ ) from e
+
+ @staticmethod
+ def _parse_attributed_body(attributed_body: bytes) -> str:
+ """
+ Parse the attributedBody field of the message table
+ for the text content of the message.
+
+ The attributedBody field is a binary blob that contains
+ the message content after the byte string b"NSString":
+
+ 5 bytes 1-3 bytes `len` bytes
+ ... | b"NSString" | preamble | `len` | contents | ...
+
+ The 5 preamble bytes are always b"\x01\x94\x84\x01+"
+
+ The size of `len` is either 1 byte or 3 bytes:
+ - If the first byte in `len` is b"\x81" then `len` is 3 bytes long.
+ So the message length is the 2 bytes after, in little Endian.
+ - Otherwise, the size of `len` is 1 byte, and the message length is
+ that byte.
+
+ Args:
+ attributed_body (bytes): attributedBody field of the message table.
+ Return:
+ str: Text content of the message.
+ """
+ content = attributed_body.split(b"NSString")[1][5:]
+ length, start = content[0], 1
+ if content[0] == 129:
+ length, start = int.from_bytes(content[1:3], "little"), 3
+ return content[start : start + length].decode("utf-8", errors="ignore")
+
+ @staticmethod
+ def _get_session_query(use_chat_handle_table: bool) -> str:
+ # Messages sent pre OSX 12 require a join through the chat_handle_join table
+ # However, the table doesn't exist if database created with OSX 12 or above.
+
+ joins_w_chat_handle = """
+ JOIN chat_handle_join ON
+ chat_message_join.chat_id = chat_handle_join.chat_id
+ JOIN handle ON
+ handle.ROWID = chat_handle_join.handle_id"""
+
+ joins_no_chat_handle = """
+ JOIN handle ON message.handle_id = handle.ROWID
+ """
+
+ joins = joins_w_chat_handle if use_chat_handle_table else joins_no_chat_handle
+
+ return f"""
+ SELECT message.date,
+ handle.id,
+ message.text,
+ message.is_from_me,
+ message.attributedBody
+ FROM message
+ JOIN chat_message_join ON
+ message.ROWID = chat_message_join.message_id
+ {joins}
+ WHERE chat_message_join.chat_id = ?
+ ORDER BY message.date ASC;
+ """
+
+ def _load_single_chat_session(
+ self, cursor: "sqlite3.Cursor", use_chat_handle_table: bool, chat_id: int
+ ) -> ChatSession:
+ """
+ Load a single chat session from the iMessage chat.db.
+
+ Args:
+ cursor: SQLite cursor object.
+ chat_id (int): ID of the chat session to load.
+
+ Returns:
+ ChatSession: Loaded chat session.
+ """
+ results: List[HumanMessage] = []
+
+ query = self._get_session_query(use_chat_handle_table)
+ cursor.execute(query, (chat_id,))
+ messages = cursor.fetchall()
+
+ for date, sender, text, is_from_me, attributedBody in messages:
+ if text:
+ content = text
+ elif attributedBody:
+ content = self._parse_attributed_body(attributedBody)
+ else: # Skip messages with no content
+ continue
+
+ results.append(
+ HumanMessage(
+ role=sender,
+ content=content,
+ additional_kwargs={
+ "message_time": date,
+ "message_time_as_datetime": nanoseconds_from_2001_to_datetime(
+ date
+ ),
+ "sender": sender,
+ "is_from_me": bool(is_from_me),
+ },
+ )
+ )
+
+ return ChatSession(messages=results)
+
+ def lazy_load(self) -> Iterator[ChatSession]:
+ """
+ Lazy load the chat sessions from the iMessage chat.db
+ and yield them in the required format.
+
+ Yields:
+ ChatSession: Loaded chat session.
+ """
+ import sqlite3
+
+ try:
+ conn = sqlite3.connect(self.db_path)
+ except sqlite3.OperationalError as e:
+ raise ValueError(
+ f"Could not open iMessage DB file {self.db_path}.\n"
+ "Make sure your terminal emulator has disk access to this file.\n"
+ " You can either copy the DB file to an accessible location"
+ " or grant full disk access for your terminal emulator."
+ " You can grant full disk access for your terminal emulator"
+ " in System Settings > Security and Privacy > Full Disk Access."
+ ) from e
+ cursor = conn.cursor()
+
+ # See if chat_handle_join table exists:
+ query = """SELECT name FROM sqlite_master
+ WHERE type='table' AND name='chat_handle_join';"""
+
+ cursor.execute(query)
+ is_chat_handle_join_exists = cursor.fetchone()
+
+ # Fetch the list of chat IDs sorted by time (most recent first)
+ query = """SELECT chat_id
+ FROM message
+ JOIN chat_message_join ON message.ROWID = chat_message_join.message_id
+ GROUP BY chat_id
+ ORDER BY MAX(date) DESC;"""
+ cursor.execute(query)
+ chat_ids = [row[0] for row in cursor.fetchall()]
+
+ for chat_id in chat_ids:
+ yield self._load_single_chat_session(
+ cursor, is_chat_handle_join_exists, chat_id
+ )
+
+ conn.close()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/langsmith.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/langsmith.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f3ac6cdd7d383968681aaa8605f2aa74d8c3505
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/langsmith.py
@@ -0,0 +1,159 @@
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Dict, Iterable, Iterator, List, Optional, Union, cast
+
+from langchain_core.chat_loaders import BaseChatLoader
+from langchain_core.chat_sessions import ChatSession
+from langchain_core.load.load import load
+
+if TYPE_CHECKING:
+ from langsmith.client import Client
+ from langsmith.schemas import Run
+
+logger = logging.getLogger(__name__)
+
+
+class LangSmithRunChatLoader(BaseChatLoader):
+ """
+ Load chat sessions from a list of LangSmith "llm" runs.
+
+ Attributes:
+ runs (Iterable[Union[str, Run]]): The list of LLM run IDs or run objects.
+ client (Client): Instance of LangSmith client for fetching data.
+ """
+
+ def __init__(
+ self, runs: Iterable[Union[str, Run]], client: Optional["Client"] = None
+ ):
+ """
+ Initialize a new LangSmithRunChatLoader instance.
+
+ :param runs: List of LLM run IDs or run objects.
+ :param client: An instance of LangSmith client, if not provided,
+ a new client instance will be created.
+ """
+ from langsmith.client import Client
+
+ self.runs = runs
+ self.client = client or Client()
+
+ @staticmethod
+ def _load_single_chat_session(llm_run: "Run") -> ChatSession:
+ """
+ Convert an individual LangSmith LLM run to a ChatSession.
+
+ :param llm_run: The LLM run object.
+ :return: A chat session representing the run's data.
+ """
+ chat_session = LangSmithRunChatLoader._get_messages_from_llm_run(llm_run)
+ functions = LangSmithRunChatLoader._get_functions_from_llm_run(llm_run)
+ if functions:
+ chat_session["functions"] = functions
+ return chat_session
+
+ @staticmethod
+ def _get_messages_from_llm_run(llm_run: "Run") -> ChatSession:
+ """
+ Extract messages from a LangSmith LLM run.
+
+ :param llm_run: The LLM run object.
+ :return: ChatSession with the extracted messages.
+ """
+ if llm_run.run_type != "llm":
+ raise ValueError(f"Expected run of type llm. Got: {llm_run.run_type}")
+ if "messages" not in llm_run.inputs:
+ raise ValueError(f"Run has no 'messages' inputs. Got {llm_run.inputs}")
+ if not llm_run.outputs:
+ raise ValueError("Cannot convert pending run")
+ messages = load(llm_run.inputs)["messages"]
+ message_chunk = load(llm_run.outputs)["generations"][0]["message"]
+ return ChatSession(messages=messages + [message_chunk])
+
+ @staticmethod
+ def _get_functions_from_llm_run(llm_run: "Run") -> Optional[List[Dict]]:
+ """
+ Extract functions from a LangSmith LLM run if they exist.
+
+ :param llm_run: The LLM run object.
+ :return: Functions from the run or None.
+ """
+ if llm_run.run_type != "llm":
+ raise ValueError(f"Expected run of type llm. Got: {llm_run.run_type}")
+ return (llm_run.extra or {}).get("invocation_params", {}).get("functions")
+
+ def lazy_load(self) -> Iterator[ChatSession]:
+ """
+ Lazy load the chat sessions from the iterable of run IDs.
+
+ This method fetches the runs and converts them to chat sessions on-the-fly,
+ yielding one session at a time.
+
+ :return: Iterator of chat sessions containing messages.
+ """
+ from langsmith.schemas import Run
+
+ for run_obj in self.runs:
+ try:
+ if hasattr(run_obj, "id"):
+ run = run_obj
+ else:
+ run = self.client.read_run(run_obj)
+ session = self._load_single_chat_session(cast(Run, run))
+ yield session
+ except ValueError as e:
+ logger.warning(f"Could not load run {run_obj}: {repr(e)}")
+ continue
+
+
+class LangSmithDatasetChatLoader(BaseChatLoader):
+ """
+ Load chat sessions from a LangSmith dataset with the "chat" data type.
+
+ Attributes:
+ dataset_name (str): The name of the LangSmith dataset.
+ client (Client): Instance of LangSmith client for fetching data.
+ """
+
+ def __init__(self, *, dataset_name: str, client: Optional["Client"] = None):
+ """
+ Initialize a new LangSmithChatDatasetLoader instance.
+
+ :param dataset_name: The name of the LangSmith dataset.
+ :param client: An instance of LangSmith client; if not provided,
+ a new client instance will be created.
+ """
+ try:
+ from langsmith.client import Client
+ except ImportError as e:
+ raise ImportError(
+ "The LangSmith client is required to load LangSmith datasets.\n"
+ "Please install it with `pip install langsmith`"
+ ) from e
+
+ self.dataset_name = dataset_name
+ self.client = client or Client()
+
+ def lazy_load(self) -> Iterator[ChatSession]:
+ """
+ Lazy load the chat sessions from the specified LangSmith dataset.
+
+ This method fetches the chat data from the dataset and
+ converts each data point to chat sessions on-the-fly,
+ yielding one session at a time.
+
+ :return: Iterator of chat sessions containing messages.
+ """
+ from langchain_community.adapters import openai as oai_adapter
+
+ data = self.client.read_dataset_openai_finetuning(
+ dataset_name=self.dataset_name
+ )
+ for data_point in data:
+ yield ChatSession(
+ messages=[
+ oai_adapter.convert_dict_to_message(m)
+ for m in data_point.get("messages", [])
+ ],
+ functions=data_point.get("functions"),
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/slack.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/slack.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ce31f4e5466f557ff59e158a2e85dd9a0689e2a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/slack.py
@@ -0,0 +1,87 @@
+import json
+import logging
+import re
+import zipfile
+from pathlib import Path
+from typing import Dict, Iterator, List, Union
+
+from langchain_core.chat_loaders import BaseChatLoader
+from langchain_core.chat_sessions import ChatSession
+from langchain_core.messages import AIMessage, HumanMessage
+
+logger = logging.getLogger(__name__)
+
+
+class SlackChatLoader(BaseChatLoader):
+ """Load `Slack` conversations from a dump zip file."""
+
+ def __init__(
+ self,
+ path: Union[str, Path],
+ ):
+ """
+ Initialize the chat loader with the path to the exported Slack dump zip file.
+
+ :param path: Path to the exported Slack dump zip file.
+ """
+ self.zip_path = path if isinstance(path, Path) else Path(path)
+ if not self.zip_path.exists():
+ raise FileNotFoundError(f"File {self.zip_path} not found")
+
+ @staticmethod
+ def _load_single_chat_session(messages: List[Dict]) -> ChatSession:
+ results: List[Union[AIMessage, HumanMessage]] = []
+ previous_sender = None
+ for message in messages:
+ if not isinstance(message, dict):
+ continue
+ text = message.get("text", "")
+ timestamp = message.get("ts", "")
+ sender = message.get("user", "")
+ if not sender:
+ continue
+ skip_pattern = re.compile(
+ r"<@U\d+> has joined the channel", flags=re.IGNORECASE
+ )
+ if skip_pattern.match(text):
+ continue
+ if sender == previous_sender:
+ results[-1].content += "\n\n" + text
+ results[-1].additional_kwargs["events"].append(
+ {"message_time": timestamp}
+ )
+ else:
+ results.append(
+ HumanMessage(
+ role=sender,
+ content=text,
+ additional_kwargs={
+ "sender": sender,
+ "events": [{"message_time": timestamp}],
+ },
+ )
+ )
+ previous_sender = sender
+ return ChatSession(messages=results)
+
+ @staticmethod
+ def _read_json(zip_file: zipfile.ZipFile, file_path: str) -> List[dict]:
+ """Read JSON data from a zip subfile."""
+ with zip_file.open(file_path, "r") as f:
+ data = json.load(f)
+ if not isinstance(data, list):
+ raise ValueError(f"Expected list of dictionaries, got {type(data)}")
+ return data
+
+ def lazy_load(self) -> Iterator[ChatSession]:
+ """
+ Lazy load the chat sessions from the Slack dump file and yield them
+ in the required format.
+
+ :return: Iterator of chat sessions containing messages.
+ """
+ with zipfile.ZipFile(str(self.zip_path), "r") as zip_file:
+ for file_path in zip_file.namelist():
+ if file_path.endswith(".json"):
+ messages = self._read_json(zip_file, file_path)
+ yield self._load_single_chat_session(messages)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/telegram.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/telegram.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5d153856cdc62f07ec8adc19883355a332d1247
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/telegram.py
@@ -0,0 +1,155 @@
+import json
+import logging
+import os
+import tempfile
+import zipfile
+from pathlib import Path
+from typing import Iterator, List, Union
+
+from langchain_core.chat_loaders import BaseChatLoader
+from langchain_core.chat_sessions import ChatSession
+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
+
+logger = logging.getLogger(__name__)
+
+
+class TelegramChatLoader(BaseChatLoader):
+ """Load `telegram` conversations to LangChain chat messages.
+
+ To export, use the Telegram Desktop app from
+ https://desktop.telegram.org/, select a conversation, click the three dots
+ in the top right corner, and select "Export chat history". Then select
+ "Machine-readable JSON" (preferred) to export. Note: the 'lite' versions of
+ the desktop app (like "Telegram for MacOS") do not support exporting chat
+ history.
+ """
+
+ def __init__(
+ self,
+ path: Union[str, Path],
+ ):
+ """Initialize the TelegramChatLoader.
+
+ Args:
+ path (Union[str, Path]): Path to the exported Telegram chat zip,
+ directory, json, or HTML file.
+ """
+ self.path = path if isinstance(path, str) else str(path)
+
+ @staticmethod
+ def _load_single_chat_session_html(file_path: str) -> ChatSession:
+ """Load a single chat session from an HTML file.
+
+ Args:
+ file_path (str): Path to the HTML file.
+
+ Returns:
+ ChatSession: The loaded chat session.
+ """
+ try:
+ from bs4 import BeautifulSoup
+ except ImportError:
+ raise ImportError(
+ "Please install the 'beautifulsoup4' package to load"
+ " Telegram HTML files. You can do this by running"
+ "'pip install beautifulsoup4' in your terminal."
+ )
+ with open(file_path, "r", encoding="utf-8") as file:
+ soup = BeautifulSoup(file, "html.parser")
+
+ results: List[Union[HumanMessage, AIMessage]] = []
+ previous_sender = None
+ for message in soup.select(".message.default"):
+ timestamp = message.select_one(".pull_right.date.details")["title"] # type: ignore[index]
+ from_name_element = message.select_one(".from_name")
+ if from_name_element is None and previous_sender is None:
+ logger.debug("from_name not found in message")
+ continue
+ elif from_name_element is None:
+ from_name = previous_sender
+ else:
+ from_name = from_name_element.text.strip()
+ text = message.select_one(".text").text.strip() # type: ignore[union-attr]
+ results.append(
+ HumanMessage(
+ content=text,
+ additional_kwargs={
+ "sender": from_name,
+ "events": [{"message_time": timestamp}],
+ },
+ )
+ )
+ previous_sender = from_name
+
+ return ChatSession(messages=results)
+
+ @staticmethod
+ def _load_single_chat_session_json(file_path: str) -> ChatSession:
+ """Load a single chat session from a JSON file.
+
+ Args:
+ file_path (str): Path to the JSON file.
+
+ Returns:
+ ChatSession: The loaded chat session.
+ """
+ with open(file_path, "r", encoding="utf-8") as file:
+ data = json.load(file)
+
+ messages = data.get("messages", [])
+ results: List[BaseMessage] = []
+ for message in messages:
+ text = message.get("text", "")
+ timestamp = message.get("date", "")
+ from_name = message.get("from", "")
+ if from_name is None:
+ from_name = "Deleted Account"
+
+ results.append(
+ HumanMessage(
+ content=text,
+ additional_kwargs={
+ "sender": from_name,
+ "events": [{"message_time": timestamp}],
+ },
+ )
+ )
+
+ return ChatSession(messages=results)
+
+ @staticmethod
+ def _iterate_files(path: str) -> Iterator[str]:
+ """Iterate over files in a directory or zip file.
+
+ Args:
+ path (str): Path to the directory or zip file.
+
+ Yields:
+ str: Path to each file.
+ """
+ if os.path.isfile(path) and path.endswith((".html", ".json")):
+ yield path
+ elif os.path.isdir(path):
+ for root, _, files in os.walk(path):
+ for file in files:
+ if file.endswith((".html", ".json")):
+ yield os.path.join(root, file)
+ elif zipfile.is_zipfile(path):
+ with zipfile.ZipFile(path) as zip_file:
+ for file in zip_file.namelist():
+ if file.endswith((".html", ".json")):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ yield zip_file.extract(file, path=temp_dir)
+
+ def lazy_load(self) -> Iterator[ChatSession]:
+ """Lazy load the messages from the chat file and yield them
+ in as chat sessions.
+
+ Yields:
+ ChatSession: The loaded chat session.
+ """
+ for file_path in self._iterate_files(self.path):
+ if file_path.endswith(".html"):
+ yield self._load_single_chat_session_html(file_path)
+ elif file_path.endswith(".json"):
+ yield self._load_single_chat_session_json(file_path)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..15811c24228522eaa9efa3b5d6c570dcf3d6a89a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/utils.py
@@ -0,0 +1,104 @@
+"""Utilities for chat loaders."""
+
+from copy import deepcopy
+from typing import Iterable, Iterator, List
+
+from langchain_core.chat_sessions import ChatSession
+from langchain_core.messages import AIMessage, BaseMessage
+
+
+def merge_chat_runs_in_session(
+ chat_session: ChatSession, delimiter: str = "\n\n"
+) -> ChatSession:
+ """Merge chat runs together in a chat session.
+
+ A chat run is a sequence of messages from the same sender.
+
+ Args:
+ chat_session: A chat session.
+
+ Returns:
+ A chat session with merged chat runs.
+ """
+ messages: List[BaseMessage] = []
+ for message in chat_session["messages"]:
+ if isinstance(message.content, list):
+ text = ""
+ for content in message.content:
+ if isinstance(content, dict):
+ text += content.get("text", "") or ""
+ else:
+ text += content
+ message.content = text
+ if not isinstance(message.content, str):
+ raise ValueError(
+ "Chat Loaders only support messages with content type string, "
+ f"got {message.content}"
+ )
+ if not messages:
+ messages.append(deepcopy(message))
+ elif (
+ isinstance(message, type(messages[-1]))
+ and messages[-1].additional_kwargs.get("sender") is not None
+ and messages[-1].additional_kwargs["sender"]
+ == message.additional_kwargs.get("sender")
+ ):
+ if not isinstance(messages[-1].content, str):
+ raise ValueError(
+ "Chat Loaders only support messages with content type string, "
+ f"got {messages[-1].content}"
+ )
+ messages[-1].content = (
+ messages[-1].content + delimiter + message.content
+ ).strip()
+ messages[-1].additional_kwargs.get("events", []).extend(
+ message.additional_kwargs.get("events") or []
+ )
+ else:
+ messages.append(deepcopy(message))
+ return ChatSession(messages=messages)
+
+
+def merge_chat_runs(chat_sessions: Iterable[ChatSession]) -> Iterator[ChatSession]:
+ """Merge chat runs together.
+
+ A chat run is a sequence of messages from the same sender.
+
+ Args:
+ chat_sessions: A list of chat sessions.
+
+ Returns:
+ A list of chat sessions with merged chat runs.
+ """
+ for chat_session in chat_sessions:
+ yield merge_chat_runs_in_session(chat_session)
+
+
+def map_ai_messages_in_session(chat_sessions: ChatSession, sender: str) -> ChatSession:
+ """Convert messages from the specified 'sender' to AI messages.
+
+ This is useful for fine-tuning the AI to adapt to your voice.
+ """
+ messages = []
+ num_converted = 0
+ for message in chat_sessions["messages"]:
+ if message.additional_kwargs.get("sender") == sender:
+ message = AIMessage(
+ content=message.content,
+ additional_kwargs=message.additional_kwargs.copy(),
+ example=getattr(message, "example", None),
+ )
+ num_converted += 1
+ messages.append(message)
+ return ChatSession(messages=messages)
+
+
+def map_ai_messages(
+ chat_sessions: Iterable[ChatSession], sender: str
+) -> Iterator[ChatSession]:
+ """Convert messages from the specified 'sender' to AI messages.
+
+ This is useful for fine-tuning the AI to adapt to your voice.
+ """
+ for chat_session in chat_sessions:
+ yield map_ai_messages_in_session(chat_session, sender)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/whatsapp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/whatsapp.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e678b10632d15e48489e1640e40d7299bb878a1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_loaders/whatsapp.py
@@ -0,0 +1,119 @@
+import logging
+import os
+import re
+import zipfile
+from typing import Iterator, List, Union
+
+from langchain_core.chat_loaders import BaseChatLoader
+from langchain_core.chat_sessions import ChatSession
+from langchain_core.messages import AIMessage, HumanMessage
+
+logger = logging.getLogger(__name__)
+
+
+class WhatsAppChatLoader(BaseChatLoader):
+ """Load `WhatsApp` conversations from a dump zip file or directory."""
+
+ def __init__(self, path: str):
+ """Initialize the WhatsAppChatLoader.
+
+ Args:
+ path (str): Path to the exported WhatsApp chat
+ zip directory, folder, or file.
+
+ To generate the dump, open the chat, click the three dots in the top
+ right corner, and select "More". Then select "Export chat" and
+ choose "Without media".
+ """
+ self.path = path
+ ignore_lines = [
+ "This message was deleted",
+ "",
+ "image omitted",
+ "Messages and calls are end-to-end encrypted. No one outside of this chat,"
+ " not even WhatsApp, can read or listen to them.",
+ ]
+ self._ignore_lines = re.compile(
+ r"(" + "|".join([r"\u200E*" + line for line in ignore_lines]) + r")",
+ flags=re.IGNORECASE,
+ )
+ self._message_line_regex = re.compile(
+ r"\u200E*\[?(\d{1,2}/\d{1,2}/\d{2,4}, \d{1,2}:\d{2}:\d{2} (?:AM|PM))\]?[ \u200E]*([^:]+): (.+)", # noqa
+ flags=re.IGNORECASE,
+ )
+
+ def _load_single_chat_session(self, file_path: str) -> ChatSession:
+ """Load a single chat session from a file.
+
+ Args:
+ file_path (str): Path to the chat file.
+
+ Returns:
+ ChatSession: The loaded chat session.
+ """
+ with open(file_path, "r", encoding="utf-8") as file:
+ txt = file.read()
+
+ # Split messages by newlines, but keep multi-line messages grouped
+ chat_lines: List[str] = []
+ current_message = ""
+ for line in txt.split("\n"):
+ if self._message_line_regex.match(line):
+ if current_message:
+ chat_lines.append(current_message)
+ current_message = line
+ else:
+ current_message += " " + line.strip()
+ if current_message:
+ chat_lines.append(current_message)
+ results: List[Union[HumanMessage, AIMessage]] = []
+ for line in chat_lines:
+ result = self._message_line_regex.match(line.strip())
+ if result:
+ timestamp, sender, text = result.groups()
+ if not self._ignore_lines.match(text.strip()):
+ results.append(
+ HumanMessage(
+ role=sender,
+ content=text,
+ additional_kwargs={
+ "sender": sender,
+ "events": [{"message_time": timestamp}],
+ },
+ )
+ )
+ else:
+ logger.debug(f"Could not parse line: {line}")
+ return ChatSession(messages=results)
+
+ @staticmethod
+ def _iterate_files(path: str) -> Iterator[str]:
+ """Iterate over the files in a directory or zip file.
+
+ Args:
+ path (str): Path to the directory or zip file.
+
+ Yields:
+ str: The path to each file.
+ """
+ if os.path.isfile(path):
+ yield path
+ elif os.path.isdir(path):
+ for root, _, files in os.walk(path):
+ for file in files:
+ if file.endswith(".txt"):
+ yield os.path.join(root, file)
+ elif zipfile.is_zipfile(path):
+ with zipfile.ZipFile(path) as zip_file:
+ for file in zip_file.namelist():
+ if file.endswith(".txt"):
+ yield zip_file.extract(file)
+
+ def lazy_load(self) -> Iterator[ChatSession]:
+ """Lazy load the messages from the chat file and yield
+ them as chat sessions.
+
+ Yields:
+ Iterator[ChatSession]: The loaded chat sessions.
+ """
+ yield self._load_single_chat_session(self.path)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc20cacacceab515e6dedb0718fd260d47668e83
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/__init__.py
@@ -0,0 +1,149 @@
+"""**Chat message history** stores a history of the message interactions in a chat.
+
+
+**Class hierarchy:**
+
+.. code-block::
+
+ BaseChatMessageHistory --> ChatMessageHistory # Examples: FileChatMessageHistory, PostgresChatMessageHistory
+
+**Main helpers:**
+
+.. code-block::
+
+ AIMessage, HumanMessage, BaseMessage
+
+""" # noqa: E501
+
+import importlib
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langchain_community.chat_message_histories.astradb import (
+ AstraDBChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.cassandra import (
+ CassandraChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.cosmos_db import (
+ CosmosDBChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.dynamodb import (
+ DynamoDBChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.elasticsearch import (
+ ElasticsearchChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.file import (
+ FileChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.firestore import (
+ FirestoreChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.in_memory import (
+ ChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.kafka import (
+ KafkaChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.momento import (
+ MomentoChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.mongodb import (
+ MongoDBChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.neo4j import (
+ Neo4jChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.postgres import (
+ PostgresChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.redis import (
+ RedisChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.rocksetdb import (
+ RocksetChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.singlestoredb import (
+ SingleStoreDBChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.sql import (
+ SQLChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.streamlit import (
+ StreamlitChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.tidb import (
+ TiDBChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.upstash_redis import (
+ UpstashRedisChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.xata import (
+ XataChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.zep import (
+ ZepChatMessageHistory,
+ )
+ from langchain_community.chat_message_histories.zep_cloud import (
+ ZepCloudChatMessageHistory,
+ )
+
+__all__ = [
+ "AstraDBChatMessageHistory",
+ "CassandraChatMessageHistory",
+ "ChatMessageHistory",
+ "CosmosDBChatMessageHistory",
+ "DynamoDBChatMessageHistory",
+ "ElasticsearchChatMessageHistory",
+ "FileChatMessageHistory",
+ "FirestoreChatMessageHistory",
+ "MomentoChatMessageHistory",
+ "MongoDBChatMessageHistory",
+ "Neo4jChatMessageHistory",
+ "PostgresChatMessageHistory",
+ "RedisChatMessageHistory",
+ "RocksetChatMessageHistory",
+ "SQLChatMessageHistory",
+ "SingleStoreDBChatMessageHistory",
+ "StreamlitChatMessageHistory",
+ "TiDBChatMessageHistory",
+ "UpstashRedisChatMessageHistory",
+ "XataChatMessageHistory",
+ "ZepChatMessageHistory",
+ "ZepCloudChatMessageHistory",
+ "KafkaChatMessageHistory",
+]
+
+_module_lookup = {
+ "AstraDBChatMessageHistory": "langchain_community.chat_message_histories.astradb",
+ "CassandraChatMessageHistory": "langchain_community.chat_message_histories.cassandra", # noqa: E501
+ "ChatMessageHistory": "langchain_community.chat_message_histories.in_memory",
+ "CosmosDBChatMessageHistory": "langchain_community.chat_message_histories.cosmos_db", # noqa: E501
+ "DynamoDBChatMessageHistory": "langchain_community.chat_message_histories.dynamodb",
+ "ElasticsearchChatMessageHistory": "langchain_community.chat_message_histories.elasticsearch", # noqa: E501
+ "FileChatMessageHistory": "langchain_community.chat_message_histories.file",
+ "FirestoreChatMessageHistory": "langchain_community.chat_message_histories.firestore", # noqa: E501
+ "MomentoChatMessageHistory": "langchain_community.chat_message_histories.momento",
+ "MongoDBChatMessageHistory": "langchain_community.chat_message_histories.mongodb",
+ "Neo4jChatMessageHistory": "langchain_community.chat_message_histories.neo4j",
+ "PostgresChatMessageHistory": "langchain_community.chat_message_histories.postgres",
+ "RedisChatMessageHistory": "langchain_community.chat_message_histories.redis",
+ "RocksetChatMessageHistory": "langchain_community.chat_message_histories.rocksetdb",
+ "SQLChatMessageHistory": "langchain_community.chat_message_histories.sql",
+ "SingleStoreDBChatMessageHistory": "langchain_community.chat_message_histories.singlestoredb", # noqa: E501
+ "StreamlitChatMessageHistory": "langchain_community.chat_message_histories.streamlit", # noqa: E501
+ "TiDBChatMessageHistory": "langchain_community.chat_message_histories.tidb",
+ "UpstashRedisChatMessageHistory": "langchain_community.chat_message_histories.upstash_redis", # noqa: E501
+ "XataChatMessageHistory": "langchain_community.chat_message_histories.xata",
+ "ZepChatMessageHistory": "langchain_community.chat_message_histories.zep",
+ "ZepCloudChatMessageHistory": "langchain_community.chat_message_histories.zep_cloud", # noqa: E501
+ "KafkaChatMessageHistory": "langchain_community.chat_message_histories.kafka",
+}
+
+
+def __getattr__(name: str) -> Any:
+ if name in _module_lookup:
+ module = importlib.import_module(_module_lookup[name])
+ return getattr(module, name)
+ raise AttributeError(f"module {__name__} has no attribute {name}")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/astradb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/astradb.py
new file mode 100644
index 0000000000000000000000000000000000000000..f64339356736c8efe182e9c1fc8c9d8209037ee1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/astradb.py
@@ -0,0 +1,162 @@
+"""Astra DB - based chat message history, based on astrapy."""
+
+from __future__ import annotations
+
+import json
+import time
+from typing import TYPE_CHECKING, List, Optional, Sequence
+
+from langchain_community.utilities.astradb import (
+ SetupMode,
+ _AstraDBCollectionEnvironment,
+)
+
+if TYPE_CHECKING:
+ from astrapy.db import AstraDB, AsyncAstraDB
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ message_to_dict,
+ messages_from_dict,
+)
+
+DEFAULT_COLLECTION_NAME = "langchain_message_store"
+
+
+@deprecated(
+ since="0.0.25",
+ removal="1.0",
+ alternative_import="langchain_astradb.AstraDBChatMessageHistory",
+)
+class AstraDBChatMessageHistory(BaseChatMessageHistory):
+ def __init__(
+ self,
+ *,
+ session_id: str,
+ collection_name: str = DEFAULT_COLLECTION_NAME,
+ token: Optional[str] = None,
+ api_endpoint: Optional[str] = None,
+ astra_db_client: Optional[AstraDB] = None,
+ async_astra_db_client: Optional[AsyncAstraDB] = None,
+ namespace: Optional[str] = None,
+ setup_mode: SetupMode = SetupMode.SYNC,
+ pre_delete_collection: bool = False,
+ ) -> None:
+ """Chat message history that stores history in Astra DB.
+
+ Args:
+ session_id: arbitrary key that is used to store the messages
+ of a single chat session.
+ collection_name: name of the Astra DB collection to create/use.
+ token: API token for Astra DB usage.
+ api_endpoint: full URL to the API endpoint,
+ such as "https://-us-east1.apps.astra.datastax.com".
+ astra_db_client: *alternative to token+api_endpoint*,
+ you can pass an already-created 'astrapy.db.AstraDB' instance.
+ async_astra_db_client: *alternative to token+api_endpoint*,
+ you can pass an already-created 'astrapy.db.AsyncAstraDB' instance.
+ namespace: namespace (aka keyspace) where the
+ collection is created. Defaults to the database's "default namespace".
+ setup_mode: mode used to create the Astra DB collection (SYNC, ASYNC or
+ OFF).
+ pre_delete_collection: whether to delete the collection
+ before creating it. If False and the collection already exists,
+ the collection will be used as is.
+ """
+ self.astra_env = _AstraDBCollectionEnvironment(
+ collection_name=collection_name,
+ token=token,
+ api_endpoint=api_endpoint,
+ astra_db_client=astra_db_client,
+ async_astra_db_client=async_astra_db_client,
+ namespace=namespace,
+ setup_mode=setup_mode,
+ pre_delete_collection=pre_delete_collection,
+ )
+
+ self.collection = self.astra_env.collection
+ self.async_collection = self.astra_env.async_collection
+
+ self.session_id = session_id
+ self.collection_name = collection_name
+
+ @property
+ def messages(self) -> List[BaseMessage]:
+ """Retrieve all session messages from DB"""
+ self.astra_env.ensure_db_setup()
+ message_blobs = [
+ doc["body_blob"]
+ for doc in sorted(
+ self.collection.paginated_find(
+ filter={
+ "session_id": self.session_id,
+ },
+ projection={
+ "timestamp": 1,
+ "body_blob": 1,
+ },
+ ),
+ key=lambda _doc: _doc["timestamp"],
+ )
+ ]
+ items = [json.loads(message_blob) for message_blob in message_blobs]
+ messages = messages_from_dict(items)
+ return messages
+
+ @messages.setter
+ def messages(self, messages: List[BaseMessage]) -> None:
+ raise NotImplementedError("Use add_messages instead")
+
+ async def aget_messages(self) -> List[BaseMessage]:
+ await self.astra_env.aensure_db_setup()
+ docs = self.async_collection.paginated_find(
+ filter={
+ "session_id": self.session_id,
+ },
+ projection={
+ "timestamp": 1,
+ "body_blob": 1,
+ },
+ )
+ sorted_docs = sorted(
+ [doc async for doc in docs],
+ key=lambda _doc: _doc["timestamp"],
+ )
+ message_blobs = [doc["body_blob"] for doc in sorted_docs]
+ items = [json.loads(message_blob) for message_blob in message_blobs]
+ messages = messages_from_dict(items)
+ return messages
+
+ def add_messages(self, messages: Sequence[BaseMessage]) -> None:
+ self.astra_env.ensure_db_setup()
+ docs = [
+ {
+ "timestamp": time.time(),
+ "session_id": self.session_id,
+ "body_blob": json.dumps(message_to_dict(message)),
+ }
+ for message in messages
+ ]
+ self.collection.chunked_insert_many(docs)
+
+ async def aadd_messages(self, messages: Sequence[BaseMessage]) -> None:
+ await self.astra_env.aensure_db_setup()
+ docs = [
+ {
+ "timestamp": time.time(),
+ "session_id": self.session_id,
+ "body_blob": json.dumps(message_to_dict(message)),
+ }
+ for message in messages
+ ]
+ await self.async_collection.chunked_insert_many(docs)
+
+ def clear(self) -> None:
+ self.astra_env.ensure_db_setup()
+ self.collection.delete_many(filter={"session_id": self.session_id})
+
+ async def aclear(self) -> None:
+ await self.astra_env.aensure_db_setup()
+ await self.async_collection.delete_many(filter={"session_id": self.session_id})
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/cassandra.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/cassandra.py
new file mode 100644
index 0000000000000000000000000000000000000000..34ccf215d57f87c27efc4e6cdfac987f5dc3bec8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/cassandra.py
@@ -0,0 +1,130 @@
+"""Cassandra-based chat message history, based on cassIO."""
+
+from __future__ import annotations
+
+import json
+import uuid
+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence
+
+from langchain_community.utilities.cassandra import SetupMode
+
+if TYPE_CHECKING:
+ from cassandra.cluster import Session
+ from cassio.table.table_types import RowType
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ message_to_dict,
+ messages_from_dict,
+)
+
+DEFAULT_TABLE_NAME = "message_store"
+DEFAULT_TTL_SECONDS = None
+
+
+def _rows_to_messages(rows: Iterable[RowType]) -> List[BaseMessage]:
+ message_blobs = [row["body_blob"] for row in rows][::-1]
+ items = [json.loads(message_blob) for message_blob in message_blobs]
+ messages = messages_from_dict(items)
+ return messages
+
+
+class CassandraChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history that is backed by Cassandra."""
+
+ def __init__(
+ self,
+ session_id: str,
+ session: Optional[Session] = None,
+ keyspace: Optional[str] = None,
+ table_name: str = DEFAULT_TABLE_NAME,
+ ttl_seconds: Optional[int] = DEFAULT_TTL_SECONDS,
+ *,
+ setup_mode: SetupMode = SetupMode.SYNC,
+ ) -> None:
+ """
+ Initialize a new instance of CassandraChatMessageHistory.
+
+ Args:
+ session_id: arbitrary key that is used to store the messages
+ of a single chat session.
+ session: Cassandra driver session.
+ If not provided, it is resolved from cassio.
+ keyspace: Cassandra key space. If not provided, it is resolved from cassio.
+ table_name: name of the table to use.
+ ttl_seconds: time-to-live (seconds) for automatic expiration
+ of stored entries. None (default) for no expiration.
+ setup_mode: mode used to create the Cassandra table (SYNC, ASYNC or OFF).
+ """
+ try:
+ from cassio.table import ClusteredCassandraTable
+ except (ImportError, ModuleNotFoundError):
+ raise ImportError(
+ "Could not import cassio python package. "
+ "Please install it with `pip install cassio`."
+ )
+ self.session_id = session_id
+ self.ttl_seconds = ttl_seconds
+ kwargs: Dict[str, Any] = {}
+ if setup_mode == SetupMode.ASYNC:
+ kwargs["async_setup"] = True
+ self.table = ClusteredCassandraTable(
+ session=session,
+ keyspace=keyspace,
+ table=table_name,
+ ttl_seconds=ttl_seconds,
+ primary_key_type=["TEXT", "TIMEUUID"],
+ ordering_in_partition="DESC",
+ skip_provisioning=setup_mode == SetupMode.OFF,
+ **kwargs,
+ )
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ """Retrieve all session messages from DB"""
+ # The latest are returned, in chronological order
+ rows = self.table.get_partition(
+ partition_id=self.session_id,
+ )
+ return _rows_to_messages(rows)
+
+ async def aget_messages(self) -> List[BaseMessage]:
+ """Retrieve all session messages from DB"""
+ # The latest are returned, in chronological order
+ rows = await self.table.aget_partition(
+ partition_id=self.session_id,
+ )
+ return _rows_to_messages(rows)
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Write a message to the table
+
+ Args:
+ message: A message to write.
+ """
+ this_row_id = uuid.uuid4()
+ self.table.put(
+ partition_id=self.session_id,
+ row_id=this_row_id,
+ body_blob=json.dumps(message_to_dict(message)),
+ ttl_seconds=self.ttl_seconds,
+ )
+
+ async def aadd_messages(self, messages: Sequence[BaseMessage]) -> None:
+ for message in messages:
+ this_row_id = uuid.uuid4()
+ await self.table.aput(
+ partition_id=self.session_id,
+ row_id=this_row_id,
+ body_blob=json.dumps(message_to_dict(message)),
+ ttl_seconds=self.ttl_seconds,
+ )
+
+ def clear(self) -> None:
+ """Clear session memory from DB"""
+ self.table.delete_partition(self.session_id)
+
+ async def aclear(self) -> None:
+ """Clear session memory from DB"""
+ await self.table.adelete_partition(self.session_id)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/cosmos_db.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/cosmos_db.py
new file mode 100644
index 0000000000000000000000000000000000000000..b38316bbe6b6e96c250fd85fa7be9fd6947597c8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/cosmos_db.py
@@ -0,0 +1,173 @@
+"""Azure CosmosDB Memory History."""
+
+from __future__ import annotations
+
+import logging
+from types import TracebackType
+from typing import TYPE_CHECKING, Any, List, Optional, Type
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ messages_from_dict,
+ messages_to_dict,
+)
+
+logger = logging.getLogger(__name__)
+
+if TYPE_CHECKING:
+ from azure.cosmos import ContainerProxy
+
+
+class CosmosDBChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history backed by Azure CosmosDB."""
+
+ def __init__(
+ self,
+ cosmos_endpoint: str,
+ cosmos_database: str,
+ cosmos_container: str,
+ session_id: str,
+ user_id: str,
+ credential: Any = None,
+ connection_string: Optional[str] = None,
+ ttl: Optional[int] = None,
+ cosmos_client_kwargs: Optional[dict] = None,
+ ):
+ """
+ Initializes a new instance of the CosmosDBChatMessageHistory class.
+
+ Make sure to call prepare_cosmos or use the context manager to make
+ sure your database is ready.
+
+ Either a credential or a connection string must be provided.
+
+ :param cosmos_endpoint: The connection endpoint for the Azure Cosmos DB account.
+ :param cosmos_database: The name of the database to use.
+ :param cosmos_container: The name of the container to use.
+ :param session_id: The session ID to use, can be overwritten while loading.
+ :param user_id: The user ID to use, can be overwritten while loading.
+ :param credential: The credential to use to authenticate to Azure Cosmos DB.
+ :param connection_string: The connection string to use to authenticate.
+ :param ttl: The time to live (in seconds) to use for documents in the container.
+ :param cosmos_client_kwargs: Additional kwargs to pass to the CosmosClient.
+ """
+ self.cosmos_endpoint = cosmos_endpoint
+ self.cosmos_database = cosmos_database
+ self.cosmos_container = cosmos_container
+ self.credential = credential
+ self.conn_string = connection_string
+ self.session_id = session_id
+ self.user_id = user_id
+ self.ttl = ttl
+
+ self.messages: List[BaseMessage] = []
+ try:
+ from azure.cosmos import ( # pylint: disable=import-outside-toplevel
+ CosmosClient,
+ )
+ except ImportError as exc:
+ raise ImportError(
+ "You must install the azure-cosmos package to use the CosmosDBChatMessageHistory." # noqa: E501
+ "Please install it with `pip install azure-cosmos`."
+ ) from exc
+ if self.credential:
+ self._client = CosmosClient(
+ url=self.cosmos_endpoint,
+ credential=self.credential,
+ **cosmos_client_kwargs or {},
+ )
+ elif self.conn_string:
+ self._client = CosmosClient.from_connection_string(
+ conn_str=self.conn_string,
+ **cosmos_client_kwargs or {},
+ )
+ else:
+ raise ValueError("Either a connection string or a credential must be set.")
+ self._container: Optional[ContainerProxy] = None
+
+ def prepare_cosmos(self) -> None:
+ """Prepare the CosmosDB client.
+
+ Use this function or the context manager to make sure your database is ready.
+ """
+ try:
+ from azure.cosmos import ( # pylint: disable=import-outside-toplevel
+ PartitionKey,
+ )
+ except ImportError as exc:
+ raise ImportError(
+ "You must install the azure-cosmos package to use the CosmosDBChatMessageHistory." # noqa: E501
+ "Please install it with `pip install azure-cosmos`."
+ ) from exc
+ database = self._client.create_database_if_not_exists(self.cosmos_database)
+ self._container = database.create_container_if_not_exists(
+ self.cosmos_container,
+ partition_key=PartitionKey("/user_id"),
+ default_ttl=self.ttl,
+ )
+ self.load_messages()
+
+ def __enter__(self) -> "CosmosDBChatMessageHistory":
+ """Context manager entry point."""
+ self._client.__enter__()
+ self.prepare_cosmos()
+ return self
+
+ def __exit__(
+ self,
+ exc_type: Optional[Type[BaseException]],
+ exc_val: Optional[BaseException],
+ traceback: Optional[TracebackType],
+ ) -> None:
+ """Context manager exit"""
+ self.upsert_messages()
+ self._client.__exit__(exc_type, exc_val, traceback)
+
+ def load_messages(self) -> None:
+ """Retrieve the messages from Cosmos"""
+ if not self._container:
+ raise ValueError("Container not initialized")
+ try:
+ from azure.cosmos.exceptions import ( # pylint: disable=import-outside-toplevel
+ CosmosHttpResponseError,
+ )
+ except ImportError as exc:
+ raise ImportError(
+ "You must install the azure-cosmos package to use the CosmosDBChatMessageHistory." # noqa: E501
+ "Please install it with `pip install azure-cosmos`."
+ ) from exc
+ try:
+ item = self._container.read_item(
+ item=self.session_id, partition_key=self.user_id
+ )
+ except CosmosHttpResponseError:
+ logger.info("no session found")
+ return
+ if "messages" in item and len(item["messages"]) > 0:
+ self.messages = messages_from_dict(item["messages"])
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Add a self-created message to the store"""
+ self.messages.append(message)
+ self.upsert_messages()
+
+ def upsert_messages(self) -> None:
+ """Update the cosmosdb item."""
+ if not self._container:
+ raise ValueError("Container not initialized")
+ self._container.upsert_item(
+ body={
+ "id": self.session_id,
+ "user_id": self.user_id,
+ "messages": messages_to_dict(self.messages),
+ }
+ )
+
+ def clear(self) -> None:
+ """Clear session memory from this memory and cosmos."""
+ self.messages = []
+ if self._container:
+ self._container.delete_item(
+ item=self.session_id, partition_key=self.user_id
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/dynamodb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/dynamodb.py
new file mode 100644
index 0000000000000000000000000000000000000000..a78e6ae54aa6c0214c430d235db03917e70233a8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/dynamodb.py
@@ -0,0 +1,178 @@
+from __future__ import annotations
+
+from decimal import Decimal
+from typing import TYPE_CHECKING, Dict, List, Optional, Sequence
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ messages_from_dict,
+ messages_to_dict,
+)
+
+if TYPE_CHECKING:
+ from boto3.session import Session
+
+
+def convert_messages(item: List) -> List:
+ if isinstance(item, list):
+ return [convert_messages(i) for i in item]
+ elif isinstance(item, dict):
+ return {k: convert_messages(v) for k, v in item.items()}
+ elif isinstance(item, float):
+ return Decimal(str(item))
+ return item
+
+
+class DynamoDBChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history that stores history in AWS DynamoDB.
+
+ This class expects that a DynamoDB table exists with name `table_name`
+
+ Args:
+ table_name: name of the DynamoDB table
+ session_id: arbitrary key that is used to store the messages
+ of a single chat session.
+ endpoint_url: URL of the AWS endpoint to connect to. This argument
+ is optional and useful for test purposes, like using Localstack.
+ If you plan to use AWS cloud service, you normally don't have to
+ worry about setting the endpoint_url.
+ primary_key_name: name of the primary key of the DynamoDB table. This argument
+ is optional, defaulting to "SessionId".
+ key: an optional dictionary with a custom primary and secondary key.
+ This argument is optional, but useful when using composite dynamodb keys, or
+ isolating records based off of application details such as a user id.
+ This may also contain global and local secondary index keys.
+ kms_key_id: an optional AWS KMS Key ID, AWS KMS Key ARN, or AWS KMS Alias for
+ client-side encryption
+ ttl: Optional Time-to-live (TTL) in seconds. Allows you to define a per-item
+ expiration timestamp that indicates when an item can be deleted from the
+ table. DynamoDB handles deletion of expired items without consuming
+ write throughput. To enable this feature on the table, follow the
+ [AWS DynamoDB documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/time-to-live-ttl-how-to.html)
+ history_size: Maximum number of messages to store. If None then there is no
+ limit. If not None then only the latest `history_size` messages are stored.
+ history_messages_key: Key for the chat history where the messages
+ are stored and updated
+ coerce_float_to_decimal: If True, all float values in the messages will be
+ converted to Decimal.
+ """
+
+ def __init__(
+ self,
+ table_name: str,
+ session_id: str,
+ endpoint_url: Optional[str] = None,
+ primary_key_name: str = "SessionId",
+ key: Optional[Dict[str, str]] = None,
+ boto3_session: Optional[Session] = None,
+ kms_key_id: Optional[str] = None,
+ ttl: Optional[int] = None,
+ ttl_key_name: str = "expireAt",
+ history_size: Optional[int] = None,
+ history_messages_key: Optional[str] = "History",
+ *,
+ coerce_float_to_decimal: bool = False,
+ ):
+ if boto3_session:
+ client = boto3_session.resource("dynamodb", endpoint_url=endpoint_url)
+ else:
+ try:
+ import boto3
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import boto3, please install with `pip install boto3`."
+ ) from e
+ if endpoint_url:
+ client = boto3.resource("dynamodb", endpoint_url=endpoint_url)
+ else:
+ client = boto3.resource("dynamodb")
+ self.table = client.Table(table_name)
+ self.session_id = session_id
+ self.key: Dict = key or {primary_key_name: session_id}
+ self.ttl = ttl
+ self.ttl_key_name = ttl_key_name
+ self.history_size = history_size
+ self.history_messages_key = history_messages_key
+ self.coerce_float_to_decimal = coerce_float_to_decimal
+
+ if kms_key_id:
+ try:
+ from dynamodb_encryption_sdk.encrypted.table import EncryptedTable
+ from dynamodb_encryption_sdk.identifiers import CryptoAction
+ from dynamodb_encryption_sdk.material_providers.aws_kms import (
+ AwsKmsCryptographicMaterialsProvider,
+ )
+ from dynamodb_encryption_sdk.structures import AttributeActions
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import dynamodb_encryption_sdk, please install with "
+ "`pip install dynamodb-encryption-sdk`."
+ ) from e
+
+ actions = AttributeActions(
+ default_action=CryptoAction.DO_NOTHING,
+ attribute_actions={
+ self.history_messages_key: CryptoAction.ENCRYPT_AND_SIGN
+ },
+ )
+ aws_kms_cmp = AwsKmsCryptographicMaterialsProvider(key_id=kms_key_id)
+ self.table = EncryptedTable(
+ table=self.table,
+ materials_provider=aws_kms_cmp,
+ attribute_actions=actions,
+ auto_refresh_table_indexes=False,
+ )
+
+ @property
+ def messages(self) -> List[BaseMessage]:
+ """Retrieve the messages from DynamoDB"""
+ response = None
+ response = self.table.get_item(Key=self.key)
+
+ if response and "Item" in response:
+ items = response["Item"][self.history_messages_key]
+ else:
+ items = []
+
+ messages = messages_from_dict(items)
+ return messages
+
+ @messages.setter
+ def messages(self, messages: List[BaseMessage]) -> None:
+ raise NotImplementedError(
+ "Direct assignment to 'messages' is not allowed."
+ " Use the 'add_messages' instead."
+ )
+
+ def add_messages(self, messages: Sequence[BaseMessage]) -> None:
+ """Append the message to the record in DynamoDB"""
+ existing_messages = messages_to_dict(self.messages)
+ existing_messages.extend(messages_to_dict(messages))
+ if self.coerce_float_to_decimal:
+ existing_messages = convert_messages(existing_messages)
+
+ if self.history_size:
+ existing_messages = existing_messages[-self.history_size :]
+
+ if self.ttl:
+ import time
+
+ expireAt = int(time.time()) + self.ttl
+ self.table.update_item(
+ Key={**self.key},
+ UpdateExpression=(
+ f"set {self.history_messages_key} = :h, {self.ttl_key_name} = :t"
+ ),
+ ExpressionAttributeValues={":h": existing_messages, ":t": expireAt},
+ )
+ else:
+ self.table.update_item(
+ Key={**self.key},
+ UpdateExpression=f"set {self.history_messages_key} = :h",
+ ExpressionAttributeValues={":h": existing_messages},
+ )
+
+ def clear(self) -> None:
+ """Clear session memory from DynamoDB"""
+ self.table.delete_item(Key=self.key)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/elasticsearch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/elasticsearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..32797aea12622ff85bb276b746d6ee29bb9d43db
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/elasticsearch.py
@@ -0,0 +1,210 @@
+import json
+import logging
+from time import time
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
+
+from langchain_core._api import deprecated
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ message_to_dict,
+ messages_from_dict,
+)
+
+if TYPE_CHECKING:
+ from elasticsearch import Elasticsearch
+
+logger = logging.getLogger(__name__)
+
+
+@deprecated("0.0.27", alternative="Use langchain-elasticsearch package", pending=True)
+class ElasticsearchChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history that stores history in Elasticsearch.
+
+ Args:
+ es_url: URL of the Elasticsearch instance to connect to.
+ es_cloud_id: Cloud ID of the Elasticsearch instance to connect to.
+ es_user: Username to use when connecting to Elasticsearch.
+ es_password: Password to use when connecting to Elasticsearch.
+ es_api_key: API key to use when connecting to Elasticsearch.
+ es_connection: Optional pre-existing Elasticsearch connection.
+ ensure_ascii: Used to escape ASCII symbols in json.dumps. Defaults to True.
+ index: Name of the index to use.
+ session_id: Arbitrary key that is used to store the messages
+ of a single chat session.
+ """
+
+ def __init__(
+ self,
+ index: str,
+ session_id: str,
+ *,
+ es_connection: Optional["Elasticsearch"] = None,
+ es_url: Optional[str] = None,
+ es_cloud_id: Optional[str] = None,
+ es_user: Optional[str] = None,
+ es_api_key: Optional[str] = None,
+ es_password: Optional[str] = None,
+ ensure_ascii: Optional[bool] = True,
+ ):
+ self.index: str = index
+ self.session_id: str = session_id
+ self.ensure_ascii = ensure_ascii
+
+ # Initialize Elasticsearch client from passed client arg or connection info
+ if es_connection is not None:
+ self.client = es_connection.options(
+ headers={"user-agent": self.get_user_agent()}
+ )
+ elif es_url is not None or es_cloud_id is not None:
+ self.client = ElasticsearchChatMessageHistory.connect_to_elasticsearch(
+ es_url=es_url,
+ username=es_user,
+ password=es_password,
+ cloud_id=es_cloud_id,
+ api_key=es_api_key,
+ )
+ else:
+ raise ValueError(
+ """Either provide a pre-existing Elasticsearch connection, \
+ or valid credentials for creating a new connection."""
+ )
+
+ if self.client.indices.exists(index=index):
+ logger.debug(
+ f"Chat history index {index} already exists, skipping creation."
+ )
+ else:
+ logger.debug(f"Creating index {index} for storing chat history.")
+
+ self.client.indices.create(
+ index=index,
+ mappings={
+ "properties": {
+ "session_id": {"type": "keyword"},
+ "created_at": {"type": "date"},
+ "history": {"type": "text"},
+ }
+ },
+ )
+
+ @staticmethod
+ def get_user_agent() -> str:
+ from langchain_community import __version__
+
+ return f"langchain-py-ms/{__version__}"
+
+ @staticmethod
+ def connect_to_elasticsearch(
+ *,
+ es_url: Optional[str] = None,
+ cloud_id: Optional[str] = None,
+ api_key: Optional[str] = None,
+ username: Optional[str] = None,
+ password: Optional[str] = None,
+ ) -> "Elasticsearch":
+ try:
+ import elasticsearch
+ except ImportError:
+ raise ImportError(
+ "Could not import elasticsearch python package. "
+ "Please install it with `pip install elasticsearch`."
+ )
+
+ if es_url and cloud_id:
+ raise ValueError(
+ "Both es_url and cloud_id are defined. Please provide only one."
+ )
+
+ connection_params: Dict[str, Any] = {}
+
+ if es_url:
+ connection_params["hosts"] = [es_url]
+ elif cloud_id:
+ connection_params["cloud_id"] = cloud_id
+ else:
+ raise ValueError("Please provide either elasticsearch_url or cloud_id.")
+
+ if api_key:
+ connection_params["api_key"] = api_key
+ elif username and password:
+ connection_params["basic_auth"] = (username, password)
+
+ es_client = elasticsearch.Elasticsearch(
+ **connection_params,
+ headers={"user-agent": ElasticsearchChatMessageHistory.get_user_agent()},
+ )
+ try:
+ es_client.info()
+ except Exception as err:
+ logger.error(f"Error connecting to Elasticsearch: {err}")
+ raise err
+
+ return es_client
+
+ @property
+ def messages(self) -> List[BaseMessage]:
+ """Retrieve the messages from Elasticsearch"""
+ try:
+ from elasticsearch import ApiError
+
+ result = self.client.search(
+ index=self.index,
+ query={"term": {"session_id": self.session_id}},
+ sort="created_at:asc",
+ )
+ except ApiError as err:
+ logger.error(f"Could not retrieve messages from Elasticsearch: {err}")
+ raise err
+
+ if result and len(result["hits"]["hits"]) > 0:
+ items = [
+ json.loads(document["_source"]["history"])
+ for document in result["hits"]["hits"]
+ ]
+ else:
+ items = []
+
+ return messages_from_dict(items)
+
+ @messages.setter
+ def messages(self, messages: List[BaseMessage]) -> None:
+ raise NotImplementedError(
+ "Direct assignment to 'messages' is not allowed."
+ " Use the 'add_messages' instead."
+ )
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Add a message to the chat session in Elasticsearch"""
+ try:
+ from elasticsearch import ApiError
+
+ self.client.index(
+ index=self.index,
+ document={
+ "session_id": self.session_id,
+ "created_at": round(time() * 1000),
+ "history": json.dumps(
+ message_to_dict(message),
+ ensure_ascii=bool(self.ensure_ascii),
+ ),
+ },
+ refresh=True,
+ )
+ except ApiError as err:
+ logger.error(f"Could not add message to Elasticsearch: {err}")
+ raise err
+
+ def clear(self) -> None:
+ """Clear session memory in Elasticsearch"""
+ try:
+ from elasticsearch import ApiError
+
+ self.client.delete_by_query(
+ index=self.index,
+ query={"term": {"session_id": self.session_id}},
+ refresh=True,
+ )
+ except ApiError as err:
+ logger.error(f"Could not clear session memory in Elasticsearch: {err}")
+ raise err
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/file.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/file.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c99144fcff00b7e9b889982e1aa185d3f358b79
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/file.py
@@ -0,0 +1,56 @@
+import json
+from pathlib import Path
+from typing import List, Optional
+
+from langchain_core.chat_history import (
+ BaseChatMessageHistory,
+)
+from langchain_core.messages import BaseMessage, messages_from_dict, messages_to_dict
+
+
+class FileChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history that stores history in a local file."""
+
+ def __init__(
+ self,
+ file_path: str,
+ *,
+ encoding: Optional[str] = None,
+ ensure_ascii: bool = True,
+ ) -> None:
+ """Initialize the file path for the chat history.
+ Args:
+ file_path: The path to the local file to store the chat history.
+ encoding: The encoding to use for file operations. Defaults to None.
+ ensure_ascii: If True, escape non-ASCII in JSON. Defaults to True.
+ """
+ self.file_path = Path(file_path)
+ self.encoding = encoding
+ self.ensure_ascii = ensure_ascii
+
+ if not self.file_path.exists():
+ self.file_path.touch()
+ self.file_path.write_text(
+ json.dumps([], ensure_ascii=self.ensure_ascii), encoding=self.encoding
+ )
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ """Retrieve the messages from the local file"""
+ items = json.loads(self.file_path.read_text(encoding=self.encoding))
+ messages = messages_from_dict(items)
+ return messages
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Append the message to the record in the local file"""
+ messages = messages_to_dict(self.messages)
+ messages.append(messages_to_dict([message])[0])
+ self.file_path.write_text(
+ json.dumps(messages, ensure_ascii=self.ensure_ascii), encoding=self.encoding
+ )
+
+ def clear(self) -> None:
+ """Clear session memory from the local file"""
+ self.file_path.write_text(
+ json.dumps([], ensure_ascii=self.ensure_ascii), encoding=self.encoding
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/firestore.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/firestore.py
new file mode 100644
index 0000000000000000000000000000000000000000..0598e25ced99246d46408d00947ad24634c15ff4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/firestore.py
@@ -0,0 +1,106 @@
+"""Firestore Chat Message History."""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, List, Optional
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ messages_from_dict,
+ messages_to_dict,
+)
+
+logger = logging.getLogger(__name__)
+
+if TYPE_CHECKING:
+ from google.cloud.firestore import Client, DocumentReference
+
+
+def _get_firestore_client() -> Client:
+ try:
+ import firebase_admin
+ from firebase_admin import firestore
+ except ImportError:
+ raise ImportError(
+ "Could not import firebase-admin python package. "
+ "Please install it with `pip install firebase-admin`."
+ )
+
+ # For multiple instances, only initialize the app once.
+ try:
+ firebase_admin.get_app()
+ except ValueError as e:
+ logger.debug("Initializing Firebase app: %s", e)
+ firebase_admin.initialize_app()
+
+ return firestore.client()
+
+
+class FirestoreChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history backed by Google Firestore."""
+
+ def __init__(
+ self,
+ collection_name: str,
+ session_id: str,
+ user_id: str,
+ firestore_client: Optional[Client] = None,
+ ):
+ """
+ Initialize a new instance of the FirestoreChatMessageHistory class.
+
+ :param collection_name: The name of the collection to use.
+ :param session_id: The session ID for the chat..
+ :param user_id: The user ID for the chat.
+ """
+ self.collection_name = collection_name
+ self.session_id = session_id
+ self.user_id = user_id
+ self._document: Optional[DocumentReference] = None
+ self.messages: List[BaseMessage] = []
+ self.firestore_client = firestore_client or _get_firestore_client()
+ self.prepare_firestore()
+
+ def prepare_firestore(self) -> None:
+ """Prepare the Firestore client.
+
+ Use this function to make sure your database is ready.
+ """
+ self._document = self.firestore_client.collection(
+ self.collection_name
+ ).document(self.session_id)
+ self.load_messages()
+
+ def load_messages(self) -> None:
+ """Retrieve the messages from Firestore"""
+ if not self._document:
+ raise ValueError("Document not initialized")
+ doc = self._document.get()
+ if doc.exists:
+ data = doc.to_dict()
+ if "messages" in data and len(data["messages"]) > 0:
+ self.messages = messages_from_dict(data["messages"])
+
+ def add_message(self, message: BaseMessage) -> None:
+ self.messages.append(message)
+ self.upsert_messages()
+
+ def upsert_messages(self, new_message: Optional[BaseMessage] = None) -> None:
+ """Update the Firestore document."""
+ if not self._document:
+ raise ValueError("Document not initialized")
+ self._document.set(
+ {
+ "id": self.session_id,
+ "user_id": self.user_id,
+ "messages": messages_to_dict(self.messages),
+ }
+ )
+
+ def clear(self) -> None:
+ """Clear session memory from this memory and Firestore."""
+ self.messages = []
+ if self._document:
+ self._document.delete()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/in_memory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/in_memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..679c9ce665e7cbea0f946d853b26bdcb392da1bd
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/in_memory.py
@@ -0,0 +1,5 @@
+from langchain_core.chat_history import InMemoryChatMessageHistory as ChatMessageHistory
+
+__all__ = [
+ "ChatMessageHistory",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/kafka.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/kafka.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f90f096c61651e06f0f79dcb0268573496e7233
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/kafka.py
@@ -0,0 +1,363 @@
+"""Kafka-based chat message history by using confluent-kafka-python.
+confluent-kafka-python is under Apache 2.0 license.
+https://github.com/confluentinc/confluent-kafka-python
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import time
+from enum import Enum
+from typing import TYPE_CHECKING, List, Optional, Sequence
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import BaseMessage, message_to_dict, messages_from_dict
+
+if TYPE_CHECKING:
+ from confluent_kafka import TopicPartition
+ from confluent_kafka.admin import AdminClient
+
+logger = logging.getLogger(__name__)
+
+BOOTSTRAP_SERVERS_CONFIG = "bootstrap.servers"
+
+DEFAULT_TTL_MS = 604800000 # 7 days
+DEFAULT_REPLICATION_FACTOR = 1
+DEFAULT_PARTITION = 3
+
+
+class ConsumeStartPosition(Enum):
+ """Consume start position for Kafka consumer to get chat history messages.
+ LAST_CONSUMED: Continue from the last consumed offset.
+ EARLIEST: Start consuming from the beginning.
+ LATEST: Start consuming from the latest offset.
+ """
+
+ LAST_CONSUMED = 1
+ EARLIEST = 2
+ LATEST = 3
+
+
+def ensure_topic_exists(
+ admin_client: AdminClient,
+ topic_name: str,
+ replication_factor: int,
+ partition: int,
+ ttl_ms: int,
+) -> int:
+ """Create topic if it doesn't exist, and return the number of partitions.
+ If the topic already exists, we don't change the topic configuration.
+ """
+ from confluent_kafka.admin import NewTopic
+
+ try:
+ topic_metadata = admin_client.list_topics().topics
+ if topic_name in topic_metadata:
+ num_partitions = len(topic_metadata[topic_name].partitions)
+ logger.info(
+ f"Topic {topic_name} already exists with {num_partitions} partitions"
+ )
+ return num_partitions
+ except Exception as e:
+ logger.error(f"Failed to list topics: {e}")
+ raise e
+
+ topics = [
+ NewTopic(
+ topic_name,
+ num_partitions=partition,
+ replication_factor=replication_factor,
+ config={"retention.ms": str(ttl_ms)},
+ )
+ ]
+ try:
+ futures = admin_client.create_topics(topics)
+ for _, f in futures.items():
+ f.result() # result is None
+ logger.info(f"Topic {topic_name} created")
+ except Exception as e:
+ logger.error(f"Failed to create topic {topic_name}: {e}")
+ raise e
+
+ return partition
+
+
+class KafkaChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history stored in Kafka.
+
+ Setup:
+ Install ``confluent-kafka-python``.
+
+ .. code-block:: bash
+
+ pip install confluent_kafka
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_message_histories import KafkaChatMessageHistory
+
+ history = KafkaChatMessageHistory(
+ session_id="your_session_id",
+ bootstrap_servers="host:port",
+ )
+
+ Add and retrieve messages:
+ .. code-block:: python
+
+ # Add messages
+ history.add_messages([message1, message2, message3, ...])
+
+ # Retrieve messages
+ message_batch_0 = history.messages
+
+ # retrieve messages after message_batch_0
+ message_batch_1 = history.messages
+
+ # Reset to beginning and retrieve messages
+ messages_from_beginning = history.messages_from_beginning()
+
+ Retrieving messages is stateful. Internally, it uses Kafka consumer to read.
+ The consumed offset is maintained persistently.
+
+ To retrieve messages, you can use the following methods:
+ - `messages`:
+ continue consuming chat messages from last one.
+ - `messages_from_beginning`:
+ reset the consumer to the beginning of the chat history and return messages.
+ Optional parameters:
+ 1. `max_message_count`: maximum number of messages to return.
+ 2. `max_time_sec`: maximum time in seconds to wait for messages.
+ - `messages_from_latest`:
+ reset to end of the chat history and try consuming messages.
+ Optional parameters same as above.
+ - `messages_from_last_consumed`:
+ continuing from the last consumed message, similar to `messages`.
+ Optional parameters same as above.
+
+ `max_message_count` and `max_time_sec` are used to avoid blocking indefinitely
+ when retrieving messages. As a result, the method to retrieve messages may not
+ return all messages. Change `max_message_count` and `max_time_sec` to retrieve
+ all history messages.
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ session_id: str,
+ bootstrap_servers: str,
+ ttl_ms: int = DEFAULT_TTL_MS,
+ replication_factor: int = DEFAULT_REPLICATION_FACTOR,
+ partition: int = DEFAULT_PARTITION,
+ ):
+ """
+ Args:
+ session_id: The ID for single chat session. It is used as Kafka topic name.
+ bootstrap_servers:
+ Comma-separated host/port pairs to establish connection to Kafka cluster
+ https://kafka.apache.org/documentation.html#adminclientconfigs_bootstrap.servers
+ ttl_ms:
+ Time-to-live (milliseconds) for automatic expiration of entries.
+ Default 7 days. -1 for no expiration.
+ It translates to https://kafka.apache.org/documentation.html#topicconfigs_retention.ms
+ replication_factor: The replication factor for the topic. Default 1.
+ partition: The number of partitions for the topic. Default 3.
+ """
+ try:
+ from confluent_kafka import Producer
+ from confluent_kafka.admin import AdminClient
+ except (ImportError, ModuleNotFoundError):
+ raise ImportError(
+ "Could not import confluent_kafka package. "
+ "Please install it with `pip install confluent_kafka`."
+ )
+
+ self.session_id = session_id
+ self.bootstrap_servers = bootstrap_servers
+ self.admin_client = AdminClient({BOOTSTRAP_SERVERS_CONFIG: bootstrap_servers})
+ self.num_partitions = ensure_topic_exists(
+ self.admin_client, session_id, replication_factor, partition, ttl_ms
+ )
+ self.producer = Producer({BOOTSTRAP_SERVERS_CONFIG: bootstrap_servers})
+
+ def add_messages(
+ self,
+ messages: Sequence[BaseMessage],
+ flush_timeout_seconds: float = 5.0,
+ ) -> None:
+ """Add messages to the chat history by producing to the Kafka topic."""
+ try:
+ for message in messages:
+ self.producer.produce(
+ topic=self.session_id,
+ value=json.dumps(message_to_dict(message)),
+ )
+ message_remaining = self.producer.flush(flush_timeout_seconds)
+ if message_remaining > 0:
+ logger.warning(f"{message_remaining} messages are still in-flight.")
+ except Exception as e:
+ logger.error(f"Failed to add messages to Kafka: {e}")
+ raise e
+
+ def __read_messages(
+ self,
+ consume_start_pos: ConsumeStartPosition,
+ max_message_count: Optional[int],
+ max_time_sec: Optional[float],
+ ) -> List[BaseMessage]:
+ """Retrieve messages from Kafka topic for the session.
+ Please note this method is stateful. Internally, it uses Kafka consumer
+ to consume messages, and maintains the consumed offset.
+
+ Args:
+ consume_start_pos: Start position for Kafka consumer.
+ max_message_count: Maximum number of messages to consume.
+ max_time_sec: Time limit in seconds to consume messages.
+ Returns:
+ List of messages.
+ """
+ from confluent_kafka import OFFSET_BEGINNING, OFFSET_END, Consumer
+
+ consumer_config = {
+ BOOTSTRAP_SERVERS_CONFIG: self.bootstrap_servers,
+ "group.id": self.session_id,
+ "auto.offset.reset": "latest"
+ if consume_start_pos == ConsumeStartPosition.LATEST
+ else "earliest",
+ }
+
+ def assign_beginning(
+ assigned_consumer: Consumer, assigned_partitions: list[TopicPartition]
+ ) -> None:
+ for p in assigned_partitions:
+ p.offset = OFFSET_BEGINNING
+ assigned_consumer.assign(assigned_partitions)
+
+ def assign_latest(
+ assigned_consumer: Consumer, assigned_partitions: list[TopicPartition]
+ ) -> None:
+ for p in assigned_partitions:
+ p.offset = OFFSET_END
+ assigned_consumer.assign(assigned_partitions)
+
+ messages: List[dict] = []
+ consumer = Consumer(consumer_config)
+ try:
+ if consume_start_pos == ConsumeStartPosition.EARLIEST:
+ consumer.subscribe([self.session_id], on_assign=assign_beginning)
+ elif consume_start_pos == ConsumeStartPosition.LATEST:
+ consumer.subscribe([self.session_id], on_assign=assign_latest)
+ else:
+ consumer.subscribe([self.session_id])
+ start_time_sec = time.time()
+ while True:
+ if (
+ max_time_sec is not None
+ and time.time() - start_time_sec > max_time_sec
+ ):
+ break
+ if max_message_count is not None and len(messages) >= max_message_count:
+ break
+
+ message = consumer.poll(timeout=1.0)
+ if message is None: # poll timeout
+ continue
+ if message.error() is not None: # error
+ logger.error(f"Consumer error: {message.error()}")
+ continue
+ if message.value() is None: # empty value
+ logger.warning("Empty message value")
+ continue
+ messages.append(json.loads(message.value()))
+ except Exception as e:
+ logger.error(f"Failed to consume messages from Kafka: {e}")
+ raise e
+ finally:
+ consumer.close()
+
+ return messages_from_dict(messages)
+
+ def messages_from_beginning(
+ self, max_message_count: Optional[int] = 5, max_time_sec: Optional[float] = 5.0
+ ) -> List[BaseMessage]:
+ """Retrieve messages from Kafka topic from the beginning.
+ This method resets the consumer to the beginning and consumes messages.
+
+ Args:
+ max_message_count: Maximum number of messages to consume.
+ max_time_sec: Time limit in seconds to consume messages.
+ Returns:
+ List of messages.
+ """
+ return self.__read_messages(
+ consume_start_pos=ConsumeStartPosition.EARLIEST,
+ max_message_count=max_message_count,
+ max_time_sec=max_time_sec,
+ )
+
+ def messages_from_latest(
+ self, max_message_count: Optional[int] = 5, max_time_sec: Optional[float] = 5.0
+ ) -> List[BaseMessage]:
+ """Reset to the end offset. Try to consume messages if available.
+
+ Args:
+ max_message_count: Maximum number of messages to consume.
+ max_time_sec: Time limit in seconds to consume messages.
+ Returns:
+ List of messages.
+ """
+
+ return self.__read_messages(
+ consume_start_pos=ConsumeStartPosition.LATEST,
+ max_message_count=max_message_count,
+ max_time_sec=max_time_sec,
+ )
+
+ def messages_from_last_consumed(
+ self, max_message_count: Optional[int] = 5, max_time_sec: Optional[float] = 5.0
+ ) -> List[BaseMessage]:
+ """Retrieve messages from Kafka topic from the last consumed message.
+ Please note this method is stateful. Internally, it uses Kafka consumer
+ to consume messages, and maintains the commit offset.
+
+ Args:
+ max_message_count: Maximum number of messages to consume.
+ max_time_sec: Time limit in seconds to consume messages.
+ Returns:
+ List of messages.
+ """
+
+ return self.__read_messages(
+ consume_start_pos=ConsumeStartPosition.LAST_CONSUMED,
+ max_message_count=max_message_count,
+ max_time_sec=max_time_sec,
+ )
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ """
+ Retrieve the messages for the session, from Kafka topic continuously
+ from last consumed message. This method is stateful and maintains
+ consumed(committed) offset based on consumer group.
+ Alternatively, use messages_from_last_consumed() with specified parameters.
+ Use messages_from_beginning() to read from the earliest message.
+ Use messages_from_latest() to read from the latest message.
+ """
+ return self.messages_from_last_consumed()
+
+ def clear(self) -> None:
+ """Clear the chat history by deleting the Kafka topic."""
+ try:
+ futures = self.admin_client.delete_topics([self.session_id])
+ for _, f in futures.items():
+ f.result() # result is None
+ logger.info(f"Topic {self.session_id} deleted")
+ except Exception as e:
+ logger.error(f"Failed to delete topic {self.session_id}: {e}")
+ raise e
+
+ def close(self) -> None:
+ """Release the resources.
+ Nothing to be released at this moment.
+ """
+ pass
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/momento.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/momento.py
new file mode 100644
index 0000000000000000000000000000000000000000..51073d789e5b636895463d698916f54534bc9159
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/momento.py
@@ -0,0 +1,189 @@
+from __future__ import annotations
+
+import json
+from datetime import timedelta
+from typing import TYPE_CHECKING, Any, Optional
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ message_to_dict,
+ messages_from_dict,
+)
+from langchain_core.utils import get_from_env
+
+if TYPE_CHECKING:
+ import momento
+
+
+def _ensure_cache_exists(cache_client: momento.CacheClient, cache_name: str) -> None:
+ """Create cache if it doesn't exist.
+
+ Raises:
+ SdkException: Momento service or network error
+ Exception: Unexpected response
+ """
+ from momento.responses import CreateCache
+
+ create_cache_response = cache_client.create_cache(cache_name)
+ if isinstance(create_cache_response, CreateCache.Success) or isinstance(
+ create_cache_response, CreateCache.CacheAlreadyExists
+ ):
+ return None
+ elif isinstance(create_cache_response, CreateCache.Error):
+ raise create_cache_response.inner_exception
+ else:
+ raise Exception(f"Unexpected response cache creation: {create_cache_response}")
+
+
+class MomentoChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history cache that uses Momento as a backend.
+
+ See https://gomomento.com/"""
+
+ def __init__(
+ self,
+ session_id: str,
+ cache_client: momento.CacheClient,
+ cache_name: str,
+ *,
+ key_prefix: str = "message_store:",
+ ttl: Optional[timedelta] = None,
+ ensure_cache_exists: bool = True,
+ ):
+ """Instantiate a chat message history cache that uses Momento as a backend.
+
+ Note: to instantiate the cache client passed to MomentoChatMessageHistory,
+ you must have a Momento account at https://gomomento.com/.
+
+ Args:
+ session_id (str): The session ID to use for this chat session.
+ cache_client (CacheClient): The Momento cache client.
+ cache_name (str): The name of the cache to use to store the messages.
+ key_prefix (str, optional): The prefix to apply to the cache key.
+ Defaults to "message_store:".
+ ttl (Optional[timedelta], optional): The TTL to use for the messages.
+ Defaults to None, ie the default TTL of the cache will be used.
+ ensure_cache_exists (bool, optional): Create the cache if it doesn't exist.
+ Defaults to True.
+
+ Raises:
+ ImportError: Momento python package is not installed.
+ TypeError: cache_client is not of type momento.CacheClientObject
+ """
+ try:
+ from momento import CacheClient
+ from momento.requests import CollectionTtl
+ except ImportError:
+ raise ImportError(
+ "Could not import momento python package. "
+ "Please install it with `pip install momento`."
+ )
+ if not isinstance(cache_client, CacheClient):
+ raise TypeError("cache_client must be a momento.CacheClient object.")
+ if ensure_cache_exists:
+ _ensure_cache_exists(cache_client, cache_name)
+ self.key = key_prefix + session_id
+ self.cache_client = cache_client
+ self.cache_name = cache_name
+ if ttl is not None:
+ self.ttl = CollectionTtl.of(ttl)
+ else:
+ self.ttl = CollectionTtl.from_cache_ttl()
+
+ @classmethod
+ def from_client_params(
+ cls,
+ session_id: str,
+ cache_name: str,
+ ttl: timedelta,
+ *,
+ configuration: Optional[momento.config.Configuration] = None,
+ api_key: Optional[str] = None,
+ auth_token: Optional[str] = None, # for backwards compatibility
+ **kwargs: Any,
+ ) -> MomentoChatMessageHistory:
+ """Construct cache from CacheClient parameters."""
+ try:
+ from momento import CacheClient, Configurations, CredentialProvider
+ except ImportError:
+ raise ImportError(
+ "Could not import momento python package. "
+ "Please install it with `pip install momento`."
+ )
+ if configuration is None:
+ configuration = Configurations.Laptop.v1()
+
+ # Try checking `MOMENTO_AUTH_TOKEN` first for backwards compatibility
+ try:
+ api_key = auth_token or get_from_env("auth_token", "MOMENTO_AUTH_TOKEN")
+ except ValueError:
+ api_key = api_key or get_from_env("api_key", "MOMENTO_API_KEY")
+ credentials = CredentialProvider.from_string(api_key)
+ cache_client = CacheClient(configuration, credentials, default_ttl=ttl)
+ return cls(session_id, cache_client, cache_name, ttl=ttl, **kwargs)
+
+ @property
+ def messages(self) -> list[BaseMessage]: # type: ignore[override]
+ """Retrieve the messages from Momento.
+
+ Raises:
+ SdkException: Momento service or network error
+ Exception: Unexpected response
+
+ Returns:
+ list[BaseMessage]: List of cached messages
+ """
+ from momento.responses import CacheListFetch
+
+ fetch_response = self.cache_client.list_fetch(self.cache_name, self.key)
+
+ if isinstance(fetch_response, CacheListFetch.Hit):
+ items = [json.loads(m) for m in fetch_response.value_list_string]
+ return messages_from_dict(items)
+ elif isinstance(fetch_response, CacheListFetch.Miss):
+ return []
+ elif isinstance(fetch_response, CacheListFetch.Error):
+ raise fetch_response.inner_exception
+ else:
+ raise Exception(f"Unexpected response: {fetch_response}")
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Store a message in the cache.
+
+ Args:
+ message (BaseMessage): The message object to store.
+
+ Raises:
+ SdkException: Momento service or network error.
+ Exception: Unexpected response.
+ """
+ from momento.responses import CacheListPushBack
+
+ item = json.dumps(message_to_dict(message))
+ push_response = self.cache_client.list_push_back(
+ self.cache_name, self.key, item, ttl=self.ttl
+ )
+ if isinstance(push_response, CacheListPushBack.Success):
+ return None
+ elif isinstance(push_response, CacheListPushBack.Error):
+ raise push_response.inner_exception
+ else:
+ raise Exception(f"Unexpected response: {push_response}")
+
+ def clear(self) -> None:
+ """Remove the session's messages from the cache.
+
+ Raises:
+ SdkException: Momento service or network error.
+ Exception: Unexpected response.
+ """
+ from momento.responses import CacheDelete
+
+ delete_response = self.cache_client.delete(self.cache_name, self.key)
+ if isinstance(delete_response, CacheDelete.Success):
+ return None
+ elif isinstance(delete_response, CacheDelete.Error):
+ raise delete_response.inner_exception
+ else:
+ raise Exception(f"Unexpected response: {delete_response}")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/mongodb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/mongodb.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ab6887657fa856ee5a975a0c055409fb00f8135
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/mongodb.py
@@ -0,0 +1,101 @@
+import json
+import logging
+from typing import List
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ message_to_dict,
+ messages_from_dict,
+)
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_DBNAME = "chat_history"
+DEFAULT_COLLECTION_NAME = "message_store"
+
+
+@deprecated(
+ since="0.0.25",
+ removal="1.0",
+ alternative_import="langchain_mongodb.MongoDBChatMessageHistory",
+)
+class MongoDBChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history that stores history in MongoDB.
+
+ Args:
+ connection_string: connection string to connect to MongoDB
+ session_id: arbitrary key that is used to store the messages
+ of a single chat session.
+ database_name: name of the database to use
+ collection_name: name of the collection to use
+ create_index: whether to create an index with name SessionId. Set to False if
+ such an index already exists.
+ """
+
+ def __init__(
+ self,
+ connection_string: str,
+ session_id: str,
+ database_name: str = DEFAULT_DBNAME,
+ collection_name: str = DEFAULT_COLLECTION_NAME,
+ create_index: bool = True,
+ ):
+ from pymongo import MongoClient, errors
+
+ self.connection_string = connection_string
+ self.session_id = session_id
+ self.database_name = database_name
+ self.collection_name = collection_name
+
+ try:
+ self.client: MongoClient = MongoClient(connection_string)
+ except errors.ConnectionFailure as error:
+ logger.error(error)
+
+ self.db = self.client[database_name]
+ self.collection = self.db[collection_name]
+ if create_index:
+ self.collection.create_index("SessionId")
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ """Retrieve the messages from MongoDB"""
+ from pymongo import errors
+
+ try:
+ cursor = self.collection.find({"SessionId": self.session_id})
+ except errors.OperationFailure as error:
+ logger.error(error)
+
+ if cursor:
+ items = [json.loads(document["History"]) for document in cursor]
+ else:
+ items = []
+
+ messages = messages_from_dict(items)
+ return messages
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Append the message to the record in MongoDB"""
+ from pymongo import errors
+
+ try:
+ self.collection.insert_one(
+ {
+ "SessionId": self.session_id,
+ "History": json.dumps(message_to_dict(message)),
+ }
+ )
+ except errors.WriteError as err:
+ logger.error(err)
+
+ def clear(self) -> None:
+ """Clear session memory from MongoDB"""
+ from pymongo import errors
+
+ try:
+ self.collection.delete_many({"SessionId": self.session_id})
+ except errors.WriteError as err:
+ logger.error(err)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/neo4j.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/neo4j.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d2cb317874cc0e2a2900f2e4e6083fdd60a07f8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/neo4j.py
@@ -0,0 +1,140 @@
+from typing import List, Optional, Union
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import BaseMessage, messages_from_dict
+from langchain_core.utils import get_from_dict_or_env
+
+from langchain_community.graphs import Neo4jGraph
+
+
+@deprecated(
+ since="0.3.8",
+ removal="1.0",
+ alternative_import="langchain_neo4j.Neo4jChatMessageHistory",
+)
+class Neo4jChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history stored in a Neo4j database."""
+
+ def __init__(
+ self,
+ session_id: Union[str, int],
+ url: Optional[str] = None,
+ username: Optional[str] = None,
+ password: Optional[str] = None,
+ database: str = "neo4j",
+ node_label: str = "Session",
+ window: int = 3,
+ *,
+ graph: Optional[Neo4jGraph] = None,
+ ):
+ try:
+ import neo4j
+ except ImportError:
+ raise ImportError(
+ "Could not import neo4j python package. "
+ "Please install it with `pip install neo4j`."
+ )
+
+ # Make sure session id is not null
+ if not session_id:
+ raise ValueError("Please ensure that the session_id parameter is provided")
+
+ # Graph object takes precedent over env or input params
+ if graph:
+ self._driver = graph._driver
+ self._database = graph._database
+ else:
+ # Handle if the credentials are environment variables
+ url = get_from_dict_or_env({"url": url}, "url", "NEO4J_URI")
+ username = get_from_dict_or_env(
+ {"username": username}, "username", "NEO4J_USERNAME"
+ )
+ password = get_from_dict_or_env(
+ {"password": password}, "password", "NEO4J_PASSWORD"
+ )
+ database = get_from_dict_or_env(
+ {"database": database}, "database", "NEO4J_DATABASE", "neo4j"
+ )
+
+ self._driver = neo4j.GraphDatabase.driver(url, auth=(username, password))
+ self._database = database
+ # Verify connection
+ try:
+ self._driver.verify_connectivity()
+ except neo4j.exceptions.ServiceUnavailable:
+ raise ValueError(
+ "Could not connect to Neo4j database. "
+ "Please ensure that the url is correct"
+ )
+ except neo4j.exceptions.AuthError:
+ raise ValueError(
+ "Could not connect to Neo4j database. "
+ "Please ensure that the username and password are correct"
+ )
+ self._session_id = session_id
+ self._node_label = node_label
+ self._window = window
+ # Create session node
+ self._driver.execute_query(
+ f"MERGE (s:`{self._node_label}` {{id:$session_id}})",
+ {"session_id": self._session_id},
+ ).summary
+
+ @property
+ def messages(self) -> List[BaseMessage]:
+ """Retrieve the messages from Neo4j"""
+ query = (
+ f"MATCH (s:`{self._node_label}`)-[:LAST_MESSAGE]->(last_message) "
+ "WHERE s.id = $session_id MATCH p=(last_message)<-[:NEXT*0.."
+ f"{self._window * 2}]-() WITH p, length(p) AS length "
+ "ORDER BY length DESC LIMIT 1 UNWIND reverse(nodes(p)) AS node "
+ "RETURN {data:{content: node.content}, type:node.type} AS result"
+ )
+ records, _, _ = self._driver.execute_query(
+ query, {"session_id": self._session_id}
+ )
+
+ messages = messages_from_dict([el["result"] for el in records])
+ return messages
+
+ @messages.setter
+ def messages(self, messages: List[BaseMessage]) -> None:
+ raise NotImplementedError(
+ "Direct assignment to 'messages' is not allowed."
+ " Use the 'add_messages' instead."
+ )
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Append the message to the record in Neo4j"""
+ query = (
+ f"MATCH (s:`{self._node_label}`) WHERE s.id = $session_id "
+ "OPTIONAL MATCH (s)-[lm:LAST_MESSAGE]->(last_message) "
+ "CREATE (s)-[:LAST_MESSAGE]->(new:Message) "
+ "SET new += {type:$type, content:$content} "
+ "WITH new, lm, last_message WHERE last_message IS NOT NULL "
+ "CREATE (last_message)-[:NEXT]->(new) "
+ "DELETE lm"
+ )
+ self._driver.execute_query(
+ query,
+ {
+ "type": message.type,
+ "content": message.content,
+ "session_id": self._session_id,
+ },
+ ).summary
+
+ def clear(self) -> None:
+ """Clear session memory from Neo4j"""
+ query = (
+ f"MATCH (s:`{self._node_label}`)-[:LAST_MESSAGE]->(last_message) "
+ "WHERE s.id = $session_id MATCH p=(last_message)<-[:NEXT]-() "
+ "WITH p, length(p) AS length ORDER BY length DESC LIMIT 1 "
+ "UNWIND nodes(p) as node DETACH DELETE node;"
+ )
+ self._driver.execute_query(query, {"session_id": self._session_id}).summary
+
+ def __del__(self) -> None:
+ if self._driver:
+ self._driver.close()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/postgres.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/postgres.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7fd0f85b02977c7d3f16122494fd8237d571340
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/postgres.py
@@ -0,0 +1,100 @@
+import json
+import logging
+from typing import List
+
+from langchain_core._api import deprecated
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ message_to_dict,
+ messages_from_dict,
+)
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_CONNECTION_STRING = "postgresql://postgres:mypassword@localhost/chat_history"
+
+
+@deprecated(
+ since="0.0.31",
+ message=(
+ "This class is deprecated and will be removed in a future version. "
+ "You can swap to using the `PostgresChatMessageHistory`"
+ " implementation in `langchain_postgres`. "
+ "Please do not submit further PRs to this class."
+ "See "
+ ),
+ alternative="from langchain_postgres import PostgresChatMessageHistory;",
+ pending=True,
+)
+class PostgresChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history stored in a Postgres database.
+
+ **DEPRECATED**: This class is deprecated and will be removed in a future version.
+
+ Use the `PostgresChatMessageHistory` implementation in `langchain_postgres`.
+ """
+
+ def __init__(
+ self,
+ session_id: str,
+ connection_string: str = DEFAULT_CONNECTION_STRING,
+ table_name: str = "message_store",
+ ):
+ import psycopg
+ from psycopg.rows import dict_row
+
+ try:
+ self.connection = psycopg.connect(connection_string)
+ self.cursor = self.connection.cursor(row_factory=dict_row)
+ except psycopg.OperationalError as error:
+ logger.error(error)
+
+ self.session_id = session_id
+ self.table_name = table_name
+
+ self._create_table_if_not_exists()
+
+ def _create_table_if_not_exists(self) -> None:
+ create_table_query = f"""CREATE TABLE IF NOT EXISTS {self.table_name} (
+ id SERIAL PRIMARY KEY,
+ session_id TEXT NOT NULL,
+ message JSONB NOT NULL
+ );"""
+ self.cursor.execute(create_table_query)
+ self.connection.commit()
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ """Retrieve the messages from PostgreSQL"""
+ query = (
+ f"SELECT message FROM {self.table_name} WHERE session_id = %s ORDER BY id;"
+ )
+ self.cursor.execute(query, (self.session_id,))
+ items = [record["message"] for record in self.cursor.fetchall()]
+ messages = messages_from_dict(items)
+ return messages
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Append the message to the record in PostgreSQL"""
+ from psycopg import sql
+
+ query = sql.SQL("INSERT INTO {} (session_id, message) VALUES (%s, %s);").format(
+ sql.Identifier(self.table_name)
+ )
+ self.cursor.execute(
+ query, (self.session_id, json.dumps(message_to_dict(message)))
+ )
+ self.connection.commit()
+
+ def clear(self) -> None:
+ """Clear session memory from PostgreSQL"""
+ query = f"DELETE FROM {self.table_name} WHERE session_id = %s;"
+ self.cursor.execute(query, (self.session_id,))
+ self.connection.commit()
+
+ def __del__(self) -> None:
+ if self.cursor:
+ self.cursor.close()
+ if self.connection:
+ self.connection.close()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/redis.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/redis.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0569e53b03cb9d2dee3defbd50d1b8dff040ac5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/redis.py
@@ -0,0 +1,120 @@
+import json
+import logging
+from typing import List, Optional
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ message_to_dict,
+ messages_from_dict,
+)
+
+from langchain_community.utilities.redis import get_client
+
+logger = logging.getLogger(__name__)
+
+
+class RedisChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history stored in a Redis database.
+
+ Setup:
+ Install ``redis`` python package.
+
+ .. code-block:: bash
+
+ pip install redis
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_message_histories import RedisChatMessageHistory
+
+ history = RedisChatMessageHistory(
+ session_id = "your-session-id",
+ url="redis://your-host:your-port:your-database", # redis://localhost:6379/0
+ )
+
+ Add and retrieve messages:
+ .. code-block:: python
+
+ # Add single message
+ history.add_message(message)
+
+ # Add batch messages
+ history.add_messages([message1, message2, message3, ...])
+
+ # Add human message
+ history.add_user_message(human_message)
+
+ # Add ai message
+ history.add_ai_message(ai_message)
+
+ # Retrieve messages
+ messages = history.messages
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ session_id: str,
+ url: str = "redis://localhost:6379/0",
+ key_prefix: str = "message_store:",
+ ttl: Optional[int] = None,
+ ):
+ """Initialize with a RedisChatMessageHistory instance.
+
+ Args:
+ session_id: str
+ The ID for single chat session. Used to form keys with `key_prefix`.
+ url: Optional[str]
+ String parameter configuration for connecting to the redis.
+ key_prefix: Optional[str]
+ The prefix of the key, combined with `session id` to form the key.
+ ttl: Optional[int]
+ Set the expiration time of `key`, the unit is seconds.
+ """
+ try:
+ import redis
+ except ImportError:
+ raise ImportError(
+ "Could not import redis python package. "
+ "Please install it with `pip install redis`."
+ )
+
+ try:
+ self.redis_client = get_client(redis_url=url)
+ except redis.exceptions.ConnectionError as error:
+ logger.error(error)
+
+ self.session_id = session_id
+ self.key_prefix = key_prefix
+ self.ttl = ttl
+
+ @property
+ def key(self) -> str:
+ """Construct the record key to use"""
+ return self.key_prefix + self.session_id
+
+ @property
+ def messages(self) -> List[BaseMessage]:
+ """Retrieve the messages from Redis"""
+ _items = self.redis_client.lrange(self.key, 0, -1)
+ items = [json.loads(m.decode("utf-8")) for m in _items[::-1]]
+ messages = messages_from_dict(items)
+ return messages
+
+ @messages.setter
+ def messages(self, messages: List[BaseMessage]) -> None:
+ raise NotImplementedError(
+ "Direct assignment to 'messages' is not allowed."
+ " Use the 'add_messages' instead."
+ )
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Append the message to the record in Redis"""
+ self.redis_client.lpush(self.key, json.dumps(message_to_dict(message)))
+ if self.ttl:
+ self.redis_client.expire(self.key, self.ttl)
+
+ def clear(self) -> None:
+ """Clear session memory from Redis"""
+ self.redis_client.delete(self.key)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/rocksetdb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/rocksetdb.py
new file mode 100644
index 0000000000000000000000000000000000000000..54016d8e1531f910dbe772402ebfe53b6010b4dc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/rocksetdb.py
@@ -0,0 +1,268 @@
+from datetime import datetime
+from time import sleep
+from typing import Any, Callable, List, Union
+from uuid import uuid4
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ message_to_dict,
+ messages_from_dict,
+)
+
+
+class RocksetChatMessageHistory(BaseChatMessageHistory):
+ """Uses Rockset to store chat messages.
+
+ To use, ensure that the `rockset` python package installed.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_message_histories import (
+ RocksetChatMessageHistory
+ )
+ from rockset import RocksetClient
+
+ history = RocksetChatMessageHistory(
+ session_id="MySession",
+ client=RocksetClient(),
+ collection="langchain_demo",
+ sync=True
+ )
+
+ history.add_user_message("hi!")
+ history.add_ai_message("whats up?")
+
+ print(history.messages) # noqa: T201
+ """
+
+ # You should set these values based on your VI.
+ # These values are configured for the typical
+ # free VI. Read more about VIs here:
+ # https://rockset.com/docs/instances
+ SLEEP_INTERVAL_MS: int = 5
+ ADD_TIMEOUT_MS: int = 5000
+ CREATE_TIMEOUT_MS: int = 20000
+
+ def _wait_until(self, method: Callable, timeout: int, **method_params: Any) -> None:
+ """Sleeps until meth() evaluates to true. Passes kwargs into
+ meth.
+ """
+ start = datetime.now()
+ while not method(**method_params):
+ curr = datetime.now()
+ if (curr - start).total_seconds() * 1000 > timeout:
+ raise TimeoutError(f"{method} timed out at {timeout} ms")
+ sleep(RocksetChatMessageHistory.SLEEP_INTERVAL_MS / 1000)
+
+ def _query(self, query: str, **query_params: Any) -> List[Any]:
+ """Executes an SQL statement and returns the result
+ Args:
+ - query: The SQL string
+ - **query_params: Parameters to pass into the query
+ """
+ return self.client.sql(query, params=query_params).results
+
+ def _create_collection(self) -> None:
+ """Creates a collection for this message history"""
+ self.client.Collections.create_s3_collection(
+ name=self.collection, workspace=self.workspace
+ )
+
+ def _collection_exists(self) -> bool:
+ """Checks whether a collection exists for this message history"""
+ try:
+ self.client.Collections.get(collection=self.collection)
+ except self.rockset.exceptions.NotFoundException:
+ return False
+ return True
+
+ def _collection_is_ready(self) -> bool:
+ """Checks whether the collection for this message history is ready
+ to be queried
+ """
+ return (
+ self.client.Collections.get(collection=self.collection).data.status
+ == "READY"
+ )
+
+ def _document_exists(self) -> bool:
+ return (
+ len(
+ self._query(
+ f"""
+ SELECT 1
+ FROM {self.location}
+ WHERE _id=:session_id
+ LIMIT 1
+ """,
+ session_id=self.session_id,
+ )
+ )
+ != 0
+ )
+
+ def _wait_until_collection_created(self) -> None:
+ """Sleeps until the collection for this message history is ready
+ to be queried
+ """
+ self._wait_until(
+ lambda: self._collection_is_ready(),
+ RocksetChatMessageHistory.CREATE_TIMEOUT_MS,
+ )
+
+ def _wait_until_message_added(self, message_id: str) -> None:
+ """Sleeps until a message is added to the messages list"""
+ self._wait_until(
+ lambda message_id: len(
+ self._query(
+ f"""
+ SELECT *
+ FROM UNNEST((
+ SELECT {self.messages_key}
+ FROM {self.location}
+ WHERE _id = :session_id
+ )) AS message
+ WHERE message.data.additional_kwargs.id = :message_id
+ LIMIT 1
+ """,
+ session_id=self.session_id,
+ message_id=message_id,
+ ),
+ )
+ != 0,
+ RocksetChatMessageHistory.ADD_TIMEOUT_MS,
+ message_id=message_id,
+ )
+
+ def _create_empty_doc(self) -> None:
+ """Creates or replaces a document for this message history with no
+ messages"""
+ self.client.Documents.add_documents(
+ collection=self.collection,
+ workspace=self.workspace,
+ data=[{"_id": self.session_id, self.messages_key: []}],
+ )
+
+ def __init__(
+ self,
+ session_id: str,
+ client: Any,
+ collection: str,
+ workspace: str = "commons",
+ messages_key: str = "messages",
+ sync: bool = False,
+ message_uuid_method: Callable[[], Union[str, int]] = lambda: str(uuid4()),
+ ) -> None:
+ """Constructs a new RocksetChatMessageHistory.
+
+ Args:
+ - session_id: The ID of the chat session
+ - client: The RocksetClient object to use to query
+ - collection: The name of the collection to use to store chat
+ messages. If a collection with the given name
+ does not exist in the workspace, it is created.
+ - workspace: The workspace containing `collection`. Defaults
+ to `"commons"`
+ - messages_key: The DB column containing message history.
+ Defaults to `"messages"`
+ - sync: Whether to wait for messages to be added. Defaults
+ to `False`. NOTE: setting this to `True` will slow
+ down performance.
+ - message_uuid_method: The method that generates message IDs.
+ If set, all messages will have an `id` field within the
+ `additional_kwargs` property. If this param is not set
+ and `sync` is `False`, message IDs will not be created.
+ If this param is not set and `sync` is `True`, the
+ `uuid.uuid4` method will be used to create message IDs.
+ """
+ try:
+ import rockset
+ except ImportError:
+ raise ImportError(
+ "Could not import rockset client python package. "
+ "Please install it with `pip install rockset`."
+ )
+
+ if not isinstance(client, rockset.RocksetClient):
+ raise ValueError(
+ f"client should be an instance of rockset.RocksetClient, "
+ f"got {type(client)}"
+ )
+
+ self.session_id = session_id
+ self.client = client
+ self.collection = collection
+ self.workspace = workspace
+ self.location = f'"{self.workspace}"."{self.collection}"'
+ self.rockset = rockset
+ self.messages_key = messages_key
+ self.message_uuid_method = message_uuid_method
+ self.sync = sync
+
+ try:
+ self.client.set_application("langchain")
+ except AttributeError:
+ # ignore
+ pass
+
+ if not self._collection_exists():
+ self._create_collection()
+ self._wait_until_collection_created()
+ self._create_empty_doc()
+ elif not self._document_exists():
+ self._create_empty_doc()
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ """Messages in this chat history."""
+ return messages_from_dict(
+ self._query(
+ f"""
+ SELECT *
+ FROM UNNEST ((
+ SELECT "{self.messages_key}"
+ FROM {self.location}
+ WHERE _id = :session_id
+ ))
+ """,
+ session_id=self.session_id,
+ )
+ )
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Add a Message object to the history.
+
+ Args:
+ message: A BaseMessage object to store.
+ """
+ if self.sync and "id" not in message.additional_kwargs:
+ message.additional_kwargs["id"] = self.message_uuid_method()
+ self.client.Documents.patch_documents(
+ collection=self.collection,
+ workspace=self.workspace,
+ data=[
+ self.rockset.model.patch_document.PatchDocument(
+ id=self.session_id,
+ patch=[
+ self.rockset.model.patch_operation.PatchOperation(
+ op="ADD",
+ path=f"/{self.messages_key}/-",
+ value=message_to_dict(message),
+ )
+ ],
+ )
+ ],
+ )
+ if self.sync:
+ self._wait_until_message_added(message.additional_kwargs["id"])
+
+ def clear(self) -> None:
+ """Removes all messages from the chat history"""
+ self._create_empty_doc()
+ if self.sync:
+ self._wait_until(
+ lambda: not self.messages,
+ RocksetChatMessageHistory.ADD_TIMEOUT_MS,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/singlestoredb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/singlestoredb.py
new file mode 100644
index 0000000000000000000000000000000000000000..316ccd675b2d01e5733fe752ab96dc3413340ccf
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/singlestoredb.py
@@ -0,0 +1,290 @@
+import json
+import logging
+import re
+from typing import (
+ Any,
+ List,
+)
+
+from langchain_core._api import deprecated
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ message_to_dict,
+ messages_from_dict,
+)
+
+logger = logging.getLogger(__name__)
+
+
+@deprecated(
+ since="0.3.22",
+ message=(
+ "This class is pending deprecation and may be removed in a future version. "
+ "You can swap to using the `SingleStoreChatMessageHistory` "
+ "implementation in `langchain_singlestore`. "
+ "See for details "
+ " about the new implementation."
+ ),
+ alternative="from langchain_singlestore import SingleStoreChatMessageHistory",
+ pending=True,
+)
+class SingleStoreDBChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history stored in a SingleStoreDB database."""
+
+ def __init__(
+ self,
+ session_id: str,
+ *,
+ table_name: str = "message_store",
+ id_field: str = "id",
+ session_id_field: str = "session_id",
+ message_field: str = "message",
+ pool_size: int = 5,
+ max_overflow: int = 10,
+ timeout: float = 30,
+ **kwargs: Any,
+ ):
+ """Initialize with necessary components.
+
+ Args:
+
+
+ table_name (str, optional): Specifies the name of the table in use.
+ Defaults to "message_store".
+ id_field (str, optional): Specifies the name of the id field in the table.
+ Defaults to "id".
+ session_id_field (str, optional): Specifies the name of the session_id
+ field in the table. Defaults to "session_id".
+ message_field (str, optional): Specifies the name of the message field
+ in the table. Defaults to "message".
+
+ Following arguments pertain to the connection pool:
+
+ pool_size (int, optional): Determines the number of active connections in
+ the pool. Defaults to 5.
+ max_overflow (int, optional): Determines the maximum number of connections
+ allowed beyond the pool_size. Defaults to 10.
+ timeout (float, optional): Specifies the maximum wait time in seconds for
+ establishing a connection. Defaults to 30.
+
+ Following arguments pertain to the database connection:
+
+ host (str, optional): Specifies the hostname, IP address, or URL for the
+ database connection. The default scheme is "mysql".
+ user (str, optional): Database username.
+ password (str, optional): Database password.
+ port (int, optional): Database port. Defaults to 3306 for non-HTTP
+ connections, 80 for HTTP connections, and 443 for HTTPS connections.
+ database (str, optional): Database name.
+
+ Additional optional arguments provide further customization over the
+ database connection:
+
+ pure_python (bool, optional): Toggles the connector mode. If True,
+ operates in pure Python mode.
+ local_infile (bool, optional): Allows local file uploads.
+ charset (str, optional): Specifies the character set for string values.
+ ssl_key (str, optional): Specifies the path of the file containing the SSL
+ key.
+ ssl_cert (str, optional): Specifies the path of the file containing the SSL
+ certificate.
+ ssl_ca (str, optional): Specifies the path of the file containing the SSL
+ certificate authority.
+ ssl_cipher (str, optional): Sets the SSL cipher list.
+ ssl_disabled (bool, optional): Disables SSL usage.
+ ssl_verify_cert (bool, optional): Verifies the server's certificate.
+ Automatically enabled if ``ssl_ca`` is specified.
+ ssl_verify_identity (bool, optional): Verifies the server's identity.
+ conv (dict[int, Callable], optional): A dictionary of data conversion
+ functions.
+ credential_type (str, optional): Specifies the type of authentication to
+ use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.
+ autocommit (bool, optional): Enables autocommits.
+ results_type (str, optional): Determines the structure of the query results:
+ tuples, namedtuples, dicts.
+ results_format (str, optional): Deprecated. This option has been renamed to
+ results_type.
+
+ Examples:
+ Basic Usage:
+
+ .. code-block:: python
+
+ from langchain_community.chat_message_histories import (
+ SingleStoreDBChatMessageHistory
+ )
+
+ message_history = SingleStoreDBChatMessageHistory(
+ session_id="my-session",
+ host="https://user:password@127.0.0.1:3306/database"
+ )
+
+ Advanced Usage:
+
+ .. code-block:: python
+
+ from langchain_community.chat_message_histories import (
+ SingleStoreDBChatMessageHistory
+ )
+
+ message_history = SingleStoreDBChatMessageHistory(
+ session_id="my-session",
+ host="127.0.0.1",
+ port=3306,
+ user="user",
+ password="password",
+ database="db",
+ table_name="my_custom_table",
+ pool_size=10,
+ timeout=60,
+ )
+
+ Using environment variables:
+
+ .. code-block:: python
+
+ from langchain_community.chat_message_histories import (
+ SingleStoreDBChatMessageHistory
+ )
+
+ os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'
+ message_history = SingleStoreDBChatMessageHistory("my-session")
+ """
+
+ self.table_name = self._sanitize_input(table_name)
+ self.session_id = self._sanitize_input(session_id)
+ self.id_field = self._sanitize_input(id_field)
+ self.session_id_field = self._sanitize_input(session_id_field)
+ self.message_field = self._sanitize_input(message_field)
+
+ # Pass the rest of the kwargs to the connection.
+ self.connection_kwargs = kwargs
+
+ # Add connection attributes to the connection kwargs.
+ if "conn_attrs" not in self.connection_kwargs:
+ self.connection_kwargs["conn_attrs"] = dict()
+
+ self.connection_kwargs["conn_attrs"]["_connector_name"] = "langchain python sdk"
+ self.connection_kwargs["conn_attrs"]["_connector_version"] = "2.1.0"
+
+ # Create a connection pool.
+ try:
+ from sqlalchemy.pool import QueuePool
+ except ImportError:
+ raise ImportError(
+ "Could not import sqlalchemy.pool python package. "
+ "Please install it with `pip install singlestoredb`."
+ )
+
+ self.connection_pool = QueuePool(
+ self._get_connection,
+ max_overflow=max_overflow,
+ pool_size=pool_size,
+ timeout=timeout,
+ )
+ self.table_created = False
+
+ def _sanitize_input(self, input_str: str) -> str:
+ # Remove characters that are not alphanumeric or underscores
+ return re.sub(r"[^a-zA-Z0-9_]", "", input_str)
+
+ def _get_connection(self) -> Any:
+ try:
+ import singlestoredb as s2
+ except ImportError:
+ raise ImportError(
+ "Could not import singlestoredb python package. "
+ "Please install it with `pip install singlestoredb`."
+ )
+ return s2.connect(**self.connection_kwargs)
+
+ def _create_table_if_not_exists(self) -> None:
+ """Create table if it doesn't exist."""
+ if self.table_created:
+ return
+ conn = self.connection_pool.connect()
+ try:
+ cur = conn.cursor()
+ try:
+ cur.execute(
+ """CREATE TABLE IF NOT EXISTS {}
+ ({} BIGINT PRIMARY KEY AUTO_INCREMENT,
+ {} TEXT NOT NULL,
+ {} JSON NOT NULL);""".format(
+ self.table_name,
+ self.id_field,
+ self.session_id_field,
+ self.message_field,
+ ),
+ )
+ self.table_created = True
+ finally:
+ cur.close()
+ finally:
+ conn.close()
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ """Retrieve the messages from SingleStoreDB"""
+ self._create_table_if_not_exists()
+ conn = self.connection_pool.connect()
+ items = []
+ try:
+ cur = conn.cursor()
+ try:
+ cur.execute(
+ """SELECT {} FROM {} WHERE {} = %s""".format(
+ self.message_field,
+ self.table_name,
+ self.session_id_field,
+ ),
+ (self.session_id),
+ )
+ for row in cur.fetchall():
+ items.append(row[0])
+ finally:
+ cur.close()
+ finally:
+ conn.close()
+ messages = messages_from_dict(items)
+ return messages
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Append the message to the record in SingleStoreDB"""
+ self._create_table_if_not_exists()
+ conn = self.connection_pool.connect()
+ try:
+ cur = conn.cursor()
+ try:
+ cur.execute(
+ """INSERT INTO {} ({}, {}) VALUES (%s, %s)""".format(
+ self.table_name,
+ self.session_id_field,
+ self.message_field,
+ ),
+ (self.session_id, json.dumps(message_to_dict(message))),
+ )
+ finally:
+ cur.close()
+ finally:
+ conn.close()
+
+ def clear(self) -> None:
+ """Clear session memory from SingleStoreDB"""
+ self._create_table_if_not_exists()
+ conn = self.connection_pool.connect()
+ try:
+ cur = conn.cursor()
+ try:
+ cur.execute(
+ """DELETE FROM {} WHERE {} = %s""".format(
+ self.table_name,
+ self.session_id_field,
+ ),
+ (self.session_id),
+ )
+ finally:
+ cur.close()
+ finally:
+ conn.close()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/sql.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/sql.py
new file mode 100644
index 0000000000000000000000000000000000000000..d26804ec73392ccb2c2961ad2a6ab84b936ffefe
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/sql.py
@@ -0,0 +1,356 @@
+import contextlib
+import json
+import logging
+from abc import ABC, abstractmethod
+from typing import (
+ Any,
+ AsyncGenerator,
+ Dict,
+ Generator,
+ List,
+ Optional,
+ Sequence,
+ Union,
+ cast,
+)
+
+from langchain_core._api import deprecated, warn_deprecated
+from sqlalchemy import Column, Integer, Text, delete, select
+
+try:
+ from sqlalchemy.orm import declarative_base
+except ImportError:
+ from sqlalchemy.ext.declarative import declarative_base
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ message_to_dict,
+ messages_from_dict,
+)
+from sqlalchemy import create_engine
+from sqlalchemy.engine import Engine
+from sqlalchemy.ext.asyncio import (
+ AsyncEngine,
+ AsyncSession,
+ create_async_engine,
+)
+from sqlalchemy.orm import (
+ Session as SQLSession,
+)
+from sqlalchemy.orm import (
+ declarative_base,
+ scoped_session,
+ sessionmaker,
+)
+
+try:
+ from sqlalchemy.ext.asyncio import async_sessionmaker
+except ImportError:
+ # dummy for sqlalchemy < 2
+ async_sessionmaker = type("async_sessionmaker", (type,), {}) # type: ignore[assignment,misc]
+
+logger = logging.getLogger(__name__)
+
+
+class BaseMessageConverter(ABC):
+ """Convert BaseMessage to the SQLAlchemy model."""
+
+ @abstractmethod
+ def from_sql_model(self, sql_message: Any) -> BaseMessage:
+ """Convert a SQLAlchemy model to a BaseMessage instance."""
+ raise NotImplementedError
+
+ @abstractmethod
+ def to_sql_model(self, message: BaseMessage, session_id: str) -> Any:
+ """Convert a BaseMessage instance to a SQLAlchemy model."""
+ raise NotImplementedError
+
+ @abstractmethod
+ def get_sql_model_class(self) -> Any:
+ """Get the SQLAlchemy model class."""
+ raise NotImplementedError
+
+
+def create_message_model(table_name: str, DynamicBase: Any) -> Any:
+ """
+ Create a message model for a given table name.
+
+ Args:
+ table_name: The name of the table to use.
+ DynamicBase: The base class to use for the model.
+
+ Returns:
+ The model class.
+
+ """
+
+ # Model declared inside a function to have a dynamic table name.
+ class Message(DynamicBase):
+ __tablename__ = table_name
+ id = Column(Integer, primary_key=True)
+ session_id = Column(Text)
+ message = Column(Text)
+
+ return Message
+
+
+class DefaultMessageConverter(BaseMessageConverter):
+ """The default message converter for SQLChatMessageHistory."""
+
+ def __init__(self, table_name: str):
+ self.model_class = create_message_model(table_name, declarative_base())
+
+ def from_sql_model(self, sql_message: Any) -> BaseMessage:
+ return messages_from_dict([json.loads(sql_message.message)])[0]
+
+ def to_sql_model(self, message: BaseMessage, session_id: str) -> Any:
+ return self.model_class(
+ session_id=session_id, message=json.dumps(message_to_dict(message))
+ )
+
+ def get_sql_model_class(self) -> Any:
+ return self.model_class
+
+
+DBConnection = Union[AsyncEngine, Engine, str]
+
+_warned_once_already = False
+
+
+class SQLChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history stored in an SQL database.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_core.messages import HumanMessage
+
+ from langchain_community.chat_message_histories import SQLChatMessageHistory
+
+ # create sync sql message history by connection_string
+ message_history = SQLChatMessageHistory(
+ session_id='foo', connection_string='sqlite///:memory.db'
+ )
+ message_history.add_message(HumanMessage("hello"))
+ message_history.message
+
+ # create async sql message history using aiosqlite
+ # from sqlalchemy.ext.asyncio import create_async_engine
+ #
+ # async_engine = create_async_engine("sqlite+aiosqlite:///memory.db")
+ # async_message_history = SQLChatMessageHistory(
+ # session_id='foo', connection=async_engine,
+ # )
+ # await async_message_history.aadd_message(HumanMessage("hello"))
+ # await async_message_history.aget_messages()
+
+ """
+
+ @property
+ @deprecated("0.2.2", removal="1.0", alternative="session_maker")
+ def Session(self) -> Union[scoped_session, async_sessionmaker]:
+ return self.session_maker
+
+ def __init__(
+ self,
+ session_id: str,
+ connection_string: Optional[str] = None,
+ table_name: str = "message_store",
+ session_id_field_name: str = "session_id",
+ custom_message_converter: Optional[BaseMessageConverter] = None,
+ connection: Union[None, DBConnection] = None,
+ engine_args: Optional[Dict[str, Any]] = None,
+ async_mode: Optional[bool] = None, # Use only if connection is a string
+ ):
+ """Initialize with a SQLChatMessageHistory instance.
+
+ Args:
+ session_id: Indicates the id of the same session.
+ connection_string: String parameter configuration for connecting
+ to the database.
+ table_name: Table name used to save data.
+ session_id_field_name: The name of field of `session_id`.
+ custom_message_converter: Custom message converter for converting
+ database data and `BaseMessage`
+ connection: Database connection object, which can be a string containing
+ connection configuration, Engine object or AsyncEngine object.
+ engine_args: Additional configuration for creating database engines.
+ async_mode: Whether it is an asynchronous connection.
+ """
+ assert not (connection_string and connection), (
+ "connection_string and connection are mutually exclusive"
+ )
+ if connection_string:
+ global _warned_once_already
+ if not _warned_once_already:
+ warn_deprecated(
+ since="0.2.2",
+ removal="1.0",
+ name="connection_string",
+ alternative="connection",
+ )
+ _warned_once_already = True
+ connection = connection_string
+ self.connection_string = connection_string
+ if isinstance(connection, str):
+ self.async_mode = async_mode
+ if async_mode:
+ self.async_engine = create_async_engine(
+ connection, **(engine_args or {})
+ )
+ else:
+ self.engine = create_engine(url=connection, **(engine_args or {}))
+ elif isinstance(connection, Engine):
+ self.async_mode = False
+ self.engine = connection
+ elif isinstance(connection, AsyncEngine):
+ self.async_mode = True
+ self.async_engine = connection
+ else:
+ raise ValueError(
+ "connection should be a connection string or an instance of "
+ "sqlalchemy.engine.Engine or sqlalchemy.ext.asyncio.engine.AsyncEngine"
+ )
+
+ # To be consistent with others SQL implementations, rename to session_maker
+ self.session_maker: Union[scoped_session, async_sessionmaker]
+ if self.async_mode:
+ self.session_maker = async_sessionmaker(bind=self.async_engine)
+ else:
+ self.session_maker = scoped_session(sessionmaker(bind=self.engine))
+
+ self.session_id_field_name = session_id_field_name
+ self.converter = custom_message_converter or DefaultMessageConverter(table_name)
+ self.sql_model_class = self.converter.get_sql_model_class()
+ if not hasattr(self.sql_model_class, session_id_field_name):
+ raise ValueError("SQL model class must have session_id column")
+ self._table_created = False
+ if not self.async_mode:
+ self._create_table_if_not_exists()
+
+ self.session_id = session_id
+
+ def _create_table_if_not_exists(self) -> None:
+ self.sql_model_class.metadata.create_all(self.engine)
+ self._table_created = True
+
+ async def _acreate_table_if_not_exists(self) -> None:
+ if not self._table_created:
+ assert self.async_mode, "This method must be called with async_mode"
+ async with self.async_engine.begin() as conn:
+ await conn.run_sync(self.sql_model_class.metadata.create_all)
+ self._table_created = True
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ """Retrieve all messages from db"""
+ with self._make_sync_session() as session:
+ result = (
+ session.query(self.sql_model_class)
+ .where(
+ getattr(self.sql_model_class, self.session_id_field_name)
+ == self.session_id
+ )
+ .order_by(self.sql_model_class.id.asc())
+ )
+ messages = []
+ for record in result:
+ messages.append(self.converter.from_sql_model(record))
+ return messages
+
+ def get_messages(self) -> List[BaseMessage]:
+ return self.messages
+
+ async def aget_messages(self) -> List[BaseMessage]:
+ """Retrieve all messages from db"""
+ await self._acreate_table_if_not_exists()
+ async with self._make_async_session() as session:
+ stmt = (
+ select(self.sql_model_class)
+ .where(
+ getattr(self.sql_model_class, self.session_id_field_name)
+ == self.session_id
+ )
+ .order_by(self.sql_model_class.id.asc())
+ )
+ result = await session.execute(stmt)
+ messages = []
+ for record in result.scalars():
+ messages.append(self.converter.from_sql_model(record))
+ return messages
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Append the message to the record in db"""
+ with self._make_sync_session() as session:
+ session.add(self.converter.to_sql_model(message, self.session_id))
+ session.commit()
+
+ async def aadd_message(self, message: BaseMessage) -> None:
+ """Add a Message object to the store.
+
+ Args:
+ message: A BaseMessage object to store.
+ """
+ await self._acreate_table_if_not_exists()
+ async with self._make_async_session() as session:
+ session.add(self.converter.to_sql_model(message, self.session_id))
+ await session.commit()
+
+ def add_messages(self, messages: Sequence[BaseMessage]) -> None:
+ # Add all messages in one transaction
+ with self._make_sync_session() as session:
+ for message in messages:
+ session.add(self.converter.to_sql_model(message, self.session_id))
+ session.commit()
+
+ async def aadd_messages(self, messages: Sequence[BaseMessage]) -> None:
+ # Add all messages in one transaction
+ await self._acreate_table_if_not_exists()
+ async with self.session_maker() as session:
+ for message in messages:
+ session.add(self.converter.to_sql_model(message, self.session_id))
+ await session.commit()
+
+ def clear(self) -> None:
+ """Clear session memory from db"""
+
+ with self._make_sync_session() as session:
+ session.query(self.sql_model_class).filter(
+ getattr(self.sql_model_class, self.session_id_field_name)
+ == self.session_id
+ ).delete()
+ session.commit()
+
+ async def aclear(self) -> None:
+ """Clear session memory from db"""
+
+ await self._acreate_table_if_not_exists()
+ async with self._make_async_session() as session:
+ stmt = delete(self.sql_model_class).filter(
+ getattr(self.sql_model_class, self.session_id_field_name)
+ == self.session_id
+ )
+ await session.execute(stmt)
+ await session.commit()
+
+ @contextlib.contextmanager
+ def _make_sync_session(self) -> Generator[SQLSession, None, None]:
+ """Make an async session."""
+ if self.async_mode:
+ raise ValueError(
+ "Attempting to use a sync method in when async mode is turned on. "
+ "Please use the corresponding async method instead."
+ )
+ with self.session_maker() as session:
+ yield cast(SQLSession, session)
+
+ @contextlib.asynccontextmanager
+ async def _make_async_session(self) -> AsyncGenerator[AsyncSession, None]:
+ """Make an async session."""
+ if not self.async_mode:
+ raise ValueError(
+ "Attempting to use an async method in when sync mode is turned on. "
+ "Please use the corresponding async method instead."
+ )
+ async with self.session_maker() as session:
+ yield cast(AsyncSession, session)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/streamlit.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/streamlit.py
new file mode 100644
index 0000000000000000000000000000000000000000..c04e865bf9a99ae1127621996788072eefd937e4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/streamlit.py
@@ -0,0 +1,47 @@
+from typing import List
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import BaseMessage
+
+
+class StreamlitChatMessageHistory(BaseChatMessageHistory):
+ """
+ Chat message history that stores messages in Streamlit session state.
+
+ Args:
+ key: The key to use in Streamlit session state for storing messages.
+ """
+
+ def __init__(self, key: str = "langchain_messages"):
+ try:
+ import streamlit as st
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import streamlit, please run `pip install streamlit`."
+ ) from e
+
+ if key not in st.session_state:
+ st.session_state[key] = []
+ self._messages = st.session_state[key]
+ self._key = key
+
+ @property
+ def messages(self) -> List[BaseMessage]:
+ """Retrieve the current list of messages"""
+ return self._messages
+
+ @messages.setter
+ def messages(self, value: List[BaseMessage]) -> None:
+ """Set the messages list with a new value"""
+ import streamlit as st
+
+ st.session_state[self._key] = value
+ self._messages = st.session_state[self._key]
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Add a message to the session memory"""
+ self.messages.append(message)
+
+ def clear(self) -> None:
+ """Clear session memory"""
+ self.messages.clear()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/tidb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/tidb.py
new file mode 100644
index 0000000000000000000000000000000000000000..309ab6d7b12c0d60de18845a69ae9390e9b84948
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/tidb.py
@@ -0,0 +1,148 @@
+import json
+import logging
+from datetime import datetime
+from typing import List, Optional
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import BaseMessage, message_to_dict, messages_from_dict
+from sqlalchemy import create_engine, text
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import sessionmaker
+
+logger = logging.getLogger(__name__)
+
+
+class TiDBChatMessageHistory(BaseChatMessageHistory):
+ """
+ Represents a chat message history stored in a TiDB database.
+ """
+
+ def __init__(
+ self,
+ session_id: str,
+ connection_string: str,
+ table_name: str = "langchain_message_store",
+ earliest_time: Optional[datetime] = None,
+ ):
+ """
+ Initializes a new instance of the TiDBChatMessageHistory class.
+
+ Args:
+ session_id (str): The ID of the chat session.
+ connection_string (str): The connection string for the TiDB database.
+ format: mysql+pymysql://:@:4000/?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true
+ table_name (str, optional): the table name to store the chat messages.
+ Defaults to "langchain_message_store".
+ earliest_time (Optional[datetime], optional): The earliest time to retrieve messages from.
+ Defaults to None.
+ """ # noqa
+
+ self.session_id = session_id
+ self.table_name = table_name
+ self.earliest_time = earliest_time
+ self.cache: List = []
+
+ # Set up SQLAlchemy engine and session
+ self.engine = create_engine(connection_string)
+ Session = sessionmaker(bind=self.engine)
+ self.session = Session()
+
+ self._create_table_if_not_exists()
+ self._load_messages_to_cache()
+
+ def _create_table_if_not_exists(self) -> None:
+ """
+ Creates a table if it does not already exist in the database.
+ """
+
+ create_table_query = text(
+ f"""
+ CREATE TABLE IF NOT EXISTS {self.table_name} (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ session_id VARCHAR(255) NOT NULL,
+ message JSON NOT NULL,
+ create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ INDEX session_idx (session_id)
+ );"""
+ )
+ try:
+ self.session.execute(create_table_query)
+ self.session.commit()
+ except SQLAlchemyError as e:
+ logger.error(f"Error creating table: {e}")
+ self.session.rollback()
+
+ def _load_messages_to_cache(self) -> None:
+ """
+ Loads messages from the database into the cache.
+
+ This method retrieves messages from the database table. The retrieved messages
+ are then stored in the cache for faster access.
+
+ Raises:
+ SQLAlchemyError: If there is an error executing the database query.
+
+ """
+ time_condition = (
+ f"AND create_time >= '{self.earliest_time}'" if self.earliest_time else ""
+ )
+ query = text(
+ f"""
+ SELECT message FROM {self.table_name}
+ WHERE session_id = :session_id {time_condition}
+ ORDER BY id;
+ """
+ )
+ try:
+ result = self.session.execute(query, {"session_id": self.session_id})
+ for record in result.fetchall():
+ message_dict = json.loads(record[0])
+ self.cache.append(messages_from_dict([message_dict])[0])
+ except SQLAlchemyError as e:
+ logger.error(f"Error loading messages to cache: {e}")
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ """returns all messages"""
+ if len(self.cache) == 0:
+ self.reload_cache()
+ return self.cache
+
+ def add_message(self, message: BaseMessage) -> None:
+ """adds a message to the database and cache"""
+ query = text(
+ f"INSERT INTO {self.table_name} (session_id, message) VALUES (:session_id, :message);" # noqa
+ )
+ try:
+ self.session.execute(
+ query,
+ {
+ "session_id": self.session_id,
+ "message": json.dumps(message_to_dict(message)),
+ },
+ )
+ self.session.commit()
+ self.cache.append(message)
+ except SQLAlchemyError as e:
+ logger.error(f"Error adding message: {e}")
+ self.session.rollback()
+
+ def clear(self) -> None:
+ """clears all messages"""
+ query = text(f"DELETE FROM {self.table_name} WHERE session_id = :session_id;")
+ try:
+ self.session.execute(query, {"session_id": self.session_id})
+ self.session.commit()
+ self.cache.clear()
+ except SQLAlchemyError as e:
+ logger.error(f"Error clearing messages: {e}")
+ self.session.rollback()
+
+ def reload_cache(self) -> None:
+ """reloads messages from database to cache"""
+ self.cache.clear()
+ self._load_messages_to_cache()
+
+ def __del__(self) -> None:
+ """closes the session"""
+ self.session.close()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/upstash_redis.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/upstash_redis.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd443812cde71a61038e8431f58af00919b0d8ea
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/upstash_redis.py
@@ -0,0 +1,69 @@
+import json
+import logging
+from typing import List, Optional
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ message_to_dict,
+ messages_from_dict,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class UpstashRedisChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history stored in an Upstash Redis database."""
+
+ def __init__(
+ self,
+ session_id: str,
+ url: str = "",
+ token: str = "",
+ key_prefix: str = "message_store:",
+ ttl: Optional[int] = None,
+ ):
+ try:
+ from upstash_redis import Redis
+ except ImportError:
+ raise ImportError(
+ "Could not import upstash redis python package. "
+ "Please install it with `pip install upstash_redis`."
+ )
+
+ if url == "" or token == "":
+ raise ValueError(
+ "UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN are needed."
+ )
+
+ try:
+ self.redis_client = Redis(url=url, token=token)
+ except Exception:
+ logger.error("Upstash Redis instance could not be initiated.")
+
+ self.session_id = session_id
+ self.key_prefix = key_prefix
+ self.ttl = ttl
+
+ @property
+ def key(self) -> str:
+ """Construct the record key to use"""
+ return self.key_prefix + self.session_id
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ """Retrieve the messages from Upstash Redis"""
+ _items = self.redis_client.lrange(self.key, 0, -1)
+ items = [json.loads(m) for m in _items[::-1]]
+ messages = messages_from_dict(items)
+ return messages
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Append the message to the record in Upstash Redis"""
+ self.redis_client.lpush(self.key, json.dumps(message_to_dict(message)))
+ if self.ttl:
+ self.redis_client.expire(self.key, self.ttl)
+
+ def clear(self) -> None:
+ """Clear session memory from Upstash Redis"""
+ self.redis_client.delete(self.key)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/xata.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/xata.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9430913f439f6e4b124233ce47885455c3e25f0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/xata.py
@@ -0,0 +1,134 @@
+import json
+from typing import List
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ BaseMessage,
+ message_to_dict,
+ messages_from_dict,
+)
+
+
+class XataChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history stored in a Xata database."""
+
+ def __init__(
+ self,
+ session_id: str,
+ db_url: str,
+ api_key: str,
+ branch_name: str = "main",
+ table_name: str = "messages",
+ create_table: bool = True,
+ ) -> None:
+ """Initialize with Xata client."""
+ try:
+ from xata.client import XataClient
+ except ImportError:
+ raise ImportError(
+ "Could not import xata python package. "
+ "Please install it with `pip install xata`."
+ )
+ self._client = XataClient(
+ api_key=api_key, db_url=db_url, branch_name=branch_name
+ )
+ self._table_name = table_name
+ self._session_id = session_id
+
+ if create_table:
+ self._create_table_if_not_exists()
+
+ def _create_table_if_not_exists(self) -> None:
+ r = self._client.table().get_schema(self._table_name)
+ if r.status_code <= 299:
+ return
+ if r.status_code != 404:
+ raise Exception(
+ f"Error checking if table exists in Xata: {r.status_code} {r}"
+ )
+ r = self._client.table().create(self._table_name)
+ if r.status_code > 299:
+ raise Exception(f"Error creating table in Xata: {r.status_code} {r}")
+ r = self._client.table().set_schema(
+ self._table_name,
+ payload={
+ "columns": [
+ {"name": "sessionId", "type": "string"},
+ {"name": "type", "type": "string"},
+ {"name": "role", "type": "string"},
+ {"name": "content", "type": "text"},
+ {"name": "name", "type": "string"},
+ {"name": "additionalKwargs", "type": "json"},
+ ]
+ },
+ )
+ if r.status_code > 299:
+ raise Exception(f"Error setting table schema in Xata: {r.status_code} {r}")
+
+ def add_message(self, message: BaseMessage) -> None:
+ """Append the message to the Xata table"""
+ msg = message_to_dict(message)
+ r = self._client.records().insert(
+ self._table_name,
+ {
+ "sessionId": self._session_id,
+ "type": msg["type"],
+ "content": message.content,
+ "additionalKwargs": json.dumps(message.additional_kwargs),
+ "role": msg["data"].get("role"),
+ "name": msg["data"].get("name"),
+ },
+ )
+ if r.status_code > 299:
+ raise Exception(f"Error adding message to Xata: {r.status_code} {r}")
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ r = self._client.data().query(
+ self._table_name,
+ payload={
+ "filter": {
+ "sessionId": self._session_id,
+ },
+ "sort": {"xata.createdAt": "asc"},
+ },
+ )
+ if r.status_code != 200:
+ raise Exception(f"Error running query: {r.status_code} {r}")
+ msgs = messages_from_dict(
+ [
+ {
+ "type": m["type"],
+ "data": {
+ "content": m["content"],
+ "role": m.get("role"),
+ "name": m.get("name"),
+ "additional_kwargs": json.loads(m["additionalKwargs"]),
+ },
+ }
+ for m in r["records"]
+ ]
+ )
+ return msgs
+
+ def clear(self) -> None:
+ """Delete session from Xata table."""
+ while True:
+ r = self._client.data().query(
+ self._table_name,
+ payload={
+ "columns": ["id"],
+ "filter": {
+ "sessionId": self._session_id,
+ },
+ },
+ )
+ if r.status_code != 200:
+ raise Exception(f"Error running query: {r.status_code} {r}")
+ ids = [rec["id"] for rec in r["records"]]
+ if len(ids) == 0:
+ break
+ operations = [
+ {"delete": {"table": self._table_name, "id": id}} for id in ids
+ ]
+ self._client.records().transaction(payload={"operations": operations})
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/zep.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/zep.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e7ff47c51311813fe1c5343f24b418e099cd2d6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/zep.py
@@ -0,0 +1,264 @@
+from __future__ import annotations
+
+import logging
+from enum import Enum
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ SystemMessage,
+)
+
+if TYPE_CHECKING:
+ from zep_python import Memory, MemorySearchResult, Message, NotFoundError
+
+logger = logging.getLogger(__name__)
+
+
+class SearchScope(str, Enum):
+ """Scope for the document search. Messages or Summaries?"""
+
+ messages = "messages"
+ """Search chat history messages."""
+ summary = "summary"
+ """Search chat history summaries."""
+
+
+class SearchType(str, Enum):
+ """Enumerator of the types of search to perform."""
+
+ similarity = "similarity"
+ """Similarity search."""
+ mmr = "mmr"
+ """Maximal Marginal Relevance reranking of similarity search."""
+
+
+class ZepChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history that uses Zep as a backend.
+
+ Recommended usage::
+
+ # Set up Zep Chat History
+ zep_chat_history = ZepChatMessageHistory(
+ session_id=session_id,
+ url=ZEP_API_URL,
+ api_key=,
+ )
+
+ # Use a standard ConversationBufferMemory to encapsulate the Zep chat history
+ memory = ConversationBufferMemory(
+ memory_key="chat_history", chat_memory=zep_chat_history
+ )
+
+
+ Zep provides long-term conversation storage for LLM apps. The server stores,
+ summarizes, embeds, indexes, and enriches conversational AI chat
+ histories, and exposes them via simple, low-latency APIs.
+
+ For server installation instructions and more, see:
+ https://docs.getzep.com/deployment/quickstart/
+
+ This class is a thin wrapper around the zep-python package. Additional
+ Zep functionality is exposed via the `zep_summary` and `zep_messages`
+ properties.
+
+ For more information on the zep-python package, see:
+ https://github.com/getzep/zep-python
+ """
+
+ def __init__(
+ self,
+ session_id: str,
+ url: str = "http://localhost:8000",
+ api_key: Optional[str] = None,
+ ) -> None:
+ try:
+ from zep_python import ZepClient
+ except ImportError:
+ raise ImportError(
+ "Could not import zep-python package. "
+ "Please install it with `pip install zep-python`."
+ )
+
+ self.zep_client = ZepClient(base_url=url, api_key=api_key)
+ self.session_id = session_id
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ """Retrieve messages from Zep memory"""
+ zep_memory: Optional[Memory] = self._get_memory()
+ if not zep_memory:
+ return []
+
+ messages: List[BaseMessage] = []
+ # Extract summary, if present, and messages
+ if zep_memory.summary:
+ if len(zep_memory.summary.content) > 0:
+ messages.append(SystemMessage(content=zep_memory.summary.content))
+ if zep_memory.messages:
+ msg: Message
+ for msg in zep_memory.messages:
+ metadata: Dict = {
+ "uuid": msg.uuid,
+ "created_at": msg.created_at,
+ "token_count": msg.token_count,
+ "metadata": msg.metadata,
+ }
+ if msg.role == "ai":
+ messages.append(
+ AIMessage(content=msg.content, additional_kwargs=metadata)
+ )
+ else:
+ messages.append(
+ HumanMessage(content=msg.content, additional_kwargs=metadata)
+ )
+
+ return messages
+
+ @property
+ def zep_messages(self) -> List[Message]:
+ """Retrieve summary from Zep memory"""
+ zep_memory: Optional[Memory] = self._get_memory()
+ if not zep_memory:
+ return []
+
+ return zep_memory.messages
+
+ @property
+ def zep_summary(self) -> Optional[str]:
+ """Retrieve summary from Zep memory"""
+ zep_memory: Optional[Memory] = self._get_memory()
+ if not zep_memory or not zep_memory.summary:
+ return None
+
+ return zep_memory.summary.content
+
+ def _get_memory(self) -> Optional[Memory]:
+ """Retrieve memory from Zep"""
+ from zep_python import NotFoundError
+
+ try:
+ zep_memory: Memory = self.zep_client.memory.get_memory(self.session_id)
+ except NotFoundError:
+ logger.warning(
+ f"Session {self.session_id} not found in Zep. Returning None"
+ )
+ return None
+ return zep_memory
+
+ def add_user_message( # type: ignore[override]
+ self, message: str, metadata: Optional[Dict[str, Any]] = None
+ ) -> None:
+ """Convenience method for adding a human message string to the store.
+
+ Args:
+ message: The string contents of a human message.
+ metadata: Optional metadata to attach to the message.
+ """
+ self.add_message(HumanMessage(content=message), metadata=metadata)
+
+ def add_ai_message( # type: ignore[override]
+ self, message: str, metadata: Optional[Dict[str, Any]] = None
+ ) -> None:
+ """Convenience method for adding an AI message string to the store.
+
+ Args:
+ message: The string contents of an AI message.
+ metadata: Optional metadata to attach to the message.
+ """
+ self.add_message(AIMessage(content=message), metadata=metadata)
+
+ def add_message(
+ self, message: BaseMessage, metadata: Optional[Dict[str, Any]] = None
+ ) -> None:
+ """Append the message to the Zep memory history"""
+ from zep_python import Memory, Message
+
+ zep_message = Message(
+ content=message.content, role=message.type, metadata=metadata
+ )
+ zep_memory = Memory(messages=[zep_message])
+
+ self.zep_client.memory.add_memory(self.session_id, zep_memory)
+
+ def add_messages(self, messages: Sequence[BaseMessage]) -> None:
+ """Append the messages to the Zep memory history"""
+ from zep_python import Memory, Message
+
+ zep_messages = [
+ Message(
+ content=message.content,
+ role=message.type,
+ metadata=message.additional_kwargs.get("metadata", None),
+ )
+ for message in messages
+ ]
+ zep_memory = Memory(messages=zep_messages)
+
+ self.zep_client.memory.add_memory(self.session_id, zep_memory)
+
+ async def aadd_messages(self, messages: Sequence[BaseMessage]) -> None:
+ """Append the messages to the Zep memory history asynchronously"""
+ from zep_python import Memory, Message
+
+ zep_messages = [
+ Message(
+ content=message.content,
+ role=message.type,
+ metadata=message.additional_kwargs.get("metadata", None),
+ )
+ for message in messages
+ ]
+ zep_memory = Memory(messages=zep_messages)
+
+ await self.zep_client.memory.aadd_memory(self.session_id, zep_memory)
+
+ def search(
+ self,
+ query: str,
+ metadata: Optional[Dict] = None,
+ search_scope: SearchScope = SearchScope.messages,
+ search_type: SearchType = SearchType.similarity,
+ mmr_lambda: Optional[float] = None,
+ limit: Optional[int] = None,
+ ) -> List[MemorySearchResult]:
+ """Search Zep memory for messages matching the query"""
+ from zep_python import MemorySearchPayload
+
+ payload = MemorySearchPayload(
+ text=query,
+ metadata=metadata,
+ search_scope=search_scope,
+ search_type=search_type,
+ mmr_lambda=mmr_lambda,
+ )
+
+ return self.zep_client.memory.search_memory(
+ self.session_id, payload, limit=limit
+ )
+
+ def clear(self) -> None:
+ """Clear session memory from Zep. Note that Zep is long-term storage for memory
+ and this is not advised unless you have specific data retention requirements.
+ """
+ try:
+ self.zep_client.memory.delete_memory(self.session_id)
+ except NotFoundError:
+ logger.warning(
+ f"Session {self.session_id} not found in Zep. Skipping delete."
+ )
+
+ async def aclear(self) -> None:
+ """Clear session memory from Zep asynchronously.
+ Note that Zep is long-term storage for memory and this is not advised
+ unless you have specific data retention requirements.
+ """
+ try:
+ await self.zep_client.memory.adelete_memory(self.session_id)
+ except NotFoundError:
+ logger.warning(
+ f"Session {self.session_id} not found in Zep. Skipping delete."
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/zep_cloud.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/zep_cloud.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0c787482a29d3636e3f4b910a02db7b4eb473cf
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_message_histories/zep_cloud.py
@@ -0,0 +1,303 @@
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence
+
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+)
+
+if TYPE_CHECKING:
+ from zep_cloud import (
+ Memory,
+ MemoryGetRequestMemoryType,
+ MemorySearchResult,
+ Message,
+ NotFoundError,
+ RoleType,
+ SearchScope,
+ SearchType,
+ )
+
+logger = logging.getLogger(__name__)
+
+
+def condense_zep_memory_into_human_message(zep_memory: Memory) -> BaseMessage:
+ """Condense Zep memory into a human message.
+
+ Args:
+ zep_memory: The Zep memory object.
+
+ Returns:
+ BaseMessage: The human message.
+ """
+ prompt = ""
+ if zep_memory.facts:
+ prompt = "\n".join(zep_memory.facts)
+ if zep_memory.summary and zep_memory.summary.content:
+ prompt += "\n" + zep_memory.summary.content
+ for msg in zep_memory.messages or []:
+ prompt += f"\n{msg.role or msg.role_type}: {msg.content}"
+ return HumanMessage(content=prompt)
+
+
+def get_zep_message_role_type(role: str) -> RoleType:
+ """Get the Zep role type from the role string.
+
+ Args:
+ role: The role string. One of "human", "ai", "system",
+ "function", "tool".
+
+ Returns:
+ RoleType: The Zep role type. One of "user", "assistant",
+ "system", "function", "tool".
+ """
+ if role == "human":
+ return "user"
+ elif role == "ai":
+ return "assistant"
+ elif role == "system":
+ return "system"
+ elif role == "function":
+ return "function"
+ elif role == "tool":
+ return "tool"
+ else:
+ return "system"
+
+
+class ZepCloudChatMessageHistory(BaseChatMessageHistory):
+ """Chat message history that uses Zep Cloud as a backend.
+
+ Recommended usage::
+
+ # Set up Zep Chat History
+ zep_chat_history = ZepChatMessageHistory(
+ session_id=session_id,
+ api_key=,
+ )
+
+ # Use a standard ConversationBufferMemory to encapsulate the Zep chat history
+ memory = ConversationBufferMemory(
+ memory_key="chat_history", chat_memory=zep_chat_history
+ )
+
+ Zep - Recall, understand, and extract data from chat histories.
+ Power personalized AI experiences.
+
+ Zep is a long-term memory service for AI Assistant apps.
+ With Zep, you can provide AI assistants with the
+ ability to recall past conversations,
+ no matter how distant,
+ while also reducing hallucinations, latency, and cost.
+
+ see Zep Cloud Docs: https://help.getzep.com
+
+ This class is a thin wrapper around the zep-python package. Additional
+ Zep functionality is exposed via the `zep_summary`, `zep_messages` and `zep_facts`
+ properties.
+
+ For more information on the zep-python package, see:
+ https://github.com/getzep/zep-python
+ """
+
+ def __init__(
+ self,
+ session_id: str,
+ api_key: str,
+ *,
+ memory_type: Optional[MemoryGetRequestMemoryType] = None,
+ lastn: Optional[int] = None,
+ ai_prefix: Optional[str] = None,
+ human_prefix: Optional[str] = None,
+ summary_instruction: Optional[str] = None,
+ ) -> None:
+ try:
+ from zep_cloud.client import AsyncZep, Zep
+ except ImportError:
+ raise ImportError(
+ "Could not import zep-cloud package. "
+ "Please install it with `pip install zep-cloud`."
+ )
+
+ self.zep_client = Zep(api_key=api_key)
+ self.zep_client_async = AsyncZep(api_key=api_key)
+ self.session_id = session_id
+
+ self.memory_type = memory_type or "perpetual"
+ self.lastn = lastn
+ self.ai_prefix = ai_prefix or "ai"
+ self.human_prefix = human_prefix or "human"
+ self.summary_instruction = summary_instruction
+
+ @property
+ def messages(self) -> List[BaseMessage]: # type: ignore[override]
+ """Retrieve messages from Zep memory"""
+ zep_memory: Optional[Memory] = self._get_memory()
+ if not zep_memory:
+ return []
+
+ return [condense_zep_memory_into_human_message(zep_memory)]
+
+ @property
+ def zep_messages(self) -> List[Message]:
+ """Retrieve summary from Zep memory"""
+ zep_memory: Optional[Memory] = self._get_memory()
+ if not zep_memory:
+ return []
+
+ return zep_memory.messages or []
+
+ @property
+ def zep_summary(self) -> Optional[str]:
+ """Retrieve summary from Zep memory"""
+ zep_memory: Optional[Memory] = self._get_memory()
+ if not zep_memory or not zep_memory.summary:
+ return None
+
+ return zep_memory.summary.content
+
+ @property
+ def zep_facts(self) -> Optional[List[str]]:
+ """Retrieve conversation facts from Zep memory"""
+ if self.memory_type != "perpetual":
+ return None
+ zep_memory: Optional[Memory] = self._get_memory()
+ if not zep_memory or not zep_memory.facts:
+ return None
+
+ return zep_memory.facts
+
+ def _get_memory(self) -> Optional[Memory]:
+ """Retrieve memory from Zep"""
+ from zep_cloud import NotFoundError
+
+ try:
+ zep_memory: Memory = self.zep_client.memory.get(
+ self.session_id, memory_type=self.memory_type, lastn=self.lastn
+ )
+ except NotFoundError:
+ logger.warning(
+ f"Session {self.session_id} not found in Zep. Returning None"
+ )
+ return None
+ return zep_memory
+
+ def add_user_message( # type: ignore[override]
+ self, message: str, metadata: Optional[Dict[str, Any]] = None
+ ) -> None:
+ """Convenience method for adding a human message string to the store.
+
+ Args:
+ message: The string contents of a human message.
+ metadata: Optional metadata to attach to the message.
+ """
+ self.add_message(HumanMessage(content=message), metadata=metadata)
+
+ def add_ai_message( # type: ignore[override]
+ self, message: str, metadata: Optional[Dict[str, Any]] = None
+ ) -> None:
+ """Convenience method for adding an AI message string to the store.
+
+ Args:
+ message: The string contents of an AI message.
+ metadata: Optional metadata to attach to the message.
+ """
+ self.add_message(AIMessage(content=message), metadata=metadata)
+
+ def add_message(
+ self, message: BaseMessage, metadata: Optional[Dict[str, Any]] = None
+ ) -> None:
+ """Append the message to the Zep memory history"""
+ from zep_cloud import Message
+
+ self.zep_client.memory.add(
+ self.session_id,
+ messages=[
+ Message(
+ content=str(message.content),
+ role=message.type,
+ role_type=get_zep_message_role_type(message.type),
+ metadata=metadata,
+ )
+ ],
+ )
+
+ def add_messages(self, messages: Sequence[BaseMessage]) -> None:
+ """Append the messages to the Zep memory history"""
+ from zep_cloud import Message
+
+ zep_messages = [
+ Message(
+ content=str(message.content),
+ role=message.type,
+ role_type=get_zep_message_role_type(message.type),
+ metadata=message.additional_kwargs.get("metadata", None),
+ )
+ for message in messages
+ ]
+
+ self.zep_client.memory.add(self.session_id, messages=zep_messages)
+
+ async def aadd_messages(self, messages: Sequence[BaseMessage]) -> None:
+ """Append the messages to the Zep memory history asynchronously"""
+ from zep_cloud import Message
+
+ zep_messages = [
+ Message(
+ content=str(message.content),
+ role=message.type,
+ role_type=get_zep_message_role_type(message.type),
+ metadata=message.additional_kwargs.get("metadata", None),
+ )
+ for message in messages
+ ]
+
+ await self.zep_client_async.memory.add(self.session_id, messages=zep_messages)
+
+ def search(
+ self,
+ query: str,
+ metadata: Optional[Dict] = None,
+ search_scope: SearchScope = "messages",
+ search_type: SearchType = "similarity",
+ mmr_lambda: Optional[float] = None,
+ limit: Optional[int] = None,
+ ) -> List[MemorySearchResult]:
+ """Search Zep memory for messages matching the query"""
+
+ return self.zep_client.memory.search(
+ self.session_id,
+ text=query,
+ metadata=metadata,
+ search_scope=search_scope,
+ search_type=search_type,
+ mmr_lambda=mmr_lambda,
+ limit=limit,
+ )
+
+ def clear(self) -> None:
+ """Clear session memory from Zep. Note that Zep is long-term storage for memory
+ and this is not advised unless you have specific data retention requirements.
+ """
+ try:
+ self.zep_client.memory.delete(self.session_id)
+ except NotFoundError:
+ logger.warning(
+ f"Session {self.session_id} not found in Zep. Skipping delete."
+ )
+
+ async def aclear(self) -> None:
+ """Clear session memory from Zep asynchronously.
+ Note that Zep is long-term storage for memory and this is not advised
+ unless you have specific data retention requirements.
+ """
+ try:
+ await self.zep_client_async.memory.delete(self.session_id)
+ except NotFoundError:
+ logger.warning(
+ f"Session {self.session_id} not found in Zep. Skipping delete."
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c83bdecbfc880c4b9e99cc8ed054c433dad052a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/__init__.py
@@ -0,0 +1,335 @@
+"""**Chat Models** are a variation on language models.
+
+While Chat Models use language models under the hood, the interface they expose
+is a bit different. Rather than expose a "text in, text out" API, they expose
+an interface where "chat messages" are the inputs and outputs.
+
+**Class hierarchy:**
+
+.. code-block::
+
+ BaseLanguageModel --> BaseChatModel --> # Examples: ChatOpenAI, ChatGooglePalm
+
+**Main helpers:**
+
+.. code-block::
+
+ AIMessage, BaseMessage, HumanMessage
+""" # noqa: E501
+
+import importlib
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langchain_community.chat_models.anthropic import (
+ ChatAnthropic,
+ )
+ from langchain_community.chat_models.anyscale import (
+ ChatAnyscale,
+ )
+ from langchain_community.chat_models.azure_openai import (
+ AzureChatOpenAI,
+ )
+ from langchain_community.chat_models.baichuan import (
+ ChatBaichuan,
+ )
+ from langchain_community.chat_models.baidu_qianfan_endpoint import (
+ QianfanChatEndpoint,
+ )
+ from langchain_community.chat_models.bedrock import (
+ BedrockChat,
+ )
+ from langchain_community.chat_models.cohere import (
+ ChatCohere,
+ )
+ from langchain_community.chat_models.coze import (
+ ChatCoze,
+ )
+ from langchain_community.chat_models.databricks import (
+ ChatDatabricks,
+ )
+ from langchain_community.chat_models.deepinfra import (
+ ChatDeepInfra,
+ )
+ from langchain_community.chat_models.edenai import ChatEdenAI
+ from langchain_community.chat_models.ernie import (
+ ErnieBotChat,
+ )
+ from langchain_community.chat_models.everlyai import (
+ ChatEverlyAI,
+ )
+ from langchain_community.chat_models.fake import (
+ FakeListChatModel,
+ )
+ from langchain_community.chat_models.fireworks import (
+ ChatFireworks,
+ )
+ from langchain_community.chat_models.friendli import (
+ ChatFriendli,
+ )
+ from langchain_community.chat_models.gigachat import (
+ GigaChat,
+ )
+ from langchain_community.chat_models.google_palm import (
+ ChatGooglePalm,
+ )
+ from langchain_community.chat_models.gpt_router import (
+ GPTRouter,
+ )
+ from langchain_community.chat_models.huggingface import (
+ ChatHuggingFace,
+ )
+ from langchain_community.chat_models.human import (
+ HumanInputChatModel,
+ )
+ from langchain_community.chat_models.hunyuan import (
+ ChatHunyuan,
+ )
+ from langchain_community.chat_models.javelin_ai_gateway import (
+ ChatJavelinAIGateway,
+ )
+ from langchain_community.chat_models.jinachat import (
+ JinaChat,
+ )
+ from langchain_community.chat_models.kinetica import (
+ ChatKinetica,
+ )
+ from langchain_community.chat_models.konko import (
+ ChatKonko,
+ )
+ from langchain_community.chat_models.litellm import (
+ ChatLiteLLM,
+ )
+ from langchain_community.chat_models.litellm_router import (
+ ChatLiteLLMRouter,
+ )
+ from langchain_community.chat_models.llama_edge import (
+ LlamaEdgeChatService,
+ )
+ from langchain_community.chat_models.llamacpp import ChatLlamaCpp
+ from langchain_community.chat_models.maritalk import (
+ ChatMaritalk,
+ )
+ from langchain_community.chat_models.minimax import (
+ MiniMaxChat,
+ )
+ from langchain_community.chat_models.mlflow import (
+ ChatMlflow,
+ )
+ from langchain_community.chat_models.mlflow_ai_gateway import (
+ ChatMLflowAIGateway,
+ )
+ from langchain_community.chat_models.mlx import (
+ ChatMLX,
+ )
+ from langchain_community.chat_models.moonshot import (
+ MoonshotChat,
+ )
+ from langchain_community.chat_models.naver import (
+ ChatClovaX,
+ )
+ from langchain_community.chat_models.oci_data_science import (
+ ChatOCIModelDeployment,
+ ChatOCIModelDeploymentTGI,
+ ChatOCIModelDeploymentVLLM,
+ )
+ from langchain_community.chat_models.oci_generative_ai import (
+ ChatOCIGenAI, # noqa: F401
+ )
+ from langchain_community.chat_models.octoai import ChatOctoAI
+ from langchain_community.chat_models.ollama import (
+ ChatOllama,
+ )
+ from langchain_community.chat_models.openai import (
+ ChatOpenAI,
+ )
+ from langchain_community.chat_models.outlines import ChatOutlines
+ from langchain_community.chat_models.pai_eas_endpoint import (
+ PaiEasChatEndpoint,
+ )
+ from langchain_community.chat_models.perplexity import (
+ ChatPerplexity,
+ )
+ from langchain_community.chat_models.premai import (
+ ChatPremAI,
+ )
+ from langchain_community.chat_models.promptlayer_openai import (
+ PromptLayerChatOpenAI,
+ )
+ from langchain_community.chat_models.reka import (
+ ChatReka,
+ )
+ from langchain_community.chat_models.sambanova import (
+ ChatSambaNovaCloud,
+ ChatSambaStudio,
+ )
+ from langchain_community.chat_models.snowflake import (
+ ChatSnowflakeCortex,
+ )
+ from langchain_community.chat_models.solar import (
+ SolarChat,
+ )
+ from langchain_community.chat_models.sparkllm import (
+ ChatSparkLLM,
+ )
+ from langchain_community.chat_models.symblai_nebula import ChatNebula
+ from langchain_community.chat_models.tongyi import (
+ ChatTongyi,
+ )
+ from langchain_community.chat_models.vertexai import (
+ ChatVertexAI,
+ )
+ from langchain_community.chat_models.volcengine_maas import (
+ VolcEngineMaasChat,
+ )
+ from langchain_community.chat_models.yandex import (
+ ChatYandexGPT,
+ )
+ from langchain_community.chat_models.yi import (
+ ChatYi,
+ )
+ from langchain_community.chat_models.yuan2 import (
+ ChatYuan2,
+ )
+ from langchain_community.chat_models.zhipuai import (
+ ChatZhipuAI,
+ )
+__all__ = [
+ "AzureChatOpenAI",
+ "BedrockChat",
+ "ChatAnthropic",
+ "ChatAnyscale",
+ "ChatBaichuan",
+ "ChatClovaX",
+ "ChatCohere",
+ "ChatCoze",
+ "ChatOctoAI",
+ "ChatDatabricks",
+ "ChatDeepInfra",
+ "ChatEdenAI",
+ "ChatEverlyAI",
+ "ChatFireworks",
+ "ChatFriendli",
+ "ChatGooglePalm",
+ "ChatHuggingFace",
+ "ChatHunyuan",
+ "ChatJavelinAIGateway",
+ "ChatKinetica",
+ "ChatKonko",
+ "ChatLiteLLM",
+ "ChatLiteLLMRouter",
+ "ChatMLX",
+ "ChatMLflowAIGateway",
+ "ChatMaritalk",
+ "ChatMlflow",
+ "ChatNebula",
+ "ChatOCIGenAI",
+ "ChatOCIModelDeployment",
+ "ChatOCIModelDeploymentVLLM",
+ "ChatOCIModelDeploymentTGI",
+ "ChatOllama",
+ "ChatOpenAI",
+ "ChatOutlines",
+ "ChatPerplexity",
+ "ChatReka",
+ "ChatPremAI",
+ "ChatSambaNovaCloud",
+ "ChatSambaStudio",
+ "ChatSparkLLM",
+ "ChatSnowflakeCortex",
+ "ChatTongyi",
+ "ChatVertexAI",
+ "ChatYandexGPT",
+ "ChatYuan2",
+ "ChatZhipuAI",
+ "ChatLlamaCpp",
+ "ErnieBotChat",
+ "FakeListChatModel",
+ "GPTRouter",
+ "GigaChat",
+ "HumanInputChatModel",
+ "JinaChat",
+ "LlamaEdgeChatService",
+ "MiniMaxChat",
+ "MoonshotChat",
+ "PaiEasChatEndpoint",
+ "PromptLayerChatOpenAI",
+ "QianfanChatEndpoint",
+ "SolarChat",
+ "VolcEngineMaasChat",
+ "ChatYi",
+]
+
+
+_module_lookup = {
+ "AzureChatOpenAI": "langchain_community.chat_models.azure_openai",
+ "BedrockChat": "langchain_community.chat_models.bedrock",
+ "ChatAnthropic": "langchain_community.chat_models.anthropic",
+ "ChatAnyscale": "langchain_community.chat_models.anyscale",
+ "ChatBaichuan": "langchain_community.chat_models.baichuan",
+ "ChatClovaX": "langchain_community.chat_models.naver",
+ "ChatCohere": "langchain_community.chat_models.cohere",
+ "ChatCoze": "langchain_community.chat_models.coze",
+ "ChatDatabricks": "langchain_community.chat_models.databricks",
+ "ChatDeepInfra": "langchain_community.chat_models.deepinfra",
+ "ChatEverlyAI": "langchain_community.chat_models.everlyai",
+ "ChatEdenAI": "langchain_community.chat_models.edenai",
+ "ChatFireworks": "langchain_community.chat_models.fireworks",
+ "ChatFriendli": "langchain_community.chat_models.friendli",
+ "ChatGooglePalm": "langchain_community.chat_models.google_palm",
+ "ChatHuggingFace": "langchain_community.chat_models.huggingface",
+ "ChatHunyuan": "langchain_community.chat_models.hunyuan",
+ "ChatJavelinAIGateway": "langchain_community.chat_models.javelin_ai_gateway",
+ "ChatKinetica": "langchain_community.chat_models.kinetica",
+ "ChatKonko": "langchain_community.chat_models.konko",
+ "ChatLiteLLM": "langchain_community.chat_models.litellm",
+ "ChatLiteLLMRouter": "langchain_community.chat_models.litellm_router",
+ "ChatMLflowAIGateway": "langchain_community.chat_models.mlflow_ai_gateway",
+ "ChatMLX": "langchain_community.chat_models.mlx",
+ "ChatMaritalk": "langchain_community.chat_models.maritalk",
+ "ChatMlflow": "langchain_community.chat_models.mlflow",
+ "ChatNebula": "langchain_community.chat_models.symblai_nebula",
+ "ChatOctoAI": "langchain_community.chat_models.octoai",
+ "ChatOCIGenAI": "langchain_community.chat_models.oci_generative_ai",
+ "ChatOCIModelDeployment": "langchain_community.chat_models.oci_data_science",
+ "ChatOCIModelDeploymentVLLM": "langchain_community.chat_models.oci_data_science",
+ "ChatOCIModelDeploymentTGI": "langchain_community.chat_models.oci_data_science",
+ "ChatOllama": "langchain_community.chat_models.ollama",
+ "ChatOpenAI": "langchain_community.chat_models.openai",
+ "ChatOutlines": "langchain_community.chat_models.outlines",
+ "ChatReka": "langchain_community.chat_models.reka",
+ "ChatPerplexity": "langchain_community.chat_models.perplexity",
+ "ChatSambaNovaCloud": "langchain_community.chat_models.sambanova",
+ "ChatSambaStudio": "langchain_community.chat_models.sambanova",
+ "ChatSnowflakeCortex": "langchain_community.chat_models.snowflake",
+ "ChatSparkLLM": "langchain_community.chat_models.sparkllm",
+ "ChatTongyi": "langchain_community.chat_models.tongyi",
+ "ChatVertexAI": "langchain_community.chat_models.vertexai",
+ "ChatYandexGPT": "langchain_community.chat_models.yandex",
+ "ChatYuan2": "langchain_community.chat_models.yuan2",
+ "ChatZhipuAI": "langchain_community.chat_models.zhipuai",
+ "ErnieBotChat": "langchain_community.chat_models.ernie",
+ "FakeListChatModel": "langchain_community.chat_models.fake",
+ "GPTRouter": "langchain_community.chat_models.gpt_router",
+ "GigaChat": "langchain_community.chat_models.gigachat",
+ "HumanInputChatModel": "langchain_community.chat_models.human",
+ "JinaChat": "langchain_community.chat_models.jinachat",
+ "LlamaEdgeChatService": "langchain_community.chat_models.llama_edge",
+ "MiniMaxChat": "langchain_community.chat_models.minimax",
+ "MoonshotChat": "langchain_community.chat_models.moonshot",
+ "PaiEasChatEndpoint": "langchain_community.chat_models.pai_eas_endpoint",
+ "PromptLayerChatOpenAI": "langchain_community.chat_models.promptlayer_openai",
+ "SolarChat": "langchain_community.chat_models.solar",
+ "QianfanChatEndpoint": "langchain_community.chat_models.baidu_qianfan_endpoint",
+ "VolcEngineMaasChat": "langchain_community.chat_models.volcengine_maas",
+ "ChatPremAI": "langchain_community.chat_models.premai",
+ "ChatLlamaCpp": "langchain_community.chat_models.llamacpp",
+ "ChatYi": "langchain_community.chat_models.yi",
+}
+
+
+def __getattr__(name: str) -> Any:
+ if name in _module_lookup:
+ module = importlib.import_module(_module_lookup[name])
+ return getattr(module, name)
+ raise AttributeError(f"module {__name__} has no attribute {name}")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/anthropic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/anthropic.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd7160eb554c8972386a93ca09760f5f25ba9cb2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/anthropic.py
@@ -0,0 +1,234 @@
+from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, cast
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.prompt_values import PromptValue
+from pydantic import ConfigDict
+
+from langchain_community.llms.anthropic import _AnthropicCommon
+
+
+def _convert_one_message_to_text(
+ message: BaseMessage,
+ human_prompt: str,
+ ai_prompt: str,
+) -> str:
+ content = cast(str, message.content)
+ if isinstance(message, ChatMessage):
+ message_text = f"\n\n{message.role.capitalize()}: {content}"
+ elif isinstance(message, HumanMessage):
+ message_text = f"{human_prompt} {content}"
+ elif isinstance(message, AIMessage):
+ message_text = f"{ai_prompt} {content}"
+ elif isinstance(message, SystemMessage):
+ message_text = content
+ else:
+ raise ValueError(f"Got unknown type {message}")
+ return message_text
+
+
+def convert_messages_to_prompt_anthropic(
+ messages: List[BaseMessage],
+ *,
+ human_prompt: str = "\n\nHuman:",
+ ai_prompt: str = "\n\nAssistant:",
+) -> str:
+ """Format a list of messages into a full prompt for the Anthropic model
+ Args:
+ messages (List[BaseMessage]): List of BaseMessage to combine.
+ human_prompt (str, optional): Human prompt tag. Defaults to "\n\nHuman:".
+ ai_prompt (str, optional): AI prompt tag. Defaults to "\n\nAssistant:".
+ Returns:
+ str: Combined string with necessary human_prompt and ai_prompt tags.
+ """
+
+ messages = messages.copy() # don't mutate the original list
+ if not isinstance(messages[-1], AIMessage):
+ messages.append(AIMessage(content=""))
+
+ text = "".join(
+ _convert_one_message_to_text(message, human_prompt, ai_prompt)
+ for message in messages
+ )
+
+ # trim off the trailing ' ' that might come from the "Assistant: "
+ return text.rstrip()
+
+
+@deprecated(
+ since="0.0.28",
+ removal="1.0",
+ alternative_import="langchain_anthropic.ChatAnthropic",
+)
+class ChatAnthropic(BaseChatModel, _AnthropicCommon):
+ """`Anthropic` chat large language models.
+
+ To use, you should have the ``anthropic`` python package installed, and the
+ environment variable ``ANTHROPIC_API_KEY`` set with your API key, or pass
+ it as a named parameter to the constructor.
+
+ Example:
+ .. code-block:: python
+
+ import anthropic
+ from langchain_community.chat_models import ChatAnthropic
+ model = ChatAnthropic(model="", anthropic_api_key="my-api-key")
+ """
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ arbitrary_types_allowed=True,
+ )
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"anthropic_api_key": "ANTHROPIC_API_KEY"}
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "anthropic-chat"
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return whether this model can be serialized by Langchain."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> List[str]:
+ """Get the namespace of the langchain object."""
+ return ["langchain", "chat_models", "anthropic"]
+
+ def _convert_messages_to_prompt(self, messages: List[BaseMessage]) -> str:
+ """Format a list of messages into a full prompt for the Anthropic model
+ Args:
+ messages (List[BaseMessage]): List of BaseMessage to combine.
+ Returns:
+ str: Combined string with necessary HUMAN_PROMPT and AI_PROMPT tags.
+ """
+ prompt_params = {}
+ if self.HUMAN_PROMPT:
+ prompt_params["human_prompt"] = self.HUMAN_PROMPT
+ if self.AI_PROMPT:
+ prompt_params["ai_prompt"] = self.AI_PROMPT
+ return convert_messages_to_prompt_anthropic(messages=messages, **prompt_params)
+
+ def convert_prompt(self, prompt: PromptValue) -> str:
+ return self._convert_messages_to_prompt(prompt.to_messages())
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ prompt = self._convert_messages_to_prompt(messages)
+ params: Dict[str, Any] = {"prompt": prompt, **self._default_params, **kwargs}
+ if stop:
+ params["stop_sequences"] = stop
+
+ stream_resp = self.client.completions.create(**params, stream=True)
+ for data in stream_resp:
+ delta = data.completion
+ chunk = ChatGenerationChunk(message=AIMessageChunk(content=delta))
+ if run_manager:
+ run_manager.on_llm_new_token(delta, chunk=chunk)
+ yield chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ prompt = self._convert_messages_to_prompt(messages)
+ params: Dict[str, Any] = {"prompt": prompt, **self._default_params, **kwargs}
+ if stop:
+ params["stop_sequences"] = stop
+
+ stream_resp = await self.async_client.completions.create(**params, stream=True)
+ async for data in stream_resp:
+ delta = data.completion
+ chunk = ChatGenerationChunk(message=AIMessageChunk(content=delta))
+ if run_manager:
+ await run_manager.on_llm_new_token(delta, chunk=chunk)
+ yield chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+ prompt = self._convert_messages_to_prompt(
+ messages,
+ )
+ params: Dict[str, Any] = {
+ "prompt": prompt,
+ **self._default_params,
+ **kwargs,
+ }
+ if stop:
+ params["stop_sequences"] = stop
+ response = self.client.completions.create(**params)
+ completion = response.completion
+ message = AIMessage(content=completion)
+ return ChatResult(generations=[ChatGeneration(message=message)])
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+ prompt = self._convert_messages_to_prompt(
+ messages,
+ )
+ params: Dict[str, Any] = {
+ "prompt": prompt,
+ **self._default_params,
+ **kwargs,
+ }
+ if stop:
+ params["stop_sequences"] = stop
+ response = await self.async_client.completions.create(**params)
+ completion = response.completion
+ message = AIMessage(content=completion)
+ return ChatResult(generations=[ChatGeneration(message=message)])
+
+ def get_num_tokens(self, text: str) -> int:
+ """Calculate number of tokens."""
+ if not self.count_tokens:
+ raise NameError("Please ensure the anthropic package is loaded")
+ return self.count_tokens(text)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/anyscale.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/anyscale.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e1a12e6d9eabd3fad25e0394c60728cb1645fe8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/anyscale.py
@@ -0,0 +1,243 @@
+"""Anyscale Endpoints chat wrapper. Relies heavily on ChatOpenAI."""
+
+from __future__ import annotations
+
+import logging
+import os
+import sys
+import warnings
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ Optional,
+ Sequence,
+ Set,
+ Type,
+ Union,
+)
+
+import requests
+from langchain_core.messages import BaseMessage
+from langchain_core.tools import BaseTool
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
+from pydantic import Field, SecretStr, model_validator
+
+from langchain_community.adapters.openai import convert_message_to_dict
+from langchain_community.chat_models.openai import (
+ ChatOpenAI,
+ _import_tiktoken,
+)
+from langchain_community.utils.openai import is_openai_v1
+
+if TYPE_CHECKING:
+ import tiktoken
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_API_BASE = "https://api.endpoints.anyscale.com/v1"
+DEFAULT_MODEL = "meta-llama/Meta-Llama-3-8B-Instruct"
+
+
+class ChatAnyscale(ChatOpenAI):
+ """`Anyscale` Chat large language models.
+
+ See https://www.anyscale.com/ for information about Anyscale.
+
+ To use, you should have the ``openai`` python package installed, and the
+ environment variable ``ANYSCALE_API_KEY`` set with your API key.
+ Alternatively, you can use the anyscale_api_key keyword argument.
+
+ Any parameters that are valid to be passed to the `openai.create` call can be passed
+ in, even if not explicitly saved on this class.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatAnyscale
+ chat = ChatAnyscale(model_name="meta-llama/Llama-2-7b-chat-hf")
+ """
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "anyscale-chat"
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"anyscale_api_key": "ANYSCALE_API_KEY"}
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ return False
+
+ anyscale_api_key: SecretStr = Field(default=SecretStr(""))
+ """AnyScale Endpoints API keys."""
+ model_name: str = Field(default=DEFAULT_MODEL, alias="model")
+ """Model name to use."""
+ anyscale_api_base: str = Field(default=DEFAULT_API_BASE)
+ """Base URL path for API requests,
+ leave blank if not using a proxy or service emulator."""
+ anyscale_proxy: Optional[str] = None
+ """To support explicit proxy for Anyscale."""
+ available_models: Optional[Set[str]] = None
+ """Available models from Anyscale API."""
+
+ @staticmethod
+ def get_available_models(
+ anyscale_api_key: Optional[str] = None,
+ anyscale_api_base: str = DEFAULT_API_BASE,
+ ) -> Set[str]:
+ """Get available models from Anyscale API."""
+ try:
+ anyscale_api_key = anyscale_api_key or os.environ["ANYSCALE_API_KEY"]
+ except KeyError as e:
+ raise ValueError(
+ "Anyscale API key must be passed as keyword argument or "
+ "set in environment variable ANYSCALE_API_KEY.",
+ ) from e
+
+ models_url = f"{anyscale_api_base}/models"
+ models_response = requests.get(
+ models_url,
+ headers={
+ "Authorization": f"Bearer {anyscale_api_key}",
+ },
+ )
+
+ if models_response.status_code != 200:
+ raise ValueError(
+ f"Error getting models from {models_url}: "
+ f"{models_response.status_code}",
+ )
+
+ return {model["id"] for model in models_response.json()["data"]}
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+ values["anyscale_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ "anyscale_api_key",
+ "ANYSCALE_API_KEY",
+ )
+ )
+ values["anyscale_api_base"] = get_from_dict_or_env(
+ values,
+ "anyscale_api_base",
+ "ANYSCALE_API_BASE",
+ default=DEFAULT_API_BASE,
+ )
+ values["openai_proxy"] = get_from_dict_or_env(
+ values,
+ "anyscale_proxy",
+ "ANYSCALE_PROXY",
+ default="",
+ )
+ try:
+ import openai
+
+ except ImportError as e:
+ raise ImportError(
+ "Could not import openai python package. "
+ "Please install it with `pip install openai`.",
+ ) from e
+ try:
+ if is_openai_v1():
+ client_params = {
+ "api_key": values["anyscale_api_key"].get_secret_value(),
+ "base_url": values["anyscale_api_base"],
+ # To do: future support
+ # "organization": values["openai_organization"],
+ # "timeout": values["request_timeout"],
+ # "max_retries": values["max_retries"],
+ # "default_headers": values["default_headers"],
+ # "default_query": values["default_query"],
+ # "http_client": values["http_client"],
+ }
+ if not values.get("client"):
+ values["client"] = openai.OpenAI(**client_params).chat.completions
+ if not values.get("async_client"):
+ values["async_client"] = openai.AsyncOpenAI(
+ **client_params
+ ).chat.completions
+ else:
+ values["openai_api_base"] = values["anyscale_api_base"]
+ values["openai_api_key"] = values["anyscale_api_key"].get_secret_value()
+ values["client"] = openai.ChatCompletion
+ except AttributeError as exc:
+ raise ValueError(
+ "`openai` has no `ChatCompletion` attribute, this is likely "
+ "due to an old version of the openai package. Try upgrading it "
+ "with `pip install --upgrade openai`.",
+ ) from exc
+
+ if "model_name" not in values.keys():
+ values["model_name"] = DEFAULT_MODEL
+
+ model_name = values["model_name"]
+ available_models = cls.get_available_models(
+ values["anyscale_api_key"].get_secret_value(),
+ values["anyscale_api_base"],
+ )
+
+ if model_name not in available_models:
+ raise ValueError(
+ f"Model name {model_name} not found in available models: "
+ f"{available_models}.",
+ )
+
+ values["available_models"] = available_models
+
+ return values
+
+ def _get_encoding_model(self) -> tuple[str, tiktoken.Encoding]:
+ tiktoken_ = _import_tiktoken()
+ if self.tiktoken_model_name is not None:
+ model = self.tiktoken_model_name
+ else:
+ model = self.model_name
+ # Returns the number of tokens used by a list of messages.
+ try:
+ encoding = tiktoken_.encoding_for_model("gpt-3.5-turbo-0301")
+ except KeyError:
+ logger.warning("Warning: model not found. Using cl100k_base encoding.")
+ model = "cl100k_base"
+ encoding = tiktoken_.get_encoding(model)
+ return model, encoding
+
+ def get_num_tokens_from_messages(
+ self,
+ messages: list[BaseMessage],
+ tools: Optional[
+ Sequence[Union[Dict[str, Any], Type, Callable, BaseTool]]
+ ] = None,
+ ) -> int:
+ """Calculate num tokens with tiktoken package.
+ Official documentation: https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb
+ """
+ if tools is not None:
+ warnings.warn(
+ "Counting tokens in tool schemas is not yet supported. Ignoring tools."
+ )
+ if sys.version_info[1] <= 7:
+ return super().get_num_tokens_from_messages(messages)
+ model, encoding = self._get_encoding_model()
+ tokens_per_message = 3
+ tokens_per_name = 1
+ num_tokens = 0
+ messages_dict = [convert_message_to_dict(m) for m in messages]
+ for message in messages_dict:
+ num_tokens += tokens_per_message
+ for key, value in message.items():
+ # Cast str(value) in case the message value is not a string
+ # This occurs with function messages
+ num_tokens += len(encoding.encode(str(value)))
+ if key == "name":
+ num_tokens += tokens_per_name
+ # every reply is primed with assistant
+ num_tokens += 3
+ return num_tokens
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/azure_openai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/azure_openai.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f52d4e563bd6030a278e6bab982010a1a63cb11
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/azure_openai.py
@@ -0,0 +1,293 @@
+"""Azure OpenAI chat wrapper."""
+
+from __future__ import annotations
+
+import logging
+import os
+import warnings
+from typing import Any, Awaitable, Callable, Dict, List, Union
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.outputs import ChatResult
+from langchain_core.utils import get_from_dict_or_env, pre_init
+from pydantic import BaseModel, Field
+
+from langchain_community.chat_models.openai import ChatOpenAI
+from langchain_community.utils.openai import is_openai_v1
+
+logger = logging.getLogger(__name__)
+
+
+@deprecated(
+ since="0.0.10",
+ removal="1.0",
+ alternative_import="langchain_openai.AzureChatOpenAI",
+)
+class AzureChatOpenAI(ChatOpenAI):
+ """`Azure OpenAI` Chat Completion API.
+
+ To use this class you
+ must have a deployed model on Azure OpenAI. Use `deployment_name` in the
+ constructor to refer to the "Model deployment name" in the Azure portal.
+
+ In addition, you should have the ``openai`` python package installed, and the
+ following environment variables set or passed in constructor in lower case:
+ - ``AZURE_OPENAI_API_KEY``
+ - ``AZURE_OPENAI_ENDPOINT``
+ - ``AZURE_OPENAI_AD_TOKEN``
+ - ``OPENAI_API_VERSION``
+ - ``OPENAI_PROXY``
+
+ For example, if you have `gpt-35-turbo` deployed, with the deployment name
+ `35-turbo-dev`, the constructor should look like:
+
+ .. code-block:: python
+
+ AzureChatOpenAI(
+ azure_deployment="35-turbo-dev",
+ openai_api_version="2023-05-15",
+ )
+
+ Be aware the API version may change.
+
+ You can also specify the version of the model using ``model_version`` constructor
+ parameter, as Azure OpenAI doesn't return model version with the response.
+
+ Default is empty. When you specify the version, it will be appended to the
+ model name in the response. Setting correct version will help you to calculate the
+ cost properly. Model version is not validated, so make sure you set it correctly
+ to get the correct cost.
+
+ Any parameters that are valid to be passed to the openai.create call can be passed
+ in, even if not explicitly saved on this class.
+ """
+
+ azure_endpoint: Union[str, None] = None
+ """Your Azure endpoint, including the resource.
+
+ Automatically inferred from env var `AZURE_OPENAI_ENDPOINT` if not provided.
+
+ Example: `https://example-resource.azure.openai.com/`
+ """
+ deployment_name: Union[str, None] = Field(default=None, alias="azure_deployment")
+ """A model deployment.
+
+ If given sets the base client URL to include `/deployments/{azure_deployment}`.
+ Note: this means you won't be able to use non-deployment endpoints.
+ """
+ openai_api_version: str = Field(default="", alias="api_version")
+ """Automatically inferred from env var `OPENAI_API_VERSION` if not provided."""
+ openai_api_key: Union[str, None] = Field(default=None, alias="api_key")
+ """Automatically inferred from env var `AZURE_OPENAI_API_KEY` if not provided."""
+ azure_ad_token: Union[str, None] = None
+ """Your Azure Active Directory token.
+
+ Automatically inferred from env var `AZURE_OPENAI_AD_TOKEN` if not provided.
+
+ For more:
+ https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id.
+ """
+ azure_ad_token_provider: Union[Callable[[], str], None] = None
+ """A function that returns an Azure Active Directory token.
+
+ Will be invoked on every sync request. For async requests,
+ will be invoked if `azure_ad_async_token_provider` is not provided.
+ """
+ azure_ad_async_token_provider: Union[Callable[[], Awaitable[str]], None] = None
+ """A function that returns an Azure Active Directory token.
+
+ Will be invoked on every async request.
+ """
+ model_version: str = ""
+ """Legacy, for openai<1.0.0 support."""
+ openai_api_type: str = ""
+ """Legacy, for openai<1.0.0 support."""
+ validate_base_url: bool = True
+ """For backwards compatibility. If legacy val openai_api_base is passed in, try to
+ infer if it is a base_url or azure_endpoint and update accordingly.
+ """
+
+ @classmethod
+ def get_lc_namespace(cls) -> List[str]:
+ """Get the namespace of the langchain object."""
+ return ["langchain", "chat_models", "azure_openai"]
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that api key and python package exists in environment."""
+ if values["n"] < 1:
+ raise ValueError("n must be at least 1.")
+ if values["n"] > 1 and values["streaming"]:
+ raise ValueError("n must be 1 when streaming.")
+
+ # Check OPENAI_KEY for backwards compatibility.
+ # TODO: Remove OPENAI_API_KEY support to avoid possible conflict when using
+ # other forms of azure credentials.
+ values["openai_api_key"] = (
+ values["openai_api_key"]
+ or os.getenv("AZURE_OPENAI_API_KEY")
+ or os.getenv("OPENAI_API_KEY")
+ )
+ values["openai_api_base"] = values["openai_api_base"] or os.getenv(
+ "OPENAI_API_BASE"
+ )
+ values["openai_api_version"] = values["openai_api_version"] or os.getenv(
+ "OPENAI_API_VERSION"
+ )
+ # Check OPENAI_ORGANIZATION for backwards compatibility.
+ values["openai_organization"] = (
+ values["openai_organization"]
+ or os.getenv("OPENAI_ORG_ID")
+ or os.getenv("OPENAI_ORGANIZATION")
+ )
+ values["azure_endpoint"] = values["azure_endpoint"] or os.getenv(
+ "AZURE_OPENAI_ENDPOINT"
+ )
+ values["azure_ad_token"] = values["azure_ad_token"] or os.getenv(
+ "AZURE_OPENAI_AD_TOKEN"
+ )
+
+ values["openai_api_type"] = get_from_dict_or_env(
+ values, "openai_api_type", "OPENAI_API_TYPE", default="azure"
+ )
+ values["openai_proxy"] = get_from_dict_or_env(
+ values, "openai_proxy", "OPENAI_PROXY", default=""
+ )
+
+ try:
+ import openai
+
+ except ImportError:
+ raise ImportError(
+ "Could not import openai python package. "
+ "Please install it with `pip install openai`."
+ )
+ if is_openai_v1():
+ # For backwards compatibility. Before openai v1, no distinction was made
+ # between azure_endpoint and base_url (openai_api_base).
+ openai_api_base = values["openai_api_base"]
+ if openai_api_base and values["validate_base_url"]:
+ if "/openai" not in openai_api_base:
+ values["openai_api_base"] = (
+ values["openai_api_base"].rstrip("/") + "/openai"
+ )
+ warnings.warn(
+ "As of openai>=1.0.0, Azure endpoints should be specified via "
+ f"the `azure_endpoint` param not `openai_api_base` "
+ f"(or alias `base_url`). Updating `openai_api_base` from "
+ f"{openai_api_base} to {values['openai_api_base']}."
+ )
+ if values["deployment_name"]:
+ warnings.warn(
+ "As of openai>=1.0.0, if `deployment_name` (or alias "
+ "`azure_deployment`) is specified then "
+ "`openai_api_base` (or alias `base_url`) should not be. "
+ "Instead use `deployment_name` (or alias `azure_deployment`) "
+ "and `azure_endpoint`."
+ )
+ if values["deployment_name"] not in values["openai_api_base"]:
+ warnings.warn(
+ "As of openai>=1.0.0, if `openai_api_base` "
+ "(or alias `base_url`) is specified it is expected to be "
+ "of the form "
+ "https://example-resource.azure.openai.com/openai/deployments/example-deployment. " # noqa: E501
+ f"Updating {openai_api_base} to "
+ f"{values['openai_api_base']}."
+ )
+ values["openai_api_base"] += (
+ "/deployments/" + values["deployment_name"]
+ )
+ values["deployment_name"] = None
+ client_params = {
+ "api_version": values["openai_api_version"],
+ "azure_endpoint": values["azure_endpoint"],
+ "azure_deployment": values["deployment_name"],
+ "api_key": values["openai_api_key"],
+ "azure_ad_token": values["azure_ad_token"],
+ "azure_ad_token_provider": values["azure_ad_token_provider"],
+ "organization": values["openai_organization"],
+ "base_url": values["openai_api_base"],
+ "timeout": values["request_timeout"],
+ "max_retries": values["max_retries"],
+ "default_headers": {
+ **(values["default_headers"] or {}),
+ "User-Agent": "langchain-comm-python-azure-openai",
+ },
+ "default_query": values["default_query"],
+ "http_client": values["http_client"],
+ }
+ values["client"] = openai.AzureOpenAI(**client_params).chat.completions
+
+ azure_ad_async_token_provider = values["azure_ad_async_token_provider"]
+
+ if azure_ad_async_token_provider:
+ client_params["azure_ad_token_provider"] = azure_ad_async_token_provider
+
+ values["async_client"] = openai.AsyncAzureOpenAI(
+ **client_params
+ ).chat.completions
+ else:
+ values["client"] = openai.ChatCompletion
+ return values
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling OpenAI API."""
+ if is_openai_v1():
+ return super()._default_params
+ else:
+ return {
+ **super()._default_params,
+ "engine": self.deployment_name,
+ }
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ return {**self._default_params}
+
+ @property
+ def _client_params(self) -> Dict[str, Any]:
+ """Get the config params used for the openai client."""
+ if is_openai_v1():
+ return super()._client_params
+ else:
+ return {
+ **super()._client_params,
+ "api_type": self.openai_api_type,
+ "api_version": self.openai_api_version,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ return "azure-openai-chat"
+
+ @property
+ def lc_attributes(self) -> Dict[str, Any]:
+ return {
+ "openai_api_type": self.openai_api_type,
+ "openai_api_version": self.openai_api_version,
+ }
+
+ def _create_chat_result(self, response: Union[dict, BaseModel]) -> ChatResult:
+ if not isinstance(response, dict):
+ response = response.dict()
+ for res in response["choices"]:
+ if res.get("finish_reason", None) == "content_filter":
+ raise ValueError(
+ "Azure has not provided the response due to a content filter "
+ "being triggered"
+ )
+ chat_result = super()._create_chat_result(response)
+
+ if "model" in response:
+ model = response["model"]
+ if self.model_version:
+ model = f"{model}-{self.model_version}"
+
+ if chat_result.llm_output is not None and isinstance(
+ chat_result.llm_output, dict
+ ):
+ chat_result.llm_output["model_name"] = model
+
+ return chat_result
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/azureml_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/azureml_endpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..d37f21f444265ce4c1dacc91376b8a341c9657a6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/azureml_endpoint.py
@@ -0,0 +1,426 @@
+import json
+import warnings
+from typing import (
+ Any,
+ AsyncIterator,
+ Dict,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Type,
+ cast,
+)
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+ ToolMessageChunk,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+
+from langchain_community.llms.azureml_endpoint import (
+ AzureMLBaseEndpoint,
+ AzureMLEndpointApiType,
+ ContentFormatterBase,
+)
+
+
+class LlamaContentFormatter(ContentFormatterBase):
+ """Content formatter for `LLaMA`."""
+
+ def __init__(self) -> None:
+ raise TypeError(
+ "`LlamaContentFormatter` is deprecated for chat models. Use "
+ "`CustomOpenAIContentFormatter` instead."
+ )
+
+
+class CustomOpenAIChatContentFormatter(ContentFormatterBase):
+ """Chat Content formatter for models with OpenAI like API scheme."""
+
+ SUPPORTED_ROLES: List[str] = ["user", "assistant", "system"]
+
+ @staticmethod
+ def _convert_message_to_dict(message: BaseMessage) -> Dict:
+ """Converts a message to a dict according to a role"""
+ content = cast(str, message.content)
+ if isinstance(message, HumanMessage):
+ return {
+ "role": "user",
+ "content": ContentFormatterBase.escape_special_characters(content),
+ }
+ elif isinstance(message, AIMessage):
+ return {
+ "role": "assistant",
+ "content": ContentFormatterBase.escape_special_characters(content),
+ }
+ elif isinstance(message, SystemMessage):
+ return {
+ "role": "system",
+ "content": ContentFormatterBase.escape_special_characters(content),
+ }
+ elif (
+ isinstance(message, ChatMessage)
+ and message.role in CustomOpenAIChatContentFormatter.SUPPORTED_ROLES
+ ):
+ return {
+ "role": message.role,
+ "content": ContentFormatterBase.escape_special_characters(content),
+ }
+ else:
+ supported = ",".join(
+ [role for role in CustomOpenAIChatContentFormatter.SUPPORTED_ROLES]
+ )
+ raise ValueError(
+ f"""Received unsupported role.
+ Supported roles for the LLaMa Foundation Model: {supported}"""
+ )
+
+ @property
+ def supported_api_types(self) -> List[AzureMLEndpointApiType]:
+ return [AzureMLEndpointApiType.dedicated, AzureMLEndpointApiType.serverless]
+
+ def format_messages_request_payload(
+ self,
+ messages: List[BaseMessage],
+ model_kwargs: Dict,
+ api_type: AzureMLEndpointApiType,
+ ) -> bytes:
+ """Formats the request according to the chosen api"""
+ chat_messages = [
+ CustomOpenAIChatContentFormatter._convert_message_to_dict(message)
+ for message in messages
+ ]
+ if api_type in [
+ AzureMLEndpointApiType.dedicated,
+ AzureMLEndpointApiType.realtime,
+ ]:
+ request_payload = json.dumps(
+ {
+ "input_data": {
+ "input_string": chat_messages,
+ "parameters": model_kwargs,
+ }
+ }
+ )
+ elif api_type == AzureMLEndpointApiType.serverless:
+ request_payload = json.dumps({"messages": chat_messages, **model_kwargs})
+ else:
+ raise ValueError(
+ f"`api_type` {api_type} is not supported by this formatter"
+ )
+ return str.encode(request_payload)
+
+ def format_response_payload(
+ self,
+ output: bytes,
+ api_type: AzureMLEndpointApiType = AzureMLEndpointApiType.dedicated,
+ ) -> ChatGeneration:
+ """Formats response"""
+ if api_type in [
+ AzureMLEndpointApiType.dedicated,
+ AzureMLEndpointApiType.realtime,
+ ]:
+ try:
+ choice = json.loads(output)["output"]
+ except (KeyError, IndexError, TypeError) as e:
+ raise ValueError(self.format_error_msg.format(api_type=api_type)) from e
+ return ChatGeneration(
+ message=AIMessage(
+ content=choice.strip(),
+ ),
+ generation_info=None,
+ )
+ if api_type == AzureMLEndpointApiType.serverless:
+ try:
+ choice = json.loads(output)["choices"][0]
+ if not isinstance(choice, dict):
+ raise TypeError(
+ "Endpoint response is not well formed for a chat "
+ "model. Expected `dict` but `{type(choice)}` was received."
+ )
+ except (KeyError, IndexError, TypeError) as e:
+ raise ValueError(self.format_error_msg.format(api_type=api_type)) from e
+ return ChatGeneration(
+ message=AIMessage(content=choice["message"]["content"].strip())
+ if choice["message"]["role"] == "assistant"
+ else BaseMessage(
+ content=choice["message"]["content"].strip(),
+ type=choice["message"]["role"],
+ ),
+ generation_info=dict(
+ finish_reason=choice.get("finish_reason"),
+ logprobs=choice.get("logprobs"),
+ ),
+ )
+ raise ValueError(f"`api_type` {api_type} is not supported by this formatter")
+
+
+class LlamaChatContentFormatter(CustomOpenAIChatContentFormatter):
+ """Deprecated: Kept for backwards compatibility
+
+ Chat Content formatter for Llama."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ warnings.warn(
+ """`LlamaChatContentFormatter` will be deprecated in the future.
+ Please use `CustomOpenAIChatContentFormatter` instead.
+ """
+ )
+
+
+class MistralChatContentFormatter(LlamaChatContentFormatter):
+ """Content formatter for `Mistral`."""
+
+ def format_messages_request_payload(
+ self,
+ messages: List[BaseMessage],
+ model_kwargs: Dict,
+ api_type: AzureMLEndpointApiType,
+ ) -> bytes:
+ """Formats the request according to the chosen api"""
+ chat_messages = [self._convert_message_to_dict(message) for message in messages]
+
+ if chat_messages and chat_messages[0]["role"] == "system":
+ # Mistral OSS models do not explicitly support system prompts, so we have to
+ # stash in the first user prompt
+ chat_messages[1]["content"] = (
+ chat_messages[0]["content"] + "\n\n" + chat_messages[1]["content"]
+ )
+ del chat_messages[0]
+
+ if api_type == AzureMLEndpointApiType.realtime:
+ request_payload = json.dumps(
+ {
+ "input_data": {
+ "input_string": chat_messages,
+ "parameters": model_kwargs,
+ }
+ }
+ )
+ elif api_type == AzureMLEndpointApiType.serverless:
+ request_payload = json.dumps({"messages": chat_messages, **model_kwargs})
+ else:
+ raise ValueError(
+ f"`api_type` {api_type} is not supported by this formatter"
+ )
+ return str.encode(request_payload)
+
+
+class AzureMLChatOnlineEndpoint(BaseChatModel, AzureMLBaseEndpoint):
+ """Azure ML Online Endpoint chat models.
+
+ Example:
+ .. code-block:: python
+ azure_llm = AzureMLOnlineEndpoint(
+ endpoint_url="https://..inference.ml.azure.com/v1/chat/completions",
+ endpoint_api_type=AzureMLApiType.serverless,
+ endpoint_api_key="my-api-key",
+ content_formatter=chat_content_formatter,
+ )
+ """
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ _model_kwargs = self.model_kwargs or {}
+ return {
+ **{"model_kwargs": _model_kwargs},
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "azureml_chat_endpoint"
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Call out to an AzureML Managed Online endpoint.
+ Args:
+ messages: The messages in the conversation with the chat model.
+ stop: Optional list of stop words to use when generating.
+ Returns:
+ The string generated by the model.
+ Example:
+ .. code-block:: python
+ response = azureml_model.invoke("Tell me a joke.")
+ """
+ _model_kwargs = self.model_kwargs or {}
+ _model_kwargs.update(kwargs)
+ if stop:
+ _model_kwargs["stop"] = stop
+
+ request_payload = self.content_formatter.format_messages_request_payload(
+ messages, _model_kwargs, self.endpoint_api_type
+ )
+ response_payload = self.http_client.call(
+ body=request_payload, run_manager=run_manager
+ )
+ generations = self.content_formatter.format_response_payload(
+ response_payload, self.endpoint_api_type
+ )
+ return ChatResult(generations=[generations])
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ self.endpoint_url = self.endpoint_url.replace("/chat/completions", "")
+ timeout = None if "timeout" not in kwargs else kwargs["timeout"]
+
+ import openai
+
+ params = {}
+ client_params = {
+ "api_key": self.endpoint_api_key.get_secret_value(),
+ "base_url": self.endpoint_url,
+ "timeout": timeout,
+ "default_headers": None,
+ "default_query": None,
+ "http_client": None,
+ }
+
+ client = openai.OpenAI(**client_params)
+ message_dicts = [
+ CustomOpenAIChatContentFormatter._convert_message_to_dict(m)
+ for m in messages
+ ]
+ params = {"stream": True, "stop": stop, "model": None, **kwargs}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ for chunk in client.chat.completions.create(messages=message_dicts, **params):
+ if not isinstance(chunk, dict):
+ chunk = chunk.dict()
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"],
+ default_chunk_class,
+ )
+ generation_info = {}
+ if finish_reason := choice.get("finish_reason"):
+ generation_info["finish_reason"] = finish_reason
+ logprobs = choice.get("logprobs")
+ if logprobs:
+ generation_info["logprobs"] = logprobs
+ default_chunk_class = chunk.__class__
+ chunk = ChatGenerationChunk(
+ message=chunk,
+ generation_info=generation_info or None,
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text, chunk=chunk, logprobs=logprobs)
+ yield chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ self.endpoint_url = self.endpoint_url.replace("/chat/completions", "")
+ timeout = None if "timeout" not in kwargs else kwargs["timeout"]
+
+ import openai
+
+ params = {}
+ client_params = {
+ "api_key": self.endpoint_api_key.get_secret_value(),
+ "base_url": self.endpoint_url,
+ "timeout": timeout,
+ "default_headers": None,
+ "default_query": None,
+ "http_client": None,
+ }
+
+ async_client = openai.AsyncOpenAI(**client_params)
+ message_dicts = [
+ CustomOpenAIChatContentFormatter._convert_message_to_dict(m)
+ for m in messages
+ ]
+ params = {"stream": True, "stop": stop, "model": None, **kwargs}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ async for chunk in await async_client.chat.completions.create(
+ messages=message_dicts,
+ **params,
+ ):
+ if not isinstance(chunk, dict):
+ chunk = chunk.dict()
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], default_chunk_class
+ )
+ generation_info = {}
+ if finish_reason := choice.get("finish_reason"):
+ generation_info["finish_reason"] = finish_reason
+ logprobs = choice.get("logprobs")
+ if logprobs:
+ generation_info["logprobs"] = logprobs
+ default_chunk_class = chunk.__class__
+ chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info or None
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(
+ token=chunk.text, chunk=chunk, logprobs=logprobs
+ )
+ yield chunk
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role = cast(str, _dict.get("role"))
+ content = cast(str, _dict.get("content") or "")
+ additional_kwargs: Dict = {}
+ if _dict.get("function_call"):
+ function_call = dict(_dict["function_call"])
+ if "name" in function_call and function_call["name"] is None:
+ function_call["name"] = ""
+ additional_kwargs["function_call"] = function_call
+ if _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = _dict["tool_calls"]
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ elif role == "function" or default_class == FunctionMessageChunk:
+ return FunctionMessageChunk(content=content, name=_dict["name"])
+ elif role == "tool" or default_class == ToolMessageChunk:
+ return ToolMessageChunk(content=content, tool_call_id=_dict["tool_call_id"])
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role)
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/baichuan.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/baichuan.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a13e09ea0c19fea963493bf576d50b48bbea19c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/baichuan.py
@@ -0,0 +1,650 @@
+import json
+import logging
+from contextlib import asynccontextmanager
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+)
+
+import requests
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+ ToolMessage,
+)
+from langchain_core.output_parsers.openai_tools import (
+ make_invalid_tool_call,
+ parse_tool_call,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable
+from langchain_core.tools import BaseTool
+from langchain_core.utils import (
+ convert_to_secret_str,
+ get_from_dict_or_env,
+ get_pydantic_field_names,
+)
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SecretStr,
+ model_validator,
+)
+
+from langchain_community.chat_models.llamacpp import (
+ _lc_invalid_tool_call_to_openai_tool_call,
+ _lc_tool_call_to_openai_tool_call,
+)
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_API_BASE = "https://api.baichuan-ai.com/v1/chat/completions"
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ message_dict: Dict[str, Any]
+ content = message.content
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": content}
+ if "tool_calls" in message.additional_kwargs:
+ message_dict["tool_calls"] = message.additional_kwargs["tool_calls"]
+
+ elif message.tool_calls or message.invalid_tool_calls:
+ message_dict["tool_calls"] = [
+ _lc_tool_call_to_openai_tool_call(tc) for tc in message.tool_calls
+ ] + [
+ _lc_invalid_tool_call_to_openai_tool_call(tc)
+ for tc in message.invalid_tool_calls
+ ]
+ elif isinstance(message, ToolMessage):
+ message_dict = {
+ "role": "tool",
+ "tool_call_id": message.tool_call_id,
+ "content": content,
+ "name": message.name or message.additional_kwargs.get("name"),
+ }
+
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": content}
+ else:
+ raise TypeError(f"Got unknown type {message}")
+
+ return message_dict
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ role = _dict["role"]
+ content = _dict.get("content", "")
+ if role == "user":
+ return HumanMessage(content=content)
+ elif role == "assistant":
+ tool_calls = []
+ invalid_tool_calls = []
+ additional_kwargs = {}
+
+ if raw_tool_calls := _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ for raw_tool_call in raw_tool_calls:
+ try:
+ tool_calls.append(parse_tool_call(raw_tool_call, return_id=True))
+ except Exception as e:
+ invalid_tool_calls.append(
+ make_invalid_tool_call(raw_tool_call, str(e))
+ )
+
+ return AIMessage(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_calls=tool_calls,
+ invalid_tool_calls=invalid_tool_calls,
+ )
+ elif role == "tool":
+ additional_kwargs = {}
+ if "name" in _dict:
+ additional_kwargs["name"] = _dict["name"]
+ return ToolMessage(
+ content=content,
+ tool_call_id=_dict.get("tool_call_id"),
+ additional_kwargs=additional_kwargs,
+ )
+ elif role == "system":
+ return SystemMessage(content=content)
+ else:
+ return ChatMessage(content=content, role=role)
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role = _dict.get("role")
+ content = _dict.get("content") or ""
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content)
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+@asynccontextmanager
+async def aconnect_httpx_sse(
+ client: Any, method: str, url: str, **kwargs: Any
+) -> AsyncIterator:
+ """Async context manager for connecting to an SSE stream.
+
+ Args:
+ client: The httpx client.
+ method: The HTTP method.
+ url: The URL to connect to.
+ kwargs: Additional keyword arguments to pass to the client.
+
+ Yields:
+ An EventSource object.
+ """
+ from httpx_sse import EventSource
+
+ async with client.stream(method, url, **kwargs) as response:
+ yield EventSource(response)
+
+
+class ChatBaichuan(BaseChatModel):
+ """Baichuan chat model integration.
+
+ Setup:
+ To use, you should have the environment variable``BAICHUAN_API_KEY`` set with
+ your API KEY.
+
+ .. code-block:: bash
+
+ export BAICHUAN_API_KEY="your-api-key"
+
+ Key init args — completion params:
+ model: Optional[str]
+ Name of Baichuan model to use.
+ max_tokens: Optional[int]
+ Max number of tokens to generate.
+ streaming: Optional[bool]
+ Whether to stream the results or not.
+ temperature: Optional[float]
+ Sampling temperature.
+ top_p: Optional[float]
+ What probability mass to use.
+ top_k: Optional[int]
+ What search sampling control to use.
+
+ Key init args — client params:
+ api_key: Optional[str]
+ Baichuan API key. If not passed in will be read from env var BAICHUAN_API_KEY.
+ base_url: Optional[str]
+ Base URL for API requests.
+
+ See full list of supported init args and their descriptions in the params section.
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatBaichuan
+
+ chat = ChatBaichuan(
+ api_key=api_key,
+ model='Baichuan4',
+ # temperature=...,
+ # other params...
+ )
+
+ Invoke:
+ .. code-block:: python
+
+ messages = [
+ ("system", "你是一名专业的翻译家,可以将用户的中文翻译为英文。"),
+ ("human", "我喜欢编程。"),
+ ]
+ chat.invoke(messages)
+
+ .. code-block:: python
+
+ AIMessage(
+ content='I enjoy programming.',
+ response_metadata={
+ 'token_usage': {
+ 'prompt_tokens': 93,
+ 'completion_tokens': 5,
+ 'total_tokens': 98
+ },
+ 'model': 'Baichuan4'
+ },
+ id='run-944ff552-6a93-44cf-a861-4e4d849746f9-0'
+ )
+
+ Stream:
+ .. code-block:: python
+
+ for chunk in chat.stream(messages):
+ print(chunk)
+
+ .. code-block:: python
+
+ content='I' id='run-f99fcd6f-dd31-46d5-be8f-0b6a22bf77d8'
+ content=' enjoy programming.' id='run-f99fcd6f-dd31-46d5-be8f-0b6a22bf77d8
+
+ .. code-block:: python
+
+ stream = chat.stream(messages)
+ full = next(stream)
+ for chunk in stream:
+ full += chunk
+ full
+
+ .. code-block:: python
+
+ AIMessageChunk(
+ content='I like programming.',
+ id='run-74689970-dc31-461d-b729-3b6aa93508d2'
+ )
+
+ Async:
+ .. code-block:: python
+
+ await chat.ainvoke(messages)
+
+ # stream
+ # async for chunk in chat.astream(messages):
+ # print(chunk)
+
+ # batch
+ # await chat.abatch([messages])
+
+ .. code-block:: python
+
+ AIMessage(
+ content='I enjoy programming.',
+ response_metadata={
+ 'token_usage': {
+ 'prompt_tokens': 93,
+ 'completion_tokens': 5,
+ 'total_tokens': 98
+ },
+ 'model': 'Baichuan4'
+ },
+ id='run-952509ed-9154-4ff9-b187-e616d7ddfbba-0'
+ )
+ Tool calling:
+
+ .. code-block:: python
+ class get_current_weather(BaseModel):
+ '''Get current weather.'''
+
+ location: str = Field('City or province, such as Shanghai')
+
+
+ llm_with_tools = ChatBaichuan(model='Baichuan3-Turbo').bind_tools([get_current_weather])
+ llm_with_tools.invoke('How is the weather today?')
+
+ .. code-block:: python
+
+ [{'name': 'get_current_weather',
+ 'args': {'location': 'New York'},
+ 'id': '3951017OF8doB0A',
+ 'type': 'tool_call'}]
+
+ Response metadata
+ .. code-block:: python
+
+ ai_msg = chat.invoke(messages)
+ ai_msg.response_metadata
+
+ .. code-block:: python
+
+ {
+ 'token_usage': {
+ 'prompt_tokens': 93,
+ 'completion_tokens': 5,
+ 'total_tokens': 98
+ },
+ 'model': 'Baichuan4'
+ }
+
+ """ # noqa: E501
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {
+ "baichuan_api_key": "BAICHUAN_API_KEY",
+ }
+
+ @property
+ def lc_serializable(self) -> bool:
+ return True
+
+ baichuan_api_base: str = Field(default=DEFAULT_API_BASE, alias="base_url")
+ """Baichuan custom endpoints"""
+ baichuan_api_key: SecretStr = Field(alias="api_key")
+ """Baichuan API Key"""
+ baichuan_secret_key: Optional[SecretStr] = None
+ """[DEPRECATED, keeping it for for backward compatibility] Baichuan Secret Key"""
+ streaming: bool = False
+ """Whether to stream the results or not."""
+ max_tokens: Optional[int] = None
+ """Maximum number of tokens to generate."""
+ request_timeout: int = Field(default=60, alias="timeout")
+ """request timeout for chat http requests"""
+ model: str = "Baichuan2-Turbo-192K"
+ """model name of Baichuan, default is `Baichuan2-Turbo-192K`,
+ other options include `Baichuan2-Turbo`"""
+ temperature: Optional[float] = Field(default=0.3)
+ """What sampling temperature to use."""
+ top_k: int = 5
+ """What search sampling control to use."""
+ top_p: float = 0.85
+ """What probability mass to use."""
+ with_search_enhance: bool = False
+ """[DEPRECATED, keeping it for for backward compatibility],
+ Whether to use search enhance, default is False."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for API call not explicitly specified."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def build_extra(cls, values: Dict[str, Any]) -> Any:
+ """Build extra kwargs from additional params that were passed in."""
+ all_required_field_names = get_pydantic_field_names(cls)
+ extra = values.get("model_kwargs", {})
+ for field_name in list(values):
+ if field_name in extra:
+ raise ValueError(f"Found {field_name} supplied twice.")
+ if field_name not in all_required_field_names:
+ logger.warning(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please confirm that {field_name} is what you intended."""
+ )
+ extra[field_name] = values.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
+ if invalid_model_kwargs:
+ raise ValueError(
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+
+ values["model_kwargs"] = extra
+ return values
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ values["baichuan_api_base"] = get_from_dict_or_env(
+ values,
+ "baichuan_api_base",
+ "BAICHUAN_API_BASE",
+ DEFAULT_API_BASE,
+ )
+ values["baichuan_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ ["baichuan_api_key", "api_key"],
+ "BAICHUAN_API_KEY",
+ )
+ )
+ return values
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling Baichuan API."""
+ normal_params = {
+ "model": self.model,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "top_k": self.top_k,
+ "stream": self.streaming,
+ "max_tokens": self.max_tokens,
+ }
+
+ return {**normal_params, **self.model_kwargs}
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages=messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ res = self._chat(messages, **kwargs)
+ if res.status_code != 200:
+ raise ValueError(f"Error from Baichuan api response: {res}")
+ response = res.json()
+ return self._create_chat_result(response)
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ res = self._chat(messages, stream=True, **kwargs)
+ if res.status_code != 200:
+ raise ValueError(f"Error from Baichuan api response: {res}")
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ for chunk in res.iter_lines():
+ chunk = chunk.decode("utf-8").strip("\r\n")
+ parts = chunk.split("data: ", 1)
+ chunk = parts[1] if len(parts) > 1 else None
+ if chunk is None:
+ continue
+ if chunk == "[DONE]":
+ break
+ response = json.loads(chunk)
+ for m in response.get("choices"):
+ chunk = _convert_delta_to_message_chunk(
+ m.get("delta"), default_chunk_class
+ )
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(message=chunk)
+ if run_manager:
+ run_manager.on_llm_new_token(str(chunk.content), chunk=cg_chunk)
+ yield cg_chunk
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ headers = self._create_headers_parameters(**kwargs)
+ payload = self._create_payload_parameters(messages, **kwargs)
+
+ import httpx
+
+ async with httpx.AsyncClient(
+ headers=headers, timeout=self.request_timeout
+ ) as client:
+ response = await client.post(self.baichuan_api_base, json=payload)
+ response.raise_for_status()
+ return self._create_chat_result(response.json())
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ headers = self._create_headers_parameters(**kwargs)
+ payload = self._create_payload_parameters(messages, stream=True, **kwargs)
+ import httpx
+
+ async with httpx.AsyncClient(
+ headers=headers, timeout=self.request_timeout
+ ) as client:
+ async with aconnect_httpx_sse(
+ client, "POST", self.baichuan_api_base, json=payload
+ ) as event_source:
+ async for sse in event_source.aiter_sse():
+ chunk = json.loads(sse.data)
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], AIMessageChunk
+ )
+ finish_reason = choice.get("finish_reason", None)
+
+ generation_info = (
+ {"finish_reason": finish_reason}
+ if finish_reason is not None
+ else None
+ )
+ chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+ if finish_reason is not None:
+ break
+
+ def _chat(self, messages: List[BaseMessage], **kwargs: Any) -> requests.Response:
+ payload = self._create_payload_parameters(messages, **kwargs)
+ url = self.baichuan_api_base
+ headers = self._create_headers_parameters(**kwargs)
+
+ res = requests.post(
+ url=url,
+ timeout=self.request_timeout,
+ headers=headers,
+ json=payload,
+ stream=self.streaming,
+ )
+ return res
+
+ def _create_payload_parameters(
+ self, messages: List[BaseMessage], **kwargs: Any
+ ) -> Dict[str, Any]:
+ parameters = {**self._default_params, **kwargs}
+ temperature = parameters.pop("temperature", 0.3)
+ top_k = parameters.pop("top_k", 5)
+ top_p = parameters.pop("top_p", 0.85)
+ model = parameters.pop("model")
+ with_search_enhance = parameters.pop("with_search_enhance", False)
+ stream = parameters.pop("stream", False)
+ tools = parameters.pop("tools", [])
+
+ payload = {
+ "model": model,
+ "messages": [_convert_message_to_dict(m) for m in messages],
+ "top_k": top_k,
+ "top_p": top_p,
+ "temperature": temperature,
+ "with_search_enhance": with_search_enhance,
+ "stream": stream,
+ "tools": tools,
+ }
+
+ return payload
+
+ def _create_headers_parameters(self, **kwargs: Any) -> Dict[str, Any]:
+ parameters = {**self._default_params, **kwargs}
+ default_headers = parameters.pop("headers", {})
+ api_key = ""
+ if self.baichuan_api_key:
+ api_key = self.baichuan_api_key.get_secret_value()
+
+ headers = {
+ "Content-Type": "application/json",
+ "Authorization": f"Bearer {api_key}",
+ **default_headers,
+ }
+ return headers
+
+ def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:
+ generations = []
+ for c in response["choices"]:
+ message = _convert_dict_to_message(c["message"])
+ gen = ChatGeneration(message=message)
+ generations.append(gen)
+
+ token_usage = response["usage"]
+ llm_output = {"token_usage": token_usage, "model": self.model}
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ @property
+ def _llm_type(self) -> str:
+ return "baichuan-chat"
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model.
+
+ Args:
+ tools: A list of tool definitions to bind to this chat model.
+ Can be a dictionary, pydantic model, callable, or BaseTool.
+ Pydantic
+ models, callables, and BaseTools will be automatically converted to
+ their schema dictionary representation.
+ **kwargs: Any additional parameters to pass to the
+ :class:`~langchain.runnable.Runnable` constructor.
+ """
+
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ return super().bind(tools=formatted_tools, **kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/baidu_qianfan_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/baidu_qianfan_endpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f1fa6012e15d99e165c5a003db8ff9759ff8d9e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/baidu_qianfan_endpoint.py
@@ -0,0 +1,841 @@
+import json
+import logging
+import uuid
+from operator import itemgetter
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+ cast,
+)
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ ChatMessage,
+ FunctionMessage,
+ HumanMessage,
+ SystemMessage,
+ ToolMessage,
+)
+from langchain_core.messages.ai import UsageMetadata
+from langchain_core.messages.tool import tool_call_chunk
+from langchain_core.output_parsers.base import OutputParserLike
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ PydanticToolsParser,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
+from langchain_core.tools import BaseTool
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from langchain_core.utils.pydantic import get_fields, is_basemodel_subclass
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SecretStr,
+ model_validator,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def convert_message_to_dict(message: BaseMessage) -> dict:
+ """Convert a message to a dictionary that can be passed to the API."""
+ message_dict: Dict[str, Any]
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ if len(message.tool_calls) != 0:
+ tool_call = message.tool_calls[0]
+ message_dict["function_call"] = {
+ "name": tool_call["name"],
+ "arguments": json.dumps(tool_call["args"], ensure_ascii=False),
+ }
+ # If function call only, content is None not empty string
+ message_dict["content"] = None
+ elif isinstance(message, (FunctionMessage, ToolMessage)):
+ message_dict = {
+ "role": "function",
+ "content": _create_tool_content(message.content),
+ "name": message.name or message.additional_kwargs.get("name"),
+ }
+ else:
+ raise TypeError(f"Got unknown type {message}")
+
+ return message_dict
+
+
+def _create_tool_content(content: Union[str, List[Union[str, Dict[Any, Any]]]]) -> str:
+ """Convert tool content to dict scheme."""
+ if isinstance(content, str):
+ try:
+ if isinstance(json.loads(content), dict):
+ return content
+ else:
+ return json.dumps({"tool_result": content})
+ except json.JSONDecodeError:
+ return json.dumps({"tool_result": content})
+ else:
+ return json.dumps({"tool_result": content})
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> AIMessage:
+ content = _dict.get("result", "") or ""
+ additional_kwargs: Mapping[str, Any] = {}
+ if _dict.get("function_call"):
+ additional_kwargs = {"function_call": dict(_dict["function_call"])}
+ if "thoughts" in additional_kwargs["function_call"]:
+ # align to api sample, which affects the llm function_call output
+ additional_kwargs["function_call"].pop("thoughts")
+
+ # DO NOT ADD ANY NUMERIC OBJECT TO `msg_additional_kwargs` AND `additional_kwargs`
+ # ALONG WITH THEIRS SUB-CONTAINERS !!!
+ # OR IT WILL RAISE A DEADLY EXCEPTION FROM `merge_dict`
+ # 不要往 `msg_additional_kwargs` 和 `additional_kwargs` 里面加任何数值类对象!
+ # 子容器也不行!
+ # 不然 `merge_dict` 会报错导致代码无法运行
+ additional_kwargs = {**_dict.get("body", {}), **additional_kwargs}
+ msg_additional_kwargs = dict(
+ finish_reason=additional_kwargs.get("finish_reason", ""),
+ request_id=additional_kwargs["id"],
+ object=additional_kwargs.get("object", ""),
+ search_info=additional_kwargs.get("search_info", []),
+ )
+
+ if additional_kwargs.get("function_call", {}):
+ msg_additional_kwargs["function_call"] = additional_kwargs.get(
+ "function_call", {}
+ )
+ msg_additional_kwargs["tool_calls"] = [
+ {
+ "type": "function",
+ "function": additional_kwargs.get("function_call", {}),
+ "id": str(uuid.uuid4()),
+ }
+ ]
+
+ ret = AIMessage(
+ content=content,
+ additional_kwargs=msg_additional_kwargs,
+ )
+
+ if usage := additional_kwargs.get("usage", None):
+ ret.usage_metadata = UsageMetadata(
+ input_tokens=usage.get("prompt_tokens", 0),
+ output_tokens=usage.get("completion_tokens", 0),
+ total_tokens=usage.get("total_tokens", 0),
+ )
+
+ return ret
+
+
+class QianfanChatEndpoint(BaseChatModel):
+ """Baidu Qianfan chat model integration.
+
+ Setup:
+ Install ``qianfan`` and set environment variables ``QIANFAN_AK``, ``QIANFAN_SK``.
+
+ .. code-block:: bash
+
+ pip install qianfan
+ export QIANFAN_AK="your-api-key"
+ export QIANFAN_SK="your-secret_key"
+
+ Key init args — completion params:
+ model: str
+ Name of Qianfan model to use.
+ temperature: Optional[float]
+ Sampling temperature.
+ endpoint: Optional[str]
+ Endpoint of the Qianfan LLM
+ top_p: Optional[float]
+ What probability mass to use.
+
+ Key init args — client params:
+ timeout: Optional[int]
+ Timeout for requests.
+ api_key: Optional[str]
+ Qianfan API KEY. If not passed in will be read from env var QIANFAN_AK.
+ secret_key: Optional[str]
+ Qianfan SECRET KEY. If not passed in will be read from env var QIANFAN_SK.
+
+ See full list of supported init args and their descriptions in the params section.
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_models import QianfanChatEndpoint
+
+ qianfan_chat = QianfanChatEndpoint(
+ model="ERNIE-3.5-8K",
+ temperature=0.2,
+ timeout=30,
+ # api_key="...",
+ # secret_key="...",
+ # top_p="...",
+ # other params...
+ )
+
+ Invoke:
+ .. code-block:: python
+
+ messages = [
+ ("system", "你是一名专业的翻译家,可以将用户的中文翻译为英文。"),
+ ("human", "我喜欢编程。"),
+ ]
+ qianfan_chat.invoke(messages)
+
+ .. code-block:: python
+
+ AIMessage(content='I enjoy programming.', additional_kwargs={'finish_reason': 'normal', 'request_id': 'as-7848zeqn1c', 'object': 'chat.completion', 'search_info': []}, response_metadata={'token_usage': {'prompt_tokens': 16, 'completion_tokens': 4, 'total_tokens': 20}, 'model_name': 'ERNIE-3.5-8K', 'finish_reason': 'normal', 'id': 'as-7848zeqn1c', 'object': 'chat.completion', 'created': 1719153606, 'result': 'I enjoy programming.', 'is_truncated': False, 'need_clear_history': False, 'usage': {'prompt_tokens': 16, 'completion_tokens': 4, 'total_tokens': 20}}, id='run-4bca0c10-5043-456b-a5be-2f62a980f3f0-0')
+
+ Stream:
+ .. code-block:: python
+
+ for chunk in qianfan_chat.stream(messages):
+ print(chunk)
+
+ .. code-block:: python
+
+ content='I enjoy' response_metadata={'finish_reason': 'normal', 'request_id': 'as-yz0yz1w1rq', 'object': 'chat.completion', 'search_info': []} id='run-0fa9da50-003e-4a26-ba16-dbfe96249b8b' role='assistant'
+ content=' programming.' response_metadata={'finish_reason': 'normal', 'request_id': 'as-yz0yz1w1rq', 'object': 'chat.completion', 'search_info': []} id='run-0fa9da50-003e-4a26-ba16-dbfe96249b8b' role='assistant'
+
+ .. code-block:: python
+
+ stream = chat.stream(messages)
+ full = next(stream)
+ for chunk in stream:
+ full += chunk
+ full
+
+ .. code-block::
+
+ AIMessageChunk(content='I enjoy programming.', response_metadata={'finish_reason': 'normalnormal', 'request_id': 'as-p63cnn3ppnas-p63cnn3ppn', 'object': 'chat.completionchat.completion', 'search_info': []}, id='run-09a8cbbd-5ded-4529-981d-5bc9d1206404')
+
+ Async:
+ .. code-block:: python
+
+ await qianfan_chat.ainvoke(messages)
+
+ # stream:
+ # async for chunk in qianfan_chat.astream(messages):
+ # print(chunk)
+
+ # batch:
+ # await qianfan_chat.abatch([messages])
+
+ .. code-block:: python
+
+ [AIMessage(content='I enjoy programming.', additional_kwargs={'finish_reason': 'normal', 'request_id': 'as-mpqa8qa1qb', 'object': 'chat.completion', 'search_info': []}, response_metadata={'token_usage': {'prompt_tokens': 16, 'completion_tokens': 4, 'total_tokens': 20}, 'model_name': 'ERNIE-3.5-8K', 'finish_reason': 'normal', 'id': 'as-mpqa8qa1qb', 'object': 'chat.completion', 'created': 1719155120, 'result': 'I enjoy programming.', 'is_truncated': False, 'need_clear_history': False, 'usage': {'prompt_tokens': 16, 'completion_tokens': 4, 'total_tokens': 20}}, id='run-443b2231-08f9-4725-b807-b77d0507ad44-0')]
+
+ Tool calling:
+ .. code-block:: python
+
+ 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"
+ )
+
+
+ class GetPopulation(BaseModel):
+ '''Get the current population in a given location'''
+
+ location: str = Field(
+ ..., description="The city and state, e.g. San Francisco, CA"
+ )
+
+ chat_with_tools = qianfan_chat.bind_tools([GetWeather, GetPopulation])
+ ai_msg = chat_with_tools.invoke(
+ "Which city is hotter today and which is bigger: LA or NY?"
+ )
+ ai_msg.tool_calls
+
+ .. code-block:: python
+
+ [
+ {
+ 'name': 'GetWeather',
+ 'args': {'location': 'Los Angeles, CA'},
+ 'id': '533e5f63-a3dc-40f2-9d9c-22b1feee62e0'
+ }
+ ]
+
+ Structured output:
+ .. code-block:: python
+
+ from typing import Optional
+
+ from pydantic import BaseModel, Field
+
+
+ class Joke(BaseModel):
+ '''Joke to tell user.'''
+
+ setup: str = Field(description="The setup of the joke")
+ punchline: str = Field(description="The punchline to the joke")
+ rating: Optional[int] = Field(description="How funny the joke is, from 1 to 10")
+
+
+ structured_chat = qianfan_chat.with_structured_output(Joke)
+ structured_chat.invoke("Tell me a joke about cats")
+
+ .. code-block:: python
+
+ Joke(
+ setup='A cat is sitting in front of a mirror and sees another cat. What does the cat think?',
+ punchline="The cat doesn't think it's another cat, it thinks it's another mirror.",
+ rating=None
+ )
+
+ Response metadata
+ .. code-block:: python
+
+ ai_msg = qianfan_chat.invoke(messages)
+ ai_msg.response_metadata
+
+ .. code-block:: python
+ {
+ 'token_usage': {
+ 'prompt_tokens': 16,
+ 'completion_tokens': 4,
+ 'total_tokens': 20},
+ 'model_name': 'ERNIE-3.5-8K',
+ 'finish_reason': 'normal',
+ 'id': 'as-qbzwtydqmi',
+ 'object': 'chat.completion',
+ 'created': 1719158153,
+ 'result': 'I enjoy programming.',
+ 'is_truncated': False,
+ 'need_clear_history': False,
+ 'usage': {
+ 'prompt_tokens': 16,
+ 'completion_tokens': 4,
+ 'total_tokens': 20
+ }
+ }
+
+ """ # noqa: E501
+
+ init_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """init kwargs for qianfan client init, such as `query_per_second` which is
+ associated with qianfan resource object to limit QPS"""
+
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """extra params for model invoke using with `do`."""
+
+ client: Any = None #: :meta private:
+
+ # It could be empty due to the use of Console API
+ # And they're not list here
+ qianfan_ak: Optional[SecretStr] = Field(default=None, alias="api_key")
+ """Qianfan API KEY"""
+ qianfan_sk: Optional[SecretStr] = Field(default=None, alias="secret_key")
+ """Qianfan SECRET KEY"""
+ streaming: Optional[bool] = False
+ """Whether to stream the results or not."""
+
+ request_timeout: Optional[int] = Field(60, alias="timeout")
+ """request timeout for chat http requests"""
+
+ top_p: Optional[float] = 0.8
+ """What probability mass to use."""
+ temperature: Optional[float] = 0.95
+ """What sampling temperature to use."""
+ penalty_score: Optional[float] = 1
+ """Model params, only supported in ERNIE-Bot and ERNIE-Bot-turbo.
+ In the case of other model, passing these params will not affect the result.
+ """
+
+ model: Optional[str] = Field(default=None)
+ """Model name.
+ you could get from https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu
+
+ preset models are mapping to an endpoint.
+ `model` will be ignored if `endpoint` is set.
+ Default is set by `qianfan` SDK, not here
+ """
+
+ endpoint: Optional[str] = None
+ """Endpoint of the Qianfan LLM, required if custom model used."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ values["qianfan_ak"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values, ["qianfan_ak", "api_key"], "QIANFAN_AK", default=""
+ )
+ )
+ values["qianfan_sk"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values, ["qianfan_sk", "secret_key"], "QIANFAN_SK", default=""
+ )
+ )
+
+ default_values = {
+ name: field.default
+ for name, field in get_fields(cls).items()
+ if field.default is not None
+ }
+ default_values.update(values)
+ params = {
+ **values.get("init_kwargs", {}),
+ "model": default_values.get("model"),
+ "stream": default_values.get("streaming"),
+ }
+ if values["qianfan_ak"].get_secret_value() != "":
+ params["ak"] = values["qianfan_ak"].get_secret_value()
+ if values["qianfan_sk"].get_secret_value() != "":
+ params["sk"] = values["qianfan_sk"].get_secret_value()
+ if (
+ default_values.get("endpoint") is not None
+ and default_values["endpoint"] != ""
+ ):
+ params["endpoint"] = default_values["endpoint"]
+ try:
+ import qianfan
+
+ values["client"] = qianfan.ChatCompletion(**params)
+ except ImportError:
+ raise ImportError(
+ "qianfan package not found, please install it with "
+ "`pip install qianfan`"
+ )
+ return values
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ return {
+ **{"endpoint": self.endpoint, "model": self.model},
+ **super()._identifying_params,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat_model."""
+ return "baidu-qianfan-chat"
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling Qianfan API."""
+ normal_params = {
+ "model": self.model,
+ "endpoint": self.endpoint,
+ "stream": self.streaming,
+ "request_timeout": self.request_timeout,
+ "top_p": self.top_p,
+ "temperature": self.temperature,
+ "penalty_score": self.penalty_score,
+ }
+
+ return {**normal_params, **self.model_kwargs}
+
+ def _convert_prompt_msg_params(
+ self,
+ messages: List[BaseMessage],
+ **kwargs: Any,
+ ) -> Dict[str, Any]:
+ """
+ Converts a list of messages into a dictionary containing the message content
+ and default parameters.
+
+ Args:
+ messages (List[BaseMessage]): The list of messages.
+ **kwargs (Any): Optional arguments to add additional parameters to the
+ resulting dictionary.
+
+ Returns:
+ `dict` containing the message content and default parameters.
+
+ """
+ messages_dict: Dict[str, Any] = {
+ "messages": [
+ convert_message_to_dict(m)
+ for m in messages
+ if not isinstance(m, SystemMessage)
+ ]
+ }
+ for i in [i for i, m in enumerate(messages) if isinstance(m, SystemMessage)]:
+ if "system" not in messages_dict:
+ messages_dict["system"] = ""
+ messages_dict["system"] += cast(str, messages[i].content) + "\n"
+
+ return {
+ **messages_dict,
+ **self._default_params,
+ **kwargs,
+ }
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Call out to an qianfan models endpoint for each generation with a prompt.
+ Args:
+ messages: The messages to pass into the model.
+ stop: Optional list of stop words to use when generating.
+ Returns:
+ The string generated by the model.
+
+ Example:
+ .. code-block:: python
+ response = qianfan_model.invoke("Tell me a joke.")
+ """
+ if self.streaming:
+ completion = ""
+ chat_generation_info: Dict = {}
+ usage_metadata: Optional[UsageMetadata] = None
+ for chunk in self._stream(messages, stop, run_manager, **kwargs):
+ chat_generation_info = (
+ chunk.generation_info
+ if chunk.generation_info is not None
+ else chat_generation_info
+ )
+ completion += chunk.text
+ if isinstance(chunk.message, AIMessageChunk):
+ usage_metadata = chunk.message.usage_metadata
+
+ lc_msg = AIMessage(
+ content=completion,
+ additional_kwargs={},
+ usage_metadata=usage_metadata,
+ )
+ gen = ChatGeneration(
+ message=lc_msg,
+ generation_info=dict(finish_reason="stop"),
+ )
+ return ChatResult(
+ generations=[gen],
+ llm_output={
+ "token_usage": usage_metadata or {},
+ "model_name": self.model,
+ },
+ )
+ params = self._convert_prompt_msg_params(messages, **kwargs)
+ params["stop"] = stop
+ response_payload = self.client.do(**params)
+ lc_msg = _convert_dict_to_message(response_payload)
+ gen = ChatGeneration(
+ message=lc_msg,
+ generation_info={
+ "finish_reason": "stop",
+ **response_payload.get("body", {}),
+ },
+ )
+ token_usage = response_payload.get("usage", {})
+ llm_output = {"token_usage": token_usage, "model_name": self.model}
+ return ChatResult(generations=[gen], llm_output=llm_output)
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ completion = ""
+ chat_generation_info: Dict = {}
+ usage_metadata: Optional[UsageMetadata] = None
+ async for chunk in self._astream(messages, stop, run_manager, **kwargs):
+ chat_generation_info = (
+ chunk.generation_info
+ if chunk.generation_info is not None
+ else chat_generation_info
+ )
+ completion += chunk.text
+
+ if isinstance(chunk.message, AIMessageChunk):
+ usage_metadata = chunk.message.usage_metadata
+
+ lc_msg = AIMessage(
+ content=completion,
+ additional_kwargs={},
+ usage_metadata=usage_metadata,
+ )
+ gen = ChatGeneration(
+ message=lc_msg,
+ generation_info=dict(finish_reason="stop"),
+ )
+ return ChatResult(
+ generations=[gen],
+ llm_output={
+ "token_usage": usage_metadata or {},
+ "model_name": self.model,
+ },
+ )
+ params = self._convert_prompt_msg_params(messages, **kwargs)
+ params["stop"] = stop
+ response_payload = await self.client.ado(**params)
+ lc_msg = _convert_dict_to_message(response_payload)
+ generations = []
+ gen = ChatGeneration(
+ message=lc_msg,
+ generation_info={
+ "finish_reason": "stop",
+ **response_payload.get("body", {}),
+ },
+ )
+ generations.append(gen)
+ token_usage = response_payload.get("usage", {})
+ llm_output = {"token_usage": token_usage, "model_name": self.model}
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ params = self._convert_prompt_msg_params(messages, **kwargs)
+ params["stop"] = stop
+ params["stream"] = True
+ for res in self.client.do(**params):
+ if res:
+ msg = _convert_dict_to_message(res)
+ additional_kwargs = msg.additional_kwargs.get("function_call", {})
+ chunk = ChatGenerationChunk(
+ text=res["result"],
+ message=AIMessageChunk( # type: ignore[call-arg]
+ content=msg.content,
+ role="assistant",
+ additional_kwargs=additional_kwargs,
+ usage_metadata=msg.usage_metadata,
+ tool_call_chunks=[
+ tool_call_chunk(
+ name=tc["name"],
+ args=json.dumps(tc["args"]),
+ id=tc["id"],
+ index=None,
+ )
+ for tc in msg.tool_calls
+ ],
+ ),
+ generation_info=msg.additional_kwargs,
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ params = self._convert_prompt_msg_params(messages, **kwargs)
+ params["stop"] = stop
+ params["stream"] = True
+ async for res in await self.client.ado(**params):
+ if res:
+ msg = _convert_dict_to_message(res)
+ additional_kwargs = msg.additional_kwargs.get("function_call", {})
+ chunk = ChatGenerationChunk(
+ text=res["result"],
+ message=AIMessageChunk( # type: ignore[call-arg]
+ content=msg.content,
+ role="assistant",
+ additional_kwargs=additional_kwargs,
+ usage_metadata=msg.usage_metadata,
+ tool_call_chunks=[
+ tool_call_chunk(
+ name=tc["name"],
+ args=json.dumps(tc["args"]),
+ id=tc["id"],
+ index=None,
+ )
+ for tc in msg.tool_calls
+ ],
+ ),
+ generation_info=msg.additional_kwargs,
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model.
+
+ Assumes model is compatible with OpenAI tool-calling API.
+
+ Args:
+ tools: A list of tool definitions to bind to this chat model.
+ Can be a dictionary, pydantic model, callable, or BaseTool. Pydantic
+ models, callables, and BaseTools will be automatically converted to
+ their schema dictionary representation.
+ **kwargs: Any additional parameters to pass to the
+ :class:`~langchain.runnable.Runnable` constructor.
+ """
+
+ formatted_tools = [convert_to_openai_tool(tool)["function"] for tool in tools]
+ return super().bind(functions=formatted_tools, **kwargs)
+
+ def with_structured_output(
+ self,
+ schema: Union[Dict, Type[BaseModel]],
+ *,
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, Union[Dict, BaseModel]]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema: The output schema as a dict or a Pydantic class. If a Pydantic class
+ then the model output will be an object of that class. If a dict then
+ the model output will be a dict. With a Pydantic class the returned
+ attributes will be validated, whereas with a dict they will not be. If
+ `method` is "function_calling" and `schema` is a dict, then the dict
+ must match the OpenAI function-calling spec.
+ include_raw: If False then only the parsed structured output is returned. If
+ an error occurs during model output parsing it will be raised. If True
+ then both the raw model response (a BaseMessage) and the parsed model
+ response will be returned. If an error occurs during output parsing it
+ will be caught and returned as well. The final output is always a dict
+ with keys "raw", "parsed", and "parsing_error".
+
+ Returns:
+ A Runnable that takes any ChatModel input and returns as output:
+
+ If include_raw is True then a dict with keys:
+ raw: BaseMessage
+ parsed: Optional[_DictOrPydantic]
+ parsing_error: Optional[BaseException]
+
+ If include_raw is False then just _DictOrPydantic is returned,
+ where _DictOrPydantic depends on the schema:
+
+ If schema is a Pydantic class then _DictOrPydantic is the Pydantic
+ class.
+
+ If schema is a dict then _DictOrPydantic is a dict.
+
+ Example: Function-calling, Pydantic schema (method="function_calling", include_raw=False):
+ .. code-block:: python
+
+ from langchain_mistralai import QianfanChatEndpoint
+ from pydantic import BaseModel
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+ answer: str
+ justification: str
+
+ llm = QianfanChatEndpoint(endpoint="ernie-3.5-8k-0329")
+ structured_llm = llm.with_structured_output(AnswerWithJustification)
+
+ structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
+
+ # -> AnswerWithJustification(
+ # answer='They weigh the same',
+ # justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'
+ # )
+
+ Example: Function-calling, Pydantic schema (method="function_calling", include_raw=True):
+ .. code-block:: python
+
+ from langchain_mistralai import QianfanChatEndpoint
+ from pydantic import BaseModel
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+ answer: str
+ justification: str
+
+ llm = QianfanChatEndpoint(endpoint="ernie-3.5-8k-0329")
+ structured_llm = llm.with_structured_output(AnswerWithJustification, include_raw=True)
+
+ structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
+ # -> {
+ # 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_Ao02pnFYXD6GN1yzc0uXPsvF', 'function': {'arguments': '{"answer":"They weigh the same.","justification":"Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ."}', 'name': 'AnswerWithJustification'}, 'type': 'function'}]}),
+ # 'parsed': AnswerWithJustification(answer='They weigh the same.', justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'),
+ # 'parsing_error': None
+ # }
+
+ Example: Function-calling, dict schema (method="function_calling", include_raw=False):
+ .. code-block:: python
+
+ from langchain_mistralai import QianfanChatEndpoint
+ from pydantic import BaseModel
+ from langchain_core.utils.function_calling import convert_to_openai_tool
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+ answer: str
+ justification: str
+
+ dict_schema = convert_to_openai_tool(AnswerWithJustification)
+ llm = QianfanChatEndpoint(endpoint="ernie-3.5-8k-0329")
+ structured_llm = llm.with_structured_output(dict_schema)
+
+ structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
+ # -> {
+ # 'answer': 'They weigh the same',
+ # 'justification': 'Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume and density of the two substances differ.'
+ # }
+
+ """ # noqa: E501
+ if kwargs:
+ raise ValueError(f"Received unsupported arguments {kwargs}")
+ is_pydantic_schema = isinstance(schema, type) and is_basemodel_subclass(schema)
+ llm = self.bind_tools([schema])
+ if is_pydantic_schema:
+ output_parser: OutputParserLike = PydanticToolsParser(
+ tools=[schema], # type: ignore[list-item]
+ first_tool_only=True,
+ )
+ else:
+ key_name = convert_to_openai_tool(schema)["function"]["name"]
+ output_parser = JsonOutputKeyToolsParser(
+ key_name=key_name, first_tool_only=True
+ )
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ else:
+ return llm | output_parser
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/bedrock.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/bedrock.py
new file mode 100644
index 0000000000000000000000000000000000000000..086a4d461301fcdc30529d1bcc26fcbc6781b4a3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/bedrock.py
@@ -0,0 +1,337 @@
+import re
+from collections import defaultdict
+from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks import (
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from pydantic import ConfigDict
+
+from langchain_community.chat_models.anthropic import (
+ convert_messages_to_prompt_anthropic,
+)
+from langchain_community.chat_models.meta import convert_messages_to_prompt_llama
+from langchain_community.llms.bedrock import BedrockBase
+from langchain_community.utilities.anthropic import (
+ get_num_tokens_anthropic,
+ get_token_ids_anthropic,
+)
+
+
+def _convert_one_message_to_text_mistral(message: BaseMessage) -> str:
+ if isinstance(message, ChatMessage):
+ message_text = f"\n\n{message.role.capitalize()}: {message.content}"
+ elif isinstance(message, HumanMessage):
+ message_text = f"[INST] {message.content} [/INST]"
+ elif isinstance(message, AIMessage):
+ message_text = f"{message.content}"
+ elif isinstance(message, SystemMessage):
+ message_text = f"<> {message.content} <>"
+ else:
+ raise ValueError(f"Got unknown type {message}")
+ return message_text
+
+
+def convert_messages_to_prompt_mistral(messages: List[BaseMessage]) -> str:
+ """Convert a list of messages to a prompt for mistral."""
+ return "\n".join(
+ [_convert_one_message_to_text_mistral(message) for message in messages]
+ )
+
+
+def _format_image(image_url: str) -> Dict:
+ """
+ Formats an image of format data:image/jpeg;base64,{b64_string}
+ to a dict for anthropic api
+
+ {
+ "type": "base64",
+ "media_type": "image/jpeg",
+ "data": "/9j/4AAQSkZJRg...",
+ }
+
+ And throws an error if it's not a b64 image
+ """
+ regex = r"^data:(?Pimage/.+);base64,(?P.+)$"
+ match = re.match(regex, image_url)
+ if match is None:
+ raise ValueError(
+ "Anthropic only supports base64-encoded images currently."
+ " Example: data:image/png;base64,'/9j/4AAQSk'..."
+ )
+ return {
+ "type": "base64",
+ "media_type": match.group("media_type"),
+ "data": match.group("data"),
+ }
+
+
+def _format_anthropic_messages(
+ messages: List[BaseMessage],
+) -> Tuple[Optional[str], List[Dict]]:
+ """Format messages for anthropic."""
+
+ """
+ [
+ {
+ "role": _message_type_lookups[m.type],
+ "content": [_AnthropicMessageContent(text=m.content).dict()],
+ }
+ for m in messages
+ ]
+ """
+ system: Optional[str] = None
+ formatted_messages: List[Dict] = []
+ for i, message in enumerate(messages):
+ if message.type == "system":
+ if i != 0:
+ raise ValueError("System message must be at beginning of message list.")
+ if not isinstance(message.content, str):
+ raise ValueError(
+ "System message must be a string, "
+ f"instead was: {type(message.content)}"
+ )
+ system = message.content
+ continue
+
+ role = _message_type_lookups[message.type]
+ content: Union[str, List[Dict]]
+
+ if not isinstance(message.content, str):
+ # parse as dict
+ assert isinstance(message.content, list), (
+ "Anthropic message content must be str or list of dicts"
+ )
+
+ # populate content
+ content = []
+ for item in message.content:
+ if isinstance(item, str):
+ content.append(
+ {
+ "type": "text",
+ "text": item,
+ }
+ )
+ elif isinstance(item, dict):
+ if "type" not in item:
+ raise ValueError("Dict content item must have a type key")
+ if item["type"] == "image_url":
+ # convert format
+ source = _format_image(item["image_url"]["url"])
+ content.append(
+ {
+ "type": "image",
+ "source": source,
+ }
+ )
+ else:
+ content.append(item)
+ else:
+ raise ValueError(
+ f"Content items must be str or dict, instead was: {type(item)}"
+ )
+ else:
+ content = message.content
+
+ formatted_messages.append(
+ {
+ "role": role,
+ "content": content,
+ }
+ )
+ return system, formatted_messages
+
+
+class ChatPromptAdapter:
+ """Adapter class to prepare the inputs from Langchain to prompt format
+ that Chat model expects.
+ """
+
+ @classmethod
+ def convert_messages_to_prompt(
+ cls, provider: str, messages: List[BaseMessage]
+ ) -> str:
+ if provider == "anthropic":
+ prompt = convert_messages_to_prompt_anthropic(messages=messages)
+ elif provider == "meta":
+ prompt = convert_messages_to_prompt_llama(messages=messages)
+ elif provider == "mistral":
+ prompt = convert_messages_to_prompt_mistral(messages=messages)
+ elif provider == "amazon":
+ prompt = convert_messages_to_prompt_anthropic(
+ messages=messages,
+ human_prompt="\n\nUser:",
+ ai_prompt="\n\nBot:",
+ )
+ else:
+ raise NotImplementedError(
+ f"Provider {provider} model does not support chat."
+ )
+ return prompt
+
+ @classmethod
+ def format_messages(
+ cls, provider: str, messages: List[BaseMessage]
+ ) -> Tuple[Optional[str], List[Dict]]:
+ if provider == "anthropic":
+ return _format_anthropic_messages(messages)
+
+ raise NotImplementedError(
+ f"Provider {provider} not supported for format_messages"
+ )
+
+
+_message_type_lookups = {
+ "human": "user",
+ "ai": "assistant",
+ "AIMessageChunk": "assistant",
+ "HumanMessageChunk": "user",
+ "function": "user",
+}
+
+
+@deprecated(
+ since="0.0.34", removal="1.0", alternative_import="langchain_aws.ChatBedrock"
+)
+class BedrockChat(BaseChatModel, BedrockBase):
+ """Chat model that uses the Bedrock API."""
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "amazon_bedrock_chat"
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return whether this model can be serialized by Langchain."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> List[str]:
+ """Get the namespace of the langchain object."""
+ return ["langchain", "chat_models", "bedrock"]
+
+ @property
+ def lc_attributes(self) -> Dict[str, Any]:
+ attributes: Dict[str, Any] = {}
+
+ if self.region_name:
+ attributes["region_name"] = self.region_name
+
+ return attributes
+
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ provider = self._get_provider()
+ prompt, system, formatted_messages = None, None, None
+
+ if provider == "anthropic":
+ system, formatted_messages = ChatPromptAdapter.format_messages(
+ provider, messages
+ )
+ else:
+ prompt = ChatPromptAdapter.convert_messages_to_prompt(
+ provider=provider, messages=messages
+ )
+
+ for chunk in self._prepare_input_and_invoke_stream(
+ prompt=prompt,
+ system=system,
+ messages=formatted_messages,
+ stop=stop,
+ run_manager=run_manager,
+ **kwargs,
+ ):
+ delta = chunk.text
+ yield ChatGenerationChunk(message=AIMessageChunk(content=delta))
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ completion = ""
+ llm_output: Dict[str, Any] = {"model_id": self.model_id}
+
+ if self.streaming:
+ for chunk in self._stream(messages, stop, run_manager, **kwargs):
+ completion += chunk.text
+ else:
+ provider = self._get_provider()
+ prompt, system, formatted_messages = None, None, None
+ params: Dict[str, Any] = {**kwargs}
+
+ if provider == "anthropic":
+ system, formatted_messages = ChatPromptAdapter.format_messages(
+ provider, messages
+ )
+ else:
+ prompt = ChatPromptAdapter.convert_messages_to_prompt(
+ provider=provider, messages=messages
+ )
+
+ if stop:
+ params["stop_sequences"] = stop
+
+ completion, usage_info = self._prepare_input_and_invoke(
+ prompt=prompt,
+ stop=stop,
+ run_manager=run_manager,
+ system=system,
+ messages=formatted_messages,
+ **params,
+ )
+
+ llm_output["usage"] = usage_info
+
+ return ChatResult(
+ generations=[ChatGeneration(message=AIMessage(content=completion))],
+ llm_output=llm_output,
+ )
+
+ def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:
+ final_usage: Dict[str, int] = defaultdict(int)
+ final_output = {}
+ for output in llm_outputs:
+ output = output or {}
+ usage = output.get("usage", {})
+ for token_type, token_count in usage.items():
+ final_usage[token_type] += token_count
+ final_output.update(output)
+ final_output["usage"] = final_usage
+ return final_output
+
+ def get_num_tokens(self, text: str) -> int:
+ if self._model_is_anthropic:
+ return get_num_tokens_anthropic(text)
+ else:
+ return super().get_num_tokens(text)
+
+ def get_token_ids(self, text: str) -> List[int]:
+ if self._model_is_anthropic:
+ return get_token_ids_anthropic(text)
+ else:
+ return super().get_token_ids(text)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/cloudflare_workersai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/cloudflare_workersai.py
new file mode 100644
index 0000000000000000000000000000000000000000..ece4845cce92f4c03232fc719c7b12c1cb171e2c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/cloudflare_workersai.py
@@ -0,0 +1,256 @@
+import logging
+from operator import itemgetter
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ List,
+ Literal,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+ cast,
+)
+from uuid import uuid4
+
+import requests
+from langchain_classic.schema import AIMessage, ChatGeneration, ChatResult, HumanMessage
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessageChunk,
+ BaseMessage,
+ SystemMessage,
+ ToolCall,
+ ToolMessage,
+)
+from langchain_core.messages.tool import tool_call
+from langchain_core.output_parsers import (
+ JsonOutputParser,
+ PydanticOutputParser,
+)
+from langchain_core.output_parsers.base import OutputParserLike
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ PydanticToolsParser,
+)
+from langchain_core.runnables import Runnable, RunnablePassthrough
+from langchain_core.runnables.base import RunnableMap
+from langchain_core.tools import BaseTool
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from langchain_core.utils.pydantic import is_basemodel_subclass
+from pydantic import BaseModel, Field
+
+# Initialize logging
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s - %(levelname)s - %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+)
+_logger = logging.getLogger(__name__)
+
+
+def _is_pydantic_class(obj: Any) -> bool:
+ return isinstance(obj, type) and is_basemodel_subclass(obj)
+
+
+def _convert_messages_to_cloudflare_messages(
+ messages: List[BaseMessage],
+) -> List[Dict[str, Any]]:
+ """Convert LangChain messages to Cloudflare Workers AI format."""
+ cloudflare_messages = []
+ msg: Dict[str, Any]
+ for message in messages:
+ # Base structure for each message
+ msg = {
+ "role": "",
+ "content": message.content if isinstance(message.content, str) else "",
+ }
+
+ # Determine role and additional fields based on message type
+ if isinstance(message, HumanMessage):
+ msg["role"] = "user"
+ elif isinstance(message, AIMessage):
+ msg["role"] = "assistant"
+ # If the AIMessage includes tool calls, format them as needed
+ if message.tool_calls:
+ tool_calls = [
+ {"name": tool_call["name"], "arguments": tool_call["args"]}
+ for tool_call in message.tool_calls
+ ]
+ msg["tool_calls"] = tool_calls
+ elif isinstance(message, SystemMessage):
+ msg["role"] = "system"
+ elif isinstance(message, ToolMessage):
+ msg["role"] = "tool"
+ msg["tool_call_id"] = (
+ message.tool_call_id
+ ) # Use tool_call_id if it's a ToolMessage
+
+ # Add the formatted message to the list
+ cloudflare_messages.append(msg)
+
+ return cloudflare_messages
+
+
+def _get_tool_calls_from_response(response: requests.Response) -> List[ToolCall]:
+ """Get tool calls from ollama response."""
+ tool_calls = []
+ if "tool_calls" in response.json()["result"]:
+ for tc in response.json()["result"]["tool_calls"]:
+ tool_calls.append(
+ tool_call(
+ id=str(uuid4()),
+ name=tc["name"],
+ args=tc["arguments"],
+ )
+ )
+ return tool_calls
+
+
+@deprecated(
+ since="0.3.23",
+ removal="1.0",
+ alternative_import="langchain_cloudflare.ChatCloudflareWorkersAI",
+)
+class ChatCloudflareWorkersAI(BaseChatModel):
+ """Custom chat model for Cloudflare Workers AI"""
+
+ account_id: str = Field(...)
+ api_token: str = Field(...)
+ model: str = Field(...)
+ ai_gateway: str = ""
+ url: str = ""
+ base_url: str = "https://api.cloudflare.com/client/v4/accounts"
+ gateway_url: str = "https://gateway.ai.cloudflare.com/v1"
+
+ def __init__(self, **kwargs: Any) -> None:
+ """Initialize with necessary credentials."""
+ super().__init__(**kwargs)
+ if self.ai_gateway:
+ self.url = (
+ f"{self.gateway_url}/{self.account_id}/"
+ f"{self.ai_gateway}/workers-ai/run/{self.model}"
+ )
+ else:
+ self.url = f"{self.base_url}/{self.account_id}/ai/run/{self.model}"
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate a response based on the messages provided."""
+ formatted_messages = _convert_messages_to_cloudflare_messages(messages)
+
+ headers = {"Authorization": f"Bearer {self.api_token}"}
+ prompt = "\n".join(
+ f"role: {msg['role']}, content: {msg['content']}"
+ + (f", tools: {msg['tool_calls']}" if "tool_calls" in msg else "")
+ + (
+ f", tool_call_id: {msg['tool_call_id']}"
+ if "tool_call_id" in msg
+ else ""
+ )
+ for msg in formatted_messages
+ )
+
+ # Initialize `data` with `prompt`
+ data = {
+ "prompt": prompt,
+ "tools": kwargs["tools"] if "tools" in kwargs else None,
+ **{key: value for key, value in kwargs.items() if key not in ["tools"]},
+ }
+
+ # Ensure `tools` is a list if it's included in `kwargs`
+ if data["tools"] is not None and not isinstance(data["tools"], list):
+ data["tools"] = [data["tools"]]
+
+ _logger.info(f"Sending prompt to Cloudflare Workers AI: {data}")
+
+ response = requests.post(self.url, headers=headers, json=data)
+ tool_calls = _get_tool_calls_from_response(response)
+ ai_message = AIMessage(
+ content=str(response.json()), tool_calls=cast(AIMessageChunk, tool_calls)
+ )
+ chat_generation = ChatGeneration(message=ai_message)
+ return ChatResult(generations=[chat_generation])
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type, Callable[..., Any], BaseTool]],
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tools for use in model generation."""
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ return super().bind(tools=formatted_tools, **kwargs)
+
+ def with_structured_output(
+ self,
+ schema: Union[Dict, Type[BaseModel]],
+ *,
+ include_raw: bool = False,
+ method: Optional[Literal["json_mode", "function_calling"]] = "function_calling",
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, Union[Dict, BaseModel]]:
+ """Model wrapper that returns outputs formatted to match the given schema."""
+
+ _ = kwargs.pop("strict", None)
+ if kwargs:
+ raise ValueError(f"Received unsupported arguments {kwargs}")
+ is_pydantic_schema = _is_pydantic_class(schema)
+ if method == "json_schema":
+ # Some applications require that incompatible parameters (e.g., unsupported
+ # methods) be handled.
+ method = "function_calling"
+ if method == "function_calling":
+ if schema is None:
+ raise ValueError(
+ "schema must be specified when method is 'function_calling'. "
+ "Received None."
+ )
+ tool_name = convert_to_openai_tool(schema)["function"]["name"]
+ llm = self.bind_tools([schema], tool_choice=tool_name)
+ if is_pydantic_schema:
+ output_parser: OutputParserLike = PydanticToolsParser(
+ tools=[schema], # type: ignore[list-item]
+ first_tool_only=True,
+ )
+ else:
+ output_parser = JsonOutputKeyToolsParser(
+ key_name=tool_name, first_tool_only=True
+ )
+ elif method == "json_mode":
+ llm = self.bind(response_format={"type": "json_object"})
+ output_parser = (
+ PydanticOutputParser(pydantic_object=schema) # type: ignore[arg-type]
+ if is_pydantic_schema
+ else JsonOutputParser()
+ )
+ else:
+ raise ValueError(
+ f"Unrecognized method argument. Expected one of 'function_calling' or "
+ f"'json_mode'. Received: '{method}'"
+ )
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ else:
+ return llm | output_parser
+
+ @property
+ def _llm_type(self) -> str:
+ """Return the type of the LLM (for Langchain compatibility)."""
+ return "cloudflare-workers-ai"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/cohere.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/cohere.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2e8560a151586b2a742fa62bb4302aafff2a544
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/cohere.py
@@ -0,0 +1,251 @@
+from typing import Any, AsyncIterator, Dict, Iterator, List, Optional
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from pydantic import ConfigDict
+
+from langchain_community.llms.cohere import BaseCohere
+
+
+def get_role(message: BaseMessage) -> str:
+ """Get the role of the message.
+
+ Args:
+ message: The message.
+
+ Returns:
+ The role of the message.
+
+ Raises:
+ ValueError: If the message is of an unknown type.
+ """
+ if isinstance(message, ChatMessage) or isinstance(message, HumanMessage):
+ return "User"
+ elif isinstance(message, AIMessage):
+ return "Chatbot"
+ elif isinstance(message, SystemMessage):
+ return "System"
+ else:
+ raise ValueError(f"Got unknown type {message}")
+
+
+def get_cohere_chat_request(
+ messages: List[BaseMessage],
+ *,
+ connectors: Optional[List[Dict[str, str]]] = None,
+ **kwargs: Any,
+) -> Dict[str, Any]:
+ """Get the request for the Cohere chat API.
+
+ Args:
+ messages: The messages.
+ connectors: The connectors.
+ **kwargs: The keyword arguments.
+
+ Returns:
+ The request for the Cohere chat API.
+ """
+ documents = (
+ None
+ if "source_documents" not in kwargs
+ else [
+ {
+ "snippet": doc.page_content,
+ "id": doc.metadata.get("id") or f"doc-{str(i)}",
+ }
+ for i, doc in enumerate(kwargs["source_documents"])
+ ]
+ )
+ kwargs.pop("source_documents", None)
+ maybe_connectors = connectors if documents is None else None
+
+ # by enabling automatic prompt truncation, the probability of request failure is
+ # reduced with minimal impact on response quality
+ prompt_truncation = (
+ "AUTO" if documents is not None or connectors is not None else None
+ )
+
+ req = {
+ "message": messages[-1].content,
+ "chat_history": [
+ {"role": get_role(x), "message": x.content} for x in messages[:-1]
+ ],
+ "documents": documents,
+ "connectors": maybe_connectors,
+ "prompt_truncation": prompt_truncation,
+ **kwargs,
+ }
+
+ return {k: v for k, v in req.items() if v is not None}
+
+
+@deprecated(
+ since="0.0.30", removal="1.0", alternative_import="langchain_cohere.ChatCohere"
+)
+class ChatCohere(BaseChatModel, BaseCohere):
+ """`Cohere` chat large language models.
+
+ To use, you should have the ``cohere`` python package installed, and the
+ environment variable ``COHERE_API_KEY`` set with your API key, or pass
+ it as a named parameter to the constructor.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatCohere
+ from langchain_core.messages import HumanMessage
+
+ chat = ChatCohere(max_tokens=256, temperature=0.75)
+
+ messages = [HumanMessage(content="knock knock")]
+ chat.invoke(messages)
+ """
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ arbitrary_types_allowed=True,
+ )
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "cohere-chat"
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling Cohere API."""
+ return {
+ "temperature": self.temperature,
+ }
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ return {**{"model": self.model}, **self._default_params}
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ request = get_cohere_chat_request(messages, **self._default_params, **kwargs)
+
+ if hasattr(self.client, "chat_stream"): # detect and support sdk v5
+ stream = self.client.chat_stream(**request)
+ else:
+ stream = self.client.chat(**request, stream=True)
+
+ for data in stream:
+ if data.event_type == "text-generation":
+ delta = data.text
+ chunk = ChatGenerationChunk(message=AIMessageChunk(content=delta))
+ if run_manager:
+ run_manager.on_llm_new_token(delta, chunk=chunk)
+ yield chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ request = get_cohere_chat_request(messages, **self._default_params, **kwargs)
+
+ if hasattr(self.async_client, "chat_stream"): # detect and support sdk v5
+ stream = await self.async_client.chat_stream(**request)
+ else:
+ stream = await self.async_client.chat(**request, stream=True)
+
+ async for data in stream:
+ if data.event_type == "text-generation":
+ delta = data.text
+ chunk = ChatGenerationChunk(message=AIMessageChunk(content=delta))
+ if run_manager:
+ await run_manager.on_llm_new_token(delta, chunk=chunk)
+ yield chunk
+
+ def _get_generation_info(self, response: Any) -> Dict[str, Any]:
+ """Get the generation info from cohere API response."""
+ return {
+ "documents": response.documents,
+ "citations": response.citations,
+ "search_results": response.search_results,
+ "search_queries": response.search_queries,
+ "token_count": response.token_count,
+ }
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ request = get_cohere_chat_request(messages, **self._default_params, **kwargs)
+ response = self.client.chat(**request)
+
+ message = AIMessage(content=response.text)
+ generation_info = None
+ if hasattr(response, "documents"):
+ generation_info = self._get_generation_info(response)
+ return ChatResult(
+ generations=[
+ ChatGeneration(message=message, generation_info=generation_info)
+ ]
+ )
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ request = get_cohere_chat_request(messages, **self._default_params, **kwargs)
+ response = self.client.chat(**request)
+
+ message = AIMessage(content=response.text)
+ generation_info = None
+ if hasattr(response, "documents"):
+ generation_info = self._get_generation_info(response)
+ return ChatResult(
+ generations=[
+ ChatGeneration(message=message, generation_info=generation_info)
+ ]
+ )
+
+ def get_num_tokens(self, text: str) -> int:
+ """Calculate number of tokens."""
+ return len(self.client.tokenize(text=text).tokens)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/coze.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/coze.py
new file mode 100644
index 0000000000000000000000000000000000000000..acf714619bf77d688c57fbc3fffd215d9542c432
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/coze.py
@@ -0,0 +1,255 @@
+import json
+import logging
+from typing import Any, Dict, Iterator, List, Mapping, Optional, Union
+
+import requests
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.utils import (
+ convert_to_secret_str,
+ get_from_dict_or_env,
+)
+from pydantic import ConfigDict, Field, SecretStr, model_validator
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_API_BASE = "https://api.coze.com"
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ message_dict: Dict[str, Any]
+ if isinstance(message, HumanMessage):
+ message_dict = {
+ "role": "user",
+ "content": message.content,
+ "content_type": "text",
+ }
+ else:
+ message_dict = {
+ "role": "assistant",
+ "content": message.content,
+ "content_type": "text",
+ }
+ return message_dict
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> Union[BaseMessage, None]:
+ msg_type = _dict["type"]
+ if msg_type != "answer":
+ return None
+ role = _dict["role"]
+ if role == "user":
+ return HumanMessage(content=_dict["content"])
+ elif role == "assistant":
+ return AIMessage(content=_dict.get("content", "") or "")
+ else:
+ return ChatMessage(content=_dict["content"], role=role)
+
+
+def _convert_delta_to_message_chunk(_dict: Mapping[str, Any]) -> BaseMessageChunk:
+ role = _dict.get("role")
+ content = _dict.get("content") or ""
+
+ if role == "user":
+ return HumanMessageChunk(content=content)
+ elif role == "assistant":
+ return AIMessageChunk(content=content)
+ else:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+
+
+class ChatCoze(BaseChatModel):
+ """ChatCoze chat models API by coze.com
+
+ For more information, see https://www.coze.com/open/docs/chat
+ """
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {
+ "coze_api_key": "COZE_API_KEY",
+ }
+
+ @property
+ def lc_serializable(self) -> bool:
+ return True
+
+ coze_api_base: str = Field(default=DEFAULT_API_BASE)
+ """Coze custom endpoints"""
+ coze_api_key: Optional[SecretStr] = None
+ """Coze API Key"""
+ request_timeout: int = Field(default=60, alias="timeout")
+ """request timeout for chat http requests"""
+ bot_id: str = Field(default="")
+ """The ID of the bot that the API interacts with."""
+ conversation_id: str = Field(default="")
+ """Indicate which conversation the dialog is taking place in. If there is no need to
+ distinguish the context of the conversation(just a question and answer), skip this
+ parameter. It will be generated by the system."""
+ user: str = Field(default="")
+ """The user who calls the API to chat with the bot."""
+ streaming: bool = False
+ """Whether to stream the response to the client.
+ false: if no value is specified or set to false, a non-streaming response is
+ returned. "Non-streaming response" means that all responses will be returned at once
+ after they are all ready, and the client does not need to concatenate the content.
+ true: set to true, partial message deltas will be sent .
+ "Streaming response" will provide real-time response of the model to the client, and
+ the client needs to assemble the final reply based on the type of message. """
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ values["coze_api_base"] = get_from_dict_or_env(
+ values,
+ "coze_api_base",
+ "COZE_API_BASE",
+ DEFAULT_API_BASE,
+ )
+ values["coze_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ "coze_api_key",
+ "COZE_API_KEY",
+ )
+ )
+
+ return values
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling Coze API."""
+ return {
+ "bot_id": self.bot_id,
+ "conversation_id": self.conversation_id,
+ "user": self.user,
+ "streaming": self.streaming,
+ }
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages=messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ r = self._chat(messages, **kwargs)
+ res = r.json()
+ if res["code"] != 0:
+ raise ValueError(
+ f"Error from Coze api response: {res['code']}: {res['msg']}, "
+ f"logid: {r.headers.get('X-Tt-Logid')}"
+ )
+
+ return self._create_chat_result(res.get("messages") or [])
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ res = self._chat(messages, **kwargs)
+ for chunk in res.iter_lines():
+ chunk = chunk.decode("utf-8").strip("\r\n")
+ parts = chunk.split("data:", 1)
+ chunk = parts[1] if len(parts) > 1 else None
+ if chunk is None:
+ continue
+ response = json.loads(chunk)
+ if response["event"] == "done":
+ break
+ elif (
+ response["event"] != "message"
+ or response["message"]["type"] != "answer"
+ ):
+ continue
+ chunk = _convert_delta_to_message_chunk(response["message"])
+ cg_chunk = ChatGenerationChunk(message=chunk)
+ if run_manager:
+ run_manager.on_llm_new_token(str(chunk.content), chunk=cg_chunk)
+ yield cg_chunk
+
+ def _chat(self, messages: List[BaseMessage], **kwargs: Any) -> requests.Response:
+ parameters = {**self._default_params, **kwargs}
+
+ query = ""
+ chat_history = []
+ for msg in messages:
+ if isinstance(msg, HumanMessage):
+ query = f"{msg.content}" # overwrite, to get last user message as query
+ chat_history.append(_convert_message_to_dict(msg))
+
+ conversation_id = parameters.pop("conversation_id")
+ bot_id = parameters.pop("bot_id")
+ user = parameters.pop("user")
+ streaming = parameters.pop("streaming")
+
+ payload = {
+ "conversation_id": conversation_id,
+ "bot_id": bot_id,
+ "user": user,
+ "query": query,
+ "stream": streaming,
+ }
+ if chat_history:
+ payload["chat_history"] = chat_history
+
+ url = self.coze_api_base + "/open_api/v2/chat"
+ api_key = ""
+ if self.coze_api_key:
+ api_key = self.coze_api_key.get_secret_value()
+
+ res = requests.post(
+ url=url,
+ timeout=self.request_timeout,
+ headers={
+ "Content-Type": "application/json",
+ "Authorization": f"Bearer {api_key}",
+ },
+ json=payload,
+ stream=streaming,
+ )
+ if res.status_code != 200:
+ logid = res.headers.get("X-Tt-Logid")
+ raise ValueError(f"Error from Coze api response: {res}, logid: {logid}")
+ return res
+
+ def _create_chat_result(self, messages: List[Mapping[str, Any]]) -> ChatResult:
+ generations = []
+ for c in messages:
+ msg = _convert_dict_to_message(c)
+ if msg:
+ generations.append(ChatGeneration(message=msg))
+
+ llm_output = {"token_usage": "", "model": ""}
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ @property
+ def _llm_type(self) -> str:
+ return "coze-chat"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/dappier.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/dappier.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc32b5a95bcffc5bed7c3023ff0594f4a5b2ef2a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/dappier.py
@@ -0,0 +1,161 @@
+from typing import Any, Dict, List, Optional, Union
+
+from aiohttp import ClientSession
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+)
+from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatResult
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
+from pydantic import ConfigDict, Field, SecretStr, model_validator
+
+from langchain_community.utilities.requests import Requests
+
+
+def _format_dappier_messages(
+ messages: List[BaseMessage],
+) -> List[Dict[str, Union[str, List[Union[str, Dict[Any, Any]]]]]]:
+ formatted_messages = []
+
+ for message in messages:
+ if message.type == "human":
+ formatted_messages.append({"role": "user", "content": message.content})
+ elif message.type == "system":
+ formatted_messages.append({"role": "system", "content": message.content})
+
+ return formatted_messages
+
+
+class ChatDappierAI(BaseChatModel):
+ """`Dappier` chat large language models.
+
+ `Dappier` is a platform enabling access to diverse, real-time data models.
+ Enhance your AI applications with Dappier's pre-trained, LLM-ready data models
+ and ensure accurate, current responses with reduced inaccuracies.
+
+ To use one of our Dappier AI Data Models, you will need an API key.
+ Please visit Dappier Platform (https://platform.dappier.com/) to log in
+ and create an API key in your profile.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatDappierAI
+ from langchain_core.messages import HumanMessage
+
+ # Initialize `ChatDappierAI` with the desired configuration
+ chat = ChatDappierAI(
+ dappier_endpoint="https://api.dappier.com/app/datamodel/dm_01hpsxyfm2fwdt2zet9cg6fdxt",
+ dappier_api_key="")
+
+ # Create a list of messages to interact with the model
+ messages = [HumanMessage(content="hello")]
+
+ # Invoke the model with the provided messages
+ chat.invoke(messages)
+
+
+ you can find more details here : https://docs.dappier.com/introduction"""
+
+ dappier_endpoint: str = "https://api.dappier.com/app/datamodelconversation"
+
+ dappier_model: str = "dm_01hpsxyfm2fwdt2zet9cg6fdxt"
+
+ dappier_api_key: Optional[SecretStr] = Field(None, description="Dappier API Token")
+
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key exists in environment."""
+ values["dappier_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(values, "dappier_api_key", "DAPPIER_API_KEY")
+ )
+ return values
+
+ @staticmethod
+ def get_user_agent() -> str:
+ from langchain_community import __version__
+
+ return f"langchain/{__version__}"
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "dappier-realtimesearch-chat"
+
+ @property
+ def _api_key(self) -> str:
+ if self.dappier_api_key:
+ return self.dappier_api_key.get_secret_value()
+ return ""
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ url = f"{self.dappier_endpoint}"
+ headers = {
+ "Authorization": f"Bearer {self._api_key}",
+ "User-Agent": self.get_user_agent(),
+ }
+ user_query = _format_dappier_messages(messages=messages)
+ payload: Dict[str, Any] = {
+ "model": self.dappier_model,
+ "conversation": user_query,
+ }
+
+ request = Requests(headers=headers)
+ response = request.post(url=url, data=payload)
+ response.raise_for_status()
+
+ data = response.json()
+
+ message_response = data["message"]
+
+ return ChatResult(
+ generations=[ChatGeneration(message=AIMessage(content=message_response))]
+ )
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ url = f"{self.dappier_endpoint}"
+ headers = {
+ "Authorization": f"Bearer {self._api_key}",
+ "User-Agent": self.get_user_agent(),
+ }
+ user_query = _format_dappier_messages(messages=messages)
+ payload: Dict[str, Any] = {
+ "model": self.dappier_model,
+ "conversation": user_query,
+ }
+
+ async with ClientSession() as session:
+ async with session.post(url, json=payload, headers=headers) as response:
+ response.raise_for_status()
+ data = await response.json()
+ message_response = data["message"]
+
+ return ChatResult(
+ generations=[
+ ChatGeneration(message=AIMessage(content=message_response))
+ ]
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/databricks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/databricks.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd459e4f29e7f2d4495f8396256e798d3252d8cf
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/databricks.py
@@ -0,0 +1,60 @@
+import logging
+from urllib.parse import urlparse
+
+from langchain_core._api import deprecated
+
+from langchain_community.chat_models.mlflow import ChatMlflow
+
+logger = logging.getLogger(__name__)
+
+
+@deprecated(
+ since="0.3.3",
+ removal="1.0",
+ alternative_import="databricks_langchain.ChatDatabricks",
+)
+class ChatDatabricks(ChatMlflow):
+ """`Databricks` chat models API.
+
+ To use, you should have the ``mlflow`` python package installed.
+ For more information, see https://mlflow.org/docs/latest/llms/deployments.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatDatabricks
+
+ chat_model = ChatDatabricks(
+ target_uri="databricks",
+ endpoint="databricks-llama-2-70b-chat",
+ temperature=0.1,
+ )
+
+ # single input invocation
+ print(chat_model.invoke("What is MLflow?").content)
+
+ # single input invocation with streaming response
+ for chunk in chat_model.stream("What is MLflow?"):
+ print(chunk.content, end="|")
+ """
+
+ target_uri: str = "databricks"
+ """The target URI to use. Defaults to ``databricks``."""
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "databricks-chat"
+
+ @property
+ def _mlflow_extras(self) -> str:
+ return ""
+
+ def _validate_uri(self) -> None:
+ if self.target_uri == "databricks":
+ return
+
+ if urlparse(self.target_uri).scheme != "databricks":
+ raise ValueError(
+ "Invalid target URI. The target URI must be a valid databricks URI."
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/deepinfra.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/deepinfra.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0f9cf733dab2b59df16caa1d9aa729bedb926a4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/deepinfra.py
@@ -0,0 +1,546 @@
+"""deepinfra.com chat models wrapper"""
+
+from __future__ import annotations
+
+import json
+import logging
+from json import JSONDecodeError
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ Union,
+)
+
+import aiohttp
+import requests
+from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.language_models.llms import create_base_retry_decorator
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessage,
+ FunctionMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+ ToolMessage,
+)
+from langchain_core.messages.tool import ToolCall
+from langchain_core.messages.tool import tool_call as create_tool_call
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ ChatResult,
+)
+from langchain_core.runnables import Runnable
+from langchain_core.tools import BaseTool
+from langchain_core.utils import get_from_dict_or_env
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+from typing_extensions import Self
+
+from langchain_community.utilities.requests import Requests
+
+logger = logging.getLogger(__name__)
+
+
+class ChatDeepInfraException(Exception):
+ """Exception raised when the DeepInfra API returns an error."""
+
+ pass
+
+
+def _create_retry_decorator(
+ llm: ChatDeepInfra,
+ run_manager: Optional[
+ Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]
+ ] = None,
+) -> Callable[[Any], Any]:
+ """Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions."""
+ return create_base_retry_decorator(
+ error_types=[requests.exceptions.ConnectTimeout, ChatDeepInfraException],
+ max_retries=llm.max_retries,
+ run_manager=run_manager,
+ )
+
+
+def _parse_tool_calling(tool_call: dict) -> ToolCall:
+ """
+ Convert a tool calling response from server to a ToolCall object.
+ Args:
+ tool_call:
+
+ Returns:
+
+ """
+ name = tool_call["function"].get("name", "")
+ try:
+ args = json.loads(tool_call["function"]["arguments"])
+ except (JSONDecodeError, TypeError):
+ args = {}
+ id = tool_call.get("id")
+ return create_tool_call(name=name, args=args, id=id)
+
+
+def _convert_to_tool_calling(tool_call: ToolCall) -> Dict[str, Any]:
+ """
+ Convert a ToolCall object to a tool calling request for server.
+ Args:
+ tool_call:
+
+ Returns:
+
+ """
+ return {
+ "type": "function",
+ "function": {
+ "arguments": json.dumps(tool_call["args"]),
+ "name": tool_call["name"],
+ },
+ "id": tool_call.get("id"),
+ }
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ role = _dict["role"]
+ if role == "user":
+ return HumanMessage(content=_dict["content"])
+ elif role == "assistant":
+ content = _dict.get("content", "") or ""
+ tool_calls_content = _dict.get("tool_calls", []) or []
+ tool_calls = [
+ _parse_tool_calling(tool_call) for tool_call in tool_calls_content
+ ]
+ return AIMessage(content=content, tool_calls=tool_calls)
+ elif role == "system":
+ return SystemMessage(content=_dict["content"])
+ elif role == "function":
+ return FunctionMessage(content=_dict["content"], name=_dict["name"])
+ else:
+ return ChatMessage(content=_dict["content"], role=role)
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role = _dict.get("role")
+ content = _dict.get("content") or ""
+ tool_calls = _dict.get("tool_calls") or []
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ tool_calls = [_parse_tool_calling(tool_call) for tool_call in tool_calls]
+ return AIMessageChunk(content=content, tool_calls=tool_calls)
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ elif role == "function" or default_class == FunctionMessageChunk:
+ return FunctionMessageChunk(content=content, name=_dict["name"])
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ tool_calls = [
+ _convert_to_tool_calling(tool_call) for tool_call in message.tool_calls
+ ]
+ message_dict = {
+ "role": "assistant",
+ "content": message.content,
+ "tool_calls": tool_calls, # type: ignore[dict-item]
+ }
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, FunctionMessage):
+ message_dict = {
+ "role": "function",
+ "content": message.content,
+ "name": message.name,
+ }
+ elif isinstance(message, ToolMessage):
+ message_dict = {
+ "role": "tool",
+ "content": message.content,
+ "name": message.name, # type: ignore[dict-item]
+ "tool_call_id": message.tool_call_id,
+ }
+ else:
+ raise ValueError(f"Got unknown type {message}")
+ if "name" in message.additional_kwargs:
+ message_dict["name"] = message.additional_kwargs["name"]
+ return message_dict
+
+
+class ChatDeepInfra(BaseChatModel):
+ """A chat model that uses the DeepInfra API."""
+
+ # client: Any #: :meta private:
+ model_name: str = Field(default="meta-llama/Llama-2-70b-chat-hf", alias="model")
+ """Model name to use."""
+
+ url: str = "https://api.deepinfra.com/v1/openai/chat/completions"
+ """URL to use for the API call."""
+
+ deepinfra_api_token: Optional[str] = None
+ request_timeout: Optional[float] = Field(default=None, alias="timeout")
+ temperature: Optional[float] = 1
+ """Run inference with this temperature. Must be in the closed
+ interval [0.0, 1.0]."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for API call not explicitly specified."""
+ top_p: Optional[float] = None
+ """Decode using nucleus sampling: consider the smallest set of tokens whose
+ probability sum is at least top_p. Must be in the closed interval [0.0, 1.0]."""
+ top_k: Optional[int] = None
+ """Decode using top-k sampling: consider the set of top_k most probable tokens.
+ Must be positive."""
+ n: int = 1
+ """Number of chat completions to generate for each prompt. Note that the API may
+ not return the full n completions if duplicates are generated."""
+ max_tokens: int = 256
+ streaming: bool = False
+ max_retries: int = 1
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling OpenAI API."""
+ return {
+ "model": self.model_name,
+ "max_tokens": self.max_tokens,
+ "stream": self.streaming,
+ "n": self.n,
+ "temperature": self.temperature,
+ "request_timeout": self.request_timeout,
+ **self.model_kwargs,
+ }
+
+ @property
+ def _client_params(self) -> Dict[str, Any]:
+ """Get the parameters used for the openai client."""
+ return {**self._default_params}
+
+ def completion_with_retry(
+ self, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any
+ ) -> Any:
+ """Use tenacity to retry the completion call."""
+ retry_decorator = _create_retry_decorator(self, run_manager=run_manager)
+
+ @retry_decorator
+ def _completion_with_retry(**kwargs: Any) -> Any:
+ try:
+ request_timeout = kwargs.pop("request_timeout")
+ request = Requests(headers=self._headers())
+ response = request.post(
+ url=self._url(), data=self._body(kwargs), timeout=request_timeout
+ )
+ self._handle_status(response.status_code, response.text)
+ return response
+ except Exception as e:
+ print("EX", e) # noqa: T201
+ raise
+
+ return _completion_with_retry(**kwargs)
+
+ async def acompletion_with_retry(
+ self,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Use tenacity to retry the async completion call."""
+ retry_decorator = _create_retry_decorator(self, run_manager=run_manager)
+
+ @retry_decorator
+ async def _completion_with_retry(**kwargs: Any) -> Any:
+ try:
+ request_timeout = kwargs.pop("request_timeout")
+ request = Requests(headers=self._headers())
+ async with request.apost(
+ url=self._url(), data=self._body(kwargs), timeout=request_timeout
+ ) as response:
+ self._handle_status(response.status, await response.text())
+ return await response.json()
+ except Exception as e:
+ print("EX", e) # noqa: T201
+ raise
+
+ return await _completion_with_retry(**kwargs)
+
+ @model_validator(mode="before")
+ @classmethod
+ def init_defaults(cls, values: Dict) -> Any:
+ """Validate api key, python package exists, temperature, top_p, and top_k."""
+ # For compatibility with LiteLLM
+ api_key = get_from_dict_or_env(
+ values,
+ "deepinfra_api_key",
+ "DEEPINFRA_API_KEY",
+ default="",
+ )
+ values["deepinfra_api_token"] = get_from_dict_or_env(
+ values,
+ "deepinfra_api_token",
+ "DEEPINFRA_API_TOKEN",
+ default=api_key,
+ )
+ return values
+
+ @model_validator(mode="after")
+ def validate_environment(self) -> Self:
+ if self.temperature is not None and not 0 <= self.temperature <= 1:
+ raise ValueError("temperature must be in the range [0.0, 1.0]")
+
+ if self.top_p is not None and not 0 <= self.top_p <= 1:
+ raise ValueError("top_p must be in the range [0.0, 1.0]")
+
+ if self.top_k is not None and self.top_k <= 0:
+ raise ValueError("top_k must be positive")
+
+ return self
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+ response = self.completion_with_retry(
+ messages=message_dicts, run_manager=run_manager, **params
+ )
+ return self._create_chat_result(response.json())
+
+ def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:
+ generations = []
+ for res in response["choices"]:
+ message = _convert_dict_to_message(res["message"])
+ gen = ChatGeneration(
+ message=message,
+ generation_info=dict(finish_reason=res.get("finish_reason")),
+ )
+ generations.append(gen)
+ token_usage = response.get("usage", {})
+ llm_output = {"token_usage": token_usage, "model": self.model_name}
+ res = ChatResult(generations=generations, llm_output=llm_output)
+ return res
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage], stop: Optional[List[str]]
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
+ params = self._client_params
+ if stop is not None:
+ if "stop" in params:
+ raise ValueError("`stop` found in both the input and default params.")
+ params["stop"] = stop
+ message_dicts = [_convert_message_to_dict(m) for m in messages]
+ return message_dicts, params
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ response = self.completion_with_retry(
+ messages=message_dicts, run_manager=run_manager, **params
+ )
+ for line in _parse_stream(response.iter_lines()):
+ chunk = _handle_sse_line(line)
+ if chunk:
+ cg_chunk = ChatGenerationChunk(message=chunk, generation_info=None)
+ if run_manager:
+ run_manager.on_llm_new_token(str(chunk.content), chunk=cg_chunk)
+ yield cg_chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {"messages": message_dicts, "stream": True, **params, **kwargs}
+
+ request_timeout = params.pop("request_timeout")
+ request = Requests(headers=self._headers())
+ async with request.apost(
+ url=self._url(), data=self._body(params), timeout=request_timeout
+ ) as response:
+ async for line in _parse_stream_async(response.content):
+ chunk = _handle_sse_line(line)
+ if chunk:
+ cg_chunk = ChatGenerationChunk(message=chunk, generation_info=None)
+ if run_manager:
+ await run_manager.on_llm_new_token(
+ str(chunk.content), chunk=cg_chunk
+ )
+ yield cg_chunk
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {"messages": message_dicts, **params, **kwargs}
+
+ res = await self.acompletion_with_retry(run_manager=run_manager, **params)
+ return self._create_chat_result(res)
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ return {
+ "model": self.model_name,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "top_k": self.top_k,
+ "n": self.n,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ return "deepinfra-chat"
+
+ def _handle_status(self, code: int, text: Any) -> None:
+ if code >= 500:
+ raise ChatDeepInfraException(
+ f"DeepInfra Server error status {code}: {text}"
+ )
+ elif code >= 400:
+ raise ValueError(f"DeepInfra received an invalid payload: {text}")
+ elif code != 200:
+ raise Exception(
+ f"DeepInfra returned an unexpected response with status {code}: {text}"
+ )
+
+ def _url(self) -> str:
+ return self.url
+
+ def _headers(self) -> Dict:
+ return {
+ "Authorization": f"bearer {self.deepinfra_api_token}",
+ "Content-Type": "application/json",
+ }
+
+ def _body(self, kwargs: Any) -> Dict:
+ return kwargs
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model.
+
+ Assumes model is compatible with OpenAI tool-calling API.
+
+ Args:
+ tools: A list of tool definitions to bind to this chat model.
+ Can be a dictionary, pydantic model, callable, or BaseTool. Pydantic
+ models, callables, and BaseTools will be automatically converted to
+ their schema dictionary representation.
+ **kwargs: Any additional parameters to pass to the
+ :class:`~langchain.runnable.Runnable` constructor.
+ """
+
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ return super().bind(tools=formatted_tools, **kwargs)
+
+
+def _parse_stream(rbody: Iterator[bytes]) -> Iterator[str]:
+ for line in rbody:
+ _line = _parse_stream_helper(line)
+ if _line is not None:
+ yield _line
+
+
+async def _parse_stream_async(rbody: aiohttp.StreamReader) -> AsyncIterator[str]:
+ async for line in rbody:
+ _line = _parse_stream_helper(line)
+ if _line is not None:
+ yield _line
+
+
+def _parse_stream_helper(line: bytes) -> Optional[str]:
+ if line and line.startswith(b"data:"):
+ if line.startswith(b"data: "):
+ # SSE event may be valid when it contain whitespace
+ line = line[len(b"data: ") :]
+ else:
+ line = line[len(b"data:") :]
+ if line.strip() == b"[DONE]":
+ # return here will cause GeneratorExit exception in urllib3
+ # and it will close http connection with TCP Reset
+ return None
+ else:
+ return line.decode("utf-8")
+ return None
+
+
+def _handle_sse_line(line: str) -> Optional[BaseMessageChunk]:
+ try:
+ obj = json.loads(line)
+ default_chunk_class = AIMessageChunk
+ delta = obj.get("choices", [{}])[0].get("delta", {})
+ return _convert_delta_to_message_chunk(delta, default_chunk_class)
+ except Exception:
+ return None
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/edenai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/edenai.py
new file mode 100644
index 0000000000000000000000000000000000000000..960c2204614029df5bfa65bc9dfddaff9c6831ff
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/edenai.py
@@ -0,0 +1,627 @@
+import json
+import warnings
+from operator import itemgetter
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Literal,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ Union,
+ cast,
+)
+
+from aiohttp import ClientSession
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ HumanMessage,
+ InvalidToolCall,
+ SystemMessage,
+ ToolCall,
+ ToolMessage,
+)
+from langchain_core.messages.tool import invalid_tool_call as create_invalid_tool_call
+from langchain_core.messages.tool import tool_call as create_tool_call
+from langchain_core.messages.tool import tool_call_chunk as create_tool_call_chunk
+from langchain_core.output_parsers.base import OutputParserLike
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ PydanticToolsParser,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
+from langchain_core.tools import BaseTool
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from langchain_core.utils.pydantic import is_basemodel_subclass
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SecretStr,
+)
+
+from langchain_community.utilities.requests import Requests
+
+
+def _result_to_chunked_message(generated_result: ChatResult) -> ChatGenerationChunk:
+ message = generated_result.generations[0].message
+ if isinstance(message, AIMessage) and message.tool_calls is not None:
+ tool_call_chunks = [
+ create_tool_call_chunk(
+ name=tool_call["name"],
+ args=json.dumps(tool_call["args"]),
+ id=tool_call["id"],
+ index=idx,
+ )
+ for idx, tool_call in enumerate(message.tool_calls)
+ ]
+ message_chunk = AIMessageChunk(
+ content=message.content,
+ tool_call_chunks=tool_call_chunks,
+ )
+ return ChatGenerationChunk(message=message_chunk)
+ else:
+ return cast(ChatGenerationChunk, generated_result.generations[0])
+
+
+def _message_role(type: str) -> str:
+ role_mapping = {
+ "ai": "assistant",
+ "human": "user",
+ "chat": "user",
+ "AIMessageChunk": "assistant",
+ }
+
+ if type in role_mapping:
+ return role_mapping[type]
+ else:
+ raise ValueError(f"Unknown type: {type}")
+
+
+def _extract_edenai_tool_results_from_messages(
+ messages: List[BaseMessage],
+) -> Tuple[List[Dict[str, Any]], List[BaseMessage]]:
+ """
+ Get the last langchain tools messages to transform them into edenai tool_results
+ Returns tool_results and messages without the extracted tool messages
+ """
+ tool_results: List[Dict[str, Any]] = []
+ other_messages = messages[:]
+ for msg in reversed(messages):
+ if isinstance(msg, ToolMessage):
+ tool_results = [
+ {"id": msg.tool_call_id, "result": msg.content},
+ *tool_results,
+ ]
+ other_messages.pop()
+ else:
+ break
+ return tool_results, other_messages
+
+
+def _format_edenai_messages(messages: List[BaseMessage]) -> Dict[str, Any]:
+ system = None
+ formatted_messages = []
+
+ human_messages = list(filter(lambda msg: isinstance(msg, HumanMessage), messages))
+ last_human_message = human_messages[-1] if human_messages else ""
+
+ tool_results, other_messages = _extract_edenai_tool_results_from_messages(messages)
+ for i, message in enumerate(other_messages):
+ if isinstance(message, SystemMessage):
+ if i != 0:
+ raise ValueError("System message must be at beginning of message list.")
+ system = message.content
+ elif isinstance(message, ToolMessage):
+ formatted_messages.append({"role": "tool", "message": message.content})
+ elif message != last_human_message:
+ formatted_messages.append(
+ {
+ "role": _message_role(message.type),
+ "message": message.content,
+ "tool_calls": _format_tool_calls_to_edenai_tool_calls(message),
+ }
+ )
+
+ return {
+ "text": getattr(last_human_message, "content", ""),
+ "previous_history": formatted_messages,
+ "chatbot_global_action": system,
+ "tool_results": tool_results,
+ }
+
+
+def _format_tool_calls_to_edenai_tool_calls(message: BaseMessage) -> List:
+ tool_calls = getattr(message, "tool_calls", [])
+ invalid_tool_calls = getattr(message, "invalid_tool_calls", [])
+ edenai_tool_calls = []
+
+ for invalid_tool_call in invalid_tool_calls:
+ edenai_tool_calls.append(
+ {
+ "arguments": invalid_tool_call.get("args"),
+ "id": invalid_tool_call.get("id"),
+ "name": invalid_tool_call.get("name"),
+ }
+ )
+
+ for tool_call in tool_calls:
+ tool_args = tool_call.get("args", {})
+ try:
+ arguments = json.dumps(tool_args)
+ except TypeError:
+ arguments = str(tool_args)
+ edenai_tool_calls.append(
+ {
+ "arguments": arguments,
+ "id": tool_call["id"],
+ "name": tool_call["name"],
+ }
+ )
+ return edenai_tool_calls
+
+
+def _extract_tool_calls_from_edenai_response(
+ provider_response: Dict[str, Any],
+) -> Tuple[List[ToolCall], List[InvalidToolCall]]:
+ tool_calls = []
+ invalid_tool_calls = []
+
+ message = provider_response.get("message", {})[1]
+
+ if raw_tool_calls := message.get("tool_calls"):
+ for raw_tool_call in raw_tool_calls:
+ try:
+ tool_calls.append(
+ create_tool_call(
+ name=raw_tool_call["name"],
+ args=json.loads(raw_tool_call["arguments"]),
+ id=raw_tool_call["id"],
+ )
+ )
+ except json.JSONDecodeError as exc:
+ invalid_tool_calls.append(
+ create_invalid_tool_call(
+ name=raw_tool_call.get("name"),
+ args=raw_tool_call.get("arguments"),
+ id=raw_tool_call.get("id"),
+ error=f"Received JSONDecodeError {exc}",
+ )
+ )
+
+ return tool_calls, invalid_tool_calls
+
+
+class ChatEdenAI(BaseChatModel):
+ """`EdenAI` chat large language models.
+
+ `EdenAI` is a versatile platform that allows you to access various language models
+ from different providers such as Google, OpenAI, Cohere, Mistral and more.
+
+ To get started, make sure you have the environment variable ``EDENAI_API_KEY``
+ set with your API key, or pass it as a named parameter to the constructor.
+
+ Additionally, `EdenAI` provides the flexibility to choose from a variety of models,
+ including the ones like "gpt-4".
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatEdenAI
+ from langchain_core.messages import HumanMessage
+
+ # Initialize `ChatEdenAI` with the desired configuration
+ chat = ChatEdenAI(
+ provider="openai",
+ model="gpt-4",
+ max_tokens=256,
+ temperature=0.75)
+
+ # Create a list of messages to interact with the model
+ messages = [HumanMessage(content="hello")]
+
+ # Invoke the model with the provided messages
+ chat.invoke(messages)
+
+ `EdenAI` goes beyond mere model invocation. It empowers you with advanced features :
+
+ - **Multiple Providers**: access to a diverse range of llms offered by various
+ providers giving you the freedom to choose the best-suited model for your use case.
+
+ - **Fallback Mechanism**: Set a fallback mechanism to ensure seamless operations
+ even if the primary provider is unavailable, you can easily switches to an
+ alternative provider.
+
+ - **Usage Statistics**: Track usage statistics on a per-project
+ and per-API key basis.
+ This feature allows you to monitor and manage resource consumption effectively.
+
+ - **Monitoring and Observability**: `EdenAI` provides comprehensive monitoring
+ and observability tools on the platform.
+
+ Example of setting up a fallback mechanism:
+ .. code-block:: python
+
+ # Initialize `ChatEdenAI` with a fallback provider
+ chat_with_fallback = ChatEdenAI(
+ provider="openai",
+ model="gpt-4",
+ max_tokens=256,
+ temperature=0.75,
+ fallback_provider="google")
+
+ you can find more details here : https://docs.edenai.co/reference/text_chat_create
+ """
+
+ provider: str = "openai"
+ """chat provider to use (eg: openai,google etc.)"""
+
+ model: Optional[str] = None
+ """
+ model name for above provider (eg: 'gpt-4' for openai)
+ available models are shown on https://docs.edenai.co/ under 'available providers'
+ """
+
+ max_tokens: int = 256
+ """Denotes the number of tokens to predict per generation."""
+
+ temperature: Optional[float] = 0
+ """A non-negative float that tunes the degree of randomness in generation."""
+
+ streaming: bool = False
+ """Whether to stream the results."""
+
+ fallback_providers: Optional[str] = None
+ """Providers in this will be used as fallback if the call to provider fails."""
+
+ edenai_api_url: str = "https://api.edenai.run/v2"
+
+ edenai_api_key: Optional[SecretStr] = Field(None, description="EdenAI API Token")
+
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that api key exists in environment."""
+ values["edenai_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(values, "edenai_api_key", "EDENAI_API_KEY")
+ )
+ return values
+
+ @staticmethod
+ def get_user_agent() -> str:
+ from langchain_community import __version__
+
+ return f"langchain/{__version__}"
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "edenai-chat"
+
+ @property
+ def _api_key(self) -> str:
+ if self.edenai_api_key:
+ return self.edenai_api_key.get_secret_value()
+ return ""
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ """Call out to EdenAI's chat endpoint."""
+ if "available_tools" in kwargs:
+ yield self._stream_with_tools_as_generate(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return
+ url = f"{self.edenai_api_url}/text/chat/stream"
+ headers = {
+ "Authorization": f"Bearer {self._api_key}",
+ "User-Agent": self.get_user_agent(),
+ }
+ formatted_data = _format_edenai_messages(messages=messages)
+ payload: Dict[str, Any] = {
+ "providers": self.provider,
+ "max_tokens": self.max_tokens,
+ "temperature": self.temperature,
+ "fallback_providers": self.fallback_providers,
+ **formatted_data,
+ **kwargs,
+ }
+
+ payload = {k: v for k, v in payload.items() if v is not None}
+
+ if self.model is not None:
+ payload["settings"] = {self.provider: self.model}
+
+ request = Requests(headers=headers)
+ response = request.post(url=url, data=payload, stream=True)
+ response.raise_for_status()
+
+ for chunk_response in response.iter_lines():
+ chunk = json.loads(chunk_response.decode())
+ token = chunk["text"]
+ cg_chunk = ChatGenerationChunk(message=AIMessageChunk(content=token))
+ if run_manager:
+ run_manager.on_llm_new_token(token, chunk=cg_chunk)
+ yield cg_chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ if "available_tools" in kwargs:
+ yield await self._astream_with_tools_as_agenerate(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return
+ url = f"{self.edenai_api_url}/text/chat/stream"
+ headers = {
+ "Authorization": f"Bearer {self._api_key}",
+ "User-Agent": self.get_user_agent(),
+ }
+ formatted_data = _format_edenai_messages(messages=messages)
+ payload: Dict[str, Any] = {
+ "providers": self.provider,
+ "max_tokens": self.max_tokens,
+ "temperature": self.temperature,
+ "fallback_providers": self.fallback_providers,
+ **formatted_data,
+ **kwargs,
+ }
+
+ payload = {k: v for k, v in payload.items() if v is not None}
+
+ if self.model is not None:
+ payload["settings"] = {self.provider: self.model}
+
+ async with ClientSession() as session:
+ async with session.post(url, json=payload, headers=headers) as response:
+ response.raise_for_status()
+ async for chunk_response in response.content:
+ chunk = json.loads(chunk_response.decode())
+ token = chunk["text"]
+ cg_chunk = ChatGenerationChunk(
+ message=AIMessageChunk(content=token)
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(
+ token=chunk["text"], chunk=cg_chunk
+ )
+ yield cg_chunk
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ *,
+ tool_choice: Optional[
+ Union[dict, str, Literal["auto", "none", "required", "any"], bool]
+ ] = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ formatted_tools = [convert_to_openai_tool(tool)["function"] for tool in tools]
+ formatted_tool_choice = "required" if tool_choice == "any" else tool_choice
+ return super().bind(
+ available_tools=formatted_tools, tool_choice=formatted_tool_choice, **kwargs
+ )
+
+ def with_structured_output(
+ self,
+ schema: Union[Dict, Type[BaseModel]],
+ *,
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, Union[Dict, BaseModel]]:
+ if kwargs:
+ raise ValueError(f"Received unsupported arguments {kwargs}")
+ llm = self.bind_tools([schema], tool_choice="required")
+ if isinstance(schema, type) and is_basemodel_subclass(schema):
+ output_parser: OutputParserLike = PydanticToolsParser(
+ tools=[schema], first_tool_only=True
+ )
+ else:
+ key_name = convert_to_openai_tool(schema)["function"]["name"]
+ output_parser = JsonOutputKeyToolsParser(
+ key_name=key_name, first_tool_only=True
+ )
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ else:
+ return llm | output_parser
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Call out to EdenAI's chat endpoint."""
+ if self.streaming:
+ if "available_tools" in kwargs:
+ warnings.warn(
+ "stream: Tool use is not yet supported in streaming mode."
+ )
+ else:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ url = f"{self.edenai_api_url}/text/chat"
+ headers = {
+ "Authorization": f"Bearer {self._api_key}",
+ "User-Agent": self.get_user_agent(),
+ }
+ formatted_data = _format_edenai_messages(messages=messages)
+
+ payload: Dict[str, Any] = {
+ "providers": self.provider,
+ "max_tokens": self.max_tokens,
+ "temperature": self.temperature,
+ "fallback_providers": self.fallback_providers,
+ **formatted_data,
+ **kwargs,
+ }
+
+ payload = {k: v for k, v in payload.items() if v is not None}
+
+ if self.model is not None:
+ payload["settings"] = {self.provider: self.model}
+
+ request = Requests(headers=headers)
+ response = request.post(url=url, data=payload)
+
+ response.raise_for_status()
+ data = response.json()
+ provider_response = data[self.provider]
+
+ if self.fallback_providers:
+ fallback_response = data.get(self.fallback_providers)
+ if fallback_response:
+ provider_response = fallback_response
+
+ if provider_response.get("status") == "fail":
+ err_msg = provider_response.get("error", {}).get("message")
+ raise Exception(err_msg)
+
+ tool_calls, invalid_tool_calls = _extract_tool_calls_from_edenai_response(
+ provider_response
+ )
+
+ return ChatResult(
+ generations=[
+ ChatGeneration(
+ message=AIMessage(
+ content=provider_response["generated_text"] or "",
+ tool_calls=tool_calls,
+ invalid_tool_calls=invalid_tool_calls,
+ )
+ )
+ ],
+ llm_output=data,
+ )
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ if "available_tools" in kwargs:
+ warnings.warn(
+ "stream: Tool use is not yet supported in streaming mode."
+ )
+ else:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ url = f"{self.edenai_api_url}/text/chat"
+ headers = {
+ "Authorization": f"Bearer {self._api_key}",
+ "User-Agent": self.get_user_agent(),
+ }
+ formatted_data = _format_edenai_messages(messages=messages)
+ payload: Dict[str, Any] = {
+ "providers": self.provider,
+ "max_tokens": self.max_tokens,
+ "temperature": self.temperature,
+ "fallback_providers": self.fallback_providers,
+ **formatted_data,
+ **kwargs,
+ }
+
+ payload = {k: v for k, v in payload.items() if v is not None}
+
+ if self.model is not None:
+ payload["settings"] = {self.provider: self.model}
+
+ async with ClientSession() as session:
+ async with session.post(url, json=payload, headers=headers) as response:
+ response.raise_for_status()
+ data = await response.json()
+ provider_response = data[self.provider]
+
+ if self.fallback_providers:
+ fallback_response = data.get(self.fallback_providers)
+ if fallback_response:
+ provider_response = fallback_response
+
+ if provider_response.get("status") == "fail":
+ err_msg = provider_response.get("error", {}).get("message")
+ raise Exception(err_msg)
+
+ return ChatResult(
+ generations=[
+ ChatGeneration(
+ message=AIMessage(
+ content=provider_response["generated_text"]
+ )
+ )
+ ],
+ llm_output=data,
+ )
+
+ def _stream_with_tools_as_generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]],
+ run_manager: Optional[CallbackManagerForLLMRun],
+ **kwargs: Any,
+ ) -> ChatGenerationChunk:
+ warnings.warn("stream: Tool use is not yet supported in streaming mode.")
+ result = self._generate(messages, stop=stop, run_manager=run_manager, **kwargs)
+ return _result_to_chunked_message(result)
+
+ async def _astream_with_tools_as_agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]],
+ run_manager: Optional[AsyncCallbackManagerForLLMRun],
+ **kwargs: Any,
+ ) -> ChatGenerationChunk:
+ warnings.warn("stream: Tool use is not yet supported in streaming mode.")
+ result = await self._agenerate(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return _result_to_chunked_message(result)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/ernie.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/ernie.py
new file mode 100644
index 0000000000000000000000000000000000000000..41cf635cfaf9febd148b431d65c84fe01ce2640a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/ernie.py
@@ -0,0 +1,229 @@
+import logging
+import threading
+from typing import Any, Dict, List, Mapping, Optional
+
+import requests
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatResult
+from langchain_core.utils import get_from_dict_or_env
+from pydantic import model_validator
+
+logger = logging.getLogger(__name__)
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ else:
+ raise ValueError(f"Got unknown type {message}")
+ return message_dict
+
+
+@deprecated(
+ since="0.0.13",
+ alternative="langchain_community.chat_models.QianfanChatEndpoint",
+)
+class ErnieBotChat(BaseChatModel):
+ """`ERNIE-Bot` large language model.
+
+ ERNIE-Bot is a large language model developed by Baidu,
+ covering a huge amount of Chinese data.
+
+ To use, you should have the `ernie_client_id` and `ernie_client_secret` set,
+ or set the environment variable `ERNIE_CLIENT_ID` and `ERNIE_CLIENT_SECRET`.
+
+ Note:
+ access_token will be automatically generated based on client_id and client_secret,
+ and will be regenerated after expiration (30 days).
+
+ Default model is `ERNIE-Bot-turbo`,
+ currently supported models are `ERNIE-Bot-turbo`, `ERNIE-Bot`, `ERNIE-Bot-8K`,
+ `ERNIE-Bot-4`, `ERNIE-Bot-turbo-AI`.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ErnieBotChat
+ chat = ErnieBotChat(model_name='ERNIE-Bot')
+
+
+ Deprecated Note:
+ Please use `QianfanChatEndpoint` instead of this class.
+ `QianfanChatEndpoint` is a more suitable choice for production.
+
+ Always test your code after changing to `QianfanChatEndpoint`.
+
+ Example of `QianfanChatEndpoint`:
+ .. code-block:: python
+
+ from langchain_community.chat_models import QianfanChatEndpoint
+ qianfan_chat = QianfanChatEndpoint(model="ERNIE-Bot",
+ endpoint="your_endpoint", qianfan_ak="your_ak", qianfan_sk="your_sk")
+
+ """
+
+ ernie_api_base: Optional[str] = None
+ """Baidu application custom endpoints"""
+
+ ernie_client_id: Optional[str] = None
+ """Baidu application client id"""
+
+ ernie_client_secret: Optional[str] = None
+ """Baidu application client secret"""
+
+ access_token: Optional[str] = None
+ """access token is generated by client id and client secret,
+ setting this value directly will cause an error"""
+
+ model_name: str = "ERNIE-Bot-turbo"
+ """model name of ernie, default is `ERNIE-Bot-turbo`.
+ Currently supported `ERNIE-Bot-turbo`, `ERNIE-Bot`"""
+
+ system: Optional[str] = None
+ """system is mainly used for model character design,
+ for example, you are an AI assistant produced by xxx company.
+ The length of the system is limiting of 1024 characters."""
+
+ request_timeout: Optional[int] = 60
+ """request timeout for chat http requests"""
+
+ streaming: Optional[bool] = False
+ """streaming mode. not supported yet."""
+
+ top_p: Optional[float] = 0.8
+ temperature: Optional[float] = 0.95
+ penalty_score: Optional[float] = 1
+
+ _lock = threading.Lock()
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ values["ernie_api_base"] = get_from_dict_or_env(
+ values, "ernie_api_base", "ERNIE_API_BASE", "https://aip.baidubce.com"
+ )
+ values["ernie_client_id"] = get_from_dict_or_env(
+ values,
+ "ernie_client_id",
+ "ERNIE_CLIENT_ID",
+ )
+ values["ernie_client_secret"] = get_from_dict_or_env(
+ values,
+ "ernie_client_secret",
+ "ERNIE_CLIENT_SECRET",
+ )
+ return values
+
+ def _chat(self, payload: object) -> dict:
+ base_url = f"{self.ernie_api_base}/rpc/2.0/ai_custom/v1/wenxinworkshop/chat"
+ model_paths = {
+ "ERNIE-Bot-turbo": "eb-instant",
+ "ERNIE-Bot": "completions",
+ "ERNIE-Bot-8K": "ernie_bot_8k",
+ "ERNIE-Bot-4": "completions_pro",
+ "ERNIE-Bot-turbo-AI": "ai_apaas",
+ "BLOOMZ-7B": "bloomz_7b1",
+ "Llama-2-7b-chat": "llama_2_7b",
+ "Llama-2-13b-chat": "llama_2_13b",
+ "Llama-2-70b-chat": "llama_2_70b",
+ }
+ if self.model_name in model_paths:
+ url = f"{base_url}/{model_paths[self.model_name]}"
+ else:
+ raise ValueError(f"Got unknown model_name {self.model_name}")
+
+ resp = requests.post(
+ url,
+ timeout=self.request_timeout,
+ headers={
+ "Content-Type": "application/json",
+ },
+ params={"access_token": self.access_token},
+ json=payload,
+ )
+ return resp.json()
+
+ def _refresh_access_token_with_lock(self) -> None:
+ with self._lock:
+ logger.debug("Refreshing access token")
+ base_url: str = f"{self.ernie_api_base}/oauth/2.0/token"
+ resp = requests.post(
+ base_url,
+ timeout=10,
+ headers={
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ },
+ params={
+ "grant_type": "client_credentials",
+ "client_id": self.ernie_client_id,
+ "client_secret": self.ernie_client_secret,
+ },
+ )
+ self.access_token = str(resp.json().get("access_token"))
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ raise ValueError("`streaming` option currently unsupported.")
+
+ if not self.access_token:
+ self._refresh_access_token_with_lock()
+ payload = {
+ "messages": [_convert_message_to_dict(m) for m in messages],
+ "top_p": self.top_p,
+ "temperature": self.temperature,
+ "penalty_score": self.penalty_score,
+ "system": self.system,
+ **kwargs,
+ }
+ logger.debug(f"Payload for ernie api is {payload}")
+ resp = self._chat(payload)
+ if resp.get("error_code"):
+ if resp.get("error_code") == 111:
+ logger.debug("access_token expired, refresh it")
+ self._refresh_access_token_with_lock()
+ resp = self._chat(payload)
+ else:
+ raise ValueError(f"Error from ErnieChat api response: {resp}")
+ return self._create_chat_result(resp)
+
+ def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:
+ if "function_call" in response:
+ additional_kwargs = {
+ "function_call": dict(response.get("function_call", {}))
+ }
+ else:
+ additional_kwargs = {}
+ generations = [
+ ChatGeneration(
+ message=AIMessage(
+ content=response.get("result", ""),
+ additional_kwargs={**additional_kwargs},
+ )
+ )
+ ]
+ token_usage = response.get("usage", {})
+ llm_output = {"token_usage": token_usage, "model_name": self.model_name}
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ @property
+ def _llm_type(self) -> str:
+ return "ernie-bot-chat"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/everlyai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/everlyai.py
new file mode 100644
index 0000000000000000000000000000000000000000..b45b40a80e07e505577a4f31453019c14e1df646
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/everlyai.py
@@ -0,0 +1,185 @@
+"""EverlyAI Endpoints chat wrapper. Relies heavily on ChatOpenAI."""
+
+from __future__ import annotations
+
+import logging
+import sys
+import warnings
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ Optional,
+ Sequence,
+ Set,
+ Type,
+ Union,
+)
+
+from langchain_core.messages import BaseMessage
+from langchain_core.tools import BaseTool
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
+from pydantic import Field, model_validator
+
+from langchain_community.adapters.openai import convert_message_to_dict
+from langchain_community.chat_models.openai import (
+ ChatOpenAI,
+ _import_tiktoken,
+)
+
+if TYPE_CHECKING:
+ import tiktoken
+
+logger = logging.getLogger(__name__)
+
+
+DEFAULT_API_BASE = "https://everlyai.xyz/hosted"
+DEFAULT_MODEL = "meta-llama/Llama-2-7b-chat-hf"
+
+
+class ChatEverlyAI(ChatOpenAI):
+ """`EverlyAI` Chat large language models.
+
+ To use, you should have the ``openai`` python package installed, and the
+ environment variable ``EVERLYAI_API_KEY`` set with your API key.
+ Alternatively, you can use the everlyai_api_key keyword argument.
+
+ Any parameters that are valid to be passed to the `openai.create` call can be passed
+ in, even if not explicitly saved on this class.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatEverlyAI
+ chat = ChatEverlyAI(model_name="meta-llama/Llama-2-7b-chat-hf")
+ """
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "everlyai-chat"
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"everlyai_api_key": "EVERLYAI_API_KEY"}
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ return False
+
+ everlyai_api_key: Optional[str] = None
+ """EverlyAI Endpoints API keys."""
+ model_name: str = Field(default=DEFAULT_MODEL, alias="model")
+ """Model name to use."""
+ everlyai_api_base: str = DEFAULT_API_BASE
+ """Base URL path for API requests."""
+ available_models: Optional[Set[str]] = None
+ """Available models from EverlyAI API."""
+
+ @staticmethod
+ def get_available_models() -> Set[str]:
+ """Get available models from EverlyAI API."""
+ # EverlyAI doesn't yet support dynamically query for available models.
+ return set(
+ [
+ "meta-llama/Llama-2-7b-chat-hf",
+ "meta-llama/Llama-2-13b-chat-hf-quantized",
+ ]
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment_override(cls, values: dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+ values["openai_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ "everlyai_api_key",
+ "EVERLYAI_API_KEY",
+ )
+ )
+ values["openai_api_base"] = DEFAULT_API_BASE
+
+ try:
+ import openai
+
+ except ImportError as e:
+ raise ImportError(
+ "Could not import openai python package. "
+ "Please install it with `pip install openai`.",
+ ) from e
+ try:
+ values["client"] = openai.ChatCompletion
+ except AttributeError as exc:
+ raise ValueError(
+ "`openai` has no `ChatCompletion` attribute, this is likely "
+ "due to an old version of the openai package. Try upgrading it "
+ "with `pip install --upgrade openai`.",
+ ) from exc
+
+ if "model_name" not in values.keys():
+ values["model_name"] = DEFAULT_MODEL
+
+ model_name = values["model_name"]
+
+ available_models = cls.get_available_models()
+
+ if model_name not in available_models:
+ raise ValueError(
+ f"Model name {model_name} not found in available models: "
+ f"{available_models}.",
+ )
+
+ values["available_models"] = available_models
+
+ return values
+
+ def _get_encoding_model(self) -> tuple[str, tiktoken.Encoding]:
+ tiktoken_ = _import_tiktoken()
+ if self.tiktoken_model_name is not None:
+ model = self.tiktoken_model_name
+ else:
+ model = self.model_name
+ # Returns the number of tokens used by a list of messages.
+ try:
+ encoding = tiktoken_.encoding_for_model("gpt-3.5-turbo-0301")
+ except KeyError:
+ logger.warning("Warning: model not found. Using cl100k_base encoding.")
+ model = "cl100k_base"
+ encoding = tiktoken_.get_encoding(model)
+ return model, encoding
+
+ def get_num_tokens_from_messages(
+ self,
+ messages: list[BaseMessage],
+ tools: Optional[
+ Sequence[Union[Dict[str, Any], Type, Callable, BaseTool]]
+ ] = None,
+ ) -> int:
+ """Calculate num tokens with tiktoken package.
+
+ Official documentation: https://github.com/openai/openai-cookbook/blob/
+ main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb"""
+ if tools is not None:
+ warnings.warn(
+ "Counting tokens in tool schemas is not yet supported. Ignoring tools."
+ )
+ if sys.version_info[1] <= 7:
+ return super().get_num_tokens_from_messages(messages)
+ model, encoding = self._get_encoding_model()
+ tokens_per_message = 3
+ tokens_per_name = 1
+ num_tokens = 0
+ messages_dict = [convert_message_to_dict(m) for m in messages]
+ for message in messages_dict:
+ num_tokens += tokens_per_message
+ for key, value in message.items():
+ # Cast str(value) in case the message value is not a string
+ # This occurs with function messages
+ num_tokens += len(encoding.encode(str(value)))
+ if key == "name":
+ num_tokens += tokens_per_name
+ # every reply is primed with assistant
+ num_tokens += 3
+ return num_tokens
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/fake.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/fake.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc30b4611b034a07b2fc9ccc61cfb5339b8493b1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/fake.py
@@ -0,0 +1,105 @@
+"""Fake ChatModel for testing purposes."""
+
+import asyncio
+import time
+from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel, SimpleChatModel
+from langchain_core.messages import AIMessageChunk, BaseMessage
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+
+
+class FakeMessagesListChatModel(BaseChatModel):
+ """Fake ChatModel for testing purposes."""
+
+ responses: List[BaseMessage]
+ sleep: Optional[float] = None
+ i: int = 0
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ generation = ChatGeneration(message=response)
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return "fake-messages-list-chat-model"
+
+
+class FakeListChatModel(SimpleChatModel):
+ """Fake ChatModel for testing purposes."""
+
+ responses: List
+ sleep: Optional[float] = None
+ i: int = 0
+
+ @property
+ def _llm_type(self) -> str:
+ return "fake-list-chat-model"
+
+ def _call(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> str:
+ """First try to lookup in queries, else return 'foo' or 'bar'."""
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ return response
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Union[List[str], None] = None,
+ run_manager: Union[CallbackManagerForLLMRun, None] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ for c in response:
+ if self.sleep is not None:
+ time.sleep(self.sleep)
+ yield ChatGenerationChunk(message=AIMessageChunk(content=c))
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Union[List[str], None] = None,
+ run_manager: Union[AsyncCallbackManagerForLLMRun, None] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ for c in response:
+ if self.sleep is not None:
+ await asyncio.sleep(self.sleep)
+ yield ChatGenerationChunk(message=AIMessageChunk(content=c))
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ return {"responses": self.responses}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/fireworks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/fireworks.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0355f6e4ddbaf82b46c205d821ac6d5c47858bc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/fireworks.py
@@ -0,0 +1,372 @@
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Optional,
+ Type,
+ Union,
+)
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.language_models.llms import create_base_retry_decorator
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessage,
+ FunctionMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.utils import convert_to_secret_str
+from langchain_core.utils.env import get_from_dict_or_env
+from pydantic import Field, SecretStr, model_validator
+
+from langchain_community.adapters.openai import convert_message_to_dict
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Any, default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ """Convert a delta response to a message chunk."""
+ role = _dict.role
+ content = _dict.content or ""
+ additional_kwargs: Dict = {}
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ elif role == "function" or default_class == FunctionMessageChunk:
+ return FunctionMessageChunk(content=content, name=_dict.name)
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role)
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+def convert_dict_to_message(_dict: Any) -> BaseMessage:
+ """Convert a dict response to a message."""
+ role = _dict.role
+ content = _dict.content or ""
+ if role == "user":
+ return HumanMessage(content=content)
+ elif role == "assistant":
+ content = _dict.content
+ additional_kwargs: Dict = {}
+ return AIMessage(content=content, additional_kwargs=additional_kwargs)
+ elif role == "system":
+ return SystemMessage(content=content)
+ elif role == "function":
+ return FunctionMessage(content=content, name=_dict.name)
+ else:
+ return ChatMessage(content=content, role=role)
+
+
+@deprecated(
+ since="0.0.26",
+ removal="1.0",
+ alternative_import="langchain_fireworks.ChatFireworks",
+)
+class ChatFireworks(BaseChatModel):
+ """Fireworks Chat models."""
+
+ model: str = "accounts/fireworks/models/llama-v2-7b-chat"
+ model_kwargs: dict = Field(
+ default_factory=lambda: {
+ "temperature": 0.7,
+ "max_tokens": 512,
+ "top_p": 1,
+ }.copy()
+ )
+ fireworks_api_key: Optional[SecretStr] = None
+ max_retries: int = 20
+ use_retry: bool = True
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"fireworks_api_key": "FIREWORKS_API_KEY"}
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> List[str]:
+ """Get the namespace of the langchain object."""
+ return ["langchain", "chat_models", "fireworks"]
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key in environment."""
+ try:
+ import fireworks.client
+ except ImportError as e:
+ raise ImportError(
+ "Could not import fireworks-ai python package. "
+ "Please install it with `pip install fireworks-ai`."
+ ) from e
+ fireworks_api_key = convert_to_secret_str(
+ get_from_dict_or_env(values, "fireworks_api_key", "FIREWORKS_API_KEY")
+ )
+ fireworks.client.api_key = fireworks_api_key.get_secret_value()
+ return values
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "fireworks-chat"
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ message_dicts = self._create_message_dicts(messages)
+
+ params = {
+ "model": self.model,
+ "messages": message_dicts,
+ **self.model_kwargs,
+ **kwargs,
+ }
+ response = completion_with_retry(
+ self,
+ self.use_retry,
+ run_manager=run_manager,
+ stop=stop,
+ **params,
+ )
+ return self._create_chat_result(response)
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ message_dicts = self._create_message_dicts(messages)
+ params = {
+ "model": self.model,
+ "messages": message_dicts,
+ **self.model_kwargs,
+ **kwargs,
+ }
+ response = await acompletion_with_retry(
+ self, self.use_retry, run_manager=run_manager, stop=stop, **params
+ )
+ return self._create_chat_result(response)
+
+ def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:
+ if llm_outputs[0] is None:
+ return {}
+ return llm_outputs[0]
+
+ def _create_chat_result(self, response: Any) -> ChatResult:
+ generations = []
+ for res in response.choices:
+ message = convert_dict_to_message(res.message)
+ gen = ChatGeneration(
+ message=message,
+ generation_info=dict(finish_reason=res.finish_reason),
+ )
+ generations.append(gen)
+ llm_output = {"model": self.model}
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage]
+ ) -> List[Dict[str, Any]]:
+ message_dicts = [convert_message_to_dict(m) for m in messages]
+ return message_dicts
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ message_dicts = self._create_message_dicts(messages)
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ params = {
+ "model": self.model,
+ "messages": message_dicts,
+ "stream": True,
+ **self.model_kwargs,
+ **kwargs,
+ }
+ for chunk in completion_with_retry(
+ self, self.use_retry, run_manager=run_manager, stop=stop, **params
+ ):
+ choice = chunk.choices[0]
+ chunk = _convert_delta_to_message_chunk(choice.delta, default_chunk_class)
+ finish_reason = choice.finish_reason
+ generation_info = (
+ dict(finish_reason=finish_reason) if finish_reason is not None else None
+ )
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(cg_chunk.text, chunk=cg_chunk)
+ yield cg_chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ message_dicts = self._create_message_dicts(messages)
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ params = {
+ "model": self.model,
+ "messages": message_dicts,
+ "stream": True,
+ **self.model_kwargs,
+ **kwargs,
+ }
+ async for chunk in await acompletion_with_retry_streaming(
+ self, self.use_retry, run_manager=run_manager, stop=stop, **params
+ ):
+ choice = chunk.choices[0]
+ chunk = _convert_delta_to_message_chunk(choice.delta, default_chunk_class)
+ finish_reason = choice.finish_reason
+ generation_info = (
+ dict(finish_reason=finish_reason) if finish_reason is not None else None
+ )
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(token=cg_chunk.text, chunk=cg_chunk)
+ yield cg_chunk
+
+
+def conditional_decorator(
+ condition: bool, decorator: Callable[[Any], Any]
+) -> Callable[[Any], Any]:
+ """Define conditional decorator.
+
+ Args:
+ condition: The condition.
+ decorator: The decorator.
+
+ Returns:
+ The decorated function.
+ """
+
+ def actual_decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
+ if condition:
+ return decorator(func)
+ return func
+
+ return actual_decorator
+
+
+def completion_with_retry(
+ llm: ChatFireworks,
+ use_retry: bool,
+ *,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+) -> Any:
+ """Use tenacity to retry the completion call."""
+ import fireworks.client
+
+ retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
+
+ @conditional_decorator(use_retry, retry_decorator)
+ def _completion_with_retry(**kwargs: Any) -> Any:
+ """Use tenacity to retry the completion call."""
+ return fireworks.client.ChatCompletion.create(
+ **kwargs,
+ )
+
+ return _completion_with_retry(**kwargs)
+
+
+async def acompletion_with_retry(
+ llm: ChatFireworks,
+ use_retry: bool,
+ *,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+) -> Any:
+ """Use tenacity to retry the async completion call."""
+ import fireworks.client
+
+ retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
+
+ @conditional_decorator(use_retry, retry_decorator)
+ async def _completion_with_retry(**kwargs: Any) -> Any:
+ return await fireworks.client.ChatCompletion.acreate(
+ **kwargs,
+ )
+
+ return await _completion_with_retry(**kwargs)
+
+
+async def acompletion_with_retry_streaming(
+ llm: ChatFireworks,
+ use_retry: bool,
+ *,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+) -> Any:
+ """Use tenacity to retry the completion call for streaming."""
+ import fireworks.client
+
+ retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
+
+ @conditional_decorator(use_retry, retry_decorator)
+ async def _completion_with_retry(**kwargs: Any) -> Any:
+ return fireworks.client.ChatCompletion.acreate(
+ **kwargs,
+ )
+
+ return await _completion_with_retry(**kwargs)
+
+
+def _create_retry_decorator(
+ llm: ChatFireworks,
+ run_manager: Optional[
+ Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]
+ ] = None,
+) -> Callable[[Any], Any]:
+ """Define retry mechanism."""
+ import fireworks.client
+
+ errors = [
+ fireworks.client.error.RateLimitError,
+ fireworks.client.error.InternalServerError,
+ fireworks.client.error.BadGatewayError,
+ fireworks.client.error.ServiceUnavailableError,
+ ]
+ return create_base_retry_decorator(
+ error_types=errors, max_retries=llm.max_retries, run_manager=run_manager
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/friendli.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/friendli.py
new file mode 100644
index 0000000000000000000000000000000000000000..76bf70c9af189df2085232b18b813e1c490e15a2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/friendli.py
@@ -0,0 +1,217 @@
+from __future__ import annotations
+
+from typing import Any, AsyncIterator, Dict, Iterator, List, Optional
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+
+from langchain_community.llms.friendli import BaseFriendli
+
+
+def get_role(message: BaseMessage) -> str:
+ """Get role of the message.
+
+ Args:
+ message (BaseMessage): The message object.
+
+ Raises:
+ ValueError: Raised when the message is of an unknown type.
+
+ Returns:
+ str: The role of the message.
+ """
+ if isinstance(message, ChatMessage) or isinstance(message, HumanMessage):
+ return "user"
+ if isinstance(message, AIMessage):
+ return "assistant"
+ if isinstance(message, SystemMessage):
+ return "system"
+ raise ValueError(f"Got unknown type {message}")
+
+
+def get_chat_request(messages: List[BaseMessage]) -> Dict[str, Any]:
+ """Get a request of the Friendli chat API.
+
+ Args:
+ messages (List[BaseMessage]): Messages comprising the conversation so far.
+
+ Returns:
+ Dict[str, Any]: The request for the Friendli chat API.
+ """
+ return {
+ "messages": [
+ {"role": get_role(message), "content": message.content}
+ for message in messages
+ ]
+ }
+
+
+class ChatFriendli(BaseChatModel, BaseFriendli):
+ """Friendli LLM for chat.
+
+ ``friendli-client`` package should be installed with `pip install friendli-client`.
+ You must set ``FRIENDLI_TOKEN`` environment variable or provide the value of your
+ personal access token for the ``friendli_token`` argument.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import FriendliChat
+
+ chat = Friendli(
+ model="meta-llama-3.1-8b-instruct", friendli_token="YOUR FRIENDLI TOKEN"
+ )
+ chat.invoke("What is generative AI?")
+ """
+
+ model: str = "meta-llama-3.1-8b-instruct"
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"friendli_token": "FRIENDLI_TOKEN"}
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling Friendli completions API."""
+ return {
+ "frequency_penalty": self.frequency_penalty,
+ "presence_penalty": self.presence_penalty,
+ "max_tokens": self.max_tokens,
+ "stop": self.stop,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ }
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ return {"model": self.model, **self._default_params}
+
+ @property
+ def _llm_type(self) -> str:
+ return "friendli-chat"
+
+ def _get_invocation_params(
+ self, stop: Optional[List[str]] = None, **kwargs: Any
+ ) -> Dict[str, Any]:
+ """Get the parameters used to invoke the model."""
+ params = self._default_params
+ if self.stop is not None and stop is not None:
+ raise ValueError("`stop` found in both the input and default params.")
+ elif self.stop is not None:
+ params["stop"] = self.stop
+ else:
+ params["stop"] = stop
+ return {**params, **kwargs}
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ stream = self.client.chat.completions.create(
+ **get_chat_request(messages), stream=True, model=self.model, **params
+ )
+ for chunk in stream:
+ delta = chunk.choices[0].delta.content
+ if delta:
+ if run_manager:
+ run_manager.on_llm_new_token(delta)
+ yield ChatGenerationChunk(message=AIMessageChunk(content=delta))
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ stream = await self.async_client.chat.completions.create(
+ **get_chat_request(messages), stream=True, model=self.model, **params
+ )
+ async for chunk in stream:
+ delta = chunk.choices[0].delta.content
+ if delta:
+ if run_manager:
+ await run_manager.on_llm_new_token(delta)
+ yield ChatGenerationChunk(message=AIMessageChunk(content=delta))
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ response = self.client.chat.completions.create(
+ messages=[
+ {
+ "role": get_role(message),
+ "content": message.content,
+ }
+ for message in messages
+ ],
+ stream=False,
+ model=self.model,
+ **params,
+ )
+
+ message = AIMessage(content=response.choices[0].message.content)
+ return ChatResult(generations=[ChatGeneration(message=message)])
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ response = await self.async_client.chat.completions.create(
+ messages=[
+ {
+ "role": get_role(message),
+ "content": message.content,
+ }
+ for message in messages
+ ],
+ stream=False,
+ model=self.model,
+ **params,
+ )
+
+ message = AIMessage(content=response.choices[0].message.content)
+ return ChatResult(generations=[ChatGeneration(message=message)])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/gigachat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/gigachat.py
new file mode 100644
index 0000000000000000000000000000000000000000..beeed4940f9be9ceb287c964256e33c15a7a5198
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/gigachat.py
@@ -0,0 +1,280 @@
+from __future__ import annotations
+
+import logging
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ AsyncIterator,
+ Dict,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Type,
+)
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessage,
+ FunctionMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+
+from langchain_community.llms.gigachat import _BaseGigaChat
+
+if TYPE_CHECKING:
+ import gigachat.models as gm
+
+logger = logging.getLogger(__name__)
+
+
+def _convert_dict_to_message(message: gm.Messages) -> BaseMessage:
+ from gigachat.models import FunctionCall, MessagesRole
+
+ additional_kwargs: Dict = {}
+ if function_call := message.function_call:
+ if isinstance(function_call, FunctionCall):
+ additional_kwargs["function_call"] = dict(function_call)
+ elif isinstance(function_call, dict):
+ additional_kwargs["function_call"] = function_call
+
+ if message.role == MessagesRole.SYSTEM:
+ return SystemMessage(content=message.content)
+ elif message.role == MessagesRole.USER:
+ return HumanMessage(content=message.content)
+ elif message.role == MessagesRole.ASSISTANT:
+ return AIMessage(content=message.content, additional_kwargs=additional_kwargs)
+ else:
+ raise TypeError(f"Got unknown role {message.role} {message}")
+
+
+def _convert_message_to_dict(message: gm.BaseMessage) -> gm.Messages:
+ from gigachat.models import Messages, MessagesRole
+
+ if isinstance(message, SystemMessage):
+ return Messages(role=MessagesRole.SYSTEM, content=message.content)
+ elif isinstance(message, HumanMessage):
+ return Messages(role=MessagesRole.USER, content=message.content)
+ elif isinstance(message, AIMessage):
+ return Messages(
+ role=MessagesRole.ASSISTANT,
+ content=message.content,
+ function_call=message.additional_kwargs.get("function_call", None),
+ )
+ elif isinstance(message, ChatMessage):
+ return Messages(role=MessagesRole(message.role), content=message.content)
+ elif isinstance(message, FunctionMessage):
+ return Messages(role=MessagesRole.FUNCTION, content=message.content)
+ else:
+ raise TypeError(f"Got unknown type {message}")
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role = _dict.get("role")
+ content = _dict.get("content") or ""
+ additional_kwargs: Dict = {}
+ if _dict.get("function_call"):
+ function_call = dict(_dict["function_call"])
+ if "name" in function_call and function_call["name"] is None:
+ function_call["name"] = ""
+ additional_kwargs["function_call"] = function_call
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ elif role == "function" or default_class == FunctionMessageChunk:
+ return FunctionMessageChunk(content=content, name=_dict["name"])
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+@deprecated(
+ since="0.3.5",
+ removal="1.0",
+ alternative_import="langchain_gigachat.GigaChat",
+)
+class GigaChat(_BaseGigaChat, BaseChatModel):
+ """`GigaChat` large language models API.
+
+ To use, you should pass login and password to access GigaChat API or use token.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import GigaChat
+ giga = GigaChat(credentials=..., scope=..., verify_ssl_certs=...)
+ """
+
+ def _build_payload(self, messages: List[BaseMessage], **kwargs: Any) -> gm.Chat:
+ from gigachat.models import Chat
+
+ payload = Chat(
+ messages=[_convert_message_to_dict(m) for m in messages],
+ )
+
+ payload.functions = kwargs.get("functions", None)
+ payload.model = self.model
+
+ if self.profanity_check is not None:
+ payload.profanity_check = self.profanity_check
+ if self.temperature is not None:
+ payload.temperature = self.temperature
+ if self.top_p is not None:
+ payload.top_p = self.top_p
+ if self.max_tokens is not None:
+ payload.max_tokens = self.max_tokens
+ if self.repetition_penalty is not None:
+ payload.repetition_penalty = self.repetition_penalty
+ if self.update_interval is not None:
+ payload.update_interval = self.update_interval
+
+ if self.verbose:
+ logger.warning("Giga request: %s", payload.dict())
+
+ return payload
+
+ def _create_chat_result(self, response: Any) -> ChatResult:
+ generations = []
+ for res in response.choices:
+ message = _convert_dict_to_message(res.message)
+ finish_reason = res.finish_reason
+ gen = ChatGeneration(
+ message=message,
+ generation_info={"finish_reason": finish_reason},
+ )
+ generations.append(gen)
+ if finish_reason != "stop":
+ logger.warning(
+ "Giga generation stopped with reason: %s",
+ finish_reason,
+ )
+ if self.verbose:
+ logger.warning("Giga response: %s", message.content)
+ llm_output = {"token_usage": response.usage, "model_name": response.model}
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ payload = self._build_payload(messages, **kwargs)
+ response = self._client.chat(payload)
+
+ return self._create_chat_result(response)
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ payload = self._build_payload(messages, **kwargs)
+ response = await self._client.achat(payload)
+
+ return self._create_chat_result(response)
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ payload = self._build_payload(messages, **kwargs)
+
+ for chunk in self._client.stream(payload):
+ if not isinstance(chunk, dict):
+ chunk = chunk.dict()
+ if len(chunk["choices"]) == 0:
+ continue
+
+ choice = chunk["choices"][0]
+ content = choice.get("delta", {}).get("content", {})
+ chunk = _convert_delta_to_message_chunk(choice["delta"], AIMessageChunk)
+
+ finish_reason = choice.get("finish_reason")
+
+ generation_info = (
+ dict(finish_reason=finish_reason) if finish_reason is not None else None
+ )
+
+ if run_manager:
+ run_manager.on_llm_new_token(content)
+
+ yield ChatGenerationChunk(message=chunk, generation_info=generation_info)
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ payload = self._build_payload(messages, **kwargs)
+
+ async for chunk in self._client.astream(payload):
+ if not isinstance(chunk, dict):
+ chunk = chunk.dict()
+ if len(chunk["choices"]) == 0:
+ continue
+
+ choice = chunk["choices"][0]
+ content = choice.get("delta", {}).get("content", {})
+ chunk = _convert_delta_to_message_chunk(choice["delta"], AIMessageChunk)
+
+ finish_reason = choice.get("finish_reason")
+
+ generation_info = (
+ dict(finish_reason=finish_reason) if finish_reason is not None else None
+ )
+
+ if run_manager:
+ await run_manager.on_llm_new_token(content)
+
+ yield ChatGenerationChunk(message=chunk, generation_info=generation_info)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/google_palm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/google_palm.py
new file mode 100644
index 0000000000000000000000000000000000000000..2204c3ecc20259f99d4189ecc03968c6b0dc34f2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/google_palm.py
@@ -0,0 +1,355 @@
+"""Wrapper around Google's PaLM Chat API."""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, cast
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatResult,
+)
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
+from pydantic import BaseModel, SecretStr
+from tenacity import (
+ before_sleep_log,
+ retry,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential,
+)
+
+if TYPE_CHECKING:
+ import google.generativeai as genai
+
+logger = logging.getLogger(__name__)
+
+
+class ChatGooglePalmError(Exception):
+ """Error with the `Google PaLM` API."""
+
+
+def _truncate_at_stop_tokens(
+ text: str,
+ stop: Optional[List[str]],
+) -> str:
+ """Truncates text at the earliest stop token found."""
+ if stop is None:
+ return text
+
+ for stop_token in stop:
+ stop_token_idx = text.find(stop_token)
+ if stop_token_idx != -1:
+ text = text[:stop_token_idx]
+ return text
+
+
+def _response_to_result(
+ response: genai.types.ChatResponse,
+ stop: Optional[List[str]],
+) -> ChatResult:
+ """Converts a PaLM API response into a LangChain ChatResult."""
+ if not response.candidates:
+ raise ChatGooglePalmError("ChatResponse must have at least one candidate.")
+
+ generations: List[ChatGeneration] = []
+ for candidate in response.candidates:
+ author = candidate.get("author")
+ if author is None:
+ raise ChatGooglePalmError(f"ChatResponse must have an author: {candidate}")
+
+ content = _truncate_at_stop_tokens(candidate.get("content", ""), stop)
+ if content is None:
+ raise ChatGooglePalmError(f"ChatResponse must have a content: {candidate}")
+
+ if author == "ai":
+ generations.append(
+ ChatGeneration(text=content, message=AIMessage(content=content))
+ )
+ elif author == "human":
+ generations.append(
+ ChatGeneration(
+ text=content,
+ message=HumanMessage(content=content),
+ )
+ )
+ else:
+ generations.append(
+ ChatGeneration(
+ text=content,
+ message=ChatMessage(role=author, content=content),
+ )
+ )
+
+ return ChatResult(generations=generations)
+
+
+def _messages_to_prompt_dict(
+ input_messages: List[BaseMessage],
+) -> genai.types.MessagePromptDict:
+ """Converts a list of LangChain messages into a PaLM API MessagePrompt structure."""
+ import google.generativeai as genai
+
+ context: str = ""
+ examples: List[genai.types.MessageDict] = []
+ messages: List[genai.types.MessageDict] = []
+
+ remaining = list(enumerate(input_messages))
+
+ while remaining:
+ index, input_message = remaining.pop(0)
+
+ if isinstance(input_message, SystemMessage):
+ if index != 0:
+ raise ChatGooglePalmError("System message must be first input message.")
+ context = cast(str, input_message.content)
+ elif isinstance(
+ input_message, HumanMessage
+ ) and input_message.additional_kwargs.get("example"):
+ if messages:
+ raise ChatGooglePalmError(
+ "Message examples must come before other messages."
+ )
+ _, next_input_message = remaining.pop(0)
+ if isinstance(
+ next_input_message, AIMessage
+ ) and next_input_message.additional_kwargs.get("example"):
+ examples.extend(
+ [
+ genai.types.MessageDict(
+ author="human", content=input_message.content
+ ),
+ genai.types.MessageDict(
+ author="ai", content=next_input_message.content
+ ),
+ ]
+ )
+ else:
+ raise ChatGooglePalmError(
+ "Human example message must be immediately followed by an "
+ " AI example response."
+ )
+ elif isinstance(
+ input_message, AIMessage
+ ) and input_message.additional_kwargs.get("example"):
+ raise ChatGooglePalmError(
+ "AI example message must be immediately preceded by a Human "
+ "example message."
+ )
+ elif isinstance(input_message, AIMessage):
+ messages.append(
+ genai.types.MessageDict(author="ai", content=input_message.content)
+ )
+ elif isinstance(input_message, HumanMessage):
+ messages.append(
+ genai.types.MessageDict(author="human", content=input_message.content)
+ )
+ elif isinstance(input_message, ChatMessage):
+ messages.append(
+ genai.types.MessageDict(
+ author=input_message.role, content=input_message.content
+ )
+ )
+ else:
+ raise ChatGooglePalmError(
+ "Messages without an explicit role not supported by PaLM API."
+ )
+
+ return genai.types.MessagePromptDict(
+ context=context,
+ examples=examples,
+ messages=messages,
+ )
+
+
+def _create_retry_decorator() -> Callable[[Any], Any]:
+ """Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions"""
+ import google.api_core.exceptions
+
+ multiplier = 2
+ min_seconds = 1
+ max_seconds = 60
+ max_retries = 10
+
+ return retry(
+ reraise=True,
+ stop=stop_after_attempt(max_retries),
+ wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds),
+ retry=(
+ retry_if_exception_type(google.api_core.exceptions.ResourceExhausted)
+ | retry_if_exception_type(google.api_core.exceptions.ServiceUnavailable)
+ | retry_if_exception_type(google.api_core.exceptions.GoogleAPIError)
+ ),
+ before_sleep=before_sleep_log(logger, logging.WARNING),
+ )
+
+
+def chat_with_retry(llm: ChatGooglePalm, **kwargs: Any) -> Any:
+ """Use tenacity to retry the completion call."""
+ retry_decorator = _create_retry_decorator()
+
+ @retry_decorator
+ def _chat_with_retry(**kwargs: Any) -> Any:
+ return llm.client.chat(**kwargs)
+
+ return _chat_with_retry(**kwargs)
+
+
+async def achat_with_retry(llm: ChatGooglePalm, **kwargs: Any) -> Any:
+ """Use tenacity to retry the async completion call."""
+ retry_decorator = _create_retry_decorator()
+
+ @retry_decorator
+ async def _achat_with_retry(**kwargs: Any) -> Any:
+ # Use OpenAI's async api https://github.com/openai/openai-python#async-api
+ return await llm.client.chat_async(**kwargs)
+
+ return await _achat_with_retry(**kwargs)
+
+
+class ChatGooglePalm(BaseChatModel, BaseModel):
+ """`Google PaLM` Chat models API.
+
+ To use you must have the google.generativeai Python package installed and
+ either:
+
+ 1. The ``GOOGLE_API_KEY`` environment variable set with your API key, or
+ 2. Pass your API key using the google_api_key kwarg to the ChatGoogle
+ constructor.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatGooglePalm
+ chat = ChatGooglePalm()
+
+ """
+
+ client: Any #: :meta private:
+ model_name: str = "models/chat-bison-001"
+ """Model name to use."""
+ google_api_key: Optional[SecretStr] = None
+ temperature: Optional[float] = None
+ """Run inference with this temperature. Must be in the closed
+ interval [0.0, 1.0]."""
+ top_p: Optional[float] = None
+ """Decode using nucleus sampling: consider the smallest set of tokens whose
+ probability sum is at least top_p. Must be in the closed interval [0.0, 1.0]."""
+ top_k: Optional[int] = None
+ """Decode using top-k sampling: consider the set of top_k most probable tokens.
+ Must be positive."""
+ n: int = 1
+ """Number of chat completions to generate for each prompt. Note that the API may
+ not return the full n completions if duplicates are generated."""
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"google_api_key": "GOOGLE_API_KEY"}
+
+ @classmethod
+ def is_lc_serializable(self) -> bool:
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> List[str]:
+ """Get the namespace of the langchain object."""
+ return ["langchain", "chat_models", "google_palm"]
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate api key, python package exists, temperature, top_p, and top_k."""
+ google_api_key = convert_to_secret_str(
+ get_from_dict_or_env(values, "google_api_key", "GOOGLE_API_KEY")
+ )
+ try:
+ import google.generativeai as genai
+
+ genai.configure(api_key=google_api_key.get_secret_value())
+ except ImportError:
+ raise ChatGooglePalmError(
+ "Could not import google.generativeai python package. "
+ "Please install it with `pip install google-generativeai`"
+ )
+
+ values["client"] = genai
+
+ if values["temperature"] is not None and not 0 <= values["temperature"] <= 1:
+ raise ValueError("temperature must be in the range [0.0, 1.0]")
+
+ if values["top_p"] is not None and not 0 <= values["top_p"] <= 1:
+ raise ValueError("top_p must be in the range [0.0, 1.0]")
+
+ if values["top_k"] is not None and values["top_k"] <= 0:
+ raise ValueError("top_k must be positive")
+
+ return values
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ prompt = _messages_to_prompt_dict(messages)
+
+ response: genai.types.ChatResponse = chat_with_retry(
+ self,
+ model=self.model_name,
+ prompt=prompt,
+ temperature=self.temperature,
+ top_p=self.top_p,
+ top_k=self.top_k,
+ candidate_count=self.n,
+ **kwargs,
+ )
+
+ return _response_to_result(response, stop)
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ prompt = _messages_to_prompt_dict(messages)
+
+ response: genai.types.ChatResponse = await achat_with_retry(
+ self,
+ model=self.model_name,
+ prompt=prompt,
+ temperature=self.temperature,
+ top_p=self.top_p,
+ top_k=self.top_k,
+ candidate_count=self.n,
+ )
+
+ return _response_to_result(response, stop)
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ return {
+ "model_name": self.model_name,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "top_k": self.top_k,
+ "n": self.n,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ return "google-palm-chat"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/gpt_router.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/gpt_router.py
new file mode 100644
index 0000000000000000000000000000000000000000..91f314a8a633a722f3ed37d924d88f7589afebae
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/gpt_router.py
@@ -0,0 +1,401 @@
+from __future__ import annotations
+
+import logging
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ AsyncGenerator,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Generator,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Tuple,
+ Type,
+ Union,
+)
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.language_models.llms import create_base_retry_decorator
+from langchain_core.messages import AIMessageChunk, BaseMessage, BaseMessageChunk
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
+from pydantic import BaseModel, Field, SecretStr, model_validator
+from typing_extensions import Self
+
+from langchain_community.adapters.openai import (
+ convert_dict_to_message,
+ convert_message_to_dict,
+)
+from langchain_community.chat_models.openai import _convert_delta_to_message_chunk
+
+if TYPE_CHECKING:
+ from gpt_router.models import ChunkedGenerationResponse, GenerationResponse
+
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_API_BASE_URL = "https://gpt-router-preview.writesonic.com"
+
+
+class GPTRouterException(Exception):
+ """Error with the `GPTRouter APIs`"""
+
+
+class GPTRouterModel(BaseModel):
+ """GPTRouter model."""
+
+ name: str
+ provider_name: str
+
+
+def get_ordered_generation_requests(
+ models_priority_list: List[GPTRouterModel], **kwargs: Any
+) -> List:
+ """
+ Return the body for the model router input.
+ """
+
+ from gpt_router.models import GenerationParams, ModelGenerationRequest
+
+ return [
+ ModelGenerationRequest(
+ model_name=model.name,
+ provider_name=model.provider_name,
+ order=index + 1,
+ prompt_params=GenerationParams(**kwargs),
+ )
+ for index, model in enumerate(models_priority_list)
+ ]
+
+
+def _create_retry_decorator(
+ llm: GPTRouter,
+ run_manager: Optional[
+ Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]
+ ] = None,
+) -> Callable[[Any], Any]:
+ from gpt_router import exceptions
+
+ errors = [
+ exceptions.GPTRouterApiTimeoutError,
+ exceptions.GPTRouterInternalServerError,
+ exceptions.GPTRouterNotAvailableError,
+ exceptions.GPTRouterTooManyRequestsError,
+ ]
+ return create_base_retry_decorator(
+ error_types=errors, max_retries=llm.max_retries, run_manager=run_manager
+ )
+
+
+def completion_with_retry(
+ llm: GPTRouter,
+ models_priority_list: List[GPTRouterModel],
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+) -> Union[GenerationResponse, Generator[ChunkedGenerationResponse, None, None]]:
+ """Use tenacity to retry the completion call."""
+ retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
+
+ @retry_decorator
+ def _completion_with_retry(**kwargs: Any) -> Any:
+ ordered_generation_requests = get_ordered_generation_requests(
+ models_priority_list, **kwargs
+ )
+ return llm.client.generate(
+ ordered_generation_requests=ordered_generation_requests,
+ is_stream=kwargs.get("stream", False),
+ )
+
+ return _completion_with_retry(**kwargs)
+
+
+async def acompletion_with_retry(
+ llm: GPTRouter,
+ models_priority_list: List[GPTRouterModel],
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+) -> Union[GenerationResponse, AsyncGenerator[ChunkedGenerationResponse, None]]:
+ """Use tenacity to retry the async completion call."""
+
+ retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
+
+ @retry_decorator
+ async def _completion_with_retry(**kwargs: Any) -> Any:
+ ordered_generation_requests = get_ordered_generation_requests(
+ models_priority_list, **kwargs
+ )
+ return await llm.client.agenerate(
+ ordered_generation_requests=ordered_generation_requests,
+ is_stream=kwargs.get("stream", False),
+ )
+
+ return await _completion_with_retry(**kwargs)
+
+
+class GPTRouter(BaseChatModel):
+ """GPTRouter by Writesonic Inc.
+
+ For more information, see https://gpt-router.writesonic.com/docs
+ """
+
+ client: Any = Field(default=None, exclude=True) #: :meta private:
+ models_priority_list: List[GPTRouterModel] = Field(min_length=1)
+ gpt_router_api_base: str = Field(default="")
+ """WriteSonic GPTRouter custom endpoint"""
+ gpt_router_api_key: Optional[SecretStr] = None
+ """WriteSonic GPTRouter API Key"""
+ temperature: float = 0.7
+ """What sampling temperature to use."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for `create` call not explicitly specified."""
+ max_retries: int = 4
+ """Maximum number of retries to make when generating."""
+ streaming: bool = False
+ """Whether to stream the results or not."""
+ n: int = 1
+ """Number of chat completions to generate for each prompt."""
+ max_tokens: int = 256
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ values["gpt_router_api_base"] = get_from_dict_or_env(
+ values,
+ "gpt_router_api_base",
+ "GPT_ROUTER_API_BASE",
+ DEFAULT_API_BASE_URL,
+ )
+
+ values["gpt_router_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ "gpt_router_api_key",
+ "GPT_ROUTER_API_KEY",
+ )
+ )
+ return values
+
+ @model_validator(mode="after")
+ def post_init(self) -> Self:
+ try:
+ from gpt_router.client import GPTRouterClient
+
+ except ImportError:
+ raise GPTRouterException(
+ "Could not import GPTRouter python package. "
+ "Please install it with `pip install GPTRouter`."
+ )
+
+ gpt_router_client = GPTRouterClient(
+ self.gpt_router_api_base,
+ self.gpt_router_api_key.get_secret_value()
+ if self.gpt_router_api_key
+ else None,
+ )
+ self.client = gpt_router_client
+
+ return self
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"gpt_router_api_key": "GPT_ROUTER_API_KEY"}
+
+ @property
+ def lc_serializable(self) -> bool:
+ return True
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "gpt-router-chat"
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ return {
+ **{"models_priority_list": self.models_priority_list},
+ **self._default_params,
+ }
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling GPTRouter API."""
+ return {
+ "max_tokens": self.max_tokens,
+ "stream": self.streaming,
+ "n": self.n,
+ "temperature": self.temperature,
+ **self.model_kwargs,
+ }
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": False}
+ response = completion_with_retry(
+ self,
+ messages=message_dicts,
+ models_priority_list=self.models_priority_list,
+ run_manager=run_manager,
+ **params,
+ )
+ return self._create_chat_result(response)
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": False}
+ response = await acompletion_with_retry(
+ self,
+ messages=message_dicts,
+ models_priority_list=self.models_priority_list,
+ run_manager=run_manager,
+ **params,
+ )
+ return self._create_chat_result(response)
+
+ def _create_chat_generation_chunk(
+ self, data: Mapping[str, Any], default_chunk_class: Type[BaseMessageChunk]
+ ) -> Tuple[ChatGenerationChunk, Type[BaseMessageChunk]]:
+ chunk = _convert_delta_to_message_chunk(
+ {"content": data.get("text", "")}, default_chunk_class
+ )
+ finish_reason = data.get("finish_reason")
+ generation_info = (
+ dict(finish_reason=finish_reason) if finish_reason is not None else None
+ )
+ default_chunk_class = chunk.__class__
+ gen_chunk = ChatGenerationChunk(message=chunk, generation_info=generation_info)
+ return gen_chunk, default_chunk_class
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ generator_response = completion_with_retry(
+ self,
+ messages=message_dicts,
+ models_priority_list=self.models_priority_list,
+ run_manager=run_manager,
+ **params,
+ )
+ for chunk in generator_response:
+ if chunk.event != "update":
+ continue
+
+ chunk, default_chunk_class = self._create_chat_generation_chunk(
+ chunk.data, default_chunk_class
+ )
+
+ if run_manager:
+ run_manager.on_llm_new_token(
+ token=str(chunk.message.content), chunk=chunk
+ )
+
+ yield chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ generator_response = acompletion_with_retry(
+ self,
+ messages=message_dicts,
+ models_priority_list=self.models_priority_list,
+ run_manager=run_manager,
+ **params,
+ )
+ async for chunk in await generator_response:
+ if chunk.event != "update":
+ continue
+
+ chunk, default_chunk_class = self._create_chat_generation_chunk(
+ chunk.data, default_chunk_class
+ )
+
+ if run_manager:
+ await run_manager.on_llm_new_token(
+ token=str(chunk.message.content), chunk=chunk
+ )
+
+ yield chunk
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage], stop: Optional[List[str]]
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
+ params = self._default_params
+ if stop is not None:
+ if "stop" in params:
+ raise ValueError("`stop` found in both the input and default params.")
+ params["stop"] = stop
+ message_dicts = [convert_message_to_dict(m) for m in messages]
+ return message_dicts, params
+
+ def _create_chat_result(self, response: GenerationResponse) -> ChatResult:
+ generations = []
+ for res in response.choices:
+ message = convert_dict_to_message(
+ {
+ "role": "assistant",
+ "content": res.text,
+ }
+ )
+ gen = ChatGeneration(
+ message=message,
+ generation_info=dict(finish_reason=res.finish_reason),
+ )
+ generations.append(gen)
+ llm_output = {"token_usage": response.meta, "model": response.model}
+ return ChatResult(generations=generations, llm_output=llm_output)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/huggingface.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/huggingface.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe029d6d6ca7a8bf84ca7223ccacbd6b26084ef7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/huggingface.py
@@ -0,0 +1,235 @@
+"""Hugging Face Chat Wrapper."""
+
+from typing import Any, AsyncIterator, Iterator, List, Optional
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ ChatResult,
+ LLMResult,
+)
+from pydantic import model_validator
+from typing_extensions import Self
+
+from langchain_community.llms.huggingface_endpoint import HuggingFaceEndpoint
+from langchain_community.llms.huggingface_hub import HuggingFaceHub
+from langchain_community.llms.huggingface_text_gen_inference import (
+ HuggingFaceTextGenInference,
+)
+
+DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful, and honest assistant."""
+
+
+@deprecated(
+ since="0.0.37",
+ removal="1.0",
+ alternative_import="langchain_huggingface.ChatHuggingFace",
+)
+class ChatHuggingFace(BaseChatModel):
+ """
+ Wrapper for using Hugging Face LLM's as ChatModels.
+
+ Works with `HuggingFaceTextGenInference`, `HuggingFaceEndpoint`,
+ and `HuggingFaceHub` LLMs.
+
+ Upon instantiating this class, the model_id is resolved from the url
+ provided to the LLM, and the appropriate tokenizer is loaded from
+ the HuggingFace Hub.
+
+ Adapted from: https://python.langchain.com/docs/integrations/chat/llama2_chat
+ """
+
+ llm: Any
+ """LLM, must be of type HuggingFaceTextGenInference, HuggingFaceEndpoint, or
+ HuggingFaceHub."""
+ system_message: SystemMessage = SystemMessage(content=DEFAULT_SYSTEM_PROMPT)
+ tokenizer: Any = None
+ model_id: Optional[str] = None
+ streaming: bool = False
+
+ def __init__(self, **kwargs: Any):
+ super().__init__(**kwargs)
+
+ from transformers import AutoTokenizer
+
+ self._resolve_model_id()
+
+ self.tokenizer = (
+ AutoTokenizer.from_pretrained(self.model_id)
+ if self.tokenizer is None
+ else self.tokenizer
+ )
+
+ @model_validator(mode="after")
+ def validate_llm(self) -> Self:
+ if not isinstance(
+ self.llm,
+ (HuggingFaceTextGenInference, HuggingFaceEndpoint, HuggingFaceHub),
+ ):
+ raise TypeError(
+ "Expected llm to be one of HuggingFaceTextGenInference, "
+ f"HuggingFaceEndpoint, HuggingFaceHub, received {type(self.llm)}"
+ )
+ return self
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ request = self._to_chat_prompt(messages)
+
+ for data in self.llm.stream(request, **kwargs):
+ delta = data
+ chunk = ChatGenerationChunk(message=AIMessageChunk(content=delta))
+ if run_manager:
+ run_manager.on_llm_new_token(delta, chunk=chunk)
+ yield chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ request = self._to_chat_prompt(messages)
+ async for data in self.llm.astream(request, **kwargs):
+ delta = data
+ chunk = ChatGenerationChunk(message=AIMessageChunk(content=delta))
+ if run_manager:
+ await run_manager.on_llm_new_token(delta, chunk=chunk)
+ yield chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ llm_input = self._to_chat_prompt(messages)
+ llm_result = self.llm._generate(
+ prompts=[llm_input], stop=stop, run_manager=run_manager, **kwargs
+ )
+ return self._to_chat_result(llm_result)
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ llm_input = self._to_chat_prompt(messages)
+ llm_result = await self.llm._agenerate(
+ prompts=[llm_input], stop=stop, run_manager=run_manager, **kwargs
+ )
+ return self._to_chat_result(llm_result)
+
+ def _to_chat_prompt(
+ self,
+ messages: List[BaseMessage],
+ ) -> str:
+ """Convert a list of messages into a prompt format expected by wrapped LLM."""
+ if not messages:
+ raise ValueError("At least one HumanMessage must be provided!")
+
+ if not isinstance(messages[-1], HumanMessage):
+ raise ValueError("Last message must be a HumanMessage!")
+
+ messages_dicts = [self._to_chatml_format(m) for m in messages]
+
+ return self.tokenizer.apply_chat_template(
+ messages_dicts, tokenize=False, add_generation_prompt=True
+ )
+
+ def _to_chatml_format(self, message: BaseMessage) -> dict:
+ """Convert LangChain message to ChatML format."""
+
+ if isinstance(message, SystemMessage):
+ role = "system"
+ elif isinstance(message, AIMessage):
+ role = "assistant"
+ elif isinstance(message, HumanMessage):
+ role = "user"
+ else:
+ raise ValueError(f"Unknown message type: {type(message)}")
+
+ return {"role": role, "content": message.content}
+
+ @staticmethod
+ def _to_chat_result(llm_result: LLMResult) -> ChatResult:
+ chat_generations = []
+
+ for g in llm_result.generations[0]:
+ chat_generation = ChatGeneration(
+ message=AIMessage(content=g.text), generation_info=g.generation_info
+ )
+ chat_generations.append(chat_generation)
+
+ return ChatResult(
+ generations=chat_generations, llm_output=llm_result.llm_output
+ )
+
+ def _resolve_model_id(self) -> None:
+ """Resolve the model_id from the LLM's inference_server_url"""
+
+ from huggingface_hub import list_inference_endpoints
+
+ available_endpoints = list_inference_endpoints("*")
+ if isinstance(self.llm, HuggingFaceHub) or (
+ hasattr(self.llm, "repo_id") and self.llm.repo_id
+ ):
+ self.model_id = self.llm.repo_id
+ return
+ elif isinstance(self.llm, HuggingFaceTextGenInference):
+ endpoint_url: Optional[str] = self.llm.inference_server_url
+ else:
+ endpoint_url = self.llm.endpoint_url
+
+ for endpoint in available_endpoints:
+ if endpoint.url == endpoint_url:
+ self.model_id = endpoint.repository
+
+ if not self.model_id:
+ raise ValueError(
+ "Failed to resolve model_id:"
+ f"Could not find model id for inference server: {endpoint_url}"
+ "Make sure that your Hugging Face token has access to the endpoint."
+ )
+
+ @property
+ def _llm_type(self) -> str:
+ return "huggingface-chat-wrapper"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/human.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/human.py
new file mode 100644
index 0000000000000000000000000000000000000000..c24964a678edded10fe35cc68f3d9e8975857abb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/human.py
@@ -0,0 +1,111 @@
+"""ChatModel wrapper which returns user input as the response.."""
+
+from io import StringIO
+from typing import Any, Callable, Dict, List, Mapping, Optional
+
+import yaml
+from langchain_core.callbacks import (
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ BaseMessage,
+ HumanMessage,
+ _message_from_dict,
+ messages_to_dict,
+)
+from langchain_core.outputs import ChatGeneration, ChatResult
+from pydantic import Field
+
+from langchain_community.llms.utils import enforce_stop_tokens
+
+
+def _display_messages(messages: List[BaseMessage]) -> None:
+ dict_messages = messages_to_dict(messages)
+ for message in dict_messages:
+ yaml_string = yaml.dump(
+ message,
+ default_flow_style=False,
+ sort_keys=False,
+ allow_unicode=True,
+ width=10000,
+ line_break=None,
+ )
+ print("\n", "======= start of message =======", "\n\n") # noqa: T201
+ print(yaml_string) # noqa: T201
+ print("======= end of message =======", "\n\n") # noqa: T201
+
+
+def _collect_yaml_input(
+ messages: List[BaseMessage], stop: Optional[List[str]] = None
+) -> BaseMessage:
+ """Collects and returns user input as a single string."""
+ lines = []
+ while True:
+ line = input()
+ if not line.strip():
+ break
+ if stop and any(seq in line for seq in stop):
+ break
+ lines.append(line)
+ yaml_string = "\n".join(lines)
+
+ # Try to parse the input string as YAML
+ try:
+ message = _message_from_dict(yaml.safe_load(StringIO(yaml_string)))
+ if message is None:
+ return HumanMessage(content="")
+ if stop:
+ if isinstance(message.content, str):
+ message.content = enforce_stop_tokens(message.content, stop)
+ else:
+ raise ValueError("Cannot use when output is not a string.")
+ return message
+ except yaml.YAMLError:
+ raise ValueError("Invalid YAML string entered.")
+ except ValueError:
+ raise ValueError("Invalid message entered.")
+
+
+class HumanInputChatModel(BaseChatModel):
+ """ChatModel which returns user input as the response."""
+
+ input_func: Callable = Field(default_factory=lambda: _collect_yaml_input)
+ message_func: Callable = Field(default_factory=lambda: _display_messages)
+ separator: str = "\n"
+ input_kwargs: Mapping[str, Any] = {}
+ message_kwargs: Mapping[str, Any] = {}
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ return {
+ "input_func": self.input_func.__name__,
+ "message_func": self.message_func.__name__,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Returns the type of LLM."""
+ return "human-input-chat-model"
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """
+ Displays the messages to the user and returns their input as a response.
+
+ Args:
+ messages (List[BaseMessage]): The messages to be displayed to the user.
+ stop (Optional[List[str]]): A list of stop strings.
+ run_manager (Optional[CallbackManagerForLLMRun]): Currently not used.
+
+ Returns:
+ ChatResult: The user's input as a response.
+ """
+ self.message_func(messages, **self.message_kwargs)
+ user_input = self.input_func(messages, stop=stop, **self.input_kwargs)
+ return ChatResult(generations=[ChatGeneration(message=user_input)])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/hunyuan.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/hunyuan.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac9ebcc55e231040f82166c6134b726aed47def6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/hunyuan.py
@@ -0,0 +1,280 @@
+import json
+import logging
+from typing import Any, Dict, Iterator, List, Mapping, Optional, Type
+
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.utils import (
+ convert_to_secret_str,
+ get_from_dict_or_env,
+ get_pydantic_field_names,
+ pre_init,
+)
+from pydantic import ConfigDict, Field, SecretStr, model_validator
+
+logger = logging.getLogger(__name__)
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ message_dict: Dict[str, Any]
+ if isinstance(message, ChatMessage):
+ message_dict = {"Role": message.role, "Content": message.content}
+ elif isinstance(message, SystemMessage):
+ message_dict = {"Role": "system", "Content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"Role": "user", "Content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"Role": "assistant", "Content": message.content}
+ else:
+ raise TypeError(f"Got unknown type {message}")
+
+ return message_dict
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ role = _dict["Role"]
+ if role == "system":
+ return SystemMessage(content=_dict.get("Content", "") or "")
+ elif role == "user":
+ return HumanMessage(content=_dict["Content"])
+ elif role == "assistant":
+ return AIMessage(content=_dict.get("Content", "") or "")
+ else:
+ return ChatMessage(content=_dict["Content"], role=role)
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role = _dict.get("Role")
+ content = _dict.get("Content") or ""
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content)
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+def _create_chat_result(response: Mapping[str, Any]) -> ChatResult:
+ generations = []
+ for choice in response["Choices"]:
+ message = _convert_dict_to_message(choice["Message"])
+ message.id = response.get("Id", "")
+ generations.append(ChatGeneration(message=message))
+
+ token_usage = response["Usage"]
+ llm_output = {"token_usage": token_usage}
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+
+class ChatHunyuan(BaseChatModel):
+ """Tencent Hunyuan chat models API by Tencent.
+
+ For more information, see https://cloud.tencent.com/document/product/1729
+ """
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {
+ "hunyuan_app_id": "HUNYUAN_APP_ID",
+ "hunyuan_secret_id": "HUNYUAN_SECRET_ID",
+ "hunyuan_secret_key": "HUNYUAN_SECRET_KEY",
+ }
+
+ @property
+ def lc_serializable(self) -> bool:
+ return True
+
+ hunyuan_app_id: Optional[int] = None
+ """Hunyuan App ID"""
+ hunyuan_secret_id: Optional[str] = None
+ """Hunyuan Secret ID"""
+ hunyuan_secret_key: Optional[SecretStr] = None
+ """Hunyuan Secret Key"""
+ streaming: bool = False
+ """Whether to stream the results or not."""
+ request_timeout: int = 60
+ """Timeout for requests to Hunyuan API. Default is 60 seconds."""
+ temperature: float = 1.0
+ """What sampling temperature to use."""
+ top_p: float = 1.0
+ """What probability mass to use."""
+ model: str = "hunyuan-lite"
+ """What Model to use.
+ Optional model:
+ - hunyuan-lite
+ - hunyuan-standard
+ - hunyuan-standard-256K
+ - hunyuan-pro
+ - hunyuan-code
+ - hunyuan-role
+ - hunyuan-functioncall
+ - hunyuan-vision
+ """
+ stream_moderation: bool = False
+ """Whether to review the results or not when streaming is true."""
+ enable_enhancement: bool = True
+ """Whether to enhancement the results or not."""
+
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for API call not explicitly specified."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def build_extra(cls, values: Dict[str, Any]) -> Any:
+ """Build extra kwargs from additional params that were passed in."""
+ all_required_field_names = get_pydantic_field_names(cls)
+ extra = values.get("model_kwargs", {})
+ for field_name in list(values):
+ if field_name in extra:
+ raise ValueError(f"Found {field_name} supplied twice.")
+ if field_name not in all_required_field_names:
+ logger.warning(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please confirm that {field_name} is what you intended."""
+ )
+ extra[field_name] = values.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
+ if invalid_model_kwargs:
+ raise ValueError(
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+
+ values["model_kwargs"] = extra
+ return values
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ values["hunyuan_app_id"] = get_from_dict_or_env(
+ values,
+ "hunyuan_app_id",
+ "HUNYUAN_APP_ID",
+ )
+ values["hunyuan_secret_id"] = get_from_dict_or_env(
+ values,
+ "hunyuan_secret_id",
+ "HUNYUAN_SECRET_ID",
+ )
+ values["hunyuan_secret_key"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ "hunyuan_secret_key",
+ "HUNYUAN_SECRET_KEY",
+ )
+ )
+ return values
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling Hunyuan API."""
+ normal_params = {
+ "Temperature": self.temperature,
+ "TopP": self.top_p,
+ "Model": self.model,
+ "Stream": self.streaming,
+ "StreamModeration": self.stream_moderation,
+ "EnableEnhancement": self.enable_enhancement,
+ }
+ return {**normal_params, **self.model_kwargs}
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages=messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ res = self._chat(messages, **kwargs)
+ return _create_chat_result(json.loads(res.to_json_string()))
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ res = self._chat(messages, **kwargs)
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ for chunk in res:
+ chunk = chunk.get("data", "")
+ if len(chunk) == 0:
+ continue
+ response = json.loads(chunk)
+ if "error" in response:
+ raise ValueError(f"Error from Hunyuan api response: {response}")
+
+ for choice in response["Choices"]:
+ chunk = _convert_delta_to_message_chunk(
+ choice["Delta"], default_chunk_class
+ )
+ chunk.id = response.get("Id", "")
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(message=chunk)
+ if run_manager:
+ run_manager.on_llm_new_token(str(chunk.content), chunk=cg_chunk)
+ yield cg_chunk
+
+ def _chat(self, messages: List[BaseMessage], **kwargs: Any) -> Any:
+ if self.hunyuan_secret_key is None:
+ raise ValueError("Hunyuan secret key is not set.")
+
+ try:
+ from tencentcloud.common import credential
+ from tencentcloud.hunyuan.v20230901 import hunyuan_client, models
+ except ImportError:
+ raise ImportError(
+ "Could not import tencentcloud python package. "
+ "Please install it with `pip install tencentcloud-sdk-python`."
+ )
+
+ parameters = {**self._default_params, **kwargs}
+ cred = credential.Credential(
+ self.hunyuan_secret_id, str(self.hunyuan_secret_key.get_secret_value())
+ )
+ client = hunyuan_client.HunyuanClient(cred, "")
+ req = models.ChatCompletionsRequest()
+ params = {
+ "Messages": [_convert_message_to_dict(m) for m in messages],
+ **parameters,
+ }
+ req.from_json_string(json.dumps(params))
+ resp = client.ChatCompletions(req)
+ return resp
+
+ @property
+ def _llm_type(self) -> str:
+ return "hunyuan-chat"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/javelin_ai_gateway.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/javelin_ai_gateway.py
new file mode 100644
index 0000000000000000000000000000000000000000..d09fb3bcaf67bb0161c132ffdf0184ab719f5d85
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/javelin_ai_gateway.py
@@ -0,0 +1,228 @@
+import logging
+from typing import Any, Dict, List, Mapping, Optional, cast
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ ChatMessage,
+ FunctionMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatResult,
+)
+from pydantic import BaseModel, ConfigDict, Field, SecretStr
+
+logger = logging.getLogger(__name__)
+
+
+# Ignoring type because below is valid pydantic code
+# Unexpected keyword argument "extra" for "__init_subclass__" of "object" [call-arg]
+class ChatParams(BaseModel, extra="allow"):
+ """Parameters for the `Javelin AI Gateway` LLM."""
+
+ temperature: float = 0.0
+ stop: Optional[List[str]] = None
+ max_tokens: Optional[int] = None
+
+
+class ChatJavelinAIGateway(BaseChatModel):
+ """`Javelin AI Gateway` chat models API.
+
+ To use, you should have the ``javelin_sdk`` python package installed.
+ For more information, see https://docs.getjavelin.io
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatJavelinAIGateway
+
+ chat = ChatJavelinAIGateway(
+ gateway_uri="",
+ route="",
+ params={
+ "temperature": 0.1
+ }
+ )
+ """
+
+ route: str
+ """The route to use for the Javelin AI Gateway API."""
+
+ gateway_uri: Optional[str] = None
+ """The URI for the Javelin AI Gateway API."""
+
+ params: Optional[ChatParams] = None
+ """Parameters for the Javelin AI Gateway LLM."""
+
+ client: Any = None
+ """javelin client."""
+
+ javelin_api_key: Optional[SecretStr] = Field(None, alias="api_key")
+ """The API key for the Javelin AI Gateway."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ def __init__(self, **kwargs: Any):
+ try:
+ from javelin_sdk import (
+ JavelinClient,
+ UnauthorizedError,
+ )
+ except ImportError:
+ raise ImportError(
+ "Could not import javelin_sdk python package. "
+ "Please install it with `pip install javelin_sdk`."
+ )
+
+ super().__init__(**kwargs)
+ if self.gateway_uri:
+ try:
+ self.client = JavelinClient(
+ base_url=self.gateway_uri,
+ api_key=cast(SecretStr, self.javelin_api_key).get_secret_value(),
+ )
+ except UnauthorizedError as e:
+ raise ValueError("Javelin: Incorrect API Key.") from e
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ params: Dict[str, Any] = {
+ "gateway_uri": self.gateway_uri,
+ "javelin_api_key": cast(SecretStr, self.javelin_api_key).get_secret_value(),
+ "route": self.route,
+ **(self.params.dict() if self.params else {}),
+ }
+ return params
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ message_dicts = [
+ ChatJavelinAIGateway._convert_message_to_dict(message)
+ for message in messages
+ ]
+ data: Dict[str, Any] = {
+ "messages": message_dicts,
+ **(self.params.dict() if self.params else {}),
+ }
+
+ resp = self.client.query_route(self.route, query_body=data)
+
+ return ChatJavelinAIGateway._create_chat_result(resp.dict())
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ message_dicts = [
+ ChatJavelinAIGateway._convert_message_to_dict(message)
+ for message in messages
+ ]
+ data: Dict[str, Any] = {
+ "messages": message_dicts,
+ **(self.params.dict() if self.params else {}),
+ }
+
+ resp = await self.client.aquery_route(self.route, query_body=data)
+
+ return ChatJavelinAIGateway._create_chat_result(resp.dict())
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ return self._default_params
+
+ def _get_invocation_params(
+ self, stop: Optional[List[str]] = None, **kwargs: Any
+ ) -> Dict[str, Any]:
+ """Get the parameters used to invoke the model FOR THE CALLBACKS."""
+ return {
+ **self._default_params,
+ **super()._get_invocation_params(stop=stop, **kwargs),
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "javelin-ai-gateway-chat"
+
+ @staticmethod
+ def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ role = _dict["role"]
+ content = _dict["content"]
+ if role == "user":
+ return HumanMessage(content=content)
+ elif role == "assistant":
+ return AIMessage(content=content)
+ elif role == "system":
+ return SystemMessage(content=content)
+ else:
+ return ChatMessage(content=content, role=role)
+
+ @staticmethod
+ def _raise_functions_not_supported() -> None:
+ raise ValueError(
+ "Function messages are not supported by the Javelin AI Gateway. Please"
+ " create a feature request at https://docs.getjavelin.io"
+ )
+
+ @staticmethod
+ def _convert_message_to_dict(message: BaseMessage) -> dict:
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, FunctionMessage):
+ raise ValueError(
+ "Function messages are not supported by the Javelin AI Gateway. Please"
+ " create a feature request at https://docs.getjavelin.io"
+ )
+ else:
+ raise ValueError(f"Got unknown message type: {message}")
+
+ if "function_call" in message.additional_kwargs:
+ ChatJavelinAIGateway._raise_functions_not_supported()
+ if message.additional_kwargs:
+ logger.warning(
+ "Additional message arguments are unsupported by Javelin AI Gateway "
+ " and will be ignored: %s",
+ message.additional_kwargs,
+ )
+ return message_dict
+
+ @staticmethod
+ def _create_chat_result(response: Mapping[str, Any]) -> ChatResult:
+ generations = []
+ for candidate in response["llm_response"]["choices"]:
+ message = ChatJavelinAIGateway._convert_dict_to_message(
+ candidate["message"]
+ )
+ message_metadata = candidate.get("metadata", {})
+ gen = ChatGeneration(
+ message=message,
+ generation_info=dict(message_metadata),
+ )
+ generations.append(gen)
+
+ response_metadata = response.get("metadata", {})
+ return ChatResult(generations=generations, llm_output=response_metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/jinachat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/jinachat.py
new file mode 100644
index 0000000000000000000000000000000000000000..52627f72d5893aeeccdca6f9c7cd48c6450ca9f3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/jinachat.py
@@ -0,0 +1,414 @@
+"""JinaChat wrapper."""
+
+from __future__ import annotations
+
+import logging
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Tuple,
+ Type,
+ Union,
+)
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessage,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.utils import (
+ convert_to_secret_str,
+ get_from_dict_or_env,
+ get_pydantic_field_names,
+ pre_init,
+)
+from pydantic import ConfigDict, Field, SecretStr, model_validator
+from tenacity import (
+ before_sleep_log,
+ retry,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def _create_retry_decorator(llm: JinaChat) -> Callable[[Any], Any]:
+ import openai
+
+ min_seconds = 1
+ max_seconds = 60
+ # Wait 2^x * 1 second between each retry starting with
+ # 4 seconds, then up to 10 seconds, then 10 seconds afterwards
+ return retry(
+ reraise=True,
+ stop=stop_after_attempt(llm.max_retries),
+ wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
+ retry=(
+ retry_if_exception_type(openai.error.Timeout)
+ | retry_if_exception_type(openai.error.APIError)
+ | retry_if_exception_type(openai.error.APIConnectionError)
+ | retry_if_exception_type(openai.error.RateLimitError)
+ | retry_if_exception_type(openai.error.ServiceUnavailableError)
+ ),
+ before_sleep=before_sleep_log(logger, logging.WARNING),
+ )
+
+
+async def acompletion_with_retry(llm: JinaChat, **kwargs: Any) -> Any:
+ """Use tenacity to retry the async completion call."""
+ retry_decorator = _create_retry_decorator(llm)
+
+ @retry_decorator
+ async def _completion_with_retry(**kwargs: Any) -> Any:
+ # Use OpenAI's async api https://github.com/openai/openai-python#async-api
+ return await llm.client.acreate(**kwargs)
+
+ return await _completion_with_retry(**kwargs)
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role = _dict.get("role")
+ content = _dict.get("content") or ""
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content)
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ role = _dict["role"]
+ if role == "user":
+ return HumanMessage(content=_dict["content"])
+ elif role == "assistant":
+ content = _dict["content"] or ""
+ return AIMessage(content=content)
+ elif role == "system":
+ return SystemMessage(content=_dict["content"])
+ else:
+ return ChatMessage(content=_dict["content"], role=role)
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, FunctionMessage):
+ message_dict = {
+ "role": "function",
+ "name": message.name,
+ "content": message.content,
+ }
+ else:
+ raise ValueError(f"Got unknown type {message}")
+ if "name" in message.additional_kwargs:
+ message_dict["name"] = message.additional_kwargs["name"]
+ return message_dict
+
+
+class JinaChat(BaseChatModel):
+ """`Jina AI` Chat models API.
+
+ To use, you should have the ``openai`` python package installed, and the
+ environment variable ``JINACHAT_API_KEY`` set to your API key, which you
+ can generate at https://chat.jina.ai/api.
+
+ Any parameters that are valid to be passed to the openai.create call can be passed
+ in, even if not explicitly saved on this class.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import JinaChat
+ chat = JinaChat()
+ """
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"jinachat_api_key": "JINACHAT_API_KEY"}
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return whether this model can be serialized by Langchain."""
+ return False
+
+ client: Any = None #: :meta private:
+ temperature: float = 0.7
+ """What sampling temperature to use."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for `create` call not explicitly specified."""
+ jinachat_api_key: Optional[SecretStr] = None
+ """Base URL path for API requests,
+ leave blank if not using a proxy or service emulator."""
+ request_timeout: Optional[Union[float, Tuple[float, float]]] = None
+ """Timeout for requests to JinaChat completion API. Default is 600 seconds."""
+ max_retries: int = 6
+ """Maximum number of retries to make when generating."""
+ streaming: bool = False
+ """Whether to stream the results or not."""
+ max_tokens: Optional[int] = None
+ """Maximum number of tokens to generate."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def build_extra(cls, values: Dict[str, Any]) -> Any:
+ """Build extra kwargs from additional params that were passed in."""
+ all_required_field_names = get_pydantic_field_names(cls)
+ extra = values.get("model_kwargs", {})
+ for field_name in list(values):
+ if field_name in extra:
+ raise ValueError(f"Found {field_name} supplied twice.")
+ if field_name not in all_required_field_names:
+ logger.warning(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please confirm that {field_name} is what you intended."""
+ )
+ extra[field_name] = values.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
+ if invalid_model_kwargs:
+ raise ValueError(
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+
+ values["model_kwargs"] = extra
+ return values
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that api key and python package exists in environment."""
+ values["jinachat_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(values, "jinachat_api_key", "JINACHAT_API_KEY")
+ )
+ try:
+ import openai
+
+ except ImportError:
+ raise ImportError(
+ "Could not import openai python package. "
+ "Please install it with `pip install openai`."
+ )
+ try:
+ values["client"] = openai.ChatCompletion
+ except AttributeError:
+ raise ValueError(
+ "`openai` has no `ChatCompletion` attribute, this is likely "
+ "due to an old version of the openai package. Try upgrading it "
+ "with `pip install --upgrade openai`."
+ )
+ return values
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling JinaChat API."""
+ return {
+ "request_timeout": self.request_timeout,
+ "max_tokens": self.max_tokens,
+ "stream": self.streaming,
+ "temperature": self.temperature,
+ **self.model_kwargs,
+ }
+
+ def _create_retry_decorator(self) -> Callable[[Any], Any]:
+ import openai
+
+ min_seconds = 1
+ max_seconds = 60
+ # Wait 2^x * 1 second between each retry starting with
+ # 4 seconds, then up to 10 seconds, then 10 seconds afterwards
+ return retry(
+ reraise=True,
+ stop=stop_after_attempt(self.max_retries),
+ wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
+ retry=(
+ retry_if_exception_type(openai.error.Timeout)
+ | retry_if_exception_type(openai.error.APIError)
+ | retry_if_exception_type(openai.error.APIConnectionError)
+ | retry_if_exception_type(openai.error.RateLimitError)
+ | retry_if_exception_type(openai.error.ServiceUnavailableError)
+ ),
+ before_sleep=before_sleep_log(logger, logging.WARNING),
+ )
+
+ def completion_with_retry(self, **kwargs: Any) -> Any:
+ """Use tenacity to retry the completion call."""
+ retry_decorator = self._create_retry_decorator()
+
+ @retry_decorator
+ def _completion_with_retry(**kwargs: Any) -> Any:
+ return self.client.create(**kwargs)
+
+ return _completion_with_retry(**kwargs)
+
+ def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:
+ overall_token_usage: dict = {}
+ for output in llm_outputs:
+ if output is None:
+ # Happens in streaming
+ continue
+ token_usage = output["token_usage"]
+ for k, v in token_usage.items():
+ if k in overall_token_usage:
+ overall_token_usage[k] += v
+ else:
+ overall_token_usage[k] = v
+ return {"token_usage": overall_token_usage}
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ for chunk in self.completion_with_retry(messages=message_dicts, **params):
+ delta = chunk["choices"][0]["delta"]
+ chunk = _convert_delta_to_message_chunk(delta, default_chunk_class)
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(message=chunk)
+ if run_manager:
+ run_manager.on_llm_new_token(str(chunk.content), chunk=cg_chunk)
+ yield cg_chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages=messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+ response = self.completion_with_retry(messages=message_dicts, **params)
+ return self._create_chat_result(response)
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage], stop: Optional[List[str]]
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
+ params = dict(self._invocation_params)
+ if stop is not None:
+ if "stop" in params:
+ raise ValueError("`stop` found in both the input and default params.")
+ params["stop"] = stop
+ message_dicts = [_convert_message_to_dict(m) for m in messages]
+ return message_dicts, params
+
+ def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:
+ generations = []
+ for res in response["choices"]:
+ message = _convert_dict_to_message(res["message"])
+ gen = ChatGeneration(message=message)
+ generations.append(gen)
+ llm_output = {"token_usage": response["usage"]}
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ async for chunk in await acompletion_with_retry(
+ self, messages=message_dicts, **params
+ ):
+ delta = chunk["choices"][0]["delta"]
+ chunk = _convert_delta_to_message_chunk(delta, default_chunk_class)
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(message=chunk)
+ if run_manager:
+ await run_manager.on_llm_new_token(str(chunk.content), chunk=cg_chunk)
+ yield cg_chunk
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._astream(
+ messages=messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+ response = await acompletion_with_retry(self, messages=message_dicts, **params)
+ return self._create_chat_result(response)
+
+ @property
+ def _invocation_params(self) -> Mapping[str, Any]:
+ """Get the parameters used to invoke the model."""
+ jinachat_creds: Dict[str, Any] = {
+ "api_key": self.jinachat_api_key
+ and self.jinachat_api_key.get_secret_value(),
+ "api_base": "https://api.chat.jina.ai/v1",
+ "model": "jinachat",
+ }
+ return {**jinachat_creds, **self._default_params}
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "jinachat"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/kinetica.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/kinetica.py
new file mode 100644
index 0000000000000000000000000000000000000000..2af8b33715d415ffe0321f2a16b69f1f79f5b7ab
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/kinetica.py
@@ -0,0 +1,603 @@
+##
+# Copyright (c) 2024, Chad Juliano, Kinetica DB Inc.
+##
+"""Kinetica SQL generation LLM API."""
+
+import json
+import logging
+import os
+import re
+from importlib.metadata import version
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Pattern, cast
+
+from langchain_core.utils import pre_init
+
+if TYPE_CHECKING:
+ import gpudb
+
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.output_parsers.transform import BaseOutputParser
+from langchain_core.outputs import ChatGeneration, ChatResult, Generation
+from pydantic import BaseModel, ConfigDict, Field
+
+LOG = logging.getLogger(__name__)
+
+# Kinetica pydantic API datatypes
+
+
+class _KdtSuggestContext(BaseModel):
+ """pydantic API request type"""
+
+ table: Optional[str] = Field(default=None, title="Name of table")
+ description: Optional[str] = Field(default=None, title="Table description")
+ columns: List[str] = Field(default=[], title="Table columns list")
+ rules: Optional[List[str]] = Field(
+ default=None, title="Rules that apply to the table."
+ )
+ samples: Optional[Dict] = Field(
+ default=None, title="Samples that apply to the entire context."
+ )
+
+ def to_system_str(self) -> str:
+ lines = []
+ lines.append(f"CREATE TABLE {self.table} AS")
+ lines.append("(")
+
+ if not self.columns or len(self.columns) == 0:
+ ValueError("columns list can't be null.")
+
+ columns = []
+ for column in self.columns:
+ column = column.replace('"', "").strip()
+ columns.append(f" {column}")
+ lines.append(",\n".join(columns))
+ lines.append(");")
+
+ if self.description:
+ lines.append(f"COMMENT ON TABLE {self.table} IS '{self.description}';")
+
+ if self.rules and len(self.rules) > 0:
+ lines.append(
+ f"-- When querying table {self.table} the following rules apply:"
+ )
+ for rule in self.rules:
+ lines.append(f"-- * {rule}")
+
+ result = "\n".join(lines)
+ return result
+
+
+class _KdtSuggestPayload(BaseModel):
+ """pydantic API request type"""
+
+ question: Optional[str] = None
+ context: List[_KdtSuggestContext]
+
+ def get_system_str(self) -> str:
+ lines = []
+ for table_context in self.context:
+ if table_context.table is None:
+ continue
+ context_str = table_context.to_system_str()
+ lines.append(context_str)
+ return "\n\n".join(lines)
+
+ def get_messages(self) -> List[Dict]:
+ messages = []
+ for context in self.context:
+ if context.samples is None:
+ continue
+ for question, answer in context.samples.items():
+ # unescape double quotes
+ answer = answer.replace("''", "'")
+
+ messages.append(dict(role="user", content=question or ""))
+ messages.append(dict(role="assistant", content=answer))
+ return messages
+
+ def to_completion(self) -> Dict:
+ messages = []
+ messages.append(dict(role="system", content=self.get_system_str()))
+ messages.extend(self.get_messages())
+ messages.append(dict(role="user", content=self.question or ""))
+ response = dict(messages=messages)
+ return response
+
+
+class _KdtoSuggestRequest(BaseModel):
+ """pydantic API request type"""
+
+ payload: _KdtSuggestPayload
+
+
+class _KdtMessage(BaseModel):
+ """pydantic API response type"""
+
+ role: str = Field(default="", title="One of [user|assistant|system]")
+ content: str
+
+
+class _KdtChoice(BaseModel):
+ """pydantic API response type"""
+
+ index: int
+ message: Optional[_KdtMessage] = Field(default=None, title="The generated SQL")
+ finish_reason: str
+
+
+class _KdtUsage(BaseModel):
+ """pydantic API response type"""
+
+ prompt_tokens: int
+ completion_tokens: int
+ total_tokens: int
+
+
+class _KdtSqlResponse(BaseModel):
+ """pydantic API response type"""
+
+ id: str
+ object: str
+ created: int
+ model: str
+ choices: List[_KdtChoice]
+ usage: _KdtUsage
+ prompt: str = Field(default="", title="The input question")
+
+
+class _KdtCompletionResponse(BaseModel):
+ """pydantic API response type"""
+
+ status: str
+ data: _KdtSqlResponse
+
+
+class _KineticaLlmFileContextParser:
+ """Parser for Kinetica LLM context datafiles."""
+
+ # parse line into a dict containing role and content
+ PARSER: Pattern = re.compile(r"^<\|(?P\w+)\|>\W*(?P.*)$", re.DOTALL)
+
+ @classmethod
+ def _removesuffix(cls, text: str, suffix: str) -> str:
+ if suffix and text.endswith(suffix):
+ return text[: -len(suffix)]
+ return text
+
+ @classmethod
+ def parse_dialogue_file(cls, input_file: os.PathLike) -> Dict:
+ path = Path(input_file)
+ # schema = path.name.removesuffix(".txt") python 3.9
+ schema = cls._removesuffix(path.name, ".txt")
+
+ lines = open(input_file).read()
+ return cls.parse_dialogue(lines, schema)
+
+ @classmethod
+ def parse_dialogue(cls, text: str, schema: str) -> Dict:
+ messages = []
+ system = None
+
+ lines = text.split("<|end|>")
+ user_message = None
+
+ for idx, line in enumerate(lines):
+ line = line.strip()
+
+ if len(line) == 0:
+ continue
+
+ match = cls.PARSER.match(line)
+ if match is None:
+ raise ValueError(f"Could not find starting token in: {line}")
+
+ groupdict = match.groupdict()
+ role = groupdict["role"]
+
+ if role == "system":
+ if system is not None:
+ raise ValueError(f"Only one system token allowed in: {line}")
+ system = groupdict["content"]
+ elif role == "user":
+ if user_message is not None:
+ raise ValueError(
+ f"Found user token without assistant token: {line}"
+ )
+ user_message = groupdict
+ elif role == "assistant":
+ if user_message is None:
+ raise Exception(f"Found assistant token without user token: {line}")
+ messages.append(user_message)
+ messages.append(groupdict)
+ user_message = None
+ else:
+ raise ValueError(f"Unknown token: {role}")
+
+ return {"schema": schema, "system": system, "messages": messages}
+
+
+class KineticaUtil:
+ """Kinetica utility functions."""
+
+ @classmethod
+ def create_kdbc(
+ cls,
+ url: Optional[str] = None,
+ user: Optional[str] = None,
+ passwd: Optional[str] = None,
+ ) -> "gpudb.GPUdb":
+ """Create a connectica connection object and verify connectivity.
+
+ If None is passed for one or more of the parameters then an attempt will be made
+ to retrieve the value from the related environment variable.
+
+ Args:
+ url: The Kinetica URL or ``KINETICA_URL`` if None.
+ user: The Kinetica user or ``KINETICA_USER`` if None.
+ passwd: The Kinetica password or ``KINETICA_PASSWD`` if None.
+
+ Returns:
+ The Kinetica connection object.
+ """
+
+ try:
+ import gpudb
+ except ModuleNotFoundError:
+ raise ImportError(
+ "Could not import Kinetica python package. "
+ "Please install it with `pip install gpudb`."
+ )
+
+ url = cls._get_env("KINETICA_URL", url)
+ user = cls._get_env("KINETICA_USER", user)
+ passwd = cls._get_env("KINETICA_PASSWD", passwd)
+
+ options = gpudb.GPUdb.Options()
+ options.username = user
+ options.password = passwd
+ options.skip_ssl_cert_verification = True
+ options.disable_failover = True
+ options.logging_level = "INFO"
+ kdbc = gpudb.GPUdb(host=url, options=options)
+
+ LOG.info(
+ "Connected to Kinetica: {}. (api={}, server={})".format(
+ kdbc.get_url(), version("gpudb"), kdbc.server_version
+ )
+ )
+
+ return kdbc
+
+ @classmethod
+ def _get_env(cls, name: str, default: Optional[str]) -> str:
+ """Get an environment variable or use a default."""
+ if default is not None:
+ return default
+
+ result = os.getenv(name)
+ if result is not None:
+ return result
+
+ raise ValueError(
+ f"Parameter was not passed and not found in the environment: {name}"
+ )
+
+
+class ChatKinetica(BaseChatModel):
+ """Kinetica LLM Chat Model API.
+
+ Prerequisites for using this API:
+
+ * The ``gpudb`` and ``typeguard`` packages installed.
+ * A Kinetica DB instance.
+ * Kinetica host specified in ``KINETICA_URL``
+ * Kinetica login specified ``KINETICA_USER``, and ``KINETICA_PASSWD``.
+ * An LLM context that specifies the tables and samples to use for inferencing.
+
+ This API is intended to interact with the Kinetica SqlAssist LLM that supports
+ generation of SQL from natural language.
+
+ In the Kinetica LLM workflow you create an LLM context in the database that provides
+ information needed for infefencing that includes tables, annotations, rules, and
+ samples. Invoking ``load_messages_from_context()`` will retrieve the contxt
+ information from the database so that it can be used to create a chat prompt.
+
+ The chat prompt consists of a ``SystemMessage`` and pairs of
+ ``HumanMessage``/``AIMessage`` that contain the samples which are question/SQL
+ pairs. You can append pairs samples to this list but it is not intended to
+ facilitate a typical natural language conversation.
+
+ When you create a chain from the chat prompt and execute it, the Kinetica LLM will
+ generate SQL from the input. Optionally you can use ``KineticaSqlOutputParser`` to
+ execute the SQL and return the result as a dataframe.
+
+ The following example creates an LLM using the environment variables for the
+ Kinetica connection. This will fail if the API is unable to connect to the database.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models.kinetica import KineticaChatLLM
+ kinetica_llm = KineticaChatLLM()
+
+ If you prefer to pass connection information directly then you can create a
+ connection using ``KineticaUtil.create_kdbc()``.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models.kinetica import (
+ KineticaChatLLM, KineticaUtil)
+ kdbc = KineticaUtil._create_kdbc(url=url, user=user, passwd=passwd)
+ kinetica_llm = KineticaChatLLM(kdbc=kdbc)
+ """
+
+ kdbc: Any = Field(exclude=True)
+ """ Kinetica DB connection. """
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Pydantic object validator."""
+
+ kdbc = values.get("kdbc", None)
+ if kdbc is None:
+ kdbc = KineticaUtil.create_kdbc()
+ values["kdbc"] = kdbc
+ return values
+
+ @property
+ def _llm_type(self) -> str:
+ return "kinetica-sqlassist"
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ return dict(
+ kinetica_version=str(self.kdbc.server_version), api_version=version("gpudb")
+ )
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if stop is not None:
+ raise ValueError("stop kwargs are not permitted.")
+
+ dict_messages = [self._convert_message_to_dict(m) for m in messages]
+ sql_response = self._submit_completion(dict_messages)
+
+ response_message = cast(_KdtMessage, sql_response.choices[0].message)
+ generated_dict = response_message.model_dump()
+
+ generated_message = self._convert_message_from_dict(generated_dict)
+
+ llm_output = dict(
+ input_tokens=sql_response.usage.prompt_tokens,
+ output_tokens=sql_response.usage.completion_tokens,
+ model_name=sql_response.model,
+ )
+ return ChatResult(
+ generations=[ChatGeneration(message=generated_message)],
+ llm_output=llm_output,
+ )
+
+ def load_messages_from_context(self, context_name: str) -> List:
+ """Load a lanchain prompt from a Kinetica context.
+
+ A Kinetica Context is an object created with the Kinetica Workbench UI or with
+ SQL syntax. This function will convert the data in the context to a list of
+ messages that can be used as a prompt. The messages will contain a
+ ``SystemMessage`` followed by pairs of ``HumanMessage``/``AIMessage`` that
+ contain the samples.
+
+ Args:
+ context_name: The name of an LLM context in the database.
+
+ Returns:
+ A list of messages containing the information from the context.
+ """
+
+ # query kinetica for the prompt
+ sql = f"GENERATE PROMPT WITH OPTIONS (CONTEXT_NAMES = '{context_name}')"
+
+ result = self._execute_sql(sql)
+ prompt = result["Prompt"]
+ prompt_json = json.loads(prompt)
+
+ # convert the prompt to messages
+ # request = SuggestRequest.model_validate(prompt_json) # pydantic v2
+
+ request = _KdtoSuggestRequest.model_validate(prompt_json)
+ payload = request.payload
+
+ dict_messages = []
+ dict_messages.append(dict(role="system", content=payload.get_system_str()))
+
+ dict_messages.extend(payload.get_messages())
+ messages = [self._convert_message_from_dict(m) for m in dict_messages]
+ return messages
+
+ def _submit_completion(self, messages: List[Dict]) -> _KdtSqlResponse:
+ """Submit a /chat/completions request to Kinetica."""
+
+ request = dict(messages=messages)
+ request_json = json.dumps(request)
+ response_raw = self.kdbc._GPUdb__submit_request_json(
+ "/chat/completions", request_json
+ )
+ response_json = json.loads(response_raw)
+
+ status = response_json["status"]
+ if status != "OK":
+ message = response_json["message"]
+ match_resp = re.compile(r"response:({.*})")
+ result = match_resp.search(message)
+ if result is not None:
+ response = result.group(1)
+ response_json = json.loads(response)
+ message = response_json["message"]
+ raise ValueError(message)
+
+ data = response_json["data"]
+ # response = CompletionResponse.model_validate(data) # pydantic v2
+ response = _KdtCompletionResponse.model_validate(data)
+ if response.status != "OK":
+ raise ValueError("SQL Generation failed")
+ return response.data
+
+ def _execute_sql(self, sql: str) -> Dict:
+ """Execute an SQL query and return the result."""
+
+ response = self.kdbc.execute_sql_and_decode(
+ sql, limit=1, get_column_major=False
+ )
+
+ status_info = response["status_info"]
+ if status_info["status"] != "OK":
+ message = status_info["message"]
+ raise ValueError(message)
+
+ records = response["records"]
+ if len(records) != 1:
+ raise ValueError("No records returned.")
+
+ record = records[0]
+ response_dict = {}
+ for col, val in record.items():
+ response_dict[col] = val
+ return response_dict
+
+ @classmethod
+ def load_messages_from_datafile(cls, sa_datafile: Path) -> List[BaseMessage]:
+ """Load a lanchain prompt from a Kinetica context datafile."""
+ datafile_dict = _KineticaLlmFileContextParser.parse_dialogue_file(sa_datafile)
+ messages = cls._convert_dict_to_messages(datafile_dict)
+ return messages
+
+ @classmethod
+ def _convert_message_to_dict(cls, message: BaseMessage) -> Dict:
+ """Convert a single message to a BaseMessage."""
+
+ content = cast(str, message.content)
+ if isinstance(message, HumanMessage):
+ role = "user"
+ elif isinstance(message, AIMessage):
+ role = "assistant"
+ elif isinstance(message, SystemMessage):
+ role = "system"
+ else:
+ raise ValueError(f"Got unsupported message type: {message}")
+
+ result_message = dict(role=role, content=content)
+ return result_message
+
+ @classmethod
+ def _convert_message_from_dict(cls, message: Dict) -> BaseMessage:
+ """Convert a single message from a BaseMessage."""
+
+ role = message["role"]
+ content = message["content"]
+ if role == "user":
+ return HumanMessage(content=content)
+ elif role == "assistant":
+ return AIMessage(content=content)
+ elif role == "system":
+ return SystemMessage(content=content)
+ else:
+ raise ValueError(f"Got unsupported role: {role}")
+
+ @classmethod
+ def _convert_dict_to_messages(cls, sa_data: Dict) -> List[BaseMessage]:
+ """Convert a dict to a list of BaseMessages."""
+
+ schema = sa_data["schema"]
+ system = sa_data["system"]
+ messages = sa_data["messages"]
+ LOG.info(f"Importing prompt for schema: {schema}")
+
+ result_list: List[BaseMessage] = []
+ result_list.append(SystemMessage(content=system))
+ result_list.extend([cls._convert_message_from_dict(m) for m in messages])
+ return result_list
+
+
+class KineticaSqlResponse(BaseModel):
+ """Response containing SQL and the fetched data.
+
+ This object is returned by a chain with ``KineticaSqlOutputParser`` and it contains
+ the generated SQL and related Pandas Dataframe fetched from the database.
+ """
+
+ sql: str = Field(default="")
+ """The generated SQL."""
+
+ # dataframe: "pd.DataFrame" = Field(default=None)
+ dataframe: Any = Field(default=None)
+ """The Pandas dataframe containing the fetched data."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+
+class KineticaSqlOutputParser(BaseOutputParser[KineticaSqlResponse]):
+ """Fetch and return data from the Kinetica LLM.
+
+ This object is used as the last element of a chain to execute generated SQL and it
+ will output a ``KineticaSqlResponse`` containing the SQL and a pandas dataframe with
+ the fetched data.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models.kinetica import (
+ KineticaChatLLM, KineticaSqlOutputParser)
+ kinetica_llm = KineticaChatLLM()
+
+ # create chain
+ ctx_messages = kinetica_llm.load_messages_from_context(self.context_name)
+ ctx_messages.append(("human", "{input}"))
+ prompt_template = ChatPromptTemplate.from_messages(ctx_messages)
+ chain = (
+ prompt_template
+ | kinetica_llm
+ | KineticaSqlOutputParser(kdbc=kinetica_llm.kdbc)
+ )
+ sql_response: KineticaSqlResponse = chain.invoke(
+ {"input": "What are the female users ordered by username?"}
+ )
+
+ assert isinstance(sql_response, KineticaSqlResponse)
+ LOG.info(f"SQL Response: {sql_response.sql}")
+ assert isinstance(sql_response.dataframe, pd.DataFrame)
+ """
+
+ kdbc: Any = Field(exclude=True)
+ """ Kinetica DB connection. """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ def parse(self, text: str) -> KineticaSqlResponse:
+ df = self.kdbc.to_df(text)
+ return KineticaSqlResponse(sql=text, dataframe=df)
+
+ def parse_result(
+ self, result: List[Generation], *, partial: bool = False
+ ) -> KineticaSqlResponse:
+ return self.parse(result[0].text)
+
+ @property
+ def _type(self) -> str:
+ return "kinetica_sql_output_parser"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/konko.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/konko.py
new file mode 100644
index 0000000000000000000000000000000000000000..db4f1eded2c8bb2651701780b1fccf8e9c981f45
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/konko.py
@@ -0,0 +1,285 @@
+"""KonkoAI chat wrapper."""
+
+from __future__ import annotations
+
+import logging
+import os
+import warnings
+from typing import (
+ Any,
+ Dict,
+ Iterator,
+ List,
+ Optional,
+ Set,
+ Tuple,
+ Type,
+ Union,
+ cast,
+)
+
+import requests
+from langchain_core.callbacks import (
+ CallbackManagerForLLMRun,
+)
+from langchain_core.messages import AIMessageChunk, BaseMessage, BaseMessageChunk
+from langchain_core.outputs import ChatGenerationChunk, ChatResult
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
+from pydantic import Field, SecretStr
+
+from langchain_community.adapters.openai import (
+ convert_message_to_dict,
+)
+from langchain_community.chat_models.openai import (
+ ChatOpenAI,
+ _convert_delta_to_message_chunk,
+ generate_from_stream,
+)
+from langchain_community.utils.openai import is_openai_v1
+
+DEFAULT_API_BASE = "https://api.konko.ai/v1"
+DEFAULT_MODEL = "meta-llama/Llama-2-13b-chat-hf"
+
+logger = logging.getLogger(__name__)
+
+
+class ChatKonko(ChatOpenAI):
+ """`ChatKonko` Chat large language models API.
+
+ To use, you should have the ``konko`` python package installed, and the
+ environment variable ``KONKO_API_KEY`` and ``OPENAI_API_KEY`` set with your API key.
+
+ Any parameters that are valid to be passed to the konko.create call can be passed
+ in, even if not explicitly saved on this class.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatKonko
+ llm = ChatKonko(model="meta-llama/Llama-2-13b-chat-hf")
+ """
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"konko_api_key": "KONKO_API_KEY", "openai_api_key": "OPENAI_API_KEY"}
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return whether this model can be serialized by Langchain."""
+ return False
+
+ client: Any = None #: :meta private:
+ model: str = Field(default=DEFAULT_MODEL, alias="model")
+ """Model name to use."""
+ temperature: float = 0.7
+ """What sampling temperature to use."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for `create` call not explicitly specified."""
+ openai_api_key: Optional[str] = None
+ konko_api_key: Optional[str] = None
+ max_retries: int = 6
+ """Maximum number of retries to make when generating."""
+ streaming: bool = False
+ """Whether to stream the results or not."""
+ n: int = 1
+ """Number of chat completions to generate for each prompt."""
+ max_tokens: int = 20
+ """Maximum number of tokens to generate."""
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that api key and python package exists in environment."""
+ values["konko_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(values, "konko_api_key", "KONKO_API_KEY")
+ )
+ try:
+ import konko
+
+ except ImportError:
+ raise ImportError(
+ "Could not import konko python package. "
+ "Please install it with `pip install konko`."
+ )
+ try:
+ if is_openai_v1():
+ values["client"] = konko.chat.completions
+ else:
+ values["client"] = konko.ChatCompletion
+ except AttributeError:
+ raise ValueError(
+ "`konko` has no `ChatCompletion` attribute, this is likely "
+ "due to an old version of the konko package. Try upgrading it "
+ "with `pip install --upgrade konko`."
+ )
+
+ if not hasattr(konko, "_is_legacy_openai"):
+ warnings.warn(
+ "You are using an older version of the 'konko' package. "
+ "Please consider upgrading to access new features."
+ )
+
+ if values["n"] < 1:
+ raise ValueError("n must be at least 1.")
+ if values["n"] > 1 and values["streaming"]:
+ raise ValueError("n must be 1 when streaming.")
+ return values
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling Konko API."""
+ return {
+ "model": self.model,
+ "max_tokens": self.max_tokens,
+ "stream": self.streaming,
+ "n": self.n,
+ "temperature": self.temperature,
+ **self.model_kwargs,
+ }
+
+ @staticmethod
+ def get_available_models(
+ konko_api_key: Union[str, SecretStr, None] = None,
+ openai_api_key: Union[str, SecretStr, None] = None,
+ konko_api_base: str = DEFAULT_API_BASE,
+ ) -> Set[str]:
+ """Get available models from Konko API."""
+
+ # Try to retrieve the OpenAI API key if it's not passed as an argument
+ if not openai_api_key:
+ try:
+ openai_api_key = convert_to_secret_str(os.environ["OPENAI_API_KEY"])
+ except KeyError:
+ pass # It's okay if it's not set, we just won't use it
+ elif isinstance(openai_api_key, str):
+ openai_api_key = convert_to_secret_str(openai_api_key)
+
+ # Try to retrieve the Konko API key if it's not passed as an argument
+ if not konko_api_key:
+ try:
+ konko_api_key = convert_to_secret_str(os.environ["KONKO_API_KEY"])
+ except KeyError:
+ raise ValueError(
+ "Konko API key must be passed as keyword argument or "
+ "set in environment variable KONKO_API_KEY."
+ )
+ elif isinstance(konko_api_key, str):
+ konko_api_key = convert_to_secret_str(konko_api_key)
+
+ models_url = f"{konko_api_base}/models"
+
+ headers = {
+ "Authorization": f"Bearer {konko_api_key.get_secret_value()}",
+ }
+
+ if openai_api_key:
+ headers["X-OpenAI-Api-Key"] = cast(
+ SecretStr, openai_api_key
+ ).get_secret_value()
+
+ models_response = requests.get(models_url, headers=headers)
+
+ if models_response.status_code != 200:
+ raise ValueError(
+ f"Error getting models from {models_url}: {models_response.status_code}"
+ )
+
+ return {model["id"] for model in models_response.json()["data"]}
+
+ def completion_with_retry(
+ self, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any
+ ) -> Any:
+ def _completion_with_retry(**kwargs: Any) -> Any:
+ return self.client.create(**kwargs)
+
+ return _completion_with_retry(**kwargs)
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ for chunk in self.completion_with_retry(
+ messages=message_dicts, run_manager=run_manager, **params
+ ):
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], default_chunk_class
+ )
+ finish_reason = choice.get("finish_reason")
+ generation_info = (
+ dict(finish_reason=finish_reason) if finish_reason is not None else None
+ )
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(cg_chunk.text, chunk=cg_chunk)
+ yield cg_chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+ response = self.completion_with_retry(
+ messages=message_dicts, run_manager=run_manager, **params
+ )
+ return self._create_chat_result(response)
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage], stop: Optional[List[str]]
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
+ params = self._client_params
+ if stop is not None:
+ if "stop" in params:
+ raise ValueError("`stop` found in both the input and default params.")
+ params["stop"] = stop
+ message_dicts = [convert_message_to_dict(m) for m in messages]
+ return message_dicts, params
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ return {**{"model_name": self.model}, **self._default_params}
+
+ @property
+ def _client_params(self) -> Dict[str, Any]:
+ """Get the parameters used for the konko client."""
+ return {**self._default_params}
+
+ def _get_invocation_params(
+ self, stop: Optional[List[str]] = None, **kwargs: Any
+ ) -> Dict[str, Any]:
+ """Get the parameters used to invoke the model."""
+ return {
+ "model": self.model,
+ **super()._get_invocation_params(stop=stop),
+ **self._default_params,
+ **kwargs,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "konko-chat"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/litellm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/litellm.py
new file mode 100644
index 0000000000000000000000000000000000000000..c92c8f38ea295a67926fc1f2230eae0b192ecd1c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/litellm.py
@@ -0,0 +1,632 @@
+"""
+Deprecated LiteLLM wrapper.
+
+⭐ Use `pip install langchain-litellm` and import
+ `from langchain_litellm import ChatLiteLLM` instead.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Literal,
+ Mapping,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ Union,
+)
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.language_models.llms import create_base_retry_decorator
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessage,
+ FunctionMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+ ToolCall,
+ ToolCallChunk,
+ ToolMessage,
+)
+from langchain_core.messages.ai import UsageMetadata
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ ChatResult,
+)
+from langchain_core.runnables import Runnable
+from langchain_core.tools import BaseTool
+from langchain_core.utils import get_from_dict_or_env, pre_init
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from pydantic import BaseModel, Field
+
+logger = logging.getLogger(__name__)
+
+
+class ChatLiteLLMException(Exception):
+ """Error with the `LiteLLM I/O` library"""
+
+
+def _create_retry_decorator(
+ llm: ChatLiteLLM,
+ run_manager: Optional[
+ Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]
+ ] = None,
+) -> Callable[[Any], Any]:
+ """Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions"""
+ import litellm
+
+ errors = [
+ litellm.Timeout,
+ litellm.APIError,
+ litellm.APIConnectionError,
+ litellm.RateLimitError,
+ ]
+ return create_base_retry_decorator(
+ error_types=errors, max_retries=llm.max_retries, run_manager=run_manager
+ )
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ role = _dict["role"]
+ if role == "user":
+ return HumanMessage(content=_dict["content"])
+ elif role == "assistant":
+ # Fix for azure
+ # Also OpenAI returns None for tool invocations
+ content = _dict.get("content", "") or ""
+
+ additional_kwargs = {}
+ if _dict.get("function_call"):
+ additional_kwargs["function_call"] = dict(_dict["function_call"])
+
+ if _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = _dict["tool_calls"]
+
+ return AIMessage(content=content, additional_kwargs=additional_kwargs)
+ elif role == "system":
+ return SystemMessage(content=_dict["content"])
+ elif role == "function":
+ return FunctionMessage(content=_dict["content"], name=_dict["name"])
+ else:
+ return ChatMessage(content=_dict["content"], role=role)
+
+
+async def acompletion_with_retry(
+ llm: ChatLiteLLM,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+) -> Any:
+ """Use tenacity to retry the async completion call."""
+ retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
+
+ @retry_decorator
+ async def _completion_with_retry(**kwargs: Any) -> Any:
+ # Use OpenAI's async api https://github.com/openai/openai-python#async-api
+ return await llm.client.acreate(**kwargs)
+
+ return await _completion_with_retry(**kwargs)
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role = _dict.get("role")
+ content = _dict.get("content") or ""
+ if _dict.get("function_call"):
+ additional_kwargs = {"function_call": dict(_dict["function_call"])}
+ elif _dict.get("reasoning_content"):
+ additional_kwargs = {"reasoning_content": _dict["reasoning_content"]}
+ else:
+ additional_kwargs = {}
+
+ tool_call_chunks = []
+ if raw_tool_calls := _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ try:
+ tool_call_chunks = [
+ ToolCallChunk(
+ name=rtc["function"].get("name"),
+ args=rtc["function"].get("arguments"),
+ id=rtc.get("id"),
+ index=rtc["index"],
+ )
+ for rtc in raw_tool_calls
+ ]
+ except KeyError:
+ pass
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_call_chunks=tool_call_chunks,
+ )
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ elif role == "function" or default_class == FunctionMessageChunk:
+ return FunctionMessageChunk(content=content, name=_dict["name"])
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+def _lc_tool_call_to_openai_tool_call(tool_call: ToolCall) -> dict:
+ return {
+ "type": "function",
+ "id": tool_call["id"],
+ "function": {
+ "name": tool_call["name"],
+ "arguments": json.dumps(tool_call["args"]),
+ },
+ }
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ message_dict: Dict[str, Any] = {"content": message.content}
+ if isinstance(message, ChatMessage):
+ message_dict["role"] = message.role
+ elif isinstance(message, HumanMessage):
+ message_dict["role"] = "user"
+ elif isinstance(message, AIMessage):
+ message_dict["role"] = "assistant"
+ if "function_call" in message.additional_kwargs:
+ message_dict["function_call"] = message.additional_kwargs["function_call"]
+ if message.tool_calls:
+ message_dict["tool_calls"] = [
+ _lc_tool_call_to_openai_tool_call(tc) for tc in message.tool_calls
+ ]
+ elif "tool_calls" in message.additional_kwargs:
+ message_dict["tool_calls"] = message.additional_kwargs["tool_calls"]
+ elif isinstance(message, SystemMessage):
+ message_dict["role"] = "system"
+ elif isinstance(message, FunctionMessage):
+ message_dict["role"] = "function"
+ message_dict["name"] = message.name
+ elif isinstance(message, ToolMessage):
+ message_dict["role"] = "tool"
+ message_dict["tool_call_id"] = message.tool_call_id
+ else:
+ raise ValueError(f"Got unknown type {message}")
+ if "name" in message.additional_kwargs:
+ message_dict["name"] = message.additional_kwargs["name"]
+ return message_dict
+
+
+_OPENAI_MODELS = [
+ "o1-mini",
+ "o1-preview",
+ "gpt-4o-mini",
+ "gpt-4o-mini-2024-07-18",
+ "gpt-4o",
+ "gpt-4o-2024-08-06",
+ "gpt-4o-2024-05-13",
+ "gpt-4-turbo",
+ "gpt-4-turbo-preview",
+ "gpt-4-0125-preview",
+ "gpt-4-1106-preview",
+ "gpt-3.5-turbo-1106",
+ "gpt-3.5-turbo",
+ "gpt-3.5-turbo-0301",
+ "gpt-3.5-turbo-0613",
+ "gpt-3.5-turbo-16k",
+ "gpt-3.5-turbo-16k-0613",
+ "gpt-4",
+ "gpt-4-0314",
+ "gpt-4-0613",
+ "gpt-4-32k",
+ "gpt-4-32k-0314",
+ "gpt-4-32k-0613",
+]
+
+
+@deprecated(
+ since="0.3.24",
+ removal="1.0",
+ alternative_import="langchain_litellm.ChatLiteLLM",
+)
+class ChatLiteLLM(BaseChatModel):
+ """DEPRECATED – use `langchain_litellm.ChatLiteLLM` instead."""
+
+ client: Any = None #: :meta private:
+ model: str = "gpt-3.5-turbo"
+ model_name: Optional[str] = None
+ """Model name to use."""
+ openai_api_key: Optional[str] = None
+ azure_api_key: Optional[str] = None
+ anthropic_api_key: Optional[str] = None
+ replicate_api_key: Optional[str] = None
+ cohere_api_key: Optional[str] = None
+ openrouter_api_key: Optional[str] = None
+ api_key: Optional[str] = None
+ streaming: bool = False
+ api_base: Optional[str] = None
+ organization: Optional[str] = None
+ custom_llm_provider: Optional[str] = None
+ request_timeout: Optional[Union[float, Tuple[float, float]]] = None
+ temperature: Optional[float] = None
+ """Run inference with this temperature. Must be in the closed
+ interval [0.0, 1.0]."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for API call not explicitly specified."""
+ top_p: Optional[float] = None
+ """Decode using nucleus sampling: consider the smallest set of tokens whose
+ probability sum is at least top_p. Must be in the closed interval [0.0, 1.0]."""
+ top_k: Optional[int] = None
+ """Decode using top-k sampling: consider the set of top_k most probable tokens.
+ Must be positive."""
+ n: Optional[int] = None
+ """Number of chat completions to generate for each prompt. Note that the API may
+ not return the full n completions if duplicates are generated."""
+ max_tokens: Optional[int] = None
+
+ max_retries: int = 1
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling OpenAI API."""
+ set_model_value = self.model
+ if self.model_name is not None:
+ set_model_value = self.model_name
+ return {
+ "model": set_model_value,
+ "force_timeout": self.request_timeout,
+ "max_tokens": self.max_tokens,
+ "stream": self.streaming,
+ "n": self.n,
+ "temperature": self.temperature,
+ "custom_llm_provider": self.custom_llm_provider,
+ **self.model_kwargs,
+ }
+
+ @property
+ def _client_params(self) -> Dict[str, Any]:
+ """Get the parameters used for the openai client."""
+ set_model_value = self.model
+ if self.model_name is not None:
+ set_model_value = self.model_name
+ self.client.api_base = self.api_base
+ self.client.api_key = self.api_key
+ for named_api_key in [
+ "openai_api_key",
+ "azure_api_key",
+ "anthropic_api_key",
+ "replicate_api_key",
+ "cohere_api_key",
+ "openrouter_api_key",
+ ]:
+ if api_key_value := getattr(self, named_api_key):
+ setattr(
+ self.client,
+ named_api_key.replace("_api_key", "_key"),
+ api_key_value,
+ )
+ self.client.organization = self.organization
+ creds: Dict[str, Any] = {
+ "model": set_model_value,
+ "force_timeout": self.request_timeout,
+ "api_base": self.api_base,
+ }
+ return {**self._default_params, **creds}
+
+ def completion_with_retry(
+ self, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any
+ ) -> Any:
+ """Use tenacity to retry the completion call."""
+ retry_decorator = _create_retry_decorator(self, run_manager=run_manager)
+
+ @retry_decorator
+ def _completion_with_retry(**kwargs: Any) -> Any:
+ return self.client.completion(**kwargs)
+
+ return _completion_with_retry(**kwargs)
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate api key, python package exists, temperature, top_p, and top_k."""
+ try:
+ import litellm
+ except ImportError:
+ raise ChatLiteLLMException(
+ "Could not import litellm python package. "
+ "Please install it with `pip install litellm`"
+ )
+
+ values["openai_api_key"] = get_from_dict_or_env(
+ values, "openai_api_key", "OPENAI_API_KEY", default=""
+ )
+ values["azure_api_key"] = get_from_dict_or_env(
+ values, "azure_api_key", "AZURE_API_KEY", default=""
+ )
+ values["anthropic_api_key"] = get_from_dict_or_env(
+ values, "anthropic_api_key", "ANTHROPIC_API_KEY", default=""
+ )
+ values["replicate_api_key"] = get_from_dict_or_env(
+ values, "replicate_api_key", "REPLICATE_API_KEY", default=""
+ )
+ values["openrouter_api_key"] = get_from_dict_or_env(
+ values, "openrouter_api_key", "OPENROUTER_API_KEY", default=""
+ )
+ values["cohere_api_key"] = get_from_dict_or_env(
+ values, "cohere_api_key", "COHERE_API_KEY", default=""
+ )
+ values["huggingface_api_key"] = get_from_dict_or_env(
+ values, "huggingface_api_key", "HUGGINGFACE_API_KEY", default=""
+ )
+ values["together_ai_api_key"] = get_from_dict_or_env(
+ values, "together_ai_api_key", "TOGETHERAI_API_KEY", default=""
+ )
+ values["client"] = litellm
+
+ if values["temperature"] is not None and not 0 <= values["temperature"] <= 1:
+ raise ValueError("temperature must be in the range [0.0, 1.0]")
+
+ if values["top_p"] is not None and not 0 <= values["top_p"] <= 1:
+ raise ValueError("top_p must be in the range [0.0, 1.0]")
+
+ if values["top_k"] is not None and values["top_k"] <= 0:
+ raise ValueError("top_k must be positive")
+
+ return values
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+ response = self.completion_with_retry(
+ messages=message_dicts, run_manager=run_manager, **params
+ )
+ return self._create_chat_result(response)
+
+ def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:
+ generations = []
+ token_usage = response.get("usage", {})
+ for res in response["choices"]:
+ message = _convert_dict_to_message(res["message"])
+ if isinstance(message, AIMessage):
+ message.response_metadata = {
+ "model_name": self.model_name or self.model
+ }
+ message.usage_metadata = _create_usage_metadata(token_usage)
+ gen = ChatGeneration(
+ message=message,
+ generation_info=dict(finish_reason=res.get("finish_reason")),
+ )
+ generations.append(gen)
+ set_model_value = self.model
+ if self.model_name is not None:
+ set_model_value = self.model_name
+ llm_output = {"token_usage": token_usage, "model": set_model_value}
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage], stop: Optional[List[str]]
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
+ params = self._client_params
+ if stop is not None:
+ if "stop" in params:
+ raise ValueError("`stop` found in both the input and default params.")
+ params["stop"] = stop
+ message_dicts = [_convert_message_to_dict(m) for m in messages]
+ return message_dicts, params
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ added_model_name = False
+ for chunk in self.completion_with_retry(
+ messages=message_dicts, run_manager=run_manager, **params
+ ):
+ if not isinstance(chunk, dict):
+ chunk = chunk.model_dump()
+ if len(chunk["choices"]) == 0:
+ continue
+ delta = chunk["choices"][0]["delta"]
+ usage = chunk.get("usage", {})
+ chunk = _convert_delta_to_message_chunk(delta, default_chunk_class)
+ if isinstance(chunk, AIMessageChunk):
+ if not added_model_name:
+ chunk.response_metadata = {
+ "model_name": self.model_name or self.model
+ }
+ added_model_name = True
+ chunk.usage_metadata = _create_usage_metadata(usage)
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(message=chunk)
+ if run_manager:
+ run_manager.on_llm_new_token(str(chunk.content), chunk=cg_chunk)
+ yield cg_chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ added_model_name = False
+ async for chunk in await acompletion_with_retry(
+ self, messages=message_dicts, run_manager=run_manager, **params
+ ):
+ if not isinstance(chunk, dict):
+ chunk = chunk.model_dump()
+ if len(chunk["choices"]) == 0:
+ continue
+ delta = chunk["choices"][0]["delta"]
+ usage = chunk.get("usage", {})
+ chunk = _convert_delta_to_message_chunk(delta, default_chunk_class)
+ if isinstance(chunk, AIMessageChunk):
+ if not added_model_name:
+ chunk.response_metadata = {
+ "model_name": self.model_name or self.model
+ }
+ added_model_name = True
+ chunk.usage_metadata = _create_usage_metadata(usage)
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(message=chunk)
+ if run_manager:
+ await run_manager.on_llm_new_token(str(chunk.content), chunk=cg_chunk)
+ yield cg_chunk
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._astream(
+ messages=messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+ response = await acompletion_with_retry(
+ self, messages=message_dicts, run_manager=run_manager, **params
+ )
+ return self._create_chat_result(response)
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ tool_choice: Optional[
+ Union[dict, str, Literal["auto", "none", "required", "any"], bool]
+ ] = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model.
+
+ LiteLLM expects tools argument in OpenAI format.
+
+ Args:
+ tools: A list of tool definitions to bind to this chat model.
+ Can be a dictionary, pydantic model, callable, or BaseTool. Pydantic
+ models, callables, and BaseTools will be automatically converted to
+ their schema dictionary representation.
+ tool_choice: Which tool to require the model to call. Options are:
+ - str of the form ``"<>"``: calls <> tool.
+ - ``"auto"``:
+ automatically selects a tool (including no tool).
+ - ``"none"``:
+ does not call a tool.
+ - ``"any"`` or ``"required"`` or ``True``:
+ forces least one tool to be called.
+ - dict of the form:
+ ``{"type": "function", "function": {"name": <>}}``
+ - ``False`` or ``None``: no effect
+ **kwargs: Any additional parameters to pass to the
+ :class:`~langchain.runnable.Runnable` constructor.
+ """
+
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+
+ # In case of openai if tool_choice is `any` or if bool has been provided we
+ # change it to `required` as that is suppored by openai.
+ if (
+ (self.model is not None and "azure" in self.model)
+ or (self.model_name is not None and "azure" in self.model_name)
+ or (self.model is not None and self.model in _OPENAI_MODELS)
+ or (self.model_name is not None and self.model_name in _OPENAI_MODELS)
+ ) and (tool_choice == "any" or isinstance(tool_choice, bool)):
+ tool_choice = "required"
+ # If tool_choice is bool apart from openai we make it `any`
+ elif isinstance(tool_choice, bool):
+ tool_choice = "any"
+ elif isinstance(tool_choice, dict):
+ tool_names = [
+ formatted_tool["function"]["name"] for formatted_tool in formatted_tools
+ ]
+ if not any(
+ tool_name == tool_choice["function"]["name"] for tool_name in tool_names
+ ):
+ raise ValueError(
+ f"Tool choice {tool_choice} was specified, but the only "
+ f"provided tools were {tool_names}."
+ )
+ return super().bind(tools=formatted_tools, tool_choice=tool_choice, **kwargs)
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ set_model_value = self.model
+ if self.model_name is not None:
+ set_model_value = self.model_name
+ return {
+ "model": set_model_value,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "top_k": self.top_k,
+ "n": self.n,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ return "litellm-chat"
+
+
+def _create_usage_metadata(token_usage: Mapping[str, Any]) -> UsageMetadata:
+ input_tokens = token_usage.get("prompt_tokens", 0)
+ output_tokens = token_usage.get("completion_tokens", 0)
+ return UsageMetadata(
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ total_tokens=input_tokens + output_tokens,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/litellm_router.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/litellm_router.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fce0d59c0c5277ab51c4f6ea4241ce908f2649e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/litellm_router.py
@@ -0,0 +1,230 @@
+"""
+Deprecated LiteLLM wrapper.
+
+⭐ Use `pip install langchain-litellm` and import
+ `from langchain_litellm import ChatLiteLLMRouter` instead.
+"""
+
+from typing import Any, AsyncIterator, Iterator, List, Mapping, Optional, Type
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import AIMessageChunk, BaseMessage, BaseMessageChunk
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+
+from langchain_community.chat_models.litellm import (
+ ChatLiteLLM,
+ _convert_delta_to_message_chunk,
+ _convert_dict_to_message,
+)
+
+token_usage_key_name = "token_usage" # nosec # incorrectly flagged as password
+model_extra_key_name = "model_extra" # nosec # incorrectly flagged as password
+
+
+def get_llm_output(usage: Any, **params: Any) -> dict:
+ """Get llm output from usage and params."""
+ llm_output = {token_usage_key_name: usage}
+ # copy over metadata (metadata came from router completion call)
+ metadata = params["metadata"]
+ for key in metadata:
+ if key not in llm_output:
+ # if token usage in metadata, prefer metadata's copy of it
+ llm_output[key] = metadata[key]
+ return llm_output
+
+
+@deprecated(
+ since="0.3.24",
+ removal="1.0",
+ alternative_import="langchain_litellm.ChatLiteLLMRouter",
+)
+class ChatLiteLLMRouter(ChatLiteLLM):
+ """DEPRECATED – use `langchain_litellm.ChatLiteLLMRouter` instead."""
+
+ router: Any
+
+ def __init__(self, *, router: Any, **kwargs: Any) -> None:
+ """Construct Chat LiteLLM Router."""
+ super().__init__(router=router, **kwargs) # type: ignore[call-arg]
+ self.router = router
+
+ @property
+ def _llm_type(self) -> str:
+ return "LiteLLMRouter"
+
+ def _prepare_params_for_router(self, params: Any) -> None:
+ # allow the router to set api_base based on its model choice
+ api_base_key_name = "api_base"
+ if api_base_key_name in params and params[api_base_key_name] is None:
+ del params[api_base_key_name]
+
+ # add metadata so router can fill it below
+ params.setdefault("metadata", {})
+
+ def set_default_model(self, model_name: str) -> None:
+ """Set the default model to use for completion calls.
+
+ Sets `self.model` to `model_name` if it is in the litellm router's
+ (`self.router`) model list. This provides the default model to use
+ for completion calls if no `model` kwarg is provided.
+ """
+ model_list = self.router.model_list
+ if not model_list:
+ raise ValueError("model_list is None or empty.")
+ for entry in model_list:
+ if entry["model_name"] == model_name:
+ self.model = model_name
+ return
+ raise ValueError(f"Model {model_name} not found in model_list.")
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+ self._prepare_params_for_router(params)
+
+ response = self.router.completion(
+ messages=message_dicts,
+ **params,
+ )
+ return self._create_chat_result(response, **params)
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+ self._prepare_params_for_router(params)
+
+ for chunk in self.router.completion(messages=message_dicts, **params):
+ if len(chunk["choices"]) == 0:
+ continue
+ delta = chunk["choices"][0]["delta"]
+ chunk = _convert_delta_to_message_chunk(delta, default_chunk_class)
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(message=chunk)
+ if run_manager:
+ run_manager.on_llm_new_token(
+ str(chunk.content), chunk=cg_chunk, **params
+ )
+ yield cg_chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+ self._prepare_params_for_router(params)
+
+ async for chunk in await self.router.acompletion(
+ messages=message_dicts, **params
+ ):
+ if len(chunk["choices"]) == 0:
+ continue
+ delta = chunk["choices"][0]["delta"]
+ chunk = _convert_delta_to_message_chunk(delta, default_chunk_class)
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(message=chunk)
+ if run_manager:
+ await run_manager.on_llm_new_token(
+ str(chunk.content), chunk=cg_chunk, **params
+ )
+ yield cg_chunk
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._astream(
+ messages=messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+ self._prepare_params_for_router(params)
+
+ response = await self.router.acompletion(
+ messages=message_dicts,
+ **params,
+ )
+ return self._create_chat_result(response, **params)
+
+ # from
+ # https://github.com/langchain-ai/langchain/blob/master/libs/community/langchain_community/chat_models/openai.py
+ # but modified to handle LiteLLM Usage class
+ def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:
+ overall_token_usage: dict = {}
+ system_fingerprint = None
+ for output in llm_outputs:
+ if output is None:
+ # Happens in streaming
+ continue
+ token_usage = output["token_usage"]
+ if token_usage is not None:
+ # get dict from LiteLLM Usage class
+ for k, v in token_usage.model_dump().items():
+ if k in overall_token_usage and overall_token_usage[k] is not None:
+ overall_token_usage[k] += v
+ else:
+ overall_token_usage[k] = v
+ if system_fingerprint is None:
+ system_fingerprint = output.get("system_fingerprint")
+ combined = {"token_usage": overall_token_usage, "model_name": self.model}
+ if system_fingerprint:
+ combined["system_fingerprint"] = system_fingerprint
+ return combined
+
+ def _create_chat_result(
+ self, response: Mapping[str, Any], **params: Any
+ ) -> ChatResult:
+ from litellm.utils import Usage
+
+ generations = []
+ for res in response["choices"]:
+ message = _convert_dict_to_message(res["message"])
+ gen = ChatGeneration(
+ message=message,
+ generation_info=dict(finish_reason=res.get("finish_reason")),
+ )
+ generations.append(gen)
+ token_usage = response.get("usage", Usage(prompt_tokens=0, total_tokens=0))
+ llm_output = get_llm_output(token_usage, **params)
+ return ChatResult(generations=generations, llm_output=llm_output)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/llama_edge.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/llama_edge.py
new file mode 100644
index 0000000000000000000000000000000000000000..85428ff0c44f8a4dd3da35dbecaff5c3fb93eb31
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/llama_edge.py
@@ -0,0 +1,241 @@
+import json
+import logging
+import re
+from typing import Any, Dict, Iterator, List, Mapping, Optional, Type
+
+import requests
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.utils import get_pydantic_field_names
+from pydantic import ConfigDict, model_validator
+
+logger = logging.getLogger(__name__)
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ role = _dict["role"]
+ if role == "user":
+ return HumanMessage(content=_dict["content"])
+ elif role == "assistant":
+ return AIMessage(content=_dict.get("content", "") or "")
+ else:
+ return ChatMessage(content=_dict["content"], role=role)
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ message_dict: Dict[str, Any]
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ else:
+ raise TypeError(f"Got unknown type {message}")
+
+ return message_dict
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role = _dict.get("role")
+ content = _dict.get("content") or ""
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content)
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+class LlamaEdgeChatService(BaseChatModel):
+ """Chat with LLMs via `llama-api-server`
+
+ For the information about `llama-api-server`, visit https://github.com/second-state/LlamaEdge
+ """
+
+ request_timeout: int = 60
+ """request timeout for chat http requests"""
+ service_url: Optional[str] = None
+ """URL of WasmChat service"""
+ model: str = "NA"
+ """model name, default is `NA`."""
+ streaming: bool = False
+ """Whether to stream the results or not."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def build_extra(cls, values: Dict[str, Any]) -> Any:
+ """Build extra kwargs from additional params that were passed in."""
+ all_required_field_names = get_pydantic_field_names(cls)
+ extra = values.get("model_kwargs", {})
+ for field_name in list(values):
+ if field_name in extra:
+ raise ValueError(f"Found {field_name} supplied twice.")
+ if field_name not in all_required_field_names:
+ logger.warning(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please confirm that {field_name} is what you intended."""
+ )
+ extra[field_name] = values.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
+ if invalid_model_kwargs:
+ raise ValueError(
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+
+ values["model_kwargs"] = extra
+ return values
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages=messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ res = self._chat(messages, **kwargs)
+
+ if res.status_code != 200:
+ raise ValueError(f"Error code: {res.status_code}, reason: {res.reason}")
+
+ response = res.json()
+
+ return self._create_chat_result(response)
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ res = self._chat(messages, **kwargs)
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ substring = '"object":"chat.completion.chunk"}'
+ for line in res.iter_lines():
+ chunks = []
+ if line:
+ json_string = line.decode("utf-8")
+
+ # Find all positions of the substring
+ positions = [m.start() for m in re.finditer(substring, json_string)]
+ positions = [-1 * len(substring)] + positions
+
+ for i in range(len(positions) - 1):
+ chunk = json.loads(
+ json_string[
+ positions[i] + len(substring) : positions[i + 1]
+ + len(substring)
+ ]
+ )
+ chunks.append(chunk)
+
+ for chunk in chunks:
+ if not isinstance(chunk, dict):
+ chunk = chunk.dict()
+ if len(chunk["choices"]) == 0:
+ continue
+
+ choice = chunk["choices"][0]
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], default_chunk_class
+ )
+ if (
+ choice.get("finish_reason") is not None
+ and choice.get("finish_reason") == "stop"
+ ):
+ break
+ finish_reason = choice.get("finish_reason")
+ generation_info = (
+ dict(finish_reason=finish_reason)
+ if finish_reason is not None
+ else None
+ )
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(cg_chunk.text, chunk=cg_chunk)
+ yield cg_chunk
+
+ def _chat(self, messages: List[BaseMessage], **kwargs: Any) -> requests.Response:
+ if self.service_url is None:
+ res = requests.models.Response()
+ res.status_code = 503
+ res.reason = "The IP address or port of the chat service is incorrect."
+ return res
+
+ service_url = f"{self.service_url}/v1/chat/completions"
+
+ if self.streaming:
+ payload = {
+ "model": self.model,
+ "messages": [_convert_message_to_dict(m) for m in messages],
+ "stream": self.streaming,
+ }
+ else:
+ payload = {
+ "model": self.model,
+ "messages": [_convert_message_to_dict(m) for m in messages],
+ }
+
+ res = requests.post(
+ url=service_url,
+ timeout=self.request_timeout,
+ headers={
+ "accept": "application/json",
+ "Content-Type": "application/json",
+ },
+ data=json.dumps(payload),
+ )
+
+ return res
+
+ def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:
+ message = _convert_dict_to_message(response["choices"][0].get("message"))
+ generations = [ChatGeneration(message=message)]
+
+ token_usage = response["usage"]
+ llm_output = {"token_usage": token_usage, "model": self.model}
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ @property
+ def _llm_type(self) -> str:
+ return "wasm-chat"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/llamacpp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/llamacpp.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec954360a37695aecb66ca0fc5819953f19602dc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/llamacpp.py
@@ -0,0 +1,818 @@
+import json
+from operator import itemgetter
+from pathlib import Path
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+ cast,
+)
+
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessage,
+ FunctionMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+ ToolMessage,
+ ToolMessageChunk,
+)
+from langchain_core.messages.tool import InvalidToolCall, ToolCall, ToolCallChunk
+from langchain_core.output_parsers.base import OutputParserLike
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ PydanticToolsParser,
+ make_invalid_tool_call,
+ parse_tool_call,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
+from langchain_core.tools import BaseTool
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from langchain_core.utils.pydantic import is_basemodel_subclass
+from pydantic import (
+ BaseModel,
+ Field,
+ model_validator,
+)
+from typing_extensions import Self
+
+
+class ChatLlamaCpp(BaseChatModel):
+ """llama.cpp model.
+
+ To use, you should have the llama-cpp-python library installed, and provide the
+ path to the Llama model as a named parameter to the constructor.
+ Check out: https://github.com/abetlen/llama-cpp-python
+
+ """
+
+ client: Any = None #: :meta private:
+
+ model_path: str
+ """The path to the Llama model file."""
+
+ lora_base: Optional[str] = None
+ """The path to the Llama LoRA base model."""
+
+ lora_path: Optional[str] = None
+ """The path to the Llama LoRA. If None, no LoRa is loaded."""
+
+ n_ctx: int = 512
+ """Token context window."""
+
+ n_parts: int = -1
+ """Number of parts to split the model into.
+ If -1, the number of parts is automatically determined."""
+
+ seed: int = -1
+ """Seed. If -1, a random seed is used."""
+
+ f16_kv: bool = True
+ """Use half-precision for key/value cache."""
+
+ logits_all: bool = False
+ """Return logits for all tokens, not just the last token."""
+
+ vocab_only: bool = False
+ """Only load the vocabulary, no weights."""
+
+ use_mlock: bool = False
+ """Force system to keep model in RAM."""
+
+ n_threads: Optional[int] = None
+ """Number of threads to use.
+ If None, the number of threads is automatically determined."""
+
+ n_batch: int = 8
+ """Number of tokens to process in parallel.
+ Should be a number between 1 and n_ctx."""
+
+ n_gpu_layers: Optional[int] = None
+ """Number of layers to be loaded into gpu memory. Default None."""
+
+ suffix: Optional[str] = None
+ """A suffix to append to the generated text. If None, no suffix is appended."""
+
+ max_tokens: int = 256
+ """The maximum number of tokens to generate."""
+
+ temperature: float = 0.8
+ """The temperature to use for sampling."""
+
+ top_p: float = 0.95
+ """The top-p value to use for sampling."""
+
+ logprobs: Optional[int] = None
+ """The number of logprobs to return. If None, no logprobs are returned."""
+
+ echo: bool = False
+ """Whether to echo the prompt."""
+
+ stop: Optional[List[str]] = None
+ """A list of strings to stop generation when encountered."""
+
+ repeat_penalty: float = 1.1
+ """The penalty to apply to repeated tokens."""
+
+ top_k: int = 40
+ """The top-k value to use for sampling."""
+
+ last_n_tokens_size: int = 64
+ """The number of tokens to look back when applying the repeat_penalty."""
+
+ use_mmap: bool = True
+ """Whether to keep the model loaded in RAM"""
+
+ rope_freq_scale: float = 1.0
+ """Scale factor for rope sampling."""
+
+ rope_freq_base: float = 10000.0
+ """Base frequency for rope sampling."""
+
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Any additional parameters to pass to llama_cpp.Llama."""
+
+ streaming: bool = True
+ """Whether to stream the results, token by token."""
+
+ grammar_path: Optional[Union[str, Path]] = None
+ """
+ grammar_path: Path to the .gbnf file that defines formal grammars
+ for constraining model outputs. For instance, the grammar can be used
+ to force the model to generate valid JSON or to speak exclusively in emojis. At most
+ one of grammar_path and grammar should be passed in.
+ """
+ grammar: Any = None
+ """
+ grammar: formal grammar for constraining model outputs. For instance, the grammar
+ can be used to force the model to generate valid JSON or to speak exclusively in
+ emojis. At most one of grammar_path and grammar should be passed in.
+ """
+
+ verbose: bool = True
+ """Print verbose output to stderr."""
+
+ @model_validator(mode="after")
+ def validate_environment(self) -> Self:
+ """Validate that llama-cpp-python library is installed."""
+ try:
+ from llama_cpp import Llama, LlamaGrammar
+ except ImportError:
+ raise ImportError(
+ "Could not import llama-cpp-python library. "
+ "Please install the llama-cpp-python library to "
+ "use this embedding model: pip install llama-cpp-python"
+ )
+
+ model_path = self.model_path
+ model_param_names = [
+ "rope_freq_scale",
+ "rope_freq_base",
+ "lora_path",
+ "lora_base",
+ "n_ctx",
+ "n_parts",
+ "seed",
+ "f16_kv",
+ "logits_all",
+ "vocab_only",
+ "use_mlock",
+ "n_threads",
+ "n_batch",
+ "use_mmap",
+ "last_n_tokens_size",
+ "verbose",
+ ]
+ model_params = {k: getattr(self, k) for k in model_param_names}
+ # For backwards compatibility, only include if non-null.
+ if self.n_gpu_layers is not None:
+ model_params["n_gpu_layers"] = self.n_gpu_layers
+
+ model_params.update(self.model_kwargs)
+
+ try:
+ self.client = Llama(model_path, **model_params)
+ except Exception as e:
+ raise ValueError(
+ f"Could not load Llama model from path: {model_path}. "
+ f"Received error {e}"
+ )
+
+ if self.grammar and self.grammar_path:
+ grammar = self.grammar
+ grammar_path = self.grammar_path
+ raise ValueError(
+ "Can only pass in one of grammar and grammar_path. Received "
+ f"{grammar=} and {grammar_path=}."
+ )
+ elif isinstance(self.grammar, str):
+ self.grammar = LlamaGrammar.from_string(self.grammar)
+ elif self.grammar_path:
+ self.grammar = LlamaGrammar.from_file(self.grammar_path)
+ else:
+ pass
+ return self
+
+ def _get_parameters(self, stop: Optional[List[str]]) -> Dict[str, Any]:
+ """
+ Performs sanity check, preparing parameters in format needed by llama_cpp.
+
+ Returns:
+ Dictionary containing the combined parameters.
+ """
+
+ params = self._default_params
+
+ # llama_cpp expects the "stop" key not this, so we remove it:
+ stop_sequences = params.pop("stop_sequences")
+
+ # then sets it as configured, or default to an empty list:
+ params["stop"] = stop or stop_sequences or self.stop or []
+
+ return params
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage]
+ ) -> List[Dict[str, Any]]:
+ message_dicts = [_convert_message_to_dict(m) for m in messages]
+
+ return message_dicts
+
+ def _create_chat_result(self, response: dict) -> ChatResult:
+ generations = []
+ for res in response["choices"]:
+ message = _convert_dict_to_message(res["message"])
+ generation_info = dict(finish_reason=res.get("finish_reason"))
+ if "logprobs" in res:
+ generation_info["logprobs"] = res["logprobs"]
+ gen = ChatGeneration(message=message, generation_info=generation_info)
+ generations.append(gen)
+ token_usage = response.get("usage", {})
+ llm_output = {
+ "token_usage": token_usage,
+ # "system_fingerprint": response.get("system_fingerprint", ""),
+ }
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ params = {**self._get_parameters(stop), **kwargs}
+
+ # Check tool_choice is whether available, if yes then run no stream with tool
+ # calling
+ if self.streaming and not params.get("tool_choice"):
+ stream_iter = self._stream(messages, run_manager=run_manager, **kwargs)
+ return generate_from_stream(stream_iter)
+
+ message_dicts = self._create_message_dicts(messages)
+
+ response = self.client.create_chat_completion(messages=message_dicts, **params)
+
+ return self._create_chat_result(response)
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ params = {**self._get_parameters(stop), **kwargs}
+ message_dicts = self._create_message_dicts(messages)
+
+ result = self.client.create_chat_completion(
+ messages=message_dicts, stream=True, **params
+ )
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ count = 0
+ for chunk in result:
+ count += 1
+ if not isinstance(chunk, dict):
+ chunk = chunk.model_dump()
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ if choice["delta"] is None:
+ continue
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], default_chunk_class
+ )
+ generation_info = {}
+ if finish_reason := choice.get("finish_reason"):
+ generation_info["finish_reason"] = finish_reason
+ logprobs = choice.get("logprobs")
+ if logprobs:
+ generation_info["logprobs"] = logprobs
+ default_chunk_class = chunk.__class__
+ chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info or None
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text, chunk=chunk, logprobs=logprobs)
+ yield chunk
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ *,
+ tool_choice: Optional[Union[dict, bool, str]] = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model
+
+ tool_choice: does not currently support "any", "auto" choices like OpenAI
+ tool-calling API. should be a dict of the form to force this tool
+ {"type": "function", "function": {"name": <>}}.
+ """
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ tool_names = [ft["function"]["name"] for ft in formatted_tools]
+ if tool_choice:
+ if isinstance(tool_choice, dict):
+ if not any(
+ tool_choice["function"]["name"] == name for name in tool_names
+ ):
+ raise ValueError(
+ f"Tool choice {tool_choice=} was specified, but the only "
+ f"provided tools were {tool_names}."
+ )
+ elif isinstance(tool_choice, str):
+ chosen = [
+ f for f in formatted_tools if f["function"]["name"] == tool_choice
+ ]
+ if not chosen:
+ raise ValueError(
+ f"Tool choice {tool_choice=} was specified, but the only "
+ f"provided tools were {tool_names}."
+ )
+ elif isinstance(tool_choice, bool):
+ if len(formatted_tools) > 1:
+ raise ValueError(
+ "tool_choice=True can only be specified when a single tool is "
+ f"passed in. Received {len(tools)} tools."
+ )
+ tool_choice = formatted_tools[0]
+ else:
+ raise ValueError(
+ """Unrecognized tool_choice type. Expected dict having format like
+ this {"type": "function", "function": {"name": <>}}"""
+ f"Received: {tool_choice}"
+ )
+
+ kwargs["tool_choice"] = tool_choice
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ return super().bind(tools=formatted_tools, **kwargs)
+
+ def with_structured_output(
+ self,
+ schema: Optional[Union[Dict, Type[BaseModel]]] = None,
+ *,
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, Union[Dict, BaseModel]]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema: The output schema as a dict or a Pydantic class. If a Pydantic class
+ then the model output will be an object of that class. If a dict then
+ the model output will be a dict. With a Pydantic class the returned
+ attributes will be validated, whereas with a dict they will not be. If
+ `method` is "function_calling" and `schema` is a dict, then the dict
+ must match the OpenAI function-calling spec or be a valid JSON schema
+ with top level 'title' and 'description' keys specified.
+ include_raw: If False then only the parsed structured output is returned. If
+ an error occurs during model output parsing it will be raised. If True
+ then both the raw model response (a BaseMessage) and the parsed model
+ response will be returned. If an error occurs during output parsing it
+ will be caught and returned as well. The final output is always a dict
+ with keys "raw", "parsed", and "parsing_error".
+ kwargs: Any other args to bind to model, ``self.bind(..., **kwargs)``.
+
+ Returns:
+ A Runnable that takes any ChatModel input and returns as output:
+
+ If include_raw is True then a dict with keys:
+ raw: BaseMessage
+ parsed: Optional[_DictOrPydantic]
+ parsing_error: Optional[BaseException]
+
+ If include_raw is False then just _DictOrPydantic is returned,
+ where _DictOrPydantic depends on the schema:
+
+ If schema is a Pydantic class then _DictOrPydantic is the Pydantic
+ class.
+
+ If schema is a dict then _DictOrPydantic is a dict.
+
+ Example: Pydantic schema (include_raw=False):
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatLlamaCpp
+ from pydantic import BaseModel
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+ answer: str
+ justification: str
+
+ llm = ChatLlamaCpp(
+ temperature=0.,
+ model_path="./SanctumAI-meta-llama-3-8b-instruct.Q8_0.gguf",
+ n_ctx=10000,
+ n_gpu_layers=4,
+ n_batch=200,
+ max_tokens=512,
+ n_threads=multiprocessing.cpu_count() - 1,
+ repeat_penalty=1.5,
+ top_p=0.5,
+ stop=["<|end_of_text|>", "<|eot_id|>"],
+ )
+ structured_llm = llm.with_structured_output(AnswerWithJustification)
+
+ structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
+
+ # -> AnswerWithJustification(
+ # answer='They weigh the same',
+ # justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'
+ # )
+
+ Example: Pydantic schema (include_raw=True):
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatLlamaCpp
+ from pydantic import BaseModel
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+ answer: str
+ justification: str
+
+ llm = ChatLlamaCpp(
+ temperature=0.,
+ model_path="./SanctumAI-meta-llama-3-8b-instruct.Q8_0.gguf",
+ n_ctx=10000,
+ n_gpu_layers=4,
+ n_batch=200,
+ max_tokens=512,
+ n_threads=multiprocessing.cpu_count() - 1,
+ repeat_penalty=1.5,
+ top_p=0.5,
+ stop=["<|end_of_text|>", "<|eot_id|>"],
+ )
+ structured_llm = llm.with_structured_output(AnswerWithJustification, include_raw=True)
+
+ structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
+ # -> {
+ # 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_Ao02pnFYXD6GN1yzc0uXPsvF', 'function': {'arguments': '{"answer":"They weigh the same.","justification":"Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ."}', 'name': 'AnswerWithJustification'}, 'type': 'function'}]}),
+ # 'parsed': AnswerWithJustification(answer='They weigh the same.', justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'),
+ # 'parsing_error': None
+ # }
+
+ Example: dict schema (include_raw=False):
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatLlamaCpp
+ from pydantic import BaseModel
+ from langchain_core.utils.function_calling import convert_to_openai_tool
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+ answer: str
+ justification: str
+
+ dict_schema = convert_to_openai_tool(AnswerWithJustification)
+ llm = ChatLlamaCpp(
+ temperature=0.,
+ model_path="./SanctumAI-meta-llama-3-8b-instruct.Q8_0.gguf",
+ n_ctx=10000,
+ n_gpu_layers=4,
+ n_batch=200,
+ max_tokens=512,
+ n_threads=multiprocessing.cpu_count() - 1,
+ repeat_penalty=1.5,
+ top_p=0.5,
+ stop=["<|end_of_text|>", "<|eot_id|>"],
+ )
+ structured_llm = llm.with_structured_output(dict_schema)
+
+ structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
+ # -> {
+ # 'answer': 'They weigh the same',
+ # 'justification': 'Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume and density of the two substances differ.'
+ # }
+
+ """ # noqa: E501
+
+ if kwargs:
+ raise ValueError(f"Received unsupported arguments {kwargs}")
+ is_pydantic_schema = isinstance(schema, type) and is_basemodel_subclass(schema)
+ if schema is None:
+ raise ValueError(
+ "schema must be specified when method is 'function_calling'. "
+ "Received None."
+ )
+ tool_name = convert_to_openai_tool(schema)["function"]["name"]
+ tool_choice = {"type": "function", "function": {"name": tool_name}}
+ llm = self.bind_tools([schema], tool_choice=tool_choice)
+ if is_pydantic_schema:
+ output_parser: OutputParserLike = PydanticToolsParser(
+ tools=[cast(Type, schema)], first_tool_only=True
+ )
+ else:
+ output_parser = JsonOutputKeyToolsParser(
+ key_name=tool_name, first_tool_only=True
+ )
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ else:
+ return llm | output_parser
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Return a dictionary of identifying parameters.
+
+ This information is used by the LangChain callback system, which
+ is used for tracing purposes make it possible to monitor LLMs.
+ """
+ return {
+ # The model name allows users to specify custom token counting
+ # rules in LLM monitoring applications (e.g., in LangSmith users
+ # can provide per token pricing for their model and monitor
+ # costs for the given LLM.)
+ **{"model_path": self.model_path},
+ **self._default_params,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Get the type of language model used by this chat model."""
+ return "llama-cpp-python"
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling create_chat_completion."""
+ params: Dict = {
+ "max_tokens": self.max_tokens,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "top_k": self.top_k,
+ "logprobs": self.logprobs,
+ "stop_sequences": self.stop, # key here is convention among LLM classes
+ "repeat_penalty": self.repeat_penalty,
+ }
+ if self.grammar:
+ params["grammar"] = self.grammar
+ return params
+
+
+def _lc_tool_call_to_openai_tool_call(tool_call: ToolCall) -> dict:
+ return {
+ "type": "function",
+ "id": tool_call["id"],
+ "function": {
+ "name": tool_call["name"],
+ "arguments": json.dumps(tool_call["args"]),
+ },
+ }
+
+
+def _lc_invalid_tool_call_to_openai_tool_call(
+ invalid_tool_call: InvalidToolCall,
+) -> dict:
+ return {
+ "type": "function",
+ "id": invalid_tool_call["id"],
+ "function": {
+ "name": invalid_tool_call["name"],
+ "arguments": invalid_tool_call["args"],
+ },
+ }
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ """Convert a dictionary to a LangChain message.
+
+ Args:
+ _dict: The dictionary.
+
+ Returns:
+ The LangChain message.
+ """
+ role = _dict.get("role")
+ name = _dict.get("name")
+ id_ = _dict.get("id")
+ if role == "user":
+ return HumanMessage(content=_dict.get("content", ""), id=id_, name=name)
+ elif role == "assistant":
+ # Fix for azure
+ # Also OpenAI returns None for tool invocations
+ content = _dict.get("content", "") or ""
+ additional_kwargs: Dict = {}
+ if function_call := _dict.get("function_call"):
+ additional_kwargs["function_call"] = dict(function_call)
+ tool_calls = []
+ invalid_tool_calls = []
+ if raw_tool_calls := _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ for raw_tool_call in raw_tool_calls:
+ try:
+ tc = parse_tool_call(raw_tool_call, return_id=True)
+ except Exception as e:
+ invalid_tc = make_invalid_tool_call(raw_tool_call, str(e))
+ invalid_tool_calls.append(invalid_tc)
+ else:
+ if not tc:
+ continue
+ else:
+ tool_calls.append(tc)
+ return AIMessage(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ name=name,
+ id=id_,
+ tool_calls=tool_calls,
+ invalid_tool_calls=invalid_tool_calls,
+ )
+ elif role == "system":
+ return SystemMessage(content=_dict.get("content", ""), name=name, id=id_)
+ elif role == "function":
+ return FunctionMessage(
+ content=_dict.get("content", ""), name=cast(str, _dict.get("name")), id=id_
+ )
+ elif role == "tool":
+ additional_kwargs = {}
+ if "name" in _dict:
+ additional_kwargs["name"] = _dict["name"]
+ return ToolMessage(
+ content=_dict.get("content", ""),
+ tool_call_id=cast(str, _dict.get("tool_call_id")),
+ additional_kwargs=additional_kwargs,
+ name=name,
+ id=id_,
+ )
+ else:
+ return ChatMessage(
+ content=_dict.get("content", ""), role=cast(str, role), id=id_
+ )
+
+
+def _format_message_content(content: Any) -> Any:
+ """Format message content."""
+ if content and isinstance(content, list):
+ # Remove unexpected block types
+ formatted_content = []
+ for block in content:
+ if (
+ isinstance(block, dict)
+ and "type" in block
+ and block["type"] == "tool_use"
+ ):
+ continue
+ else:
+ formatted_content.append(block)
+ else:
+ formatted_content = content
+
+ return formatted_content
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ """Convert a LangChain message to a dictionary.
+
+ Args:
+ message: The LangChain message.
+
+ Returns:
+ The dictionary.
+ """
+ message_dict: Dict[str, Any] = {
+ "content": _format_message_content(message.content),
+ }
+ if (name := message.name or message.additional_kwargs.get("name")) is not None:
+ message_dict["name"] = name
+
+ # populate role and additional message data
+ if isinstance(message, ChatMessage):
+ message_dict["role"] = message.role
+ elif isinstance(message, HumanMessage):
+ message_dict["role"] = "user"
+ elif isinstance(message, AIMessage):
+ message_dict["role"] = "assistant"
+ if "function_call" in message.additional_kwargs:
+ message_dict["function_call"] = message.additional_kwargs["function_call"]
+ if message.tool_calls or message.invalid_tool_calls:
+ message_dict["tool_calls"] = [
+ _lc_tool_call_to_openai_tool_call(tc) for tc in message.tool_calls
+ ] + [
+ _lc_invalid_tool_call_to_openai_tool_call(tc)
+ for tc in message.invalid_tool_calls
+ ]
+ elif "tool_calls" in message.additional_kwargs:
+ message_dict["tool_calls"] = message.additional_kwargs["tool_calls"]
+ tool_call_supported_props = {"id", "type", "function"}
+ message_dict["tool_calls"] = [
+ {k: v for k, v in tool_call.items() if k in tool_call_supported_props}
+ for tool_call in message_dict["tool_calls"]
+ ]
+ else:
+ pass
+ # If tool calls present, content null value should be None not empty string.
+ if "function_call" in message_dict or "tool_calls" in message_dict:
+ message_dict["content"] = message_dict["content"] or None
+ elif isinstance(message, SystemMessage):
+ message_dict["role"] = "system"
+ elif isinstance(message, FunctionMessage):
+ message_dict["role"] = "function"
+ elif isinstance(message, ToolMessage):
+ message_dict["role"] = "tool"
+ message_dict["tool_call_id"] = message.tool_call_id
+
+ supported_props = {"content", "role", "tool_call_id"}
+ message_dict = {k: v for k, v in message_dict.items() if k in supported_props}
+ else:
+ raise TypeError(f"Got unknown type {message}")
+ return message_dict
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ id_ = _dict.get("id")
+ role = cast(str, _dict.get("role"))
+ content = cast(str, _dict.get("content") or "")
+ additional_kwargs: Dict = {}
+ if _dict.get("function_call"):
+ function_call = dict(_dict["function_call"])
+ if "name" in function_call and function_call["name"] is None:
+ function_call["name"] = ""
+ additional_kwargs["function_call"] = function_call
+ tool_call_chunks = []
+ if raw_tool_calls := _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ for rtc in raw_tool_calls:
+ try:
+ tool_call = ToolCallChunk(
+ name=rtc["function"].get("name"),
+ args=rtc["function"].get("arguments"),
+ id=rtc.get("id"),
+ index=rtc["index"],
+ )
+ tool_call_chunks.append(tool_call)
+ except KeyError:
+ pass
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content, id=id_)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ id=id_,
+ tool_call_chunks=tool_call_chunks,
+ )
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content, id=id_)
+ elif role == "function" or default_class == FunctionMessageChunk:
+ return FunctionMessageChunk(content=content, name=_dict["name"], id=id_)
+ elif role == "tool" or default_class == ToolMessageChunk:
+ return ToolMessageChunk(
+ content=content, tool_call_id=_dict["tool_call_id"], id=id_
+ )
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role, id=id_)
+ else:
+ return default_class(content=content, id=id_) # type: ignore[call-arg]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/maritalk.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/maritalk.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e089a174aecae0c2c621ff365389515afef45b2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/maritalk.py
@@ -0,0 +1,374 @@
+import json
+from http import HTTPStatus
+from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union
+
+import requests
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from pydantic import Field
+from requests import Response
+from requests.exceptions import HTTPError
+
+
+class MaritalkHTTPError(HTTPError):
+ def __init__(self, request_obj: Response) -> None:
+ self.request_obj = request_obj
+ try:
+ response_json = request_obj.json()
+ if "detail" in response_json:
+ api_message = response_json["detail"]
+ elif "message" in response_json:
+ api_message = response_json["message"]
+ else:
+ api_message = response_json
+ except Exception:
+ api_message = request_obj.text
+
+ self.message = api_message
+ self.status_code = request_obj.status_code
+
+ def __str__(self) -> str:
+ status_code_meaning = HTTPStatus(self.status_code).phrase
+ formatted_message = f"HTTP Error: {self.status_code} - {status_code_meaning}"
+ formatted_message += f"\nDetail: {self.message}"
+ return formatted_message
+
+
+class ChatMaritalk(BaseChatModel):
+ """`MariTalk` Chat models API.
+
+ This class allows interacting with the MariTalk chatbot API.
+ To use it, you must provide an API key either through the constructor.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatMaritalk
+ chat = ChatMaritalk(api_key="your_api_key_here")
+ """
+
+ api_key: str
+ """Your MariTalk API key."""
+
+ model: str
+ """Chose one of the available models:
+ - `sabia-2-medium`
+ - `sabia-2-small`
+ - `sabia-2-medium-2024-03-13`
+ - `sabia-2-small-2024-03-13`
+ - `maritalk-2024-01-08` (deprecated)"""
+
+ temperature: float = Field(default=0.7, gt=0.0, lt=1.0)
+ """Run inference with this temperature.
+ Must be in the closed interval [0.0, 1.0]."""
+
+ max_tokens: int = Field(default=512, gt=0)
+ """The maximum number of tokens to generate in the reply."""
+
+ do_sample: bool = Field(default=True)
+ """Whether or not to use sampling; use `True` to enable."""
+
+ top_p: float = Field(default=0.95, gt=0.0, lt=1.0)
+ """Nucleus sampling parameter controlling the size of
+ the probability mass considered for sampling."""
+
+ @property
+ def _llm_type(self) -> str:
+ """Identifies the LLM type as 'maritalk'."""
+ return "maritalk"
+
+ def parse_messages_for_model(
+ self, messages: List[BaseMessage]
+ ) -> List[Dict[str, Union[str, List[Union[str, Dict[Any, Any]]]]]]:
+ """
+ Parses messages from LangChain's format to the format expected by
+ the MariTalk API.
+
+ Parameters:
+ messages (List[BaseMessage]): A list of messages in LangChain
+ format to be parsed.
+
+ Returns:
+ A list of messages formatted for the MariTalk API.
+ """
+ parsed_messages = []
+
+ for message in messages:
+ if isinstance(message, HumanMessage):
+ role = "user"
+ elif isinstance(message, AIMessage):
+ role = "assistant"
+ elif isinstance(message, SystemMessage):
+ role = "system"
+
+ parsed_messages.append({"role": role, "content": message.content})
+ return parsed_messages
+
+ def _call(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> str:
+ """
+ Sends the parsed messages to the MariTalk API and returns the generated
+ response or an error message.
+
+ This method makes an HTTP POST request to the MariTalk API with the
+ provided messages and other parameters.
+ If the request is successful and the API returns a response,
+ this method returns a string containing the answer.
+ If the request is rate-limited or encounters another error,
+ it returns a string with the error message.
+
+ Parameters:
+ messages (List[BaseMessage]): Messages to send to the model.
+ stop (Optional[List[str]]): Tokens that will signal the model
+ to stop generating further tokens.
+
+ Returns:
+ str: If the API call is successful, returns the answer.
+ If an error occurs (e.g., rate limiting), returns a string
+ describing the error.
+ """
+ url = "https://chat.maritaca.ai/api/chat/inference"
+ headers = {"authorization": f"Key {self.api_key}"}
+ stopping_tokens = stop if stop is not None else []
+
+ parsed_messages = self.parse_messages_for_model(messages)
+
+ data = {
+ "messages": parsed_messages,
+ "model": self.model,
+ "do_sample": self.do_sample,
+ "max_tokens": self.max_tokens,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "stopping_tokens": stopping_tokens,
+ **kwargs,
+ }
+
+ response = requests.post(url, json=data, headers=headers)
+
+ if response.ok:
+ return response.json().get("answer", "No answer found")
+ else:
+ raise MaritalkHTTPError(response)
+
+ async def _acall(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> str:
+ """
+ Asynchronously sends the parsed messages to the MariTalk API and returns
+ the generated response or an error message.
+
+ This method makes an HTTP POST request to the MariTalk API with the
+ provided messages and other parameters using async I/O.
+ If the request is successful and the API returns a response,
+ this method returns a string containing the answer.
+ If the request is rate-limited or encounters another error,
+ it returns a string with the error message.
+ """
+ try:
+ import httpx
+
+ url = "https://chat.maritaca.ai/api/chat/inference"
+ headers = {"authorization": f"Key {self.api_key}"}
+ stopping_tokens = stop if stop is not None else []
+
+ parsed_messages = self.parse_messages_for_model(messages)
+
+ data = {
+ "messages": parsed_messages,
+ "model": self.model,
+ "do_sample": self.do_sample,
+ "max_tokens": self.max_tokens,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "stopping_tokens": stopping_tokens,
+ **kwargs,
+ }
+
+ async with httpx.AsyncClient() as client:
+ response = await client.post(
+ url, json=data, headers=headers, timeout=None
+ )
+
+ if response.status_code == 200:
+ return response.json().get("answer", "No answer found")
+ else:
+ raise MaritalkHTTPError(response) # type: ignore[arg-type]
+
+ except ImportError:
+ raise ImportError(
+ "Could not import httpx python package. "
+ "Please install it with `pip install httpx`."
+ )
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ headers = {"Authorization": f"Key {self.api_key}"}
+ stopping_tokens = stop if stop is not None else []
+
+ parsed_messages = self.parse_messages_for_model(messages)
+
+ data = {
+ "messages": parsed_messages,
+ "model": self.model,
+ "do_sample": self.do_sample,
+ "max_tokens": self.max_tokens,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "stopping_tokens": stopping_tokens,
+ "stream": True,
+ **kwargs,
+ }
+
+ response = requests.post(
+ "https://chat.maritaca.ai/api/chat/inference",
+ data=json.dumps(data),
+ headers=headers,
+ stream=True,
+ )
+
+ if response.ok:
+ for line in response.iter_lines():
+ if line.startswith(b"data: "):
+ response_data = line.replace(b"data: ", b"").decode("utf-8")
+ if response_data:
+ parsed_data = json.loads(response_data)
+ if "text" in parsed_data:
+ delta = parsed_data["text"]
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(content=delta)
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(delta, chunk=chunk)
+ yield chunk
+
+ else:
+ raise MaritalkHTTPError(response)
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ try:
+ import httpx
+
+ headers = {"Authorization": f"Key {self.api_key}"}
+ stopping_tokens = stop if stop is not None else []
+
+ parsed_messages = self.parse_messages_for_model(messages)
+
+ data = {
+ "messages": parsed_messages,
+ "model": self.model,
+ "do_sample": self.do_sample,
+ "max_tokens": self.max_tokens,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "stopping_tokens": stopping_tokens,
+ "stream": True,
+ **kwargs,
+ }
+
+ async with httpx.AsyncClient() as client:
+ async with client.stream(
+ "POST",
+ "https://chat.maritaca.ai/api/chat/inference",
+ data=json.dumps(data), # type: ignore[arg-type]
+ headers=headers,
+ timeout=None,
+ ) as response:
+ if response.status_code == 200:
+ async for line in response.aiter_lines():
+ if line.startswith("data: "):
+ response_data = line.replace("data: ", "")
+ if response_data:
+ parsed_data = json.loads(response_data)
+ if "text" in parsed_data:
+ delta = parsed_data["text"]
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(content=delta)
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(
+ delta, chunk=chunk
+ )
+ yield chunk
+
+ else:
+ raise MaritalkHTTPError(response) # type: ignore[arg-type]
+
+ except ImportError:
+ raise ImportError(
+ "Could not import httpx python package. "
+ "Please install it with `pip install httpx`."
+ )
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ output_str = self._call(messages, stop=stop, run_manager=run_manager, **kwargs)
+ message = AIMessage(content=output_str)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ output_str = await self._acall(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ message = AIMessage(content=output_str)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """
+ Identifies the key parameters of the chat model for logging
+ or tracking purposes.
+
+ Returns:
+ A dictionary of the key configuration parameters.
+ """
+ return {
+ "model": self.model,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "max_tokens": self.max_tokens,
+ }
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/meta.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/meta.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7b560bb630fe82c122062af105590c19aa288ce
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/meta.py
@@ -0,0 +1,31 @@
+from typing import List
+
+from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+)
+
+
+def _convert_one_message_to_text_llama(message: BaseMessage) -> str:
+ if isinstance(message, ChatMessage):
+ message_text = f"\n\n{message.role.capitalize()}: {message.content}"
+ elif isinstance(message, HumanMessage):
+ message_text = f"[INST] {message.content} [/INST]"
+ elif isinstance(message, AIMessage):
+ message_text = f"{message.content}"
+ elif isinstance(message, SystemMessage):
+ message_text = f"<> {message.content} <>"
+ else:
+ raise ValueError(f"Got unknown type {message}")
+ return message_text
+
+
+def convert_messages_to_prompt_llama(messages: List[BaseMessage]) -> str:
+ """Convert a list of messages to a prompt for llama."""
+
+ return "\n".join(
+ [_convert_one_message_to_text_llama(message) for message in messages]
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/minimax.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/minimax.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ea1889f14bcb2f31b68caac30ffc5fc66b3298a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/minimax.py
@@ -0,0 +1,798 @@
+"""Wrapper around Minimax chat models."""
+
+import json
+import logging
+from contextlib import asynccontextmanager, contextmanager
+from operator import itemgetter
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+)
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ HumanMessage,
+ SystemMessage,
+ ToolMessage,
+)
+from langchain_core.output_parsers.base import OutputParserLike
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ PydanticToolsParser,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
+from langchain_core.tools import BaseTool
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from langchain_core.utils.pydantic import get_fields
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SecretStr,
+ model_validator,
+)
+
+logger = logging.getLogger(__name__)
+
+
+@contextmanager
+def connect_httpx_sse(client: Any, method: str, url: str, **kwargs: Any) -> Iterator:
+ """Context manager for connecting to an SSE stream.
+
+ Args:
+ client: The httpx client.
+ method: The HTTP method.
+ url: The URL to connect to.
+ kwargs: Additional keyword arguments to pass to the client.
+
+ Yields:
+ An EventSource object.
+ """
+ from httpx_sse import EventSource
+
+ with client.stream(method, url, **kwargs) as response:
+ yield EventSource(response)
+
+
+@asynccontextmanager
+async def aconnect_httpx_sse(
+ client: Any, method: str, url: str, **kwargs: Any
+) -> AsyncIterator:
+ """Async context manager for connecting to an SSE stream.
+
+ Args:
+ client: The httpx client.
+ method: The HTTP method.
+ url: The URL to connect to.
+ kwargs: Additional keyword arguments to pass to the client.
+
+ Yields:
+ An EventSource object.
+ """
+ from httpx_sse import EventSource
+
+ async with client.stream(method, url, **kwargs) as response:
+ yield EventSource(response)
+
+
+def _convert_message_to_dict(message: BaseMessage) -> Dict[str, Any]:
+ """Convert a LangChain messages to Dict."""
+ message_dict: Dict[str, Any]
+ if isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {
+ "role": "assistant",
+ "content": message.content,
+ "tool_calls": message.additional_kwargs.get("tool_calls"),
+ }
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, ToolMessage):
+ message_dict = {
+ "role": "tool",
+ "content": message.content,
+ "tool_call_id": message.tool_call_id,
+ "name": message.name or message.additional_kwargs.get("name"),
+ }
+ else:
+ raise TypeError(f"Got unknown type '{message.__class__.__name__}'.")
+ return message_dict
+
+
+def _convert_dict_to_message(dct: Dict[str, Any]) -> BaseMessage:
+ """Convert a dict to LangChain message."""
+ role = dct.get("role")
+ content = dct.get("content", "")
+ if role == "assistant":
+ additional_kwargs = {}
+ tool_calls = dct.get("tool_calls", None)
+ if tool_calls is not None:
+ additional_kwargs["tool_calls"] = tool_calls
+ return AIMessage(content=content, additional_kwargs=additional_kwargs)
+ return ChatMessage(role=role, content=content) # type: ignore[arg-type]
+
+
+def _convert_delta_to_message_chunk(
+ dct: Dict[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role = dct.get("role")
+ content = dct.get("content", "")
+ additional_kwargs = {}
+ tool_calls = dct.get("tool_call", None)
+ if tool_calls is not None:
+ additional_kwargs["tool_calls"] = tool_calls
+
+ if role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)
+ if role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+class MiniMaxChat(BaseChatModel):
+ """MiniMax chat model integration.
+
+ Setup:
+ To use, you should have the environment variable``MINIMAX_API_KEY`` set with
+ your API KEY.
+
+ .. code-block:: bash
+
+ export MINIMAX_API_KEY="your-api-key"
+
+ Key init args — completion params:
+ model: Optional[str]
+ Name of MiniMax model to use.
+ max_tokens: Optional[int]
+ Max number of tokens to generate.
+ temperature: Optional[float]
+ Sampling temperature.
+ top_p: Optional[float]
+ Total probability mass of tokens to consider at each step.
+ streaming: Optional[bool]
+ Whether to stream the results or not.
+
+ Key init args — client params:
+ api_key: Optional[str]
+ MiniMax API key. If not passed in will be read from env var MINIMAX_API_KEY.
+ base_url: Optional[str]
+ Base URL for API requests.
+
+ See full list of supported init args and their descriptions in the params section.
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_models import MiniMaxChat
+
+ chat = MiniMaxChat(
+ api_key=api_key,
+ model='abab6.5-chat',
+ # temperature=...,
+ # other params...
+ )
+
+ Invoke:
+ .. code-block:: python
+
+ messages = [
+ ("system", "你是一名专业的翻译家,可以将用户的中文翻译为英文。"),
+ ("human", "我喜欢编程。"),
+ ]
+ chat.invoke(messages)
+
+ .. code-block:: python
+
+ AIMessage(
+ content='I enjoy programming.',
+ response_metadata={
+ 'token_usage': {'total_tokens': 48},
+ 'model_name': 'abab6.5-chat',
+ 'finish_reason': 'stop'
+ },
+ id='run-42d62ba6-5dc1-4e16-98dc-f72708a4162d-0'
+ )
+
+ Stream:
+ .. code-block:: python
+
+ for chunk in chat.stream(messages):
+ print(chunk)
+
+ .. code-block:: python
+
+ content='I' id='run-a5837c45-4aaa-4f64-9ab4-2679bbd55522'
+ content=' enjoy programming.' response_metadata={'finish_reason': 'stop'} id='run-a5837c45-4aaa-4f64-9ab4-2679bbd55522'
+
+ .. code-block:: python
+
+ stream = chat.stream(messages)
+ full = next(stream)
+ for chunk in stream:
+ full += chunk
+ full
+
+ .. code-block:: python
+
+ AIMessageChunk(
+ content='I enjoy programming.',
+ response_metadata={'finish_reason': 'stop'},
+ id='run-01aed0a0-61c4-4709-be22-c6d8b17155d6'
+ )
+
+ Async:
+ .. code-block:: python
+
+ await chat.ainvoke(messages)
+
+ # stream
+ # async for chunk in chat.astream(messages):
+ # print(chunk)
+
+ # batch
+ # await chat.abatch([messages])
+
+ .. code-block:: python
+
+ AIMessage(
+ content='I enjoy programming.',
+ response_metadata={
+ 'token_usage': {'total_tokens': 48},
+ 'model_name': 'abab6.5-chat',
+ 'finish_reason': 'stop'
+ },
+ id='run-c263b6f1-1736-4ece-a895-055c26b3436f-0'
+ )
+
+ Tool calling:
+ .. code-block:: python
+
+ 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"
+ )
+
+
+ class GetPopulation(BaseModel):
+ '''Get the current population in a given location'''
+
+ location: str = Field(
+ ..., description="The city and state, e.g. San Francisco, CA"
+ )
+
+ chat_with_tools = chat.bind_tools([GetWeather, GetPopulation])
+ ai_msg = chat_with_tools.invoke(
+ "Which city is hotter today and which is bigger: LA or NY?"
+ )
+ ai_msg.tool_calls
+
+ .. code-block:: python
+
+ [
+ {
+ 'name': 'GetWeather',
+ 'args': {'location': 'LA'},
+ 'id': 'call_function_2140449382',
+ 'type': 'tool_call'
+ }
+ ]
+
+ Structured output:
+ .. code-block:: python
+
+ from typing import Optional
+
+ from pydantic import BaseModel, Field
+
+
+ class Joke(BaseModel):
+ '''Joke to tell user.'''
+ setup: str = Field(description="The setup of the joke")
+ punchline: str = Field(description="The punchline to the joke")
+ rating: Optional[int] = Field(description="How funny the joke is, from 1 to 10")
+
+
+ structured_chat = chat.with_structured_output(Joke)
+ structured_chat.invoke("Tell me a joke about cats")
+
+ .. code-block:: python
+
+ Joke(
+ setup='Why do cats have nine lives?',
+ punchline='Because they are so cute and cuddly!',
+ rating=None
+ )
+
+ Response metadata
+ .. code-block:: python
+
+ ai_msg = chat.invoke(messages)
+ ai_msg.response_metadata
+
+ .. code-block:: python
+
+ {'token_usage': {'total_tokens': 48},
+ 'model_name': 'abab6.5-chat',
+ 'finish_reason': 'stop'}
+
+ """ # noqa: E501
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ return {**{"model": self.model}, **self._default_params}
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "minimax"
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling OpenAI API."""
+ return {
+ "model": self.model,
+ "max_tokens": self.max_tokens,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ **self.model_kwargs,
+ }
+
+ _client: Any = None
+ model: str = "abab6.5s-chat"
+ """Model name to use."""
+ max_tokens: int = 256
+ """Denotes the number of tokens to predict per generation."""
+ temperature: float = 0.7
+ """A non-negative float that tunes the degree of randomness in generation."""
+ top_p: float = 0.95
+ """Total probability mass of tokens to consider at each step."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for `create` call not explicitly specified."""
+ minimax_api_host: str = Field(
+ default="https://api.minimaxi.chat/v1/text/chatcompletion_v2", alias="base_url"
+ )
+ minimax_group_id: Optional[str] = Field(default=None, alias="group_id")
+ """[DEPRECATED, keeping it for for backward compatibility] Group Id"""
+ minimax_api_key: SecretStr = Field(alias="api_key")
+ """Minimax API Key"""
+ streaming: bool = False
+ """Whether to stream the results or not."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+ values["minimax_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ ["minimax_api_key", "api_key"],
+ "MINIMAX_API_KEY",
+ )
+ )
+
+ default_values = {
+ name: field.default
+ for name, field in get_fields(cls).items()
+ if field.default is not None
+ }
+ default_values.update(values)
+
+ # Get custom api url from environment.
+ values["minimax_api_host"] = get_from_dict_or_env(
+ values,
+ ["minimax_api_host", "base_url"],
+ "MINIMAX_API_HOST",
+ default_values["minimax_api_host"],
+ )
+ return values
+
+ def _create_chat_result(self, response: Union[dict, BaseModel]) -> ChatResult:
+ generations = []
+ if not isinstance(response, dict):
+ response = response.dict()
+ for res in response["choices"]:
+ message = _convert_dict_to_message(res["message"])
+ generation_info = dict(finish_reason=res.get("finish_reason"))
+ generations.append(
+ ChatGeneration(message=message, generation_info=generation_info)
+ )
+ token_usage = response.get("usage", {})
+ llm_output = {
+ "token_usage": token_usage,
+ "model_name": self.model,
+ }
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ def _create_payload_parameters(
+ self, messages: List[BaseMessage], is_stream: bool = False, **kwargs: Any
+ ) -> Dict[str, Any]:
+ """Create API request body parameters."""
+ message_dicts = [_convert_message_to_dict(m) for m in messages]
+ payload = self._default_params
+ payload["messages"] = message_dicts
+
+ self._reformat_function_parameters(kwargs.get("tools", {}))
+ payload.update(**kwargs)
+
+ if is_stream:
+ payload["stream"] = True
+
+ return payload
+
+ @staticmethod
+ def _reformat_function_parameters(tools_arg: Dict[Any, Any]) -> None:
+ """Reformat the function parameters to strings."""
+ for tool_arg in tools_arg:
+ if tool_arg["type"] == "function" and not isinstance(
+ tool_arg["function"]["parameters"], str
+ ):
+ tool_arg["function"]["parameters"] = json.dumps(
+ tool_arg["function"]["parameters"]
+ )
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate next turn in the conversation.
+ Args:
+ messages: The history of the conversation as a list of messages. Code chat
+ does not support context.
+ stop: The list of stop words (optional).
+ run_manager: The CallbackManager for LLM run, it's not used at the moment.
+ stream: Whether to stream the results or not.
+
+ Returns:
+ The ChatResult that contains outputs generated by the model.
+
+ Raises:
+ ValueError: if the last message in the list is not from human.
+ """
+ if not messages:
+ raise ValueError(
+ "You should provide at least one message to start the chat!"
+ )
+ is_stream = stream if stream is not None else self.streaming
+ if is_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+ payload = self._create_payload_parameters(messages, **kwargs)
+ api_key = ""
+ if self.minimax_api_key is not None:
+ api_key = self.minimax_api_key.get_secret_value()
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+ import httpx
+
+ with httpx.Client(headers=headers, timeout=60) as client:
+ response = client.post(self.minimax_api_host, json=payload)
+ response.raise_for_status()
+ final_response = response.json()
+ if (
+ "base_resp" in final_response
+ and "status_msg" in final_response["base_resp"]
+ and final_response["base_resp"]["status_msg"] == "invalid api key"
+ ):
+ raise Exception("Invalid API Key Provided")
+ return self._create_chat_result(response.json())
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ """Stream the chat response in chunks."""
+ payload = self._create_payload_parameters(messages, is_stream=True, **kwargs)
+ api_key = ""
+ if self.minimax_api_key is not None:
+ api_key = self.minimax_api_key.get_secret_value()
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+ import httpx
+
+ with httpx.Client(headers=headers, timeout=60) as client:
+ with connect_httpx_sse(
+ client, "POST", self.minimax_api_host, json=payload
+ ) as event_source:
+ for sse in event_source.iter_sse():
+ chunk = json.loads(sse.data)
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], AIMessageChunk
+ )
+ finish_reason = choice.get("finish_reason", None)
+
+ generation_info = (
+ {"finish_reason": finish_reason}
+ if finish_reason is not None
+ else None
+ )
+ chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+
+ if finish_reason is not None:
+ break
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if not messages:
+ raise ValueError(
+ "You should provide at least one message to start the chat!"
+ )
+ is_stream = stream if stream is not None else self.streaming
+ if is_stream:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+ payload = self._create_payload_parameters(messages, **kwargs)
+ api_key = ""
+ if self.minimax_api_key is not None:
+ api_key = self.minimax_api_key.get_secret_value()
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+ import httpx
+
+ async with httpx.AsyncClient(headers=headers, timeout=60) as client:
+ response = await client.post(self.minimax_api_host, json=payload)
+ response.raise_for_status()
+ return self._create_chat_result(response.json())
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ payload = self._create_payload_parameters(messages, is_stream=True, **kwargs)
+ api_key = ""
+ if self.minimax_api_key is not None:
+ api_key = self.minimax_api_key.get_secret_value()
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+ import httpx
+
+ async with httpx.AsyncClient(headers=headers, timeout=60) as client:
+ async with aconnect_httpx_sse(
+ client, "POST", self.minimax_api_host, json=payload
+ ) as event_source:
+ async for sse in event_source.aiter_sse():
+ chunk = json.loads(sse.data)
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], AIMessageChunk
+ )
+ finish_reason = choice.get("finish_reason", None)
+
+ generation_info = (
+ {"finish_reason": finish_reason}
+ if finish_reason is not None
+ else None
+ )
+ chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+
+ if finish_reason is not None:
+ break
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model.
+
+ Args:
+ tools: A list of tool definitions to bind to this chat model.
+ Can be a dictionary, pydantic model, callable, or BaseTool. Pydantic
+ models, callables, and BaseTools will be automatically converted to
+ their schema dictionary representation.
+ **kwargs: Any additional parameters to pass to the
+ :class: `~langchain.runnable.Runnable` constructor.
+ """
+
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ return super().bind(tools=formatted_tools, **kwargs)
+
+ def with_structured_output(
+ self,
+ schema: Union[Dict, Type[BaseModel]],
+ *,
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, Union[Dict, BaseModel]]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema: The output schema as a dict or a Pydantic class. If a Pydantic class
+ then the model output will be an object of that class. If a dict then
+ the model output will be a dict. With a Pydantic class the returned
+ attributes will be validated, whereas with a dict they will not be. If
+ `method` is "function_calling" and `schema` is a dict, then the dict
+ must match the OpenAI function-calling spec.
+ include_raw: If False then only the parsed structured output is returned. If
+ an error occurs during model output parsing it will be raised. If True
+ then both the raw model response (a BaseMessage) and the parsed model
+ response will be returned. If an error occurs during output parsing it
+ will be caught and returned as well. The final output is always a dict
+ with keys "raw", "parsed", and "parsing_error".
+
+ Returns:
+ A Runnable that takes any ChatModel input and returns as output:
+
+ If include_raw is True then a dict with keys:
+ raw: BaseMessage
+ parsed: Optional[_DictOrPydantic]
+ parsing_error: Optional[BaseException]
+
+ If include_raw is False then just _DictOrPydantic is returned,
+ where _DictOrPydantic depends on the schema:
+
+ If schema is a Pydantic class then _DictOrPydantic is the Pydantic
+ class.
+
+ If schema is a dict then _DictOrPydantic is a dict.
+
+ Example: Function-calling, Pydantic schema (method="function_calling", include_raw=False):
+ .. code-block:: python
+
+ from langchain_community.chat_models import MiniMaxChat
+ from pydantic import BaseModel
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+ answer: str
+ justification: str
+
+ llm = MiniMaxChat()
+ structured_llm = llm.with_structured_output(AnswerWithJustification)
+
+ structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
+
+ # -> AnswerWithJustification(
+ # answer='A pound of bricks and a pound of feathers weigh the same.',
+ # justification='The weight of the feathers is much less dense than the weight of the bricks, but since both weigh one pound, they weigh the same.'
+ # )
+
+ Example: Function-calling, Pydantic schema (method="function_calling", include_raw=True):
+ .. code-block:: python
+
+ from langchain_community.chat_models import MiniMaxChat
+ from pydantic import BaseModel
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+ answer: str
+ justification: str
+
+ llm = MiniMaxChat()
+ structured_llm = llm.with_structured_output(AnswerWithJustification, include_raw=True)
+
+ structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
+
+ # -> {
+ # 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_function_8953642285', 'type': 'function', 'function': {'name': 'AnswerWithJustification', 'arguments': '{"answer": "A pound of bricks and a pound of feathers weigh the same.", "justification": "The weight of the feathers is much less dense than the weight of the bricks, but since both weigh one pound, they weigh the same."}'}}]}, response_metadata={'token_usage': {'total_tokens': 257}, 'model_name': 'abab6.5-chat', 'finish_reason': 'tool_calls'}, id='run-d897e037-2796-49f5-847e-f9f69dd390db-0', tool_calls=[{'name': 'AnswerWithJustification', 'args': {'answer': 'A pound of bricks and a pound of feathers weigh the same.', 'justification': 'The weight of the feathers is much less dense than the weight of the bricks, but since both weigh one pound, they weigh the same.'}, 'id': 'call_function_8953642285', 'type': 'tool_call'}]),
+ # 'parsed': AnswerWithJustification(answer='A pound of bricks and a pound of feathers weigh the same.', justification='The weight of the feathers is much less dense than the weight of the bricks, but since both weigh one pound, they weigh the same.'),
+ # 'parsing_error': None
+ # }
+
+ Example: Function-calling, dict schema (method="function_calling", include_raw=False):
+ .. code-block:: python
+
+ from langchain_community.chat_models import MiniMaxChat
+ from pydantic import BaseModel
+ from langchain_core.utils.function_calling import convert_to_openai_tool
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+ answer: str
+ justification: str
+
+ dict_schema = convert_to_openai_tool(AnswerWithJustification)
+ llm = MiniMaxChat()
+ structured_llm = llm.with_structured_output(dict_schema)
+
+ structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
+
+ # -> {
+ # 'answer': 'A pound of bricks and a pound of feathers both weigh the same, which is a pound.',
+ # 'justification': 'The difference is that bricks are much denser than feathers, so a pound of bricks will take up much less space than a pound of feathers.'
+ # }
+ """ # noqa: E501
+ if kwargs:
+ raise ValueError(f"Received unsupported arguments {kwargs}")
+ is_pydantic_schema = isinstance(schema, type) and issubclass(schema, BaseModel)
+ llm = self.bind_tools([schema])
+ if is_pydantic_schema:
+ output_parser: OutputParserLike = PydanticToolsParser(
+ tools=[schema], # type: ignore[list-item]
+ first_tool_only=True,
+ )
+ else:
+ key_name = convert_to_openai_tool(schema)["function"]["name"]
+ output_parser = JsonOutputKeyToolsParser(
+ key_name=key_name, first_tool_only=True
+ )
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ else:
+ return llm | output_parser
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/mlflow.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/mlflow.py
new file mode 100644
index 0000000000000000000000000000000000000000..4154ad7413b62a44c7b7772874f454a1196892b3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/mlflow.py
@@ -0,0 +1,489 @@
+import json
+import logging
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Literal,
+ Mapping,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+ cast,
+)
+from urllib.parse import urlparse
+
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models import BaseChatModel
+from langchain_core.language_models.base import LanguageModelInput
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessage,
+ HumanMessage,
+ HumanMessageChunk,
+ InvalidToolCall,
+ SystemMessage,
+ SystemMessageChunk,
+ ToolCall,
+ ToolMessage,
+ ToolMessageChunk,
+)
+from langchain_core.messages.tool import tool_call_chunk
+from langchain_core.output_parsers.openai_tools import (
+ make_invalid_tool_call,
+ parse_tool_call,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable, RunnableConfig
+from langchain_core.tools import BaseTool
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from pydantic import (
+ BaseModel,
+ Field,
+ PrivateAttr,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class ChatMlflow(BaseChatModel):
+ """`MLflow` chat models API.
+
+ To use, you should have the `mlflow[genai]` python package installed.
+ For more information, see https://mlflow.org/docs/latest/llms/deployments.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatMlflow
+
+ chat = ChatMlflow(
+ target_uri="http://localhost:5000",
+ endpoint="chat",
+ temperature=0.1,
+ )
+ """
+
+ endpoint: str
+ """The endpoint to use."""
+ target_uri: str
+ """The target URI to use."""
+ temperature: float = 0.0
+ """The sampling temperature."""
+ n: int = 1
+ """The number of completion choices to generate."""
+ stop: Optional[List[str]] = None
+ """The stop sequence."""
+ max_tokens: Optional[int] = None
+ """The maximum number of tokens to generate."""
+ extra_params: dict = Field(default_factory=dict)
+ """Any extra parameters to pass to the endpoint."""
+ _client: Any = PrivateAttr()
+
+ def __init__(self, **kwargs: Any):
+ super().__init__(**kwargs)
+ self._validate_uri()
+ try:
+ from mlflow.deployments import get_deploy_client
+
+ self._client = get_deploy_client(self.target_uri)
+ except ImportError as e:
+ raise ImportError(
+ "Failed to create the client. "
+ f"Please run `pip install mlflow{self._mlflow_extras}` to install "
+ "required dependencies."
+ ) from e
+
+ @property
+ def _mlflow_extras(self) -> str:
+ return "[genai]"
+
+ def _validate_uri(self) -> None:
+ if self.target_uri == "databricks":
+ return
+ allowed = ["http", "https", "databricks"]
+ if urlparse(self.target_uri).scheme not in allowed:
+ raise ValueError(
+ f"Invalid target URI: {self.target_uri}. "
+ f"The scheme must be one of {allowed}."
+ )
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ params: Dict[str, Any] = {
+ "target_uri": self.target_uri,
+ "endpoint": self.endpoint,
+ "temperature": self.temperature,
+ "n": self.n,
+ "stop": self.stop,
+ "max_tokens": self.max_tokens,
+ "extra_params": self.extra_params,
+ }
+ return params
+
+ def _prepare_inputs(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ **kwargs: Any,
+ ) -> Dict[str, Any]:
+ message_dicts = [
+ ChatMlflow._convert_message_to_dict(message) for message in messages
+ ]
+ data: Dict[str, Any] = {
+ "messages": message_dicts,
+ "temperature": self.temperature,
+ "n": self.n,
+ **self.extra_params,
+ **kwargs,
+ }
+ if stop := self.stop or stop:
+ data["stop"] = stop
+ if self.max_tokens is not None:
+ data["max_tokens"] = self.max_tokens
+
+ return data
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ data = self._prepare_inputs(
+ messages,
+ stop,
+ **kwargs,
+ )
+ resp = self._client.predict(endpoint=self.endpoint, inputs=data)
+ return ChatMlflow._create_chat_result(resp)
+
+ def stream(
+ self,
+ input: LanguageModelInput,
+ config: Optional[RunnableConfig] = None,
+ *,
+ stop: Optional[List[str]] = None,
+ **kwargs: Any,
+ ) -> Iterator[AIMessageChunk]:
+ # We need to override `stream` to handle the case
+ # that `self._client` does not implement `predict_stream`
+ if not hasattr(self._client, "predict_stream"):
+ # MLflow deployment client does not implement streaming,
+ # so use default implementation
+ yield cast(
+ AIMessageChunk, self.invoke(input, config=config, stop=stop, **kwargs)
+ )
+ else:
+ yield from super().stream(input, config, stop=stop, **kwargs)
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ data = self._prepare_inputs(
+ messages,
+ stop,
+ **kwargs,
+ )
+ # TODO: check if `_client.predict_stream` is available.
+ chunk_iter = self._client.predict_stream(endpoint=self.endpoint, inputs=data)
+ first_chunk_role = None
+ for chunk in chunk_iter:
+ if chunk["choices"]:
+ choice = chunk["choices"][0]
+
+ chunk_delta = choice["delta"]
+ if first_chunk_role is None:
+ first_chunk_role = chunk_delta.get("role")
+
+ chunk_message = ChatMlflow._convert_delta_to_message_chunk(
+ chunk_delta, first_chunk_role
+ )
+
+ generation_info = {}
+ if finish_reason := choice.get("finish_reason"):
+ generation_info["finish_reason"] = finish_reason
+ if logprobs := choice.get("logprobs"):
+ generation_info["logprobs"] = logprobs
+
+ chunk = ChatGenerationChunk(
+ message=chunk_message, generation_info=generation_info or None
+ )
+
+ if run_manager:
+ run_manager.on_llm_new_token(
+ chunk.text, chunk=chunk, logprobs=logprobs
+ )
+
+ yield chunk
+ else:
+ # Handle the case where choices are empty if needed
+ continue
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ return self._default_params
+
+ def _get_invocation_params(
+ self, stop: Optional[List[str]] = None, **kwargs: Any
+ ) -> Dict[str, Any]:
+ """Get the parameters used to invoke the model FOR THE CALLBACKS."""
+ return {
+ **self._default_params,
+ **super()._get_invocation_params(stop=stop, **kwargs),
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "mlflow-chat"
+
+ @staticmethod
+ def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ role = _dict["role"]
+ content = cast(str, _dict.get("content"))
+ if role == "user":
+ return HumanMessage(content=content)
+ elif role == "assistant":
+ content = content or ""
+ additional_kwargs: Dict = {}
+ tool_calls = []
+ invalid_tool_calls = []
+ if raw_tool_calls := _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ for raw_tool_call in raw_tool_calls:
+ try:
+ tool_calls.append(
+ parse_tool_call(raw_tool_call, return_id=True)
+ )
+ except Exception as e:
+ invalid_tool_calls.append(
+ make_invalid_tool_call(raw_tool_call, str(e))
+ )
+ return AIMessage(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ id=_dict.get("id"),
+ tool_calls=tool_calls,
+ invalid_tool_calls=invalid_tool_calls,
+ )
+ elif role == "system":
+ return SystemMessage(content=content)
+ else:
+ return ChatMessage(content=content, role=role)
+
+ @staticmethod
+ def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_role: str
+ ) -> BaseMessageChunk:
+ role = _dict.get("role", default_role)
+ content = _dict.get("content") or ""
+ if role == "user":
+ return HumanMessageChunk(content=content)
+ elif role == "assistant":
+ additional_kwargs: Dict = {}
+ tool_call_chunks = []
+ if raw_tool_calls := _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ try:
+ tool_call_chunks = [
+ tool_call_chunk(
+ name=rtc["function"].get("name"),
+ args=rtc["function"].get("arguments"),
+ id=rtc.get("id"),
+ index=rtc["index"],
+ )
+ for rtc in raw_tool_calls
+ ]
+ except KeyError:
+ pass
+ return AIMessageChunk(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ id=_dict.get("id"),
+ tool_call_chunks=tool_call_chunks,
+ )
+ elif role == "system":
+ return SystemMessageChunk(content=content)
+ elif role == "tool":
+ return ToolMessageChunk(
+ content=content, tool_call_id=_dict["tool_call_id"], id=_dict.get("id")
+ )
+ else:
+ return ChatMessageChunk(content=content, role=role)
+
+ @staticmethod
+ def _raise_functions_not_supported() -> None:
+ raise ValueError(
+ "Function messages are not supported by Databricks. Please"
+ " create a feature request at https://github.com/mlflow/mlflow/issues."
+ )
+
+ @staticmethod
+ def _convert_message_to_dict(message: BaseMessage) -> dict:
+ message_dict = {"content": message.content}
+ if (name := message.name or message.additional_kwargs.get("name")) is not None:
+ message_dict["name"] = name
+ if isinstance(message, ChatMessage):
+ message_dict["role"] = message.role
+ elif isinstance(message, HumanMessage):
+ message_dict["role"] = "user"
+ elif isinstance(message, AIMessage):
+ message_dict["role"] = "assistant"
+ if message.tool_calls or message.invalid_tool_calls:
+ message_dict["tool_calls"] = [
+ _lc_tool_call_to_openai_tool_call(tc) for tc in message.tool_calls
+ ] + [
+ _lc_invalid_tool_call_to_openai_tool_call(tc)
+ for tc in message.invalid_tool_calls
+ ] # type: ignore[assignment]
+ elif "tool_calls" in message.additional_kwargs:
+ message_dict["tool_calls"] = message.additional_kwargs["tool_calls"]
+ tool_call_supported_props = {"id", "type", "function"}
+ message_dict["tool_calls"] = [
+ {
+ k: v
+ for k, v in tool_call.items() # type: ignore[union-attr]
+ if k in tool_call_supported_props
+ }
+ for tool_call in message_dict["tool_calls"]
+ ]
+ else:
+ pass
+ # If tool calls present, content null value should be None not empty string.
+ if "tool_calls" in message_dict:
+ message_dict["content"] = message_dict["content"] or None # type: ignore[assignment]
+ elif isinstance(message, SystemMessage):
+ message_dict["role"] = "system"
+ elif isinstance(message, ToolMessage):
+ message_dict["role"] = "tool"
+ message_dict["tool_call_id"] = message.tool_call_id
+ supported_props = {"content", "role", "tool_call_id"}
+ message_dict = {
+ k: v for k, v in message_dict.items() if k in supported_props
+ }
+ elif isinstance(message, FunctionMessage):
+ raise ValueError(
+ "Function messages are not supported by Databricks. Please"
+ " create a feature request at https://github.com/mlflow/mlflow/issues."
+ )
+ else:
+ raise ValueError(f"Got unknown message type: {message}")
+
+ if "function_call" in message.additional_kwargs:
+ ChatMlflow._raise_functions_not_supported()
+ return message_dict
+
+ @staticmethod
+ def _create_chat_result(response: Mapping[str, Any]) -> ChatResult:
+ generations = []
+ for choice in response["choices"]:
+ message = ChatMlflow._convert_dict_to_message(choice["message"])
+ usage = choice.get("usage", {})
+ gen = ChatGeneration(
+ message=message,
+ generation_info=usage,
+ )
+ generations.append(gen)
+
+ usage = response.get("usage", {})
+ return ChatResult(generations=generations, llm_output=usage)
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ *,
+ tool_choice: Optional[
+ Union[dict, str, Literal["auto", "none", "required", "any"], bool]
+ ] = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model.
+
+ Assumes model is compatible with OpenAI tool-calling API.
+
+ Args:
+ tools: A list of tool definitions to bind to this chat model.
+ Can be a dictionary, pydantic model, callable, or BaseTool. Pydantic
+ models, callables, and BaseTools will be automatically converted to
+ their schema dictionary representation.
+ tool_choice: Which tool to require the model to call.
+ Options are:
+ name of the tool (str): calls corresponding tool;
+ "auto": automatically selects a tool (including no tool);
+ "none": model does not generate any tool calls and instead must
+ generate a standard assistant message;
+ "required": the model picks the most relevant tool in tools and
+ must generate a tool call;
+
+ or a dict of the form:
+ {"type": "function", "function": {"name": <>}}.
+ **kwargs: Any additional parameters to pass to the
+ :class:`~langchain.runnable.Runnable` constructor.
+ """
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ if tool_choice:
+ if isinstance(tool_choice, str):
+ # tool_choice is a tool/function name
+ if tool_choice not in ("auto", "none", "required"):
+ tool_choice = {
+ "type": "function",
+ "function": {"name": tool_choice},
+ }
+ elif isinstance(tool_choice, dict):
+ tool_names = [
+ formatted_tool["function"]["name"]
+ for formatted_tool in formatted_tools
+ ]
+ if not any(
+ tool_name == tool_choice["function"]["name"]
+ for tool_name in tool_names
+ ):
+ raise ValueError(
+ f"Tool choice {tool_choice} was specified, but the only "
+ f"provided tools were {tool_names}."
+ )
+ else:
+ raise ValueError(
+ f"Unrecognized tool_choice type. Expected str, bool or dict. "
+ f"Received: {tool_choice}"
+ )
+ kwargs["tool_choice"] = tool_choice
+ return super().bind(tools=formatted_tools, **kwargs)
+
+
+def _lc_tool_call_to_openai_tool_call(tool_call: ToolCall) -> dict:
+ return {
+ "type": "function",
+ "id": tool_call["id"],
+ "function": {
+ "name": tool_call["name"],
+ "arguments": json.dumps(tool_call["args"]),
+ },
+ }
+
+
+def _lc_invalid_tool_call_to_openai_tool_call(
+ invalid_tool_call: InvalidToolCall,
+) -> dict:
+ return {
+ "type": "function",
+ "id": invalid_tool_call["id"],
+ "function": {
+ "name": invalid_tool_call["name"],
+ "arguments": invalid_tool_call["args"],
+ },
+ }
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/mlflow_ai_gateway.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/mlflow_ai_gateway.py
new file mode 100644
index 0000000000000000000000000000000000000000..e33a656466eae9e21da2935a9571b839393d689e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/mlflow_ai_gateway.py
@@ -0,0 +1,195 @@
+import logging
+import warnings
+from typing import Any, Dict, List, Mapping, Optional
+
+from langchain_core.callbacks import (
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ ChatMessage,
+ FunctionMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatResult,
+)
+from pydantic import BaseModel
+
+logger = logging.getLogger(__name__)
+
+
+# Ignoring type because below is valid pydantic code
+# Unexpected keyword argument "extra" for "__init_subclass__" of "object" [call-arg]
+class ChatParams(BaseModel, extra="allow"):
+ """Parameters for the `MLflow AI Gateway` LLM."""
+
+ temperature: float = 0.0
+ candidate_count: int = 1
+ """The number of candidates to return."""
+ stop: Optional[List[str]] = None
+ max_tokens: Optional[int] = None
+
+
+class ChatMLflowAIGateway(BaseChatModel):
+ """`MLflow AI Gateway` chat models API.
+
+ To use, you should have the ``mlflow[gateway]`` python package installed.
+ For more information, see https://mlflow.org/docs/latest/gateway/index.html.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatMLflowAIGateway
+
+ chat = ChatMLflowAIGateway(
+ gateway_uri="",
+ route="",
+ params={
+ "temperature": 0.1
+ }
+ )
+ """
+
+ def __init__(self, **kwargs: Any):
+ warnings.warn(
+ "`ChatMLflowAIGateway` is deprecated. Use `ChatMlflow` or "
+ "`ChatDatabricks` instead.",
+ DeprecationWarning,
+ )
+ try:
+ import mlflow.gateway
+ except ImportError as e:
+ raise ImportError(
+ "Could not import `mlflow.gateway` module. "
+ "Please install it with `pip install mlflow[gateway]`."
+ ) from e
+
+ super().__init__(**kwargs)
+ if self.gateway_uri:
+ mlflow.gateway.set_gateway_uri(self.gateway_uri)
+
+ route: str
+ gateway_uri: Optional[str] = None
+ params: Optional[ChatParams] = None
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ params: Dict[str, Any] = {
+ "gateway_uri": self.gateway_uri,
+ "route": self.route,
+ **(self.params.dict() if self.params else {}),
+ }
+ return params
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ try:
+ import mlflow.gateway
+ except ImportError as e:
+ raise ImportError(
+ "Could not import `mlflow.gateway` module. "
+ "Please install it with `pip install mlflow[gateway]`."
+ ) from e
+
+ message_dicts = [
+ ChatMLflowAIGateway._convert_message_to_dict(message)
+ for message in messages
+ ]
+ data: Dict[str, Any] = {
+ "messages": message_dicts,
+ **(self.params.dict() if self.params else {}),
+ }
+
+ resp = mlflow.gateway.query(self.route, data=data)
+ return ChatMLflowAIGateway._create_chat_result(resp)
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ return self._default_params
+
+ def _get_invocation_params(
+ self, stop: Optional[List[str]] = None, **kwargs: Any
+ ) -> Dict[str, Any]:
+ """Get the parameters used to invoke the model FOR THE CALLBACKS."""
+ return {
+ **self._default_params,
+ **super()._get_invocation_params(stop=stop, **kwargs),
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "mlflow-ai-gateway-chat"
+
+ @staticmethod
+ def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ role = _dict["role"]
+ content = _dict["content"]
+ if role == "user":
+ return HumanMessage(content=content)
+ elif role == "assistant":
+ return AIMessage(content=content)
+ elif role == "system":
+ return SystemMessage(content=content)
+ else:
+ return ChatMessage(content=content, role=role)
+
+ @staticmethod
+ def _raise_functions_not_supported() -> None:
+ raise ValueError(
+ "Function messages are not supported by the MLflow AI Gateway. Please"
+ " create a feature request at https://github.com/mlflow/mlflow/issues."
+ )
+
+ @staticmethod
+ def _convert_message_to_dict(message: BaseMessage) -> dict:
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, FunctionMessage):
+ raise ValueError(
+ "Function messages are not supported by the MLflow AI Gateway. Please"
+ " create a feature request at https://github.com/mlflow/mlflow/issues."
+ )
+ else:
+ raise ValueError(f"Got unknown message type: {message}")
+
+ if "function_call" in message.additional_kwargs:
+ ChatMLflowAIGateway._raise_functions_not_supported()
+ if message.additional_kwargs:
+ logger.warning(
+ "Additional message arguments are unsupported by MLflow AI Gateway "
+ " and will be ignored: %s",
+ message.additional_kwargs,
+ )
+ return message_dict
+
+ @staticmethod
+ def _create_chat_result(response: Mapping[str, Any]) -> ChatResult:
+ generations = []
+ for candidate in response["candidates"]:
+ message = ChatMLflowAIGateway._convert_dict_to_message(candidate["message"])
+ message_metadata = candidate.get("metadata", {})
+ gen = ChatGeneration(
+ message=message,
+ generation_info=dict(message_metadata),
+ )
+ generations.append(gen)
+
+ response_metadata = response.get("metadata", {})
+ return ChatResult(generations=generations, llm_output=response_metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/mlx.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/mlx.py
new file mode 100644
index 0000000000000000000000000000000000000000..644b3406e644265f309e12b87d14fd4fd7333bfc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/mlx.py
@@ -0,0 +1,277 @@
+"""MLX Chat Wrapper."""
+
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Literal,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+)
+
+from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ ChatResult,
+ LLMResult,
+)
+from langchain_core.runnables import Runnable
+from langchain_core.tools import BaseTool
+from langchain_core.utils.function_calling import convert_to_openai_tool
+
+from langchain_community.llms.mlx_pipeline import MLXPipeline
+
+DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful, and honest assistant."""
+
+
+class ChatMLX(BaseChatModel):
+ """MLX chat models.
+
+ Works with `MLXPipeline` LLM.
+
+ To use, you should have the ``mlx-lm`` python package installed.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import chatMLX
+ from langchain_community.llms import MLXPipeline
+
+ llm = MLXPipeline.from_model_id(
+ model_id="mlx-community/quantized-gemma-2b-it",
+ )
+ chat = chatMLX(llm=llm)
+
+ """
+
+ llm: MLXPipeline
+ system_message: SystemMessage = SystemMessage(content=DEFAULT_SYSTEM_PROMPT)
+ tokenizer: Any = None
+
+ def __init__(self, **kwargs: Any):
+ super().__init__(**kwargs)
+ self.tokenizer = self.llm.tokenizer
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ llm_input = self._to_chat_prompt(messages)
+ llm_result = self.llm._generate(
+ prompts=[llm_input], stop=stop, run_manager=run_manager, **kwargs
+ )
+ return self._to_chat_result(llm_result)
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ llm_input = self._to_chat_prompt(messages)
+ llm_result = await self.llm._agenerate(
+ prompts=[llm_input], stop=stop, run_manager=run_manager, **kwargs
+ )
+ return self._to_chat_result(llm_result)
+
+ def _to_chat_prompt(
+ self,
+ messages: List[BaseMessage],
+ tokenize: bool = False,
+ return_tensors: Optional[str] = None,
+ ) -> str:
+ """Convert a list of messages into a prompt format expected by wrapped LLM."""
+ if not messages:
+ raise ValueError("At least one HumanMessage must be provided!")
+
+ if not isinstance(messages[-1], HumanMessage):
+ raise ValueError("Last message must be a HumanMessage!")
+
+ messages_dicts = [self._to_chatml_format(m) for m in messages]
+ return self.tokenizer.apply_chat_template(
+ messages_dicts,
+ tokenize=tokenize,
+ add_generation_prompt=True,
+ return_tensors=return_tensors,
+ )
+
+ def _to_chatml_format(self, message: BaseMessage) -> dict:
+ """Convert LangChain message to ChatML format."""
+
+ if isinstance(message, SystemMessage):
+ role = "system"
+ elif isinstance(message, AIMessage):
+ role = "assistant"
+ elif isinstance(message, HumanMessage):
+ role = "user"
+ else:
+ raise ValueError(f"Unknown message type: {type(message)}")
+
+ return {"role": role, "content": message.content}
+
+ @staticmethod
+ def _to_chat_result(llm_result: LLMResult) -> ChatResult:
+ chat_generations = []
+
+ for g in llm_result.generations[0]:
+ chat_generation = ChatGeneration(
+ message=AIMessage(content=g.text), generation_info=g.generation_info
+ )
+ chat_generations.append(chat_generation)
+
+ return ChatResult(
+ generations=chat_generations, llm_output=llm_result.llm_output
+ )
+
+ @property
+ def _llm_type(self) -> str:
+ return "mlx-chat-wrapper"
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ import mlx.core as mx
+ from mlx_lm.utils import generate_step
+
+ try:
+ import mlx.core as mx
+ from mlx_lm.sample_utils import make_logits_processors, make_sampler
+ from mlx_lm.utils import generate_step
+
+ except ImportError:
+ raise ImportError(
+ "Could not import mlx_lm python package. "
+ "Please install it with `pip install mlx_lm`."
+ )
+ model_kwargs = kwargs.get("model_kwargs", self.llm.pipeline_kwargs) or {}
+ temp: float = model_kwargs.get("temp", 0.0)
+ max_new_tokens: int = model_kwargs.get("max_tokens", 100)
+ repetition_penalty: Optional[float] = model_kwargs.get(
+ "repetition_penalty", None
+ )
+ repetition_context_size: Optional[int] = model_kwargs.get(
+ "repetition_context_size", None
+ )
+ top_p: float = model_kwargs.get("top_p", 1.0)
+ min_p: float = model_kwargs.get("min_p", 0.0)
+ min_tokens_to_keep: int = model_kwargs.get("min_tokens_to_keep", 1)
+
+ llm_input = self._to_chat_prompt(messages, tokenize=True, return_tensors="np")
+
+ prompt_tokens = mx.array(llm_input[0])
+
+ eos_token_id = self.tokenizer.eos_token_id
+
+ sampler = make_sampler(temp or 0.0, top_p, min_p, min_tokens_to_keep)
+
+ logits_processors = make_logits_processors(
+ None, repetition_penalty, repetition_context_size
+ )
+
+ for (token, prob), n in zip(
+ generate_step(
+ prompt_tokens,
+ self.llm.model,
+ sampler=sampler,
+ logits_processors=logits_processors,
+ ),
+ range(max_new_tokens),
+ ):
+ # identify text to yield
+ text: Optional[str] = None
+ if not isinstance(token, int):
+ text = self.tokenizer.decode(token.item())
+ else:
+ text = self.tokenizer.decode(token)
+
+ # yield text, if any
+ if text:
+ chunk = ChatGenerationChunk(message=AIMessageChunk(content=text))
+ if run_manager:
+ run_manager.on_llm_new_token(text, chunk=chunk)
+ yield chunk
+
+ # break if stop sequence found
+ if token == eos_token_id or (stop is not None and text in stop):
+ break
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type, Callable, BaseTool]],
+ *,
+ tool_choice: Optional[Union[dict, str, Literal["auto", "none"], bool]] = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model.
+
+ Assumes model is compatible with OpenAI tool-calling API.
+
+ Args:
+ tools: A list of tool definitions to bind to this chat model.
+ Supports any tool definition handled by
+ :meth:`langchain_core.utils.function_calling.convert_to_openai_tool`.
+ tool_choice: Which tool to require the model to call.
+ Must be the name of the single provided function or
+ "auto" to automatically determine which function to call
+ (if any), or a dict of the form:
+ {"type": "function", "function": {"name": <>}}.
+ **kwargs: Any additional parameters to pass to the
+ :class:`~langchain.runnable.Runnable` constructor.
+ """
+
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ if tool_choice is not None and tool_choice:
+ if len(formatted_tools) != 1:
+ raise ValueError(
+ "When specifying `tool_choice`, you must provide exactly one "
+ f"tool. Received {len(formatted_tools)} tools."
+ )
+ if isinstance(tool_choice, str):
+ if tool_choice not in ("auto", "none"):
+ tool_choice = {
+ "type": "function",
+ "function": {"name": tool_choice},
+ }
+ elif isinstance(tool_choice, bool):
+ tool_choice = formatted_tools[0]
+ elif isinstance(tool_choice, dict):
+ if (
+ formatted_tools[0]["function"]["name"]
+ != tool_choice["function"]["name"]
+ ):
+ raise ValueError(
+ f"Tool choice {tool_choice} was specified, but the only "
+ f"provided tool was {formatted_tools[0]['function']['name']}."
+ )
+ else:
+ raise ValueError(
+ f"Unrecognized tool_choice type. Expected str, bool or dict. "
+ f"Received: {tool_choice}"
+ )
+ kwargs["tool_choice"] = tool_choice
+ return super().bind(tools=formatted_tools, **kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/moonshot.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/moonshot.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d31426fda7270913ef4067d98b9fe38094bc63d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/moonshot.py
@@ -0,0 +1,187 @@
+"""Wrapper around Moonshot chat models."""
+
+from typing import Dict
+
+from langchain_core.utils import (
+ convert_to_secret_str,
+ get_from_dict_or_env,
+ pre_init,
+)
+
+from langchain_community.chat_models import ChatOpenAI
+from langchain_community.llms.moonshot import MOONSHOT_SERVICE_URL_BASE, MoonshotCommon
+
+
+class MoonshotChat(MoonshotCommon, ChatOpenAI): # type: ignore[misc]
+ """Moonshot chat model integration.
+
+ Setup:
+ Install ``openai`` and set environment variables ``MOONSHOT_API_KEY``.
+
+ .. code-block:: bash
+
+ pip install openai
+ export MOONSHOT_API_KEY="your-api-key"
+
+ Key init args — completion params:
+ model: str
+ Name of Moonshot model to use.
+ temperature: float
+ Sampling temperature.
+ max_tokens: Optional[int]
+ Max number of tokens to generate.
+
+ Key init args — client params:
+ api_key: Optional[str]
+ Moonshot API KEY. If not passed in will be read from env var MOONSHOT_API_KEY.
+ api_base: Optional[str]
+ Base URL for API requests.
+
+ See full list of supported init args and their descriptions in the params section.
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_models import MoonshotChat
+
+ chat = MoonshotChat(
+ temperature=0.5,
+ api_key="your-api-key",
+ model="moonshot-v1-8k",
+ # api_base="...",
+ # other params...
+ )
+
+ Invoke:
+ .. code-block:: python
+
+ messages = [
+ ("system", "你是一名专业的翻译家,可以将用户的中文翻译为英文。"),
+ ("human", "我喜欢编程。"),
+ ]
+ chat.invoke(messages)
+
+ .. code-block:: python
+
+ AIMessage(
+ content='I like programming.',
+ additional_kwargs={},
+ response_metadata={
+ 'token_usage': {
+ 'completion_tokens': 5,
+ 'prompt_tokens': 27,
+ 'total_tokens': 32
+ },
+ 'model_name': 'moonshot-v1-8k',
+ 'system_fingerprint': None,
+ 'finish_reason': 'stop',
+ 'logprobs': None
+ },
+ id='run-71c03f4e-6628-41d5-beb6-d2559ae68266-0'
+ )
+
+ Stream:
+ .. code-block:: python
+
+ for chunk in chat.stream(messages):
+ print(chunk)
+
+ .. code-block:: python
+
+ content='' additional_kwargs={} response_metadata={} id='run-80d77096-8b83-4c39-a84d-71d9c746da92'
+ content='I' additional_kwargs={} response_metadata={} id='run-80d77096-8b83-4c39-a84d-71d9c746da92'
+ content=' like' additional_kwargs={} response_metadata={} id='run-80d77096-8b83-4c39-a84d-71d9c746da92'
+ content=' programming' additional_kwargs={} response_metadata={} id='run-80d77096-8b83-4c39-a84d-71d9c746da92'
+ content='.' additional_kwargs={} response_metadata={} id='run-80d77096-8b83-4c39-a84d-71d9c746da92'
+ content='' additional_kwargs={} response_metadata={'finish_reason': 'stop'} id='run-80d77096-8b83-4c39-a84d-71d9c746da92'
+
+ .. code-block:: python
+
+ stream = chat.stream(messages)
+ full = next(stream)
+ for chunk in stream:
+ full += chunk
+ full
+
+ .. code-block:: python
+
+ AIMessageChunk(
+ content='I like programming.',
+ additional_kwargs={},
+ response_metadata={'finish_reason': 'stop'},
+ id='run-10c80976-7aa5-4ff7-ba3e-1251665557ef'
+ )
+
+ Async:
+ .. code-block:: python
+
+ await chat.ainvoke(messages)
+
+ # stream:
+ # async for chunk in chat.astream(messages):
+ # print(chunk)
+
+ # batch:
+ # await chat.abatch([messages])
+
+ .. code-block:: python
+
+ [AIMessage(content='I like programming.', additional_kwargs={}, response_metadata={'token_usage': {'completion_tokens': 5, 'prompt_tokens': 27, 'total_tokens': 32}, 'model_name': 'moonshot-v1-8k', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-2938b005-9204-4b9f-b273-1c3272fce9e5-0')]
+
+ Response metadata
+ .. code-block:: python
+
+ ai_msg = chat.invoke(messages)
+ ai_msg.response_metadata
+
+ .. code-block:: python
+
+ {
+ 'token_usage': {
+ 'completion_tokens': 5,
+ 'prompt_tokens': 27,
+ 'total_tokens': 32
+ },
+ 'model_name': 'moonshot-v1-8k',
+ 'system_fingerprint': None,
+ 'finish_reason': 'stop',
+ 'logprobs': None
+ }
+
+ """ # noqa: E501
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that the environment is set up correctly."""
+ values["moonshot_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ values,
+ ["moonshot_api_key", "api_key", "openai_api_key"],
+ "MOONSHOT_API_KEY",
+ )
+ )
+
+ try:
+ import openai
+
+ except ImportError:
+ raise ImportError(
+ "Could not import openai python package. "
+ "Please install it with `pip install openai`."
+ )
+
+ client_params = {
+ "api_key": values["moonshot_api_key"].get_secret_value(),
+ "base_url": values["base_url"]
+ if "base_url" in values
+ else MOONSHOT_SERVICE_URL_BASE,
+ }
+
+ if not values.get("client"):
+ values["client"] = openai.OpenAI(**client_params).chat.completions
+ if not values.get("async_client"):
+ values["async_client"] = openai.AsyncOpenAI(
+ **client_params
+ ).chat.completions
+
+ return values
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/naver.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/naver.py
new file mode 100644
index 0000000000000000000000000000000000000000..413c9e79c2b389036126681271de65b6f2ac23ba
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/naver.py
@@ -0,0 +1,572 @@
+import logging
+from typing import (
+ Any,
+ AsyncContextManager,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Optional,
+ Tuple,
+ Type,
+ Union,
+ cast,
+)
+
+import httpx
+from httpx_sse import SSEError
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel, LangSmithParams
+from langchain_core.language_models.llms import create_base_retry_decorator
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.utils import convert_to_secret_str, get_from_env
+from pydantic import (
+ AliasChoices,
+ ConfigDict,
+ Field,
+ SecretStr,
+ model_validator,
+)
+from typing_extensions import Self
+
+_DEFAULT_BASE_URL = "https://clovastudio.stream.ntruss.com"
+
+logger = logging.getLogger(__name__)
+
+
+def _convert_chunk_to_message_chunk(
+ sse: Any, default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ sse_data = sse.json()
+ if sse.event == "result":
+ response_metadata = _sse_data_to_response_metadata(sse_data)
+ return AIMessageChunk(content="", response_metadata=response_metadata)
+
+ message = sse_data.get("message")
+ role = message.get("role")
+ content = message.get("content") or ""
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content)
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role)
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+def _sse_data_to_response_metadata(sse_data: Dict) -> Dict[str, Any]:
+ response_metadata = {}
+ if "stopReason" in sse_data:
+ response_metadata["stop_reason"] = sse_data["stopReason"]
+ if "inputLength" in sse_data:
+ response_metadata["input_length"] = sse_data["inputLength"]
+ if "outputLength" in sse_data:
+ response_metadata["output_length"] = sse_data["outputLength"]
+ if "seed" in sse_data:
+ response_metadata["seed"] = sse_data["seed"]
+ if "aiFilter" in sse_data:
+ response_metadata["ai_filter"] = sse_data["aiFilter"]
+ return response_metadata
+
+
+def _convert_message_to_naver_chat_message(
+ message: BaseMessage,
+) -> Dict:
+ if isinstance(message, ChatMessage):
+ return dict(role=message.role, content=message.content)
+ elif isinstance(message, HumanMessage):
+ return dict(role="user", content=message.content)
+ elif isinstance(message, SystemMessage):
+ return dict(role="system", content=message.content)
+ elif isinstance(message, AIMessage):
+ return dict(role="assistant", content=message.content)
+ else:
+ logger.warning(
+ "FunctionMessage, ToolMessage not yet supported "
+ "(https://api.ncloud-docs.com/docs/clovastudio-chatcompletions)"
+ )
+ raise ValueError(f"Got unknown type {message}")
+
+
+def _convert_naver_chat_message_to_message(
+ _message: Dict,
+) -> BaseMessage:
+ role = _message["role"]
+ assert role in (
+ "assistant",
+ "system",
+ "user",
+ ), f"Expected role to be 'assistant', 'system', 'user', got {role}"
+ content = cast(str, _message["content"])
+ additional_kwargs: Dict = {}
+
+ if role == "user":
+ return HumanMessage(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ )
+ elif role == "system":
+ return SystemMessage(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ )
+ elif role == "assistant":
+ return AIMessage(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ )
+ else:
+ logger.warning("Got unknown role %s", role)
+ raise ValueError(f"Got unknown role {role}")
+
+
+async def _aiter_sse(
+ event_source_mgr: AsyncContextManager[Any],
+) -> AsyncIterator[Dict]:
+ """Iterate over the server-sent events."""
+ async with event_source_mgr as event_source:
+ await _araise_on_error(event_source.response)
+ async for sse in event_source.aiter_sse():
+ event_data = sse.json()
+ if sse.event == "signal" and event_data.get("data", {}) == "[DONE]":
+ return
+ if sse.event == "error":
+ raise SSEError(message=sse.data)
+ yield sse
+
+
+def _raise_on_error(response: httpx.Response) -> None:
+ """Raise an error if the response is an error."""
+ if httpx.codes.is_error(response.status_code):
+ error_message = response.read().decode("utf-8")
+ raise httpx.HTTPStatusError(
+ f"Error response {response.status_code} "
+ f"while fetching {response.url}: {error_message}",
+ request=response.request,
+ response=response,
+ )
+
+
+async def _araise_on_error(response: httpx.Response) -> None:
+ """Raise an error if the response is an error."""
+ if httpx.codes.is_error(response.status_code):
+ error_message = (await response.aread()).decode("utf-8")
+ raise httpx.HTTPStatusError(
+ f"Error response {response.status_code} "
+ f"while fetching {response.url}: {error_message}",
+ request=response.request,
+ response=response,
+ )
+
+
+class ChatClovaX(BaseChatModel):
+ """`NCP ClovaStudio` Chat Completion API.
+
+ following environment variables set or passed in constructor in lower case:
+ - ``NCP_CLOVASTUDIO_API_KEY``
+ - ``NCP_APIGW_API_KEY``
+
+ Example:
+ .. code-block:: python
+
+ from langchain_core.messages import HumanMessage
+
+ from langchain_community import ChatClovaX
+
+ model = ChatClovaX()
+ model.invoke([HumanMessage(content="Come up with 10 names for a song about parrots.")])
+ """ # noqa: E501
+
+ client: Optional[httpx.Client] = Field(default=None) #: :meta private:
+ async_client: Optional[httpx.AsyncClient] = Field(default=None) #: :meta private:
+
+ model_name: str = Field(
+ default="HCX-003",
+ validation_alias=AliasChoices("model_name", "model"),
+ description="NCP ClovaStudio chat model name",
+ )
+ task_id: Optional[str] = Field(
+ default=None, description="NCP Clova Studio chat model tuning task ID"
+ )
+ service_app: bool = Field(
+ default=False,
+ description="false: use testapp, true: use service app on NCP Clova Studio",
+ )
+
+ ncp_clovastudio_api_key: Optional[SecretStr] = Field(default=None, alias="api_key")
+ """Automatically inferred from env are `NCP_CLOVASTUDIO_API_KEY` if not provided."""
+
+ ncp_apigw_api_key: Optional[SecretStr] = Field(default=None, alias="apigw_api_key")
+ """Automatically inferred from env are `NCP_APIGW_API_KEY` if not provided."""
+
+ base_url: str = Field(default="", alias="base_url")
+ """
+ Automatically inferred from env are `NCP_CLOVASTUDIO_API_BASE_URL` if not provided.
+ """
+
+ temperature: Optional[float] = Field(gt=0.0, le=1.0, default=0.5)
+ top_k: Optional[int] = Field(ge=0, le=128, default=0)
+ top_p: Optional[float] = Field(ge=0, le=1.0, default=0.8)
+ repeat_penalty: Optional[float] = Field(gt=0.0, le=10, default=5.0)
+ max_tokens: Optional[int] = Field(ge=0, le=4096, default=100)
+ stop_before: Optional[list[str]] = Field(default=None, alias="stop")
+ include_ai_filters: Optional[bool] = Field(default=False)
+ seed: Optional[int] = Field(ge=0, le=4294967295, default=0)
+
+ timeout: int = Field(gt=0, default=90)
+ max_retries: int = Field(ge=1, default=2)
+
+ model_config = ConfigDict(populate_by_name=True, protected_namespaces=())
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling the API."""
+ defaults = {
+ "temperature": self.temperature,
+ "topK": self.top_k,
+ "topP": self.top_p,
+ "repeatPenalty": self.repeat_penalty,
+ "maxTokens": self.max_tokens,
+ "stopBefore": self.stop_before,
+ "includeAiFilters": self.include_ai_filters,
+ "seed": self.seed,
+ }
+ filtered = {k: v for k, v in defaults.items() if v is not None}
+ return filtered
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ self._default_params["model_name"] = self.model_name
+ return self._default_params
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ if not self._is_new_api_key():
+ return {
+ "ncp_clovastudio_api_key": "NCP_CLOVASTUDIO_API_KEY",
+ }
+ else:
+ return {
+ "ncp_clovastudio_api_key": "NCP_CLOVASTUDIO_API_KEY",
+ "ncp_apigw_api_key": "NCP_APIGW_API_KEY",
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "chat-naver"
+
+ def _get_ls_params(
+ self, stop: Optional[List[str]] = None, **kwargs: Any
+ ) -> LangSmithParams:
+ """Get the parameters used to invoke the model."""
+ params = super()._get_ls_params(stop=stop, **kwargs)
+ params["ls_provider"] = "naver"
+ return params
+
+ @property
+ def _client_params(self) -> Dict[str, Any]:
+ """Get the parameters used for the client."""
+ return self._default_params
+
+ @property
+ def _api_url(self) -> str:
+ """GET chat completion api url"""
+ app_type = "serviceapp" if self.service_app else "testapp"
+
+ if self.task_id:
+ return (
+ f"{self.base_url}/{app_type}/v1/tasks/{self.task_id}/chat-completions"
+ )
+ else:
+ return f"{self.base_url}/{app_type}/v1/chat-completions/{self.model_name}"
+
+ @model_validator(mode="after")
+ def validate_model_after(self) -> Self:
+ if not (self.model_name or self.task_id):
+ raise ValueError("either model_name or task_id must be assigned a value.")
+
+ if not self.ncp_clovastudio_api_key:
+ self.ncp_clovastudio_api_key = convert_to_secret_str(
+ get_from_env("ncp_clovastudio_api_key", "NCP_CLOVASTUDIO_API_KEY")
+ )
+
+ if not self._is_new_api_key():
+ self._init_fields_on_old_api_key()
+
+ if not self.base_url:
+ self.base_url = get_from_env(
+ "base_url", "NCP_CLOVASTUDIO_API_BASE_URL", _DEFAULT_BASE_URL
+ )
+
+ if not self.client:
+ self.client = httpx.Client(
+ base_url=self.base_url,
+ headers=self.default_headers(),
+ timeout=self.timeout,
+ )
+
+ if not self.async_client:
+ self.async_client = httpx.AsyncClient(
+ base_url=self.base_url,
+ headers=self.default_headers(),
+ timeout=self.timeout,
+ )
+
+ return self
+
+ def _is_new_api_key(self) -> bool:
+ if self.ncp_clovastudio_api_key:
+ return self.ncp_clovastudio_api_key.get_secret_value().startswith("nv-")
+ else:
+ return False
+
+ def _init_fields_on_old_api_key(self) -> None:
+ if not self.ncp_apigw_api_key:
+ self.ncp_apigw_api_key = convert_to_secret_str(
+ get_from_env("ncp_apigw_api_key", "NCP_APIGW_API_KEY", "")
+ )
+
+ def default_headers(self) -> Dict[str, Any]:
+ headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ }
+
+ clovastudio_api_key = (
+ self.ncp_clovastudio_api_key.get_secret_value()
+ if self.ncp_clovastudio_api_key
+ else None
+ )
+
+ if self._is_new_api_key():
+ ### headers on new api key
+ headers["Authorization"] = f"Bearer {clovastudio_api_key}"
+ else:
+ ### headers on old api key
+ if clovastudio_api_key:
+ headers["X-NCP-CLOVASTUDIO-API-KEY"] = clovastudio_api_key
+
+ apigw_api_key = (
+ self.ncp_apigw_api_key.get_secret_value()
+ if self.ncp_apigw_api_key
+ else None
+ )
+ if apigw_api_key:
+ headers["X-NCP-APIGW-API-KEY"] = apigw_api_key
+
+ return headers
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage], stop: Optional[List[str]]
+ ) -> Tuple[List[Dict], Dict[str, Any]]:
+ params = self._client_params
+ if stop is not None and "stopBefore" in params:
+ params["stopBefore"] = stop
+
+ message_dicts = [_convert_message_to_naver_chat_message(m) for m in messages]
+ return message_dicts, params
+
+ def _completion_with_retry(self, **kwargs: Any) -> Any:
+ from httpx_sse import (
+ ServerSentEvent,
+ connect_sse,
+ )
+
+ if "stream" not in kwargs:
+ kwargs["stream"] = False
+
+ stream = kwargs["stream"]
+ client = cast(httpx.Client, self.client)
+ if stream:
+
+ def iter_sse() -> Iterator[ServerSentEvent]:
+ with connect_sse(
+ client, "POST", self._api_url, json=kwargs
+ ) as event_source:
+ _raise_on_error(event_source.response)
+ for sse in event_source.iter_sse():
+ event_data = sse.json()
+ if (
+ sse.event == "signal"
+ and event_data.get("data", {}) == "[DONE]"
+ ):
+ return
+ if sse.event == "error":
+ raise SSEError(message=sse.data)
+ yield sse
+
+ return iter_sse()
+ else:
+ response = client.post(url=self._api_url, json=kwargs)
+ _raise_on_error(response)
+ return response.json()
+
+ async def _acompletion_with_retry(
+ self,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Any:
+ from httpx_sse import aconnect_sse
+
+ """Use tenacity to retry the async completion call."""
+ retry_decorator = _create_retry_decorator(self, run_manager=run_manager)
+
+ @retry_decorator
+ async def _completion_with_retry(**kwargs: Any) -> Any:
+ if "stream" not in kwargs:
+ kwargs["stream"] = False
+ stream = kwargs["stream"]
+ async_client = cast(httpx.AsyncClient, self.async_client)
+ if stream:
+ event_source = aconnect_sse(
+ async_client, "POST", self._api_url, json=kwargs
+ )
+ return _aiter_sse(event_source)
+ else:
+ response = await async_client.post(url=self._api_url, json=kwargs)
+ await _araise_on_error(response)
+ return response.json()
+
+ return await _completion_with_retry(**kwargs)
+
+ def _create_chat_result(self, response: Dict) -> ChatResult:
+ generations = []
+ result = response.get("result", {})
+ msg = result.get("message", {})
+ message = _convert_naver_chat_message_to_message(msg)
+
+ if isinstance(message, AIMessage):
+ message.usage_metadata = {
+ "input_tokens": result.get("inputLength"),
+ "output_tokens": result.get("outputLength"),
+ "total_tokens": result.get("inputLength") + result.get("outputLength"),
+ }
+
+ gen = ChatGeneration(
+ message=message,
+ )
+ generations.append(gen)
+
+ llm_output = {
+ "stop_reason": result.get("stopReason"),
+ "input_length": result.get("inputLength"),
+ "output_length": result.get("outputLength"),
+ "seed": result.get("seed"),
+ "ai_filter": result.get("aiFilter"),
+ }
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+
+ response = self._completion_with_retry(messages=message_dicts, **params)
+
+ return self._create_chat_result(response)
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ for sse in self._completion_with_retry(
+ messages=message_dicts, run_manager=run_manager, **params
+ ):
+ new_chunk = _convert_chunk_to_message_chunk(sse, default_chunk_class)
+ default_chunk_class = new_chunk.__class__
+ gen_chunk = ChatGenerationChunk(message=new_chunk)
+
+ if run_manager:
+ run_manager.on_llm_new_token(
+ token=cast(str, new_chunk.content), chunk=gen_chunk
+ )
+
+ yield gen_chunk
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+
+ response = await self._acompletion_with_retry(
+ messages=message_dicts, run_manager=run_manager, **params
+ )
+
+ return self._create_chat_result(response)
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ async for chunk in await self._acompletion_with_retry(
+ messages=message_dicts, run_manager=run_manager, **params
+ ):
+ new_chunk = _convert_chunk_to_message_chunk(chunk, default_chunk_class)
+ default_chunk_class = new_chunk.__class__
+ gen_chunk = ChatGenerationChunk(message=new_chunk)
+
+ if run_manager:
+ await run_manager.on_llm_new_token(
+ token=cast(str, new_chunk.content), chunk=gen_chunk
+ )
+
+ yield gen_chunk
+
+
+def _create_retry_decorator(
+ llm: ChatClovaX,
+ run_manager: Optional[
+ Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]
+ ] = None,
+) -> Callable[[Any], Any]:
+ """Returns a tenacity retry decorator, preconfigured to handle exceptions"""
+
+ errors = [httpx.RequestError, httpx.StreamError]
+ return create_base_retry_decorator(
+ error_types=errors, max_retries=llm.max_retries, run_manager=run_manager
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/oci_data_science.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/oci_data_science.py
new file mode 100644
index 0000000000000000000000000000000000000000..439cd85cef239350ab0353cc1a02e6e50afeebac
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/oci_data_science.py
@@ -0,0 +1,1036 @@
+# Copyright (c) 2024, Oracle and/or its affiliates.
+
+"""Chat model for OCI data science model deployment endpoint."""
+
+import importlib
+import json
+import logging
+from operator import itemgetter
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Literal,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+)
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+)
+from langchain_core.output_parsers import (
+ JsonOutputParser,
+ PydanticOutputParser,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
+from langchain_core.tools import BaseTool
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from pydantic import BaseModel, Field, model_validator
+
+from langchain_community.llms.oci_data_science_model_deployment_endpoint import (
+ DEFAULT_MODEL_NAME,
+ BaseOCIModelDeployment,
+)
+
+logger = logging.getLogger(__name__)
+DEFAULT_INFERENCE_ENDPOINT_CHAT = "/v1/chat/completions"
+
+
+def _is_pydantic_class(obj: Any) -> bool:
+ return isinstance(obj, type) and issubclass(obj, BaseModel)
+
+
+class ChatOCIModelDeployment(BaseChatModel, BaseOCIModelDeployment):
+ """OCI Data Science Model Deployment chat model integration.
+
+ Prerequisite
+ The OCI Model Deployment plugins are installable only on
+ python version 3.9 and above. If you're working inside the notebook,
+ try installing the python 3.10 based conda pack and running the
+ following setup.
+
+
+ Setup:
+ Install ``oracle-ads`` and ``langchain-openai``.
+
+ .. code-block:: bash
+
+ pip install -U oracle-ads langchain-openai
+
+ Use `ads.set_auth()` to configure authentication.
+ For example, to use OCI resource_principal for authentication:
+
+ .. code-block:: python
+
+ import ads
+ ads.set_auth("resource_principal")
+
+ For more details on authentication, see:
+ https://accelerated-data-science.readthedocs.io/en/latest/user_guide/cli/authentication.html
+
+ Make sure to have the required policies to access the OCI Data
+ Science Model Deployment endpoint. See:
+ https://docs.oracle.com/en-us/iaas/data-science/using/model-dep-policies-auth.htm
+
+
+ Key init args - completion params:
+ endpoint: str
+ The OCI model deployment endpoint.
+ temperature: float
+ Sampling temperature.
+ max_tokens: Optional[int]
+ Max number of tokens to generate.
+
+ Key init args — client params:
+ auth: dict
+ ADS auth dictionary for OCI authentication.
+ default_headers: Optional[Dict]
+ The headers to be added to the Model Deployment request.
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatOCIModelDeployment
+
+ chat = ChatOCIModelDeployment(
+ endpoint="https://modeldeployment..oci.customer-oci.com//predict",
+ model="odsc-llm", # this is the default model name if deployed with AQUA
+ streaming=True,
+ max_retries=3,
+ model_kwargs={
+ "max_token": 512,
+ "temperature": 0.2,
+ # other model parameters ...
+ },
+ default_headers={
+ "route": "/v1/chat/completions",
+ # other request headers ...
+ },
+ )
+
+ Invocation:
+ .. code-block:: python
+
+ messages = [
+ ("system", "Translate the user sentence to French."),
+ ("human", "Hello World!"),
+ ]
+ chat.invoke(messages)
+
+ .. code-block:: python
+
+ AIMessage(
+ content='Bonjour le monde!',
+ response_metadata={
+ 'token_usage': {
+ 'prompt_tokens': 40,
+ 'total_tokens': 50,
+ 'completion_tokens': 10
+ },
+ 'model_name': 'odsc-llm',
+ 'system_fingerprint': '',
+ 'finish_reason': 'stop'
+ },
+ id='run-cbed62da-e1b3-4abd-9df3-ec89d69ca012-0'
+ )
+
+ Streaming:
+ .. code-block:: python
+
+ for chunk in chat.stream(messages):
+ print(chunk)
+
+ .. code-block:: python
+
+ content='' id='run-02c6-c43f-42de'
+ content='\n' id='run-02c6-c43f-42de'
+ content='B' id='run-02c6-c43f-42de'
+ content='on' id='run-02c6-c43f-42de'
+ content='j' id='run-02c6-c43f-42de'
+ content='our' id='run-02c6-c43f-42de'
+ content=' le' id='run-02c6-c43f-42de'
+ content=' monde' id='run-02c6-c43f-42de'
+ content='!' id='run-02c6-c43f-42de'
+ content='' response_metadata={'finish_reason': 'stop'} id='run-02c6-c43f-42de'
+
+ Async:
+ .. code-block:: python
+
+ await chat.ainvoke(messages)
+
+ # stream:
+ # async for chunk in (await chat.astream(messages))
+
+ .. code-block:: python
+
+ AIMessage(
+ content='Bonjour le monde!',
+ response_metadata={'finish_reason': 'stop'},
+ id='run-8657a105-96b7-4bb6-b98e-b69ca420e5d1-0'
+ )
+
+ Structured output:
+ .. code-block:: python
+
+ from typing import Optional
+ from pydantic import BaseModel, Field
+
+ class Joke(BaseModel):
+ setup: str = Field(description="The setup of the joke")
+ punchline: str = Field(description="The punchline to the joke")
+
+ structured_llm = chat.with_structured_output(Joke, method="json_mode")
+ structured_llm.invoke(
+ "Tell me a joke about cats, "
+ "respond in JSON with `setup` and `punchline` keys"
+ )
+
+ .. code-block:: python
+
+ Joke(
+ setup='Why did the cat get stuck in the tree?',
+ punchline='Because it was chasing its tail!'
+ )
+
+ See ``ChatOCIModelDeployment.with_structured_output()`` for more.
+
+ Customized Usage:
+ You can inherit from base class and overwrite the `_process_response`,
+ `_process_stream_response`, `_construct_json_body` for customized usage.
+
+ .. code-block:: python
+
+ class MyChatModel(ChatOCIModelDeployment):
+ def _process_stream_response(self, response_json: dict) -> ChatGenerationChunk:
+ print("My customized streaming result handler.")
+ return GenerationChunk(...)
+
+ def _process_response(self, response_json:dict) -> ChatResult:
+ print("My customized output handler.")
+ return ChatResult(...)
+
+ def _construct_json_body(self, messages: list, params: dict) -> dict:
+ print("My customized payload handler.")
+ return {
+ "messages": messages,
+ **params,
+ }
+
+ chat = MyChatModel(
+ endpoint=f"https://modeldeployment..oci.customer-oci.com/{ocid}/predict",
+ model="odsc-llm",
+ }
+
+ chat.invoke("tell me a joke")
+
+ Response metadata
+ .. code-block:: python
+
+ ai_msg = chat.invoke(messages)
+ ai_msg.response_metadata
+
+ .. code-block:: python
+
+ {
+ 'token_usage': {
+ 'prompt_tokens': 40,
+ 'total_tokens': 50,
+ 'completion_tokens': 10
+ },
+ 'model_name': 'odsc-llm',
+ 'system_fingerprint': '',
+ 'finish_reason': 'stop'
+ }
+
+ """ # noqa: E501
+
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass to the model."""
+
+ model: str = DEFAULT_MODEL_NAME
+ """The name of the model."""
+
+ stop: Optional[List[str]] = None
+ """Stop words to use when generating. Model output is cut off
+ at the first occurrence of any of these substrings."""
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_openai(cls, values: Any) -> Any:
+ """Checks if langchain_openai is installed."""
+ if not importlib.util.find_spec("langchain_openai"):
+ raise ImportError(
+ "Could not import langchain_openai package. "
+ "Please install it with `pip install langchain_openai`."
+ )
+ return values
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "oci_model_depolyment_chat_endpoint"
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ _model_kwargs = self.model_kwargs or {}
+ return {
+ **{"endpoint": self.endpoint, "model_kwargs": _model_kwargs},
+ **self._default_params,
+ }
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters."""
+ return {
+ "model": self.model,
+ "stop": self.stop,
+ "stream": self.streaming,
+ }
+
+ def _headers(
+ self, is_async: Optional[bool] = False, body: Optional[dict] = None
+ ) -> Dict:
+ """Construct and return the headers for a request.
+
+ Args:
+ is_async (bool, optional): Indicates if the request is asynchronous.
+ Defaults to `False`.
+ body (optional): The request body to be included in the headers if
+ the request is asynchronous.
+
+ Returns:
+ `dict` containing the appropriate headers for the request.
+ """
+ return {
+ "route": DEFAULT_INFERENCE_ENDPOINT_CHAT,
+ **super()._headers(is_async=is_async, body=body),
+ }
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Call out to an OCI Model Deployment Online endpoint.
+
+ Args:
+ messages: The messages in the conversation with the chat model.
+ stop: Optional list of stop words to use when generating.
+
+ Returns:
+ LangChain ChatResult
+
+ Raises:
+ RuntimeError:
+ Raise when invoking endpoint fails.
+
+ Example:
+
+ .. code-block:: python
+
+ messages = [
+ (
+ "system",
+ "You are a helpful assistant that translates English to French. Translate the user sentence.",
+ ),
+ ("human", "Hello World!"),
+ ]
+
+ response = chat.invoke(messages)
+ """ # noqa: E501
+ if self.streaming:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ requests_kwargs = kwargs.pop("requests_kwargs", {})
+ params = self._invocation_params(stop, **kwargs)
+ body = self._construct_json_body(messages, params)
+ res = self.completion_with_retry(
+ data=body, run_manager=run_manager, **requests_kwargs
+ )
+ return self._process_response(res.json())
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ """Stream OCI Data Science Model Deployment endpoint on given messages.
+
+ Args:
+ messages (List[BaseMessage]):
+ The messagaes to pass into the model.
+ stop (List[str], Optional):
+ List of stop words to use when generating.
+ kwargs:
+ requests_kwargs:
+ Additional ``**kwargs`` to pass to requests.post
+
+ Returns:
+ An iterator of ChatGenerationChunk.
+
+ Raises:
+ RuntimeError:
+ Raise when invoking endpoint fails.
+
+ Example:
+
+ .. code-block:: python
+
+ messages = [
+ (
+ "system",
+ "You are a helpful assistant that translates English to French. Translate the user sentence.",
+ ),
+ ("human", "Hello World!"),
+ ]
+
+ chunk_iter = chat.stream(messages)
+
+ """ # noqa: E501
+ requests_kwargs = kwargs.pop("requests_kwargs", {})
+ self.streaming = True
+ params = self._invocation_params(stop, **kwargs)
+ body = self._construct_json_body(messages, params) # request json body
+
+ response = self.completion_with_retry(
+ data=body, run_manager=run_manager, stream=True, **requests_kwargs
+ )
+ default_chunk_class = AIMessageChunk
+ for line in self._parse_stream(response.iter_lines()):
+ chunk = self._handle_sse_line(line, default_chunk_class)
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Asynchronously call out to OCI Data Science Model Deployment
+ endpoint on given messages.
+
+ Args:
+ messages (List[BaseMessage]):
+ The messagaes to pass into the model.
+ stop (List[str], Optional):
+ List of stop words to use when generating.
+ kwargs:
+ requests_kwargs:
+ Additional ``**kwargs`` to pass to requests.post
+
+ Returns:
+ LangChain ChatResult.
+
+ Raises:
+ ValueError:
+ Raise when invoking endpoint fails.
+
+ Example:
+
+ .. code-block:: python
+
+ messages = [
+ (
+ "system",
+ "You are a helpful assistant that translates English to French. Translate the user sentence.",
+ ),
+ ("human", "I love programming."),
+ ]
+
+ resp = await chat.ainvoke(messages)
+
+ """ # noqa: E501
+ if self.streaming:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ requests_kwargs = kwargs.pop("requests_kwargs", {})
+ params = self._invocation_params(stop, **kwargs)
+ body = self._construct_json_body(messages, params)
+ response = await self.acompletion_with_retry(
+ data=body,
+ run_manager=run_manager,
+ **requests_kwargs,
+ )
+ return self._process_response(response)
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ """Asynchronously streaming OCI Data Science Model Deployment
+ endpoint on given messages.
+
+ Args:
+ messages (List[BaseMessage]):
+ The messagaes to pass into the model.
+ stop (List[str], Optional):
+ List of stop words to use when generating.
+ kwargs:
+ requests_kwargs:
+ Additional ``**kwargs`` to pass to requests.post
+
+ Returns:
+ An Asynciterator of ChatGenerationChunk.
+
+ Raises:
+ ValueError:
+ Raise when invoking endpoint fails.
+
+ Example:
+
+ .. code-block:: python
+
+ messages = [
+ (
+ "system",
+ "You are a helpful assistant that translates English to French. Translate the user sentence.",
+ ),
+ ("human", "I love programming."),
+ ]
+
+ chunk_iter = await chat.astream(messages)
+
+ """ # noqa: E501
+ requests_kwargs = kwargs.pop("requests_kwargs", {})
+ self.streaming = True
+ params = self._invocation_params(stop, **kwargs)
+ body = self._construct_json_body(messages, params) # request json body
+
+ default_chunk_class = AIMessageChunk
+ async for line in await self.acompletion_with_retry(
+ data=body, run_manager=run_manager, stream=True, **requests_kwargs
+ ):
+ chunk = self._handle_sse_line(line, default_chunk_class)
+ if run_manager:
+ await run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+
+ def with_structured_output(
+ self,
+ schema: Optional[Union[Dict, Type[BaseModel]]] = None,
+ *,
+ method: Literal["json_mode"] = "json_mode",
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, Union[Dict, BaseModel]]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema: The output schema as a dict or a Pydantic class. If a Pydantic class
+ then the model output will be an object of that class. If a dict then
+ the model output will be a dict. With a Pydantic class the returned
+ attributes will be validated, whereas with a dict they will not be. If
+ `method` is "function_calling" and `schema` is a dict, then the dict
+ must match the OpenAI function-calling spec.
+ method: The method for steering model generation, currently only support
+ for "json_mode". If "json_mode" then JSON mode will be used. Note that
+ if using "json_mode" then you must include instructions for formatting
+ the output into the desired schema into the model call.
+ include_raw: If False then only the parsed structured output is returned. If
+ an error occurs during model output parsing it will be raised. If True
+ then both the raw model response (a BaseMessage) and the parsed model
+ response will be returned. If an error occurs during output parsing it
+ will be caught and returned as well. The final output is always a dict
+ with keys "raw", "parsed", and "parsing_error".
+
+ Returns:
+ A Runnable that takes any ChatModel input and returns as output:
+
+ If include_raw is True then a dict with keys:
+ raw: BaseMessage
+ parsed: Optional[_DictOrPydantic]
+ parsing_error: Optional[BaseException]
+
+ If include_raw is False then just _DictOrPydantic is returned,
+ where _DictOrPydantic depends on the schema:
+
+ If schema is a Pydantic class then _DictOrPydantic is the Pydantic
+ class.
+
+ If schema is a dict then _DictOrPydantic is a dict.
+
+ """ # noqa: E501
+ if kwargs:
+ raise ValueError(f"Received unsupported arguments {kwargs}")
+ is_pydantic_schema = _is_pydantic_class(schema)
+ if method == "json_mode":
+ llm = self.bind(response_format={"type": "json_object"})
+ output_parser = (
+ PydanticOutputParser(pydantic_object=schema) # type: ignore[arg-type]
+ if is_pydantic_schema
+ else JsonOutputParser()
+ )
+ else:
+ raise ValueError(
+ f"Unrecognized method argument. Expected `json_mode`."
+ f"Received: `{method}`."
+ )
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ else:
+ return llm | output_parser
+
+ def _invocation_params(self, stop: Optional[List[str]], **kwargs: Any) -> dict:
+ """Combines the invocation parameters with default parameters."""
+ params = self._default_params
+ _model_kwargs = self.model_kwargs or {}
+ params["stop"] = stop or params.get("stop", [])
+ return {**params, **_model_kwargs, **kwargs}
+
+ def _handle_sse_line(
+ self, line: str, default_chunk_cls: Type[BaseMessageChunk] = AIMessageChunk
+ ) -> ChatGenerationChunk:
+ """Handle a single Server-Sent Events (SSE) line and process it into
+ a chat generation chunk.
+
+ Args:
+ line (str): A single line from the SSE stream in string format.
+ default_chunk_cls (AIMessageChunk): The default class for message
+ chunks to be used during the processing of the stream response.
+
+ Returns:
+ ChatGenerationChunk: The processed chat generation chunk. If an error
+ occurs, an empty `ChatGenerationChunk` is returned.
+ """
+ try:
+ obj = json.loads(line)
+ return self._process_stream_response(obj, default_chunk_cls)
+ except Exception as e:
+ logger.debug(f"Error occurs when processing line={line}: {str(e)}")
+ return ChatGenerationChunk(message=AIMessageChunk(content=""))
+
+ def _construct_json_body(self, messages: list, params: dict) -> dict:
+ """Constructs the request body as a dictionary (JSON).
+
+ Args:
+ messages (list): A list of message objects to be included in the
+ request body.
+ params (dict): A dictionary of additional parameters to be included
+ in the request body.
+
+ Returns:
+ dict: A dictionary representing the JSON request body, including
+ converted messages and additional parameters.
+
+ """
+ from langchain_openai.chat_models.base import _convert_message_to_dict
+
+ return {
+ "messages": [_convert_message_to_dict(m) for m in messages],
+ **params,
+ }
+
+ def _process_stream_response(
+ self,
+ response_json: dict,
+ default_chunk_cls: Type[BaseMessageChunk] = AIMessageChunk,
+ ) -> ChatGenerationChunk:
+ """Formats streaming response in OpenAI spec.
+
+ Args:
+ response_json (dict): The JSON response from the streaming endpoint.
+ default_chunk_cls (type, optional): The default class to use for
+ creating message chunks. Defaults to `AIMessageChunk`.
+
+ Returns:
+ ChatGenerationChunk: An object containing the processed message
+ chunk and any relevant generation information such as finish
+ reason and usage.
+
+ Raises:
+ ValueError: If the response JSON is not well-formed or does not
+ contain the expected structure.
+ """
+ from langchain_openai.chat_models.base import _convert_delta_to_message_chunk
+
+ try:
+ choice = response_json["choices"][0]
+ if not isinstance(choice, dict):
+ raise TypeError("Endpoint response is not well formed.")
+ except (KeyError, IndexError, TypeError) as e:
+ raise ValueError(
+ "Error while formatting response payload for chat model of type"
+ ) from e
+
+ chunk = _convert_delta_to_message_chunk(choice["delta"], default_chunk_cls)
+ default_chunk_cls = chunk.__class__
+ finish_reason = choice.get("finish_reason")
+ usage = choice.get("usage")
+ gen_info = {}
+ if finish_reason is not None:
+ gen_info.update({"finish_reason": finish_reason})
+ if usage is not None:
+ gen_info.update({"usage": usage})
+
+ return ChatGenerationChunk(
+ message=chunk, generation_info=gen_info if gen_info else None
+ )
+
+ def _process_response(self, response_json: dict) -> ChatResult:
+ """Formats response in OpenAI spec.
+
+ Args:
+ response_json (dict): The JSON response from the chat model endpoint.
+
+ Returns:
+ ChatResult: An object containing the list of `ChatGeneration` objects
+ and additional LLM output information.
+
+ Raises:
+ ValueError: If the response JSON is not well-formed or does not
+ contain the expected structure.
+
+ """
+ from langchain_openai.chat_models.base import _convert_dict_to_message
+
+ generations = []
+ try:
+ choices = response_json["choices"]
+ if not isinstance(choices, list):
+ raise TypeError("Endpoint response is not well formed.")
+ except (KeyError, TypeError) as e:
+ raise ValueError(
+ "Error while formatting response payload for chat model of type"
+ ) from e
+
+ for choice in choices:
+ message = _convert_dict_to_message(choice["message"])
+ generation_info = {"finish_reason": choice.get("finish_reason")}
+ if "logprobs" in choice:
+ generation_info["logprobs"] = choice["logprobs"]
+
+ gen = ChatGeneration(
+ message=message,
+ generation_info=generation_info,
+ )
+ generations.append(gen)
+
+ token_usage = response_json.get("usage", {})
+ llm_output = {
+ "token_usage": token_usage,
+ "model_name": self.model,
+ "system_fingerprint": response_json.get("system_fingerprint", ""),
+ }
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ return super().bind(tools=formatted_tools, **kwargs)
+
+
+class ChatOCIModelDeploymentVLLM(ChatOCIModelDeployment):
+ """OCI large language chat models deployed with vLLM.
+
+ To use, you must provide the model HTTP endpoint from your deployed
+ model, e.g. https://modeldeployment.us-ashburn-1.oci.customer-oci.com//predict.
+
+ To authenticate, `oracle-ads` has been used to automatically load
+ credentials: https://accelerated-data-science.readthedocs.io/en/latest/user_guide/cli/authentication.html
+
+ Make sure to have the required policies to access the OCI Data
+ Science Model Deployment endpoint. See:
+ https://docs.oracle.com/en-us/iaas/data-science/using/model-dep-policies-auth.htm#model_dep_policies_auth__predict-endpoint
+
+ Example:
+
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatOCIModelDeploymentVLLM
+
+ chat = ChatOCIModelDeploymentVLLM(
+ endpoint="https://modeldeployment.us-ashburn-1.oci.customer-oci.com//predict",
+ frequency_penalty=0.1,
+ max_tokens=512,
+ temperature=0.2,
+ top_p=1.0,
+ # other model parameters...
+ )
+
+ """ # noqa: E501
+
+ frequency_penalty: float = 0.0
+ """Penalizes repeated tokens according to frequency. Between 0 and 1."""
+
+ logit_bias: Optional[Dict[str, float]] = None
+ """Adjust the probability of specific tokens being generated."""
+
+ max_tokens: Optional[int] = 256
+ """The maximum number of tokens to generate in the completion."""
+
+ n: int = 1
+ """Number of output sequences to return for the given prompt."""
+
+ presence_penalty: float = 0.0
+ """Penalizes repeated tokens. Between 0 and 1."""
+
+ temperature: float = 0.2
+ """What sampling temperature to use."""
+
+ top_p: float = 1.0
+ """Total probability mass of tokens to consider at each step."""
+
+ best_of: Optional[int] = None
+ """Generates best_of completions server-side and returns the "best"
+ (the one with the highest log probability per token).
+ """
+
+ use_beam_search: Optional[bool] = False
+ """Whether to use beam search instead of sampling."""
+
+ top_k: Optional[int] = -1
+ """Number of most likely tokens to consider at each step."""
+
+ min_p: Optional[float] = 0.0
+ """Float that represents the minimum probability for a token to be considered.
+ Must be in [0,1]. 0 to disable this."""
+
+ repetition_penalty: Optional[float] = 1.0
+ """Float that penalizes new tokens based on their frequency in the
+ generated text. Values > 1 encourage the model to use new tokens."""
+
+ length_penalty: Optional[float] = 1.0
+ """Float that penalizes sequences based on their length. Used only
+ when `use_beam_search` is True."""
+
+ early_stopping: Optional[bool] = False
+ """Controls the stopping condition for beam search. It accepts the
+ following values: `True`, where the generation stops as soon as there
+ are `best_of` complete candidates; `False`, where a heuristic is applied
+ to the generation stops when it is very unlikely to find better candidates;
+ `never`, where the beam search procedure only stops where there cannot be
+ better candidates (canonical beam search algorithm)."""
+
+ ignore_eos: Optional[bool] = False
+ """Whether to ignore the EOS token and continue generating tokens after
+ the EOS token is generated."""
+
+ min_tokens: Optional[int] = 0
+ """Minimum number of tokens to generate per output sequence before
+ EOS or stop_token_ids can be generated"""
+
+ stop_token_ids: Optional[List[int]] = None
+ """List of tokens that stop the generation when they are generated.
+ The returned output will contain the stop tokens unless the stop tokens
+ are special tokens."""
+
+ skip_special_tokens: Optional[bool] = True
+ """Whether to skip special tokens in the output. Defaults to True."""
+
+ spaces_between_special_tokens: Optional[bool] = True
+ """Whether to add spaces between special tokens in the output.
+ Defaults to True."""
+
+ tool_choice: Optional[str] = None
+ """Whether to use tool calling.
+ Defaults to None, tool calling is disabled.
+ Tool calling requires model support and the vLLM to be configured
+ with `--tool-call-parser`.
+ Set this to `auto` for the model to make tool calls automatically.
+ Set this to `required` to force the model to always call one or more tools.
+ """
+
+ chat_template: Optional[str] = None
+ """Use customized chat template.
+ Defaults to None. The chat template from the tokenizer will be used.
+ """
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "oci_model_depolyment_chat_endpoint_vllm"
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters."""
+ params = {
+ "model": self.model,
+ "stop": self.stop,
+ "stream": self.streaming,
+ }
+ for attr_name in self._get_model_params():
+ try:
+ value = getattr(self, attr_name)
+ if value is not None:
+ params.update({attr_name: value})
+ except Exception:
+ pass
+
+ return params
+
+ def _get_model_params(self) -> List[str]:
+ """Gets the name of model parameters."""
+ return [
+ "best_of",
+ "early_stopping",
+ "frequency_penalty",
+ "ignore_eos",
+ "length_penalty",
+ "logit_bias",
+ "logprobs",
+ "max_tokens",
+ "min_p",
+ "min_tokens",
+ "n",
+ "presence_penalty",
+ "repetition_penalty",
+ "skip_special_tokens",
+ "spaces_between_special_tokens",
+ "stop_token_ids",
+ "temperature",
+ "top_k",
+ "top_p",
+ "use_beam_search",
+ "tool_choice",
+ "chat_template",
+ ]
+
+
+class ChatOCIModelDeploymentTGI(ChatOCIModelDeployment):
+ """OCI large language chat models deployed with Text Generation Inference.
+
+ To use, you must provide the model HTTP endpoint from your deployed
+ model, e.g. https://modeldeployment.us-ashburn-1.oci.customer-oci.com//predict.
+
+ To authenticate, `oracle-ads` has been used to automatically load
+ credentials: https://accelerated-data-science.readthedocs.io/en/latest/user_guide/cli/authentication.html
+
+ Make sure to have the required policies to access the OCI Data
+ Science Model Deployment endpoint. See:
+ https://docs.oracle.com/en-us/iaas/data-science/using/model-dep-policies-auth.htm#model_dep_policies_auth__predict-endpoint
+
+ Example:
+
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatOCIModelDeploymentTGI
+
+ chat = ChatOCIModelDeploymentTGI(
+ endpoint="https://modeldeployment.us-ashburn-1.oci.customer-oci.com//predict",
+ max_token=512,
+ temperature=0.2,
+ frequency_penalty=0.1,
+ seed=42,
+ # other model parameters...
+ )
+
+ """ # noqa: E501
+
+ frequency_penalty: Optional[float] = None
+ """Penalizes repeated tokens according to frequency. Between 0 and 1."""
+
+ logit_bias: Optional[Dict[str, float]] = None
+ """Adjust the probability of specific tokens being generated."""
+
+ logprobs: Optional[bool] = None
+ """Whether to return log probabilities of the output tokens or not."""
+
+ max_tokens: int = 256
+ """The maximum number of tokens to generate in the completion."""
+
+ n: int = 1
+ """Number of output sequences to return for the given prompt."""
+
+ presence_penalty: Optional[float] = None
+ """Penalizes repeated tokens. Between 0 and 1."""
+
+ seed: Optional[int] = None
+ """To sample deterministically,"""
+
+ temperature: float = 0.2
+ """What sampling temperature to use."""
+
+ top_p: Optional[float] = None
+ """Total probability mass of tokens to consider at each step."""
+
+ top_logprobs: Optional[int] = None
+ """An integer between 0 and 5 specifying the number of most
+ likely tokens to return at each token position, each with an
+ associated log probability. logprobs must be set to true if
+ this parameter is used."""
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "oci_model_depolyment_chat_endpoint_tgi"
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters."""
+ params = {
+ "model": self.model,
+ "stop": self.stop,
+ "stream": self.streaming,
+ }
+ for attr_name in self._get_model_params():
+ try:
+ value = getattr(self, attr_name)
+ if value is not None:
+ params.update({attr_name: value})
+ except Exception:
+ pass
+
+ return params
+
+ def _get_model_params(self) -> List[str]:
+ """Gets the name of model parameters."""
+ return [
+ "frequency_penalty",
+ "logit_bias",
+ "logprobs",
+ "max_tokens",
+ "n",
+ "presence_penalty",
+ "seed",
+ "temperature",
+ "top_k",
+ "top_p",
+ "top_logprobs",
+ ]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/oci_generative_ai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/oci_generative_ai.py
new file mode 100644
index 0000000000000000000000000000000000000000..914cb9c81f23b55543250a3fc5a36a2487169592
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/oci_generative_ai.py
@@ -0,0 +1,865 @@
+import json
+import re
+import uuid
+from abc import ABC, abstractmethod
+from operator import itemgetter
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Literal,
+ Mapping,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+)
+
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+ ToolCall,
+ ToolMessage,
+)
+from langchain_core.messages.tool import ToolCallChunk
+from langchain_core.output_parsers import (
+ JsonOutputParser,
+ PydanticOutputParser,
+)
+from langchain_core.output_parsers.base import OutputParserLike
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ PydanticToolsParser,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
+from langchain_core.tools import BaseTool
+from langchain_core.utils.function_calling import convert_to_openai_function
+from pydantic import BaseModel, ConfigDict
+
+from langchain_community.llms.oci_generative_ai import OCIGenAIBase
+from langchain_community.llms.utils import enforce_stop_tokens
+
+CUSTOM_ENDPOINT_PREFIX = "ocid1.generativeaiendpoint"
+
+JSON_TO_PYTHON_TYPES = {
+ "string": "str",
+ "number": "float",
+ "boolean": "bool",
+ "integer": "int",
+ "array": "List",
+ "object": "Dict",
+ "any": "any",
+}
+
+
+def _is_pydantic_class(obj: Any) -> bool:
+ return isinstance(obj, type) and issubclass(obj, BaseModel)
+
+
+def _remove_signature_from_tool_description(name: str, description: str) -> str:
+ """
+ Removes the `{name}{signature} - ` prefix and Args: section from tool description.
+ The signature is usually present for tools created with the @tool decorator,
+ whereas the Args: section may be present in function doc blocks.
+ """
+ description = re.sub(rf"^{name}\(.*?\) -(?:> \w+? -)? ", "", description)
+ description = re.sub(r"(?s)(?:\n?\n\s*?)?Args:.*$", "", description)
+ return description
+
+
+def _format_oci_tool_calls(
+ tool_calls: Optional[List[Any]] = None,
+) -> List[Dict]:
+ """
+ Formats a OCI GenAI API response into the tool call format used in Langchain.
+ """
+ if not tool_calls:
+ return []
+
+ formatted_tool_calls = []
+ for tool_call in tool_calls:
+ formatted_tool_calls.append(
+ {
+ "id": uuid.uuid4().hex[:],
+ "function": {
+ "name": tool_call.name,
+ "arguments": json.dumps(tool_call.parameters),
+ },
+ "type": "function",
+ }
+ )
+ return formatted_tool_calls
+
+
+def _convert_oci_tool_call_to_langchain(tool_call: Any) -> ToolCall:
+ """Convert a OCI GenAI tool call into langchain_core.messages.ToolCall"""
+ _id = uuid.uuid4().hex[:]
+ return ToolCall(name=tool_call.name, args=tool_call.parameters, id=_id)
+
+
+class Provider(ABC):
+ @property
+ @abstractmethod
+ def stop_sequence_key(self) -> str: ...
+
+ @abstractmethod
+ def chat_response_to_text(self, response: Any) -> str: ...
+
+ @abstractmethod
+ def chat_stream_to_text(self, event_data: Dict) -> str: ...
+
+ @abstractmethod
+ def is_chat_stream_end(self, event_data: Dict) -> bool: ...
+
+ @abstractmethod
+ def chat_generation_info(self, response: Any) -> Dict[str, Any]: ...
+
+ @abstractmethod
+ def chat_stream_generation_info(self, event_data: Dict) -> Dict[str, Any]: ...
+
+ @abstractmethod
+ def get_role(self, message: BaseMessage) -> str: ...
+
+ @abstractmethod
+ def messages_to_oci_params(
+ self, messages: Any, **kwargs: Any
+ ) -> Dict[str, Any]: ...
+
+ @abstractmethod
+ def convert_to_oci_tool(
+ self,
+ tool: Union[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ ) -> Dict[str, Any]: ...
+
+
+class CohereProvider(Provider):
+ stop_sequence_key: str = "stop_sequences"
+
+ def __init__(self) -> None:
+ from oci.generative_ai_inference import models
+
+ self.oci_chat_request = models.CohereChatRequest
+ self.oci_tool = models.CohereTool
+ self.oci_tool_param = models.CohereParameterDefinition
+ self.oci_tool_result = models.CohereToolResult
+ self.oci_tool_call = models.CohereToolCall
+ self.oci_chat_message = {
+ "USER": models.CohereUserMessage,
+ "CHATBOT": models.CohereChatBotMessage,
+ "SYSTEM": models.CohereSystemMessage,
+ "TOOL": models.CohereToolMessage,
+ }
+ self.chat_api_format = models.BaseChatRequest.API_FORMAT_COHERE
+
+ def chat_response_to_text(self, response: Any) -> str:
+ return response.data.chat_response.text
+
+ def chat_stream_to_text(self, event_data: Dict) -> str:
+ if "text" in event_data:
+ if "finishReason" in event_data or "toolCalls" in event_data:
+ return ""
+ else:
+ return event_data["text"]
+ else:
+ return ""
+
+ def is_chat_stream_end(self, event_data: Dict) -> bool:
+ return "finishReason" in event_data
+
+ def chat_generation_info(self, response: Any) -> Dict[str, Any]:
+ generation_info: Dict[str, Any] = {
+ "documents": response.data.chat_response.documents,
+ "citations": response.data.chat_response.citations,
+ "search_queries": response.data.chat_response.search_queries,
+ "is_search_required": response.data.chat_response.is_search_required,
+ "finish_reason": response.data.chat_response.finish_reason,
+ }
+ if response.data.chat_response.tool_calls:
+ # Only populate tool_calls when 1) present on the response and
+ # 2) has one or more calls.
+ generation_info["tool_calls"] = _format_oci_tool_calls(
+ response.data.chat_response.tool_calls
+ )
+
+ return generation_info
+
+ def chat_stream_generation_info(self, event_data: Dict) -> Dict[str, Any]:
+ generation_info: Dict[str, Any] = {
+ "documents": event_data.get("documents"),
+ "citations": event_data.get("citations"),
+ "finish_reason": event_data.get("finishReason"),
+ }
+ if "toolCalls" in event_data:
+ generation_info["tool_calls"] = []
+ for tool_call in event_data["toolCalls"]:
+ generation_info["tool_calls"].append(
+ {
+ "id": uuid.uuid4().hex[:],
+ "function": {
+ "name": tool_call["name"],
+ "arguments": json.dumps(tool_call["parameters"]),
+ },
+ "type": "function",
+ }
+ )
+
+ generation_info = {k: v for k, v in generation_info.items() if v is not None}
+
+ return generation_info
+
+ def get_role(self, message: BaseMessage) -> str:
+ if isinstance(message, HumanMessage):
+ return "USER"
+ elif isinstance(message, AIMessage):
+ return "CHATBOT"
+ elif isinstance(message, SystemMessage):
+ return "SYSTEM"
+ elif isinstance(message, ToolMessage):
+ return "TOOL"
+ else:
+ raise ValueError(f"Got unknown type {message}")
+
+ def messages_to_oci_params(
+ self, messages: Sequence[ChatMessage], **kwargs: Any
+ ) -> Dict[str, Any]:
+ is_force_single_step = kwargs.get("is_force_single_step") or False
+
+ oci_chat_history = []
+
+ for msg in messages[:-1]:
+ if self.get_role(msg) == "USER" or self.get_role(msg) == "SYSTEM":
+ oci_chat_history.append(
+ self.oci_chat_message[self.get_role(msg)](message=msg.content)
+ )
+ elif isinstance(msg, AIMessage):
+ if msg.tool_calls and is_force_single_step:
+ continue
+ tool_calls = (
+ [
+ self.oci_tool_call(name=tc["name"], parameters=tc["args"])
+ for tc in msg.tool_calls
+ ]
+ if msg.tool_calls
+ else None
+ )
+ msg_content = msg.content if msg.content else " "
+ oci_chat_history.append(
+ self.oci_chat_message[self.get_role(msg)](
+ message=msg_content, tool_calls=tool_calls
+ )
+ )
+
+ # Get the messages for the current chat turn
+ current_chat_turn_messages = []
+ for message in messages[::-1]:
+ current_chat_turn_messages.append(message)
+ if isinstance(message, HumanMessage):
+ break
+ current_chat_turn_messages = current_chat_turn_messages[::-1]
+
+ oci_tool_results: Union[List[Any], None] = []
+ for message in current_chat_turn_messages:
+ if isinstance(message, ToolMessage):
+ tool_message = message
+ previous_ai_msgs = [
+ message
+ for message in current_chat_turn_messages
+ if isinstance(message, AIMessage) and message.tool_calls
+ ]
+ if previous_ai_msgs:
+ previous_ai_msg = previous_ai_msgs[-1]
+ for lc_tool_call in previous_ai_msg.tool_calls:
+ if lc_tool_call["id"] == tool_message.tool_call_id:
+ tool_result = self.oci_tool_result()
+ tool_result.call = self.oci_tool_call(
+ name=lc_tool_call["name"],
+ parameters=lc_tool_call["args"],
+ )
+ tool_result.outputs = [{"output": tool_message.content}]
+ oci_tool_results.append(tool_result)
+
+ if not oci_tool_results:
+ oci_tool_results = None
+
+ message_str = "" if oci_tool_results else messages[-1].content
+
+ oci_params = {
+ "message": message_str,
+ "chat_history": oci_chat_history,
+ "tool_results": oci_tool_results,
+ "api_format": self.chat_api_format,
+ }
+
+ return {k: v for k, v in oci_params.items() if v is not None}
+
+ def convert_to_oci_tool(
+ self,
+ tool: Union[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ ) -> Dict[str, Any]:
+ """
+ Convert a BaseTool instance, JSON schema dict, or BaseModel type to a OCI tool.
+ """
+ if isinstance(tool, BaseTool):
+ return self.oci_tool(
+ name=tool.name,
+ description=_remove_signature_from_tool_description(
+ tool.name, tool.description
+ ),
+ parameter_definitions={
+ p_name: self.oci_tool_param(
+ description=p_def.get("description")
+ if "description" in p_def
+ else "",
+ type=JSON_TO_PYTHON_TYPES.get(
+ p_def.get("type"), p_def.get("type", "any")
+ ),
+ is_required="default" not in p_def,
+ )
+ for p_name, p_def in tool.args.items()
+ },
+ )
+ elif isinstance(tool, dict):
+ if not all(k in tool for k in ("title", "description", "properties")):
+ raise ValueError(
+ "Unsupported dict type. Tool must be passed in as a BaseTool instance, JSON schema dict, or BaseModel type." # noqa: E501
+ )
+ return self.oci_tool(
+ name=tool.get("title"),
+ description=tool.get("description"),
+ parameter_definitions={
+ p_name: self.oci_tool_param(
+ description=p_def.get("description"),
+ type=JSON_TO_PYTHON_TYPES.get(
+ p_def.get("type"), p_def.get("type", "any")
+ ),
+ is_required="default" not in p_def,
+ )
+ for p_name, p_def in tool.get("properties", {}).items()
+ },
+ )
+ elif (isinstance(tool, type) and issubclass(tool, BaseModel)) or callable(tool):
+ as_json_schema_function = convert_to_openai_function(tool)
+ parameters = as_json_schema_function.get("parameters", {})
+ properties = parameters.get("properties", {})
+ return self.oci_tool(
+ name=as_json_schema_function.get("name"),
+ description=as_json_schema_function.get(
+ "description",
+ as_json_schema_function.get("name"),
+ ),
+ parameter_definitions={
+ p_name: self.oci_tool_param(
+ description=p_def.get("description"),
+ type=JSON_TO_PYTHON_TYPES.get(
+ p_def.get("type"), p_def.get("type", "any")
+ ),
+ is_required=p_name in parameters.get("required", []),
+ )
+ for p_name, p_def in properties.items()
+ },
+ )
+ else:
+ raise ValueError(
+ f"Unsupported tool type {type(tool)}. Tool must be passed in as a BaseTool instance, JSON schema dict, or BaseModel type." # noqa: E501
+ )
+
+
+class MetaProvider(Provider):
+ stop_sequence_key: str = "stop"
+
+ def __init__(self) -> None:
+ from oci.generative_ai_inference import models
+
+ self.oci_chat_request = models.GenericChatRequest
+ self.oci_chat_message = {
+ "USER": models.UserMessage,
+ "SYSTEM": models.SystemMessage,
+ "ASSISTANT": models.AssistantMessage,
+ }
+ self.oci_chat_message_content = models.ChatContent
+ self.oci_chat_message_text_content = models.TextContent
+ self.oci_chat_message_image_content = models.ImageContent
+ self.oci_chat_message_image_url = models.ImageUrl
+ self.chat_api_format = models.BaseChatRequest.API_FORMAT_GENERIC
+
+ def chat_response_to_text(self, response: Any) -> str:
+ return response.data.chat_response.choices[0].message.content[0].text
+
+ def chat_stream_to_text(self, event_data: Dict) -> str:
+ return event_data["message"]["content"][0]["text"]
+
+ def is_chat_stream_end(self, event_data: Dict) -> bool:
+ return "message" not in event_data
+
+ def chat_generation_info(self, response: Any) -> Dict[str, Any]:
+ return {
+ "finish_reason": response.data.chat_response.choices[0].finish_reason,
+ "time_created": str(response.data.chat_response.time_created),
+ }
+
+ def chat_stream_generation_info(self, event_data: Dict) -> Dict[str, Any]:
+ return {
+ "finish_reason": event_data["finishReason"],
+ }
+
+ def get_role(self, message: BaseMessage) -> str:
+ # meta only supports alternating user/assistant roles
+ if isinstance(message, HumanMessage):
+ return "USER"
+ elif isinstance(message, AIMessage):
+ return "ASSISTANT"
+ elif isinstance(message, SystemMessage):
+ return "SYSTEM"
+ else:
+ raise ValueError(f"Got unknown type {message}")
+
+ def messages_to_oci_params(
+ self, messages: List[BaseMessage], **kwargs: Any
+ ) -> Dict[str, Any]:
+ """Convert LangChain messages to OCI chat parameters.
+
+ Args:
+ messages: List of LangChain BaseMessage objects
+ **kwargs: Additional keyword arguments
+
+ Returns:
+ Dict containing OCI chat parameters
+
+ Raises:
+ ValueError: If message content is invalid
+ """
+ oci_messages = []
+
+ for message in messages:
+ content = self._process_message_content(message.content)
+ oci_message = self.oci_chat_message[self.get_role(message)](content=content)
+ oci_messages.append(oci_message)
+
+ return {
+ "messages": oci_messages,
+ "api_format": self.chat_api_format,
+ "top_k": -1,
+ }
+
+ def _process_message_content(
+ self, content: Union[str, List[Union[str, Dict]]]
+ ) -> List[Any]:
+ """Process message content into OCI chat content format.
+
+ Args:
+ content: Message content as string or list
+
+ Returns:
+ List of OCI chat content objects
+
+ Raises:
+ ValueError: If content format is invalid
+ """
+ if isinstance(content, str):
+ return [self.oci_chat_message_text_content(text=content)]
+
+ if not isinstance(content, list):
+ raise ValueError("Message content must be str or list of items")
+
+ processed_content = []
+ for item in content:
+ if isinstance(item, str):
+ processed_content.append(self.oci_chat_message_text_content(text=item))
+ continue
+
+ if not isinstance(item, dict):
+ raise ValueError(
+ f"Content items must be str or dict, got: {type(item)}"
+ )
+
+ if "type" not in item:
+ raise ValueError("Dict content item must have a type key")
+
+ if item["type"] == "image_url":
+ processed_content.append(
+ self.oci_chat_message_image_content(
+ image_url=self.oci_chat_message_image_url(
+ url=item["image_url"]["url"]
+ )
+ )
+ )
+ elif item["type"] == "text":
+ processed_content.append(
+ self.oci_chat_message_text_content(text=item["text"])
+ )
+ else:
+ raise ValueError(f"Unsupported content type: {item['type']}")
+
+ return processed_content
+
+ def convert_to_oci_tool(
+ self,
+ tool: Union[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ ) -> Dict[str, Any]:
+ raise NotImplementedError("Tools not supported for Meta models")
+
+
+class ChatOCIGenAI(BaseChatModel, OCIGenAIBase):
+ """ChatOCIGenAI chat model integration.
+
+ Setup:
+ Install ``langchain-community`` and the ``oci`` sdk.
+
+ .. code-block:: bash
+
+ pip install -U langchain-community oci
+
+ Key init args — completion params:
+ model_id: str
+ Id of the OCIGenAI chat model to use, e.g., cohere.command-r-16k.
+ is_stream: bool
+ Whether to stream back partial progress
+ model_kwargs: Optional[Dict]
+ Keyword arguments to pass to the specific model used, e.g., temperature, max_tokens.
+
+ Key init args — client params:
+ service_endpoint: str
+ The endpoint URL for the OCIGenAI service, e.g., https://inference.generativeai.us-chicago-1.oci.oraclecloud.com.
+ compartment_id: str
+ The compartment OCID.
+ auth_type: str
+ The authentication type to use, e.g., API_KEY (default), SECURITY_TOKEN, INSTANCE_PRINCIPAL, RESOURCE_PRINCIPAL.
+ auth_profile: Optional[str]
+ The name of the profile in ~/.oci/config, if not specified , DEFAULT will be used.
+ auth_file_location: Optional[str]
+ Path to the config file, If not specified, ~/.oci/config will be used.
+ provider: str
+ Provider name of the model. Default to None, will try to be derived from the model_id otherwise, requires user input.
+ See full list of supported init args and their descriptions in the params section.
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatOCIGenAI
+
+ chat = ChatOCIGenAI(
+ model_id="cohere.command-r-16k",
+ service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",
+ compartment_id="MY_OCID",
+ model_kwargs={"temperature": 0.7, "max_tokens": 500},
+ )
+
+ Invoke:
+ .. code-block:: python
+ messages = [
+ SystemMessage(content="your are an AI assistant."),
+ AIMessage(content="Hi there human!"),
+ HumanMessage(content="tell me a joke."),
+ ]
+ response = chat.invoke(messages)
+
+ Stream:
+ .. code-block:: python
+
+ for r in chat.stream(messages):
+ print(r.content, end="", flush=True)
+
+ Response metadata
+ .. code-block:: python
+
+ response = chat.invoke(messages)
+ print(response.response_metadata)
+
+ """ # noqa: E501
+
+ model_config = ConfigDict(
+ extra="forbid",
+ arbitrary_types_allowed=True,
+ )
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "oci_generative_ai_chat"
+
+ @property
+ def _provider_map(self) -> Mapping[str, Any]:
+ """Get the provider map"""
+ return {
+ "cohere": CohereProvider(),
+ "meta": MetaProvider(),
+ }
+
+ @property
+ def _provider(self) -> Any:
+ """Get the internal provider object"""
+ return self._get_provider(provider_map=self._provider_map)
+
+ def _prepare_request(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]],
+ stream: bool,
+ **kwargs: Any,
+ ) -> Dict[str, Any]:
+ try:
+ from oci.generative_ai_inference import models
+
+ except ImportError as ex:
+ raise ModuleNotFoundError(
+ "Could not import oci python package. "
+ "Please make sure you have the oci package installed."
+ ) from ex
+
+ oci_params = self._provider.messages_to_oci_params(messages, **kwargs)
+
+ oci_params["is_stream"] = stream
+ _model_kwargs = self.model_kwargs or {}
+
+ if stop is not None:
+ _model_kwargs[self._provider.stop_sequence_key] = stop
+
+ chat_params = {**_model_kwargs, **kwargs, **oci_params}
+
+ if not self.model_id:
+ raise ValueError("Model ID is required to chat")
+
+ if self.model_id.startswith(CUSTOM_ENDPOINT_PREFIX):
+ serving_mode = models.DedicatedServingMode(endpoint_id=self.model_id)
+ else:
+ serving_mode = models.OnDemandServingMode(model_id=self.model_id)
+
+ request = models.ChatDetails(
+ compartment_id=self.compartment_id,
+ serving_mode=serving_mode,
+ chat_request=self._provider.oci_chat_request(**chat_params),
+ )
+
+ return request
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ formatted_tools = [self._provider.convert_to_oci_tool(tool) for tool in tools]
+ return super().bind(tools=formatted_tools, **kwargs)
+
+ def with_structured_output(
+ self,
+ schema: Optional[Union[Dict, Type[BaseModel]]] = None,
+ *,
+ method: Literal["function_calling", "json_mode"] = "function_calling",
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, Union[Dict, BaseModel]]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema: The output schema as a dict or a Pydantic class. If a Pydantic class
+ then the model output will be an object of that class. If a dict then
+ the model output will be a dict. With a Pydantic class the returned
+ attributes will be validated, whereas with a dict they will not be. If
+ `method` is "function_calling" and `schema` is a dict, then the dict
+ must match the OCI Generative AI function-calling spec.
+ method:
+ The method for steering model generation, either "function_calling"
+ or "json_mode". If "function_calling" then the schema will be converted
+ to an OCI function and the returned model will make use of the
+ function-calling API. If "json_mode" then Cohere's JSON mode will be
+ used. Note that if using "json_mode" then you must include instructions
+ for formatting the output into the desired schema into the model call.
+ include_raw:
+ If False then only the parsed structured output is returned. If
+ an error occurs during model output parsing it will be raised. If True
+ then both the raw model response (a BaseMessage) and the parsed model
+ response will be returned. If an error occurs during output parsing it
+ will be caught and returned as well. The final output is always a dict
+ with keys "raw", "parsed", and "parsing_error".
+
+ Returns:
+ A Runnable that takes any ChatModel input and returns as output:
+
+ If include_raw is True then a dict with keys:
+ raw: BaseMessage
+ parsed: Optional[_DictOrPydantic]
+ parsing_error: Optional[BaseException]
+
+ If include_raw is False then just _DictOrPydantic is returned,
+ where _DictOrPydantic depends on the schema:
+
+ If schema is a Pydantic class then _DictOrPydantic is the Pydantic
+ class.
+
+ If schema is a dict then _DictOrPydantic is a dict.
+
+ """ # noqa: E501
+ if kwargs:
+ raise ValueError(f"Received unsupported arguments {kwargs}")
+ is_pydantic_schema = _is_pydantic_class(schema)
+ if method == "function_calling":
+ if schema is None:
+ raise ValueError(
+ "schema must be specified when method is 'function_calling'. "
+ "Received None."
+ )
+ llm = self.bind_tools([schema], **kwargs)
+ tool_name = getattr(self._provider.convert_to_oci_tool(schema), "name")
+ if is_pydantic_schema:
+ output_parser: OutputParserLike = PydanticToolsParser(
+ tools=[schema], # type: ignore[list-item]
+ first_tool_only=True,
+ )
+ else:
+ output_parser = JsonOutputKeyToolsParser(
+ key_name=tool_name, first_tool_only=True
+ )
+ elif method == "json_mode":
+ llm = self.bind(response_format={"type": "json_object"})
+ output_parser = (
+ PydanticOutputParser(pydantic_object=schema) # type: ignore[arg-type]
+ if is_pydantic_schema
+ else JsonOutputParser()
+ )
+ else:
+ raise ValueError(
+ f"Unrecognized method argument. "
+ f"Expected `function_calling` or `json_mode`."
+ f"Received: `{method}`."
+ )
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ else:
+ return llm | output_parser
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Call out to a OCIGenAI chat model.
+
+ Args:
+ messages: list of LangChain messages
+ stop: Optional list of stop words to use.
+
+ Returns:
+ LangChain ChatResult
+
+ Example:
+ .. code-block:: python
+
+ messages = [
+ HumanMessage(content="hello!"),
+ AIMessage(content="Hi there human!"),
+ HumanMessage(content="Meow!")
+ ]
+
+ response = llm.invoke(messages)
+ """
+ if self.is_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ request = self._prepare_request(messages, stop=stop, stream=False, **kwargs)
+ response = self.client.chat(request)
+
+ content = self._provider.chat_response_to_text(response)
+
+ if stop is not None:
+ content = enforce_stop_tokens(content, stop)
+
+ generation_info = self._provider.chat_generation_info(response)
+
+ llm_output = {
+ "model_id": response.data.model_id,
+ "model_version": response.data.model_version,
+ "request_id": response.request_id,
+ "content-length": response.headers["content-length"],
+ }
+
+ if "tool_calls" in generation_info:
+ tool_calls = [
+ _convert_oci_tool_call_to_langchain(tool_call)
+ for tool_call in response.data.chat_response.tool_calls
+ ]
+ else:
+ tool_calls = []
+
+ message = AIMessage(
+ content=content,
+ additional_kwargs=generation_info,
+ tool_calls=tool_calls,
+ )
+ return ChatResult(
+ generations=[
+ ChatGeneration(message=message, generation_info=generation_info)
+ ],
+ llm_output=llm_output,
+ )
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ request = self._prepare_request(messages, stop=stop, stream=True, **kwargs)
+ response = self.client.chat(request)
+
+ for event in response.data.events():
+ event_data = json.loads(event.data)
+ if not self._provider.is_chat_stream_end(event_data): # still streaming
+ delta = self._provider.chat_stream_to_text(event_data)
+ chunk = ChatGenerationChunk(message=AIMessageChunk(content=delta))
+ if run_manager:
+ run_manager.on_llm_new_token(delta, chunk=chunk)
+ yield chunk
+ else: # stream end
+ generation_info = self._provider.chat_stream_generation_info(event_data)
+ tool_call_chunks = []
+ if tool_calls := generation_info.get("tool_calls"):
+ content = self._provider.chat_stream_to_text(event_data)
+ try:
+ tool_call_chunks = [
+ ToolCallChunk(
+ name=tool_call["function"].get("name"),
+ args=tool_call["function"].get("arguments"),
+ id=tool_call.get("id"),
+ index=tool_call.get("index"),
+ )
+ for tool_call in tool_calls
+ ]
+ except KeyError:
+ pass
+ else:
+ content = ""
+ message = AIMessageChunk(
+ content=content,
+ additional_kwargs=generation_info,
+ tool_call_chunks=tool_call_chunks,
+ )
+ yield ChatGenerationChunk(
+ message=message,
+ generation_info=generation_info,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/octoai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/octoai.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2d6b927561dc4c456ae95e9b3a6b11a086434e8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/octoai.py
@@ -0,0 +1,158 @@
+"""OctoAI Endpoints chat wrapper. Relies heavily on ChatOpenAI."""
+
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Literal,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+)
+
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.messages import AIMessage
+from langchain_core.runnables import Runnable
+from langchain_core.tools import BaseTool
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from pydantic import Field, SecretStr
+
+from langchain_community.chat_models.openai import ChatOpenAI
+from langchain_community.utils.openai import is_openai_v1
+
+DEFAULT_API_BASE = "https://text.octoai.run/v1/"
+DEFAULT_MODEL = "llama-2-13b-chat"
+
+
+class ChatOctoAI(ChatOpenAI):
+ """OctoAI Chat large language models.
+
+ See https://octo.ai/ for information about OctoAI.
+
+ To use, you should have the ``openai`` python package installed and the
+ environment variable ``OCTOAI_API_TOKEN`` set with your API token.
+ Alternatively, you can use the octoai_api_token keyword argument.
+
+ Any parameters that are valid to be passed to the `openai.create` call can be passed
+ in, even if not explicitly saved on this class.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatOctoAI
+ chat = ChatOctoAI(model_name="mixtral-8x7b-instruct")
+ """
+
+ octoai_api_base: str = Field(default=DEFAULT_API_BASE)
+ octoai_api_token: SecretStr = Field(default=SecretStr(""), alias="api_key")
+ model_name: str = Field(default=DEFAULT_MODEL, alias="model")
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "octoai-chat"
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"octoai_api_token": "OCTOAI_API_TOKEN"}
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ return False
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that api key and python package exists in environment."""
+ values["octoai_api_base"] = get_from_dict_or_env(
+ values,
+ "octoai_api_base",
+ "OCTOAI_API_BASE",
+ default=DEFAULT_API_BASE,
+ )
+ values["octoai_api_token"] = convert_to_secret_str(
+ get_from_dict_or_env(values, "octoai_api_token", "OCTOAI_API_TOKEN")
+ )
+ values["model_name"] = get_from_dict_or_env(
+ values,
+ "model_name",
+ "MODEL_NAME",
+ default=DEFAULT_MODEL,
+ )
+
+ try:
+ import openai
+
+ if is_openai_v1():
+ client_params = {
+ "api_key": values["octoai_api_token"].get_secret_value(),
+ "base_url": values["octoai_api_base"],
+ }
+ if not values.get("client"):
+ values["client"] = openai.OpenAI(**client_params).chat.completions
+ if not values.get("async_client"):
+ values["async_client"] = openai.AsyncOpenAI(
+ **client_params
+ ).chat.completions
+ else:
+ values["openai_api_base"] = values["octoai_api_base"]
+ values["openai_api_key"] = values["octoai_api_token"].get_secret_value()
+ values["client"] = openai.ChatCompletion
+ except ImportError:
+ raise ImportError(
+ "Could not import openai python package. "
+ "Please install it with `pip install openai`."
+ )
+
+ return values
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type, Callable, BaseTool]],
+ *,
+ tool_choice: Optional[
+ Union[dict, str, Literal["auto", "none", "required", "any"], bool]
+ ] = None,
+ strict: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Imitating bind_tool method from langchain_openai.ChatOpenAI"""
+
+ formatted_tools = [
+ convert_to_openai_tool(tool, strict=strict) for tool in tools
+ ]
+ if tool_choice:
+ if isinstance(tool_choice, str):
+ # tool_choice is a tool/function name
+ if tool_choice not in ("auto", "none", "any", "required"):
+ tool_choice = {
+ "type": "function",
+ "function": {"name": tool_choice},
+ }
+ # 'any' is not natively supported by OpenAI API.
+ # We support 'any' since other models use this instead of 'required'.
+ if tool_choice == "any":
+ tool_choice = "required"
+ elif isinstance(tool_choice, bool):
+ tool_choice = "required"
+ elif isinstance(tool_choice, dict):
+ tool_names = [
+ formatted_tool["function"]["name"]
+ for formatted_tool in formatted_tools
+ ]
+ if not any(
+ tool_name == tool_choice["function"]["name"]
+ for tool_name in tool_names
+ ):
+ raise ValueError(
+ f"Tool choice {tool_choice} was specified, but the only "
+ f"provided tools were {tool_names}."
+ )
+ else:
+ raise ValueError(
+ f"Unrecognized tool_choice type. Expected str, bool or dict. "
+ f"Received: {tool_choice}"
+ )
+ kwargs["tool_choice"] = tool_choice
+ return super().bind(tools=formatted_tools, **kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/ollama.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/ollama.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a3788b48d57c62beb37a088c4a6d438456278ce
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/ollama.py
@@ -0,0 +1,398 @@
+import json
+from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union, cast
+
+from langchain_core._api import deprecated
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel, LangSmithParams
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+
+from langchain_community.llms.ollama import OllamaEndpointNotFoundError, _OllamaCommon
+
+
+@deprecated("0.0.3", alternative="_chat_stream_response_to_chat_generation_chunk")
+def _stream_response_to_chat_generation_chunk(
+ stream_response: str,
+) -> ChatGenerationChunk:
+ """Convert a stream response to a generation chunk."""
+ parsed_response = json.loads(stream_response)
+ generation_info = parsed_response if parsed_response.get("done") is True else None
+ return ChatGenerationChunk(
+ message=AIMessageChunk(content=parsed_response.get("response", "")),
+ generation_info=generation_info,
+ )
+
+
+def _chat_stream_response_to_chat_generation_chunk(
+ stream_response: str,
+) -> ChatGenerationChunk:
+ """Convert a stream response to a generation chunk."""
+ parsed_response = json.loads(stream_response)
+ generation_info = parsed_response if parsed_response.get("done") is True else None
+ return ChatGenerationChunk(
+ message=AIMessageChunk(
+ content=parsed_response.get("message", {}).get("content", "")
+ ),
+ generation_info=generation_info,
+ )
+
+
+@deprecated(
+ since="0.3.1",
+ removal="1.0.0",
+ alternative_import="langchain_ollama.ChatOllama",
+)
+class ChatOllama(BaseChatModel, _OllamaCommon):
+ """Ollama locally runs large language models.
+
+ To use, follow the instructions at https://ollama.ai/.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatOllama
+ ollama = ChatOllama(model="llama2")
+ """
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "ollama-chat"
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return whether this model can be serialized by Langchain."""
+ return False
+
+ def _get_ls_params(
+ self, stop: Optional[List[str]] = None, **kwargs: Any
+ ) -> LangSmithParams:
+ """Get standard params for tracing."""
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ ls_params = LangSmithParams(
+ ls_provider="ollama",
+ ls_model_name=self.model,
+ ls_model_type="chat",
+ ls_temperature=params.get("temperature", self.temperature),
+ )
+ if ls_max_tokens := params.get("num_predict", self.num_predict):
+ ls_params["ls_max_tokens"] = ls_max_tokens
+ if ls_stop := stop or params.get("stop", None) or self.stop:
+ ls_params["ls_stop"] = ls_stop
+ return ls_params
+
+ @deprecated("0.0.3", alternative="_convert_messages_to_ollama_messages")
+ def _format_message_as_text(self, message: BaseMessage) -> str:
+ if isinstance(message, ChatMessage):
+ message_text = f"\n\n{message.role.capitalize()}: {message.content}"
+ elif isinstance(message, HumanMessage):
+ if isinstance(message.content, List):
+ first_content = cast(List[Dict], message.content)[0]
+ content_type = first_content.get("type")
+ if content_type == "text":
+ message_text = f"[INST] {first_content['text']} [/INST]"
+ elif content_type == "image_url":
+ message_text = first_content["image_url"]["url"]
+ else:
+ message_text = f"[INST] {message.content} [/INST]"
+ elif isinstance(message, AIMessage):
+ message_text = f"{message.content}"
+ elif isinstance(message, SystemMessage):
+ message_text = f"<> {message.content} <>"
+ else:
+ raise ValueError(f"Got unknown type {message}")
+ return message_text
+
+ def _format_messages_as_text(self, messages: List[BaseMessage]) -> str:
+ return "\n".join(
+ [self._format_message_as_text(message) for message in messages]
+ )
+
+ def _convert_messages_to_ollama_messages(
+ self, messages: List[BaseMessage]
+ ) -> List[Dict[str, Union[str, List[str]]]]:
+ ollama_messages: List = []
+ for message in messages:
+ role = ""
+ if isinstance(message, HumanMessage):
+ role = "user"
+ elif isinstance(message, AIMessage):
+ role = "assistant"
+ elif isinstance(message, SystemMessage):
+ role = "system"
+ else:
+ raise ValueError("Received unsupported message type for Ollama.")
+
+ content = ""
+ images = []
+ if isinstance(message.content, str):
+ content = message.content
+ else:
+ for content_part in cast(List[Dict], message.content):
+ if content_part.get("type") == "text":
+ content += f"\n{content_part['text']}"
+ elif content_part.get("type") == "image_url":
+ image_url = None
+ temp_image_url = content_part.get("image_url")
+ if isinstance(temp_image_url, str):
+ image_url = content_part["image_url"]
+ elif (
+ isinstance(temp_image_url, dict) and "url" in temp_image_url
+ ):
+ image_url = temp_image_url["url"]
+ else:
+ raise ValueError(
+ "Only string image_url or dict with string 'url' "
+ "inside content parts are supported."
+ )
+
+ image_url_components = image_url.split(",")
+ # Support data:image/jpeg;base64, format
+ # and base64 strings
+ if len(image_url_components) > 1:
+ images.append(image_url_components[1])
+ else:
+ images.append(image_url_components[0])
+
+ else:
+ raise ValueError(
+ "Unsupported message content type. "
+ "Must either have type 'text' or type 'image_url' "
+ "with a string 'image_url' field."
+ )
+
+ ollama_messages.append(
+ {
+ "role": role,
+ "content": content,
+ "images": images,
+ }
+ )
+
+ return ollama_messages
+
+ def _create_chat_stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ **kwargs: Any,
+ ) -> Iterator[str]:
+ payload = {
+ "model": self.model,
+ "messages": self._convert_messages_to_ollama_messages(messages),
+ }
+ yield from self._create_stream(
+ payload=payload, stop=stop, api_url=f"{self.base_url}/api/chat", **kwargs
+ )
+
+ async def _acreate_chat_stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[str]:
+ payload = {
+ "model": self.model,
+ "messages": self._convert_messages_to_ollama_messages(messages),
+ }
+ async for stream_resp in self._acreate_stream(
+ payload=payload, stop=stop, api_url=f"{self.base_url}/api/chat", **kwargs
+ ):
+ yield stream_resp
+
+ def _chat_stream_with_aggregation(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ verbose: bool = False,
+ **kwargs: Any,
+ ) -> ChatGenerationChunk:
+ final_chunk: Optional[ChatGenerationChunk] = None
+ for stream_resp in self._create_chat_stream(messages, stop, **kwargs):
+ if stream_resp:
+ chunk = _chat_stream_response_to_chat_generation_chunk(stream_resp)
+ if final_chunk is None:
+ final_chunk = chunk
+ else:
+ final_chunk += chunk
+ if run_manager:
+ run_manager.on_llm_new_token(
+ chunk.text,
+ chunk=chunk,
+ verbose=verbose,
+ )
+ if final_chunk is None:
+ raise ValueError("No data received from Ollama stream.")
+
+ return final_chunk
+
+ async def _achat_stream_with_aggregation(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ verbose: bool = False,
+ **kwargs: Any,
+ ) -> ChatGenerationChunk:
+ final_chunk: Optional[ChatGenerationChunk] = None
+ async for stream_resp in self._acreate_chat_stream(messages, stop, **kwargs):
+ if stream_resp:
+ chunk = _chat_stream_response_to_chat_generation_chunk(stream_resp)
+ if final_chunk is None:
+ final_chunk = chunk
+ else:
+ final_chunk += chunk
+ if run_manager:
+ await run_manager.on_llm_new_token(
+ chunk.text,
+ chunk=chunk,
+ verbose=verbose,
+ )
+ if final_chunk is None:
+ raise ValueError("No data received from Ollama stream.")
+
+ return final_chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Call out to Ollama's generate endpoint.
+
+ Args:
+ messages: The list of base messages to pass into the model.
+ stop: Optional list of stop words to use when generating.
+
+ Returns:
+ Chat generations from the model
+
+ Example:
+ .. code-block:: python
+
+ response = ollama([
+ HumanMessage(content="Tell me about the history of AI")
+ ])
+ """
+
+ final_chunk = self._chat_stream_with_aggregation(
+ messages,
+ stop=stop,
+ run_manager=run_manager,
+ verbose=self.verbose,
+ **kwargs,
+ )
+ chat_generation = ChatGeneration(
+ message=AIMessage(content=final_chunk.text),
+ generation_info=final_chunk.generation_info,
+ )
+ return ChatResult(generations=[chat_generation])
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Call out to Ollama's generate endpoint.
+
+ Args:
+ messages: The list of base messages to pass into the model.
+ stop: Optional list of stop words to use when generating.
+
+ Returns:
+ Chat generations from the model
+
+ Example:
+ .. code-block:: python
+
+ response = ollama([
+ HumanMessage(content="Tell me about the history of AI")
+ ])
+ """
+
+ final_chunk = await self._achat_stream_with_aggregation(
+ messages,
+ stop=stop,
+ run_manager=run_manager,
+ verbose=self.verbose,
+ **kwargs,
+ )
+ chat_generation = ChatGeneration(
+ message=AIMessage(content=final_chunk.text),
+ generation_info=final_chunk.generation_info,
+ )
+ return ChatResult(generations=[chat_generation])
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ try:
+ for stream_resp in self._create_chat_stream(messages, stop, **kwargs):
+ if stream_resp:
+ chunk = _chat_stream_response_to_chat_generation_chunk(stream_resp)
+ if run_manager:
+ run_manager.on_llm_new_token(
+ chunk.text,
+ chunk=chunk,
+ verbose=self.verbose,
+ )
+ yield chunk
+ except OllamaEndpointNotFoundError:
+ yield from self._legacy_stream(messages, stop, **kwargs)
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ async for stream_resp in self._acreate_chat_stream(messages, stop, **kwargs):
+ if stream_resp:
+ chunk = _chat_stream_response_to_chat_generation_chunk(stream_resp)
+ if run_manager:
+ await run_manager.on_llm_new_token(
+ chunk.text,
+ chunk=chunk,
+ verbose=self.verbose,
+ )
+ yield chunk
+
+ @deprecated("0.0.3", alternative="_stream")
+ def _legacy_stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ prompt = self._format_messages_as_text(messages)
+ for stream_resp in self._create_generate_stream(prompt, stop, **kwargs):
+ if stream_resp:
+ chunk = _stream_response_to_chat_generation_chunk(stream_resp)
+ if run_manager:
+ run_manager.on_llm_new_token(
+ chunk.text,
+ chunk=chunk,
+ verbose=self.verbose,
+ )
+ yield chunk
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/openai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/openai.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b69019bae8908458461ac3227ae99b350d77f14
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/openai.py
@@ -0,0 +1,736 @@
+"""OpenAI chat wrapper."""
+
+from __future__ import annotations
+
+import logging
+import os
+import sys
+import warnings
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ Union,
+)
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.language_models.llms import create_base_retry_decorator
+from langchain_core.messages import (
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessageChunk,
+ FunctionMessageChunk,
+ HumanMessageChunk,
+ SystemMessageChunk,
+ ToolMessageChunk,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable
+from langchain_core.tools import BaseTool
+from langchain_core.utils import (
+ get_from_dict_or_env,
+ get_pydantic_field_names,
+ pre_init,
+)
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+from langchain_community.adapters.openai import (
+ convert_dict_to_message,
+ convert_message_to_dict,
+)
+from langchain_community.utils.openai import is_openai_v1
+
+if TYPE_CHECKING:
+ import tiktoken
+
+
+logger = logging.getLogger(__name__)
+
+
+def _import_tiktoken() -> Any:
+ try:
+ import tiktoken
+ except ImportError:
+ raise ImportError(
+ "Could not import tiktoken python package. "
+ "This is needed in order to calculate get_token_ids. "
+ "Please install it with `pip install tiktoken`."
+ )
+ return tiktoken
+
+
+def _create_retry_decorator(
+ llm: ChatOpenAI,
+ run_manager: Optional[
+ Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]
+ ] = None,
+) -> Callable[[Any], Any]:
+ import openai
+
+ errors = [
+ openai.error.Timeout,
+ openai.error.APIError,
+ openai.error.APIConnectionError,
+ openai.error.RateLimitError,
+ openai.error.ServiceUnavailableError,
+ ]
+ return create_base_retry_decorator(
+ error_types=errors, max_retries=llm.max_retries, run_manager=run_manager
+ )
+
+
+async def acompletion_with_retry(
+ llm: ChatOpenAI,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+) -> Any:
+ """Use tenacity to retry the async completion call."""
+ if is_openai_v1():
+ return await llm.async_client.create(**kwargs)
+
+ retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
+
+ @retry_decorator
+ async def _completion_with_retry(**kwargs: Any) -> Any:
+ # Use OpenAI's async api https://github.com/openai/openai-python#async-api
+ return await llm.client.acreate(**kwargs)
+
+ return await _completion_with_retry(**kwargs)
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role = _dict.get("role")
+ content = _dict.get("content") or ""
+ additional_kwargs: Dict = {}
+ if _dict.get("function_call"):
+ function_call = dict(_dict["function_call"])
+ if "name" in function_call and function_call["name"] is None:
+ function_call["name"] = ""
+ additional_kwargs["function_call"] = function_call
+ if _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = _dict["tool_calls"]
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ elif role == "function" or default_class == FunctionMessageChunk:
+ return FunctionMessageChunk(content=content, name=_dict["name"])
+ elif role == "tool" or default_class == ToolMessageChunk:
+ return ToolMessageChunk(content=content, tool_call_id=_dict["tool_call_id"])
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+def _update_token_usage(
+ overall_token_usage: Union[int, dict], new_usage: Union[int, dict]
+) -> Union[int, dict]:
+ # Token usage is either ints or dictionaries
+ # `reasoning_tokens` is nested inside `completion_tokens_details`
+ if isinstance(new_usage, int):
+ if not isinstance(overall_token_usage, int):
+ raise ValueError(
+ f"Got different types for token usage: "
+ f"{type(new_usage)} and {type(overall_token_usage)}"
+ )
+ return new_usage + overall_token_usage
+ elif isinstance(new_usage, dict):
+ if not isinstance(overall_token_usage, dict):
+ raise ValueError(
+ f"Got different types for token usage: "
+ f"{type(new_usage)} and {type(overall_token_usage)}"
+ )
+ return {
+ k: _update_token_usage(overall_token_usage.get(k, 0), v)
+ for k, v in new_usage.items()
+ }
+ else:
+ warnings.warn(f"Unexpected type for token usage: {type(new_usage)}")
+ return new_usage
+
+
+@deprecated(
+ since="0.0.10", removal="1.0", alternative_import="langchain_openai.ChatOpenAI"
+)
+class ChatOpenAI(BaseChatModel):
+ """`OpenAI` Chat large language models API.
+
+ To use, you should have the ``openai`` python package installed, and the
+ environment variable ``OPENAI_API_KEY`` set with your API key.
+
+ Any parameters that are valid to be passed to the openai.create call can be passed
+ in, even if not explicitly saved on this class.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatOpenAI
+ openai = ChatOpenAI(model="gpt-3.5-turbo")
+ """
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"openai_api_key": "OPENAI_API_KEY"}
+
+ @classmethod
+ def get_lc_namespace(cls) -> List[str]:
+ """Get the namespace of the langchain object."""
+ return ["langchain", "chat_models", "openai"]
+
+ @property
+ def lc_attributes(self) -> Dict[str, Any]:
+ attributes: Dict[str, Any] = {}
+
+ if self.openai_organization:
+ attributes["openai_organization"] = self.openai_organization
+
+ if self.openai_api_base:
+ attributes["openai_api_base"] = self.openai_api_base
+
+ if self.openai_proxy:
+ attributes["openai_proxy"] = self.openai_proxy
+
+ return attributes
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return whether this model can be serialized by Langchain."""
+ return True
+
+ client: Any = Field(default=None, exclude=True) #: :meta private:
+ async_client: Any = Field(default=None, exclude=True) #: :meta private:
+ model_name: str = Field(default="gpt-3.5-turbo", alias="model")
+ """Model name to use."""
+ temperature: float = 0.7
+ """What sampling temperature to use."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for `create` call not explicitly specified."""
+ # When updating this to use a SecretStr
+ # Check for classes that derive from this class (as some of them
+ # may assume openai_api_key is a str)
+ openai_api_key: Optional[str] = Field(default=None, alias="api_key")
+ """Automatically inferred from env var `OPENAI_API_KEY` if not provided."""
+ openai_api_base: Optional[str] = Field(default=None, alias="base_url")
+ """Base URL path for API requests, leave blank if not using a proxy or service
+ emulator."""
+ openai_organization: Optional[str] = Field(default=None, alias="organization")
+ """Automatically inferred from env var `OPENAI_ORG_ID` if not provided."""
+ # to support explicit proxy for OpenAI
+ openai_proxy: Optional[str] = None
+ request_timeout: Union[float, Tuple[float, float], Any, None] = Field(
+ default=None, alias="timeout"
+ )
+ """Timeout for requests to OpenAI completion API. Can be float, httpx.Timeout or
+ None."""
+ max_retries: int = Field(default=2)
+ """Maximum number of retries to make when generating."""
+ streaming: bool = False
+ """Whether to stream the results or not."""
+ n: int = 1
+ """Number of chat completions to generate for each prompt."""
+ max_tokens: Optional[int] = None
+ """Maximum number of tokens to generate."""
+ tiktoken_model_name: Optional[str] = None
+ """The model name to pass to tiktoken when using this class.
+ Tiktoken is used to count the number of tokens in documents to constrain
+ them to be under a certain limit. By default, when set to None, this will
+ be the same as the embedding model name. However, there are some cases
+ where you may want to use this Embedding class with a model name not
+ supported by tiktoken. This can include when using Azure embeddings or
+ when using one of the many model providers that expose an OpenAI-like
+ API but with different models. In those cases, in order to avoid erroring
+ when tiktoken is called, you can specify a model name to use here."""
+ default_headers: Union[Mapping[str, str], None] = None
+ default_query: Union[Mapping[str, object], None] = None
+ # Configure a custom httpx client. See the
+ # [httpx documentation](https://www.python-httpx.org/api/#client) for more details.
+ http_client: Union[Any, None] = None
+ """Optional httpx.Client."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def build_extra(cls, values: Dict[str, Any]) -> Any:
+ """Build extra kwargs from additional params that were passed in."""
+ all_required_field_names = get_pydantic_field_names(cls)
+ extra = values.get("model_kwargs", {})
+ for field_name in list(values):
+ if field_name in extra:
+ raise ValueError(f"Found {field_name} supplied twice.")
+ if field_name not in all_required_field_names:
+ logger.warning(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please confirm that {field_name} is what you intended."""
+ )
+ extra[field_name] = values.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
+ if invalid_model_kwargs:
+ raise ValueError(
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+
+ values["model_kwargs"] = extra
+ return values
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that api key and python package exists in environment."""
+ if values["n"] < 1:
+ raise ValueError("n must be at least 1.")
+ if values["n"] > 1 and values["streaming"]:
+ raise ValueError("n must be 1 when streaming.")
+
+ values["openai_api_key"] = get_from_dict_or_env(
+ values, "openai_api_key", "OPENAI_API_KEY"
+ )
+ # Check OPENAI_ORGANIZATION for backwards compatibility.
+ values["openai_organization"] = (
+ values["openai_organization"]
+ or os.getenv("OPENAI_ORG_ID")
+ or os.getenv("OPENAI_ORGANIZATION")
+ )
+ values["openai_api_base"] = values["openai_api_base"] or os.getenv(
+ "OPENAI_API_BASE"
+ )
+ values["openai_proxy"] = get_from_dict_or_env(
+ values,
+ "openai_proxy",
+ "OPENAI_PROXY",
+ default="",
+ )
+ try:
+ import openai
+
+ except ImportError:
+ raise ImportError(
+ "Could not import openai python package. "
+ "Please install it with `pip install openai`."
+ )
+
+ if is_openai_v1():
+ client_params = {
+ "api_key": values["openai_api_key"],
+ "organization": values["openai_organization"],
+ "base_url": values["openai_api_base"],
+ "timeout": values["request_timeout"],
+ "max_retries": values["max_retries"],
+ "default_headers": values["default_headers"],
+ "default_query": values["default_query"],
+ "http_client": values["http_client"],
+ }
+
+ if not values.get("client"):
+ values["client"] = openai.OpenAI(**client_params).chat.completions
+ if not values.get("async_client"):
+ values["async_client"] = openai.AsyncOpenAI(
+ **client_params
+ ).chat.completions
+ elif not values.get("client"):
+ values["client"] = openai.ChatCompletion
+ else:
+ pass
+ return values
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling OpenAI API."""
+ params = {
+ "model": self.model_name,
+ "stream": self.streaming,
+ "n": self.n,
+ "temperature": self.temperature,
+ **self.model_kwargs,
+ }
+ if self.max_tokens is not None:
+ params["max_tokens"] = self.max_tokens
+ if self.request_timeout is not None and not is_openai_v1():
+ params["request_timeout"] = self.request_timeout
+ return params
+
+ def completion_with_retry(
+ self, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any
+ ) -> Any:
+ """Use tenacity to retry the completion call."""
+ if is_openai_v1():
+ return self.client.create(**kwargs)
+
+ retry_decorator = _create_retry_decorator(self, run_manager=run_manager)
+
+ @retry_decorator
+ def _completion_with_retry(**kwargs: Any) -> Any:
+ return self.client.create(**kwargs)
+
+ return _completion_with_retry(**kwargs)
+
+ def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:
+ overall_token_usage: dict = {}
+ system_fingerprint = None
+ for output in llm_outputs:
+ if output is None:
+ # Happens in streaming
+ continue
+ token_usage = output["token_usage"]
+ if token_usage is not None:
+ for k, v in token_usage.items():
+ if k in overall_token_usage:
+ overall_token_usage[k] = _update_token_usage(
+ overall_token_usage[k], v
+ )
+ else:
+ overall_token_usage[k] = v
+ if system_fingerprint is None:
+ system_fingerprint = output.get("system_fingerprint")
+ combined = {"token_usage": overall_token_usage, "model_name": self.model_name}
+ if system_fingerprint:
+ combined["system_fingerprint"] = system_fingerprint
+ return combined
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ for chunk in self.completion_with_retry(
+ messages=message_dicts, run_manager=run_manager, **params
+ ):
+ if not isinstance(chunk, dict):
+ chunk = chunk.dict()
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ if choice["delta"] is None:
+ continue
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], default_chunk_class
+ )
+ finish_reason = choice.get("finish_reason")
+ generation_info = (
+ dict(finish_reason=finish_reason) if finish_reason is not None else None
+ )
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(cg_chunk.text, chunk=cg_chunk)
+ yield cg_chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {
+ **params,
+ **({"stream": stream} if stream is not None else {}),
+ **kwargs,
+ }
+ response = self.completion_with_retry(
+ messages=message_dicts, run_manager=run_manager, **params
+ )
+ return self._create_chat_result(response)
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage], stop: Optional[List[str]]
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
+ params = self._client_params
+ if stop is not None:
+ if "stop" in params:
+ raise ValueError("`stop` found in both the input and default params.")
+ params["stop"] = stop
+ message_dicts = [convert_message_to_dict(m) for m in messages]
+ return message_dicts, params
+
+ def _create_chat_result(self, response: Union[dict, BaseModel]) -> ChatResult:
+ generations = []
+ if not isinstance(response, dict):
+ response = response.dict()
+ for res in response["choices"]:
+ message = convert_dict_to_message(res["message"])
+ generation_info = dict(finish_reason=res.get("finish_reason"))
+ if "logprobs" in res:
+ generation_info["logprobs"] = res["logprobs"]
+ gen = ChatGeneration(
+ message=message,
+ generation_info=generation_info,
+ )
+ generations.append(gen)
+ token_usage = response.get("usage", {})
+ llm_output = {
+ "token_usage": token_usage,
+ "model_name": self.model_name,
+ "system_fingerprint": response.get("system_fingerprint", ""),
+ }
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ async for chunk in await acompletion_with_retry(
+ self, messages=message_dicts, run_manager=run_manager, **params
+ ):
+ if not isinstance(chunk, dict):
+ chunk = chunk.dict()
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ if choice["delta"] is None:
+ continue
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], default_chunk_class
+ )
+ finish_reason = choice.get("finish_reason")
+ generation_info = (
+ dict(finish_reason=finish_reason) if finish_reason is not None else None
+ )
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(token=cg_chunk.text, chunk=cg_chunk)
+ yield cg_chunk
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {
+ **params,
+ **({"stream": stream} if stream is not None else {}),
+ **kwargs,
+ }
+ response = await acompletion_with_retry(
+ self, messages=message_dicts, run_manager=run_manager, **params
+ )
+ return self._create_chat_result(response)
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ return {**{"model_name": self.model_name}, **self._default_params}
+
+ @property
+ def _client_params(self) -> Dict[str, Any]:
+ """Get the parameters used for the openai client."""
+ openai_creds: Dict[str, Any] = {
+ "model": self.model_name,
+ }
+ if not is_openai_v1():
+ openai_creds.update(
+ {
+ "api_key": self.openai_api_key,
+ "api_base": self.openai_api_base,
+ "organization": self.openai_organization,
+ }
+ )
+ if self.openai_proxy:
+ import openai
+
+ openai.proxy = {"http": self.openai_proxy, "https": self.openai_proxy}
+ return {**self._default_params, **openai_creds}
+
+ def _get_invocation_params(
+ self, stop: Optional[List[str]] = None, **kwargs: Any
+ ) -> Dict[str, Any]:
+ """Get the parameters used to invoke the model."""
+ return {
+ "model": self.model_name,
+ **super()._get_invocation_params(stop=stop),
+ **self._default_params,
+ **kwargs,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "openai-chat"
+
+ def _get_encoding_model(self) -> Tuple[str, tiktoken.Encoding]:
+ tiktoken_ = _import_tiktoken()
+ if self.tiktoken_model_name is not None:
+ model = self.tiktoken_model_name
+ else:
+ model = self.model_name
+ if model == "gpt-3.5-turbo":
+ # gpt-3.5-turbo may change over time.
+ # Returning num tokens assuming gpt-3.5-turbo-0301.
+ model = "gpt-3.5-turbo-0301"
+ elif model == "gpt-4":
+ # gpt-4 may change over time.
+ # Returning num tokens assuming gpt-4-0314.
+ model = "gpt-4-0314"
+ # Returns the number of tokens used by a list of messages.
+ try:
+ encoding = tiktoken_.encoding_for_model(model)
+ except KeyError:
+ logger.warning("Warning: model not found. Using cl100k_base encoding.")
+ model = "cl100k_base"
+ encoding = tiktoken_.get_encoding(model)
+ return model, encoding
+
+ def get_token_ids(self, text: str) -> List[int]:
+ """Get the tokens present in the text with tiktoken package."""
+ # tiktoken NOT supported for Python 3.7 or below
+ if sys.version_info[1] <= 7:
+ return super().get_token_ids(text)
+ _, encoding_model = self._get_encoding_model()
+ return encoding_model.encode(text)
+
+ def get_num_tokens_from_messages(
+ self,
+ messages: List[BaseMessage],
+ tools: Optional[
+ Sequence[Union[Dict[str, Any], Type, Callable, BaseTool]]
+ ] = None,
+ ) -> int:
+ """Calculate num tokens for gpt-3.5-turbo and gpt-4 with tiktoken package.
+
+ Official documentation: https://github.com/openai/openai-cookbook/blob/
+ main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb"""
+ if tools is not None:
+ warnings.warn(
+ "Counting tokens in tool schemas is not yet supported. Ignoring tools."
+ )
+ if sys.version_info[1] <= 7:
+ return super().get_num_tokens_from_messages(messages)
+ model, encoding = self._get_encoding_model()
+ if model.startswith("gpt-3.5-turbo-0301"):
+ # every message follows {role/name}\n{content}\n
+ tokens_per_message = 4
+ # if there's a name, the role is omitted
+ tokens_per_name = -1
+ elif model.startswith("gpt-3.5-turbo") or model.startswith("gpt-4"):
+ tokens_per_message = 3
+ tokens_per_name = 1
+ else:
+ raise NotImplementedError(
+ f"get_num_tokens_from_messages() is not presently implemented "
+ f"for model {model}."
+ "See https://github.com/openai/openai-python/blob/main/chatml.md for "
+ "information on how messages are converted to tokens."
+ )
+ num_tokens = 0
+ messages_dict = [convert_message_to_dict(m) for m in messages]
+ for message in messages_dict:
+ num_tokens += tokens_per_message
+ for key, value in message.items():
+ # Cast str(value) in case the message value is not a string
+ # This occurs with function messages
+ num_tokens += len(encoding.encode(str(value)))
+ if key == "name":
+ num_tokens += tokens_per_name
+ # every reply is primed with assistant
+ num_tokens += 3
+ return num_tokens
+
+ def bind_functions(
+ self,
+ functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]],
+ function_call: Optional[str] = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, BaseMessage]:
+ """Bind functions (and other objects) to this chat model.
+
+ Args:
+ functions: A list of function definitions to bind to this chat model.
+ Can be a dictionary, pydantic model, or callable. Pydantic
+ models and callables will be automatically converted to
+ their schema dictionary representation.
+ function_call: Which function to require the model to call.
+ Must be the name of the single provided function or
+ "auto" to automatically determine which function to call
+ (if any).
+ kwargs: Any additional parameters to pass to the
+ :class:`~langchain.runnable.Runnable` constructor.
+ """
+ from langchain_classic.chains.openai_functions.base import (
+ convert_to_openai_function,
+ )
+
+ formatted_functions = [convert_to_openai_function(fn) for fn in functions]
+ if function_call is not None:
+ if len(formatted_functions) != 1:
+ raise ValueError(
+ "When specifying `function_call`, you must provide exactly one "
+ "function."
+ )
+ if formatted_functions[0]["name"] != function_call:
+ raise ValueError(
+ f"Function call {function_call} was specified, but the only "
+ f"provided function was {formatted_functions[0]['name']}."
+ )
+ function_call_ = {"name": function_call}
+ kwargs = {**kwargs, "function_call": function_call_}
+ return super().bind(
+ functions=formatted_functions,
+ **kwargs,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/outlines.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/outlines.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fa41dc8df9436ba3fb89da07a667c271a1be530
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/outlines.py
@@ -0,0 +1,538 @@
+from __future__ import annotations
+
+import importlib.util
+import platform
+from collections.abc import AsyncIterator
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ TypedDict,
+ TypeVar,
+ Union,
+ get_origin,
+)
+
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.callbacks.manager import AsyncCallbackManagerForLLMRun
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import AIMessage, AIMessageChunk, BaseMessage
+from langchain_core.output_parsers import JsonOutputParser, PydanticOutputParser
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable
+from langchain_core.tools import BaseTool
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from pydantic import BaseModel, Field, model_validator
+from typing_extensions import Literal
+
+from langchain_community.adapters.openai import convert_message_to_dict
+
+_BM = TypeVar("_BM", bound=BaseModel)
+_DictOrPydanticClass = Union[Dict[str, Any], Type[_BM], Type]
+
+
+class ChatOutlines(BaseChatModel):
+ """Outlines chat model integration.
+
+ Setup:
+ pip install outlines
+
+ Key init args — client params:
+ backend: Literal["llamacpp", "transformers", "transformers_vision", "vllm", "mlxlm"] = "transformers"
+ Specifies the backend to use for the model.
+
+ Key init args — completion params:
+ model: str
+ Identifier for the model to use with Outlines.
+ max_tokens: int = 256
+ The maximum number of tokens to generate.
+ stop: Optional[List[str]] = None
+ A list of strings to stop generation when encountered.
+ streaming: bool = True
+ Whether to stream the results, token by token.
+
+ See full list of supported init args and their descriptions in the params section.
+
+ Instantiate:
+ from langchain_community.chat_models import ChatOutlines
+ chat = ChatOutlines(model="meta-llama/Llama-2-7b-chat-hf")
+
+ Invoke:
+ chat.invoke([HumanMessage(content="Say foo:")])
+
+ Stream:
+ for chunk in chat.stream([HumanMessage(content="Count to 10:")]):
+ print(chunk.content, end="", flush=True)
+
+ """ # noqa: E501
+
+ client: Any = None # :meta private:
+
+ model: str
+ """Identifier for the model to use with Outlines.
+
+ The model identifier should be a string specifying:
+ - A Hugging Face model name (e.g., "meta-llama/Llama-2-7b-chat-hf")
+ - A local path to a model
+ - For GGUF models, the format is "repo_id/file_name"
+ (e.g., "TheBloke/Llama-2-7B-Chat-GGUF/llama-2-7b-chat.Q4_K_M.gguf")
+
+ Examples:
+ - "TheBloke/Llama-2-7B-Chat-GGUF/llama-2-7b-chat.Q4_K_M.gguf"
+ - "meta-llama/Llama-2-7b-chat-hf"
+ """
+
+ backend: Literal[
+ "llamacpp", "transformers", "transformers_vision", "vllm", "mlxlm"
+ ] = "transformers"
+ """Specifies the backend to use for the model.
+
+ Supported backends are:
+ - "llamacpp": For GGUF models using llama.cpp
+ - "transformers": For Hugging Face Transformers models (default)
+ - "transformers_vision": For vision-language models (e.g., LLaVA)
+ - "vllm": For models using the vLLM library
+ - "mlxlm": For models using the MLX framework
+
+ Note: Ensure you have the necessary dependencies installed for the chosen backend.
+ The system will attempt to import required packages and may raise an ImportError
+ if they are not available.
+ """
+
+ max_tokens: int = 256
+ """The maximum number of tokens to generate."""
+
+ stop: Optional[List[str]] = None
+ """A list of strings to stop generation when encountered."""
+
+ streaming: bool = True
+ """Whether to stream the results, token by token."""
+
+ regex: Optional[str] = None
+ """Regular expression for structured generation.
+
+ If provided, Outlines will guarantee that the generated text matches this regex.
+ This can be useful for generating structured outputs like IP addresses, dates, etc.
+
+ Example: (valid IP address)
+ regex = r"((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)"
+
+ Note: Computing the regex index can take some time, so it's recommended to reuse
+ the same regex for multiple generations if possible.
+
+ For more details, see: https://dottxt-ai.github.io/outlines/reference/generation/regex/
+ """ # noqa: E501
+
+ type_constraints: Optional[Union[type, str]] = None
+ """Type constraints for structured generation.
+
+ Restricts the output to valid Python types. Supported types include:
+ int, float, bool, datetime.date, datetime.time, datetime.datetime.
+
+ Example:
+ type_constraints = int
+
+ For more details, see: https://dottxt-ai.github.io/outlines/reference/generation/format/
+ """
+
+ json_schema: Optional[Union[Any, Dict, Callable]] = None
+ """Pydantic model, JSON Schema, or callable (function signature)
+ for structured JSON generation.
+
+ Outlines can generate JSON output that follows a specified structure,
+ which is useful for:
+ 1. Parsing the answer (e.g., with Pydantic), storing it, or returning it to a user.
+ 2. Calling a function with the result.
+
+ You can provide:
+ - A Pydantic model
+ - A JSON Schema (as a Dict)
+ - A callable (function signature)
+
+ The generated JSON will adhere to the specified structure.
+
+ For more details, see: https://dottxt-ai.github.io/outlines/reference/generation/json/
+ """
+
+ grammar: Optional[str] = None
+ """Context-free grammar for structured generation.
+
+ If provided, Outlines will generate text that adheres to the specified grammar.
+ The grammar should be defined in EBNF format.
+
+ This can be useful for generating structured outputs like mathematical expressions,
+ programming languages, or custom domain-specific languages.
+
+ Example:
+ grammar = '''
+ ?start: expression
+ ?expression: term (("+" | "-") term)*
+ ?term: factor (("*" | "/") factor)*
+ ?factor: NUMBER | "-" factor | "(" expression ")"
+ %import common.NUMBER
+ '''
+
+ Note: Grammar-based generation is currently experimental and may have performance
+ limitations. It uses greedy generation to mitigate these issues.
+
+ For more details and examples, see:
+ https://dottxt-ai.github.io/outlines/reference/generation/cfg/
+ """
+
+ custom_generator: Optional[Any] = None
+ """Set your own outlines generator object to override the default behavior."""
+
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Additional parameters to pass to the underlying model.
+
+ Example:
+ model_kwargs = {"temperature": 0.8, "seed": 42}
+ """
+
+ @model_validator(mode="after")
+ def validate_environment(self) -> "ChatOutlines":
+ """Validate that outlines is installed and create a model instance."""
+ num_constraints = sum(
+ [
+ bool(self.regex),
+ bool(self.type_constraints),
+ bool(self.json_schema),
+ bool(self.grammar),
+ ]
+ )
+ if num_constraints > 1:
+ raise ValueError(
+ "Either none or exactly one of regex, type_constraints, "
+ "json_schema, or grammar can be provided."
+ )
+ return self.build_client()
+
+ def build_client(self) -> "ChatOutlines":
+ try:
+ import outlines.models as models
+ except ImportError:
+ raise ImportError(
+ "Could not import the Outlines library. "
+ "Please install it with `pip install outlines`."
+ )
+
+ def check_packages_installed(
+ packages: List[Union[str, Tuple[str, str]]],
+ ) -> None:
+ missing_packages = [
+ pkg if isinstance(pkg, str) else pkg[0]
+ for pkg in packages
+ if importlib.util.find_spec(pkg[1] if isinstance(pkg, tuple) else pkg)
+ is None
+ ]
+ if missing_packages:
+ raise ImportError(
+ f"Missing packages: {', '.join(missing_packages)}. "
+ "You can install them with:\n\n"
+ f" pip install {' '.join(missing_packages)}"
+ )
+
+ if self.backend == "llamacpp":
+ check_packages_installed([("llama-cpp-python", "llama_cpp")])
+ if ".gguf" in self.model:
+ creator, repo_name, file_name = self.model.split("/", 2)
+ repo_id = f"{creator}/{repo_name}"
+ else:
+ raise ValueError("GGUF file_name must be provided for llama.cpp.")
+ self.client = models.llamacpp(repo_id, file_name, **self.model_kwargs)
+ elif self.backend == "transformers":
+ check_packages_installed(["transformers", "torch", "datasets"])
+ self.client = models.transformers(
+ model_name=self.model, **self.model_kwargs
+ )
+ elif self.backend == "transformers_vision":
+ if hasattr(models, "transformers_vision"):
+ from transformers import LlavaNextForConditionalGeneration
+
+ self.client = models.transformers_vision(
+ self.model,
+ model_class=LlavaNextForConditionalGeneration,
+ **self.model_kwargs,
+ )
+ else:
+ raise ValueError("transformers_vision backend is not supported")
+ elif self.backend == "vllm":
+ if platform.system() == "Darwin":
+ raise ValueError("vLLM backend is not supported on macOS.")
+ check_packages_installed(["vllm"])
+ self.client = models.vllm(self.model, **self.model_kwargs)
+ elif self.backend == "mlxlm":
+ check_packages_installed(["mlx"])
+ self.client = models.mlxlm(self.model, **self.model_kwargs)
+ else:
+ raise ValueError(f"Unsupported backend: {self.backend}")
+ return self
+
+ @property
+ def _llm_type(self) -> str:
+ return "outlines-chat"
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ return {
+ "max_tokens": self.max_tokens,
+ "stop_at": self.stop,
+ **self.model_kwargs,
+ }
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ return {
+ "model": self.model,
+ "backend": self.backend,
+ "regex": self.regex,
+ "type_constraints": self.type_constraints,
+ "json_schema": self.json_schema,
+ "grammar": self.grammar,
+ **self._default_params,
+ }
+
+ @property
+ def _generator(self) -> Any:
+ from outlines import generate
+
+ if self.custom_generator:
+ return self.custom_generator
+ constraints = [
+ self.regex,
+ self.type_constraints,
+ self.json_schema,
+ self.grammar,
+ ]
+
+ num_constraints = sum(constraint is not None for constraint in constraints)
+ if num_constraints != 1 and num_constraints != 0:
+ raise ValueError(
+ "Either none or exactly one of regex, type_constraints, "
+ "json_schema, or grammar can be provided."
+ )
+ if self.regex:
+ return generate.regex(self.client, regex_str=self.regex)
+ if self.type_constraints:
+ return generate.format(self.client, python_type=self.type_constraints)
+ if self.json_schema:
+ return generate.json(self.client, schema_object=self.json_schema)
+ if self.grammar:
+ return generate.cfg(self.client, cfg_str=self.grammar)
+ return generate.text(self.client)
+
+ def _convert_messages_to_openai_format(
+ self, messages: list[BaseMessage]
+ ) -> list[dict]:
+ return [convert_message_to_dict(message) for message in messages]
+
+ def _convert_messages_to_prompt(self, messages: list[BaseMessage]) -> str:
+ """Convert a list of messages to a single prompt."""
+ if self.backend == "llamacpp": # get base_model_name from gguf repo_id
+ from huggingface_hub import ModelCard
+
+ repo_creator, gguf_repo_name, file_name = self.model.split("/")
+ model_card = ModelCard.load(f"{repo_creator}/{gguf_repo_name}")
+ if hasattr(model_card.data, "base_model"):
+ model_name = model_card.data.base_model
+ else:
+ raise ValueError(f"Base model name not found for {self.model}")
+ else:
+ model_name = self.model
+
+ from transformers import AutoTokenizer
+
+ return AutoTokenizer.from_pretrained(model_name).apply_chat_template(
+ self._convert_messages_to_openai_format(messages),
+ tokenize=False,
+ add_generation_prompt=True,
+ )
+
+ def bind_tools(
+ self,
+ tools: Sequence[Dict[str, Any] | type | Callable[..., Any] | BaseTool],
+ *,
+ tool_choice: Optional[Union[Dict, bool, str]] = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model
+
+ tool_choice: does not currently support "any", "auto" choices like OpenAI
+ tool-calling API. should be a dict of the form to force this tool
+ {"type": "function", "function": {"name": <>}}.
+ """
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ tool_names = [ft["function"]["name"] for ft in formatted_tools]
+ if tool_choice:
+ if isinstance(tool_choice, dict):
+ if not any(
+ tool_choice["function"]["name"] == name for name in tool_names
+ ):
+ raise ValueError(
+ f"Tool choice {tool_choice=} was specified, but the only "
+ f"provided tools were {tool_names}."
+ )
+ elif isinstance(tool_choice, str):
+ chosen = [
+ f for f in formatted_tools if f["function"]["name"] == tool_choice
+ ]
+ if not chosen:
+ raise ValueError(
+ f"Tool choice {tool_choice=} was specified, but the only "
+ f"provided tools were {tool_names}."
+ )
+ elif isinstance(tool_choice, bool):
+ if len(formatted_tools) > 1:
+ raise ValueError(
+ "tool_choice=True can only be specified when a single tool is "
+ f"passed in. Received {len(tools)} tools."
+ )
+ tool_choice = formatted_tools[0]
+
+ kwargs["tool_choice"] = tool_choice
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ return super().bind_tools(tools=formatted_tools, **kwargs)
+
+ def with_structured_output(
+ self,
+ schema: Optional[_DictOrPydanticClass],
+ *,
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, Union[dict, BaseModel]]:
+ if get_origin(schema) is TypedDict:
+ raise NotImplementedError("TypedDict is not supported yet by Outlines")
+
+ self.json_schema = schema
+
+ if isinstance(schema, type) and issubclass(schema, BaseModel):
+ parser: Union[PydanticOutputParser, JsonOutputParser] = (
+ PydanticOutputParser(pydantic_object=schema)
+ )
+ else:
+ parser = JsonOutputParser()
+
+ if include_raw: # TODO
+ raise NotImplementedError("include_raw is not yet supported")
+
+ return self | parser
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ params = {**self._default_params, **kwargs}
+ if stop:
+ params["stop_at"] = stop
+
+ prompt = self._convert_messages_to_prompt(messages)
+
+ response = ""
+ if self.streaming:
+ for chunk in self._stream(
+ messages=messages,
+ stop=stop,
+ run_manager=run_manager,
+ **kwargs,
+ ):
+ if isinstance(chunk.message.content, str):
+ response += chunk.message.content
+ else:
+ raise ValueError(
+ "Invalid content type, only str is supported, "
+ f"got {type(chunk.message.content)}"
+ )
+ else:
+ response = self._generator(prompt, **params)
+
+ message = AIMessage(content=response)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ params = {**self._default_params, **kwargs}
+ if stop:
+ params["stop_at"] = stop
+
+ prompt = self._convert_messages_to_prompt(messages)
+
+ for token in self._generator.stream(prompt, **params):
+ if run_manager:
+ run_manager.on_llm_new_token(token)
+ message_chunk = AIMessageChunk(content=token)
+ chunk = ChatGenerationChunk(message=message_chunk)
+ yield chunk
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: List[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if hasattr(self._generator, "agenerate"):
+ params = {**self._default_params, **kwargs}
+ if stop:
+ params["stop_at"] = stop
+
+ prompt = self._convert_messages_to_prompt(messages)
+ response = await self._generator.agenerate(prompt, **params)
+
+ message = AIMessage(content=response)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+ elif self.streaming:
+ response = ""
+ async for chunk in self._astream(messages, stop, run_manager, **kwargs):
+ if isinstance(chunk.message.content, str):
+ response += chunk.message.content
+ elif chunk.message.content is not None:
+ raise ValueError(
+ "Invalid content type, only str is supported, "
+ f"got {type(chunk.message.content)}"
+ )
+ message = AIMessage(content=response)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+ else:
+ return await super()._agenerate(messages, stop, run_manager, **kwargs)
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: List[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ if hasattr(self._generator, "astream"):
+ params = {**self._default_params, **kwargs}
+ if stop:
+ params["stop_at"] = stop
+
+ prompt = self._convert_messages_to_prompt(messages)
+
+ async for token in self._generator.astream(prompt, **params):
+ if run_manager:
+ await run_manager.on_llm_new_token(token)
+ message_chunk = AIMessageChunk(content=token)
+ chunk = ChatGenerationChunk(message=message_chunk)
+ yield chunk
+ else:
+ async for chunk in super()._astream(messages, stop, run_manager, **kwargs):
+ yield chunk
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/pai_eas_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/pai_eas_endpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..55dd0ccbf93c3fd06c873963b37b5f5477f5545d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/pai_eas_endpoint.py
@@ -0,0 +1,304 @@
+import json
+import logging
+from typing import Any, AsyncIterator, Dict, List, Optional, cast
+
+import requests
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.utils import get_from_dict_or_env
+from pydantic import model_validator
+
+from langchain_community.llms.utils import enforce_stop_tokens
+
+logger = logging.getLogger(__name__)
+
+
+class PaiEasChatEndpoint(BaseChatModel):
+ """Alibaba Cloud PAI-EAS LLM Service chat model API.
+
+ To use, must have a deployed eas chat llm service on AliCloud. One can set the
+ environment variable ``eas_service_url`` and ``eas_service_token`` set with your eas
+ service url and service token.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import PaiEasChatEndpoint
+ eas_chat_endpoint = PaiEasChatEndpoint(
+ eas_service_url="your_service_url",
+ eas_service_token="your_service_token"
+ )
+ """
+
+ """PAI-EAS Service URL"""
+ eas_service_url: str
+
+ """PAI-EAS Service TOKEN"""
+ eas_service_token: str
+
+ """PAI-EAS Service Infer Params"""
+ max_new_tokens: Optional[int] = 512
+ temperature: Optional[float] = 0.8
+ top_p: Optional[float] = 0.1
+ top_k: Optional[int] = 10
+ do_sample: Optional[bool] = False
+ use_cache: Optional[bool] = True
+ stop_sequences: Optional[List[str]] = None
+
+ """Enable stream chat mode."""
+ streaming: bool = False
+
+ """Key/value arguments to pass to the model. Reserved for future use"""
+ model_kwargs: Optional[dict] = None
+
+ version: Optional[str] = "2.0"
+
+ timeout: Optional[int] = 5000
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+ values["eas_service_url"] = get_from_dict_or_env(
+ values, "eas_service_url", "EAS_SERVICE_URL"
+ )
+ values["eas_service_token"] = get_from_dict_or_env(
+ values, "eas_service_token", "EAS_SERVICE_TOKEN"
+ )
+
+ return values
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ _model_kwargs = self.model_kwargs or {}
+ return {
+ "eas_service_url": self.eas_service_url,
+ "eas_service_token": self.eas_service_token,
+ **{"model_kwargs": _model_kwargs},
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "pai_eas_chat_endpoint"
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling Cohere API."""
+ return {
+ "max_new_tokens": self.max_new_tokens,
+ "temperature": self.temperature,
+ "top_k": self.top_k,
+ "top_p": self.top_p,
+ "stop_sequences": [],
+ "do_sample": self.do_sample,
+ "use_cache": self.use_cache,
+ }
+
+ def _invocation_params(
+ self, stop_sequences: Optional[List[str]], **kwargs: Any
+ ) -> dict:
+ params = self._default_params
+ if self.model_kwargs:
+ params.update(self.model_kwargs)
+ if self.stop_sequences is not None and stop_sequences is not None:
+ raise ValueError("`stop` found in both the input and default params.")
+ elif self.stop_sequences is not None:
+ params["stop"] = self.stop_sequences
+ else:
+ params["stop"] = stop_sequences
+ return {**params, **kwargs}
+
+ def format_request_payload(
+ self, messages: List[BaseMessage], **model_kwargs: Any
+ ) -> dict:
+ prompt: Dict[str, Any] = {}
+ user_content: List[str] = []
+ assistant_content: List[str] = []
+
+ for message in messages:
+ """Converts message to a dict according to role"""
+ content = cast(str, message.content)
+ if isinstance(message, HumanMessage):
+ user_content = user_content + [content]
+ elif isinstance(message, AIMessage):
+ assistant_content = assistant_content + [content]
+ elif isinstance(message, SystemMessage):
+ prompt["system_prompt"] = content
+ elif isinstance(message, ChatMessage) and message.role in [
+ "user",
+ "assistant",
+ "system",
+ ]:
+ if message.role == "system":
+ prompt["system_prompt"] = content
+ elif message.role == "user":
+ user_content = user_content + [content]
+ elif message.role == "assistant":
+ assistant_content = assistant_content + [content]
+ else:
+ supported = ",".join([role for role in ["user", "assistant", "system"]])
+ raise ValueError(
+ f"""Received unsupported role.
+ Supported roles for the LLaMa Foundation Model: {supported}"""
+ )
+ prompt["prompt"] = user_content[len(user_content) - 1]
+ history = [
+ history_item
+ for _, history_item in enumerate(zip(user_content[:-1], assistant_content))
+ ]
+
+ prompt["history"] = history
+
+ return {**prompt, **model_kwargs}
+
+ def _format_response_payload(
+ self, output: bytes, stop_sequences: Optional[List[str]]
+ ) -> str:
+ """Formats response"""
+ try:
+ text = json.loads(output)["response"]
+ if stop_sequences:
+ text = enforce_stop_tokens(text, stop_sequences)
+ return text
+ except Exception as e:
+ if isinstance(e, json.decoder.JSONDecodeError):
+ return output.decode("utf-8")
+ raise e
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ output_str = self._call(messages, stop=stop, run_manager=run_manager, **kwargs)
+ message = AIMessage(content=output_str)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ def _call(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> str:
+ params = self._invocation_params(stop, **kwargs)
+
+ request_payload = self.format_request_payload(messages, **params)
+ response_payload = self._call_eas(request_payload)
+ generated_text = self._format_response_payload(response_payload, params["stop"])
+
+ if run_manager:
+ run_manager.on_llm_new_token(generated_text)
+
+ return generated_text
+
+ def _call_eas(self, query_body: dict) -> Any:
+ """Generate text from the eas service."""
+ headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ "Authorization": f"{self.eas_service_token}",
+ }
+
+ # make request
+ response = requests.post(
+ self.eas_service_url, headers=headers, json=query_body, timeout=self.timeout
+ )
+
+ if response.status_code != 200:
+ raise Exception(
+ f"Request failed with status code {response.status_code}"
+ f" and message {response.text}"
+ )
+
+ return response.text
+
+ def _call_eas_stream(self, query_body: dict) -> Any:
+ """Generate text from the eas service."""
+ headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ "Authorization": f"{self.eas_service_token}",
+ }
+
+ # make request
+ response = requests.post(
+ self.eas_service_url, headers=headers, json=query_body, timeout=self.timeout
+ )
+
+ if response.status_code != 200:
+ raise Exception(
+ f"Request failed with status code {response.status_code}"
+ f" and message {response.text}"
+ )
+
+ return response
+
+ def _convert_chunk_to_message_message(
+ self,
+ chunk: str,
+ ) -> AIMessageChunk:
+ data = json.loads(chunk.encode("utf-8"))
+ return AIMessageChunk(content=data.get("response", ""))
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ params = self._invocation_params(stop, **kwargs)
+
+ request_payload = self.format_request_payload(messages, **params)
+ request_payload["use_stream_chat"] = True
+
+ response = self._call_eas_stream(request_payload)
+ for chunk in response.iter_lines(
+ chunk_size=8192, decode_unicode=False, delimiter=b"\0"
+ ):
+ if chunk:
+ content = self._convert_chunk_to_message_message(chunk)
+
+ # identify stop sequence in generated text, if any
+ stop_seq_found: Optional[str] = None
+ for stop_seq in params["stop"]:
+ if stop_seq in content.content:
+ stop_seq_found = stop_seq
+
+ # identify text to yield
+ text: Optional[str] = None
+ if stop_seq_found:
+ content.content = content.content[
+ : content.content.index(stop_seq_found)
+ ]
+
+ # yield text, if any
+ if text:
+ cg_chunk = ChatGenerationChunk(message=content)
+ if run_manager:
+ await run_manager.on_llm_new_token(
+ cast(str, content.content), chunk=cg_chunk
+ )
+ yield cg_chunk
+
+ # break if stop sequence found
+ if stop_seq_found:
+ break
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/perplexity.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/perplexity.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7d57ea04ea62adbfd5045ccb5756e21a3b9eb61
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/perplexity.py
@@ -0,0 +1,525 @@
+"""Wrapper around Perplexity APIs."""
+
+from __future__ import annotations
+
+import logging
+from operator import itemgetter
+from typing import (
+ Any,
+ Dict,
+ Iterator,
+ List,
+ Literal,
+ Mapping,
+ Optional,
+ Tuple,
+ Type,
+ TypeVar,
+ Union,
+)
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+ ToolMessageChunk,
+)
+from langchain_core.messages.ai import UsageMetadata
+from langchain_core.output_parsers import JsonOutputParser, PydanticOutputParser
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
+from langchain_core.utils import from_env, get_pydantic_field_names
+from langchain_core.utils.pydantic import (
+ is_basemodel_subclass,
+)
+from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, model_validator
+from typing_extensions import Self
+
+_BM = TypeVar("_BM", bound=BaseModel)
+_DictOrPydanticClass = Union[Dict[str, Any], Type[_BM], Type]
+_DictOrPydantic = Union[Dict, _BM]
+
+logger = logging.getLogger(__name__)
+
+
+def _is_pydantic_class(obj: Any) -> bool:
+ return isinstance(obj, type) and is_basemodel_subclass(obj)
+
+
+def _create_usage_metadata(token_usage: dict) -> UsageMetadata:
+ input_tokens = token_usage.get("prompt_tokens", 0)
+ output_tokens = token_usage.get("completion_tokens", 0)
+ total_tokens = token_usage.get("total_tokens", input_tokens + output_tokens)
+ return UsageMetadata(
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ total_tokens=total_tokens,
+ )
+
+
+@deprecated(
+ since="0.3.21",
+ removal="1.0",
+ alternative_import="langchain_perplexity.ChatPerplexity",
+)
+class ChatPerplexity(BaseChatModel):
+ """`Perplexity AI` Chat models API.
+
+ Setup:
+ To use, you should have the ``openai`` python package installed, and the
+ environment variable ``PPLX_API_KEY`` set to your API key.
+ Any parameters that are valid to be passed to the openai.create call
+ can be passed in, even if not explicitly saved on this class.
+
+ .. code-block:: bash
+
+ pip install openai
+ export PPLX_API_KEY=your_api_key
+
+ Key init args - completion params:
+ model: str
+ Name of the model to use. e.g. "llama-3.1-sonar-small-128k-online"
+ temperature: float
+ Sampling temperature to use. Default is 0.7
+ max_tokens: Optional[int]
+ Maximum number of tokens to generate.
+ streaming: bool
+ Whether to stream the results or not.
+
+ Key init args - client params:
+ pplx_api_key: Optional[str]
+ API key for PerplexityChat API. Default is None.
+ request_timeout: Optional[Union[float, Tuple[float, float]]]
+ Timeout for requests to PerplexityChat completion API. Default is None.
+ max_retries: int
+ Maximum number of retries to make when generating.
+
+ See full list of supported init args and their descriptions in the params section.
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatPerplexity
+
+ llm = ChatPerplexity(
+ model="llama-3.1-sonar-small-128k-online",
+ temperature=0.7,
+ )
+
+ Invoke:
+ .. code-block:: python
+
+ messages = [
+ ("system", "You are a chatbot."),
+ ("user", "Hello!")
+ ]
+ llm.invoke(messages)
+
+ Invoke with structured output:
+ .. code-block:: python
+
+ from pydantic import BaseModel
+
+ class StructuredOutput(BaseModel):
+ role: str
+ content: str
+
+ llm.with_structured_output(StructuredOutput)
+ llm.invoke(messages)
+
+ Invoke with perplexity-specific params:
+ .. code-block:: python
+
+ llm.invoke(messages, extra_body={"search_recency_filter": "week"})
+
+ Stream:
+ .. code-block:: python
+
+ for chunk in llm.stream(messages):
+ print(chunk.content)
+
+ Token usage:
+ .. code-block:: python
+
+ response = llm.invoke(messages)
+ response.usage_metadata
+
+ Response metadata:
+ .. code-block:: python
+
+ response = llm.invoke(messages)
+ response.response_metadata
+
+ """ # noqa: E501
+
+ client: Any = None #: :meta private:
+ model: str = "llama-3.1-sonar-small-128k-online"
+ """Model name."""
+ temperature: float = 0.7
+ """What sampling temperature to use."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for `create` call not explicitly specified."""
+ pplx_api_key: Optional[str] = Field(
+ default_factory=from_env("PPLX_API_KEY", default=None), alias="api_key"
+ )
+ """Base URL path for API requests,
+ leave blank if not using a proxy or service emulator."""
+ request_timeout: Optional[Union[float, Tuple[float, float]]] = Field(
+ None, alias="timeout"
+ )
+ """Timeout for requests to PerplexityChat completion API. Default is None."""
+ max_retries: int = 6
+ """Maximum number of retries to make when generating."""
+ streaming: bool = False
+ """Whether to stream the results or not."""
+ max_tokens: Optional[int] = None
+ """Maximum number of tokens to generate."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"pplx_api_key": "PPLX_API_KEY"}
+
+ @model_validator(mode="before")
+ @classmethod
+ def build_extra(cls, values: Dict[str, Any]) -> Any:
+ """Build extra kwargs from additional params that were passed in."""
+ all_required_field_names = get_pydantic_field_names(cls)
+ extra = values.get("model_kwargs", {})
+ for field_name in list(values):
+ if field_name in extra:
+ raise ValueError(f"Found {field_name} supplied twice.")
+ if field_name not in all_required_field_names:
+ logger.warning(
+ f"""WARNING! {field_name} is not a default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please confirm that {field_name} is what you intended."""
+ )
+ extra[field_name] = values.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
+ if invalid_model_kwargs:
+ raise ValueError(
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+
+ values["model_kwargs"] = extra
+ return values
+
+ @model_validator(mode="after")
+ def validate_environment(self) -> Self:
+ """Validate that api key and python package exists in environment."""
+ try:
+ import openai
+ except ImportError:
+ raise ImportError(
+ "Could not import openai python package. "
+ "Please install it with `pip install openai`."
+ )
+ try:
+ self.client = openai.OpenAI(
+ api_key=self.pplx_api_key, base_url="https://api.perplexity.ai"
+ )
+ except AttributeError:
+ raise ValueError(
+ "`openai` has no `ChatCompletion` attribute, this is likely "
+ "due to an old version of the openai package. Try upgrading it "
+ "with `pip install --upgrade openai`."
+ )
+ return self
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling PerplexityChat API."""
+ return {
+ "max_tokens": self.max_tokens,
+ "stream": self.streaming,
+ "temperature": self.temperature,
+ **self.model_kwargs,
+ }
+
+ def _convert_message_to_dict(self, message: BaseMessage) -> Dict[str, Any]:
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ else:
+ raise TypeError(f"Got unknown type {message}")
+ return message_dict
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage], stop: Optional[List[str]]
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
+ params = dict(self._invocation_params)
+ if stop is not None:
+ if "stop" in params:
+ raise ValueError("`stop` found in both the input and default params.")
+ params["stop"] = stop
+ message_dicts = [self._convert_message_to_dict(m) for m in messages]
+ return message_dicts, params
+
+ def _convert_delta_to_message_chunk(
+ self, _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+ ) -> BaseMessageChunk:
+ role = _dict.get("role")
+ content = _dict.get("content") or ""
+ additional_kwargs: Dict = {}
+ if _dict.get("function_call"):
+ function_call = dict(_dict["function_call"])
+ if "name" in function_call and function_call["name"] is None:
+ function_call["name"] = ""
+ additional_kwargs["function_call"] = function_call
+ if _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = _dict["tool_calls"]
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ elif role == "function" or default_class == FunctionMessageChunk:
+ return FunctionMessageChunk(content=content, name=_dict["name"])
+ elif role == "tool" or default_class == ToolMessageChunk:
+ return ToolMessageChunk(content=content, tool_call_id=_dict["tool_call_id"])
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+ default_chunk_class = AIMessageChunk
+ params.pop("stream", None)
+ if stop:
+ params["stop_sequences"] = stop
+ stream_resp = self.client.chat.completions.create(
+ messages=message_dicts, stream=True, **params
+ )
+ first_chunk = True
+ prev_total_usage: Optional[UsageMetadata] = None
+ for chunk in stream_resp:
+ if not isinstance(chunk, dict):
+ chunk = chunk.dict()
+ # Collect standard usage metadata (transform from aggregate to delta)
+ if total_usage := chunk.get("usage"):
+ lc_total_usage = _create_usage_metadata(total_usage)
+ if prev_total_usage:
+ usage_metadata: Optional[UsageMetadata] = {
+ "input_tokens": lc_total_usage["input_tokens"]
+ - prev_total_usage["input_tokens"],
+ "output_tokens": lc_total_usage["output_tokens"]
+ - prev_total_usage["output_tokens"],
+ "total_tokens": lc_total_usage["total_tokens"]
+ - prev_total_usage["total_tokens"],
+ }
+ else:
+ usage_metadata = lc_total_usage
+ prev_total_usage = lc_total_usage
+ else:
+ usage_metadata = None
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+
+ additional_kwargs = {}
+ if first_chunk:
+ additional_kwargs["citations"] = chunk.get("citations", [])
+ for attr in ["images", "related_questions"]:
+ if attr in chunk:
+ additional_kwargs[attr] = chunk[attr]
+
+ chunk = self._convert_delta_to_message_chunk(
+ choice["delta"], default_chunk_class
+ )
+
+ if isinstance(chunk, AIMessageChunk) and usage_metadata:
+ chunk.usage_metadata = usage_metadata
+
+ if first_chunk:
+ chunk.additional_kwargs |= additional_kwargs
+ first_chunk = False
+
+ finish_reason = choice.get("finish_reason")
+ generation_info = (
+ dict(finish_reason=finish_reason) if finish_reason is not None else None
+ )
+ default_chunk_class = chunk.__class__
+ chunk = ChatGenerationChunk(message=chunk, generation_info=generation_info)
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ if stream_iter:
+ return generate_from_stream(stream_iter)
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+ response = self.client.chat.completions.create(messages=message_dicts, **params)
+ if usage := getattr(response, "usage", None):
+ usage_metadata = _create_usage_metadata(usage.model_dump())
+ else:
+ usage_metadata = None
+
+ additional_kwargs = {"citations": response.citations}
+ for attr in ["images", "related_questions"]:
+ if hasattr(response, attr):
+ additional_kwargs[attr] = getattr(response, attr)
+
+ message = AIMessage(
+ content=response.choices[0].message.content,
+ additional_kwargs=additional_kwargs,
+ usage_metadata=usage_metadata,
+ )
+ return ChatResult(generations=[ChatGeneration(message=message)])
+
+ @property
+ def _invocation_params(self) -> Mapping[str, Any]:
+ """Get the parameters used to invoke the model."""
+ pplx_creds: Dict[str, Any] = {
+ "model": self.model,
+ }
+ return {**pplx_creds, **self._default_params}
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "perplexitychat"
+
+ def with_structured_output(
+ self,
+ schema: Optional[_DictOrPydanticClass] = None,
+ *,
+ method: Literal["json_schema"] = "json_schema",
+ include_raw: bool = False,
+ strict: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, _DictOrPydantic]:
+ """Model wrapper that returns outputs formatted to match the given schema for Preplexity.
+ Currently, Preplexity only supports "json_schema" method for structured output
+ as per their official documentation: https://docs.perplexity.ai/guides/structured-outputs
+
+ Args:
+ schema:
+ The output schema. Can be passed in as:
+
+ - a JSON Schema,
+ - a TypedDict class,
+ - or a Pydantic class
+
+ method: The method for steering model generation, currently only support:
+
+ - "json_schema": Use the JSON Schema to parse the model output
+
+
+ include_raw:
+ If False then only the parsed structured output is returned. If
+ an error occurs during model output parsing it will be raised. If True
+ then both the raw model response (a BaseMessage) and the parsed model
+ response will be returned. If an error occurs during output parsing it
+ will be caught and returned as well. The final output is always a dict
+ with keys "raw", "parsed", and "parsing_error".
+
+ kwargs: Additional keyword args aren't supported.
+
+ Returns:
+ A Runnable that takes same inputs as a :class:`langchain_core.language_models.chat.BaseChatModel`.
+
+ | If ``include_raw`` is False and ``schema`` is a Pydantic class, Runnable outputs an instance of ``schema`` (i.e., a Pydantic object). Otherwise, if ``include_raw`` is False then Runnable outputs a dict.
+
+ | If ``include_raw`` is True, then Runnable outputs a dict with keys:
+
+ - "raw": BaseMessage
+ - "parsed": None if there was a parsing error, otherwise the type depends on the ``schema`` as described above.
+ - "parsing_error": Optional[BaseException]
+
+ """ # noqa: E501
+ if method in ("function_calling", "json_mode"):
+ method = "json_schema"
+ if method == "json_schema":
+ if schema is None:
+ raise ValueError(
+ "schema must be specified when method is not 'json_schema'. "
+ "Received None."
+ )
+ is_pydantic_schema = _is_pydantic_class(schema)
+ if is_pydantic_schema and hasattr(
+ schema, "model_json_schema"
+ ): # accounting for pydantic v1 and v2
+ response_format = schema.model_json_schema()
+ elif is_pydantic_schema:
+ response_format = schema.schema() # type: ignore[union-attr]
+ elif isinstance(schema, dict):
+ response_format = schema
+ elif type(schema).__name__ == "_TypedDictMeta":
+ adapter = TypeAdapter(schema) # if use passes typeddict
+ response_format = adapter.json_schema()
+
+ llm = self.bind(
+ response_format={
+ "type": "json_schema",
+ "json_schema": {"schema": response_format},
+ }
+ )
+ output_parser = (
+ PydanticOutputParser(pydantic_object=schema) # type: ignore[arg-type]
+ if is_pydantic_schema
+ else JsonOutputParser()
+ )
+ else:
+ raise ValueError(
+ f"Unrecognized method argument. Expected 'json_schema' Received:\
+ '{method}'"
+ )
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ else:
+ return llm | output_parser
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/premai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/premai.py
new file mode 100644
index 0000000000000000000000000000000000000000..3be2d0389a276655c45b1ccc85c0255d44bf90ef
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/premai.py
@@ -0,0 +1,541 @@
+"""Wrapper around Prem's Chat API."""
+
+from __future__ import annotations
+
+import logging
+import warnings
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ Union,
+)
+
+from langchain_core.callbacks import (
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.language_models.llms import create_base_retry_decorator
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+ ToolMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable
+from langchain_core.tools import BaseTool
+from langchain_core.utils import get_from_dict_or_env, pre_init
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SecretStr,
+)
+
+if TYPE_CHECKING:
+ from premai.api.chat_completions.v1_chat_completions_create import (
+ ChatCompletionResponseStream,
+ )
+ from premai.models.chat_completion_response import ChatCompletionResponse
+
+logger = logging.getLogger(__name__)
+
+TOOL_PROMPT_HEADER = """
+Given the set of tools you used and the response, provide the final answer\n
+"""
+
+INTERMEDIATE_TOOL_RESULT_TEMPLATE = """
+{json}
+"""
+
+SINGLE_TOOL_PROMPT_TEMPLATE = """
+tool id: {tool_id}
+tool_response: {tool_response}
+"""
+
+
+class ChatPremAPIError(Exception):
+ """Error with the `PremAI` API."""
+
+
+def _truncate_at_stop_tokens(
+ text: str,
+ stop: Optional[List[str]],
+) -> str:
+ """Truncates text at the earliest stop token found."""
+ if stop is None:
+ return text
+
+ for stop_token in stop:
+ stop_token_idx = text.find(stop_token)
+ if stop_token_idx != -1:
+ text = text[:stop_token_idx]
+ return text
+
+
+def _response_to_result(
+ response: ChatCompletionResponse,
+ stop: Optional[List[str]],
+) -> ChatResult:
+ """Converts a Prem API response into a LangChain result"""
+
+ if not response.choices:
+ raise ChatPremAPIError("ChatResponse must have at least one candidate")
+ generations: List[ChatGeneration] = []
+ for choice in response.choices:
+ role = choice.message.role
+ if role is None:
+ raise ChatPremAPIError(f"ChatResponse {choice} must have a role.")
+
+ # If content is None then it will be replaced by ""
+ content = _truncate_at_stop_tokens(text=choice.message.content or "", stop=stop)
+ if content is None:
+ raise ChatPremAPIError(f"ChatResponse must have a content: {content}")
+
+ if role == "assistant":
+ tool_calls = choice.message["tool_calls"]
+ if tool_calls is None:
+ tools = []
+ else:
+ tools = [
+ {
+ "id": tool_call["id"],
+ "name": tool_call["function"]["name"],
+ "args": tool_call["function"]["arguments"],
+ }
+ for tool_call in tool_calls
+ ]
+ generations.append(
+ ChatGeneration(
+ text=content, message=AIMessage(content=content, tool_calls=tools)
+ )
+ )
+ elif role == "user":
+ generations.append(
+ ChatGeneration(text=content, message=HumanMessage(content=content))
+ )
+ else:
+ generations.append(
+ ChatGeneration(
+ text=content, message=ChatMessage(role=role, content=content)
+ )
+ )
+
+ if response.document_chunks is not None:
+ return ChatResult(
+ generations=generations,
+ llm_output={
+ "document_chunks": [
+ chunk.to_dict() for chunk in response.document_chunks
+ ]
+ },
+ )
+ else:
+ return ChatResult(generations=generations, llm_output={"document_chunks": None})
+
+
+def _convert_delta_response_to_message_chunk(
+ response: ChatCompletionResponseStream, default_class: Type[BaseMessageChunk]
+) -> Tuple[
+ Union[BaseMessageChunk, HumanMessageChunk, AIMessageChunk, SystemMessageChunk],
+ Optional[str],
+]:
+ """Converts delta response to message chunk"""
+ _delta = response.choices[0].delta
+ role = _delta.get("role", "")
+ content = _delta.get("content", "")
+ additional_kwargs: Dict = {}
+ finish_reasons: Optional[str] = response.choices[0].finish_reason
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content), finish_reasons
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return (
+ AIMessageChunk(content=content, additional_kwargs=additional_kwargs),
+ finish_reasons,
+ )
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content), finish_reasons
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role), finish_reasons
+ else:
+ return default_class(content=content), finish_reasons # type: ignore[call-arg]
+
+
+def _messages_to_prompt_dict(
+ input_messages: List[BaseMessage],
+ template_id: Optional[str] = None,
+) -> Tuple[Optional[str], List[Dict[str, Any]]]:
+ """Converts a list of LangChain Messages into a simple dict
+ which is the message structure in Prem"""
+
+ system_prompt: Optional[str] = None
+ examples_and_messages: List[Dict[str, Any]] = []
+
+ for input_msg in input_messages:
+ if isinstance(input_msg, SystemMessage):
+ system_prompt = str(input_msg.content)
+
+ elif isinstance(input_msg, HumanMessage):
+ if template_id is None:
+ examples_and_messages.append(
+ {
+ "role": "user",
+ "content": str(input_msg.content),
+ }
+ )
+ else:
+ params: Dict[str, str] = {}
+ assert (input_msg.id is not None) and (input_msg.id != ""), ValueError(
+ "When using prompt template there should be id associated ",
+ "with each HumanMessage",
+ )
+ params[str(input_msg.id)] = str(input_msg.content)
+ examples_and_messages.append(
+ {
+ "role": "user",
+ "template_id": template_id,
+ "params": params,
+ }
+ )
+ elif isinstance(input_msg, AIMessage):
+ if input_msg.tool_calls is None or len(input_msg.tool_calls) == 0:
+ examples_and_messages.append(
+ {
+ "role": "assistant",
+ "content": str(input_msg.content),
+ }
+ )
+ else:
+ ai_msg_to_json = {
+ "id": input_msg.id,
+ "content": input_msg.content,
+ "response_metadata": input_msg.response_metadata,
+ "tool_calls": input_msg.tool_calls,
+ }
+ examples_and_messages.append(
+ {
+ "role": "assistant",
+ "content": INTERMEDIATE_TOOL_RESULT_TEMPLATE.format(
+ json=ai_msg_to_json,
+ ),
+ }
+ )
+ elif isinstance(input_msg, ToolMessage):
+ pass
+
+ else:
+ raise ChatPremAPIError("No such role explicitly exists")
+
+ # do a separate search for tool calls
+ tool_prompt = ""
+ for input_msg in input_messages:
+ if isinstance(input_msg, ToolMessage):
+ tool_id = input_msg.tool_call_id
+ tool_result = input_msg.content
+ tool_prompt += SINGLE_TOOL_PROMPT_TEMPLATE.format(
+ tool_id=tool_id, tool_response=tool_result
+ )
+ if tool_prompt != "":
+ prompt = TOOL_PROMPT_HEADER
+ prompt += tool_prompt
+ examples_and_messages.append({"role": "user", "content": prompt})
+
+ return system_prompt, examples_and_messages
+
+
+class ChatPremAI(BaseChatModel, BaseModel):
+ """PremAI Chat models.
+
+ To use, you will need to have an API key. You can find your existing API Key
+ or generate a new one here: https://app.premai.io/api_keys/
+ """
+
+ # TODO: Need to add the default parameters through prem-sdk here
+
+ project_id: int
+ """The project ID in which the experiments or deployments are carried out.
+ You can find all your projects here: https://app.premai.io/projects/"""
+ premai_api_key: Optional[SecretStr] = Field(default=None, alias="api_key")
+ """Prem AI API Key. Get it here: https://app.premai.io/api_keys/"""
+
+ model: Optional[str] = Field(default=None, alias="model_name")
+ """Name of the model. This is an optional parameter.
+ The default model is the one deployed from Prem's LaunchPad: https://app.premai.io/projects/8/launchpad
+ If model name is other than default model then it will override the calls
+ from the model deployed from launchpad."""
+
+ session_id: Optional[str] = None
+ """The ID of the session to use. It helps to track the chat history."""
+
+ temperature: Optional[float] = Field(default=None)
+ """Model temperature. Value should be >= 0 and <= 1.0"""
+
+ top_p: Optional[float] = None
+ """top_p adjusts the number of choices for each predicted tokens based on
+ cumulative probabilities. Value should be ranging between 0.0 and 1.0.
+ """
+
+ max_tokens: Optional[int] = Field(default=None)
+
+ """The maximum number of tokens to generate"""
+
+ max_retries: int = Field(default=1)
+ """Max number of retries to call the API"""
+
+ system_prompt: Optional[str] = ""
+ """Acts like a default instruction that helps the LLM act or generate
+ in a specific way.This is an Optional Parameter. By default the
+ system prompt would be using Prem's Launchpad models system prompt.
+ Changing the system prompt would override the default system prompt.
+ """
+
+ repositories: Optional[dict] = None
+ """Add valid repository ids. This will be overriding existing connected
+ repositories (if any) and will use RAG with the connected repos.
+ """
+
+ streaming: Optional[bool] = False
+ """Whether to stream the responses or not."""
+
+ client: Any = None
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ @pre_init
+ def validate_environments(cls, values: Dict) -> Dict:
+ """Validate that the package is installed and that the API token is valid"""
+ try:
+ from premai import Prem
+ except ImportError as error:
+ raise ImportError(
+ "Could not import Prem Python package."
+ "Please install it with: `pip install premai`"
+ ) from error
+
+ try:
+ premai_api_key: Union[str, SecretStr] = get_from_dict_or_env(
+ values, "premai_api_key", "PREMAI_API_KEY"
+ )
+ values["client"] = Prem(
+ api_key=premai_api_key
+ if isinstance(premai_api_key, str)
+ else premai_api_key._secret_value
+ )
+ except Exception as error:
+ raise ValueError("Your API Key is incorrect. Please try again.") from error
+ return values
+
+ @property
+ def _llm_type(self) -> str:
+ return "premai"
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ return {
+ "model": self.model,
+ "system_prompt": self.system_prompt,
+ "temperature": self.temperature,
+ "max_tokens": self.max_tokens,
+ "repositories": self.repositories,
+ }
+
+ def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]:
+ kwargs_to_ignore = [
+ "top_p",
+ "frequency_penalty",
+ "presence_penalty",
+ "logit_bias",
+ "stop",
+ "seed",
+ ]
+ keys_to_remove = []
+
+ for key in kwargs:
+ if key in kwargs_to_ignore:
+ warnings.warn(f"WARNING: Parameter {key} is not supported in kwargs.")
+ keys_to_remove.append(key)
+
+ for key in keys_to_remove:
+ kwargs.pop(key)
+
+ all_kwargs = {**self._default_params, **kwargs}
+ for key in list(self._default_params.keys()):
+ if all_kwargs.get(key) is None or all_kwargs.get(key) == "":
+ all_kwargs.pop(key, None)
+ return all_kwargs
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if "template_id" in kwargs:
+ system_prompt, messages_to_pass = _messages_to_prompt_dict(
+ messages, template_id=kwargs["template_id"]
+ )
+ else:
+ system_prompt, messages_to_pass = _messages_to_prompt_dict(messages)
+
+ if system_prompt is not None and system_prompt != "":
+ kwargs["system_prompt"] = system_prompt
+
+ all_kwargs = self._get_all_kwargs(**kwargs)
+ response = chat_with_retry(
+ self,
+ project_id=self.project_id,
+ messages=messages_to_pass,
+ stream=False,
+ run_manager=run_manager,
+ **all_kwargs,
+ )
+
+ return _response_to_result(response=response, stop=stop)
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ if "template_id" in kwargs:
+ system_prompt, messages_to_pass = _messages_to_prompt_dict(
+ messages, template_id=kwargs["template_id"]
+ )
+ else:
+ system_prompt, messages_to_pass = _messages_to_prompt_dict(messages)
+
+ if stop is not None:
+ logger.warning("stop is not supported in langchain streaming")
+
+ if "system_prompt" not in kwargs:
+ if system_prompt is not None and system_prompt != "":
+ kwargs["system_prompt"] = system_prompt
+
+ all_kwargs = self._get_all_kwargs(**kwargs)
+
+ default_chunk_class = AIMessageChunk
+
+ for streamed_response in chat_with_retry(
+ self,
+ project_id=self.project_id,
+ messages=messages_to_pass,
+ stream=True,
+ run_manager=run_manager,
+ **all_kwargs,
+ ):
+ try:
+ chunk, finish_reason = _convert_delta_response_to_message_chunk(
+ response=streamed_response, default_class=default_chunk_class
+ )
+ generation_info = (
+ dict(finish_reason=finish_reason)
+ if finish_reason is not None
+ else None
+ )
+ cg_chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(cg_chunk.text, chunk=cg_chunk)
+ yield cg_chunk
+ except Exception as _:
+ continue
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ return super().bind(tools=formatted_tools, **kwargs)
+
+
+def create_prem_retry_decorator(
+ llm: ChatPremAI,
+ *,
+ max_retries: int = 1,
+ run_manager: Optional[Union[CallbackManagerForLLMRun]] = None,
+) -> Callable[[Any], Any]:
+ """Create a retry decorator for PremAI API errors."""
+ import premai.models
+
+ errors = [
+ premai.models.api_response_validation_error.APIResponseValidationError,
+ premai.models.conflict_error.ConflictError,
+ premai.models.model_not_found_error.ModelNotFoundError,
+ premai.models.permission_denied_error.PermissionDeniedError,
+ premai.models.provider_api_connection_error.ProviderAPIConnectionError,
+ premai.models.provider_api_status_error.ProviderAPIStatusError,
+ premai.models.provider_api_timeout_error.ProviderAPITimeoutError,
+ premai.models.provider_internal_server_error.ProviderInternalServerError,
+ premai.models.provider_not_found_error.ProviderNotFoundError,
+ premai.models.rate_limit_error.RateLimitError,
+ premai.models.unprocessable_entity_error.UnprocessableEntityError,
+ premai.models.validation_error.ValidationError,
+ ]
+
+ decorator = create_base_retry_decorator(
+ error_types=errors, max_retries=max_retries, run_manager=run_manager
+ )
+ return decorator
+
+
+def chat_with_retry(
+ llm: ChatPremAI,
+ project_id: int,
+ messages: List[dict],
+ stream: bool = False,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+) -> Any:
+ """Using tenacity for retry in completion call"""
+ retry_decorator = create_prem_retry_decorator(
+ llm, max_retries=llm.max_retries, run_manager=run_manager
+ )
+
+ @retry_decorator
+ def _completion_with_retry(
+ project_id: int,
+ messages: List[dict],
+ stream: Optional[bool] = False,
+ **kwargs: Any,
+ ) -> Any:
+ response = llm.client.chat.completions.create(
+ project_id=project_id,
+ messages=messages,
+ stream=stream,
+ **kwargs,
+ )
+ return response
+
+ return _completion_with_retry(
+ project_id=project_id,
+ messages=messages,
+ stream=stream,
+ **kwargs,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/promptlayer_openai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/promptlayer_openai.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee64362679bdef17eefd6bf097a9e85038276173
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/promptlayer_openai.py
@@ -0,0 +1,141 @@
+"""PromptLayer wrapper."""
+
+import datetime
+from typing import Any, Dict, List, Optional
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.messages import BaseMessage
+from langchain_core.outputs import ChatResult
+
+from langchain_community.chat_models import ChatOpenAI
+
+
+class PromptLayerChatOpenAI(ChatOpenAI):
+ """`PromptLayer` and `OpenAI` Chat large language models API.
+
+ To use, you should have the ``openai`` and ``promptlayer`` python
+ package installed, and the environment variable ``OPENAI_API_KEY``
+ and ``PROMPTLAYER_API_KEY`` set with your openAI API key and
+ promptlayer key respectively.
+
+ All parameters that can be passed to the OpenAI LLM can also
+ be passed here. The PromptLayerChatOpenAI adds to optional
+
+ parameters:
+ ``pl_tags``: List of strings to tag the request with.
+ ``return_pl_id``: If True, the PromptLayer request ID will be
+ returned in the ``generation_info`` field of the
+ ``Generation`` object.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import PromptLayerChatOpenAI
+ openai = PromptLayerChatOpenAI(model="gpt-3.5-turbo")
+ """
+
+ pl_tags: Optional[List[str]]
+ return_pl_id: Optional[bool] = False
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ return False
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Call ChatOpenAI generate and then call PromptLayer API to log the request."""
+ from promptlayer.utils import get_api_key, promptlayer_api_request
+
+ request_start_time = datetime.datetime.now().timestamp()
+ generated_responses = super()._generate(
+ messages, stop, run_manager, stream=stream, **kwargs
+ )
+ request_end_time = datetime.datetime.now().timestamp()
+ message_dicts, params = super()._create_message_dicts(messages, stop)
+ for i, generation in enumerate(generated_responses.generations):
+ response_dict, params = super()._create_message_dicts(
+ [generation.message], stop
+ )
+ params = {**params, **kwargs}
+ pl_request_id = promptlayer_api_request(
+ "langchain.PromptLayerChatOpenAI",
+ "langchain",
+ message_dicts,
+ params,
+ self.pl_tags,
+ response_dict,
+ request_start_time,
+ request_end_time,
+ get_api_key(),
+ return_pl_id=self.return_pl_id,
+ )
+ if self.return_pl_id:
+ if generation.generation_info is None or not isinstance(
+ generation.generation_info, dict
+ ):
+ generation.generation_info = {}
+ generation.generation_info["pl_request_id"] = pl_request_id
+ return generated_responses
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Call ChatOpenAI agenerate and then call PromptLayer to log."""
+ from promptlayer.utils import get_api_key, promptlayer_api_request_async
+
+ request_start_time = datetime.datetime.now().timestamp()
+ generated_responses = await super()._agenerate(
+ messages, stop, run_manager, stream=stream, **kwargs
+ )
+ request_end_time = datetime.datetime.now().timestamp()
+ message_dicts, params = super()._create_message_dicts(messages, stop)
+ for i, generation in enumerate(generated_responses.generations):
+ response_dict, params = super()._create_message_dicts(
+ [generation.message], stop
+ )
+ params = {**params, **kwargs}
+ pl_request_id = await promptlayer_api_request_async(
+ "langchain.PromptLayerChatOpenAI.async",
+ "langchain",
+ message_dicts,
+ params,
+ self.pl_tags,
+ response_dict,
+ request_start_time,
+ request_end_time,
+ get_api_key(),
+ return_pl_id=self.return_pl_id,
+ )
+ if self.return_pl_id:
+ if generation.generation_info is None or not isinstance(
+ generation.generation_info, dict
+ ):
+ generation.generation_info = {}
+ generation.generation_info["pl_request_id"] = pl_request_id
+ return generated_responses
+
+ @property
+ def _llm_type(self) -> str:
+ return "promptlayer-openai-chat"
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ return {
+ **super()._identifying_params,
+ "pl_tags": self.pl_tags,
+ "return_pl_id": self.return_pl_id,
+ }
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/reka.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/reka.py
new file mode 100644
index 0000000000000000000000000000000000000000..22c2b91838e1a7e02450e1fedd0261ae40e179e6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/reka.py
@@ -0,0 +1,440 @@
+import json
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Literal,
+ Mapping,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+)
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ HumanMessage,
+ SystemMessage,
+ ToolMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable
+from langchain_core.tools import BaseTool
+from langchain_core.utils import get_from_dict_or_env
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+DEFAULT_REKA_MODEL = "reka-flash"
+
+ContentType = Union[str, List[Union[str, Dict[str, Any]]]]
+
+
+def process_content_item(item: Dict[str, Any]) -> Dict[str, Any]:
+ """Process a single content item."""
+ if item["type"] == "image_url":
+ image_url = item["image_url"]
+ if isinstance(image_url, dict) and "url" in image_url:
+ # If it's in LangChain format, extract the URL value
+ item["image_url"] = image_url["url"]
+ return item
+
+
+def process_content(content: ContentType) -> List[Dict[str, Any]]:
+ """Process content to handle both text and media inputs,
+ returning a list of content items."""
+ if isinstance(content, str):
+ return [{"type": "text", "text": content}]
+ elif isinstance(content, list):
+ result = []
+ for item in content:
+ if isinstance(item, str):
+ result.append({"type": "text", "text": item})
+ elif isinstance(item, dict):
+ result.append(process_content_item(item))
+ else:
+ raise ValueError(f"Invalid content item format: {item}")
+ return result
+ else:
+ raise ValueError("Invalid content format")
+
+
+def convert_to_reka_messages(messages: List[BaseMessage]) -> List[Dict[str, Any]]:
+ """Convert LangChain messages to Reka message format."""
+ reka_messages: List[Dict[str, Any]] = []
+ system_message: Optional[str] = None
+
+ for message in messages:
+ if isinstance(message, SystemMessage):
+ if system_message is None:
+ if isinstance(message.content, str):
+ system_message = message.content
+ else:
+ raise TypeError("SystemMessage content must be a string.")
+ else:
+ raise ValueError("Multiple system messages are not supported.")
+ elif isinstance(message, HumanMessage):
+ processed_content = process_content(message.content)
+ if system_message:
+ if (
+ processed_content
+ and isinstance(processed_content[0], dict)
+ and processed_content[0].get("type") == "text"
+ and "text" in processed_content[0]
+ ):
+ processed_content[0]["text"] = (
+ f"{system_message}\n{processed_content[0]['text']}"
+ )
+ else:
+ processed_content.insert(
+ 0, {"type": "text", "text": system_message}
+ )
+ system_message = None
+ reka_messages.append({"role": "user", "content": processed_content})
+ elif isinstance(message, AIMessage):
+ reka_message: Dict[str, Any] = {"role": "assistant"}
+ if message.content:
+ processed_content = process_content(message.content)
+ reka_message["content"] = processed_content
+ if "tool_calls" in message.additional_kwargs:
+ tool_calls = message.additional_kwargs["tool_calls"]
+ formatted_tool_calls = []
+ for tool_call in tool_calls:
+ formatted_tool_call = {
+ "id": tool_call["id"],
+ "name": tool_call["function"]["name"],
+ "parameters": json.loads(tool_call["function"]["arguments"]),
+ }
+ formatted_tool_calls.append(formatted_tool_call)
+ reka_message["tool_calls"] = formatted_tool_calls
+ reka_messages.append(reka_message)
+ elif isinstance(message, ToolMessage):
+ content_list: List[Dict[str, Any]] = []
+ content_list.append(
+ {
+ "tool_call_id": message.tool_call_id,
+ "output": json.dumps({"status": message.content}),
+ }
+ )
+ reka_messages.append(
+ {
+ "role": "tool_output",
+ "content": content_list,
+ }
+ )
+ else:
+ raise ValueError(f"Unsupported message type: {type(message)}")
+
+ return reka_messages
+
+
+class ChatReka(BaseChatModel):
+ """Reka chat large language models."""
+
+ client: Any = None #: :meta private:
+ async_client: Any = None #: :meta private:
+ model: str = Field(default=DEFAULT_REKA_MODEL)
+ max_tokens: int = Field(default=256)
+ temperature: Optional[float] = None
+ streaming: bool = False
+ default_request_timeout: Optional[float] = None
+ max_retries: int = 2
+ reka_api_key: Optional[str] = None
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ model_config = ConfigDict(extra="forbid")
+ token_counter: Optional[
+ Callable[[Union[str, BaseMessage, List[BaseMessage]]], int]
+ ] = None
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict[str, Any]) -> Dict[str, Any]:
+ """Validate that API key and Python package exist in the environment."""
+ reka_api_key = values.get("reka_api_key")
+ reka_api_key = get_from_dict_or_env(
+ {"reka_api_key": reka_api_key}, "reka_api_key", "REKA_API_KEY"
+ )
+ values["reka_api_key"] = reka_api_key
+
+ try:
+ # Import reka libraries here
+ from reka.client import AsyncReka, Reka
+
+ values["client"] = Reka(
+ api_key=reka_api_key,
+ )
+ values["async_client"] = AsyncReka(
+ api_key=reka_api_key,
+ )
+ except ImportError:
+ raise ImportError(
+ "Could not import Reka Python package. "
+ "Please install it with `pip install reka-api`."
+ )
+ return values
+
+ @property
+ def _default_params(self) -> Mapping[str, Any]:
+ """Get the default parameters for calling Reka API."""
+ params = {
+ "model": self.model,
+ "max_tokens": self.max_tokens,
+ }
+ if self.temperature is not None:
+ params["temperature"] = self.temperature
+ return {**params, **self.model_kwargs}
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "reka-chat"
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ reka_messages = convert_to_reka_messages(messages)
+ params = {**self._default_params, **kwargs}
+ if stop:
+ params["stop"] = stop
+
+ stream = self.client.chat.create_stream(messages=reka_messages, **params)
+
+ for chunk in stream:
+ content = chunk.responses[0].chunk.content
+ chat_chunk = ChatGenerationChunk(message=AIMessageChunk(content=content))
+ if run_manager:
+ run_manager.on_llm_new_token(content, chunk=chat_chunk)
+ yield chat_chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ reka_messages = convert_to_reka_messages(messages)
+ params = {**self._default_params, **kwargs}
+ if stop:
+ params["stop"] = stop
+
+ stream = self.async_client.chat.create_stream(messages=reka_messages, **params)
+
+ async for chunk in stream:
+ content = chunk.responses[0].chunk.content
+ chat_chunk = ChatGenerationChunk(message=AIMessageChunk(content=content))
+ if run_manager:
+ await run_manager.on_llm_new_token(content, chunk=chat_chunk)
+ yield chat_chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ return generate_from_stream(
+ self._stream(messages, stop=stop, run_manager=run_manager, **kwargs)
+ )
+
+ reka_messages = convert_to_reka_messages(messages)
+ params = {**self._default_params, **kwargs}
+ if stop:
+ params["stop"] = stop
+ response = self.client.chat.create(messages=reka_messages, **params)
+
+ if response.responses[0].message.tool_calls:
+ tool_calls = response.responses[0].message.tool_calls
+ message = AIMessage(
+ content="", # Empty string instead of None
+ additional_kwargs={
+ "tool_calls": [
+ {
+ "id": tc.id,
+ "type": "function",
+ "function": {
+ "name": tc.name,
+ "arguments": json.dumps(tc.parameters),
+ },
+ }
+ for tc in tool_calls
+ ]
+ },
+ )
+ else:
+ content = response.responses[0].message.content
+ # Ensure content is never None
+ message = AIMessage(content=content if content is not None else "")
+
+ return ChatResult(generations=[ChatGeneration(message=message)])
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ return await agenerate_from_stream(
+ self._astream(messages, stop=stop, run_manager=run_manager, **kwargs)
+ )
+
+ reka_messages = convert_to_reka_messages(messages)
+ params = {**self._default_params, **kwargs}
+ if stop:
+ params["stop"] = stop
+ response = await self.async_client.chat.create(messages=reka_messages, **params)
+
+ if response.responses[0].message.tool_calls:
+ tool_calls = response.responses[0].message.tool_calls
+ message = AIMessage(
+ content="", # Empty string instead of None
+ additional_kwargs={
+ "tool_calls": [
+ {
+ "id": tc.id,
+ "type": "function",
+ "function": {
+ "name": tc.name,
+ "arguments": json.dumps(tc.parameters),
+ },
+ }
+ for tc in tool_calls
+ ]
+ },
+ )
+ else:
+ content = response.responses[0].message.content
+ # Ensure content is never None
+ message = AIMessage(content=content if content is not None else "")
+
+ return ChatResult(generations=[ChatGeneration(message=message)])
+
+ def get_num_tokens(self, input: Union[str, BaseMessage, List[BaseMessage]]) -> int:
+ """Calculate number of tokens.
+
+ Args:
+ input: Either a string, a single BaseMessage, or a list of BaseMessages.
+
+ Returns:
+ int: Number of tokens in the input.
+
+ Raises:
+ ImportError: If tiktoken is not installed.
+ ValueError: If message content is not a string.
+ """
+ if self.token_counter is not None:
+ return self.token_counter(input)
+
+ try:
+ import tiktoken
+ except ImportError:
+ raise ImportError(
+ "Could not import tiktoken python package. "
+ "Please install it with `pip install tiktoken`."
+ )
+
+ encoding = tiktoken.get_encoding("cl100k_base")
+
+ if isinstance(input, str):
+ return len(encoding.encode(input))
+ elif isinstance(input, BaseMessage):
+ content = input.content
+ if not isinstance(content, str):
+ raise ValueError(
+ f"Message content must be a string, got {type(content)}"
+ )
+ return len(encoding.encode(content))
+ elif isinstance(input, list):
+ total = 0
+ for msg in input:
+ content = msg.content
+ if not isinstance(content, str):
+ raise ValueError(
+ f"Message content must be a string, got {type(content)}"
+ )
+ total += len(encoding.encode(content))
+ return total
+ else:
+ raise TypeError(f"Unsupported input type: {type(input)}")
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ *,
+ tool_choice: Optional[Union[str, Literal["any"]]] = "auto",
+ strict: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model.
+
+ The `tool_choice` parameter controls how the model uses the tools you pass.
+ There are three available options:
+
+ - `"auto"`: Lets the model decide whether or not to invoke a tool. This is the
+ recommended way to do function calling with our models.
+ - `"none"`: Disables tool calling. In this case, even if you pass tools to
+ the model, the model will not invoke any tools.
+ - `"tool"`: Forces the model to invoke one or more of the tools it has
+ been passed.
+
+ Args:
+ tools: A list of tool definitions to bind to this chat model.
+ Supports any tool definition handled by
+ :meth:`langchain_core.utils.function_calling.convert_to_openai_tool`.
+ tool_choice: Controls how the model uses the tools you pass.
+ Options are "auto", "none", or "tool". Defaults to "auto".
+ strict:
+ If True, model output is guaranteed to exactly match the JSON Schema
+ provided in the tool definition.
+ If False, input schema will not be validated
+ and model output will not be validated.
+ If None, ``strict`` argument will not
+ be passed to the model.
+ kwargs: Any additional parameters are passed directly to the model.
+
+ Returns:
+ Runnable: An executable chain or component.
+ """
+ formatted_tools = [
+ convert_to_openai_tool(tool, strict=strict) for tool in tools
+ ]
+
+ # Ensure tool_choice is one of the allowed options
+ if tool_choice is None:
+ tool_choice = "auto"
+ if tool_choice == "any":
+ tool_choice = "tool"
+ if tool_choice not in ("auto", "none", "tool"):
+ raise ValueError(
+ f"Invalid tool_choice '{tool_choice}' provided. "
+ "Tool choice must be one of: 'auto', 'none', or 'tool'."
+ )
+
+ # Map tool_choice to the parameter expected by the Reka API
+ kwargs["tool_choice"] = tool_choice
+
+ # Pass the tools and updated kwargs to the model
+ formatted_tools = [tool["function"] for tool in formatted_tools]
+ return super().bind(tools=formatted_tools, **kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/sambanova.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/sambanova.py
new file mode 100644
index 0000000000000000000000000000000000000000..1146a037475c004c6728c404259c5b37d31c2aa2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/sambanova.py
@@ -0,0 +1,2219 @@
+import json
+from operator import itemgetter
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Literal,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ Union,
+ cast,
+)
+
+import requests
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks import (
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+ ToolMessage,
+)
+from langchain_core.output_parsers import (
+ JsonOutputParser,
+ PydanticOutputParser,
+)
+from langchain_core.output_parsers.base import OutputParserLike
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ PydanticToolsParser,
+ make_invalid_tool_call,
+ parse_tool_call,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
+from langchain_core.tools import BaseTool
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from langchain_core.utils.pydantic import is_basemodel_subclass
+from pydantic import BaseModel, Field, SecretStr
+from requests import Response
+
+
+def _convert_message_to_dict(message: BaseMessage) -> Dict[str, Any]:
+ """
+ convert a BaseMessage to a dictionary with Role / content
+
+ Args:
+ message: BaseMessage
+
+ Returns:
+ messages_dict: role / content dict
+ """
+ message_dict: Dict[str, Any] = {}
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ if "tool_calls" in message.additional_kwargs:
+ message_dict["tool_calls"] = message.additional_kwargs["tool_calls"]
+ if message_dict["content"] == "":
+ message_dict["content"] = None
+ elif isinstance(message, ToolMessage):
+ message_dict = {
+ "role": "tool",
+ "content": message.content,
+ "tool_call_id": message.tool_call_id,
+ }
+ else:
+ raise TypeError(f"Got unknown type {message}")
+ return message_dict
+
+
+def _create_message_dicts(messages: List[BaseMessage]) -> List[Dict[str, Any]]:
+ """
+ Convert a list of BaseMessages to a list of dictionaries with Role / content
+
+ Args:
+ messages: list of BaseMessages
+
+ Returns:
+ messages_dicts: list of role / content dicts
+ """
+ message_dicts = [_convert_message_to_dict(m) for m in messages]
+ return message_dicts
+
+
+def _is_pydantic_class(obj: Any) -> bool:
+ return isinstance(obj, type) and is_basemodel_subclass(obj)
+
+
+@deprecated(
+ since="0.3.16",
+ removal="1.0",
+ alternative_import="langchain_sambanova.ChatSambaNovaCloud",
+)
+class ChatSambaNovaCloud(BaseChatModel):
+ """
+ SambaNova Cloud chat model.
+
+ Setup:
+ To use, you should have the environment variables:
+ `SAMBANOVA_URL` set with your SambaNova Cloud URL.
+ `SAMBANOVA_API_KEY` set with your SambaNova Cloud API Key.
+ http://cloud.sambanova.ai/
+ Example:
+ .. code-block:: python
+ ChatSambaNovaCloud(
+ sambanova_url = SambaNova cloud endpoint URL,
+ sambanova_api_key = set with your SambaNova cloud API key,
+ model = model name,
+ max_tokens = max number of tokens to generate,
+ temperature = model temperature,
+ top_p = model top p,
+ top_k = model top k,
+ stream_options = include usage to get generation metrics
+ )
+
+ Key init args — completion params:
+ model: str
+ The name of the model to use, e.g., Meta-Llama-3-70B-Instruct.
+ streaming: bool
+ Whether to use streaming handler when using non streaming methods
+ max_tokens: int
+ max tokens to generate
+ temperature: float
+ model temperature
+ top_p: float
+ model top p
+ top_k: int
+ model top k
+ stream_options: dict
+ stream options, include usage to get generation metrics
+
+ Key init args — client params:
+ sambanova_url: str
+ SambaNova Cloud Url
+ sambanova_api_key: str
+ SambaNova Cloud api key
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatSambaNovaCloud
+
+ chat = ChatSambaNovaCloud(
+ sambanova_url = SambaNova cloud endpoint URL,
+ sambanova_api_key = set with your SambaNova cloud API key,
+ model = model name,
+ max_tokens = max number of tokens to generate,
+ temperature = model temperature,
+ top_p = model top p,
+ top_k = model top k,
+ stream_options = include usage to get generation metrics
+ )
+
+ Invoke:
+ .. code-block:: python
+
+ messages = [
+ SystemMessage(content="your are an AI assistant."),
+ HumanMessage(content="tell me a joke."),
+ ]
+ response = chat.invoke(messages)
+
+ Stream:
+ .. code-block:: python
+
+ for chunk in chat.stream(messages):
+ print(chunk.content, end="", flush=True)
+
+ Async:
+ .. code-block:: python
+
+ response = chat.ainvoke(messages)
+ await response
+
+ Tool calling:
+ .. code-block:: python
+
+ 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. Los Angeles, CA"
+ )
+
+ llm_with_tools = llm.bind_tools([GetWeather, GetPopulation])
+ ai_msg = llm_with_tools.invoke("Should I bring my umbrella today in LA?")
+ ai_msg.tool_calls
+
+ .. code-block:: none
+
+ [
+ {
+ 'name': 'GetWeather',
+ 'args': {'location': 'Los Angeles, CA'},
+ 'id': 'call_adf61180ea2b4d228a'
+ }
+ ]
+
+ Structured output:
+ .. code-block:: python
+
+ from typing import Optional
+
+ from pydantic import BaseModel, Field
+
+ class Joke(BaseModel):
+ '''Joke to tell user.'''
+
+ setup: str = Field(description="The setup of the joke")
+ punchline: str = Field(description="The punchline to the joke")
+
+ structured_model = llm.with_structured_output(Joke)
+ structured_model.invoke("Tell me a joke about cats")
+
+ .. code-block:: python
+
+ Joke(setup="Why did the cat join a band?",
+ punchline="Because it wanted to be the purr-cussionist!")
+
+ See `ChatSambanovaCloud.with_structured_output()` for more.
+
+ Token usage:
+ .. code-block:: python
+
+ response = chat.invoke(messages)
+ print(response.response_metadata["usage"]["prompt_tokens"]
+ print(response.response_metadata["usage"]["total_tokens"]
+
+ Response metadata
+ .. code-block:: python
+
+ response = chat.invoke(messages)
+ print(response.response_metadata)
+
+ """
+
+ sambanova_url: str = Field(default="")
+ """SambaNova Cloud Url"""
+
+ sambanova_api_key: SecretStr = Field(default=SecretStr(""))
+ """SambaNova Cloud api key"""
+
+ model: str = Field(default="Meta-Llama-3.1-8B-Instruct")
+ """The name of the model"""
+
+ streaming: bool = Field(default=False)
+ """Whether to use streaming handler when using non streaming methods"""
+
+ max_tokens: int = Field(default=1024)
+ """max tokens to generate"""
+
+ temperature: float = Field(default=0.7)
+ """model temperature"""
+
+ top_p: Optional[float] = Field(default=None)
+ """model top p"""
+
+ top_k: Optional[int] = Field(default=None)
+ """model top k"""
+
+ stream_options: Dict[str, Any] = Field(default={"include_usage": True})
+ """stream options, include usage to get generation metrics"""
+
+ additional_headers: Dict[str, Any] = Field(default={})
+ """Additional headers to sent in request"""
+
+ class Config:
+ populate_by_name = True
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return whether this model can be serialized by Langchain."""
+ return False
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"sambanova_api_key": "sambanova_api_key"}
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Return a dictionary of identifying parameters.
+
+ This information is used by the LangChain callback system, which
+ is used for tracing purposes make it possible to monitor LLMs.
+ """
+ return {
+ "model": self.model,
+ "streaming": self.streaming,
+ "max_tokens": self.max_tokens,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "top_k": self.top_k,
+ "stream_options": self.stream_options,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Get the type of language model used by this chat model."""
+ return "sambanovacloud-chatmodel"
+
+ def __init__(self, **kwargs: Any) -> None:
+ """init and validate environment variables"""
+ kwargs["sambanova_url"] = get_from_dict_or_env(
+ kwargs,
+ "sambanova_url",
+ "SAMBANOVA_URL",
+ default="https://api.sambanova.ai/v1/chat/completions",
+ )
+ kwargs["sambanova_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(kwargs, "sambanova_api_key", "SAMBANOVA_API_KEY")
+ )
+ super().__init__(**kwargs)
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[Any], Callable[..., Any], BaseTool]],
+ *,
+ tool_choice: Optional[Union[Dict[str, Any], bool, str]] = None,
+ parallel_tool_calls: Optional[bool] = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model
+
+ tool_choice: does not currently support "any", choice like
+ should be one of ["auto", "none", "required"]
+ """
+
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+
+ if tool_choice:
+ if isinstance(tool_choice, str):
+ # tool_choice is a tool/function name
+ if tool_choice not in ("auto", "none", "required"):
+ tool_choice = "auto"
+ elif isinstance(tool_choice, bool):
+ if tool_choice:
+ tool_choice = "required"
+ elif isinstance(tool_choice, dict):
+ raise ValueError(
+ "tool_choice must be one of ['auto', 'none', 'required']"
+ )
+ else:
+ raise ValueError(
+ f"Unrecognized tool_choice type. Expected str, bool"
+ f"Received: {tool_choice}"
+ )
+ else:
+ tool_choice = "auto"
+ kwargs["tool_choice"] = tool_choice
+ kwargs["parallel_tool_calls"] = parallel_tool_calls
+ return super().bind(tools=formatted_tools, **kwargs)
+
+ def with_structured_output(
+ self,
+ schema: Optional[Union[Dict[str, Any], Type[BaseModel]]] = None,
+ *,
+ method: Literal[
+ "function_calling", "json_mode", "json_schema"
+ ] = "function_calling",
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, Union[Dict[str, Any], BaseModel]]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema:
+ The output schema. Can be passed in as:
+ - an OpenAI function/tool schema,
+ - a JSON Schema,
+ - a TypedDict class,
+ - or a Pydantic.BaseModel class.
+ If `schema` is a Pydantic class then the model output will be a
+ Pydantic instance of that class, and the model-generated fields will be
+ validated by the Pydantic class. Otherwise the model output will be a
+ dict and will not be validated. See :meth:`langchain_core.utils.function_calling.convert_to_openai_tool`
+ for more on how to properly specify types and descriptions of
+ schema fields when specifying a Pydantic or TypedDict class.
+
+ method:
+ The method for steering model generation, either "function_calling"
+ "json_mode" or "json_schema".
+ If "function_calling" then the schema will be converted
+ to an OpenAI function and the returned model will make use of the
+ function-calling API. If "json_mode" or "json_schema" then OpenAI's
+ JSON mode will be used.
+ Note that if using "json_mode" or "json_schema" then you must include instructions
+ for formatting the output into the desired schema into the model call.
+
+ include_raw:
+ If False then only the parsed structured output is returned. If
+ an error occurs during model output parsing it will be raised. If True
+ then both the raw model response (a BaseMessage) and the parsed model
+ response will be returned. If an error occurs during output parsing it
+ will be caught and returned as well. The final output is always a dict
+ with keys "raw", "parsed", and "parsing_error".
+
+ Returns:
+ A Runnable that takes same inputs as a :class:`langchain_core.language_models.chat.BaseChatModel`.
+
+ If `include_raw` is False and `schema` is a Pydantic class, Runnable outputs
+ an instance of `schema` (i.e., a Pydantic object).
+
+ Otherwise, if `include_raw` is False then Runnable outputs a dict.
+
+ If `include_raw` is True, then Runnable outputs a dict with keys:
+ - `"raw"`: BaseMessage
+ - `"parsed"`: None if there was a parsing error, otherwise the type depends on the `schema` as described above.
+ - `"parsing_error"`: Optional[BaseException]
+
+ Example: schema=Pydantic class, method="function_calling", include_raw=False:
+ .. code-block:: python
+
+ from typing import Optional
+
+ from langchain_community.chat_models import ChatSambaNovaCloud
+ from pydantic import BaseModel, Field
+
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+
+ answer: str
+ justification: str = Field(
+ description="A justification for the answer."
+ )
+
+
+ llm = ChatSambaNovaCloud(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(AnswerWithJustification)
+
+ structured_llm.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+
+ # -> AnswerWithJustification(
+ # answer='They weigh the same',
+ # justification='A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same.'
+ # )
+
+ Example: schema=Pydantic class, method="function_calling", include_raw=True:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatSambaNovaCloud
+ from pydantic import BaseModel
+
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+
+ answer: str
+ justification: str
+
+
+ llm = ChatSambaNovaCloud(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(
+ AnswerWithJustification, include_raw=True
+ )
+
+ structured_llm.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+ # -> {
+ # 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'function': {'arguments': '{"answer": "They weigh the same.", "justification": "A pound is a unit of weight or mass, so one pound of bricks and one pound of feathers both weigh the same amount."}', 'name': 'AnswerWithJustification'}, 'id': 'call_17a431fc6a4240e1bd', 'type': 'function'}]}, response_metadata={'finish_reason': 'tool_calls', 'usage': {'acceptance_rate': 5, 'completion_tokens': 53, 'completion_tokens_after_first_per_sec': 343.7964936837758, 'completion_tokens_after_first_per_sec_first_ten': 439.1205661878638, 'completion_tokens_per_sec': 162.8511306784833, 'end_time': 1731527851.0698032, 'is_last_response': True, 'prompt_tokens': 213, 'start_time': 1731527850.7137961, 'time_to_first_token': 0.20475482940673828, 'total_latency': 0.32545061111450196, 'total_tokens': 266, 'total_tokens_per_sec': 817.3283162354066}, 'model_name': 'Meta-Llama-3.1-70B-Instruct', 'system_fingerprint': 'fastcoe', 'created': 1731527850}, id='95667eaf-447f-4b53-bb6e-b6e1094ded88', tool_calls=[{'name': 'AnswerWithJustification', 'args': {'answer': 'They weigh the same.', 'justification': 'A pound is a unit of weight or mass, so one pound of bricks and one pound of feathers both weigh the same amount.'}, 'id': 'call_17a431fc6a4240e1bd', 'type': 'tool_call'}]),
+ # 'parsed': AnswerWithJustification(answer='They weigh the same.', justification='A pound is a unit of weight or mass, so one pound of bricks and one pound of feathers both weigh the same amount.'),
+ # 'parsing_error': None
+ # }
+
+ Example: schema=TypedDict class, method="function_calling", include_raw=False:
+ .. code-block:: python
+
+ # IMPORTANT: If you are using Python <=3.8, you need to import Annotated
+ # from typing_extensions, not from typing.
+ from typing_extensions import Annotated, TypedDict
+
+ from langchain_community.chat_models import ChatSambaNovaCloud
+
+
+ class AnswerWithJustification(TypedDict):
+ '''An answer to the user question along with justification for the answer.'''
+
+ answer: str
+ justification: Annotated[
+ Optional[str], None, "A justification for the answer."
+ ]
+
+
+ llm = ChatSambaNovaCloud(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(AnswerWithJustification)
+
+ structured_llm.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+ # -> {
+ # 'answer': 'They weigh the same',
+ # 'justification': 'A pound is a unit of weight or mass, so one pound of bricks and one pound of feathers both weigh the same amount.'
+ # }
+
+ Example: schema=OpenAI function schema, method="function_calling", include_raw=False:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatSambaNovaCloud
+
+ oai_schema = {
+ 'name': 'AnswerWithJustification',
+ 'description': 'An answer to the user question along with justification for the answer.',
+ 'parameters': {
+ 'type': 'object',
+ 'properties': {
+ 'answer': {'type': 'string'},
+ 'justification': {'description': 'A justification for the answer.', 'type': 'string'}
+ },
+ 'required': ['answer']
+ }
+ }
+
+ llm = ChatSambaNovaCloud(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(oai_schema)
+
+ structured_llm.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+ # -> {
+ # 'answer': 'They weigh the same',
+ # 'justification': 'A pound is a unit of weight or mass, so one pound of bricks and one pound of feathers both weigh the same amount.'
+ # }
+
+ Example: schema=Pydantic class, method="json_mode", include_raw=True:
+ .. code-block::
+
+ from langchain_community.chat_models import ChatSambaNovaCloud
+ from pydantic import BaseModel
+
+ class AnswerWithJustification(BaseModel):
+ answer: str
+ justification: str
+
+ llm = ChatSambaNovaCloud(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(
+ AnswerWithJustification,
+ method="json_mode",
+ include_raw=True
+ )
+
+ structured_llm.invoke(
+ "Answer the following question. "
+ "Make sure to return a JSON blob with keys 'answer' and 'justification'.\n\n"
+ "What's heavier a pound of bricks or a pound of feathers?"
+ )
+ # -> {
+ # 'raw': AIMessage(content='{\n "answer": "They are the same weight",\n "justification": "A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same amount, one pound. The difference is in their density and volume. A pound of feathers would take up more space than a pound of bricks due to the difference in their densities."\n}', additional_kwargs={}, response_metadata={'finish_reason': 'stop', 'usage': {'acceptance_rate': 5.3125, 'completion_tokens': 79, 'completion_tokens_after_first_per_sec': 292.65701089829776, 'completion_tokens_after_first_per_sec_first_ten': 346.43324678555325, 'completion_tokens_per_sec': 200.012158915008, 'end_time': 1731528071.1708555, 'is_last_response': True, 'prompt_tokens': 70, 'start_time': 1731528070.737394, 'time_to_first_token': 0.16693782806396484, 'total_latency': 0.3949759876026827, 'total_tokens': 149, 'total_tokens_per_sec': 377.2381225105847}, 'model_name': 'Meta-Llama-3.1-70B-Instruct', 'system_fingerprint': 'fastcoe', 'created': 1731528070}, id='83208297-3eb9-4021-a856-ca78a15758df'),
+ # 'parsed': AnswerWithJustification(answer='They are the same weight', justification='A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same amount, one pound. The difference is in their density and volume. A pound of feathers would take up more space than a pound of bricks due to the difference in their densities.'),
+ # 'parsing_error': None
+ # }
+
+ Example: schema=None, method="json_mode", include_raw=True:
+ .. code-block::
+
+ from langchain_community.chat_models import ChatSambaNovaCloud
+
+ llm = ChatSambaNovaCloud(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(method="json_mode", include_raw=True)
+
+ structured_llm.invoke(
+ "Answer the following question. "
+ "Make sure to return a JSON blob with keys 'answer' and 'justification'.\n\n"
+ "What's heavier a pound of bricks or a pound of feathers?"
+ )
+ # -> {
+ # 'raw': AIMessage(content='{\n "answer": "They are the same weight",\n "justification": "A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same amount, one pound. The difference is in their density and volume. A pound of feathers would take up more space than a pound of bricks due to the difference in their densities."\n}', additional_kwargs={}, response_metadata={'finish_reason': 'stop', 'usage': {'acceptance_rate': 4.722222222222222, 'completion_tokens': 79, 'completion_tokens_after_first_per_sec': 357.1315485254867, 'completion_tokens_after_first_per_sec_first_ten': 416.83279609305305, 'completion_tokens_per_sec': 240.92819585198137, 'end_time': 1731528164.8474727, 'is_last_response': True, 'prompt_tokens': 70, 'start_time': 1731528164.4906917, 'time_to_first_token': 0.13837409019470215, 'total_latency': 0.3278985247892492, 'total_tokens': 149, 'total_tokens_per_sec': 454.4088757208256}, 'model_name': 'Meta-Llama-3.1-70B-Instruct', 'system_fingerprint': 'fastcoe', 'created': 1731528164}, id='15261eaf-8a25-42ef-8ed5-f63d8bf5b1b0'),
+ # 'parsed': {
+ # 'answer': 'They are the same weight',
+ # 'justification': 'A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same amount, one pound. The difference is in their density and volume. A pound of feathers would take up more space than a pound of bricks due to the difference in their densities.'},
+ # },
+ # 'parsing_error': None
+ # }
+
+ Example: schema=None, method="json_schema", include_raw=True:
+ .. code-block::
+
+ from langchain_community.chat_models import ChatSambaNovaCloud
+
+ class AnswerWithJustification(BaseModel):
+ answer: str
+ justification: str
+
+ llm = ChatSambaNovaCloud(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(AnswerWithJustification, method="json_schema", include_raw=True)
+
+ structured_llm.invoke(
+ "Answer the following question. "
+ "Make sure to return a JSON blob with keys 'answer' and 'justification'.\n\n"
+ "What's heavier a pound of bricks or a pound of feathers?"
+ )
+ # -> {
+ # 'raw': AIMessage(content='{\n "answer": "They are the same weight",\n "justification": "A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same amount, one pound. The difference is in their density and volume. A pound of feathers would take up more space than a pound of bricks due to the difference in their densities."\n}', additional_kwargs={}, response_metadata={'finish_reason': 'stop', 'usage': {'acceptance_rate': 5.3125, 'completion_tokens': 79, 'completion_tokens_after_first_per_sec': 292.65701089829776, 'completion_tokens_after_first_per_sec_first_ten': 346.43324678555325, 'completion_tokens_per_sec': 200.012158915008, 'end_time': 1731528071.1708555, 'is_last_response': True, 'prompt_tokens': 70, 'start_time': 1731528070.737394, 'time_to_first_token': 0.16693782806396484, 'total_latency': 0.3949759876026827, 'total_tokens': 149, 'total_tokens_per_sec': 377.2381225105847}, 'model_name': 'Meta-Llama-3.1-70B-Instruct', 'system_fingerprint': 'fastcoe', 'created': 1731528070}, id='83208297-3eb9-4021-a856-ca78a15758df'),
+ # 'parsed': AnswerWithJustification(answer='They are the same weight', justification='A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same amount, one pound. The difference is in their density and volume. A pound of feathers would take up more space than a pound of bricks due to the difference in their densities.'),
+ # 'parsing_error': None
+ # }
+ """ # noqa: E501
+ if kwargs:
+ raise ValueError(f"Received unsupported arguments {kwargs}")
+ is_pydantic_schema = _is_pydantic_class(schema)
+ if method == "function_calling":
+ if schema is None:
+ raise ValueError(
+ "`schema` must be specified when method is `function_calling`. "
+ "Received None."
+ )
+ tool_name = convert_to_openai_tool(schema)["function"]["name"]
+ llm = self.bind_tools([schema], tool_choice=tool_name)
+ if is_pydantic_schema:
+ output_parser: OutputParserLike[Any] = PydanticToolsParser(
+ tools=[schema], # type: ignore[list-item]
+ first_tool_only=True,
+ )
+ else:
+ output_parser = JsonOutputKeyToolsParser(
+ key_name=tool_name, first_tool_only=True
+ )
+ elif method == "json_mode":
+ llm = self
+ # TODO bind response format when json mode available by API
+ # llm = self.bind(response_format={"type": "json_object"})
+ if is_pydantic_schema:
+ schema = cast(Type[BaseModel], schema)
+ output_parser = PydanticOutputParser(pydantic_object=schema)
+ else:
+ output_parser = JsonOutputParser()
+
+ elif method == "json_schema":
+ if schema is None:
+ raise ValueError(
+ "`schema` must be specified when method is not `json_mode`. "
+ "Received None."
+ )
+ llm = self
+ # TODO bind response format when json schema available by API,
+ # update example
+ # llm = self.bind(
+ # response_format={"type": "json_object", "json_schema": schema}
+ # )
+ if is_pydantic_schema:
+ schema = cast(Type[BaseModel], schema)
+ output_parser = PydanticOutputParser(pydantic_object=schema)
+ else:
+ output_parser = JsonOutputParser()
+ else:
+ raise ValueError(
+ f"Unrecognized method argument. Expected one of `function_calling` or "
+ f"`json_mode`. Received: `{method}`"
+ )
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ else:
+ return llm | output_parser
+
+ def _handle_request(
+ self,
+ messages_dicts: List[Dict[str, Any]],
+ stop: Optional[List[str]] = None,
+ streaming: bool = False,
+ **kwargs: Any,
+ ) -> Response:
+ """
+ Performs a post request to the LLM API.
+
+ Args:
+ messages_dicts: List of role / content dicts to use as input.
+ stop: list of stop tokens
+ streaming: wether to do a streaming call
+
+ Returns:
+ An iterator of response dicts.
+ """
+ if streaming:
+ data = {
+ "messages": messages_dicts,
+ "max_tokens": self.max_tokens,
+ "stop": stop,
+ "model": self.model,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "top_k": self.top_k,
+ "stream": True,
+ "stream_options": self.stream_options,
+ **kwargs,
+ }
+ else:
+ data = {
+ "messages": messages_dicts,
+ "max_tokens": self.max_tokens,
+ "stop": stop,
+ "model": self.model,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "top_k": self.top_k,
+ **kwargs,
+ }
+ http_session = requests.Session()
+ response = http_session.post(
+ self.sambanova_url,
+ headers={
+ "Authorization": f"Bearer {self.sambanova_api_key.get_secret_value()}",
+ "Content-Type": "application/json",
+ **self.additional_headers,
+ },
+ json=data,
+ stream=streaming,
+ )
+ if response.status_code != 200:
+ raise RuntimeError(
+ f"Sambanova /complete call failed with status code "
+ f"{response.status_code}.",
+ f"{response.text}.",
+ )
+ return response
+
+ def _process_response(self, response: Response) -> AIMessage:
+ """
+ Process a non streaming response from the api
+
+ Args:
+ response: A request Response object
+
+ Returns
+ generation: an AIMessage with model generation
+ """
+ try:
+ response_dict = response.json()
+ if response_dict.get("error"):
+ raise RuntimeError(
+ f"Sambanova /complete call failed with status code "
+ f"{response.status_code}.",
+ f"{response_dict}.",
+ )
+ except Exception as e:
+ raise RuntimeError(
+ f"Sambanova /complete call failed couldn't get JSON response {e}"
+ f"response: {response.text}"
+ )
+ content = response_dict["choices"][0]["message"].get("content", "")
+ if content is None:
+ content = ""
+ additional_kwargs: Dict[str, Any] = {}
+ tool_calls = []
+ invalid_tool_calls = []
+ raw_tool_calls = response_dict["choices"][0]["message"].get("tool_calls")
+ if raw_tool_calls:
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ for raw_tool_call in raw_tool_calls:
+ if isinstance(raw_tool_call["function"]["arguments"], dict):
+ raw_tool_call["function"]["arguments"] = json.dumps(
+ raw_tool_call["function"].get("arguments", {})
+ )
+ try:
+ tool_calls.append(parse_tool_call(raw_tool_call, return_id=True))
+ except Exception as e:
+ invalid_tool_calls.append(
+ make_invalid_tool_call(raw_tool_call, str(e))
+ )
+ message = AIMessage(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_calls=tool_calls,
+ invalid_tool_calls=invalid_tool_calls,
+ response_metadata={
+ "finish_reason": response_dict["choices"][0]["finish_reason"],
+ "usage": response_dict.get("usage"),
+ "model_name": response_dict["model"],
+ "system_fingerprint": response_dict["system_fingerprint"],
+ "created": response_dict["created"],
+ },
+ id=response_dict["id"],
+ )
+ return message
+
+ def _process_stream_response(
+ self, response: Response
+ ) -> Iterator[BaseMessageChunk]:
+ """
+ Process a streaming response from the api
+
+ Args:
+ response: An iterable request Response object
+
+ Yields:
+ generation: an AIMessageChunk with model partial generation
+ """
+ try:
+ import sseclient
+ except ImportError:
+ raise ImportError(
+ "could not import sseclient library"
+ "Please install it with `pip install sseclient-py`."
+ )
+
+ client = sseclient.SSEClient(response)
+
+ for event in client.events():
+ if event.event == "error_event":
+ raise RuntimeError(
+ f"Sambanova /complete call failed with status code "
+ f"{response.status_code}."
+ f"{event.data}."
+ )
+
+ try:
+ # check if the response is a final event
+ # in that case event data response is '[DONE]'
+ if event.data != "[DONE]":
+ if isinstance(event.data, str):
+ data = json.loads(event.data)
+ else:
+ raise RuntimeError(
+ f"Sambanova /complete call failed with status code "
+ f"{response.status_code}."
+ f"{event.data}."
+ )
+ if data.get("error"):
+ raise RuntimeError(
+ f"Sambanova /complete call failed with status code "
+ f"{response.status_code}."
+ f"{event.data}."
+ )
+ if len(data["choices"]) > 0:
+ finish_reason = data["choices"][0].get("finish_reason")
+ content = data["choices"][0]["delta"]["content"]
+ id = data["id"]
+ chunk = AIMessageChunk(
+ content=content, id=id, additional_kwargs={}
+ )
+ else:
+ content = ""
+ id = data["id"]
+ metadata = {
+ "finish_reason": finish_reason,
+ "usage": data.get("usage"),
+ "model_name": data["model"],
+ "system_fingerprint": data["system_fingerprint"],
+ "created": data["created"],
+ }
+ chunk = AIMessageChunk(
+ content=content,
+ id=id,
+ response_metadata=metadata,
+ additional_kwargs={},
+ )
+ yield chunk
+
+ except Exception as e:
+ raise RuntimeError(
+ f"Error getting content chunk raw streamed response: {e}"
+ f"data: {event.data}"
+ )
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """
+ Call SambaNovaCloud models.
+
+ Args:
+ messages: the prompt composed of a list of messages.
+ stop: a list of strings on which the model should stop generating.
+ If generation stops due to a stop token, the stop token itself
+ SHOULD BE INCLUDED as part of the output. This is not enforced
+ across models right now, but it's a good practice to follow since
+ it makes it much easier to parse the output of the model
+ downstream and understand why generation stopped.
+ run_manager: A run manager with callbacks for the LLM.
+
+ Returns:
+ result: ChatResult with model generation
+ """
+ if self.streaming:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ if stream_iter:
+ return generate_from_stream(stream_iter)
+ messages_dicts = _create_message_dicts(messages)
+ response = self._handle_request(messages_dicts, stop, streaming=False, **kwargs)
+ message = self._process_response(response)
+ generation = ChatGeneration(
+ message=message,
+ generation_info={
+ "finish_reason": message.response_metadata["finish_reason"]
+ },
+ )
+ return ChatResult(generations=[generation])
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ """
+ Stream the output of the SambaNovaCloud chat model.
+
+ Args:
+ messages: the prompt composed of a list of messages.
+ stop: a list of strings on which the model should stop generating.
+ If generation stops due to a stop token, the stop token itself
+ SHOULD BE INCLUDED as part of the output. This is not enforced
+ across models right now, but it's a good practice to follow since
+ it makes it much easier to parse the output of the model
+ downstream and understand why generation stopped.
+ run_manager: A run manager with callbacks for the LLM.
+
+ Yields:
+ chunk: ChatGenerationChunk with model partial generation
+ """
+ messages_dicts = _create_message_dicts(messages)
+ response = self._handle_request(messages_dicts, stop, streaming=True, **kwargs)
+ for ai_message_chunk in self._process_stream_response(response):
+ chunk = ChatGenerationChunk(message=ai_message_chunk)
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+
+
+@deprecated(
+ since="0.3.16",
+ removal="1.0",
+ alternative_import="langchain_sambanova.ChatSambaStudio",
+)
+class ChatSambaStudio(BaseChatModel):
+ """
+ SambaStudio chat model.
+
+ Setup:
+ To use, you should have the environment variables:
+ `SAMBASTUDIO_URL` set with your SambaStudio deployed endpoint URL.
+ `SAMBASTUDIO_API_KEY` set with your SambaStudio deployed endpoint Key.
+ https://docs.sambanova.ai/sambastudio/latest/index.html
+ Example:
+
+ .. code-block:: python
+
+ ChatSambaStudio(
+ sambastudio_url = set with your SambaStudio deployed endpoint URL,
+ sambastudio_api_key = set with your SambaStudio deployed endpoint Key.
+ model = model or expert name (set for Bundle endpoints),
+ max_tokens = max number of tokens to generate,
+ temperature = model temperature,
+ top_p = model top p,
+ top_k = model top k,
+ do_sample = wether to do sample
+ process_prompt = wether to process prompt
+ (set for Bundle generic v1 and v2 endpoints)
+ stream_options = include usage to get generation metrics
+ special_tokens = start, start_role, end_role, end special tokens
+ (set for Bundle generic v1 and v2 endpoints when process prompt
+ set to false or for StandAlone v1 and v2 endpoints)
+ model_kwargs: Optional = Extra Key word arguments to pass to the model.
+ )
+
+ Key init args — completion params:
+ model: str
+ The name of the model to use, e.g., Meta-Llama-3-70B-Instruct-4096
+ (set for Bundle endpoints).
+ streaming: bool
+ Whether to use streaming
+ max_tokens: inthandler when using non streaming methods
+ max tokens to generate
+ temperature: float
+ model temperature
+ top_p: float
+ model top p
+ top_k: int
+ model top k
+ do_sample: bool
+ wether to do sample
+ process_prompt:
+ wether to process prompt (set for Bundle generic v1 and v2 endpoints)
+ stream_options: dict
+ stream options, include usage to get generation metrics
+ special_tokens: dict
+ start, start_role, end_role and end special tokens
+ (set for Bundle generic v1 and v2 endpoints when process prompt set to false
+ or for StandAlone v1 and v2 endpoints) default to llama3 special tokens
+ model_kwargs: dict
+ Extra Key word arguments to pass to the model.
+
+ Key init args — client params:
+ sambastudio_url: str
+ SambaStudio endpoint Url
+ sambastudio_api_key: str
+ SambaStudio endpoint api key
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatSambaStudio
+
+ chat = ChatSambaStudio=(
+ sambastudio_url = set with your SambaStudio deployed endpoint URL,
+ sambastudio_api_key = set with your SambaStudio deployed endpoint Key.
+ model = model or expert name (set for Bundle endpoints),
+ max_tokens = max number of tokens to generate,
+ temperature = model temperature,
+ top_p = model top p,
+ top_k = model top k,
+ do_sample = wether to do sample
+ process_prompt = wether to process prompt
+ (set for Bundle generic v1 and v2 endpoints)
+ stream_options = include usage to get generation metrics
+ special_tokens = start, start_role, end_role, and special tokens
+ (set for Bundle generic v1 and v2 endpoints when process prompt
+ set to false or for StandAlone v1 and v2 endpoints)
+ model_kwargs: Optional = Extra Key word arguments to pass to the model.
+ )
+
+ Invoke:
+ .. code-block:: python
+
+ messages = [
+ SystemMessage(content="your are an AI assistant."),
+ HumanMessage(content="tell me a joke."),
+ ]
+ response = chat.invoke(messages)
+
+ Stream:
+ .. code-block:: python
+
+ for chunk in chat.stream(messages):
+ print(chunk.content, end="", flush=True)
+
+ Async:
+ .. code-block:: python
+
+ response = chat.ainvoke(messages)
+ await response
+
+ Tool calling:
+ .. code-block:: python
+
+ 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. Los Angeles, CA"
+ )
+
+ llm_with_tools = llm.bind_tools([GetWeather, GetPopulation])
+ ai_msg = llm_with_tools.invoke("Should I bring my umbrella today in LA?")
+ ai_msg.tool_calls
+
+ .. code-block:: python
+
+ [
+ {
+ 'name': 'GetWeather',
+ 'args': {'location': 'Los Angeles, CA'},
+ 'id': 'call_adf61180ea2b4d228a'
+ }
+ ]
+
+ Structured output:
+ .. code-block:: python
+
+ from typing import Optional
+
+ from pydantic import BaseModel, Field
+
+ class Joke(BaseModel):
+ '''Joke to tell user.'''
+
+ setup: str = Field(description="The setup of the joke")
+ punchline: str = Field(description="The punchline to the joke")
+
+ structured_model = llm.with_structured_output(Joke)
+ structured_model.invoke("Tell me a joke about cats")
+
+ .. code-block:: python
+
+ Joke(setup="Why did the cat join a band?",
+ punchline="Because it wanted to be the purr-cussionist!")
+
+ See `ChatSambaStudio.with_structured_output()` for more.
+
+ Token usage:
+ .. code-block:: python
+
+ response = chat.invoke(messages)
+ print(response.response_metadata["usage"]["prompt_tokens"]
+ print(response.response_metadata["usage"]["total_tokens"]
+
+ Response metadata
+ .. code-block:: python
+
+ response = chat.invoke(messages)
+ print(response.response_metadata)
+ """
+
+ sambastudio_url: str = Field(default="")
+ """SambaStudio Url"""
+
+ sambastudio_api_key: SecretStr = Field(default=SecretStr(""))
+ """SambaStudio api key"""
+
+ base_url: str = Field(default="", exclude=True)
+ """SambaStudio non streaming Url"""
+
+ streaming_url: str = Field(default="", exclude=True)
+ """SambaStudio streaming Url"""
+
+ model: Optional[str] = Field(default=None)
+ """The name of the model or expert to use (for Bundle endpoints)"""
+
+ streaming: bool = Field(default=False)
+ """Whether to use streaming handler when using non streaming methods"""
+
+ max_tokens: int = Field(default=1024)
+ """max tokens to generate"""
+
+ temperature: Optional[float] = Field(default=0.7)
+ """model temperature"""
+
+ top_p: Optional[float] = Field(default=None)
+ """model top p"""
+
+ top_k: Optional[int] = Field(default=None)
+ """model top k"""
+
+ do_sample: Optional[bool] = Field(default=None)
+ """whether to do sampling"""
+
+ process_prompt: Optional[bool] = Field(default=True)
+ """whether process prompt (for Bundle generic v1 and v2 endpoints)"""
+
+ stream_options: Dict[str, Any] = Field(default={"include_usage": True})
+ """stream options, include usage to get generation metrics"""
+
+ special_tokens: Dict[str, Any] = Field(
+ default={
+ "start": "<|begin_of_text|>",
+ "start_role": "<|begin_of_text|><|start_header_id|>{role}<|end_header_id|>",
+ "end_role": "<|eot_id|>",
+ "end": "<|start_header_id|>assistant<|end_header_id|>\n",
+ }
+ )
+ """start, start_role, end_role and end special tokens
+ (set for Bundle generic v1 and v2 endpoints when process prompt set to false
+ or for StandAlone v1 and v2 endpoints)
+ default to llama3 special tokens"""
+
+ model_kwargs: Optional[Dict[str, Any]] = None
+ """Key word arguments to pass to the model."""
+
+ additional_headers: Dict[str, Any] = Field(default={})
+ """Additional headers to send in request"""
+
+ class Config:
+ populate_by_name = True
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return whether this model can be serialized by Langchain."""
+ return False
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {
+ "sambastudio_url": "sambastudio_url",
+ "sambastudio_api_key": "sambastudio_api_key",
+ }
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Return a dictionary of identifying parameters.
+
+ This information is used by the LangChain callback system, which
+ is used for tracing purposes make it possible to monitor LLMs.
+ """
+ return {
+ "model": self.model,
+ "streaming": self.streaming,
+ "max_tokens": self.max_tokens,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "top_k": self.top_k,
+ "do_sample": self.do_sample,
+ "process_prompt": self.process_prompt,
+ "stream_options": self.stream_options,
+ "special_tokens": self.special_tokens,
+ "model_kwargs": self.model_kwargs,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Get the type of language model used by this chat model."""
+ return "sambastudio-chatmodel"
+
+ def __init__(self, **kwargs: Any) -> None:
+ """init and validate environment variables"""
+ kwargs["sambastudio_url"] = get_from_dict_or_env(
+ kwargs, "sambastudio_url", "SAMBASTUDIO_URL"
+ )
+
+ kwargs["sambastudio_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(kwargs, "sambastudio_api_key", "SAMBASTUDIO_API_KEY")
+ )
+ kwargs["base_url"], kwargs["streaming_url"] = self._get_sambastudio_urls(
+ kwargs["sambastudio_url"]
+ )
+ super().__init__(**kwargs)
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[Any], Callable[..., Any], BaseTool]],
+ *,
+ tool_choice: Optional[Union[Dict[str, Any], bool, str]] = None,
+ parallel_tool_calls: Optional[bool] = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model
+
+ tool_choice: does not currently support "any", choice like
+ should be one of ["auto", "none", "required"]
+ """
+
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+
+ if tool_choice:
+ if isinstance(tool_choice, str):
+ # tool_choice is a tool/function name
+ if tool_choice not in ("auto", "none", "required"):
+ tool_choice = "auto"
+ elif isinstance(tool_choice, bool):
+ if tool_choice:
+ tool_choice = "required"
+ elif isinstance(tool_choice, dict):
+ raise ValueError(
+ "tool_choice must be one of ['auto', 'none', 'required']"
+ )
+ else:
+ raise ValueError(
+ f"Unrecognized tool_choice type. Expected str, bool"
+ f"Received: {tool_choice}"
+ )
+ else:
+ tool_choice = "auto"
+ kwargs["tool_choice"] = tool_choice
+ kwargs["parallel_tool_calls"] = parallel_tool_calls
+ return super().bind(tools=formatted_tools, **kwargs)
+
+ def with_structured_output(
+ self,
+ schema: Optional[Union[Dict[str, Any], Type[BaseModel]]] = None,
+ *,
+ method: Literal[
+ "function_calling", "json_mode", "json_schema"
+ ] = "function_calling",
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, Union[Dict[str, Any], BaseModel]]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema:
+ The output schema. Can be passed in as:
+ - an OpenAI function/tool schema,
+ - a JSON Schema,
+ - a TypedDict class,
+ - or a Pydantic class.
+ If `schema` is a Pydantic class then the model output will be a
+ Pydantic instance of that class, and the model-generated fields will be
+ validated by the Pydantic class. Otherwise the model output will be a
+ dict and will not be validated. See :meth:`langchain_core.utils.function_calling.convert_to_openai_tool`
+ for more on how to properly specify types and descriptions of
+ schema fields when specifying a Pydantic or TypedDict class.
+
+ method:
+ The method for steering model generation, either "function_calling"
+ "json_mode" or "json_schema".
+ If "function_calling" then the schema will be converted
+ to an OpenAI function and the returned model will make use of the
+ function-calling API. If "json_mode" or "json_schema" then OpenAI's
+ JSON mode will be used.
+ Note that if using "json_mode" or "json_schema" then you must include instructions
+ for formatting the output into the desired schema into the model call.
+
+ include_raw:
+ If False then only the parsed structured output is returned. If
+ an error occurs during model output parsing it will be raised. If True
+ then both the raw model response (a BaseMessage) and the parsed model
+ response will be returned. If an error occurs during output parsing it
+ will be caught and returned as well. The final output is always a dict
+ with keys "raw", "parsed", and "parsing_error".
+
+ Returns:
+ A Runnable that takes same inputs as a :class:`langchain_core.language_models.chat.BaseChatModel`.
+
+ If `include_raw` is False and `schema` is a Pydantic class, Runnable outputs
+ an instance of `schema` (i.e., a Pydantic object).
+
+ Otherwise, if `include_raw` is False then Runnable outputs a dict.
+
+ If `include_raw` is True, then Runnable outputs a dict with keys:
+ - `"raw"`: BaseMessage
+ - `"parsed"`: None if there was a parsing error, otherwise the type depends on the `schema` as described above.
+ - `"parsing_error"`: Optional[BaseException]
+
+ Example: schema=Pydantic class, method="function_calling", include_raw=False:
+ .. code-block:: python
+
+ from typing import Optional
+
+ from langchain_community.chat_models import ChatSambaStudio
+ from pydantic import BaseModel, Field
+
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+
+ answer: str
+ justification: str = Field(
+ description="A justification for the answer."
+ )
+
+
+ llm = ChatSambaStudio(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(AnswerWithJustification)
+
+ structured_llm.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+
+ # -> AnswerWithJustification(
+ # answer='They weigh the same',
+ # justification='A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same.'
+ # )
+
+ Example: schema=Pydantic class, method="function_calling", include_raw=True:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatSambaStudio
+ from pydantic import BaseModel
+
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+
+ answer: str
+ justification: str
+
+
+ llm = ChatSambaStudio(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(
+ AnswerWithJustification, include_raw=True
+ )
+
+ structured_llm.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+ # -> {
+ # 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'function': {'arguments': '{"answer": "They weigh the same.", "justification": "A pound is a unit of weight or mass, so one pound of bricks and one pound of feathers both weigh the same amount."}', 'name': 'AnswerWithJustification'}, 'id': 'call_17a431fc6a4240e1bd', 'type': 'function'}]}, response_metadata={'finish_reason': 'tool_calls', 'usage': {'acceptance_rate': 5, 'completion_tokens': 53, 'completion_tokens_after_first_per_sec': 343.7964936837758, 'completion_tokens_after_first_per_sec_first_ten': 439.1205661878638, 'completion_tokens_per_sec': 162.8511306784833, 'end_time': 1731527851.0698032, 'is_last_response': True, 'prompt_tokens': 213, 'start_time': 1731527850.7137961, 'time_to_first_token': 0.20475482940673828, 'total_latency': 0.32545061111450196, 'total_tokens': 266, 'total_tokens_per_sec': 817.3283162354066}, 'model_name': 'Meta-Llama-3.1-70B-Instruct', 'system_fingerprint': 'fastcoe', 'created': 1731527850}, id='95667eaf-447f-4b53-bb6e-b6e1094ded88', tool_calls=[{'name': 'AnswerWithJustification', 'args': {'answer': 'They weigh the same.', 'justification': 'A pound is a unit of weight or mass, so one pound of bricks and one pound of feathers both weigh the same amount.'}, 'id': 'call_17a431fc6a4240e1bd', 'type': 'tool_call'}]),
+ # 'parsed': AnswerWithJustification(answer='They weigh the same.', justification='A pound is a unit of weight or mass, so one pound of bricks and one pound of feathers both weigh the same amount.'),
+ # 'parsing_error': None
+ # }
+
+ Example: schema=TypedDict class, method="function_calling", include_raw=False:
+ .. code-block:: python
+
+ # IMPORTANT: If you are using Python <=3.8, you need to import Annotated
+ # from typing_extensions, not from typing.
+ from typing_extensions import Annotated, TypedDict
+
+ from langchain_community.chat_models import ChatSambaStudio
+
+
+ class AnswerWithJustification(TypedDict):
+ '''An answer to the user question along with justification for the answer.'''
+
+ answer: str
+ justification: Annotated[
+ Optional[str], None, "A justification for the answer."
+ ]
+
+
+ llm = ChatSambaStudio(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(AnswerWithJustification)
+
+ structured_llm.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+ # -> {
+ # 'answer': 'They weigh the same',
+ # 'justification': 'A pound is a unit of weight or mass, so one pound of bricks and one pound of feathers both weigh the same amount.'
+ # }
+
+ Example: schema=OpenAI function schema, method="function_calling", include_raw=False:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatSambaStudio
+
+ oai_schema = {
+ 'name': 'AnswerWithJustification',
+ 'description': 'An answer to the user question along with justification for the answer.',
+ 'parameters': {
+ 'type': 'object',
+ 'properties': {
+ 'answer': {'type': 'string'},
+ 'justification': {'description': 'A justification for the answer.', 'type': 'string'}
+ },
+ 'required': ['answer']
+ }
+ }
+
+ llm = ChatSambaStudio(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(oai_schema)
+
+ structured_llm.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+ # -> {
+ # 'answer': 'They weigh the same',
+ # 'justification': 'A pound is a unit of weight or mass, so one pound of bricks and one pound of feathers both weigh the same amount.'
+ # }
+
+ Example: schema=Pydantic class, method="json_mode", include_raw=True:
+ .. code-block::
+
+ from langchain_community.chat_models import ChatSambaStudio
+ from pydantic import BaseModel
+
+ class AnswerWithJustification(BaseModel):
+ answer: str
+ justification: str
+
+ llm = ChatSambaStudio(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(
+ AnswerWithJustification,
+ method="json_mode",
+ include_raw=True
+ )
+
+ structured_llm.invoke(
+ "Answer the following question. "
+ "Make sure to return a JSON blob with keys 'answer' and 'justification'.\n\n"
+ "What's heavier a pound of bricks or a pound of feathers?"
+ )
+ # -> {
+ # 'raw': AIMessage(content='{\n "answer": "They are the same weight",\n "justification": "A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same amount, one pound. The difference is in their density and volume. A pound of feathers would take up more space than a pound of bricks due to the difference in their densities."\n}', additional_kwargs={}, response_metadata={'finish_reason': 'stop', 'usage': {'acceptance_rate': 5.3125, 'completion_tokens': 79, 'completion_tokens_after_first_per_sec': 292.65701089829776, 'completion_tokens_after_first_per_sec_first_ten': 346.43324678555325, 'completion_tokens_per_sec': 200.012158915008, 'end_time': 1731528071.1708555, 'is_last_response': True, 'prompt_tokens': 70, 'start_time': 1731528070.737394, 'time_to_first_token': 0.16693782806396484, 'total_latency': 0.3949759876026827, 'total_tokens': 149, 'total_tokens_per_sec': 377.2381225105847}, 'model_name': 'Meta-Llama-3.1-70B-Instruct', 'system_fingerprint': 'fastcoe', 'created': 1731528070}, id='83208297-3eb9-4021-a856-ca78a15758df'),
+ # 'parsed': AnswerWithJustification(answer='They are the same weight', justification='A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same amount, one pound. The difference is in their density and volume. A pound of feathers would take up more space than a pound of bricks due to the difference in their densities.'),
+ # 'parsing_error': None
+ # }
+
+ Example: schema=None, method="json_mode", include_raw=True:
+ .. code-block::
+
+ from langchain_community.chat_models import ChatSambaStudio
+
+ llm = ChatSambaStudio(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(method="json_mode", include_raw=True)
+
+ structured_llm.invoke(
+ "Answer the following question. "
+ "Make sure to return a JSON blob with keys 'answer' and 'justification'.\n\n"
+ "What's heavier a pound of bricks or a pound of feathers?"
+ )
+ # -> {
+ # 'raw': AIMessage(content='{\n "answer": "They are the same weight",\n "justification": "A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same amount, one pound. The difference is in their density and volume. A pound of feathers would take up more space than a pound of bricks due to the difference in their densities."\n}', additional_kwargs={}, response_metadata={'finish_reason': 'stop', 'usage': {'acceptance_rate': 4.722222222222222, 'completion_tokens': 79, 'completion_tokens_after_first_per_sec': 357.1315485254867, 'completion_tokens_after_first_per_sec_first_ten': 416.83279609305305, 'completion_tokens_per_sec': 240.92819585198137, 'end_time': 1731528164.8474727, 'is_last_response': True, 'prompt_tokens': 70, 'start_time': 1731528164.4906917, 'time_to_first_token': 0.13837409019470215, 'total_latency': 0.3278985247892492, 'total_tokens': 149, 'total_tokens_per_sec': 454.4088757208256}, 'model_name': 'Meta-Llama-3.1-70B-Instruct', 'system_fingerprint': 'fastcoe', 'created': 1731528164}, id='15261eaf-8a25-42ef-8ed5-f63d8bf5b1b0'),
+ # 'parsed': {
+ # 'answer': 'They are the same weight',
+ # 'justification': 'A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same amount, one pound. The difference is in their density and volume. A pound of feathers would take up more space than a pound of bricks due to the difference in their densities.'},
+ # },
+ # 'parsing_error': None
+ # }
+
+ Example: schema=None, method="json_schema", include_raw=True:
+ .. code-block::
+
+ from langchain_community.chat_models import ChatSambaStudio
+
+ class AnswerWithJustification(BaseModel):
+ answer: str
+ justification: str
+
+ llm = ChatSambaStudio(model="Meta-Llama-3.1-70B-Instruct", temperature=0)
+ structured_llm = llm.with_structured_output(AnswerWithJustification, method="json_schema", include_raw=True)
+
+ structured_llm.invoke(
+ "Answer the following question. "
+ "Make sure to return a JSON blob with keys 'answer' and 'justification'.\n\n"
+ "What's heavier a pound of bricks or a pound of feathers?"
+ )
+ # -> {
+ # 'raw': AIMessage(content='{\n "answer": "They are the same weight",\n "justification": "A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same amount, one pound. The difference is in their density and volume. A pound of feathers would take up more space than a pound of bricks due to the difference in their densities."\n}', additional_kwargs={}, response_metadata={'finish_reason': 'stop', 'usage': {'acceptance_rate': 5.3125, 'completion_tokens': 79, 'completion_tokens_after_first_per_sec': 292.65701089829776, 'completion_tokens_after_first_per_sec_first_ten': 346.43324678555325, 'completion_tokens_per_sec': 200.012158915008, 'end_time': 1731528071.1708555, 'is_last_response': True, 'prompt_tokens': 70, 'start_time': 1731528070.737394, 'time_to_first_token': 0.16693782806396484, 'total_latency': 0.3949759876026827, 'total_tokens': 149, 'total_tokens_per_sec': 377.2381225105847}, 'model_name': 'Meta-Llama-3.1-70B-Instruct', 'system_fingerprint': 'fastcoe', 'created': 1731528070}, id='83208297-3eb9-4021-a856-ca78a15758df'),
+ # 'parsed': AnswerWithJustification(answer='They are the same weight', justification='A pound is a unit of weight or mass, so a pound of bricks and a pound of feathers both weigh the same amount, one pound. The difference is in their density and volume. A pound of feathers would take up more space than a pound of bricks due to the difference in their densities.'),
+ # 'parsing_error': None
+ # }
+
+ """ # noqa: E501
+ if kwargs:
+ raise ValueError(f"Received unsupported arguments {kwargs}")
+ is_pydantic_schema = _is_pydantic_class(schema)
+ if method == "function_calling":
+ if schema is None:
+ raise ValueError(
+ "schema must be specified when method is 'function_calling'. "
+ "Received None."
+ )
+ tool_name = convert_to_openai_tool(schema)["function"]["name"]
+ llm = self.bind_tools([schema], tool_choice=tool_name)
+ if is_pydantic_schema:
+ output_parser: OutputParserLike[Any] = PydanticToolsParser(
+ tools=[schema], # type: ignore[list-item]
+ first_tool_only=True,
+ )
+ else:
+ output_parser = JsonOutputKeyToolsParser(
+ key_name=tool_name, first_tool_only=True
+ )
+ elif method == "json_mode":
+ llm = self
+ # TODO bind response format when json mode available by API
+ # llm = self.bind(response_format={"type": "json_object"})
+ if is_pydantic_schema:
+ schema = cast(Type[BaseModel], schema)
+ output_parser = PydanticOutputParser(pydantic_object=schema)
+ else:
+ output_parser = JsonOutputParser()
+
+ elif method == "json_schema":
+ if schema is None:
+ raise ValueError(
+ "schema must be specified when method is not 'json_mode'. "
+ "Received None."
+ )
+ llm = self
+ # TODO bind response format when json schema available by API,
+ # update example
+ # llm = self.bind(
+ # response_format={"type": "json_object", "json_schema": schema}
+ # )
+ if is_pydantic_schema:
+ schema = cast(Type[BaseModel], schema)
+ output_parser = PydanticOutputParser(pydantic_object=schema)
+ else:
+ output_parser = JsonOutputParser()
+ else:
+ raise ValueError(
+ f"Unrecognized method argument. Expected one of 'function_calling' or "
+ f"'json_mode'. Received: '{method}'"
+ )
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ else:
+ return llm | output_parser
+
+ def _get_role(self, message: BaseMessage) -> str:
+ """
+ Get the role of LangChain BaseMessage
+
+ Args:
+ message: LangChain BaseMessage
+
+ Returns:
+ str: Role of the LangChain BaseMessage
+ """
+ if isinstance(message, SystemMessage):
+ role = "system"
+ elif isinstance(message, HumanMessage):
+ role = "user"
+ elif isinstance(message, AIMessage):
+ role = "assistant"
+ elif isinstance(message, ToolMessage):
+ role = "tool"
+ elif isinstance(message, ChatMessage):
+ role = message.role
+ else:
+ raise TypeError(f"Got unknown type {message}")
+ return role
+
+ def _messages_to_string(self, messages: List[BaseMessage], **kwargs: Any) -> str:
+ """
+ Convert a list of BaseMessages to a:
+ - dumped json string with Role / content dict structure
+ when process_prompt is true,
+ - string with special tokens if process_prompt is false
+ for generic V1 and V2 endpoints
+
+ Args:
+ messages: list of BaseMessages
+
+ Returns:
+ str: string to send as model input depending on process_prompt param
+ """
+ if self.process_prompt:
+ messages_dict: Dict[str, Any] = {
+ "conversation_id": "sambaverse-conversation-id",
+ "messages": [],
+ **kwargs,
+ }
+ for message in messages:
+ if isinstance(message, AIMessage):
+ message_dict = {
+ "message_id": message.id,
+ "role": self._get_role(message),
+ "content": message.content,
+ }
+ if "tool_calls" in message.additional_kwargs:
+ message_dict["tool_calls"] = message.additional_kwargs[
+ "tool_calls"
+ ]
+ if message_dict["content"] == "":
+ message_dict["content"] = None
+
+ elif isinstance(message, ToolMessage):
+ message_dict = {
+ "message_id": message.id,
+ "role": self._get_role(message),
+ "content": message.content,
+ "tool_call_id": message.tool_call_id,
+ }
+
+ else:
+ message_dict = {
+ "message_id": message.id,
+ "role": self._get_role(message),
+ "content": message.content,
+ }
+
+ messages_dict["messages"].append(message_dict)
+
+ messages_string = json.dumps(messages_dict)
+
+ else:
+ if "tools" in kwargs.keys():
+ raise NotImplementedError(
+ "tool calling not supported in API Generic V2 "
+ "without process_prompt, switch to OpenAI compatible API "
+ "or Generic V2 API with process_prompt=True"
+ )
+ messages_string = self.special_tokens["start"]
+ for message in messages:
+ messages_string += self.special_tokens["start_role"].format(
+ role=self._get_role(message)
+ )
+ messages_string += f" {message.content} "
+ messages_string += self.special_tokens["end_role"]
+ messages_string += self.special_tokens["end"]
+
+ return messages_string
+
+ def _get_sambastudio_urls(self, url: str) -> Tuple[str, str]:
+ """
+ Get streaming and non streaming URLs from the given URL
+
+ Args:
+ url: string with sambastudio base or streaming endpoint url
+
+ Returns:
+ base_url: string with url to do non streaming calls
+ streaming_url: string with url to do streaming calls
+ """
+ if "chat/completions" in url:
+ base_url = url
+ stream_url = url
+ else:
+ if "stream" in url:
+ base_url = url.replace("stream/", "")
+ stream_url = url
+ else:
+ base_url = url
+ if "generic" in url:
+ stream_url = "generic/stream".join(url.split("generic"))
+ else:
+ raise ValueError("Unsupported URL")
+ return base_url, stream_url
+
+ def _handle_request(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ streaming: Optional[bool] = False,
+ **kwargs: Any,
+ ) -> Response:
+ """
+ Performs a post request to the LLM API.
+
+ Args:
+ messages_dicts: List of role / content dicts to use as input.
+ stop: list of stop tokens
+ streaming: wether to do a streaming call
+
+ Returns:
+ A request Response object
+ """
+
+ # create request payload for openai compatible API
+ if "chat/completions" in self.sambastudio_url:
+ messages_dicts = _create_message_dicts(messages)
+ data = {
+ "messages": messages_dicts,
+ "max_tokens": self.max_tokens,
+ "stop": stop,
+ "model": self.model,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "top_k": self.top_k,
+ "stream": streaming,
+ "stream_options": self.stream_options,
+ **kwargs,
+ }
+ data = {key: value for key, value in data.items() if value is not None}
+ headers = {
+ "Authorization": f"Bearer "
+ f"{self.sambastudio_api_key.get_secret_value()}",
+ "Content-Type": "application/json",
+ **self.additional_headers,
+ }
+
+ # create request payload for generic v2 API
+ elif "api/v2/predict/generic" in self.sambastudio_url:
+ items = [
+ {"id": "item0", "value": self._messages_to_string(messages, **kwargs)}
+ ]
+ params: Dict[str, Any] = {
+ "select_expert": self.model,
+ "process_prompt": self.process_prompt,
+ "max_tokens_to_generate": self.max_tokens,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "top_k": self.top_k,
+ "do_sample": self.do_sample,
+ }
+ if self.model_kwargs is not None:
+ params = {**params, **self.model_kwargs}
+ params = {key: value for key, value in params.items() if value is not None}
+ data = {"items": items, "params": params}
+ headers = {
+ "key": self.sambastudio_api_key.get_secret_value(),
+ **self.additional_headers,
+ }
+
+ # create request payload for generic v1 API
+ elif "api/predict/generic" in self.sambastudio_url:
+ if "tools" in kwargs.keys():
+ raise NotImplementedError(
+ "tool calling not supported in API Generic V1, "
+ "switch to OpenAI compatible API or Generic V2 API"
+ )
+ params = {
+ "select_expert": self.model,
+ "process_prompt": self.process_prompt,
+ "max_tokens_to_generate": self.max_tokens,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "top_k": self.top_k,
+ "do_sample": self.do_sample,
+ **kwargs,
+ }
+ if self.model_kwargs is not None:
+ params = {**params, **self.model_kwargs}
+ params = {
+ key: {"type": type(value).__name__, "value": str(value)}
+ for key, value in params.items()
+ if value is not None
+ }
+ if streaming:
+ data = {
+ "instance": self._messages_to_string(messages),
+ "params": params,
+ }
+ else:
+ data = {
+ "instances": [self._messages_to_string(messages)],
+ "params": params,
+ }
+ headers = {
+ "key": self.sambastudio_api_key.get_secret_value(),
+ **self.additional_headers,
+ }
+
+ else:
+ raise ValueError(
+ f"Unsupported URL{self.sambastudio_url}"
+ "only openai, generic v1 and generic v2 APIs are supported"
+ )
+
+ http_session = requests.Session()
+ if streaming:
+ response = http_session.post(
+ self.streaming_url, headers=headers, json=data, stream=True
+ )
+ else:
+ response = http_session.post(
+ self.base_url, headers=headers, json=data, stream=False
+ )
+ if response.status_code != 200:
+ raise RuntimeError(
+ f"Sambanova /complete call failed with status code "
+ f"{response.status_code}."
+ f"{response.text}."
+ )
+ return response
+
+ def _process_response(self, response: Response) -> AIMessage:
+ """
+ Process a non streaming response from the api
+
+ Args:
+ response: A request Response object
+
+ Returns
+ generation: an AIMessage with model generation
+ """
+
+ # Extract json payload form response
+ try:
+ response_dict = response.json()
+ except Exception as e:
+ raise RuntimeError(
+ f"Sambanova /complete call failed couldn't get JSON response {e}"
+ f"response: {response.text}"
+ )
+
+ additional_kwargs: Dict[str, Any] = {}
+ tool_calls = []
+ invalid_tool_calls = []
+
+ # process response payload for openai compatible API
+ if "chat/completions" in self.sambastudio_url:
+ content = response_dict["choices"][0]["message"].get("content", "")
+ if content is None:
+ content = ""
+ id = response_dict["id"]
+ response_metadata = {
+ "finish_reason": response_dict["choices"][0]["finish_reason"],
+ "usage": response_dict.get("usage"),
+ "model_name": response_dict["model"],
+ "system_fingerprint": response_dict["system_fingerprint"],
+ "created": response_dict["created"],
+ }
+ raw_tool_calls = response_dict["choices"][0]["message"].get("tool_calls")
+ if raw_tool_calls:
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ for raw_tool_call in raw_tool_calls:
+ if isinstance(raw_tool_call["function"]["arguments"], dict):
+ raw_tool_call["function"]["arguments"] = json.dumps(
+ raw_tool_call["function"].get("arguments", {})
+ )
+ try:
+ tool_calls.append(
+ parse_tool_call(raw_tool_call, return_id=True)
+ )
+ except Exception as e:
+ invalid_tool_calls.append(
+ make_invalid_tool_call(raw_tool_call, str(e))
+ )
+
+ # process response payload for generic v2 API
+ elif "api/v2/predict/generic" in self.sambastudio_url:
+ content = response_dict["items"][0]["value"]["completion"]
+ id = response_dict["items"][0]["id"]
+ response_metadata = response_dict["items"][0]
+ raw_tool_calls = response_dict["items"][0]["value"].get("tool_calls")
+ if raw_tool_calls:
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ for raw_tool_call in raw_tool_calls:
+ if isinstance(raw_tool_call["function"]["arguments"], dict):
+ raw_tool_call["function"]["arguments"] = json.dumps(
+ raw_tool_call["function"].get("arguments", {})
+ )
+ try:
+ tool_calls.append(
+ parse_tool_call(raw_tool_call, return_id=True)
+ )
+ except Exception as e:
+ invalid_tool_calls.append(
+ make_invalid_tool_call(raw_tool_call, str(e))
+ )
+
+ # process response payload for generic v1 API
+ elif "api/predict/generic" in self.sambastudio_url:
+ content = response_dict["predictions"][0]["completion"]
+ id = None
+ response_metadata = response_dict
+
+ else:
+ raise ValueError(
+ f"Unsupported URL{self.sambastudio_url}"
+ "only openai, generic v1 and generic v2 APIs are supported"
+ )
+
+ return AIMessage(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_calls=tool_calls,
+ invalid_tool_calls=invalid_tool_calls,
+ response_metadata=response_metadata,
+ id=id,
+ )
+
+ def _process_stream_response(
+ self, response: Response
+ ) -> Iterator[BaseMessageChunk]:
+ """
+ Process a streaming response from the api
+
+ Args:
+ response: An iterable request Response object
+
+ Yields:
+ generation: an AIMessageChunk with model partial generation
+ """
+
+ try:
+ import sseclient
+ except ImportError:
+ raise ImportError(
+ "could not import sseclient library"
+ "Please install it with `pip install sseclient-py`."
+ )
+
+ # process response payload for openai compatible API
+ if "chat/completions" in self.sambastudio_url:
+ finish_reason = ""
+ client = sseclient.SSEClient(response)
+ for event in client.events():
+ if event.event == "error_event":
+ raise RuntimeError(
+ f"Sambanova /complete call failed with status code "
+ f"{response.status_code}."
+ f"{event.data}."
+ )
+ try:
+ # check if the response is not a final event ("[DONE]")
+ if event.data != "[DONE]":
+ if isinstance(event.data, str):
+ data = json.loads(event.data)
+ else:
+ raise RuntimeError(
+ f"Sambanova /complete call failed with status code "
+ f"{response.status_code}."
+ f"{event.data}."
+ )
+ if data.get("error"):
+ raise RuntimeError(
+ f"Sambanova /complete call failed with status code "
+ f"{response.status_code}."
+ f"{event.data}."
+ )
+ if len(data["choices"]) > 0:
+ finish_reason = data["choices"][0].get("finish_reason")
+ content = data["choices"][0]["delta"]["content"]
+ id = data["id"]
+ metadata = {}
+ else:
+ content = ""
+ id = data["id"]
+ metadata = {
+ "finish_reason": finish_reason,
+ "usage": data.get("usage"),
+ "model_name": data["model"],
+ "system_fingerprint": data["system_fingerprint"],
+ "created": data["created"],
+ }
+ if data.get("usage") is not None:
+ content = ""
+ id = data["id"]
+ metadata = {
+ "finish_reason": finish_reason,
+ "usage": data.get("usage"),
+ "model_name": data["model"],
+ "system_fingerprint": data["system_fingerprint"],
+ "created": data["created"],
+ }
+ yield AIMessageChunk(
+ content=content,
+ id=id,
+ response_metadata=metadata,
+ additional_kwargs={},
+ )
+
+ except Exception as e:
+ raise RuntimeError(
+ f"Error getting content chunk raw streamed response: {e}"
+ f"data: {event.data}"
+ )
+
+ # process response payload for generic v2 API
+ elif "api/v2/predict/generic" in self.sambastudio_url:
+ for line in response.iter_lines():
+ try:
+ data = json.loads(line)
+ content = data["result"]["items"][0]["value"]["stream_token"]
+ id = data["result"]["items"][0]["id"]
+ if data["result"]["items"][0]["value"]["is_last_response"]:
+ metadata = {
+ "finish_reason": data["result"]["items"][0]["value"].get(
+ "stop_reason"
+ ),
+ "prompt": data["result"]["items"][0]["value"].get("prompt"),
+ "usage": {
+ "prompt_tokens_count": data["result"]["items"][0][
+ "value"
+ ].get("prompt_tokens_count"),
+ "completion_tokens_count": data["result"]["items"][0][
+ "value"
+ ].get("completion_tokens_count"),
+ "total_tokens_count": data["result"]["items"][0][
+ "value"
+ ].get("total_tokens_count"),
+ "start_time": data["result"]["items"][0]["value"].get(
+ "start_time"
+ ),
+ "end_time": data["result"]["items"][0]["value"].get(
+ "end_time"
+ ),
+ "model_execution_time": data["result"]["items"][0][
+ "value"
+ ].get("model_execution_time"),
+ "time_to_first_token": data["result"]["items"][0][
+ "value"
+ ].get("time_to_first_token"),
+ "throughput_after_first_token": data["result"]["items"][
+ 0
+ ]["value"].get("throughput_after_first_token"),
+ "batch_size_used": data["result"]["items"][0][
+ "value"
+ ].get("batch_size_used"),
+ },
+ }
+ else:
+ metadata = {}
+ yield AIMessageChunk(
+ content=content,
+ id=id,
+ response_metadata=metadata,
+ additional_kwargs={},
+ )
+
+ except Exception as e:
+ raise RuntimeError(
+ f"Error getting content chunk raw streamed response: {e}"
+ f"line: {line}"
+ )
+
+ # process response payload for generic v1 API
+ elif "api/predict/generic" in self.sambastudio_url:
+ for line in response.iter_lines():
+ try:
+ data = json.loads(line)
+ content = data["result"]["responses"][0]["stream_token"]
+ id = None
+ if data["result"]["responses"][0]["is_last_response"]:
+ metadata = {
+ "finish_reason": data["result"]["responses"][0].get(
+ "stop_reason"
+ ),
+ "prompt": data["result"]["responses"][0].get("prompt"),
+ "usage": {
+ "prompt_tokens_count": data["result"]["responses"][
+ 0
+ ].get("prompt_tokens_count"),
+ "completion_tokens_count": data["result"]["responses"][
+ 0
+ ].get("completion_tokens_count"),
+ "total_tokens_count": data["result"]["responses"][
+ 0
+ ].get("total_tokens_count"),
+ "start_time": data["result"]["responses"][0].get(
+ "start_time"
+ ),
+ "end_time": data["result"]["responses"][0].get(
+ "end_time"
+ ),
+ "model_execution_time": data["result"]["responses"][
+ 0
+ ].get("model_execution_time"),
+ "time_to_first_token": data["result"]["responses"][
+ 0
+ ].get("time_to_first_token"),
+ "throughput_after_first_token": data["result"][
+ "responses"
+ ][0].get("throughput_after_first_token"),
+ "batch_size_used": data["result"]["responses"][0].get(
+ "batch_size_used"
+ ),
+ },
+ }
+ else:
+ metadata = {}
+ yield AIMessageChunk(
+ content=content,
+ id=id,
+ response_metadata=metadata,
+ additional_kwargs={},
+ )
+
+ except Exception as e:
+ raise RuntimeError(
+ f"Error getting content chunk raw streamed response: {e}"
+ f"line: {line}"
+ )
+
+ else:
+ raise ValueError(
+ f"Unsupported URL{self.sambastudio_url}"
+ "only openai, generic v1 and generic v2 APIs are supported"
+ )
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """
+ Call SambaStudio models.
+
+ Args:
+ messages: the prompt composed of a list of messages.
+ stop: a list of strings on which the model should stop generating.
+ If generation stops due to a stop token, the stop token itself
+ SHOULD BE INCLUDED as part of the output. This is not enforced
+ across models right now, but it's a good practice to follow since
+ it makes it much easier to parse the output of the model
+ downstream and understand why generation stopped.
+ run_manager: A run manager with callbacks for the LLM.
+
+ Returns:
+ result: ChatResult with model generation
+ """
+ if self.streaming:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ if stream_iter:
+ return generate_from_stream(stream_iter)
+ response = self._handle_request(messages, stop, streaming=False, **kwargs)
+ message = self._process_response(response)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ """
+ Stream the output of the SambaStudio model.
+
+ Args:
+ messages: the prompt composed of a list of messages.
+ stop: a list of strings on which the model should stop generating.
+ If generation stops due to a stop token, the stop token itself
+ SHOULD BE INCLUDED as part of the output. This is not enforced
+ across models right now, but it's a good practice to follow since
+ it makes it much easier to parse the output of the model
+ downstream and understand why generation stopped.
+ run_manager: A run manager with callbacks for the LLM.
+
+ Yields:
+ chunk: ChatGenerationChunk with model partial generation
+ """
+ response = self._handle_request(messages, stop, streaming=True, **kwargs)
+ for ai_message_chunk in self._process_stream_response(response):
+ chunk = ChatGenerationChunk(message=ai_message_chunk)
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/snowflake.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/snowflake.py
new file mode 100644
index 0000000000000000000000000000000000000000..aba661e627528dd90918c9c7e1c382a354c5a820
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/snowflake.py
@@ -0,0 +1,391 @@
+import json
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Literal,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+)
+
+from langchain_core.callbacks.manager import CallbackManagerForLLMRun
+from langchain_core.language_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.tools import BaseTool
+from langchain_core.utils import (
+ convert_to_secret_str,
+ get_from_dict_or_env,
+ get_pydantic_field_names,
+)
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from langchain_core.utils.utils import _build_model_kwargs
+from pydantic import Field, SecretStr, model_validator
+
+SUPPORTED_ROLES: List[str] = [
+ "system",
+ "user",
+ "assistant",
+]
+
+
+class ChatSnowflakeCortexError(Exception):
+ """Error with Snowpark client."""
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ """Convert a LangChain message to a dictionary.
+
+ Args:
+ message: The LangChain message.
+
+ Returns:
+ The dictionary.
+ """
+ message_dict: Dict[str, Any] = {
+ "content": message.content,
+ }
+
+ # Populate role and additional message data
+ if isinstance(message, ChatMessage) and message.role in SUPPORTED_ROLES:
+ message_dict["role"] = message.role
+ elif isinstance(message, SystemMessage):
+ message_dict["role"] = "system"
+ elif isinstance(message, HumanMessage):
+ message_dict["role"] = "user"
+ elif isinstance(message, AIMessage):
+ message_dict["role"] = "assistant"
+ else:
+ raise TypeError(f"Got unknown type {message}")
+ return message_dict
+
+
+def _truncate_at_stop_tokens(
+ text: str,
+ stop: Optional[List[str]],
+) -> str:
+ """Truncates text at the earliest stop token found."""
+ if stop is None:
+ return text
+
+ for stop_token in stop:
+ stop_token_idx = text.find(stop_token)
+ if stop_token_idx != -1:
+ text = text[:stop_token_idx]
+ return text
+
+
+class ChatSnowflakeCortex(BaseChatModel):
+ """Snowflake Cortex based Chat model
+
+ To use the chat model, you must have the ``snowflake-snowpark-python`` Python
+ package installed and either:
+
+ 1. environment variables set with your snowflake credentials or
+ 2. directly passed in as kwargs to the ChatSnowflakeCortex constructor.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatSnowflakeCortex
+ chat = ChatSnowflakeCortex()
+ """
+
+ # test_tools: Dict[str, Any] = Field(default_factory=dict)
+ test_tools: Dict[str, Union[Dict[str, Any], Type, Callable, BaseTool]] = Field(
+ default_factory=dict
+ )
+
+ session: Any = None
+ """Snowpark session object."""
+
+ model: str = "mistral-large"
+ """Snowflake cortex hosted LLM model name, defaulted to `mistral-large`.
+ Refer to docs for more options. Also note, not all models support
+ agentic workflows."""
+
+ cortex_function: str = "complete"
+ """Cortex function to use, defaulted to `complete`.
+ Refer to docs for more options."""
+
+ temperature: float = 0
+ """Model temperature. Value should be >= 0 and <= 1.0"""
+
+ max_tokens: Optional[int] = None
+ """The maximum number of output tokens in the response."""
+
+ top_p: Optional[float] = 0
+ """top_p adjusts the number of choices for each predicted tokens based on
+ cumulative probabilities. Value should be ranging between 0.0 and 1.0.
+ """
+
+ snowflake_username: Optional[str] = Field(default=None, alias="username")
+ """Automatically inferred from env var `SNOWFLAKE_USERNAME` if not provided."""
+ snowflake_password: Optional[SecretStr] = Field(default=None, alias="password")
+ """Automatically inferred from env var `SNOWFLAKE_PASSWORD` if not provided."""
+ snowflake_account: Optional[str] = Field(default=None, alias="account")
+ """Automatically inferred from env var `SNOWFLAKE_ACCOUNT` if not provided."""
+ snowflake_database: Optional[str] = Field(default=None, alias="database")
+ """Automatically inferred from env var `SNOWFLAKE_DATABASE` if not provided."""
+ snowflake_schema: Optional[str] = Field(default=None, alias="schema")
+ """Automatically inferred from env var `SNOWFLAKE_SCHEMA` if not provided."""
+ snowflake_warehouse: Optional[str] = Field(default=None, alias="warehouse")
+ """Automatically inferred from env var `SNOWFLAKE_WAREHOUSE` if not provided."""
+ snowflake_role: Optional[str] = Field(default=None, alias="role")
+ """Automatically inferred from env var `SNOWFLAKE_ROLE` if not provided."""
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type, Callable, BaseTool]],
+ *,
+ tool_choice: Optional[
+ Union[dict, str, Literal["auto", "any", "none"], bool]
+ ] = "auto",
+ **kwargs: Any,
+ ) -> "ChatSnowflakeCortex":
+ """Bind tool-like objects to this chat model, ensuring they conform to
+ expected formats."""
+
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ # self.test_tools.update(formatted_tools)
+ formatted_tools_dict = {
+ tool["name"]: tool for tool in formatted_tools if "name" in tool
+ }
+ self.test_tools.update(formatted_tools_dict)
+
+ return self
+
+ @model_validator(mode="before")
+ @classmethod
+ def build_extra(cls, values: Dict[str, Any]) -> Any:
+ """Build extra kwargs from additional params that were passed in."""
+ all_required_field_names = get_pydantic_field_names(cls)
+ values = _build_model_kwargs(values, all_required_field_names)
+ return values
+
+ @model_validator(mode="before")
+ def validate_environment(cls, values: Dict) -> Dict:
+ try:
+ from snowflake.snowpark import Session
+ except ImportError:
+ raise ImportError(
+ """`snowflake-snowpark-python` package not found, please install:
+ `pip install snowflake-snowpark-python`
+ """
+ )
+
+ values["snowflake_username"] = get_from_dict_or_env(
+ values, "snowflake_username", "SNOWFLAKE_USERNAME"
+ )
+ values["snowflake_password"] = convert_to_secret_str(
+ get_from_dict_or_env(values, "snowflake_password", "SNOWFLAKE_PASSWORD")
+ )
+ values["snowflake_account"] = get_from_dict_or_env(
+ values, "snowflake_account", "SNOWFLAKE_ACCOUNT"
+ )
+ values["snowflake_database"] = get_from_dict_or_env(
+ values, "snowflake_database", "SNOWFLAKE_DATABASE"
+ )
+ values["snowflake_schema"] = get_from_dict_or_env(
+ values, "snowflake_schema", "SNOWFLAKE_SCHEMA"
+ )
+ values["snowflake_warehouse"] = get_from_dict_or_env(
+ values, "snowflake_warehouse", "SNOWFLAKE_WAREHOUSE"
+ )
+ values["snowflake_role"] = get_from_dict_or_env(
+ values, "snowflake_role", "SNOWFLAKE_ROLE"
+ )
+
+ connection_params = {
+ "account": values["snowflake_account"],
+ "user": values["snowflake_username"],
+ "password": values["snowflake_password"].get_secret_value(),
+ "database": values["snowflake_database"],
+ "schema": values["snowflake_schema"],
+ "warehouse": values["snowflake_warehouse"],
+ "role": values["snowflake_role"],
+ "client_session_keep_alive": "True",
+ }
+
+ try:
+ values["session"] = Session.builder.configs(connection_params).create()
+ except Exception as e:
+ raise ChatSnowflakeCortexError(f"Failed to create session: {e}")
+
+ return values
+
+ def __del__(self) -> None:
+ if getattr(self, "session", None) is not None:
+ self.session.close()
+
+ @property
+ def _llm_type(self) -> str:
+ """Get the type of language model used by this chat model."""
+ return f"snowflake-cortex-{self.model}"
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ message_dicts = [_convert_message_to_dict(m) for m in messages]
+
+ # Check for tool invocation in the messages and prepare for tool use
+ tool_output = None
+ for message in messages:
+ if (
+ isinstance(message.content, dict)
+ and isinstance(message, SystemMessage)
+ and "invoke_tool" in message.content
+ ):
+ tool_info = json.loads(message.content.get("invoke_tool"))
+ tool_name = tool_info.get("tool_name")
+ if tool_name in self.test_tools:
+ tool_args = tool_info.get("args", {})
+ tool_output = self.test_tools[tool_name](**tool_args)
+ break
+
+ # Prepare messages for SQL query
+ if tool_output:
+ message_dicts.append(
+ {"tool_output": str(tool_output)}
+ ) # Ensure tool_output is a string
+
+ # JSON dump the message_dicts and options without additional escaping
+ message_json = json.dumps(message_dicts)
+ options = {
+ "temperature": self.temperature,
+ "top_p": self.top_p if self.top_p is not None else 1.0,
+ "max_tokens": self.max_tokens if self.max_tokens is not None else 2048,
+ }
+ options_json = json.dumps(options) # JSON string of options
+
+ # Form the SQL statement using JSON literals
+ sql_stmt = f"""
+ select snowflake.cortex.{self.cortex_function}(
+ '{self.model}',
+ parse_json($${message_json}$$),
+ parse_json($${options_json}$$)
+ ) as llm_response;
+ """
+
+ try:
+ # Use the Snowflake Cortex Complete function
+ self.session.sql(
+ f"USE WAREHOUSE {self.session.get_current_warehouse()};"
+ ).collect()
+ l_rows = self.session.sql(sql_stmt).collect()
+ except Exception as e:
+ raise ChatSnowflakeCortexError(
+ f"Error while making request to Snowflake Cortex: {e}"
+ )
+
+ response = json.loads(l_rows[0]["LLM_RESPONSE"])
+ ai_message_content = response["choices"][0]["messages"]
+
+ content = _truncate_at_stop_tokens(ai_message_content, stop)
+ message = AIMessage(
+ content=content,
+ response_metadata=response["usage"],
+ )
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ def _stream_content(
+ self, content: str, stop: Optional[List[str]]
+ ) -> Iterator[ChatGenerationChunk]:
+ """
+ Stream the output of the model in chunks to return ChatGenerationChunk.
+ """
+ chunk_size = 50 # Define a reasonable chunk size for streaming
+ truncated_content = _truncate_at_stop_tokens(content, stop)
+
+ for i in range(0, len(truncated_content), chunk_size):
+ chunk_content = truncated_content[i : i + chunk_size]
+
+ # Create and yield a ChatGenerationChunk with partial content
+ yield ChatGenerationChunk(message=AIMessageChunk(content=chunk_content))
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ """Stream the output of the model in chunks to return ChatGenerationChunk."""
+ message_dicts = [_convert_message_to_dict(m) for m in messages]
+
+ # Check for and potentially use a tool before streaming
+ for message in messages:
+ if (
+ isinstance(message, str)
+ and isinstance(message, SystemMessage)
+ and "invoke_tool" in message.content
+ ):
+ tool_info = json.loads(message.content)
+ tool_list = tool_info.get("invoke_tools", [])
+ for tool in tool_list:
+ tool_name = tool.get("tool_name")
+ tool_args = tool.get("args", {})
+
+ if tool_name in self.test_tools:
+ tool_args = tool_info.get("args", {})
+ tool_result = self.test_tools[tool_name](**tool_args)
+ additional_context = {"tool_output": tool_result}
+ message_dicts.append(
+ additional_context
+ ) # Append tool result to message dicts
+
+ # JSON dump the message_dicts and options without additional escaping
+ message_json = json.dumps(message_dicts)
+ options = {
+ "temperature": self.temperature,
+ "top_p": self.top_p if self.top_p is not None else 1.0,
+ "max_tokens": self.max_tokens if self.max_tokens is not None else 2048,
+ # "stream": True,
+ }
+ options_json = json.dumps(options) # JSON string of options
+
+ # Form the SQL statement using JSON literals
+ sql_stmt = f"""
+ select snowflake.cortex.{self.cortex_function}(
+ '{self.model}',
+ parse_json($${message_json}$$),
+ parse_json($${options_json}$$)
+ ) as llm_stream_response;
+ """
+
+ try:
+ # Use the Snowflake Cortex Complete function
+ self.session.sql(
+ f"USE WAREHOUSE {self.session.get_current_warehouse()};"
+ ).collect()
+ result = self.session.sql(sql_stmt).collect()
+
+ # Iterate over the generator to yield streaming responses
+ for row in result:
+ response = json.loads(row["LLM_STREAM_RESPONSE"])
+ ai_message_content = response["choices"][0]["messages"]
+
+ # Stream response content in chunks
+ for chunk in self._stream_content(ai_message_content, stop):
+ yield chunk
+
+ except Exception as e:
+ raise ChatSnowflakeCortexError(
+ f"Error while making request to Snowflake Cortex stream: {e}"
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/solar.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/solar.py
new file mode 100644
index 0000000000000000000000000000000000000000..2be70ddc1ced6d9710b943490b1e4b4779eb5408
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/solar.py
@@ -0,0 +1,69 @@
+"""Wrapper around Solar chat models."""
+
+from typing import Dict
+
+from langchain_core._api import deprecated
+from langchain_core.utils import get_from_dict_or_env, pre_init
+from pydantic import ConfigDict, Field
+
+from langchain_community.chat_models import ChatOpenAI
+from langchain_community.llms.solar import SOLAR_SERVICE_URL_BASE, SolarCommon
+
+
+@deprecated(
+ since="0.0.34", removal="1.0", alternative_import="langchain_upstage.ChatUpstage"
+)
+class SolarChat(SolarCommon, ChatOpenAI):
+ """Wrapper around Solar large language models.
+ To use, you should have the ``openai`` python package installed, and the
+ environment variable ``SOLAR_API_KEY`` set with your API key.
+ (Solar's chat API is compatible with OpenAI's SDK.)
+ Referenced from https://console.upstage.ai/services/solar
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models.solar import SolarChat
+
+ solar = SolarChat(model="solar-mini")
+ """
+
+ max_tokens: int = Field(default=1024)
+
+ # this is needed to match ChatOpenAI superclass
+ model_config = ConfigDict(
+ populate_by_name=True,
+ arbitrary_types_allowed=True,
+ extra="ignore",
+ )
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that the environment is set up correctly."""
+ values["solar_api_key"] = get_from_dict_or_env(
+ values, "solar_api_key", "SOLAR_API_KEY"
+ )
+
+ try:
+ import openai
+
+ except ImportError:
+ raise ImportError(
+ "Could not import openai python package. "
+ "Please install it with `pip install openai`."
+ )
+
+ client_params = {
+ "api_key": values["solar_api_key"],
+ "base_url": (
+ values["base_url"] if "base_url" in values else SOLAR_SERVICE_URL_BASE
+ ),
+ }
+
+ if not values.get("client"):
+ values["client"] = openai.OpenAI(**client_params).chat.completions
+ if not values.get("async_client"):
+ values["async_client"] = openai.AsyncOpenAI(
+ **client_params
+ ).chat.completions
+
+ return values
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/sparkllm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/sparkllm.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b7d1d47d29cfdfb705be7731d9cc04cc433bb43
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/sparkllm.py
@@ -0,0 +1,652 @@
+import base64
+import hashlib
+import hmac
+import json
+import logging
+import queue
+import threading
+from datetime import datetime
+from queue import Queue
+from time import mktime
+from typing import Any, Dict, Generator, Iterator, List, Mapping, Optional, Type, cast
+from urllib.parse import urlencode, urlparse, urlunparse
+from wsgiref.handlers import format_date_time
+
+from langchain_core.callbacks import (
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ ToolMessageChunk,
+)
+from langchain_core.output_parsers.openai_tools import (
+ make_invalid_tool_call,
+ parse_tool_call,
+)
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ ChatResult,
+)
+from langchain_core.utils import (
+ get_from_dict_or_env,
+ get_pydantic_field_names,
+)
+from langchain_core.utils.pydantic import get_fields
+from pydantic import ConfigDict, Field, model_validator
+
+logger = logging.getLogger(__name__)
+
+SPARK_API_URL = "wss://spark-api.xf-yun.com/v3.5/chat"
+SPARK_LLM_DOMAIN = "generalv3.5"
+
+
+def convert_message_to_dict(message: BaseMessage) -> dict:
+ message_dict: Dict[str, Any]
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ if "function_call" in message.additional_kwargs:
+ message_dict["function_call"] = message.additional_kwargs["function_call"]
+ # If function call only, content is None not empty string
+ if message_dict["content"] == "":
+ message_dict["content"] = None
+ if "tool_calls" in message.additional_kwargs:
+ message_dict["tool_calls"] = message.additional_kwargs["tool_calls"]
+ # If tool calls only, content is None not empty string
+ if message_dict["content"] == "":
+ message_dict["content"] = None
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ else:
+ raise ValueError(f"Got unknown type {message}")
+
+ return message_dict
+
+
+def convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ msg_role = _dict["role"]
+ msg_content = _dict["content"]
+ if msg_role == "user":
+ return HumanMessage(content=msg_content)
+ elif msg_role == "assistant":
+ invalid_tool_calls = []
+ additional_kwargs: Dict = {}
+ if function_call := _dict.get("function_call"):
+ additional_kwargs["function_call"] = dict(function_call)
+ tool_calls = []
+ if raw_tool_calls := _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ for raw_tool_call in _dict["tool_calls"]:
+ try:
+ tool_calls.append(parse_tool_call(raw_tool_call, return_id=True))
+ except Exception as e:
+ invalid_tool_calls.append(
+ make_invalid_tool_call(raw_tool_call, str(e))
+ )
+ else:
+ additional_kwargs = {}
+ content = msg_content or ""
+ return AIMessage(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_calls=tool_calls,
+ invalid_tool_calls=invalid_tool_calls,
+ )
+ elif msg_role == "system":
+ return SystemMessage(content=msg_content)
+ else:
+ return ChatMessage(content=msg_content, role=msg_role)
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ msg_role = cast(str, _dict.get("role"))
+ msg_content = cast(str, _dict.get("content") or "")
+ additional_kwargs: Dict = {}
+ if _dict.get("function_call"):
+ function_call = dict(_dict["function_call"])
+ if "name" in function_call and function_call["name"] is None:
+ function_call["name"] = ""
+ additional_kwargs["function_call"] = function_call
+ if _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = _dict["tool_calls"]
+ if msg_role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=msg_content)
+ elif msg_role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=msg_content, additional_kwargs=additional_kwargs)
+ elif msg_role == "function" or default_class == FunctionMessageChunk:
+ return FunctionMessageChunk(content=msg_content, name=_dict["name"])
+ elif msg_role == "tool" or default_class == ToolMessageChunk:
+ return ToolMessageChunk(content=msg_content, tool_call_id=_dict["tool_call_id"])
+ elif msg_role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=msg_content, role=msg_role)
+ else:
+ return default_class(content=msg_content) # type: ignore[call-arg]
+
+
+class ChatSparkLLM(BaseChatModel):
+ """IFlyTek Spark chat model integration.
+
+ Setup:
+ To use, you should have the environment variable``IFLYTEK_SPARK_API_KEY``,
+ ``IFLYTEK_SPARK_API_SECRET`` and ``IFLYTEK_SPARK_APP_ID``.
+
+ Key init args — completion params:
+ model: Optional[str]
+ Name of IFLYTEK SPARK model to use.
+ temperature: Optional[float]
+ Sampling temperature.
+ top_k: Optional[float]
+ What search sampling control to use.
+ streaming: Optional[bool]
+ Whether to stream the results or not.
+
+ Key init args — client params:
+ api_key: Optional[str]
+ IFLYTEK SPARK API KEY. If not passed in will be read from env var IFLYTEK_SPARK_API_KEY.
+ api_secret: Optional[str]
+ IFLYTEK SPARK API SECRET. If not passed in will be read from env var IFLYTEK_SPARK_API_SECRET.
+ api_url: Optional[str]
+ Base URL for API requests.
+ timeout: Optional[int]
+ Timeout for requests.
+
+ See full list of supported init args and their descriptions in the params section.
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatSparkLLM
+
+ chat = ChatSparkLLM(
+ api_key="your-api-key",
+ api_secret="your-api-secret",
+ model='Spark4.0 Ultra',
+ # temperature=...,
+ # other params...
+ )
+
+ Invoke:
+ .. code-block:: python
+
+ messages = [
+ ("system", "你是一名专业的翻译家,可以将用户的中文翻译为英文。"),
+ ("human", "我喜欢编程。"),
+ ]
+ chat.invoke(messages)
+
+ .. code-block:: python
+
+ AIMessage(
+ content='I like programming.',
+ response_metadata={
+ 'token_usage': {
+ 'question_tokens': 3,
+ 'prompt_tokens': 16,
+ 'completion_tokens': 4,
+ 'total_tokens': 20
+ }
+ },
+ id='run-af8b3531-7bf7-47f0-bfe8-9262cb2a9d47-0'
+ )
+
+ Stream:
+ .. code-block:: python
+
+ for chunk in chat.stream(messages):
+ print(chunk)
+
+ .. code-block:: python
+
+ content='I' id='run-fdbb57c2-2d32-4516-b894-6c5a67605d83'
+ content=' like programming' id='run-fdbb57c2-2d32-4516-b894-6c5a67605d83'
+ content='.' id='run-fdbb57c2-2d32-4516-b894-6c5a67605d83'
+
+ .. code-block:: python
+
+ stream = chat.stream(messages)
+ full = next(stream)
+ for chunk in stream:
+ full += chunk
+ full
+
+ .. code-block:: python
+
+ AIMessageChunk(
+ content='I like programming.',
+ id='run-aca2fa82-c2e4-4835-b7e2-865ddd3c46cb'
+ )
+
+ Response metadata
+ .. code-block:: python
+
+ ai_msg = chat.invoke(messages)
+ ai_msg.response_metadata
+
+ .. code-block:: python
+
+ {
+ 'token_usage': {
+ 'question_tokens': 3,
+ 'prompt_tokens': 16,
+ 'completion_tokens': 4,
+ 'total_tokens': 20
+ }
+ }
+
+ """ # noqa: E501
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return whether this model can be serialized by Langchain."""
+ return False
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {
+ "spark_app_id": "IFLYTEK_SPARK_APP_ID",
+ "spark_api_key": "IFLYTEK_SPARK_API_KEY",
+ "spark_api_secret": "IFLYTEK_SPARK_API_SECRET",
+ "spark_api_url": "IFLYTEK_SPARK_API_URL",
+ "spark_llm_domain": "IFLYTEK_SPARK_LLM_DOMAIN",
+ }
+
+ client: Any = None #: :meta private:
+ spark_app_id: Optional[str] = Field(default=None, alias="app_id")
+ """Automatically inferred from env var `IFLYTEK_SPARK_APP_ID`
+ if not provided."""
+ spark_api_key: Optional[str] = Field(default=None, alias="api_key")
+ """Automatically inferred from env var `IFLYTEK_SPARK_API_KEY`
+ if not provided."""
+ spark_api_secret: Optional[str] = Field(default=None, alias="api_secret")
+ """Automatically inferred from env var `IFLYTEK_SPARK_API_SECRET`
+ if not provided."""
+ spark_api_url: Optional[str] = Field(default=None, alias="api_url")
+ """Base URL path for API requests, leave blank if not using a proxy or service
+ emulator."""
+ spark_llm_domain: Optional[str] = Field(default=None, alias="model")
+ """Model name to use."""
+ spark_user_id: str = "lc_user"
+ streaming: bool = False
+ """Whether to stream the results or not."""
+ request_timeout: int = Field(30, alias="timeout")
+ """request timeout for chat http requests"""
+ temperature: float = Field(default=0.5)
+ """What sampling temperature to use."""
+ top_k: int = 4
+ """What search sampling control to use."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for API call not explicitly specified."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ values["spark_app_id"] = get_from_dict_or_env(
+ values,
+ ["spark_app_id", "app_id"],
+ "IFLYTEK_SPARK_APP_ID",
+ )
+ values["spark_api_key"] = get_from_dict_or_env(
+ values,
+ ["spark_api_key", "api_key"],
+ "IFLYTEK_SPARK_API_KEY",
+ )
+ values["spark_api_secret"] = get_from_dict_or_env(
+ values,
+ ["spark_api_secret", "api_secret"],
+ "IFLYTEK_SPARK_API_SECRET",
+ )
+ values["spark_api_url"] = get_from_dict_or_env(
+ values,
+ "spark_api_url",
+ "IFLYTEK_SPARK_API_URL",
+ SPARK_API_URL,
+ )
+ values["spark_llm_domain"] = get_from_dict_or_env(
+ values,
+ "spark_llm_domain",
+ "IFLYTEK_SPARK_LLM_DOMAIN",
+ SPARK_LLM_DOMAIN,
+ )
+
+ # put extra params into model_kwargs
+ default_values = {
+ name: field.default
+ for name, field in get_fields(cls).items()
+ if field.default is not None
+ }
+ values["model_kwargs"]["temperature"] = default_values.get("temperature")
+ values["model_kwargs"]["top_k"] = default_values.get("top_k")
+
+ values["client"] = _SparkLLMClient(
+ app_id=values["spark_app_id"],
+ api_key=values["spark_api_key"],
+ api_secret=values["spark_api_secret"],
+ api_url=values["spark_api_url"],
+ spark_domain=values["spark_llm_domain"],
+ model_kwargs=values["model_kwargs"],
+ )
+ return values
+
+ # When using Pydantic V2
+ # The execution order of multiple @model_validator decorators is opposite to
+ # their declaration order. https://github.com/pydantic/pydantic/discussions/7434
+
+ @model_validator(mode="before")
+ @classmethod
+ def build_extra(cls, values: Dict[str, Any]) -> Any:
+ """Build extra kwargs from additional params that were passed in."""
+ all_required_field_names = get_pydantic_field_names(cls)
+ extra = values.get("model_kwargs", {})
+ for field_name in list(values):
+ if field_name in extra:
+ raise ValueError(f"Found {field_name} supplied twice.")
+ if field_name not in all_required_field_names:
+ logger.warning(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please confirm that {field_name} is what you intended."""
+ )
+ extra[field_name] = values.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
+ if invalid_model_kwargs:
+ raise ValueError(
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+
+ values["model_kwargs"] = extra
+
+ return values
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ default_chunk_class = AIMessageChunk
+
+ self.client.arun(
+ [convert_message_to_dict(m) for m in messages],
+ self.spark_user_id,
+ self.model_kwargs,
+ streaming=True,
+ )
+ for content in self.client.subscribe(timeout=self.request_timeout):
+ if "data" not in content:
+ continue
+ delta = content["data"]
+ chunk = _convert_delta_to_message_chunk(delta, default_chunk_class)
+ cg_chunk = ChatGenerationChunk(message=chunk)
+ if run_manager:
+ run_manager.on_llm_new_token(str(chunk.content), chunk=cg_chunk)
+ yield cg_chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if stream or self.streaming:
+ stream_iter = self._stream(
+ messages=messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ self.client.arun(
+ [convert_message_to_dict(m) for m in messages],
+ self.spark_user_id,
+ self.model_kwargs,
+ False,
+ )
+ completion = {}
+ llm_output = {}
+ for content in self.client.subscribe(timeout=self.request_timeout):
+ if "usage" in content:
+ llm_output["token_usage"] = content["usage"]
+ if "data" not in content:
+ continue
+ completion = content["data"]
+ message = convert_dict_to_message(completion)
+ generations = [ChatGeneration(message=message)]
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ @property
+ def _llm_type(self) -> str:
+ return "spark-llm-chat"
+
+
+class _SparkLLMClient:
+ """
+ Use websocket-client to call the SparkLLM interface provided by Xfyun,
+ which is the iFlyTek's open platform for AI capabilities
+ """
+
+ def __init__(
+ self,
+ app_id: str,
+ api_key: str,
+ api_secret: str,
+ api_url: Optional[str] = None,
+ spark_domain: Optional[str] = None,
+ model_kwargs: Optional[dict] = None,
+ ):
+ try:
+ import websocket
+
+ self.websocket_client = websocket
+ except ImportError:
+ raise ImportError(
+ "Could not import websocket client python package. "
+ "Please install it with `pip install websocket-client`."
+ )
+
+ self.api_url = SPARK_API_URL if not api_url else api_url
+ self.app_id = app_id
+ self.model_kwargs = model_kwargs
+ self.spark_domain = spark_domain or SPARK_LLM_DOMAIN
+ self.queue: Queue[Dict] = Queue()
+ self.blocking_message = {"content": "", "role": "assistant"}
+ self.api_key = api_key
+ self.api_secret = api_secret
+
+ @staticmethod
+ def _create_url(api_url: str, api_key: str, api_secret: str) -> str:
+ """
+ Generate a request url with an api key and an api secret.
+ """
+ # generate timestamp by RFC1123
+ date = format_date_time(mktime(datetime.now().timetuple()))
+
+ # urlparse
+ parsed_url = urlparse(api_url)
+ host = parsed_url.netloc
+ path = parsed_url.path
+
+ signature_origin = f"host: {host}\ndate: {date}\nGET {path} HTTP/1.1"
+
+ # encrypt using hmac-sha256
+ signature_sha = hmac.new(
+ api_secret.encode("utf-8"),
+ signature_origin.encode("utf-8"),
+ digestmod=hashlib.sha256,
+ ).digest()
+
+ signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding="utf-8")
+
+ authorization_origin = f'api_key="{api_key}", algorithm="hmac-sha256", \
+ headers="host date request-line", signature="{signature_sha_base64}"'
+ authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode(
+ encoding="utf-8"
+ )
+
+ # generate url
+ params_dict = {"authorization": authorization, "date": date, "host": host}
+ encoded_params = urlencode(params_dict)
+ url = urlunparse(
+ (
+ parsed_url.scheme,
+ parsed_url.netloc,
+ parsed_url.path,
+ parsed_url.params,
+ encoded_params,
+ parsed_url.fragment,
+ )
+ )
+ return url
+
+ def run(
+ self,
+ messages: List[Dict],
+ user_id: str,
+ model_kwargs: Optional[dict] = None,
+ streaming: bool = False,
+ ) -> None:
+ self.websocket_client.enableTrace(False)
+ ws = self.websocket_client.WebSocketApp(
+ _SparkLLMClient._create_url(
+ self.api_url,
+ self.api_key,
+ self.api_secret,
+ ),
+ on_message=self.on_message,
+ on_error=self.on_error,
+ on_close=self.on_close,
+ on_open=self.on_open,
+ )
+ ws.messages = messages # type: ignore[attr-defined]
+ ws.user_id = user_id # type: ignore[attr-defined]
+ ws.model_kwargs = self.model_kwargs if model_kwargs is None else model_kwargs # type: ignore[attr-defined]
+ ws.streaming = streaming # type: ignore[attr-defined]
+ ws.run_forever()
+
+ def arun(
+ self,
+ messages: List[Dict],
+ user_id: str,
+ model_kwargs: Optional[dict] = None,
+ streaming: bool = False,
+ ) -> threading.Thread:
+ ws_thread = threading.Thread(
+ target=self.run,
+ args=(
+ messages,
+ user_id,
+ model_kwargs,
+ streaming,
+ ),
+ )
+ ws_thread.start()
+ return ws_thread
+
+ def on_error(self, ws: Any, error: Optional[Any]) -> None:
+ self.queue.put({"error": error})
+ ws.close()
+
+ def on_close(self, ws: Any, close_status_code: int, close_reason: str) -> None:
+ logger.debug(
+ {
+ "log": {
+ "close_status_code": close_status_code,
+ "close_reason": close_reason,
+ }
+ }
+ )
+ self.queue.put({"done": True})
+
+ def on_open(self, ws: Any) -> None:
+ self.blocking_message = {"content": "", "role": "assistant"}
+ data = json.dumps(
+ self.gen_params(
+ messages=ws.messages, user_id=ws.user_id, model_kwargs=ws.model_kwargs
+ )
+ )
+ ws.send(data)
+
+ def on_message(self, ws: Any, message: str) -> None:
+ data = json.loads(message)
+ code = data["header"]["code"]
+ if code != 0:
+ self.queue.put(
+ {"error": f"Code: {code}, Error: {data['header']['message']}"}
+ )
+ ws.close()
+ else:
+ choices = data["payload"]["choices"]
+ status = choices["status"]
+ content = choices["text"][0]["content"]
+ if ws.streaming:
+ self.queue.put({"data": choices["text"][0]})
+ else:
+ self.blocking_message["content"] += content
+ if status == 2:
+ if not ws.streaming:
+ self.queue.put({"data": self.blocking_message})
+ usage_data = (
+ data.get("payload", {}).get("usage", {}).get("text", {})
+ if data
+ else {}
+ )
+ self.queue.put({"usage": usage_data})
+ ws.close()
+
+ def gen_params(
+ self, messages: list, user_id: str, model_kwargs: Optional[dict] = None
+ ) -> dict:
+ data: Dict = {
+ "header": {"app_id": self.app_id, "uid": user_id},
+ "parameter": {"chat": {"domain": self.spark_domain}},
+ "payload": {"message": {"text": messages}},
+ }
+
+ if model_kwargs:
+ data["parameter"]["chat"].update(model_kwargs)
+ logger.debug(f"Spark Request Parameters: {data}")
+ return data
+
+ def subscribe(self, timeout: Optional[int] = 30) -> Generator[Dict, None, None]:
+ while True:
+ try:
+ content = self.queue.get(timeout=timeout)
+ except queue.Empty as _:
+ raise TimeoutError(
+ f"SparkLLMClient wait LLM api response timeout {timeout} seconds"
+ )
+ if "error" in content:
+ raise ConnectionError(content["error"])
+ if "usage" in content:
+ yield content
+ continue
+ if "done" in content:
+ break
+ if "data" not in content:
+ break
+ yield content
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/symblai_nebula.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/symblai_nebula.py
new file mode 100644
index 0000000000000000000000000000000000000000..9eb9d5f08d828beef14f0214712761222e15f9de
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/symblai_nebula.py
@@ -0,0 +1,270 @@
+import json
+import os
+from json import JSONDecodeError
+from typing import Any, AsyncIterator, Dict, Iterator, List, Optional
+
+import requests
+from aiohttp import ClientSession
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import AIMessage, AIMessageChunk, BaseMessage
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.utils import convert_to_secret_str
+from pydantic import ConfigDict, Field, SecretStr
+
+
+def _convert_role(role: str) -> str:
+ map = {"ai": "assistant", "human": "human", "chat": "human"}
+ if role in map:
+ return map[role]
+ else:
+ raise ValueError(f"Unknown role type: {role}")
+
+
+def _format_nebula_messages(messages: List[BaseMessage]) -> Dict[str, Any]:
+ system = ""
+ formatted_messages = []
+ for message in messages[:-1]:
+ if message.type == "system":
+ if isinstance(message.content, str):
+ system = message.content
+ else:
+ raise ValueError("System prompt must be a string")
+ else:
+ formatted_messages.append(
+ {
+ "role": _convert_role(message.type),
+ "text": message.content,
+ }
+ )
+
+ text = messages[-1].content
+ formatted_messages.append({"role": "human", "text": text})
+ return {"system_prompt": system, "messages": formatted_messages}
+
+
+class ChatNebula(BaseChatModel):
+ """`Nebula` chat large language model - https://docs.symbl.ai/docs/nebula-llm
+
+ API Reference: https://docs.symbl.ai/reference/nebula-chat
+
+ To use, set the environment variable ``NEBULA_API_KEY``,
+ or pass it as a named parameter to the constructor.
+ To request an API key, visit https://platform.symbl.ai/#/login
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatNebula
+ from langchain_core.messages import SystemMessage, HumanMessage
+
+ chat = ChatNebula(max_new_tokens=1024, temperature=0.5)
+
+ messages = [
+ SystemMessage(
+ content="You are a helpful assistant."
+ ),
+ HumanMessage(
+ "Answer the following question. How can I help save the world."
+ ),
+ ]
+ chat.invoke(messages)
+ """
+
+ max_new_tokens: int = 1024
+ """Denotes the number of tokens to predict per generation."""
+
+ temperature: Optional[float] = 0
+ """A non-negative float that tunes the degree of randomness in generation."""
+
+ streaming: bool = False
+
+ nebula_api_url: str = "https://api-nebula.symbl.ai"
+
+ nebula_api_key: Optional[SecretStr] = Field(None, description="Nebula API Token")
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ arbitrary_types_allowed=True,
+ )
+
+ def __init__(self, **kwargs: Any) -> None:
+ if "nebula_api_key" in kwargs:
+ api_key = convert_to_secret_str(kwargs.pop("nebula_api_key"))
+ elif "NEBULA_API_KEY" in os.environ:
+ api_key = convert_to_secret_str(os.environ["NEBULA_API_KEY"])
+ else:
+ api_key = None
+ super().__init__(nebula_api_key=api_key, **kwargs) # type: ignore[call-arg]
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "nebula-chat"
+
+ @property
+ def _api_key(self) -> str:
+ if self.nebula_api_key:
+ return self.nebula_api_key.get_secret_value()
+ return ""
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ """Call out to Nebula's chat endpoint."""
+ url = f"{self.nebula_api_url}/v1/model/chat/streaming"
+ headers = {
+ "ApiKey": self._api_key,
+ "Content-Type": "application/json",
+ }
+ formatted_data = _format_nebula_messages(messages=messages)
+ payload: Dict[str, Any] = {
+ "max_new_tokens": self.max_new_tokens,
+ "temperature": self.temperature,
+ **formatted_data,
+ **kwargs,
+ }
+
+ payload = {k: v for k, v in payload.items() if v is not None}
+ json_payload = json.dumps(payload)
+
+ response = requests.request(
+ "POST", url, headers=headers, data=json_payload, stream=True
+ )
+ response.raise_for_status()
+
+ for chunk_response in response.iter_lines():
+ chunk_decoded = chunk_response.decode()[6:]
+ try:
+ chunk = json.loads(chunk_decoded)
+ except JSONDecodeError:
+ continue
+ token = chunk["delta"]
+ cg_chunk = ChatGenerationChunk(message=AIMessageChunk(content=token))
+ if run_manager:
+ run_manager.on_llm_new_token(token, chunk=cg_chunk)
+ yield cg_chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ url = f"{self.nebula_api_url}/v1/model/chat/streaming"
+ headers = {"ApiKey": self._api_key, "Content-Type": "application/json"}
+ formatted_data = _format_nebula_messages(messages=messages)
+ payload: Dict[str, Any] = {
+ "max_new_tokens": self.max_new_tokens,
+ "temperature": self.temperature,
+ **formatted_data,
+ **kwargs,
+ }
+
+ payload = {k: v for k, v in payload.items() if v is not None}
+ json_payload = json.dumps(payload)
+
+ async with ClientSession() as session:
+ async with session.post( # type: ignore[call-arg,unused-ignore]
+ url, data=json_payload, headers=headers, stream=True
+ ) as response:
+ response.raise_for_status()
+ async for chunk_response in response.content:
+ chunk_decoded = chunk_response.decode()[6:]
+ try:
+ chunk = json.loads(chunk_decoded)
+ except JSONDecodeError:
+ continue
+ token = chunk["delta"]
+ cg_chunk = ChatGenerationChunk(
+ message=AIMessageChunk(content=token)
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(token, chunk=cg_chunk)
+ yield cg_chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ url = f"{self.nebula_api_url}/v1/model/chat"
+ headers = {"ApiKey": self._api_key, "Content-Type": "application/json"}
+ formatted_data = _format_nebula_messages(messages=messages)
+ payload: Dict[str, Any] = {
+ "max_new_tokens": self.max_new_tokens,
+ "temperature": self.temperature,
+ **formatted_data,
+ **kwargs,
+ }
+
+ payload = {k: v for k, v in payload.items() if v is not None}
+ json_payload = json.dumps(payload)
+
+ response = requests.request("POST", url, headers=headers, data=json_payload)
+ response.raise_for_status()
+ data = response.json()
+
+ return ChatResult(
+ generations=[ChatGeneration(message=AIMessage(content=data["messages"]))],
+ llm_output=data,
+ )
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ url = f"{self.nebula_api_url}/v1/model/chat"
+ headers = {"ApiKey": self._api_key, "Content-Type": "application/json"}
+ formatted_data = _format_nebula_messages(messages=messages)
+ payload: Dict[str, Any] = {
+ "max_new_tokens": self.max_new_tokens,
+ "temperature": self.temperature,
+ **formatted_data,
+ **kwargs,
+ }
+
+ payload = {k: v for k, v in payload.items() if v is not None}
+ json_payload = json.dumps(payload)
+
+ async with ClientSession() as session:
+ async with session.post(
+ url, data=json_payload, headers=headers
+ ) as response:
+ response.raise_for_status()
+ data = await response.json()
+
+ return ChatResult(
+ generations=[
+ ChatGeneration(message=AIMessage(content=data["messages"]))
+ ],
+ llm_output=data,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/tongyi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/tongyi.py
new file mode 100644
index 0000000000000000000000000000000000000000..402c5d03c6bdf6b0aadb0b2b0e2cc4e9ad9be82e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/tongyi.py
@@ -0,0 +1,917 @@
+from __future__ import annotations
+
+import asyncio
+import functools
+import json
+import logging
+from operator import itemgetter
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+ cast,
+)
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessage,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+ ToolMessage,
+ ToolMessageChunk,
+)
+from langchain_core.output_parsers.base import OutputParserLike
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ PydanticToolsParser,
+ make_invalid_tool_call,
+ parse_tool_call,
+)
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ ChatResult,
+)
+from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
+from langchain_core.tools import BaseTool
+from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env, pre_init
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from langchain_core.utils.pydantic import is_basemodel_subclass
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SecretStr,
+)
+from requests.exceptions import HTTPError
+from tenacity import (
+ before_sleep_log,
+ retry,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential,
+)
+
+from langchain_community.llms.tongyi import (
+ agenerate_with_last_element_mark,
+ check_response,
+ generate_with_last_element_mark,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def convert_dict_to_message(
+ _dict: Mapping[str, Any], is_chunk: bool = False
+) -> Union[BaseMessage, BaseMessageChunk]:
+ """Convert a dict to a message."""
+ role = _dict["role"]
+ content = _dict["content"]
+ if role == "user":
+ return (
+ HumanMessageChunk(content=content)
+ if is_chunk
+ else HumanMessage(content=content)
+ )
+ elif role == "assistant":
+ tool_calls = []
+ invalid_tool_calls = []
+ if "tool_calls" in _dict:
+ additional_kwargs = {"tool_calls": _dict["tool_calls"]}
+
+ for index, value in enumerate(_dict["tool_calls"]):
+ if is_chunk:
+ try:
+ tool_calls.append(
+ {
+ "name": value["function"].get("name"),
+ "args": value["function"].get("arguments"),
+ "id": value.get("id"),
+ # Tongyi does not respond with index,
+ # use index in the list instead
+ "index": index,
+ }
+ )
+ except KeyError:
+ pass
+ else:
+ try:
+ parsed_tool = parse_tool_call(value, return_id=True)
+ if parsed_tool:
+ tool_calls.append(parsed_tool)
+ except Exception as e:
+ invalid_tool_calls.append(make_invalid_tool_call(value, str(e)))
+ elif "reasoning_content" in _dict:
+ additional_kwargs = {"reasoning_content": _dict["reasoning_content"]}
+ elif "partial" in _dict and isinstance(_dict["partial"], bool):
+ additional_kwargs = {"partial": _dict["partial"]}
+ else:
+ additional_kwargs = {}
+
+ return (
+ AIMessageChunk(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_call_chunks=tool_calls, # type: ignore[arg-type]
+ id=_dict.get("id"),
+ )
+ if is_chunk
+ else AIMessage(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_calls=tool_calls,
+ invalid_tool_calls=invalid_tool_calls,
+ )
+ )
+ elif role == "system":
+ return (
+ SystemMessageChunk(content=content)
+ if is_chunk
+ else SystemMessage(content=content)
+ )
+ elif role == "tool":
+ additional_kwargs = {}
+ if "name" in _dict:
+ additional_kwargs["name"] = _dict["name"]
+ return (
+ ToolMessageChunk(
+ content=_dict.get("content", ""),
+ tool_call_id=_dict.get("tool_call_id"), # type: ignore[arg-type]
+ additional_kwargs=additional_kwargs,
+ )
+ if is_chunk
+ else ToolMessage(
+ content=_dict.get("content", ""),
+ tool_call_id=_dict.get("tool_call_id"),
+ additional_kwargs=additional_kwargs,
+ )
+ )
+ else:
+ return (
+ ChatMessageChunk(role=role, content=content)
+ if is_chunk
+ else ChatMessage(role=role, content=content)
+ )
+
+
+def convert_message_chunk_to_message(message_chunk: BaseMessageChunk) -> BaseMessage:
+ """Convert a message chunk to a message.
+
+ Args:
+ chunk: Message chunk to convert.
+
+ Returns:
+ Message.
+ """
+ if not isinstance(message_chunk, BaseMessageChunk):
+ return message_chunk
+ # chunk classes always have the equivalent non-chunk class as their first parent
+ ignore_keys = ["type"]
+ if isinstance(message_chunk, AIMessageChunk):
+ ignore_keys.append("tool_call_chunks")
+ return message_chunk.__class__.__mro__[1](
+ **{k: v for k, v in message_chunk.__dict__.items() if k not in ignore_keys}
+ )
+
+
+def convert_message_to_dict(message: BaseMessage) -> dict:
+ """Convert a message to a dict."""
+
+ message_dict: Dict[str, Any]
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ if "tool_calls" in message.additional_kwargs:
+ message_dict["tool_calls"] = message.additional_kwargs["tool_calls"]
+ # support Partial Mode for text continuation
+ if "partial" in message.additional_kwargs:
+ message_dict["partial"] = message.additional_kwargs["partial"]
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, ToolMessage):
+ message_dict = {
+ "role": "tool",
+ "tool_call_id": message.tool_call_id,
+ "content": message.content,
+ "name": message.name or message.additional_kwargs.get("name"),
+ }
+ elif isinstance(message, FunctionMessage):
+ message_dict = {
+ "role": "tool",
+ "tool_call_id": "",
+ "content": message.content,
+ "name": message.name,
+ }
+ else:
+ raise TypeError(f"Got unknown type {message}")
+ return message_dict
+
+
+def _create_retry_decorator(llm: ChatTongyi) -> Callable[[Any], Any]:
+ min_seconds = 1
+ max_seconds = 4
+ # Wait 2^x * 1 second between each retry starting with
+ # 4 seconds, then up to 10 seconds, then 10 seconds afterward
+ return retry(
+ reraise=True,
+ stop=stop_after_attempt(llm.max_retries),
+ wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
+ retry=(retry_if_exception_type(HTTPError)),
+ before_sleep=before_sleep_log(logger, logging.WARNING),
+ )
+
+
+class ChatTongyi(BaseChatModel):
+ """Alibaba Tongyi Qwen chat model integration.
+
+ Setup:
+ Install ``dashscope`` and set environment variables ``DASHSCOPE_API_KEY``.
+
+ .. code-block:: bash
+
+ pip install dashscope
+ export DASHSCOPE_API_KEY="your-api-key"
+
+ Key init args — completion params:
+ model: str
+ Name of Qianfan model to use.
+ top_p: float
+ Total probability mass of tokens to consider at each step.
+ streaming: bool
+ Whether to stream the results or not.
+
+ Key init args — client params:
+ api_key: Optional[str]
+ Dashscope API KEY. If not passed in will be read from env var DASHSCOPE_API_KEY.
+ max_retries: int
+ Maximum number of retries to make when generating.
+
+ See full list of supported init args and their descriptions in the params section.
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatTongyi
+
+ tongyi_chat = ChatTongyi(
+ model="qwen-max",
+ # top_p="...",
+ # api_key="...",
+ # other params...
+ )
+
+ Invoke:
+ .. code-block:: python
+
+ messages = [
+ ("system", "你是一名专业的翻译家,可以将用户的中文翻译为英文。"),
+ ("human", "我喜欢编程。"),
+ ]
+ tongyi_chat.invoke(messages)
+
+ .. code-block:: python
+
+ AIMessage(
+ content='I enjoy programming.',
+ response_metadata={
+ 'model_name': 'qwen-max',
+ 'finish_reason': 'stop',
+ 'request_id': '0bd14853-4abc-9593-8642-8dbb915bd4df',
+ 'token_usage': {
+ 'input_tokens': 30,
+ 'output_tokens': 4,
+ 'total_tokens': 34
+ }
+ },
+ id='run-533b3688-d12b-40c6-a2f7-52f291f8fa0a-0'
+ )
+
+ Stream:
+ .. code-block:: python
+
+ for chunk in tongyi_chat.stream(messages):
+ print(chunk)
+
+ .. code-block:: python
+
+ content='I' id='run-8fbcce63-42fc-4208-9399-da46ac40c967'
+ content=' enjoy' id='run-8fbcce63-42fc-4208-9399-da46ac40c967'
+ content=' programming' id='run-8fbcce63-42fc-4208-9399-da46ac40c967'
+ content='.' response_metadata={'finish_reason': 'stop', 'request_id': '67aec2b5-72bf-96a4-ae29-5bfebd2e7305', 'token_usage': {'input_tokens': 30, 'output_tokens': 4, 'total_tokens': 34}} id='run-8fbcce63-42fc-4208-9399-da46ac40c967'
+
+ Async:
+ .. code-block:: python
+
+ await tongyi_chat.ainvoke(messages)
+
+ # stream:
+ # async for chunk in tongyi_chat.astream(messages):
+ # print(chunk)
+
+ # batch:
+ # await tongyi_chat.abatch([messages])
+
+ .. code-block:: python
+
+ AIMessage(
+ content='I enjoy programming.',
+ response_metadata={
+ 'model_name': 'qwen-max',
+ 'finish_reason': 'stop',
+ 'request_id': 'a55a2d6c-a876-9789-9dd9-7b52bf8adde0',
+ 'token_usage': {
+ 'input_tokens': 30,
+ 'output_tokens': 4,
+ 'total_tokens': 34
+ }
+ },
+ id='run-3bffa3ec-e8d9-4043-b57d-348e047d64de-0'
+ )
+
+ Tool calling:
+ .. code-block:: python
+
+ 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"
+ )
+
+
+ class GetPopulation(BaseModel):
+ '''Get the current population in a given location'''
+
+ location: str = Field(
+ ..., description="The city and state, e.g. San Francisco, CA"
+ )
+
+ chat_with_tools = tongyi_chat.bind_tools([GetWeather, GetPopulation])
+ ai_msg = chat_with_tools.invoke(
+ "Which city is hotter today and which is bigger: LA or NY?"
+ )
+ ai_msg.tool_calls
+
+ .. code-block:: python
+ [
+ {
+ 'name': 'GetWeather',
+ 'args': {'location': 'Los Angeles, CA'},
+ 'id': ''
+ }
+ ]
+
+ Structured output:
+ .. code-block:: python
+
+ from typing import Optional
+
+ from pydantic import BaseModel, Field
+
+
+ class Joke(BaseModel):
+ '''Joke to tell user.'''
+
+ setup: str = Field(description="The setup of the joke")
+ punchline: str = Field(description="The punchline to the joke")
+ rating: Optional[int] = Field(description="How funny the joke is, from 1 to 10")
+
+
+ structured_chat = tongyi_chat.with_structured_output(Joke)
+ structured_chat.invoke("Tell me a joke about cats")
+
+ .. code-block:: python
+
+ Joke(
+ setup='Why did the cat join the band?',
+ punchline='Because it wanted to be a solo purr-sonality!',
+ rating=None
+ )
+
+ Response metadata
+ .. code-block:: python
+
+ ai_msg = tongyi_chat.invoke(messages)
+ ai_msg.response_metadata
+
+ .. code-block:: python
+
+ {
+ 'model_name': 'qwen-max',
+ 'finish_reason': 'stop',
+ 'request_id': '32a13e4c-370e-99cb-8f9b-4c999d98c57d',
+ 'token_usage': {
+ 'input_tokens': 30,
+ 'output_tokens': 4,
+ 'total_tokens': 34
+ }
+ }
+
+ """ # noqa: E501
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"dashscope_api_key": "DASHSCOPE_API_KEY"}
+
+ client: Any = None #: :meta private:
+ model_name: str = Field(default="qwen-turbo", alias="model")
+ """Model name to use.
+ callable multimodal model:
+ - qwen-vl-v1
+ - qwen-vl-chat-v1
+ - qwen-audio-turbo
+ - qwen-vl-plus
+ - qwen-vl-max
+ """
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+
+ top_p: float = 0.8
+ """Total probability mass of tokens to consider at each step."""
+
+ dashscope_api_key: Optional[SecretStr] = Field(None, alias="api_key")
+ """Dashscope api key provide by Alibaba Cloud."""
+
+ streaming: bool = False
+ """Whether to stream the results or not."""
+
+ max_retries: int = 10
+ """Maximum number of retries to make when generating."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "tongyi"
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that api key and python package exists in environment."""
+ values["dashscope_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(values, "dashscope_api_key", "DASHSCOPE_API_KEY")
+ )
+ try:
+ import dashscope
+ except ImportError:
+ raise ImportError(
+ "Could not import dashscope python package. "
+ "Please install it with `pip install dashscope --upgrade`."
+ )
+ dashscope_multimodal_models = [
+ "qwen-audio-turbo",
+ "qwen-audio-turbo-latest",
+ "qwen-vl-plus",
+ "qwen-vl-plus-latest",
+ "qwen-vl-max",
+ "qwen-vl-max-latest",
+ ]
+ if (
+ values["model_name"] in dashscope_multimodal_models
+ or "vl" in values["model_name"]
+ ):
+ try:
+ values["client"] = dashscope.MultiModalConversation
+ except AttributeError:
+ raise ValueError(
+ "`dashscope` has no `MultiModalConversation` attribute, this is "
+ "likely due to an old version of the dashscope package. Try "
+ "upgrading it with `pip install --upgrade dashscope`."
+ )
+ else:
+ try:
+ values["client"] = dashscope.Generation
+ except AttributeError:
+ raise ValueError(
+ "`dashscope` has no `Generation` attribute, this is likely "
+ "due to an old version of the dashscope package. Try upgrading it "
+ "with `pip install --upgrade dashscope`."
+ )
+ return values
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling Tongyi Qwen API."""
+ return {
+ "model": self.model_name,
+ "top_p": self.top_p,
+ "api_key": cast(SecretStr, self.dashscope_api_key).get_secret_value(),
+ "result_format": "message",
+ **self.model_kwargs,
+ }
+
+ def completion_with_retry(self, **kwargs: Any) -> Any:
+ """Use tenacity to retry the completion call."""
+ retry_decorator = _create_retry_decorator(self)
+
+ @retry_decorator
+ def _completion_with_retry(**_kwargs: Any) -> Any:
+ resp = self.client.call(**_kwargs)
+ return check_response(resp)
+
+ return _completion_with_retry(**kwargs)
+
+ def stream_completion_with_retry(self, **kwargs: Any) -> Any:
+ """Use tenacity to retry the completion call."""
+ retry_decorator = _create_retry_decorator(self)
+
+ @retry_decorator
+ def _stream_completion_with_retry(**_kwargs: Any) -> Any:
+ responses = self.client.call(**_kwargs)
+ prev_resp = None
+
+ for resp in responses:
+ # If we are streaming without `incremental_output = True`,
+ # we need to calculate the delta response manually
+ if _kwargs.get("stream") and not _kwargs.get(
+ "incremental_output", False
+ ):
+ # inline fix response text logic
+ resp_copy = json.loads(json.dumps(resp))
+ if resp_copy.get("output") and resp_copy["output"].get("choices"):
+ choice = resp_copy["output"]["choices"][0]
+ message = choice["message"]
+ if isinstance(message.get("content"), list):
+ content_text = "".join(
+ item.get("text", "")
+ for item in message["content"]
+ if isinstance(item, dict)
+ )
+ message["content"] = content_text
+ resp = resp_copy
+ if prev_resp is None:
+ delta_resp = resp
+ else:
+ delta_resp = self.subtract_client_response(resp, prev_resp)
+ prev_resp = resp
+ yield check_response(delta_resp)
+ else:
+ yield check_response(resp)
+
+ return _stream_completion_with_retry(**kwargs)
+
+ def subtract_client_response(self, resp: Any, prev_resp: Any) -> Any:
+ """Subtract prev response from curr response.
+
+ Useful when streaming without `incremental_output = True`
+ """
+
+ resp_copy = json.loads(json.dumps(resp))
+ choice = resp_copy["output"]["choices"][0]
+ message = choice["message"]
+
+ prev_resp_copy = json.loads(json.dumps(prev_resp))
+ prev_choice = prev_resp_copy["output"]["choices"][0]
+ prev_message = prev_choice["message"]
+
+ message["content"] = message["content"].replace(prev_message["content"], "")
+
+ if message.get("tool_calls"):
+ for index, tool_call in enumerate(message["tool_calls"]):
+ function = tool_call["function"]
+
+ if prev_message.get("tool_calls"):
+ prev_function = prev_message["tool_calls"][index]["function"]
+
+ if "name" in function:
+ function["name"] = function["name"].replace(
+ prev_function["name"], ""
+ )
+ if "arguments" in function:
+ function["arguments"] = function["arguments"].replace(
+ prev_function["arguments"], ""
+ )
+
+ return resp_copy
+
+ async def astream_completion_with_retry(self, **kwargs: Any) -> Any:
+ """Because the dashscope SDK doesn't provide an async API,
+ we wrap `stream_generate_with_retry` with an async generator."""
+
+ class _AioTongyiGenerator:
+ def __init__(self, generator: Any):
+ self.generator = generator
+
+ def __aiter__(self) -> AsyncIterator[Any]:
+ return self
+
+ async def __anext__(self) -> Any:
+ value = await asyncio.get_running_loop().run_in_executor(
+ None, self._safe_next
+ )
+ if value is not None:
+ return value
+ else:
+ raise StopAsyncIteration
+
+ def _safe_next(self) -> Any:
+ try:
+ return next(self.generator)
+ except StopIteration:
+ return None
+
+ async for chunk in _AioTongyiGenerator(
+ generator=self.stream_completion_with_retry(**kwargs)
+ ):
+ yield chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ generations = []
+ if self.streaming:
+ generation_chunk: Optional[ChatGenerationChunk] = None
+ for chunk in self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ ):
+ if generation_chunk is None:
+ generation_chunk = chunk
+ else:
+ generation_chunk += chunk
+ assert generation_chunk is not None
+ generations.append(self._chunk_to_generation(generation_chunk))
+ else:
+ params: Dict[str, Any] = self._invocation_params(
+ messages=messages, stop=stop, **kwargs
+ )
+ resp = self.completion_with_retry(**params)
+ generations.append(
+ ChatGeneration(**self._chat_generation_from_qwen_resp(resp))
+ )
+ return ChatResult(
+ generations=generations,
+ llm_output={
+ "model_name": self.model_name,
+ },
+ )
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ generations = []
+ if self.streaming:
+ generation: Optional[ChatGenerationChunk] = None
+ async for chunk in self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ ):
+ if generation is None:
+ generation = chunk
+ else:
+ generation += chunk
+ assert generation is not None
+ generations.append(self._chunk_to_generation(generation))
+ else:
+ params: Dict[str, Any] = self._invocation_params(
+ messages=messages, stop=stop, **kwargs
+ )
+ resp = await asyncio.get_running_loop().run_in_executor(
+ None,
+ functools.partial(self.completion_with_retry, **params),
+ )
+ generations.append(
+ ChatGeneration(**self._chat_generation_from_qwen_resp(resp))
+ )
+ return ChatResult(
+ generations=generations,
+ llm_output={
+ "model_name": self.model_name,
+ },
+ )
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ params: Dict[str, Any] = self._invocation_params(
+ messages=messages, stop=stop, stream=True, **kwargs
+ )
+
+ for stream_resp, is_last_chunk in generate_with_last_element_mark(
+ self.stream_completion_with_retry(**params)
+ ):
+ choice = stream_resp["output"]["choices"][0]
+ message = choice["message"]
+ if (
+ choice["finish_reason"] == "null"
+ and message["content"] == ""
+ and message.get("reasoning_content", "") == ""
+ and "tool_calls" not in message
+ ):
+ continue
+
+ chunk = ChatGenerationChunk(
+ **self._chat_generation_from_qwen_resp(
+ stream_resp, is_chunk=True, is_last_chunk=is_last_chunk
+ )
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ params: Dict[str, Any] = self._invocation_params(
+ messages=messages, stop=stop, stream=True, **kwargs
+ )
+ async for stream_resp, is_last_chunk in agenerate_with_last_element_mark(
+ self.astream_completion_with_retry(**params)
+ ):
+ chunk = ChatGenerationChunk(
+ **self._chat_generation_from_qwen_resp(
+ stream_resp, is_chunk=True, is_last_chunk=is_last_chunk
+ )
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+
+ def _invocation_params(
+ self, messages: List[BaseMessage], stop: Any, **kwargs: Any
+ ) -> Dict[str, Any]:
+ params = {**self._default_params, **kwargs}
+ if stop is not None:
+ params["stop"] = stop
+ # According to the Tongyi official docs,
+ # `incremental_output` with `tools` is not supported yet
+ if params.get("stream") and not params.get("tools"):
+ params["incremental_output"] = True
+
+ message_dicts = [convert_message_to_dict(m) for m in messages]
+
+ # And the `system` message should be the first message if present
+ system_message_indices = [
+ i for i, m in enumerate(message_dicts) if m["role"] == "system"
+ ]
+ if len(system_message_indices) == 1 and system_message_indices[0] != 0:
+ raise ValueError("System message can only be the first message.")
+
+ params["messages"] = message_dicts
+
+ return params
+
+ def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:
+ if llm_outputs[0] is None:
+ return {}
+ return llm_outputs[0]
+
+ @staticmethod
+ def _chat_generation_from_qwen_resp(
+ resp: Any, is_chunk: bool = False, is_last_chunk: bool = True
+ ) -> Dict[str, Any]:
+ # According to the response from dashscope,
+ # each chunk's `generation_info` overwrites the previous one.
+ # Besides, The `merge_dicts` method,
+ # which is used to concatenate `generation_info` in `GenerationChunk`,
+ # does not support merging of int type values.
+ # Therefore, we adopt the `generation_info` of the last chunk
+ # and discard the `generation_info` of the intermediate chunks.
+ choice = resp["output"]["choices"][0]
+ message = convert_dict_to_message(choice["message"], is_chunk=is_chunk)
+ if is_last_chunk:
+ return dict(
+ message=message,
+ generation_info=dict(
+ finish_reason=choice["finish_reason"],
+ request_id=resp["request_id"],
+ token_usage=dict(resp["usage"]),
+ ),
+ )
+ else:
+ return dict(message=message)
+
+ @staticmethod
+ def _chunk_to_generation(chunk: ChatGenerationChunk) -> ChatGeneration:
+ return ChatGeneration(
+ message=convert_message_chunk_to_message(chunk.message),
+ generation_info=chunk.generation_info,
+ )
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model.
+
+ Args:
+ tools: A list of tool definitions to bind to this chat model.
+ Can be a dictionary, pydantic model, callable, or BaseTool. Pydantic
+ models, callables, and BaseTools will be automatically converted to
+ their schema dictionary representation.
+ **kwargs: Any additional parameters to pass to the
+ :class:`~langchain.runnable.Runnable` constructor.
+ """
+
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ return super().bind(tools=formatted_tools, **kwargs)
+
+ def with_structured_output(
+ self,
+ schema: Union[Dict, Type[BaseModel]],
+ *,
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, Union[Dict, BaseModel]]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema: The output schema as a dict or a Pydantic class. If a Pydantic class
+ then the model output will be an object of that class. If a dict then
+ the model output will be a dict. With a Pydantic class the returned
+ attributes will be validated, whereas with a dict they will not be. If
+ `method` is "function_calling" and `schema` is a dict, then the dict
+ must match the OpenAI function-calling spec.
+ include_raw: If False then only the parsed structured output is returned. If
+ an error occurs during model output parsing it will be raised. If True
+ then both the raw model response (a BaseMessage) and the parsed model
+ response will be returned. If an error occurs during output parsing it
+ will be caught and returned as well. The final output is always a dict
+ with keys "raw", "parsed", and "parsing_error".
+
+ Returns:
+ A Runnable that takes any ChatModel input and returns as output:
+
+ If include_raw is True then a dict with keys:
+ raw: BaseMessage
+ parsed: Optional[_DictOrPydantic]
+ parsing_error: Optional[BaseException]
+
+ If include_raw is False then just _DictOrPydantic is returned,
+ where _DictOrPydantic depends on the schema:
+
+ If schema is a Pydantic class then _DictOrPydantic is the Pydantic
+ class.
+
+ If schema is a dict then _DictOrPydantic is a dict.
+
+ """
+ if kwargs:
+ raise ValueError(f"Received unsupported arguments {kwargs}")
+ is_pydantic_schema = isinstance(schema, type) and is_basemodel_subclass(schema)
+ llm = self.bind_tools([schema])
+ if is_pydantic_schema:
+ output_parser: OutputParserLike = PydanticToolsParser(
+ tools=[schema], # type: ignore[list-item]
+ first_tool_only=True,
+ )
+ else:
+ key_name = convert_to_openai_tool(schema)["function"]["name"]
+ output_parser = JsonOutputKeyToolsParser(
+ key_name=key_name, first_tool_only=True
+ )
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ else:
+ return llm | output_parser
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/vertexai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/vertexai.py
new file mode 100644
index 0000000000000000000000000000000000000000..eeb638e2dc074a192bf32f77a5b1cc514f5ef0c5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/vertexai.py
@@ -0,0 +1,393 @@
+"""Wrapper around Google VertexAI chat-based models."""
+
+from __future__ import annotations
+
+import base64
+import logging
+import re
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Union, cast
+from urllib.parse import urlparse
+
+import requests
+from langchain_core._api.deprecation import deprecated
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.utils import pre_init
+
+from langchain_community.llms.vertexai import (
+ _VertexAICommon,
+ is_codey_model,
+ is_gemini_model,
+)
+from langchain_community.utilities.vertexai import (
+ load_image_from_gcs,
+ raise_vertex_import_error,
+)
+
+if TYPE_CHECKING:
+ from vertexai.language_models import (
+ ChatMessage,
+ ChatSession,
+ CodeChatSession,
+ InputOutputTextPair,
+ )
+ from vertexai.preview.generative_models import Content
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class _ChatHistory:
+ """Represents a context and a history of messages."""
+
+ history: List["ChatMessage"] = field(default_factory=list)
+ context: Optional[str] = None
+
+
+def _parse_chat_history(history: List[BaseMessage]) -> _ChatHistory:
+ """Parse a sequence of messages into history.
+
+ Args:
+ history: The list of messages to re-create the history of the chat.
+ Returns:
+ A parsed chat history.
+ Raises:
+ ValueError: If a sequence of message has a SystemMessage not at the
+ first place.
+ """
+ from vertexai.language_models import ChatMessage
+
+ vertex_messages, context = [], None
+ for i, message in enumerate(history):
+ content = cast(str, message.content)
+ if i == 0 and isinstance(message, SystemMessage):
+ context = content
+ elif isinstance(message, AIMessage):
+ vertex_message = ChatMessage(content=message.content, author="bot")
+ vertex_messages.append(vertex_message)
+ elif isinstance(message, HumanMessage):
+ vertex_message = ChatMessage(content=message.content, author="user")
+ vertex_messages.append(vertex_message)
+ else:
+ raise ValueError(
+ f"Unexpected message with type {type(message)} at the position {i}."
+ )
+ chat_history = _ChatHistory(context=context, history=vertex_messages)
+ return chat_history
+
+
+def _is_url(s: str) -> bool:
+ try:
+ result = urlparse(s)
+ return all([result.scheme, result.netloc])
+ except Exception as e:
+ logger.debug(f"Unable to parse URL: {e}")
+ return False
+
+
+def _parse_chat_history_gemini(
+ history: List[BaseMessage], project: Optional[str]
+) -> List["Content"]:
+ from vertexai.preview.generative_models import Content, Image, Part
+
+ def _convert_to_prompt(part: Union[str, Dict]) -> Part:
+ if isinstance(part, str):
+ return Part.from_text(part)
+
+ if not isinstance(part, Dict):
+ raise ValueError(
+ f"Message's content is expected to be a dict, got {type(part)}!"
+ )
+ if part["type"] == "text":
+ return Part.from_text(part["text"])
+ elif part["type"] == "image_url":
+ path = part["image_url"]["url"]
+ if path.startswith("gs://"):
+ image = load_image_from_gcs(path=path, project=project)
+ elif path.startswith("data:image/"):
+ # extract base64 component from image uri
+ encoded: Any = re.search(r"data:image/\w{2,4};base64,(.*)", path)
+ if encoded:
+ encoded = encoded.group(1)
+ else:
+ raise ValueError(
+ "Invalid image uri. It should be in the format "
+ "data:image/;base64,."
+ )
+ image = Image.from_bytes(base64.b64decode(encoded))
+ elif _is_url(path):
+ response = requests.get(path)
+ response.raise_for_status()
+ image = Image.from_bytes(response.content)
+ else:
+ image = Image.load_from_file(path)
+ else:
+ raise ValueError("Only text and image_url types are supported!")
+ return Part.from_image(image)
+
+ vertex_messages = []
+ for i, message in enumerate(history):
+ if i == 0 and isinstance(message, SystemMessage):
+ raise ValueError("SystemMessages are not yet supported!")
+ elif isinstance(message, AIMessage):
+ role = "model"
+ elif isinstance(message, HumanMessage):
+ role = "user"
+ else:
+ raise ValueError(
+ f"Unexpected message with type {type(message)} at the position {i}."
+ )
+
+ raw_content = message.content
+ if isinstance(raw_content, str):
+ raw_content = [raw_content]
+ parts = [_convert_to_prompt(part) for part in raw_content]
+ vertex_message = Content(role=role, parts=parts)
+ vertex_messages.append(vertex_message)
+ return vertex_messages
+
+
+def _parse_examples(examples: List[BaseMessage]) -> List["InputOutputTextPair"]:
+ from vertexai.language_models import InputOutputTextPair
+
+ if len(examples) % 2 != 0:
+ raise ValueError(
+ f"Expect examples to have an even amount of messages, got {len(examples)}."
+ )
+ example_pairs = []
+ input_text = None
+ for i, example in enumerate(examples):
+ if i % 2 == 0:
+ if not isinstance(example, HumanMessage):
+ raise ValueError(
+ f"Expected the first message in a part to be from human, got "
+ f"{type(example)} for the {i}th message."
+ )
+ input_text = example.content
+ if i % 2 == 1:
+ if not isinstance(example, AIMessage):
+ raise ValueError(
+ f"Expected the second message in a part to be from AI, got "
+ f"{type(example)} for the {i}th message."
+ )
+ pair = InputOutputTextPair(
+ input_text=input_text, output_text=example.content
+ )
+ example_pairs.append(pair)
+ return example_pairs
+
+
+def _get_question(messages: List[BaseMessage]) -> HumanMessage:
+ """Get the human message at the end of a list of input messages to a chat model."""
+ if not messages:
+ raise ValueError("You should provide at least one message to start the chat!")
+ question = messages[-1]
+ if not isinstance(question, HumanMessage):
+ raise ValueError(
+ f"Last message in the list should be from human, got {question.type}."
+ )
+ return question
+
+
+@deprecated(
+ since="0.0.12",
+ removal="1.0",
+ alternative_import="langchain_google_vertexai.ChatVertexAI",
+)
+class ChatVertexAI(_VertexAICommon, BaseChatModel):
+ """`Vertex AI` Chat large language models API."""
+
+ model_name: str = "chat-bison"
+ "Underlying model name."
+ examples: Optional[List[BaseMessage]] = None
+
+ @classmethod
+ def is_lc_serializable(self) -> bool:
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> List[str]:
+ """Get the namespace of the langchain object."""
+ return ["langchain", "chat_models", "vertexai"]
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that the python package exists in environment."""
+ is_gemini = is_gemini_model(values["model_name"])
+ cls._try_init_vertexai(values)
+ try:
+ from vertexai.language_models import ChatModel, CodeChatModel
+
+ if is_gemini:
+ from vertexai.preview.generative_models import (
+ GenerativeModel,
+ )
+ except ImportError:
+ raise_vertex_import_error()
+ if is_gemini:
+ values["client"] = GenerativeModel(model_name=values["model_name"])
+ else:
+ if is_codey_model(values["model_name"]):
+ model_cls = CodeChatModel
+ else:
+ model_cls = ChatModel
+ values["client"] = model_cls.from_pretrained(values["model_name"])
+ return values
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate next turn in the conversation.
+
+ Args:
+ messages: The history of the conversation as a list of messages. Code chat
+ does not support context.
+ stop: The list of stop words (optional).
+ run_manager: The CallbackManager for LLM run, it's not used at the moment.
+ stream: Whether to use the streaming endpoint.
+
+ Returns:
+ The ChatResult that contains outputs generated by the model.
+
+ Raises:
+ ValueError: if the last message in the list is not from human.
+ """
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ question = _get_question(messages)
+ params = self._prepare_params(stop=stop, stream=False, **kwargs)
+ msg_params = {}
+ if "candidate_count" in params:
+ msg_params["candidate_count"] = params.pop("candidate_count")
+
+ if self._is_gemini_model:
+ history_gemini = _parse_chat_history_gemini(messages, project=self.project)
+ message = history_gemini.pop()
+ chat = self.client.start_chat(history=history_gemini)
+ response = chat.send_message(message, generation_config=params)
+ else:
+ history = _parse_chat_history(messages[:-1])
+ examples = kwargs.get("examples") or self.examples
+ if examples:
+ params["examples"] = _parse_examples(examples)
+ chat = self._start_chat(history, **params)
+ response = chat.send_message(question.content, **msg_params)
+ generations = [
+ ChatGeneration(message=AIMessage(content=r.text))
+ for r in response.candidates
+ ]
+ return ChatResult(generations=generations)
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Asynchronously generate next turn in the conversation.
+
+ Args:
+ messages: The history of the conversation as a list of messages. Code chat
+ does not support context.
+ stop: The list of stop words (optional).
+ run_manager: The CallbackManager for LLM run, it's not used at the moment.
+
+ Returns:
+ The ChatResult that contains outputs generated by the model.
+
+ Raises:
+ ValueError: if the last message in the list is not from human.
+ """
+ if "stream" in kwargs:
+ kwargs.pop("stream")
+ logger.warning("ChatVertexAI does not currently support async streaming.")
+
+ params = self._prepare_params(stop=stop, **kwargs)
+ msg_params = {}
+ if "candidate_count" in params:
+ msg_params["candidate_count"] = params.pop("candidate_count")
+
+ if self._is_gemini_model:
+ history_gemini = _parse_chat_history_gemini(messages, project=self.project)
+ message = history_gemini.pop()
+ chat = self.client.start_chat(history=history_gemini)
+ response = await chat.send_message_async(message, generation_config=params)
+ else:
+ question = _get_question(messages)
+ history = _parse_chat_history(messages[:-1])
+ examples = kwargs.get("examples", None)
+ if examples:
+ params["examples"] = _parse_examples(examples)
+ chat = self._start_chat(history, **params)
+ response = await chat.send_message_async(question.content, **msg_params)
+
+ generations = [
+ ChatGeneration(message=AIMessage(content=r.text))
+ for r in response.candidates
+ ]
+ return ChatResult(generations=generations)
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ params = self._prepare_params(stop=stop, stream=True, **kwargs)
+ if self._is_gemini_model:
+ history_gemini = _parse_chat_history_gemini(messages, project=self.project)
+ message = history_gemini.pop()
+ chat = self.client.start_chat(history=history_gemini)
+ responses = chat.send_message(
+ message, stream=True, generation_config=params
+ )
+ else:
+ question = _get_question(messages)
+ history = _parse_chat_history(messages[:-1])
+ examples = kwargs.get("examples", None)
+ if examples:
+ params["examples"] = _parse_examples(examples)
+ chat = self._start_chat(history, **params)
+ responses = chat.send_message_streaming(question.content, **params)
+ for response in responses:
+ chunk = ChatGenerationChunk(message=AIMessageChunk(content=response.text))
+ if run_manager:
+ run_manager.on_llm_new_token(response.text, chunk=chunk)
+ yield chunk
+
+ def _start_chat(
+ self, history: _ChatHistory, **kwargs: Any
+ ) -> Union[ChatSession, CodeChatSession]:
+ if not self.is_codey_model:
+ return self.client.start_chat(
+ context=history.context, message_history=history.history, **kwargs
+ )
+ else:
+ return self.client.start_chat(message_history=history.history, **kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/volcengine_maas.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/volcengine_maas.py
new file mode 100644
index 0000000000000000000000000000000000000000..687a540bb30ea405e90615f32be6f433ded2cbb3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/volcengine_maas.py
@@ -0,0 +1,146 @@
+from __future__ import annotations
+
+from typing import Any, Dict, Iterator, List, Mapping, Optional, cast
+
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ FunctionMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+
+from langchain_community.llms.volcengine_maas import VolcEngineMaasBase
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ if isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ elif isinstance(message, FunctionMessage):
+ message_dict = {"role": "function", "content": message.content}
+ else:
+ raise ValueError(f"Got unknown type {message}")
+ return message_dict
+
+
+def convert_dict_to_message(_dict: Mapping[str, Any]) -> AIMessage:
+ """Convert a dict to a message."""
+
+ content = _dict.get("choice", {}).get("message", {}).get("content", "")
+ return AIMessage(content=content)
+
+
+class VolcEngineMaasChat(BaseChatModel, VolcEngineMaasBase):
+ """Volc Engine Maas hosts a plethora of models.
+
+ You can utilize these models through this class.
+
+ To use, you should have the ``volcengine`` python package installed.
+ and set access key and secret key by environment variable or direct pass those
+ to this class.
+ access key, secret key are required parameters which you could get help
+ https://www.volcengine.com/docs/6291/65568
+
+ In order to use them, it is necessary to install the 'volcengine' Python package.
+ The access key and secret key must be set either via environment variables or
+ passed directly to this class.
+ access key and secret key are mandatory parameters for which assistance can be
+ sought at https://www.volcengine.com/docs/6291/65568.
+
+ The two methods are as follows:
+ * Environment Variable
+ Set the environment variables 'VOLC_ACCESSKEY' and 'VOLC_SECRETKEY' with your
+ access key and secret key.
+
+ * Pass Directly to Class
+ Example:
+ .. code-block:: python
+
+ from langchain_community.llms import VolcEngineMaasLLM
+ model = VolcEngineMaasChat(model="skylark-lite-public",
+ volc_engine_maas_ak="your_ak",
+ volc_engine_maas_sk="your_sk")
+ """
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "volc-engine-maas-chat"
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return whether this model can be serialized by Langchain."""
+ return False
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ return {
+ **{"endpoint": self.endpoint, "model": self.model},
+ **super()._identifying_params,
+ }
+
+ def _convert_prompt_msg_params(
+ self,
+ messages: List[BaseMessage],
+ **kwargs: Any,
+ ) -> Dict[str, Any]:
+ model_req = {
+ "model": {
+ "name": self.model,
+ }
+ }
+ if self.model_version is not None:
+ model_req["model"]["version"] = self.model_version
+ return {
+ **model_req,
+ "messages": [_convert_message_to_dict(message) for message in messages],
+ "parameters": {**self._default_params, **kwargs},
+ }
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ if stop is not None:
+ kwargs["stop"] = stop
+ params = self._convert_prompt_msg_params(messages, **kwargs)
+ for res in self.client.stream_chat(params):
+ if res:
+ msg = convert_dict_to_message(res)
+ chunk = ChatGenerationChunk(message=AIMessageChunk(content=msg.content))
+ if run_manager:
+ run_manager.on_llm_new_token(cast(str, msg.content), chunk=chunk)
+ yield chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ completion = ""
+ if self.streaming:
+ for chunk in self._stream(messages, stop, run_manager, **kwargs):
+ completion += chunk.text
+ else:
+ if stop is not None:
+ kwargs["stop"] = stop
+ params = self._convert_prompt_msg_params(messages, **kwargs)
+ res = self.client.chat(params)
+ msg = convert_dict_to_message(res)
+ completion = cast(str, msg.content)
+
+ message = AIMessage(content=completion)
+ return ChatResult(generations=[ChatGeneration(message=message)])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/writer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/writer.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4d5ca7e3bd7d0a8fd3e7e487bbbc4bf398d0bbb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/writer.py
@@ -0,0 +1,373 @@
+"""Writer chat wrapper."""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Literal,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ Union,
+ cast,
+)
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+ ToolMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable
+from langchain_core.tools import BaseTool
+from langchain_core.utils import get_from_dict_or_env
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator
+
+logger = logging.getLogger(__name__)
+
+
+class ChatWriter(BaseChatModel):
+ """Writer chat model.
+
+ To use, you should have the ``writer-sdk`` Python package installed, and the
+ environment variable ``WRITER_API_KEY`` set with your API key or pass 'api_key'
+ init param.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatWriter
+
+ chat = ChatWriter(
+ api_key="your key"
+ model="palmyra-x-004"
+ )
+ """
+
+ client: Any = Field(default=None, exclude=True) #: :meta private:
+ async_client: Any = Field(default=None, exclude=True) #: :meta private:
+
+ api_key: Optional[SecretStr] = Field(default=None)
+ """Writer API key."""
+
+ model_name: str = Field(default="palmyra-x-004", alias="model")
+ """Model name to use."""
+
+ temperature: float = 0.7
+ """What sampling temperature to use."""
+
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for `create` call not explicitly specified."""
+
+ n: int = 1
+ """Number of chat completions to generate for each prompt."""
+
+ max_tokens: Optional[int] = None
+ """Maximum number of tokens to generate."""
+
+ model_config = ConfigDict(populate_by_name=True)
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "writer-chat"
+
+ @property
+ def _identifying_params(self) -> Dict[str, Any]:
+ """Get the identifying parameters."""
+ return {
+ "model_name": self.model_name,
+ "temperature": self.temperature,
+ **self.model_kwargs,
+ }
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling Writer API."""
+ return {
+ "model": self.model_name,
+ "temperature": self.temperature,
+ "n": self.n,
+ "max_tokens": self.max_tokens,
+ **self.model_kwargs,
+ }
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validates that api key is passed and creates Writer clients."""
+ try:
+ from writerai import AsyncClient, Client
+ except ImportError as e:
+ raise ImportError(
+ "Could not import writerai python package. "
+ "Please install it with `pip install writerai`."
+ ) from e
+
+ if not values.get("client"):
+ values.update(
+ {
+ "client": Client(
+ api_key=get_from_dict_or_env(
+ values, "api_key", "WRITER_API_KEY"
+ )
+ )
+ }
+ )
+
+ if not values.get("async_client"):
+ values.update(
+ {
+ "async_client": AsyncClient(
+ api_key=get_from_dict_or_env(
+ values, "api_key", "WRITER_API_KEY"
+ )
+ )
+ }
+ )
+
+ if not (
+ type(values.get("client")) is Client
+ and type(values.get("async_client")) is AsyncClient
+ ):
+ raise ValueError(
+ "'client' attribute must be with type 'Client' and "
+ "'async_client' must be with type 'AsyncClient' from 'writerai' package"
+ )
+
+ return values
+
+ def _create_chat_result(self, response: Any) -> ChatResult:
+ generations = []
+ for choice in response.choices:
+ message = self._convert_writer_to_langchain(choice.message)
+ gen = ChatGeneration(
+ message=message,
+ generation_info=dict(finish_reason=choice.finish_reason),
+ )
+ generations.append(gen)
+
+ token_usage = {}
+
+ if response.usage:
+ token_usage = response.usage.__dict__
+ llm_output = {
+ "token_usage": token_usage,
+ "model_name": self.model_name,
+ "system_fingerprint": response.system_fingerprint,
+ }
+
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ @staticmethod
+ def _convert_langchain_to_writer(message: BaseMessage) -> dict:
+ """Convert a LangChain message to a Writer message dict."""
+ message_dict = {"role": "", "content": message.content}
+
+ if isinstance(message, ChatMessage):
+ message_dict["role"] = message.role
+ elif isinstance(message, HumanMessage):
+ message_dict["role"] = "user"
+ elif isinstance(message, AIMessage):
+ message_dict["role"] = "assistant"
+ if message.tool_calls:
+ message_dict["tool_calls"] = [
+ {
+ "id": tool["id"],
+ "type": "function",
+ "function": {"name": tool["name"], "arguments": tool["args"]},
+ }
+ for tool in message.tool_calls
+ ]
+ elif isinstance(message, SystemMessage):
+ message_dict["role"] = "system"
+ elif isinstance(message, ToolMessage):
+ message_dict["role"] = "tool"
+ message_dict["tool_call_id"] = message.tool_call_id
+ else:
+ raise ValueError(f"Got unknown message type: {type(message)}")
+
+ if message.name:
+ message_dict["name"] = message.name
+
+ return message_dict
+
+ @staticmethod
+ def _convert_writer_to_langchain(response_message: Any) -> BaseMessage:
+ """Convert a Writer message to a LangChain message."""
+ if not isinstance(response_message, dict):
+ response_message = json.loads(
+ json.dumps(response_message, default=lambda o: o.__dict__)
+ )
+
+ role = response_message.get("role", "")
+ content = response_message.get("content")
+ if not content:
+ content = ""
+
+ if role == "user":
+ return HumanMessage(content=content)
+ elif role == "assistant":
+ additional_kwargs = {}
+ if tool_calls := response_message.get("tool_calls", []):
+ additional_kwargs["tool_calls"] = tool_calls
+ return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)
+ elif role == "system":
+ return SystemMessage(content=content)
+ elif role == "tool":
+ return ToolMessage(
+ content=content,
+ tool_call_id=response_message.get("tool_call_id", ""),
+ name=response_message.get("name", ""),
+ )
+ else:
+ return ChatMessage(content=content, role=role)
+
+ def _convert_messages_to_writer(
+ self, messages: List[BaseMessage], stop: Optional[List[str]] = None
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
+ """Convert a list of LangChain messages to List of Writer dicts."""
+ params = {
+ "model": self.model_name,
+ "temperature": self.temperature,
+ "n": self.n,
+ **self.model_kwargs,
+ }
+ if stop:
+ params["stop"] = stop
+ if self.max_tokens is not None:
+ params["max_tokens"] = self.max_tokens
+
+ message_dicts = [self._convert_langchain_to_writer(m) for m in messages]
+ return message_dicts, params
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ message_dicts, params = self._convert_messages_to_writer(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ response = self.client.chat.chat(messages=message_dicts, **params)
+
+ for chunk in response:
+ delta = chunk.choices[0].delta
+ if not delta or not delta.content:
+ continue
+ message_chunk = self._convert_writer_to_langchain(
+ {
+ "role": "assistant",
+ "content": delta.content,
+ }
+ )
+ chunk = ChatGenerationChunk(message=cast(BaseMessageChunk, message_chunk))
+
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text)
+
+ yield chunk
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ message_dicts, params = self._convert_messages_to_writer(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ response = await self.async_client.chat.chat(messages=message_dicts, **params)
+
+ async for chunk in response:
+ delta = chunk.choices[0].delta
+ if not delta or not delta.content:
+ continue
+ message_chunk = self._convert_writer_to_langchain(
+ {
+ "role": "assistant",
+ "content": delta.content,
+ }
+ )
+ chunk = ChatGenerationChunk(message=cast(BaseMessageChunk, message_chunk))
+
+ if run_manager:
+ await run_manager.on_llm_new_token(chunk.text)
+
+ yield chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ message_dicts, params = self._convert_messages_to_writer(messages, stop)
+ params = {**params, **kwargs}
+ response = self.client.chat.chat(messages=message_dicts, **params)
+ return self._create_chat_result(response)
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ message_dicts, params = self._convert_messages_to_writer(messages, stop)
+ params = {**params, **kwargs}
+ response = await self.async_client.chat.chat(messages=message_dicts, **params)
+ return self._create_chat_result(response)
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ tool_choice: Optional[Union[str, Literal["auto", "none"]]] = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tools to the chat model.
+
+ Args:
+ tools: Tools to bind to the model
+ tool_choice: Which tool to require ('auto', 'none', or specific tool name)
+ **kwargs: Additional parameters to pass to the chat model
+
+ Returns:
+ A runnable that will use the tools
+ """
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+
+ if tool_choice:
+ kwargs["tool_choice"] = (
+ (tool_choice)
+ if tool_choice in ("auto", "none")
+ else {"type": "function", "function": {"name": tool_choice}}
+ )
+
+ return super().bind(tools=formatted_tools, **kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/yandex.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/yandex.py
new file mode 100644
index 0000000000000000000000000000000000000000..02aed41650c45e47c7e0c00ba0419d9843cb087b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/yandex.py
@@ -0,0 +1,283 @@
+"""Wrapper around YandexGPT chat models."""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Callable, Dict, List, Optional, cast
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import (
+ AIMessage,
+ BaseMessage,
+ HumanMessage,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatResult
+from tenacity import (
+ before_sleep_log,
+ retry,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential,
+)
+
+from langchain_community.llms.utils import enforce_stop_tokens
+from langchain_community.llms.yandex import _BaseYandexGPT
+
+logger = logging.getLogger(__name__)
+
+
+def _parse_message(role: str, text: str) -> Dict:
+ return {"role": role, "text": text}
+
+
+def _parse_chat_history(history: List[BaseMessage]) -> List[Dict[str, str]]:
+ """Parse a sequence of messages into history.
+
+ Returns:
+ A list of parsed messages.
+ """
+ chat_history = []
+ for message in history:
+ content = cast(str, message.content)
+ if isinstance(message, HumanMessage):
+ chat_history.append(_parse_message("user", content))
+ if isinstance(message, AIMessage):
+ chat_history.append(_parse_message("assistant", content))
+ if isinstance(message, SystemMessage):
+ chat_history.append(_parse_message("system", content))
+ return chat_history
+
+
+class ChatYandexGPT(_BaseYandexGPT, BaseChatModel):
+ """YandexGPT large language models.
+
+ There are two authentication options for the service account
+ with the ``ai.languageModels.user`` role:
+ - You can specify the token in a constructor parameter `iam_token`
+ or in an environment variable `YC_IAM_TOKEN`.
+ - You can specify the key in a constructor parameter `api_key`
+ or in an environment variable `YC_API_KEY`.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatYandexGPT
+ chat_model = ChatYandexGPT(iam_token="t1.9eu...")
+
+ """
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate next turn in the conversation.
+ Args:
+ messages: The history of the conversation as a list of messages.
+ stop: The list of stop words (optional).
+ run_manager: The CallbackManager for LLM run, it's not used at the moment.
+
+ Returns:
+ The ChatResult that contains outputs generated by the model.
+
+ Raises:
+ ValueError: if the last message in the list is not from human.
+ """
+ text = completion_with_retry(self, messages=messages)
+ text = text if stop is None else enforce_stop_tokens(text, stop)
+ message = AIMessage(content=text)
+ return ChatResult(generations=[ChatGeneration(message=message)])
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Async method to generate next turn in the conversation.
+
+ Args:
+ messages: The history of the conversation as a list of messages.
+ stop: The list of stop words (optional).
+ run_manager: The CallbackManager for LLM run, it's not used at the moment.
+
+ Returns:
+ The ChatResult that contains outputs generated by the model.
+
+ Raises:
+ ValueError: if the last message in the list is not from human.
+ """
+ text = await acompletion_with_retry(self, messages=messages)
+ text = text if stop is None else enforce_stop_tokens(text, stop)
+ message = AIMessage(content=text)
+ return ChatResult(generations=[ChatGeneration(message=message)])
+
+
+def _make_request(
+ self: ChatYandexGPT,
+ messages: List[BaseMessage],
+) -> str:
+ try:
+ import grpc
+ from google.protobuf.wrappers_pb2 import DoubleValue, Int64Value
+
+ try:
+ from yandex.cloud.ai.foundation_models.v1.text_common_pb2 import (
+ CompletionOptions,
+ Message,
+ )
+ from yandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2 import ( # noqa: E501
+ CompletionRequest,
+ )
+ from yandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2_grpc import ( # noqa: E501
+ TextGenerationServiceStub,
+ )
+ except ModuleNotFoundError:
+ from yandex.cloud.ai.foundation_models.v1.foundation_models_pb2 import (
+ CompletionOptions,
+ Message,
+ )
+ from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2 import ( # noqa: E501
+ CompletionRequest,
+ )
+ from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2_grpc import ( # noqa: E501
+ TextGenerationServiceStub,
+ )
+ except ImportError as e:
+ raise ImportError(
+ "Please install YandexCloud SDK with `pip install yandexcloud` \
+ or upgrade it to recent version."
+ ) from e
+ if not messages:
+ raise ValueError("You should provide at least one message to start the chat!")
+ message_history = _parse_chat_history(messages)
+ channel_credentials = grpc.ssl_channel_credentials()
+ channel = grpc.secure_channel(self.url, channel_credentials)
+ request = CompletionRequest(
+ model_uri=self.model_uri,
+ completion_options=CompletionOptions(
+ temperature=DoubleValue(value=self.temperature),
+ max_tokens=Int64Value(value=self.max_tokens),
+ ),
+ messages=[Message(**message) for message in message_history],
+ )
+ stub = TextGenerationServiceStub(channel)
+ res = stub.Completion(request, metadata=self.grpc_metadata)
+ return list(res)[0].alternatives[0].message.text
+
+
+async def _amake_request(self: ChatYandexGPT, messages: List[BaseMessage]) -> str:
+ try:
+ import asyncio
+
+ import grpc
+ from google.protobuf.wrappers_pb2 import DoubleValue, Int64Value
+
+ try:
+ from yandex.cloud.ai.foundation_models.v1.text_common_pb2 import (
+ CompletionOptions,
+ Message,
+ )
+ from yandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2 import ( # noqa: E501
+ CompletionRequest,
+ CompletionResponse,
+ )
+ from yandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2_grpc import ( # noqa: E501
+ TextGenerationAsyncServiceStub,
+ )
+ except ModuleNotFoundError:
+ from yandex.cloud.ai.foundation_models.v1.foundation_models_pb2 import (
+ CompletionOptions,
+ Message,
+ )
+ from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2 import ( # noqa: E501
+ CompletionRequest,
+ CompletionResponse,
+ )
+ from yandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2_grpc import ( # noqa: E501
+ TextGenerationAsyncServiceStub,
+ )
+ from yandex.cloud.operation.operation_service_pb2 import GetOperationRequest
+ from yandex.cloud.operation.operation_service_pb2_grpc import (
+ OperationServiceStub,
+ )
+ except ImportError as e:
+ raise ImportError(
+ "Please install YandexCloud SDK with `pip install yandexcloud` \
+ or upgrade it to recent version."
+ ) from e
+ if not messages:
+ raise ValueError("You should provide at least one message to start the chat!")
+ message_history = _parse_chat_history(messages)
+ operation_api_url = "operation.api.cloud.yandex.net:443"
+ channel_credentials = grpc.ssl_channel_credentials()
+ async with grpc.aio.secure_channel(self.url, channel_credentials) as channel:
+ request = CompletionRequest(
+ model_uri=self.model_uri,
+ completion_options=CompletionOptions(
+ temperature=DoubleValue(value=self.temperature),
+ max_tokens=Int64Value(value=self.max_tokens),
+ ),
+ messages=[Message(**message) for message in message_history],
+ )
+ stub = TextGenerationAsyncServiceStub(channel)
+ operation = await stub.Completion(request, metadata=self.grpc_metadata)
+ async with grpc.aio.secure_channel(
+ operation_api_url, channel_credentials
+ ) as operation_channel:
+ operation_stub = OperationServiceStub(operation_channel)
+ while not operation.done:
+ await asyncio.sleep(1)
+ operation_request = GetOperationRequest(operation_id=operation.id)
+ operation = await operation_stub.Get(
+ operation_request,
+ metadata=self.grpc_metadata,
+ )
+
+ completion_response = CompletionResponse()
+ operation.response.Unpack(completion_response)
+ return completion_response.alternatives[0].message.text
+
+
+def _create_retry_decorator(llm: ChatYandexGPT) -> Callable[[Any], Any]:
+ from grpc import RpcError
+
+ min_seconds = llm.sleep_interval
+ max_seconds = 60
+ return retry(
+ reraise=True,
+ stop=stop_after_attempt(llm.max_retries),
+ wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
+ retry=(retry_if_exception_type((RpcError))),
+ before_sleep=before_sleep_log(logger, logging.WARNING),
+ )
+
+
+def completion_with_retry(llm: ChatYandexGPT, **kwargs: Any) -> Any:
+ """Use tenacity to retry the completion call."""
+ retry_decorator = _create_retry_decorator(llm)
+
+ @retry_decorator
+ def _completion_with_retry(**_kwargs: Any) -> Any:
+ return _make_request(llm, **_kwargs)
+
+ return _completion_with_retry(**kwargs)
+
+
+async def acompletion_with_retry(llm: ChatYandexGPT, **kwargs: Any) -> Any:
+ """Use tenacity to retry the async completion call."""
+ retry_decorator = _create_retry_decorator(llm)
+
+ @retry_decorator
+ async def _completion_with_retry(**_kwargs: Any) -> Any:
+ return await _amake_request(llm, **_kwargs)
+
+ return await _completion_with_retry(**kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/yi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/yi.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1a26019a5d6cf20c108ad9b8a4eb904ce1eb7bb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/yi.py
@@ -0,0 +1,340 @@
+import json
+import logging
+from contextlib import asynccontextmanager
+from typing import Any, AsyncIterator, Dict, Iterator, List, Mapping, Optional, Type
+
+import requests
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.utils import (
+ convert_to_secret_str,
+ get_from_dict_or_env,
+ get_pydantic_field_names,
+)
+from pydantic import ConfigDict, Field, SecretStr
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_API_BASE_CN = "https://api.lingyiwanwu.com/v1/chat/completions"
+DEFAULT_API_BASE_GLOBAL = "https://api.01.ai/v1/chat/completions"
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ message_dict: Dict[str, Any]
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ else:
+ raise TypeError(f"Got unknown type {message}")
+
+ return message_dict
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ role = _dict["role"]
+ if role == "user":
+ return HumanMessage(content=_dict["content"])
+ elif role == "assistant":
+ return AIMessage(content=_dict.get("content", "") or "")
+ elif role == "system":
+ return AIMessage(content=_dict["content"])
+ else:
+ return ChatMessage(content=_dict["content"], role=role)
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role: str = _dict["role"]
+ content = _dict.get("content") or ""
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content)
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role)
+ else:
+ return default_class(content=content, type=role)
+
+
+@asynccontextmanager
+async def aconnect_httpx_sse(
+ client: Any, method: str, url: str, **kwargs: Any
+) -> AsyncIterator:
+ from httpx_sse import EventSource
+
+ async with client.stream(method, url, **kwargs) as response:
+ yield EventSource(response)
+
+
+class ChatYi(BaseChatModel):
+ """Yi chat models API."""
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {
+ "yi_api_key": "YI_API_KEY",
+ }
+
+ @property
+ def lc_serializable(self) -> bool:
+ return True
+
+ yi_api_base: str = Field(default=DEFAULT_API_BASE_CN)
+ yi_api_key: SecretStr = Field(alias="api_key")
+ region: str = Field(default="cn") # 默认使用中国区
+ streaming: bool = False
+ request_timeout: int = Field(default=60, alias="timeout")
+ model: str = "yi-large"
+ temperature: Optional[float] = Field(default=0.7)
+ top_p: float = 0.7
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ def __init__(self, **kwargs: Any) -> None:
+ kwargs["yi_api_key"] = convert_to_secret_str(
+ get_from_dict_or_env(
+ kwargs,
+ ["yi_api_key", "api_key"],
+ "YI_API_KEY",
+ )
+ )
+ if kwargs.get("yi_api_base") is None:
+ region = kwargs.get("region", "cn").lower()
+ if region == "global":
+ kwargs["yi_api_base"] = DEFAULT_API_BASE_GLOBAL
+ else:
+ kwargs["yi_api_base"] = DEFAULT_API_BASE_CN
+
+ all_required_field_names = get_pydantic_field_names(self.__class__)
+ extra = kwargs.get("model_kwargs", {})
+ for field_name in list(kwargs):
+ if field_name in extra:
+ raise ValueError(f"Found {field_name} supplied twice.")
+ if field_name not in all_required_field_names:
+ extra[field_name] = kwargs.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
+ if invalid_model_kwargs:
+ raise ValueError(
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+
+ kwargs["model_kwargs"] = extra
+ super().__init__(**kwargs)
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ return {
+ "model": self.model,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ "stream": self.streaming,
+ }
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages=messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ res = self._chat(messages, **kwargs)
+ if res.status_code != 200:
+ raise ValueError(f"Error from Yi api response: {res}")
+ response = res.json()
+ return self._create_chat_result(response)
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ res = self._chat(messages, stream=True, **kwargs)
+ if res.status_code != 200:
+ raise ValueError(f"Error from Yi api response: {res}")
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ for chunk in res.iter_lines():
+ chunk = chunk.decode("utf-8").strip("\r\n")
+ parts = chunk.split("data: ", 1)
+ chunk = parts[1] if len(parts) > 1 else None
+ if chunk is None:
+ continue
+ if chunk == "[DONE]":
+ break
+ response = json.loads(chunk)
+ for m in response.get("choices"):
+ chunk = _convert_delta_to_message_chunk(
+ m.get("delta"), default_chunk_class
+ )
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(message=chunk)
+ if run_manager:
+ run_manager.on_llm_new_token(str(chunk.content), chunk=cg_chunk)
+ yield cg_chunk
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ headers = self._create_headers_parameters(**kwargs)
+ payload = self._create_payload_parameters(messages, **kwargs)
+
+ import httpx
+
+ async with httpx.AsyncClient(
+ headers=headers, timeout=self.request_timeout
+ ) as client:
+ response = await client.post(self.yi_api_base, json=payload)
+ response.raise_for_status()
+ return self._create_chat_result(response.json())
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ headers = self._create_headers_parameters(**kwargs)
+ payload = self._create_payload_parameters(messages, stream=True, **kwargs)
+ import httpx
+
+ async with httpx.AsyncClient(
+ headers=headers, timeout=self.request_timeout
+ ) as client:
+ async with aconnect_httpx_sse(
+ client, "POST", self.yi_api_base, json=payload
+ ) as event_source:
+ async for sse in event_source.aiter_sse():
+ chunk = json.loads(sse.data)
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], AIMessageChunk
+ )
+ finish_reason = choice.get("finish_reason", None)
+
+ generation_info = (
+ {"finish_reason": finish_reason}
+ if finish_reason is not None
+ else None
+ )
+ chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+ if finish_reason is not None:
+ break
+
+ def _chat(self, messages: List[BaseMessage], **kwargs: Any) -> requests.Response:
+ payload = self._create_payload_parameters(messages, **kwargs)
+ url = self.yi_api_base
+ headers = self._create_headers_parameters(**kwargs)
+
+ res = requests.post(
+ url=url,
+ timeout=self.request_timeout,
+ headers=headers,
+ json=payload,
+ stream=self.streaming,
+ )
+ return res
+
+ def _create_payload_parameters(
+ self, messages: List[BaseMessage], **kwargs: Any
+ ) -> Dict[str, Any]:
+ parameters = {**self._default_params, **kwargs}
+ temperature = parameters.pop("temperature", 0.7)
+ top_p = parameters.pop("top_p", 0.7)
+ model = parameters.pop("model")
+ stream = parameters.pop("stream", False)
+
+ payload = {
+ "model": model,
+ "messages": [_convert_message_to_dict(m) for m in messages],
+ "top_p": top_p,
+ "temperature": temperature,
+ "stream": stream,
+ }
+ return payload
+
+ def _create_headers_parameters(self, **kwargs: Any) -> Dict[str, Any]:
+ parameters = {**self._default_params, **kwargs}
+ default_headers = parameters.pop("headers", {})
+ api_key = ""
+ if self.yi_api_key:
+ api_key = self.yi_api_key.get_secret_value()
+
+ headers = {
+ "Content-Type": "application/json",
+ "Authorization": f"Bearer {api_key}",
+ **default_headers,
+ }
+ return headers
+
+ def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult:
+ generations = []
+ for c in response["choices"]:
+ message = _convert_dict_to_message(c["message"])
+ gen = ChatGeneration(message=message)
+ generations.append(gen)
+
+ token_usage = response["usage"]
+ llm_output = {"token_usage": token_usage, "model": self.model}
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ @property
+ def _llm_type(self) -> str:
+ return "yi-chat"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/yuan2.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/yuan2.py
new file mode 100644
index 0000000000000000000000000000000000000000..14808e25a40b4817b2e3a82d8e2295c43daf3a5b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/yuan2.py
@@ -0,0 +1,499 @@
+"""ChatYuan2 wrapper."""
+
+from __future__ import annotations
+
+import logging
+from typing import (
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Tuple,
+ Type,
+ Union,
+)
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessage,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.utils import (
+ get_from_dict_or_env,
+ get_pydantic_field_names,
+ pre_init,
+)
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+from tenacity import (
+ before_sleep_log,
+ retry,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class ChatYuan2(BaseChatModel):
+ """`Yuan2.0` Chat models API.
+
+ To use, you should have the ``openai-python`` package installed, if package
+ not installed, using ```pip install openai``` to install it. The
+ environment variable ``YUAN2_API_KEY`` set to your API key, if not set,
+ everyone can access apis.
+
+ Any parameters that are valid to be passed to the openai.create call can be passed
+ in, even if not explicitly saved on this class.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatYuan2
+
+ chat = ChatYuan2()
+ """
+
+ client: Any = None #: :meta private:
+ async_client: Any = Field(default=None, exclude=True) #: :meta private:
+
+ model_name: str = Field(default="yuan2", alias="model")
+ """Model name to use."""
+
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for `create` call not explicitly specified."""
+
+ yuan2_api_key: Optional[str] = Field(default="EMPTY", alias="api_key")
+ """Automatically inferred from env var `YUAN2_API_KEY` if not provided."""
+
+ yuan2_api_base: Optional[str] = Field(
+ default="http://127.0.0.1:8000/v1", alias="base_url"
+ )
+ """Base URL path for API requests, an OpenAI compatible API server."""
+
+ request_timeout: Optional[Union[float, Tuple[float, float]]] = Field(
+ default=None, alias="timeout"
+ )
+ """Timeout for requests to yuan2 completion API. Default is 600 seconds."""
+
+ max_retries: int = 6
+ """Maximum number of retries to make when generating."""
+
+ streaming: bool = False
+ """Whether to stream the results or not."""
+
+ max_tokens: Optional[int] = None
+ """Maximum number of tokens to generate."""
+
+ temperature: float = 1.0
+ """What sampling temperature to use."""
+
+ top_p: Optional[float] = 0.9
+ """The top-p value to use for sampling."""
+
+ stop: Optional[List[str]] = Field(default=[""], alias="stop_sequences")
+ """A list of strings to stop generation when encountered."""
+
+ repeat_last_n: Optional[int] = 64
+ "Last n tokens to penalize"
+
+ repeat_penalty: Optional[float] = 1.18
+ """The penalty to apply to repeated tokens."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"yuan2_api_key": "YUAN2_API_KEY"}
+
+ @property
+ def lc_attributes(self) -> Dict[str, Any]:
+ attributes: Dict[str, Any] = {}
+
+ if self.yuan2_api_base:
+ attributes["yuan2_api_base"] = self.yuan2_api_base
+
+ if self.yuan2_api_key:
+ attributes["yuan2_api_key"] = self.yuan2_api_key
+
+ return attributes
+
+ @model_validator(mode="before")
+ @classmethod
+ def build_extra(cls, values: Dict[str, Any]) -> Any:
+ """Build extra kwargs from additional params that were passed in."""
+ all_required_field_names = get_pydantic_field_names(cls)
+ extra = values.get("model_kwargs", {})
+ for field_name in list(values):
+ if field_name in extra:
+ raise ValueError(f"Found {field_name} supplied twice.")
+ if field_name not in all_required_field_names:
+ logger.warning(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please confirm that {field_name} is what you intended."""
+ )
+ extra[field_name] = values.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
+ if invalid_model_kwargs:
+ raise ValueError(
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+
+ values["model_kwargs"] = extra
+ return values
+
+ @pre_init
+ def validate_environment(cls, values: Dict) -> Dict:
+ """Validate that api key and python package exists in environment."""
+ values["yuan2_api_key"] = get_from_dict_or_env(
+ values, "yuan2_api_key", "YUAN2_API_KEY"
+ )
+
+ try:
+ import openai
+
+ except ImportError:
+ raise ImportError(
+ "Could not import openai python package. "
+ "Please install it with `pip install openai`."
+ )
+ client_params = {
+ "api_key": values["yuan2_api_key"],
+ "base_url": values["yuan2_api_base"],
+ "timeout": values["request_timeout"],
+ "max_retries": values["max_retries"],
+ }
+
+ # generate client and async_client
+ if not values.get("client"):
+ values["client"] = openai.OpenAI(**client_params).chat.completions
+ if not values.get("async_client"):
+ values["async_client"] = openai.AsyncOpenAI(
+ **client_params
+ ).chat.completions
+
+ return values
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling yuan2 API."""
+ params = {
+ "model": self.model_name,
+ "stream": self.streaming,
+ "temperature": self.temperature,
+ "top_p": self.top_p,
+ **self.model_kwargs,
+ }
+ if self.max_tokens is not None:
+ params["max_tokens"] = self.max_tokens
+ if self.request_timeout is not None:
+ params["request_timeout"] = self.request_timeout
+ return params
+
+ def completion_with_retry(self, **kwargs: Any) -> Any:
+ """Use tenacity to retry the completion call."""
+ retry_decorator = _create_retry_decorator(self)
+
+ @retry_decorator
+ def _completion_with_retry(**kwargs: Any) -> Any:
+ return self.client.create(**kwargs)
+
+ return _completion_with_retry(**kwargs)
+
+ def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict:
+ overall_token_usage: dict = {}
+ logger.debug(
+ f"type(llm_outputs): {type(llm_outputs)}; llm_outputs: {llm_outputs}"
+ )
+ for output in llm_outputs:
+ if output is None:
+ # Happens in streaming
+ continue
+ token_usage = output["token_usage"]
+ for k, v in token_usage.items():
+ if k in overall_token_usage:
+ overall_token_usage[k] += v
+ else:
+ overall_token_usage[k] = v
+ return {"token_usage": overall_token_usage, "model_name": self.model_name}
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ for chunk in self.completion_with_retry(messages=message_dicts, **params):
+ if not isinstance(chunk, dict):
+ chunk = chunk.model_dump()
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], default_chunk_class
+ )
+ finish_reason = choice.get("finish_reason")
+ generation_info = (
+ dict(finish_reason=finish_reason) if finish_reason is not None else None
+ )
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(
+ message=chunk,
+ generation_info=generation_info,
+ )
+ if run_manager:
+ token = (
+ chunk.content
+ if isinstance(chunk.content, str)
+ else str(chunk.content)
+ )
+ run_manager.on_llm_new_token(token, chunk=cg_chunk)
+ yield cg_chunk
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._stream(
+ messages=messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+ response = self.completion_with_retry(messages=message_dicts, **params)
+ return self._create_chat_result(response)
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage], stop: Optional[List[str]]
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
+ params = dict(self._invocation_params)
+ if stop is not None:
+ if "stop" in params:
+ raise ValueError("`stop` found in both the input and default params.")
+ params["stop"] = stop
+ message_dicts = [_convert_message_to_dict(m) for m in messages]
+ return message_dicts, params
+
+ def _create_chat_result(self, response: Union[dict, BaseModel]) -> ChatResult:
+ generations = []
+ logger.debug(f"type(response): {type(response)}; response: {response}")
+ if not isinstance(response, dict):
+ response = response.dict()
+ for res in response["choices"]:
+ message = _convert_dict_to_message(res["message"])
+ generation_info = dict(finish_reason=res["finish_reason"])
+ if "logprobs" in res:
+ generation_info["logprobs"] = res["logprobs"]
+ gen = ChatGeneration(
+ message=message,
+ generation_info=generation_info,
+ )
+ generations.append(gen)
+ llm_output = {
+ "token_usage": response.get("usage", {}),
+ "model_name": self.model_name,
+ }
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: Type[BaseMessageChunk] = AIMessageChunk
+ async for chunk in await acompletion_with_retry(
+ self, messages=message_dicts, **params
+ ):
+ if not isinstance(chunk, dict):
+ chunk = chunk.model_dump()
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], default_chunk_class
+ )
+ finish_reason = choice.get("finish_reason")
+ generation_info = (
+ dict(finish_reason=finish_reason) if finish_reason is not None else None
+ )
+ default_chunk_class = chunk.__class__
+ cg_chunk = ChatGenerationChunk(
+ message=chunk,
+ generation_info=generation_info,
+ )
+ if run_manager:
+ token = (
+ chunk.content
+ if isinstance(chunk.content, str)
+ else str(chunk.content)
+ )
+ await run_manager.on_llm_new_token(token, chunk=cg_chunk)
+ yield cg_chunk
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.streaming:
+ stream_iter = self._astream(
+ messages=messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs}
+ response = await acompletion_with_retry(self, messages=message_dicts, **params)
+ return self._create_chat_result(response)
+
+ @property
+ def _invocation_params(self) -> Mapping[str, Any]:
+ """Get the parameters used to invoke the model."""
+ yuan2_creds: Dict[str, Any] = {
+ "model": self.model_name,
+ }
+ return {**yuan2_creds, **self._default_params}
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+ return "chat-yuan2"
+
+
+def _create_retry_decorator(llm: ChatYuan2) -> Callable[[Any], Any]:
+ import openai
+
+ min_seconds = 1
+ max_seconds = 60
+ # Wait 2^x * 1 second between each retry starting with
+ # 4 seconds, then up to 10 seconds, then 10 seconds afterwards
+ return retry(
+ reraise=True,
+ stop=stop_after_attempt(llm.max_retries),
+ wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
+ retry=(
+ retry_if_exception_type(openai.APITimeoutError)
+ | retry_if_exception_type(openai.APIError)
+ | retry_if_exception_type(openai.APIConnectionError)
+ | retry_if_exception_type(openai.RateLimitError)
+ | retry_if_exception_type(openai.InternalServerError)
+ ),
+ before_sleep=before_sleep_log(logger, logging.WARNING),
+ )
+
+
+async def acompletion_with_retry(llm: ChatYuan2, **kwargs: Any) -> Any:
+ """Use tenacity to retry the async completion call."""
+ retry_decorator = _create_retry_decorator(llm)
+
+ @retry_decorator
+ async def _completion_with_retry(**kwargs: Any) -> Any:
+ # Use OpenAI's async api https://github.com/openai/openai-python#async-api
+ return await llm.async_client.create(**kwargs)
+
+ return await _completion_with_retry(**kwargs)
+
+
+def _convert_delta_to_message_chunk(
+ _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role = _dict.get("role")
+ content = _dict.get("content") or ""
+
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ elif role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content)
+ elif role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ elif role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+ else:
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ role = _dict.get("role")
+ if role == "user":
+ return HumanMessage(content=_dict.get("content", ""))
+ elif role == "assistant":
+ return AIMessage(content=_dict.get("content", ""))
+ elif role == "system":
+ return SystemMessage(content=_dict.get("content", ""))
+ else:
+ return ChatMessage(content=_dict.get("content", ""), role=role) # type: ignore[arg-type]
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ """Convert a LangChain message to a dictionary.
+
+ Args:
+ message: The LangChain message.
+
+ Returns:
+ The dictionary.
+ """
+ message_dict: Dict[str, Any]
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, FunctionMessage):
+ message_dict = {
+ "role": "function",
+ "name": message.name,
+ "content": message.content,
+ }
+ else:
+ raise ValueError(f"Got unknown type {message}")
+ if "name" in message.additional_kwargs:
+ message_dict["name"] = message.additional_kwargs["name"]
+ return message_dict
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/zhipuai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/zhipuai.py
new file mode 100644
index 0000000000000000000000000000000000000000..c48b16bee7a33898dd96751427c91aff72621bb7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/chat_models/zhipuai.py
@@ -0,0 +1,886 @@
+"""ZhipuAI chat models wrapper."""
+
+from __future__ import annotations
+
+import json
+import logging
+import time
+from collections.abc import AsyncIterator, Iterator
+from contextlib import asynccontextmanager, contextmanager
+from operator import itemgetter
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ List,
+ Literal,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ Union,
+)
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ SystemMessage,
+ SystemMessageChunk,
+ ToolMessage,
+)
+from langchain_core.output_parsers.base import OutputParserLike
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ PydanticToolsParser,
+)
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
+from langchain_core.tools import BaseTool
+from langchain_core.utils import get_from_dict_or_env
+from langchain_core.utils.function_calling import convert_to_openai_tool
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+logger = logging.getLogger(__name__)
+
+API_TOKEN_TTL_SECONDS = 3 * 60
+ZHIPUAI_API_BASE = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
+
+
+def _is_pydantic_class(obj: Any) -> bool:
+ return isinstance(obj, type) and issubclass(obj, BaseModel)
+
+
+@contextmanager
+def connect_sse(client: Any, method: str, url: str, **kwargs: Any) -> Iterator:
+ """Context manager for connecting to an SSE stream.
+
+ Args:
+ client: The HTTP client.
+ method: The HTTP method.
+ url: The URL.
+ kwargs: Additional keyword arguments.
+
+ Yields:
+ The event source.
+ """
+ from httpx_sse import EventSource
+
+ with client.stream(method, url, **kwargs) as response:
+ yield EventSource(response)
+
+
+@asynccontextmanager
+async def aconnect_sse(
+ client: Any, method: str, url: str, **kwargs: Any
+) -> AsyncIterator:
+ """Async context manager for connecting to an SSE stream.
+
+ Args:
+ client: The HTTP client.
+ method: The HTTP method.
+ url: The URL.
+ kwargs: Additional keyword arguments.
+
+ Yields:
+ The event source.
+ """
+ from httpx_sse import EventSource
+
+ async with client.stream(method, url, **kwargs) as response:
+ yield EventSource(response)
+
+
+def _get_jwt_token(api_key: str) -> str:
+ """Gets JWT token for ZhipuAI API.
+
+ See 'https://open.bigmodel.cn/dev/api#nosdk'.
+
+ Args:
+ api_key: The API key for ZhipuAI API.
+
+ Returns:
+ The JWT token.
+ """
+ try:
+ import jwt
+ except ImportError:
+ raise ImportError(
+ "jwt package not found, please install it with`pip install pyjwt`"
+ )
+
+ try:
+ id, secret = api_key.split(".")
+ except ValueError as err:
+ raise ValueError(f"Invalid API key: {api_key}") from err
+
+ payload = {
+ "api_key": id,
+ "exp": int(round(time.time() * 1000)) + API_TOKEN_TTL_SECONDS * 1000,
+ "timestamp": int(round(time.time() * 1000)),
+ }
+
+ return jwt.encode(
+ payload,
+ secret,
+ algorithm="HS256",
+ headers={"alg": "HS256", "sign_type": "SIGN"},
+ )
+
+
+def _convert_dict_to_message(dct: Dict[str, Any]) -> BaseMessage:
+ role = dct.get("role")
+ content = dct.get("content", "")
+ if role == "system":
+ return SystemMessage(content=content)
+ if role == "user":
+ return HumanMessage(content=content)
+ if role == "assistant":
+ additional_kwargs = {}
+ tool_calls = dct.get("tool_calls", None)
+ if tool_calls is not None:
+ additional_kwargs["tool_calls"] = tool_calls
+ return AIMessage(content=content, additional_kwargs=additional_kwargs)
+ if role == "tool":
+ additional_kwargs = {}
+ if "name" in dct:
+ additional_kwargs["name"] = dct["name"]
+ return ToolMessage(
+ content=content,
+ tool_call_id=dct.get("tool_call_id"),
+ additional_kwargs=additional_kwargs,
+ )
+ return ChatMessage(role=role, content=content) # type: ignore[arg-type]
+
+
+def _convert_message_to_dict(message: BaseMessage) -> Dict[str, Any]:
+ """Convert a LangChain message to a dictionary.
+
+ Args:
+ message: The LangChain message.
+
+ Returns:
+ The dictionary.
+ """
+ message_dict: Dict[str, Any]
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ elif isinstance(message, ToolMessage):
+ message_dict = {
+ "role": "tool",
+ "content": message.content,
+ "tool_call_id": message.tool_call_id,
+ "name": message.name or message.additional_kwargs.get("name"),
+ }
+ else:
+ raise TypeError(f"Got unknown type '{message.__class__.__name__}'.")
+ return message_dict
+
+
+def _convert_delta_to_message_chunk(
+ dct: Dict[str, Any], default_class: Type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ role = dct.get("role")
+ content = dct.get("content", "")
+ additional_kwargs = {}
+ tool_calls = dct.get("tool_calls", None)
+ if tool_calls is not None:
+ additional_kwargs["tool_calls"] = tool_calls
+
+ if role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ if role == "assistant" or default_class == AIMessageChunk:
+ return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)
+ if role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+def _truncate_params(payload: Dict[str, Any]) -> None:
+ """Truncate temperature and top_p parameters between [0.01, 0.99].
+
+ ZhipuAI only support temperature / top_p between (0, 1) open interval,
+ so we truncate them to [0.01, 0.99].
+ """
+ temperature = payload.get("temperature")
+ top_p = payload.get("top_p")
+ if temperature is not None:
+ payload["temperature"] = max(0.01, min(0.99, temperature))
+ if top_p is not None:
+ payload["top_p"] = max(0.01, min(0.99, top_p))
+
+
+class ChatZhipuAI(BaseChatModel):
+ """ZhipuAI chat model integration.
+
+ Setup:
+ Install ``PyJWT`` and set environment variable ``ZHIPUAI_API_KEY``
+
+ .. code-block:: bash
+
+ pip install pyjwt
+ export ZHIPUAI_API_KEY="your-api-key"
+
+ Key init args — completion params:
+ model: Optional[str]
+ Name of ZhipuAI model to use.
+ temperature: float
+ Sampling temperature.
+ max_tokens: Optional[int]
+ Max number of tokens to generate.
+
+ Key init args — client params:
+ api_key: Optional[str]
+ ZhipuAI API key. If not passed in will be read from env var ZHIPUAI_API_KEY.
+ api_base: Optional[str]
+ Base URL for API requests.
+
+ See full list of supported init args and their descriptions in the params section.
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatZhipuAI
+
+ zhipuai_chat = ChatZhipuAI(
+ temperature=0.5,
+ api_key="your-api-key",
+ model="glm-4",
+ # api_base="...",
+ # other params...
+ )
+
+ Invoke:
+ .. code-block:: python
+
+ messages = [
+ ("system", "你是一名专业的翻译家,可以将用户的中文翻译为英文。"),
+ ("human", "我喜欢编程。"),
+ ]
+ zhipuai_chat.invoke(messages)
+
+ .. code-block:: python
+
+ AIMessage(content='I enjoy programming.', response_metadata={'token_usage': {'completion_tokens': 6, 'prompt_tokens': 23, 'total_tokens': 29}, 'model_name': 'glm-4', 'finish_reason': 'stop'}, id='run-c5d9af91-55c6-470e-9545-02b2fa0d7f9d-0')
+
+ Stream:
+ .. code-block:: python
+
+ for chunk in zhipuai_chat.stream(messages):
+ print(chunk)
+
+ .. code-block:: python
+
+ content='I' id='run-4df71729-618f-4e2b-a4ff-884682723082'
+ content=' enjoy' id='run-4df71729-618f-4e2b-a4ff-884682723082'
+ content=' programming' id='run-4df71729-618f-4e2b-a4ff-884682723082'
+ content='.' id='run-4df71729-618f-4e2b-a4ff-884682723082'
+ content='' response_metadata={'finish_reason': 'stop'} id='run-4df71729-618f-4e2b-a4ff-884682723082'
+
+ .. code-block:: python
+
+ stream = zhipuai_chat.stream(messages)
+ full = next(stream)
+ for chunk in stream:
+ full += chunk
+ full
+
+ .. code-block::
+
+ AIMessageChunk(content='I enjoy programming.', response_metadata={'finish_reason': 'stop'}, id='run-20b05040-a0b4-4715-8fdc-b39dba9bfb53')
+
+ Async:
+ .. code-block:: python
+
+ await zhipuai_chat.ainvoke(messages)
+
+ # stream:
+ # async for chunk in zhipuai_chat.astream(messages):
+ # print(chunk)
+
+ # batch:
+ # await zhipuai_chat.abatch([messages])
+
+ .. code-block:: python
+
+ [AIMessage(content='I enjoy programming.', response_metadata={'token_usage': {'completion_tokens': 6, 'prompt_tokens': 23, 'total_tokens': 29}, 'model_name': 'glm-4', 'finish_reason': 'stop'}, id='run-ba06af9d-4baa-40b2-9298-be9c62aa0849-0')]
+
+ Tool calling:
+ .. code-block:: python
+
+ 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"
+ )
+
+
+ class GetPopulation(BaseModel):
+ '''Get the current population in a given location'''
+
+ location: str = Field(
+ ..., description="The city and state, e.g. San Francisco, CA"
+ )
+
+ chat_with_tools = zhipuai_chat.bind_tools([GetWeather, GetPopulation])
+ ai_msg = chat_with_tools.invoke(
+ "Which city is hotter today and which is bigger: LA or NY?"
+ )
+ ai_msg.tool_calls
+
+ .. code-block:: python
+
+ [
+ {
+ 'name': 'GetWeather',
+ 'args': {'location': 'Los Angeles, CA'},
+ 'id': 'call_202408222146464ea49ec8731145a9',
+ 'type': 'tool_call'
+ }
+ ]
+
+ Structured output:
+ .. code-block:: python
+
+ from typing import Optional
+
+ from pydantic import BaseModel, Field
+
+
+ class Joke(BaseModel):
+ '''Joke to tell user.'''
+
+ setup: str = Field(description="The setup of the joke")
+ punchline: str = Field(description="The punchline to the joke")
+ rating: Optional[int] = Field(description="How funny the joke is, from 1 to 10")
+
+
+ structured_chat = zhipuai_chat.with_structured_output(Joke)
+ structured_chat.invoke("Tell me a joke about cats")
+
+ .. code-block:: python
+
+ Joke(setup='What do cats like to eat for breakfast?', punchline='Mice Krispies!', rating=None)
+
+ Response metadata
+ .. code-block:: python
+
+ ai_msg = zhipuai_chat.invoke(messages)
+ ai_msg.response_metadata
+
+ .. code-block:: python
+
+ {'token_usage': {'completion_tokens': 6,
+ 'prompt_tokens': 23,
+ 'total_tokens': 29},
+ 'model_name': 'glm-4',
+ 'finish_reason': 'stop'}
+
+ """ # noqa: E501
+
+ @property
+ def lc_secrets(self) -> Dict[str, str]:
+ return {"zhipuai_api_key": "ZHIPUAI_API_KEY"}
+
+ @classmethod
+ def get_lc_namespace(cls) -> List[str]:
+ """Get the namespace of the langchain object."""
+ return ["langchain", "chat_models", "zhipuai"]
+
+ @property
+ def lc_attributes(self) -> Dict[str, Any]:
+ attributes: Dict[str, Any] = {}
+
+ if self.zhipuai_api_base:
+ attributes["zhipuai_api_base"] = self.zhipuai_api_base
+
+ return attributes
+
+ @property
+ def _llm_type(self) -> str:
+ """Return the type of chat model."""
+ return "zhipuai-chat"
+
+ @property
+ def _default_params(self) -> Dict[str, Any]:
+ """Get the default parameters for calling OpenAI API."""
+ params = {
+ "model": self.model_name,
+ "stream": self.streaming,
+ "temperature": self.temperature,
+ }
+ if self.max_tokens is not None:
+ params["max_tokens"] = self.max_tokens
+ return params
+
+ # client:
+ zhipuai_api_key: Optional[str] = Field(default=None, alias="api_key")
+ """Automatically inferred from env var `ZHIPUAI_API_KEY` if not provided."""
+ zhipuai_api_base: Optional[str] = Field(default=None, alias="api_base")
+ """Base URL path for API requests, leave blank if not using a proxy or service
+ emulator.
+ """
+
+ model_name: Optional[str] = Field(default="glm-4", alias="model")
+ """
+ Model name to use, see 'https://open.bigmodel.cn/dev/api#language'.
+ Alternatively, you can use any fine-tuned model from the GLM series.
+ """
+
+ temperature: float = 0.95
+ """
+ What sampling temperature to use. The value ranges from 0.0 to 1.0 and cannot
+ be equal to 0.
+ The larger the value, the more random and creative the output; The smaller
+ the value, the more stable or certain the output will be.
+ You are advised to adjust top_p or temperature parameters based on application
+ scenarios, but do not adjust the two parameters at the same time.
+ """
+
+ top_p: float = 0.7
+ """
+ Another method of sampling temperature is called nuclear sampling. The value
+ ranges from 0.0 to 1.0 and cannot be equal to 0 or 1.
+ The model considers the results with top_p probability quality tokens.
+ For example, 0.1 means that the model decoder only considers tokens from the
+ top 10% probability of the candidate set.
+ You are advised to adjust top_p or temperature parameters based on application
+ scenarios, but do not adjust the two parameters at the same time.
+ """
+
+ streaming: bool = False
+ """Whether to stream the results or not."""
+ max_tokens: Optional[int] = None
+ """Maximum number of tokens to generate."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict[str, Any]) -> Any:
+ values["zhipuai_api_key"] = get_from_dict_or_env(
+ values, ["zhipuai_api_key", "api_key"], "ZHIPUAI_API_KEY"
+ )
+ values["zhipuai_api_base"] = get_from_dict_or_env(
+ values, "zhipuai_api_base", "ZHIPUAI_API_BASE", default=ZHIPUAI_API_BASE
+ )
+
+ return values
+
+ def _create_message_dicts(
+ self, messages: List[BaseMessage], stop: Optional[List[str]]
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
+ params = self._default_params
+ if stop is not None:
+ params["stop"] = stop
+ message_dicts = [_convert_message_to_dict(m) for m in messages]
+ return message_dicts, params
+
+ def _create_chat_result(self, response: Union[dict, BaseModel]) -> ChatResult:
+ generations = []
+ if not isinstance(response, dict):
+ response = response.dict()
+ for res in response["choices"]:
+ message = _convert_dict_to_message(res["message"])
+ generation_info = dict(finish_reason=res.get("finish_reason"))
+ generations.append(
+ ChatGeneration(message=message, generation_info=generation_info)
+ )
+ token_usage = response.get("usage", {})
+ llm_output = {
+ "token_usage": token_usage,
+ "model_name": self.model_name,
+ }
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ def _generate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate a chat response."""
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+
+ if self.zhipuai_api_key is None:
+ raise ValueError("Did not find zhipuai_api_key.")
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ payload = {
+ **params,
+ **kwargs,
+ "messages": message_dicts,
+ "stream": False,
+ }
+ _truncate_params(payload)
+ headers = {
+ "Authorization": _get_jwt_token(self.zhipuai_api_key),
+ "Accept": "application/json",
+ }
+ import httpx
+
+ with httpx.Client(headers=headers, timeout=60) as client:
+ response = client.post(self.zhipuai_api_base, json=payload) # type: ignore[arg-type]
+ response.raise_for_status()
+ return self._create_chat_result(response.json())
+
+ def _stream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ """Stream the chat response in chunks."""
+ if self.zhipuai_api_key is None:
+ raise ValueError("Did not find zhipuai_api_key.")
+ if self.zhipuai_api_base is None:
+ raise ValueError("Did not find zhipu_api_base.")
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ payload = {**params, **kwargs, "messages": message_dicts, "stream": True}
+ _truncate_params(payload)
+ headers = {
+ "Authorization": _get_jwt_token(self.zhipuai_api_key),
+ "Accept": "application/json",
+ }
+
+ default_chunk_class = AIMessageChunk
+ import httpx
+
+ with httpx.Client(headers=headers, timeout=60) as client:
+ with connect_sse(
+ client, "POST", self.zhipuai_api_base, json=payload
+ ) as event_source:
+ for sse in event_source.iter_sse():
+ chunk = json.loads(sse.data)
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ usage = chunk.get("usage", None)
+ model_name = chunk.get("model", "")
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], default_chunk_class
+ )
+ finish_reason = choice.get("finish_reason", None)
+
+ generation_info = (
+ {
+ "finish_reason": finish_reason,
+ "token_usage": usage,
+ "model_name": model_name,
+ }
+ if finish_reason is not None
+ else None
+ )
+ chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+
+ if finish_reason is not None:
+ break
+
+ async def _agenerate(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ stream: Optional[bool] = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+
+ if self.zhipuai_api_key is None:
+ raise ValueError("Did not find zhipuai_api_key.")
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ payload = {
+ **params,
+ **kwargs,
+ "messages": message_dicts,
+ "stream": False,
+ }
+ _truncate_params(payload)
+ headers = {
+ "Authorization": _get_jwt_token(self.zhipuai_api_key),
+ "Accept": "application/json",
+ }
+ import httpx
+
+ async with httpx.AsyncClient(headers=headers, timeout=60) as client:
+ response = await client.post(self.zhipuai_api_base, json=payload) # type: ignore[arg-type]
+ response.raise_for_status()
+ return self._create_chat_result(response.json())
+
+ async def _astream(
+ self,
+ messages: List[BaseMessage],
+ stop: Optional[List[str]] = None,
+ run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ if self.zhipuai_api_key is None:
+ raise ValueError("Did not find zhipuai_api_key.")
+ if self.zhipuai_api_base is None:
+ raise ValueError("Did not find zhipu_api_base.")
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ payload = {**params, **kwargs, "messages": message_dicts, "stream": True}
+ _truncate_params(payload)
+ headers = {
+ "Authorization": _get_jwt_token(self.zhipuai_api_key),
+ "Accept": "application/json",
+ }
+
+ default_chunk_class = AIMessageChunk
+ import httpx
+
+ async with httpx.AsyncClient(headers=headers, timeout=60) as client:
+ async with aconnect_sse(
+ client, "POST", self.zhipuai_api_base, json=payload
+ ) as event_source:
+ async for sse in event_source.aiter_sse():
+ chunk = json.loads(sse.data)
+ if len(chunk["choices"]) == 0:
+ continue
+ choice = chunk["choices"][0]
+ usage = chunk.get("usage", None)
+ model_name = chunk.get("model", "")
+ chunk = _convert_delta_to_message_chunk(
+ choice["delta"], default_chunk_class
+ )
+ finish_reason = choice.get("finish_reason", None)
+
+ generation_info = (
+ {
+ "finish_reason": finish_reason,
+ "token_usage": usage,
+ "model_name": model_name,
+ }
+ if finish_reason is not None
+ else None
+ )
+ chunk = ChatGenerationChunk(
+ message=chunk, generation_info=generation_info
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+ yield chunk
+
+ if finish_reason is not None:
+ break
+
+ def bind_tools(
+ self,
+ tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]],
+ *,
+ tool_choice: Optional[
+ Union[dict, str, Literal["auto", "any", "none"], bool]
+ ] = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model.
+ Args:
+ tools: A list of tool definitions to bind to this chat model.
+ Can be a dictionary, pydantic model, callable, or BaseTool. Pydantic
+ models, callables, and BaseTools will be automatically converted to
+ their schema dictionary representation.
+ tool_choice: Currently this can only be auto for this chat model.
+ **kwargs: Any additional parameters to pass to the
+ :class:`~langchain.runnable.Runnable` constructor.
+ """
+ if self.model_name == "glm-4v":
+ raise ValueError("glm-4v currently does not support tool calling")
+
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ if tool_choice and tool_choice != "auto":
+ raise ValueError("ChatZhipuAI currently only supports `auto` tool choice")
+ elif tool_choice and tool_choice == "auto":
+ kwargs["tool_choice"] = tool_choice
+ return self.bind(tools=formatted_tools, **kwargs)
+
+ def with_structured_output(
+ self,
+ schema: Optional[Union[Dict, Type[BaseModel]]] = None,
+ *,
+ method: Literal["function_calling", "json_mode"] = "function_calling",
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, Union[Dict, BaseModel]]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema: The output schema as a dict or a Pydantic class. If a Pydantic class
+ then the model output will be an object of that class. If a dict then
+ the model output will be a dict. With a Pydantic class the returned
+ attributes will be validated, whereas with a dict they will not be. If
+ `method` is "function_calling" and `schema` is a dict, then the dict
+ must match the OpenAI function-calling spec.
+ method: The method for steering model generation, either "function_calling"
+ or "json_mode". ZhipuAI only supports "function_calling" which
+ converts the schema to a OpenAI function and the model will make use of the
+ function-calling API.
+ include_raw: If False then only the parsed structured output is returned. If
+ an error occurs during model output parsing it will be raised. If True
+ then both the raw model response (a BaseMessage) and the parsed model
+ response will be returned. If an error occurs during output parsing it
+ will be caught and returned as well. The final output is always a dict
+ with keys "raw", "parsed", and "parsing_error".
+
+ Returns:
+ A Runnable that takes any ChatModel input and returns as output:
+
+ If include_raw is True then a dict with keys:
+ raw: BaseMessage
+ parsed: Optional[_DictOrPydantic]
+ parsing_error: Optional[BaseException]
+
+ If include_raw is False then just _DictOrPydantic is returned,
+ where _DictOrPydantic depends on the schema:
+
+ If schema is a Pydantic class then _DictOrPydantic is the Pydantic
+ class.
+
+ If schema is a dict then _DictOrPydantic is a dict.
+
+ Example: Function-calling, Pydantic schema (method="function_calling", include_raw=False):
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatZhipuAI
+ from pydantic import BaseModel
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+ answer: str
+ justification: str
+
+ llm = ChatZhipuAI(temperature=0)
+ structured_llm = llm.with_structured_output(AnswerWithJustification)
+
+ structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
+ # -> AnswerWithJustification(
+ # answer='A pound of bricks and a pound of feathers weigh the same.'
+ # justification="Both a pound of bricks and a pound of feathers have been defined to have the same weight. The 'pound' is a unit of weight, so any two things that are described as weighing a pound will weigh the same."
+ # )
+
+ Example: Function-calling, Pydantic schema (method="function_calling", include_raw=True):
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatZhipuAI
+ from pydantic import BaseModel
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+ answer: str
+ justification: str
+
+ llm = ChatZhipuAI(temperature=0)
+ structured_llm = llm.with_structured_output(AnswerWithJustification, include_raw=True)
+
+ structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
+ # -> {
+ # 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_01htjn3cspevxbqc1d7nkk8wab', 'function': {'arguments': '{"answer": "A pound of bricks and a pound of feathers weigh the same.", "justification": "Both a pound of bricks and a pound of feathers have been defined to have the same weight. The \'pound\' is a unit of weight, so any two things that are described as weighing a pound will weigh the same.", "unit": "pounds"}', 'name': 'AnswerWithJustification'}, 'type': 'function'}]}, id='run-456beee6-65f6-4e80-88af-a6065480822c-0'),
+ # 'parsed': AnswerWithJustification(answer='A pound of bricks and a pound of feathers weigh the same.', justification="Both a pound of bricks and a pound of feathers have been defined to have the same weight. The 'pound' is a unit of weight, so any two things that are described as weighing a pound will weigh the same."),
+ # 'parsing_error': None
+ # }
+
+ Example: Function-calling, dict schema (method="function_calling", include_raw=False):
+ .. code-block:: python
+
+ from langchain_community.chat_models import ChatZhipuAI
+ from pydantic import BaseModel
+ from langchain_core.utils.function_calling import convert_to_openai_tool
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+ answer: str
+ justification: str
+
+ dict_schema = convert_to_openai_tool(AnswerWithJustification)
+ llm = ChatZhipuAI(temperature=0)
+ structured_llm = llm.with_structured_output(dict_schema)
+
+ structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
+ # -> {
+ # 'answer': 'A pound of bricks and a pound of feathers weigh the same.',
+ # 'justification': "Both a pound of bricks and a pound of feathers have been defined to have the same weight. The 'pound' is a unit of weight, so any two things that are described as weighing a pound will weigh the same.", 'unit': 'pounds'}
+ # }
+
+ """ # noqa: E501
+ if kwargs:
+ raise ValueError(f"Received unsupported arguments {kwargs}")
+ is_pydantic_schema = _is_pydantic_class(schema)
+ if method == "function_calling":
+ if schema is None:
+ raise ValueError(
+ "schema must be specified when method is 'function_calling'. "
+ "Received None."
+ )
+ tool_name = convert_to_openai_tool(schema)["function"]["name"]
+ llm = self.bind_tools([schema], tool_choice="auto")
+ if is_pydantic_schema:
+ output_parser: OutputParserLike = PydanticToolsParser(
+ tools=[schema], # type: ignore[list-item]
+ first_tool_only=True,
+ )
+ else:
+ output_parser = JsonOutputKeyToolsParser(
+ key_name=tool_name, first_tool_only=True
+ )
+ else:
+ raise ValueError(
+ f"""Unrecognized method argument. Expected 'function_calling'.
+ Received: '{method}'"""
+ )
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ else:
+ return llm | output_parser
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..65d304ee1dfef7658388caec7dd191208bf1d824
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/__init__.py
@@ -0,0 +1,49 @@
+"""**Cross encoders** are wrappers around cross encoder models from different APIs and
+ services.
+
+**Cross encoder models** can be LLMs or not.
+
+**Class hierarchy:**
+
+.. code-block::
+
+ BaseCrossEncoder --> CrossEncoder # Examples: SagemakerEndpointCrossEncoder
+"""
+
+import importlib
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langchain_community.cross_encoders.base import (
+ BaseCrossEncoder,
+ )
+ from langchain_community.cross_encoders.fake import (
+ FakeCrossEncoder,
+ )
+ from langchain_community.cross_encoders.huggingface import (
+ HuggingFaceCrossEncoder,
+ )
+ from langchain_community.cross_encoders.sagemaker_endpoint import (
+ SagemakerEndpointCrossEncoder,
+ )
+
+__all__ = [
+ "BaseCrossEncoder",
+ "FakeCrossEncoder",
+ "HuggingFaceCrossEncoder",
+ "SagemakerEndpointCrossEncoder",
+]
+
+_module_lookup = {
+ "BaseCrossEncoder": "langchain_community.cross_encoders.base",
+ "FakeCrossEncoder": "langchain_community.cross_encoders.fake",
+ "HuggingFaceCrossEncoder": "langchain_community.cross_encoders.huggingface",
+ "SagemakerEndpointCrossEncoder": "langchain_community.cross_encoders.sagemaker_endpoint", # noqa: E501
+}
+
+
+def __getattr__(name: str) -> Any:
+ if name in _module_lookup:
+ module = importlib.import_module(_module_lookup[name])
+ return getattr(module, name)
+ raise AttributeError(f"module {__name__} has no attribute {name}")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..549e451a27a786f034566891b3e45ae773e3adcd
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/base.py
@@ -0,0 +1,5 @@
+from langchain_classic.retrievers.document_compressors.cross_encoder import (
+ BaseCrossEncoder,
+)
+
+__all__ = ["BaseCrossEncoder"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/fake.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/fake.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c38175e50f4ecdd0b2436040ae0c60397ed5d85
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/fake.py
@@ -0,0 +1,18 @@
+from difflib import SequenceMatcher
+from typing import List, Tuple
+
+from pydantic import BaseModel
+
+from langchain_community.cross_encoders.base import BaseCrossEncoder
+
+
+class FakeCrossEncoder(BaseCrossEncoder, BaseModel):
+ """Fake cross encoder model."""
+
+ def score(self, text_pairs: List[Tuple[str, str]]) -> List[float]:
+ scores = list(
+ map(
+ lambda pair: SequenceMatcher(None, pair[0], pair[1]).ratio(), text_pairs
+ )
+ )
+ return scores
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/huggingface.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/huggingface.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0d1f68a12fea9260457603db6b79a04aa0de916
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/huggingface.py
@@ -0,0 +1,64 @@
+from typing import Any, Dict, List, Tuple
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from langchain_community.cross_encoders.base import BaseCrossEncoder
+
+DEFAULT_MODEL_NAME = "BAAI/bge-reranker-base"
+
+
+class HuggingFaceCrossEncoder(BaseModel, BaseCrossEncoder):
+ """HuggingFace cross encoder models.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.cross_encoders import HuggingFaceCrossEncoder
+
+ model_name = "BAAI/bge-reranker-base"
+ model_kwargs = {'device': 'cpu'}
+ hf = HuggingFaceCrossEncoder(
+ model_name=model_name,
+ model_kwargs=model_kwargs
+ )
+ """
+
+ client: Any = None #: :meta private:
+ model_name: str = DEFAULT_MODEL_NAME
+ """Model name to use."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass to the model."""
+
+ def __init__(self, **kwargs: Any):
+ """Initialize the sentence_transformer."""
+ super().__init__(**kwargs)
+ try:
+ import sentence_transformers
+
+ except ImportError as exc:
+ raise ImportError(
+ "Could not import sentence_transformers python package. "
+ "Please install it with `pip install sentence-transformers`."
+ ) from exc
+
+ self.client = sentence_transformers.CrossEncoder(
+ self.model_name, **self.model_kwargs
+ )
+
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
+
+ def score(self, text_pairs: List[Tuple[str, str]]) -> List[float]:
+ """Compute similarity scores using a HuggingFace transformer model.
+
+ Args:
+ text_pairs: The list of text text_pairs to score the similarity.
+
+ Returns:
+ List of scores, one for each pair.
+ """
+ scores = self.client.predict(text_pairs)
+ # Some models e.g bert-multilingual-passage-reranking-msmarco
+ # gives two score not_relevant and relevant as compare with the query.
+ if len(scores.shape) > 1: # we are going to get the relevant scores
+ scores = map(lambda x: x[1], scores)
+ return scores
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/sagemaker_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/sagemaker_endpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b948ef772bb59c4c5729f2680216138c0457f7b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/cross_encoders/sagemaker_endpoint.py
@@ -0,0 +1,150 @@
+import json
+from typing import Any, Dict, List, Optional, Tuple
+
+from pydantic import BaseModel, ConfigDict, model_validator
+
+from langchain_community.cross_encoders.base import BaseCrossEncoder
+
+
+class CrossEncoderContentHandler:
+ """Content handler for CrossEncoder class."""
+
+ content_type = "application/json"
+ accepts = "application/json"
+
+ def transform_input(self, text_pairs: List[Tuple[str, str]]) -> bytes:
+ input_str = json.dumps({"text_pairs": text_pairs})
+ return input_str.encode("utf-8")
+
+ def transform_output(self, output: Any) -> List[float]:
+ response_json = json.loads(output.read().decode("utf-8"))
+ scores = response_json["scores"]
+ return scores
+
+
+class SagemakerEndpointCrossEncoder(BaseModel, BaseCrossEncoder):
+ """SageMaker Inference CrossEncoder endpoint.
+
+ To use, you must supply the endpoint name from your deployed
+ Sagemaker model & the region where it is deployed.
+
+ To authenticate, the AWS client uses the following methods to
+ automatically load credentials:
+ https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
+
+ If a specific credential profile should be used, you must pass
+ the name of the profile from the ~/.aws/credentials file that is to be used.
+
+ Make sure the credentials / roles used have the required policies to
+ access the Sagemaker endpoint.
+ See: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html
+ """
+
+ """
+ Example:
+ .. code-block:: python
+
+
+ from langchain_classic.embeddings import SagemakerEndpointCrossEncoder
+ endpoint_name = (
+ "my-endpoint-name"
+ )
+ region_name = (
+ "us-west-2"
+ )
+ credentials_profile_name = (
+ "default"
+ )
+ se = SagemakerEndpointCrossEncoder(
+ endpoint_name=endpoint_name,
+ region_name=region_name,
+ credentials_profile_name=credentials_profile_name
+ )
+ """
+ client: Any = None #: :meta private:
+
+ endpoint_name: str = ""
+ """The name of the endpoint from the deployed Sagemaker model.
+ Must be unique within an AWS Region."""
+
+ region_name: str = ""
+ """The aws region where the Sagemaker model is deployed, eg. `us-west-2`."""
+
+ credentials_profile_name: Optional[str] = None
+ """The name of the profile in the ~/.aws/credentials or ~/.aws/config files, which
+ has either access keys or role information specified.
+ If not specified, the default credential profile or, if on an EC2 instance,
+ credentials from IMDS will be used.
+ See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
+ """
+
+ content_handler: CrossEncoderContentHandler = CrossEncoderContentHandler()
+
+ model_kwargs: Optional[Dict] = None
+ """Keyword arguments to pass to the model."""
+
+ endpoint_kwargs: Optional[Dict] = None
+ """Optional attributes passed to the invoke_endpoint
+ function. See `boto3`_. docs for more info.
+ .. _boto3:
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True, extra="forbid", protected_namespaces=()
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that AWS credentials to and python package exists in environment."""
+ try:
+ import boto3
+
+ try:
+ if values.get("credentials_profile_name"):
+ session = boto3.Session(
+ profile_name=values["credentials_profile_name"]
+ )
+ else:
+ # use default credentials
+ session = boto3.Session()
+
+ values["client"] = session.client(
+ "sagemaker-runtime", region_name=values["region_name"]
+ )
+
+ except Exception as e:
+ raise ValueError(
+ "Could not load credentials to authenticate with AWS client. "
+ "Please check that credentials in the specified "
+ "profile name are valid."
+ ) from e
+
+ except ImportError:
+ raise ImportError(
+ "Could not import boto3 python package. "
+ "Please install it with `pip install boto3`."
+ )
+ return values
+
+ def score(self, text_pairs: List[Tuple[str, str]]) -> List[float]:
+ """Call out to SageMaker Inference CrossEncoder endpoint."""
+ _endpoint_kwargs = self.endpoint_kwargs or {}
+
+ body = self.content_handler.transform_input(text_pairs)
+ content_type = self.content_handler.content_type
+ accepts = self.content_handler.accepts
+
+ # send request
+ try:
+ response = self.client.invoke_endpoint(
+ EndpointName=self.endpoint_name,
+ Body=body,
+ ContentType=content_type,
+ Accept=accepts,
+ **_endpoint_kwargs,
+ )
+ except Exception as e:
+ raise ValueError(f"Error raised by inference endpoint: {e}")
+
+ return self.content_handler.transform_output(response["Body"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea98f747acc95bbdaa91890731b8aa6a6fdcd3a3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/__init__.py
@@ -0,0 +1,46 @@
+"""**Docstores** are classes to store and load Documents.
+
+The **Docstore** is a simplified version of the Document Loader.
+
+**Class hierarchy:**
+
+.. code-block::
+
+ Docstore --> # Examples: InMemoryDocstore, Wikipedia
+
+**Main helpers:**
+
+.. code-block::
+
+ Document, AddableMixin
+"""
+
+import importlib
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langchain_community.docstore.arbitrary_fn import (
+ DocstoreFn,
+ )
+ from langchain_community.docstore.in_memory import (
+ InMemoryDocstore,
+ )
+ from langchain_community.docstore.wikipedia import (
+ Wikipedia,
+ )
+
+_module_lookup = {
+ "DocstoreFn": "langchain_community.docstore.arbitrary_fn",
+ "InMemoryDocstore": "langchain_community.docstore.in_memory",
+ "Wikipedia": "langchain_community.docstore.wikipedia",
+}
+
+
+def __getattr__(name: str) -> Any:
+ if name in _module_lookup:
+ module = importlib.import_module(_module_lookup[name])
+ return getattr(module, name)
+ raise AttributeError(f"module {__name__} has no attribute {name}")
+
+
+__all__ = ["DocstoreFn", "InMemoryDocstore", "Wikipedia"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/arbitrary_fn.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/arbitrary_fn.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2eba5ddafda3c2ef5209228e705af3ea164fc88
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/arbitrary_fn.py
@@ -0,0 +1,38 @@
+from typing import Callable, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.docstore.base import Docstore
+
+
+class DocstoreFn(Docstore):
+ """Docstore via arbitrary lookup function.
+
+ This is useful when:
+ * it's expensive to construct an InMemoryDocstore/dict
+ * you retrieve documents from remote sources
+ * you just want to reuse existing objects
+ """
+
+ def __init__(
+ self,
+ lookup_fn: Callable[[str], Union[Document, str]],
+ ):
+ self._lookup_fn = lookup_fn
+
+ def search(self, search: str) -> Document:
+ """Search for a document.
+
+ Args:
+ search: search string
+
+ Returns:
+ Document if found, else error message.
+ """
+ r = self._lookup_fn(search)
+ if isinstance(r, str):
+ # NOTE: assume the search string is the source ID
+ return Document(page_content=r, metadata={"source": search})
+ elif isinstance(r, Document):
+ return r
+ raise ValueError(f"Unexpected type of document {type(r)}")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..da479827f39a6e504507078e496009a46fd42145
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/base.py
@@ -0,0 +1,30 @@
+"""Interface to access to place that stores documents."""
+
+from abc import ABC, abstractmethod
+from typing import Dict, List, Union
+
+from langchain_core.documents import Document
+
+
+class Docstore(ABC):
+ """Interface to access to place that stores documents."""
+
+ @abstractmethod
+ def search(self, search: str) -> Union[str, Document]:
+ """Search for document.
+
+ If page exists, return the page summary, and a Document object.
+ If page does not exist, return similar entries.
+ """
+
+ def delete(self, ids: List) -> None:
+ """Deleting IDs from in memory dictionary."""
+ raise NotImplementedError
+
+
+class AddableMixin(ABC):
+ """Mixin class that supports adding texts."""
+
+ @abstractmethod
+ def add(self, texts: Dict[str, Document]) -> None:
+ """Add more documents."""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/document.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/document.py
new file mode 100644
index 0000000000000000000000000000000000000000..88aebd279509aa19084281e0a84e647ee39b1849
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/document.py
@@ -0,0 +1,3 @@
+from langchain_core.documents import Document
+
+__all__ = ["Document"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/in_memory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/in_memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..60f0c24fa3ab6f544dbfbb8bb0a511f10bfc839a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/in_memory.py
@@ -0,0 +1,51 @@
+"""Simple in memory docstore in the form of a dict."""
+
+from typing import Dict, List, Optional, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.docstore.base import AddableMixin, Docstore
+
+
+class InMemoryDocstore(Docstore, AddableMixin):
+ """Simple in memory docstore in the form of a dict."""
+
+ def __init__(self, _dict: Optional[Dict[str, Document]] = None):
+ """Initialize with dict."""
+ self._dict = _dict if _dict is not None else {}
+
+ def add(self, texts: Dict[str, Document]) -> None:
+ """Add texts to in memory dictionary.
+
+ Args:
+ texts: dictionary of id -> document.
+
+ Returns:
+ None
+ """
+ overlapping = set(texts).intersection(self._dict)
+ if overlapping:
+ raise ValueError(f"Tried to add ids that already exist: {overlapping}")
+ self._dict = {**self._dict, **texts}
+
+ def delete(self, ids: List) -> None:
+ """Deleting IDs from in memory dictionary."""
+ overlapping = set(ids).intersection(self._dict)
+ if not overlapping:
+ raise ValueError(f"Tried to delete ids that does not exist: {ids}")
+ for _id in ids:
+ self._dict.pop(_id)
+
+ def search(self, search: str) -> Union[str, Document]:
+ """Search via direct lookup.
+
+ Args:
+ search: id of a document to search for.
+
+ Returns:
+ Document if found, else error message.
+ """
+ if search not in self._dict:
+ return f"ID {search} not found."
+ else:
+ return self._dict[search]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/wikipedia.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/wikipedia.py
new file mode 100644
index 0000000000000000000000000000000000000000..20146e84f2139bb9432e062f3d481422287bbe64
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/docstore/wikipedia.py
@@ -0,0 +1,46 @@
+"""Wrapper around wikipedia API."""
+
+from typing import Union
+
+from langchain_core.documents import Document
+
+from langchain_community.docstore.base import Docstore
+
+
+class Wikipedia(Docstore):
+ """Wikipedia API."""
+
+ def __init__(self) -> None:
+ """Check that wikipedia package is installed."""
+ try:
+ import wikipedia # noqa: F401
+ except ImportError:
+ raise ImportError(
+ "Could not import wikipedia python package. "
+ "Please install it with `pip install wikipedia`."
+ )
+
+ def search(self, search: str) -> Union[str, Document]:
+ """Try to search for wiki page.
+
+ If page exists, return the page summary, and a PageWithLookups object.
+ If page does not exist, return similar entries.
+
+ Args:
+ search: search string.
+
+ Returns: a Document object or error message.
+ """
+ import wikipedia
+
+ try:
+ page_content = wikipedia.page(search).content
+ url = wikipedia.page(search).url
+ result: Union[str, Document] = Document(
+ page_content=page_content, metadata={"page": url}
+ )
+ except wikipedia.PageError:
+ result = f"Could not find [{search}]. Similar: {wikipedia.search(search)}"
+ except wikipedia.DisambiguationError:
+ result = f"Could not find [{search}]. Similar: {wikipedia.search(search)}"
+ return result
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b26bf579d487c097d75062d4d33acbfc4a94d8df
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/__init__.py
@@ -0,0 +1,58 @@
+import importlib
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langchain_community.document_compressors.dashscope_rerank import (
+ DashScopeRerank,
+ )
+ from langchain_community.document_compressors.flashrank_rerank import (
+ FlashrankRerank,
+ )
+ from langchain_community.document_compressors.infinity_rerank import (
+ InfinityRerank,
+ )
+ from langchain_community.document_compressors.jina_rerank import (
+ JinaRerank,
+ )
+ from langchain_community.document_compressors.llmlingua_filter import (
+ LLMLinguaCompressor,
+ )
+ from langchain_community.document_compressors.openvino_rerank import (
+ OpenVINOReranker,
+ )
+ from langchain_community.document_compressors.rankllm_rerank import (
+ RankLLMRerank,
+ )
+ from langchain_community.document_compressors.volcengine_rerank import (
+ VolcengineRerank,
+ )
+
+_module_lookup = {
+ "LLMLinguaCompressor": "langchain_community.document_compressors.llmlingua_filter",
+ "OpenVINOReranker": "langchain_community.document_compressors.openvino_rerank",
+ "JinaRerank": "langchain_community.document_compressors.jina_rerank",
+ "RankLLMRerank": "langchain_community.document_compressors.rankllm_rerank",
+ "FlashrankRerank": "langchain_community.document_compressors.flashrank_rerank",
+ "DashScopeRerank": "langchain_community.document_compressors.dashscope_rerank",
+ "VolcengineRerank": "langchain_community.document_compressors.volcengine_rerank",
+ "InfinityRerank": "langchain_community.document_compressors.infinity_rerank",
+}
+
+
+def __getattr__(name: str) -> Any:
+ if name in _module_lookup:
+ module = importlib.import_module(_module_lookup[name])
+ return getattr(module, name)
+ raise AttributeError(f"module {__name__} has no attribute {name}")
+
+
+__all__ = [
+ "LLMLinguaCompressor",
+ "OpenVINOReranker",
+ "FlashrankRerank",
+ "JinaRerank",
+ "RankLLMRerank",
+ "DashScopeRerank",
+ "VolcengineRerank",
+ "InfinityRerank",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/dashscope_rerank.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/dashscope_rerank.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc77ec95457126117892592d5ff798a6488a1eac
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/dashscope_rerank.py
@@ -0,0 +1,122 @@
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import Any, Dict, List, Optional, Sequence, Union
+
+from langchain_core.callbacks.base import Callbacks
+from langchain_core.documents import BaseDocumentCompressor, Document
+from langchain_core.utils import get_from_dict_or_env
+from pydantic import ConfigDict, Field, model_validator
+
+
+class DashScopeRerank(BaseDocumentCompressor):
+ """Document compressor that uses `DashScope Rerank API`."""
+
+ client: Any = None
+ """DashScope client to use for compressing documents."""
+
+ model: Optional[str] = None
+ """Model to use for reranking."""
+
+ top_n: Optional[int] = 3
+ """Number of documents to return."""
+
+ dashscope_api_key: Optional[str] = Field(None, alias="api_key")
+ """DashScope API key. Must be specified directly or via environment variable
+ DASHSCOPE_API_KEY."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+
+ if not values.get("client"):
+ try:
+ import dashscope
+ except ImportError:
+ raise ImportError(
+ "Could not import dashscope python package. "
+ "Please install it with `pip install dashscope`."
+ )
+
+ values["client"] = dashscope.TextReRank
+ values["dashscope_api_key"] = get_from_dict_or_env(
+ values, "dashscope_api_key", "DASHSCOPE_API_KEY"
+ )
+ values["model"] = dashscope.TextReRank.Models.gte_rerank
+
+ return values
+
+ def rerank(
+ self,
+ documents: Sequence[Union[str, Document, dict]],
+ query: str,
+ *,
+ top_n: Optional[int] = -1,
+ ) -> List[Dict[str, Any]]:
+ """Returns an ordered list of documents ordered by their relevance to the provided query.
+
+ Args:
+ query: The query to use for reranking.
+ documents: A sequence of documents to rerank.
+ top_n : The number of results to return. If None returns all results.
+ Defaults to self.top_n.
+ """ # noqa: E501
+
+ if len(documents) == 0: # to avoid empty api call
+ return []
+ docs = [
+ doc.page_content if isinstance(doc, Document) else doc for doc in documents
+ ]
+
+ top_n = top_n if (top_n is None or top_n > 0) else self.top_n
+
+ results = self.client.call(
+ model=self.model,
+ query=query,
+ documents=docs,
+ top_n=top_n,
+ return_documents=False,
+ api_key=self.dashscope_api_key,
+ )
+
+ result_dicts = []
+ for res in results.output.results:
+ result_dicts.append(
+ {
+ "index": res.index,
+ "relevance_score": res.relevance_score,
+ }
+ )
+ return result_dicts
+
+ def compress_documents(
+ self,
+ documents: Sequence[Document],
+ query: str,
+ callbacks: Optional[Callbacks] = None,
+ ) -> Sequence[Document]:
+ """
+ Compress documents using DashScope's rerank API.
+
+ Args:
+ documents: A sequence of documents to compress.
+ query: The query to use for compressing the documents.
+ callbacks: Callbacks to run during the compression process.
+
+ Returns:
+ A sequence of compressed documents.
+ """
+ compressed = []
+ for res in self.rerank(documents, query):
+ doc = documents[res["index"]]
+ doc_copy = Document(doc.page_content, metadata=deepcopy(doc.metadata))
+ doc_copy.metadata["relevance_score"] = res["relevance_score"]
+ compressed.append(doc_copy)
+ return compressed
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/flashrank_rerank.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/flashrank_rerank.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b8e116fd72acc477935d5eed74c63c49778592c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/flashrank_rerank.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence
+
+from langchain_core.callbacks.manager import Callbacks
+from langchain_core.documents import BaseDocumentCompressor, Document
+from pydantic import ConfigDict, model_validator
+
+if TYPE_CHECKING:
+ from flashrank import Ranker, RerankRequest
+else:
+ # Avoid pydantic annotation issues when actually instantiating
+ # while keeping this import optional
+ try:
+ from flashrank import Ranker, RerankRequest
+ except ImportError:
+ pass
+
+DEFAULT_MODEL_NAME = "ms-marco-MultiBERT-L-12"
+
+
+class FlashrankRerank(BaseDocumentCompressor):
+ """Document compressor using Flashrank interface."""
+
+ client: Ranker
+ """Flashrank client to use for compressing documents"""
+ top_n: int = 3
+ """Number of documents to return."""
+ score_threshold: float = 0.0
+ """Minimum relevance threshold to return."""
+ model: Optional[str] = None
+ """Model to use for reranking."""
+ prefix_metadata: str = ""
+ """Prefix for flashrank_rerank metadata keys"""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+ if "client" in values:
+ return values
+ else:
+ try:
+ from flashrank import Ranker
+ except ImportError:
+ raise ImportError(
+ "Could not import flashrank python package. "
+ "Please install it with `pip install flashrank`."
+ )
+
+ values["model"] = values.get("model", DEFAULT_MODEL_NAME)
+ values["client"] = Ranker(model_name=values["model"])
+ return values
+
+ def compress_documents(
+ self,
+ documents: Sequence[Document],
+ query: str,
+ callbacks: Optional[Callbacks] = None,
+ ) -> Sequence[Document]:
+ passages = [
+ {"id": i, "text": doc.page_content, "meta": doc.metadata}
+ for i, doc in enumerate(documents)
+ ]
+
+ rerank_request = RerankRequest(query=query, passages=passages)
+ rerank_response = self.client.rerank(rerank_request)[: self.top_n]
+ final_results = []
+
+ for r in rerank_response:
+ if r["score"] >= self.score_threshold:
+ doc = Document(
+ page_content=r["text"],
+ metadata={
+ self.prefix_metadata + "id": r["id"],
+ self.prefix_metadata + "relevance_score": r["score"],
+ **r["meta"],
+ },
+ )
+ final_results.append(doc)
+ return final_results
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/infinity_rerank.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/infinity_rerank.py
new file mode 100644
index 0000000000000000000000000000000000000000..407dd8ecb6cfc4424e5acf968e4b8c25bf2f048c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/infinity_rerank.py
@@ -0,0 +1,140 @@
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union
+
+from langchain_classic.retrievers.document_compressors.base import (
+ BaseDocumentCompressor,
+)
+from langchain_core.callbacks.manager import Callbacks
+from langchain_core.documents import Document
+from pydantic import ConfigDict, model_validator
+
+if TYPE_CHECKING:
+ from infinity_client.api.default import rerank
+ from infinity_client.client import Client
+ from infinity_client.models import RerankInput
+else:
+ # Avoid pydantic annotation issues when actually instantiating
+ # while keeping this import optional
+ try:
+ from infinity_client.api.default import rerank
+ from infinity_client.client import Client
+ from infinity_client.models import RerankInput
+ except ImportError:
+ pass
+
+DEFAULT_MODEL_NAME = "BAAI/bge-reranker-base"
+DEFAULT_BASE_URL = "http://localhost:7997"
+
+
+class InfinityRerank(BaseDocumentCompressor):
+ """Document compressor that uses `Infinity Rerank API`."""
+
+ client: Optional[Client] = None
+ """Infinity client to use for compressing documents."""
+
+ model: Optional[str] = None
+ """Model to use for reranking."""
+
+ top_n: Optional[int] = 3
+ """Number of documents to return."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that python package exists in environment."""
+ if "client" in values:
+ return values
+ else:
+ try:
+ from infinity_client.client import Client
+ except ImportError:
+ raise ImportError(
+ "Could not import infinity_client python package. "
+ "Please install it with `pip install infinity_client`."
+ )
+
+ values["model"] = values.get("model", DEFAULT_MODEL_NAME)
+ values["client"] = Client(base_url=DEFAULT_BASE_URL)
+ return values
+
+ def rerank(
+ self,
+ documents: Sequence[Union[str, Document, dict]],
+ query: str,
+ *,
+ model: Optional[str] = None,
+ top_n: Optional[int] = -1,
+ ) -> List[Dict[str, Any]]:
+ """Returns an ordered list of documents ordered by their relevance to the provided query.
+
+ Args:
+ query: The query to use for reranking.
+ documents: A sequence of documents to rerank.
+ model: The model to use for re-ranking. Default to self.model.
+ top_n : The number of results to return. If None returns all results.
+ Defaults to self.top_n.
+ max_chunks_per_doc : The maximum number of chunks derived from a document.
+ """ # noqa: E501
+ if len(documents) == 0: # to avoid empty api call
+ return []
+ docs = [
+ doc.page_content if isinstance(doc, Document) else doc for doc in documents
+ ]
+ model = model or self.model
+
+ input = RerankInput(
+ query=query,
+ documents=docs,
+ model=model,
+ )
+ results = rerank.sync(client=self.client, body=input)
+
+ if hasattr(results, "results"):
+ results = getattr(results, "results")
+
+ result_dicts = []
+ for res in results:
+ result_dicts.append(
+ {
+ "index": res.index,
+ "relevance_score": res.relevance_score,
+ }
+ )
+
+ result_dicts.sort(key=lambda x: x["relevance_score"], reverse=True)
+ top_n = top_n if (top_n is None or top_n > 0) else self.top_n
+
+ return result_dicts[:top_n]
+
+ def compress_documents(
+ self,
+ documents: Sequence[Document],
+ query: str,
+ callbacks: Optional[Callbacks] = None,
+ ) -> Sequence[Document]:
+ """
+ Compress documents using Infinity's rerank API.
+
+ Args:
+ documents: A sequence of documents to compress.
+ query: The query to use for compressing the documents.
+ callbacks: Callbacks to run during the compression process.
+
+ Returns:
+ A sequence of compressed documents.
+ """
+ compressed = []
+ for res in self.rerank(documents, query):
+ doc = documents[res["index"]]
+ doc_copy = Document(doc.page_content, metadata=deepcopy(doc.metadata))
+ doc_copy.metadata["relevance_score"] = res["relevance_score"]
+ compressed.append(doc_copy)
+ return compressed
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/jina_rerank.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/jina_rerank.py
new file mode 100644
index 0000000000000000000000000000000000000000..91dc7f30951c5ceb12a88a01e19986e52a2f90b1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/jina_rerank.py
@@ -0,0 +1,128 @@
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import Any, Dict, List, Optional, Sequence, Union
+
+import requests
+from langchain_core.callbacks import Callbacks
+from langchain_core.documents import BaseDocumentCompressor, Document
+from langchain_core.utils import get_from_dict_or_env
+from pydantic import ConfigDict, model_validator
+
+JINA_API_URL: str = "https://api.jina.ai/v1/rerank"
+
+
+class JinaRerank(BaseDocumentCompressor):
+ """Document compressor that uses `Jina Rerank API`."""
+
+ session: Any = None
+ """Requests session to communicate with API."""
+ top_n: Optional[int] = 3
+ """Number of documents to return."""
+ model: str = "jina-reranker-v1-base-en"
+ """Model to use for reranking."""
+ jina_api_key: Optional[str] = None
+ """Jina API key. Must be specified directly or via environment variable
+ JINA_API_KEY."""
+ user_agent: str = "langchain"
+ """Identifier for the application making the request."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key exists in environment."""
+ jina_api_key = get_from_dict_or_env(values, "jina_api_key", "JINA_API_KEY")
+ user_agent = values.get("user_agent", "langchain")
+ session = requests.Session()
+ session.headers.update(
+ {
+ "Authorization": f"Bearer {jina_api_key}",
+ "Accept-Encoding": "identity",
+ "Content-type": "application/json",
+ "user-agent": user_agent,
+ }
+ )
+ values["session"] = session
+ return values
+
+ def rerank(
+ self,
+ documents: Sequence[Union[str, Document, dict]],
+ query: str,
+ *,
+ model: Optional[str] = None,
+ top_n: Optional[int] = -1,
+ max_chunks_per_doc: Optional[int] = None,
+ ) -> List[Dict[str, Any]]:
+ """Returns an ordered list of documents ordered by their relevance to the provided query.
+
+ Args:
+ query: The query to use for reranking.
+ documents: A sequence of documents to rerank.
+ model: The model to use for re-ranking. Default to self.model.
+ top_n : The number of results to return. If None returns all results.
+ Defaults to self.top_n.
+ max_chunks_per_doc : The maximum number of chunks derived from a document.
+ """ # noqa: E501
+ if len(documents) == 0: # to avoid empty api call
+ return []
+ docs = [
+ doc.page_content if isinstance(doc, Document) else doc for doc in documents
+ ]
+ model = model or self.model
+ top_n = top_n if (top_n is None or top_n > 0) else self.top_n
+ data = {
+ "query": query,
+ "documents": docs,
+ "model": model,
+ "top_n": top_n,
+ }
+
+ resp = self.session.post(
+ JINA_API_URL,
+ json=data,
+ ).json()
+
+ if "results" not in resp:
+ raise RuntimeError(resp["detail"])
+
+ results = resp["results"]
+ result_dicts = []
+ for res in results:
+ result_dicts.append(
+ {
+ "index": res["index"],
+ "relevance_score": res["relevance_score"],
+ }
+ )
+ return result_dicts
+
+ def compress_documents(
+ self,
+ documents: Sequence[Document],
+ query: str,
+ callbacks: Optional[Callbacks] = None,
+ ) -> Sequence[Document]:
+ """
+ Compress documents using Jina's Rerank API.
+
+ Args:
+ documents: A sequence of documents to compress.
+ query: The query to use for compressing the documents.
+ callbacks: Callbacks to run during the compression process.
+
+ Returns:
+ A sequence of compressed documents.
+ """
+ compressed = []
+ for res in self.rerank(documents, query):
+ doc = documents[res["index"]]
+ doc_copy = Document(doc.page_content, metadata=deepcopy(doc.metadata))
+ doc_copy.metadata["relevance_score"] = res["relevance_score"]
+ compressed.append(doc_copy)
+ return compressed
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/llmlingua_filter.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/llmlingua_filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..8fe82901608b88eab74b1af7f909feba409c20fb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/llmlingua_filter.py
@@ -0,0 +1,187 @@
+# LLM Lingua Document Compressor
+
+import re
+from typing import Any, Dict, List, Optional, Pattern, Sequence, Tuple
+
+from langchain_core.callbacks import Callbacks
+from langchain_core.documents import Document
+from langchain_core.documents.compressor import (
+ BaseDocumentCompressor,
+)
+from pydantic import ConfigDict, Field, model_validator
+
+DEFAULT_LLM_LINGUA_INSTRUCTION = (
+ "Given this documents, please answer the final question"
+)
+
+
+class LLMLinguaCompressor(BaseDocumentCompressor):
+ """
+ Compress using LLMLingua Project.
+
+ https://github.com/microsoft/LLMLingua
+ """
+
+ # Pattern to match ref tags at the beginning or end of the string,
+ # allowing for malformed tags
+ _pattern_beginning: Pattern = re.compile(r"\A(?:<#)?(?:ref)?(\d+)(?:#>?)?")
+ _pattern_ending: Pattern = re.compile(r"(?:<#)?(?:ref)?(\d+)(?:#>?)?\Z")
+
+ model_name: str = "NousResearch/Llama-2-7b-hf"
+ """The hugging face model to use"""
+ device_map: str = "cuda"
+ """The device to use for llm lingua"""
+ target_token: int = 300
+ """The target number of compressed tokens"""
+ rank_method: str = "longllmlingua"
+ """The ranking method to use"""
+ model_configuration: dict = Field(default_factory=dict, alias="model_config")
+ """Custom configuration for the model"""
+ open_api_config: dict = Field(default_factory=dict)
+ """open_api configuration"""
+ instruction: str = DEFAULT_LLM_LINGUA_INSTRUCTION
+ """The instruction for the LLM"""
+ additional_compress_kwargs: dict = {
+ "condition_compare": True,
+ "condition_in_question": "after",
+ "context_budget": "+100",
+ "reorder_context": "sort",
+ "dynamic_context_compression_ratio": 0.4,
+ }
+ """Extra compression arguments"""
+ lingua: Any = None
+ """The instance of the llm linqua"""
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that the python package exists in environment."""
+ try:
+ from llmlingua import PromptCompressor
+ except ImportError:
+ raise ImportError(
+ "Could not import llmlingua python package. "
+ "Please install it with `pip install llmlingua`."
+ )
+ if not values.get("lingua"):
+ values["lingua"] = PromptCompressor(
+ model_name=values.get("model_name", {}),
+ device_map=values.get("device_map", {}),
+ model_config=values.get("model_config", {}),
+ open_api_config=values.get("open_api_config", {}),
+ )
+ return values
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ populate_by_name=True,
+ protected_namespaces=(),
+ )
+
+ @staticmethod
+ def _format_context(docs: Sequence[Document]) -> List[str]:
+ """
+ Format the output of the retriever by including
+ special ref tags for tracking the metadata after compression
+ """
+ formatted_docs = []
+ for i, doc in enumerate(docs):
+ content = doc.page_content.replace("\n\n", "\n")
+ doc_string = f"\n\n<#ref{i}#> {content} <#ref{i}#>\n\n"
+ formatted_docs.append(doc_string)
+ return formatted_docs
+
+ def extract_ref_id_tuples_and_clean(
+ self, contents: List[str]
+ ) -> List[Tuple[str, int]]:
+ """
+ Extracts reference IDs from the contents and cleans up the ref tags.
+
+ This function processes a list of strings, searching for reference ID tags
+ at the beginning and end of each string. When a ref tag is found, it is
+ removed from the string, and its ID is recorded. If no ref ID is found,
+ a generic ID of "-1" is assigned.
+
+ The search for ref tags is performed only at the beginning and
+ end of the string, with the assumption that there will
+ be at most one ref ID per string. Malformed ref tags are
+ handled gracefully.
+
+ Args:
+ contents (List[str]): A list of contents to be processed.
+
+ Returns:
+ List[Tuple[str, int]]: The cleaned string and the associated ref ID.
+
+ Examples:
+ >>> strings_list = [
+ '<#ref0#> Example content <#ref0#>',
+ 'Content with no ref ID.'
+ ]
+ >>> extract_ref_id_tuples_and_clean(strings_list)
+ [('Example content', 0), ('Content with no ref ID.', -1)]
+ """
+ ref_id_tuples = []
+ for content in contents:
+ clean_string = content.strip()
+ if not clean_string:
+ continue
+
+ # Search for ref tags at the beginning and the end of the string
+ ref_id = None
+ for pattern in [self._pattern_beginning, self._pattern_ending]:
+ match = pattern.search(clean_string)
+ if match:
+ ref_id = match.group(1)
+ clean_string = pattern.sub("", clean_string).strip()
+ # Convert ref ID to int or use -1 if not found
+ ref_id_to_use = int(ref_id) if ref_id and ref_id.isdigit() else -1
+ ref_id_tuples.append((clean_string, ref_id_to_use))
+
+ return ref_id_tuples
+
+ def compress_documents(
+ self,
+ documents: Sequence[Document],
+ query: str,
+ callbacks: Optional[Callbacks] = None,
+ ) -> Sequence[Document]:
+ """
+ Compress documents using BAAI/bge-reranker models.
+
+ Args:
+ documents: A sequence of documents to compress.
+ query: The query to use for compressing the documents.
+ callbacks: Callbacks to run during the compression process.
+
+ Returns:
+ A sequence of compressed documents.
+ """
+ if len(documents) == 0: # to avoid empty api call
+ return []
+
+ compressed_prompt = self.lingua.compress_prompt(
+ context=self._format_context(documents),
+ instruction=self.instruction,
+ question=query,
+ target_token=self.target_token,
+ rank_method=self.rank_method,
+ concate_question=False,
+ add_instruction=True,
+ **self.additional_compress_kwargs,
+ )
+ compreseed_context = compressed_prompt["compressed_prompt"].split("\n\n")[1:]
+
+ extracted_metadata = self.extract_ref_id_tuples_and_clean(compreseed_context)
+
+ compressed_docs: List[Document] = []
+
+ for context, index in extracted_metadata:
+ if index == -1 or index >= len(documents):
+ doc = Document(page_content=context)
+ else:
+ doc = Document(page_content=context, metadata=documents[index].metadata)
+ compressed_docs.append(doc)
+
+ return compressed_docs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/openvino_rerank.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/openvino_rerank.py
new file mode 100644
index 0000000000000000000000000000000000000000..47d8fb6e0bfed7a7f49796e736c12878b31e864c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/openvino_rerank.py
@@ -0,0 +1,176 @@
+from pathlib import Path
+from typing import Any, Dict, Optional, Sequence
+
+import numpy as np
+from langchain_core.callbacks import Callbacks
+from langchain_core.documents import Document
+from langchain_core.documents.compressor import BaseDocumentCompressor
+from pydantic import Field
+
+
+class RerankRequest:
+ """Request for reranking."""
+
+ def __init__(self, query: Any = None, passages: Any = None):
+ self.query = query
+ self.passages = passages if passages is not None else []
+
+
+class OpenVINOReranker(BaseDocumentCompressor):
+ """
+ OpenVINO rerank models.
+ """
+
+ ov_model: Any = None
+ """OpenVINO model object."""
+ tokenizer: Any = None
+ """Tokenizer for embedding model."""
+ model_name_or_path: str
+ """HuggingFace model id."""
+ model_kwargs: Dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments passed to the model."""
+ top_n: int = 4
+ """return Top n texts."""
+
+ def __init__(self, **kwargs: Any):
+ super().__init__(**kwargs)
+
+ try:
+ from optimum.intel.openvino import OVModelForSequenceClassification
+ except ImportError as e:
+ raise ImportError(
+ "Could not import optimum-intel python package. "
+ "Please install it with: "
+ "pip install -U 'optimum[openvino,nncf]'"
+ ) from e
+
+ try:
+ from huggingface_hub import HfApi
+ except ImportError as e:
+ raise ImportError(
+ "Could not import huggingface_hub python package. "
+ "Please install it with: "
+ "`pip install -U huggingface_hub`."
+ ) from e
+
+ def require_model_export(
+ model_id: str, revision: Any = None, subfolder: Any = None
+ ) -> bool:
+ model_dir = Path(model_id)
+ if subfolder is not None:
+ model_dir = model_dir / subfolder
+ if model_dir.is_dir():
+ return (
+ not (model_dir / "openvino_model.xml").exists()
+ or not (model_dir / "openvino_model.bin").exists()
+ )
+ hf_api = HfApi()
+ try:
+ model_info = hf_api.model_info(model_id, revision=revision or "main")
+ normalized_subfolder = (
+ None if subfolder is None else Path(subfolder).as_posix()
+ )
+ model_files = [
+ file.rfilename
+ for file in model_info.siblings
+ if normalized_subfolder is None
+ or file.rfilename.startswith(normalized_subfolder)
+ ]
+ ov_model_path = (
+ "openvino_model.xml"
+ if subfolder is None
+ else f"{normalized_subfolder}/openvino_model.xml"
+ )
+ return (
+ ov_model_path not in model_files
+ or ov_model_path.replace(".xml", ".bin") not in model_files
+ )
+ except Exception:
+ return True
+
+ if require_model_export(self.model_name_or_path):
+ # use remote model
+ self.ov_model = OVModelForSequenceClassification.from_pretrained(
+ self.model_name_or_path, export=True, **self.model_kwargs
+ )
+ else:
+ # use local model
+ self.ov_model = OVModelForSequenceClassification.from_pretrained(
+ self.model_name_or_path, **self.model_kwargs
+ )
+
+ try:
+ from transformers import AutoTokenizer
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import transformers, please install with "
+ "`pip install -U transformers`."
+ ) from e
+
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name_or_path)
+
+ def rerank(self, request: Any) -> Any:
+ query = request.query
+ passages = request.passages
+
+ query_passage_pairs = [[query, passage["text"]] for passage in passages]
+ length = self.ov_model.request.inputs[0].get_partial_shape()[1]
+ if length.is_dynamic:
+ input_tensors = self.tokenizer(
+ query_passage_pairs, padding=True, truncation=True, return_tensors="pt"
+ )
+ else:
+ input_tensors = self.tokenizer(
+ query_passage_pairs,
+ padding="max_length",
+ max_length=length.get_length(),
+ truncation=True,
+ return_tensors="pt",
+ )
+
+ outputs = self.ov_model(**input_tensors, return_dict=True)
+ if outputs[0].shape[1] > 1:
+ scores = outputs[0][:, 1]
+ else:
+ scores = outputs[0].flatten()
+
+ scores = list(1 / (1 + np.exp(-scores)))
+
+ # Combine scores with passages, including metadata
+ for score, passage in zip(scores, passages):
+ passage["score"] = score
+
+ # Sort passages based on scores
+ passages.sort(key=lambda x: x["score"], reverse=True)
+
+ return passages
+
+ def compress_documents(
+ self,
+ documents: Sequence[Document],
+ query: str,
+ callbacks: Optional[Callbacks] = None,
+ ) -> Sequence[Document]:
+ passages = [
+ {"id": i, "text": doc.page_content} for i, doc in enumerate(documents)
+ ]
+
+ rerank_request = RerankRequest(query=query, passages=passages)
+ rerank_response = self.rerank(rerank_request)[: self.top_n]
+ final_results = []
+ for r in rerank_response:
+ doc = Document(
+ page_content=r["text"],
+ metadata={"id": r["id"], "relevance_score": r["score"]},
+ )
+ final_results.append(doc)
+ return final_results
+
+ def save_model(
+ self,
+ model_path: str,
+ ) -> bool:
+ self.ov_model.half()
+ self.ov_model.save_pretrained(model_path)
+ self.tokenizer.save_pretrained(model_path)
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/rankllm_rerank.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/rankllm_rerank.py
new file mode 100644
index 0000000000000000000000000000000000000000..3225d12f3c30899bc32bf0a8a76e178fe90e188b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/rankllm_rerank.py
@@ -0,0 +1,153 @@
+from __future__ import annotations
+
+from copy import deepcopy
+from enum import Enum
+from importlib.metadata import version
+from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence
+
+from langchain_classic.retrievers.document_compressors.base import (
+ BaseDocumentCompressor,
+)
+from langchain_core.callbacks.manager import Callbacks
+from langchain_core.documents import Document
+from langchain_core.utils import get_from_dict_or_env
+from packaging.version import Version
+from pydantic import ConfigDict, Field, PrivateAttr, model_validator
+
+if TYPE_CHECKING:
+ from rank_llm.data import Candidate, Query, Request
+else:
+ # Avoid pydantic annotation issues when actually instantiating
+ # while keeping this import optional
+ try:
+ from rank_llm.data import Candidate, Query, Request
+ except ImportError:
+ pass
+
+
+class RankLLMRerank(BaseDocumentCompressor):
+ """Document compressor using Flashrank interface."""
+
+ client: Any = None
+ """RankLLM client to use for compressing documents"""
+ top_n: int = Field(default=3)
+ """Top N documents to return."""
+ model: str = Field(default="zephyr")
+ """Name of model to use for reranking."""
+ step_size: int = Field(default=10)
+ """Step size for moving sliding window."""
+ gpt_model: str = Field(default="gpt-3.5-turbo")
+ """OpenAI model name."""
+ _retriever: Any = PrivateAttr()
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate python package exists in environment."""
+
+ if not values.get("client"):
+ client_name = values.get("model", "zephyr")
+
+ is_pre_rank_llm_revamp = Version(version=version("rank_llm")) <= Version(
+ "0.12.8"
+ )
+
+ try:
+ model_enum = ModelType(client_name.lower())
+ except ValueError:
+ raise ValueError(
+ "Unsupported model type. Please use 'vicuna', 'zephyr', or 'gpt'."
+ )
+
+ try:
+ if model_enum == ModelType.VICUNA:
+ if is_pre_rank_llm_revamp:
+ from rank_llm.rerank.vicuna_reranker import VicunaReranker
+ else:
+ from rank_llm.rerank.listwise.vicuna_reranker import (
+ VicunaReranker,
+ )
+
+ values["client"] = VicunaReranker()
+ elif model_enum == ModelType.ZEPHYR:
+ if is_pre_rank_llm_revamp:
+ from rank_llm.rerank.zephyr_reranker import ZephyrReranker
+ else:
+ from rank_llm.rerank.listwise.zephyr_reranker import (
+ ZephyrReranker,
+ )
+
+ values["client"] = ZephyrReranker()
+ elif model_enum == ModelType.GPT:
+ if is_pre_rank_llm_revamp:
+ from rank_llm.rerank.rank_gpt import SafeOpenai
+ else:
+ from rank_llm.rerank.listwise.rank_gpt import SafeOpenai
+
+ from rank_llm.rerank.reranker import Reranker
+
+ openai_api_key = get_from_dict_or_env(
+ values, "open_api_key", "OPENAI_API_KEY"
+ )
+
+ agent = SafeOpenai(
+ model=values["gpt_model"],
+ context_size=4096,
+ keys=openai_api_key,
+ )
+ values["client"] = Reranker(agent)
+
+ except ImportError:
+ raise ImportError(
+ "Could not import rank_llm python package. "
+ "Please install it with `pip install rank_llm`."
+ )
+
+ return values
+
+ def compress_documents(
+ self,
+ documents: Sequence[Document],
+ query: str,
+ callbacks: Optional[Callbacks] = None,
+ ) -> Sequence[Document]:
+ request = Request(
+ query=Query(text=query, qid=1),
+ candidates=[
+ Candidate(doc={"text": doc.page_content}, docid=index, score=1)
+ for index, doc in enumerate(documents)
+ ],
+ )
+
+ rerank_results = self.client.rerank(
+ request,
+ rank_end=len(documents),
+ window_size=min(20, len(documents)),
+ step=10,
+ )
+
+ final_results = []
+ if hasattr(rerank_results, "candidates"):
+ # Old API format
+ for res in rerank_results.candidates:
+ doc = documents[int(res.docid)]
+ doc_copy = Document(doc.page_content, metadata=deepcopy(doc.metadata))
+ final_results.append(doc_copy)
+ else:
+ for res in rerank_results:
+ doc = documents[int(res.docid)]
+ doc_copy = Document(doc.page_content, metadata=deepcopy(doc.metadata))
+ final_results.append(doc_copy)
+
+ return final_results[: self.top_n]
+
+
+class ModelType(Enum):
+ VICUNA = "vicuna"
+ ZEPHYR = "zephyr"
+ GPT = "gpt"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/volcengine_rerank.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/volcengine_rerank.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7b0cab2c1a8ca76c2e9c212de348bdab4bbeb37
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_compressors/volcengine_rerank.py
@@ -0,0 +1,134 @@
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import Any, Dict, List, Optional, Sequence, Union
+
+from langchain_core.callbacks.base import Callbacks
+from langchain_core.documents import BaseDocumentCompressor, Document
+from langchain_core.utils import get_from_dict_or_env
+from pydantic import ConfigDict, model_validator
+
+
+class VolcengineRerank(BaseDocumentCompressor):
+ """Document compressor that uses `Volcengine Rerank API`."""
+
+ client: Any = None
+ """Volcengine client to use for compressing documents."""
+
+ ak: Optional[str] = None
+ """Access Key ID.
+ https://www.volcengine.com/docs/84313/1254553"""
+
+ sk: Optional[str] = None
+ """Secret Access Key.
+ https://www.volcengine.com/docs/84313/1254553"""
+
+ region: str = "api-vikingdb.volces.com"
+ """https://www.volcengine.com/docs/84313/1254488. """
+
+ host: str = "cn-beijing"
+ """https://www.volcengine.com/docs/84313/1254488. """
+
+ top_n: Optional[int] = 3
+ """Number of documents to return."""
+
+ model_config = ConfigDict(
+ populate_by_name=True,
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that api key and python package exists in environment."""
+
+ if not values.get("client"):
+ try:
+ from volcengine.viking_db import VikingDBService
+ except ImportError:
+ raise ImportError(
+ "Could not import volcengine python package. "
+ "Please install it with `pip install volcengine` "
+ "or `pip install --user volcengine`."
+ )
+
+ values["ak"] = get_from_dict_or_env(values, "ak", "VOLC_API_AK")
+ values["sk"] = get_from_dict_or_env(values, "sk", "VOLC_API_SK")
+
+ values["client"] = VikingDBService(
+ host="api-vikingdb.volces.com",
+ region="cn-beijing",
+ scheme="https",
+ connection_timeout=30,
+ socket_timeout=30,
+ ak=values["ak"],
+ sk=values["sk"],
+ )
+
+ return values
+
+ def rerank(
+ self,
+ documents: Sequence[Union[str, Document, dict]],
+ query: str,
+ *,
+ top_n: Optional[int] = -1,
+ ) -> List[Dict[str, Any]]:
+ """Returns an ordered list of documents ordered by their relevance to the provided query.
+
+ Args:
+ query: The query to use for reranking.
+ documents: A sequence of documents to rerank.
+ top_n : The number of results to return. If None returns all results.
+ Defaults to self.top_n.
+ """ # noqa: E501
+
+ if len(documents) == 0: # to avoid empty api call
+ return []
+ docs = [
+ {
+ "query": query,
+ "content": doc.page_content if isinstance(doc, Document) else doc,
+ }
+ for doc in documents
+ ]
+
+ from volcengine.viking_db import VikingDBService
+
+ client: VikingDBService = self.client
+ results = client.batch_rerank(docs)
+
+ result_dicts = []
+ for index, score in enumerate(results):
+ result_dicts.append({"index": index, "relevance_score": score})
+
+ result_dicts.sort(key=lambda x: x["relevance_score"], reverse=True)
+ top_n = top_n if (top_n is None or top_n > 0) else self.top_n
+
+ return result_dicts[:top_n]
+
+ def compress_documents(
+ self,
+ documents: Sequence[Document],
+ query: str,
+ callbacks: Optional[Callbacks] = None,
+ ) -> Sequence[Document]:
+ """
+ Compress documents using Volcengine's rerank API.
+
+ Args:
+ documents: A sequence of documents to compress.
+ query: The query to use for compressing the documents.
+ callbacks: Callbacks to run during the compression process.
+
+ Returns:
+ A sequence of compressed documents.
+ """
+ compressed = []
+ for res in self.rerank(documents, query):
+ doc = documents[res["index"]]
+ doc_copy = Document(doc.page_content, metadata=deepcopy(doc.metadata))
+ doc_copy.metadata["relevance_score"] = res["relevance_score"]
+ compressed.append(doc_copy)
+ return compressed
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/acreom.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/acreom.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5656728b609a65525b25fefcac678c7f423d0cd
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/acreom.py
@@ -0,0 +1,81 @@
+import re
+from pathlib import Path
+from typing import Iterator, Pattern, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class AcreomLoader(BaseLoader):
+ """Load `acreom` vault from a directory."""
+
+ FRONT_MATTER_REGEX: Pattern = re.compile(
+ r"^---\n(.*?)\n---\n", re.MULTILINE | re.DOTALL
+ )
+ """Regex to match front matter metadata in markdown files."""
+
+ def __init__(
+ self,
+ path: Union[str, Path],
+ encoding: str = "UTF-8",
+ collect_metadata: bool = True,
+ ):
+ """Initialize the loader."""
+ self.file_path = path
+ """Path to the directory containing the markdown files."""
+ self.encoding = encoding
+ """Encoding to use when reading the files."""
+ self.collect_metadata = collect_metadata
+ """Whether to collect metadata from the front matter."""
+
+ def _parse_front_matter(self, content: str) -> dict:
+ """Parse front matter metadata from the content and return it as a dict."""
+ if not self.collect_metadata:
+ return {}
+ match = self.FRONT_MATTER_REGEX.search(content)
+ front_matter = {}
+ if match:
+ lines = match.group(1).split("\n")
+ for line in lines:
+ if ":" in line:
+ key, value = line.split(":", 1)
+ front_matter[key.strip()] = value.strip()
+ else:
+ # Skip lines without a colon
+ continue
+ return front_matter
+
+ def _remove_front_matter(self, content: str) -> str:
+ """Remove front matter metadata from the given content."""
+ if not self.collect_metadata:
+ return content
+ return self.FRONT_MATTER_REGEX.sub("", content)
+
+ def _process_acreom_content(self, content: str) -> str:
+ # remove acreom specific elements from content that
+ # do not contribute to the context of current document
+ content = re.sub(r"\s*-\s\[\s\]\s.*|\s*\[\s\]\s.*", "", content) # rm tasks
+ content = re.sub(r"#", "", content) # rm hashtags
+ content = re.sub(r"\[\[.*?\]\]", "", content) # rm doclinks
+ return content
+
+ def lazy_load(self) -> Iterator[Document]:
+ ps = list(Path(self.file_path).glob("**/*.md"))
+
+ for p in ps:
+ with open(p, encoding=self.encoding) as f:
+ text = f.read()
+
+ front_matter = self._parse_front_matter(text)
+ text = self._remove_front_matter(text)
+
+ text = self._process_acreom_content(text)
+
+ metadata = {
+ "source": str(p.name),
+ "path": str(p),
+ **front_matter,
+ }
+
+ yield Document(page_content=text, metadata=metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/airbyte.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/airbyte.py
new file mode 100644
index 0000000000000000000000000000000000000000..323c37fc35df36c74e4e35d8fa9986d05b6dc67e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/airbyte.py
@@ -0,0 +1,287 @@
+from typing import Any, Callable, Iterator, Mapping, Optional
+
+from langchain_core.documents import Document
+from langchain_core.utils.utils import guard_import
+
+from langchain_community.document_loaders.base import BaseLoader
+
+RecordHandler = Callable[[Any, Optional[str]], Document]
+
+
+class AirbyteCDKLoader(BaseLoader):
+ """Load with an `Airbyte` source connector implemented using the `CDK`."""
+
+ def __init__(
+ self,
+ config: Mapping[str, Any],
+ source_class: Any,
+ stream_name: str,
+ record_handler: Optional[RecordHandler] = None,
+ state: Optional[Any] = None,
+ ) -> None:
+ """Initializes the loader.
+
+ Args:
+ config: The config to pass to the source connector.
+ source_class: The source connector class.
+ stream_name: The name of the stream to load.
+ record_handler: A function that takes in a record and an optional id and
+ returns a Document. If None, the record will be used as the document.
+ Defaults to None.
+ state: The state to pass to the source connector. Defaults to None.
+ """
+ from airbyte_cdk.models.airbyte_protocol import AirbyteRecordMessage
+ from airbyte_cdk.sources.embedded.base_integration import (
+ BaseEmbeddedIntegration,
+ )
+ from airbyte_cdk.sources.embedded.runner import CDKRunner
+
+ class CDKIntegration(BaseEmbeddedIntegration):
+ """A wrapper around the CDK integration."""
+
+ def _handle_record(
+ self, record: AirbyteRecordMessage, id: Optional[str]
+ ) -> Document:
+ if record_handler:
+ return record_handler(record, id)
+ return Document(page_content="", metadata=record.data)
+
+ self._integration = CDKIntegration(
+ config=config,
+ runner=CDKRunner(source=source_class(), name=source_class.__name__),
+ )
+ self._stream_name = stream_name
+ self._state = state
+
+ def lazy_load(self) -> Iterator[Document]:
+ return self._integration._load_data(
+ stream_name=self._stream_name, state=self._state
+ )
+
+ @property
+ def last_state(self) -> Any:
+ return self._integration.last_state
+
+
+class AirbyteHubspotLoader(AirbyteCDKLoader):
+ """Load from `Hubspot` using an `Airbyte` source connector."""
+
+ def __init__(
+ self,
+ config: Mapping[str, Any],
+ stream_name: str,
+ record_handler: Optional[RecordHandler] = None,
+ state: Optional[Any] = None,
+ ) -> None:
+ """Initializes the loader.
+
+ Args:
+ config: The config to pass to the source connector.
+ stream_name: The name of the stream to load.
+ record_handler: A function that takes in a record and an optional id and
+ returns a Document. If None, the record will be used as the document.
+ Defaults to None.
+ state: The state to pass to the source connector. Defaults to None.
+ """
+ source_class = guard_import(
+ "source_hubspot", pip_name="airbyte-source-hubspot"
+ ).SourceHubspot
+ super().__init__(
+ config=config,
+ source_class=source_class,
+ stream_name=stream_name,
+ record_handler=record_handler,
+ state=state,
+ )
+
+
+class AirbyteStripeLoader(AirbyteCDKLoader):
+ """Load from `Stripe` using an `Airbyte` source connector."""
+
+ def __init__(
+ self,
+ config: Mapping[str, Any],
+ stream_name: str,
+ record_handler: Optional[RecordHandler] = None,
+ state: Optional[Any] = None,
+ ) -> None:
+ """Initializes the loader.
+
+ Args:
+ config: The config to pass to the source connector.
+ stream_name: The name of the stream to load.
+ record_handler: A function that takes in a record and an optional id and
+ returns a Document. If None, the record will be used as the document.
+ Defaults to None.
+ state: The state to pass to the source connector. Defaults to None.
+ """
+ source_class = guard_import(
+ "source_stripe", pip_name="airbyte-source-stripe"
+ ).SourceStripe
+ super().__init__(
+ config=config,
+ source_class=source_class,
+ stream_name=stream_name,
+ record_handler=record_handler,
+ state=state,
+ )
+
+
+class AirbyteTypeformLoader(AirbyteCDKLoader):
+ """Load from `Typeform` using an `Airbyte` source connector."""
+
+ def __init__(
+ self,
+ config: Mapping[str, Any],
+ stream_name: str,
+ record_handler: Optional[RecordHandler] = None,
+ state: Optional[Any] = None,
+ ) -> None:
+ """Initializes the loader.
+
+ Args:
+ config: The config to pass to the source connector.
+ stream_name: The name of the stream to load.
+ record_handler: A function that takes in a record and an optional id and
+ returns a Document. If None, the record will be used as the document.
+ Defaults to None.
+ state: The state to pass to the source connector. Defaults to None.
+ """
+ source_class = guard_import(
+ "source_typeform", pip_name="airbyte-source-typeform"
+ ).SourceTypeform
+ super().__init__(
+ config=config,
+ source_class=source_class,
+ stream_name=stream_name,
+ record_handler=record_handler,
+ state=state,
+ )
+
+
+class AirbyteZendeskSupportLoader(AirbyteCDKLoader):
+ """Load from `Zendesk Support` using an `Airbyte` source connector."""
+
+ def __init__(
+ self,
+ config: Mapping[str, Any],
+ stream_name: str,
+ record_handler: Optional[RecordHandler] = None,
+ state: Optional[Any] = None,
+ ) -> None:
+ """Initializes the loader.
+
+ Args:
+ config: The config to pass to the source connector.
+ stream_name: The name of the stream to load.
+ record_handler: A function that takes in a record and an optional id and
+ returns a Document. If None, the record will be used as the document.
+ Defaults to None.
+ state: The state to pass to the source connector. Defaults to None.
+ """
+ source_class = guard_import(
+ "source_zendesk_support", pip_name="airbyte-source-zendesk-support"
+ ).SourceZendeskSupport
+ super().__init__(
+ config=config,
+ source_class=source_class,
+ stream_name=stream_name,
+ record_handler=record_handler,
+ state=state,
+ )
+
+
+class AirbyteShopifyLoader(AirbyteCDKLoader):
+ """Load from `Shopify` using an `Airbyte` source connector."""
+
+ def __init__(
+ self,
+ config: Mapping[str, Any],
+ stream_name: str,
+ record_handler: Optional[RecordHandler] = None,
+ state: Optional[Any] = None,
+ ) -> None:
+ """Initializes the loader.
+
+ Args:
+ config: The config to pass to the source connector.
+ stream_name: The name of the stream to load.
+ record_handler: A function that takes in a record and an optional id and
+ returns a Document. If None, the record will be used as the document.
+ Defaults to None.
+ state: The state to pass to the source connector. Defaults to None.
+ """
+ source_class = guard_import(
+ "source_shopify", pip_name="airbyte-source-shopify"
+ ).SourceShopify
+ super().__init__(
+ config=config,
+ source_class=source_class,
+ stream_name=stream_name,
+ record_handler=record_handler,
+ state=state,
+ )
+
+
+class AirbyteSalesforceLoader(AirbyteCDKLoader):
+ """Load from `Salesforce` using an `Airbyte` source connector."""
+
+ def __init__(
+ self,
+ config: Mapping[str, Any],
+ stream_name: str,
+ record_handler: Optional[RecordHandler] = None,
+ state: Optional[Any] = None,
+ ) -> None:
+ """Initializes the loader.
+
+ Args:
+ config: The config to pass to the source connector.
+ stream_name: The name of the stream to load.
+ record_handler: A function that takes in a record and an optional id and
+ returns a Document. If None, the record will be used as the document.
+ Defaults to None.
+ state: The state to pass to the source connector. Defaults to None.
+ """
+ source_class = guard_import(
+ "source_salesforce", pip_name="airbyte-source-salesforce"
+ ).SourceSalesforce
+ super().__init__(
+ config=config,
+ source_class=source_class,
+ stream_name=stream_name,
+ record_handler=record_handler,
+ state=state,
+ )
+
+
+class AirbyteGongLoader(AirbyteCDKLoader):
+ """Load from `Gong` using an `Airbyte` source connector."""
+
+ def __init__(
+ self,
+ config: Mapping[str, Any],
+ stream_name: str,
+ record_handler: Optional[RecordHandler] = None,
+ state: Optional[Any] = None,
+ ) -> None:
+ """Initializes the loader.
+
+ Args:
+ config: The config to pass to the source connector.
+ stream_name: The name of the stream to load.
+ record_handler: A function that takes in a record and an optional id and
+ returns a Document. If None, the record will be used as the document.
+ Defaults to None.
+ state: The state to pass to the source connector. Defaults to None.
+ """
+ source_class = guard_import(
+ "source_gong", pip_name="airbyte-source-gong"
+ ).SourceGong
+ super().__init__(
+ config=config,
+ source_class=source_class,
+ stream_name=stream_name,
+ record_handler=record_handler,
+ state=state,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/airbyte_json.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/airbyte_json.py
new file mode 100644
index 0000000000000000000000000000000000000000..aeb4b43cab83398ccea96e3545405e05dcd1fe2a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/airbyte_json.py
@@ -0,0 +1,25 @@
+import json
+from pathlib import Path
+from typing import List, Union
+
+from langchain_core.documents import Document
+from langchain_core.utils import stringify_dict
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class AirbyteJSONLoader(BaseLoader):
+ """Load local `Airbyte` json files."""
+
+ def __init__(self, file_path: Union[str, Path]):
+ """Initialize with a file path. This should start with '/tmp/airbyte_local/'."""
+ self.file_path = file_path
+ """Path to the directory containing the json files."""
+
+ def load(self) -> List[Document]:
+ text = ""
+ for line in open(self.file_path, "r"):
+ data = json.loads(line)["_airbyte_data"]
+ text += stringify_dict(data)
+ metadata = {"source": str(self.file_path)}
+ return [Document(page_content=text, metadata=metadata)]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/airtable.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/airtable.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc3e25dd47dd8a854a4cd852e1b9e6b3d5dbfc9c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/airtable.py
@@ -0,0 +1,44 @@
+from typing import Any, Iterator
+
+from langchain_core.document_loaders import BaseLoader
+from langchain_core.documents import Document
+
+
+class AirtableLoader(BaseLoader):
+ """Load the `Airtable` tables."""
+
+ def __init__(
+ self, api_token: str, table_id: str, base_id: str, **kwargs: Any
+ ) -> None:
+ """Initialize with API token and the IDs for table and base.
+
+ Args:
+ api_token: Airtable API token.
+ table_id: Airtable table ID.
+ base_id:
+ kwargs: Additional parameters to pass to Table.all(). Refer to the
+ pyairtable documentation for available options:
+ https://pyairtable.readthedocs.io/en/latest/api.html#pyairtable.Table.all
+ """ # noqa: E501
+ self.api_token = api_token
+ self.table_id = table_id
+ self.base_id = base_id
+ self.kwargs = kwargs
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load Documents from table."""
+
+ from pyairtable import Table
+
+ table = Table(self.api_token, self.base_id, self.table_id)
+ records = table.all(**self.kwargs)
+ for record in records:
+ metadata = {
+ "source": self.base_id + "_" + self.table_id,
+ "base_id": self.base_id,
+ "table_id": self.table_id,
+ }
+ if "view" in self.kwargs:
+ metadata["view"] = self.kwargs["view"]
+ # Need to convert record from dict to str
+ yield Document(page_content=str(record), metadata=metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/apify_dataset.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/apify_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..34f74185a7d7904ef7fbea092e172b61561f6d7a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/apify_dataset.py
@@ -0,0 +1,93 @@
+from typing import Any, Callable, Dict, List
+
+from langchain_core._api import deprecated
+from langchain_core.documents import Document
+from pydantic import BaseModel, model_validator
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+@deprecated(
+ since="0.3.18",
+ message=(
+ "This class is deprecated and will be removed in a future version. "
+ "You can swap to using the `ApifyDatasetLoader`"
+ " implementation in `langchain_apify` package. "
+ "See "
+ ),
+ alternative_import="langchain_apify.ApifyDatasetLoader",
+)
+class ApifyDatasetLoader(BaseLoader, BaseModel):
+ """Load datasets from `Apify` web scraping, crawling, and data extraction platform.
+
+ For details, see https://docs.apify.com/platform/integrations/langchain
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import ApifyDatasetLoader
+ from langchain_core.documents import Document
+
+ loader = ApifyDatasetLoader(
+ dataset_id="YOUR-DATASET-ID",
+ dataset_mapping_function=lambda dataset_item: Document(
+ page_content=dataset_item["text"], metadata={"source": dataset_item["url"]}
+ ),
+ )
+ documents = loader.load()
+ """ # noqa: E501
+
+ apify_client: Any
+ """An instance of the ApifyClient class from the apify-client Python package."""
+ dataset_id: str
+ """The ID of the dataset on the Apify platform."""
+ dataset_mapping_function: Callable[[Dict], Document]
+ """A custom function that takes a single dictionary (an Apify dataset item)
+ and converts it to an instance of the Document class."""
+
+ def __init__(
+ self, dataset_id: str, dataset_mapping_function: Callable[[Dict], Document]
+ ):
+ """Initialize the loader with an Apify dataset ID and a mapping function.
+
+ Args:
+ dataset_id (str): The ID of the dataset on the Apify platform.
+ dataset_mapping_function (Callable): A function that takes a single
+ dictionary (an Apify dataset item) and converts it to an instance
+ of the Document class.
+ """
+ super().__init__(
+ dataset_id=dataset_id, dataset_mapping_function=dataset_mapping_function
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate environment.
+
+ Args:
+ values: The values to validate.
+ """
+
+ try:
+ from apify_client import ApifyClient
+
+ client = ApifyClient()
+ if httpx_client := getattr(client.http_client, "httpx_client"):
+ httpx_client.headers["user-agent"] += "; Origin/langchain"
+
+ values["apify_client"] = client
+ except ImportError:
+ raise ImportError(
+ "Could not import apify-client Python package. "
+ "Please install it with `pip install apify-client`."
+ )
+
+ return values
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ dataset_items = (
+ self.apify_client.dataset(self.dataset_id).list_items(clean=True).items
+ )
+ return list(map(self.dataset_mapping_function, dataset_items))
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/arcgis_loader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/arcgis_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9e098d320da27c981d85eb7b2f064edb3fe63dc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/arcgis_loader.py
@@ -0,0 +1,150 @@
+"""Document Loader for ArcGIS FeatureLayers."""
+
+from __future__ import annotations
+
+import json
+import re
+import warnings
+from datetime import datetime, timezone
+from typing import TYPE_CHECKING, Any, Iterator, List, Optional, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+if TYPE_CHECKING:
+ import arcgis
+
+_NOT_PROVIDED = "(Not Provided)"
+
+
+class ArcGISLoader(BaseLoader):
+ """Load records from an ArcGIS FeatureLayer."""
+
+ def __init__(
+ self,
+ layer: Union[str, arcgis.features.FeatureLayer],
+ gis: Optional[arcgis.gis.GIS] = None,
+ where: str = "1=1",
+ out_fields: Optional[Union[List[str], str]] = None,
+ return_geometry: bool = False,
+ result_record_count: Optional[int] = None,
+ lyr_desc: Optional[str] = None,
+ **kwargs: Any,
+ ):
+ try:
+ import arcgis
+ except ImportError as e:
+ raise ImportError(
+ "arcgis is required to use the ArcGIS Loader. "
+ "Install it with pip or conda."
+ ) from e
+
+ try:
+ from bs4 import BeautifulSoup
+
+ self.BEAUTIFULSOUP = BeautifulSoup
+ except ImportError:
+ warnings.warn("BeautifulSoup not found. HTML will not be parsed.")
+ self.BEAUTIFULSOUP = None # type: ignore[assignment]
+
+ self.gis = gis or arcgis.gis.GIS()
+
+ if isinstance(layer, str):
+ self.url = layer
+ self.layer = arcgis.features.FeatureLayer(layer, gis=gis)
+ else:
+ self.url = layer.url
+ self.layer = layer
+
+ self.layer_properties = self._get_layer_properties(lyr_desc)
+
+ self.where = where
+
+ if isinstance(out_fields, str):
+ self.out_fields = out_fields
+ elif out_fields is None:
+ self.out_fields = "*"
+ else:
+ self.out_fields = ",".join(out_fields)
+
+ self.return_geometry = return_geometry
+
+ self.result_record_count = result_record_count
+ self.return_all_records = not isinstance(result_record_count, int)
+
+ query_params = dict(
+ where=self.where,
+ out_fields=self.out_fields,
+ return_geometry=self.return_geometry,
+ return_all_records=self.return_all_records,
+ result_record_count=self.result_record_count,
+ )
+ query_params.update(kwargs)
+ self.query_params = query_params
+
+ def _get_layer_properties(self, lyr_desc: Optional[str] = None) -> dict:
+ """Get the layer properties from the FeatureLayer."""
+ import arcgis
+
+ layer_number_pattern = re.compile(r"/\d+$")
+ props = self.layer.properties
+
+ if lyr_desc is None:
+ # retrieve description from the FeatureLayer if not provided
+ try:
+ if self.BEAUTIFULSOUP: # type: ignore[truthy-function]
+ lyr_desc = self.BEAUTIFULSOUP(props["description"]).text
+ else:
+ lyr_desc = props["description"]
+ lyr_desc = lyr_desc or _NOT_PROVIDED
+ except KeyError:
+ lyr_desc = _NOT_PROVIDED
+ try:
+ item_id = props["serviceItemId"]
+ item = self.gis.content.get(item_id) or arcgis.features.FeatureLayer(
+ re.sub(layer_number_pattern, "", self.url),
+ )
+ try:
+ raw_desc = item.description
+ except AttributeError:
+ raw_desc = item.properties.description
+ if self.BEAUTIFULSOUP: # type: ignore # noqa: PGH003
+ item_desc = self.BEAUTIFULSOUP(raw_desc).text
+ else:
+ item_desc = raw_desc
+ item_desc = item_desc or _NOT_PROVIDED
+ except KeyError:
+ item_desc = _NOT_PROVIDED
+ return {
+ "layer_description": lyr_desc,
+ "item_description": item_desc,
+ "layer_properties": props,
+ }
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load records from FeatureLayer."""
+ query_response = self.layer.query(**self.query_params)
+ features = (feature.as_dict for feature in query_response)
+ for feature in features:
+ attributes = feature["attributes"]
+ page_content = json.dumps(attributes)
+
+ metadata = {
+ "accessed": f"{datetime.now(timezone.utc).isoformat()}Z",
+ "name": self.layer_properties["layer_properties"]["name"],
+ "url": self.url,
+ "layer_description": self.layer_properties["layer_description"],
+ "item_description": self.layer_properties["item_description"],
+ "layer_properties": self.layer_properties["layer_properties"],
+ }
+
+ if self.return_geometry:
+ try:
+ metadata["geometry"] = feature["geometry"]
+ except KeyError:
+ warnings.warn(
+ "Geometry could not be retrieved from the feature layer."
+ )
+
+ yield Document(page_content=page_content, metadata=metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/arxiv.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/arxiv.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4171c4694d33815af239ad01bef34d3d1b00636
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/arxiv.py
@@ -0,0 +1,153 @@
+from typing import Any, Iterator, List, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.arxiv import ArxivAPIWrapper
+
+
+class ArxivLoader(BaseLoader):
+ """Load a query result from `Arxiv`.
+ The loader converts the original PDF format into the text.
+
+ Setup:
+ Install ``arxiv`` and ``PyMuPDF`` packages.
+ ``PyMuPDF`` transforms PDF files downloaded from the arxiv.org site
+ into the text format.
+
+ .. code-block:: bash
+
+ pip install -U arxiv pymupdf
+
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import ArxivLoader
+
+ loader = ArxivLoader(
+ query="reasoning",
+ # load_max_docs=2,
+ # load_all_available_meta=False
+ )
+
+ Load:
+ .. code-block:: python
+
+ docs = loader.load()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+ Understanding the Reasoning Ability of Language Models
+ From the Perspective of Reasoning Paths Aggre
+ {
+ 'Published': '2024-02-29',
+ 'Title': 'Understanding the Reasoning Ability of Language Models From the
+ Perspective of Reasoning Paths Aggregation',
+ 'Authors': 'Xinyi Wang, Alfonso Amayuelas, Kexun Zhang, Liangming Pan,
+ Wenhu Chen, William Yang Wang',
+ 'Summary': 'Pre-trained language models (LMs) are able to perform complex reasoning
+ without explicit fine-tuning...'
+ }
+
+
+ Lazy load:
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ # async variant:
+ # docs_lazy = await loader.alazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Understanding the Reasoning Ability of Language Models
+ From the Perspective of Reasoning Paths Aggre
+ {
+ 'Published': '2024-02-29',
+ 'Title': 'Understanding the Reasoning Ability of Language Models From the
+ Perspective of Reasoning Paths Aggregation',
+ 'Authors': 'Xinyi Wang, Alfonso Amayuelas, Kexun Zhang, Liangming Pan,
+ Wenhu Chen, William Yang Wang',
+ 'Summary': 'Pre-trained language models (LMs) are able to perform complex reasoning
+ without explicit fine-tuning...'
+ }
+
+ Async load:
+ .. code-block:: python
+
+ docs = await loader.aload()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Understanding the Reasoning Ability of Language Models
+ From the Perspective of Reasoning Paths Aggre
+ {
+ 'Published': '2024-02-29',
+ 'Title': 'Understanding the Reasoning Ability of Language Models From the
+ Perspective of Reasoning Paths Aggregation',
+ 'Authors': 'Xinyi Wang, Alfonso Amayuelas, Kexun Zhang, Liangming Pan,
+ Wenhu Chen, William Yang Wang',
+ 'Summary': 'Pre-trained language models (LMs) are able to perform complex reasoning
+ without explicit fine-tuning...'
+ }
+
+ Use summaries of articles as docs:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import ArxivLoader
+
+ loader = ArxivLoader(
+ query="reasoning"
+ )
+
+ docs = loader.get_summaries_as_docs()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Pre-trained language models (LMs) are able to perform complex reasoning
+ without explicit fine-tuning
+ {
+ 'Entry ID': 'http://arxiv.org/abs/2402.03268v2',
+ 'Published': datetime.date(2024, 2, 29),
+ 'Title': 'Understanding the Reasoning Ability of Language Models From the
+ Perspective of Reasoning Paths Aggregation',
+ 'Authors': 'Xinyi Wang, Alfonso Amayuelas, Kexun Zhang, Liangming Pan,
+ Wenhu Chen, William Yang Wang'
+ }
+ """ # noqa: E501
+
+ def __init__(
+ self, query: str, doc_content_chars_max: Optional[int] = None, **kwargs: Any
+ ):
+ """Initialize with search query to find documents in the Arxiv.
+ Supports all arguments of `ArxivAPIWrapper`.
+
+ Args:
+ query: free text which used to find documents in the Arxiv
+ doc_content_chars_max: cut limit for the length of a document's content
+ """ # noqa: E501
+
+ self.query = query
+ self.client = ArxivAPIWrapper(
+ doc_content_chars_max=doc_content_chars_max, **kwargs
+ )
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load Arvix documents"""
+ yield from self.client.lazy_load(self.query)
+
+ def get_summaries_as_docs(self) -> List[Document]:
+ """Uses papers summaries as documents rather than source Arvix papers"""
+ return self.client.get_summaries_as_docs(self.query)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/assemblyai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/assemblyai.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7713d33bf485927b4a98d7ce460bb26184a7385
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/assemblyai.py
@@ -0,0 +1,217 @@
+from __future__ import annotations
+
+from enum import Enum
+from pathlib import Path
+from typing import TYPE_CHECKING, Iterator, Optional, Union
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+if TYPE_CHECKING:
+ import assemblyai
+
+
+class TranscriptFormat(Enum):
+ """Transcript format to use for the document loader."""
+
+ TEXT = "text"
+ """One document with the transcription text"""
+ SENTENCES = "sentences"
+ """Multiple documents, splits the transcription by each sentence"""
+ PARAGRAPHS = "paragraphs"
+ """Multiple documents, splits the transcription by each paragraph"""
+ SUBTITLES_SRT = "subtitles_srt"
+ """One document with the transcript exported in SRT subtitles format"""
+ SUBTITLES_VTT = "subtitles_vtt"
+ """One document with the transcript exported in VTT subtitles format"""
+
+
+class AssemblyAIAudioTranscriptLoader(BaseLoader):
+ """Load AssemblyAI audio transcripts.
+
+ It uses the AssemblyAI API to transcribe audio files
+ and loads the transcribed text into one or more Documents,
+ depending on the specified format.
+
+ To use, you should have the ``assemblyai`` python package installed, and the
+ environment variable ``ASSEMBLYAI_API_KEY`` set with your API key.
+ Alternatively, the API key can also be passed as an argument.
+
+ Audio files can be specified via an URL or a local file path.
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ *,
+ transcript_format: TranscriptFormat = TranscriptFormat.TEXT,
+ config: Optional[assemblyai.TranscriptionConfig] = None,
+ api_key: Optional[str] = None,
+ ):
+ """
+ Initializes the AssemblyAI AudioTranscriptLoader.
+
+ Args:
+ file_path: An URL or a local file path.
+ transcript_format: Transcript format to use.
+ See class ``TranscriptFormat`` for more info.
+ config: Transcription options and features. If ``None`` is given,
+ the Transcriber's default configuration will be used.
+ api_key: AssemblyAI API key.
+ """
+ try:
+ import assemblyai
+ except ImportError:
+ raise ImportError(
+ "Could not import assemblyai python package. "
+ "Please install it with `pip install assemblyai`."
+ )
+ if api_key is not None:
+ assemblyai.settings.api_key = api_key
+
+ self.file_path = str(file_path)
+ self.transcript_format = transcript_format
+ self.transcriber = assemblyai.Transcriber(config=config)
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Transcribes the audio file and loads the transcript into documents.
+
+ It uses the AssemblyAI API to transcribe the audio file and blocks until
+ the transcription is finished.
+ """
+ transcript = self.transcriber.transcribe(self.file_path)
+ # This will raise a ValueError if no API key is set.
+
+ if transcript.error:
+ raise ValueError(f"Could not transcribe file: {transcript.error}")
+
+ if self.transcript_format == TranscriptFormat.TEXT:
+ yield Document(
+ page_content=transcript.text, metadata=transcript.json_response
+ )
+ elif self.transcript_format == TranscriptFormat.SENTENCES:
+ sentences = transcript.get_sentences()
+ for s in sentences:
+ yield Document(page_content=s.text, metadata=s.dict(exclude={"text"}))
+ elif self.transcript_format == TranscriptFormat.PARAGRAPHS:
+ paragraphs = transcript.get_paragraphs()
+ for p in paragraphs:
+ yield Document(page_content=p.text, metadata=p.dict(exclude={"text"}))
+ elif self.transcript_format == TranscriptFormat.SUBTITLES_SRT:
+ yield Document(page_content=transcript.export_subtitles_srt())
+ elif self.transcript_format == TranscriptFormat.SUBTITLES_VTT:
+ yield Document(page_content=transcript.export_subtitles_vtt())
+ else:
+ raise ValueError("Unknown transcript format.")
+
+
+class AssemblyAIAudioLoaderById(BaseLoader):
+ """
+ Load AssemblyAI audio transcripts.
+
+ It uses the AssemblyAI API to get an existing transcription
+ and loads the transcribed text into one or more Documents,
+ depending on the specified format.
+
+ """
+
+ def __init__(
+ self, transcript_id: str, api_key: str, transcript_format: TranscriptFormat
+ ):
+ """
+ Initializes the AssemblyAI AssemblyAIAudioLoaderById.
+
+ Args:
+ transcript_id: Id of an existing transcription.
+ transcript_format: Transcript format to use.
+ See class ``TranscriptFormat`` for more info.
+ api_key: AssemblyAI API key.
+ """
+
+ self.api_key = api_key
+ self.transcript_id = transcript_id
+ self.transcript_format = transcript_format
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load data into Document objects."""
+ HEADERS = {"authorization": self.api_key}
+
+ if self.transcript_format == TranscriptFormat.TEXT:
+ try:
+ transcript_response = requests.get(
+ f"https://api.assemblyai.com/v2/transcript/{self.transcript_id}",
+ headers=HEADERS,
+ )
+ transcript_response.raise_for_status()
+ except Exception as e:
+ print(f"An error occurred: {e}") # noqa: T201
+ raise
+
+ transcript = transcript_response.json()["text"]
+
+ yield Document(page_content=transcript, metadata=transcript_response.json())
+ elif self.transcript_format == TranscriptFormat.PARAGRAPHS:
+ try:
+ paragraphs_response = requests.get(
+ f"https://api.assemblyai.com/v2/transcript/{self.transcript_id}/paragraphs",
+ headers=HEADERS,
+ )
+ paragraphs_response.raise_for_status()
+ except Exception as e:
+ print(f"An error occurred: {e}") # noqa: T201
+ raise
+
+ paragraphs = paragraphs_response.json()["paragraphs"]
+
+ for p in paragraphs:
+ yield Document(page_content=p["text"], metadata=p)
+
+ elif self.transcript_format == TranscriptFormat.SENTENCES:
+ try:
+ sentences_response = requests.get(
+ f"https://api.assemblyai.com/v2/transcript/{self.transcript_id}/sentences",
+ headers=HEADERS,
+ )
+ sentences_response.raise_for_status()
+ except Exception as e:
+ print(f"An error occurred: {e}") # noqa: T201
+ raise
+
+ sentences = sentences_response.json()["sentences"]
+
+ for s in sentences:
+ yield Document(page_content=s["text"], metadata=s)
+
+ elif self.transcript_format == TranscriptFormat.SUBTITLES_SRT:
+ try:
+ srt_response = requests.get(
+ f"https://api.assemblyai.com/v2/transcript/{self.transcript_id}/srt",
+ headers=HEADERS,
+ )
+ srt_response.raise_for_status()
+ except Exception as e:
+ print(f"An error occurred: {e}") # noqa: T201
+ raise
+
+ srt = srt_response.text
+
+ yield Document(page_content=srt)
+
+ elif self.transcript_format == TranscriptFormat.SUBTITLES_VTT:
+ try:
+ vtt_response = requests.get(
+ f"https://api.assemblyai.com/v2/transcript/{self.transcript_id}/vtt",
+ headers=HEADERS,
+ )
+ vtt_response.raise_for_status()
+ except Exception as e:
+ print(f"An error occurred: {e}") # noqa: T201
+ raise
+
+ vtt = vtt_response.text
+
+ yield Document(page_content=vtt)
+ else:
+ raise ValueError("Unknown transcript format.")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/astradb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/astradb.py
new file mode 100644
index 0000000000000000000000000000000000000000..18a351d33f56ba44ae0650768b17589138b3092a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/astradb.py
@@ -0,0 +1,124 @@
+from __future__ import annotations
+
+import json
+import logging
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ AsyncIterator,
+ Callable,
+ Dict,
+ Iterator,
+ List,
+ Optional,
+)
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.astradb import _AstraDBEnvironment
+
+if TYPE_CHECKING:
+ from astrapy.db import AstraDB, AsyncAstraDB
+
+logger = logging.getLogger(__name__)
+
+
+@deprecated(
+ since="0.0.29",
+ removal="1.0",
+ alternative_import="langchain_astradb.AstraDBLoader",
+)
+class AstraDBLoader(BaseLoader):
+ def __init__(
+ self,
+ collection_name: str,
+ *,
+ token: Optional[str] = None,
+ api_endpoint: Optional[str] = None,
+ astra_db_client: Optional[AstraDB] = None,
+ async_astra_db_client: Optional[AsyncAstraDB] = None,
+ namespace: Optional[str] = None,
+ filter_criteria: Optional[Dict[str, Any]] = None,
+ projection: Optional[Dict[str, Any]] = None,
+ find_options: Optional[Dict[str, Any]] = None,
+ nb_prefetched: int = 1000,
+ extraction_function: Callable[[Dict], str] = json.dumps,
+ ) -> None:
+ """Load DataStax Astra DB documents.
+
+ Args:
+ collection_name: name of the Astra DB collection to use.
+ token: API token for Astra DB usage.
+ api_endpoint: full URL to the API endpoint,
+ such as `https://-us-east1.apps.astra.datastax.com`.
+ astra_db_client: *alternative to token+api_endpoint*,
+ you can pass an already-created 'astrapy.db.AstraDB' instance.
+ async_astra_db_client: *alternative to token+api_endpoint*,
+ you can pass an already-created 'astrapy.db.AsyncAstraDB' instance.
+ namespace: namespace (aka keyspace) where the
+ collection is. Defaults to the database's "default namespace".
+ filter_criteria: Criteria to filter documents.
+ projection: Specifies the fields to return.
+ find_options: Additional options for the query.
+ nb_prefetched: Max number of documents to pre-fetch. Defaults to 1000.
+ extraction_function: Function applied to collection documents to create
+ the `page_content` of the LangChain Document. Defaults to `json.dumps`.
+ """
+ astra_env = _AstraDBEnvironment(
+ token=token,
+ api_endpoint=api_endpoint,
+ astra_db_client=astra_db_client,
+ async_astra_db_client=async_astra_db_client,
+ namespace=namespace,
+ )
+ self.astra_env = astra_env
+ self.collection = astra_env.astra_db.collection(collection_name)
+ self.collection_name = collection_name
+ self.filter = filter_criteria
+ self.projection = projection
+ self.find_options = find_options or {}
+ self.nb_prefetched = nb_prefetched
+ self.extraction_function = extraction_function
+
+ def lazy_load(self) -> Iterator[Document]:
+ for doc in self.collection.paginated_find(
+ filter=self.filter,
+ options=self.find_options,
+ projection=self.projection,
+ sort=None,
+ prefetched=self.nb_prefetched,
+ ):
+ yield Document(
+ page_content=self.extraction_function(doc),
+ metadata={
+ "namespace": self.collection.astra_db.namespace,
+ "api_endpoint": self.collection.astra_db.base_url,
+ "collection": self.collection_name,
+ },
+ )
+
+ async def aload(self) -> List[Document]:
+ """Load data into Document objects."""
+ return [doc async for doc in self.alazy_load()]
+
+ async def alazy_load(self) -> AsyncIterator[Document]:
+ async_collection = await self.astra_env.async_astra_db.collection(
+ self.collection_name
+ )
+ async for doc in async_collection.paginated_find(
+ filter=self.filter,
+ options=self.find_options,
+ projection=self.projection,
+ sort=None,
+ prefetched=self.nb_prefetched,
+ ):
+ yield Document(
+ page_content=self.extraction_function(doc),
+ metadata={
+ "namespace": async_collection.astra_db.namespace,
+ "api_endpoint": async_collection.astra_db.base_url,
+ "collection": self.collection_name,
+ },
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/async_html.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/async_html.py
new file mode 100644
index 0000000000000000000000000000000000000000..20b3c7ae1e5ab72b2f26e9a9631dc9808582f9df
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/async_html.py
@@ -0,0 +1,244 @@
+import asyncio
+import logging
+import warnings
+from concurrent.futures import Future, ThreadPoolExecutor
+from typing import (
+ Any,
+ AsyncIterator,
+ Dict,
+ Iterator,
+ List,
+ Optional,
+ Tuple,
+ Union,
+ cast,
+)
+
+import aiohttp
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utils.user_agent import get_user_agent
+
+logger = logging.getLogger(__name__)
+
+default_header_template = {
+ "User-Agent": get_user_agent(),
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*"
+ ";q=0.8",
+ "Accept-Language": "en-US,en;q=0.5",
+ "Referer": "https://www.google.com/",
+ "DNT": "1",
+ "Connection": "keep-alive",
+ "Upgrade-Insecure-Requests": "1",
+}
+
+
+def _build_metadata(soup: Any, url: str) -> dict:
+ """Build metadata from BeautifulSoup output."""
+ metadata = {"source": url}
+ if title := soup.find("title"):
+ metadata["title"] = title.get_text()
+ if description := soup.find("meta", attrs={"name": "description"}):
+ metadata["description"] = description.get("content", "No description found.")
+ if html := soup.find("html"):
+ metadata["language"] = html.get("lang", "No language found.")
+ return metadata
+
+
+class AsyncHtmlLoader(BaseLoader):
+ """Load `HTML` asynchronously."""
+
+ def __init__(
+ self,
+ web_path: Union[str, List[str]],
+ header_template: Optional[dict] = None,
+ verify_ssl: Optional[bool] = True,
+ proxies: Optional[dict] = None,
+ autoset_encoding: bool = True,
+ encoding: Optional[str] = None,
+ default_parser: str = "html.parser",
+ requests_per_second: int = 2,
+ requests_kwargs: Optional[Dict[str, Any]] = None,
+ raise_for_status: bool = False,
+ ignore_load_errors: bool = False,
+ *,
+ preserve_order: bool = True,
+ trust_env: bool = False,
+ ):
+ """Initialize with a webpage path."""
+
+ # TODO: Deprecate web_path in favor of web_paths, and remove this
+ # left like this because there are a number of loaders that expect single
+ # urls
+ if isinstance(web_path, str):
+ self.web_paths = [web_path]
+ elif isinstance(web_path, List):
+ self.web_paths = web_path
+
+ headers = header_template or default_header_template
+ if not headers.get("User-Agent"):
+ try:
+ from fake_useragent import UserAgent
+
+ headers["User-Agent"] = UserAgent().random
+ except ImportError:
+ logger.info(
+ "fake_useragent not found, using default user agent."
+ "To get a realistic header for requests, "
+ "`pip install fake_useragent`."
+ )
+
+ self.session = requests.Session()
+ self.session.headers = dict(headers)
+ self.session.verify = verify_ssl
+
+ if proxies:
+ self.session.proxies.update(proxies)
+
+ self.requests_per_second = requests_per_second
+ self.default_parser = default_parser
+ self.requests_kwargs = requests_kwargs or {}
+ self.raise_for_status = raise_for_status
+ self.autoset_encoding = autoset_encoding
+ self.encoding = encoding
+ self.ignore_load_errors = ignore_load_errors
+ self.preserve_order = preserve_order
+
+ self.trust_env = trust_env
+
+ def _fetch_valid_connection_docs(self, url: str) -> Any:
+ if self.ignore_load_errors:
+ try:
+ return self.session.get(url, **self.requests_kwargs)
+ except Exception as e:
+ warnings.warn(str(e))
+ return None
+
+ return self.session.get(url, **self.requests_kwargs)
+
+ @staticmethod
+ def _check_parser(parser: str) -> None:
+ """Check that parser is valid for bs4."""
+ valid_parsers = ["html.parser", "lxml", "xml", "lxml-xml", "html5lib"]
+ if parser not in valid_parsers:
+ raise ValueError(
+ "`parser` must be one of " + ", ".join(valid_parsers) + "."
+ )
+
+ async def _fetch(
+ self, url: str, retries: int = 3, cooldown: int = 2, backoff: float = 1.5
+ ) -> str:
+ async with aiohttp.ClientSession(trust_env=self.trust_env) as session:
+ for i in range(retries):
+ try:
+ kwargs: Dict = dict(
+ headers=self.session.headers,
+ cookies=self.session.cookies.get_dict(),
+ **self.requests_kwargs,
+ )
+ if not self.session.verify:
+ kwargs["ssl"] = False
+ async with session.get(
+ url,
+ **kwargs,
+ ) as response:
+ try:
+ text = await response.text()
+ except UnicodeDecodeError:
+ logger.error(f"Failed to decode content from {url}")
+ text = ""
+ return text
+ except (aiohttp.ClientConnectionError, TimeoutError) as e:
+ if i == retries - 1 and self.ignore_load_errors:
+ logger.warning(f"Error fetching {url} after {retries} retries.")
+ return ""
+ elif i == retries - 1:
+ raise
+ else:
+ logger.warning(
+ f"Error fetching {url} with attempt "
+ f"{i + 1}/{retries}: {e}. Retrying..."
+ )
+ await asyncio.sleep(cooldown * backoff**i)
+ raise ValueError("retry count exceeded")
+
+ async def _fetch_with_rate_limit(
+ self, url: str, semaphore: asyncio.Semaphore
+ ) -> Tuple[str, str]:
+ async with semaphore:
+ return url, await self._fetch(url)
+
+ async def _lazy_fetch_all(
+ self, urls: List[str], preserve_order: bool
+ ) -> AsyncIterator[Tuple[str, str]]:
+ semaphore = asyncio.Semaphore(self.requests_per_second)
+ tasks = [
+ asyncio.create_task(self._fetch_with_rate_limit(url, semaphore))
+ for url in urls
+ ]
+ try:
+ from tqdm.asyncio import tqdm_asyncio
+
+ if preserve_order:
+ for task in tqdm_asyncio(
+ tasks, desc="Fetching pages", ascii=True, mininterval=1
+ ):
+ yield await task
+ else:
+ for task in tqdm_asyncio.as_completed(
+ tasks, desc="Fetching pages", ascii=True, mininterval=1
+ ):
+ yield await task
+ except ImportError:
+ warnings.warn("For better logging of progress, `pip install tqdm`")
+ if preserve_order:
+ for result in await asyncio.gather(*tasks):
+ yield result
+ else:
+ for task in asyncio.as_completed(tasks):
+ yield await task
+
+ async def fetch_all(self, urls: List[str]) -> List[str]:
+ """Fetch all urls concurrently with rate limiting."""
+ return [doc async for _, doc in self._lazy_fetch_all(urls, True)]
+
+ def _to_document(self, url: str, text: str) -> Document:
+ from bs4 import BeautifulSoup
+
+ if url.endswith(".xml"):
+ parser = "xml"
+ else:
+ parser = self.default_parser
+ self._check_parser(parser)
+ soup = BeautifulSoup(text, parser)
+ metadata = _build_metadata(soup, url)
+ return Document(page_content=text, metadata=metadata)
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load text from the url(s) in web_path."""
+ results: List[str]
+ try:
+ # Raises RuntimeError if there is no current event loop.
+ asyncio.get_running_loop()
+ # If there is a current event loop, we need to run the async code
+ # in a separate loop, in a separate thread.
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ future: Future[List[str]] = executor.submit(
+ asyncio.run,
+ self.fetch_all(self.web_paths),
+ )
+ results = future.result()
+ except RuntimeError:
+ results = asyncio.run(self.fetch_all(self.web_paths))
+
+ for i, text in enumerate(cast(List[str], results)):
+ yield self._to_document(self.web_paths[i], text)
+
+ async def alazy_load(self) -> AsyncIterator[Document]:
+ """Lazy load text from the url(s) in web_path."""
+ async for url, text in self._lazy_fetch_all(
+ self.web_paths, self.preserve_order
+ ):
+ yield self._to_document(url, text)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/athena.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/athena.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ba31820a676a583de86e2c67c2cfd444a7d7683
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/athena.py
@@ -0,0 +1,160 @@
+from __future__ import annotations
+
+import io
+import json
+import time
+from typing import Any, Dict, Iterator, List, Optional, Tuple
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class AthenaLoader(BaseLoader):
+ """Load documents from `AWS Athena`.
+
+ Each document represents one row of the result.
+ - By default, all columns are written into the `page_content` of the document
+ and none into the `metadata` of the document.
+ - If `metadata_columns` are provided then these columns are written
+ into the `metadata` of the document while the rest of the columns
+ are written into the `page_content` of the document.
+
+ To authenticate, the AWS client uses this method to automatically load credentials:
+ https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
+
+ If a specific credential profile should be used, you must pass
+ the name of the profile from the ~/.aws/credentials file that is to be used.
+
+ Make sure the credentials / roles used have the required policies to
+ access the Amazon Textract service.
+ """
+
+ def __init__(
+ self,
+ query: str,
+ database: str,
+ s3_output_uri: str,
+ profile_name: Optional[str] = None,
+ metadata_columns: Optional[List[str]] = None,
+ ):
+ """Initialize Athena document loader.
+
+ Args:
+ query: The query to run in Athena.
+ database: Athena database.
+ s3_output_uri: Athena output path.
+ profile_name: Optional. AWS credential profile, if profiles are being used.
+ metadata_columns: Optional. Columns written to Document `metadata`.
+ """
+ self.query = query
+ self.database = database
+ self.s3_output_uri = s3_output_uri
+ self.metadata_columns = metadata_columns if metadata_columns is not None else []
+
+ try:
+ import boto3
+ except ImportError:
+ raise ImportError(
+ "Could not import boto3 python package. "
+ "Please install it with `pip install boto3`."
+ )
+
+ try:
+ session = (
+ boto3.Session(profile_name=profile_name)
+ if profile_name is not None
+ else boto3.Session()
+ )
+ except Exception as e:
+ raise ValueError(
+ "Could not load credentials to authenticate with AWS client. "
+ "Please check that credentials in the specified "
+ "profile name are valid."
+ ) from e
+
+ self.athena_client = session.client("athena")
+ self.s3_client = session.client("s3")
+
+ def _execute_query(self) -> List[Dict[str, Any]]:
+ response = self.athena_client.start_query_execution(
+ QueryString=self.query,
+ QueryExecutionContext={"Database": self.database},
+ ResultConfiguration={"OutputLocation": self.s3_output_uri},
+ )
+ query_execution_id = response["QueryExecutionId"]
+ while True:
+ response = self.athena_client.get_query_execution(
+ QueryExecutionId=query_execution_id
+ )
+ state = response["QueryExecution"]["Status"]["State"]
+ if state == "SUCCEEDED":
+ break
+ elif state == "FAILED":
+ resp_status = response["QueryExecution"]["Status"]
+ state_change_reason = resp_status["StateChangeReason"]
+ err = f"Query Failed: {state_change_reason}"
+ raise Exception(err)
+ elif state == "CANCELLED":
+ raise Exception("Query was cancelled by the user.")
+ time.sleep(1)
+
+ result_set = self._get_result_set(query_execution_id)
+ return json.loads(result_set.to_json(orient="records"))
+
+ def _remove_suffix(self, input_string: str, suffix: str) -> str:
+ if suffix and input_string.endswith(suffix):
+ return input_string[: -len(suffix)]
+ return input_string
+
+ def _remove_prefix(self, input_string: str, suffix: str) -> str:
+ if suffix and input_string.startswith(suffix):
+ return input_string[len(suffix) :]
+ return input_string
+
+ def _get_result_set(self, query_execution_id: str) -> Any:
+ try:
+ import pandas as pd
+ except ImportError:
+ raise ImportError(
+ "Could not import pandas python package. "
+ "Please install it with `pip install pandas`."
+ )
+
+ output_uri = self.s3_output_uri
+ tokens = self._remove_prefix(
+ self._remove_suffix(output_uri, "/"), "s3://"
+ ).split("/")
+ bucket = tokens[0]
+ key = "/".join(tokens[1:] + [query_execution_id]) + ".csv"
+
+ obj = self.s3_client.get_object(Bucket=bucket, Key=key)
+ df = pd.read_csv(io.BytesIO(obj["Body"].read()), encoding="utf8")
+ return df
+
+ def _get_columns(
+ self, query_result: List[Dict[str, Any]]
+ ) -> Tuple[List[str], List[str]]:
+ content_columns = []
+ metadata_columns = []
+ all_columns = list(query_result[0].keys())
+ for key in all_columns:
+ if key in self.metadata_columns:
+ metadata_columns.append(key)
+ else:
+ content_columns.append(key)
+
+ return content_columns, metadata_columns
+
+ def lazy_load(self) -> Iterator[Document]:
+ query_result = self._execute_query()
+ content_columns, metadata_columns = self._get_columns(query_result)
+ for row in query_result:
+ page_content = "\n".join(
+ f"{k}: {v}" for k, v in row.items() if k in content_columns
+ )
+ metadata = {
+ k: v for k, v in row.items() if k in metadata_columns and v is not None
+ }
+ doc = Document(page_content=page_content, metadata=metadata)
+ yield doc
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/azlyrics.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/azlyrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..b763c8fb4b38249010afcfae421d44805cd01ae9
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/azlyrics.py
@@ -0,0 +1,18 @@
+from typing import List
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.web_base import WebBaseLoader
+
+
+class AZLyricsLoader(WebBaseLoader):
+ """Load `AZLyrics` webpages."""
+
+ def load(self) -> List[Document]:
+ """Load webpages into Documents."""
+ soup = self.scrape()
+ title = soup.title.text
+ lyrics = soup.find_all("div", {"class": ""})[2].text
+ text = title + lyrics
+ metadata = {"source": self.web_path}
+ return [Document(page_content=text, metadata=metadata)]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/azure_ai_data.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/azure_ai_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..05f404ddd1333f747175e250b22c943c6482d3d6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/azure_ai_data.py
@@ -0,0 +1,39 @@
+from typing import Iterator, Optional
+
+from langchain_community.docstore.document import Document
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.unstructured import UnstructuredFileIOLoader
+
+
+class AzureAIDataLoader(BaseLoader):
+ """Load from Azure AI Data."""
+
+ def __init__(self, url: str, glob: Optional[str] = None):
+ """Initialize with URL to a data asset or storage location
+ ."""
+ self.url = url
+ """URL to the data asset or storage location."""
+ self.glob_pattern = glob
+ """Optional glob pattern to select files. Defaults to None."""
+
+ def lazy_load(self) -> Iterator[Document]:
+ """A lazy loader for Documents."""
+ try:
+ from azureml.fsspec import AzureMachineLearningFileSystem
+ except ImportError as exc:
+ raise ImportError(
+ "Could not import azureml-fspec package."
+ "Please install it with `pip install azureml-fsspec`."
+ ) from exc
+
+ fs = AzureMachineLearningFileSystem(self.url)
+
+ if self.glob_pattern:
+ remote_paths_list = fs.glob(self.glob_pattern)
+ else:
+ remote_paths_list = fs.ls()
+
+ for remote_path in remote_paths_list:
+ with fs.open(remote_path) as f:
+ loader = UnstructuredFileIOLoader(file=f)
+ yield from loader.load()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/azure_blob_storage_container.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/azure_blob_storage_container.py
new file mode 100644
index 0000000000000000000000000000000000000000..8beb3afa9b5e702468126d5f06a49c5054bb3743
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/azure_blob_storage_container.py
@@ -0,0 +1,51 @@
+from typing import List
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.azure_blob_storage_file import (
+ AzureBlobStorageFileLoader,
+)
+from langchain_community.document_loaders.base import BaseLoader
+
+
+@deprecated(
+ since="0.4",
+ removal="1.0",
+ alternative_import="langchain_azure_storage.document_loaders.AzureBlobStorageLoader",
+)
+class AzureBlobStorageContainerLoader(BaseLoader):
+ """Load from `Azure Blob Storage` container."""
+
+ def __init__(self, conn_str: str, container: str, prefix: str = ""):
+ """Initialize with connection string, container and blob prefix."""
+ self.conn_str = conn_str
+ """Connection string for Azure Blob Storage."""
+ self.container = container
+ """Container name."""
+ self.prefix = prefix
+ """Prefix for blob names."""
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ try:
+ from azure.storage.blob import ContainerClient
+ except ImportError as exc:
+ raise ImportError(
+ "Could not import azure storage blob python package. "
+ "Please install it with `pip install azure-storage-blob`."
+ ) from exc
+
+ container = ContainerClient.from_connection_string(
+ conn_str=self.conn_str, container_name=self.container
+ )
+ docs = []
+ blob_list = container.list_blobs(name_starts_with=self.prefix)
+ for blob in blob_list:
+ loader = AzureBlobStorageFileLoader(
+ self.conn_str,
+ self.container,
+ blob.name,
+ )
+ docs.extend(loader.load())
+ return docs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/azure_blob_storage_file.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/azure_blob_storage_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..d85ab002b043fa28b18870f81d49d951344d4ea0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/azure_blob_storage_file.py
@@ -0,0 +1,50 @@
+import os
+import tempfile
+from typing import List
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
+
+
+@deprecated(
+ since="0.4",
+ removal="1.0",
+ alternative_import="langchain_azure_storage.document_loaders.AzureBlobStorageLoader",
+)
+class AzureBlobStorageFileLoader(BaseLoader):
+ """Load from `Azure Blob Storage` files."""
+
+ def __init__(self, conn_str: str, container: str, blob_name: str):
+ """Initialize with connection string, container and blob name."""
+ self.conn_str = conn_str
+ """Connection string for Azure Blob Storage."""
+ self.container = container
+ """Container name."""
+ self.blob = blob_name
+ """Blob name."""
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ try:
+ from azure.storage.blob import BlobClient
+ except ImportError as exc:
+ raise ImportError(
+ "Could not import azure storage blob python package. "
+ "Please install it with `pip install azure-storage-blob`."
+ ) from exc
+
+ client = BlobClient.from_connection_string(
+ conn_str=self.conn_str, container_name=self.container, blob_name=self.blob
+ )
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ file_path = f"{temp_dir}/{self.container}/{self.blob}"
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
+ with open(f"{file_path}", "wb") as file:
+ blob_data = client.download_blob()
+ blob_data.readinto(file)
+ loader = UnstructuredFileLoader(file_path)
+ return loader.load()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/baiducloud_bos_directory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/baiducloud_bos_directory.py
new file mode 100644
index 0000000000000000000000000000000000000000..c069c24f9b8e593fd04f538b97bd3b91c77f19d6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/baiducloud_bos_directory.py
@@ -0,0 +1,52 @@
+from typing import Any, Iterator
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class BaiduBOSDirectoryLoader(BaseLoader):
+ """Load from `Baidu BOS directory`."""
+
+ def __init__(self, conf: Any, bucket: str, prefix: str = ""):
+ """Initialize with BOS config, bucket and prefix.
+ :param conf(BosConfig): BOS config.
+ :param bucket(str): BOS bucket.
+ :param prefix(str): prefix.
+ """
+ self.conf = conf
+ self.bucket = bucket
+ self.prefix = prefix
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load documents."""
+ try:
+ from baidubce.services.bos.bos_client import BosClient
+ except ImportError:
+ raise ImportError(
+ "Please install bce-python-sdk with `pip install bce-python-sdk`."
+ )
+ client = BosClient(self.conf)
+ contents = []
+ marker = ""
+ while True:
+ response = client.list_objects(
+ bucket_name=self.bucket,
+ prefix=self.prefix,
+ marker=marker,
+ max_keys=1000,
+ )
+ contents_len = len(response.contents)
+ contents.extend(response.contents)
+ if response.is_truncated or contents_len < int(str(response.max_keys)):
+ break
+ marker = response.next_marker
+ from langchain_community.document_loaders.baiducloud_bos_file import (
+ BaiduBOSFileLoader,
+ )
+
+ for content in contents:
+ if str(content.key).endswith("/"):
+ continue
+ loader = BaiduBOSFileLoader(self.conf, self.bucket, str(content.key))
+ yield loader.load()[0]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/baiducloud_bos_file.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/baiducloud_bos_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..dca4cd544f167462f10f7653f5a049113f186958
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/baiducloud_bos_file.py
@@ -0,0 +1,51 @@
+import logging
+import os
+import tempfile
+from typing import Any, Iterator
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
+
+logger = logging.getLogger(__name__)
+
+
+class BaiduBOSFileLoader(BaseLoader):
+ """Load from `Baidu Cloud BOS` file."""
+
+ def __init__(self, conf: Any, bucket: str, key: str):
+ """Initialize with BOS config, bucket and key name.
+ :param conf(BceClientConfiguration): BOS config.
+ :param bucket(str): BOS bucket.
+ :param key(str): BOS file key.
+ """
+ self.conf = conf
+ self.bucket = bucket
+ self.key = key
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load documents."""
+ try:
+ from baidubce.services.bos.bos_client import BosClient
+ except ImportError:
+ raise ImportError(
+ "Please using `pip install bce-python-sdk`"
+ + " before import bos related package."
+ )
+
+ # Initialize BOS Client
+ client = BosClient(self.conf)
+ with tempfile.TemporaryDirectory() as temp_dir:
+ file_path = f"{temp_dir}/{self.bucket}/{self.key}"
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
+ # Download the file to a destination
+ logger.debug(f"get object key {self.key} to file {file_path}")
+ client.get_object_to_file(self.bucket, self.key, file_path)
+ try:
+ loader = UnstructuredFileLoader(file_path)
+ documents = loader.load()
+ return iter(documents)
+ except Exception as ex:
+ logger.error(f"load document error = {ex}")
+ return iter([Document(page_content="")])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1c3d82524f15632d40738e9863fec332e5792ca
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/base.py
@@ -0,0 +1,6 @@
+from langchain_core.document_loaders import BaseBlobParser, BaseLoader
+
+__all__ = [
+ "BaseBlobParser",
+ "BaseLoader",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/base_o365.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/base_o365.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbc07b504a8ede40d455a5c3020910323fecfb6c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/base_o365.py
@@ -0,0 +1,334 @@
+"""Base class for all loaders that uses O365 Package"""
+
+from __future__ import annotations
+
+import logging
+import mimetypes
+import os
+import re
+import tempfile
+import urllib
+from abc import abstractmethod
+from datetime import datetime
+from pathlib import Path, PurePath
+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Union
+
+from pydantic import (
+ BaseModel,
+ Field,
+ FilePath,
+ PrivateAttr,
+ SecretStr,
+)
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+from langchain_community.document_loaders.base import BaseBlobParser, BaseLoader
+from langchain_community.document_loaders.blob_loaders.file_system import (
+ FileSystemBlobLoader,
+)
+from langchain_community.document_loaders.blob_loaders.schema import Blob
+from langchain_community.document_loaders.parsers.generic import MimeTypeBasedParser
+from langchain_community.document_loaders.parsers.registry import get_parser
+
+if TYPE_CHECKING:
+ from O365 import Account
+ from O365.drive import Drive, Folder
+
+logger = logging.getLogger(__name__)
+
+CHUNK_SIZE = 1024 * 1024 * 5
+
+
+class _O365Settings(BaseSettings):
+ client_id: str = Field(..., alias="O365_CLIENT_ID")
+ client_secret: SecretStr = Field(..., alias="O365_CLIENT_SECRET")
+
+ model_config = SettingsConfigDict(
+ case_sensitive=False, env_file=".env", env_prefix="", extra="ignore"
+ )
+
+
+class _O365TokenStorage(BaseSettings):
+ token_path: FilePath = Path.home() / ".credentials" / "o365_token.txt"
+
+
+def fetch_mime_types(file_types: Sequence[str]) -> Dict[str, str]:
+ """Fetch the mime types for the specified file types."""
+ mime_types_mapping = {}
+ for ext in file_types:
+ mime_type, _ = mimetypes.guess_type(f"file.{ext}")
+ if mime_type:
+ mime_types_mapping[ext] = mime_type
+ else:
+ raise ValueError(f"Unknown mimetype of extension {ext}")
+ return mime_types_mapping
+
+
+def fetch_extensions(mime_types: Sequence[str]) -> Dict[str, str]:
+ """Fetch the mime types for the specified file types."""
+ mime_types_mapping = {}
+ for mime_type in mime_types:
+ ext = mimetypes.guess_extension(mime_type)
+ if ext:
+ mime_types_mapping[ext[1:]] = mime_type # ignore leading `.`
+ else:
+ raise ValueError(f"Unknown mimetype {mime_type}")
+ return mime_types_mapping
+
+
+class O365BaseLoader(BaseLoader, BaseModel):
+ """Base class for all loaders that uses O365 Package"""
+
+ settings: _O365Settings = Field(default_factory=_O365Settings) # type: ignore[arg-type]
+ """Settings for the Office365 API client."""
+ auth_with_token: bool = False
+ """Whether to authenticate with a token or not. Defaults to False."""
+ chunk_size: Union[int, str] = CHUNK_SIZE
+ """Number of bytes to retrieve from each api call to the server. int or 'auto'."""
+ recursive: bool = False
+ """Should the loader recursively load subfolders?"""
+ modified_since: Optional[datetime] = None
+ """Only fetch documents modified since given datetime. The datetime object
+ must be timezone aware."""
+ handlers: Optional[Dict[str, Any]] = {}
+ """
+ Provide custom handlers for MimeTypeBasedParser.
+
+ Pass a dictionary mapping either file extensions (like "doc", "pdf", etc.)
+ or MIME types (like "application/pdf", "text/plain", etc.) to parsers.
+ Note that you must use either file extensions or MIME types exclusively and
+ cannot mix them.
+
+ Do not include the leading dot for file extensions.
+
+ Example using file extensions:
+ ```python
+ handlers = {
+ "doc": MsWordParser(),
+ "pdf": PDFMinerParser(),
+ "txt": TextParser()
+ }
+ ```
+
+ Example using MIME types:
+ ```python
+ handlers = {
+ "application/msword": MsWordParser(),
+ "application/pdf": PDFMinerParser(),
+ "text/plain": TextParser()
+ }
+ ```
+ """
+
+ _blob_parser: BaseBlobParser = PrivateAttr()
+ _file_types: Sequence[str] = PrivateAttr()
+ _mime_types: Dict[str, str] = PrivateAttr()
+
+ def __init__(self, **kwargs: Any) -> None:
+ super().__init__(**kwargs)
+ if self.handlers:
+ handler_keys = list(self.handlers.keys())
+ try:
+ # assume handlers.keys() are file extensions
+ self._mime_types = fetch_mime_types(handler_keys)
+ self._file_types = list(set(handler_keys))
+ mime_handlers = {
+ self._mime_types[extension]: handler
+ for extension, handler in self.handlers.items()
+ }
+ except ValueError:
+ try:
+ # assume handlers.keys() are mime types
+ self._mime_types = fetch_extensions(handler_keys)
+ self._file_types = list(set(self._mime_types.keys()))
+ mime_handlers = self.handlers
+ except ValueError:
+ raise ValueError(
+ "`handlers` keys must be either file extensions or mimetypes.\n"
+ f"{handler_keys} could not be interpreted as either.\n"
+ "File extensions and mimetypes cannot mix. "
+ "Use either one or the other"
+ )
+
+ self._blob_parser = MimeTypeBasedParser(
+ handlers=mime_handlers, fallback_parser=None
+ )
+ else:
+ self._blob_parser = get_parser("default")
+ if not isinstance(self._blob_parser, MimeTypeBasedParser):
+ raise TypeError(
+ 'get_parser("default) was supposed to return MimeTypeBasedParser.'
+ f"It returned {type(self._blob_parser)}"
+ )
+ self._mime_types = fetch_extensions(list(self._blob_parser.handlers.keys()))
+
+ @property
+ def _fetch_mime_types(self) -> Dict[str, str]:
+ """Return a dict of supported file types to corresponding mime types."""
+ return self._mime_types
+
+ @property
+ @abstractmethod
+ def _scopes(self) -> List[str]:
+ """Return required scopes."""
+
+ def _load_from_folder(self, folder: Folder) -> Iterable[Blob]:
+ """Lazily load all files from a specified folder of the configured MIME type.
+
+ Args:
+ folder: The Folder instance from which the files are to be loaded. This
+ Folder instance should represent a directory in a file system where the
+ files are stored.
+
+ Yields:
+ An iterator that yields Blob instances, which are binary representations of
+ the files loaded from the folder.
+ """
+ file_mime_types = self._fetch_mime_types
+ items = folder.get_items()
+ metadata_dict: Dict[str, Dict[str, Any]] = {}
+ with tempfile.TemporaryDirectory() as temp_dir:
+ os.makedirs(os.path.dirname(temp_dir), exist_ok=True)
+ for file in items:
+ if file.is_file:
+ if file.mime_type in list(file_mime_types.values()):
+ if (not self.modified_since) or (
+ file.modified > self.modified_since
+ ):
+ source = file.web_url
+ if re.search(
+ r"Doc.aspx\?sourcedoc=.*file=([^&]+)", file.web_url
+ ):
+ source = (
+ file._parent.web_url
+ + "/"
+ + urllib.parse.quote(file.name)
+ )
+ file.download(to_path=temp_dir, chunk_size=self.chunk_size)
+ metadata_dict[file.name] = {
+ "source": source,
+ "mime_type": file.mime_type,
+ "created": str(file.created),
+ "modified": str(file.modified),
+ "created_by": str(file.created_by),
+ "modified_by": str(file.modified_by),
+ "description": file.description,
+ "id": str(file.object_id),
+ }
+
+ loader = FileSystemBlobLoader(path=temp_dir)
+ for blob in loader.yield_blobs():
+ if not isinstance(blob.path, PurePath):
+ raise NotImplementedError("Expected blob path to be a PurePath")
+ if blob.path:
+ file_metadata_ = metadata_dict.get(str(blob.path.name), {})
+ blob.metadata.update(file_metadata_)
+ yield blob
+ if self.recursive:
+ for subfolder in folder.get_child_folders():
+ yield from self._load_from_folder(subfolder)
+
+ def _load_from_object_ids(
+ self, drive: Drive, object_ids: List[str]
+ ) -> Iterable[Blob]:
+ """Lazily load files specified by their object_ids from a drive.
+
+ Load files into the system as binary large objects (Blobs) and return Iterable.
+
+ Args:
+ drive: The Drive instance from which the files are to be loaded. This Drive
+ instance should represent a cloud storage service or similar storage
+ system where the files are stored.
+ object_ids: A list of object_id strings. Each object_id represents a unique
+ identifier for a file in the drive.
+
+ Yields:
+ An iterator that yields Blob instances, which are binary representations of
+ the files loaded from the drive using the specified object_ids.
+ """
+ file_mime_types = self._fetch_mime_types
+ metadata_dict: Dict[str, Dict[str, Any]] = {}
+ with tempfile.TemporaryDirectory() as temp_dir:
+ for object_id in object_ids:
+ file = drive.get_item(object_id)
+ if not file:
+ logging.warning(
+ "There isn't a file with"
+ f"object_id {object_id} in drive {drive}."
+ )
+ continue
+ if file.is_file:
+ if file.mime_type in list(file_mime_types.values()):
+ source = file.web_url
+ if re.search(
+ r"Doc.aspx\?sourcedoc=.*file=([^&]+)", file.web_url
+ ):
+ source = (
+ file._parent.web_url
+ + "/"
+ + urllib.parse.quote(file.name)
+ )
+ file.download(to_path=temp_dir, chunk_size=self.chunk_size)
+ metadata_dict[file.name] = {
+ "source": source,
+ "mime_type": file.mime_type,
+ "created": file.created,
+ "modified": file.modified,
+ "created_by": str(file.created_by),
+ "modified_by": str(file.modified_by),
+ "description": file.description,
+ "id": str(file.object_id),
+ }
+
+ loader = FileSystemBlobLoader(path=temp_dir)
+ for blob in loader.yield_blobs():
+ if not isinstance(blob.path, PurePath):
+ raise NotImplementedError("Expected blob path to be a PurePath")
+ if blob.path:
+ file_metadata_ = metadata_dict.get(str(blob.path.name), {})
+ blob.metadata.update(file_metadata_)
+ yield blob
+
+ def _auth(self) -> Account:
+ """Authenticates the OneDrive API client
+
+ Returns:
+ The authenticated Account object.
+ """
+ try:
+ from O365 import Account, FileSystemTokenBackend
+ except ImportError:
+ raise ImportError(
+ "O365 package not found, please install it with `pip install o365`"
+ )
+ if self.auth_with_token:
+ token_storage = _O365TokenStorage()
+ token_path = token_storage.token_path
+ token_backend = FileSystemTokenBackend(
+ token_path=token_path.parent, token_filename=token_path.name
+ )
+ account = Account(
+ credentials=(
+ self.settings.client_id,
+ self.settings.client_secret.get_secret_value(),
+ ),
+ scopes=self._scopes,
+ token_backend=token_backend,
+ **{"raise_http_errors": False},
+ )
+ else:
+ token_backend = FileSystemTokenBackend(
+ token_path=Path.home() / ".credentials"
+ )
+ account = Account(
+ credentials=(
+ self.settings.client_id,
+ self.settings.client_secret.get_secret_value(),
+ ),
+ scopes=self._scopes,
+ token_backend=token_backend,
+ **{"raise_http_errors": False},
+ )
+ # make the auth
+ account.authenticate()
+ return account
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/bibtex.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/bibtex.py
new file mode 100644
index 0000000000000000000000000000000000000000..49f9c6b2dbe260a8c3fa9617af63dd9999dc25cd
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/bibtex.py
@@ -0,0 +1,98 @@
+import logging
+import re
+from pathlib import Path
+from typing import Any, Iterator, List, Mapping, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.bibtex import BibtexparserWrapper
+
+logger = logging.getLogger(__name__)
+
+
+class BibtexLoader(BaseLoader):
+ """Load a `bibtex` file.
+
+ Each document represents one entry from the bibtex file.
+
+ If a PDF file is present in the `file` bibtex field, the original PDF
+ is loaded into the document text. If no such file entry is present,
+ the `abstract` field is used instead.
+ """
+
+ def __init__(
+ self,
+ file_path: str,
+ *,
+ parser: Optional[BibtexparserWrapper] = None,
+ max_docs: Optional[int] = None,
+ max_content_chars: Optional[int] = 4_000,
+ load_extra_metadata: bool = False,
+ file_pattern: str = r"[^:]+\.pdf",
+ ):
+ """Initialize the BibtexLoader.
+
+ Args:
+ file_path: Path to the bibtex file.
+ parser: The parser to use. If None, a default parser is used.
+ max_docs: Max number of associated documents to load. Use -1 means
+ no limit.
+ max_content_chars: Maximum number of characters to load from the PDF.
+ load_extra_metadata: Whether to load extra metadata from the PDF.
+ file_pattern: Regex pattern to match the file name in the bibtex.
+ """
+ self.file_path = file_path
+ self.parser = parser or BibtexparserWrapper()
+ self.max_docs = max_docs
+ self.max_content_chars = max_content_chars
+ self.load_extra_metadata = load_extra_metadata
+ self.file_regex = re.compile(file_pattern)
+
+ def _load_entry(self, entry: Mapping[str, Any]) -> Optional[Document]:
+ import fitz
+
+ parent_dir = Path(self.file_path).parent
+ # regex is useful for Zotero flavor bibtex files
+ file_names = self.file_regex.findall(entry.get("file", ""))
+ if not file_names:
+ return None
+ texts: List[str] = []
+ for file_name in file_names:
+ try:
+ with fitz.open(parent_dir / file_name) as f:
+ texts.extend(page.get_text() for page in f)
+ except FileNotFoundError as e:
+ logger.debug(e)
+ content = "\n".join(texts) or entry.get("abstract", "")
+ if self.max_content_chars:
+ content = content[: self.max_content_chars]
+ metadata = self.parser.get_metadata(entry, load_extra=self.load_extra_metadata)
+ return Document(
+ page_content=content,
+ metadata=metadata,
+ )
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load bibtex file using bibtexparser and get the article texts plus the
+ article metadata.
+ See https://bibtexparser.readthedocs.io/en/master/
+
+ Returns:
+ a list of documents with the document.page_content in text format
+ """
+ try:
+ import fitz # noqa: F401
+ except ImportError:
+ raise ImportError(
+ "PyMuPDF package not found, please install it with "
+ "`pip install pymupdf`"
+ )
+
+ entries = self.parser.load_bibtex_entries(self.file_path)
+ if self.max_docs:
+ entries = entries[: self.max_docs]
+ for entry in entries:
+ doc = self._load_entry(entry)
+ if doc:
+ yield doc
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/bigquery.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/bigquery.py
new file mode 100644
index 0000000000000000000000000000000000000000..25ce99b3c384f4eb4fa740015e68d34cc272bcc8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/bigquery.py
@@ -0,0 +1,100 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, List, Optional
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.vertexai import get_client_info
+
+if TYPE_CHECKING:
+ from google.auth.credentials import Credentials
+
+
+@deprecated(
+ since="0.0.32",
+ removal="1.0",
+ alternative_import="langchain_google_community.BigQueryLoader",
+)
+class BigQueryLoader(BaseLoader):
+ """Load from the Google Cloud Platform `BigQuery`.
+
+ Each document represents one row of the result. The `page_content_columns`
+ are written into the `page_content` of the document. The `metadata_columns`
+ are written into the `metadata` of the document. By default, all columns
+ are written into the `page_content` and none into the `metadata`.
+
+ """
+
+ def __init__(
+ self,
+ query: str,
+ project: Optional[str] = None,
+ page_content_columns: Optional[List[str]] = None,
+ metadata_columns: Optional[List[str]] = None,
+ credentials: Optional[Credentials] = None,
+ ):
+ """Initialize BigQuery document loader.
+
+ Args:
+ query: The query to run in BigQuery.
+ project: Optional. The project to run the query in.
+ page_content_columns: Optional. The columns to write into the `page_content`
+ of the document.
+ metadata_columns: Optional. The columns to write into the `metadata` of the
+ document.
+ credentials : google.auth.credentials.Credentials, optional
+ Credentials for accessing Google APIs. Use this parameter to override
+ default credentials, such as to use Compute Engine
+ (`google.auth.compute_engine.Credentials`) or Service Account
+ (`google.oauth2.service_account.Credentials`) credentials directly.
+ """
+ self.query = query
+ self.project = project
+ self.page_content_columns = page_content_columns
+ self.metadata_columns = metadata_columns
+ self.credentials = credentials
+
+ def load(self) -> List[Document]:
+ try:
+ from google.cloud import bigquery
+ except ImportError as ex:
+ raise ImportError(
+ "Could not import google-cloud-bigquery python package. "
+ "Please install it with `pip install google-cloud-bigquery`."
+ ) from ex
+
+ bq_client = bigquery.Client(
+ credentials=self.credentials,
+ project=self.project,
+ client_info=get_client_info(module="bigquery"),
+ )
+ if not bq_client.project:
+ error_desc = (
+ "GCP project for Big Query is not set! Either provide a "
+ "`project` argument during BigQueryLoader instantiation, "
+ "or set a default project with `gcloud config set project` "
+ "command."
+ )
+ raise ValueError(error_desc)
+ query_result = bq_client.query(self.query).result()
+ docs: List[Document] = []
+
+ page_content_columns = self.page_content_columns
+ metadata_columns = self.metadata_columns
+
+ if page_content_columns is None:
+ page_content_columns = [column.name for column in query_result.schema]
+ if metadata_columns is None:
+ metadata_columns = []
+
+ for row in query_result:
+ page_content = "\n".join(
+ f"{k}: {v}" for k, v in row.items() if k in page_content_columns
+ )
+ metadata = {k: v for k, v in row.items() if k in metadata_columns}
+ doc = Document(page_content=page_content, metadata=metadata)
+ docs.append(doc)
+
+ return docs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/bilibili.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/bilibili.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8d4d36b4054cb7bdc4cfecf9cf328a1e45c0ca2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/bilibili.py
@@ -0,0 +1,136 @@
+import json
+import re
+import warnings
+from typing import List, Tuple
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+# Pre-compile regular expressions for video ID extraction
+BV_PATTERN = re.compile(r"BV\w+")
+AV_PATTERN = re.compile(r"av[0-9]+")
+PAGE_INDEX_PATTERN = re.compile(r"p=(\d+)")
+
+
+class BiliBiliLoader(BaseLoader):
+ """
+ Load fetching transcripts from BiliBili videos.
+ """
+
+ def __init__(
+ self,
+ video_urls: List[str],
+ sessdata: str = "",
+ bili_jct: str = "",
+ buvid3: str = "",
+ ):
+ """
+ Initialize the loader with BiliBili video URLs and authentication cookies.
+ if no authentication cookies are provided, the loader can't get transcripts
+ and will only fetch videos info.
+
+ Args:
+ video_urls (List[str]): List of BiliBili video URLs.
+ sessdata (str): SESSDATA cookie value for authentication.
+ bili_jct (str): BILI_JCT cookie value for authentication.
+ buvid3 (str): BUVI3 cookie value for authentication.
+ """
+ self.video_urls = video_urls
+ self.credential = None
+ try:
+ from bilibili_api import video
+ except ImportError:
+ raise ImportError(
+ "requests package not found, please install it with "
+ "`pip install bilibili-api-python`"
+ )
+ if sessdata and bili_jct and buvid3:
+ self.credential = video.Credential(
+ sessdata=sessdata, bili_jct=bili_jct, buvid3=buvid3
+ )
+
+ def load(self) -> List[Document]:
+ """
+ Load and return a list of documents containing video transcripts.
+
+ Returns:
+ List[Document]: List of Document objects transcripts and metadata.
+ """
+ results = []
+ for url in self.video_urls:
+ transcript, video_info = self._get_bilibili_subs_and_info(url)
+ doc = Document(page_content=transcript, metadata=video_info)
+ results.append(doc)
+
+ return results
+
+ def _get_bilibili_subs_and_info(self, url: str) -> Tuple[str, dict]:
+ """
+ Retrieve video information and transcript for a given BiliBili URL.
+ """
+ bvid = BV_PATTERN.search(url)
+ try:
+ from bilibili_api import sync, video
+ except ImportError:
+ raise ImportError(
+ "requests package not found, please install it with "
+ "`pip install bilibili-api-python`"
+ )
+ if bvid:
+ v = video.Video(bvid=bvid.group(), credential=self.credential)
+ else:
+ aid = AV_PATTERN.search(url)
+ if aid:
+ v = video.Video(aid=int(aid.group()[2:]), credential=self.credential)
+ else:
+ raise ValueError(f"Unable to find a valid video ID in URL: {url}")
+
+ video_info = sync(v.get_info())
+ video_info.update({"url": url})
+
+ # Return if no credential is provided
+ if not self.credential:
+ return "", video_info
+
+ cid = 0
+ page_match = PAGE_INDEX_PATTERN.search(url)
+ if page_match:
+ cid = video_info["pages"][int(page_match.group(1)) - 1][
+ "cid"
+ ] # Bilibili page index starts from 1
+ else:
+ cid = video_info["cid"]
+
+ # Fetching and processing subtitles
+ sub = sync(v.get_subtitle(cid))
+ sub_list = sub.get("subtitles", [])
+ if sub_list:
+ sub_url = sub_list[0].get("subtitle_url", "")
+ if not sub_url.startswith("http"):
+ sub_url = "https:" + sub_url
+
+ response = requests.get(sub_url)
+ if response.status_code == 200:
+ raw_sub_titles = json.loads(response.content).get("body", [])
+ raw_transcript = " ".join([c["content"] for c in raw_sub_titles])
+
+ raw_transcript_with_meta_info = (
+ f"Video Title: {video_info['title']}, "
+ f"description: {video_info['desc']}\n\n"
+ f"Transcript: {raw_transcript}"
+ )
+ return raw_transcript_with_meta_info, video_info
+ else:
+ warnings.warn(
+ f"Failed to fetch subtitles for {url}. "
+ f"HTTP Status Code: {response.status_code}"
+ )
+ else:
+ warnings.warn(
+ f"No subtitles found for video: {url}. Returning empty transcript."
+ )
+
+ # Return empty transcript if no subtitles are found
+ return "", video_info
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/blackboard.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/blackboard.py
new file mode 100644
index 0000000000000000000000000000000000000000..bedc937c7f5906c447b5dfcfe404a458ac0dc99f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/blackboard.py
@@ -0,0 +1,302 @@
+import contextlib
+import re
+from pathlib import Path
+from typing import Any, List, Optional, Tuple
+from urllib.parse import unquote
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.directory import DirectoryLoader
+from langchain_community.document_loaders.pdf import PyPDFLoader
+from langchain_community.document_loaders.web_base import WebBaseLoader
+
+
+class BlackboardLoader(WebBaseLoader):
+ """Load a `Blackboard` course.
+
+ This loader is not compatible with all Blackboard courses. It is only
+ compatible with courses that use the new Blackboard interface.
+ To use this loader, you must have the BbRouter cookie. You can get this
+ cookie by logging into the course and then copying the value of the
+ BbRouter cookie from the browser's developer tools.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import BlackboardLoader
+
+ loader = BlackboardLoader(
+ blackboard_course_url="https://blackboard.example.com/webapps/blackboard/execute/announcement?method=search&context=course_entry&course_id=_123456_1",
+ bbrouter="expires:12345...",
+ )
+ documents = loader.load()
+
+ """
+
+ def __init__(
+ self,
+ blackboard_course_url: str,
+ bbrouter: str,
+ load_all_recursively: bool = True,
+ basic_auth: Optional[Tuple[str, str]] = None,
+ cookies: Optional[dict] = None,
+ continue_on_failure: bool = False,
+ show_progress: bool = True,
+ ):
+ """Initialize with blackboard course url.
+
+ The BbRouter cookie is required for most blackboard courses.
+
+ Args:
+ blackboard_course_url: Blackboard course url.
+ bbrouter: BbRouter cookie.
+ load_all_recursively: If True, load all documents recursively.
+ basic_auth: Basic auth credentials.
+ cookies: Cookies.
+ continue_on_failure: whether to continue loading the sitemap if an error
+ occurs loading a url, emitting a warning instead of raising an
+ exception. Setting this to True makes the loader more robust, but also
+ may result in missing data. Default: False
+ show_progress: whether to show a progress bar while loading. Default: True
+
+ Raises:
+ ValueError: If blackboard course url is invalid.
+ """
+ super().__init__(
+ web_paths=(blackboard_course_url),
+ continue_on_failure=continue_on_failure,
+ show_progress=show_progress,
+ )
+ # Get base url
+ try:
+ self.base_url = blackboard_course_url.split("/webapps/blackboard")[0]
+ except IndexError:
+ raise IndexError(
+ "Invalid blackboard course url. "
+ "Please provide a url that starts with "
+ "https:///webapps/blackboard"
+ )
+ if basic_auth is not None:
+ self.session.auth = basic_auth
+ # Combine cookies
+ if cookies is None:
+ cookies = {}
+ cookies.update({"BbRouter": bbrouter})
+ self.session.cookies.update(cookies)
+ self.load_all_recursively = load_all_recursively
+ self.check_bs4()
+
+ def check_bs4(self) -> None:
+ """Check if BeautifulSoup4 is installed.
+
+ Raises:
+ ImportError: If BeautifulSoup4 is not installed.
+ """
+ try:
+ import bs4 # noqa: F401
+ except ImportError:
+ raise ImportError(
+ "BeautifulSoup4 is required for BlackboardLoader. "
+ "Please install it with `pip install beautifulsoup4`."
+ )
+
+ def load(self) -> List[Document]:
+ """Load data into Document objects.
+
+ Returns:
+ List of Documents.
+ """
+ if self.load_all_recursively:
+ soup_info = self.scrape()
+ self.folder_path = self._get_folder_path(soup_info)
+ relative_paths = self._get_paths(soup_info)
+ documents = []
+ for path in relative_paths:
+ url = self.base_url + path
+ print(f"Fetching documents from {url}") # noqa: T201
+ soup_info = self._scrape(url)
+ with contextlib.suppress(ValueError):
+ documents.extend(self._get_documents(soup_info))
+ return documents
+ else:
+ print(f"Fetching documents from {self.web_path}") # noqa: T201
+ soup_info = self.scrape()
+ self.folder_path = self._get_folder_path(soup_info)
+ return self._get_documents(soup_info)
+
+ def _get_folder_path(self, soup: Any) -> str:
+ """Get the folder path to save the Documents in.
+
+ Args:
+ soup: BeautifulSoup4 soup object.
+
+ Returns:
+ Folder path.
+ """
+ # Get the course name
+ course_name = soup.find("span", {"id": "crumb_1"})
+ if course_name is None:
+ raise ValueError("No course name found.")
+ course_name = course_name.text.strip()
+ # Prepare the folder path
+ course_name_clean = (
+ unquote(course_name)
+ .replace(" ", "_")
+ .replace("/", "_")
+ .replace(":", "_")
+ .replace(",", "_")
+ .replace("?", "_")
+ .replace("'", "_")
+ .replace("!", "_")
+ .replace('"', "_")
+ )
+ # Get the folder path
+ folder_path = Path(".") / course_name_clean
+ return str(folder_path)
+
+ def _get_documents(self, soup: Any) -> List[Document]:
+ """Fetch content from page and return Documents.
+
+ Args:
+ soup: BeautifulSoup4 soup object.
+
+ Returns:
+ List of documents.
+ """
+ attachments = self._get_attachments(soup)
+ self._download_attachments(attachments)
+ documents = self._load_documents()
+ return documents
+
+ def _get_attachments(self, soup: Any) -> List[str]:
+ """Get all attachments from a page.
+
+ Args:
+ soup: BeautifulSoup4 soup object.
+
+ Returns:
+ List of attachments.
+ """
+ from bs4 import BeautifulSoup, Tag
+
+ # Get content list
+ content_list: BeautifulSoup
+ content_list = soup.find("ul", {"class": "contentList"})
+ if content_list is None:
+ raise ValueError("No content list found.")
+ # Get all attachments
+ attachments = []
+ attachment: Tag
+ for attachment in content_list.find_all("ul", {"class": "attachments"}):
+ link: Tag
+ for link in attachment.find_all("a"):
+ href = link.get("href")
+ # Only add if href is not None and does not start with #
+ if href is not None and not href.startswith("#"): # type: ignore[union-attr]
+ attachments.append(href)
+ return attachments # type: ignore[return-value]
+
+ def _download_attachments(self, attachments: List[str]) -> None:
+ """Download all attachments.
+
+ Args:
+ attachments: List of attachments.
+ """
+ # Make sure the folder exists
+ Path(self.folder_path).mkdir(parents=True, exist_ok=True)
+ # Download all attachments
+ for attachment in attachments:
+ self.download(attachment)
+
+ def _load_documents(self) -> List[Document]:
+ """Load all documents in the folder.
+
+ Returns:
+ List of documents.
+ """
+ # Create the document loader
+ loader = DirectoryLoader(
+ path=self.folder_path,
+ glob="*.pdf",
+ loader_cls=PyPDFLoader, # type: ignore[arg-type]
+ )
+ # Load the documents
+ documents = loader.load()
+ # Return all documents
+ return documents
+
+ def _get_paths(self, soup: Any) -> List[str]:
+ """Get all relative paths in the navbar."""
+ relative_paths = []
+ course_menu = soup.find("ul", {"class": "courseMenu"})
+ if course_menu is None:
+ raise ValueError("No course menu found.")
+ for link in course_menu.find_all("a"):
+ href = link.get("href")
+ if href is not None and href.startswith("/"):
+ relative_paths.append(href)
+ return relative_paths
+
+ def download(self, path: str) -> None:
+ """Download a file from an url.
+
+ Args:
+ path: Path to the file.
+ """
+ # Get the file content
+ response = self.session.get(self.base_url + path, allow_redirects=True)
+ # Get the filename
+ filename = self.parse_filename(response.url)
+ # Write the file to disk
+ with open(Path(self.folder_path) / filename, "wb") as f:
+ f.write(response.content)
+
+ def parse_filename(self, url: str) -> str:
+ """Parse the filename from an url.
+
+ Args:
+ url: Url to parse the filename from.
+
+ Returns:
+ The filename.
+ """
+ if (url_path := Path(url)) and url_path.suffix == ".pdf":
+ return url_path.name
+ else:
+ return self._parse_filename_from_url(url)
+
+ def _parse_filename_from_url(self, url: str) -> str:
+ """Parse the filename from an url.
+
+ Args:
+ url: Url to parse the filename from.
+
+ Returns:
+ The filename.
+
+ Raises:
+ ValueError: If the filename could not be parsed.
+ """
+ filename_matches = re.search(r"filename%2A%3DUTF-8%27%27(.+)", url)
+ if filename_matches:
+ filename = filename_matches.group(1)
+ else:
+ raise ValueError(f"Could not parse filename from {url}")
+ if ".pdf" not in filename:
+ raise ValueError(f"Incorrect file type: {filename}")
+ filename = filename.split(".pdf")[0] + ".pdf"
+ filename = unquote(filename)
+ filename = filename.replace("%20", " ")
+ return filename
+
+
+if __name__ == "__main__":
+ loader = BlackboardLoader(
+ "https:///webapps/blackboard/content/listContent.jsp?course_id=__1&content_id=__1&mode=reset",
+ "",
+ load_all_recursively=True,
+ )
+ documents = loader.load()
+ print(f"Loaded {len(documents)} pages of PDFs from {loader.web_path}") # noqa: T201
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/blockchain.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/blockchain.py
new file mode 100644
index 0000000000000000000000000000000000000000..8db66fd6ab206a6528f2c2d5202b6853a7ca1cfc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/blockchain.py
@@ -0,0 +1,182 @@
+import os
+import re
+import time
+from enum import Enum
+from typing import List, Optional
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class BlockchainType(Enum):
+ """Enumerator of the supported blockchains."""
+
+ ETH_MAINNET = "eth-mainnet"
+ ETH_GOERLI = "eth-goerli"
+ ETH_SEPOLIA = "eth-sepolia"
+ ETH_HOLESKY = "eth-holesky"
+ POLYGON_MAINNET = "polygon-mainnet"
+ POLYGON_MUMBAI = "polygon-mumbai"
+ POLYGON_AMOY = "polygon-amoy"
+ ARB_MAINNET = "arb-mainnet"
+ ARB_SEPOLIA = "arb-sepolia"
+ OP_MAINNET = "opt-mainnet"
+ OP_SEPOLIA = "opt-sepolia"
+ BASE_MAINNET = "base-mainnet"
+ BASE_SEPOLIA = "base-sepolia"
+ BLAST_MAINNET = "blast-mainnet"
+ BLAST_SEPOLIA = "blast-sepolia"
+ ZKSYNC_MAINNET = "zksync-mainnet"
+ ZKSYNC_SEPOLIA = "zksync-sepolia"
+ ZORA_MAINNET = "zora-mainnet"
+ ZORA_SEPOLIA = "zora-sepolia"
+
+
+class BlockchainDocumentLoader(BaseLoader):
+ """Load elements from a blockchain smart contract.
+
+ See supported blockchains here: https://python.langchain.com/v0.2/api_reference/community/document_loaders/langchain_community.document_loaders.blockchain.BlockchainType.html
+
+ If no BlockchainType is specified, the default is Ethereum mainnet.
+
+ The Loader uses the Alchemy API to interact with the blockchain.
+ ALCHEMY_API_KEY environment variable must be set to use this loader.
+
+ The API returns 100 NFTs per request and can be paginated using the
+ startToken parameter.
+
+ If get_all_tokens is set to True, the loader will get all tokens
+ on the contract. Note that for contracts with a large number of tokens,
+ this may take a long time (e.g. 10k tokens is 100 requests).
+ Default value is false for this reason.
+
+ The max_execution_time (sec) can be set to limit the execution time
+ of the loader.
+
+ Future versions of this loader can:
+ - Support additional Alchemy APIs (e.g. getTransactions, etc.)
+ - Support additional blockchain APIs (e.g. Infura, Opensea, etc.)
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ contract_address: str,
+ blockchainType: BlockchainType = BlockchainType.ETH_MAINNET,
+ api_key: str = "docs-demo",
+ startToken: str = "",
+ get_all_tokens: bool = False,
+ max_execution_time: Optional[int] = None,
+ ):
+ """
+
+ Args:
+ contract_address: The address of the smart contract.
+ blockchainType: The blockchain type.
+ api_key: The Alchemy API key.
+ startToken: The start token for pagination.
+ get_all_tokens: Whether to get all tokens on the contract.
+ max_execution_time: The maximum execution time (sec).
+ """
+ self.contract_address = contract_address
+ self.blockchainType = blockchainType.value
+ self.api_key = os.environ.get("ALCHEMY_API_KEY") or api_key
+ self.startToken = startToken
+ self.get_all_tokens = get_all_tokens
+ self.max_execution_time = max_execution_time
+
+ if not self.api_key:
+ raise ValueError("Alchemy API key not provided.")
+
+ if not re.match(r"^0x[a-fA-F0-9]{40}$", self.contract_address):
+ raise ValueError(f"Invalid contract address {self.contract_address}")
+
+ def load(self) -> List[Document]:
+ result = []
+
+ current_start_token = self.startToken
+
+ start_time = time.time()
+
+ while True:
+ url = (
+ f"https://{self.blockchainType}.g.alchemy.com/nft/v2/"
+ f"{self.api_key}/getNFTsForCollection?withMetadata="
+ f"True&contractAddress={self.contract_address}"
+ f"&startToken={current_start_token}"
+ )
+
+ response = requests.get(url)
+
+ if response.status_code != 200:
+ raise ValueError(
+ f"Request failed with status code {response.status_code}"
+ )
+
+ items = response.json()["nfts"]
+
+ if not items:
+ break
+
+ for item in items:
+ content = str(item)
+ tokenId = item["id"]["tokenId"]
+ metadata = {
+ "source": self.contract_address,
+ "blockchain": self.blockchainType,
+ "tokenId": tokenId,
+ }
+ result.append(Document(page_content=content, metadata=metadata))
+
+ # exit after the first API call if get_all_tokens is False
+ if not self.get_all_tokens:
+ break
+
+ # get the start token for the next API call from the last item in array
+ current_start_token = self._get_next_tokenId(result[-1].metadata["tokenId"])
+
+ if (
+ self.max_execution_time is not None
+ and (time.time() - start_time) > self.max_execution_time
+ ):
+ raise RuntimeError("Execution time exceeded the allowed time limit.")
+
+ if not result:
+ raise ValueError(
+ f"No NFTs found for contract address {self.contract_address}"
+ )
+
+ return result
+
+ # add one to the tokenId, ensuring the correct tokenId format is used
+ def _get_next_tokenId(self, tokenId: str) -> str:
+ value_type = self._detect_value_type(tokenId)
+
+ if value_type == "hex_0x":
+ value_int = int(tokenId, 16)
+ elif value_type == "hex_0xbf":
+ value_int = int(tokenId[2:], 16)
+ else:
+ value_int = int(tokenId)
+
+ result = value_int + 1
+
+ if value_type == "hex_0x":
+ return "0x" + format(result, "0" + str(len(tokenId) - 2) + "x")
+ elif value_type == "hex_0xbf":
+ return "0xbf" + format(result, "0" + str(len(tokenId) - 4) + "x")
+ else:
+ return str(result)
+
+ # A smart contract can use different formats for the tokenId
+ @staticmethod
+ def _detect_value_type(tokenId: str) -> str:
+ if isinstance(tokenId, int):
+ return "int"
+ elif tokenId.startswith("0x"):
+ return "hex_0x"
+ elif tokenId.startswith("0xbf"):
+ return "hex_0xbf"
+ else:
+ return "hex_0xbf"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/brave_search.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/brave_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..6759e0d6359e94a54243c0a70b67aaf58e05e036
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/brave_search.py
@@ -0,0 +1,34 @@
+from typing import Iterator, List, Optional
+
+from langchain_core.documents import Document
+from pydantic import SecretStr
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.brave_search import BraveSearchWrapper
+
+
+class BraveSearchLoader(BaseLoader):
+ """Load with `Brave Search` engine."""
+
+ def __init__(self, query: str, api_key: str, search_kwargs: Optional[dict] = None):
+ """Initializes the BraveLoader.
+
+ Args:
+ query: The query to search for.
+ api_key: The API key to use.
+ search_kwargs: The search kwargs to use.
+ """
+ self.query = query
+ self.api_key = api_key
+ self.search_kwargs = search_kwargs or {}
+
+ def load(self) -> List[Document]:
+ brave_client = BraveSearchWrapper(
+ api_key=SecretStr(self.api_key),
+ search_kwargs=self.search_kwargs,
+ )
+ return brave_client.download_documents(self.query)
+
+ def lazy_load(self) -> Iterator[Document]:
+ for doc in self.load():
+ yield doc
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/browserbase.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/browserbase.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bda0c17a66713819083d8409c3999ce3725eb26
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/browserbase.py
@@ -0,0 +1,89 @@
+from typing import Any, Dict, Iterator, Optional, Sequence
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class BrowserbaseLoader(BaseLoader):
+ """Load pre-rendered web pages using a headless browser hosted on Browserbase.
+
+ Depends on `browserbase` and `playwright` packages.
+ Get your API key from https://browserbase.com
+ """
+
+ def __init__(
+ self,
+ urls: Sequence[str],
+ text_content: bool = False,
+ api_key: Optional[str] = None,
+ project_id: Optional[str] = None,
+ session_id: Optional[str] = None,
+ proxy: Optional[bool] = None,
+ ):
+ self.urls = urls
+ self.text_content = text_content
+ self.session_id = session_id
+ self.project_id = project_id
+ self.proxy = proxy
+
+ try:
+ from browserbase import Browserbase
+ except ImportError:
+ raise ImportError(
+ "You must run "
+ "`pip install --upgrade "
+ "browserbase playwright` "
+ "to use the Browserbase loader."
+ )
+
+ self.browserbase = Browserbase(api_key=api_key)
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load pages from URLs"""
+ try:
+ from playwright.sync_api import sync_playwright
+ except ImportError:
+ raise ImportError(
+ "playwright is required for BrowserbaseLoader. "
+ "Please run `pip install --upgrade playwright`."
+ )
+
+ for url in self.urls:
+ with sync_playwright() as playwright:
+ # Create or use existing session
+ if self.session_id:
+ session = self.browserbase.sessions.retrieve(id=self.session_id)
+ else:
+ if not self.project_id:
+ raise ValueError("project_id is required to create a session")
+ session_params: Dict[str, Any] = {"project_id": self.project_id}
+ if self.proxy is not None:
+ session_params["proxy"] = bool(self.proxy)
+ session = self.browserbase.sessions.create(**session_params)
+
+ # Connect to the remote session
+ browser = playwright.chromium.connect_over_cdp(session.connect_url)
+ context = browser.contexts[0]
+ page = context.pages[0]
+
+ # Navigate to URL and get content
+ page.goto(url)
+ # Get content based on the text_content flag
+ if self.text_content:
+ page_text = page.inner_text("body")
+ content = str(page_text)
+ else:
+ page_html = page.content()
+ content = str(page_html)
+
+ # Close browser
+ page.close()
+ browser.close()
+
+ yield Document(
+ page_content=content,
+ metadata={
+ "url": url,
+ },
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/browserless.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/browserless.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a315be44b41615bdf183af2113646923afdda4b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/browserless.py
@@ -0,0 +1,63 @@
+from typing import Iterator, List, Union
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class BrowserlessLoader(BaseLoader):
+ """Load webpages with `Browserless` /content endpoint."""
+
+ def __init__(
+ self, api_token: str, urls: Union[str, List[str]], text_content: bool = True
+ ):
+ """Initialize with API token and the URLs to scrape"""
+ self.api_token = api_token
+ """Browserless API token."""
+ self.urls = urls
+ """List of URLs to scrape."""
+ self.text_content = text_content
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load Documents from URLs."""
+
+ for url in self.urls:
+ if self.text_content:
+ response = requests.post(
+ "https://chrome.browserless.io/scrape",
+ params={
+ "token": self.api_token,
+ },
+ json={
+ "url": url,
+ "elements": [
+ {
+ "selector": "body",
+ }
+ ],
+ },
+ )
+ yield Document(
+ page_content=response.json()["data"][0]["results"][0]["text"],
+ metadata={
+ "source": url,
+ },
+ )
+ else:
+ response = requests.post(
+ "https://chrome.browserless.io/content",
+ params={
+ "token": self.api_token,
+ },
+ json={
+ "url": url,
+ },
+ )
+
+ yield Document(
+ page_content=response.text,
+ metadata={
+ "source": url,
+ },
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/cassandra.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/cassandra.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c31df029e6ed02ed520d6db9cee0a38789492ad
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/cassandra.py
@@ -0,0 +1,126 @@
+from __future__ import annotations
+
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ AsyncIterator,
+ Callable,
+ Iterator,
+ Optional,
+ Sequence,
+ Union,
+)
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.cassandra import aexecute_cql
+
+_NOT_SET = object()
+
+if TYPE_CHECKING:
+ from cassandra.cluster import Session
+ from cassandra.pool import Host
+ from cassandra.query import Statement
+
+
+class CassandraLoader(BaseLoader):
+ def __init__(
+ self,
+ table: Optional[str] = None,
+ session: Optional[Session] = None,
+ keyspace: Optional[str] = None,
+ query: Union[str, Statement, None] = None,
+ page_content_mapper: Callable[[Any], str] = str,
+ metadata_mapper: Callable[[Any], dict] = lambda _: {},
+ *,
+ query_parameters: Union[dict, Sequence, None] = None,
+ query_timeout: Optional[float] = _NOT_SET, # type: ignore[assignment]
+ query_trace: bool = False,
+ query_custom_payload: Optional[dict] = None,
+ query_execution_profile: Any = _NOT_SET,
+ query_paging_state: Any = None,
+ query_host: Optional[Host] = None,
+ query_execute_as: Optional[str] = None,
+ ) -> None:
+ """
+ Document Loader for Apache Cassandra.
+
+ Args:
+ table: The table to load the data from.
+ (do not use together with the query parameter)
+ session: The cassandra driver session.
+ If not provided, the cassio resolved session will be used.
+ keyspace: The keyspace of the table.
+ If not provided, the cassio resolved keyspace will be used.
+ query: The query used to load the data.
+ (do not use together with the table parameter)
+ page_content_mapper: a function to convert a row to string page content.
+ Defaults to the str representation of the row.
+ metadata_mapper: a function to convert a row to document metadata.
+ query_parameters: The query parameters used when calling session.execute .
+ query_timeout: The query timeout used when calling session.execute .
+ query_trace: Whether to use tracing when calling session.execute .
+ query_custom_payload: The query custom_payload used when calling
+ session.execute .
+ query_execution_profile: The query execution_profile used when calling
+ session.execute .
+ query_host: The query host used when calling session.execute .
+ query_execute_as: The query execute_as used when calling session.execute .
+ """
+ if query and table:
+ raise ValueError("Cannot specify both query and table.")
+
+ if not query and not table:
+ raise ValueError("Must specify query or table.")
+
+ if not session or (table and not keyspace):
+ try:
+ from cassio.config import check_resolve_keyspace, check_resolve_session
+ except (ImportError, ModuleNotFoundError):
+ raise ImportError(
+ "Could not import a recent cassio package."
+ "Please install it with `pip install --upgrade cassio`."
+ )
+
+ if table:
+ _keyspace = keyspace or check_resolve_keyspace(keyspace)
+ self.query = f"SELECT * FROM {_keyspace}.{table};"
+ self.metadata = {"table": table, "keyspace": _keyspace}
+ else:
+ self.query = query # type: ignore[assignment]
+ self.metadata = {}
+
+ self.session = session or check_resolve_session(session)
+ self.page_content_mapper = page_content_mapper
+ self.metadata_mapper = metadata_mapper
+
+ self.query_kwargs = {
+ "parameters": query_parameters,
+ "trace": query_trace,
+ "custom_payload": query_custom_payload,
+ "paging_state": query_paging_state,
+ "host": query_host,
+ "execute_as": query_execute_as,
+ }
+ if query_timeout is not _NOT_SET:
+ self.query_kwargs["timeout"] = query_timeout
+
+ if query_execution_profile is not _NOT_SET:
+ self.query_kwargs["execution_profile"] = query_execution_profile
+
+ def lazy_load(self) -> Iterator[Document]:
+ for row in self.session.execute(self.query, **self.query_kwargs):
+ metadata = self.metadata.copy()
+ metadata.update(self.metadata_mapper(row))
+ yield Document(
+ page_content=self.page_content_mapper(row), metadata=metadata
+ )
+
+ async def alazy_load(self) -> AsyncIterator[Document]:
+ for row in await aexecute_cql(self.session, self.query, **self.query_kwargs):
+ metadata = self.metadata.copy()
+ metadata.update(self.metadata_mapper(row))
+ yield Document(
+ page_content=self.page_content_mapper(row), metadata=metadata
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/chatgpt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/chatgpt.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6001be41915d313714d2581b47c1bc7528e72db
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/chatgpt.py
@@ -0,0 +1,65 @@
+import datetime
+import json
+from typing import List
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+def concatenate_rows(message: dict, title: str) -> str:
+ """
+ Combine message information in a readable format ready to be used.
+ Args:
+ message: Message to be concatenated
+ title: Title of the conversation
+
+ Returns:
+ Concatenated message
+ """
+ if not message:
+ return ""
+
+ sender = message["author"]["role"] if message["author"] else "unknown"
+ text = message["content"]["parts"][0]
+ date = datetime.datetime.fromtimestamp(message["create_time"]).strftime(
+ "%Y-%m-%d %H:%M:%S"
+ )
+ return f"{title} - {sender} on {date}: {text}\n\n"
+
+
+class ChatGPTLoader(BaseLoader):
+ """Load conversations from exported `ChatGPT` data."""
+
+ def __init__(self, log_file: str, num_logs: int = -1):
+ """Initialize a class object.
+
+ Args:
+ log_file: Path to the log file
+ num_logs: Number of logs to load. If 0, load all logs.
+ """
+ self.log_file = log_file
+ self.num_logs = num_logs
+
+ def load(self) -> List[Document]:
+ with open(self.log_file, encoding="utf8") as f:
+ data = json.load(f)[: self.num_logs] if self.num_logs else json.load(f)
+
+ documents = []
+ for d in data:
+ title = d["title"]
+ messages = d["mapping"]
+ text = "".join(
+ [
+ concatenate_rows(messages[key]["message"], title)
+ for idx, key in enumerate(messages)
+ if not (
+ idx == 0
+ and messages[key]["message"]["author"]["role"] == "system"
+ )
+ ]
+ )
+ metadata = {"source": str(self.log_file)}
+ documents.append(Document(page_content=text, metadata=metadata))
+
+ return documents
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/chm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/chm.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7b990506143d9c77d85e6138261ff357c91cca7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/chm.py
@@ -0,0 +1,134 @@
+from pathlib import Path
+from types import TracebackType
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+
+from typing_extensions import Self
+
+from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
+
+if TYPE_CHECKING:
+ from chm import chm
+
+
+class UnstructuredCHMLoader(UnstructuredFileLoader):
+ """Load `CHM` files using `Unstructured`.
+
+ CHM means Microsoft Compiled HTML Help.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredCHMLoader
+
+ loader = UnstructuredCHMLoader("example.chm")
+ docs = loader.load()
+
+ References
+ ----------
+ https://github.com/dottedmag/pychm
+ http://www.jedrea.com/chmlib/
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+
+ Args:
+ file_path: The path to the CHM file to load.
+ mode: The mode to use when loading the file. Can be one of "single",
+ "multi", or "all". Default is "single".
+ **unstructured_kwargs: Any kwargs to pass to the unstructured.
+ """
+ file_path = str(file_path)
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.html import partition_html
+
+ with CHMParser(self.file_path) as f: # type: ignore[arg-type]
+ return [
+ partition_html(text=item["content"], **self.unstructured_kwargs)
+ for item in f.load_all()
+ ]
+
+
+class CHMParser(object):
+ """Microsoft Compiled HTML Help (CHM) Parser."""
+
+ path: str
+ file: "chm.CHMFile"
+
+ def __init__(self, path: str):
+ from chm import chm
+
+ self.path = path
+ self.file = chm.CHMFile()
+ self.file.LoadCHM(path)
+
+ def __enter__(self) -> Self:
+ return self
+
+ def __exit__(
+ self,
+ exc_type: Optional[type[BaseException]],
+ exc_value: Optional[BaseException],
+ traceback: Optional[TracebackType],
+ ) -> None:
+ if self.file:
+ self.file.CloseCHM()
+
+ @property
+ def encoding(self) -> str:
+ return self.file.GetEncoding().decode("utf-8")
+
+ def index(self) -> List[Dict[str, str]]:
+ from urllib.parse import urlparse
+
+ from bs4 import BeautifulSoup
+
+ res = []
+ index = self.file.GetTopicsTree().decode(self.encoding)
+ soup = BeautifulSoup(index)
+ #
", "\n").replace("
", "\n"), "lxml"
+ ).get_text(" ") + "".join(attachment_texts)
+ else:
+ text = BeautifulSoup(content, "lxml").get_text(
+ " ", strip=True
+ ) + "".join(attachment_texts)
+
+ if include_comments:
+ comments = self.confluence.get_page_comments(
+ page["id"], expand="body.view.value", depth="all"
+ )["results"]
+ comment_texts = [
+ BeautifulSoup(comment["body"]["view"]["value"], "lxml").get_text(
+ " ", strip=True
+ )
+ for comment in comments
+ ]
+ text = text + "".join(comment_texts)
+
+ if include_labels:
+ labels = [
+ label["name"]
+ for label in page.get("metadata", {})
+ .get("labels", {})
+ .get("results", [])
+ ]
+
+ metadata = {
+ "title": page["title"],
+ "id": page["id"],
+ "source": self.base_url.strip("/") + page["_links"]["webui"],
+ **({"labels": labels} if include_labels else {}),
+ }
+
+ if "version" in page and "when" in page["version"]:
+ metadata["when"] = page["version"]["when"]
+
+ return Document(
+ page_content=text,
+ metadata=metadata,
+ )
+
+ def process_attachment(
+ self,
+ page_id: str,
+ ocr_languages: Optional[str] = None,
+ ) -> List[str]:
+ try:
+ from PIL import Image # noqa: F401
+ except ImportError:
+ raise ImportError(
+ "`Pillow` package not found, please run `pip install Pillow`"
+ )
+
+ # depending on setup you may also need to set the correct path for
+ # poppler and tesseract
+ attachments = self.confluence.get_attachments_from_content(page_id)["results"]
+ texts = []
+ for attachment in attachments:
+ if self.attachment_filter_func and not self.attachment_filter_func(
+ attachment
+ ):
+ continue
+
+ media_type = attachment["metadata"]["mediaType"]
+ absolute_url = self.base_url + attachment["_links"]["download"]
+ title = attachment["title"]
+ try:
+ if media_type == "application/pdf":
+ text = title + self.process_pdf(absolute_url, ocr_languages)
+ elif (
+ media_type == "image/png"
+ or media_type == "image/jpg"
+ or media_type == "image/jpeg"
+ ):
+ text = title + self.process_image(absolute_url, ocr_languages)
+ elif (
+ media_type == "application/vnd.openxmlformats-officedocument"
+ ".wordprocessingml.document"
+ ):
+ text = title + self.process_doc(absolute_url)
+ elif media_type == "application/vnd.ms-excel":
+ text = title + self.process_xls(absolute_url)
+ elif media_type == "image/svg+xml":
+ text = title + self.process_svg(absolute_url, ocr_languages)
+ else:
+ continue
+ texts.append(text)
+ except requests.HTTPError as e:
+ if e.response.status_code == 404:
+ print(f"Attachment not found at {absolute_url}") # noqa: T201
+ continue
+ else:
+ raise
+
+ return texts
+
+ def process_pdf(
+ self,
+ link: str,
+ ocr_languages: Optional[str] = None,
+ ) -> str:
+ try:
+ import pytesseract
+ from pdf2image import convert_from_bytes
+ except ImportError:
+ raise ImportError(
+ "`pytesseract` or `pdf2image` package not found, "
+ "please run `pip install pytesseract pdf2image`"
+ )
+
+ response = self.confluence.request(path=link, absolute=True)
+ text = ""
+
+ if (
+ response.status_code != 200
+ or response.content == b""
+ or response.content is None
+ ):
+ return text
+ try:
+ images = convert_from_bytes(response.content)
+ except ValueError:
+ return text
+
+ for i, image in enumerate(images):
+ try:
+ image_text = pytesseract.image_to_string(image, lang=ocr_languages)
+ text += f"Page {i + 1}:\n{image_text}\n\n"
+ except pytesseract.TesseractError as ex:
+ logger.warning(f"TesseractError: {ex}")
+
+ return text
+
+ def process_image(
+ self,
+ link: str,
+ ocr_languages: Optional[str] = None,
+ ) -> str:
+ try:
+ import pytesseract
+ from PIL import Image
+ except ImportError:
+ raise ImportError(
+ "`pytesseract` or `Pillow` package not found, "
+ "please run `pip install pytesseract Pillow`"
+ )
+
+ response = self.confluence.request(path=link, absolute=True)
+ text = ""
+
+ if (
+ response.status_code != 200
+ or response.content == b""
+ or response.content is None
+ ):
+ return text
+ try:
+ image = Image.open(BytesIO(response.content))
+ except OSError:
+ return text
+
+ return pytesseract.image_to_string(image, lang=ocr_languages)
+
+ def process_doc(self, link: str) -> str:
+ try:
+ import docx2txt
+ except ImportError:
+ raise ImportError(
+ "`docx2txt` package not found, please run `pip install docx2txt`"
+ )
+
+ response = self.confluence.request(path=link, absolute=True)
+ text = ""
+
+ if (
+ response.status_code != 200
+ or response.content == b""
+ or response.content is None
+ ):
+ return text
+ file_data = BytesIO(response.content)
+
+ return docx2txt.process(file_data)
+
+ def process_xls(self, link: str) -> str:
+ import io
+ import os
+
+ try:
+ import xlrd
+
+ except ImportError:
+ raise ImportError("`xlrd` package not found, please run `pip install xlrd`")
+
+ try:
+ import pandas as pd
+
+ except ImportError:
+ raise ImportError(
+ "`pandas` package not found, please run `pip install pandas`"
+ )
+
+ response = self.confluence.request(path=link, absolute=True)
+ text = ""
+
+ if (
+ response.status_code != 200
+ or response.content == b""
+ or response.content is None
+ ):
+ return text
+
+ filename = os.path.basename(link)
+ # Getting the whole content of the url after filename,
+ # Example: ".csv?version=2&modificationDate=1631800010678&cacheVersion=1&api=v2"
+ file_extension = os.path.splitext(filename)[1]
+
+ if file_extension.startswith(
+ ".csv"
+ ): # if the extension found in the url is ".csv"
+ content_string = response.content.decode("utf-8")
+ df = pd.read_csv(io.StringIO(content_string))
+ text += df.to_string(index=False, header=False) + "\n\n"
+ else:
+ workbook = xlrd.open_workbook(file_contents=response.content)
+ for sheet in workbook.sheets():
+ text += f"{sheet.name}:\n"
+ for row in range(sheet.nrows):
+ for col in range(sheet.ncols):
+ text += f"{sheet.cell_value(row, col)}\t"
+ text += "\n"
+ text += "\n"
+
+ return text
+
+ def process_svg(
+ self,
+ link: str,
+ ocr_languages: Optional[str] = None,
+ ) -> str:
+ try:
+ import pytesseract
+ from PIL import Image
+ from reportlab.graphics import renderPM
+ from svglib.svglib import svg2rlg
+ except ImportError:
+ raise ImportError(
+ "`pytesseract`, `Pillow`, `reportlab` or `svglib` package not found, "
+ "please run `pip install pytesseract Pillow reportlab svglib`"
+ )
+
+ response = self.confluence.request(path=link, absolute=True)
+ text = ""
+
+ if (
+ response.status_code != 200
+ or response.content == b""
+ or response.content is None
+ ):
+ return text
+
+ drawing = svg2rlg(BytesIO(response.content))
+
+ img_data = BytesIO()
+ renderPM.drawToFile(drawing, img_data, fmt="PNG")
+ img_data.seek(0)
+ image = Image.open(img_data)
+
+ return pytesseract.image_to_string(image, lang=ocr_languages)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/conllu.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/conllu.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa43af653a6ce9e548d7af0a92b3e55ef82931fd
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/conllu.py
@@ -0,0 +1,34 @@
+import csv
+from pathlib import Path
+from typing import List, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class CoNLLULoader(BaseLoader):
+ """Load `CoNLL-U` files."""
+
+ def __init__(self, file_path: Union[str, Path]):
+ """Initialize with a file path."""
+ self.file_path = file_path
+
+ def load(self) -> List[Document]:
+ """Load from a file path."""
+ with open(self.file_path, encoding="utf8") as f:
+ tsv = list(csv.reader(f, delimiter="\t"))
+
+ # If len(line) > 1, the line is not a comment
+ lines = [line for line in tsv if len(line) > 1]
+
+ text = ""
+ for i, line in enumerate(lines):
+ # Do not add a space after a punctuation mark or at the end of the sentence
+ if line[9] == "SpaceAfter=No" or i == len(lines) - 1:
+ text += line[1]
+ else:
+ text += line[1] + " "
+
+ metadata = {"source": str(self.file_path)}
+ return [Document(page_content=text, metadata=metadata)]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/couchbase.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/couchbase.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d89016202b7cc450569037752883908d338d90a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/couchbase.py
@@ -0,0 +1,96 @@
+import logging
+from typing import Iterator, List, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+
+class CouchbaseLoader(BaseLoader):
+ """Load documents from `Couchbase`.
+
+ Each document represents one row of the result. The `page_content_fields` are
+ written into the `page_content`of the document. The `metadata_fields` are written
+ into the `metadata` of the document. By default, all columns are written into
+ the `page_content` and none into the `metadata`.
+ """
+
+ def __init__(
+ self,
+ connection_string: str,
+ db_username: str,
+ db_password: str,
+ query: str,
+ *,
+ page_content_fields: Optional[List[str]] = None,
+ metadata_fields: Optional[List[str]] = None,
+ ) -> None:
+ """Initialize Couchbase document loader.
+
+ Args:
+ connection_string (str): The connection string to the Couchbase cluster.
+ db_username (str): The username to connect to the Couchbase cluster.
+ db_password (str): The password to connect to the Couchbase cluster.
+ query (str): The SQL++ query to execute.
+ page_content_fields (Optional[List[str]]): The columns to write into the
+ `page_content` field of the document. By default, all columns are
+ written.
+ metadata_fields (Optional[List[str]]): The columns to write into the
+ `metadata` field of the document. By default, no columns are written.
+ """
+ try:
+ from couchbase.auth import PasswordAuthenticator
+ from couchbase.cluster import Cluster
+ from couchbase.options import ClusterOptions
+ except ImportError as e:
+ raise ImportError(
+ "Could not import couchbase package."
+ "Please install couchbase SDK with `pip install couchbase`."
+ ) from e
+ if not connection_string:
+ raise ValueError("connection_string must be provided.")
+
+ if not db_username:
+ raise ValueError("db_username must be provided.")
+
+ if not db_password:
+ raise ValueError("db_password must be provided.")
+
+ auth = PasswordAuthenticator(
+ db_username,
+ db_password,
+ )
+
+ self.cluster: Cluster = Cluster(connection_string, ClusterOptions(auth))
+ self.query = query
+ self.page_content_fields = page_content_fields
+ self.metadata_fields = metadata_fields
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load Couchbase data into Document objects lazily."""
+ from datetime import timedelta
+
+ # Ensure connection to Couchbase cluster
+ self.cluster.wait_until_ready(timedelta(seconds=5))
+
+ # Run SQL++ Query
+ result = self.cluster.query(self.query)
+ for row in result:
+ metadata_fields = self.metadata_fields
+ page_content_fields = self.page_content_fields
+
+ if not page_content_fields:
+ page_content_fields = list(row.keys())
+
+ if not metadata_fields:
+ metadata_fields = []
+
+ metadata = {field: row[field] for field in metadata_fields}
+
+ document = "\n".join(
+ f"{k}: {v}" for k, v in row.items() if k in page_content_fields
+ )
+
+ yield (Document(page_content=document, metadata=metadata))
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/csv_loader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/csv_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f23516026f35b58e65c452325b09c1a1d83721e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/csv_loader.py
@@ -0,0 +1,226 @@
+import csv
+from io import TextIOWrapper
+from pathlib import Path
+from typing import Any, Dict, Iterator, List, Optional, Sequence, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.helpers import detect_file_encodings
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ validate_unstructured_version,
+)
+
+
+class CSVLoader(BaseLoader):
+ """Load a `CSV` file into a list of `Document` objects.
+
+ Each document represents one row of the CSV file. Every row is converted
+ into a key/value pair and outputted to a new line in the document's
+ page_content.
+
+ The source for each document loaded from csv is set to the value of the
+ `file_path` argument for all documents by default.
+ You can override this by setting the `source_column` argument to the
+ name of a column in the CSV file.
+ The source of each document will then be set to the value of the column
+ with the name specified in `source_column`.
+
+ Output Example:
+ .. code-block:: txt
+
+ column1: value1
+ column2: value2
+ column3: value3
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import CSVLoader
+
+ loader = CSVLoader(file_path='./hw_200.csv',
+ csv_args={
+ 'delimiter': ',',
+ 'quotechar': '"',
+ 'fieldnames': ['Index', 'Height', 'Weight']
+ })
+
+ Load:
+ .. code-block:: python
+
+ docs = loader.load()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Index: Index
+ Height: Height(Inches)"
+ Weight: "Weight(Pounds)"
+ {'source': './hw_200.csv', 'row': 0}
+
+ Async load:
+ .. code-block:: python
+
+ docs = await loader.aload()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Index: Index
+ Height: Height(Inches)"
+ Weight: "Weight(Pounds)"
+ {'source': './hw_200.csv', 'row': 0}
+
+ Lazy load:
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ # async variant:
+ # docs_lazy = await loader.alazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Index: Index
+ Height: Height(Inches)"
+ Weight: "Weight(Pounds)"
+ {'source': './hw_200.csv', 'row': 0}
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ source_column: Optional[str] = None,
+ metadata_columns: Sequence[str] = (),
+ csv_args: Optional[Dict] = None,
+ encoding: Optional[str] = None,
+ autodetect_encoding: bool = False,
+ *,
+ content_columns: Sequence[str] = (),
+ ):
+ """
+
+ Args:
+ file_path: The path to the CSV file.
+ source_column: The name of the column in the CSV file to use as the source.
+ Optional. Defaults to None.
+ metadata_columns: A sequence of column names to use as metadata. Optional.
+ csv_args: A dictionary of arguments to pass to the csv.DictReader.
+ Optional. Defaults to None.
+ encoding: The encoding of the CSV file. Optional. Defaults to None.
+ autodetect_encoding: Whether to try to autodetect the file encoding.
+ content_columns: A sequence of column names to use for the document content.
+ If not present, use all columns that are not part of the metadata.
+ """
+ self.file_path = file_path
+ self.source_column = source_column
+ self.metadata_columns = metadata_columns
+ self.encoding = encoding
+ self.csv_args = csv_args or {}
+ self.autodetect_encoding = autodetect_encoding
+ self.content_columns = content_columns
+
+ def lazy_load(self) -> Iterator[Document]:
+ try:
+ with open(self.file_path, newline="", encoding=self.encoding) as csvfile:
+ yield from self.__read_file(csvfile)
+ except UnicodeDecodeError as e:
+ if self.autodetect_encoding:
+ detected_encodings = detect_file_encodings(self.file_path)
+ for encoding in detected_encodings:
+ try:
+ with open(
+ self.file_path, newline="", encoding=encoding.encoding
+ ) as csvfile:
+ yield from self.__read_file(csvfile)
+ break
+ except UnicodeDecodeError:
+ continue
+ else:
+ raise RuntimeError(f"Error loading {self.file_path}") from e
+ except Exception as e:
+ raise RuntimeError(f"Error loading {self.file_path}") from e
+
+ def __read_file(self, csvfile: TextIOWrapper) -> Iterator[Document]:
+ csv_reader = csv.DictReader(csvfile, **self.csv_args)
+ for i, row in enumerate(csv_reader):
+ try:
+ source = (
+ row[self.source_column]
+ if self.source_column is not None
+ else str(self.file_path)
+ )
+ except KeyError:
+ raise ValueError(
+ f"Source column '{self.source_column}' not found in CSV file."
+ )
+ content = "\n".join(
+ f"""{k.strip() if k is not None else k}: {
+ v.strip()
+ if isinstance(v, str)
+ else ",".join(map(str.strip, v))
+ if isinstance(v, list)
+ else v
+ }"""
+ for k, v in row.items()
+ if (
+ k in self.content_columns
+ if self.content_columns
+ else k not in self.metadata_columns
+ )
+ )
+ metadata = {"source": source, "row": i}
+ for col in self.metadata_columns:
+ try:
+ metadata[col] = row[col]
+ except KeyError:
+ raise ValueError(f"Metadata column '{col}' not found in CSV file.")
+ yield Document(page_content=content, metadata=metadata)
+
+
+class UnstructuredCSVLoader(UnstructuredFileLoader):
+ """Load `CSV` files using `Unstructured`.
+
+ Like other
+ Unstructured loaders, UnstructuredCSVLoader can be used in both
+ "single" and "elements" mode. If you use the loader in "elements"
+ mode, the CSV file will be a single Unstructured Table element.
+ If you use the loader in "elements" mode, an HTML representation
+ of the table will be available in the "text_as_html" key in the
+ document metadata.
+
+ Examples
+ --------
+ from langchain_community.document_loaders.csv_loader import UnstructuredCSVLoader
+
+ loader = UnstructuredCSVLoader("stanley-cups.csv", mode="elements")
+ docs = loader.load()
+ """
+
+ def __init__(
+ self, file_path: str, mode: str = "single", **unstructured_kwargs: Any
+ ):
+ """
+
+ Args:
+ file_path: The path to the CSV file.
+ mode: The mode to use when loading the CSV file.
+ Optional. Defaults to "single".
+ **unstructured_kwargs: Keyword arguments to pass to unstructured.
+ """
+ validate_unstructured_version(min_unstructured_version="0.6.8")
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.csv import partition_csv
+
+ return partition_csv(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/cube_semantic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/cube_semantic.py
new file mode 100644
index 0000000000000000000000000000000000000000..94198b848adefb668c60d4b1a932578a0fe55ff1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/cube_semantic.py
@@ -0,0 +1,181 @@
+import json
+import logging
+import time
+from typing import Iterator, List
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+
+class CubeSemanticLoader(BaseLoader):
+ """Load `Cube semantic layer` metadata.
+
+ Args:
+ cube_api_url: REST API endpoint.
+ Use the REST API of your Cube's deployment.
+ Please find out more information here:
+ https://cube.dev/docs/http-api/rest#configuration-base-path
+ cube_api_token: Cube API token.
+ Authentication tokens are generated based on your Cube's API secret.
+ Please find out more information here:
+ https://cube.dev/docs/security#generating-json-web-tokens-jwt
+ load_dimension_values: Whether to load dimension values for every string
+ dimension or not.
+ dimension_values_limit: Maximum number of dimension values to load.
+ dimension_values_max_retries: Maximum number of retries to load dimension
+ values.
+ dimension_values_retry_delay: Delay between retries to load dimension values.
+ """
+
+ def __init__(
+ self,
+ cube_api_url: str,
+ cube_api_token: str,
+ load_dimension_values: bool = True,
+ dimension_values_limit: int = 10_000,
+ dimension_values_max_retries: int = 10,
+ dimension_values_retry_delay: int = 3,
+ ):
+ self.cube_api_url = cube_api_url
+ self.cube_api_token = cube_api_token
+ self.load_dimension_values = load_dimension_values
+ self.dimension_values_limit = dimension_values_limit
+ self.dimension_values_max_retries = dimension_values_max_retries
+ self.dimension_values_retry_delay = dimension_values_retry_delay
+
+ def _get_dimension_values(self, dimension_name: str) -> List[str]:
+ """Makes a call to Cube's REST API load endpoint to retrieve
+ values for dimensions.
+
+ These values can be used to achieve a more accurate filtering.
+ """
+ logger.info("Loading dimension values for: %s ...", dimension_name)
+
+ headers = {
+ "Content-Type": "application/json",
+ "Authorization": self.cube_api_token,
+ }
+
+ query = {
+ "query": {
+ "dimensions": [dimension_name],
+ "limit": self.dimension_values_limit,
+ }
+ }
+
+ retries = 0
+ while retries < self.dimension_values_max_retries:
+ response = requests.request(
+ "POST",
+ f"{self.cube_api_url}/load",
+ headers=headers,
+ data=json.dumps(query),
+ )
+
+ if response.status_code == 200:
+ response_data = response.json()
+ if (
+ "error" in response_data
+ and response_data["error"] == "Continue wait"
+ ):
+ logger.info("Retrying...")
+ retries += 1
+ time.sleep(self.dimension_values_retry_delay)
+ continue
+ else:
+ dimension_values = [
+ item[dimension_name] for item in response_data["data"]
+ ]
+ return dimension_values
+ else:
+ logger.error(
+ "Request failed with status code: %s", response.status_code
+ )
+ break
+
+ if retries == self.dimension_values_max_retries:
+ logger.info("Maximum retries reached.")
+ return []
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Makes a call to Cube's REST API metadata endpoint.
+
+ Returns:
+ A list of documents with attributes:
+ - page_content=column_title + column_description
+ - metadata
+ - table_name
+ - column_name
+ - column_data_type
+ - column_member_type
+ - column_title
+ - column_description
+ - column_values
+ - cube_data_obj_type
+ """
+ headers = {
+ "Content-Type": "application/json",
+ "Authorization": self.cube_api_token,
+ }
+
+ logger.info("Loading metadata from %s ...", self.cube_api_url)
+ response = requests.get(f"{self.cube_api_url}/meta", headers=headers)
+ response.raise_for_status()
+ raw_meta_json = response.json()
+ cube_data_objects = raw_meta_json.get("cubes", [])
+
+ logger.info("Found %s cube data objects in metadata.", len(cube_data_objects))
+
+ if not cube_data_objects:
+ raise ValueError("No cubes found in metadata.")
+
+ for cube_data_obj in cube_data_objects:
+ cube_data_obj_name = cube_data_obj.get("name")
+ cube_data_obj_type = cube_data_obj.get("type")
+ cube_data_obj_is_public = cube_data_obj.get("public")
+ measures = cube_data_obj.get("measures", [])
+ dimensions = cube_data_obj.get("dimensions", [])
+
+ logger.info("Processing %s ...", cube_data_obj_name)
+
+ if not cube_data_obj_is_public:
+ logger.info("Skipping %s because it is not public.", cube_data_obj_name)
+ continue
+
+ for item in measures + dimensions:
+ column_member_type = "measure" if item in measures else "dimension"
+ dimension_values = []
+ item_name = str(item.get("name"))
+ item_type = str(item.get("type"))
+
+ is_public = bool(item.get("public"))
+ if not is_public:
+ logger.info("Skipping %s because it is not public.", item_name)
+ continue
+
+ if (
+ self.load_dimension_values
+ and column_member_type == "dimension"
+ and item_type == "string"
+ ):
+ dimension_values = self._get_dimension_values(item_name)
+
+ metadata = dict(
+ table_name=str(cube_data_obj_name),
+ column_name=item_name,
+ column_data_type=item_type,
+ column_title=str(item.get("title")),
+ column_description=str(item.get("description")),
+ column_member_type=column_member_type,
+ column_values=dimension_values,
+ cube_data_obj_type=cube_data_obj_type,
+ )
+
+ page_content = f"{str(item.get('title'))}, "
+ page_content += f"{str(item.get('description'))}"
+
+ yield Document(page_content=page_content, metadata=metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/datadog_logs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/datadog_logs.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0c238cb87fba6d9a85dbeba5e161a2c7bacb3e0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/datadog_logs.py
@@ -0,0 +1,137 @@
+from datetime import datetime, timedelta
+from typing import List, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class DatadogLogsLoader(BaseLoader):
+ """Load `Datadog` logs.
+
+ Logs are written into the `page_content` and into the `metadata`.
+ """
+
+ def __init__(
+ self,
+ query: str,
+ api_key: str,
+ app_key: str,
+ from_time: Optional[int] = None,
+ to_time: Optional[int] = None,
+ limit: int = 100,
+ ) -> None:
+ """Initialize Datadog document loader.
+
+ Requirements:
+ - Must have datadog_api_client installed. Install with `pip install datadog_api_client`.
+
+ Args:
+ query: The query to run in Datadog.
+ api_key: The Datadog API key.
+ app_key: The Datadog APP key.
+ from_time: Optional. The start of the time range to query.
+ Supports date math and regular timestamps (milliseconds) like '1688732708951'
+ Defaults to 20 minutes ago.
+ to_time: Optional. The end of the time range to query.
+ Supports date math and regular timestamps (milliseconds) like '1688732708951'
+ Defaults to now.
+ limit: The maximum number of logs to return.
+ Defaults to 100.
+ """ # noqa: E501
+ try:
+ from datadog_api_client import Configuration
+ except ImportError as ex:
+ raise ImportError(
+ "Could not import datadog_api_client python package. "
+ "Please install it with `pip install datadog_api_client`."
+ ) from ex
+
+ self.query = query
+ configuration = Configuration()
+ configuration.api_key["apiKeyAuth"] = api_key
+ configuration.api_key["appKeyAuth"] = app_key
+ self.configuration = configuration
+ self.from_time = from_time
+ self.to_time = to_time
+ self.limit = limit
+
+ def parse_log(self, log: dict) -> Document:
+ """
+ Create Document objects from Datadog log items.
+ """
+ attributes = log.get("attributes", {})
+ metadata = {
+ "id": log.get("id", ""),
+ "status": attributes.get("status"),
+ "service": attributes.get("service", ""),
+ "tags": attributes.get("tags", []),
+ "timestamp": attributes.get("timestamp", ""),
+ }
+
+ message = attributes.get("message", "")
+ inside_attributes = attributes.get("attributes", {})
+ content_dict = {**inside_attributes, "message": message}
+ content = ", ".join(f"{k}: {v}" for k, v in content_dict.items())
+ return Document(page_content=content, metadata=metadata)
+
+ def load(self) -> List[Document]:
+ """
+ Get logs from Datadog.
+
+ Returns:
+ A list of `Document` objects.
+ - page_content
+ - metadata
+ - id
+ - service
+ - status
+ - tags
+ - timestamp
+ """
+ try:
+ from datadog_api_client import ApiClient
+ from datadog_api_client.v2.api.logs_api import LogsApi
+ from datadog_api_client.v2.model.logs_list_request import LogsListRequest
+ from datadog_api_client.v2.model.logs_list_request_page import (
+ LogsListRequestPage,
+ )
+ from datadog_api_client.v2.model.logs_query_filter import LogsQueryFilter
+ from datadog_api_client.v2.model.logs_sort import LogsSort
+ except ImportError as ex:
+ raise ImportError(
+ "Could not import datadog_api_client python package. "
+ "Please install it with `pip install datadog_api_client`."
+ ) from ex
+
+ now = datetime.now()
+ twenty_minutes_before = now - timedelta(minutes=20)
+ now_timestamp = int(now.timestamp() * 1000)
+ twenty_minutes_before_timestamp = int(twenty_minutes_before.timestamp() * 1000)
+ _from = (
+ self.from_time
+ if self.from_time is not None
+ else twenty_minutes_before_timestamp
+ )
+
+ body = LogsListRequest(
+ filter=LogsQueryFilter(
+ query=self.query,
+ _from=_from,
+ to=f"{self.to_time if self.to_time is not None else now_timestamp}",
+ ),
+ sort=LogsSort.TIMESTAMP_ASCENDING,
+ page=LogsListRequestPage(
+ limit=self.limit,
+ ),
+ )
+
+ with ApiClient(configuration=self.configuration) as api_client:
+ api_instance = LogsApi(api_client)
+ response = api_instance.list_logs(body=body).to_dict()
+
+ docs: List[Document] = []
+ for row in response["data"]:
+ docs.append(self.parse_log(row))
+
+ return docs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/dataframe.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/dataframe.py
new file mode 100644
index 0000000000000000000000000000000000000000..74ad56b53f7837a925e997462be5ba80909258e1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/dataframe.py
@@ -0,0 +1,63 @@
+from typing import Any, Iterator, Literal
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class BaseDataFrameLoader(BaseLoader):
+ def __init__(self, data_frame: Any, *, page_content_column: str = "text"):
+ """Initialize with dataframe object.
+
+ Args:
+ data_frame: DataFrame object.
+ page_content_column: Name of the column containing the page content.
+ Defaults to "text".
+ """
+ self.data_frame = data_frame
+ self.page_content_column = page_content_column
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load records from dataframe."""
+
+ for _, row in self.data_frame.iterrows():
+ metadata = row.to_dict()
+ text = metadata.pop(self.page_content_column)
+ yield Document(page_content=text, metadata=metadata)
+
+
+class DataFrameLoader(BaseDataFrameLoader):
+ """Load `Pandas` DataFrame."""
+
+ def __init__(
+ self,
+ data_frame: Any,
+ page_content_column: str = "text",
+ engine: Literal["pandas", "modin"] = "pandas",
+ ):
+ """Initialize with dataframe object.
+
+ Args:
+ data_frame: Pandas DataFrame object.
+ page_content_column: Name of the column containing the page content.
+ Defaults to "text".
+ """
+ try:
+ if engine == "pandas":
+ import pandas as pd
+ elif engine == "modin":
+ import modin.pandas as pd
+ else:
+ raise ValueError(
+ f"Unsupported engine {engine}. Must be one of 'pandas', or 'modin'."
+ )
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import pandas, please install with `pip install pandas`."
+ ) from e
+
+ if not isinstance(data_frame, pd.DataFrame):
+ raise ValueError(
+ f"Expected data_frame to be a pd.DataFrame, got {type(data_frame)}"
+ )
+ super().__init__(data_frame, page_content_column=page_content_column)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/dedoc.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/dedoc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed8ebc11d73fa89c0f22ff36f571b3f846293574
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/dedoc.py
@@ -0,0 +1,546 @@
+import html
+import json
+import os
+from abc import ABC, abstractmethod
+from typing import (
+ Dict,
+ Iterator,
+ Optional,
+ Tuple,
+ Union,
+)
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class DedocBaseLoader(BaseLoader, ABC):
+ """
+ Base Loader that uses `dedoc` (https://dedoc.readthedocs.io).
+
+ Loader enables extracting text, tables and attached files from the given file:
+ * `Text` can be split by pages, `dedoc` tree nodes, textual lines
+ (according to the `split` parameter).
+ * `Attached files` (when with_attachments=True)
+ are split according to the `split` parameter.
+ For attachments, langchain Document object has an additional metadata field
+ `type`="attachment".
+ * `Tables` (when with_tables=True) are not split - each table corresponds to one
+ langchain Document object.
+ For tables, Document object has additional metadata fields `type`="table"
+ and `text_as_html` with table HTML representation.
+ """
+
+ def __init__(
+ self,
+ file_path: str,
+ *,
+ split: str = "document",
+ with_tables: bool = True,
+ with_attachments: Union[str, bool] = False,
+ recursion_deep_attachments: int = 10,
+ pdf_with_text_layer: str = "auto_tabby",
+ language: str = "rus+eng",
+ pages: str = ":",
+ is_one_column_document: str = "auto",
+ document_orientation: str = "auto",
+ need_header_footer_analysis: Union[str, bool] = False,
+ need_binarization: Union[str, bool] = False,
+ need_pdf_table_analysis: Union[str, bool] = True,
+ delimiter: Optional[str] = None,
+ encoding: Optional[str] = None,
+ ) -> None:
+ """
+ Initialize with file path and parsing parameters.
+
+ Args:
+ file_path: path to the file for processing
+ split: type of document splitting into parts (each part is returned
+ separately), default value "document"
+ "document": document text is returned as a single langchain Document
+ object (don't split)
+ "page": split document text into pages (works for PDF, DJVU, PPTX, PPT,
+ ODP)
+ "node": split document text into tree nodes (title nodes, list item
+ nodes, raw text nodes)
+ "line": split document text into lines
+ with_tables: add tables to the result - each table is returned as a single
+ langchain Document object
+
+ Parameters used for document parsing via `dedoc`
+ (https://dedoc.readthedocs.io/en/latest/parameters/parameters.html):
+
+ with_attachments: enable attached files extraction
+ recursion_deep_attachments: recursion level for attached files
+ extraction, works only when with_attachments==True
+ pdf_with_text_layer: type of handler for parsing PDF documents,
+ available options
+ ["true", "false", "tabby", "auto", "auto_tabby" (default)]
+ language: language of the document for PDF without a textual layer and
+ images, available options ["eng", "rus", "rus+eng" (default)],
+ the list of languages can be extended, please see
+ https://dedoc.readthedocs.io/en/latest/tutorials/add_new_language.html
+ pages: page slice to define the reading range for parsing PDF documents
+ is_one_column_document: detect number of columns for PDF without
+ a textual layer and images, available options
+ ["true", "false", "auto" (default)]
+ document_orientation: fix document orientation (90, 180, 270 degrees)
+ for PDF without a textual layer and images, available options
+ ["auto" (default), "no_change"]
+ need_header_footer_analysis: remove headers and footers from the output
+ result for parsing PDF and images
+ need_binarization: clean pages background (binarize) for PDF without a
+ textual layer and images
+ need_pdf_table_analysis: parse tables for PDF without a textual layer
+ and images
+ delimiter: column separator for CSV, TSV files
+ encoding: encoding of TXT, CSV, TSV
+ """
+ self.parsing_parameters = {
+ key: value
+ for key, value in locals().items()
+ if key not in {"self", "file_path", "split", "with_tables"}
+ }
+ self.valid_split_values = {"document", "page", "node", "line"}
+ if split not in self.valid_split_values:
+ raise ValueError(
+ f"Got {split} for `split`, but should be one of "
+ f"`{self.valid_split_values}`"
+ )
+ self.split = split
+ self.with_tables = with_tables
+ self.file_path = file_path
+
+ structure_type = "tree" if self.split == "node" else "linear"
+ self.parsing_parameters["structure_type"] = structure_type
+ self.parsing_parameters["need_content_analysis"] = with_attachments
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazily load documents."""
+ import tempfile
+
+ try:
+ from dedoc import DedocManager
+ except ImportError:
+ raise ImportError(
+ "`dedoc` package not found, please install it with `pip install dedoc`"
+ )
+ dedoc_manager = DedocManager(manager_config=self._make_config())
+ dedoc_manager.config["logger"].disabled = True
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ document_tree = dedoc_manager.parse(
+ file_path=self.file_path,
+ parameters={**self.parsing_parameters, "attachments_dir": tmpdir},
+ )
+ yield from self._split_document(
+ document_tree=document_tree.to_api_schema().dict(), split=self.split
+ )
+
+ @abstractmethod
+ def _make_config(self) -> dict:
+ """
+ Make configuration for DedocManager according to the file extension and
+ parsing parameters.
+ """
+ pass
+
+ def _json2txt(self, paragraph: dict) -> str:
+ """Get text (recursively) of the document tree node."""
+ subparagraphs_text = "\n".join(
+ [
+ self._json2txt(subparagraph)
+ for subparagraph in paragraph["subparagraphs"]
+ ]
+ )
+ text = (
+ f"{paragraph['text']}\n{subparagraphs_text}"
+ if subparagraphs_text
+ else paragraph["text"]
+ )
+ return text
+
+ def _parse_subparagraphs(
+ self, document_tree: dict, document_metadata: dict
+ ) -> Iterator[Document]:
+ """Parse recursively document tree obtained by `dedoc`."""
+ if len(document_tree["subparagraphs"]) > 0:
+ for subparagraph in document_tree["subparagraphs"]:
+ yield from self._parse_subparagraphs(
+ document_tree=subparagraph, document_metadata=document_metadata
+ )
+ else:
+ yield Document(
+ page_content=document_tree["text"],
+ metadata={**document_metadata, **document_tree["metadata"]},
+ )
+
+ def _split_document(
+ self,
+ document_tree: dict,
+ split: str,
+ additional_metadata: Optional[dict] = None,
+ ) -> Iterator[Document]:
+ """Split document into parts according to the `split` parameter."""
+ document_metadata = document_tree["metadata"]
+ if additional_metadata:
+ document_metadata = {**document_metadata, **additional_metadata}
+
+ if split == "document":
+ text = self._json2txt(paragraph=document_tree["content"]["structure"])
+ yield Document(page_content=text, metadata=document_metadata)
+
+ elif split == "page":
+ nodes = document_tree["content"]["structure"]["subparagraphs"]
+ page_id = nodes[0]["metadata"]["page_id"]
+ page_text = ""
+
+ for node in nodes:
+ if node["metadata"]["page_id"] == page_id:
+ page_text += self._json2txt(node)
+ else:
+ yield Document(
+ page_content=page_text,
+ metadata={**document_metadata, "page_id": page_id},
+ )
+ page_id = node["metadata"]["page_id"]
+ page_text = self._json2txt(node)
+
+ yield Document(
+ page_content=page_text,
+ metadata={**document_metadata, "page_id": page_id},
+ )
+
+ elif split == "line":
+ for node in document_tree["content"]["structure"]["subparagraphs"]:
+ line_metadata = node["metadata"]
+ yield Document(
+ page_content=self._json2txt(node),
+ metadata={**document_metadata, **line_metadata},
+ )
+
+ elif split == "node":
+ yield from self._parse_subparagraphs(
+ document_tree=document_tree["content"]["structure"],
+ document_metadata=document_metadata,
+ )
+
+ else:
+ raise ValueError(
+ f"Got {split} for `split`, but should be one of "
+ f"`{self.valid_split_values}`"
+ )
+
+ if self.with_tables:
+ for table in document_tree["content"]["tables"]:
+ table_text, table_html = self._get_table(table)
+ yield Document(
+ page_content=table_text,
+ metadata={
+ **table["metadata"],
+ "type": "table",
+ "text_as_html": table_html,
+ },
+ )
+
+ for attachment in document_tree["attachments"]:
+ yield from self._split_document(
+ document_tree=attachment,
+ split=self.split,
+ additional_metadata={"type": "attachment"},
+ )
+
+ def _get_table(self, table: dict) -> Tuple[str, str]:
+ """Get text and HTML representation of the table."""
+ table_text = ""
+ for row in table["cells"]:
+ for cell in row:
+ table_text += " ".join(line["text"] for line in cell["lines"])
+ table_text += "\t"
+ table_text += "\n"
+
+ table_html = (
+ '\n\n'
+ )
+ for row in table["cells"]:
+ table_html += "\n"
+ for cell in row:
+ cell_text = "\n".join(line["text"] for line in cell["lines"])
+ cell_text = html.escape(cell_text)
+ table_html += "| {cell_text} | \n'
+ )
+ table_html += "
\n"
+ table_html += "\n
"
+
+ return table_text, table_html
+
+
+class DedocFileLoader(DedocBaseLoader):
+ """
+ DedocFileLoader document loader integration to load files using `dedoc`.
+
+ The file loader automatically detects the file type (with the correct extension).
+ The list of supported file types is gives at
+ https://dedoc.readthedocs.io/en/latest/index.html#id1.
+ Please see the documentation of DedocBaseLoader to get more details.
+
+ Setup:
+ Install ``dedoc`` package.
+
+ .. code-block:: bash
+
+ pip install -U dedoc
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import DedocFileLoader
+
+ loader = DedocFileLoader(
+ file_path="example.pdf",
+ # split=...,
+ # with_tables=...,
+ # pdf_with_text_layer=...,
+ # pages=...,
+ # ...
+ )
+
+ Load:
+ .. code-block:: python
+
+ docs = loader.load()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Some text
+ {
+ 'file_name': 'example.pdf',
+ 'file_type': 'application/pdf',
+ # ...
+ }
+
+ Lazy load:
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Some text
+ {
+ 'file_name': 'example.pdf',
+ 'file_type': 'application/pdf',
+ # ...
+ }
+ """
+
+ def _make_config(self) -> dict:
+ from dedoc.utils.langchain import make_manager_config
+
+ return make_manager_config(
+ file_path=self.file_path,
+ parsing_params=self.parsing_parameters,
+ split=self.split,
+ )
+
+
+class DedocAPIFileLoader(DedocBaseLoader):
+ """
+ Load files using `dedoc` API.
+ The file loader automatically detects the file type (even with the wrong extension).
+ By default, the loader makes a call to the locally hosted `dedoc` API.
+ More information about `dedoc` API can be found in `dedoc` documentation:
+ https://dedoc.readthedocs.io/en/latest/dedoc_api_usage/api.html
+
+ Please see the documentation of DedocBaseLoader to get more details.
+
+ Setup:
+ You don't need to install `dedoc` library for using this loader.
+ Instead, the `dedoc` API needs to be run.
+ You may use Docker container for this purpose.
+ Please see `dedoc` documentation for more details:
+ https://dedoc.readthedocs.io/en/latest/getting_started/installation.html#install-and-run-dedoc-using-docker
+
+ .. code-block:: bash
+
+ docker pull dedocproject/dedoc
+ docker run -p 1231:1231
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import DedocAPIFileLoader
+
+ loader = DedocAPIFileLoader(
+ file_path="example.pdf",
+ # url=...,
+ # split=...,
+ # with_tables=...,
+ # pdf_with_text_layer=...,
+ # pages=...,
+ # ...
+ )
+
+ Load:
+ .. code-block:: python
+
+ docs = loader.load()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Some text
+ {
+ 'file_name': 'example.pdf',
+ 'file_type': 'application/pdf',
+ # ...
+ }
+
+ Lazy load:
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Some text
+ {
+ 'file_name': 'example.pdf',
+ 'file_type': 'application/pdf',
+ # ...
+ }
+ """
+
+ def __init__(
+ self,
+ file_path: str,
+ *,
+ url: str = "http://0.0.0.0:1231",
+ split: str = "document",
+ with_tables: bool = True,
+ with_attachments: Union[str, bool] = False,
+ recursion_deep_attachments: int = 10,
+ pdf_with_text_layer: str = "auto_tabby",
+ language: str = "rus+eng",
+ pages: str = ":",
+ is_one_column_document: str = "auto",
+ document_orientation: str = "auto",
+ need_header_footer_analysis: Union[str, bool] = False,
+ need_binarization: Union[str, bool] = False,
+ need_pdf_table_analysis: Union[str, bool] = True,
+ delimiter: Optional[str] = None,
+ encoding: Optional[str] = None,
+ ) -> None:
+ """Initialize with file path, API url and parsing parameters.
+
+ Args:
+ file_path: path to the file for processing
+ url: URL to call `dedoc` API
+ split: type of document splitting into parts (each part is returned
+ separately), default value "document"
+ "document": document is returned as a single langchain Document object
+ (don't split)
+ "page": split document into pages (works for PDF, DJVU, PPTX, PPT, ODP)
+ "node": split document into tree nodes (title nodes, list item nodes,
+ raw text nodes)
+ "line": split document into lines
+ with_tables: add tables to the result - each table is returned as a single
+ langchain Document object
+
+ Parameters used for document parsing via `dedoc`
+ (https://dedoc.readthedocs.io/en/latest/parameters/parameters.html):
+
+ with_attachments: enable attached files extraction
+ recursion_deep_attachments: recursion level for attached files
+ extraction, works only when with_attachments==True
+ pdf_with_text_layer: type of handler for parsing PDF documents,
+ available options
+ ["true", "false", "tabby", "auto", "auto_tabby" (default)]
+ language: language of the document for PDF without a textual layer and
+ images, available options ["eng", "rus", "rus+eng" (default)],
+ the list of languages can be extended, please see
+ https://dedoc.readthedocs.io/en/latest/tutorials/add_new_language.html
+ pages: page slice to define the reading range for parsing PDF documents
+ is_one_column_document: detect number of columns for PDF without
+ a textual layer and images, available options
+ ["true", "false", "auto" (default)]
+ document_orientation: fix document orientation (90, 180, 270 degrees)
+ for PDF without a textual layer and images, available options
+ ["auto" (default), "no_change"]
+ need_header_footer_analysis: remove headers and footers from the output
+ result for parsing PDF and images
+ need_binarization: clean pages background (binarize) for PDF without a
+ textual layer and images
+ need_pdf_table_analysis: parse tables for PDF without a textual layer
+ and images
+ delimiter: column separator for CSV, TSV files
+ encoding: encoding of TXT, CSV, TSV
+ """
+ super().__init__(
+ file_path=file_path,
+ split=split,
+ with_tables=with_tables,
+ with_attachments=with_attachments,
+ recursion_deep_attachments=recursion_deep_attachments,
+ pdf_with_text_layer=pdf_with_text_layer,
+ language=language,
+ pages=pages,
+ is_one_column_document=is_one_column_document,
+ document_orientation=document_orientation,
+ need_header_footer_analysis=need_header_footer_analysis,
+ need_binarization=need_binarization,
+ need_pdf_table_analysis=need_pdf_table_analysis,
+ delimiter=delimiter,
+ encoding=encoding,
+ )
+ self.url = url
+ self.parsing_parameters["return_format"] = "json"
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazily load documents."""
+ doc_tree = self._send_file(
+ url=self.url, file_path=self.file_path, parameters=self.parsing_parameters
+ )
+ yield from self._split_document(document_tree=doc_tree, split=self.split)
+
+ def _make_config(self) -> dict:
+ return {}
+
+ def _send_file(
+ self, url: str, file_path: str, parameters: dict
+ ) -> Dict[str, Union[list, dict, str]]:
+ """Send POST-request to `dedoc` API and return the results"""
+ import requests
+
+ file_name = os.path.basename(file_path)
+ with open(file_path, "rb") as file:
+ files = {"file": (file_name, file)}
+ r = requests.post(f"{url}/upload", files=files, data=parameters)
+
+ if r.status_code != 200:
+ raise ValueError(f"Error during file handling: {r.content.decode()}")
+
+ result = json.loads(r.content.decode())
+ return result
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/diffbot.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/diffbot.py
new file mode 100644
index 0000000000000000000000000000000000000000..5014ecf780cf1a4ebd19521d996fd88a9235c313
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/diffbot.py
@@ -0,0 +1,61 @@
+import logging
+from typing import Any, List
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+
+class DiffbotLoader(BaseLoader):
+ """Load `Diffbot` json file."""
+
+ def __init__(
+ self, api_token: str, urls: List[str], continue_on_failure: bool = True
+ ):
+ """Initialize with API token, ids, and key.
+
+ Args:
+ api_token: Diffbot API token.
+ urls: List of URLs to load.
+ continue_on_failure: Whether to continue loading other URLs if one fails.
+ Defaults to True.
+ """
+ self.api_token = api_token
+ self.urls = urls
+ self.continue_on_failure = continue_on_failure
+
+ def _diffbot_api_url(self, diffbot_api: str) -> str:
+ return f"https://api.diffbot.com/v3/{diffbot_api}"
+
+ def _get_diffbot_data(self, url: str) -> Any:
+ """Get Diffbot file from Diffbot REST API."""
+ # TODO: Add support for other Diffbot APIs
+ diffbot_url = self._diffbot_api_url("article")
+ params = {
+ "token": self.api_token,
+ "url": url,
+ }
+ response = requests.get(diffbot_url, params=params, timeout=10)
+
+ # TODO: handle non-ok errors
+ return response.json() if response.ok else {}
+
+ def load(self) -> List[Document]:
+ """Extract text from Diffbot on all the URLs and return Documents"""
+ docs: List[Document] = list()
+
+ for url in self.urls:
+ try:
+ data = self._get_diffbot_data(url)
+ text = data["objects"][0]["text"] if "objects" in data else ""
+ metadata = {"source": url}
+ docs.append(Document(page_content=text, metadata=metadata))
+ except Exception as e:
+ if self.continue_on_failure:
+ logger.error(f"Error fetching or processing {url}, exception: {e}")
+ else:
+ raise e
+ return docs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/directory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/directory.py
new file mode 100644
index 0000000000000000000000000000000000000000..d46d545656e024a60eca79be5605ecb4f1906b51
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/directory.py
@@ -0,0 +1,236 @@
+import concurrent
+import logging
+import random
+from pathlib import Path
+from typing import Any, Callable, Iterator, List, Optional, Sequence, Tuple, Type, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.csv_loader import CSVLoader
+from langchain_community.document_loaders.html_bs import BSHTMLLoader
+from langchain_community.document_loaders.text import TextLoader
+from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
+
+FILE_LOADER_TYPE = Union[
+ Type[UnstructuredFileLoader], Type[TextLoader], Type[BSHTMLLoader], Type[CSVLoader]
+]
+logger = logging.getLogger(__name__)
+
+
+def _is_visible(p: Path) -> bool:
+ parts = p.parts
+ for _p in parts:
+ if _p.startswith("."):
+ return False
+ return True
+
+
+class DirectoryLoader(BaseLoader):
+ """Load from a directory."""
+
+ def __init__(
+ self,
+ path: str,
+ glob: Union[List[str], Tuple[str], str] = "**/[!.]*",
+ silent_errors: bool = False,
+ load_hidden: bool = False,
+ loader_cls: FILE_LOADER_TYPE = UnstructuredFileLoader,
+ loader_kwargs: Union[dict, None] = None,
+ recursive: bool = False,
+ show_progress: bool = False,
+ use_multithreading: bool = False,
+ max_concurrency: int = 4,
+ *,
+ exclude: Union[Sequence[str], str] = (),
+ sample_size: int = 0,
+ randomize_sample: bool = False,
+ sample_seed: Union[int, None] = None,
+ ):
+ """Initialize with a path to directory and how to glob over it.
+
+ Args:
+ path: Path to directory.
+ glob: A glob pattern or list of glob patterns to use to find files.
+ Defaults to "**/[!.]*" (all files except hidden).
+ exclude: A pattern or list of patterns to exclude from results.
+ Use glob syntax.
+ silent_errors: Whether to silently ignore errors. Defaults to False.
+ load_hidden: Whether to load hidden files. Defaults to False.
+ loader_cls: Loader class to use for loading files.
+ Defaults to UnstructuredFileLoader.
+ loader_kwargs: Keyword arguments to pass to loader_cls. Defaults to None.
+ recursive: Whether to recursively search for files. Defaults to False.
+ show_progress: Whether to show a progress bar. Defaults to False.
+ use_multithreading: Whether to use multithreading. Defaults to False.
+ max_concurrency: The maximum number of threads to use. Defaults to 4.
+ sample_size: The maximum number of files you would like to load from the
+ directory.
+ randomize_sample: Shuffle the files to get a random sample.
+ sample_seed: set the seed of the random shuffle for reproducibility.
+
+ Examples:
+
+ .. code-block:: python
+ from langchain_community.document_loaders import DirectoryLoader
+
+ # Load all non-hidden files in a directory.
+ loader = DirectoryLoader("/path/to/directory")
+
+ # Load all text files in a directory without recursion.
+ loader = DirectoryLoader("/path/to/directory", glob="*.txt")
+
+ # Recursively load all text files in a directory.
+ loader = DirectoryLoader(
+ "/path/to/directory", glob="*.txt", recursive=True
+ )
+
+ # Load all files in a directory, except for py files.
+ loader = DirectoryLoader("/path/to/directory", exclude="*.py")
+
+ # Load all files in a directory, except for py or pyc files.
+ loader = DirectoryLoader(
+ "/path/to/directory", exclude=["*.py", "*.pyc"]
+ )
+ """
+ if loader_kwargs is None:
+ loader_kwargs = {}
+ if isinstance(exclude, str):
+ exclude = (exclude,)
+ self.path = path
+ self.glob = glob
+ self.exclude = exclude
+ self.load_hidden = load_hidden
+ self.loader_cls = loader_cls
+ self.loader_kwargs = loader_kwargs
+ self.silent_errors = silent_errors
+ self.recursive = recursive
+ self.show_progress = show_progress
+ self.use_multithreading = use_multithreading
+ self.max_concurrency = max_concurrency
+ self.sample_size = sample_size
+ self.randomize_sample = randomize_sample
+ self.sample_seed = sample_seed
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ return list(self.lazy_load())
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load documents lazily."""
+ p = Path(self.path)
+ if not p.exists():
+ raise FileNotFoundError(f"Directory not found: '{self.path}'")
+ if not p.is_dir():
+ raise ValueError(f"Expected directory, got file: '{self.path}'")
+
+ # glob multiple patterns if a list is provided, e.g., multiple file extensions
+ if isinstance(self.glob, (list, tuple)):
+ paths = []
+ for pattern in self.glob:
+ paths.extend(
+ list(p.rglob(pattern) if self.recursive else p.glob(pattern))
+ )
+ elif isinstance(self.glob, str):
+ paths = list(p.rglob(self.glob) if self.recursive else p.glob(self.glob))
+ else:
+ raise TypeError(
+ f"Expected glob to be str or sequence of str, but got {type(self.glob)}"
+ )
+
+ items = [
+ path
+ for path in paths
+ if not (self.exclude and any(path.match(glob) for glob in self.exclude))
+ and path.is_file()
+ ]
+
+ if self.sample_size > 0:
+ if self.randomize_sample:
+ randomizer = random.Random(
+ self.sample_seed if self.sample_seed else None
+ )
+ randomizer.shuffle(items)
+ items = items[: min(len(items), self.sample_size)]
+
+ pbar = None
+ if self.show_progress:
+ try:
+ from tqdm import tqdm
+
+ pbar = tqdm(total=len(items))
+ except ImportError as e:
+ logger.warning(
+ "To log the progress of DirectoryLoader you need to install tqdm, "
+ "`pip install tqdm`"
+ )
+ if self.silent_errors:
+ logger.warning(e)
+ else:
+ raise ImportError(
+ "To log the progress of DirectoryLoader "
+ "you need to install tqdm, "
+ "`pip install tqdm`"
+ )
+
+ if self.use_multithreading:
+ futures = []
+ with concurrent.futures.ThreadPoolExecutor(
+ max_workers=self.max_concurrency
+ ) as executor:
+ for i in items:
+ futures.append(
+ executor.submit(
+ self._lazy_load_file_to_non_generator(self._lazy_load_file),
+ i,
+ p,
+ pbar,
+ )
+ )
+ for future in concurrent.futures.as_completed(futures):
+ for item in future.result():
+ yield item
+ else:
+ for i in items:
+ yield from self._lazy_load_file(i, p, pbar)
+
+ if pbar:
+ pbar.close()
+
+ def _lazy_load_file_to_non_generator(self, func: Callable) -> Callable:
+ def non_generator(item: Path, path: Path, pbar: Optional[Any]) -> List:
+ return [x for x in func(item, path, pbar)]
+
+ return non_generator
+
+ def _lazy_load_file(
+ self, item: Path, path: Path, pbar: Optional[Any]
+ ) -> Iterator[Document]:
+ """Load a file.
+
+ Args:
+ item: File path.
+ path: Directory path.
+ pbar: Progress bar. Defaults to None.
+
+ """
+ if item.is_file():
+ if _is_visible(item.relative_to(path)) or self.load_hidden:
+ try:
+ logger.debug(f"Processing file: {str(item)}")
+ loader = self.loader_cls(str(item), **self.loader_kwargs)
+ try:
+ for subdoc in loader.lazy_load():
+ yield subdoc
+ except NotImplementedError:
+ for subdoc in loader.load():
+ yield subdoc
+ except Exception as e:
+ if self.silent_errors:
+ logger.warning(f"Error loading file {str(item)}: {e}")
+ else:
+ logger.error(f"Error loading file {str(item)}")
+ raise e
+ finally:
+ if pbar:
+ pbar.update(1)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/discord.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/discord.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c5308e6ae017ab2234b85a9544b8370ba947248
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/discord.py
@@ -0,0 +1,38 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, List
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+if TYPE_CHECKING:
+ import pandas as pd
+
+
+class DiscordChatLoader(BaseLoader):
+ """Load `Discord` chat logs."""
+
+ def __init__(self, chat_log: pd.DataFrame, user_id_col: str = "ID"):
+ """Initialize with a Pandas DataFrame containing chat logs.
+
+ Args:
+ chat_log: Pandas DataFrame containing chat logs.
+ user_id_col: Name of the column containing the user ID. Defaults to "ID".
+ """
+ if not isinstance(chat_log, pd.DataFrame):
+ raise ValueError(
+ f"Expected chat_log to be a pd.DataFrame, got {type(chat_log)}"
+ )
+ self.chat_log = chat_log
+ self.user_id_col = user_id_col
+
+ def load(self) -> List[Document]:
+ """Load all chat messages."""
+ result = []
+ for _, row in self.chat_log.iterrows():
+ user_id = row[self.user_id_col]
+ metadata = row.to_dict()
+ metadata.pop(self.user_id_col)
+ result.append(Document(page_content=user_id, metadata=metadata))
+ return result
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/doc_intelligence.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/doc_intelligence.py
new file mode 100644
index 0000000000000000000000000000000000000000..10369e5d70edf500ef5a6f3564fd811dce1482fa
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/doc_intelligence.py
@@ -0,0 +1,126 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Iterator, List, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.blob_loaders import Blob
+from langchain_community.document_loaders.parsers import (
+ AzureAIDocumentIntelligenceParser,
+)
+
+if TYPE_CHECKING:
+ from azure.core.credentials import TokenCredential
+
+
+class AzureAIDocumentIntelligenceLoader(BaseLoader):
+ """Load a PDF with Azure Document Intelligence."""
+
+ def __init__(
+ self,
+ api_endpoint: str,
+ api_key: Optional[str] = None,
+ file_path: Optional[str] = None,
+ url_path: Optional[str] = None,
+ bytes_source: Optional[bytes] = None,
+ api_version: Optional[str] = None,
+ api_model: str = "prebuilt-layout",
+ mode: str = "markdown",
+ *,
+ analysis_features: Optional[List[str]] = None,
+ azure_credential: Optional["TokenCredential"] = None,
+ ) -> None:
+ """
+ Initialize the object for file processing with Azure Document Intelligence
+ (formerly Form Recognizer).
+
+ This constructor initializes a AzureAIDocumentIntelligenceParser object to be
+ used for parsing files using the Azure Document Intelligence API. The load
+ method generates Documents whose content representations are determined by the
+ mode parameter.
+
+ Parameters:
+ -----------
+ api_endpoint: str
+ The API endpoint to use for DocumentIntelligenceClient construction.
+ api_key: str
+ The API key to use for DocumentIntelligenceClient construction.
+ file_path : Optional[str]
+ The path to the file that needs to be loaded.
+ Either file_path, url_path or bytes_source must be specified.
+ url_path : Optional[str]
+ The URL to the file that needs to be loaded.
+ Either file_path, url_path or bytes_source must be specified.
+ bytes_source : Optional[bytes]
+ The bytes array of the file that needs to be loaded.
+ Either file_path, url_path or bytes_source must be specified.
+ api_version: Optional[str]
+ The API version for DocumentIntelligenceClient. Setting None to use
+ the default value from `azure-ai-documentintelligence` package.
+ api_model: str
+ Unique document model name. Default value is "prebuilt-layout".
+ Note that overriding this default value may result in unsupported
+ behavior.
+ mode: Optional[str]
+ The type of content representation of the generated Documents.
+ Use either "single", "page", or "markdown". Default value is "markdown".
+ analysis_features: Optional[List[str]]
+ List of optional analysis features, each feature should be passed
+ as a str that conforms to the enum `DocumentAnalysisFeature` in
+ `azure-ai-documentintelligence` package. Default value is None.
+ azure_credential: Optional[TokenCredential]
+ The credentials to use for DocumentIntelligenceClient construction, when
+ using credentials other than api_key (like AD).
+
+ Examples:
+ ---------
+ >>> obj = AzureAIDocumentIntelligenceLoader(
+ ... file_path="path/to/file",
+ ... api_endpoint="https://endpoint.azure.com",
+ ... api_key="APIKEY",
+ ... api_version="2023-10-31-preview",
+ ... api_model="prebuilt-layout",
+ ... mode="markdown"
+ ... )
+ """
+
+ assert (
+ file_path is not None or url_path is not None or bytes_source is not None
+ ), "file_path, url_path or bytes_source must be provided"
+
+ assert api_key is not None or azure_credential is not None, (
+ "Either api_key or azure_credential must be provided."
+ )
+
+ assert api_key is None or azure_credential is None, (
+ "Only one of api_key or azure_credential should be provided."
+ )
+
+ self.file_path = file_path
+ self.url_path = url_path
+ self.bytes_source = bytes_source
+
+ self.parser = AzureAIDocumentIntelligenceParser(
+ api_endpoint=api_endpoint,
+ api_key=api_key,
+ api_version=api_version,
+ api_model=api_model,
+ mode=mode,
+ analysis_features=analysis_features,
+ azure_credential=azure_credential,
+ )
+
+ def lazy_load(
+ self,
+ ) -> Iterator[Document]:
+ """Lazy load the document as pages."""
+ if self.file_path is not None:
+ blob = Blob.from_path(self.file_path)
+ yield from self.parser.parse(blob)
+ elif self.url_path is not None:
+ yield from self.parser.parse_url(self.url_path)
+ elif self.bytes_source is not None:
+ yield from self.parser.parse_bytes(self.bytes_source)
+ else:
+ raise ValueError("No data source provided.")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/docugami.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/docugami.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ca99f16d572083d26198e8cfeade142690fec1a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/docugami.py
@@ -0,0 +1,369 @@
+import hashlib
+import io
+import logging
+import os
+from pathlib import Path
+from typing import Any, Dict, List, Mapping, Optional, Sequence, Union
+
+import requests
+from langchain_core._api.deprecation import deprecated
+from langchain_core.documents import Document
+from pydantic import BaseModel, model_validator
+
+from langchain_community.document_loaders.base import BaseLoader
+
+TABLE_NAME = "{http://www.w3.org/1999/xhtml}table"
+
+XPATH_KEY = "xpath"
+ID_KEY = "id"
+DOCUMENT_SOURCE_KEY = "source"
+DOCUMENT_NAME_KEY = "name"
+STRUCTURE_KEY = "structure"
+TAG_KEY = "tag"
+PROJECTS_KEY = "projects"
+
+DEFAULT_API_ENDPOINT = "https://api.docugami.com/v1preview1"
+
+logger = logging.getLogger(__name__)
+
+
+@deprecated(
+ since="0.0.24",
+ removal="1.0",
+ alternative_import="docugami_langchain.DocugamiLoader",
+)
+class DocugamiLoader(BaseLoader, BaseModel):
+ """Load from `Docugami`.
+
+ To use, you should have the ``dgml-utils`` python package installed.
+ """
+
+ api: str = DEFAULT_API_ENDPOINT
+ """The Docugami API endpoint to use."""
+
+ access_token: Optional[str] = os.environ.get("DOCUGAMI_API_KEY")
+ """The Docugami API access token to use."""
+
+ max_text_length: int = 4096
+ """Max length of chunk text returned."""
+
+ min_text_length: int = 32
+ """Threshold under which chunks are appended to next to avoid over-chunking."""
+
+ max_metadata_length: int = 512
+ """Max length of metadata text returned."""
+
+ include_xml_tags: bool = False
+ """Set to true for XML tags in chunk output text."""
+
+ parent_hierarchy_levels: int = 0
+ """Set appropriately to get parent chunks using the chunk hierarchy."""
+
+ parent_id_key: str = "doc_id"
+ """Metadata key for parent doc ID."""
+
+ sub_chunk_tables: bool = False
+ """Set to True to return sub-chunks within tables."""
+
+ whitespace_normalize_text: bool = True
+ """Set to False if you want to full whitespace formatting in the original
+ XML doc, including indentation."""
+
+ docset_id: Optional[str] = None
+ """The Docugami API docset ID to use."""
+
+ document_ids: Optional[Sequence[str]] = None
+ """The Docugami API document IDs to use."""
+
+ file_paths: Optional[Sequence[Union[Path, str]]]
+ """The local file paths to use."""
+
+ include_project_metadata_in_doc_metadata: bool = True
+ """Set to True if you want to include the project metadata in the doc metadata."""
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_local_or_remote(cls, values: Dict[str, Any]) -> Any:
+ """Validate that either local file paths are given, or remote API docset ID.
+
+ Args:
+ values: The values to validate.
+
+ Returns:
+ The validated values.
+ """
+ if values.get("file_paths") and values.get("docset_id"):
+ raise ValueError("Cannot specify both file_paths and remote API docset_id")
+
+ if not values.get("file_paths") and not values.get("docset_id"):
+ raise ValueError("Must specify either file_paths or remote API docset_id")
+
+ if values.get("docset_id") and not values.get("access_token"):
+ raise ValueError("Must specify access token if using remote API docset_id")
+
+ return values
+
+ def _parse_dgml(
+ self,
+ content: bytes,
+ document_name: Optional[str] = None,
+ additional_doc_metadata: Optional[Mapping] = None,
+ ) -> List[Document]:
+ """Parse a single DGML document into a list of `Document` objects."""
+ try:
+ from lxml import etree
+ except ImportError:
+ raise ImportError(
+ "Could not import lxml python package. "
+ "Please install it with `pip install lxml`."
+ )
+
+ try:
+ from dgml_utils.models import Chunk
+ from dgml_utils.segmentation import get_chunks
+ except ImportError:
+ raise ImportError(
+ "Could not import from dgml-utils python package. "
+ "Please install it with `pip install dgml-utils`."
+ )
+
+ def _build_framework_chunk(dg_chunk: Chunk) -> Document:
+ # Stable IDs for chunks with the same text.
+ _hashed_id = hashlib.md5(dg_chunk.text.encode()).hexdigest()
+ metadata = {
+ XPATH_KEY: dg_chunk.xpath,
+ ID_KEY: _hashed_id,
+ DOCUMENT_NAME_KEY: document_name,
+ DOCUMENT_SOURCE_KEY: document_name,
+ STRUCTURE_KEY: dg_chunk.structure,
+ TAG_KEY: dg_chunk.tag,
+ }
+
+ text = dg_chunk.text
+ if additional_doc_metadata:
+ if self.include_project_metadata_in_doc_metadata:
+ metadata.update(additional_doc_metadata)
+
+ return Document(
+ page_content=text[: self.max_text_length],
+ metadata=metadata,
+ )
+
+ # Parse the tree and return chunks
+ tree = etree.parse(io.BytesIO(content))
+ root = tree.getroot()
+
+ dg_chunks = get_chunks(
+ root,
+ min_text_length=self.min_text_length,
+ max_text_length=self.max_text_length,
+ whitespace_normalize_text=self.whitespace_normalize_text,
+ sub_chunk_tables=self.sub_chunk_tables,
+ include_xml_tags=self.include_xml_tags,
+ parent_hierarchy_levels=self.parent_hierarchy_levels,
+ )
+
+ framework_chunks: Dict[str, Document] = {}
+ for dg_chunk in dg_chunks:
+ framework_chunk = _build_framework_chunk(dg_chunk)
+ chunk_id = framework_chunk.metadata.get(ID_KEY)
+ if chunk_id:
+ framework_chunks[chunk_id] = framework_chunk
+ if dg_chunk.parent:
+ framework_parent_chunk = _build_framework_chunk(dg_chunk.parent)
+ parent_id = framework_parent_chunk.metadata.get(ID_KEY)
+ if parent_id and framework_parent_chunk.page_content:
+ framework_chunk.metadata[self.parent_id_key] = parent_id
+ framework_chunks[parent_id] = framework_parent_chunk
+
+ return list(framework_chunks.values())
+
+ def _document_details_for_docset_id(self, docset_id: str) -> List[Dict]:
+ """Gets all document details for the given docset ID"""
+ url = f"{self.api}/docsets/{docset_id}/documents"
+ all_documents = []
+
+ while url:
+ response = requests.get(
+ url,
+ headers={"Authorization": f"Bearer {self.access_token}"},
+ )
+ if response.ok:
+ data = response.json()
+ all_documents.extend(data["documents"])
+ url = data.get("next", None)
+ else:
+ raise Exception(
+ f"Failed to download {url} (status: {response.status_code})"
+ )
+
+ return all_documents
+
+ def _project_details_for_docset_id(self, docset_id: str) -> List[Dict]:
+ """Gets all project details for the given docset ID"""
+ url = f"{self.api}/projects?docset.id={docset_id}"
+ all_projects = []
+
+ while url:
+ response = requests.request(
+ "GET",
+ url,
+ headers={"Authorization": f"Bearer {self.access_token}"},
+ data={},
+ )
+ if response.ok:
+ data = response.json()
+ all_projects.extend(data["projects"])
+ url = data.get("next", None)
+ else:
+ raise Exception(
+ f"Failed to download {url} (status: {response.status_code})"
+ )
+
+ return all_projects
+
+ def _metadata_for_project(self, project: Dict) -> Dict:
+ """Gets project metadata for all files"""
+ project_id = project.get(ID_KEY)
+
+ url = f"{self.api}/projects/{project_id}/artifacts/latest"
+ all_artifacts = []
+
+ per_file_metadata: Dict = {}
+ while url:
+ response = requests.request(
+ "GET",
+ url,
+ headers={"Authorization": f"Bearer {self.access_token}"},
+ data={},
+ )
+ if response.ok:
+ data = response.json()
+ all_artifacts.extend(data["artifacts"])
+ url = data.get("next", None)
+ elif response.status_code == 404:
+ # Not found is ok, just means no published projects
+ return per_file_metadata
+ else:
+ raise Exception(
+ f"Failed to download {url} (status: {response.status_code})"
+ )
+
+ for artifact in all_artifacts:
+ artifact_name = artifact.get("name")
+ artifact_url = artifact.get("url")
+ artifact_doc = artifact.get("document")
+
+ if artifact_name == "report-values.xml" and artifact_url and artifact_doc:
+ doc_id = artifact_doc[ID_KEY]
+ metadata: Dict = {}
+
+ # The evaluated XML for each document is named after the project
+ response = requests.request(
+ "GET",
+ f"{artifact_url}/content",
+ headers={"Authorization": f"Bearer {self.access_token}"},
+ data={},
+ )
+
+ if response.ok:
+ try:
+ from lxml import etree
+ except ImportError:
+ raise ImportError(
+ "Could not import lxml python package. "
+ "Please install it with `pip install lxml`."
+ )
+ artifact_tree = etree.parse(io.BytesIO(response.content))
+ artifact_root = artifact_tree.getroot()
+ ns = artifact_root.nsmap
+ entries = artifact_root.xpath("//pr:Entry", namespaces=ns)
+ for entry in entries:
+ heading = entry.xpath("./pr:Heading", namespaces=ns)[0].text
+ value = " ".join(
+ entry.xpath("./pr:Value", namespaces=ns)[0].itertext()
+ ).strip()
+ metadata[heading] = value[: self.max_metadata_length]
+ per_file_metadata[doc_id] = metadata
+ else:
+ raise Exception(
+ f"Failed to download {artifact_url}/content "
+ + "(status: {response.status_code})"
+ )
+
+ return per_file_metadata
+
+ def _load_chunks_for_document(
+ self,
+ document_id: str,
+ docset_id: str,
+ document_name: Optional[str] = None,
+ additional_metadata: Optional[Mapping] = None,
+ ) -> List[Document]:
+ """Load chunks for a document."""
+ url = f"{self.api}/docsets/{docset_id}/documents/{document_id}/dgml"
+
+ response = requests.request(
+ "GET",
+ url,
+ headers={"Authorization": f"Bearer {self.access_token}"},
+ data={},
+ )
+
+ if response.ok:
+ return self._parse_dgml(
+ content=response.content,
+ document_name=document_name,
+ additional_doc_metadata=additional_metadata,
+ )
+ else:
+ raise Exception(
+ f"Failed to download {url} (status: {response.status_code})"
+ )
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ chunks: List[Document] = []
+
+ if self.access_token and self.docset_id:
+ # Remote mode
+ _document_details = self._document_details_for_docset_id(self.docset_id)
+ if self.document_ids:
+ _document_details = [
+ d for d in _document_details if d[ID_KEY] in self.document_ids
+ ]
+
+ _project_details = self._project_details_for_docset_id(self.docset_id)
+ combined_project_metadata: Dict[str, Dict] = {}
+ if _project_details and self.include_project_metadata_in_doc_metadata:
+ # If there are any projects for this docset and the caller requested
+ # project metadata, load it.
+ for project in _project_details:
+ metadata = self._metadata_for_project(project)
+ for file_id in metadata:
+ if file_id not in combined_project_metadata:
+ combined_project_metadata[file_id] = metadata[file_id]
+ else:
+ combined_project_metadata[file_id].update(metadata[file_id])
+
+ for doc in _document_details:
+ doc_id = doc[ID_KEY]
+ doc_name = doc.get(DOCUMENT_NAME_KEY)
+ doc_metadata = combined_project_metadata.get(doc_id)
+ chunks += self._load_chunks_for_document(
+ document_id=doc_id,
+ docset_id=self.docset_id,
+ document_name=doc_name,
+ additional_metadata=doc_metadata,
+ )
+ elif self.file_paths:
+ # Local mode (for integration testing, or pre-downloaded XML)
+ for path in self.file_paths:
+ path = Path(path)
+ with open(path, "rb") as file:
+ chunks += self._parse_dgml(
+ content=file.read(),
+ document_name=path.name,
+ )
+
+ return chunks
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/docusaurus.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/docusaurus.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc37fb810e18b5d3756792fb3280919ed7e2f3e6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/docusaurus.py
@@ -0,0 +1,51 @@
+"""Load Documents from Docusarus Documentation"""
+
+from typing import Any, List, Optional
+
+from langchain_community.document_loaders.sitemap import SitemapLoader
+
+
+class DocusaurusLoader(SitemapLoader):
+ """Load from Docusaurus Documentation.
+
+ It leverages the SitemapLoader to loop through the generated pages of a
+ Docusaurus Documentation website and extracts the content by looking for specific
+ HTML tags. By default, the parser searches for the main content of the Docusaurus
+ page, which is normally the . You can also define your own
+ custom HTML tags by providing them as a list, for example: ["div", ".main", "a"].
+ """
+
+ def __init__(
+ self,
+ url: str,
+ custom_html_tags: Optional[List[str]] = None,
+ **kwargs: Any,
+ ):
+ """Initialize DocusaurusLoader
+
+ Args:
+ url: The base URL of the Docusaurus website.
+ custom_html_tags: Optional custom html tags to extract content from pages.
+ kwargs: Additional args to extend the underlying SitemapLoader, for example:
+ filter_urls, blocksize, meta_function, is_local, continue_on_failure
+ """
+ if not kwargs.get("is_local"):
+ url = f"{url}/sitemap.xml"
+
+ self.custom_html_tags = custom_html_tags or ["main article"]
+
+ super().__init__(
+ url,
+ parsing_function=kwargs.get("parsing_function") or self._parsing_function,
+ **kwargs,
+ )
+
+ def _parsing_function(self, content: Any) -> str:
+ """Parses specific elements from a Docusaurus page."""
+ relevant_elements = content.select(",".join(self.custom_html_tags))
+
+ for element in relevant_elements:
+ if element not in relevant_elements:
+ element.decompose()
+
+ return str(content.get_text())
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/dropbox.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/dropbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0350914536f5d6fc3404ce034b5e00b2872bc2a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/dropbox.py
@@ -0,0 +1,174 @@
+# Prerequisites:
+# 1. Create a Dropbox app.
+# 2. Give the app these scope permissions: `files.metadata.read`
+# and `files.content.read`.
+# 3. Generate access token: https://www.dropbox.com/developers/apps/create.
+# 4. `pip install dropbox` (requires `pip install unstructured[pdf]` for PDF filetype).
+
+
+import os
+import tempfile
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+from langchain_core.documents import Document
+from pydantic import BaseModel, model_validator
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class DropboxLoader(BaseLoader, BaseModel):
+ """Load files from `Dropbox`.
+
+ In addition to common files such as text and PDF files, it also supports
+ *Dropbox Paper* files.
+ """
+
+ dropbox_access_token: str
+ """Dropbox access token."""
+ dropbox_folder_path: Optional[str] = None
+ """The folder path to load from."""
+ dropbox_file_paths: Optional[List[str]] = None
+ """The file paths to load from."""
+ recursive: bool = False
+ """Flag to indicate whether to load files recursively from subfolders."""
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_inputs(cls, values: Dict[str, Any]) -> Any:
+ """Validate that either folder_path or file_paths is set, but not both."""
+ if (
+ values.get("dropbox_folder_path") is not None
+ and values.get("dropbox_file_paths") is not None
+ ):
+ raise ValueError("Cannot specify both folder_path and file_paths")
+ if values.get("dropbox_folder_path") is None and not values.get(
+ "dropbox_file_paths"
+ ):
+ raise ValueError("Must specify either folder_path or file_paths")
+
+ return values
+
+ def _create_dropbox_client(self) -> Any:
+ """Create a Dropbox client."""
+ try:
+ from dropbox import Dropbox, exceptions
+ except ImportError:
+ raise ImportError("You must run `pip install dropbox")
+
+ try:
+ dbx = Dropbox(self.dropbox_access_token)
+ dbx.users_get_current_account()
+ except exceptions.AuthError as ex:
+ raise ValueError(
+ "Invalid Dropbox access token. Please verify your token and try again."
+ ) from ex
+ return dbx
+
+ def _load_documents_from_folder(self, folder_path: str) -> List[Document]:
+ """Load documents from a Dropbox folder."""
+ dbx = self._create_dropbox_client()
+
+ try:
+ from dropbox import exceptions
+ from dropbox.files import FileMetadata
+ except ImportError:
+ raise ImportError("You must run `pip install dropbox")
+
+ try:
+ results = dbx.files_list_folder(folder_path, recursive=self.recursive)
+ except exceptions.ApiError as ex:
+ raise ValueError(
+ f"Could not list files in the folder: {folder_path}. "
+ "Please verify the folder path and try again."
+ ) from ex
+
+ files = [entry for entry in results.entries if isinstance(entry, FileMetadata)]
+ documents = [
+ doc
+ for doc in (self._load_file_from_path(file.path_display) for file in files)
+ if doc is not None
+ ]
+ return documents
+
+ def _load_file_from_path(self, file_path: str) -> Optional[Document]:
+ """Load a file from a Dropbox path."""
+ dbx = self._create_dropbox_client()
+
+ try:
+ from dropbox import exceptions
+ except ImportError:
+ raise ImportError("You must run `pip install dropbox")
+
+ try:
+ file_metadata = dbx.files_get_metadata(file_path)
+
+ if file_metadata.is_downloadable:
+ _, response = dbx.files_download(file_path)
+
+ # Some types such as Paper, need to be exported.
+ elif file_metadata.export_info:
+ _, response = dbx.files_export(file_path, "markdown")
+
+ except exceptions.ApiError as ex:
+ raise ValueError(
+ f"Could not load file: {file_path}. Please verify the file path"
+ "and try again."
+ ) from ex
+
+ try:
+ text = response.content.decode("utf-8")
+ except UnicodeDecodeError:
+ file_extension = os.path.splitext(file_path)[1].lower()
+
+ if file_extension == ".pdf":
+ print(f"File {file_path} type detected as .pdf") # noqa: T201
+ from langchain_community.document_loaders import UnstructuredPDFLoader
+
+ # Download it to a temporary file.
+ temp_dir = tempfile.TemporaryDirectory()
+ temp_pdf = Path(temp_dir.name) / "tmp.pdf"
+ with open(temp_pdf, mode="wb") as f:
+ f.write(response.content)
+
+ try:
+ loader = UnstructuredPDFLoader(str(temp_pdf))
+ docs = loader.load()
+ if docs:
+ return docs[0]
+ except Exception as pdf_ex:
+ print(f"Error while trying to parse PDF {file_path}: {pdf_ex}") # noqa: T201
+ return None
+ else:
+ print( # noqa: T201
+ f"File {file_path} could not be decoded as pdf or text. Skipping."
+ )
+
+ return None
+
+ metadata = {
+ "source": f"dropbox://{file_path}",
+ "title": os.path.basename(file_path),
+ }
+ return Document(page_content=text, metadata=metadata)
+
+ def _load_documents_from_paths(self) -> List[Document]:
+ """Load documents from a list of Dropbox file paths."""
+ if not self.dropbox_file_paths:
+ raise ValueError("file_paths must be set")
+
+ return [
+ doc
+ for doc in (
+ self._load_file_from_path(file_path)
+ for file_path in self.dropbox_file_paths
+ )
+ if doc is not None
+ ]
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ if self.dropbox_folder_path is not None:
+ return self._load_documents_from_folder(self.dropbox_folder_path)
+ else:
+ return self._load_documents_from_paths()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/duckdb_loader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/duckdb_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e2c3022d547a5bea200940b8d0114c6f48d3850
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/duckdb_loader.py
@@ -0,0 +1,89 @@
+from typing import Dict, List, Optional, cast
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class DuckDBLoader(BaseLoader):
+ """Load from `DuckDB`.
+
+ Each document represents one row of the result. The `page_content_columns`
+ are written into the `page_content` of the document. The `metadata_columns`
+ are written into the `metadata` of the document. By default, all columns
+ are written into the `page_content` and none into the `metadata`.
+ """
+
+ def __init__(
+ self,
+ query: str,
+ database: str = ":memory:",
+ read_only: bool = False,
+ config: Optional[Dict[str, str]] = None,
+ page_content_columns: Optional[List[str]] = None,
+ metadata_columns: Optional[List[str]] = None,
+ ):
+ """
+
+ Args:
+ query: The query to execute.
+ database: The database to connect to. Defaults to ":memory:".
+ read_only: Whether to open the database in read-only mode.
+ Defaults to False.
+ config: A dictionary of configuration options to pass to the database.
+ Optional.
+ page_content_columns: The columns to write into the `page_content`
+ of the document. Optional.
+ metadata_columns: The columns to write into the `metadata` of the document.
+ Optional.
+ """
+ self.query = query
+ self.database = database
+ self.read_only = read_only
+ self.config = config or {}
+ self.page_content_columns = page_content_columns
+ self.metadata_columns = metadata_columns
+
+ def load(self) -> List[Document]:
+ try:
+ import duckdb
+ except ImportError:
+ raise ImportError(
+ "Could not import duckdb python package. "
+ "Please install it with `pip install duckdb`."
+ )
+
+ docs = []
+ with duckdb.connect(
+ database=self.database, read_only=self.read_only, config=self.config
+ ) as con:
+ query_result = con.execute(self.query)
+ results = query_result.fetchall()
+ description = cast(list, query_result.description)
+ field_names = [c[0] for c in description]
+
+ if self.page_content_columns is None:
+ page_content_columns = field_names
+ else:
+ page_content_columns = self.page_content_columns
+
+ if self.metadata_columns is None:
+ metadata_columns = []
+ else:
+ metadata_columns = self.metadata_columns
+
+ for result in results:
+ page_content = "\n".join(
+ f"{column}: {result[field_names.index(column)]}"
+ for column in page_content_columns
+ )
+
+ metadata = {
+ column: result[field_names.index(column)]
+ for column in metadata_columns
+ }
+
+ doc = Document(page_content=page_content, metadata=metadata)
+ docs.append(doc)
+
+ return docs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/email.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/email.py
new file mode 100644
index 0000000000000000000000000000000000000000..24716c55a9fd77d0e0b34e3606b6c6fc412ba868
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/email.py
@@ -0,0 +1,119 @@
+import os
+from pathlib import Path
+from typing import Any, Iterator, List, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ satisfies_min_unstructured_version,
+)
+
+
+class UnstructuredEmailLoader(UnstructuredFileLoader):
+ """Load email files using `Unstructured`.
+
+ Works with both
+ .eml and .msg files. You can process attachments in addition to the
+ e-mail message itself by passing process_attachments=True into the
+ constructor for the loader. By default, attachments will be processed
+ with the unstructured partition function. If you already know the document
+ types of the attachments, you can specify another partitioning function
+ with the attachment partitioner kwarg.
+
+ Example
+ -------
+ from langchain_community.document_loaders import UnstructuredEmailLoader
+
+ loader = UnstructuredEmailLoader("example_data/fake-email.eml", mode="elements")
+ loader.load()
+
+ Example
+ -------
+ from langchain_community.document_loaders import UnstructuredEmailLoader
+
+ loader = UnstructuredEmailLoader(
+ "example_data/fake-email-attachment.eml",
+ mode="elements",
+ process_attachments=True,
+ )
+ loader.load()
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ process_attachments = unstructured_kwargs.get("process_attachments")
+ attachment_partitioner = unstructured_kwargs.get("attachment_partitioner")
+
+ if process_attachments and attachment_partitioner is None:
+ from unstructured.partition.auto import partition
+
+ unstructured_kwargs["attachment_partitioner"] = partition
+
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.file_utils.filetype import FileType, detect_filetype
+
+ filetype = detect_filetype(self.file_path)
+
+ if filetype == FileType.EML:
+ from unstructured.partition.email import partition_email
+
+ return partition_email(filename=self.file_path, **self.unstructured_kwargs)
+ elif satisfies_min_unstructured_version("0.5.8") and filetype == FileType.MSG:
+ from unstructured.partition.msg import partition_msg
+
+ return partition_msg(filename=self.file_path, **self.unstructured_kwargs)
+ else:
+ raise ValueError(
+ f"Filetype {filetype} is not supported in UnstructuredEmailLoader."
+ )
+
+
+class OutlookMessageLoader(BaseLoader):
+ """
+ Loads Outlook Message files using extract_msg.
+
+ https://github.com/TeamMsgExtractor/msg-extractor
+ """
+
+ def __init__(self, file_path: Union[str, Path]):
+ """Initialize with a file path.
+
+ Args:
+ file_path: The path to the Outlook Message file.
+ """
+
+ self.file_path = str(file_path)
+
+ if not os.path.isfile(self.file_path):
+ raise ValueError(f"File path {self.file_path} is not a valid file")
+
+ try:
+ import extract_msg # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "extract_msg is not installed. Please install it with "
+ "`pip install extract_msg`"
+ )
+
+ def lazy_load(self) -> Iterator[Document]:
+ import extract_msg
+
+ msg = extract_msg.Message(self.file_path)
+ yield Document(
+ page_content=msg.body,
+ metadata={
+ "source": self.file_path,
+ "subject": msg.subject,
+ "sender": msg.sender,
+ "date": msg.date,
+ },
+ )
+ msg.close()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/epub.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/epub.py
new file mode 100644
index 0000000000000000000000000000000000000000..806737b62a5b9d629ac0238e06e2bae1a19a0e1e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/epub.py
@@ -0,0 +1,55 @@
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ validate_unstructured_version,
+)
+
+
+class UnstructuredEPubLoader(UnstructuredFileLoader):
+ """Load `EPub` files using `Unstructured`.
+
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredEPubLoader
+
+ loader = UnstructuredEPubLoader(
+ "example.epub", mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/bricks.html#partition-epub
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+
+ Args:
+ file_path: The path to the EPub file to load.
+ mode: The mode to use when loading the file. Can be one of "single",
+ "multi", or "all". Default is "single".
+ **unstructured_kwargs: Any kwargs to pass to the unstructured.
+ """
+ file_path = str(file_path)
+ validate_unstructured_version("0.5.4")
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.epub import partition_epub
+
+ return partition_epub(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/etherscan.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/etherscan.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff78aa90a91af83f7ac77bf338d514a2aa7a8166
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/etherscan.py
@@ -0,0 +1,199 @@
+import os
+import re
+from typing import Iterator, List
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class EtherscanLoader(BaseLoader):
+ """Load transactions from `Ethereum` mainnet.
+
+ The Loader use Etherscan API to interact with Ethereum mainnet.
+
+ ETHERSCAN_API_KEY environment variable must be set use this loader.
+ """
+
+ def __init__(
+ self,
+ account_address: str,
+ api_key: str = "docs-demo",
+ filter: str = "normal_transaction",
+ page: int = 1,
+ offset: int = 10,
+ start_block: int = 0,
+ end_block: int = 99999999,
+ sort: str = "desc",
+ ):
+ self.account_address = account_address
+ self.api_key = os.environ.get("ETHERSCAN_API_KEY") or api_key
+ self.filter = filter
+ self.page = page
+ self.offset = offset
+ self.start_block = start_block
+ self.end_block = end_block
+ self.sort = sort
+
+ if not self.api_key:
+ raise ValueError("Etherscan API key not provided")
+
+ if not re.match(r"^0x[a-fA-F0-9]{40}$", self.account_address):
+ raise ValueError(f"Invalid contract address {self.account_address}")
+ if filter not in [
+ "normal_transaction",
+ "internal_transaction",
+ "erc20_transaction",
+ "eth_balance",
+ "erc721_transaction",
+ "erc1155_transaction",
+ ]:
+ raise ValueError(f"Invalid filter {filter}")
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load Documents from table."""
+ result = []
+ if self.filter == "normal_transaction":
+ result = self.getNormTx()
+ elif self.filter == "internal_transaction":
+ result = self.getInternalTx()
+ elif self.filter == "erc20_transaction":
+ result = self.getERC20Tx()
+ elif self.filter == "eth_balance":
+ result = self.getEthBalance()
+ elif self.filter == "erc721_transaction":
+ result = self.getERC721Tx()
+ elif self.filter == "erc1155_transaction":
+ result = self.getERC1155Tx()
+ else:
+ raise ValueError(f"Invalid filter {filter}")
+ for doc in result:
+ yield doc
+
+ def getNormTx(self) -> List[Document]:
+ url = (
+ f"https://api.etherscan.io/api?module=account&action=txlist&address={self.account_address}"
+ f"&startblock={self.start_block}&endblock={self.end_block}&page={self.page}"
+ f"&offset={self.offset}&sort={self.sort}&apikey={self.api_key}"
+ )
+ try:
+ response = requests.get(url)
+ response.raise_for_status()
+ except requests.exceptions.RequestException as e:
+ print("Error occurred while making the request:", e) # noqa: T201
+ items = response.json()["result"]
+ result = []
+ if len(items) == 0:
+ return [Document(page_content="")]
+ for item in items:
+ content = str(item)
+ metadata = {"from": item["from"], "tx_hash": item["hash"], "to": item["to"]}
+ result.append(Document(page_content=content, metadata=metadata))
+ print(len(result)) # noqa: T201
+ return result
+
+ def getEthBalance(self) -> List[Document]:
+ url = (
+ f"https://api.etherscan.io/api?module=account&action=balance"
+ f"&address={self.account_address}&tag=latest&apikey={self.api_key}"
+ )
+
+ try:
+ response = requests.get(url)
+ response.raise_for_status()
+ except requests.exceptions.RequestException as e:
+ print("Error occurred while making the request:", e) # noqa: T201
+ return [Document(page_content=response.json()["result"])]
+
+ def getInternalTx(self) -> List[Document]:
+ url = (
+ f"https://api.etherscan.io/api?module=account&action=txlistinternal"
+ f"&address={self.account_address}&startblock={self.start_block}"
+ f"&endblock={self.end_block}&page={self.page}&offset={self.offset}"
+ f"&sort={self.sort}&apikey={self.api_key}"
+ )
+
+ try:
+ response = requests.get(url)
+ response.raise_for_status()
+ except requests.exceptions.RequestException as e:
+ print("Error occurred while making the request:", e) # noqa: T201
+ items = response.json()["result"]
+ result = []
+ if len(items) == 0:
+ return [Document(page_content="")]
+ for item in items:
+ content = str(item)
+ metadata = {"from": item["from"], "tx_hash": item["hash"], "to": item["to"]}
+ result.append(Document(page_content=content, metadata=metadata))
+ return result
+
+ def getERC20Tx(self) -> List[Document]:
+ url = (
+ f"https://api.etherscan.io/api?module=account&action=tokentx"
+ f"&address={self.account_address}&startblock={self.start_block}"
+ f"&endblock={self.end_block}&page={self.page}&offset={self.offset}"
+ f"&sort={self.sort}&apikey={self.api_key}"
+ )
+
+ try:
+ response = requests.get(url)
+ response.raise_for_status()
+ except requests.exceptions.RequestException as e:
+ print("Error occurred while making the request:", e) # noqa: T201
+ items = response.json()["result"]
+ result = []
+ if len(items) == 0:
+ return [Document(page_content="")]
+ for item in items:
+ content = str(item)
+ metadata = {"from": item["from"], "tx_hash": item["hash"], "to": item["to"]}
+ result.append(Document(page_content=content, metadata=metadata))
+ return result
+
+ def getERC721Tx(self) -> List[Document]:
+ url = (
+ f"https://api.etherscan.io/api?module=account&action=tokennfttx"
+ f"&address={self.account_address}&startblock={self.start_block}"
+ f"&endblock={self.end_block}&page={self.page}&offset={self.offset}"
+ f"&sort={self.sort}&apikey={self.api_key}"
+ )
+
+ try:
+ response = requests.get(url)
+ response.raise_for_status()
+ except requests.exceptions.RequestException as e:
+ print("Error occurred while making the request:", e) # noqa: T201
+ items = response.json()["result"]
+ result = []
+ if len(items) == 0:
+ return [Document(page_content="")]
+ for item in items:
+ content = str(item)
+ metadata = {"from": item["from"], "tx_hash": item["hash"], "to": item["to"]}
+ result.append(Document(page_content=content, metadata=metadata))
+ return result
+
+ def getERC1155Tx(self) -> List[Document]:
+ url = (
+ f"https://api.etherscan.io/api?module=account&action=token1155tx"
+ f"&address={self.account_address}&startblock={self.start_block}"
+ f"&endblock={self.end_block}&page={self.page}&offset={self.offset}"
+ f"&sort={self.sort}&apikey={self.api_key}"
+ )
+
+ try:
+ response = requests.get(url)
+ response.raise_for_status()
+ except requests.exceptions.RequestException as e:
+ print("Error occurred while making the request:", e) # noqa: T201
+ items = response.json()["result"]
+ result = []
+ if len(items) == 0:
+ return [Document(page_content="")]
+ for item in items:
+ content = str(item)
+ metadata = {"from": item["from"], "tx_hash": item["hash"], "to": item["to"]}
+ result.append(Document(page_content=content, metadata=metadata))
+ return result
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/evernote.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/evernote.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebc8f7772cb6595058d3d82a23f04bcda5b1947b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/evernote.py
@@ -0,0 +1,250 @@
+"""Document loader for EverNote ENEX export files.
+
+This module provides functionality to securely load and parse EverNote notebook
+export files (``.enex`` format) into LangChain Document objects.
+"""
+
+import hashlib
+import logging
+from base64 import b64decode
+from pathlib import Path
+from time import strptime
+from typing import Any, Dict, Iterator, List, Optional, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+
+class EverNoteLoader(BaseLoader):
+ """Document loader for EverNote ENEX export files.
+
+ Loads EverNote notebook export files (``.enex`` format) into LangChain Documents.
+ Extracts plain text content from HTML and preserves note metadata including
+ titles, timestamps, and attachments. Uses secure XML parsing to prevent
+ vulnerabilities.
+
+ The loader supports two modes:
+ - Single document: Concatenates all notes into one Document (default)
+ - Multiple documents: Creates separate Documents for each note
+
+ `Instructions for creating ENEX files `__
+
+ Example:
+
+ .. code-block:: python
+
+ from langchain_community.document_loaders import EverNoteLoader
+
+ # Load all notes as a single document
+ loader = EverNoteLoader("my_notebook.enex")
+ documents = loader.load()
+
+ # Load each note as a separate document:
+ # documents = [ document1, document2, ... ]
+ loader = EverNoteLoader("my_notebook.enex", load_single_document=False)
+ documents = loader.load()
+
+ # Lazy loading for large files
+ for doc in loader.lazy_load():
+ print(f"Title: {doc.metadata.get('title', 'Untitled')}")
+ print(f"Content: {doc.page_content[:100]}...")
+
+ Note:
+ Requires the ``lxml`` and ``html2text`` packages to be installed.
+ Install with: ``pip install lxml html2text``
+ """
+
+ def __init__(self, file_path: Union[str, Path], load_single_document: bool = True):
+ """Initialize the EverNote loader.
+
+ Args:
+ file_path: Path to the EverNote export file (``.enex`` extension).
+ load_single_document: Whether to concatenate all notes into a single
+ Document. If ``True``, only the ``source`` metadata is preserved.
+ If ``False``, each note becomes a separate Document with its own
+ metadata.
+ """
+ self.file_path = str(file_path)
+ self.load_single_document = load_single_document
+
+ def _lazy_load(self) -> Iterator[Document]:
+ """Lazily load documents from the EverNote export file.
+
+ Lazy loading allows processing large EverNote files without
+ loading everything into memory at once. This method yields Documents
+ one by one by parsning the XML. Each document represents a note in the EverNote
+ export, containing the note's content as ``page_content`` and metadata including
+ ``title``, ``created/updated`` ``timestamps``, and other note attributes.
+
+ Yields:
+ Document: A Document object for each note in the export file.
+ """
+ for note in self._parse_note_xml(self.file_path):
+ if note.get("content") is not None:
+ yield Document(
+ page_content=note["content"],
+ metadata={
+ **{
+ key: value
+ for key, value in note.items()
+ if key not in ["content", "content-raw", "resource"]
+ },
+ **{"source": self.file_path},
+ },
+ )
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load documents from EverNote export file.
+
+ Depending on the ``load_single_document`` setting, either yields individual
+ Documents for each note or a single Document containing all notes.
+
+ Yields:
+ Document: Either individual note Documents or a single combined Document.
+ """
+ if not self.load_single_document:
+ yield from self._lazy_load()
+ else:
+ yield Document(
+ page_content="".join(
+ [document.page_content for document in self._lazy_load()]
+ ),
+ metadata={"source": self.file_path},
+ )
+
+ @staticmethod
+ def _parse_content(content: str) -> str:
+ """Parse HTML content from EverNote into plain text.
+
+ Converts HTML content to plain text using the ``html2text`` library.
+ Strips whitespace from the result.
+
+ Args:
+ content: HTML content string from EverNote.
+
+ Returns:
+ Plain text version of the content.
+
+ Raises:
+ ImportError: If ``html2text`` is not installed.
+ """
+ try:
+ import html2text
+
+ return html2text.html2text(content).strip()
+ except ImportError as e:
+ raise ImportError(
+ "Could not import `html2text`. Although it is not a required package "
+ "to use LangChain, using the EverNote loader requires `html2text`. "
+ "Please install `html2text` via `pip install html2text` and try again."
+ ) from e
+
+ @staticmethod
+ def _parse_resource(resource: list) -> dict:
+ """Parse resource elements from EverNote XML.
+
+ Extracts resource information like attachments, images, etc.
+ Base64 decodes data elements and generates MD5 hashes.
+
+ Args:
+ resource: List of XML elements representing a resource.
+
+ Returns:
+ Dictionary containing resource metadata and decoded data.
+ """
+ rsc_dict: Dict[str, Any] = {}
+ for elem in resource:
+ if elem.tag == "data":
+ # Sometimes elem.text is None
+ rsc_dict[elem.tag] = b64decode(elem.text) if elem.text else b""
+ rsc_dict["hash"] = hashlib.md5(rsc_dict[elem.tag]).hexdigest()
+ else:
+ rsc_dict[elem.tag] = elem.text
+
+ return rsc_dict
+
+ @staticmethod
+ def _parse_note(note: List, prefix: Optional[str] = None) -> dict:
+ """Parse a note element from EverNote XML.
+
+ Extracts note content, metadata, resources, and attributes.
+ Handles nested note-attributes recursively with prefixes.
+
+ Args:
+ note: List of XML elements representing a note.
+ prefix: Optional prefix for nested attribute names.
+
+ Returns:
+ Dictionary containing note content and metadata.
+ """
+ note_dict: Dict[str, Any] = {}
+ resources = []
+
+ def add_prefix(element_tag: str) -> str:
+ if prefix is None:
+ return element_tag
+ return f"{prefix}.{element_tag}"
+
+ for elem in note:
+ if elem.tag == "content":
+ note_dict[elem.tag] = EverNoteLoader._parse_content(elem.text)
+ # A copy of original content
+ note_dict["content-raw"] = elem.text
+ elif elem.tag == "resource":
+ resources.append(EverNoteLoader._parse_resource(elem))
+ elif elem.tag == "created" or elem.tag == "updated":
+ note_dict[elem.tag] = strptime(elem.text, "%Y%m%dT%H%M%SZ")
+ elif elem.tag == "note-attributes":
+ additional_attributes = EverNoteLoader._parse_note(
+ elem, elem.tag
+ ) # Recursively enter the note-attributes tag
+ note_dict.update(additional_attributes)
+ else:
+ note_dict[elem.tag] = elem.text
+
+ if len(resources) > 0:
+ note_dict["resource"] = resources
+
+ return {add_prefix(key): value for key, value in note_dict.items()}
+
+ @staticmethod
+ def _parse_note_xml(xml_file: str) -> Iterator[Dict[str, Any]]:
+ """Parse EverNote XML file securely.
+
+ Uses ``lxml`` with secure parsing configuration to prevent XML vulnerabilities
+ including XXE attacks, XML bombs, and malformed XML exploitation.
+
+ Args:
+ xml_file: Path to the EverNote export XML file.
+
+ Yields:
+ Dictionary containing parsed note data for each note in the file.
+
+ Raises:
+ ImportError: If ``lxml`` is not installed.
+ """
+ try:
+ from lxml import etree
+ except ImportError as e:
+ logger.error(
+ "Could not import `lxml`. Although it is not a required package to use "
+ "LangChain, using the EverNote loader requires `lxml`. Please install "
+ "`lxml` via `pip install lxml` and try again."
+ )
+ raise e
+
+ context = etree.iterparse(
+ xml_file,
+ encoding="utf-8",
+ resolve_entities=False, # Prevents XXE attacks
+ no_network=True, # Blocks network-based external entities
+ recover=False, # Avoid parsing invalid/malformed XML
+ huge_tree=False, # Protect against XML Bomb DoS attacks
+ )
+
+ for action, elem in context:
+ if elem.tag == "note":
+ yield EverNoteLoader._parse_note(elem)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/excel.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/excel.py
new file mode 100644
index 0000000000000000000000000000000000000000..eeb08c1873f043550e6a9b8910598feeda61442d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/excel.py
@@ -0,0 +1,52 @@
+"""Loads Microsoft Excel files."""
+
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ validate_unstructured_version,
+)
+
+
+class UnstructuredExcelLoader(UnstructuredFileLoader):
+ """Load Microsoft Excel files using `Unstructured`.
+
+ Like other
+ Unstructured loaders, UnstructuredExcelLoader can be used in both
+ "single" and "elements" mode. If you use the loader in "elements"
+ mode, each sheet in the Excel file will be an Unstructured Table
+ element. If you use the loader in "single" mode, an
+ HTML representation of the table will be available in the
+ "text_as_html" key in the document metadata.
+
+ Examples
+ --------
+ from langchain_community.document_loaders.excel import UnstructuredExcelLoader
+
+ loader = UnstructuredExcelLoader("stanley-cups.xlsx", mode="elements")
+ docs = loader.load()
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+
+ Args:
+ file_path: The path to the Microsoft Excel file.
+ mode: The mode to use when partitioning the file. See unstructured docs
+ for more info. Optional. Defaults to "single".
+ **unstructured_kwargs: Keyword arguments to pass to unstructured.
+ """
+ file_path = str(file_path)
+ validate_unstructured_version(min_unstructured_version="0.6.7")
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.xlsx import partition_xlsx
+
+ return partition_xlsx(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/facebook_chat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/facebook_chat.py
new file mode 100644
index 0000000000000000000000000000000000000000..443c9ce07f9857bf41ee44e69fd171f13fc7c05e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/facebook_chat.py
@@ -0,0 +1,45 @@
+import datetime
+import json
+from pathlib import Path
+from typing import Iterator, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+def concatenate_rows(row: dict) -> str:
+ """Combine message information in a readable format ready to be used.
+
+ Args:
+ row: dictionary containing message information.
+ """
+ sender = row["sender_name"]
+ text = row["content"]
+ date = datetime.datetime.fromtimestamp(row["timestamp_ms"] / 1000).strftime(
+ "%Y-%m-%d %H:%M:%S"
+ )
+ return f"{sender} on {date}: {text}\n\n"
+
+
+class FacebookChatLoader(BaseLoader):
+ """Load `Facebook Chat` messages directory dump."""
+
+ def __init__(self, path: Union[str, Path]):
+ """Initialize with a path."""
+ self.file_path = path
+
+ def lazy_load(self) -> Iterator[Document]:
+ p = Path(self.file_path)
+
+ with open(p, encoding="utf8") as f:
+ d = json.load(f)
+
+ text = "".join(
+ concatenate_rows(message)
+ for message in d["messages"]
+ if message.get("content") and isinstance(message["content"], str)
+ )
+ metadata = {"source": str(p)}
+
+ yield Document(page_content=text, metadata=metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/fauna.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/fauna.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbfda737850eed3fd1868bb9cb1e60e42187e01a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/fauna.py
@@ -0,0 +1,62 @@
+from typing import Iterator, Optional, Sequence
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class FaunaLoader(BaseLoader):
+ """Load from `FaunaDB`.
+
+ Attributes:
+ query (str): The FQL query string to execute.
+ page_content_field (str): The field that contains the content of each page.
+ secret (str): The secret key for authenticating to FaunaDB.
+ metadata_fields (Optional[Sequence[str]]):
+ Optional list of field names to include in metadata.
+ """
+
+ def __init__(
+ self,
+ query: str,
+ page_content_field: str,
+ secret: str,
+ metadata_fields: Optional[Sequence[str]] = None,
+ ):
+ self.query = query
+ self.page_content_field = page_content_field
+ self.secret = secret
+ self.metadata_fields = metadata_fields
+
+ def lazy_load(self) -> Iterator[Document]:
+ try:
+ from fauna import Page, fql
+ from fauna.client import Client
+ from fauna.encoding import QuerySuccess
+ except ImportError:
+ raise ImportError(
+ "Could not import fauna python package. "
+ "Please install it with `pip install fauna`."
+ )
+ # Create Fauna Client
+ client = Client(secret=self.secret)
+ # Run FQL Query
+ response: QuerySuccess = client.query(fql(self.query))
+ page: Page = response.data
+ for result in page:
+ if result is not None:
+ document_dict = dict(result.items())
+ page_content = ""
+ for key, value in document_dict.items():
+ if key == self.page_content_field:
+ page_content = value
+ document: Document = Document(
+ page_content=page_content,
+ metadata={"id": result.id, "ts": result.ts},
+ )
+ yield document
+ if page.after is not None:
+ yield Document(
+ page_content="Next Page Exists",
+ metadata={"after": page.after},
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/figma.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/figma.py
new file mode 100644
index 0000000000000000000000000000000000000000..d147aaf9f206c8449f3cc36efdba03dd8963a243
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/figma.py
@@ -0,0 +1,48 @@
+import json
+import urllib.request
+from typing import Any, List
+
+from langchain_core.documents import Document
+from langchain_core.utils import stringify_dict
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class FigmaFileLoader(BaseLoader):
+ """Load `Figma` file."""
+
+ def __init__(self, access_token: str, ids: str, key: str):
+ """Initialize with access token, ids, and key.
+
+ Args:
+ access_token: The access token for the Figma REST API.
+ ids: The ids of the Figma file.
+ key: The key for the Figma file
+ """
+ self.access_token = access_token
+ self.ids = ids
+ self.key = key
+
+ def _construct_figma_api_url(self) -> str:
+ api_url = "https://api.figma.com/v1/files/%s/nodes?ids=%s" % (
+ self.key,
+ self.ids,
+ )
+ return api_url
+
+ def _get_figma_file(self) -> Any:
+ """Get Figma file from Figma REST API."""
+ headers = {"X-Figma-Token": self.access_token}
+ request = urllib.request.Request(
+ self._construct_figma_api_url(), headers=headers
+ )
+ with urllib.request.urlopen(request) as response:
+ json_data = json.loads(response.read().decode())
+ return json_data
+
+ def load(self) -> List[Document]:
+ """Load file"""
+ data = self._get_figma_file()
+ text = stringify_dict(data)
+ metadata = {"source": self._construct_figma_api_url()}
+ return [Document(page_content=text, metadata=metadata)]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/firecrawl.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/firecrawl.py
new file mode 100644
index 0000000000000000000000000000000000000000..82fe9efa45ae1ab6958232dc35ec1e0be9712e5f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/firecrawl.py
@@ -0,0 +1,409 @@
+import dataclasses
+import os
+from typing import Any, Iterator, Literal, Optional
+
+from langchain_core.document_loaders import BaseLoader
+from langchain_core.documents import Document
+from langchain_core.utils import get_from_env
+
+
+class FireCrawlLoader(BaseLoader):
+ """
+ FireCrawlLoader document loader integration
+
+ Setup:
+ Install ``firecrawl-py``,``langchain_community`` and set environment variable ``FIRECRAWL_API_KEY``.
+
+ .. code-block:: bash
+
+ pip install -U firecrawl-py langchain_community
+ export FIRECRAWL_API_KEY="your-api-key"
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import FireCrawlLoader
+
+ loader = FireCrawlLoader(
+ url = "https://firecrawl.dev",
+ mode = "crawl"
+ # other params = ...
+ )
+
+ Lazy load:
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ # async variant:
+ # docs_lazy = await loader.alazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Introducing [Smart Crawl!](https://www.firecrawl.dev/smart-crawl)
+ Join the waitlist to turn any web
+ {'ogUrl': 'https://www.firecrawl.dev/', 'title': 'Home - Firecrawl', 'robots': 'follow, index', 'ogImage': 'https://www.firecrawl.dev/og.png?123', 'ogTitle': 'Firecrawl', 'sitemap': {'lastmod': '2024-08-12T00:28:16.681Z', 'changefreq': 'weekly'}, 'keywords': 'Firecrawl,Markdown,Data,Mendable,Langchain', 'sourceURL': 'https://www.firecrawl.dev/', 'ogSiteName': 'Firecrawl', 'description': 'Firecrawl crawls and converts any website into clean markdown.', 'ogDescription': 'Turn any website into LLM-ready data.', 'pageStatusCode': 200, 'ogLocaleAlternate': []}
+
+ Async load:
+ .. code-block:: python
+
+ docs = await loader.aload()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Introducing [Smart Crawl!](https://www.firecrawl.dev/smart-crawl)
+ Join the waitlist to turn any web
+ {'ogUrl': 'https://www.firecrawl.dev/', 'title': 'Home - Firecrawl', 'robots': 'follow, index', 'ogImage': 'https://www.firecrawl.dev/og.png?123', 'ogTitle': 'Firecrawl', 'sitemap': {'lastmod': '2024-08-12T00:28:16.681Z', 'changefreq': 'weekly'}, 'keywords': 'Firecrawl,Markdown,Data,Mendable,Langchain', 'sourceURL': 'https://www.firecrawl.dev/', 'ogSiteName': 'Firecrawl', 'description': 'Firecrawl crawls and converts any website into clean markdown.', 'ogDescription': 'Turn any website into LLM-ready data.', 'pageStatusCode': 200, 'ogLocaleAlternate': []}
+
+ """ # noqa: E501
+
+ # No legacy support in v2-only implementation
+
+ def __init__(
+ self,
+ url: Optional[str] = None,
+ *,
+ query: Optional[str] = None,
+ api_key: Optional[str] = None,
+ api_url: Optional[str] = None,
+ mode: Literal["crawl", "scrape", "map", "extract", "search"] = "crawl",
+ params: Optional[dict] = None,
+ ):
+ """Initialize with API key and url.
+
+ Args:
+ url: The url to be crawled.
+ api_key: The Firecrawl API key. If not specified will be read from env var
+ FIRECRAWL_API_KEY. Get an API key
+ api_url: The Firecrawl API URL. If not specified will be read from env var
+ FIRECRAWL_API_URL or defaults to https://api.firecrawl.dev.
+ mode: The mode to run the loader in. Default is "crawl".
+ Options include "scrape" (single url),
+ "crawl" (all accessible sub pages),
+ "map" (returns list of links that are semantically related).
+ "extract" (extracts structured data from a page).
+ "search" (search for data across the web).
+ params: The parameters to pass to the Firecrawl API.
+ Examples include crawlerOptions.
+ For more details, visit: https://github.com/mendableai/firecrawl-py
+ """
+
+ try:
+ from firecrawl import FirecrawlApp
+ except ImportError:
+ raise ImportError(
+ "`firecrawl` package not found, please run `pip install firecrawl-py`"
+ )
+ if mode not in ("crawl", "scrape", "search", "map", "extract", "search"):
+ raise ValueError(
+ f"""Invalid mode '{mode}'.
+ Allowed: 'crawl', 'scrape', 'search', 'map', 'extract', 'search'."""
+ )
+
+ if mode in ("scrape", "crawl", "map", "extract") and not url:
+ raise ValueError("Url must be provided for modes other than 'search'")
+ if mode == "search" and not (query or (params and params.get("query"))):
+ raise ValueError("Query must be provided for search mode")
+
+ api_key = api_key or get_from_env("api_key", "FIRECRAWL_API_KEY")
+ # Ensure we never pass None for api_url (v2 client validates as str).
+ # Avoid get_from_env to prevent raising.
+ resolved_api_url = (
+ api_url or os.getenv("FIRECRAWL_API_URL") or "https://api.firecrawl.dev"
+ )
+ self.firecrawl = FirecrawlApp(api_key=api_key, api_url=resolved_api_url)
+ self.url = url or ""
+ self.mode = mode
+ self.params = params or {}
+ if query is not None:
+ self.params["query"] = query
+
+ def lazy_load(self) -> Iterator[Document]:
+ # Prepare integration tag and filter params per method
+ firecrawl_docs: list[Any] = []
+ if self.mode == "scrape":
+ allowed = {
+ "formats",
+ "headers",
+ "include_tags",
+ "exclude_tags",
+ "only_main_content",
+ "timeout",
+ "wait_for",
+ "mobile",
+ "parsers",
+ "actions",
+ "location",
+ "skip_tls_verification",
+ "remove_base64_images",
+ "fast_mode",
+ "use_mock",
+ "block_ads",
+ "proxy",
+ "max_age",
+ "store_in_cache",
+ }
+ kwargs = {k: v for k, v in self.params.items() if k in allowed}
+ kwargs["integration"] = "langchain"
+ firecrawl_docs = [self.firecrawl.scrape(self.url, **kwargs)]
+ elif self.mode == "crawl":
+ if not self.url:
+ raise ValueError("URL is required for crawl mode")
+ allowed = {
+ "prompt",
+ "exclude_paths",
+ "include_paths",
+ "max_discovery_depth",
+ "ignore_sitemap",
+ "ignore_query_parameters",
+ "limit",
+ "crawl_entire_domain",
+ "allow_external_links",
+ "allow_subdomains",
+ "delay",
+ "max_concurrency",
+ "webhook",
+ "scrape_options",
+ "zero_data_retention",
+ "poll_interval",
+ "timeout",
+ }
+ kwargs = {k: v for k, v in self.params.items() if k in allowed}
+ kwargs["integration"] = "langchain"
+ crawl_response = self.firecrawl.crawl(self.url, **kwargs)
+ # Support dict or object with 'data'
+ if isinstance(crawl_response, dict):
+ data = crawl_response.get("data", [])
+ firecrawl_docs = list(data) if isinstance(data, list) else []
+ else:
+ data = getattr(crawl_response, "data", [])
+ firecrawl_docs = list(data) if isinstance(data, list) else []
+ elif self.mode == "map":
+ if not self.url:
+ raise ValueError("URL is required for map mode")
+ allowed = {
+ "search",
+ "include_subdomains",
+ "limit",
+ "sitemap",
+ "timeout",
+ "location",
+ }
+ kwargs = {k: v for k, v in self.params.items() if k in allowed}
+ kwargs["integration"] = "langchain"
+ map_response = self.firecrawl.map(self.url, **kwargs)
+ # Firecrawl v2 (>=4.3.6) returns an object with a `links` array
+ # Fallback to legacy list response if needed
+ if isinstance(map_response, dict):
+ links = map_response.get("links")
+ firecrawl_docs = list(links) if isinstance(links, list) else []
+ elif hasattr(map_response, "links"):
+ links = getattr(map_response, "links")
+ firecrawl_docs = list(links) if isinstance(links, list) else []
+ else:
+ is_list = isinstance(map_response, list)
+ firecrawl_docs = list(map_response) if is_list else []
+ elif self.mode == "extract":
+ if not self.url:
+ raise ValueError("URL is required for extract mode")
+ allowed = {
+ "prompt",
+ "schema",
+ "system_prompt",
+ "allow_external_links",
+ "enable_web_search",
+ "show_sources",
+ "scrape_options",
+ "ignore_invalid_urls",
+ "poll_interval",
+ "timeout",
+ "agent",
+ }
+ kwargs = {k: v for k, v in self.params.items() if k in allowed}
+ kwargs["integration"] = "langchain"
+ firecrawl_docs = [str(self.firecrawl.extract([self.url], **kwargs))]
+ elif self.mode == "search":
+ allowed = {
+ "sources",
+ "categories",
+ "limit",
+ "tbs",
+ "location",
+ "ignore_invalid_urls",
+ "timeout",
+ "scrape_options",
+ }
+ kwargs = {k: v for k, v in self.params.items() if k in allowed}
+ kwargs["integration"] = "langchain"
+ search_data = self.firecrawl.search(
+ query=self.params.get("query"), **kwargs
+ )
+ # If SDK already returns a list[dict], use it directly
+ if isinstance(search_data, list):
+ firecrawl_docs = list(search_data)
+ else:
+ # Normalize typed SearchData into list of dicts with markdown + metadata
+ results: list[dict[str, Any]] = []
+ containers = []
+ if isinstance(search_data, dict):
+ containers = [
+ search_data.get("web"),
+ search_data.get("news"),
+ search_data.get("images"),
+ ]
+ else:
+ containers = [
+ getattr(search_data, "web", None),
+ getattr(search_data, "news", None),
+ getattr(search_data, "images", None),
+ ]
+ for kind, items in (
+ ("web", containers[0]),
+ ("news", containers[1]),
+ ("images", containers[2]),
+ ):
+ if not items:
+ continue
+ for item in items:
+ url_val = (
+ getattr(item, "url", None)
+ if not isinstance(item, dict)
+ else item.get("url")
+ )
+ title_val = (
+ getattr(item, "title", None)
+ if not isinstance(item, dict)
+ else item.get("title")
+ )
+ desc_val = (
+ getattr(item, "description", None)
+ if not isinstance(item, dict)
+ else item.get("description")
+ )
+ content_val = desc_val or title_val or url_val or ""
+ metadata_val = {
+ k: v
+ for k, v in {
+ "url": url_val,
+ "title": title_val,
+ "category": getattr(item, "category", None)
+ if not isinstance(item, dict)
+ else item.get("category"),
+ "type": kind,
+ }.items()
+ if v is not None
+ }
+ results.append(
+ {"markdown": content_val, "metadata": metadata_val}
+ )
+ firecrawl_docs = results
+ else:
+ raise ValueError(
+ f"""Invalid mode '{self.mode}'.
+ Allowed: 'crawl', 'scrape', 'map', 'extract', 'search'."""
+ )
+ for doc in firecrawl_docs:
+ if self.mode == "map":
+ # Support both legacy string list and v2 link objects
+ if isinstance(doc, str):
+ page_content: str = doc
+ meta: dict[str, Any] = {}
+ elif isinstance(doc, dict):
+ page_content_value = doc.get("url") or doc.get("href") or ""
+ page_content = (
+ page_content_value
+ if isinstance(page_content_value, str)
+ else str(page_content_value or "")
+ )
+ meta = {
+ k: v
+ for k, v in {
+ "title": doc.get("title"),
+ "description": doc.get("description"),
+ }.items()
+ if v is not None
+ }
+ elif hasattr(doc, "url") or hasattr(doc, "title"):
+ page_content_value = getattr(doc, "url", "") or getattr(
+ doc, "href", ""
+ )
+ page_content = (
+ page_content_value
+ if isinstance(page_content_value, str)
+ else str(page_content_value or "")
+ )
+ meta = {}
+ title = getattr(doc, "title", None)
+ description = getattr(doc, "description", None)
+ if title is not None:
+ meta["title"] = title
+ if description is not None:
+ meta["description"] = description
+ else:
+ page_content = str(doc)
+ meta = {}
+ elif self.mode == "extract":
+ page_content = str(doc)
+ meta = {}
+ elif self.mode == "search":
+ # Already normalized to dicts with markdown/metadata above
+ if isinstance(doc, dict):
+ markdown_value = doc.get("markdown") or ""
+ page_content = (
+ markdown_value
+ if isinstance(markdown_value, str)
+ else str(markdown_value or "")
+ )
+ metadata_obj = doc.get("metadata", {})
+ meta = metadata_obj if isinstance(metadata_obj, dict) else {}
+ else:
+ page_content = str(doc)
+ meta = {}
+ else:
+ if isinstance(doc, dict):
+ content_value = (
+ doc.get("markdown") or doc.get("html") or doc.get("rawHtml", "")
+ )
+ page_content = (
+ content_value
+ if isinstance(content_value, str)
+ else str(content_value or "")
+ )
+ meta = doc.get("metadata", {})
+ else:
+ content_value = (
+ getattr(doc, "markdown", None)
+ or getattr(doc, "html", None)
+ or getattr(doc, "rawHtml", "")
+ )
+ page_content = (
+ content_value
+ if isinstance(content_value, str)
+ else str(content_value or "")
+ )
+ meta = getattr(doc, "metadata", {}) or {}
+
+ # Normalize metadata to plain dict for LangChain Document
+ if not isinstance(meta, dict):
+ if hasattr(meta, "model_dump") and callable(meta.model_dump):
+ meta = meta.model_dump()
+ elif dataclasses.is_dataclass(meta):
+ meta = dataclasses.asdict(meta) # type: ignore[arg-type]
+ elif hasattr(meta, "__dict__"):
+ meta = dict(vars(meta))
+ else:
+ meta = {"value": str(meta)}
+ if not page_content:
+ continue
+ yield Document(
+ page_content=page_content,
+ metadata=meta,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/gcs_directory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/gcs_directory.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc736c3e974e7ff80a8d50aac2145d46ed22c785
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/gcs_directory.py
@@ -0,0 +1,83 @@
+import logging
+from typing import Callable, List, Optional
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.gcs_file import GCSFileLoader
+from langchain_community.utilities.vertexai import get_client_info
+
+logger = logging.getLogger(__name__)
+
+
+@deprecated(
+ since="0.0.32",
+ removal="1.0",
+ alternative_import="langchain_google_community.GCSDirectoryLoader",
+)
+class GCSDirectoryLoader(BaseLoader):
+ """Load from GCS directory."""
+
+ def __init__(
+ self,
+ project_name: str,
+ bucket: str,
+ prefix: str = "",
+ loader_func: Optional[Callable[[str], BaseLoader]] = None,
+ continue_on_failure: bool = False,
+ ):
+ """Initialize with bucket and key name.
+
+ Args:
+ project_name: The ID of the project for the GCS bucket.
+ bucket: The name of the GCS bucket.
+ prefix: The prefix of the GCS bucket.
+ loader_func: A loader function that instantiates a loader based on a
+ file_path argument. If nothing is provided, the GCSFileLoader
+ would use its default loader.
+ continue_on_failure: To use try-except block for each file within the GCS
+ directory. If set to `True`, then failure to process a file will not
+ cause an error.
+ """
+ self.project_name = project_name
+ self.bucket = bucket
+ self.prefix = prefix
+ self._loader_func = loader_func
+ self.continue_on_failure = continue_on_failure
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ try:
+ from google.cloud import storage
+ except ImportError:
+ raise ImportError(
+ "Could not import google-cloud-storage python package. "
+ "Please install it with `pip install google-cloud-storage`."
+ )
+ client = storage.Client(
+ project=self.project_name,
+ client_info=get_client_info(module="google-cloud-storage"),
+ )
+ docs = []
+ for blob in client.list_blobs(self.bucket, prefix=self.prefix):
+ # we shall just skip directories since GCSFileLoader creates
+ # intermediate directories on the fly
+ if blob.name.endswith("/"):
+ continue
+ # Use the try-except block here
+ try:
+ loader = GCSFileLoader(
+ self.project_name,
+ self.bucket,
+ blob.name,
+ loader_func=self._loader_func,
+ )
+ docs.extend(loader.load())
+ except Exception as e:
+ if self.continue_on_failure:
+ logger.warning(f"Problem processing blob {blob.name}, message: {e}")
+ continue
+ else:
+ raise e
+ return docs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/gcs_file.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/gcs_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..52a476a2083fd42646f5e7fffc8d379d361913da
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/gcs_file.py
@@ -0,0 +1,89 @@
+import os
+import tempfile
+from typing import Callable, List, Optional
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
+from langchain_community.utilities.vertexai import get_client_info
+
+
+@deprecated(
+ since="0.0.32",
+ removal="1.0",
+ alternative_import="langchain_google_community.GCSFileLoader",
+)
+class GCSFileLoader(BaseLoader):
+ """Load from GCS file."""
+
+ def __init__(
+ self,
+ project_name: str,
+ bucket: str,
+ blob: str,
+ loader_func: Optional[Callable[[str], BaseLoader]] = None,
+ ):
+ """Initialize with bucket and key name.
+
+ Args:
+ project_name: The name of the project to load
+ bucket: The name of the GCS bucket.
+ blob: The name of the GCS blob to load.
+ loader_func: A loader function that instantiates a loader based on a
+ file_path argument. If nothing is provided, the
+ UnstructuredFileLoader is used.
+
+ Examples:
+ To use an alternative PDF loader:
+ >> from from langchain_community.document_loaders import PyPDFLoader
+ >> loader = GCSFileLoader(..., loader_func=PyPDFLoader)
+
+ To use UnstructuredFileLoader with additional arguments:
+ >> loader = GCSFileLoader(...,
+ >> loader_func=lambda x: UnstructuredFileLoader(x, mode="elements"))
+
+ """
+ self.bucket = bucket
+ self.blob = blob
+ self.project_name = project_name
+
+ def default_loader_func(file_path: str) -> BaseLoader:
+ return UnstructuredFileLoader(file_path)
+
+ self._loader_func = loader_func if loader_func else default_loader_func
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ try:
+ from google.cloud import storage
+ except ImportError:
+ raise ImportError(
+ "Could not import google-cloud-storage python package. "
+ "Please install it with `pip install google-cloud-storage`."
+ )
+
+ # initialize a client
+ storage_client = storage.Client(
+ self.project_name, client_info=get_client_info("google-cloud-storage")
+ )
+ # Create a bucket object for our bucket
+ bucket = storage_client.get_bucket(self.bucket)
+ # Create a blob object from the filepath
+ blob = bucket.blob(self.blob)
+ # retrieve custom metadata associated with the blob
+ metadata = bucket.get_blob(self.blob).metadata
+ with tempfile.TemporaryDirectory() as temp_dir:
+ file_path = f"{temp_dir}/{self.blob}"
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
+ # Download the file to a destination
+ blob.download_to_filename(file_path)
+ loader = self._loader_func(file_path)
+ docs = loader.load()
+ for doc in docs:
+ if "source" in doc.metadata:
+ doc.metadata["source"] = f"gs://{self.bucket}/{self.blob}"
+ if metadata:
+ doc.metadata.update(metadata)
+ return docs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/generic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/generic.py
new file mode 100644
index 0000000000000000000000000000000000000000..191149618b13682059f29f660d64b0f4f302ef01
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/generic.py
@@ -0,0 +1,186 @@
+from __future__ import annotations
+
+from pathlib import Path
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Iterator,
+ List,
+ Literal,
+ Optional,
+ Sequence,
+ Union,
+)
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseBlobParser, BaseLoader
+from langchain_community.document_loaders.blob_loaders import (
+ BlobLoader,
+ FileSystemBlobLoader,
+)
+from langchain_community.document_loaders.parsers.registry import get_parser
+
+if TYPE_CHECKING:
+ from langchain_text_splitters import TextSplitter
+
+_PathLike = Union[str, Path]
+
+DEFAULT = Literal["default"]
+
+
+class GenericLoader(BaseLoader):
+ """Generic Document Loader.
+
+ A generic document loader that allows combining an arbitrary blob loader with
+ a blob parser.
+
+ Examples:
+
+ Parse a specific PDF file:
+
+ .. code-block:: python
+
+ from langchain_community.document_loaders import GenericLoader
+ from langchain_community.document_loaders.parsers.pdf import PyPDFParser
+
+ # Recursively load all text files in a directory.
+ loader = GenericLoader.from_filesystem(
+ "my_lovely_pdf.pdf",
+ parser=PyPDFParser()
+ )
+
+ .. code-block:: python
+
+ from langchain_community.document_loaders import GenericLoader
+ from langchain_community.document_loaders.blob_loaders import FileSystemBlobLoader
+
+
+ loader = GenericLoader.from_filesystem(
+ path="path/to/directory",
+ glob="**/[!.]*",
+ suffixes=[".pdf"],
+ show_progress=True,
+ )
+
+ docs = loader.lazy_load()
+ next(docs)
+
+ Example instantiations to change which files are loaded:
+
+ .. code-block:: python
+
+ # Recursively load all text files in a directory.
+ loader = GenericLoader.from_filesystem("/path/to/dir", glob="**/*.txt")
+
+ # Recursively load all non-hidden files in a directory.
+ loader = GenericLoader.from_filesystem("/path/to/dir", glob="**/[!.]*")
+
+ # Load all files in a directory without recursion.
+ loader = GenericLoader.from_filesystem("/path/to/dir", glob="*")
+
+ Example instantiations to change which parser is used:
+
+ .. code-block:: python
+
+ from langchain_community.document_loaders.parsers.pdf import PyPDFParser
+
+ # Recursively load all text files in a directory.
+ loader = GenericLoader.from_filesystem(
+ "/path/to/dir",
+ glob="**/*.pdf",
+ parser=PyPDFParser()
+ )
+
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ blob_loader: BlobLoader,
+ blob_parser: BaseBlobParser,
+ ) -> None:
+ """A generic document loader.
+
+ Args:
+ blob_loader: A blob loader which knows how to yield blobs
+ blob_parser: A blob parser which knows how to parse blobs into documents
+ """
+ self.blob_loader = blob_loader
+ self.blob_parser = blob_parser
+
+ def lazy_load(
+ self,
+ ) -> Iterator[Document]:
+ """Load documents lazily. Use this when working at a large scale."""
+ for blob in self.blob_loader.yield_blobs():
+ yield from self.blob_parser.lazy_parse(blob)
+
+ def load_and_split(
+ self, text_splitter: Optional[TextSplitter] = None
+ ) -> List[Document]:
+ """Load all documents and split them into sentences."""
+ raise NotImplementedError(
+ "Loading and splitting is not yet implemented for generic loaders. "
+ "When they will be implemented they will be added via the initializer. "
+ "This method should not be used going forward."
+ )
+
+ @classmethod
+ def from_filesystem(
+ cls,
+ path: _PathLike,
+ *,
+ glob: str = "**/[!.]*",
+ exclude: Sequence[str] = (),
+ suffixes: Optional[Sequence[str]] = None,
+ show_progress: bool = False,
+ parser: Union[DEFAULT, BaseBlobParser] = "default",
+ parser_kwargs: Optional[dict] = None,
+ ) -> GenericLoader:
+ """Create a generic document loader using a filesystem blob loader.
+
+ Args:
+ path: The path to the directory to load documents from OR the path to a
+ single file to load. If this is a file, glob, exclude, suffixes
+ will be ignored.
+ glob: The glob pattern to use to find documents.
+ suffixes: The suffixes to use to filter documents. If None, all files
+ matching the glob will be loaded.
+ exclude: A list of patterns to exclude from the loader.
+ show_progress: Whether to show a progress bar or not (requires tqdm).
+ Proxies to the file system loader.
+ parser: A blob parser which knows how to parse blobs into documents,
+ will instantiate a default parser if not provided.
+ The default can be overridden by either passing a parser or
+ setting the class attribute `blob_parser` (the latter
+ should be used with inheritance).
+ parser_kwargs: Keyword arguments to pass to the parser.
+
+ Returns:
+ A generic document loader.
+ """
+ blob_loader = FileSystemBlobLoader(
+ path,
+ glob=glob,
+ exclude=exclude,
+ suffixes=suffixes,
+ show_progress=show_progress,
+ )
+ if isinstance(parser, str):
+ if parser == "default":
+ try:
+ # If there is an implementation of get_parser on the class, use it.
+ blob_parser = cls.get_parser(**(parser_kwargs or {}))
+ except NotImplementedError:
+ # if not then use the global registry.
+ blob_parser = get_parser(parser)
+ else:
+ blob_parser = get_parser(parser)
+ else:
+ blob_parser = parser
+ return cls(blob_loader, blob_parser)
+
+ @staticmethod
+ def get_parser(**kwargs: Any) -> BaseBlobParser:
+ """Override this method to associate a default parser with the class."""
+ raise NotImplementedError()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/geodataframe.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/geodataframe.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f867fef233f0e1dd1ace9f47069158d30537139
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/geodataframe.py
@@ -0,0 +1,69 @@
+from typing import Any, Iterator
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class GeoDataFrameLoader(BaseLoader):
+ """Load `geopandas` Dataframe."""
+
+ def __init__(self, data_frame: Any, page_content_column: str = "geometry"):
+ """Initialize with geopandas Dataframe.
+
+ Args:
+ data_frame: geopandas DataFrame object.
+ page_content_column: Name of the column containing the page content.
+ Defaults to "geometry".
+ """
+
+ try:
+ import geopandas as gpd
+ except ImportError:
+ raise ImportError(
+ "geopandas package not found, please install it with "
+ "`pip install geopandas`"
+ )
+
+ if not isinstance(data_frame, gpd.GeoDataFrame):
+ raise ValueError(
+ f"Expected data_frame to be a gpd.GeoDataFrame, got {type(data_frame)}"
+ )
+
+ if page_content_column not in data_frame.columns:
+ raise ValueError(
+ f"Expected data_frame to have a column named {page_content_column}"
+ )
+
+ if not isinstance(data_frame[page_content_column], gpd.GeoSeries):
+ raise ValueError(
+ f"Expected data_frame[{page_content_column}] to be a GeoSeries"
+ )
+
+ self.data_frame = data_frame
+ self.page_content_column = page_content_column
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load records from dataframe."""
+
+ # assumes all geometries in GeoSeries are same CRS and Geom Type
+ crs_str = self.data_frame.crs.to_string() if self.data_frame.crs else None
+ geometry_type = self.data_frame.geometry.geom_type.iloc[0]
+
+ for _, row in self.data_frame.iterrows():
+ geom = row[self.page_content_column]
+
+ xmin, ymin, xmax, ymax = geom.bounds
+
+ metadata = row.to_dict()
+ metadata["crs"] = crs_str
+ metadata["geometry_type"] = geometry_type
+ metadata["xmin"] = xmin
+ metadata["ymin"] = ymin
+ metadata["xmax"] = xmax
+ metadata["ymax"] = ymax
+
+ metadata.pop(self.page_content_column)
+
+ # using WKT instead of str() to help GIS system interoperability
+ yield Document(page_content=geom.wkt, metadata=metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/git.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/git.py
new file mode 100644
index 0000000000000000000000000000000000000000..b37f575eacbb8fc64e48f75ae14dd6b10da8410e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/git.py
@@ -0,0 +1,105 @@
+import os
+from typing import Callable, Iterator, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class GitLoader(BaseLoader):
+ """Load `Git` repository files.
+
+ The Repository can be local on disk available at `repo_path`,
+ or remote at `clone_url` that will be cloned to `repo_path`.
+ Currently, supports only text files.
+
+ Each document represents one file in the repository. The `path` points to
+ the local Git repository, and the `branch` specifies the branch to load
+ files from. By default, it loads from the `main` branch.
+ """
+
+ def __init__(
+ self,
+ repo_path: str,
+ clone_url: Optional[str] = None,
+ branch: Optional[str] = "main",
+ file_filter: Optional[Callable[[str], bool]] = None,
+ ):
+ """
+
+ Args:
+ repo_path: The path to the Git repository.
+ clone_url: Optional. The URL to clone the repository from.
+ branch: Optional. The branch to load files from. Defaults to `main`.
+ file_filter: Optional. A function that takes a file path and returns
+ a boolean indicating whether to load the file. Defaults to None.
+ """
+ self.repo_path = repo_path
+ self.clone_url = clone_url
+ self.branch = branch
+ self.file_filter = file_filter
+
+ def lazy_load(self) -> Iterator[Document]:
+ try:
+ from git import Blob, Repo
+ except ImportError as ex:
+ raise ImportError(
+ "Could not import git python package. "
+ "Please install it with `pip install GitPython`."
+ ) from ex
+
+ if not os.path.exists(self.repo_path) and self.clone_url is None:
+ raise ValueError(f"Path {self.repo_path} does not exist")
+ elif self.clone_url:
+ # If the repo_path already contains a git repository, verify that it's the
+ # same repository as the one we're trying to clone.
+ if os.path.isdir(os.path.join(self.repo_path, ".git")):
+ repo = Repo(self.repo_path)
+ # If the existing repository is not the same as the one we're trying to
+ # clone, raise an error.
+ if repo.remotes.origin.url != self.clone_url:
+ raise ValueError(
+ "A different repository is already cloned at this path."
+ )
+ else:
+ repo = Repo.clone_from(self.clone_url, self.repo_path)
+ repo.git.checkout(self.branch)
+ else:
+ repo = Repo(self.repo_path)
+ repo.git.checkout(self.branch)
+
+ for item in repo.tree().traverse():
+ if not isinstance(item, Blob):
+ continue
+
+ file_path = os.path.join(self.repo_path, item.path)
+
+ ignored_files = repo.ignored([file_path])
+ if len(ignored_files):
+ continue
+
+ # uses filter to skip files
+ if self.file_filter and not self.file_filter(file_path):
+ continue
+
+ rel_file_path = os.path.relpath(file_path, self.repo_path)
+ try:
+ with open(file_path, "rb") as f:
+ content = f.read()
+ file_type = os.path.splitext(item.name)[1]
+
+ # loads only text files
+ try:
+ text_content = content.decode("utf-8")
+ except UnicodeDecodeError:
+ continue
+
+ metadata = {
+ "source": rel_file_path,
+ "file_path": rel_file_path,
+ "file_name": item.name,
+ "file_type": file_type,
+ }
+ yield Document(page_content=text_content, metadata=metadata)
+ except Exception as e:
+ print(f"Error reading file {file_path}: {e}") # noqa: T201
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/gitbook.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/gitbook.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cb51a886e99f5b4bafd76c36bba09716868a673
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/gitbook.py
@@ -0,0 +1,386 @@
+import warnings
+from typing import Any, AsyncIterator, Iterator, List, Optional, Set, Union
+from urllib.parse import urlparse
+
+from bs4 import BeautifulSoup
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.web_base import WebBaseLoader
+
+
+class GitbookLoader(BaseLoader):
+ """Load `GitBook` data.
+
+ 1. load from either a single page, or
+ 2. load all (relative) paths in the sitemap, handling nested sitemap indexes.
+
+ When `load_all_paths=True`, the loader parses XML sitemaps and requires the
+ `lxml` package to be installed (`pip install lxml`).
+ """
+
+ def __init__(
+ self,
+ web_page: str,
+ load_all_paths: bool = False,
+ base_url: Optional[str] = None,
+ content_selector: str = "main",
+ continue_on_failure: bool = False,
+ show_progress: bool = True,
+ *,
+ sitemap_url: Optional[str] = None,
+ allowed_domains: Optional[Set[str]] = None,
+ ):
+ """Initialize with web page and whether to load all paths.
+
+ Args:
+ web_page: The web page to load or the starting point from where
+ relative paths are discovered.
+ load_all_paths: If set to True, all relative paths in the navbar
+ are loaded instead of only `web_page`. Requires `lxml` package.
+ base_url: If `load_all_paths` is True, the relative paths are
+ appended to this base url. Defaults to `web_page`.
+ content_selector: The CSS selector for the content to load.
+ Defaults to "main".
+ continue_on_failure: whether to continue loading the sitemap if an error
+ occurs loading a url, emitting a warning instead of raising an
+ exception. Setting this to True makes the loader more robust, but also
+ may result in missing data. Default: False
+ show_progress: whether to show a progress bar while loading. Default: True
+ sitemap_url: Custom sitemap URL to use when load_all_paths is True.
+ Defaults to "{base_url}/sitemap.xml".
+ allowed_domains: Optional set of allowed domains to fetch from.
+ If None (default), the loader will restrict crawling to the domain
+ of the `web_page` URL to prevent potential SSRF vulnerabilities.
+ Provide an explicit set (e.g., {"example.com", "docs.example.com"})
+ to allow crawling across multiple domains. Use with caution in
+ server environments where users might control the input URLs.
+ """
+ self.base_url = base_url or web_page
+ if self.base_url.endswith("/"):
+ self.base_url = self.base_url[:-1]
+
+ self.web_page = web_page
+ self.load_all_paths = load_all_paths
+ self.content_selector = content_selector
+ self.continue_on_failure = continue_on_failure
+ self.show_progress = show_progress
+ self.allowed_domains = allowed_domains
+
+ # If allowed_domains is not specified, extract domain from web_page as default
+ if self.allowed_domains is None:
+ initial_domain = urlparse(web_page).netloc
+ if initial_domain:
+ self.allowed_domains = {initial_domain}
+
+ # Determine the starting URL (either a sitemap or a direct page)
+ if load_all_paths:
+ self.start_url = sitemap_url or f"{self.base_url}/sitemap.xml"
+ else:
+ self.start_url = web_page
+
+ # Validate the start_url is allowed
+ if not self._is_url_allowed(self.start_url):
+ raise ValueError(
+ f"Domain in {self.start_url} is not in the allowed domains list: "
+ f"{self.allowed_domains}"
+ )
+
+ def _is_url_allowed(self, url: str) -> bool:
+ """Check if a URL has an allowed scheme and domain."""
+ # It's assumed self.allowed_domains is always set by __init__
+ # either explicitly or derived from web_page. If it's somehow still
+ # None here, it indicates an initialization issue, so denying is safer.
+ if self.allowed_domains is None:
+ return False # Should not happen if init worked
+
+ try:
+ parsed = urlparse(url)
+
+ # 1. Validate scheme (Minimal Enhancement)
+ if parsed.scheme not in ("http", "https"):
+ return False
+
+ # 2. Validate domain (Existing logic - handles suffix correctly)
+ # Ensure netloc is not empty before checking membership
+ if not parsed.netloc:
+ return False
+ return parsed.netloc in self.allowed_domains
+ except Exception: # Catch potential urlparse errors
+ return False
+
+ def _safe_add_url(
+ self, url_list: List[str], url: str, url_type: str = "URL"
+ ) -> bool:
+ """Safely add a URL to a list if it's from an allowed domain.
+
+ Args:
+ url_list: The list to add the URL to
+ url: The URL to add
+ url_type: Type of URL for warning message (e.g., "sitemap", "content")
+
+ Returns:
+ bool: True if URL was added, False if skipped
+ """
+ if self._is_url_allowed(url):
+ url_list.append(url)
+ return True
+ else:
+ warnings.warn(f"Skipping disallowed {url_type} URL: {url}")
+ return False
+
+ def _create_web_loader(self, url_or_urls: Union[str, List[str]]) -> WebBaseLoader:
+ """Create a new WebBaseLoader instance for the given URL(s).
+
+ This ensures each operation gets its own isolated WebBaseLoader.
+ """
+ return WebBaseLoader(
+ web_path=url_or_urls,
+ continue_on_failure=self.continue_on_failure,
+ show_progress=self.show_progress,
+ )
+
+ def _is_sitemap_index(self, soup: BeautifulSoup) -> bool:
+ """Check if the soup contains a sitemap index."""
+ return soup.find("sitemapindex") is not None
+
+ def _extract_sitemap_urls(self, soup: BeautifulSoup) -> List[str]:
+ """Extract sitemap URLs from a sitemap index."""
+ sitemap_tags = soup.find_all("sitemap")
+ urls: List[str] = []
+ for sitemap in sitemap_tags:
+ loc = sitemap.find("loc")
+ if loc and loc.text:
+ self._safe_add_url(urls, loc.text, "sitemap")
+ return urls
+
+ def _process_sitemap(
+ self,
+ soup: BeautifulSoup,
+ processed_urls: Set[str],
+ web_loader: Optional[WebBaseLoader] = None,
+ ) -> List[str]:
+ """Process a sitemap, handling both direct content URLs and sitemap indexes.
+
+ Args:
+ soup: The BeautifulSoup object of the sitemap
+ processed_urls: Set of already processed URLs to avoid cycles
+ web_loader: WebBaseLoader instance to reuse for all requests,
+ created if None
+ """
+ # Create a loader if not provided
+ if web_loader is None:
+ web_loader = self._create_web_loader(self.start_url)
+
+ # If it's a sitemap index, recursively process each sitemap URL
+ if self._is_sitemap_index(soup):
+ sitemap_urls = self._extract_sitemap_urls(soup)
+ all_content_urls = []
+
+ for sitemap_url in sitemap_urls:
+ if sitemap_url in processed_urls:
+ warnings.warn(
+ f"Skipping already processed sitemap URL: {sitemap_url}"
+ )
+ continue
+
+ processed_urls.add(sitemap_url)
+ try:
+ # Temporarily override the web_path of the loader
+ original_web_paths = web_loader.web_paths
+ web_loader.web_paths = [sitemap_url]
+
+ # Reuse the same loader for the next sitemap,
+ # explicitly use lxml-xml
+ sitemap_soup = web_loader.scrape(parser="lxml-xml")
+
+ # Restore original web_paths
+ web_loader.web_paths = original_web_paths
+
+ # Recursive call with the same loader
+ content_urls = self._process_sitemap(
+ sitemap_soup, processed_urls, web_loader
+ )
+ all_content_urls.extend(content_urls)
+ except Exception as e:
+ if self.continue_on_failure:
+ warnings.warn(f"Error processing sitemap {sitemap_url}: {e}")
+ else:
+ raise
+
+ return all_content_urls
+ else:
+ # It's a content sitemap, so extract content URLs
+ return self._get_paths(soup)
+
+ async def _aprocess_sitemap(
+ self,
+ soup: BeautifulSoup,
+ base_url: str,
+ processed_urls: Set[str],
+ web_loader: Optional[WebBaseLoader] = None,
+ ) -> List[str]:
+ """Async version of _process_sitemap.
+
+ Args:
+ soup: The BeautifulSoup object of the sitemap
+ base_url: The base URL for relative paths
+ processed_urls: Set of already processed URLs to avoid cycles
+ web_loader: WebBaseLoader instance to reuse for all requests,
+ created if None
+ """
+ # Create a loader if not provided
+ if web_loader is None:
+ web_loader = self._create_web_loader(self.start_url)
+
+ # If it's a sitemap index, recursively process each sitemap URL
+ if self._is_sitemap_index(soup):
+ sitemap_urls = self._extract_sitemap_urls(soup)
+ all_content_urls = []
+
+ # Filter out already processed URLs
+ new_urls = [url for url in sitemap_urls if url not in processed_urls]
+
+ if not new_urls:
+ return []
+
+ # Update the web_paths of the loader to fetch all sitemaps at once
+ original_web_paths = web_loader.web_paths
+ web_loader.web_paths = new_urls
+
+ # Use the same WebBaseLoader's ascrape_all for efficient parallel
+ # fetching, explicitly use lxml-xml
+ soups = await web_loader.ascrape_all(new_urls, parser="lxml-xml")
+
+ # Restore original web_paths
+ web_loader.web_paths = original_web_paths
+
+ for sitemap_url, sitemap_soup in zip(new_urls, soups):
+ processed_urls.add(sitemap_url)
+ try:
+ # Recursive call with the same loader
+ content_urls = await self._aprocess_sitemap(
+ sitemap_soup, base_url, processed_urls, web_loader
+ )
+ all_content_urls.extend(content_urls)
+ except Exception as e:
+ if self.continue_on_failure:
+ warnings.warn(f"Error processing sitemap {sitemap_url}: {e}")
+ else:
+ raise
+
+ return all_content_urls
+ else:
+ # It's a content sitemap, so extract content URLs
+ return self._get_paths(soup)
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Fetch text from one single GitBook page or recursively from sitemap."""
+ if not self.load_all_paths:
+ # Simple case: load a single page
+ temp_loader = self._create_web_loader(self.web_page)
+ soup = temp_loader.scrape()
+ doc = self._get_document(soup, self.web_page)
+ if doc:
+ yield doc
+ else:
+ # Get initial sitemap using the recursive method
+ temp_loader = self._create_web_loader(self.start_url)
+ # Explicitly use lxml-xml for parsing the initial sitemap
+ soup_info = temp_loader.scrape(parser="lxml-xml")
+
+ # Process sitemap(s) recursively to get all content URLs
+ processed_urls: Set[str] = set()
+ relative_paths = self._process_sitemap(soup_info, processed_urls)
+
+ if not relative_paths and self.show_progress:
+ warnings.warn(f"No content URLs found in sitemap at {self.start_url}")
+
+ # Build full URLs from relative paths
+ urls: List[str] = []
+ for url in relative_paths:
+ # URLs are now already absolute from _get_paths
+ self._safe_add_url(urls, url, "content")
+
+ if not urls:
+ return
+
+ # Create a loader for content pages
+ content_loader = self._create_web_loader(urls)
+
+ # Use WebBaseLoader to fetch all pages
+ soup_infos = content_loader.scrape_all(urls)
+
+ for soup_info, url in zip(soup_infos, urls):
+ doc = self._get_document(soup_info, url)
+ if doc:
+ yield doc
+
+ async def alazy_load(self) -> AsyncIterator[Document]:
+ """Asynchronously fetch text from GitBook page(s)."""
+ if not self.load_all_paths:
+ # Simple case: load a single page asynchronously
+ temp_loader = self._create_web_loader(self.web_page)
+ soups = await temp_loader.ascrape_all([self.web_page])
+ soup_info = soups[0]
+ doc = self._get_document(soup_info, self.web_page)
+ if doc:
+ yield doc
+ else:
+ # Get initial sitemap - web_loader will be created in _aprocess_sitemap
+ temp_loader = self._create_web_loader(self.start_url)
+ # Explicitly use lxml-xml for parsing the initial sitemap
+ soups = await temp_loader.ascrape_all([self.start_url], parser="lxml-xml")
+ soup_info = soups[0]
+
+ # Process sitemap(s) recursively to get all content URLs
+ processed_urls: Set[str] = set()
+ relative_paths = await self._aprocess_sitemap(
+ soup_info, self.base_url, processed_urls
+ )
+
+ if not relative_paths and self.show_progress:
+ warnings.warn(f"No content URLs found in sitemap at {self.start_url}")
+
+ # Build full URLs from relative paths
+ urls: List[str] = []
+ for url in relative_paths:
+ # URLs are now already absolute from _get_paths
+ self._safe_add_url(urls, url, "content")
+
+ if not urls:
+ return
+
+ # Create a loader for content pages
+ content_loader = self._create_web_loader(urls)
+
+ # Use WebBaseLoader's ascrape_all for efficient parallel fetching
+ soup_infos = await content_loader.ascrape_all(urls)
+
+ for soup_info, url in zip(soup_infos, urls):
+ maybe_doc = self._get_document(soup_info, url)
+ if maybe_doc is not None:
+ yield maybe_doc
+
+ def _get_document(
+ self, soup: Any, custom_url: Optional[str] = None
+ ) -> Optional[Document]:
+ """Fetch content from page and return Document."""
+ page_content_raw = soup.find(self.content_selector)
+ if not page_content_raw:
+ return None
+ content = page_content_raw.get_text(separator="\n").strip()
+ title_if_exists = page_content_raw.find("h1")
+ title = title_if_exists.text if title_if_exists else ""
+ metadata = {"source": custom_url or self.web_page, "title": title}
+ return Document(page_content=content, metadata=metadata)
+
+ def _get_paths(self, soup: Any) -> List[str]:
+ """Fetch all URLs in the sitemap."""
+ urls = []
+ for loc in soup.find_all("loc"):
+ if loc.text:
+ # Instead of extracting just the path, keep the full URL
+ # to preserve domain information
+ urls.append(loc.text)
+ return urls
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/github.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/github.py
new file mode 100644
index 0000000000000000000000000000000000000000..94cbe0553d0bfdd305830157b3b80da3681be5ff
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/github.py
@@ -0,0 +1,237 @@
+import base64
+from abc import ABC
+from datetime import datetime
+from typing import Any, Callable, Dict, Iterator, List, Literal, Optional, Union
+
+import requests
+from langchain_core.documents import Document
+from langchain_core.utils import get_from_dict_or_env
+from pydantic import BaseModel, field_validator, model_validator
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class BaseGitHubLoader(BaseLoader, BaseModel, ABC):
+ """Load `GitHub` repository Issues."""
+
+ repo: str
+ """Name of repository"""
+ access_token: str
+ """Personal access token - see https://github.com/settings/tokens?type=beta"""
+ github_api_url: str = "https://api.github.com"
+ """URL of GitHub API"""
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_environment(cls, values: Dict) -> Any:
+ """Validate that access token exists in environment."""
+ values["access_token"] = get_from_dict_or_env(
+ values, "access_token", "GITHUB_PERSONAL_ACCESS_TOKEN"
+ )
+ return values
+
+ @property
+ def headers(self) -> Dict[str, str]:
+ return {
+ "Accept": "application/vnd.github+json",
+ "Authorization": f"Bearer {self.access_token}",
+ }
+
+
+class GitHubIssuesLoader(BaseGitHubLoader):
+ """Load issues of a GitHub repository."""
+
+ include_prs: bool = True
+ """If True include Pull Requests in results, otherwise ignore them."""
+ milestone: Union[int, Literal["*", "none"], None] = None
+ """If integer is passed, it should be a milestone's number field.
+ If the string '*' is passed, issues with any milestone are accepted.
+ If the string 'none' is passed, issues without milestones are returned.
+ """
+ state: Optional[Literal["open", "closed", "all"]] = None
+ """Filter on issue state. Can be one of: 'open', 'closed', 'all'."""
+ assignee: Optional[str] = None
+ """Filter on assigned user. Pass 'none' for no user and '*' for any user."""
+ creator: Optional[str] = None
+ """Filter on the user that created the issue."""
+ mentioned: Optional[str] = None
+ """Filter on a user that's mentioned in the issue."""
+ labels: Optional[List[str]] = None
+ """Label names to filter one. Example: bug,ui,@high."""
+ sort: Optional[Literal["created", "updated", "comments"]] = None
+ """What to sort results by. Can be one of: 'created', 'updated', 'comments'.
+ Default is 'created'."""
+ direction: Optional[Literal["asc", "desc"]] = None
+ """The direction to sort the results by. Can be one of: 'asc', 'desc'."""
+ since: Optional[str] = None
+ """Only show notifications updated after the given time.
+ This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ."""
+ page: Optional[int] = None
+ """The page number for paginated results.
+ Defaults to 1 in the GitHub API."""
+ per_page: Optional[int] = None
+ """Number of items per page.
+ Defaults to 30 in the GitHub API."""
+
+ @field_validator("since")
+ @classmethod
+ def validate_since(cls, v: Optional[str]) -> Optional[str]:
+ if v:
+ try:
+ datetime.strptime(v, "%Y-%m-%dT%H:%M:%SZ")
+ except ValueError:
+ raise ValueError(
+ "Invalid value for 'since'. Expected a date string in "
+ f"YYYY-MM-DDTHH:MM:SSZ format. Received: {v}"
+ )
+ return v
+
+ def lazy_load(self) -> Iterator[Document]:
+ """
+ Get issues of a GitHub repository.
+
+ Returns:
+ A list of Documents with attributes:
+ - page_content
+ - metadata
+ - url
+ - title
+ - creator
+ - created_at
+ - last_update_time
+ - closed_time
+ - number of comments
+ - state
+ - labels
+ - assignee
+ - assignees
+ - milestone
+ - locked
+ - number
+ - is_pull_request
+ """
+ url: Optional[str] = self.url
+ while url:
+ response = requests.get(url, headers=self.headers)
+ response.raise_for_status()
+ issues = response.json()
+ for issue in issues:
+ doc = self.parse_issue(issue)
+ if not self.include_prs and doc.metadata["is_pull_request"]:
+ continue
+ yield doc
+ if (
+ response.links
+ and response.links.get("next")
+ and (not self.page and not self.per_page)
+ ):
+ url = response.links["next"]["url"]
+ else:
+ url = None
+
+ def parse_issue(self, issue: dict) -> Document:
+ """Create Document objects from a list of GitHub issues."""
+ metadata = {
+ "url": issue["html_url"],
+ "title": issue["title"],
+ "creator": issue["user"]["login"],
+ "created_at": issue["created_at"],
+ "comments": issue["comments"],
+ "state": issue["state"],
+ "labels": [label["name"] for label in issue["labels"]],
+ "assignee": issue["assignee"]["login"] if issue["assignee"] else None,
+ "milestone": issue["milestone"]["title"] if issue["milestone"] else None,
+ "locked": issue["locked"],
+ "number": issue["number"],
+ "is_pull_request": "pull_request" in issue,
+ }
+ content = issue["body"] if issue["body"] is not None else ""
+ return Document(page_content=content, metadata=metadata)
+
+ @property
+ def query_params(self) -> str:
+ """Create query parameters for GitHub API."""
+ labels = ",".join(self.labels) if self.labels else self.labels
+ query_params_dict = {
+ "milestone": self.milestone,
+ "state": self.state,
+ "assignee": self.assignee,
+ "creator": self.creator,
+ "mentioned": self.mentioned,
+ "labels": labels,
+ "sort": self.sort,
+ "direction": self.direction,
+ "since": self.since,
+ "page": self.page,
+ "per_page": self.per_page,
+ }
+ query_params_list = [
+ f"{k}={v}" for k, v in query_params_dict.items() if v is not None
+ ]
+ query_params = "&".join(query_params_list)
+ return query_params
+
+ @property
+ def url(self) -> str:
+ """Create URL for GitHub API."""
+ return f"{self.github_api_url}/repos/{self.repo}/issues?{self.query_params}"
+
+
+class GithubFileLoader(BaseGitHubLoader, ABC):
+ """Load GitHub File"""
+
+ branch: str = "main"
+
+ file_filter: Optional[Callable[[str], bool]]
+
+ def get_file_paths(self) -> List[Dict]:
+ base_url = (
+ f"{self.github_api_url}/repos/{self.repo}/git/trees/"
+ f"{self.branch}?recursive=1"
+ )
+ response = requests.get(base_url, headers=self.headers)
+ response.raise_for_status()
+ all_files = response.json()["tree"]
+ """ one element in all_files
+ {
+ 'path': '.github',
+ 'mode': '040000',
+ 'type': 'tree',
+ 'sha': '5dc46e6b38b22707894ced126270b15e2f22f64e',
+ 'url': 'https://api.github.com/repos/langchain-ai/langchain/git/blobs/5dc46e6b38b22707894ced126270b15e2f22f64e'
+ }
+ """
+ return [
+ f
+ for f in all_files
+ if not (self.file_filter and not self.file_filter(f["path"]))
+ ]
+
+ def get_file_content_by_path(self, path: str) -> str:
+ queryparams = f"?ref={self.branch}" if self.branch else ""
+ base_url = (
+ f"{self.github_api_url}/repos/{self.repo}/contents/{path}{queryparams}"
+ )
+ response = requests.get(base_url, headers=self.headers)
+ response.raise_for_status()
+
+ if isinstance(response.json(), dict):
+ content_encoded = response.json()["content"]
+ return base64.b64decode(content_encoded).decode("utf-8")
+
+ return ""
+
+ def lazy_load(self) -> Iterator[Document]:
+ files = self.get_file_paths()
+ for file in files:
+ content = self.get_file_content_by_path(file["path"])
+ if content == "":
+ continue
+
+ metadata = {
+ "path": file["path"],
+ "sha": file["sha"],
+ "source": f"{self.github_api_url}/{self.repo}/{file['type']}/"
+ f"{self.branch}/{file['path']}",
+ }
+ yield Document(page_content=content, metadata=metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/glue_catalog.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/glue_catalog.py
new file mode 100644
index 0000000000000000000000000000000000000000..657dbe60ce6aa521978fb2432ad542a89d8d49be
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/glue_catalog.py
@@ -0,0 +1,126 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+if TYPE_CHECKING:
+ from boto3.session import Session
+
+
+class GlueCatalogLoader(BaseLoader):
+ """Load table schemas from AWS Glue.
+
+ This loader fetches the schema of each table within a specified AWS Glue database.
+ The schema details include column names and their data types, similar to pandas
+ dtype representation.
+
+ AWS credentials are automatically loaded using boto3, following the standard AWS
+ method:
+ https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
+
+ If a specific AWS profile is required, it can be specified and will be used to
+ establish the session.
+ """
+
+ def __init__(
+ self,
+ database: str,
+ *,
+ session: Optional[Session] = None,
+ profile_name: Optional[str] = None,
+ table_filter: Optional[List[str]] = None,
+ ):
+ """Initialize Glue database loader.
+
+ Args:
+ database: The name of the Glue database from which to load table schemas.
+ session: Optional. A boto3 Session object. If not provided, a new
+ session will be created.
+ profile_name: Optional. The name of the AWS profile to use for credentials.
+ table_filter: Optional. List of table names to fetch schemas for,
+ fetching all if None.
+ """
+ self.database = database
+ self.profile_name = profile_name
+ self.table_filter = table_filter
+ if session:
+ self.glue_client = session.client("glue")
+ else:
+ self.glue_client = self._initialize_glue_client()
+
+ def _initialize_glue_client(self) -> Any:
+ """Initialize the AWS Glue client.
+
+ Returns:
+ The initialized AWS Glue client.
+
+ Raises:
+ ValueError: If there is an issue with AWS session/client initialization.
+ """
+ try:
+ import boto3
+ except ImportError as e:
+ raise ImportError(
+ "boto3 is required to use the GlueCatalogLoader. "
+ "Please install it with `pip install boto3`."
+ ) from e
+
+ try:
+ session = (
+ boto3.Session(profile_name=self.profile_name)
+ if self.profile_name
+ else boto3.Session()
+ )
+ return session.client("glue")
+ except Exception as e:
+ raise ValueError("Issue with AWS session/client initialization.") from e
+
+ def _fetch_tables(self) -> List[str]:
+ """Retrieve all table names in the specified Glue database.
+
+ Returns:
+ A list of table names.
+ """
+ paginator = self.glue_client.get_paginator("get_tables")
+ table_names = []
+ for page in paginator.paginate(DatabaseName=self.database):
+ for table in page["TableList"]:
+ if self.table_filter is None or table["Name"] in self.table_filter:
+ table_names.append(table["Name"])
+ return table_names
+
+ def _fetch_table_schema(self, table_name: str) -> Dict[str, str]:
+ """Fetch the schema of a specified table.
+
+ Args:
+ table_name: The name of the table for which to fetch the schema.
+
+ Returns:
+ A dictionary mapping column names to their data types.
+ """
+ response = self.glue_client.get_table(
+ DatabaseName=self.database, Name=table_name
+ )
+ columns = response["Table"]["StorageDescriptor"]["Columns"]
+ return {col["Name"]: col["Type"] for col in columns}
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazily load table schemas as Document objects.
+
+ Yields:
+ Document objects, each representing the schema of a table.
+ """
+ table_names = self._fetch_tables()
+ for table_name in table_names:
+ schema = self._fetch_table_schema(table_name)
+ page_content = (
+ f"Database: {self.database}\nTable: {table_name}\nSchema:\n"
+ + "\n".join(f"{col}: {dtype}" for col, dtype in schema.items())
+ )
+ doc = Document(
+ page_content=page_content, metadata={"table_name": table_name}
+ )
+ yield doc
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/google_speech_to_text.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/google_speech_to_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ed087b8497d8f855165d07de2ad88284bbdbc73
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/google_speech_to_text.py
@@ -0,0 +1,143 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, List, Optional
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.vertexai import get_client_info
+
+if TYPE_CHECKING:
+ from google.cloud.speech_v2 import RecognitionConfig
+ from google.protobuf.field_mask_pb2 import FieldMask
+
+
+@deprecated(
+ since="0.0.32",
+ removal="1.0",
+ alternative_import="langchain_google_community.SpeechToTextLoader",
+)
+class GoogleSpeechToTextLoader(BaseLoader):
+ """
+ Loader for Google Cloud Speech-to-Text audio transcripts.
+
+ It uses the Google Cloud Speech-to-Text API to transcribe audio files
+ and loads the transcribed text into one or more Documents,
+ depending on the specified format.
+
+ To use, you should have the ``google-cloud-speech`` python package installed.
+
+ Audio files can be specified via a Google Cloud Storage uri or a local file path.
+
+ For a detailed explanation of Google Cloud Speech-to-Text, refer to the product
+ documentation.
+ https://cloud.google.com/speech-to-text
+ """
+
+ def __init__(
+ self,
+ project_id: str,
+ file_path: str,
+ location: str = "us-central1",
+ recognizer_id: str = "_",
+ config: Optional[RecognitionConfig] = None,
+ config_mask: Optional[FieldMask] = None,
+ ):
+ """
+ Initializes the GoogleSpeechToTextLoader.
+
+ Args:
+ project_id: Google Cloud Project ID.
+ file_path: A Google Cloud Storage URI or a local file path.
+ location: Speech-to-Text recognizer location.
+ recognizer_id: Speech-to-Text recognizer id.
+ config: Recognition options and features.
+ For more information:
+ https://cloud.google.com/python/docs/reference/speech/latest/google.cloud.speech_v2.types.RecognitionConfig
+ config_mask: The list of fields in config that override the values in the
+ ``default_recognition_config`` of the recognizer during this
+ recognition request.
+ For more information:
+ https://cloud.google.com/python/docs/reference/speech/latest/google.cloud.speech_v2.types.RecognizeRequest
+ """
+ try:
+ from google.api_core.client_options import ClientOptions
+ from google.cloud.speech_v2 import (
+ AutoDetectDecodingConfig,
+ RecognitionConfig,
+ RecognitionFeatures,
+ SpeechClient,
+ )
+ except ImportError as exc:
+ raise ImportError(
+ "Could not import google-cloud-speech python package. "
+ "Please install it with `pip install google-cloud-speech`."
+ ) from exc
+
+ self.project_id = project_id
+ self.file_path = file_path
+ self.location = location
+ self.recognizer_id = recognizer_id
+ # Config must be set in speech recognition request.
+ self.config = config or RecognitionConfig(
+ auto_decoding_config=AutoDetectDecodingConfig(),
+ language_codes=["en-US"],
+ model="chirp",
+ features=RecognitionFeatures(
+ # Automatic punctuation could be useful for language applications
+ enable_automatic_punctuation=True,
+ ),
+ )
+ self.config_mask = config_mask
+
+ self._client = SpeechClient(
+ client_info=get_client_info(module="speech-to-text"),
+ client_options=(
+ ClientOptions(api_endpoint=f"{location}-speech.googleapis.com")
+ if location != "global"
+ else None
+ ),
+ )
+ self._recognizer_path = self._client.recognizer_path(
+ project_id, location, recognizer_id
+ )
+
+ def load(self) -> List[Document]:
+ """Transcribes the audio file and loads the transcript into documents.
+
+ It uses the Google Cloud Speech-to-Text API to transcribe the audio file
+ and blocks until the transcription is finished.
+ """
+ try:
+ from google.cloud.speech_v2 import RecognizeRequest
+ except ImportError as exc:
+ raise ImportError(
+ "Could not import google-cloud-speech python package. "
+ "Please install it with `pip install google-cloud-speech`."
+ ) from exc
+
+ request = RecognizeRequest(
+ recognizer=self._recognizer_path,
+ config=self.config,
+ config_mask=self.config_mask,
+ )
+
+ if "gs://" in self.file_path:
+ request.uri = self.file_path
+ else:
+ with open(self.file_path, "rb") as f:
+ request.content = f.read()
+
+ response = self._client.recognize(request=request)
+
+ return [
+ Document(
+ page_content=result.alternatives[0].transcript,
+ metadata={
+ "language_code": result.language_code,
+ "result_end_offset": result.result_end_offset,
+ },
+ )
+ for result in response.results
+ ]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/googledrive.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/googledrive.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6b866288501cf8adc9be1925b1d54f0f8653604
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/googledrive.py
@@ -0,0 +1,373 @@
+# Prerequisites:
+# 1. Create a Google Cloud project
+# 2. Enable the Google Drive API:
+# https://console.cloud.google.com/flows/enableapi?apiid=drive.googleapis.com
+# 3. Authorize credentials for desktop app:
+# https://developers.google.com/drive/api/quickstart/python#authorize_credentials_for_a_desktop_application # noqa: E501
+# 4. For service accounts visit
+# https://cloud.google.com/iam/docs/service-accounts-create
+
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Sequence, Union
+
+from langchain_core._api.deprecation import deprecated
+from langchain_core.documents import Document
+from pydantic import BaseModel, model_validator, validator
+
+from langchain_community.document_loaders.base import BaseLoader
+
+SCOPES = ["https://www.googleapis.com/auth/drive.readonly"]
+
+
+@deprecated(
+ since="0.0.32",
+ removal="1.0",
+ alternative_import="langchain_google_community.GoogleDriveLoader",
+)
+class GoogleDriveLoader(BaseLoader, BaseModel):
+ """Load Google Docs from `Google Drive`."""
+
+ service_account_key: Path = Path.home() / ".credentials" / "keys.json"
+ """Path to the service account key file."""
+ credentials_path: Path = Path.home() / ".credentials" / "credentials.json"
+ """Path to the credentials file."""
+ token_path: Path = Path.home() / ".credentials" / "token.json"
+ """Path to the token file."""
+ folder_id: Optional[str] = None
+ """The folder id to load from."""
+ document_ids: Optional[List[str]] = None
+ """The document ids to load from."""
+ file_ids: Optional[List[str]] = None
+ """The file ids to load from."""
+ recursive: bool = False
+ """Whether to load recursively. Only applies when folder_id is given."""
+ file_types: Optional[Sequence[str]] = None
+ """The file types to load. Only applies when folder_id is given."""
+ load_trashed_files: bool = False
+ """Whether to load trashed files. Only applies when folder_id is given."""
+ # NOTE(MthwRobinson) - changing the file_loader_cls to type here currently
+ # results in pydantic validation errors
+ file_loader_cls: Any = None
+ """The file loader class to use."""
+ file_loader_kwargs: Dict["str", Any] = {}
+ """The file loader kwargs to use."""
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_inputs(cls, values: Dict[str, Any]) -> Any:
+ """Validate that either folder_id or document_ids is set, but not both."""
+ if values.get("folder_id") and (
+ values.get("document_ids") or values.get("file_ids")
+ ):
+ raise ValueError(
+ "Cannot specify both folder_id and document_ids nor "
+ "folder_id and file_ids"
+ )
+ if (
+ not values.get("folder_id")
+ and not values.get("document_ids")
+ and not values.get("file_ids")
+ ):
+ raise ValueError("Must specify either folder_id, document_ids, or file_ids")
+
+ file_types = values.get("file_types")
+ if file_types:
+ if values.get("document_ids") or values.get("file_ids"):
+ raise ValueError(
+ "file_types can only be given when folder_id is given,"
+ " (not when document_ids or file_ids are given)."
+ )
+ type_mapping = {
+ "document": "application/vnd.google-apps.document",
+ "sheet": "application/vnd.google-apps.spreadsheet",
+ "pdf": "application/pdf",
+ }
+ allowed_types = list(type_mapping.keys()) + list(type_mapping.values())
+ short_names = ", ".join([f"'{x}'" for x in type_mapping.keys()])
+ full_names = ", ".join([f"'{x}'" for x in type_mapping.values()])
+ for file_type in file_types:
+ if file_type not in allowed_types:
+ raise ValueError(
+ f"Given file type {file_type} is not supported. "
+ f"Supported values are: {short_names}; and "
+ f"their full-form names: {full_names}"
+ )
+
+ # replace short-form file types by full-form file types
+ def full_form(x: str) -> str:
+ return type_mapping[x] if x in type_mapping else x
+
+ values["file_types"] = [full_form(file_type) for file_type in file_types]
+ return values
+
+ @validator("credentials_path")
+ def validate_credentials_path(cls, v: Any, **kwargs: Any) -> Any:
+ """Validate that credentials_path exists."""
+ if not v.exists():
+ raise ValueError(f"credentials_path {v} does not exist")
+ return v
+
+ def _load_credentials(self) -> Any:
+ """Load credentials.
+ The order of loading credentials:
+ 1. Service account key if file exists
+ 2. Token path (for OAuth Client) if file exists
+ 3. Credentials path (for OAuth Client) if file exists
+ 4. Default credentials. if no credentials found, raise DefaultCredentialsError
+ """
+ # Adapted from https://developers.google.com/drive/api/v3/quickstart/python
+ try:
+ from google.auth import default
+ from google.auth.transport.requests import Request
+ from google.oauth2 import service_account
+ from google.oauth2.credentials import Credentials
+ from google_auth_oauthlib.flow import InstalledAppFlow
+ except ImportError:
+ raise ImportError(
+ "You must run "
+ "`pip install --upgrade "
+ "google-api-python-client google-auth-httplib2 "
+ "google-auth-oauthlib` "
+ "to use the Google Drive loader."
+ )
+
+ creds = None
+ # From service account
+ if self.service_account_key.exists():
+ return service_account.Credentials.from_service_account_file(
+ str(self.service_account_key), scopes=SCOPES
+ )
+
+ # From Oauth Client
+ if self.token_path.exists():
+ creds = Credentials.from_authorized_user_file(str(self.token_path), SCOPES)
+
+ if not creds or not creds.valid:
+ if creds and creds.expired and creds.refresh_token:
+ creds.refresh(Request())
+ elif self.credentials_path.exists():
+ flow = InstalledAppFlow.from_client_secrets_file(
+ str(self.credentials_path), SCOPES
+ )
+ creds = flow.run_local_server(port=0)
+ if creds:
+ with open(self.token_path, "w") as token:
+ token.write(creds.to_json())
+
+ # From Application Default Credentials
+ if not creds:
+ creds, _ = default(scopes=SCOPES)
+
+ return creds
+
+ def _load_sheet_from_id(self, id: str) -> List[Document]:
+ """Load a sheet and all tabs from an ID."""
+
+ from googleapiclient.discovery import build
+
+ creds = self._load_credentials()
+ sheets_service = build("sheets", "v4", credentials=creds)
+ spreadsheet = sheets_service.spreadsheets().get(spreadsheetId=id).execute()
+ sheets = spreadsheet.get("sheets", [])
+
+ documents = []
+ for sheet in sheets:
+ sheet_name = sheet["properties"]["title"]
+ result = (
+ sheets_service.spreadsheets()
+ .values()
+ .get(spreadsheetId=id, range=sheet_name)
+ .execute()
+ )
+ values = result.get("values", [])
+ if not values:
+ continue # empty sheet
+
+ header = values[0]
+ for i, row in enumerate(values[1:], start=1):
+ metadata = {
+ "source": (
+ f"https://docs.google.com/spreadsheets/d/{id}/"
+ f"edit?gid={sheet['properties']['sheetId']}"
+ ),
+ "title": f"{spreadsheet['properties']['title']} - {sheet_name}",
+ "row": i,
+ }
+ content = []
+ for j, v in enumerate(row):
+ title = header[j].strip() if len(header) > j else ""
+ content.append(f"{title}: {v.strip()}")
+
+ page_content = "\n".join(content)
+ documents.append(Document(page_content=page_content, metadata=metadata))
+
+ return documents
+
+ def _load_document_from_id(self, id: str) -> Document:
+ """Load a document from an ID."""
+ from io import BytesIO
+
+ from googleapiclient.discovery import build
+ from googleapiclient.errors import HttpError
+ from googleapiclient.http import MediaIoBaseDownload
+
+ creds = self._load_credentials()
+ service = build("drive", "v3", credentials=creds)
+
+ file = (
+ service.files()
+ .get(fileId=id, supportsAllDrives=True, fields="modifiedTime,name")
+ .execute()
+ )
+ request = service.files().export_media(fileId=id, mimeType="text/plain")
+ fh = BytesIO()
+ downloader = MediaIoBaseDownload(fh, request)
+ done = False
+ try:
+ while done is False:
+ status, done = downloader.next_chunk()
+
+ except HttpError as e:
+ if e.resp.status == 404:
+ print("File not found: {}".format(id)) # noqa: T201
+ else:
+ print("An error occurred: {}".format(e)) # noqa: T201
+
+ text = fh.getvalue().decode("utf-8")
+ metadata = {
+ "source": f"https://docs.google.com/document/d/{id}/edit",
+ "title": f"{file.get('name')}",
+ "when": f"{file.get('modifiedTime')}",
+ }
+ return Document(page_content=text, metadata=metadata)
+
+ def _load_documents_from_folder(
+ self, folder_id: str, *, file_types: Optional[Sequence[str]] = None
+ ) -> List[Document]:
+ """Load documents from a folder."""
+ from googleapiclient.discovery import build
+
+ creds = self._load_credentials()
+ service = build("drive", "v3", credentials=creds)
+ files = self._fetch_files_recursive(service, folder_id)
+ # If file types filter is provided, we'll filter by the file type.
+ if file_types:
+ _files = [f for f in files if f["mimeType"] in file_types]
+ else:
+ _files = files
+
+ returns = []
+ for file in _files:
+ if file["trashed"] and not self.load_trashed_files:
+ continue
+ elif file["mimeType"] == "application/vnd.google-apps.document":
+ returns.append(self._load_document_from_id(file["id"])) # type: ignore[arg-type]
+ elif file["mimeType"] == "application/vnd.google-apps.spreadsheet":
+ returns.extend(self._load_sheet_from_id(file["id"])) # type: ignore[arg-type]
+ elif (
+ file["mimeType"] == "application/pdf"
+ or self.file_loader_cls is not None
+ ):
+ returns.extend(self._load_file_from_id(file["id"])) # type: ignore[arg-type]
+ else:
+ pass
+ return returns
+
+ def _fetch_files_recursive(
+ self, service: Any, folder_id: str
+ ) -> List[Dict[str, Union[str, List[str]]]]:
+ """Fetch all files and subfolders recursively."""
+ results = (
+ service.files()
+ .list(
+ q=f"'{folder_id}' in parents",
+ pageSize=1000,
+ includeItemsFromAllDrives=True,
+ supportsAllDrives=True,
+ fields="nextPageToken, files(id, name, mimeType, parents, trashed)",
+ )
+ .execute()
+ )
+ files = results.get("files", [])
+ returns = []
+ for file in files:
+ if file["mimeType"] == "application/vnd.google-apps.folder":
+ if self.recursive:
+ returns.extend(self._fetch_files_recursive(service, file["id"]))
+ else:
+ returns.append(file)
+
+ return returns
+
+ def _load_documents_from_ids(self) -> List[Document]:
+ """Load documents from a list of IDs."""
+ if not self.document_ids:
+ raise ValueError("document_ids must be set")
+
+ return [self._load_document_from_id(doc_id) for doc_id in self.document_ids]
+
+ def _load_file_from_id(self, id: str) -> List[Document]:
+ """Load a file from an ID."""
+ from io import BytesIO
+
+ from googleapiclient.discovery import build
+ from googleapiclient.http import MediaIoBaseDownload
+
+ creds = self._load_credentials()
+ service = build("drive", "v3", credentials=creds)
+
+ file = service.files().get(fileId=id, supportsAllDrives=True).execute()
+ request = service.files().get_media(fileId=id)
+ fh = BytesIO()
+ downloader = MediaIoBaseDownload(fh, request)
+ done = False
+ while done is False:
+ status, done = downloader.next_chunk()
+
+ if self.file_loader_cls is not None:
+ fh.seek(0)
+ loader = self.file_loader_cls(file=fh, **self.file_loader_kwargs)
+ docs = loader.load()
+ for doc in docs:
+ doc.metadata["source"] = f"https://drive.google.com/file/d/{id}/view"
+ if "title" not in doc.metadata:
+ doc.metadata["title"] = f"{file.get('name')}"
+ return docs
+
+ else:
+ from PyPDF2 import PdfReader
+
+ content = fh.getvalue()
+ pdf_reader = PdfReader(BytesIO(content))
+
+ return [
+ Document(
+ page_content=page.extract_text(),
+ metadata={
+ "source": f"https://drive.google.com/file/d/{id}/view",
+ "title": f"{file.get('name')}",
+ "page": i,
+ },
+ )
+ for i, page in enumerate(pdf_reader.pages)
+ ]
+
+ def _load_file_from_ids(self) -> List[Document]:
+ """Load files from a list of IDs."""
+ if not self.file_ids:
+ raise ValueError("file_ids must be set")
+ docs = []
+ for file_id in self.file_ids:
+ docs.extend(self._load_file_from_id(file_id))
+ return docs
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ if self.folder_id:
+ return self._load_documents_from_folder(
+ self.folder_id, file_types=self.file_types
+ )
+ elif self.document_ids:
+ return self._load_documents_from_ids()
+ else:
+ return self._load_file_from_ids()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/gutenberg.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/gutenberg.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe253ae88875fb78346335a68c4641d91dbfa474
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/gutenberg.py
@@ -0,0 +1,28 @@
+from typing import List
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class GutenbergLoader(BaseLoader):
+ """Load from `Gutenberg.org`."""
+
+ def __init__(self, file_path: str):
+ """Initialize with a file path."""
+ if not file_path.startswith("https://www.gutenberg.org"):
+ raise ValueError("file path must start with 'https://www.gutenberg.org'")
+
+ if not file_path.endswith(".txt"):
+ raise ValueError("file path must end with '.txt'")
+
+ self.file_path = file_path
+
+ def load(self) -> List[Document]:
+ """Load file."""
+ from urllib.request import urlopen
+
+ elements = urlopen(self.file_path)
+ text = "\n\n".join([str(el.decode("utf-8-sig")) for el in elements])
+ metadata = {"source": self.file_path}
+ return [Document(page_content=text, metadata=metadata)]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/helpers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..e094db687280ed19f3315ddfd094b81458e3bcda
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/helpers.py
@@ -0,0 +1,51 @@
+"""Document loader helpers."""
+
+import concurrent.futures
+from pathlib import Path
+from typing import List, NamedTuple, Optional, Union, cast
+
+
+class FileEncoding(NamedTuple):
+ """File encoding as the NamedTuple."""
+
+ encoding: Optional[str]
+ """The encoding of the file."""
+ confidence: float
+ """The confidence of the encoding."""
+ language: Optional[str]
+ """The language of the file."""
+
+
+def detect_file_encodings(
+ file_path: Union[str, Path], timeout: int = 5
+) -> List[FileEncoding]:
+ """Try to detect the file encoding.
+
+ Returns a list of `FileEncoding` tuples with the detected encodings ordered
+ by confidence.
+
+ Args:
+ file_path: The path to the file to detect the encoding for.
+ timeout: The timeout in seconds for the encoding detection.
+ """
+ import chardet
+
+ file_path = str(file_path)
+
+ def read_and_detect(file_path: str) -> List[dict]:
+ with open(file_path, "rb") as f:
+ rawdata = f.read()
+ return cast(List[dict], chardet.detect_all(rawdata))
+
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ future = executor.submit(read_and_detect, file_path)
+ try:
+ encodings = future.result(timeout=timeout)
+ except concurrent.futures.TimeoutError:
+ raise TimeoutError(
+ f"Timeout reached while detecting encoding for {file_path}"
+ )
+
+ if all(encoding["encoding"] is None for encoding in encodings):
+ raise RuntimeError(f"Could not detect encoding for {file_path}")
+ return [FileEncoding(**enc) for enc in encodings if enc["encoding"] is not None]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/hn.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/hn.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca36ca5f2b9573defb1060ddd14bd6f4360ad9e7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/hn.py
@@ -0,0 +1,62 @@
+from typing import Any, List
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.web_base import WebBaseLoader
+
+
+class HNLoader(WebBaseLoader):
+ """Load `Hacker News` data.
+
+ It loads data from either main page results or the comments page."""
+
+ def load(self) -> List[Document]:
+ """Get important HN webpage information.
+
+ HN webpage components are:
+ - title
+ - content
+ - source url,
+ - time of post
+ - author of the post
+ - number of comments
+ - rank of the post
+ """
+ soup_info = self.scrape()
+ if "item" in self.web_path:
+ return self.load_comments(soup_info)
+ else:
+ return self.load_results(soup_info)
+
+ def load_comments(self, soup_info: Any) -> List[Document]:
+ """Load comments from a HN post."""
+ comments = soup_info.select("tr[class='athing comtr']")
+ title = soup_info.select_one("tr[id='pagespace']").get("title")
+ return [
+ Document(
+ page_content=comment.text.strip(),
+ metadata={"source": self.web_path, "title": title},
+ )
+ for comment in comments
+ ]
+
+ def load_results(self, soup: Any) -> List[Document]:
+ """Load items from an HN page."""
+ items = soup.select("tr[class='athing']")
+ documents = []
+ for lineItem in items:
+ ranking = lineItem.select_one("span[class='rank']").text
+ link = lineItem.find("span", {"class": "titleline"}).find("a").get("href")
+ title = lineItem.find("span", {"class": "titleline"}).text.strip()
+ metadata = {
+ "source": self.web_path,
+ "title": title,
+ "link": link,
+ "ranking": ranking,
+ }
+ documents.append(
+ Document(
+ page_content=title, link=link, ranking=ranking, metadata=metadata
+ )
+ )
+ return documents
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/html.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/html.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ec3224e66308681b6b8274c61ee49c639773c97
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/html.py
@@ -0,0 +1,51 @@
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
+
+
+class UnstructuredHTMLLoader(UnstructuredFileLoader):
+ """Load `HTML` files using `Unstructured`.
+
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredHTMLLoader
+
+ loader = UnstructuredHTMLLoader(
+ "example.html", mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/bricks.html#partition-html
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+
+ Args:
+ file_path: The path to the HTML file to load.
+ mode: The mode to use when loading the file. Can be one of "single",
+ "multi", or "all". Default is "single".
+ **unstructured_kwargs: Any kwargs to pass to the unstructured.
+ """
+ file_path = str(file_path)
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.html import partition_html
+
+ return partition_html(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/html_bs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/html_bs.py
new file mode 100644
index 0000000000000000000000000000000000000000..6448e4c7fe7aa816008982c6c7b20fe904df7bee
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/html_bs.py
@@ -0,0 +1,139 @@
+import importlib.util
+import logging
+from pathlib import Path
+from typing import Dict, Iterator, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+
+class BSHTMLLoader(BaseLoader):
+ """
+ __ModuleName__ document loader integration
+
+ Setup:
+ Install ``langchain-community`` and ``bs4``.
+
+ .. code-block:: bash
+
+ pip install -U langchain-community bs4
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import BSHTMLLoader
+
+ loader = BSHTMLLoader(
+ file_path="./example_data/fake-content.html",
+ )
+
+ Lazy load:
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ # async variant:
+ # docs_lazy = await loader.alazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+
+ Test Title
+
+
+ My First Heading
+ My first paragraph.
+
+
+
+ {'source': './example_data/fake-content.html', 'title': 'Test Title'}
+
+ Async load:
+ .. code-block:: python
+
+ docs = await loader.aload()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+
+
+ Test Title
+
+
+ My First Heading
+ My first paragraph.
+
+
+
+ {'source': './example_data/fake-content.html', 'title': 'Test Title'}
+
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ open_encoding: Union[str, None] = None,
+ bs_kwargs: Union[dict, None] = None,
+ get_text_separator: str = "",
+ ) -> None:
+ """initialize with path, and optionally, file encoding to use, and any kwargs
+ to pass to the BeautifulSoup object.
+
+ Args:
+ file_path: The path to the file to load.
+ open_encoding: The encoding to use when opening the file.
+ bs_kwargs: Any kwargs to pass to the BeautifulSoup object.
+ get_text_separator: The separator to use when calling get_text on the soup.
+ """
+ try:
+ import bs4 # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "beautifulsoup4 package not found, please install it with "
+ "`pip install beautifulsoup4`"
+ )
+
+ self.file_path = file_path
+ self.open_encoding = open_encoding
+ if bs_kwargs is None:
+ if not importlib.util.find_spec("lxml"):
+ raise ImportError(
+ "By default BSHTMLLoader uses the 'lxml' package. Please either "
+ "install it with `pip install -U lxml` or pass in init arg "
+ "`bs_kwargs={'features': '...'}` to overwrite the default "
+ "BeautifulSoup kwargs."
+ )
+ bs_kwargs = {"features": "lxml"}
+ self.bs_kwargs = bs_kwargs
+ self.get_text_separator = get_text_separator
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load HTML document into document objects."""
+ from bs4 import BeautifulSoup
+
+ with open(self.file_path, "r", encoding=self.open_encoding) as f:
+ soup = BeautifulSoup(f, **self.bs_kwargs)
+
+ text = soup.get_text(self.get_text_separator)
+
+ if soup.title:
+ title = str(soup.title.string)
+ else:
+ title = ""
+
+ metadata: Dict[str, Union[str, None]] = {
+ "source": str(self.file_path),
+ "title": title,
+ }
+ yield Document(page_content=text, metadata=metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/hugging_face_dataset.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/hugging_face_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..4aafc42b681296fad4198f8e34f4b60a59bc5228
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/hugging_face_dataset.py
@@ -0,0 +1,90 @@
+import json
+from typing import Iterator, Mapping, Optional, Sequence, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class HuggingFaceDatasetLoader(BaseLoader):
+ """Load from `Hugging Face Hub` datasets."""
+
+ def __init__(
+ self,
+ path: str,
+ page_content_column: str = "text",
+ name: Optional[str] = None,
+ data_dir: Optional[str] = None,
+ data_files: Optional[
+ Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]
+ ] = None,
+ cache_dir: Optional[str] = None,
+ keep_in_memory: Optional[bool] = None,
+ save_infos: bool = False,
+ use_auth_token: Optional[Union[bool, str]] = None,
+ num_proc: Optional[int] = None,
+ ):
+ """Initialize the HuggingFaceDatasetLoader.
+
+ Args:
+ path: Path or name of the dataset.
+ page_content_column: Page content column name. Default is "text".
+ name: Name of the dataset configuration.
+ data_dir: Data directory of the dataset configuration.
+ data_files: Path(s) to source data file(s).
+ cache_dir: Directory to read/write data.
+ keep_in_memory: Whether to copy the dataset in-memory.
+ save_infos: Save the dataset information (checksums/size/splits/...).
+ Default is False.
+ use_auth_token: Bearer token for remote files on the Dataset Hub.
+ num_proc: Number of processes.
+ """
+
+ self.path = path
+ self.page_content_column = page_content_column
+ self.name = name
+ self.data_dir = data_dir
+ self.data_files = data_files
+ self.cache_dir = cache_dir
+ self.keep_in_memory = keep_in_memory
+ self.save_infos = save_infos
+ self.use_auth_token = use_auth_token
+ self.num_proc = num_proc
+
+ def lazy_load(
+ self,
+ ) -> Iterator[Document]:
+ """Load documents lazily."""
+ try:
+ from datasets import load_dataset
+ except ImportError:
+ raise ImportError(
+ "Could not import datasets python package. "
+ "Please install it with `pip install datasets`."
+ )
+
+ dataset = load_dataset(
+ path=self.path,
+ name=self.name,
+ data_dir=self.data_dir,
+ data_files=self.data_files,
+ cache_dir=self.cache_dir,
+ keep_in_memory=self.keep_in_memory,
+ save_infos=self.save_infos,
+ use_auth_token=self.use_auth_token,
+ num_proc=self.num_proc,
+ )
+
+ yield from (
+ Document(
+ page_content=self.parse_obj(row.pop(self.page_content_column)),
+ metadata=row,
+ )
+ for key in dataset.keys()
+ for row in dataset[key]
+ )
+
+ def parse_obj(self, page_content: Union[str, object]) -> str:
+ if isinstance(page_content, object):
+ return json.dumps(page_content)
+ return page_content
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/hugging_face_model.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/hugging_face_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bd74aa2e922b27ca5dd0b7a6798b407b274a196
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/hugging_face_model.py
@@ -0,0 +1,108 @@
+from typing import Iterator, List, Optional
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class HuggingFaceModelLoader(BaseLoader):
+ """
+ Load model information from `Hugging Face Hub`, including README content.
+
+ This loader interfaces with the Hugging Face Models API to fetch and load
+ model metadata and README files.
+ The API allows you to search and filter models based on specific criteria
+ such as model tags, authors, and more.
+
+ API URL: https://huggingface.co/api/models
+ DOC URL: https://huggingface.co/docs/hub/en/api
+
+ Examples:
+
+ .. code-block:: python
+
+ from langchain_community.document_loaders import HuggingFaceModelLoader
+
+ # Initialize the loader with search criteria
+ loader = HuggingFaceModelLoader(search="bert", limit=10)
+
+ # Load models
+ documents = loader.load()
+
+ # Iterate through the fetched documents
+ for doc in documents:
+ print(doc.page_content) # README content of the model
+ print(doc.metadata) # Metadata of the model
+ """
+
+ BASE_URL: str = "https://huggingface.co/api/models"
+ README_BASE_URL: str = "https://huggingface.co/{model_id}/raw/main/README.md"
+
+ def __init__(
+ self,
+ *,
+ search: Optional[str] = None,
+ author: Optional[str] = None,
+ filter: Optional[str] = None,
+ sort: Optional[str] = None,
+ direction: Optional[str] = None,
+ limit: Optional[int] = 3,
+ full: Optional[bool] = None,
+ config: Optional[bool] = None,
+ ):
+ """Initialize the HuggingFaceModelLoader.
+
+ Args:
+ search: Filter based on substrings for repos and their usernames.
+ author: Filter models by an author or organization.
+ filter: Filter based on tags.
+ sort: Property to use when sorting.
+ direction: Direction in which to sort.
+ limit: Limit the number of models fetched.
+ full: Whether to fetch most model data.
+ config: Whether to also fetch the repo config.
+ """
+
+ self.params = {
+ "search": search,
+ "author": author,
+ "filter": filter,
+ "sort": sort,
+ "direction": direction,
+ "limit": limit,
+ "full": full,
+ "config": config,
+ }
+
+ def fetch_models(self) -> List[dict]:
+ """Fetch model information from Hugging Face Hub."""
+ response = requests.get(
+ self.BASE_URL,
+ params={k: v for k, v in self.params.items() if v is not None},
+ )
+ response.raise_for_status()
+ return response.json()
+
+ def fetch_readme_content(self, model_id: str) -> str:
+ """Fetch the README content for a given model."""
+ readme_url = self.README_BASE_URL.format(model_id=model_id)
+ try:
+ response = requests.get(readme_url)
+ response.raise_for_status()
+ return response.text
+ except requests.RequestException:
+ return "README not available for this model."
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load model information lazily, including README content."""
+ models = self.fetch_models()
+
+ for model in models:
+ model_id = model.get("modelId", "")
+ readme_content = self.fetch_readme_content(model_id)
+
+ yield Document(
+ page_content=readme_content,
+ metadata=model,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/ifixit.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/ifixit.py
new file mode 100644
index 0000000000000000000000000000000000000000..335a4a1816e9b85b00f44e4582471a275e6a7a16
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/ifixit.py
@@ -0,0 +1,240 @@
+from typing import List, Optional
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.web_base import WebBaseLoader
+
+IFIXIT_BASE_URL = "https://www.ifixit.com/api/2.0"
+
+
+class IFixitLoader(BaseLoader):
+ """Load `iFixit` repair guides, device wikis and answers.
+
+ iFixit is the largest, open repair community on the web. The site contains nearly
+ 100k repair manuals, 200k Questions & Answers on 42k devices, and all the data is
+ licensed under CC-BY.
+
+ This loader will allow you to download the text of a repair guide, text of Q&A's
+ and wikis from devices on iFixit using their open APIs and web scraping.
+ """
+
+ def __init__(self, web_path: str):
+ """Initialize with a web path."""
+ if not web_path.startswith("https://www.ifixit.com"):
+ raise ValueError("web path must start with 'https://www.ifixit.com'")
+
+ path = web_path.replace("https://www.ifixit.com", "")
+
+ allowed_paths = ["/Device", "/Guide", "/Answers", "/Teardown"]
+
+ """ TODO: Add /Wiki """
+ if not any(path.startswith(allowed_path) for allowed_path in allowed_paths):
+ raise ValueError(
+ "web path must start with /Device, /Guide, /Teardown or /Answers"
+ )
+
+ pieces = [x for x in path.split("/") if x]
+
+ """Teardowns are just guides by a different name"""
+ self.page_type = pieces[0] if pieces[0] != "Teardown" else "Guide"
+
+ if self.page_type == "Guide" or self.page_type == "Answers":
+ self.id = pieces[2]
+ else:
+ self.id = pieces[1]
+
+ self.web_path = web_path
+
+ def load(self) -> List[Document]:
+ if self.page_type == "Device":
+ return self.load_device()
+ elif self.page_type == "Guide" or self.page_type == "Teardown":
+ return self.load_guide()
+ elif self.page_type == "Answers":
+ return self.load_questions_and_answers()
+ else:
+ raise ValueError("Unknown page type: " + self.page_type)
+
+ @staticmethod
+ def load_suggestions(query: str = "", doc_type: str = "all") -> List[Document]:
+ """Load suggestions.
+
+ Args:
+ query: A query string
+ doc_type: The type of document to search for. Can be one of "all",
+ "device", "guide", "teardown", "answer", "wiki".
+
+ Returns:
+
+ """
+ res = requests.get(
+ IFIXIT_BASE_URL + "/suggest/" + query + "?doctypes=" + doc_type
+ )
+
+ if res.status_code != 200:
+ raise ValueError(
+ 'Could not load suggestions for "' + query + '"\n' + res.json()
+ )
+
+ data = res.json()
+
+ results = data["results"]
+ output = []
+
+ for result in results:
+ try:
+ loader = IFixitLoader(result["url"])
+ if loader.page_type == "Device":
+ output += loader.load_device(include_guides=False)
+ else:
+ output += loader.load()
+ except ValueError:
+ continue
+
+ return output
+
+ def load_questions_and_answers(
+ self, url_override: Optional[str] = None
+ ) -> List[Document]:
+ """Load a list of questions and answers.
+
+ Args:
+ url_override: A URL to override the default URL.
+
+ Returns: List[Document]
+
+ """
+ loader = WebBaseLoader(self.web_path if url_override is None else url_override)
+ soup = loader.scrape()
+
+ output = []
+
+ title = soup.find("h1", "post-title").text
+
+ output.append("# " + title)
+ output.append(soup.select_one(".post-content .post-text").text.strip())
+
+ answersHeader = soup.find("div", "post-answers-header")
+ if answersHeader:
+ output.append("\n## " + answersHeader.text.strip())
+
+ for answer in soup.select(".js-answers-list .post.post-answer"):
+ if answer.has_attr("itemprop") and "acceptedAnswer" in answer["itemprop"]:
+ output.append("\n### Accepted Answer")
+ elif "post-helpful" in answer["class"]:
+ output.append("\n### Most Helpful Answer")
+ else:
+ output.append("\n### Other Answer")
+
+ output += [
+ a.text.strip() for a in answer.select(".post-content .post-text")
+ ]
+ output.append("\n")
+
+ text = "\n".join(output).strip()
+
+ metadata = {"source": self.web_path, "title": title}
+
+ return [Document(page_content=text, metadata=metadata)]
+
+ def load_device(
+ self, url_override: Optional[str] = None, include_guides: bool = True
+ ) -> List[Document]:
+ """Loads a device
+
+ Args:
+ url_override: A URL to override the default URL.
+ include_guides: Whether to include guides linked to from the device.
+ Defaults to True.
+
+ Returns:
+
+ """
+ documents = []
+ if url_override is None:
+ url = IFIXIT_BASE_URL + "/wikis/CATEGORY/" + self.id
+ else:
+ url = url_override
+
+ res = requests.get(url)
+ data = res.json()
+ text = "\n".join(
+ [
+ data[key]
+ for key in ["title", "description", "contents_raw"]
+ if key in data
+ ]
+ ).strip()
+
+ metadata = {"source": self.web_path, "title": data["title"]}
+ documents.append(Document(page_content=text, metadata=metadata))
+
+ if include_guides:
+ """Load and return documents for each guide linked to from the device"""
+ guide_urls = [guide["url"] for guide in data["guides"]]
+ for guide_url in guide_urls:
+ documents.append(IFixitLoader(guide_url).load()[0])
+
+ return documents
+
+ def load_guide(self, url_override: Optional[str] = None) -> List[Document]:
+ """Load a guide
+
+ Args:
+ url_override: A URL to override the default URL.
+
+ Returns: List[Document]
+
+ """
+ if url_override is None:
+ url = IFIXIT_BASE_URL + "/guides/" + self.id
+ else:
+ url = url_override
+
+ res = requests.get(url)
+
+ if res.status_code != 200:
+ raise ValueError(
+ "Could not load guide: " + self.web_path + "\n" + res.json()
+ )
+
+ data = res.json()
+
+ doc_parts = ["# " + data["title"], data["introduction_raw"]]
+
+ doc_parts.append("\n\n###Tools Required:")
+ if len(data["tools"]) == 0:
+ doc_parts.append("\n - None")
+ else:
+ for tool in data["tools"]:
+ doc_parts.append("\n - " + tool["text"])
+
+ doc_parts.append("\n\n###Parts Required:")
+ if len(data["parts"]) == 0:
+ doc_parts.append("\n - None")
+ else:
+ for part in data["parts"]:
+ doc_parts.append("\n - " + part["text"])
+
+ for row in data["steps"]:
+ doc_parts.append(
+ "\n\n## "
+ + (
+ row["title"]
+ if row["title"] != ""
+ else "Step {}".format(row["orderby"])
+ )
+ )
+
+ for line in row["lines"]:
+ doc_parts.append(line["text_raw"])
+
+ doc_parts.append(data["conclusion_raw"])
+
+ text = "\n".join(doc_parts)
+
+ metadata = {"source": self.web_path, "title": data["title"]}
+
+ return [Document(page_content=text, metadata=metadata)]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/image.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/image.py
new file mode 100644
index 0000000000000000000000000000000000000000..acec0f360d02c28832ad2aed9f1ed9e579cf13c9
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/image.py
@@ -0,0 +1,51 @@
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
+
+
+class UnstructuredImageLoader(UnstructuredFileLoader):
+ """Load `PNG` and `JPG` files using `Unstructured`.
+
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredImageLoader
+
+ loader = UnstructuredImageLoader(
+ "example.png", mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/bricks.html#partition-image
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+
+ Args:
+ file_path: The path to the Image file to load.
+ mode: The mode to use when loading the file. Can be one of "single",
+ "multi", or "all". Default is "single".
+ **unstructured_kwargs: Any kwargs to pass to the unstructured.
+ """
+ file_path = str(file_path)
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.image import partition_image
+
+ return partition_image(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/image_captions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/image_captions.py
new file mode 100644
index 0000000000000000000000000000000000000000..568fa0a25aacbe253fe57073455b7874251698c2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/image_captions.py
@@ -0,0 +1,102 @@
+from io import BytesIO
+from pathlib import Path
+from typing import Any, List, Tuple, Union
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class ImageCaptionLoader(BaseLoader):
+ """Load image captions.
+
+ By default, the loader utilizes the pre-trained
+ Salesforce BLIP image captioning model.
+ https://huggingface.co/Salesforce/blip-image-captioning-base
+ """
+
+ def __init__(
+ self,
+ images: Union[str, Path, bytes, List[Union[str, bytes, Path]]],
+ blip_processor: str = "Salesforce/blip-image-captioning-base",
+ blip_model: str = "Salesforce/blip-image-captioning-base",
+ ):
+ """Initialize with a list of image data (bytes) or file paths
+
+ Args:
+ images: Either a single image or a list of images. Accepts
+ image data (bytes) or file paths to images.
+ blip_processor: The name of the pre-trained BLIP processor.
+ blip_model: The name of the pre-trained BLIP model.
+ """
+ if isinstance(images, (str, Path, bytes)):
+ self.images = [images]
+ else:
+ self.images = images
+
+ self.blip_processor = blip_processor
+ self.blip_model = blip_model
+
+ def load(self) -> List[Document]:
+ """Load from a list of image data or file paths"""
+ try:
+ from transformers import BlipForConditionalGeneration, BlipProcessor
+ except ImportError:
+ raise ImportError(
+ "`transformers` package not found, please install with "
+ "`pip install transformers`."
+ )
+
+ processor = BlipProcessor.from_pretrained(self.blip_processor)
+ model = BlipForConditionalGeneration.from_pretrained(self.blip_model)
+
+ results = []
+ for image in self.images:
+ caption, metadata = self._get_captions_and_metadata(
+ model=model, processor=processor, image=image
+ )
+ doc = Document(page_content=caption, metadata=metadata)
+ results.append(doc)
+
+ return results
+
+ def _get_captions_and_metadata(
+ self, model: Any, processor: Any, image: Union[str, Path, bytes]
+ ) -> Tuple[str, dict]:
+ """Helper function for getting the captions and metadata of an image."""
+ try:
+ from PIL import Image
+ except ImportError:
+ raise ImportError(
+ "`PIL` package not found, please install with `pip install pillow`"
+ )
+
+ image_source = image # Save the original source for later reference
+
+ try:
+ if isinstance(image, bytes):
+ image = Image.open(BytesIO(image)).convert("RGB")
+ elif isinstance(image, str) and (
+ image.startswith("http://") or image.startswith("https://")
+ ):
+ image = Image.open(requests.get(image, stream=True).raw).convert("RGB")
+ else:
+ image = Image.open(image).convert("RGB")
+ except Exception:
+ if isinstance(image_source, bytes):
+ msg = "Could not get image data from bytes"
+ else:
+ msg = f"Could not get image data for {image_source}"
+ raise ValueError(msg)
+
+ inputs = processor(image, "an image of", return_tensors="pt")
+ output = model.generate(**inputs)
+
+ caption: str = processor.decode(output[0])
+ if isinstance(image_source, bytes):
+ metadata: dict = {"image_source": "Image bytes provided"}
+ else:
+ metadata = {"image_path": str(image_source)}
+
+ return caption, metadata
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/imsdb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/imsdb.py
new file mode 100644
index 0000000000000000000000000000000000000000..af2240206202a1a0a916a2b7c65aaa78d5335f89
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/imsdb.py
@@ -0,0 +1,16 @@
+from typing import List
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.web_base import WebBaseLoader
+
+
+class IMSDbLoader(WebBaseLoader):
+ """Load `IMSDb` webpages."""
+
+ def load(self) -> List[Document]:
+ """Load webpage."""
+ soup = self.scrape()
+ text = soup.select_one("td[class='scrtext']").text
+ metadata = {"source": self.web_path}
+ return [Document(page_content=text, metadata=metadata)]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/iugu.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/iugu.py
new file mode 100644
index 0000000000000000000000000000000000000000..31e56bb0c7a3cc4cda1dbd7303b2ed601305d2e1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/iugu.py
@@ -0,0 +1,49 @@
+import json
+import urllib.request
+from typing import List, Optional
+
+from langchain_core.documents import Document
+from langchain_core.utils import get_from_env, stringify_dict
+
+from langchain_community.document_loaders.base import BaseLoader
+
+IUGU_ENDPOINTS = {
+ "invoices": "https://api.iugu.com/v1/invoices",
+ "customers": "https://api.iugu.com/v1/customers",
+ "charges": "https://api.iugu.com/v1/charges",
+ "subscriptions": "https://api.iugu.com/v1/subscriptions",
+ "plans": "https://api.iugu.com/v1/plans",
+}
+
+
+class IuguLoader(BaseLoader):
+ """Load from `IUGU`."""
+
+ def __init__(self, resource: str, api_token: Optional[str] = None) -> None:
+ """Initialize the IUGU resource.
+
+ Args:
+ resource: The name of the resource to fetch.
+ api_token: The IUGU API token to use.
+ """
+ self.resource = resource
+ api_token = api_token or get_from_env("api_token", "IUGU_API_TOKEN")
+ self.headers = {"Authorization": f"Bearer {api_token}"}
+
+ def _make_request(self, url: str) -> List[Document]:
+ request = urllib.request.Request(url, headers=self.headers)
+
+ with urllib.request.urlopen(request) as response:
+ json_data = json.loads(response.read().decode())
+ text = stringify_dict(json_data)
+ metadata = {"source": url}
+ return [Document(page_content=text, metadata=metadata)]
+
+ def _get_resource(self) -> List[Document]:
+ endpoint = IUGU_ENDPOINTS.get(self.resource)
+ if endpoint is None:
+ return []
+ return self._make_request(endpoint)
+
+ def load(self) -> List[Document]:
+ return self._get_resource()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/joplin.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/joplin.py
new file mode 100644
index 0000000000000000000000000000000000000000..407af7e6a35739a817039bbfd66095d29f461102
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/joplin.py
@@ -0,0 +1,93 @@
+import json
+import urllib
+from datetime import datetime
+from typing import Iterator, List, Optional
+
+from langchain_core.documents import Document
+from langchain_core.utils import get_from_env
+
+from langchain_community.document_loaders.base import BaseLoader
+
+LINK_NOTE_TEMPLATE = "joplin://x-callback-url/openNote?id={id}"
+
+
+class JoplinLoader(BaseLoader):
+ """Load notes from `Joplin`.
+
+ In order to use this loader, you need to have Joplin running with the
+ Web Clipper enabled (look for "Web Clipper" in the app settings).
+
+ To get the access token, you need to go to the Web Clipper options and
+ under "Advanced Options" you will find the access token.
+
+ You can find more information about the Web Clipper service here:
+ https://joplinapp.org/clipper/
+ """
+
+ def __init__(
+ self,
+ access_token: Optional[str] = None,
+ port: int = 41184,
+ host: str = "localhost",
+ ) -> None:
+ """
+
+ Args:
+ access_token: The access token to use.
+ port: The port where the Web Clipper service is running. Default is 41184.
+ host: The host where the Web Clipper service is running.
+ Default is localhost.
+ """
+ access_token = access_token or get_from_env(
+ "access_token", "JOPLIN_ACCESS_TOKEN"
+ )
+ base_url = f"http://{host}:{port}"
+ self._get_note_url = (
+ f"{base_url}/notes?token={access_token}"
+ f"&fields=id,parent_id,title,body,created_time,updated_time&page={{page}}"
+ )
+ self._get_folder_url = (
+ f"{base_url}/folders/{{id}}?token={access_token}&fields=title"
+ )
+ self._get_tag_url = (
+ f"{base_url}/notes/{{id}}/tags?token={access_token}&fields=title"
+ )
+
+ def _get_notes(self) -> Iterator[Document]:
+ has_more = True
+ page = 1
+ while has_more:
+ req_note = urllib.request.Request(self._get_note_url.format(page=page))
+ with urllib.request.urlopen(req_note) as response:
+ json_data = json.loads(response.read().decode())
+ for note in json_data["items"]:
+ metadata = {
+ "source": LINK_NOTE_TEMPLATE.format(id=note["id"]),
+ "folder": self._get_folder(note["parent_id"]),
+ "tags": self._get_tags(note["id"]),
+ "title": note["title"],
+ "created_time": self._convert_date(note["created_time"]),
+ "updated_time": self._convert_date(note["updated_time"]),
+ }
+ yield Document(page_content=note["body"], metadata=metadata)
+
+ has_more = json_data["has_more"]
+ page += 1
+
+ def _get_folder(self, folder_id: str) -> str:
+ req_folder = urllib.request.Request(self._get_folder_url.format(id=folder_id))
+ with urllib.request.urlopen(req_folder) as response:
+ json_data = json.loads(response.read().decode())
+ return json_data["title"]
+
+ def _get_tags(self, note_id: str) -> List[str]:
+ req_tag = urllib.request.Request(self._get_tag_url.format(id=note_id))
+ with urllib.request.urlopen(req_tag) as response:
+ json_data = json.loads(response.read().decode())
+ return [tag["title"] for tag in json_data["items"]]
+
+ def _convert_date(self, date: int) -> str:
+ return datetime.fromtimestamp(date / 1000).strftime("%Y-%m-%d %H:%M:%S")
+
+ def lazy_load(self) -> Iterator[Document]:
+ yield from self._get_notes()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/json_loader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/json_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9c67413a26e0b0b21b98bbcf6169c437d424a33
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/json_loader.py
@@ -0,0 +1,241 @@
+import json
+from os import PathLike
+from pathlib import Path
+from typing import Any, Callable, Dict, Iterator, Optional, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class JSONLoader(BaseLoader):
+ """
+ Load a `JSON` file using a `jq` schema.
+
+ Setup:
+ .. code-block:: bash
+
+ pip install -U jq
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import JSONLoader
+ import json
+ from pathlib import Path
+
+ file_path='./sample_quiz.json'
+ data = json.loads(Path(file_path).read_text())
+ loader = JSONLoader(
+ file_path=file_path,
+ jq_schema='.quiz',
+ text_content=False)
+
+ Load:
+ .. code-block:: python
+
+ docs = loader.load()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ {"sport": {"q1": {"question": "Which one is correct team name in
+ NBA?", "options": ["New York Bulls"
+ {'source': '/sample_quiz
+ .json', 'seq_num': 1}
+
+ Async load:
+ .. code-block:: python
+
+ docs = await loader.aload()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ {"sport": {"q1": {"question": "Which one is correct team name in
+ NBA?", "options": ["New York Bulls"
+ {'source': '/sample_quizg
+ .json', 'seq_num': 1}
+
+ Lazy load:
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ # async variant:
+ # docs_lazy = await loader.alazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ {"sport": {"q1": {"question": "Which one is correct team name in
+ NBA?", "options": ["New York Bulls"
+ {'source': '/sample_quiz
+ .json', 'seq_num': 1}
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, PathLike],
+ jq_schema: str,
+ content_key: Optional[str] = None,
+ is_content_key_jq_parsable: Optional[bool] = False,
+ metadata_func: Optional[Callable[[Dict, Dict], Dict]] = None,
+ text_content: bool = True,
+ json_lines: bool = False,
+ ):
+ """Initialize the JSONLoader.
+
+ Args:
+ file_path (Union[str, PathLike]): The path to the JSON or JSON Lines file.
+ jq_schema (str): The jq schema to use to extract the data or text from
+ the JSON.
+ content_key (str): The key to use to extract the content from
+ the JSON if the jq_schema results to a list of objects (dict).
+ If is_content_key_jq_parsable is True, this has to be a jq compatible
+ schema. If is_content_key_jq_parsable is False, this should be a simple
+ string key.
+ is_content_key_jq_parsable (bool): A flag to determine if
+ content_key is parsable by jq or not. If True, content_key is
+ treated as a jq schema and compiled accordingly. If False or if
+ content_key is None, content_key is used as a simple string.
+ Default is False.
+ metadata_func (Callable[Dict, Dict]): A function that takes in the JSON
+ object extracted by the jq_schema and the default metadata and returns
+ a dict of the updated metadata.
+ text_content (bool): Boolean flag to indicate whether the content is in
+ string format, default to True.
+ json_lines (bool): Boolean flag to indicate whether the input is in
+ JSON Lines format.
+ """
+ try:
+ import jq
+
+ self.jq = jq
+ except ImportError:
+ raise ImportError(
+ "jq package not found, please install it with `pip install jq`"
+ )
+
+ self.file_path = Path(file_path).resolve()
+ self._jq_schema = jq.compile(jq_schema)
+ self._is_content_key_jq_parsable = is_content_key_jq_parsable
+ self._content_key = content_key
+ self._metadata_func = metadata_func
+ self._text_content = text_content
+ self._json_lines = json_lines
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load and return documents from the JSON file."""
+ index = 0
+ if self._json_lines:
+ with self.file_path.open(encoding="utf-8-sig") as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ for doc in self._parse(line, index):
+ yield doc
+ index += 1
+ else:
+ for doc in self._parse(
+ self.file_path.read_text(encoding="utf-8-sig"), index
+ ):
+ yield doc
+ index += 1
+
+ def _parse(self, content: str, index: int) -> Iterator[Document]:
+ """Convert given content to documents."""
+ data = self._jq_schema.input(json.loads(content))
+
+ # Perform some validation
+ # This is not a perfect validation, but it should catch most cases
+ # and prevent the user from getting a cryptic error later on.
+ if self._content_key is not None:
+ self._validate_content_key(data)
+
+ for i, sample in enumerate(data, index + 1):
+ text = self._get_text(sample=sample)
+ metadata = self._get_metadata(
+ sample=sample, source=str(self.file_path), seq_num=i
+ )
+ yield Document(page_content=text, metadata=metadata)
+
+ def _get_text(self, sample: Any) -> str:
+ """Convert sample to string format"""
+ if self._content_key is not None:
+ if self._is_content_key_jq_parsable:
+ compiled_content_key = self.jq.compile(self._content_key)
+ content = compiled_content_key.input(sample).first()
+ else:
+ content = sample[self._content_key]
+ else:
+ content = sample
+
+ if self._text_content and not isinstance(content, str) and content is not None:
+ raise ValueError(
+ f"Expected page_content is string, got {type(content)} instead. \
+ Set `text_content=False` if the desired input for \
+ `page_content` is not a string"
+ )
+
+ # In case the text is None, set it to an empty string
+ elif isinstance(content, str):
+ return content
+ elif isinstance(content, (dict, list)):
+ return json.dumps(content) if content else ""
+ else:
+ return str(content) if content is not None else ""
+
+ def _get_metadata(
+ self, sample: Dict[str, Any], **additional_fields: Any
+ ) -> Dict[str, Any]:
+ """
+ Return a metadata dictionary base on the existence of metadata_func
+ :param sample: single data payload
+ :param additional_fields: key-word arguments to be added as metadata values
+ :return:
+ """
+ if self._metadata_func is not None:
+ result = self._metadata_func(sample, additional_fields)
+ if not isinstance(result, dict):
+ raise ValueError(
+ f"Expected the metadata_func to return a dict but got \
+ `{type(result)}`"
+ )
+ return result
+ else:
+ return additional_fields
+
+ def _validate_content_key(self, data: Any) -> None:
+ """Check if a content key is valid"""
+
+ sample = data.first()
+ if not isinstance(sample, dict):
+ raise ValueError(
+ f"Expected the jq schema to result in a list of objects (dict), \
+ so sample must be a dict but got `{type(sample)}`"
+ )
+
+ if (
+ not self._is_content_key_jq_parsable
+ and sample.get(self._content_key) is None
+ ):
+ raise ValueError(
+ f"Expected the jq schema to result in a list of objects (dict) \
+ with the key `{self._content_key}`"
+ )
+ if (
+ self._is_content_key_jq_parsable
+ and self.jq.compile(self._content_key).input(sample).text() is None
+ ):
+ raise ValueError(
+ f"Expected the jq schema to result in a list of objects (dict) \
+ with the key `{self._content_key}` which should be parsable by jq"
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/kinetica_loader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/kinetica_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2a3b7169dcd3ff3508965fc62ac8215d1fd0f1e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/kinetica_loader.py
@@ -0,0 +1,103 @@
+from __future__ import annotations
+
+from typing import Any, Dict, Iterator, List, Optional, Tuple
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class KineticaLoader(BaseLoader):
+ """Load from `Kinetica` API.
+
+ Each document represents one row of the result. The `page_content_columns`
+ are written into the `page_content` of the document. The `metadata_columns`
+ are written into the `metadata` of the document. By default, all columns
+ are written into the `page_content` and none into the `metadata`.
+
+ """
+
+ def __init__(
+ self,
+ query: str,
+ host: str,
+ username: str,
+ password: str,
+ parameters: Optional[Dict[str, Any]] = None,
+ page_content_columns: Optional[List[str]] = None,
+ metadata_columns: Optional[List[str]] = None,
+ ):
+ """Initialize Kinetica document loader.
+
+ Args:
+ query: The query to run in Kinetica.
+ parameters: Optional. Parameters to pass to the query.
+ page_content_columns: Optional. Columns written to Document `page_content`.
+ metadata_columns: Optional. Columns written to Document `metadata`.
+ """
+ self.query = query
+ self.host = host
+ self.username = username
+ self.password = password
+ self.parameters = parameters
+ self.page_content_columns = page_content_columns
+ self.metadata_columns = metadata_columns if metadata_columns is not None else []
+
+ def _execute_query(self) -> List[Dict[str, Any]]:
+ try:
+ from gpudb import GPUdb, GPUdbSqlIterator
+ except ImportError:
+ raise ImportError(
+ "Could not import Kinetica python API. "
+ "Please install it with `pip install gpudb==7.2.0.9`."
+ )
+
+ try:
+ options = GPUdb.Options()
+ options.username = self.username
+ options.password = self.password
+
+ conn = GPUdb(host=self.host, options=options)
+
+ with GPUdbSqlIterator(conn, self.query) as records:
+ column_names = records.type_map.keys()
+ query_result = [dict(zip(column_names, record)) for record in records]
+
+ except Exception as e:
+ print(f"An error occurred: {e}") # noqa: T201
+ query_result = []
+
+ return query_result
+
+ def _get_columns(
+ self, query_result: List[Dict[str, Any]]
+ ) -> Tuple[List[str], List[str]]:
+ page_content_columns = (
+ self.page_content_columns if self.page_content_columns else []
+ )
+ metadata_columns = self.metadata_columns if self.metadata_columns else []
+ if page_content_columns is None and query_result:
+ page_content_columns = list(query_result[0].keys())
+ if metadata_columns is None:
+ metadata_columns = []
+ return page_content_columns or [], metadata_columns
+
+ def lazy_load(self) -> Iterator[Document]:
+ query_result = self._execute_query()
+ if isinstance(query_result, Exception):
+ print(f"An error occurred during the query: {query_result}") # noqa: T201
+ return []
+ page_content_columns, metadata_columns = self._get_columns(query_result)
+ if "*" in page_content_columns:
+ page_content_columns = list(query_result[0].keys())
+ for row in query_result:
+ page_content = "\n".join(
+ f"{k}: {v}" for k, v in row.items() if k in page_content_columns
+ )
+ metadata = {k: v for k, v in row.items() if k in metadata_columns}
+ doc = Document(page_content=page_content, metadata=metadata)
+ yield doc
+
+ def load(self) -> List[Document]:
+ """Load data into document objects."""
+ return list(self.lazy_load())
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/lakefs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/lakefs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca7d53c104a5ed170b3c674b17e7a784c3ee1f1f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/lakefs.py
@@ -0,0 +1,183 @@
+import os
+import tempfile
+import urllib.parse
+from typing import Any, List, Optional
+from urllib.parse import urljoin
+
+import requests
+from langchain_core.documents import Document
+from requests.auth import HTTPBasicAuth
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.unstructured import UnstructuredBaseLoader
+
+
+class LakeFSClient:
+ """Client for lakeFS."""
+
+ def __init__(
+ self,
+ lakefs_access_key: str,
+ lakefs_secret_key: str,
+ lakefs_endpoint: str,
+ ):
+ self.__endpoint = "/".join([lakefs_endpoint, "api", "v1/"])
+ self.__auth = HTTPBasicAuth(lakefs_access_key, lakefs_secret_key)
+ try:
+ health_check = requests.get(
+ urljoin(self.__endpoint, "healthcheck"), auth=self.__auth
+ )
+ health_check.raise_for_status()
+ except Exception:
+ raise ValueError(
+ "lakeFS server isn't accessible. Make sure lakeFS is running."
+ )
+
+ def ls_objects(
+ self, repo: str, ref: str, path: str, presign: Optional[bool]
+ ) -> List:
+ qp = {"prefix": path, "presign": presign}
+ eqp = urllib.parse.urlencode(qp)
+ objects_ls_endpoint = urljoin(
+ self.__endpoint, f"repositories/{repo}/refs/{ref}/objects/ls?{eqp}"
+ )
+ olsr = requests.get(objects_ls_endpoint, auth=self.__auth)
+ olsr.raise_for_status()
+ olsr_json = olsr.json()
+ return list(
+ map(
+ lambda res: (res["path"], res["physical_address"]), olsr_json["results"]
+ )
+ )
+
+ def is_presign_supported(self) -> bool:
+ config_endpoint = self.__endpoint + "config"
+ response = requests.get(config_endpoint, auth=self.__auth)
+ response.raise_for_status()
+ config = response.json()
+ return config["storage_config"]["pre_sign_support"]
+
+
+class LakeFSLoader(BaseLoader):
+ """Load from `lakeFS`."""
+
+ repo: str
+ ref: str
+ path: str
+
+ def __init__(
+ self,
+ lakefs_access_key: str,
+ lakefs_secret_key: str,
+ lakefs_endpoint: str,
+ repo: Optional[str] = None,
+ ref: Optional[str] = "main",
+ path: Optional[str] = "",
+ ):
+ """
+
+ :param lakefs_access_key: [required] lakeFS server's access key
+ :param lakefs_secret_key: [required] lakeFS server's secret key
+ :param lakefs_endpoint: [required] lakeFS server's endpoint address,
+ ex: https://example.my-lakefs.com
+ :param repo: [optional, default = ''] target repository
+ :param ref: [optional, default = 'main'] target ref (branch name,
+ tag, or commit ID)
+ :param path: [optional, default = ''] target path
+ """
+
+ self.__lakefs_client = LakeFSClient(
+ lakefs_access_key, lakefs_secret_key, lakefs_endpoint
+ )
+ self.repo = "" if repo is None or repo == "" else str(repo)
+ self.ref = "main" if ref is None or ref == "" else str(ref)
+ self.path = "" if path is None else str(path)
+
+ def set_path(self, path: str) -> None:
+ self.path = path
+
+ def set_ref(self, ref: str) -> None:
+ self.ref = ref
+
+ def set_repo(self, repo: str) -> None:
+ self.repo = repo
+
+ def load(self) -> List[Document]:
+ self.__validate_instance()
+ presigned = self.__lakefs_client.is_presign_supported()
+ docs: List[Document] = []
+ objs = self.__lakefs_client.ls_objects(
+ repo=self.repo, ref=self.ref, path=self.path, presign=presigned
+ )
+ for obj in objs:
+ lakefs_unstructured_loader = UnstructuredLakeFSLoader(
+ obj[1], self.repo, self.ref, obj[0], presigned
+ )
+ docs.extend(lakefs_unstructured_loader.load())
+ return docs
+
+ def __validate_instance(self) -> None:
+ if self.repo is None or self.repo == "":
+ raise ValueError(
+ "no repository was provided. use `set_repo` to specify a repository"
+ )
+ if self.ref is None or self.ref == "":
+ raise ValueError("no ref was provided. use `set_ref` to specify a ref")
+ if self.path is None:
+ raise ValueError("no path was provided. use `set_path` to specify a path")
+
+
+class UnstructuredLakeFSLoader(UnstructuredBaseLoader):
+ """Load from `lakeFS` as unstructured data."""
+
+ def __init__(
+ self,
+ url: str,
+ repo: str,
+ ref: str = "main",
+ path: str = "",
+ presign: bool = True,
+ **unstructured_kwargs: Any,
+ ):
+ """Initialize UnstructuredLakeFSLoader.
+
+ Args:
+
+ :param lakefs_access_key:
+ :param lakefs_secret_key:
+ :param lakefs_endpoint:
+ :param repo:
+ :param ref:
+ """
+
+ super().__init__(**unstructured_kwargs)
+ self.url = url
+ self.repo = repo
+ self.ref = ref
+ self.path = path
+ self.presign = presign
+
+ def _get_metadata(self) -> dict:
+ return {"repo": self.repo, "ref": self.ref, "path": self.path}
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.auto import partition
+
+ local_prefix = "local://"
+
+ if self.presign:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ file_path = f"{temp_dir}/{self.path.split('/')[-1]}"
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
+ response = requests.get(self.url)
+ response.raise_for_status()
+ with open(file_path, mode="wb") as file:
+ file.write(response.content)
+ return partition(filename=file_path)
+ elif not self.url.startswith(local_prefix):
+ raise ValueError(
+ "Non pre-signed URLs are supported only with 'local' blockstore"
+ )
+ else:
+ local_path = self.url[len(local_prefix) :]
+ return partition(filename=local_path)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/larksuite.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/larksuite.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae680ec2c63328a0cccc1106c2c5430123bcfec5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/larksuite.py
@@ -0,0 +1,78 @@
+import json
+import urllib.request
+from typing import Any, Iterator
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class LarkSuiteDocLoader(BaseLoader):
+ """Load from `LarkSuite` (`FeiShu`)."""
+
+ def __init__(self, domain: str, access_token: str, document_id: str):
+ """Initialize with domain, access_token (tenant / user), and document_id.
+
+ Args:
+ domain: The domain to load the LarkSuite.
+ access_token: The access_token to use.
+ document_id: The document_id to load.
+ """
+ self.domain = domain
+ self.access_token = access_token
+ self.document_id = document_id
+
+ def _get_larksuite_api_json_data(self, api_url: str) -> Any:
+ """Get LarkSuite (FeiShu) API response json data."""
+ headers = {"Authorization": f"Bearer {self.access_token}"}
+ request = urllib.request.Request(api_url, headers=headers)
+ with urllib.request.urlopen(request) as response:
+ json_data = json.loads(response.read().decode())
+ return json_data
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load LarkSuite (FeiShu) document."""
+ api_url_prefix = f"{self.domain}/open-apis/docx/v1/documents"
+ metadata_json = self._get_larksuite_api_json_data(
+ f"{api_url_prefix}/{self.document_id}"
+ )
+ raw_content_json = self._get_larksuite_api_json_data(
+ f"{api_url_prefix}/{self.document_id}/raw_content"
+ )
+ text = raw_content_json["data"]["content"]
+ metadata = {
+ "document_id": self.document_id,
+ "revision_id": metadata_json["data"]["document"]["revision_id"],
+ "title": metadata_json["data"]["document"]["title"],
+ }
+ yield Document(page_content=text, metadata=metadata)
+
+
+class LarkSuiteWikiLoader(LarkSuiteDocLoader):
+ """Load from `LarkSuite` (`FeiShu`) wiki."""
+
+ def __init__(self, domain: str, access_token: str, wiki_id: str):
+ """Initialize with domain, access_token (tenant / user), and wiki_id.
+
+ Args:
+ domain: The domain to load the LarkSuite.
+ access_token: The access_token to use.
+ wiki_id: The wiki_id to load.
+ """
+ self.domain = domain
+ self.access_token = access_token
+ self.wiki_id = wiki_id
+ self.document_id = ""
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load LarkSuite (FeiShu) wiki document."""
+
+ # convert Feishu wiki id to document id
+ if not self.document_id:
+ wiki_url_prefix = f"{self.domain}/open-apis/wiki/v2/spaces/get_node"
+ wiki_node_info_json = self._get_larksuite_api_json_data(
+ f"{wiki_url_prefix}?token={self.wiki_id}"
+ )
+ self.document_id = wiki_node_info_json["data"]["node"]["obj_token"]
+
+ yield from super().lazy_load()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/llmsherpa.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/llmsherpa.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c2e76758a0cc2b94c13f5546e872d0a7180d0e6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/llmsherpa.py
@@ -0,0 +1,142 @@
+from pathlib import Path
+from typing import Iterator, Union
+from urllib.parse import urlparse
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.pdf import BaseLoader
+
+DEFAULT_API = "https://readers.llmsherpa.com/api/document/developer/parseDocument?renderFormat=all"
+
+
+class LLMSherpaFileLoader(BaseLoader):
+ """Load Documents using `LLMSherpa`.
+
+ LLMSherpaFileLoader use LayoutPDFReader, which is part of the LLMSherpa library.
+ This tool is designed to parse PDFs while preserving their layout information,
+ which is often lost when using most PDF to text parsers.
+
+ Examples
+ --------
+ from langchain_community.document_loaders.llmsherpa import LLMSherpaFileLoader
+
+ loader = LLMSherpaFileLoader(
+ "example.pdf",
+ strategy="chunks",
+ llmsherpa_api_url="http://localhost:5010/api/parseDocument?renderFormat=all",
+ )
+ docs = loader.load()
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ new_indent_parser: bool = True,
+ apply_ocr: bool = True,
+ strategy: str = "chunks",
+ llmsherpa_api_url: str = DEFAULT_API,
+ ):
+ """Initialize with a file path."""
+ try:
+ import llmsherpa # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "llmsherpa package not found, please install it with "
+ "`pip install llmsherpa`"
+ )
+ _valid_strategies = ["sections", "chunks", "html", "text"]
+ if strategy not in _valid_strategies:
+ raise ValueError(
+ f"Got {strategy} for `strategy`, "
+ f"but should be one of `{_valid_strategies}`"
+ )
+ # validate llmsherpa url
+ if not self._is_valid_url(llmsherpa_api_url):
+ raise ValueError(f"Invalid URL: {llmsherpa_api_url}")
+ self.url = self._validate_llmsherpa_url(
+ url=llmsherpa_api_url,
+ new_indent_parser=new_indent_parser,
+ apply_ocr=apply_ocr,
+ )
+
+ self.strategy = strategy
+ self.file_path = str(file_path)
+
+ @staticmethod
+ def _is_valid_url(url: str) -> bool:
+ """Check if the url is valid."""
+ parsed = urlparse(url)
+ return bool(parsed.netloc) and bool(parsed.scheme)
+
+ @staticmethod
+ def _validate_llmsherpa_url(
+ url: str, new_indent_parser: bool = True, apply_ocr: bool = True
+ ) -> str:
+ """Check if the llmsherpa url is valid."""
+ parsed = urlparse(url)
+ valid_url = url
+ if ("/api/parseDocument" not in parsed.path) and (
+ "/api/document/developer/parseDocument" not in parsed.path
+ ):
+ raise ValueError(f"Invalid LLMSherpa URL: {url}")
+
+ if "renderFormat=all" not in parsed.query:
+ valid_url = valid_url + "?renderFormat=all"
+ if new_indent_parser and "useNewIndentParser=true" not in parsed.query:
+ valid_url = valid_url + "&useNewIndentParser=true"
+ if apply_ocr and "applyOcr=yes" not in parsed.query:
+ valid_url = valid_url + "&applyOcr=yes"
+
+ return valid_url
+
+ def lazy_load(
+ self,
+ ) -> Iterator[Document]:
+ """Load file."""
+ from llmsherpa.readers import LayoutPDFReader
+
+ docs_reader = LayoutPDFReader(self.url)
+ doc = docs_reader.read_pdf(self.file_path)
+
+ if self.strategy == "sections":
+ yield from [
+ Document(
+ page_content=section.to_text(include_children=True, recurse=True),
+ metadata={
+ "source": self.file_path,
+ "section_number": section_num,
+ "section_title": section.title,
+ },
+ )
+ for section_num, section in enumerate(doc.sections())
+ ]
+ if self.strategy == "chunks":
+ yield from [
+ Document(
+ page_content=chunk.to_context_text(),
+ metadata={
+ "source": self.file_path,
+ "chunk_number": chunk_num,
+ "chunk_type": chunk.tag,
+ },
+ )
+ for chunk_num, chunk in enumerate(doc.chunks())
+ ]
+ if self.strategy == "html":
+ yield from [
+ Document(
+ page_content=doc.to_html(),
+ metadata={
+ "source": self.file_path,
+ },
+ )
+ ]
+ if self.strategy == "text":
+ yield from [
+ Document(
+ page_content=doc.to_text(),
+ metadata={
+ "source": self.file_path,
+ },
+ )
+ ]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/markdown.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/markdown.py
new file mode 100644
index 0000000000000000000000000000000000000000..e940bff593de62d4fe6271b689112af5b4e627e5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/markdown.py
@@ -0,0 +1,96 @@
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ validate_unstructured_version,
+)
+
+
+class UnstructuredMarkdownLoader(UnstructuredFileLoader):
+ """Load `Markdown` files using `Unstructured`.
+
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Setup:
+ Install ``langchain-community``.
+
+ .. code-block:: bash
+
+ pip install -U langchain-community
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import UnstructuredMarkdownLoader
+
+ loader = UnstructuredMarkdownLoader(
+ "./example_data/example.md",
+ mode="elements",
+ strategy="fast",
+ )
+
+ Lazy load:
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ # async variant:
+ # docs_lazy = await loader.alazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Sample Markdown Document
+ {'source': './example_data/example.md', 'category_depth': 0, 'last_modified': '2024-08-14T15:04:18', 'languages': ['eng'], 'filetype': 'text/markdown', 'file_directory': './example_data', 'filename': 'example.md', 'category': 'Title', 'element_id': '3d0b313864598e704aa26c728ecb61e5'}
+
+
+ Async load:
+ .. code-block:: python
+
+ docs = await loader.aload()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Sample Markdown Document
+ {'source': './example_data/example.md', 'category_depth': 0, 'last_modified': '2024-08-14T15:04:18', 'languages': ['eng'], 'filetype': 'text/markdown', 'file_directory': './example_data', 'filename': 'example.md', 'category': 'Title', 'element_id': '3d0b313864598e704aa26c728ecb61e5'}
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/core/partition.html#partition-md
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+
+ Args:
+ file_path: The path to the Markdown file to load.
+ mode: The mode to use when loading the file. Can be one of "single",
+ "multi", or "all". Default is "single".
+ **unstructured_kwargs: Any kwargs to pass to the unstructured.
+ """
+ file_path = str(file_path)
+ validate_unstructured_version("0.4.16")
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.md import partition_md
+
+ return partition_md(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mastodon.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mastodon.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a757620acb367004c8b7ee1abb63246850b68db
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mastodon.py
@@ -0,0 +1,96 @@
+from __future__ import annotations
+
+import os
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ Iterable,
+ Iterator,
+ List,
+ Optional,
+ Sequence,
+)
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+if TYPE_CHECKING:
+ import mastodon
+
+
+def _dependable_mastodon_import() -> mastodon:
+ try:
+ import mastodon
+ except ImportError:
+ raise ImportError(
+ "Mastodon.py package not found, "
+ "please install it with `pip install Mastodon.py`"
+ )
+ return mastodon
+
+
+class MastodonTootsLoader(BaseLoader):
+ """Load the `Mastodon` 'toots'."""
+
+ def __init__(
+ self,
+ mastodon_accounts: Sequence[str],
+ number_toots: Optional[int] = 100,
+ exclude_replies: bool = False,
+ access_token: Optional[str] = None,
+ api_base_url: str = "https://mastodon.social",
+ ):
+ """Instantiate Mastodon toots loader.
+
+ Args:
+ mastodon_accounts: The list of Mastodon accounts to query.
+ number_toots: How many toots to pull for each account. Defaults to 100.
+ exclude_replies: Whether to exclude reply toots from the load.
+ Defaults to False.
+ access_token: An access token if toots are loaded as a Mastodon app. Can
+ also be specified via the environment variables "MASTODON_ACCESS_TOKEN".
+ api_base_url: A Mastodon API base URL to talk to, if not using the default.
+ Defaults to "https://mastodon.social".
+ """
+ mastodon = _dependable_mastodon_import()
+ access_token = access_token or os.environ.get("MASTODON_ACCESS_TOKEN")
+ self.api = mastodon.Mastodon(
+ access_token=access_token, api_base_url=api_base_url
+ )
+ self.mastodon_accounts = mastodon_accounts
+ self.number_toots = number_toots
+ self.exclude_replies = exclude_replies
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load toots into documents."""
+ for account in self.mastodon_accounts:
+ user = self.api.account_lookup(account)
+ toots = self.api.account_statuses(
+ user.id,
+ only_media=False,
+ pinned=False,
+ exclude_replies=self.exclude_replies,
+ exclude_reblogs=True,
+ limit=self.number_toots,
+ )
+ yield from self._format_toots(toots, user)
+
+ def _format_toots(
+ self, toots: List[Dict[str, Any]], user_info: dict
+ ) -> Iterable[Document]:
+ """Format toots into documents.
+
+ Adding user info, and selected toot fields into the metadata.
+ """
+ for toot in toots:
+ metadata = {
+ "created_at": toot["created_at"],
+ "user_info": user_info,
+ "is_reply": toot["in_reply_to_id"] is not None,
+ }
+ yield Document(
+ page_content=toot["content"],
+ metadata=metadata,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/max_compute.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/max_compute.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b507da89c94e3c25fce867c9a69ff256d1b9c4d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/max_compute.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+from typing import Any, Iterator, Optional, Sequence
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.max_compute import MaxComputeAPIWrapper
+
+
+class MaxComputeLoader(BaseLoader):
+ """Load from `Alibaba Cloud MaxCompute` table."""
+
+ def __init__(
+ self,
+ query: str,
+ api_wrapper: MaxComputeAPIWrapper,
+ *,
+ page_content_columns: Optional[Sequence[str]] = None,
+ metadata_columns: Optional[Sequence[str]] = None,
+ ):
+ """Initialize Alibaba Cloud MaxCompute document loader.
+
+ Args:
+ query: SQL query to execute.
+ api_wrapper: MaxCompute API wrapper.
+ page_content_columns: The columns to write into the `page_content` of the
+ Document. If unspecified, all columns will be written to `page_content`.
+ metadata_columns: The columns to write into the `metadata` of the Document.
+ If unspecified, all columns not added to `page_content` will be written.
+ """
+ self.query = query
+ self.api_wrapper = api_wrapper
+ self.page_content_columns = page_content_columns
+ self.metadata_columns = metadata_columns
+
+ @classmethod
+ def from_params(
+ cls,
+ query: str,
+ endpoint: str,
+ project: str,
+ *,
+ access_id: Optional[str] = None,
+ secret_access_key: Optional[str] = None,
+ **kwargs: Any,
+ ) -> MaxComputeLoader:
+ """Convenience constructor that builds the MaxCompute API wrapper from
+ given parameters.
+
+ Args:
+ query: SQL query to execute.
+ endpoint: MaxCompute endpoint.
+ project: A project is a basic organizational unit of MaxCompute, which is
+ similar to a database.
+ access_id: MaxCompute access ID. Should be passed in directly or set as the
+ environment variable `MAX_COMPUTE_ACCESS_ID`.
+ secret_access_key: MaxCompute secret access key. Should be passed in
+ directly or set as the environment variable
+ `MAX_COMPUTE_SECRET_ACCESS_KEY`.
+ """
+ api_wrapper = MaxComputeAPIWrapper.from_params(
+ endpoint, project, access_id=access_id, secret_access_key=secret_access_key
+ )
+ return cls(query, api_wrapper, **kwargs)
+
+ def lazy_load(self) -> Iterator[Document]:
+ for row in self.api_wrapper.query(self.query):
+ if self.page_content_columns:
+ page_content_data = {
+ k: v for k, v in row.items() if k in self.page_content_columns
+ }
+ else:
+ page_content_data = row
+ page_content = "\n".join(f"{k}: {v}" for k, v in page_content_data.items())
+ if self.metadata_columns:
+ metadata = {k: v for k, v in row.items() if k in self.metadata_columns}
+ else:
+ metadata = {k: v for k, v in row.items() if k not in page_content_data}
+ yield Document(page_content=page_content, metadata=metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mediawikidump.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mediawikidump.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc082228b922bf60ab462cc48af6e9b2b2ce442a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mediawikidump.py
@@ -0,0 +1,112 @@
+import logging
+from pathlib import Path
+from typing import TYPE_CHECKING, Iterator, Optional, Sequence, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+if TYPE_CHECKING:
+ import mwxml
+
+
+class MWDumpLoader(BaseLoader):
+ """Load `MediaWiki` dump from an `XML` file.
+
+ Example:
+ .. code-block:: python
+
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
+ from langchain_community.document_loaders import MWDumpLoader
+
+ loader = MWDumpLoader(
+ file_path="myWiki.xml",
+ encoding="utf8"
+ )
+ docs = loader.load()
+ text_splitter = RecursiveCharacterTextSplitter(
+ chunk_size=1000, chunk_overlap=0
+ )
+ texts = text_splitter.split_documents(docs)
+
+
+ :param file_path: XML local file path
+ :type file_path: str
+ :param encoding: Charset encoding, defaults to "utf8"
+ :type encoding: str, optional
+ :param namespaces: The namespace of pages you want to parse.
+ See https://www.mediawiki.org/wiki/Help:Namespaces#Localisation
+ for a list of all common namespaces
+ :type namespaces: List[int],optional
+ :param skip_redirects: TR=rue to skip pages that redirect to other pages,
+ False to keep them. False by default
+ :type skip_redirects: bool, optional
+ :param stop_on_error: False to skip over pages that cause parsing errors,
+ True to stop. True by default
+ :type stop_on_error: bool, optional
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ encoding: Optional[str] = "utf8",
+ namespaces: Optional[Sequence[int]] = None,
+ skip_redirects: Optional[bool] = False,
+ stop_on_error: Optional[bool] = True,
+ ):
+ self.file_path = file_path if isinstance(file_path, str) else str(file_path)
+ self.encoding = encoding
+ # Namespaces range from -2 to 15, inclusive.
+ self.namespaces = namespaces
+ self.skip_redirects = skip_redirects
+ self.stop_on_error = stop_on_error
+
+ def _load_dump_file(self) -> "mwxml.Dump":
+ try:
+ import mwxml
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import 'mwxml'. Please install with `pip install mwxml`."
+ ) from e
+
+ return mwxml.Dump.from_file(open(self.file_path, encoding=self.encoding))
+
+ def _load_single_page_from_dump(self, page: "mwxml.Page") -> Document: # type: ignore[return]
+ """Parse a single page."""
+ try:
+ import mwparserfromhell
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import 'mwparserfromhell'. Please install with"
+ " `pip install mwparserfromhell`."
+ ) from e
+ for revision in page:
+ code = mwparserfromhell.parse(revision.text)
+ text = code.strip_code(
+ normalize=True, collapse=True, keep_template_params=False
+ )
+ metadata = {"source": page.title}
+ return Document(page_content=text, metadata=metadata)
+
+ def lazy_load(
+ self,
+ ) -> Iterator[Document]:
+ """Lazy load from a file path."""
+
+ dump = self._load_dump_file()
+
+ for page in dump.pages:
+ if self.skip_redirects and page.redirect:
+ continue
+ if self.namespaces and page.namespace not in self.namespaces:
+ continue
+ try:
+ yield self._load_single_page_from_dump(page)
+ except Exception as e:
+ logger.error("Parsing error: {}".format(e))
+ if self.stop_on_error:
+ raise e
+ else:
+ continue
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/merge.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/merge.py
new file mode 100644
index 0000000000000000000000000000000000000000..41f79e53f41043e006882cb924ce17f9db4f6f8d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/merge.py
@@ -0,0 +1,30 @@
+from typing import AsyncIterator, Iterator, List
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class MergedDataLoader(BaseLoader):
+ """Merge documents from a list of loaders"""
+
+ def __init__(self, loaders: List):
+ """Initialize with a list of loaders"""
+ self.loaders = loaders
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load docs from each individual loader."""
+ for loader in self.loaders:
+ # Check if lazy_load is implemented
+ try:
+ data = loader.lazy_load()
+ except NotImplementedError:
+ data = loader.load()
+ for document in data:
+ yield document
+
+ async def alazy_load(self) -> AsyncIterator[Document]:
+ """Lazy load docs from each individual loader."""
+ for loader in self.loaders:
+ async for document in loader.alazy_load():
+ yield document
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mhtml.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mhtml.py
new file mode 100644
index 0000000000000000000000000000000000000000..809f46c031a18f521bac1c34fe6d8d9f354e8c36
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mhtml.py
@@ -0,0 +1,77 @@
+import email
+import logging
+from pathlib import Path
+from typing import Dict, Iterator, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+
+class MHTMLLoader(BaseLoader):
+ """Parse `MHTML` files with `BeautifulSoup`."""
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ open_encoding: Union[str, None] = None,
+ bs_kwargs: Union[dict, None] = None,
+ get_text_separator: str = "",
+ ) -> None:
+ """initialize with path, and optionally, file encoding to use, and any kwargs
+ to pass to the BeautifulSoup object.
+
+ Args:
+ file_path: Path to file to load.
+ open_encoding: The encoding to use when opening the file.
+ bs_kwargs: Any kwargs to pass to the BeautifulSoup object.
+ get_text_separator: The separator to use when getting the text
+ from the soup.
+ """
+ try:
+ import bs4 # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "beautifulsoup4 package not found, please install it with "
+ "`pip install beautifulsoup4`"
+ )
+
+ self.file_path = file_path
+ self.open_encoding = open_encoding
+ if bs_kwargs is None:
+ bs_kwargs = {"features": "lxml"}
+ self.bs_kwargs = bs_kwargs
+ self.get_text_separator = get_text_separator
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load MHTML document into document objects."""
+
+ from bs4 import BeautifulSoup
+
+ with open(self.file_path, "r", encoding=self.open_encoding) as f:
+ message = email.message_from_string(f.read())
+ parts = message.get_payload()
+
+ if not isinstance(parts, list):
+ parts = [message]
+
+ for part in parts:
+ if part.get_content_type() == "text/html": # type: ignore[union-attr]
+ html = part.get_payload(decode=True).decode() # type: ignore[union-attr]
+
+ soup = BeautifulSoup(html, **self.bs_kwargs)
+ text = soup.get_text(self.get_text_separator)
+
+ if soup.title:
+ title = str(soup.title.string)
+ else:
+ title = ""
+
+ metadata: Dict[str, Union[str, None]] = {
+ "source": str(self.file_path),
+ "title": title,
+ }
+ yield Document(page_content=text, metadata=metadata)
+ return
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mintbase.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mintbase.py
new file mode 100644
index 0000000000000000000000000000000000000000..18e6f4016633a6682d4d098e2c308969feecbef5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mintbase.py
@@ -0,0 +1,264 @@
+import json
+import os
+import re
+import time
+from typing import Iterator, List, Literal, Optional
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class MintbaseDocumentLoader(BaseLoader):
+ """Load elements from a blockchain smart contract.
+
+ The supported blockchains are: Near mainnet, Near testnet.
+
+ If no BlockchainType is specified, the default is Near mainnet.
+
+ The Loader uses the Mintbase API to interact with the blockchain.
+ MB_API_KEY environment variable must be set to use this loader.
+
+ The API returns 100 NFTs per request and can be paginated using the
+ startToken parameter.
+
+ If get_all_tokens is set to True, the loader will get all tokens
+ on the contract. Note that for contracts with a large number of tokens,
+ this may take a long time (e.g. 10k tokens is 100 requests).
+ Default value is false for this reason.
+
+ The max_execution_time (sec) can be set to limit the execution time
+ of the loader.
+
+ Future versions of this loader can:
+ - Support additional Mintbase APIs (e.g. getTokens, etc.)
+
+ Example:
+ .. code-block:: python
+
+ contractAddress = "nft.yearofchef.near" # Year of chef contract address
+ blockchainLoader = MintbaseDocumentLoader(
+ contract_address=contractAddress, blockchain_type="mainnet",api_key="omni-site"
+ )
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ contract_address: str,
+ *,
+ blockchain_type: Literal["mainnet", "testnet"],
+ api_key: str = "",
+ table: str = "",
+ select: str = "",
+ fields: Optional[List[str]] = None,
+ get_all_tokens: bool = False,
+ max_execution_time: Optional[int] = None,
+ ):
+ """
+
+ Args:
+ contract_address: The address of the smart contract.
+ blockchainType: The blockchain type.
+ api_key: The Mintbase API key.
+ table: name of the table to query
+ select: Conditions for querying
+ fields: Information to display after query
+ get_all_tokens: Whether to get all tokens on the contract.
+ max_execution_time: The maximum execution time (sec).
+ """
+ self.contract_address = contract_address
+ self.blockchainType = blockchain_type
+ self.api_key = os.environ.get("MB_API_KEY") or api_key
+ self.table = "mb_views_nft_tokens" or table
+ self.select = 'where: {nft_contract_id: {_eq: "contract_address"}}' or select
+ self.fields = fields or [
+ "base_uri",
+ "burned_receipt_id",
+ "burned_timestamp",
+ "copies",
+ "description",
+ "expires_at",
+ "extra",
+ "issued_at",
+ "last_transfer_receipt_id",
+ "last_transfer_timestamp",
+ "media",
+ "media_hash",
+ "metadata_content_flag",
+ "metadata_id",
+ "mint_memo",
+ "minted_receipt_id",
+ "minted_timestamp",
+ "minter",
+ "nft_contract_content_flag",
+ "nft_contract_created_at",
+ "nft_contract_icon",
+ "nft_contract_id",
+ "nft_contract_is_mintbase",
+ "nft_contract_name",
+ "nft_contract_owner_id",
+ "nft_contract_reference",
+ "nft_contract_spec",
+ "nft_contract_symbol",
+ "owner",
+ "reference",
+ "reference_blob",
+ "reference_hash",
+ "royalties",
+ "royalties_percent",
+ "splits",
+ "starts_at",
+ "title",
+ "token_id",
+ "updated_at",
+ ]
+
+ self.get_all_tokens = get_all_tokens
+ self.max_execution_time = max_execution_time
+
+ if not self.api_key:
+ raise ValueError("Mintbase API key not provided.")
+
+ if not re.match(
+ r"^(([a-z\d]+[\-_])*[a-z\d]+\.)*([a-z\d]+[\-_])*[a-z\d]+$",
+ self.contract_address,
+ ):
+ raise ValueError(f"Invalid contract address {self.contract_address}")
+
+ def load(self) -> List[Document]:
+ result = []
+
+ start_time = time.time()
+
+ while True:
+ # Define the GraphQL query as a multi-line string
+ operations_doc = """
+ query MyQuery {
+ table(select) {
+ fields
+ }
+ }
+ """
+
+ # Replace the placeholder with the actual contract address
+ operations_doc = operations_doc.replace("select", self.select)
+ operations_doc = operations_doc.replace(
+ "contract_address", self.contract_address
+ )
+ operations_doc = operations_doc.replace("table", self.table)
+ operations_doc = operations_doc.replace("fields", "\n".join(self.fields))
+
+ # Define the headers
+ headers = {"mb-api-key": self.api_key, "Content-Type": "application/json"}
+ # Define the POST data
+ data = {
+ "query": operations_doc,
+ "variables": {},
+ "operationName": "MyQuery",
+ }
+
+ url = f"https://graph.mintbase.xyz/{self.blockchainType}"
+
+ response = requests.post(url, headers=headers, data=json.dumps(data))
+
+ if response.status_code != 200:
+ raise ValueError(
+ f"Request failed with status code {response.status_code}"
+ )
+
+ items = response.json()["data"]["mb_views_nft_tokens"]
+
+ if not items:
+ break
+
+ for item in items:
+ content = str(item)
+ token_id = item["token_id"]
+ metadata = {
+ "source": self.contract_address,
+ "blockchain": self.blockchainType,
+ "tokenId": token_id,
+ }
+ result.append(Document(page_content=content, metadata=metadata))
+
+ # exit after the first API call if get_all_tokens is False
+ if not self.get_all_tokens:
+ break
+
+ if (
+ self.max_execution_time is not None
+ and (time.time() - start_time) > self.max_execution_time
+ ):
+ raise RuntimeError("Execution time exceeded the allowed time limit.")
+
+ if not result:
+ raise ValueError(
+ f"No NFTs found for contract address {self.contract_address}"
+ )
+
+ return result
+
+ def lazy_load(self) -> Iterator[Document]:
+ start_time = time.time()
+
+ while True:
+ # Define the GraphQL query as a multi-line string
+ operations_doc = """
+ query MyQuery {
+ table(select) {
+ fields
+ }
+ }
+ """
+
+ # Replace the placeholder with the actual contract address
+ operations_doc = operations_doc.replace("select", self.select)
+ operations_doc = operations_doc.replace(
+ "contract_address", self.contract_address
+ )
+ operations_doc = operations_doc.replace("table", self.table)
+ operations_doc = operations_doc.replace("fields", "\n".join(self.fields))
+
+ # Define the headers
+ headers = {"mb-api-key": self.api_key, "Content-Type": "application/json"}
+ # Define the POST data
+ data = {
+ "query": operations_doc,
+ "variables": {},
+ "operationName": "MyQuery",
+ }
+
+ url = f"https://graph.mintbase.xyz/{self.blockchainType}"
+
+ response = requests.post(url, headers=headers, data=json.dumps(data))
+
+ if response.status_code != 200:
+ raise ValueError(
+ f"Request failed with status code {response.status_code}"
+ )
+
+ items = response.json()["data"]["mb_views_nft_tokens"]
+
+ if not items:
+ break
+
+ for item in items:
+ content = str(item)
+ tokenId = item["token_id"]
+ metadata = {
+ "source": self.contract_address,
+ "blockchain": self.blockchainType,
+ "tokenId": tokenId,
+ }
+ yield Document(page_content=content, metadata=metadata)
+
+ # exit after the first API call if get_all_tokens is False
+ if not self.get_all_tokens:
+ break
+
+ if (
+ self.max_execution_time is not None
+ and (time.time() - start_time) > self.max_execution_time
+ ):
+ raise RuntimeError("Execution time exceeded the allowed time limit.")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/modern_treasury.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/modern_treasury.py
new file mode 100644
index 0000000000000000000000000000000000000000..045a2e786edf133d751c46240059dba47d635fa0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/modern_treasury.py
@@ -0,0 +1,73 @@
+import json
+import urllib.request
+from base64 import b64encode
+from typing import List, Optional
+
+from langchain_core.documents import Document
+from langchain_core.utils import get_from_env, stringify_value
+
+from langchain_community.document_loaders.base import BaseLoader
+
+MODERN_TREASURY_ENDPOINTS = {
+ "payment_orders": "https://app.moderntreasury.com/api/payment_orders",
+ "expected_payments": "https://app.moderntreasury.com/api/expected_payments",
+ "returns": "https://app.moderntreasury.com/api/returns",
+ "incoming_payment_details": "https://app.moderntreasury.com/api/\
+incoming_payment_details",
+ "counterparties": "https://app.moderntreasury.com/api/counterparties",
+ "internal_accounts": "https://app.moderntreasury.com/api/internal_accounts",
+ "external_accounts": "https://app.moderntreasury.com/api/external_accounts",
+ "transactions": "https://app.moderntreasury.com/api/transactions",
+ "ledgers": "https://app.moderntreasury.com/api/ledgers",
+ "ledger_accounts": "https://app.moderntreasury.com/api/ledger_accounts",
+ "ledger_transactions": "https://app.moderntreasury.com/api/ledger_transactions",
+ "events": "https://app.moderntreasury.com/api/events",
+ "invoices": "https://app.moderntreasury.com/api/invoices",
+}
+
+
+class ModernTreasuryLoader(BaseLoader):
+ """Load from `Modern Treasury`."""
+
+ def __init__(
+ self,
+ resource: str,
+ organization_id: Optional[str] = None,
+ api_key: Optional[str] = None,
+ ) -> None:
+ """
+
+ Args:
+ resource: The Modern Treasury resource to load.
+ organization_id: The Modern Treasury organization ID. It can also be
+ specified via the environment variable
+ "MODERN_TREASURY_ORGANIZATION_ID".
+ api_key: The Modern Treasury API key. It can also be specified via
+ the environment variable "MODERN_TREASURY_API_KEY".
+ """
+ self.resource = resource
+ organization_id = organization_id or get_from_env(
+ "organization_id", "MODERN_TREASURY_ORGANIZATION_ID"
+ )
+ api_key = api_key or get_from_env("api_key", "MODERN_TREASURY_API_KEY")
+ credentials = f"{organization_id}:{api_key}".encode("utf-8")
+ basic_auth_token = b64encode(credentials).decode("utf-8")
+ self.headers = {"Authorization": f"Basic {basic_auth_token}"}
+
+ def _make_request(self, url: str) -> List[Document]:
+ request = urllib.request.Request(url, headers=self.headers)
+
+ with urllib.request.urlopen(request) as response:
+ json_data = json.loads(response.read().decode())
+ text = stringify_value(json_data)
+ metadata = {"source": url}
+ return [Document(page_content=text, metadata=metadata)]
+
+ def _get_resource(self) -> List[Document]:
+ endpoint = MODERN_TREASURY_ENDPOINTS.get(self.resource)
+ if endpoint is None:
+ return []
+ return self._make_request(endpoint)
+
+ def load(self) -> List[Document]:
+ return self._get_resource()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mongodb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mongodb.py
new file mode 100644
index 0000000000000000000000000000000000000000..55d17f2876fce8092139d1eb795cd858d32949f9
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/mongodb.py
@@ -0,0 +1,198 @@
+import asyncio
+import logging
+from typing import AsyncIterator, Dict, Iterator, List, Optional, Sequence
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+
+class MongodbLoader(BaseLoader):
+ """Load MongoDB documents."""
+
+ def __init__(
+ self,
+ connection_string: str,
+ db_name: str,
+ collection_name: str,
+ *,
+ filter_criteria: Optional[Dict] = None,
+ field_names: Optional[Sequence[str]] = None,
+ metadata_names: Optional[Sequence[str]] = None,
+ include_db_collection_in_metadata: bool = True,
+ ) -> None:
+ """
+ Initializes the MongoDB loader with necessary database connection
+ details and configurations.
+
+ Args:
+ connection_string (str): MongoDB connection URI.
+ db_name (str):Name of the database to connect to.
+ collection_name (str): Name of the collection to fetch documents from.
+ filter_criteria (Optional[Dict]): MongoDB filter criteria for querying
+ documents.
+ field_names (Optional[Sequence[str]]): List of field names to retrieve
+ from documents.
+ metadata_names (Optional[Sequence[str]]): Additional metadata fields to
+ extract from documents.
+ include_db_collection_in_metadata (bool): Flag to include database and
+ collection names in metadata.
+
+ Raises:
+ ImportError: If the motor library is not installed.
+ ValueError: If any necessary argument is missing.
+ """
+ try:
+ from motor.motor_asyncio import AsyncIOMotorClient
+ except ImportError as e:
+ raise ImportError(
+ "Cannot import from motor, please install with `pip install motor`."
+ ) from e
+
+ if not connection_string:
+ raise ValueError("connection_string must be provided.")
+
+ if not db_name:
+ raise ValueError("db_name must be provided.")
+
+ if not collection_name:
+ raise ValueError("collection_name must be provided.")
+
+ self.client = AsyncIOMotorClient(connection_string)
+ self.db_name = db_name
+ self.collection_name = collection_name
+ self.field_names = field_names or []
+ self.filter_criteria = filter_criteria or {}
+ self.metadata_names = metadata_names or []
+ self.include_db_collection_in_metadata = include_db_collection_in_metadata
+
+ self.db = self.client.get_database(db_name)
+ self.collection = self.db.get_collection(collection_name)
+
+ def load(self) -> List[Document]:
+ """Load data into Document objects.
+
+ Attention:
+
+ This implementation starts an asyncio event loop which
+ will only work if running in a sync env. In an async env, it should
+ fail since there is already an event loop running.
+
+ This code should be updated to kick off the event loop from a separate
+ thread if running within an async context.
+ """
+ return asyncio.run(self.aload())
+
+ def lazy_load(self) -> Iterator[Document]:
+ """A lazy loader for MongoDB documents.
+
+ Attention:
+
+ This implementation starts an asyncio event loop which
+ will only work if running in a sync env. In an async env, it should
+ fail since there is already an event loop running.
+
+ This code should be updated to kick off the event loop from a separate
+ thread if running within an async context.
+
+ Yields:
+ Document: A document from the MongoDB collection.
+ """
+ try:
+ event_loop = asyncio.get_running_loop()
+ except RuntimeError:
+ event_loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(event_loop)
+
+ async_generator = self.alazy_load()
+
+ while True:
+ try:
+ document = event_loop.run_until_complete(async_generator.__anext__())
+ yield document
+ except StopAsyncIteration:
+ break
+
+ async def alazy_load(self) -> AsyncIterator[Document]:
+ """Asynchronously yields Document objects one at a time.
+
+ Yields:
+ Document: A document from the MongoDB collection.
+ """
+ projection = self._construct_projection()
+
+ async for doc in self.collection.find(self.filter_criteria, projection):
+ yield self._process_document(doc)
+
+ async def aload(self) -> List[Document]:
+ """Asynchronously loads data into Document objects."""
+ result = []
+ total_docs = await self.collection.count_documents(self.filter_criteria)
+
+ projection = self._construct_projection()
+
+ async for doc in self.collection.find(self.filter_criteria, projection):
+ result.append(self._process_document(doc))
+
+ if len(result) != total_docs:
+ logger.warning(
+ f"Only partial collection of documents returned. "
+ f"Loaded {len(result)} docs, expected {total_docs}."
+ )
+
+ return result
+
+ def _process_document(self, doc: Dict) -> Document:
+ """Process a single MongoDB document into a Document object.
+
+ Args:
+ doc: The MongoDB document dictionary to process into a Document object.
+ """
+ metadata = self._extract_fields(doc, self.metadata_names, default="")
+
+ # Optionally add database and collection names to metadata
+ if self.include_db_collection_in_metadata:
+ metadata.update(
+ {
+ "database": self.db_name,
+ "collection": self.collection_name,
+ }
+ )
+
+ # Extract text content from filtered fields or use the entire document
+ if self.field_names is not None:
+ fields = self._extract_fields(doc, self.field_names, default="")
+ texts = [str(value) for value in fields.values()]
+ text = " ".join(texts)
+ else:
+ text = str(doc)
+
+ return Document(page_content=text, metadata=metadata)
+
+ def _construct_projection(self) -> Optional[Dict]:
+ """Constructs the projection dictionary for MongoDB query based
+ on the specified field names and metadata names."""
+ field_names = list(self.field_names) or []
+ metadata_names = list(self.metadata_names) or []
+ all_fields = field_names + metadata_names
+ return {field: 1 for field in all_fields} if all_fields else None
+
+ def _extract_fields(
+ self,
+ document: Dict,
+ fields: Sequence[str],
+ default: str = "",
+ ) -> Dict:
+ """Extracts and returns values for specified fields from a document."""
+ extracted = {}
+ for field in fields or []:
+ value = document
+ for key in field.split("."):
+ value = value.get(key, default)
+ if value == default:
+ break
+ new_field_name = field.replace(".", "_")
+ extracted[new_field_name] = value
+ return extracted
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/needle.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/needle.py
new file mode 100644
index 0000000000000000000000000000000000000000..03b9ee0c0e01e1f4b43d57b62a632d8a6bb5261f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/needle.py
@@ -0,0 +1,164 @@
+from typing import Dict, Iterator, List, Optional
+
+from langchain_core.document_loaders.base import BaseLoader
+from langchain_core.documents import Document
+
+
+class NeedleLoader(BaseLoader):
+ """
+ NeedleLoader is a document loader for managing documents stored in a collection.
+
+ Setup:
+ Install the `needle-python` library and set your Needle API key.
+
+ .. code-block:: bash
+
+ pip install needle-python
+ export NEEDLE_API_KEY="your-api-key"
+
+ Key init args:
+ - `needle_api_key` (Optional[str]): API key for authenticating with Needle.
+ - `collection_id` (str): Needle collection to load documents from.
+
+ Usage:
+ .. code-block:: python
+
+ from langchain_community.document_loaders.needle import NeedleLoader
+
+ loader = NeedleLoader(
+ needle_api_key="your-api-key",
+ collection_id="your-collection-id"
+ )
+
+ # Load documents
+ documents = loader.load()
+ for doc in documents:
+ print(doc.metadata)
+
+ # Lazy load documents
+ for doc in loader.lazy_load():
+ print(doc.metadata)
+ """
+
+ def __init__(
+ self,
+ needle_api_key: Optional[str] = None,
+ collection_id: Optional[str] = None,
+ ) -> None:
+ """
+ Initializes the NeedleLoader with API key and collection ID.
+
+ Args:
+ needle_api_key (Optional[str]): API key for authenticating with Needle.
+ collection_id (Optional[str]): Identifier for the Needle collection.
+
+ Raises:
+ ImportError: If the `needle-python` library is not installed.
+ ValueError: If the collection ID is not provided.
+ """
+ try:
+ from needle.v1 import NeedleClient
+ except ImportError:
+ raise ImportError(
+ "Please install with `pip install needle-python` to use NeedleLoader."
+ )
+
+ super().__init__()
+ self.needle_api_key = needle_api_key
+ self.collection_id = collection_id
+ self.client: Optional[NeedleClient] = None
+
+ if self.needle_api_key:
+ self.client = NeedleClient(api_key=self.needle_api_key)
+
+ if not self.collection_id:
+ raise ValueError("Collection ID must be provided.")
+
+ def _get_collection(self) -> None:
+ """
+ Ensures the Needle collection is set and the client is initialized.
+
+ Raises:
+ ValueError: If the Needle client is not initialized or
+ if the collection ID is missing.
+ """
+ if self.client is None:
+ raise ValueError(
+ "NeedleClient is not initialized. Provide a valid API key."
+ )
+ if not self.collection_id:
+ raise ValueError("Collection ID must be provided.")
+
+ def add_files(self, files: Dict[str, str]) -> None:
+ """
+ Adds files to the Needle collection.
+
+ Args:
+ files (Dict[str, str]): Dictionary where keys are file names and values
+ are file URLs.
+
+ Raises:
+ ImportError: If the `needle-python` library is not installed.
+ ValueError: If the collection is not properly initialized.
+ """
+ try:
+ from needle.v1.models import FileToAdd
+ except ImportError:
+ raise ImportError(
+ "Please install with `pip install needle-python` to add files."
+ )
+
+ self._get_collection()
+ assert self.client is not None, "NeedleClient must be initialized."
+
+ files_to_add = [FileToAdd(name=name, url=url) for name, url in files.items()]
+
+ self.client.collections.files.add(
+ collection_id=self.collection_id, files=files_to_add
+ )
+
+ def _fetch_documents(self) -> List[Document]:
+ """
+ Fetches metadata for documents from the Needle collection.
+
+ Returns:
+ List[Document]: A list of documents with metadata. Content is excluded.
+
+ Raises:
+ ValueError: If the collection is not properly initialized.
+ """
+ self._get_collection()
+ assert self.client is not None, "NeedleClient must be initialized."
+
+ files = self.client.collections.files.list(self.collection_id)
+ docs = [
+ Document(
+ page_content="", # Needle doesn't provide file content fetching
+ metadata={
+ "source": file.url,
+ "title": file.name,
+ "size": getattr(file, "size", None),
+ },
+ )
+ for file in files
+ if file.status == "indexed"
+ ]
+ return docs
+
+ def load(self) -> List[Document]:
+ """
+ Loads all documents from the Needle collection.
+
+ Returns:
+ List[Document]: A list of documents from the collection.
+ """
+ return self._fetch_documents()
+
+ def lazy_load(self) -> Iterator[Document]:
+ """
+ Lazily loads documents from the Needle collection.
+
+ Yields:
+ Iterator[Document]: An iterator over the documents.
+ """
+ yield from self._fetch_documents()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/news.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/news.py
new file mode 100644
index 0000000000000000000000000000000000000000..33d3681bc79714bd4471c509f0786a2c29f71ce3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/news.py
@@ -0,0 +1,126 @@
+"""Loader that uses unstructured to load HTML files."""
+
+import logging
+from typing import Any, Iterator, List
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+
+class NewsURLLoader(BaseLoader):
+ """Load news articles from URLs using `Unstructured`.
+
+ Args:
+ urls: URLs to load. Each is loaded into its own document.
+ text_mode: If True, extract text from URL and use that for page content.
+ Otherwise, extract raw HTML.
+ nlp: If True, perform NLP on the extracted contents, like providing a summary
+ and extracting keywords.
+ continue_on_failure: If True, continue loading documents even if
+ loading fails for a particular URL.
+ show_progress_bar: If True, use tqdm to show a loading progress bar. Requires
+ tqdm to be installed, ``pip install tqdm``.
+ **newspaper_kwargs: Any additional named arguments to pass to
+ newspaper.Article().
+
+ Example:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import NewsURLLoader
+
+ loader = NewsURLLoader(
+ urls=["", ""],
+ )
+ docs = loader.load()
+
+ Newspaper reference:
+ https://newspaper.readthedocs.io/en/latest/
+ """
+
+ def __init__(
+ self,
+ urls: List[str],
+ text_mode: bool = True,
+ nlp: bool = False,
+ continue_on_failure: bool = True,
+ show_progress_bar: bool = False,
+ **newspaper_kwargs: Any,
+ ) -> None:
+ """Initialize with file path."""
+ try:
+ import newspaper
+
+ self.__version = newspaper.__version__
+ except ImportError:
+ raise ImportError(
+ "newspaper package not found, please install it with "
+ "`pip install newspaper3k`"
+ )
+
+ self.urls = urls
+ self.text_mode = text_mode
+ self.nlp = nlp
+ self.continue_on_failure = continue_on_failure
+ self.newspaper_kwargs = newspaper_kwargs
+ self.show_progress_bar = show_progress_bar
+
+ def load(self) -> List[Document]:
+ iter = self.lazy_load()
+ if self.show_progress_bar:
+ try:
+ from tqdm import tqdm
+ except ImportError as e:
+ raise ImportError(
+ "Package tqdm must be installed if show_progress_bar=True. "
+ "Please install with 'pip install tqdm' or set "
+ "show_progress_bar=False."
+ ) from e
+ iter = tqdm(iter)
+ return list(iter)
+
+ def lazy_load(self) -> Iterator[Document]:
+ try:
+ from newspaper import Article
+ except ImportError as e:
+ raise ImportError(
+ "Cannot import newspaper, please install with `pip install newspaper3k`"
+ ) from e
+
+ for url in self.urls:
+ try:
+ article = Article(url, **self.newspaper_kwargs)
+ article.download()
+ article.parse()
+
+ if self.nlp:
+ article.nlp()
+
+ except Exception as e:
+ if self.continue_on_failure:
+ logger.error(f"Error fetching or processing {url}, exception: {e}")
+ continue
+ else:
+ raise e
+
+ metadata = {
+ "title": getattr(article, "title", ""),
+ "link": getattr(article, "url", getattr(article, "canonical_link", "")),
+ "authors": getattr(article, "authors", []),
+ "language": getattr(article, "meta_lang", ""),
+ "description": getattr(article, "meta_description", ""),
+ "publish_date": getattr(article, "publish_date", ""),
+ }
+
+ if self.text_mode:
+ content = article.text
+ else:
+ content = article.html
+
+ if self.nlp:
+ metadata["keywords"] = getattr(article, "keywords", [])
+ metadata["summary"] = getattr(article, "summary", "")
+
+ yield Document(page_content=content, metadata=metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/notebook.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/notebook.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e70b038eb389bf98e8912bad4c91fe756af9f97
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/notebook.py
@@ -0,0 +1,137 @@
+"""Loads .ipynb notebook files."""
+
+import json
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+def concatenate_cells(
+ cell: dict, include_outputs: bool, max_output_length: int, traceback: bool
+) -> str:
+ """Combine cells information in a readable format ready to be used.
+
+ Args:
+ cell: A dictionary
+ include_outputs: Whether to include the outputs of the cell.
+ max_output_length: Maximum length of the output to be displayed.
+ traceback: Whether to return a traceback of the error.
+
+ Returns:
+ A string with the cell information.
+
+ """
+ cell_type = cell["cell_type"]
+ source = cell["source"]
+ if include_outputs:
+ try:
+ output = cell["outputs"]
+ except KeyError:
+ pass
+
+ if include_outputs and cell_type == "code" and output:
+ if "ename" in output[0].keys():
+ error_name = output[0]["ename"]
+ error_value = output[0]["evalue"]
+ if traceback:
+ traceback = output[0]["traceback"]
+ return (
+ f"'{cell_type}' cell: '{source}'\n, gives error '{error_name}',"
+ f" with description '{error_value}'\n"
+ f"and traceback '{traceback}'\n\n"
+ )
+ else:
+ return (
+ f"'{cell_type}' cell: '{source}'\n, gives error '{error_name}',"
+ f"with description '{error_value}'\n\n"
+ )
+ elif output[0]["output_type"] == "stream":
+ output = output[0]["text"]
+ min_output = min(max_output_length, len(output))
+ return (
+ f"'{cell_type}' cell: '{source}'\n with "
+ f"output: '{output[:min_output]}'\n\n"
+ )
+ else:
+ return f"'{cell_type}' cell: '{source}'\n\n"
+
+ return ""
+
+
+def remove_newlines(x: Any) -> Any:
+ """Recursively remove newlines, no matter the data structure they are stored in."""
+
+ if isinstance(x, str):
+ return x.replace("\n", "")
+ elif isinstance(x, list):
+ return [remove_newlines(elem) for elem in x]
+ elif isinstance(x, dict):
+ return {k: remove_newlines(v) for (k, v) in x.items()}
+ else:
+ return x
+
+
+class NotebookLoader(BaseLoader):
+ """Load `Jupyter notebook` (.ipynb) files."""
+
+ def __init__(
+ self,
+ path: Union[str, Path],
+ include_outputs: bool = False,
+ max_output_length: int = 10,
+ remove_newline: bool = False,
+ traceback: bool = False,
+ ):
+ """Initialize with a path.
+
+ Args:
+ path: The path to load the notebook from.
+ include_outputs: Whether to include the outputs of the cell.
+ Defaults to False.
+ max_output_length: Maximum length of the output to be displayed.
+ Defaults to 10.
+ remove_newline: Whether to remove newlines from the notebook.
+ Defaults to False.
+ traceback: Whether to return a traceback of the error.
+ Defaults to False.
+ """
+ self.file_path = path
+ self.include_outputs = include_outputs
+ self.max_output_length = max_output_length
+ self.remove_newline = remove_newline
+ self.traceback = traceback
+
+ def load(
+ self,
+ ) -> List[Document]:
+ """Load documents."""
+ p = Path(self.file_path)
+
+ with open(p, encoding="utf8") as f:
+ d = json.load(f)
+
+ filtered_data = [
+ {k: v for (k, v) in cell.items() if k in ["cell_type", "source", "outputs"]}
+ for cell in d["cells"]
+ ]
+
+ if self.remove_newline:
+ filtered_data = list(map(remove_newlines, filtered_data))
+
+ text = "".join(
+ list(
+ map(
+ lambda x: concatenate_cells(
+ x, self.include_outputs, self.max_output_length, self.traceback
+ ),
+ filtered_data,
+ )
+ )
+ )
+
+ metadata = {"source": str(p)}
+
+ return [Document(page_content=text, metadata=metadata)]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/notion.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/notion.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed01891c444f2b68beee86f33b9aa34c8677021c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/notion.py
@@ -0,0 +1,26 @@
+from pathlib import Path
+from typing import List, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class NotionDirectoryLoader(BaseLoader):
+ """Load `Notion directory` dump."""
+
+ def __init__(self, path: Union[str, Path], *, encoding: str = "utf-8") -> None:
+ """Initialize with a file path."""
+ self.file_path = path
+ self.encoding = encoding
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ paths = list(Path(self.file_path).glob("**/*.md"))
+ docs = []
+ for p in paths:
+ with open(p, encoding=self.encoding) as f:
+ text = f.read()
+ metadata = {"source": str(p)}
+ docs.append(Document(page_content=text, metadata=metadata))
+ return docs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/notiondb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/notiondb.py
new file mode 100644
index 0000000000000000000000000000000000000000..37c367dcb486d7bb0c69b7b639c57a88143ec6b3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/notiondb.py
@@ -0,0 +1,230 @@
+import logging
+from typing import Any, Dict, List, Optional
+
+import requests
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+NOTION_BASE_URL = "https://api.notion.com/v1"
+DATABASE_URL = NOTION_BASE_URL + "/databases/{database_id}/query"
+PAGE_URL = NOTION_BASE_URL + "/pages/{page_id}"
+BLOCK_URL = NOTION_BASE_URL + "/blocks/{block_id}/children"
+
+# Configure logging
+logging.basicConfig(level=logging.WARNING)
+logger = logging.getLogger(__name__)
+
+
+class NotionDBLoader(BaseLoader):
+ """Load from `Notion DB`.
+
+ Reads content from pages within a Notion Database.
+ Args:
+ integration_token (str): Notion integration token.
+ database_id (str): Notion database id.
+ request_timeout_sec (int): Timeout for Notion requests in seconds.
+ Defaults to 10.
+ filter_object (Dict[str, Any]): Filter object used to limit returned
+ entries based on specified criteria.
+ E.g.: {
+ "timestamp": "last_edited_time",
+ "last_edited_time": {
+ "on_or_after": "2024-02-07"
+ }
+ } -> will only return entries that were last edited
+ on or after 2024-02-07
+ Notion docs: https://developers.notion.com/reference/post-database-query-filter
+ Defaults to None, which will return ALL entries.
+ """
+
+ def __init__(
+ self,
+ integration_token: str,
+ database_id: str,
+ request_timeout_sec: Optional[int] = 10,
+ *,
+ filter_object: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ """Initialize with parameters."""
+ if not integration_token:
+ raise ValueError("integration_token must be provided")
+ if not database_id:
+ raise ValueError("database_id must be provided")
+
+ self.token = integration_token
+ self.database_id = database_id
+ self.headers = {
+ "Authorization": "Bearer " + self.token,
+ "Content-Type": "application/json",
+ "Notion-Version": "2022-06-28",
+ }
+ self.request_timeout_sec = request_timeout_sec
+ self.filter_object = filter_object or {}
+
+ def load(self) -> List[Document]:
+ """Load documents from the Notion database.
+ Returns:
+ List[Document]: List of documents.
+ """
+ page_summaries = self._retrieve_page_summaries()
+ return list(self.load_page(page_summary) for page_summary in page_summaries)
+
+ def _retrieve_page_summaries(
+ self, query_dict: Dict[str, Any] = {"page_size": 100}
+ ) -> List[Dict[str, Any]]:
+ """
+ Get all the pages from a Notion database
+ OR filter based on specified criteria.
+ """
+ pages: List[Dict[str, Any]] = []
+
+ while True:
+ data = self._request(
+ DATABASE_URL.format(database_id=self.database_id),
+ method="POST",
+ query_dict=query_dict,
+ filter_object=self.filter_object,
+ )
+
+ pages.extend(data.get("results"))
+
+ if not data.get("has_more"):
+ break
+
+ query_dict["start_cursor"] = data.get("next_cursor")
+
+ return pages
+
+ def load_page(self, page_summary: Dict[str, Any]) -> Document:
+ """Read a page.
+
+ Args:
+ page_summary: Page summary from Notion API.
+ """
+ page_id = page_summary["id"]
+
+ # load properties as metadata
+ metadata: Dict[str, Any] = {}
+
+ value: Any
+
+ for prop_name, prop_data in page_summary["properties"].items():
+ prop_type = prop_data["type"]
+
+ if prop_type == "rich_text":
+ value = self._concatenate_rich_text(prop_data["rich_text"])
+ elif prop_type == "title":
+ value = self._concatenate_rich_text(prop_data["title"])
+ elif prop_type == "multi_select":
+ value = (
+ [item["name"] for item in prop_data["multi_select"]]
+ if prop_data["multi_select"]
+ else []
+ )
+ elif prop_type == "url":
+ value = prop_data["url"]
+ elif prop_type == "unique_id":
+ value = (
+ f"{prop_data['unique_id']['prefix']}-{prop_data['unique_id']['number']}"
+ if prop_data["unique_id"]
+ else None
+ )
+ elif prop_type == "status":
+ value = prop_data["status"]["name"] if prop_data["status"] else None
+ elif prop_type == "people":
+ value = []
+ if prop_data["people"]:
+ for item in prop_data["people"]:
+ name = item.get("name")
+ if not name:
+ logger.warning(
+ "Missing 'name' in 'people' property "
+ f"for page {page_id}"
+ )
+ value.append(name)
+ elif prop_type == "date":
+ value = prop_data["date"] if prop_data["date"] else None
+ elif prop_type == "last_edited_time":
+ value = (
+ prop_data["last_edited_time"]
+ if prop_data["last_edited_time"]
+ else None
+ )
+ elif prop_type == "created_time":
+ value = prop_data["created_time"] if prop_data["created_time"] else None
+ elif prop_type == "checkbox":
+ value = prop_data["checkbox"]
+ elif prop_type == "email":
+ value = prop_data["email"]
+ elif prop_type == "number":
+ value = prop_data["number"]
+ elif prop_type == "select":
+ value = prop_data["select"]["name"] if prop_data["select"] else None
+ else:
+ value = None
+
+ metadata[prop_name.lower()] = value
+
+ metadata["id"] = page_id
+
+ return Document(page_content=self._load_blocks(page_id), metadata=metadata)
+
+ def _load_blocks(self, block_id: str, num_tabs: int = 0) -> str:
+ """Read a block and its children."""
+ result_lines_arr: List[str] = []
+ cur_block_id: str = block_id
+
+ while cur_block_id:
+ data = self._request(BLOCK_URL.format(block_id=cur_block_id))
+
+ for result in data["results"]:
+ result_obj = result[result["type"]]
+
+ if "rich_text" not in result_obj:
+ continue
+
+ cur_result_text_arr: List[str] = []
+
+ for rich_text in result_obj["rich_text"]:
+ if "text" in rich_text:
+ cur_result_text_arr.append(
+ "\t" * num_tabs + rich_text["text"]["content"]
+ )
+
+ if result["has_children"]:
+ children_text = self._load_blocks(
+ result["id"], num_tabs=num_tabs + 1
+ )
+ cur_result_text_arr.append(children_text)
+
+ result_lines_arr.append("\n".join(cur_result_text_arr))
+
+ cur_block_id = data.get("next_cursor")
+
+ return "\n".join(result_lines_arr)
+
+ def _request(
+ self,
+ url: str,
+ method: str = "GET",
+ query_dict: Dict[str, Any] = {},
+ *,
+ filter_object: Optional[Dict[str, Any]] = None,
+ ) -> Any:
+ json_payload = query_dict.copy()
+ if filter_object:
+ json_payload["filter"] = filter_object
+ res = requests.request(
+ method,
+ url,
+ headers=self.headers,
+ json=json_payload,
+ timeout=self.request_timeout_sec,
+ )
+ res.raise_for_status()
+ return res.json()
+
+ def _concatenate_rich_text(self, rich_text_array: List[Dict[str, Any]]) -> str:
+ """Concatenate all text content from a rich_text array."""
+ return "".join(item["plain_text"] for item in rich_text_array)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/nuclia.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/nuclia.py
new file mode 100644
index 0000000000000000000000000000000000000000..97e9337b0b9e567510db6323081c5f621f8e119a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/nuclia.py
@@ -0,0 +1,38 @@
+import json
+import uuid
+from typing import List
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.tools.nuclia.tool import NucliaUnderstandingAPI
+
+
+class NucliaLoader(BaseLoader):
+ """Load from any file type using `Nuclia Understanding API`."""
+
+ def __init__(self, path: str, nuclia_tool: NucliaUnderstandingAPI):
+ self.nua = nuclia_tool
+ self.id = str(uuid.uuid4())
+ self.nua.run({"action": "push", "id": self.id, "path": path, "text": None})
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ data = self.nua.run(
+ {
+ "action": "pull",
+ "id": self.id,
+ "path": None,
+ "text": None,
+ }
+ )
+ if not data:
+ return []
+ obj = json.loads(data)
+ text = obj["extracted_text"][0]["body"]["text"]
+ print(text) # noqa: T201
+ metadata = {
+ "file": obj["file_extracted_data"][0],
+ "metadata": obj["field_metadata"][0],
+ }
+ return [Document(page_content=text, metadata=metadata)]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/obs_directory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/obs_directory.py
new file mode 100644
index 0000000000000000000000000000000000000000..24b67149788d4790a008e06c35082c8d9d643512
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/obs_directory.py
@@ -0,0 +1,83 @@
+# coding:utf-8
+from typing import List, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.obs_file import OBSFileLoader
+
+
+class OBSDirectoryLoader(BaseLoader):
+ """Load from `Huawei OBS directory`."""
+
+ def __init__(
+ self,
+ bucket: str,
+ endpoint: str,
+ config: Optional[dict] = None,
+ prefix: str = "",
+ ):
+ """Initialize the OBSDirectoryLoader with the specified settings.
+
+ Args:
+ bucket (str): The name of the OBS bucket to be used.
+ endpoint (str): The endpoint URL of your OBS bucket.
+ config (dict): The parameters for connecting to OBS, provided as a dictionary. The dictionary could have the following keys:
+ - "ak" (str, optional): Your OBS access key (required if `get_token_from_ecs` is False and bucket policy is not public read).
+ - "sk" (str, optional): Your OBS secret key (required if `get_token_from_ecs` is False and bucket policy is not public read).
+ - "token" (str, optional): Your security token (required if using temporary credentials).
+ - "get_token_from_ecs" (bool, optional): Whether to retrieve the security token from ECS. Defaults to False if not provided. If set to True, `ak`, `sk`, and `token` will be ignored.
+ prefix (str, optional): The prefix to be added to the OBS key. Defaults to "".
+
+ Note:
+ Before using this class, make sure you have registered with OBS and have the necessary credentials. The `ak`, `sk`, and `endpoint` values are mandatory unless `get_token_from_ecs` is True or the bucket policy is public read. `token` is required when using temporary credentials.
+ Example:
+ To create a new OBSDirectoryLoader:
+ ```
+ config = {
+ "ak": "your-access-key",
+ "sk": "your-secret-key"
+ }
+ ```
+ directory_loader = OBSDirectoryLoader("your-bucket-name", "your-end-endpoint", config, "your-prefix")
+ """ # noqa: E501
+ try:
+ from obs import ObsClient
+ except ImportError:
+ raise ImportError(
+ "Could not import esdk-obs-python python package. "
+ "Please install it with `pip install esdk-obs-python`."
+ )
+ if not config:
+ config = dict()
+ if config.get("get_token_from_ecs"):
+ self.client = ObsClient(server=endpoint, security_provider_policy="ECS")
+ else:
+ self.client = ObsClient(
+ access_key_id=config.get("ak"),
+ secret_access_key=config.get("sk"),
+ security_token=config.get("token"),
+ server=endpoint,
+ )
+
+ self.bucket = bucket
+ self.prefix = prefix
+
+ def load(self) -> List[Document]:
+ """Load documents."""
+ max_num = 1000
+ mark = None
+ docs = []
+ while True:
+ resp = self.client.listObjects(
+ self.bucket, prefix=self.prefix, marker=mark, max_keys=max_num
+ )
+ if resp.status < 300:
+ for content in resp.body.contents:
+ loader = OBSFileLoader(self.bucket, content.key, client=self.client)
+ docs.extend(loader.load())
+ if resp.body.is_truncated is True:
+ mark = resp.body.next_marker
+ else:
+ break
+ return docs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/obs_file.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/obs_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..f96ad3cd7ecc58e6f91426d7e1767e24fa67165a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/obs_file.py
@@ -0,0 +1,105 @@
+# coding:utf-8
+
+import os
+import tempfile
+from typing import Any, List, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
+
+
+class OBSFileLoader(BaseLoader):
+ """Load from the `Huawei OBS file`."""
+
+ def __init__(
+ self,
+ bucket: str,
+ key: str,
+ client: Any = None,
+ endpoint: str = "",
+ config: Optional[dict] = None,
+ ) -> None:
+ """Initialize the OBSFileLoader with the specified settings.
+
+ Args:
+ bucket (str): The name of the OBS bucket to be used.
+ key (str): The name of the object in the OBS bucket.
+ client (ObsClient, optional): An instance of the ObsClient to connect to OBS.
+ endpoint (str, optional): The endpoint URL of your OBS bucket. This parameter is mandatory if `client` is not provided.
+ config (dict, optional): The parameters for connecting to OBS, provided as a dictionary. This parameter is ignored if `client` is provided. The dictionary could have the following keys:
+ - "ak" (str, optional): Your OBS access key (required if `get_token_from_ecs` is False and bucket policy is not public read).
+ - "sk" (str, optional): Your OBS secret key (required if `get_token_from_ecs` is False and bucket policy is not public read).
+ - "token" (str, optional): Your security token (required if using temporary credentials).
+ - "get_token_from_ecs" (bool, optional): Whether to retrieve the security token from ECS. Defaults to False if not provided. If set to True, `ak`, `sk`, and `token` will be ignored.
+
+ Raises:
+ ValueError: If the `esdk-obs-python` package is not installed.
+ TypeError: If the provided `client` is not an instance of ObsClient.
+ ValueError: If `client` is not provided, but `endpoint` is missing.
+
+ Note:
+ Before using this class, make sure you have registered with OBS and have the necessary credentials. The `ak`, `sk`, and `endpoint` values are mandatory unless `get_token_from_ecs` is True or the bucket policy is public read. `token` is required when using temporary credentials.
+
+ Example:
+ To create a new OBSFileLoader with a new client:
+ ```
+ config = {
+ "ak": "your-access-key",
+ "sk": "your-secret-key"
+ }
+ obs_loader = OBSFileLoader("your-bucket-name", "your-object-key", config=config)
+ ```
+
+ To create a new OBSFileLoader with an existing client:
+ ```
+ from obs import ObsClient
+
+ # Assuming you have an existing ObsClient object 'obs_client'
+ obs_loader = OBSFileLoader("your-bucket-name", "your-object-key", client=obs_client)
+ ```
+
+ To create a new OBSFileLoader without an existing client:
+ ```
+ obs_loader = OBSFileLoader("your-bucket-name", "your-object-key", endpoint="your-endpoint-url")
+ ```
+ """ # noqa: E501
+ try:
+ from obs import ObsClient
+ except ImportError:
+ raise ImportError(
+ "Could not import esdk-obs-python python package. "
+ "Please install it with `pip install esdk-obs-python`."
+ )
+ if not client:
+ if not endpoint:
+ raise ValueError("Either OBSClient or endpoint must be provided.")
+ if not config:
+ config = dict()
+ if config.get("get_token_from_ecs"):
+ client = ObsClient(server=endpoint, security_provider_policy="ECS")
+ else:
+ client = ObsClient(
+ access_key_id=config.get("ak"),
+ secret_access_key=config.get("sk"),
+ security_token=config.get("token"),
+ server=endpoint,
+ )
+ if not isinstance(client, ObsClient):
+ raise TypeError("Client must be ObsClient type")
+ self.client = client
+ self.bucket = bucket
+ self.key = key
+
+ def load(self, mode: str = "single") -> List[Document]:
+ """Load documents."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ file_path = f"{temp_dir}/{self.bucket}/{self.key}"
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
+ # Download the file to a destination
+ self.client.downloadFile(
+ bucketName=self.bucket, objectKey=self.key, downloadFile=file_path
+ )
+ loader = UnstructuredFileLoader(file_path, mode=mode)
+ return loader.load()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/obsidian.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/obsidian.py
new file mode 100644
index 0000000000000000000000000000000000000000..703b743a0c2d1f22573f14aff4123e249548b5e1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/obsidian.py
@@ -0,0 +1,171 @@
+import functools
+import logging
+import re
+from pathlib import Path
+from typing import Any, Dict, Iterator, Pattern, Union
+
+import yaml
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+logger = logging.getLogger(__name__)
+
+
+class ObsidianLoader(BaseLoader):
+ """Load `Obsidian` files from directory."""
+
+ FRONT_MATTER_REGEX: Pattern = re.compile(r"^---\n(.*?)\n---\n", re.DOTALL)
+ TEMPLATE_VARIABLE_REGEX: Pattern = re.compile(r"{{(.*?)}}", re.DOTALL)
+ TAG_REGEX: Pattern = re.compile(r"[^\S\/]#([a-zA-Z_]+[-_/\w]*)")
+ DATAVIEW_LINE_REGEX: Pattern = re.compile(r"^\s*(\w+)::\s*(.*)$", re.MULTILINE)
+ DATAVIEW_INLINE_BRACKET_REGEX: Pattern = re.compile(
+ r"\[(\w+)::\s*(.*)\]", re.MULTILINE
+ )
+ DATAVIEW_INLINE_PAREN_REGEX: Pattern = re.compile(
+ r"\((\w+)::\s*(.*)\)", re.MULTILINE
+ )
+
+ def __init__(
+ self,
+ path: Union[str, Path],
+ encoding: str = "UTF-8",
+ collect_metadata: bool = True,
+ ):
+ """Initialize with a path.
+
+ Args:
+ path: Path to the directory containing the Obsidian files.
+ encoding: Charset encoding, defaults to "UTF-8"
+ collect_metadata: Whether to collect metadata from the front matter.
+ Defaults to True.
+ """
+ self.file_path = path
+ self.encoding = encoding
+ self.collect_metadata = collect_metadata
+
+ def _replace_template_var(
+ self, placeholders: Dict[str, str], match: re.Match
+ ) -> str:
+ """Replace a template variable with a placeholder."""
+ placeholder = f"__TEMPLATE_VAR_{len(placeholders)}__"
+ placeholders[placeholder] = match.group(1)
+ return placeholder
+
+ def _restore_template_vars(self, obj: Any, placeholders: Dict[str, str]) -> Any:
+ """Restore template variables replaced with placeholders to original values."""
+ if isinstance(obj, str):
+ for placeholder, value in placeholders.items():
+ obj = obj.replace(placeholder, f"{{{{{value}}}}}")
+ elif isinstance(obj, dict):
+ for key, value in obj.items():
+ obj[key] = self._restore_template_vars(value, placeholders)
+ elif isinstance(obj, list):
+ for i, item in enumerate(obj):
+ obj[i] = self._restore_template_vars(item, placeholders)
+ return obj
+
+ def _parse_front_matter(self, content: str) -> dict:
+ """Parse front matter metadata from the content and return it as a dict."""
+ if not self.collect_metadata:
+ return {}
+
+ match = self.FRONT_MATTER_REGEX.search(content)
+ if not match:
+ return {}
+
+ placeholders: Dict[str, str] = {}
+ replace_template_var = functools.partial(
+ self._replace_template_var, placeholders
+ )
+ front_matter_text = self.TEMPLATE_VARIABLE_REGEX.sub(
+ replace_template_var, match.group(1)
+ )
+
+ try:
+ front_matter = yaml.safe_load(front_matter_text)
+ front_matter = self._restore_template_vars(front_matter, placeholders)
+
+ # If tags are a string, split them into a list
+ if "tags" in front_matter and isinstance(front_matter["tags"], str):
+ front_matter["tags"] = front_matter["tags"].split(", ")
+
+ return front_matter
+ except yaml.parser.ParserError:
+ logger.warning("Encountered non-yaml frontmatter")
+ return {}
+
+ def _to_langchain_compatible_metadata(self, metadata: dict) -> dict:
+ """Convert a dictionary to a compatible with langchain."""
+ result = {}
+ for key, value in metadata.items():
+ if type(value) in {str, int, float}:
+ result[key] = value
+ else:
+ result[key] = str(value)
+ return result
+
+ def _parse_document_tags(self, content: str) -> set:
+ """Return a set of all tags in within the document."""
+ if not self.collect_metadata:
+ return set()
+
+ match = self.TAG_REGEX.findall(content)
+ if not match:
+ return set()
+
+ return {tag for tag in match}
+
+ def _parse_dataview_fields(self, content: str) -> dict:
+ """Parse obsidian dataview plugin fields from the content and return it
+ as a dict."""
+ if not self.collect_metadata:
+ return {}
+
+ return {
+ **{
+ match[0]: match[1]
+ for match in self.DATAVIEW_LINE_REGEX.findall(content)
+ },
+ **{
+ match[0]: match[1]
+ for match in self.DATAVIEW_INLINE_PAREN_REGEX.findall(content)
+ },
+ **{
+ match[0]: match[1]
+ for match in self.DATAVIEW_INLINE_BRACKET_REGEX.findall(content)
+ },
+ }
+
+ def _remove_front_matter(self, content: str) -> str:
+ """Remove front matter metadata from the given content."""
+ if not self.collect_metadata:
+ return content
+ return self.FRONT_MATTER_REGEX.sub("", content)
+
+ def lazy_load(self) -> Iterator[Document]:
+ paths = list(Path(self.file_path).glob("**/*.md"))
+ for path in paths:
+ with open(path, encoding=self.encoding) as f:
+ text = f.read()
+
+ front_matter = self._parse_front_matter(text)
+ tags = self._parse_document_tags(text)
+ dataview_fields = self._parse_dataview_fields(text)
+ text = self._remove_front_matter(text)
+ metadata = {
+ "source": str(path.name),
+ "path": str(path),
+ "created": path.stat().st_ctime,
+ "last_modified": path.stat().st_mtime,
+ "last_accessed": path.stat().st_atime,
+ **self._to_langchain_compatible_metadata(front_matter),
+ **dataview_fields,
+ }
+
+ if tags or front_matter.get("tags"):
+ metadata["tags"] = ",".join(
+ tags | set(front_matter.get("tags", []) or [])
+ )
+
+ yield Document(page_content=text, metadata=metadata)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/odt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/odt.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1598d068d4826d9ba7019ded257993693c5e2fc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/odt.py
@@ -0,0 +1,55 @@
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ validate_unstructured_version,
+)
+
+
+class UnstructuredODTLoader(UnstructuredFileLoader):
+ """Load `OpenOffice ODT` files using `Unstructured`.
+
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredODTLoader
+
+ loader = UnstructuredODTLoader(
+ "example.odt", mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/bricks.html#partition-odt
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+
+ Args:
+ file_path: The path to the file to load.
+ mode: The mode to use when loading the file. Can be one of "single",
+ "multi", or "all". Default is "single".
+ **unstructured_kwargs: Any kwargs to pass to the unstructured.
+ """
+ file_path = str(file_path)
+ validate_unstructured_version(min_unstructured_version="0.6.3")
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.odt import partition_odt
+
+ return partition_odt(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/onedrive.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/onedrive.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0369233c22bfe9732802d5c5cf004b9a5f35783
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/onedrive.py
@@ -0,0 +1,19 @@
+from typing import Any
+
+from pydantic import Field
+
+from langchain_community.document_loaders import SharePointLoader
+
+
+class OneDriveLoader(SharePointLoader):
+ """
+ Load documents from Microsoft OneDrive.
+ Uses `SharePointLoader` under the hood.
+ """
+
+ drive_id: str = Field(...)
+ """The ID of the OneDrive drive to load data from."""
+
+ def __init__(self, **kwargs: Any) -> None:
+ kwargs["document_library_id"] = kwargs["drive_id"]
+ super().__init__(**kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/onedrive_file.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/onedrive_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..d92cfdea917779e3223f74e6d6a7adfb85e33add
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/onedrive_file.py
@@ -0,0 +1,34 @@
+from __future__ import annotations
+
+import tempfile
+from typing import TYPE_CHECKING, List
+
+from langchain_core.documents import Document
+from pydantic import BaseModel, ConfigDict, Field
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
+
+if TYPE_CHECKING:
+ from O365.drive import File
+
+CHUNK_SIZE = 1024 * 1024 * 5
+
+
+class OneDriveFileLoader(BaseLoader, BaseModel):
+ """Load a file from `Microsoft OneDrive`."""
+
+ file: File = Field(...)
+ """The file to load."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ def load(self) -> List[Document]:
+ """Load Documents"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ file_path = f"{temp_dir}/{self.file.name}"
+ self.file.download(to_path=temp_dir, chunk_size=CHUNK_SIZE)
+ loader = UnstructuredFileLoader(file_path)
+ return loader.load()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/onenote.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/onenote.py
new file mode 100644
index 0000000000000000000000000000000000000000..e19b57044d186171ae2275140f0727cd84c12400
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/onenote.py
@@ -0,0 +1,221 @@
+"""Loads data from OneNote Notebooks"""
+
+from pathlib import Path
+from typing import Any, Dict, Iterator, List, Optional
+
+import requests
+from langchain_core.documents import Document
+from pydantic import (
+ BaseModel,
+ Field,
+ FilePath,
+ SecretStr,
+ model_validator,
+)
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class _OneNoteGraphSettings(BaseSettings):
+ client_id: str = Field(...)
+ client_secret: SecretStr = Field(...)
+
+ model_config = SettingsConfigDict(
+ case_sensitive=False,
+ populate_by_name=True,
+ env_file=".env",
+ env_prefix="MS_GRAPH_",
+ extra="ignore",
+ )
+
+
+class OneNoteLoader(BaseLoader, BaseModel):
+ """Load pages from OneNote notebooks."""
+
+ settings: _OneNoteGraphSettings = Field(default_factory=_OneNoteGraphSettings) # type: ignore[arg-type]
+ """Settings for the Microsoft Graph API client."""
+ auth_with_token: bool = False
+ """Whether to authenticate with a token or not. Defaults to False."""
+ access_token: str = ""
+ """Personal access token"""
+ onenote_api_base_url: str = "https://graph.microsoft.com/v1.0/me/onenote"
+ """URL of Microsoft Graph API for OneNote"""
+ authority_url: str = "https://login.microsoftonline.com/consumers/"
+ """A URL that identifies a token authority"""
+ token_path: FilePath = Path.home() / ".credentials" / "onenote_graph_token.txt"
+ """Path to the file where the access token is stored"""
+ notebook_name: Optional[str] = None
+ """Filter on notebook name"""
+ section_name: Optional[str] = None
+ """Filter on section name"""
+ page_title: Optional[str] = None
+ """Filter on section name"""
+ object_ids: Optional[List[str]] = None
+ """ The IDs of the objects to load data from."""
+
+ @model_validator(mode="before")
+ @classmethod
+ def init(cls, values: Dict) -> Any:
+ """Initialize the class."""
+ if "settings" in values and isinstance(values["settings"], dict):
+ values["settings"] = _OneNoteGraphSettings(**values["settings"])
+ return values
+
+ def lazy_load(self) -> Iterator[Document]:
+ """
+ Get pages from OneNote notebooks.
+
+ Returns:
+ A list of Documents with attributes:
+ - page_content
+ - metadata
+ - title
+ """
+ self._auth()
+
+ try:
+ from bs4 import BeautifulSoup
+ except ImportError:
+ raise ImportError(
+ "beautifulsoup4 package not found, please install it with "
+ "`pip install bs4`"
+ )
+
+ if self.object_ids is not None:
+ for object_id in self.object_ids:
+ page_content_html = self._get_page_content(object_id)
+ soup = BeautifulSoup(page_content_html, "html.parser")
+ page_title = ""
+ title_tag = soup.title
+ if title_tag:
+ page_title = title_tag.get_text(strip=True)
+ page_content = soup.get_text(separator="\n", strip=True)
+ yield Document(
+ page_content=page_content, metadata={"title": page_title}
+ )
+ else:
+ request_url = self._url
+
+ while request_url != "":
+ response = requests.get(request_url, headers=self._headers, timeout=10)
+ response.raise_for_status()
+ pages = response.json()
+
+ for page in pages["value"]:
+ page_id = page["id"]
+ page_content_html = self._get_page_content(page_id)
+ soup = BeautifulSoup(page_content_html, "html.parser")
+ page_title = ""
+ title_tag = soup.title
+ if title_tag:
+ page_content = soup.get_text(separator="\n", strip=True)
+ yield Document(
+ page_content=page_content, metadata={"title": page_title}
+ )
+
+ if "@odata.nextLink" in pages:
+ request_url = pages["@odata.nextLink"]
+ else:
+ request_url = ""
+
+ def _get_page_content(self, page_id: str) -> str:
+ """Get page content from OneNote API"""
+ request_url = self.onenote_api_base_url + f"/pages/{page_id}/content"
+ response = requests.get(request_url, headers=self._headers, timeout=10)
+ response.raise_for_status()
+ return response.text
+
+ @property
+ def _headers(self) -> Dict[str, str]:
+ """Return headers for requests to OneNote API"""
+ return {
+ "Authorization": f"Bearer {self.access_token}",
+ }
+
+ @property
+ def _scopes(self) -> List[str]:
+ """Return required scopes."""
+ return ["Notes.Read"]
+
+ def _auth(self) -> None:
+ """Authenticate with Microsoft Graph API"""
+ if self.access_token != "":
+ return
+
+ if self.auth_with_token:
+ with self.token_path.open("r") as token_file:
+ self.access_token = token_file.read()
+ else:
+ try:
+ from msal import ConfidentialClientApplication
+ except ImportError as e:
+ raise ImportError(
+ "MSAL package not found, please install it with `pip install msal`"
+ ) from e
+
+ client_instance = ConfidentialClientApplication(
+ client_id=self.settings.client_id,
+ client_credential=self.settings.client_secret.get_secret_value(),
+ authority=self.authority_url,
+ )
+
+ authorization_request_url = client_instance.get_authorization_request_url(
+ self._scopes
+ )
+ print("Visit the following url to give consent:") # noqa: T201
+ print(authorization_request_url) # noqa: T201
+ authorization_url = input("Paste the authenticated url here:\n")
+
+ authorization_code = authorization_url.split("code=")[1].split("&")[0]
+ access_token_json = client_instance.acquire_token_by_authorization_code(
+ code=authorization_code, scopes=self._scopes
+ )
+ self.access_token = access_token_json["access_token"]
+
+ try:
+ if not self.token_path.parent.exists():
+ self.token_path.parent.mkdir(parents=True)
+ except Exception as e:
+ raise Exception(
+ f"Could not create the folder {self.token_path.parent} "
+ + "to store the access token."
+ ) from e
+
+ with self.token_path.open("w") as token_file:
+ token_file.write(self.access_token)
+
+ @property
+ def _url(self) -> str:
+ """Create URL for getting page ids from the OneNoteApi API."""
+ query_params_list = []
+ filter_list = []
+ expand_list = []
+
+ query_params_list.append("$select=id")
+ if self.notebook_name is not None:
+ filter_list.append(
+ "parentNotebook/displayName%20eq%20"
+ + f"'{self.notebook_name.replace(' ', '%20')}'"
+ )
+ expand_list.append("parentNotebook")
+ if self.section_name is not None:
+ filter_list.append(
+ "parentSection/displayName%20eq%20"
+ + f"'{self.section_name.replace(' ', '%20')}'"
+ )
+ expand_list.append("parentSection")
+ if self.page_title is not None:
+ filter_list.append(
+ "title%20eq%20" + f"'{self.page_title.replace(' ', '%20')}'"
+ )
+
+ if len(expand_list) > 0:
+ query_params_list.append("$expand=" + ",".join(expand_list))
+ if len(filter_list) > 0:
+ query_params_list.append("$filter=" + "%20and%20".join(filter_list))
+
+ query_params = "&".join(query_params_list)
+ if query_params != "":
+ query_params = "?" + query_params
+ return f"{self.onenote_api_base_url}/pages{query_params}"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/open_city_data.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/open_city_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c0c1a53c763506fb3a963a6a32856d417a425ea
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/open_city_data.py
@@ -0,0 +1,39 @@
+from typing import Iterator
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class OpenCityDataLoader(BaseLoader):
+ """Load from `Open City`."""
+
+ def __init__(self, city_id: str, dataset_id: str, limit: int):
+ """Initialize with dataset_id.
+ Example: https://dev.socrata.com/foundry/data.sfgov.org/vw6y-z8j6
+ e.g., city_id = data.sfgov.org
+ e.g., dataset_id = vw6y-z8j6
+
+ Args:
+ city_id: The Open City city identifier.
+ dataset_id: The Open City dataset identifier.
+ limit: The maximum number of documents to load.
+ """
+ self.city_id = city_id
+ self.dataset_id = dataset_id
+ self.limit = limit
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load records."""
+
+ from sodapy import Socrata
+
+ client = Socrata(self.city_id, None)
+ results = client.get(self.dataset_id, limit=self.limit)
+ for record in results:
+ yield Document(
+ page_content=str(record),
+ metadata={
+ "source": self.city_id + "_" + self.dataset_id,
+ },
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/oracleadb_loader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/oracleadb_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9a60b013fa642a8b720b9ecf0ca0a8fd1a412a8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/oracleadb_loader.py
@@ -0,0 +1,137 @@
+from typing import Any, Dict, List, Optional, Union
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class OracleAutonomousDatabaseLoader(BaseLoader):
+ """
+ Load from oracle adb
+
+ Autonomous Database connection can be made by either connection_string
+ or tns name. wallet_location and wallet_password are required
+ for TLS connection.
+ Each document will represent one row of the query result.
+ Columns are written into the `page_content` and 'metadata' in
+ constructor is written into 'metadata' of document,
+ by default, the 'metadata' is None.
+ """
+
+ def __init__(
+ self,
+ query: str,
+ user: str,
+ password: str,
+ *,
+ schema: Optional[str] = None,
+ tns_name: Optional[str] = None,
+ config_dir: Optional[str] = None,
+ wallet_location: Optional[str] = None,
+ wallet_password: Optional[str] = None,
+ connection_string: Optional[str] = None,
+ metadata: Optional[List[str]] = None,
+ parameters: Optional[Union[list, tuple, dict]] = None,
+ ):
+ """
+ init method
+ :param query: sql query to execute
+ :param user: username
+ :param password: user password
+ :param schema: schema to run in database
+ :param tns_name: tns name in tnsname.ora
+ :param config_dir: directory of config files(tnsname.ora, wallet)
+ :param wallet_location: location of wallet
+ :param wallet_password: password of wallet
+ :param connection_string: connection string to connect to adb instance
+ :param metadata: metadata used in document
+ :param parameters: bind variable to use in query
+ """
+ # Mandatory required arguments.
+ self.query = query
+ self.user = user
+ self.password = password
+
+ # Schema
+ self.schema = schema
+
+ # TNS connection Method
+ self.tns_name = tns_name
+ self.config_dir = config_dir
+
+ # Wallet configuration is required for mTLS connection
+ self.wallet_location = wallet_location
+ self.wallet_password = wallet_password
+
+ # Connection String connection method
+ self.connection_string = connection_string
+
+ # metadata column
+ self.metadata = metadata
+
+ # parameters, e.g bind variable
+ self.parameters = parameters
+
+ # dsn
+ self.dsn: Optional[str]
+ self._set_dsn()
+
+ def _set_dsn(self) -> None:
+ if self.connection_string:
+ self.dsn = self.connection_string
+ elif self.tns_name:
+ self.dsn = self.tns_name
+
+ def _run_query(self) -> List[Dict[str, Any]]:
+ try:
+ import oracledb
+ except ImportError as e:
+ raise ImportError(
+ "Could not import oracledb, please install with 'pip install oracledb'"
+ ) from e
+ connect_param = {"user": self.user, "password": self.password, "dsn": self.dsn}
+ if self.dsn == self.tns_name:
+ connect_param["config_dir"] = self.config_dir
+ if self.wallet_location and self.wallet_password:
+ connect_param["wallet_location"] = self.wallet_location
+ connect_param["wallet_password"] = self.wallet_password
+
+ try:
+ connection = oracledb.connect(**connect_param)
+ cursor = connection.cursor()
+ if self.schema:
+ cursor.execute(f"alter session set current_schema={self.schema}")
+ if self.parameters:
+ cursor.execute(self.query, self.parameters)
+ else:
+ cursor.execute(self.query)
+ columns = [col[0] for col in cursor.description]
+ data = cursor.fetchall()
+ data = [
+ {
+ i: (j if not isinstance(j, oracledb.LOB) else j.read())
+ for i, j in zip(columns, row)
+ }
+ for row in data
+ ]
+ except oracledb.DatabaseError as e:
+ print("Got error while connecting: " + str(e)) # noqa: T201
+ data = []
+ finally:
+ cursor.close()
+ connection.close()
+
+ return data
+
+ def load(self) -> List[Document]:
+ data = self._run_query()
+ documents = []
+ metadata_columns = self.metadata if self.metadata else []
+ for row in data:
+ metadata = {
+ key: value for key, value in row.items() if key in metadata_columns
+ }
+ doc = Document(page_content=str(row), metadata=metadata)
+ documents.append(doc)
+
+ return documents
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/oracleai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/oracleai.py
new file mode 100644
index 0000000000000000000000000000000000000000..0637227bf7db87f00cd97bad8c5f00bb822760b4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/oracleai.py
@@ -0,0 +1,447 @@
+# Authors:
+# Harichandan Roy (hroy)
+# David Jiang (ddjiang)
+#
+# -----------------------------------------------------------------------------
+# oracleai.py
+# -----------------------------------------------------------------------------
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import os
+import random
+import struct
+import time
+import traceback
+from html.parser import HTMLParser
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
+
+from langchain_core.document_loaders import BaseLoader
+from langchain_core.documents import Document
+from langchain_text_splitters import TextSplitter
+
+if TYPE_CHECKING:
+ from oracledb import Connection
+
+logger = logging.getLogger(__name__)
+
+"""ParseOracleDocMetadata class"""
+
+
+class ParseOracleDocMetadata(HTMLParser):
+ """Parse Oracle doc metadata..."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.reset()
+ self.match = False
+ self.metadata: Dict[str, Any] = {}
+
+ def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None:
+ if tag == "meta":
+ entry: Optional[str] = ""
+ for name, value in attrs:
+ if name == "name":
+ entry = value
+ if name == "content":
+ if entry:
+ self.metadata[entry] = value
+ elif tag == "title":
+ self.match = True
+
+ def handle_data(self, data: str) -> None:
+ if self.match:
+ self.metadata["title"] = data
+ self.match = False
+
+ def get_metadata(self) -> Dict[str, Any]:
+ return self.metadata
+
+
+"""OracleDocReader class"""
+
+
+class OracleDocReader:
+ """Read a file"""
+
+ @staticmethod
+ def generate_object_id(input_string: Union[str, None] = None) -> str:
+ out_length = 32 # output length
+ hash_len = 8 # hash value length
+
+ if input_string is None:
+ input_string = "".join(
+ random.choices(
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
+ k=16,
+ )
+ )
+
+ # timestamp
+ timestamp = int(time.time())
+ timestamp_bin = struct.pack(">I", timestamp) # 4 bytes
+
+ # hash_value
+ hashval_bin = hashlib.sha256(input_string.encode()).digest()
+ hashval_bin = hashval_bin[:hash_len] # 8 bytes
+
+ # counter
+ counter_bin = struct.pack(">I", random.getrandbits(32)) # 4 bytes
+
+ # binary object id
+ object_id = timestamp_bin + hashval_bin + counter_bin # 16 bytes
+ object_id_hex = object_id.hex() # 32 bytes
+ object_id_hex = object_id_hex.zfill(
+ out_length
+ ) # fill with zeros if less than 32 bytes
+
+ object_id_hex = object_id_hex[:out_length]
+
+ return object_id_hex
+
+ @staticmethod
+ def read_file(
+ conn: Connection, file_path: str, params: dict
+ ) -> Union[Document, None]:
+ """Read a file using OracleReader
+ Args:
+ conn: Oracle Connection,
+ file_path: Oracle Directory,
+ params: ONNX file name.
+ Returns:
+ Plain text and metadata as Langchain Document.
+ """
+
+ metadata: Dict[str, Any] = {}
+ try:
+ import oracledb
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import oracledb, please install with "
+ "`pip install -U oracledb`."
+ ) from e
+ try:
+ oracledb.defaults.fetch_lobs = False
+ cursor = conn.cursor()
+
+ with open(file_path, "rb") as f:
+ data = f.read()
+
+ if data is None:
+ return Document(page_content="", metadata=metadata)
+
+ mdata = cursor.var(oracledb.DB_TYPE_CLOB)
+ text = cursor.var(oracledb.DB_TYPE_CLOB)
+ cursor.execute(
+ """
+ declare
+ input blob;
+ begin
+ input := :blob;
+ :mdata := dbms_vector_chain.utl_to_text(input, json(:pref));
+ :text := dbms_vector_chain.utl_to_text(input);
+ end;""",
+ blob=data,
+ pref=json.dumps(params),
+ mdata=mdata,
+ text=text,
+ )
+ cursor.close()
+
+ if mdata is None:
+ metadata = {}
+ else:
+ doc_data = str(mdata.getvalue())
+ if doc_data.startswith(""
+ ):
+ p = ParseOracleDocMetadata()
+ p.feed(doc_data)
+ metadata = p.get_metadata()
+
+ doc_id = OracleDocReader.generate_object_id(conn.username + "$" + file_path)
+ metadata["_oid"] = doc_id
+ metadata["_file"] = file_path
+
+ if text is None:
+ return Document(page_content="", metadata=metadata)
+ else:
+ return Document(page_content=str(text.getvalue()), metadata=metadata)
+
+ except Exception as ex:
+ logger.info(f"An exception occurred :: {ex}")
+ logger.info(f"Skip processing {file_path}")
+ cursor.close()
+ return None
+
+
+"""OracleDocLoader class"""
+
+
+class OracleDocLoader(BaseLoader):
+ """Read documents using OracleDocLoader
+ Args:
+ conn: Oracle Connection,
+ params: Loader parameters.
+ """
+
+ def __init__(self, conn: Connection, params: Dict[str, Any], **kwargs: Any):
+ self.conn = conn
+ self.params = json.loads(json.dumps(params))
+ super().__init__(**kwargs)
+
+ def load(self) -> List[Document]:
+ """Load data into LangChain Document objects..."""
+ try:
+ import oracledb
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import oracledb, please install with "
+ "`pip install -U oracledb`."
+ ) from e
+
+ ncols = 0
+ results: List[Document] = []
+ metadata: Dict[str, Any] = {}
+ m_params = {"plaintext": "false"}
+ try:
+ # extract the parameters
+ if self.params is not None:
+ self.file = self.params.get("file")
+ self.dir = self.params.get("dir")
+ self.owner = self.params.get("owner")
+ self.tablename = self.params.get("tablename")
+ self.colname = self.params.get("colname")
+ else:
+ raise Exception("Missing loader parameters")
+
+ oracledb.defaults.fetch_lobs = False
+
+ if self.file:
+ doc = OracleDocReader.read_file(self.conn, self.file, m_params)
+
+ if doc is None:
+ return results
+
+ results.append(doc)
+
+ if self.dir:
+ skip_count = 0
+ for file_name in os.listdir(self.dir):
+ file_path = os.path.join(self.dir, file_name)
+ if os.path.isfile(file_path):
+ doc = OracleDocReader.read_file(self.conn, file_path, m_params)
+
+ if doc is None:
+ skip_count = skip_count + 1
+ logger.info(f"Total skipped: {skip_count}\n")
+ else:
+ results.append(doc)
+
+ if self.tablename:
+ try:
+ if self.owner is None or self.colname is None:
+ raise Exception("Missing owner or column name or both.")
+
+ cursor = self.conn.cursor()
+ self.mdata_cols = self.params.get("mdata_cols")
+ if self.mdata_cols is not None:
+ if len(self.mdata_cols) > 3:
+ raise Exception(
+ "Exceeds the max number of columns "
+ + "you can request for metadata."
+ )
+
+ # execute a query to get column data types
+ sql = (
+ "select column_name, data_type from all_tab_columns "
+ + "where owner = :ownername and "
+ + "table_name = :tablename"
+ )
+ cursor.execute(
+ sql,
+ ownername=self.owner.upper(),
+ tablename=self.tablename.upper(),
+ )
+
+ # cursor.execute(sql)
+ rows = cursor.fetchall()
+ for row in rows:
+ if row[0] in self.mdata_cols:
+ if row[1] not in [
+ "NUMBER",
+ "BINARY_DOUBLE",
+ "BINARY_FLOAT",
+ "LONG",
+ "DATE",
+ "TIMESTAMP",
+ "VARCHAR2",
+ ]:
+ raise Exception(
+ "The datatype for the column requested "
+ + "for metadata is not supported."
+ )
+
+ self.mdata_cols_sql = ", rowid"
+ if self.mdata_cols is not None:
+ for col in self.mdata_cols:
+ self.mdata_cols_sql = self.mdata_cols_sql + ", " + col
+
+ # [TODO] use bind variables
+ sql = (
+ "select dbms_vector_chain.utl_to_text(t."
+ + self.colname
+ + ", json('"
+ + json.dumps(m_params)
+ + "')) mdata, dbms_vector_chain.utl_to_text(t."
+ + self.colname
+ + ") text"
+ + self.mdata_cols_sql
+ + " from "
+ + self.owner
+ + "."
+ + self.tablename
+ + " t"
+ )
+
+ cursor.execute(sql)
+ for row in cursor:
+ metadata = {}
+
+ if row is None:
+ doc_id = OracleDocReader.generate_object_id(
+ self.conn.username
+ + "$"
+ + self.owner
+ + "$"
+ + self.tablename
+ + "$"
+ + self.colname
+ )
+ metadata["_oid"] = doc_id
+ results.append(Document(page_content="", metadata=metadata))
+ else:
+ if row[0] is not None:
+ data = str(row[0])
+ if data.startswith(""
+ ):
+ p = ParseOracleDocMetadata()
+ p.feed(data)
+ metadata = p.get_metadata()
+
+ doc_id = OracleDocReader.generate_object_id(
+ self.conn.username
+ + "$"
+ + self.owner
+ + "$"
+ + self.tablename
+ + "$"
+ + self.colname
+ + "$"
+ + str(row[2])
+ )
+ metadata["_oid"] = doc_id
+ metadata["_rowid"] = row[2]
+
+ # process projected metadata cols
+ if self.mdata_cols is not None:
+ ncols = len(self.mdata_cols)
+
+ for i in range(0, ncols):
+ metadata[self.mdata_cols[i]] = row[i + 2]
+
+ if row[1] is None:
+ results.append(
+ Document(page_content="", metadata=metadata)
+ )
+ else:
+ results.append(
+ Document(
+ page_content=str(row[1]), metadata=metadata
+ )
+ )
+ except Exception as ex:
+ logger.info(f"An exception occurred :: {ex}")
+ traceback.print_exc()
+ cursor.close()
+ raise
+
+ return results
+ except Exception as ex:
+ logger.info(f"An exception occurred :: {ex}")
+ traceback.print_exc()
+ raise
+
+
+class OracleTextSplitter(TextSplitter):
+ """Splitting text using Oracle chunker."""
+
+ def __init__(self, conn: Connection, params: Dict[str, Any], **kwargs: Any) -> None:
+ """Initialize."""
+ self.conn = conn
+ self.params = params
+ super().__init__(**kwargs)
+ try:
+ import json
+
+ try:
+ import oracledb
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import oracledb, please install with "
+ "`pip install -U oracledb`."
+ ) from e
+
+ self._oracledb = oracledb
+ self._json = json
+ except ImportError:
+ raise ImportError(
+ "oracledb or json or both are not installed. "
+ + "Please install them. "
+ + "Recommendations: `pip install oracledb`. "
+ )
+
+ def split_text(self, text: str) -> List[str]:
+ """Split incoming text and return chunks."""
+
+ try:
+ import oracledb
+ except ImportError as e:
+ raise ImportError(
+ "Unable to import oracledb, please install with "
+ "`pip install -U oracledb`."
+ ) from e
+
+ splits = []
+
+ try:
+ # returns strings or bytes instead of a locator
+ self._oracledb.defaults.fetch_lobs = False
+
+ cursor = self.conn.cursor()
+
+ cursor.setinputsizes(content=oracledb.CLOB)
+ cursor.execute(
+ "select t.column_value from "
+ + "dbms_vector_chain.utl_to_chunks(:content, json(:params)) t",
+ content=text,
+ params=self._json.dumps(self.params),
+ )
+
+ while True:
+ row = cursor.fetchone()
+ if row is None:
+ break
+ d = self._json.loads(row[0])
+ splits.append(d["chunk_data"])
+
+ return splits
+
+ except Exception as ex:
+ logger.info(f"An exception occurred :: {ex}")
+ traceback.print_exc()
+ raise
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/org_mode.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/org_mode.py
new file mode 100644
index 0000000000000000000000000000000000000000..614ad70b72352bc3e0a056cf55fcfa451ee22530
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/org_mode.py
@@ -0,0 +1,55 @@
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ validate_unstructured_version,
+)
+
+
+class UnstructuredOrgModeLoader(UnstructuredFileLoader):
+ """Load `Org-Mode` files using `Unstructured`.
+
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredOrgModeLoader
+
+ loader = UnstructuredOrgModeLoader(
+ "example.org", mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/bricks.html#partition-org
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+
+ Args:
+ file_path: The path to the file to load.
+ mode: The mode to load the file from. Default is "single".
+ **unstructured_kwargs: Any additional keyword arguments to pass
+ to the unstructured.
+ """
+ file_path = str(file_path)
+ validate_unstructured_version(min_unstructured_version="0.7.9")
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.partition.org import partition_org
+
+ return partition_org(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/pdf.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/pdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b51e481eba0b5b40c1e89ff4f75f7594aafbde1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/pdf.py
@@ -0,0 +1,1417 @@
+import json
+import logging
+import os
+import re
+import tempfile
+import time
+from abc import ABC
+from io import StringIO
+from pathlib import Path, PurePath
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ BinaryIO,
+ Iterator,
+ Literal,
+ Mapping,
+ Optional,
+ Sequence,
+ Union,
+ cast,
+)
+from urllib.parse import urlparse
+
+import requests
+from langchain_core.documents import Document
+from langchain_core.utils import get_from_dict_or_env
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders.blob_loaders import Blob
+from langchain_community.document_loaders.dedoc import DedocBaseLoader
+from langchain_community.document_loaders.parsers.images import BaseImageBlobParser
+from langchain_community.document_loaders.parsers.pdf import (
+ _DEFAULT_PAGES_DELIMITER,
+ AmazonTextractPDFParser,
+ DocumentIntelligenceParser,
+ PDFMinerParser,
+ PDFPlumberParser,
+ PyMuPDFParser,
+ PyPDFium2Parser,
+ PyPDFParser,
+)
+from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
+
+if TYPE_CHECKING:
+ from textractor.data.text_linearization_config import TextLinearizationConfig
+
+logger = logging.getLogger(__file__)
+
+
+class UnstructuredPDFLoader(UnstructuredFileLoader):
+ """Load `PDF` files using `Unstructured`.
+
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredPDFLoader
+
+ loader = UnstructuredPDFLoader(
+ "example.pdf", mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/bricks.html#partition-pdf
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+
+ Args:
+ file_path: The path to the PDF file to load.
+ mode: The mode to use when loading the file. Can be one of "single",
+ "multi", or "all". Default is "single".
+ **unstructured_kwargs: Any kwargs to pass to the unstructured.
+ """
+ file_path = str(file_path)
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> list:
+ from unstructured.partition.pdf import partition_pdf
+
+ return partition_pdf(filename=self.file_path, **self.unstructured_kwargs)
+
+
+class BasePDFLoader(BaseLoader, ABC):
+ """Base Loader class for `PDF` files.
+
+ If the file is a web path, it will download it to a temporary file, use it, then
+ clean up the temporary file after completion.
+ """
+
+ def __init__(
+ self, file_path: Union[str, PurePath], *, headers: Optional[dict] = None
+ ):
+ """Initialize with a file path.
+
+ Args:
+ file_path: Either a local, S3 or web path to a PDF file.
+ headers: Headers to use for GET request to download a file from a web path.
+ """
+ self.file_path = str(file_path)
+ self.web_path = None
+ self.headers = headers
+ if "~" in self.file_path:
+ self.file_path = os.path.expanduser(self.file_path)
+
+ # If the file is a web path or S3, download it to a temporary file,
+ # and use that. It's better to use a BlobLoader.
+ if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path):
+ self.temp_dir = tempfile.TemporaryDirectory()
+ _, suffix = os.path.splitext(self.file_path)
+ if self._is_s3_presigned_url(self.file_path):
+ suffix = urlparse(self.file_path).path.split("/")[-1]
+ temp_pdf = os.path.join(self.temp_dir.name, f"tmp{suffix}")
+ self.web_path = self.file_path
+ if not self._is_s3_url(self.file_path):
+ r = requests.get(self.file_path, headers=self.headers)
+ if r.status_code != 200:
+ raise ValueError(
+ "Check the url of your file; returned status code %s"
+ % r.status_code
+ )
+
+ with open(temp_pdf, mode="wb") as f:
+ f.write(r.content)
+ self.file_path = str(temp_pdf)
+ elif not os.path.isfile(self.file_path):
+ raise ValueError("File path %s is not a valid file or url" % self.file_path)
+
+ def __del__(self) -> None:
+ if hasattr(self, "temp_dir"):
+ self.temp_dir.cleanup()
+
+ @staticmethod
+ def _is_valid_url(url: str) -> bool:
+ """Check if the url is valid."""
+ parsed = urlparse(url)
+ return bool(parsed.netloc) and bool(parsed.scheme)
+
+ @staticmethod
+ def _is_s3_url(url: str) -> bool:
+ """check if the url is S3"""
+ try:
+ result = urlparse(url)
+ if result.scheme == "s3" and result.netloc:
+ return True
+ return False
+ except ValueError:
+ return False
+
+ @staticmethod
+ def _is_s3_presigned_url(url: str) -> bool:
+ """Check if the url is a presigned S3 url."""
+ try:
+ result = urlparse(url)
+ return bool(re.search(r"\.s3\.amazonaws\.com$", result.netloc))
+ except ValueError:
+ return False
+
+ @property
+ def source(self) -> str:
+ return self.web_path if self.web_path is not None else self.file_path
+
+
+class OnlinePDFLoader(BasePDFLoader):
+ """Load online `PDF`."""
+
+ def load(self) -> list[Document]:
+ """Load documents."""
+ loader = UnstructuredPDFLoader(str(self.file_path))
+ return loader.load()
+
+
+class PyPDFLoader(BasePDFLoader):
+ """Load and parse a PDF file using 'pypdf' library.
+
+ This class provides methods to load and parse PDF documents, supporting various
+ configurations such as handling password-protected files, extracting images, and
+ defining extraction mode. It integrates the `pypdf` library for PDF processing and
+ offers both synchronous and asynchronous document loading.
+
+ Examples:
+ Setup:
+
+ .. code-block:: bash
+
+ pip install -U langchain-community pypdf
+
+ Instantiate the loader:
+
+ .. code-block:: python
+
+ from langchain_community.document_loaders import PyPDFLoader
+
+ loader = PyPDFLoader(
+ file_path = "./example_data/layout-parser-paper.pdf",
+ # headers = None
+ # password = None,
+ mode = "single",
+ pages_delimiter = "\n\f",
+ # extract_images = True,
+ # images_parser = RapidOCRBlobParser(),
+ )
+
+ Lazy load documents:
+
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ Load documents asynchronously:
+
+ .. code-block:: python
+
+ docs = await loader.aload()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, PurePath],
+ password: Optional[Union[str, bytes]] = None,
+ headers: Optional[dict] = None,
+ extract_images: bool = False,
+ *,
+ mode: Literal["single", "page"] = "page",
+ images_parser: Optional[BaseImageBlobParser] = None,
+ images_inner_format: Literal["text", "markdown-img", "html-img"] = "text",
+ pages_delimiter: str = _DEFAULT_PAGES_DELIMITER,
+ extraction_mode: Literal["plain", "layout"] = "plain",
+ extraction_kwargs: Optional[dict] = None,
+ ) -> None:
+ """Initialize with a file path.
+
+ Args:
+ file_path: The path to the PDF file to be loaded.
+ headers: Optional headers to use for GET request to download a file from a
+ web path.
+ password: Optional password for opening encrypted PDFs.
+ mode: The extraction mode, either "single" for the entire document or "page"
+ for page-wise extraction.
+ pages_delimiter: A string delimiter to separate pages in single-mode
+ extraction.
+ extract_images: Whether to extract images from the PDF.
+ images_parser: Optional image blob parser.
+ images_inner_format: The format for the parsed output.
+ - "text" = return the content as is
+ - "markdown-img" = wrap the content into an image markdown link, w/ link
+ pointing to (`![body)(#)`]
+ - "html-img" = wrap the content as the `alt` text of an tag and link to
+ (`
`)
+ extraction_mode: “plain” for legacy functionality, “layout” extract text
+ in a fixed width format that closely adheres to the rendered layout in
+ the source pdf
+ extraction_kwargs: Optional additional parameters for the extraction
+ process.
+
+ Returns:
+ This method does not directly return data. Use the `load`, `lazy_load` or
+ `aload` methods to retrieve parsed documents with content and metadata.
+ """
+ super().__init__(file_path, headers=headers)
+ self.parser = PyPDFParser(
+ password=password,
+ mode=mode,
+ extract_images=extract_images,
+ images_parser=images_parser,
+ images_inner_format=images_inner_format,
+ pages_delimiter=pages_delimiter,
+ extraction_mode=extraction_mode,
+ extraction_kwargs=extraction_kwargs,
+ )
+
+ def lazy_load(
+ self,
+ ) -> Iterator[Document]:
+ """
+ Lazy load given path as pages.
+ Insert image, if possible, between two paragraphs.
+ In this way, a paragraph can be continued on the next page.
+ """
+ if self.web_path:
+ blob = Blob.from_data(open(self.file_path, "rb").read(), path=self.web_path)
+ else:
+ blob = Blob.from_path(self.file_path)
+ yield from self.parser.lazy_parse(blob)
+
+
+class PyPDFium2Loader(BasePDFLoader):
+ """Load and parse a PDF file using the `pypdfium2` library.
+
+ This class provides methods to load and parse PDF documents, supporting various
+ configurations such as handling password-protected files, extracting images, and
+ defining extraction mode.
+ It integrates the `pypdfium2` library for PDF processing and offers both
+ synchronous and asynchronous document loading.
+
+ Examples:
+ Setup:
+
+ .. code-block:: bash
+
+ pip install -U langchain-community pypdfium2
+
+ Instantiate the loader:
+
+ .. code-block:: python
+
+ from langchain_community.document_loaders import PyPDFium2Loader
+
+ loader = PyPDFium2Loader(
+ file_path = "./example_data/layout-parser-paper.pdf",
+ # headers = None
+ # password = None,
+ mode = "single",
+ pages_delimiter = "\n\f",
+ # extract_images = True,
+ # images_to_text = convert_images_to_text_with_tesseract(),
+ )
+
+ Lazy load documents:
+
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ Load documents asynchronously:
+
+ .. code-block:: python
+
+ docs = await loader.aload()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, PurePath],
+ *,
+ mode: Literal["single", "page"] = "page",
+ pages_delimiter: str = _DEFAULT_PAGES_DELIMITER,
+ password: Optional[str] = None,
+ extract_images: bool = False,
+ images_parser: Optional[BaseImageBlobParser] = None,
+ images_inner_format: Literal["text", "markdown-img", "html-img"] = "text",
+ headers: Optional[dict] = None,
+ ):
+ """Initialize with a file path.
+
+ Args:
+ file_path: The path to the PDF file to be loaded.
+ headers: Optional headers to use for GET request to download a file from a
+ web path.
+ password: Optional password for opening encrypted PDFs.
+ mode: The extraction mode, either "single" for the entire document or "page"
+ for page-wise extraction.
+ pages_delimiter: A string delimiter to separate pages in single-mode
+ extraction.
+ extract_images: Whether to extract images from the PDF.
+ images_parser: Optional image blob parser.
+ images_inner_format: The format for the parsed output.
+ - "text" = return the content as is
+ - "markdown-img" = wrap the content into an image markdown link, w/ link
+ pointing to (`![body)(#)`]
+ - "html-img" = wrap the content as the `alt` text of an tag and link to
+ (`
`)
+
+ Returns:
+ This class does not directly return data. Use the `load`, `lazy_load` or
+ `aload` methods to retrieve parsed documents with content and metadata.
+ """
+ super().__init__(file_path, headers=headers)
+ self.parser = PyPDFium2Parser(
+ mode=mode,
+ password=password,
+ extract_images=extract_images,
+ images_parser=images_parser,
+ images_inner_format=images_inner_format,
+ pages_delimiter=pages_delimiter,
+ )
+
+ def lazy_load(
+ self,
+ ) -> Iterator[Document]:
+ """
+ Lazy load given path as pages.
+ Insert image, if possible, between two paragraphs.
+ In this way, a paragraph can be continued on the next page.
+ """
+ if self.web_path:
+ blob = Blob.from_data(open(self.file_path, "rb").read(), path=self.web_path)
+ else:
+ blob = Blob.from_path(self.file_path)
+ yield from self.parser.parse(blob)
+
+
+class PyPDFDirectoryLoader(BaseLoader):
+ """Load and parse a directory of PDF files using 'pypdf' library.
+
+ This class provides methods to load and parse multiple PDF documents in a directory,
+ supporting options for recursive search, handling password-protected files,
+ extracting images, and defining extraction modes. It integrates the `pypdf` library
+ for PDF processing and offers synchronous document loading.
+
+ Examples:
+ Setup:
+
+ .. code-block:: bash
+
+ pip install -U langchain-community pypdf
+
+ Instantiate the loader:
+
+ .. code-block:: python
+
+ from langchain_community.document_loaders import PyPDFDirectoryLoader
+
+ loader = PyPDFDirectoryLoader(
+ path = "./example_data/",
+ glob = "**/[!.]*.pdf",
+ silent_errors = False,
+ load_hidden = False,
+ recursive = False,
+ extract_images = False,
+ password = None,
+ mode = "page",
+ images_to_text = None,
+ headers = None,
+ extraction_mode = "plain",
+ # extraction_kwargs = None,
+ )
+
+ Load documents:
+
+ .. code-block:: python
+
+ docs = loader.load()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ Load documents asynchronously:
+
+ .. code-block:: python
+
+ docs = await loader.aload()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+ """
+
+ def __init__(
+ self,
+ path: Union[str, PurePath],
+ glob: str = "**/[!.]*.pdf",
+ silent_errors: bool = False,
+ load_hidden: bool = False,
+ recursive: bool = False,
+ extract_images: bool = False,
+ *,
+ password: Optional[str] = None,
+ mode: Literal["single", "page"] = "page",
+ images_parser: Optional[BaseImageBlobParser] = None,
+ headers: Optional[dict] = None,
+ extraction_mode: Literal["plain", "layout"] = "plain",
+ extraction_kwargs: Optional[dict] = None,
+ ):
+ """Initialize with a directory path.
+
+ Args:
+ path: The path to the directory containing PDF files to be loaded.
+ glob: The glob pattern to match files in the directory.
+ silent_errors: Whether to log errors instead of raising them.
+ load_hidden: Whether to include hidden files in the search.
+ recursive: Whether to search subdirectories recursively.
+ extract_images: Whether to extract images from PDFs.
+ password: Optional password for opening encrypted PDFs.
+ mode: The extraction mode, either "single" for extracting the entire
+ document or "page" for page-wise extraction.
+ images_parser: Optional image blob parser..
+ headers: Optional headers to use for GET request to download a file from a
+ web path.
+ extraction_mode: “plain” for legacy functionality, “layout” for
+ experimental layout mode functionality
+ extraction_kwargs: Optional additional parameters for the extraction
+ process.
+
+ Returns:
+ This method does not directly return data. Use the `load` method to
+ retrieve parsed documents with content and metadata.
+ """
+ self.password = password
+ self.mode = mode
+ self.path = path
+ self.glob = glob
+ self.load_hidden = load_hidden
+ self.recursive = recursive
+ self.silent_errors = silent_errors
+ self.extract_images = extract_images
+ self.images_parser = images_parser
+ self.headers = headers
+ self.extraction_mode = extraction_mode
+ self.extraction_kwargs = extraction_kwargs
+
+ @staticmethod
+ def _is_visible(path: PurePath) -> bool:
+ return not any(part.startswith(".") for part in path.parts)
+
+ def load(self) -> list[Document]:
+ p = Path(self.path)
+ docs = []
+ items = p.rglob(self.glob) if self.recursive else p.glob(self.glob)
+ for i in items:
+ if i.is_file():
+ if self._is_visible(i.relative_to(p)) or self.load_hidden:
+ try:
+ loader = PyPDFLoader(
+ str(i),
+ password=self.password,
+ mode=self.mode,
+ extract_images=self.extract_images,
+ images_parser=self.images_parser,
+ headers=self.headers,
+ extraction_mode=self.extraction_mode,
+ extraction_kwargs=self.extraction_kwargs,
+ )
+ sub_docs = loader.load()
+ for doc in sub_docs:
+ doc.metadata["source"] = str(i)
+ docs.extend(sub_docs)
+ except Exception as e:
+ if self.silent_errors:
+ logger.warning(e)
+ else:
+ raise e
+ return docs
+
+
+class PDFMinerLoader(BasePDFLoader):
+ """Load and parse a PDF file using 'pdfminer.six' library.
+
+ This class provides methods to load and parse PDF documents, supporting various
+ configurations such as handling password-protected files, extracting images, and
+ defining extraction mode. It integrates the `pdfminer.six` library for PDF
+ processing and offers both synchronous and asynchronous document loading.
+
+ Examples:
+ Setup:
+
+ .. code-block:: bash
+
+ pip install -U langchain-community pdfminer.six
+
+ Instantiate the loader:
+
+ .. code-block:: python
+
+ from langchain_community.document_loaders import PDFMinerLoader
+
+ loader = PDFMinerLoader(
+ file_path = "./example_data/layout-parser-paper.pdf",
+ # headers = None
+ # password = None,
+ mode = "single",
+ pages_delimiter = "\n\f",
+ # extract_images = True,
+ # images_to_text = convert_images_to_text_with_tesseract(),
+ )
+
+ Lazy load documents:
+
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ Load documents asynchronously:
+
+ .. code-block:: python
+
+ docs = await loader.aload()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, PurePath],
+ *,
+ password: Optional[str] = None,
+ mode: Literal["single", "page"] = "single",
+ pages_delimiter: str = _DEFAULT_PAGES_DELIMITER,
+ extract_images: bool = False,
+ images_parser: Optional[BaseImageBlobParser] = None,
+ images_inner_format: Literal["text", "markdown-img", "html-img"] = "text",
+ headers: Optional[dict] = None,
+ concatenate_pages: Optional[bool] = None,
+ ) -> None:
+ """Initialize with a file path.
+
+ Args:
+ file_path: The path to the PDF file to be loaded.
+ headers: Optional headers to use for GET request to download a file from a
+ web path.
+ password: Optional password for opening encrypted PDFs.
+ mode: The extraction mode, either "single" for the entire document or "page"
+ for page-wise extraction.
+ pages_delimiter: A string delimiter to separate pages in single-mode
+ extraction.
+ extract_images: Whether to extract images from the PDF.
+ images_parser: Optional image blob parser.
+ images_inner_format: The format for the parsed output.
+ - "text" = return the content as is
+ - "markdown-img" = wrap the content into an image markdown link, w/ link
+ pointing to (`![body)(#)`]
+ - "html-img" = wrap the content as the `alt` text of an tag and link to
+ (`
`)
+ concatenate_pages: Deprecated. If True, concatenate all PDF pages into one
+ a single document. Otherwise, return one document per page.
+
+ Returns:
+ This method does not directly return data. Use the `load`, `lazy_load` or
+ `aload` methods to retrieve parsed documents with content and metadata.
+ """
+ super().__init__(file_path, headers=headers)
+ self.parser = PDFMinerParser(
+ password=password,
+ extract_images=extract_images,
+ images_parser=images_parser,
+ concatenate_pages=concatenate_pages,
+ mode=mode,
+ pages_delimiter=pages_delimiter,
+ images_inner_format=images_inner_format,
+ )
+
+ def lazy_load(
+ self,
+ ) -> Iterator[Document]:
+ """
+ Lazy load given path as pages.
+ Insert image, if possible, between two paragraphs.
+ In this way, a paragraph can be continued on the next page.
+ """
+ if self.web_path:
+ blob = Blob.from_data(open(self.file_path, "rb").read(), path=self.web_path)
+ else:
+ blob = Blob.from_path(self.file_path)
+ yield from self.parser.lazy_parse(blob)
+
+
+class PDFMinerPDFasHTMLLoader(BasePDFLoader):
+ """Load `PDF` files as HTML content using `PDFMiner`."""
+
+ def __init__(
+ self, file_path: Union[str, PurePath], *, headers: Optional[dict] = None
+ ):
+ """Initialize with a file path."""
+ try:
+ from pdfminer.high_level import extract_text_to_fp # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "`pdfminer` package not found, please install it with "
+ "`pip install pdfminer.six`"
+ )
+
+ super().__init__(file_path, headers=headers)
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load file."""
+ from pdfminer.high_level import extract_text_to_fp
+ from pdfminer.layout import LAParams
+ from pdfminer.utils import open_filename
+
+ output_string = StringIO()
+ with open_filename(self.file_path, "rb") as fp:
+ extract_text_to_fp(
+ cast(BinaryIO, fp),
+ output_string,
+ codec="",
+ laparams=LAParams(),
+ output_type="html",
+ )
+ metadata = {
+ "source": str(self.file_path) if self.web_path is None else self.web_path
+ }
+ yield Document(page_content=output_string.getvalue(), metadata=metadata)
+
+
+class PyMuPDFLoader(BasePDFLoader):
+ """Load and parse a PDF file using 'PyMuPDF' library.
+
+ This class provides methods to load and parse PDF documents, supporting various
+ configurations such as handling password-protected files, extracting tables,
+ extracting images, and defining extraction mode. It integrates the `PyMuPDF`
+ library for PDF processing and offers both synchronous and asynchronous document
+ loading.
+
+ Examples:
+ Setup:
+
+ .. code-block:: bash
+
+ pip install -U langchain-community pymupdf
+
+ Instantiate the loader:
+
+ .. code-block:: python
+
+ from langchain_community.document_loaders import PyMuPDFLoader
+
+ loader = PyMuPDFLoader(
+ file_path = "./example_data/layout-parser-paper.pdf",
+ # headers = None
+ # password = None,
+ mode = "single",
+ pages_delimiter = "\n\f",
+ # extract_images = True,
+ # images_parser = TesseractBlobParser(),
+ # extract_tables = "markdown",
+ # extract_tables_settings = None,
+ )
+
+ Lazy load documents:
+
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ Load documents asynchronously:
+
+ .. code-block:: python
+
+ docs = await loader.aload()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, PurePath],
+ *,
+ password: Optional[str] = None,
+ mode: Literal["single", "page"] = "page",
+ pages_delimiter: str = _DEFAULT_PAGES_DELIMITER,
+ extract_images: bool = False,
+ images_parser: Optional[BaseImageBlobParser] = None,
+ images_inner_format: Literal["text", "markdown-img", "html-img"] = "text",
+ extract_tables: Union[Literal["csv", "markdown", "html"], None] = None,
+ headers: Optional[dict] = None,
+ extract_tables_settings: Optional[dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize with a file path.
+
+ Args:
+ file_path: The path to the PDF file to be loaded.
+ headers: Optional headers to use for GET request to download a file from a
+ web path.
+ password: Optional password for opening encrypted PDFs.
+ mode: The extraction mode, either "single" for the entire document or "page"
+ for page-wise extraction.
+ pages_delimiter: A string delimiter to separate pages in single-mode
+ extraction.
+ extract_images: Whether to extract images from the PDF.
+ images_parser: Optional image blob parser.
+ images_inner_format: The format for the parsed output.
+ - "text" = return the content as is
+ - "markdown-img" = wrap the content into an image markdown link, w/ link
+ pointing to (`![body)(#)`]
+ - "html-img" = wrap the content as the `alt` text of an tag and link to
+ (`
`)
+ extract_tables: Whether to extract tables in a specific format, such as
+ "csv", "markdown", or "html".
+ extract_tables_settings: Optional dictionary of settings for customizing
+ table extraction.
+ **kwargs: Additional keyword arguments for customizing text extraction
+ behavior.
+
+ Returns:
+ This method does not directly return data. Use the `load`, `lazy_load`, or
+ `aload` methods to retrieve parsed documents with content and metadata.
+
+ Raises:
+ ValueError: If the `mode` argument is not one of "single" or "page".
+ """
+ if mode not in ["single", "page"]:
+ raise ValueError("mode must be single or page")
+ super().__init__(file_path, headers=headers)
+ self.parser = PyMuPDFParser(
+ password=password,
+ mode=mode,
+ pages_delimiter=pages_delimiter,
+ text_kwargs=kwargs,
+ extract_images=extract_images,
+ images_parser=images_parser,
+ images_inner_format=images_inner_format,
+ extract_tables=extract_tables,
+ extract_tables_settings=extract_tables_settings,
+ )
+
+ def _lazy_load(self, **kwargs: Any) -> Iterator[Document]:
+ """Lazy load given path as pages or single document (see `mode`).
+ Insert image, if possible, between two paragraphs.
+ In this way, a paragraph can be continued on the next page.
+ """
+ if kwargs:
+ logger.warning(
+ f"Received runtime arguments {kwargs}. Passing runtime args to `load`"
+ f" is deprecated. Please pass arguments during initialization instead."
+ )
+ parser = self.parser
+ if self.web_path:
+ blob = Blob.from_data(open(self.file_path, "rb").read(), path=self.web_path)
+ else:
+ blob = Blob.from_path(self.file_path)
+ yield from parser._lazy_parse(blob, text_kwargs=kwargs)
+
+ def load(self, **kwargs: Any) -> list[Document]:
+ return list(self._lazy_load(**kwargs))
+
+ def lazy_load(self) -> Iterator[Document]:
+ yield from self._lazy_load()
+
+
+# MathpixPDFLoader implementation taken largely from Daniel Gross's:
+# https://gist.github.com/danielgross/3ab4104e14faccc12b49200843adab21
+class MathpixPDFLoader(BasePDFLoader):
+ """Load `PDF` files using `Mathpix` service."""
+
+ def __init__(
+ self,
+ file_path: Union[str, PurePath],
+ processed_file_format: str = "md",
+ max_wait_time_seconds: int = 500,
+ should_clean_pdf: bool = False,
+ extra_request_data: Optional[dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize with a file path.
+
+ Args:
+ file_path: a file for loading.
+ processed_file_format: a format of the processed file. Default is "md".
+ max_wait_time_seconds: a maximum time to wait for the response from
+ the server. Default is 500.
+ should_clean_pdf: a flag to clean the PDF file. Default is False.
+ extra_request_data: Additional request data.
+ **kwargs: additional keyword arguments.
+ """
+ self.mathpix_api_key = get_from_dict_or_env(
+ kwargs, "mathpix_api_key", "MATHPIX_API_KEY"
+ )
+ self.mathpix_api_id = get_from_dict_or_env(
+ kwargs, "mathpix_api_id", "MATHPIX_API_ID"
+ )
+
+ # The base class isn't expecting these and doesn't collect **kwargs
+ kwargs.pop("mathpix_api_key", None)
+ kwargs.pop("mathpix_api_id", None)
+
+ super().__init__(file_path, **kwargs)
+ self.processed_file_format = processed_file_format
+ self.extra_request_data = (
+ extra_request_data if extra_request_data is not None else {}
+ )
+ self.max_wait_time_seconds = max_wait_time_seconds
+ self.should_clean_pdf = should_clean_pdf
+
+ @property
+ def _mathpix_headers(self) -> dict[str, str]:
+ return {"app_id": self.mathpix_api_id, "app_key": self.mathpix_api_key}
+
+ @property
+ def url(self) -> str:
+ return "https://api.mathpix.com/v3/pdf"
+
+ @property
+ def data(self) -> dict:
+ options = {
+ "conversion_formats": {self.processed_file_format: True},
+ **self.extra_request_data,
+ }
+ return {"options_json": json.dumps(options)}
+
+ def send_pdf(self) -> str:
+ with open(str(self.file_path), "rb") as f:
+ files = {"file": f}
+ response = requests.post(
+ self.url, headers=self._mathpix_headers, files=files, data=self.data
+ )
+ response_data = response.json()
+ if "error" in response_data:
+ raise ValueError(f"Mathpix request failed: {response_data['error']}")
+ if "pdf_id" in response_data:
+ pdf_id = response_data["pdf_id"]
+ return pdf_id
+ else:
+ raise ValueError("Unable to send PDF to Mathpix.")
+
+ def wait_for_processing(self, pdf_id: str) -> None:
+ """Wait for processing to complete.
+
+ Args:
+ pdf_id: a PDF id.
+
+ Returns: None
+ """
+ url = self.url + "/" + pdf_id
+ for _ in range(0, self.max_wait_time_seconds, 5):
+ response = requests.get(url, headers=self._mathpix_headers)
+ response_data = response.json()
+
+ # This indicates an error with the request (e.g. auth problems)
+ error = response_data.get("error", None)
+ error_info = response_data.get("error_info", None)
+
+ if error is not None:
+ error_msg = f"Unable to retrieve PDF from Mathpix: {error}"
+
+ if error_info is not None:
+ error_msg += f" ({error_info['id']})"
+
+ raise ValueError(error_msg)
+
+ status = response_data.get("status", None)
+
+ if status == "completed":
+ return
+ elif status == "error":
+ # This indicates an error with the PDF processing
+ raise ValueError("Unable to retrieve PDF from Mathpix")
+ else:
+ logger.info("Status: %s, waiting for processing to complete", status)
+ time.sleep(5)
+ raise TimeoutError
+
+ def get_processed_pdf(self, pdf_id: str) -> str:
+ self.wait_for_processing(pdf_id)
+ url = f"{self.url}/{pdf_id}.{self.processed_file_format}"
+ response = requests.get(url, headers=self._mathpix_headers)
+ return response.content.decode("utf-8")
+
+ def clean_pdf(self, contents: str) -> str:
+ """Clean the PDF file.
+
+ Args:
+ contents: a PDF file contents.
+
+ Returns:
+
+ """
+ contents = "\n".join(
+ [line for line in contents.split("\n") if not line.startswith("![]")]
+ )
+ # replace \section{Title} with # Title
+ contents = contents.replace("\\section{", "# ").replace("}", "")
+ # replace the "\" slash that Mathpix adds to escape $, %, (, etc.
+ contents = (
+ contents.replace(r"\$", "$")
+ .replace(r"\%", "%")
+ .replace(r"\(", "(")
+ .replace(r"\)", ")")
+ )
+ return contents
+
+ def load(self) -> list[Document]:
+ pdf_id = self.send_pdf()
+ contents = self.get_processed_pdf(pdf_id)
+ if self.should_clean_pdf:
+ contents = self.clean_pdf(contents)
+ metadata = {"source": self.source, "file_path": self.source, "pdf_id": pdf_id}
+ return [Document(page_content=contents, metadata=metadata)]
+
+
+class PDFPlumberLoader(BasePDFLoader):
+ """Load `PDF` files using `pdfplumber`."""
+
+ def __init__(
+ self,
+ file_path: Union[str, PurePath],
+ text_kwargs: Optional[Mapping[str, Any]] = None,
+ dedupe: bool = False,
+ headers: Optional[dict] = None,
+ extract_images: bool = False,
+ ) -> None:
+ """Initialize with a file path."""
+ try:
+ import pdfplumber # noqa:F401
+ except ImportError:
+ raise ImportError(
+ "pdfplumber package not found, please install it with "
+ "`pip install pdfplumber`"
+ )
+
+ super().__init__(file_path, headers=headers)
+ self.text_kwargs = text_kwargs or {}
+ self.dedupe = dedupe
+ self.extract_images = extract_images
+
+ def load(self) -> list[Document]:
+ """Load file."""
+
+ parser = PDFPlumberParser(
+ text_kwargs=self.text_kwargs,
+ dedupe=self.dedupe,
+ extract_images=self.extract_images,
+ )
+ if self.web_path:
+ blob = Blob.from_data(open(self.file_path, "rb").read(), path=self.web_path)
+ else:
+ blob = Blob.from_path(self.file_path)
+ return parser.parse(blob)
+
+
+class AmazonTextractPDFLoader(BasePDFLoader):
+ """Load `PDF` files from a local file system, HTTP or S3.
+
+ To authenticate, the AWS client uses the following methods to
+ automatically load credentials:
+ https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
+
+ If a specific credential profile should be used, you must pass
+ the name of the profile from the ~/.aws/credentials file that is to be used.
+
+ Make sure the credentials / roles used have the required policies to
+ access the Amazon Textract service.
+
+ Example:
+ .. code-block:: python
+ from langchain_community.document_loaders import AmazonTextractPDFLoader
+ loader = AmazonTextractPDFLoader(
+ file_path="s3://pdfs/myfile.pdf"
+ )
+ document = loader.load()
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, PurePath],
+ textract_features: Optional[Sequence[str]] = None,
+ client: Optional[Any] = None,
+ credentials_profile_name: Optional[str] = None,
+ region_name: Optional[str] = None,
+ endpoint_url: Optional[str] = None,
+ headers: Optional[dict] = None,
+ *,
+ linearization_config: Optional["TextLinearizationConfig"] = None,
+ ) -> None:
+ """Initialize the loader.
+
+ Args:
+ file_path: A file, url or s3 path for input file
+ textract_features: Features to be used for extraction, each feature
+ should be passed as a str that conforms to the enum
+ `Textract_Features`, see `amazon-textract-caller` pkg
+ client: boto3 textract client (Optional)
+ credentials_profile_name: AWS profile name, if not default (Optional)
+ region_name: AWS region, eg us-east-1 (Optional)
+ endpoint_url: endpoint url for the textract service (Optional)
+ linearization_config: Config to be used for linearization of the output
+ should be an instance of TextLinearizationConfig from
+ the `textractor` pkg
+ """
+ super().__init__(file_path, headers=headers)
+
+ try:
+ import textractcaller as tc
+ except ImportError:
+ raise ImportError(
+ "Could not import amazon-textract-caller python package. "
+ "Please install it with `pip install amazon-textract-caller`."
+ )
+ if textract_features:
+ features = [tc.Textract_Features[x] for x in textract_features]
+ else:
+ features = []
+
+ if credentials_profile_name or region_name or endpoint_url:
+ try:
+ import boto3
+
+ if credentials_profile_name is not None:
+ session = boto3.Session(profile_name=credentials_profile_name)
+ else:
+ # use default credentials
+ session = boto3.Session()
+
+ client_params = {}
+ if region_name:
+ client_params["region_name"] = region_name
+ if endpoint_url:
+ client_params["endpoint_url"] = endpoint_url
+
+ client = session.client("textract", **client_params)
+
+ except ImportError:
+ raise ImportError(
+ "Could not import boto3 python package. "
+ "Please install it with `pip install boto3`."
+ )
+ except Exception as e:
+ raise ValueError(
+ "Could not load credentials to authenticate with AWS client. "
+ "Please check that credentials in the specified "
+ f"profile name are valid. {e}"
+ ) from e
+ self.parser = AmazonTextractPDFParser(
+ textract_features=features,
+ client=client,
+ linearization_config=linearization_config,
+ )
+
+ def load(self) -> list[Document]:
+ """Load given path as pages."""
+ return list(self.lazy_load())
+
+ def lazy_load(
+ self,
+ ) -> Iterator[Document]:
+ """Lazy load documents"""
+ # the self.file_path is local, but the blob has to include
+ # the S3 location if the file originated from S3 for multipage documents
+ # raises ValueError when multipage and not on S3"""
+
+ if self.web_path and self._is_s3_url(self.web_path):
+ blob = Blob(path=self.web_path)
+ else:
+ blob = Blob.from_path(self.file_path)
+ if AmazonTextractPDFLoader._get_number_of_pages(blob) > 1:
+ raise ValueError(
+ f"the file {blob.path} is a multi-page document, \
+ but not stored on S3. \
+ Textract requires multi-page documents to be on S3."
+ )
+
+ yield from self.parser.parse(blob)
+
+ @staticmethod
+ def _get_number_of_pages(blob: Blob) -> int:
+ try:
+ import pypdf
+ from PIL import Image, ImageSequence
+
+ except ImportError:
+ raise ImportError(
+ "Could not import pypdf or Pilloe python package. "
+ "Please install it with `pip install pypdf Pillow`."
+ )
+ if blob.mimetype == "application/pdf":
+ with blob.as_bytes_io() as input_pdf_file:
+ pdf_reader = pypdf.PdfReader(input_pdf_file)
+ return len(pdf_reader.pages)
+ elif blob.mimetype == "image/tiff":
+ num_pages = 0
+ img = Image.open(blob.as_bytes())
+ for _, _ in enumerate(ImageSequence.Iterator(img)):
+ num_pages += 1
+ return num_pages
+ elif blob.mimetype in ["image/png", "image/jpeg"]:
+ return 1
+ else:
+ raise ValueError(f"unsupported mime type: {blob.mimetype}")
+
+
+class DedocPDFLoader(DedocBaseLoader):
+ """DedocPDFLoader document loader integration to load PDF files using `dedoc`.
+ The file loader can automatically detect the correctness of a textual layer in the
+ PDF document.
+ Note that `__init__` method supports parameters that differ from ones of
+ DedocBaseLoader.
+
+ Setup:
+ Install ``dedoc`` package.
+
+ .. code-block:: bash
+
+ pip install -U dedoc
+
+ Instantiate:
+ .. code-block:: python
+
+ from langchain_community.document_loaders import DedocPDFLoader
+
+ loader = DedocPDFLoader(
+ file_path="example.pdf",
+ # split=...,
+ # with_tables=...,
+ # pdf_with_text_layer=...,
+ # pages=...,
+ # ...
+ )
+
+ Load:
+ .. code-block:: python
+
+ docs = loader.load()
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Some text
+ {
+ 'file_name': 'example.pdf',
+ 'file_type': 'application/pdf',
+ # ...
+ }
+
+ Lazy load:
+ .. code-block:: python
+
+ docs = []
+ docs_lazy = loader.lazy_load()
+
+ for doc in docs_lazy:
+ docs.append(doc)
+ print(docs[0].page_content[:100])
+ print(docs[0].metadata)
+
+ .. code-block:: python
+
+ Some text
+ {
+ 'file_name': 'example.pdf',
+ 'file_type': 'application/pdf',
+ # ...
+ }
+
+ Parameters used for document parsing via `dedoc`
+ (https://dedoc.readthedocs.io/en/latest/parameters/pdf_handling.html):
+
+ with_attachments: enable attached files extraction
+ recursion_deep_attachments: recursion level for attached files extraction,
+ works only when with_attachments==True
+ pdf_with_text_layer: type of handler for parsing, available options
+ ["true", "false", "tabby", "auto", "auto_tabby" (default)]
+ language: language of the document for PDF without a textual layer,
+ available options ["eng", "rus", "rus+eng" (default)], the list of
+ languages can be extended, please see
+ https://dedoc.readthedocs.io/en/latest/tutorials/add_new_language.html
+ pages: page slice to define the reading range for parsing
+ is_one_column_document: detect number of columns for PDF without a textual
+ layer, available options ["true", "false", "auto" (default)]
+ document_orientation: fix document orientation (90, 180, 270 degrees) for PDF
+ without a textual layer, available options ["auto" (default), "no_change"]
+ need_header_footer_analysis: remove headers and footers from the output result
+ need_binarization: clean pages background (binarize) for PDF without a textual
+ layer
+ need_pdf_table_analysis: parse tables for PDF without a textual layer
+ """
+
+ def _make_config(self) -> dict:
+ from dedoc.utils.langchain import make_manager_pdf_config
+
+ return make_manager_pdf_config(
+ file_path=str(self.file_path),
+ parsing_params=self.parsing_parameters,
+ split=self.split,
+ )
+
+
+class DocumentIntelligenceLoader(BasePDFLoader):
+ """Load a PDF with Azure Document Intelligence"""
+
+ def __init__(
+ self,
+ file_path: Union[str, PurePath],
+ client: Any,
+ model: str = "prebuilt-document",
+ headers: Optional[dict] = None,
+ ) -> None:
+ """Initialize the object for file processing with Azure Document Intelligence
+ (formerly Form Recognizer).
+
+ This constructor initializes a DocumentIntelligenceParser object to be used
+ for parsing files using the Azure Document Intelligence API. The load method
+ generates a Document node including metadata (source blob and page number)
+ for each page.
+
+ Parameters:
+ -----------
+ file_path : str
+ The path to the file that needs to be parsed.
+ client: Any
+ A DocumentAnalysisClient to perform the analysis of the blob
+ model : str
+ The model name or ID to be used for form recognition in Azure.
+
+ Examples:
+ ---------
+ >>> obj = DocumentIntelligenceLoader(
+ ... file_path="path/to/file",
+ ... client=client,
+ ... model="prebuilt-document"
+ ... )
+ """
+
+ super().__init__(file_path, headers=headers)
+ self.parser = DocumentIntelligenceParser(client=client, model=model)
+
+ def load(self) -> list[Document]:
+ """Load given path as pages."""
+ return list(self.lazy_load())
+
+ def lazy_load(
+ self,
+ ) -> Iterator[Document]:
+ """Lazy load given path as pages."""
+ blob = Blob.from_path(self.file_path)
+ yield from self.parser.parse(blob)
+
+
+class ZeroxPDFLoader(BasePDFLoader):
+ """Document loader utilizing Zerox library:
+ https://github.com/getomni-ai/zerox
+
+ Zerox converts PDF document to series of images (page-wise) and
+ uses vision-capable LLM model to generate Markdown representation.
+
+ Zerox utilizes anyc operations. Therefore when using this loader
+ inside Jupyter Notebook (or any environment running async)
+ you will need to:
+ ```python
+ import nest_asyncio
+ nest_asyncio.apply()
+ ```
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, PurePath],
+ model: str = "gpt-4o-mini",
+ **zerox_kwargs: Any,
+ ) -> None:
+ super().__init__(file_path=file_path)
+ """Initialize the parser with arguments to be passed to the zerox function.
+ Make sure to set necessary environment variables such as API key, endpoint, etc.
+ Check zerox documentation for list of necessary environment variables for
+ any given model.
+
+ Args:
+ file_path:
+ Path or url of the pdf file
+ model:
+ Vision capable model to use. Defaults to "gpt-4o-mini".
+ Hosted models are passed in format "/"
+ Examples: "azure/gpt-4o-mini", "vertex_ai/gemini-1.5-flash-001"
+ See more details in zerox documentation.
+ **zerox_kwargs:
+ Arguments specific to the zerox function.
+ see datailed list of arguments here in zerox repository:
+ https://github.com/getomni-ai/zerox/blob/main/py_zerox/pyzerox/core/zerox.py#L25
+ """ # noqa: E501
+ self.zerox_kwargs = zerox_kwargs
+ self.model = model
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazily load pages."""
+ import asyncio
+
+ from pyzerox import zerox
+
+ # Directly call asyncio.run to execute zerox synchronously
+ zerox_output = asyncio.run(
+ zerox(file_path=str(self.file_path), model=self.model, **self.zerox_kwargs)
+ )
+
+ # Convert zerox output to Document instances and yield them
+ if len(zerox_output.pages) > 0:
+ num_pages = zerox_output.pages[-1].page
+ for page in zerox_output.pages:
+ yield Document(
+ page_content=page.content,
+ metadata={
+ "source": self.source,
+ "page": page.page,
+ "num_pages": num_pages,
+ },
+ )
+
+
+# Legacy: only for backwards compatibility. Use PyPDFLoader instead
+PagedPDFSplitter = PyPDFLoader
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/pebblo.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/pebblo.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bc56d95efd02625b2289cf7c6fe6d617c4c88f5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/pebblo.py
@@ -0,0 +1,339 @@
+"""Pebblo's safe dataloader is a wrapper for document loaders"""
+
+import logging
+import os
+import uuid
+from importlib.metadata import version
+from typing import Any, Dict, Iterable, Iterator, List, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.pebblo import (
+ BATCH_SIZE_BYTES,
+ PLUGIN_VERSION,
+ App,
+ Framework,
+ IndexedDocument,
+ PebbloLoaderAPIWrapper,
+ generate_size_based_batches,
+ get_full_path,
+ get_loader_full_path,
+ get_loader_type,
+ get_runtime,
+ get_source_size,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class PebbloSafeLoader(BaseLoader):
+ """Pebblo Safe Loader class is a wrapper around document loaders enabling the data
+ to be scrutinized.
+ """
+
+ _discover_sent: bool = False
+
+ def __init__(
+ self,
+ langchain_loader: BaseLoader,
+ name: str,
+ owner: str = "",
+ description: str = "",
+ api_key: Optional[str] = None,
+ load_semantic: bool = False,
+ classifier_url: Optional[str] = None,
+ *,
+ classifier_location: str = "local",
+ anonymize_snippets: bool = False,
+ ):
+ if not name or not isinstance(name, str):
+ raise NameError("Must specify a valid name.")
+ self.app_name = name
+ self.load_id = str(uuid.uuid4())
+ self.loader = langchain_loader
+ self.load_semantic = os.environ.get("PEBBLO_LOAD_SEMANTIC") or load_semantic
+ self.owner = owner
+ self.description = description
+ self.source_path = get_loader_full_path(self.loader)
+ self.docs: List[Document] = []
+ self.docs_with_id: List[IndexedDocument] = []
+ loader_name = str(type(self.loader)).split(".")[-1].split("'")[0]
+ self.source_type = get_loader_type(loader_name)
+ self.source_path_size = get_source_size(self.source_path)
+ self.batch_size = BATCH_SIZE_BYTES
+ self.loader_details = {
+ "loader": loader_name,
+ "source_path": self.source_path,
+ "source_type": self.source_type,
+ **(
+ {"source_path_size": str(self.source_path_size)}
+ if self.source_path_size > 0
+ else {}
+ ),
+ }
+ # generate app
+ self.app = self._get_app_details()
+ # initialize Pebblo Loader API client
+ self.pb_client = PebbloLoaderAPIWrapper(
+ api_key=api_key,
+ classifier_location=classifier_location,
+ classifier_url=classifier_url,
+ anonymize_snippets=anonymize_snippets,
+ )
+ self.pb_client.send_loader_discover(self.app)
+
+ def load(self) -> List[Document]:
+ """Load Documents.
+
+ Returns:
+ list: Documents fetched from load method of the wrapped `loader`.
+ """
+ self.docs = self.loader.load()
+ # Classify docs in batches
+ self.classify_in_batches()
+ return self.docs
+
+ def classify_in_batches(self) -> None:
+ """
+ Classify documents in batches.
+ This is to avoid API timeouts when sending large number of documents.
+ Batches are generated based on the page_content size.
+ """
+ batches: List[List[Document]] = generate_size_based_batches(
+ self.docs, self.batch_size
+ )
+
+ processed_docs: List[Document] = []
+
+ total_batches = len(batches)
+ for i, batch in enumerate(batches):
+ is_last_batch: bool = i == total_batches - 1
+ self.docs = batch
+ self.docs_with_id = self._index_docs()
+ classified_docs = self.pb_client.classify_documents(
+ self.docs_with_id,
+ self.app,
+ self.loader_details,
+ loading_end=is_last_batch,
+ )
+ self._add_pebblo_specific_metadata(classified_docs)
+ if self.load_semantic:
+ batch_processed_docs = self._add_semantic_to_docs(classified_docs)
+ else:
+ batch_processed_docs = self._unindex_docs()
+ processed_docs.extend(batch_processed_docs)
+
+ self.docs = processed_docs
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Load documents in lazy fashion.
+
+ Raises:
+ NotImplementedError: raised when lazy_load id not implemented
+ within wrapped loader.
+
+ Yields:
+ list: Documents from loader's lazy loading.
+ """
+ try:
+ doc_iterator = self.loader.lazy_load()
+ except NotImplementedError as exc:
+ err_str = f"{self.loader.__class__.__name__} does not implement lazy_load()"
+ logger.error(err_str)
+ raise NotImplementedError(err_str) from exc
+ while True:
+ try:
+ doc = next(doc_iterator)
+ except StopIteration:
+ self.docs = []
+ break
+ self.docs = list((doc,))
+ self.docs_with_id = self._index_docs()
+ classified_doc = self.pb_client.classify_documents(
+ self.docs_with_id, self.app, self.loader_details
+ )
+ self._add_pebblo_specific_metadata(classified_doc)
+ if self.load_semantic:
+ self.docs = self._add_semantic_to_docs(classified_doc)
+ else:
+ self.docs = self._unindex_docs()
+ yield self.docs[0]
+
+ @classmethod
+ def set_discover_sent(cls) -> None:
+ cls._discover_sent = True
+
+ def _get_app_details(self) -> App:
+ """Fetch app details. Internal method.
+
+ Returns:
+ App: App details.
+ """
+ framework, runtime = get_runtime()
+ app = App(
+ name=self.app_name,
+ owner=self.owner,
+ description=self.description,
+ load_id=self.load_id,
+ runtime=runtime,
+ framework=framework,
+ plugin_version=PLUGIN_VERSION,
+ client_version=Framework(
+ name="langchain_community",
+ version=version("langchain_community"),
+ ),
+ )
+ return app
+
+ def _index_docs(self) -> List[IndexedDocument]:
+ """
+ Indexes the documents and returns a list of IndexedDocument objects.
+
+ Returns:
+ List[IndexedDocument]: A list of IndexedDocument objects with unique IDs.
+ """
+ docs_with_id = [
+ IndexedDocument(pb_id=str(i), **doc.dict())
+ for i, doc in enumerate(self.docs)
+ ]
+ return docs_with_id
+
+ def _add_semantic_to_docs(self, classified_docs: Dict) -> List[Document]:
+ """
+ Adds semantic metadata to the given list of documents.
+
+ Args:
+ classified_docs (Dict): A dictionary of dictionaries containing the
+ classified documents with pb_id as key.
+
+ Returns:
+ A list of `Document` objects with added semantic metadata.
+ """
+ indexed_docs = {
+ doc.pb_id: Document(page_content=doc.page_content, metadata=doc.metadata)
+ for doc in self.docs_with_id
+ }
+
+ for classified_doc in classified_docs.values():
+ doc_id = classified_doc.get("pb_id")
+ if doc_id in indexed_docs:
+ self._add_semantic_to_doc(indexed_docs[doc_id], classified_doc)
+
+ semantic_metadata_docs = [doc for doc in indexed_docs.values()]
+
+ return semantic_metadata_docs
+
+ def _unindex_docs(self) -> List[Document]:
+ """
+ Converts a list of `IndexedDocument` objects to a list of `Document` objects.
+
+ Returns:
+ A list of `Document` objects.
+ """
+ docs = [
+ Document(page_content=doc.page_content, metadata=doc.metadata)
+ for i, doc in enumerate(self.docs_with_id)
+ ]
+ return docs
+
+ def _add_semantic_to_doc(self, doc: Document, classified_doc: dict) -> Document:
+ """
+ Adds semantic metadata to the given document in-place.
+
+ Args:
+ doc (Document): A Document object.
+ classified_doc: `dict` containing the classified document.
+
+ Returns:
+ Document: The Document object with added semantic metadata.
+ """
+ doc.metadata["pebblo_semantic_entities"] = list(
+ classified_doc.get("entities", {}).keys()
+ )
+ doc.metadata["pebblo_semantic_topics"] = list(
+ classified_doc.get("topics", {}).keys()
+ )
+ return doc
+
+ def _add_pebblo_specific_metadata(self, classified_docs: dict) -> None:
+ """Add Pebblo specific metadata to documents."""
+ for doc in self.docs_with_id:
+ doc_metadata = doc.metadata
+ if self.loader.__class__.__name__ == "SharePointLoader":
+ doc_metadata["full_path"] = get_full_path(
+ doc_metadata.get("source", self.source_path)
+ )
+ else:
+ doc_metadata["full_path"] = get_full_path(
+ doc_metadata.get(
+ "full_path", doc_metadata.get("source", self.source_path)
+ )
+ )
+ doc_metadata["pb_checksum"] = classified_docs.get(doc.pb_id, {}).get(
+ "pb_checksum", None
+ )
+
+
+class PebbloTextLoader(BaseLoader):
+ """
+ Loader for text data.
+
+ Since PebbloSafeLoader is a wrapper around document loaders, this loader is
+ used to load text data directly into Documents.
+ """
+
+ def __init__(
+ self,
+ texts: Iterable[str],
+ *,
+ source: Optional[str] = None,
+ ids: Optional[List[str]] = None,
+ metadata: Optional[Dict[str, Any]] = None,
+ metadatas: Optional[List[Dict[str, Any]]] = None,
+ ) -> None:
+ """
+ Args:
+ texts: Iterable of text data.
+ source: Source of the text data.
+ Optional. Defaults to None.
+ ids: List of unique identifiers for each text.
+ Optional. Defaults to None.
+ metadata: Metadata for all texts.
+ Optional. Defaults to None.
+ metadatas: List of metadata for each text.
+ Optional. Defaults to None.
+ """
+ self.texts = texts
+ self.source = source
+ self.ids = ids
+ self.metadata = metadata
+ self.metadatas = metadatas
+
+ def lazy_load(self) -> Iterator[Document]:
+ """
+ Lazy load text data into Documents.
+
+ Returns:
+ Iterator of Documents
+ """
+ for i, text in enumerate(self.texts):
+ _id = None
+ metadata = self.metadata or {}
+ if self.metadatas and i < len(self.metadatas) and self.metadatas[i]:
+ metadata.update(self.metadatas[i])
+ if self.ids and i < len(self.ids):
+ _id = self.ids[i]
+ yield Document(id=_id, page_content=text, metadata=metadata)
+
+ def load(self) -> List[Document]:
+ """
+ Load text data into Documents.
+
+ Returns:
+ List of Documents
+ """
+ documents = []
+ for doc in self.lazy_load():
+ documents.append(doc)
+ return documents
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/polars_dataframe.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/polars_dataframe.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb523df647f4a51b1083049314581a9c3591e0eb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/polars_dataframe.py
@@ -0,0 +1,33 @@
+from typing import Any, Iterator
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.dataframe import BaseDataFrameLoader
+
+
+class PolarsDataFrameLoader(BaseDataFrameLoader):
+ """Load `Polars` DataFrame."""
+
+ def __init__(self, data_frame: Any, *, page_content_column: str = "text"):
+ """Initialize with dataframe object.
+
+ Args:
+ data_frame: Polars DataFrame object.
+ page_content_column: Name of the column containing the page content.
+ Defaults to "text".
+ """
+ import polars as pl
+
+ if not isinstance(data_frame, pl.DataFrame):
+ raise ValueError(
+ f"Expected data_frame to be a pl.DataFrame, got {type(data_frame)}"
+ )
+ super().__init__(data_frame, page_content_column=page_content_column)
+
+ def lazy_load(self) -> Iterator[Document]:
+ """Lazy load records from dataframe."""
+
+ for row in self.data_frame.iter_rows(named=True):
+ text = row[self.page_content_column]
+ row.pop(self.page_content_column)
+ yield Document(page_content=text, metadata=row)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/powerpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/powerpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..d075402647ca53d514bef54c27c123e44a71d8db
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/powerpoint.py
@@ -0,0 +1,77 @@
+import os
+from pathlib import Path
+from typing import Any, List, Union
+
+from langchain_community.document_loaders.unstructured import (
+ UnstructuredFileLoader,
+ validate_unstructured_version,
+)
+
+
+class UnstructuredPowerPointLoader(UnstructuredFileLoader):
+ """Load `Microsoft PowerPoint` files using `Unstructured`.
+
+ Works with both .ppt and .pptx files.
+ You can run the loader in one of two modes: "single" and "elements".
+ If you use "single" mode, the document will be returned as a single
+ langchain Document object. If you use "elements" mode, the unstructured
+ library will split the document into elements such as Title and NarrativeText.
+ You can pass in additional unstructured kwargs after mode to apply
+ different unstructured settings.
+
+ Examples
+ --------
+ from langchain_community.document_loaders import UnstructuredPowerPointLoader
+
+ loader = UnstructuredPowerPointLoader(
+ "example.pptx", mode="elements", strategy="fast",
+ )
+ docs = loader.load()
+
+ References
+ ----------
+ https://unstructured-io.github.io/unstructured/bricks.html#partition-pptx
+ """
+
+ def __init__(
+ self,
+ file_path: Union[str, Path],
+ mode: str = "single",
+ **unstructured_kwargs: Any,
+ ):
+ """
+
+ Args:
+ file_path: The path to the PowerPoint file to load.
+ mode: The mode to use when loading the file. Can be one of "single",
+ "multi", or "all". Default is "single".
+ **unstructured_kwargs: Any kwargs to pass to the unstructured.
+ """
+ file_path = str(file_path)
+ super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
+
+ def _get_elements(self) -> List:
+ from unstructured.file_utils.filetype import FileType, detect_filetype
+
+ # NOTE(MthwRobinson) - magic will raise an import error if the libmagic
+ # system dependency isn't installed. If it's not installed, we'll just
+ # check the file extension
+ try:
+ import magic # noqa: F401
+
+ is_ppt = detect_filetype(self.file_path) == FileType.PPT
+ except ImportError:
+ _, extension = os.path.splitext(str(self.file_path))
+ is_ppt = extension == ".ppt"
+
+ if is_ppt:
+ validate_unstructured_version("0.4.11")
+
+ if is_ppt:
+ from unstructured.partition.ppt import partition_ppt
+
+ return partition_ppt(filename=self.file_path, **self.unstructured_kwargs)
+ else:
+ from unstructured.partition.pptx import partition_pptx
+
+ return partition_pptx(filename=self.file_path, **self.unstructured_kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/psychic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/psychic.py
new file mode 100644
index 0000000000000000000000000000000000000000..28f1478fa2f3a24a6ef0a33c308ffc0cb9e286d1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/psychic.py
@@ -0,0 +1,40 @@
+from typing import Iterator, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+
+
+class PsychicLoader(BaseLoader):
+ """Load from `Psychic.dev`."""
+
+ def __init__(
+ self, api_key: str, account_id: str, connector_id: Optional[str] = None
+ ):
+ """Initialize with API key, connector id, and account id.
+
+ Args:
+ api_key: The Psychic API key.
+ account_id: The Psychic account id.
+ connector_id: The Psychic connector id.
+ """
+
+ try:
+ from psychicapi import ConnectorId, Psychic
+ except ImportError:
+ raise ImportError(
+ "`psychicapi` package not found, please run `pip install psychicapi`"
+ )
+ self.psychic = Psychic(secret_key=api_key)
+ self.connector_id = ConnectorId(connector_id)
+ self.account_id = account_id
+
+ def lazy_load(self) -> Iterator[Document]:
+ psychic_docs = self.psychic.get_documents(
+ connector_id=self.connector_id, account_id=self.account_id
+ )
+ for doc in psychic_docs.documents:
+ yield Document(
+ page_content=doc["content"],
+ metadata={"title": doc["title"], "source": doc["uri"]},
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/pubmed.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/pubmed.py
new file mode 100644
index 0000000000000000000000000000000000000000..78d89977b549d06ee7d14b7b4fcaf8bf2be11a66
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_community/document_loaders/pubmed.py
@@ -0,0 +1,37 @@
+from typing import Iterator, Optional
+
+from langchain_core.documents import Document
+
+from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.utilities.pubmed import PubMedAPIWrapper
+
+
+class PubMedLoader(BaseLoader):
+ """Load from the `PubMed` biomedical library.
+
+ Attributes:
+ query: The query to be passed to the PubMed API.
+ load_max_docs: The maximum number of documents to load.
+ """
+
+ def __init__(
+ self,
+ query: str,
+ load_max_docs: Optional[int] = 3,
+ ):
+ """Initialize the PubMedLoader.
+
+ Args:
+ query: The query to be passed to the PubMed API.
+ load_max_docs: The maximum number of documents to load.
+ Defaults to 3.
+ """
+ self.query = query
+ self.load_max_docs = load_max_docs
+ self._client = PubMedAPIWrapper( # type: ignore[call-arg]
+ top_k_results=load_max_docs, # type: ignore[arg-type]
+ )
+
+ def lazy_load(self) -> Iterator[Document]:
+ for doc in self._client.lazy_load_docs(self.query):
+ yield doc
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cf2c2185a0955a4ac88055a2ceb34921a287328
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/_import_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/_import_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5dcc161749f3d9f32be9c4d4e196756c1bf81919
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/_import_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/agents.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/agents.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a14e447b6b3180169a67c5341c04535db306838f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/agents.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/caches.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/caches.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea73250dedced80c17245e05c2dd9d4744df94b8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/caches.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/chat_history.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/chat_history.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d4f1f72091bcb425ec70b4452cb33dce38fee067
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/chat_history.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/chat_loaders.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/chat_loaders.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9cd8f8b3b5ed5a40c860c6b74087fce951eb5b6
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/chat_loaders.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/chat_sessions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/chat_sessions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fd4350de62a8ebd7c71f2f6f9c20a3b145407952
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/chat_sessions.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/cross_encoders.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/cross_encoders.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd2668d58e319e55bdcde108455852c92a53e694
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/cross_encoders.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/env.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/env.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6db903fdd2ee0f97f74aec88447e09a2d2a77204
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/env.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/exceptions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd050b9422095ded415e0886c18679680a954ce6
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/exceptions.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/globals.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/globals.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33beffca31319976c55711ba59537b85d184d81e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/globals.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/prompt_values.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/prompt_values.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..114530ebe71ef13294a50c3e5ad32faca1505f11
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/prompt_values.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/rate_limiters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/rate_limiters.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff9f3da36de9c29a01a7f70fc0242a5b32eeee8c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/rate_limiters.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/retrievers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/retrievers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..092fa13e3df6f0f3455607bb07c57218c8e3a61e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/retrievers.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/stores.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/stores.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17bad8d52d62a5b8707681ed89117313e2c847a7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/stores.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/structured_query.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/structured_query.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec9fda4069119f2342a3c3ff634da1d413fdcf90
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/structured_query.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/sys_info.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/sys_info.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d48efeed2dab59f4c187f6faa019896c35c4634
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/sys_info.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/version.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/version.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e036a7d5da3c521972020d00e2b26765d861dc17
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/__pycache__/version.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1028cd366bb906c26f8c4dfe04081a2aba1fcda2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__init__.py
@@ -0,0 +1,87 @@
+"""Helper functions for managing the LangChain API.
+
+This module is only relevant for LangChain developers, not for users.
+
+!!! warning
+
+ This module and its submodules are for internal use only. Do not use them in your
+ own code. We may change the API at any time with no warning.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core._api.beta_decorator import (
+ LangChainBetaWarning,
+ beta,
+ suppress_langchain_beta_warning,
+ surface_langchain_beta_warnings,
+ )
+ from langchain_core._api.deprecation import (
+ LangChainDeprecationWarning,
+ deprecated,
+ suppress_langchain_deprecation_warning,
+ surface_langchain_deprecation_warnings,
+ warn_deprecated,
+ )
+ from langchain_core._api.path import as_import_path, get_relative_path
+
+__all__ = (
+ "LangChainBetaWarning",
+ "LangChainDeprecationWarning",
+ "as_import_path",
+ "beta",
+ "deprecated",
+ "get_relative_path",
+ "suppress_langchain_beta_warning",
+ "suppress_langchain_deprecation_warning",
+ "surface_langchain_beta_warnings",
+ "surface_langchain_deprecation_warnings",
+ "warn_deprecated",
+)
+
+_dynamic_imports = {
+ "LangChainBetaWarning": "beta_decorator",
+ "beta": "beta_decorator",
+ "suppress_langchain_beta_warning": "beta_decorator",
+ "surface_langchain_beta_warnings": "beta_decorator",
+ "as_import_path": "path",
+ "get_relative_path": "path",
+ "LangChainDeprecationWarning": "deprecation",
+ "deprecated": "deprecation",
+ "surface_langchain_deprecation_warnings": "deprecation",
+ "suppress_langchain_deprecation_warning": "deprecation",
+ "warn_deprecated": "deprecation",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ """Dynamically import and return an attribute from a submodule.
+
+ This function enables lazy loading of API functions from submodules, reducing
+ initial import time and circular dependency issues.
+
+ Args:
+ attr_name: Name of the attribute to import.
+
+ Returns:
+ The imported attribute object.
+
+ Raises:
+ AttributeError: If the attribute is not a valid dynamic import.
+ """
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ """Return a list of available attributes for this module.
+
+ Returns:
+ List of attribute names that can be imported from this module.
+ """
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9245729c697dc8cefd9c8772536f8057682a5014
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/beta_decorator.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/beta_decorator.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..814d114ad9c137acba1c496507431d92ef311297
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/beta_decorator.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/deprecation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/deprecation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ae195605fc3c1955b843a84fcf9d9a5ca3e89471
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/deprecation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/internal.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/internal.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa6a648a634e501df0a623aa2b1cccc8a13b3cef
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/internal.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/path.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/path.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ec0b4cba95749e45ec82aa7b821b04d88777849
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/__pycache__/path.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/beta_decorator.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/beta_decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..94671a112249319a7742188786060aed12d8c59e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/beta_decorator.py
@@ -0,0 +1,253 @@
+"""Helper functions for marking parts of the LangChain API as beta.
+
+This module was loosely adapted from matplotlib's [`_api/deprecation.py`](https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py)
+module.
+
+!!! warning
+
+ This module is for internal use only. Do not use it in your own code. We may change
+ the API at any time with no warning.
+"""
+
+import contextlib
+import functools
+import inspect
+import warnings
+from collections.abc import Callable, Generator
+from typing import Any, TypeVar, cast
+
+from langchain_core._api.internal import is_caller_internal
+
+
+class LangChainBetaWarning(DeprecationWarning):
+ """A class for issuing beta warnings for LangChain users."""
+
+
+# PUBLIC API
+
+
+T = TypeVar("T", bound=Callable[..., Any] | type)
+
+
+def beta(
+ *,
+ message: str = "",
+ name: str = "",
+ obj_type: str = "",
+ addendum: str = "",
+) -> Callable[[T], T]:
+ """Decorator to mark a function, a class, or a property as beta.
+
+ When marking a classmethod, a staticmethod, or a property, the `@beta` decorator
+ should go *under* `@classmethod` and `@staticmethod` (i.e., `beta` should directly
+ decorate the underlying callable), but *over* `@property`.
+
+ When marking a class `C` intended to be used as a base class in a multiple
+ inheritance hierarchy, `C` *must* define an `__init__` method (if `C` instead
+ inherited its `__init__` from its own base class, then `@beta` would mess up
+ `__init__` inheritance when installing its own (annotation-emitting) `C.__init__`).
+
+ Args:
+ message: Override the default beta message.
+
+ The %(since)s, %(name)s, %(alternative)s, %(obj_type)s, %(addendum)s, and
+ %(removal)s format specifiers will be replaced by the values of the
+ respective arguments passed to this function.
+ name: The name of the beta object.
+ obj_type: The object type being beta.
+ addendum: Additional text appended directly to the final message.
+
+ Returns:
+ A decorator which can be used to mark functions or classes as beta.
+
+ Example:
+ ```python
+ @beta
+ def the_function_to_annotate():
+ pass
+ ```
+ """
+
+ def beta(
+ obj: T,
+ *,
+ _obj_type: str = obj_type,
+ _name: str = name,
+ _message: str = message,
+ _addendum: str = addendum,
+ ) -> T:
+ """Implementation of the decorator returned by `beta`."""
+
+ def emit_warning() -> None:
+ """Emit the warning."""
+ warn_beta(
+ message=_message,
+ name=_name,
+ obj_type=_obj_type,
+ addendum=_addendum,
+ )
+
+ warned = False
+
+ def warning_emitting_wrapper(*args: Any, **kwargs: Any) -> Any:
+ """Wrapper for the original wrapped callable that emits a warning.
+
+ Args:
+ *args: The positional arguments to the function.
+ **kwargs: The keyword arguments to the function.
+
+ Returns:
+ The return value of the function being wrapped.
+ """
+ nonlocal warned
+ if not warned and not is_caller_internal():
+ warned = True
+ emit_warning()
+ return wrapped(*args, **kwargs)
+
+ async def awarning_emitting_wrapper(*args: Any, **kwargs: Any) -> Any:
+ """Same as warning_emitting_wrapper, but for async functions."""
+ nonlocal warned
+ if not warned and not is_caller_internal():
+ warned = True
+ emit_warning()
+ return await wrapped(*args, **kwargs)
+
+ if isinstance(obj, type):
+ if not _obj_type:
+ _obj_type = "class"
+ wrapped = obj.__init__ # type: ignore[misc]
+ _name = _name or obj.__qualname__
+ old_doc = obj.__doc__
+
+ def finalize(_: Callable[..., Any], new_doc: str, /) -> T:
+ """Finalize the annotation of a class."""
+ # Can't set new_doc on some extension objects.
+ with contextlib.suppress(AttributeError):
+ obj.__doc__ = new_doc
+
+ def warn_if_direct_instance(
+ self: Any, *args: Any, **kwargs: Any
+ ) -> Any:
+ """Warn that the class is in beta."""
+ nonlocal warned
+ if not warned and type(self) is obj and not is_caller_internal():
+ warned = True
+ emit_warning()
+ return wrapped(self, *args, **kwargs)
+
+ obj.__init__ = functools.wraps(obj.__init__)( # type: ignore[misc]
+ warn_if_direct_instance
+ )
+ return obj
+
+ elif isinstance(obj, property):
+ if not _obj_type:
+ _obj_type = "attribute"
+ wrapped = None
+ _name = _name or obj.fget.__qualname__
+ old_doc = obj.__doc__
+
+ def _fget(instance: Any) -> Any:
+ if instance is not None:
+ emit_warning()
+ return obj.fget(instance)
+
+ def _fset(instance: Any, value: Any) -> None:
+ if instance is not None:
+ emit_warning()
+ obj.fset(instance, value)
+
+ def _fdel(instance: Any) -> None:
+ if instance is not None:
+ emit_warning()
+ obj.fdel(instance)
+
+ def finalize(_: Callable[..., Any], new_doc: str, /) -> Any:
+ """Finalize the property."""
+ return property(fget=_fget, fset=_fset, fdel=_fdel, doc=new_doc)
+
+ else:
+ _name = _name or obj.__qualname__
+ if not _obj_type:
+ # edge case: when a function is within another function
+ # within a test, this will call it a "method" not a "function"
+ _obj_type = "function" if "." not in _name else "method"
+ wrapped = obj
+ old_doc = wrapped.__doc__
+
+ def finalize(wrapper: Callable[..., Any], new_doc: str, /) -> T:
+ """Wrap the wrapped function using the wrapper and update the docstring.
+
+ Args:
+ wrapper: The wrapper function.
+ new_doc: The new docstring.
+
+ Returns:
+ The wrapped function.
+ """
+ wrapper = functools.wraps(wrapped)(wrapper)
+ wrapper.__doc__ = new_doc
+ return cast("T", wrapper)
+
+ old_doc = inspect.cleandoc(old_doc or "").strip("\n") or ""
+ components = [message, addendum]
+ details = " ".join([component.strip() for component in components if component])
+ new_doc = f".. beta::\n {details}\n\n{old_doc}\n"
+
+ if inspect.iscoroutinefunction(obj):
+ return finalize(awarning_emitting_wrapper, new_doc)
+ return finalize(warning_emitting_wrapper, new_doc)
+
+ return beta
+
+
+@contextlib.contextmanager
+def suppress_langchain_beta_warning() -> Generator[None, None, None]:
+ """Context manager to suppress `LangChainDeprecationWarning`."""
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", LangChainBetaWarning)
+ yield
+
+
+def warn_beta(
+ *,
+ message: str = "",
+ name: str = "",
+ obj_type: str = "",
+ addendum: str = "",
+) -> None:
+ """Display a standardized beta annotation.
+
+ Args:
+ message: Override the default beta message.
+
+ The %(name)s, %(obj_type)s, %(addendum)s format specifiers will be replaced
+ by the values of the respective arguments passed to this function.
+ name: The name of the annotated object.
+ obj_type: The object type being annotated.
+ addendum: Additional text appended directly to the final message.
+ """
+ if not message:
+ message = ""
+
+ if obj_type:
+ message += f"The {obj_type} `{name}`"
+ else:
+ message += f"`{name}`"
+
+ message += " is in beta. It is actively being worked on, so the API may change."
+
+ if addendum:
+ message += f" {addendum}"
+
+ warning = LangChainBetaWarning(message)
+ warnings.warn(warning, category=LangChainBetaWarning, stacklevel=4)
+
+
+def surface_langchain_beta_warnings() -> None:
+ """Unmute LangChain beta warnings."""
+ warnings.filterwarnings(
+ "default",
+ category=LangChainBetaWarning,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/deprecation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccc31d6b9a5fcff4a2ee6f325c11009338951190
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/deprecation.py
@@ -0,0 +1,617 @@
+"""Helper functions for deprecating parts of the LangChain API.
+
+This module was adapted from matplotlib's [`_api/deprecation.py`](https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py)
+module.
+
+!!! warning
+
+ This module is for internal use only. Do not use it in your own code. We may change
+ the API at any time with no warning.
+"""
+
+import contextlib
+import functools
+import inspect
+import sys
+import warnings
+from collections.abc import Callable, Generator
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ ParamSpec,
+ TypeGuard,
+ TypeVar,
+ cast,
+)
+
+from pydantic.fields import FieldInfo
+
+from langchain_core._api.internal import is_caller_internal
+
+if TYPE_CHECKING:
+ from pydantic.v1.fields import FieldInfo as FieldInfoV1
+
+
+def _is_pydantic_v1_field_info(obj: Any) -> TypeGuard["FieldInfoV1"]:
+ """Check if `obj` is a `pydantic.v1.fields.FieldInfo` without forcing import.
+
+ Importing `pydantic.v1` emits a `UserWarning` on Python 3.14+. Skipping the
+ import entirely when no caller has constructed a v1 `FieldInfo` keeps that
+ warning out of `langchain_core`'s import path. If a caller did construct one,
+ `pydantic.v1.fields` is already in `sys.modules` and isinstance is safe.
+ """
+ mod = sys.modules.get("pydantic.v1.fields")
+ if mod is None:
+ return False
+ return isinstance(obj, mod.FieldInfo)
+
+
+def _build_deprecation_message(
+ *,
+ alternative: str = "",
+ alternative_import: str = "",
+) -> str:
+ """Build a simple deprecation message for `__deprecated__` attribute.
+
+ Args:
+ alternative: An alternative API name.
+ alternative_import: A fully qualified import path for the alternative.
+
+ Returns:
+ A deprecation message string for IDE/type checker display.
+ """
+ if alternative_import:
+ return f"Use {alternative_import} instead."
+ if alternative:
+ return f"Use {alternative} instead."
+ return "Deprecated."
+
+
+class LangChainDeprecationWarning(DeprecationWarning):
+ """A class for issuing deprecation warnings for LangChain users."""
+
+
+class LangChainPendingDeprecationWarning(PendingDeprecationWarning):
+ """A class for issuing deprecation warnings for LangChain users."""
+
+
+# PUBLIC API
+
+
+# Bound is `Any` (not `FieldInfoV1`) because importing `pydantic.v1` at module
+# scope emits a `UserWarning` on Python 3.14+; v1 `FieldInfo` support is handled
+# at runtime via `_is_pydantic_v1_field_info`.
+T = TypeVar("T", bound=type | Callable[..., Any] | Any)
+
+
+def _validate_deprecation_params(
+ removal: str,
+ alternative: str,
+ alternative_import: str,
+ *,
+ pending: bool,
+) -> None:
+ """Validate the deprecation parameters."""
+ if pending and removal:
+ msg = "A pending deprecation cannot have a scheduled removal"
+ raise ValueError(msg)
+ if alternative and alternative_import:
+ msg = "Cannot specify both alternative and alternative_import"
+ raise ValueError(msg)
+
+ if alternative_import and "." not in alternative_import:
+ msg = (
+ "alternative_import must be a fully qualified module path. Got "
+ f" {alternative_import}"
+ )
+ raise ValueError(msg)
+
+
+def deprecated(
+ since: str,
+ *,
+ message: str = "",
+ name: str = "",
+ alternative: str = "",
+ alternative_import: str = "",
+ pending: bool = False,
+ obj_type: str = "",
+ addendum: str = "",
+ removal: str = "",
+ package: str = "",
+) -> Callable[[T], T]:
+ """Decorator to mark a function, a class, or a property as deprecated.
+
+ When deprecating a classmethod, a staticmethod, or a property, the `@deprecated`
+ decorator should go *under* `@classmethod` and `@staticmethod` (i.e., `deprecated`
+ should directly decorate the underlying callable), but *over* `@property`.
+
+ When deprecating a class `C` intended to be used as a base class in a multiple
+ inheritance hierarchy, `C` *must* define an `__init__` method (if `C` instead
+ inherited its `__init__` from its own base class, then `@deprecated` would mess up
+ `__init__` inheritance when installing its own (deprecation-emitting) `C.__init__`).
+
+ Parameters are the same as for `warn_deprecated`, except that *obj_type* defaults to
+ 'class' if decorating a class, 'attribute' if decorating a property, and 'function'
+ otherwise.
+
+ Args:
+ since: The release at which this API became deprecated.
+ message: Override the default deprecation message.
+
+ The `%(since)s`, `%(name)s`, `%(alternative)s`, `%(obj_type)s`,
+ `%(addendum)s`, and `%(removal)s` format specifiers will be replaced by the
+ values of the respective arguments passed to this function.
+ name: The name of the deprecated object.
+ alternative: An alternative API that the user may use in place of the deprecated
+ API.
+
+ The deprecation warning will tell the user about this alternative if
+ provided.
+ alternative_import: An alternative import that the user may use instead.
+ pending: If `True`, uses a `PendingDeprecationWarning` instead of a
+ `DeprecationWarning`.
+
+ Cannot be used together with removal.
+ obj_type: The object type being deprecated.
+ addendum: Additional text appended directly to the final message.
+ removal: The expected removal version.
+
+ With the default (an empty string), no removal version is shown in the
+ warning message.
+
+ Cannot be used together with pending.
+ package: The package of the deprecated object.
+
+ Returns:
+ A decorator to mark a function or class as deprecated.
+
+ Example:
+ ```python
+ @deprecated("1.4.0")
+ def the_function_to_deprecate():
+ pass
+ ```
+ """
+ _validate_deprecation_params(
+ removal, alternative, alternative_import, pending=pending
+ )
+
+ def deprecate(
+ obj: T,
+ *,
+ _obj_type: str = obj_type,
+ _name: str = name,
+ _message: str = message,
+ _alternative: str = alternative,
+ _alternative_import: str = alternative_import,
+ _pending: bool = pending,
+ _addendum: str = addendum,
+ _package: str = package,
+ ) -> T:
+ """Implementation of the decorator returned by `deprecated`."""
+
+ def emit_warning() -> None:
+ """Emit the warning."""
+ warn_deprecated(
+ since,
+ message=_message,
+ name=_name,
+ alternative=_alternative,
+ alternative_import=_alternative_import,
+ pending=_pending,
+ obj_type=_obj_type,
+ addendum=_addendum,
+ removal=removal,
+ package=_package,
+ )
+
+ warned = False
+
+ def warning_emitting_wrapper(*args: Any, **kwargs: Any) -> Any:
+ """Wrapper for the original wrapped callable that emits a warning.
+
+ Args:
+ *args: The positional arguments to the function.
+ **kwargs: The keyword arguments to the function.
+
+ Returns:
+ The return value of the function being wrapped.
+ """
+ nonlocal warned
+ if not warned and not is_caller_internal():
+ warned = True
+ emit_warning()
+ return wrapped(*args, **kwargs)
+
+ async def awarning_emitting_wrapper(*args: Any, **kwargs: Any) -> Any:
+ """Same as warning_emitting_wrapper, but for async functions."""
+ nonlocal warned
+ if not warned and not is_caller_internal():
+ warned = True
+ emit_warning()
+ return await wrapped(*args, **kwargs)
+
+ _package = _package or obj.__module__.split(".")[0].replace("_", "-")
+
+ if isinstance(obj, type):
+ if not _obj_type:
+ _obj_type = "class"
+ wrapped = obj.__init__ # type: ignore[misc]
+ _name = _name or obj.__qualname__
+ old_doc = obj.__doc__
+
+ def finalize(_: Callable[..., Any], new_doc: str, /) -> T:
+ """Finalize the deprecation of a class."""
+ # Can't set new_doc on some extension objects.
+ with contextlib.suppress(AttributeError):
+ obj.__doc__ = new_doc
+
+ def warn_if_direct_instance(
+ self: Any, *args: Any, **kwargs: Any
+ ) -> Any:
+ """Warn that the class is in beta."""
+ nonlocal warned
+ if not warned and type(self) is obj and not is_caller_internal():
+ warned = True
+ emit_warning()
+ return wrapped(self, *args, **kwargs)
+
+ obj.__init__ = functools.wraps(obj.__init__)( # type: ignore[misc]
+ warn_if_direct_instance
+ )
+ # Set __deprecated__ for PEP 702 (IDE/type checker support)
+ obj.__deprecated__ = _build_deprecation_message( # type: ignore[attr-defined]
+ alternative=alternative,
+ alternative_import=alternative_import,
+ )
+ return obj
+
+ elif _is_pydantic_v1_field_info(obj):
+ wrapped = None
+ if not _obj_type:
+ _obj_type = "attribute"
+ if not _name:
+ msg = f"Field {obj} must have a name to be deprecated."
+ raise ValueError(msg)
+ old_doc = obj.description
+
+ def finalize(_: Callable[..., Any], new_doc: str, /) -> T:
+ from pydantic.v1.fields import FieldInfo as FieldInfoV1 # noqa: PLC0415
+
+ return cast(
+ "T",
+ FieldInfoV1(
+ default=obj.default,
+ default_factory=obj.default_factory,
+ description=new_doc,
+ alias=obj.alias,
+ exclude=obj.exclude,
+ ),
+ )
+
+ elif isinstance(obj, FieldInfo):
+ wrapped = None
+ if not _obj_type:
+ _obj_type = "attribute"
+ if not _name:
+ msg = f"Field {obj} must have a name to be deprecated."
+ raise ValueError(msg)
+ old_doc = obj.description
+
+ def finalize(_: Callable[..., Any], new_doc: str, /) -> T:
+ return cast(
+ "T",
+ FieldInfo(
+ default=obj.default,
+ default_factory=obj.default_factory,
+ description=new_doc,
+ alias=obj.alias,
+ exclude=obj.exclude,
+ ),
+ )
+
+ elif isinstance(obj, property):
+ if not _obj_type:
+ _obj_type = "attribute"
+ wrapped = None
+ _name = _name or cast("type | Callable", obj.fget).__qualname__
+ old_doc = obj.__doc__
+
+ class _DeprecatedProperty(property):
+ """A deprecated property."""
+
+ def __init__(
+ self,
+ fget: Callable[[Any], Any] | None = None,
+ fset: Callable[[Any, Any], None] | None = None,
+ fdel: Callable[[Any], None] | None = None,
+ doc: str | None = None,
+ ) -> None:
+ super().__init__(fget, fset, fdel, doc)
+ self.__orig_fget = fget
+ self.__orig_fset = fset
+ self.__orig_fdel = fdel
+
+ def __get__(self, instance: Any, owner: type | None = None) -> Any:
+ if instance is not None or owner is not None:
+ emit_warning()
+ if self.fget is None:
+ return None
+ return self.fget(instance)
+
+ def __set__(self, instance: Any, value: Any) -> None:
+ if instance is not None:
+ emit_warning()
+ if self.fset is not None:
+ self.fset(instance, value)
+
+ def __delete__(self, instance: Any) -> None:
+ if instance is not None:
+ emit_warning()
+ if self.fdel is not None:
+ self.fdel(instance)
+
+ def __set_name__(self, owner: type | None, set_name: str) -> None:
+ nonlocal _name
+ if _name == "":
+ _name = set_name
+
+ def finalize(_: Callable[..., Any], new_doc: str, /) -> T:
+ """Finalize the property."""
+ prop = _DeprecatedProperty(
+ fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc
+ )
+ # Set __deprecated__ for PEP 702 (IDE/type checker support)
+ prop.__deprecated__ = _build_deprecation_message( # type: ignore[attr-defined]
+ alternative=alternative,
+ alternative_import=alternative_import,
+ )
+ return cast("T", prop)
+
+ else:
+ _name = _name or cast("type | Callable", obj).__qualname__
+ if not _obj_type:
+ # edge case: when a function is within another function
+ # within a test, this will call it a "method" not a "function"
+ _obj_type = "function" if "." not in _name else "method"
+ wrapped = obj
+ old_doc = wrapped.__doc__
+
+ def finalize(wrapper: Callable[..., Any], new_doc: str, /) -> T:
+ """Wrap the wrapped function using the wrapper and update the docstring.
+
+ Args:
+ wrapper: The wrapper function.
+ new_doc: The new docstring.
+
+ Returns:
+ The wrapped function.
+ """
+ wrapper = functools.wraps(wrapped)(wrapper)
+ wrapper.__doc__ = new_doc
+ # Set __deprecated__ for PEP 702 (IDE/type checker support)
+ wrapper.__deprecated__ = _build_deprecation_message( # type: ignore[attr-defined]
+ alternative=alternative,
+ alternative_import=alternative_import,
+ )
+ return cast("T", wrapper)
+
+ old_doc = inspect.cleandoc(old_doc or "").strip("\n")
+
+ # old_doc can be None
+ if not old_doc:
+ old_doc = ""
+
+ # Modify the docstring to include a deprecation notice.
+ if (
+ _alternative
+ and _alternative.rsplit(".", maxsplit=1)[-1].lower()
+ == _alternative.rsplit(".", maxsplit=1)[-1]
+ ) or _alternative:
+ _alternative = f"`{_alternative}`"
+
+ if (
+ _alternative_import
+ and _alternative_import.rsplit(".", maxsplit=1)[-1].lower()
+ == _alternative_import.rsplit(".", maxsplit=1)[-1]
+ ) or _alternative_import:
+ _alternative_import = f"`{_alternative_import}`"
+
+ components = [
+ _message,
+ f"Use {_alternative} instead." if _alternative else "",
+ f"Use {_alternative_import} instead." if _alternative_import else "",
+ _addendum,
+ ]
+ details = " ".join([component.strip() for component in components if component])
+ package = _package or (
+ _name.split(".")[0].replace("_", "-") if "." in _name else None
+ )
+ if removal:
+ if removal.startswith("1.") and package and package.startswith("langchain"):
+ removal_str = f"It will not be removed until {package}=={removal}."
+ else:
+ removal_str = f"It will be removed in {package}=={removal}."
+ else:
+ removal_str = ""
+ new_doc = f"""\
+!!! deprecated "{since} {details} {removal_str}"
+
+{old_doc}\
+"""
+
+ if inspect.iscoroutinefunction(obj):
+ return finalize(awarning_emitting_wrapper, new_doc)
+ return finalize(warning_emitting_wrapper, new_doc)
+
+ return deprecate
+
+
+@contextlib.contextmanager
+def suppress_langchain_deprecation_warning() -> Generator[None, None, None]:
+ """Context manager to suppress `LangChainDeprecationWarning`."""
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", LangChainDeprecationWarning)
+ warnings.simplefilter("ignore", LangChainPendingDeprecationWarning)
+ yield
+
+
+def warn_deprecated(
+ since: str,
+ *,
+ message: str = "",
+ name: str = "",
+ alternative: str = "",
+ alternative_import: str = "",
+ pending: bool = False,
+ obj_type: str = "",
+ addendum: str = "",
+ removal: str = "",
+ package: str = "",
+) -> None:
+ """Display a standardized deprecation.
+
+ Args:
+ since: The release at which this API became deprecated.
+ message: Override the default deprecation message.
+
+ The `%(since)s`, `%(name)s`, `%(alternative)s`, `%(obj_type)s`,
+ `%(addendum)s`, and `%(removal)s` format specifiers will be replaced by the
+ values of the respective arguments passed to this function.
+ name: The name of the deprecated object.
+ alternative: An alternative API that the user may use in place of the
+ deprecated API.
+
+ The deprecation warning will tell the user about this alternative if
+ provided.
+ alternative_import: An alternative import that the user may use instead.
+ pending: If `True`, uses a `PendingDeprecationWarning` instead of a
+ `DeprecationWarning`.
+
+ Cannot be used together with removal.
+ obj_type: The object type being deprecated.
+ addendum: Additional text appended directly to the final message.
+ removal: The expected removal version.
+
+ With the default (an empty string), no removal version is shown in the
+ warning message.
+
+ Cannot be used together with pending.
+ package: The package of the deprecated object.
+ """
+ if not pending and removal:
+ removal = f"in {removal}"
+
+ if not message:
+ message = ""
+ package_ = (
+ package or name.split(".", maxsplit=1)[0].replace("_", "-")
+ if "." in name
+ else "LangChain"
+ )
+
+ if obj_type:
+ message += f"The {obj_type} `{name}`"
+ else:
+ message += f"`{name}`"
+
+ if pending:
+ message += " will be deprecated in a future version"
+ else:
+ message += f" was deprecated in {package_} {since}"
+
+ if removal:
+ message += f" and will be removed {removal}"
+
+ if alternative_import:
+ alt_package = alternative_import.split(".", maxsplit=1)[0].replace("_", "-")
+ if alt_package == package_:
+ message += f". Use {alternative_import} instead."
+ else:
+ alt_module, alt_name = alternative_import.rsplit(".", 1)
+ message += (
+ f". An updated version of the {obj_type} exists in the "
+ f"{alt_package} package and should be used instead. To use it run "
+ f"`pip install -U {alt_package}` and import as "
+ f"`from {alt_module} import {alt_name}`."
+ )
+ elif alternative:
+ message += f". Use {alternative} instead."
+
+ if addendum:
+ message += f" {addendum}"
+
+ warning_cls = (
+ LangChainPendingDeprecationWarning if pending else LangChainDeprecationWarning
+ )
+ warning = warning_cls(message)
+ warnings.warn(warning, category=LangChainDeprecationWarning, stacklevel=4)
+
+
+def surface_langchain_deprecation_warnings() -> None:
+ """Unmute LangChain deprecation warnings."""
+ warnings.filterwarnings(
+ "default",
+ category=LangChainPendingDeprecationWarning,
+ )
+
+ warnings.filterwarnings(
+ "default",
+ category=LangChainDeprecationWarning,
+ )
+
+
+_P = ParamSpec("_P")
+_R = TypeVar("_R")
+
+
+def rename_parameter(
+ *,
+ since: str,
+ removal: str,
+ old: str,
+ new: str,
+) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]:
+ """Decorator indicating that parameter *old* of *func* is renamed to *new*.
+
+ The actual implementation of *func* should use *new*, not *old*. If *old* is passed
+ to *func*, a `DeprecationWarning` is emitted, and its value is used, even if *new*
+ is also passed by keyword.
+
+ Args:
+ since: The version in which the parameter was renamed.
+ removal: The version in which the old parameter will be removed.
+ old: The old parameter name.
+ new: The new parameter name.
+
+ Returns:
+ A decorator indicating that a parameter was renamed.
+
+ Example:
+ ```python
+ @_api.rename_parameter("3.1", "bad_name", "good_name")
+ def func(good_name): ...
+ ```
+ """
+
+ def decorator(f: Callable[_P, _R]) -> Callable[_P, _R]:
+ @functools.wraps(f)
+ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
+ if new in kwargs and old in kwargs:
+ msg = f"{f.__name__}() got multiple values for argument {new!r}"
+ raise TypeError(msg)
+ if old in kwargs:
+ warn_deprecated(
+ since,
+ removal=removal,
+ message=f"The parameter `{old}` of `{f.__name__}` was "
+ f"deprecated in {since} and will be removed "
+ f"in {removal} Use `{new}` instead.",
+ )
+ kwargs[new] = kwargs.pop(old)
+ return f(*args, **kwargs)
+
+ return wrapper
+
+ return decorator
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/internal.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bebb59347e27ba30bc0ff5c69c194ada210ca59
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/internal.py
@@ -0,0 +1,23 @@
+import inspect
+from typing import cast
+
+
+def is_caller_internal(depth: int = 2) -> bool:
+ """Return whether the caller at `depth` of this function is internal."""
+ try:
+ frame = inspect.currentframe()
+ except AttributeError:
+ return False
+ if frame is None:
+ return False
+ try:
+ for _ in range(depth):
+ frame = frame.f_back
+ if frame is None:
+ return False
+ # Directly access the module name from the frame's global variables
+ module_globals = frame.f_globals
+ caller_module_name = cast("str", module_globals.get("__name__", ""))
+ return caller_module_name.startswith("langchain")
+ finally:
+ del frame
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/path.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/path.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b597523eb9a8d315e8bb8fe5b4c86277c8cfbf6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_api/path.py
@@ -0,0 +1,50 @@
+import os
+from pathlib import Path
+
+HERE = Path(__file__).parent
+
+# Get directory of langchain package
+PACKAGE_DIR = HERE.parent
+SEPARATOR = os.sep
+
+
+def get_relative_path(file: Path | str, *, relative_to: Path = PACKAGE_DIR) -> str:
+ """Get the path of the file as a relative path to the package directory.
+
+ Args:
+ file: The file path to convert.
+ relative_to: The base path to make the file path relative to.
+
+ Returns:
+ The relative path as a string.
+ """
+ if isinstance(file, str):
+ file = Path(file)
+ return str(file.relative_to(relative_to))
+
+
+def as_import_path(
+ file: Path | str,
+ *,
+ suffix: str | None = None,
+ relative_to: Path = PACKAGE_DIR,
+) -> str:
+ """Path of the file as a LangChain import exclude langchain top namespace.
+
+ Args:
+ file: The file path to convert.
+ suffix: An optional suffix to append to the import path.
+ relative_to: The base path to make the file path relative to.
+
+ Returns:
+ The import path as a string.
+ """
+ if isinstance(file, str):
+ file = Path(file)
+ path = get_relative_path(file, relative_to=relative_to)
+ if file.is_file():
+ path = path[: -len(file.suffix)]
+ import_path = path.replace(SEPARATOR, ".")
+ if suffix:
+ import_path += "." + suffix
+ return import_path
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a6fd41939ffc2fb5b175c2c04c563426245296e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__init__.py
@@ -0,0 +1,36 @@
+"""SSRF protection and security utilities.
+
+This is an **internal** module (note the `_security` prefix). It is NOT part of
+the public `langchain-core` API and may change or be removed at any time without
+notice. External code should not import from or depend on anything in this
+module. Any vulnerability reports should target the public APIs that use these
+utilities, not this internal module directly.
+"""
+
+from langchain_core._security._exceptions import SSRFBlockedError
+from langchain_core._security._policy import (
+ SSRFPolicy,
+ validate_hostname,
+ validate_resolved_ip,
+ validate_url,
+ validate_url_sync,
+)
+from langchain_core._security._transport import (
+ SSRFSafeSyncTransport,
+ SSRFSafeTransport,
+ ssrf_safe_async_client,
+ ssrf_safe_client,
+)
+
+__all__ = [
+ "SSRFBlockedError",
+ "SSRFPolicy",
+ "SSRFSafeSyncTransport",
+ "SSRFSafeTransport",
+ "ssrf_safe_async_client",
+ "ssrf_safe_client",
+ "validate_hostname",
+ "validate_resolved_ip",
+ "validate_url",
+ "validate_url_sync",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d49ed08fa8198eee14504fbfdad0797db75fc5eb
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/_exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/_exceptions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e2883f296f4a17105ed762f504fd0893528b11bc
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/_exceptions.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/_policy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/_policy.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0595e0c91309f904b53553e206f15b1cd8456352
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/_policy.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/_ssrf_protection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/_ssrf_protection.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aeae5a3a376ffa2b82c51f5d13d48e8a81136120
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/_ssrf_protection.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/_transport.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/_transport.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..92fa2d162217c74cdccae9c3611408846a715c07
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/__pycache__/_transport.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/_exceptions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..6046a4829a8b45d51d3b5a4fc595e78e0621f165
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/_exceptions.py
@@ -0,0 +1,9 @@
+"""SSRF protection exceptions."""
+
+
+class SSRFBlockedError(Exception):
+ """Raised when a request is blocked by SSRF protection policy."""
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+ super().__init__(f"SSRF blocked: {reason}")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/_policy.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..79cf437c899a27d5f530ccbd4ecc55fd9995b0d4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/_policy.py
@@ -0,0 +1,306 @@
+"""SSRF protection policy with IP validation and DNS-aware URL checking."""
+
+import asyncio
+import dataclasses
+import ipaddress
+import os
+import socket
+import urllib.parse
+
+from langchain_core._security._exceptions import SSRFBlockedError
+
+# ---------------------------------------------------------------------------
+# Blocklist constants
+# ---------------------------------------------------------------------------
+
+_BLOCKED_IPV4_NETWORKS: tuple[ipaddress.IPv4Network, ...] = tuple(
+ ipaddress.IPv4Network(n)
+ for n in (
+ "10.0.0.0/8", # RFC 1918 - private class A
+ "172.16.0.0/12", # RFC 1918 - private class B
+ "192.168.0.0/16", # RFC 1918 - private class C
+ "127.0.0.0/8", # RFC 1122 - loopback
+ "169.254.0.0/16", # RFC 3927 - link-local
+ "0.0.0.0/8", # RFC 1122 - "this network"
+ "100.64.0.0/10", # RFC 6598 - shared/CGN address space
+ "192.0.0.0/24", # RFC 6890 - IETF protocol assignments
+ "192.0.2.0/24", # RFC 5737 - TEST-NET-1 (documentation)
+ "198.18.0.0/15", # RFC 2544 - benchmarking
+ "198.51.100.0/24", # RFC 5737 - TEST-NET-2 (documentation)
+ "203.0.113.0/24", # RFC 5737 - TEST-NET-3 (documentation)
+ "224.0.0.0/4", # RFC 5771 - multicast
+ "240.0.0.0/4", # RFC 1112 - reserved for future use
+ "255.255.255.255/32", # RFC 919 - limited broadcast
+ )
+)
+
+_BLOCKED_IPV6_NETWORKS: tuple[ipaddress.IPv6Network, ...] = tuple(
+ ipaddress.IPv6Network(n)
+ for n in (
+ "::1/128", # RFC 4291 - loopback
+ "fc00::/7", # RFC 4193 - unique local addresses (ULA)
+ "fe80::/10", # RFC 4291 - link-local
+ "ff00::/8", # RFC 4291 - multicast
+ "::ffff:0:0/96", # RFC 4291 - IPv4-mapped IPv6 addresses
+ "::0.0.0.0/96", # RFC 4291 - IPv4-compatible IPv6 (deprecated)
+ "64:ff9b::/96", # RFC 6052 - NAT64 well-known prefix
+ "64:ff9b:1::/48", # RFC 8215 - NAT64 discovery prefix
+ )
+)
+
+_CLOUD_METADATA_IPS: frozenset[str] = frozenset(
+ {
+ "169.254.169.254", # AWS, GCP, Azure, DigitalOcean, Oracle Cloud
+ "169.254.170.2", # AWS ECS task metadata
+ "169.254.170.23", # AWS EKS Pod Identity Agent
+ "100.100.100.200", # Alibaba Cloud metadata
+ "fd00:ec2::254", # AWS EC2 IMDSv2 over IPv6 (Nitro instances)
+ "fd00:ec2::23", # AWS EKS Pod Identity Agent (IPv6)
+ "fe80::a9fe:a9fe", # OpenStack Nova metadata (IPv6 link-local)
+ }
+)
+
+# Network ranges that are always blocked when block_cloud_metadata=True,
+# independent of block_private_ips. The entire link-local range is used by
+# cloud metadata services across providers.
+_CLOUD_METADATA_NETWORKS: tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, ...] = (
+ ipaddress.IPv4Network("169.254.0.0/16"),
+)
+
+_CLOUD_METADATA_HOSTNAMES: frozenset[str] = frozenset(
+ {
+ "metadata.google.internal",
+ "metadata.amazonaws.com",
+ "metadata",
+ "instance-data",
+ }
+)
+
+_LOCALHOST_NAMES: frozenset[str] = frozenset(
+ {
+ "localhost",
+ "localhost.localdomain",
+ "host.docker.internal",
+ }
+)
+
+_K8S_SUFFIX = ".svc.cluster.local"
+
+_LOOPBACK_IPV4 = ipaddress.IPv4Network("127.0.0.0/8")
+_LOOPBACK_IPV6 = ipaddress.IPv6Address("::1")
+
+# NAT64 well-known prefixes
+_NAT64_PREFIX = ipaddress.IPv6Network("64:ff9b::/96")
+_NAT64_DISCOVERY_PREFIX = ipaddress.IPv6Network("64:ff9b:1::/48")
+
+
+# ---------------------------------------------------------------------------
+# SSRFPolicy
+# ---------------------------------------------------------------------------
+
+
+@dataclasses.dataclass(frozen=True)
+class SSRFPolicy:
+ """Immutable policy controlling which URLs/IPs are considered safe."""
+
+ allowed_schemes: frozenset[str] = frozenset({"http", "https"})
+ block_private_ips: bool = True
+ block_localhost: bool = True
+ block_cloud_metadata: bool = True
+ block_k8s_internal: bool = True
+ allowed_hosts: frozenset[str] = frozenset()
+ additional_blocked_cidrs: tuple[
+ ipaddress.IPv4Network | ipaddress.IPv6Network, ...
+ ] = ()
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _extract_embedded_ipv4(
+ addr: ipaddress.IPv6Address,
+) -> ipaddress.IPv4Address | None:
+ """Extract an embedded IPv4 from IPv4-mapped or NAT64 IPv6 addresses."""
+ # Check ipv4_mapped first (covers ::ffff:x.x.x.x)
+ if addr.ipv4_mapped is not None:
+ return addr.ipv4_mapped
+
+ # Check NAT64 prefixes — embedded IPv4 is in the last 4 bytes
+ if addr in _NAT64_PREFIX or addr in _NAT64_DISCOVERY_PREFIX:
+ raw = addr.packed
+ return ipaddress.IPv4Address(raw[-4:])
+
+ return None
+
+
+def _ip_in_blocked_networks(
+ addr: ipaddress.IPv4Address | ipaddress.IPv6Address,
+ policy: SSRFPolicy,
+) -> str | None:
+ """Return a reason string if *addr* falls in a blocked range, else None."""
+ # NOTE: if profiling shows this is a hot path, consider memoising with
+ # @functools.lru_cache (key on (addr, id(policy))).
+ if isinstance(addr, ipaddress.IPv4Address):
+ if policy.block_private_ips:
+ for net in _BLOCKED_IPV4_NETWORKS:
+ if addr in net:
+ return "private IP range"
+ for net in policy.additional_blocked_cidrs: # type: ignore[assignment]
+ if isinstance(net, ipaddress.IPv4Network) and addr in net:
+ return "blocked CIDR"
+ else:
+ if policy.block_private_ips:
+ for net in _BLOCKED_IPV6_NETWORKS: # type: ignore[assignment]
+ if addr in net:
+ return "private IP range"
+ for net in policy.additional_blocked_cidrs: # type: ignore[assignment]
+ if isinstance(net, ipaddress.IPv6Network) and addr in net:
+ return "blocked CIDR"
+
+ # Loopback check — independent of block_private_ips so that
+ # block_localhost=True still catches 127.x.x.x / ::1 even when
+ # private IPs are allowed.
+ if policy.block_localhost:
+ if isinstance(addr, ipaddress.IPv4Address) and (
+ addr in _LOOPBACK_IPV4 or addr in ipaddress.IPv4Network("0.0.0.0/8")
+ ):
+ return "localhost address"
+ if isinstance(addr, ipaddress.IPv6Address) and addr == _LOOPBACK_IPV6:
+ return "localhost address"
+
+ # Cloud metadata check — IP set *and* network ranges (e.g. 169.254.0.0/16).
+ # Independent of block_private_ips so that allow_private=True still blocks
+ # cloud metadata endpoints.
+ if policy.block_cloud_metadata:
+ if str(addr) in _CLOUD_METADATA_IPS:
+ return "cloud metadata endpoint"
+ for net in _CLOUD_METADATA_NETWORKS: # type: ignore[assignment]
+ if addr in net:
+ return "cloud metadata endpoint"
+
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Public validation functions
+# ---------------------------------------------------------------------------
+
+
+def validate_resolved_ip(ip_str: str, policy: SSRFPolicy) -> None:
+ """Validate a resolved IP address against the SSRF policy.
+
+ Raises SSRFBlockedError if the IP is blocked.
+ """
+ try:
+ addr = ipaddress.ip_address(ip_str)
+ except ValueError as exc:
+ raise SSRFBlockedError("invalid IP address") from exc
+
+ if isinstance(addr, ipaddress.IPv6Address):
+ inner = _extract_embedded_ipv4(addr)
+ if inner is not None:
+ addr = inner
+
+ reason = _ip_in_blocked_networks(addr, policy)
+ if reason is not None:
+ raise SSRFBlockedError(reason)
+
+
+def validate_hostname(hostname: str, policy: SSRFPolicy) -> None:
+ """Validate a hostname against the SSRF policy.
+
+ Raises SSRFBlockedError if the hostname is blocked.
+ """
+ lower = hostname.lower()
+
+ if policy.block_localhost and lower in _LOCALHOST_NAMES:
+ raise SSRFBlockedError("localhost address")
+
+ if policy.block_cloud_metadata and lower in _CLOUD_METADATA_HOSTNAMES:
+ raise SSRFBlockedError("cloud metadata endpoint")
+
+ if policy.block_k8s_internal and lower.endswith(_K8S_SUFFIX):
+ raise SSRFBlockedError("Kubernetes internal DNS")
+
+
+def _effective_allowed_hosts(policy: SSRFPolicy) -> frozenset[str]:
+ """Return allowed_hosts, augmented for local environments."""
+ extra: set[str] = set()
+ if os.environ.get("LANGCHAIN_ENV", "").startswith("local"):
+ extra.update({"localhost", "testserver"})
+ if extra:
+ return policy.allowed_hosts | frozenset(extra)
+ return policy.allowed_hosts
+
+
+async def validate_url(url: str, policy: SSRFPolicy = SSRFPolicy()) -> None:
+ """Validate a URL against the SSRF policy, including DNS resolution.
+
+ This is the primary entry-point for async code paths. It delegates
+ scheme/hostname/allowed-hosts checks to `validate_url_sync`, then
+ resolves DNS and validates every resolved IP.
+
+ Raises:
+ SSRFBlockedError: If the URL violates the policy.
+ """
+ parsed = urllib.parse.urlparse(url)
+ hostname = parsed.hostname or ""
+
+ validate_url_sync(url, policy)
+
+ allowed = {h.lower() for h in _effective_allowed_hosts(policy)}
+ if hostname.lower() in allowed:
+ return
+
+ scheme = (parsed.scheme or "").lower()
+ port = parsed.port or (443 if scheme == "https" else 80)
+ try:
+ addrinfo = await asyncio.to_thread(
+ socket.getaddrinfo, hostname, port, type=socket.SOCK_STREAM
+ )
+ except socket.gaierror as exc:
+ msg = "DNS resolution failed"
+ raise SSRFBlockedError(msg) from exc
+
+ for _family, _type, _proto, _canonname, sockaddr in addrinfo:
+ validate_resolved_ip(str(sockaddr[0]), policy)
+
+
+def validate_url_sync(url: str, policy: SSRFPolicy = SSRFPolicy()) -> None:
+ """Synchronous URL validation (no DNS resolution).
+
+ Suitable for Pydantic validators and other sync contexts. Checks scheme
+ and hostname patterns only - use `validate_url` for full DNS-aware checking.
+
+ Raises:
+ SSRFBlockedError: If the URL violates the policy.
+ """
+ parsed = urllib.parse.urlparse(url)
+
+ scheme = (parsed.scheme or "").lower()
+ if scheme not in policy.allowed_schemes:
+ msg = f"scheme '{scheme}' not allowed"
+ raise SSRFBlockedError(msg)
+
+ hostname = parsed.hostname
+ if not hostname:
+ msg = "missing hostname"
+ raise SSRFBlockedError(msg)
+
+ allowed = _effective_allowed_hosts(policy)
+ if hostname.lower() in {h.lower() for h in allowed}:
+ return
+
+ try:
+ ipaddress.ip_address(hostname)
+ validate_resolved_ip(hostname, policy)
+ except SSRFBlockedError:
+ raise
+ except ValueError:
+ pass
+ else:
+ return
+
+ validate_hostname(hostname, policy)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/_ssrf_protection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/_ssrf_protection.py
new file mode 100644
index 0000000000000000000000000000000000000000..0eb3cd7e11c6e227602f013757910947c81c50dd
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/_ssrf_protection.py
@@ -0,0 +1,155 @@
+"""SSRF Protection - thin wrapper raising ValueError for internal callers.
+
+Delegates all validation to `langchain_core._security._policy`.
+"""
+
+import os
+import socket
+from typing import Annotated, Any
+from urllib.parse import urlparse
+
+from pydantic import (
+ AnyHttpUrl,
+ BeforeValidator,
+ HttpUrl,
+)
+
+from langchain_core._security._exceptions import SSRFBlockedError
+from langchain_core._security._policy import (
+ SSRFPolicy,
+)
+from langchain_core._security._policy import (
+ validate_resolved_ip as _validate_resolved_ip,
+)
+from langchain_core._security._policy import (
+ validate_url_sync as _validate_url_sync,
+)
+
+
+def _policy_for(*, allow_private: bool, allow_http: bool) -> SSRFPolicy:
+ """Build an `SSRFPolicy` from the legacy flag interface."""
+ schemes = frozenset({"http", "https"}) if allow_http else frozenset({"https"})
+ return SSRFPolicy(
+ allowed_schemes=schemes,
+ block_private_ips=not allow_private,
+ block_localhost=not allow_private,
+ block_cloud_metadata=True,
+ block_k8s_internal=True,
+ )
+
+
+def validate_safe_url(
+ url: str | AnyHttpUrl,
+ *,
+ allow_private: bool = False,
+ allow_http: bool = True,
+) -> str:
+ """Validate a URL for SSRF protection.
+
+ This function validates URLs to prevent Server-Side Request Forgery (SSRF) attacks
+ by blocking requests to private networks and cloud metadata endpoints.
+
+ Args:
+ url: The URL to validate (string or Pydantic HttpUrl).
+ allow_private: If `True`, allows private IPs and localhost (for development).
+ Cloud metadata endpoints are ALWAYS blocked.
+ allow_http: If `True`, allows both HTTP and HTTPS. If `False`, only HTTPS.
+
+ Returns:
+ The validated URL as a string.
+
+ Raises:
+ ValueError: If URL is invalid or potentially dangerous.
+ """
+ url_str = str(url)
+ parsed = urlparse(url_str)
+ hostname = parsed.hostname or ""
+
+ # Test-environment bypass (preserved from original implementation)
+ if (
+ os.environ.get("LANGCHAIN_ENV") == "local_test"
+ and hostname.startswith("test")
+ and "server" in hostname
+ ):
+ return url_str
+
+ policy = _policy_for(allow_private=allow_private, allow_http=allow_http)
+
+ # Synchronous scheme + hostname checks
+ try:
+ _validate_url_sync(url_str, policy)
+ except SSRFBlockedError as exc:
+ raise ValueError(str(exc)) from exc
+
+ # DNS resolution and IP validation
+ try:
+ addr_info = socket.getaddrinfo(
+ hostname,
+ parsed.port or (443 if parsed.scheme == "https" else 80),
+ socket.AF_UNSPEC,
+ socket.SOCK_STREAM,
+ )
+
+ for result in addr_info:
+ ip_str: str = result[4][0] # type: ignore[assignment]
+ try:
+ _validate_resolved_ip(ip_str, policy)
+ except SSRFBlockedError as exc:
+ raise ValueError(str(exc)) from exc
+
+ except socket.gaierror as e:
+ msg = f"Failed to resolve hostname '{hostname}': {e}"
+ raise ValueError(msg) from e
+ except OSError as e:
+ msg = f"Network error while validating URL: {e}"
+ raise ValueError(msg) from e
+
+ return url_str
+
+
+def is_safe_url(
+ url: str | AnyHttpUrl,
+ *,
+ allow_private: bool = False,
+ allow_http: bool = True,
+) -> bool:
+ """Non-throwing version of `validate_safe_url`."""
+ try:
+ validate_safe_url(url, allow_private=allow_private, allow_http=allow_http)
+ except ValueError:
+ return False
+ else:
+ return True
+
+
+def _validate_url_ssrf_strict(v: Any) -> Any:
+ """Validate URL for SSRF protection (strict mode)."""
+ if isinstance(v, str):
+ validate_safe_url(v, allow_private=False, allow_http=True)
+ return v
+
+
+def _validate_url_ssrf_https_only(v: Any) -> Any:
+ if isinstance(v, str):
+ validate_safe_url(v, allow_private=False, allow_http=False)
+ return v
+
+
+def _validate_url_ssrf_relaxed(v: Any) -> Any:
+ """Validate URL for SSRF protection (relaxed mode - allows private IPs)."""
+ if isinstance(v, str):
+ validate_safe_url(v, allow_private=True, allow_http=True)
+ return v
+
+
+# Annotated types with SSRF protection
+SSRFProtectedUrl = Annotated[HttpUrl, BeforeValidator(_validate_url_ssrf_strict)]
+SSRFProtectedUrlRelaxed = Annotated[
+ HttpUrl, BeforeValidator(_validate_url_ssrf_relaxed)
+]
+SSRFProtectedHttpsUrl = Annotated[
+ HttpUrl, BeforeValidator(_validate_url_ssrf_https_only)
+]
+SSRFProtectedHttpsUrlStr = Annotated[
+ str, BeforeValidator(_validate_url_ssrf_https_only)
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/_transport.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/_transport.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bbc8d8989fcd5f379af83f1e36d268d059907db
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/_security/_transport.py
@@ -0,0 +1,252 @@
+"""SSRF-safe httpx transport with DNS resolution and IP pinning."""
+
+import asyncio
+import socket
+
+import httpx
+
+from langchain_core._security._exceptions import SSRFBlockedError
+from langchain_core._security._policy import (
+ SSRFPolicy,
+ _effective_allowed_hosts,
+ validate_resolved_ip,
+ validate_url_sync,
+)
+
+# Keys that AsyncHTTPTransport accepts (forwarded from factory kwargs).
+_TRANSPORT_KWARGS = frozenset(
+ {
+ "verify",
+ "cert",
+ "trust_env",
+ "http1",
+ "http2",
+ "limits",
+ "retries",
+ }
+)
+
+
+class SSRFSafeTransport(httpx.AsyncBaseTransport):
+ """httpx async transport that validates DNS results against an SSRF policy.
+
+ For every outgoing request the transport:
+ 1. Checks the URL scheme against `policy.allowed_schemes`.
+ 2. Validates the hostname against blocked patterns.
+ 3. Resolves DNS and validates **all** returned IPs.
+ 4. Rewrites the request to connect to the first valid IP while
+ preserving the original `Host` header and TLS SNI hostname.
+
+ Redirects are re-validated on each hop because `follow_redirects`
+ is set on the *client*, causing `handle_async_request` to be called
+ again for each redirect target.
+ """
+
+ def __init__(
+ self,
+ policy: SSRFPolicy = SSRFPolicy(),
+ **transport_kwargs: object,
+ ) -> None:
+ self._policy = policy
+ self._inner = httpx.AsyncHTTPTransport(**transport_kwargs) # type: ignore[arg-type]
+
+ # ------------------------------------------------------------------ #
+ # Core request handler
+ # ------------------------------------------------------------------ #
+
+ async def handle_async_request(
+ self,
+ request: httpx.Request,
+ ) -> httpx.Response:
+ hostname = request.url.host or ""
+ scheme = request.url.scheme.lower()
+
+ # 1-3. Scheme, hostname, and pattern checks (reuse sync validator).
+ try:
+ validate_url_sync(str(request.url), self._policy)
+ except SSRFBlockedError:
+ raise
+
+ # Allowed-hosts bypass - skip DNS/IP validation entirely.
+ allowed = {h.lower() for h in _effective_allowed_hosts(self._policy)}
+ if hostname.lower() in allowed:
+ return await self._inner.handle_async_request(request)
+
+ # 4. DNS resolution
+ port = request.url.port or (443 if scheme == "https" else 80)
+ try:
+ addrinfo = await asyncio.to_thread(
+ socket.getaddrinfo,
+ hostname,
+ port,
+ type=socket.SOCK_STREAM,
+ )
+ except socket.gaierror as exc:
+ raise SSRFBlockedError("DNS resolution failed") from exc
+
+ if not addrinfo:
+ raise SSRFBlockedError("DNS resolution returned no results")
+
+ # 5. Validate ALL resolved IPs - any blocked means reject.
+ for _family, _type, _proto, _canonname, sockaddr in addrinfo:
+ ip_str: str = sockaddr[0] # type: ignore[assignment]
+ validate_resolved_ip(ip_str, self._policy)
+
+ # 6. Pin to first resolved IP.
+ pinned_ip = addrinfo[0][4][0]
+
+ # 7. Rewrite URL to use pinned IP, preserving Host header and SNI.
+ pinned_url = request.url.copy_with(host=pinned_ip)
+
+ # Build extensions dict, adding sni_hostname for HTTPS so TLS
+ # certificate validation uses the original hostname.
+ extensions = dict(request.extensions)
+ if scheme == "https":
+ extensions["sni_hostname"] = hostname.encode("ascii")
+
+ pinned_request = httpx.Request(
+ method=request.method,
+ url=pinned_url,
+ headers=request.headers, # Host header already set to original
+ content=request.content,
+ extensions=extensions,
+ )
+
+ return await self._inner.handle_async_request(pinned_request)
+
+ # ------------------------------------------------------------------ #
+ # Lifecycle
+ # ------------------------------------------------------------------ #
+
+ async def aclose(self) -> None:
+ await self._inner.aclose()
+
+
+# ---------------------------------------------------------------------- #
+# Factory
+# ---------------------------------------------------------------------- #
+
+
+class SSRFSafeSyncTransport(httpx.BaseTransport):
+ """httpx sync transport that validates DNS results against an SSRF policy.
+
+ Sync mirror of `SSRFSafeTransport`. See that class for full documentation.
+ """
+
+ def __init__(
+ self,
+ policy: SSRFPolicy = SSRFPolicy(),
+ **transport_kwargs: object,
+ ) -> None:
+ self._policy = policy
+ self._inner = httpx.HTTPTransport(**transport_kwargs) # type: ignore[arg-type]
+
+ def handle_request(
+ self,
+ request: httpx.Request,
+ ) -> httpx.Response:
+ hostname = request.url.host or ""
+ scheme = request.url.scheme.lower()
+
+ validate_url_sync(str(request.url), self._policy)
+
+ allowed = {h.lower() for h in _effective_allowed_hosts(self._policy)}
+ if hostname.lower() in allowed:
+ return self._inner.handle_request(request)
+
+ port = request.url.port or (443 if scheme == "https" else 80)
+ try:
+ addrinfo = socket.getaddrinfo(
+ hostname,
+ port,
+ type=socket.SOCK_STREAM,
+ )
+ except socket.gaierror as exc:
+ raise SSRFBlockedError("DNS resolution failed") from exc
+
+ if not addrinfo:
+ raise SSRFBlockedError("DNS resolution returned no results")
+
+ for _family, _type, _proto, _canonname, sockaddr in addrinfo:
+ ip_str: str = sockaddr[0] # type: ignore[assignment]
+ validate_resolved_ip(ip_str, self._policy)
+
+ pinned_ip = addrinfo[0][4][0]
+ pinned_url = request.url.copy_with(host=pinned_ip)
+
+ extensions = dict(request.extensions)
+ if scheme == "https":
+ extensions["sni_hostname"] = hostname.encode("ascii")
+
+ pinned_request = httpx.Request(
+ method=request.method,
+ url=pinned_url,
+ headers=request.headers,
+ content=request.content,
+ extensions=extensions,
+ )
+
+ return self._inner.handle_request(pinned_request)
+
+ def close(self) -> None:
+ self._inner.close()
+
+
+# ---------------------------------------------------------------------- #
+# Factories
+# ---------------------------------------------------------------------- #
+
+
+def ssrf_safe_client(
+ policy: SSRFPolicy = SSRFPolicy(),
+ **kwargs: object,
+) -> httpx.Client:
+ """Create an `httpx.Client` with SSRF protection."""
+ transport_kwargs: dict[str, object] = {}
+ client_kwargs: dict[str, object] = {}
+ for key, value in kwargs.items():
+ if key in _TRANSPORT_KWARGS:
+ transport_kwargs[key] = value
+ else:
+ client_kwargs[key] = value
+
+ transport = SSRFSafeSyncTransport(policy=policy, **transport_kwargs)
+
+ client_kwargs.setdefault("follow_redirects", True)
+ client_kwargs.setdefault("max_redirects", 10)
+
+ return httpx.Client(
+ transport=transport,
+ **client_kwargs, # type: ignore[arg-type]
+ )
+
+
+def ssrf_safe_async_client(
+ policy: SSRFPolicy = SSRFPolicy(),
+ **kwargs: object,
+) -> httpx.AsyncClient:
+ """Create an `httpx.AsyncClient` with SSRF protection.
+
+ Drop-in replacement for `httpx.AsyncClient(...)` - callers just swap
+ the constructor call. Transport-specific kwargs (`verify`, `cert`,
+ `retries`, etc.) are forwarded to the inner `AsyncHTTPTransport`;
+ everything else goes to the `AsyncClient`.
+ """
+ transport_kwargs: dict[str, object] = {}
+ client_kwargs: dict[str, object] = {}
+ for key, value in kwargs.items():
+ if key in _TRANSPORT_KWARGS:
+ transport_kwargs[key] = value
+ else:
+ client_kwargs[key] = value
+
+ transport = SSRFSafeTransport(policy=policy, **transport_kwargs)
+
+ # Apply defaults only if not overridden by caller.
+ client_kwargs.setdefault("follow_redirects", True)
+ client_kwargs.setdefault("max_redirects", 10)
+
+ return httpx.AsyncClient(
+ transport=transport,
+ **client_kwargs, # type: ignore[arg-type]
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1f1775248f4c58ce4a4250b8b600c4d76ce7184
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__init__.py
@@ -0,0 +1,132 @@
+"""Callback handlers allow listening to events in LangChain."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.callbacks.base import (
+ AsyncCallbackHandler,
+ BaseCallbackHandler,
+ BaseCallbackManager,
+ CallbackManagerMixin,
+ Callbacks,
+ ChainManagerMixin,
+ LLMManagerMixin,
+ RetrieverManagerMixin,
+ RunManagerMixin,
+ ToolManagerMixin,
+ )
+ from langchain_core.callbacks.file import FileCallbackHandler
+ from langchain_core.callbacks.manager import (
+ AsyncCallbackManager,
+ AsyncCallbackManagerForChainGroup,
+ AsyncCallbackManagerForChainRun,
+ AsyncCallbackManagerForLLMRun,
+ AsyncCallbackManagerForRetrieverRun,
+ AsyncCallbackManagerForToolRun,
+ AsyncParentRunManager,
+ AsyncRunManager,
+ BaseRunManager,
+ CallbackManager,
+ CallbackManagerForChainGroup,
+ CallbackManagerForChainRun,
+ CallbackManagerForLLMRun,
+ CallbackManagerForRetrieverRun,
+ CallbackManagerForToolRun,
+ ParentRunManager,
+ RunManager,
+ adispatch_custom_event,
+ dispatch_custom_event,
+ )
+ from langchain_core.callbacks.stdout import StdOutCallbackHandler
+ from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
+ from langchain_core.callbacks.usage import (
+ UsageMetadataCallbackHandler,
+ get_usage_metadata_callback,
+ )
+
+__all__ = (
+ "AsyncCallbackHandler",
+ "AsyncCallbackManager",
+ "AsyncCallbackManagerForChainGroup",
+ "AsyncCallbackManagerForChainRun",
+ "AsyncCallbackManagerForLLMRun",
+ "AsyncCallbackManagerForRetrieverRun",
+ "AsyncCallbackManagerForToolRun",
+ "AsyncParentRunManager",
+ "AsyncRunManager",
+ "BaseCallbackHandler",
+ "BaseCallbackManager",
+ "BaseRunManager",
+ "CallbackManager",
+ "CallbackManagerForChainGroup",
+ "CallbackManagerForChainRun",
+ "CallbackManagerForLLMRun",
+ "CallbackManagerForRetrieverRun",
+ "CallbackManagerForToolRun",
+ "CallbackManagerMixin",
+ "Callbacks",
+ "ChainManagerMixin",
+ "FileCallbackHandler",
+ "LLMManagerMixin",
+ "ParentRunManager",
+ "RetrieverManagerMixin",
+ "RunManager",
+ "RunManagerMixin",
+ "StdOutCallbackHandler",
+ "StreamingStdOutCallbackHandler",
+ "ToolManagerMixin",
+ "UsageMetadataCallbackHandler",
+ "adispatch_custom_event",
+ "dispatch_custom_event",
+ "get_usage_metadata_callback",
+)
+
+_dynamic_imports = {
+ "AsyncCallbackHandler": "base",
+ "BaseCallbackHandler": "base",
+ "BaseCallbackManager": "base",
+ "CallbackManagerMixin": "base",
+ "Callbacks": "base",
+ "ChainManagerMixin": "base",
+ "LLMManagerMixin": "base",
+ "RetrieverManagerMixin": "base",
+ "RunManagerMixin": "base",
+ "ToolManagerMixin": "base",
+ "FileCallbackHandler": "file",
+ "AsyncCallbackManager": "manager",
+ "AsyncCallbackManagerForChainGroup": "manager",
+ "AsyncCallbackManagerForChainRun": "manager",
+ "AsyncCallbackManagerForLLMRun": "manager",
+ "AsyncCallbackManagerForRetrieverRun": "manager",
+ "AsyncCallbackManagerForToolRun": "manager",
+ "AsyncParentRunManager": "manager",
+ "AsyncRunManager": "manager",
+ "BaseRunManager": "manager",
+ "CallbackManager": "manager",
+ "CallbackManagerForChainGroup": "manager",
+ "CallbackManagerForChainRun": "manager",
+ "CallbackManagerForLLMRun": "manager",
+ "CallbackManagerForRetrieverRun": "manager",
+ "CallbackManagerForToolRun": "manager",
+ "ParentRunManager": "manager",
+ "RunManager": "manager",
+ "adispatch_custom_event": "manager",
+ "dispatch_custom_event": "manager",
+ "StdOutCallbackHandler": "stdout",
+ "StreamingStdOutCallbackHandler": "streaming_stdout",
+ "UsageMetadataCallbackHandler": "usage",
+ "get_usage_metadata_callback": "usage",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..caa882b2307dbafba8c4dc9a65b464a01b5ffce5
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3caa44c42dc8a26a1cb249dfab1014efa67cdd1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/file.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/file.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d1b04440da9cb9c3c3571d418f2551e4e0644f1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/file.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/manager.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/manager.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a8d5d14e5c162d295e14dd4f591edcc3a49c14ae
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/manager.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/stdout.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/stdout.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..041de72f0a14d911a440b31bf94eb10a5864c7d5
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/stdout.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/streaming_stdout.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/streaming_stdout.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..782f68b391d4bd48b22d361b59d8e4f18f9f9d56
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/streaming_stdout.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/usage.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/usage.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c910e5028d39be714789a49a9864e8aa81ae8e1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/__pycache__/usage.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..234193190407861fe3833dc4949d76ed71dc7146
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/base.py
@@ -0,0 +1,1223 @@
+"""Base callback handler for LangChain."""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+ from uuid import UUID
+
+ from langchain_protocol.protocol import MessagesData
+ from tenacity import RetryCallState
+ from typing_extensions import Self
+
+ from langchain_core.agents import AgentAction, AgentFinish
+ from langchain_core.documents import Document
+ from langchain_core.messages import BaseMessage
+ from langchain_core.outputs import ChatGenerationChunk, GenerationChunk, LLMResult
+
+_LOGGER = logging.getLogger(__name__)
+
+
+class RetrieverManagerMixin:
+ """Mixin for `Retriever` callbacks."""
+
+ def on_retriever_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when `Retriever` errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_retriever_end(
+ self,
+ documents: Sequence[Document],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when `Retriever` ends running.
+
+ Args:
+ documents: The documents retrieved.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+
+class LLMManagerMixin:
+ """Mixin for LLM callbacks."""
+
+ def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on new output token.
+
+ Only available when streaming is enabled.
+
+ For both chat models and non-chat models (legacy text completion LLMs).
+
+ Args:
+ token: The new token.
+ chunk: The new generated chunk, containing content and other information.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when LLM ends running.
+
+ Args:
+ response: The response which was generated.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when LLM errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_stream_event(
+ self,
+ event: MessagesData,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on each protocol event from `stream_events(version="v3")`.
+
+ Also fires for the async equivalent
+ (`astream_events(version="v3")`).
+
+ Fires once per `MessagesData` event — `message-start`, per-block
+ `content-block-start` / `content-block-delta` /
+ `content-block-finish`, and `message-finish`. Analogous to
+ `on_llm_new_token` in v1 streaming, but at event granularity rather
+ than chunk: a single chunk can map to multiple events (e.g. a
+ `content-block-start` plus its first `content-block-delta`), and
+ lifecycle boundaries are explicit.
+
+ Fires uniformly whether the provider emits events natively via
+ `_stream_chat_model_events` or goes through the chunk-to-event
+ compat bridge. Observers see the same event stream regardless of
+ how the underlying model produces output.
+
+ Not fired from v1 `stream()` / `astream()`; for those, keep using
+ `on_llm_new_token`. Purely additive — `on_chat_model_start`,
+ `on_llm_end`, and `on_llm_error` still fire around a v2 call as
+ they do around a v1 call.
+
+ Args:
+ event: The protocol event.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+
+class ChainManagerMixin:
+ """Mixin for chain callbacks."""
+
+ def on_chain_end(
+ self,
+ outputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when chain ends running.
+
+ Args:
+ outputs: The outputs of the chain.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chain_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when chain errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_agent_action(
+ self,
+ action: AgentAction,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on agent action.
+
+ Args:
+ action: The agent action.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_agent_finish(
+ self,
+ finish: AgentFinish,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on the agent end.
+
+ Args:
+ finish: The agent finish.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+
+class ToolManagerMixin:
+ """Mixin for tool callbacks."""
+
+ def on_tool_end(
+ self,
+ output: Any,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when the tool ends running.
+
+ Args:
+ output: The output of the tool.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when tool errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+
+class CallbackManagerMixin:
+ """Mixin for callback manager."""
+
+ def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when LLM starts running.
+
+ !!! warning
+
+ This method is called for non-chat models (regular text completion LLMs). If
+ you're implementing a handler for a chat model, you should use
+ `on_chat_model_start` instead.
+
+ Args:
+ serialized: The serialized LLM.
+ prompts: The prompts.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when a chat model starts running.
+
+ !!! warning
+
+ This method is called for chat models. If you're implementing a handler for
+ a non-chat model, you should use `on_llm_start` instead.
+
+ !!! note
+
+ When overriding this method, the signature **must** include the two
+ required positional arguments `serialized` and `messages`. Avoid
+ using `*args` in your override — doing so causes an `IndexError`
+ in the fallback path when the callback system converts `messages`
+ to prompt strings for `on_llm_start`. Always declare the
+ signature explicitly:
+
+ .. code-block:: python
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ **kwargs: Any,
+ ) -> None:
+ raise NotImplementedError # triggers fallback to on_llm_start
+
+ Args:
+ serialized: The serialized chat model.
+ messages: The messages. Must be a list of message lists — this is a
+ required positional argument and must be present in any override.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+ # NotImplementedError is thrown intentionally
+ # Callback handler will fall back to on_llm_start if this exception is thrown
+ msg = f"{self.__class__.__name__} does not implement `on_chat_model_start`"
+ raise NotImplementedError(msg)
+
+ def on_retriever_start(
+ self,
+ serialized: dict[str, Any],
+ query: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when the `Retriever` starts running.
+
+ Args:
+ serialized: The serialized `Retriever`.
+ query: The query.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chain_start(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when a chain starts running.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_tool_start(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when the tool starts running.
+
+ Args:
+ serialized: The serialized chain.
+ input_str: The input string.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ inputs: The inputs.
+ **kwargs: Additional keyword arguments.
+ """
+
+
+class RunManagerMixin:
+ """Mixin for run manager."""
+
+ def on_text(
+ self,
+ text: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on an arbitrary text.
+
+ Args:
+ text: The text.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_retry(
+ self,
+ retry_state: RetryCallState,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on a retry event.
+
+ Args:
+ retry_state: The retry state.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Override to define a handler for a custom event.
+
+ Args:
+ name: The name of the custom event.
+ data: The data for the custom event.
+
+ Format will match the format specified by the user.
+ run_id: The ID of the run.
+ tags: The tags associated with the custom event (includes inherited tags).
+ metadata: The metadata associated with the custom event (includes inherited
+ metadata).
+ """
+
+
+class BaseCallbackHandler(
+ LLMManagerMixin,
+ ChainManagerMixin,
+ ToolManagerMixin,
+ RetrieverManagerMixin,
+ CallbackManagerMixin,
+ RunManagerMixin,
+):
+ """Base callback handler."""
+
+ raise_error: bool = False
+ """Whether to raise an error if an exception occurs."""
+
+ run_inline: bool = False
+ """Whether to run the callback inline."""
+
+ @property
+ def ignore_llm(self) -> bool:
+ """Whether to ignore LLM callbacks."""
+ return False
+
+ @property
+ def ignore_retry(self) -> bool:
+ """Whether to ignore retry callbacks."""
+ return False
+
+ @property
+ def ignore_chain(self) -> bool:
+ """Whether to ignore chain callbacks."""
+ return False
+
+ @property
+ def ignore_agent(self) -> bool:
+ """Whether to ignore agent callbacks."""
+ return False
+
+ @property
+ def ignore_retriever(self) -> bool:
+ """Whether to ignore retriever callbacks."""
+ return False
+
+ @property
+ def ignore_chat_model(self) -> bool:
+ """Whether to ignore chat model callbacks."""
+ return False
+
+ @property
+ def ignore_custom_event(self) -> bool:
+ """Ignore custom event."""
+ return False
+
+
+class AsyncCallbackHandler(BaseCallbackHandler):
+ """Base async callback handler."""
+
+ async def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when the model starts running.
+
+ !!! warning
+
+ This method is called for non-chat models (regular text completion LLMs). If
+ you're implementing a handler for a chat model, you should use
+ `on_chat_model_start` instead.
+
+ Args:
+ serialized: The serialized LLM.
+ prompts: The prompts.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run when a chat model starts running.
+
+ !!! warning
+
+ This method is called for chat models. If you're implementing a handler for
+ a non-chat model, you should use `on_llm_start` instead.
+
+ !!! note
+
+ When overriding this method, the signature **must** include the two
+ required positional arguments `serialized` and `messages`. Avoid
+ using `*args` in your override — doing so causes an `IndexError`
+ in the fallback path when the callback system converts `messages`
+ to prompt strings for `on_llm_start`. Always declare the
+ signature explicitly:
+
+ .. code-block:: python
+
+ async def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ **kwargs: Any,
+ ) -> None:
+ raise NotImplementedError # triggers fallback to on_llm_start
+
+ Args:
+ serialized: The serialized chat model.
+ messages: The messages. Must be a list of message lists — this is a
+ required positional argument and must be present in any override.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+ # NotImplementedError is thrown intentionally
+ # Callback handler will fall back to on_llm_start if this exception is thrown
+ msg = f"{self.__class__.__name__} does not implement `on_chat_model_start`"
+ raise NotImplementedError(msg)
+
+ async def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on new output token. Only available when streaming is enabled.
+
+ For both chat models and non-chat models (legacy text completion LLMs).
+
+ Args:
+ token: The new token.
+ chunk: The new generated chunk, containing content and other information.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when the model ends running.
+
+ Args:
+ response: The response which was generated.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+
+ - response (LLMResult): The response which was generated before
+ the error occurred.
+ """
+
+ async def on_stream_event(
+ self,
+ event: MessagesData,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on each protocol event produced by `astream_events(version="v3")`.
+
+ See :meth:`LLMManagerMixin.on_stream_event` for the full contract.
+ Fires once per `MessagesData` event at event granularity, uniformly
+ across native and compat-bridge providers, and is purely additive
+ to the existing `on_chat_model_start` / `on_llm_end` /
+ `on_llm_error` callbacks.
+
+ Args:
+ event: The protocol event.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_chain_start(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when a chain starts running.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_chain_end(
+ self,
+ outputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when a chain ends running.
+
+ Args:
+ outputs: The outputs of the chain.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_chain_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when chain errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_tool_start(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when the tool starts running.
+
+ Args:
+ serialized: The serialized tool.
+ input_str: The input string.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ inputs: The inputs.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_tool_end(
+ self,
+ output: Any,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when the tool ends running.
+
+ Args:
+ output: The output of the tool.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when tool errors.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_text(
+ self,
+ text: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on an arbitrary text.
+
+ Args:
+ text: The text.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_retry(
+ self,
+ retry_state: RetryCallState,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run on a retry event.
+
+ Args:
+ retry_state: The retry state.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_agent_action(
+ self,
+ action: AgentAction,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on agent action.
+
+ Args:
+ action: The agent action.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_agent_finish(
+ self,
+ finish: AgentFinish,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on the agent end.
+
+ Args:
+ finish: The agent finish.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_retriever_start(
+ self,
+ serialized: dict[str, Any],
+ query: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on the retriever start.
+
+ Args:
+ serialized: The serialized retriever.
+ query: The query.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ metadata: The metadata.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_retriever_end(
+ self,
+ documents: Sequence[Document],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on the retriever end.
+
+ Args:
+ documents: The documents retrieved.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_retriever_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on retriever error.
+
+ Args:
+ error: The error that occurred.
+ run_id: The ID of the current run.
+ parent_run_id: The ID of the parent run.
+ tags: The tags.
+ **kwargs: Additional keyword arguments.
+ """
+
+ async def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Override to define a handler for custom events.
+
+ Args:
+ name: The name of the custom event.
+ data: The data for the custom event.
+
+ Format will match the format specified by the user.
+ run_id: The ID of the run.
+ tags: The tags associated with the custom event (includes inherited tags).
+ metadata: The metadata associated with the custom event (includes inherited
+ metadata).
+ """
+
+
+class BaseCallbackManager(CallbackManagerMixin):
+ """Base callback manager."""
+
+ def __init__(
+ self,
+ handlers: list[BaseCallbackHandler],
+ inheritable_handlers: list[BaseCallbackHandler] | None = None,
+ parent_run_id: UUID | None = None,
+ *,
+ tags: list[str] | None = None,
+ inheritable_tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ inheritable_metadata: dict[str, Any] | None = None,
+ ) -> None:
+ """Initialize callback manager.
+
+ Args:
+ handlers: The handlers.
+ inheritable_handlers: The inheritable handlers.
+ parent_run_id: The parent run ID.
+ tags: The tags.
+ inheritable_tags: The inheritable tags.
+ metadata: The metadata.
+ inheritable_metadata: The inheritable metadata.
+ """
+ self.handlers: list[BaseCallbackHandler] = handlers
+ self.inheritable_handlers: list[BaseCallbackHandler] = (
+ inheritable_handlers or []
+ )
+ self.parent_run_id: UUID | None = parent_run_id
+ self.tags = tags or []
+ self.inheritable_tags = inheritable_tags or []
+ self.metadata = metadata or {}
+ self.inheritable_metadata = inheritable_metadata or {}
+
+ def copy(self) -> Self:
+ """Return a copy of the callback manager."""
+ return self.__class__(
+ handlers=self.handlers.copy(),
+ inheritable_handlers=self.inheritable_handlers.copy(),
+ parent_run_id=self.parent_run_id,
+ tags=self.tags.copy(),
+ inheritable_tags=self.inheritable_tags.copy(),
+ metadata=self.metadata.copy(),
+ inheritable_metadata=self.inheritable_metadata.copy(),
+ )
+
+ def merge(self, other: BaseCallbackManager) -> Self:
+ """Merge the callback manager with another callback manager.
+
+ May be overwritten in subclasses.
+
+ Primarily used internally within `merge_configs`.
+
+ Returns:
+ The merged callback manager of the same type as the current object.
+
+ Example:
+ ```python
+ # Merging two callback managers`
+ from langchain_core.callbacks.manager import (
+ CallbackManager,
+ trace_as_chain_group,
+ )
+ from langchain_core.callbacks.stdout import StdOutCallbackHandler
+
+ manager = CallbackManager(handlers=[StdOutCallbackHandler()], tags=["tag2"])
+ with trace_as_chain_group("My Group Name", tags=["tag1"]) as group_manager:
+ merged_manager = group_manager.merge(manager)
+ print(merged_manager.handlers)
+ # [
+ # ,
+ # ,
+ # ]
+
+ print(merged_manager.tags)
+ # ['tag2', 'tag1']
+ ```
+ """ # noqa: E501
+ # Combine handlers and inheritable_handlers separately, using sets
+ # to deduplicate (order not preserved)
+ combined_handlers = list(set(self.handlers) | set(other.handlers))
+ combined_inheritable = list(
+ set(self.inheritable_handlers) | set(other.inheritable_handlers)
+ )
+
+ return self.__class__(
+ parent_run_id=self.parent_run_id or other.parent_run_id,
+ handlers=combined_handlers,
+ inheritable_handlers=combined_inheritable,
+ tags=list(set(self.tags + other.tags)),
+ inheritable_tags=list(set(self.inheritable_tags + other.inheritable_tags)),
+ metadata={
+ **self.metadata,
+ **other.metadata,
+ },
+ inheritable_metadata={
+ **self.inheritable_metadata,
+ **other.inheritable_metadata,
+ },
+ )
+
+ @property
+ def is_async(self) -> bool:
+ """Whether the callback manager is async."""
+ return False
+
+ def add_handler(
+ self,
+ handler: BaseCallbackHandler,
+ inherit: bool = True, # noqa: FBT001,FBT002
+ ) -> None:
+ """Add a handler to the callback manager.
+
+ Args:
+ handler: The handler to add.
+ inherit: Whether to inherit the handler.
+ """
+ if handler not in self.handlers:
+ self.handlers.append(handler)
+ if inherit and handler not in self.inheritable_handlers:
+ self.inheritable_handlers.append(handler)
+
+ def remove_handler(self, handler: BaseCallbackHandler) -> None:
+ """Remove a handler from the callback manager.
+
+ Args:
+ handler: The handler to remove.
+ """
+ if handler in self.handlers:
+ self.handlers.remove(handler)
+ if handler in self.inheritable_handlers:
+ self.inheritable_handlers.remove(handler)
+
+ def set_handlers(
+ self,
+ handlers: list[BaseCallbackHandler],
+ inherit: bool = True, # noqa: FBT001,FBT002
+ ) -> None:
+ """Set handlers as the only handlers on the callback manager.
+
+ Args:
+ handlers: The handlers to set.
+ inherit: Whether to inherit the handlers.
+ """
+ self.handlers = []
+ self.inheritable_handlers = []
+ for handler in handlers:
+ self.add_handler(handler, inherit=inherit)
+
+ def set_handler(
+ self,
+ handler: BaseCallbackHandler,
+ inherit: bool = True, # noqa: FBT001,FBT002
+ ) -> None:
+ """Set handler as the only handler on the callback manager.
+
+ Args:
+ handler: The handler to set.
+ inherit: Whether to inherit the handler.
+ """
+ self.set_handlers([handler], inherit=inherit)
+
+ def add_tags(
+ self,
+ tags: list[str],
+ inherit: bool = True, # noqa: FBT001,FBT002
+ ) -> None:
+ """Add tags to the callback manager.
+
+ Args:
+ tags: The tags to add.
+ inherit: Whether to inherit the tags.
+ """
+ for tag in tags:
+ if tag in self.tags:
+ self.remove_tags([tag])
+ self.tags.extend(tags)
+ if inherit:
+ self.inheritable_tags.extend(tags)
+
+ def remove_tags(self, tags: list[str]) -> None:
+ """Remove tags from the callback manager.
+
+ Args:
+ tags: The tags to remove.
+ """
+ for tag in tags:
+ if tag in self.tags:
+ self.tags.remove(tag)
+ if tag in self.inheritable_tags:
+ self.inheritable_tags.remove(tag)
+
+ def add_metadata(
+ self,
+ metadata: dict[str, Any],
+ inherit: bool = True, # noqa: FBT001,FBT002
+ ) -> None:
+ """Add metadata to the callback manager.
+
+ Args:
+ metadata: The metadata to add.
+ inherit: Whether to inherit the metadata.
+ """
+ self.metadata.update(metadata)
+ if inherit:
+ self.inheritable_metadata.update(metadata)
+
+ def remove_metadata(self, keys: list[str]) -> None:
+ """Remove metadata from the callback manager.
+
+ Args:
+ keys: The keys to remove.
+ """
+ for key in keys:
+ self.metadata.pop(key, None)
+ self.inheritable_metadata.pop(key, None)
+
+
+Callbacks = list[BaseCallbackHandler] | BaseCallbackManager | None
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/file.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/file.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ba0e863c73dad6ffc1add52f5647e71d87d8f41
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/file.py
@@ -0,0 +1,267 @@
+"""Callback handler that writes to a file."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, TextIO, cast
+
+from typing_extensions import Self, override
+
+from langchain_core._api import warn_deprecated
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.utils.input import print_text
+
+if TYPE_CHECKING:
+ from langchain_core.agents import AgentAction, AgentFinish
+
+
+_GLOBAL_DEPRECATION_WARNED = False
+
+
+class FileCallbackHandler(BaseCallbackHandler):
+ """Callback handler that writes to a file.
+
+ This handler supports both context manager usage (recommended) and direct
+ instantiation (deprecated) for backwards compatibility.
+
+ Examples:
+ Using as a context manager (recommended):
+
+ ```python
+ with FileCallbackHandler("output.txt") as handler:
+ # Use handler with your chain/agent
+ chain.invoke(inputs, config={"callbacks": [handler]})
+ ```
+
+ Direct instantiation (deprecated):
+
+ ```python
+ handler = FileCallbackHandler("output.txt")
+ # File remains open until handler is garbage collected
+ try:
+ chain.invoke(inputs, config={"callbacks": [handler]})
+ finally:
+ handler.close() # Explicit cleanup recommended
+ ```
+
+ Args:
+ filename: The file path to write to.
+ mode: The file open mode. Defaults to `'a'` (append).
+ color: Default color for text output.
+
+ !!! note
+
+ When not used as a context manager, a deprecation warning will be issued on
+ first use. The file will be opened immediately in `__init__` and closed in
+ `__del__` or when `close()` is called explicitly.
+
+ """
+
+ def __init__(
+ self, filename: str, mode: str = "a", color: str | None = None
+ ) -> None:
+ """Initialize the file callback handler.
+
+ Args:
+ filename: Path to the output file.
+ mode: File open mode (e.g., `'w'`, `'a'`, `'x'`). Defaults to `'a'`.
+ color: Default text color for output.
+
+ """
+ self.filename = filename
+ self.mode = mode
+ self.color = color
+ self._file_opened_in_context = False
+ self.file: TextIO = cast(
+ "TextIO",
+ # Open the file in the specified mode with UTF-8 encoding.
+ Path(self.filename).open(self.mode, encoding="utf-8"), # noqa: SIM115
+ )
+
+ def __enter__(self) -> Self:
+ """Enter the context manager.
+
+ Returns:
+ The `FileCallbackHandler` instance.
+
+ !!! note
+
+ The file is already opened in `__init__`, so this just marks that the
+ handler is being used as a context manager.
+
+ """
+ self._file_opened_in_context = True
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: object,
+ ) -> None:
+ """Exit the context manager and close the file.
+
+ Args:
+ exc_type: Exception type if an exception occurred.
+ exc_val: Exception value if an exception occurred.
+ exc_tb: Exception traceback if an exception occurred.
+
+ """
+ self.close()
+
+ def __del__(self) -> None:
+ """Destructor to cleanup when done."""
+ self.close()
+
+ def close(self) -> None:
+ """Close the file if it's open.
+
+ This method is safe to call multiple times and will only close
+ the file if it's currently open.
+
+ """
+ if hasattr(self, "file") and self.file and not self.file.closed:
+ self.file.close()
+
+ def _write(
+ self,
+ text: str,
+ color: str | None = None,
+ end: str = "",
+ ) -> None:
+ """Write text to the file with deprecation warning if needed.
+
+ Args:
+ text: The text to write to the file.
+ color: Optional color for the text. Defaults to `self.color`.
+ end: String appended after the text.
+ file: Optional file to write to. Defaults to `self.file`.
+
+ Raises:
+ RuntimeError: If the file is closed or not available.
+
+ """
+ global _GLOBAL_DEPRECATION_WARNED # noqa: PLW0603
+ if not self._file_opened_in_context and not _GLOBAL_DEPRECATION_WARNED:
+ warn_deprecated(
+ since="0.3.67",
+ pending=True,
+ message=(
+ "Using FileCallbackHandler without a context manager is "
+ "deprecated. Use 'with FileCallbackHandler(...) as "
+ "handler:' instead."
+ ),
+ )
+ _GLOBAL_DEPRECATION_WARNED = True
+
+ if not hasattr(self, "file") or self.file is None or self.file.closed:
+ msg = "File is not open. Use FileCallbackHandler as a context manager."
+ raise RuntimeError(msg)
+
+ print_text(text, file=self.file, color=color, end=end)
+
+ @override
+ def on_chain_start(
+ self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Print that we are entering a chain.
+
+ Args:
+ serialized: The serialized chain information.
+ inputs: The inputs to the chain.
+ **kwargs: Additional keyword arguments that may contain `'name'`.
+
+ """
+ name = (
+ kwargs.get("name")
+ or serialized.get("name", serialized.get("id", [""])[-1])
+ or ""
+ )
+ self._write(f"\n\n> Entering new {name} chain...", end="\n")
+
+ @override
+ def on_chain_end(self, outputs: dict[str, Any], **kwargs: Any) -> None:
+ """Print that we finished a chain.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+
+ """
+ self._write("\n> Finished chain.", end="\n")
+
+ @override
+ def on_agent_action(
+ self, action: AgentAction, color: str | None = None, **kwargs: Any
+ ) -> Any:
+ """Handle agent action by writing the action log.
+
+ Args:
+ action: The agent action containing the log to write.
+ color: Color override for this specific output.
+
+ If `None`, uses `self.color`.
+ **kwargs: Additional keyword arguments.
+
+ """
+ self._write(action.log, color=color or self.color)
+
+ @override
+ def on_tool_end(
+ self,
+ output: str,
+ color: str | None = None,
+ observation_prefix: str | None = None,
+ llm_prefix: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Handle tool end by writing the output with optional prefixes.
+
+ Args:
+ output: The tool output to write.
+ color: Color override for this specific output.
+
+ If `None`, uses `self.color`.
+ observation_prefix: Optional prefix to write before the output.
+ llm_prefix: Optional prefix to write after the output.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if observation_prefix is not None:
+ self._write(f"\n{observation_prefix}")
+ self._write(output)
+ if llm_prefix is not None:
+ self._write(f"\n{llm_prefix}")
+
+ @override
+ def on_text(
+ self, text: str, color: str | None = None, end: str = "", **kwargs: Any
+ ) -> None:
+ """Handle text output.
+
+ Args:
+ text: The text to write.
+ color: Color override for this specific output.
+
+ If `None`, uses `self.color`.
+ end: String appended after the text.
+ **kwargs: Additional keyword arguments.
+
+ """
+ self._write(text, color=color or self.color, end=end)
+
+ @override
+ def on_agent_finish(
+ self, finish: AgentFinish, color: str | None = None, **kwargs: Any
+ ) -> None:
+ """Handle agent finish by writing the finish log.
+
+ Args:
+ finish: The agent finish object containing the log to write.
+ color: Color override for this specific output.
+
+ If `None`, uses `self.color`.
+ **kwargs: Additional keyword arguments.
+
+ """
+ self._write(finish.log, color=color or self.color, end="\n")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/manager.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1ba9b76c0a299d4642eabd56443688fc817c17c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/manager.py
@@ -0,0 +1,2792 @@
+"""Run managers."""
+
+from __future__ import annotations
+
+import asyncio
+import atexit
+import functools
+import logging
+from abc import ABC, abstractmethod
+from collections.abc import Callable, Mapping
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import asynccontextmanager, contextmanager
+from contextvars import copy_context
+from typing import TYPE_CHECKING, Any, TypeVar, cast
+
+from typing_extensions import Self, override
+
+from langchain_core.callbacks.base import (
+ BaseCallbackHandler,
+ BaseCallbackManager,
+ Callbacks,
+ ChainManagerMixin,
+ LLMManagerMixin,
+ RetrieverManagerMixin,
+ RunManagerMixin,
+ ToolManagerMixin,
+)
+from langchain_core.callbacks.stdout import StdOutCallbackHandler
+from langchain_core.globals import get_debug
+from langchain_core.messages import BaseMessage, get_buffer_string
+from langchain_core.utils.env import env_var_is_set
+from langchain_core.utils.uuid import uuid7
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncGenerator, Coroutine, Generator, Sequence
+ from uuid import UUID
+
+ from langchain_protocol.protocol import MessagesData
+ from tenacity import RetryCallState
+
+ from langchain_core.agents import AgentAction, AgentFinish
+ from langchain_core.documents import Document
+ from langchain_core.outputs import ChatGenerationChunk, GenerationChunk, LLMResult
+ from langchain_core.runnables.config import RunnableConfig
+ from langchain_core.tracers.schemas import Run
+
+logger = logging.getLogger(__name__)
+
+
+def _get_debug() -> bool:
+ return get_debug()
+
+
+@contextmanager
+def trace_as_chain_group(
+ group_name: str,
+ callback_manager: CallbackManager | None = None,
+ *,
+ inputs: dict[str, Any] | None = None,
+ project_name: str | None = None,
+ example_id: str | UUID | None = None,
+ run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+) -> Generator[CallbackManagerForChainGroup, None, None]:
+ """Get a callback manager for a chain group in a context manager.
+
+ Useful for grouping different calls together as a single run even if they aren't
+ composed in a single chain.
+
+ Args:
+ group_name: The name of the chain group.
+ callback_manager: The callback manager to use.
+ inputs: The inputs to the chain group.
+ project_name: The name of the project.
+ example_id: The ID of the example.
+ run_id: The ID of the run.
+ tags: The inheritable tags to apply to all runs.
+ metadata: The metadata to apply to all runs.
+
+ !!! note
+
+ Must have `LANGCHAIN_TRACING_V2` env var set to true to see the trace in
+ LangSmith.
+
+ Yields:
+ The callback manager for the chain group.
+
+ Example:
+ ```python
+ llm_input = "Foo"
+ with trace_as_chain_group("group_name", inputs={"input": llm_input}) as manager:
+ # Use the callback manager for the chain group
+ res = llm.invoke(llm_input, {"callbacks": manager})
+ manager.on_chain_end({"output": res})
+ ```
+ """
+ from langchain_core.tracers.context import ( # noqa: PLC0415 -- deferred to avoid importing langsmith at module level
+ _get_trace_callbacks,
+ )
+
+ cb = _get_trace_callbacks(
+ project_name, example_id, callback_manager=callback_manager
+ )
+ cm = CallbackManager.configure(
+ inheritable_callbacks=cb,
+ inheritable_tags=tags,
+ inheritable_metadata=metadata,
+ )
+
+ run_manager = cm.on_chain_start({"name": group_name}, inputs or {}, run_id=run_id)
+ child_cm = run_manager.get_child()
+ group_cm = CallbackManagerForChainGroup(
+ child_cm.handlers,
+ child_cm.inheritable_handlers,
+ child_cm.parent_run_id,
+ parent_run_manager=run_manager,
+ tags=child_cm.tags,
+ inheritable_tags=child_cm.inheritable_tags,
+ metadata=child_cm.metadata,
+ inheritable_metadata=child_cm.inheritable_metadata,
+ )
+ try:
+ yield group_cm
+ except Exception as e:
+ if not group_cm.ended:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ if not group_cm.ended:
+ run_manager.on_chain_end({})
+
+
+@asynccontextmanager
+async def atrace_as_chain_group(
+ group_name: str,
+ callback_manager: AsyncCallbackManager | None = None,
+ *,
+ inputs: dict[str, Any] | None = None,
+ project_name: str | None = None,
+ example_id: str | UUID | None = None,
+ run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+) -> AsyncGenerator[AsyncCallbackManagerForChainGroup, None]:
+ """Get an async callback manager for a chain group in a context manager.
+
+ Useful for grouping different async calls together as a single run even if they
+ aren't composed in a single chain.
+
+ Args:
+ group_name: The name of the chain group.
+ callback_manager: The async callback manager to use, which manages tracing and
+ other callback behavior.
+ inputs: The inputs to the chain group.
+ project_name: The name of the project.
+ example_id: The ID of the example.
+ run_id: The ID of the run.
+ tags: The inheritable tags to apply to all runs.
+ metadata: The metadata to apply to all runs.
+
+ Yields:
+ The async callback manager for the chain group.
+
+ !!! note
+
+ Must have `LANGCHAIN_TRACING_V2` env var set to true to see the trace in
+ LangSmith.
+
+ Example:
+ ```python
+ llm_input = "Foo"
+ async with atrace_as_chain_group(
+ "group_name", inputs={"input": llm_input}
+ ) as manager:
+ # Use the async callback manager for the chain group
+ res = await llm.ainvoke(llm_input, {"callbacks": manager})
+ await manager.on_chain_end({"output": res})
+ ```
+ """
+ from langchain_core.tracers.context import ( # noqa: PLC0415 -- deferred to avoid importing langsmith at module level
+ _get_trace_callbacks,
+ )
+
+ cb = _get_trace_callbacks(
+ project_name, example_id, callback_manager=callback_manager
+ )
+ cm = AsyncCallbackManager.configure(
+ inheritable_callbacks=cb, inheritable_tags=tags, inheritable_metadata=metadata
+ )
+
+ run_manager = await cm.on_chain_start(
+ {"name": group_name}, inputs or {}, run_id=run_id
+ )
+ child_cm = run_manager.get_child()
+ group_cm = AsyncCallbackManagerForChainGroup(
+ child_cm.handlers,
+ child_cm.inheritable_handlers,
+ child_cm.parent_run_id,
+ parent_run_manager=run_manager,
+ tags=child_cm.tags,
+ inheritable_tags=child_cm.inheritable_tags,
+ metadata=child_cm.metadata,
+ inheritable_metadata=child_cm.inheritable_metadata,
+ )
+ try:
+ yield group_cm
+ except Exception as e:
+ if not group_cm.ended:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ if not group_cm.ended:
+ await run_manager.on_chain_end({})
+
+
+Func = TypeVar("Func", bound=Callable)
+
+
+def shielded(func: Func) -> Func:
+ """Makes so an awaitable method is always shielded from cancellation.
+
+ Args:
+ func: The function to shield.
+
+ Returns:
+ The shielded function
+
+ """
+
+ @functools.wraps(func)
+ async def wrapped(*args: Any, **kwargs: Any) -> Any:
+ # Capture the current context to preserve context variables
+ ctx = copy_context()
+
+ # Create the coroutine
+ coro = func(*args, **kwargs)
+
+ # For Python 3.11+, create task with explicit context
+ # For older versions, fallback to original behavior
+ try:
+ # Create a task with the captured context to preserve context variables
+ task = asyncio.create_task(coro, context=ctx) # type: ignore[call-arg, unused-ignore]
+ # `call-arg` used to not fail 3.9 or 3.10 tests
+ return await asyncio.shield(task)
+ except TypeError:
+ # Python < 3.11 fallback - create task normally then shield
+ # This won't preserve context perfectly but is better than nothing
+ task = asyncio.create_task(coro)
+ return await asyncio.shield(task)
+
+ return cast("Func", wrapped)
+
+
+def handle_event(
+ handlers: list[BaseCallbackHandler],
+ event_name: str,
+ ignore_condition_name: str | None,
+ *args: Any,
+ **kwargs: Any,
+) -> None:
+ """Generic event handler for `CallbackManager`.
+
+ Args:
+ handlers: The list of handlers that will handle the event.
+ event_name: The name of the event (e.g., `'on_llm_start'`).
+ ignore_condition_name: Name of the attribute defined on handler that if `True`
+ will cause the handler to be skipped for the given event.
+ *args: The arguments to pass to the event handler.
+ **kwargs: The keyword arguments to pass to the event handler
+
+ """
+ coros: list[Coroutine[Any, Any, Any]] = []
+
+ try:
+ message_strings: list[str] | None = None
+ for handler in handlers:
+ try:
+ if ignore_condition_name is None or not getattr(
+ handler, ignore_condition_name
+ ):
+ event = getattr(handler, event_name)(*args, **kwargs)
+ if asyncio.iscoroutine(event):
+ coros.append(event)
+ except NotImplementedError as e:
+ if event_name == "on_chat_model_start":
+ if message_strings is None:
+ message_strings = [get_buffer_string(m) for m in args[1]]
+ handle_event(
+ [handler],
+ "on_llm_start",
+ "ignore_llm",
+ args[0],
+ message_strings,
+ *args[2:],
+ **kwargs,
+ )
+ else:
+ handler_name = handler.__class__.__name__
+ logger.warning(
+ "NotImplementedError in %s.%s callback: %s",
+ handler_name,
+ event_name,
+ repr(e),
+ )
+ except Exception as e:
+ logger.warning(
+ "Error in %s.%s callback: %s",
+ handler.__class__.__name__,
+ event_name,
+ repr(e),
+ )
+ if handler.raise_error:
+ raise
+ finally:
+ if coros:
+ try:
+ # Raises RuntimeError if there is no current event loop.
+ asyncio.get_running_loop()
+ loop_running = True
+ except RuntimeError:
+ loop_running = False
+
+ if loop_running:
+ # If we try to submit this coroutine to the running loop
+ # we end up in a deadlock, as we'd have gotten here from a
+ # running coroutine, which we cannot interrupt to run this one.
+ # The solution is to run the synchronous function on the globally shared
+ # thread pool executor to avoid blocking the main event loop.
+ _executor().submit(
+ cast("Callable", copy_context().run), _run_coros, coros
+ ).result()
+ else:
+ # If there's no running loop, we can run the coroutines directly.
+ _run_coros(coros)
+
+
+def _run_coros(coros: list[Coroutine[Any, Any, Any]]) -> None:
+ if hasattr(asyncio, "Runner"):
+ # Python 3.11+
+ # Run the coroutines in a new event loop, taking care to
+ # - install signal handlers
+ # - run pending tasks scheduled by `coros`
+ # - close asyncgens and executors
+ # - close the loop
+ with asyncio.Runner() as runner:
+ # Run the coroutine, get the result
+ for coro in coros:
+ try:
+ runner.run(coro)
+ except Exception as e:
+ logger.warning("Error in callback coroutine: %s", repr(e))
+
+ # Run pending tasks scheduled by coros until they are all done
+ while pending := asyncio.all_tasks(runner.get_loop()):
+ runner.run(asyncio.wait(pending))
+ else:
+ # Before Python 3.11 we need to run each coroutine in a new event loop
+ # as the Runner api is not available.
+ for coro in coros:
+ try:
+ asyncio.run(coro)
+ except Exception as e:
+ logger.warning("Error in callback coroutine: %s", repr(e))
+
+
+async def _ahandle_event_for_handler(
+ handler: BaseCallbackHandler,
+ event_name: str,
+ ignore_condition_name: str | None,
+ *args: Any,
+ **kwargs: Any,
+) -> None:
+ try:
+ if ignore_condition_name is None or not getattr(handler, ignore_condition_name):
+ event = getattr(handler, event_name)
+ if asyncio.iscoroutinefunction(event):
+ await event(*args, **kwargs)
+ elif handler.run_inline:
+ event(*args, **kwargs)
+ else:
+ await asyncio.get_event_loop().run_in_executor(
+ None,
+ cast(
+ "Callable",
+ functools.partial(copy_context().run, event, *args, **kwargs),
+ ),
+ )
+ except NotImplementedError as e:
+ if event_name == "on_chat_model_start":
+ message_strings = [get_buffer_string(m) for m in args[1]]
+ await _ahandle_event_for_handler(
+ handler,
+ "on_llm_start",
+ "ignore_llm",
+ args[0],
+ message_strings,
+ *args[2:],
+ **kwargs,
+ )
+ else:
+ logger.warning(
+ "NotImplementedError in %s.%s callback: %s",
+ handler.__class__.__name__,
+ event_name,
+ repr(e),
+ )
+ except Exception as e:
+ logger.warning(
+ "Error in %s.%s callback: %s",
+ handler.__class__.__name__,
+ event_name,
+ repr(e),
+ )
+ if handler.raise_error:
+ raise
+
+
+async def ahandle_event(
+ handlers: list[BaseCallbackHandler],
+ event_name: str,
+ ignore_condition_name: str | None,
+ *args: Any,
+ **kwargs: Any,
+) -> None:
+ """Async generic event handler for `AsyncCallbackManager`.
+
+ Args:
+ handlers: The list of handlers that will handle the event.
+ event_name: The name of the event (e.g., `'on_llm_start'`).
+ ignore_condition_name: Name of the attribute defined on handler that if `True`
+ will cause the handler to be skipped for the given event.
+ *args: The arguments to pass to the event handler.
+ **kwargs: The keyword arguments to pass to the event handler.
+
+ """
+ for handler in [h for h in handlers if h.run_inline]:
+ await _ahandle_event_for_handler(
+ handler, event_name, ignore_condition_name, *args, **kwargs
+ )
+ await asyncio.gather(
+ *(
+ _ahandle_event_for_handler(
+ handler,
+ event_name,
+ ignore_condition_name,
+ *args,
+ **kwargs,
+ )
+ for handler in handlers
+ if not handler.run_inline
+ )
+ )
+
+
+class BaseRunManager(RunManagerMixin):
+ """Base class for run manager (a bound callback manager)."""
+
+ def __init__(
+ self,
+ *,
+ run_id: UUID,
+ handlers: list[BaseCallbackHandler],
+ inheritable_handlers: list[BaseCallbackHandler],
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ inheritable_tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ inheritable_metadata: dict[str, Any] | None = None,
+ ) -> None:
+ """Initialize the run manager.
+
+ Args:
+ run_id: The ID of the run.
+ handlers: The list of handlers.
+ inheritable_handlers: The list of inheritable handlers.
+ parent_run_id: The ID of the parent run.
+ tags: The list of tags.
+ inheritable_tags: The list of inheritable tags.
+ metadata: The metadata.
+ inheritable_metadata: The inheritable metadata.
+
+ """
+ self.run_id = run_id
+ self.handlers = handlers
+ self.inheritable_handlers = inheritable_handlers
+ self.parent_run_id = parent_run_id
+ self.tags = tags or []
+ self.inheritable_tags = inheritable_tags or []
+ self.metadata = metadata or {}
+ self.inheritable_metadata = inheritable_metadata or {}
+
+ @classmethod
+ def get_noop_manager(cls) -> Self:
+ """Return a manager that doesn't perform any operations.
+
+ Returns:
+ The noop manager.
+
+ """
+ return cls(
+ run_id=uuid7(),
+ handlers=[],
+ inheritable_handlers=[],
+ tags=[],
+ inheritable_tags=[],
+ metadata={},
+ inheritable_metadata={},
+ )
+
+
+class RunManager(BaseRunManager):
+ """Synchronous run manager."""
+
+ def on_text(
+ self,
+ text: str,
+ **kwargs: Any,
+ ) -> None:
+ """Run when a text is received.
+
+ Args:
+ text: The received text.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_text",
+ None,
+ text,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_retry(
+ self,
+ retry_state: RetryCallState,
+ **kwargs: Any,
+ ) -> None:
+ """Run when a retry is received.
+
+ Args:
+ retry_state: The retry state.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_retry",
+ "ignore_retry",
+ retry_state,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class ParentRunManager(RunManager):
+ """Synchronous parent run manager."""
+
+ def get_child(self, tag: str | None = None) -> CallbackManager:
+ """Get a child callback manager.
+
+ Args:
+ tag: The tag for the child callback manager.
+
+ Returns:
+ The child callback manager.
+
+ """
+ manager = CallbackManager(handlers=[], parent_run_id=self.run_id)
+ manager.set_handlers(self.inheritable_handlers)
+ manager.add_tags(self.inheritable_tags)
+ manager.add_metadata(self.inheritable_metadata)
+ if tag is not None:
+ manager.add_tags([tag], inherit=False)
+ return manager
+
+
+class AsyncRunManager(BaseRunManager, ABC):
+ """Async run manager."""
+
+ @abstractmethod
+ def get_sync(self) -> RunManager:
+ """Get the equivalent sync `RunManager`.
+
+ Returns:
+ The sync `RunManager`.
+
+ """
+
+ async def on_text(
+ self,
+ text: str,
+ **kwargs: Any,
+ ) -> None:
+ """Run when a text is received.
+
+ Args:
+ text: The received text.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_text",
+ None,
+ text,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ async def on_retry(
+ self,
+ retry_state: RetryCallState,
+ **kwargs: Any,
+ ) -> None:
+ """Async run when a retry is received.
+
+ Args:
+ retry_state: The retry state.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_retry",
+ "ignore_retry",
+ retry_state,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class AsyncParentRunManager(AsyncRunManager):
+ """Async parent run manager."""
+
+ def get_child(self, tag: str | None = None) -> AsyncCallbackManager:
+ """Get a child callback manager.
+
+ Args:
+ tag: The tag for the child callback manager.
+
+ Returns:
+ The child callback manager.
+
+ """
+ manager = AsyncCallbackManager(handlers=[], parent_run_id=self.run_id)
+ manager.set_handlers(self.inheritable_handlers)
+ manager.add_tags(self.inheritable_tags)
+ manager.add_metadata(self.inheritable_metadata)
+ if tag is not None:
+ manager.add_tags([tag], inherit=False)
+ return manager
+
+
+class CallbackManagerForLLMRun(RunManager, LLMManagerMixin):
+ """Callback manager for LLM run."""
+
+ def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM generates a new token.
+
+ Args:
+ token: The new token.
+ chunk: The chunk.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_llm_new_token",
+ "ignore_llm",
+ token=token,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ chunk=chunk,
+ **kwargs,
+ )
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running.
+
+ Args:
+ response: The LLM result.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_llm_end",
+ "ignore_llm",
+ response,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_llm_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ - response (LLMResult): The response which was generated before
+ the error occurred.
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_llm_error",
+ "ignore_llm",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_stream_event(self, event: MessagesData, **kwargs: Any) -> None:
+ """Run on each protocol event from `stream_events(version="v3")`.
+
+ Args:
+ event: The protocol event.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_stream_event",
+ "ignore_llm",
+ event,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class AsyncCallbackManagerForLLMRun(AsyncRunManager, LLMManagerMixin):
+ """Async callback manager for LLM run."""
+
+ def get_sync(self) -> CallbackManagerForLLMRun:
+ """Get the equivalent sync `RunManager`.
+
+ Returns:
+ The sync `RunManager`.
+
+ """
+ return CallbackManagerForLLMRun(
+ run_id=self.run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ async def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM generates a new token.
+
+ Args:
+ token: The new token.
+ chunk: The chunk.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_llm_new_token",
+ "ignore_llm",
+ token,
+ chunk=chunk,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ @shielded
+ async def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running.
+
+ Args:
+ response: The LLM result.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_llm_end",
+ "ignore_llm",
+ response,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ @shielded
+ async def on_llm_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ - response (LLMResult): The response which was generated before
+ the error occurred.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_llm_error",
+ "ignore_llm",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ async def on_stream_event(self, event: MessagesData, **kwargs: Any) -> None:
+ """Run on each protocol event from `astream_events(version="v3")`.
+
+ Args:
+ event: The protocol event.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_stream_event",
+ "ignore_llm",
+ event,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class CallbackManagerForChainRun(ParentRunManager, ChainManagerMixin):
+ """Callback manager for chain run."""
+
+ def on_chain_end(self, outputs: dict[str, Any] | Any, **kwargs: Any) -> None:
+ """Run when chain ends running.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_chain_end",
+ "ignore_chain",
+ outputs,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_chain_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when chain errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_chain_error",
+ "ignore_chain",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> None:
+ """Run when agent action is received.
+
+ Args:
+ action: The agent action.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_agent_action",
+ "ignore_agent",
+ action,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run when agent finish is received.
+
+ Args:
+ finish: The agent finish.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_agent_finish",
+ "ignore_agent",
+ finish,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class AsyncCallbackManagerForChainRun(AsyncParentRunManager, ChainManagerMixin):
+ """Async callback manager for chain run."""
+
+ def get_sync(self) -> CallbackManagerForChainRun:
+ """Get the equivalent sync `RunManager`.
+
+ Returns:
+ The sync `RunManager`.
+ """
+ return CallbackManagerForChainRun(
+ run_id=self.run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ @shielded
+ async def on_chain_end(self, outputs: dict[str, Any] | Any, **kwargs: Any) -> None:
+ """Run when a chain ends running.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_chain_end",
+ "ignore_chain",
+ outputs,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ @shielded
+ async def on_chain_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when chain errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_chain_error",
+ "ignore_chain",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ async def on_agent_action(self, action: AgentAction, **kwargs: Any) -> None:
+ """Run when agent action is received.
+
+ Args:
+ action: The agent action.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_agent_action",
+ "ignore_agent",
+ action,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ async def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run when agent finish is received.
+
+ Args:
+ finish: The agent finish.
+ **kwargs: Additional keyword arguments.
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_agent_finish",
+ "ignore_agent",
+ finish,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class CallbackManagerForToolRun(ParentRunManager, ToolManagerMixin):
+ """Callback manager for tool run."""
+
+ def on_tool_end(
+ self,
+ output: Any,
+ **kwargs: Any,
+ ) -> None:
+ """Run when the tool ends running.
+
+ Args:
+ output: The output of the tool.
+ **kwargs: The keyword arguments to pass to the event handler
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_tool_end",
+ "ignore_agent",
+ output,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_tool_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when tool errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_tool_error",
+ "ignore_agent",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class AsyncCallbackManagerForToolRun(AsyncParentRunManager, ToolManagerMixin):
+ """Async callback manager for tool run."""
+
+ def get_sync(self) -> CallbackManagerForToolRun:
+ """Get the equivalent sync `RunManager`.
+
+ Returns:
+ The sync `RunManager`.
+ """
+ return CallbackManagerForToolRun(
+ run_id=self.run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ async def on_tool_end(self, output: Any, **kwargs: Any) -> None:
+ """Async run when the tool ends running.
+
+ Args:
+ output: The output of the tool.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_tool_end",
+ "ignore_agent",
+ output,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ async def on_tool_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when tool errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_tool_error",
+ "ignore_agent",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class CallbackManagerForRetrieverRun(ParentRunManager, RetrieverManagerMixin):
+ """Callback manager for retriever run."""
+
+ def on_retriever_end(
+ self,
+ documents: Sequence[Document],
+ **kwargs: Any,
+ ) -> None:
+ """Run when retriever ends running.
+
+ Args:
+ documents: The retrieved documents.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_retriever_end",
+ "ignore_retriever",
+ documents,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ def on_retriever_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when retriever errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ handle_event(
+ self.handlers,
+ "on_retriever_error",
+ "ignore_retriever",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class AsyncCallbackManagerForRetrieverRun(
+ AsyncParentRunManager,
+ RetrieverManagerMixin,
+):
+ """Async callback manager for retriever run."""
+
+ def get_sync(self) -> CallbackManagerForRetrieverRun:
+ """Get the equivalent sync `RunManager`.
+
+ Returns:
+ The sync `RunManager`.
+
+ """
+ return CallbackManagerForRetrieverRun(
+ run_id=self.run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ @shielded
+ async def on_retriever_end(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> None:
+ """Run when the retriever ends running.
+
+ Args:
+ documents: The retrieved documents.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_retriever_end",
+ "ignore_retriever",
+ documents,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+ @shielded
+ async def on_retriever_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when retriever errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ if not self.handlers:
+ return
+ await ahandle_event(
+ self.handlers,
+ "on_retriever_error",
+ "ignore_retriever",
+ error,
+ run_id=self.run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ **kwargs,
+ )
+
+
+class CallbackManager(BaseCallbackManager):
+ """Callback manager for LangChain."""
+
+ def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> list[CallbackManagerForLLMRun]:
+ """Run when LLM starts running.
+
+ Args:
+ serialized: The serialized LLM.
+ prompts: The list of prompts.
+ run_id: The ID of the run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ A callback manager for each prompt as an LLM run.
+
+ """
+ managers = []
+ for i, prompt in enumerate(prompts):
+ # Can't have duplicate runs with the same run ID (if provided)
+ run_id_ = run_id if i == 0 and run_id is not None else uuid7()
+ handle_event(
+ self.handlers,
+ "on_llm_start",
+ "ignore_llm",
+ serialized,
+ [prompt],
+ run_id=run_id_,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ managers.append(
+ CallbackManagerForLLMRun(
+ run_id=run_id_,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+ )
+
+ return managers
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> list[CallbackManagerForLLMRun]:
+ """Run when chat model starts running.
+
+ Args:
+ serialized: The serialized LLM.
+ messages: The list of messages.
+ run_id: The ID of the run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ A callback manager for each list of messages as an LLM run.
+
+ """
+ managers = []
+ for message_list in messages:
+ if run_id is not None:
+ run_id_ = run_id
+ run_id = None
+ else:
+ run_id_ = uuid7()
+ handle_event(
+ self.handlers,
+ "on_chat_model_start",
+ "ignore_chat_model",
+ serialized,
+ [message_list],
+ run_id=run_id_,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ managers.append(
+ CallbackManagerForLLMRun(
+ run_id=run_id_,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+ )
+
+ return managers
+
+ def on_chain_start(
+ self,
+ serialized: dict[str, Any] | None,
+ inputs: dict[str, Any] | Any,
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> CallbackManagerForChainRun:
+ """Run when chain starts running.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs to the chain.
+ run_id: The ID of the run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The callback manager for the chain run.
+
+ """
+ if run_id is None:
+ run_id = uuid7()
+ handle_event(
+ self.handlers,
+ "on_chain_start",
+ "ignore_chain",
+ serialized,
+ inputs,
+ run_id=run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ return CallbackManagerForChainRun(
+ run_id=run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ @override
+ def on_tool_start(
+ self,
+ serialized: dict[str, Any] | None,
+ input_str: str,
+ run_id: UUID | None = None,
+ parent_run_id: UUID | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> CallbackManagerForToolRun:
+ """Run when tool starts running.
+
+ Args:
+ serialized: Serialized representation of the tool.
+ input_str: The input to the tool as a string.
+
+ Non-string inputs are cast to strings.
+ run_id: ID for the run.
+ parent_run_id: The ID of the parent run.
+ inputs: The original input to the tool if provided.
+
+ Recommended for usage instead of input_str when the original input is
+ needed.
+
+ If provided, the inputs are expected to be formatted as a dict. The keys
+ will correspond to the named-arguments in the tool.
+ **kwargs: The keyword arguments to pass to the event handler
+
+ Returns:
+ The callback manager for the tool run.
+
+ """
+ if run_id is None:
+ run_id = uuid7()
+
+ handle_event(
+ self.handlers,
+ "on_tool_start",
+ "ignore_agent",
+ serialized,
+ input_str,
+ run_id=run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ inputs=inputs,
+ **kwargs,
+ )
+
+ return CallbackManagerForToolRun(
+ run_id=run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ @override
+ def on_retriever_start(
+ self,
+ serialized: dict[str, Any] | None,
+ query: str,
+ run_id: UUID | None = None,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> CallbackManagerForRetrieverRun:
+ """Run when the retriever starts running.
+
+ Args:
+ serialized: The serialized retriever.
+ query: The query.
+ run_id: The ID of the run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The callback manager for the retriever run.
+ """
+ if run_id is None:
+ run_id = uuid7()
+
+ handle_event(
+ self.handlers,
+ "on_retriever_start",
+ "ignore_retriever",
+ serialized,
+ query,
+ run_id=run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ return CallbackManagerForRetrieverRun(
+ run_id=run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Dispatch an adhoc event to the handlers (async version).
+
+ This event should NOT be used in any internal LangChain code. The event is meant
+ specifically for users of the library to dispatch custom events that are
+ tailored to their application.
+
+ Args:
+ name: The name of the adhoc event.
+ data: The data for the adhoc event.
+ run_id: The ID of the run.
+
+ Raises:
+ ValueError: If additional keyword arguments are passed.
+ """
+ if not self.handlers:
+ return
+ if kwargs:
+ msg = (
+ "The dispatcher API does not accept additional keyword arguments."
+ "Please do not pass any additional keyword arguments, instead "
+ "include them in the data field."
+ )
+ raise ValueError(msg)
+ if run_id is None:
+ run_id = uuid7()
+
+ handle_event(
+ self.handlers,
+ "on_custom_event",
+ "ignore_custom_event",
+ name,
+ data,
+ run_id=run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ )
+
+ @classmethod
+ def configure(
+ cls,
+ inheritable_callbacks: Callbacks = None,
+ local_callbacks: Callbacks = None,
+ verbose: bool = False, # noqa: FBT001,FBT002
+ inheritable_tags: list[str] | None = None,
+ local_tags: list[str] | None = None,
+ inheritable_metadata: dict[str, Any] | None = None,
+ local_metadata: dict[str, Any] | None = None,
+ *,
+ langsmith_inheritable_metadata: Mapping[str, Any] | None = None,
+ langsmith_inheritable_tags: list[str] | None = None,
+ ) -> CallbackManager:
+ """Configure the callback manager.
+
+ Args:
+ inheritable_callbacks: The inheritable callbacks.
+ local_callbacks: The local callbacks.
+ verbose: Whether to enable verbose mode.
+ inheritable_tags: The inheritable tags.
+ local_tags: The local tags.
+ inheritable_metadata: The inheritable metadata.
+ local_metadata: The local metadata.
+ langsmith_inheritable_metadata: Default inheritable metadata applied
+ to any `LangChainTracer` handlers via `set_defaults`.
+ langsmith_inheritable_tags: Default inheritable tags applied to any
+ `LangChainTracer` handlers via `set_defaults`.
+
+ Returns:
+ The configured callback manager.
+ """
+ return _configure(
+ cls,
+ inheritable_callbacks,
+ local_callbacks,
+ inheritable_tags,
+ local_tags,
+ inheritable_metadata,
+ local_metadata,
+ verbose=verbose,
+ langsmith_inheritable_metadata=langsmith_inheritable_metadata,
+ langsmith_inheritable_tags=langsmith_inheritable_tags,
+ )
+
+
+class CallbackManagerForChainGroup(CallbackManager):
+ """Callback manager for the chain group."""
+
+ def __init__(
+ self,
+ handlers: list[BaseCallbackHandler],
+ inheritable_handlers: list[BaseCallbackHandler] | None = None,
+ parent_run_id: UUID | None = None,
+ *,
+ parent_run_manager: CallbackManagerForChainRun,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize the callback manager.
+
+ Args:
+ handlers: The list of handlers.
+ inheritable_handlers: The list of inheritable handlers.
+ parent_run_id: The ID of the parent run.
+ parent_run_manager: The parent run manager.
+ **kwargs: Additional keyword arguments.
+
+ """
+ super().__init__(
+ handlers,
+ inheritable_handlers,
+ parent_run_id,
+ **kwargs,
+ )
+ self.parent_run_manager = parent_run_manager
+ self.ended = False
+
+ @override
+ def copy(self) -> CallbackManagerForChainGroup:
+ return self.__class__(
+ handlers=self.handlers.copy(),
+ inheritable_handlers=self.inheritable_handlers.copy(),
+ parent_run_id=self.parent_run_id,
+ tags=self.tags.copy(),
+ inheritable_tags=self.inheritable_tags.copy(),
+ metadata=self.metadata.copy(),
+ inheritable_metadata=self.inheritable_metadata.copy(),
+ parent_run_manager=self.parent_run_manager,
+ )
+
+ def merge(
+ self: CallbackManagerForChainGroup, other: BaseCallbackManager
+ ) -> CallbackManagerForChainGroup:
+ """Merge the group callback manager with another callback manager.
+
+ Overwrites the merge method in the base class to ensure that the parent run
+ manager is preserved. Keeps the `parent_run_manager` from the current object.
+
+ Returns:
+ A copy of the current object with the handlers, tags, and other attributes
+ merged from the other object.
+
+ Example:
+ ```python
+ # Merging two callback managers
+ from langchain_core.callbacks.manager import (
+ CallbackManager,
+ trace_as_chain_group,
+ )
+ from langchain_core.callbacks.stdout import StdOutCallbackHandler
+
+ manager = CallbackManager(handlers=[StdOutCallbackHandler()], tags=["tag2"])
+ with trace_as_chain_group("My Group Name", tags=["tag1"]) as group_manager:
+ merged_manager = group_manager.merge(manager)
+ print(type(merged_manager))
+ #
+
+ print(merged_manager.handlers)
+ # [
+ # ,
+ # ,
+ # ]
+
+ print(merged_manager.tags)
+ # ['tag2', 'tag1']
+ ```
+ """ # noqa: E501
+ manager = self.__class__(
+ parent_run_id=self.parent_run_id or other.parent_run_id,
+ handlers=[],
+ inheritable_handlers=[],
+ tags=list(set(self.tags + other.tags)),
+ inheritable_tags=list(set(self.inheritable_tags + other.inheritable_tags)),
+ metadata={
+ **self.metadata,
+ **other.metadata,
+ },
+ parent_run_manager=self.parent_run_manager,
+ )
+
+ handlers = self.handlers + other.handlers
+ inheritable_handlers = self.inheritable_handlers + other.inheritable_handlers
+
+ for handler in handlers:
+ manager.add_handler(handler)
+
+ for handler in inheritable_handlers:
+ manager.add_handler(handler, inherit=True)
+ return manager
+
+ def on_chain_end(self, outputs: dict[str, Any] | Any, **kwargs: Any) -> None:
+ """Run when traced chain group ends.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+
+ """
+ self.ended = True
+ return self.parent_run_manager.on_chain_end(outputs, **kwargs)
+
+ def on_chain_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when chain errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+
+ """
+ self.ended = True
+ return self.parent_run_manager.on_chain_error(error, **kwargs)
+
+
+class AsyncCallbackManager(BaseCallbackManager):
+ """Async callback manager that handles callbacks from LangChain."""
+
+ @property
+ def is_async(self) -> bool:
+ """Return whether the handler is async."""
+ return True
+
+ async def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> list[AsyncCallbackManagerForLLMRun]:
+ """Run when LLM starts running.
+
+ Args:
+ serialized: The serialized LLM.
+ prompts: The list of prompts.
+ run_id: The ID of the run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The list of async callback managers, one for each LLM run corresponding to
+ each prompt.
+ """
+ inline_tasks = []
+ non_inline_tasks = []
+ inline_handlers = [handler for handler in self.handlers if handler.run_inline]
+ non_inline_handlers = [
+ handler for handler in self.handlers if not handler.run_inline
+ ]
+ managers = []
+
+ for prompt in prompts:
+ if run_id is not None:
+ run_id_ = run_id
+ run_id = None
+ else:
+ run_id_ = uuid7()
+
+ if inline_handlers:
+ inline_tasks.append(
+ ahandle_event(
+ inline_handlers,
+ "on_llm_start",
+ "ignore_llm",
+ serialized,
+ [prompt],
+ run_id=run_id_,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+ )
+ else:
+ non_inline_tasks.append(
+ ahandle_event(
+ non_inline_handlers,
+ "on_llm_start",
+ "ignore_llm",
+ serialized,
+ [prompt],
+ run_id=run_id_,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+ )
+
+ managers.append(
+ AsyncCallbackManagerForLLMRun(
+ run_id=run_id_,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+ )
+
+ # Run inline tasks sequentially
+ for inline_task in inline_tasks:
+ await inline_task
+
+ # Run non-inline tasks concurrently
+ if non_inline_tasks:
+ await asyncio.gather(*non_inline_tasks)
+
+ return managers
+
+ async def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> list[AsyncCallbackManagerForLLMRun]:
+ """Async run when LLM starts running.
+
+ Args:
+ serialized: The serialized LLM.
+ messages: The list of messages.
+ run_id: The ID of the run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The list of async callback managers, one for each LLM run corresponding to
+ each inner message list.
+ """
+ inline_tasks = []
+ non_inline_tasks = []
+ managers = []
+
+ for message_list in messages:
+ if run_id is not None:
+ run_id_ = run_id
+ run_id = None
+ else:
+ run_id_ = uuid7()
+
+ for handler in self.handlers:
+ task = ahandle_event(
+ [handler],
+ "on_chat_model_start",
+ "ignore_chat_model",
+ serialized,
+ [message_list],
+ run_id=run_id_,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+ if handler.run_inline:
+ inline_tasks.append(task)
+ else:
+ non_inline_tasks.append(task)
+
+ managers.append(
+ AsyncCallbackManagerForLLMRun(
+ run_id=run_id_,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+ )
+
+ # Run inline tasks sequentially
+ for task in inline_tasks:
+ await task
+
+ # Run non-inline tasks concurrently
+ if non_inline_tasks:
+ await asyncio.gather(*non_inline_tasks)
+
+ return managers
+
+ async def on_chain_start(
+ self,
+ serialized: dict[str, Any] | None,
+ inputs: dict[str, Any] | Any,
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> AsyncCallbackManagerForChainRun:
+ """Async run when chain starts running.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs to the chain.
+ run_id: The ID of the run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The async callback manager for the chain run.
+ """
+ if run_id is None:
+ run_id = uuid7()
+
+ await ahandle_event(
+ self.handlers,
+ "on_chain_start",
+ "ignore_chain",
+ serialized,
+ inputs,
+ run_id=run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ return AsyncCallbackManagerForChainRun(
+ run_id=run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ @override
+ async def on_tool_start(
+ self,
+ serialized: dict[str, Any] | None,
+ input_str: str,
+ run_id: UUID | None = None,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> AsyncCallbackManagerForToolRun:
+ """Run when the tool starts running.
+
+ Args:
+ serialized: The serialized tool.
+ input_str: The input to the tool.
+ run_id: The ID of the run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The async callback manager for the tool run.
+ """
+ if run_id is None:
+ run_id = uuid7()
+
+ await ahandle_event(
+ self.handlers,
+ "on_tool_start",
+ "ignore_agent",
+ serialized,
+ input_str,
+ run_id=run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ return AsyncCallbackManagerForToolRun(
+ run_id=run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ async def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Dispatch an adhoc event to the handlers (async version).
+
+ This event should NOT be used in any internal LangChain code. The event is meant
+ specifically for users of the library to dispatch custom events that are
+ tailored to their application.
+
+ Args:
+ name: The name of the adhoc event.
+ data: The data for the adhoc event.
+ run_id: The ID of the run.
+
+ Raises:
+ ValueError: If additional keyword arguments are passed.
+ """
+ if not self.handlers:
+ return
+ if run_id is None:
+ run_id = uuid7()
+
+ if kwargs:
+ msg = (
+ "The dispatcher API does not accept additional keyword arguments."
+ "Please do not pass any additional keyword arguments, instead "
+ "include them in the data field."
+ )
+ raise ValueError(msg)
+ await ahandle_event(
+ self.handlers,
+ "on_custom_event",
+ "ignore_custom_event",
+ name,
+ data,
+ run_id=run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ )
+
+ @override
+ async def on_retriever_start(
+ self,
+ serialized: dict[str, Any] | None,
+ query: str,
+ run_id: UUID | None = None,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> AsyncCallbackManagerForRetrieverRun:
+ """Run when the retriever starts running.
+
+ Args:
+ serialized: The serialized retriever.
+ query: The query.
+ run_id: The ID of the run.
+ parent_run_id: The ID of the parent run.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The async callback manager for the retriever run.
+ """
+ if run_id is None:
+ run_id = uuid7()
+
+ await ahandle_event(
+ self.handlers,
+ "on_retriever_start",
+ "ignore_retriever",
+ serialized,
+ query,
+ run_id=run_id,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ metadata=self.metadata,
+ **kwargs,
+ )
+
+ return AsyncCallbackManagerForRetrieverRun(
+ run_id=run_id,
+ handlers=self.handlers,
+ inheritable_handlers=self.inheritable_handlers,
+ parent_run_id=self.parent_run_id,
+ tags=self.tags,
+ inheritable_tags=self.inheritable_tags,
+ metadata=self.metadata,
+ inheritable_metadata=self.inheritable_metadata,
+ )
+
+ @classmethod
+ def configure(
+ cls,
+ inheritable_callbacks: Callbacks = None,
+ local_callbacks: Callbacks = None,
+ verbose: bool = False, # noqa: FBT001,FBT002
+ inheritable_tags: list[str] | None = None,
+ local_tags: list[str] | None = None,
+ inheritable_metadata: dict[str, Any] | None = None,
+ local_metadata: dict[str, Any] | None = None,
+ *,
+ langsmith_inheritable_metadata: Mapping[str, Any] | None = None,
+ langsmith_inheritable_tags: list[str] | None = None,
+ ) -> AsyncCallbackManager:
+ """Configure the async callback manager.
+
+ Args:
+ inheritable_callbacks: The inheritable callbacks.
+ local_callbacks: The local callbacks.
+ verbose: Whether to enable verbose mode.
+ inheritable_tags: The inheritable tags.
+ local_tags: The local tags.
+ inheritable_metadata: The inheritable metadata.
+ local_metadata: The local metadata.
+ langsmith_inheritable_metadata: Default inheritable metadata applied
+ to any `LangChainTracer` handlers via `set_defaults`.
+ langsmith_inheritable_tags: Default inheritable tags applied to any
+ `LangChainTracer` handlers via `set_defaults`.
+
+ Returns:
+ The configured async callback manager.
+ """
+ return _configure(
+ cls,
+ inheritable_callbacks,
+ local_callbacks,
+ inheritable_tags,
+ local_tags,
+ inheritable_metadata,
+ local_metadata,
+ verbose=verbose,
+ langsmith_inheritable_metadata=langsmith_inheritable_metadata,
+ langsmith_inheritable_tags=langsmith_inheritable_tags,
+ )
+
+
+class AsyncCallbackManagerForChainGroup(AsyncCallbackManager):
+ """Async callback manager for the chain group."""
+
+ def __init__(
+ self,
+ handlers: list[BaseCallbackHandler],
+ inheritable_handlers: list[BaseCallbackHandler] | None = None,
+ parent_run_id: UUID | None = None,
+ *,
+ parent_run_manager: AsyncCallbackManagerForChainRun,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize the async callback manager.
+
+ Args:
+ handlers: The list of handlers.
+ inheritable_handlers: The list of inheritable handlers.
+ parent_run_id: The ID of the parent run.
+ parent_run_manager: The parent run manager.
+ **kwargs: Additional keyword arguments.
+ """
+ super().__init__(
+ handlers,
+ inheritable_handlers,
+ parent_run_id,
+ **kwargs,
+ )
+ self.parent_run_manager = parent_run_manager
+ self.ended = False
+
+ def copy(self) -> AsyncCallbackManagerForChainGroup:
+ """Return a copy the async callback manager."""
+ return self.__class__(
+ handlers=self.handlers.copy(),
+ inheritable_handlers=self.inheritable_handlers.copy(),
+ parent_run_id=self.parent_run_id,
+ tags=self.tags.copy(),
+ inheritable_tags=self.inheritable_tags.copy(),
+ metadata=self.metadata.copy(),
+ inheritable_metadata=self.inheritable_metadata.copy(),
+ parent_run_manager=self.parent_run_manager,
+ )
+
+ def merge(
+ self: AsyncCallbackManagerForChainGroup, other: BaseCallbackManager
+ ) -> AsyncCallbackManagerForChainGroup:
+ """Merge the group callback manager with another callback manager.
+
+ Overwrites the merge method in the base class to ensure that the parent run
+ manager is preserved. Keeps the `parent_run_manager` from the current object.
+
+ Returns:
+ A copy of the current `AsyncCallbackManagerForChainGroup` with the handlers,
+ tags, etc. of the other callback manager merged in.
+
+ Example:
+ ```python
+ # Merging two callback managers
+ from langchain_core.callbacks.manager import (
+ CallbackManager,
+ atrace_as_chain_group,
+ )
+ from langchain_core.callbacks.stdout import StdOutCallbackHandler
+
+ manager = CallbackManager(handlers=[StdOutCallbackHandler()], tags=["tag2"])
+ async with atrace_as_chain_group(
+ "My Group Name", tags=["tag1"]
+ ) as group_manager:
+ merged_manager = group_manager.merge(manager)
+ print(type(merged_manager))
+ #
+
+ print(merged_manager.handlers)
+ # [
+ # ,
+ # ,
+ # ]
+
+ print(merged_manager.tags)
+ # ['tag2', 'tag1']
+ ```
+ """ # noqa: E501
+ manager = self.__class__(
+ parent_run_id=self.parent_run_id or other.parent_run_id,
+ handlers=[],
+ inheritable_handlers=[],
+ tags=list(set(self.tags + other.tags)),
+ inheritable_tags=list(set(self.inheritable_tags + other.inheritable_tags)),
+ metadata={
+ **self.metadata,
+ **other.metadata,
+ },
+ parent_run_manager=self.parent_run_manager,
+ )
+
+ handlers = self.handlers + other.handlers
+ inheritable_handlers = self.inheritable_handlers + other.inheritable_handlers
+
+ for handler in handlers:
+ manager.add_handler(handler)
+
+ for handler in inheritable_handlers:
+ manager.add_handler(handler, inherit=True)
+ return manager
+
+ async def on_chain_end(self, outputs: dict[str, Any] | Any, **kwargs: Any) -> None:
+ """Run when traced chain group ends.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+ """
+ self.ended = True
+ await self.parent_run_manager.on_chain_end(outputs, **kwargs)
+
+ async def on_chain_error(
+ self,
+ error: BaseException,
+ **kwargs: Any,
+ ) -> None:
+ """Run when chain errors.
+
+ Args:
+ error: The error.
+ **kwargs: Additional keyword arguments.
+ """
+ self.ended = True
+ await self.parent_run_manager.on_chain_error(error, **kwargs)
+
+
+T = TypeVar("T", CallbackManager, AsyncCallbackManager)
+
+
+def _configure(
+ callback_manager_cls: type[T],
+ inheritable_callbacks: Callbacks = None,
+ local_callbacks: Callbacks = None,
+ inheritable_tags: list[str] | None = None,
+ local_tags: list[str] | None = None,
+ inheritable_metadata: dict[str, Any] | None = None,
+ local_metadata: dict[str, Any] | None = None,
+ *,
+ verbose: bool = False,
+ langsmith_inheritable_metadata: Mapping[str, Any] | None = None,
+ langsmith_inheritable_tags: list[str] | None = None,
+) -> T:
+ """Configure the callback manager.
+
+ Args:
+ callback_manager_cls: The callback manager class.
+ inheritable_callbacks: The inheritable callbacks.
+ local_callbacks: The local callbacks.
+ inheritable_tags: The inheritable tags.
+ local_tags: The local tags.
+ inheritable_metadata: The inheritable metadata.
+ local_metadata: The local metadata.
+ verbose: Whether to enable verbose mode.
+ langsmith_inheritable_metadata: Default inheritable metadata applied to
+ any `LangChainTracer` handlers via `set_defaults`.
+ langsmith_inheritable_tags: Default inheritable tags applied to any
+ `LangChainTracer` handlers via `set_defaults`.
+
+ Raises:
+ RuntimeError: If `LANGCHAIN_TRACING` is set but `LANGCHAIN_TRACING_V2` is not.
+
+ Returns:
+ The configured callback manager.
+ """
+ # Deferred to avoid importing langsmith at module level (~132ms).
+ from langsmith.run_helpers import get_tracing_context # noqa: PLC0415
+
+ from langchain_core.tracers.context import ( # noqa: PLC0415
+ _configure_hooks,
+ _get_tracer_project,
+ _tracing_v2_is_enabled,
+ tracing_v2_callback_var,
+ )
+ from langchain_core.tracers.langchain import LangChainTracer # noqa: PLC0415
+ from langchain_core.tracers.stdout import ConsoleCallbackHandler # noqa: PLC0415
+
+ tracing_context = get_tracing_context()
+ tracing_metadata = tracing_context["metadata"]
+ tracing_tags = tracing_context["tags"]
+ run_tree: Run | None = tracing_context["parent"]
+ parent_run_id = None if run_tree is None else run_tree.id
+ callback_manager = callback_manager_cls(
+ handlers=[],
+ parent_run_id=parent_run_id,
+ )
+ if inheritable_callbacks or local_callbacks:
+ if isinstance(inheritable_callbacks, list) or inheritable_callbacks is None:
+ inheritable_callbacks_ = inheritable_callbacks or []
+ callback_manager = callback_manager_cls(
+ handlers=inheritable_callbacks_.copy(),
+ inheritable_handlers=inheritable_callbacks_.copy(),
+ parent_run_id=parent_run_id,
+ )
+ else:
+ parent_run_id_ = inheritable_callbacks.parent_run_id
+ # Break ties between the external tracing context and inherited context
+ if parent_run_id is not None and (
+ parent_run_id_ is None
+ # If the LC parent has already been reflected
+ # in the run tree, we know the run_tree is either the
+ # same parent or a child of the parent.
+ or (run_tree and str(parent_run_id_) in run_tree.dotted_order)
+ ):
+ parent_run_id_ = parent_run_id
+ # Otherwise, we assume the LC context has progressed
+ # beyond the run tree and we should not inherit the parent.
+ callback_manager = callback_manager_cls(
+ handlers=inheritable_callbacks.handlers.copy(),
+ inheritable_handlers=inheritable_callbacks.inheritable_handlers.copy(),
+ parent_run_id=parent_run_id_,
+ tags=inheritable_callbacks.tags.copy(),
+ inheritable_tags=inheritable_callbacks.inheritable_tags.copy(),
+ metadata=inheritable_callbacks.metadata.copy(),
+ inheritable_metadata=inheritable_callbacks.inheritable_metadata.copy(),
+ )
+ local_handlers_ = (
+ local_callbacks
+ if isinstance(local_callbacks, list)
+ else (local_callbacks.handlers if local_callbacks else [])
+ )
+ for handler in local_handlers_:
+ callback_manager.add_handler(handler, inherit=False)
+ if inheritable_tags or local_tags:
+ callback_manager.add_tags(inheritable_tags or [])
+ callback_manager.add_tags(local_tags or [], inherit=False)
+ if inheritable_metadata or local_metadata:
+ callback_manager.add_metadata(inheritable_metadata or {})
+ callback_manager.add_metadata(local_metadata or {}, inherit=False)
+ if tracing_tags:
+ callback_manager.add_tags(tracing_tags.copy())
+
+ v1_tracing_enabled_ = env_var_is_set("LANGCHAIN_TRACING") or env_var_is_set(
+ "LANGCHAIN_HANDLER"
+ )
+
+ tracer_v2 = tracing_v2_callback_var.get()
+ tracing_v2_enabled_ = _tracing_v2_is_enabled()
+
+ if v1_tracing_enabled_ and not tracing_v2_enabled_:
+ # if both are enabled, can silently ignore the v1 tracer
+ msg = (
+ "Tracing using LangChainTracerV1 is no longer supported. "
+ "Please set the LANGCHAIN_TRACING_V2 environment variable to enable "
+ "tracing instead."
+ )
+ raise RuntimeError(msg)
+
+ tracer_project = _get_tracer_project()
+ debug = _get_debug()
+ if verbose or debug or tracing_v2_enabled_:
+ if verbose and not any(
+ isinstance(handler, StdOutCallbackHandler)
+ for handler in callback_manager.handlers
+ ):
+ if debug:
+ pass
+ else:
+ callback_manager.add_handler(StdOutCallbackHandler(), inherit=False)
+ if debug and not any(
+ isinstance(handler, ConsoleCallbackHandler)
+ for handler in callback_manager.handlers
+ ):
+ callback_manager.add_handler(ConsoleCallbackHandler())
+ if tracing_v2_enabled_ and not any(
+ isinstance(handler, LangChainTracer)
+ for handler in callback_manager.handlers
+ ):
+ if tracer_v2:
+ callback_manager.add_handler(tracer_v2)
+ else:
+ try:
+ handler = LangChainTracer(
+ project_name=tracer_project,
+ client=(
+ run_tree.client
+ if run_tree is not None
+ else tracing_context["client"]
+ ),
+ tags=tracing_tags,
+ metadata=tracing_metadata,
+ )
+ callback_manager.add_handler(handler)
+ except Exception as e:
+ logger.warning(
+ "Unable to load requested LangChainTracer."
+ " To disable this warning,"
+ " unset the LANGCHAIN_TRACING_V2 environment variables.\n"
+ "%s",
+ repr(e),
+ )
+ if run_tree is not None:
+ for handler in callback_manager.handlers:
+ if isinstance(handler, LangChainTracer):
+ handler.order_map[run_tree.id] = (
+ run_tree.trace_id,
+ run_tree.dotted_order,
+ )
+ run_id_str = str(run_tree.id)
+ if run_id_str not in handler.run_map:
+ handler.run_map[run_id_str] = run_tree
+ handler._external_run_ids.setdefault( # noqa: SLF001
+ run_id_str, 0
+ )
+ for var, inheritable, handler_class, env_var in _configure_hooks:
+ create_one = (
+ env_var is not None
+ and env_var_is_set(env_var)
+ and handler_class is not None
+ )
+ if var.get() is not None or create_one:
+ var_handler = (
+ var.get() or cast("type[BaseCallbackHandler]", handler_class)()
+ )
+ if handler_class is None:
+ if not any(
+ handler is var_handler # direct pointer comparison
+ for handler in callback_manager.handlers
+ ):
+ callback_manager.add_handler(var_handler, inheritable)
+ elif not any(
+ isinstance(handler, handler_class)
+ for handler in callback_manager.handlers
+ ):
+ callback_manager.add_handler(var_handler, inheritable)
+
+ if tracing_metadata:
+ langsmith_inheritable_metadata = {
+ **tracing_metadata,
+ **(langsmith_inheritable_metadata or {}),
+ }
+
+ if langsmith_inheritable_metadata or langsmith_inheritable_tags:
+ callback_manager.handlers = [
+ handler.copy_with_metadata_defaults(
+ metadata=langsmith_inheritable_metadata,
+ tags=langsmith_inheritable_tags,
+ )
+ if isinstance(handler, LangChainTracer)
+ else handler
+ for handler in callback_manager.handlers
+ ]
+ callback_manager.inheritable_handlers = [
+ handler.copy_with_metadata_defaults(
+ metadata=langsmith_inheritable_metadata,
+ tags=langsmith_inheritable_tags,
+ )
+ if isinstance(handler, LangChainTracer)
+ else handler
+ for handler in callback_manager.inheritable_handlers
+ ]
+ return callback_manager
+
+
+async def adispatch_custom_event(
+ name: str, data: Any, *, config: RunnableConfig | None = None
+) -> None:
+ """Dispatch an adhoc event to the handlers.
+
+ Args:
+ name: The name of the adhoc event.
+ data: The data for the adhoc event.
+
+ Free form data. Ideally should be JSON serializable to avoid serialization
+ issues downstream, but this is not enforced.
+ config: Optional config object.
+
+ Mirrors the async API but not strictly needed.
+
+ Raises:
+ RuntimeError: If there is no parent run ID available to associate the event
+ with.
+
+ Example:
+ ```python
+ from langchain_core.callbacks import (
+ AsyncCallbackHandler,
+ adispatch_custom_event
+ )
+ from langchain_core.runnable import RunnableLambda
+
+ class CustomCallbackManager(AsyncCallbackHandler):
+ async def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ print(f"Received custom event: {name} with data: {data}")
+
+ callback = CustomCallbackManager()
+
+ async def foo(inputs):
+ await adispatch_custom_event("my_event", {"bar": "buzz})
+ return inputs
+
+ foo_ = RunnableLambda(foo)
+ await foo_.ainvoke({"a": "1"}, {"callbacks": [CustomCallbackManager()]})
+ ```
+
+ Example: Use with astream events
+
+ ```python
+ from langchain_core.callbacks import (
+ AsyncCallbackHandler,
+ adispatch_custom_event
+ )
+ from langchain_core.runnable import RunnableLambda
+
+ class CustomCallbackManager(AsyncCallbackHandler):
+ async def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ print(f"Received custom event: {name} with data: {data}")
+
+ callback = CustomCallbackManager()
+
+ async def foo(inputs):
+ await adispatch_custom_event("event_type_1", {"bar": "buzz})
+ await adispatch_custom_event("event_type_2", 5)
+ return inputs
+
+ foo_ = RunnableLambda(foo)
+
+ async for event in foo_.ainvoke_stream(
+ {"a": "1"},
+ version="v2",
+ config={"callbacks": [CustomCallbackManager()]}
+ ):
+ print(event)
+ ```
+
+ !!! warning
+
+ If using python 3.10 and async, you MUST specify the `config` parameter or the
+ function will raise an error. This is due to a limitation in asyncio for python
+ 3.10 that prevents LangChain from automatically propagating the config object on
+ the user's behalf.
+ """
+ # Import locally to prevent circular imports.
+ from langchain_core.runnables.config import ( # noqa: PLC0415
+ ensure_config,
+ get_async_callback_manager_for_config,
+ )
+
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ # We want to get the callback manager for the parent run.
+ # This is a work-around for now to be able to dispatch adhoc events from
+ # within a tool or a lambda and have the metadata events associated
+ # with the parent run rather than have a new run id generated for each.
+ if callback_manager.parent_run_id is None:
+ msg = (
+ "Unable to dispatch an adhoc event without a parent run id."
+ "This function can only be called from within an existing run (e.g.,"
+ "inside a tool or a RunnableLambda or a RunnableGenerator.)"
+ "If you are doing that and still seeing this error, try explicitly"
+ "passing the config parameter to this function."
+ )
+ raise RuntimeError(msg)
+
+ await callback_manager.on_custom_event(
+ name,
+ data,
+ run_id=callback_manager.parent_run_id,
+ )
+
+
+def dispatch_custom_event(
+ name: str, data: Any, *, config: RunnableConfig | None = None
+) -> None:
+ """Dispatch an adhoc event.
+
+ Args:
+ name: The name of the adhoc event.
+ data: The data for the adhoc event.
+
+ Free form data. Ideally should be JSON serializable to avoid serialization
+ issues downstream, but this is not enforced.
+ config: Optional config object.
+
+ Mirrors the async API but not strictly needed.
+
+ Raises:
+ RuntimeError: If there is no parent run ID available to associate the event
+ with.
+
+ Example:
+ ```python
+ from langchain_core.callbacks import BaseCallbackHandler
+ from langchain_core.callbacks import dispatch_custom_event
+ from langchain_core.runnable import RunnableLambda
+
+ class CustomCallbackManager(BaseCallbackHandler):
+ def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ print(f"Received custom event: {name} with data: {data}")
+
+ def foo(inputs):
+ dispatch_custom_event("my_event", {"bar": "buzz})
+ return inputs
+
+ foo_ = RunnableLambda(foo)
+ foo_.invoke({"a": "1"}, {"callbacks": [CustomCallbackManager()]})
+ ```
+ """
+ # Import locally to prevent circular imports.
+ from langchain_core.runnables.config import ( # noqa: PLC0415
+ ensure_config,
+ get_callback_manager_for_config,
+ )
+
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ # We want to get the callback manager for the parent run.
+ # This is a work-around for now to be able to dispatch adhoc events from
+ # within a tool or a lambda and have the metadata events associated
+ # with the parent run rather than have a new run id generated for each.
+ if callback_manager.parent_run_id is None:
+ msg = (
+ "Unable to dispatch an adhoc event without a parent run id."
+ "This function can only be called from within an existing run (e.g.,"
+ "inside a tool or a RunnableLambda or a RunnableGenerator.)"
+ "If you are doing that and still seeing this error, try explicitly"
+ "passing the config parameter to this function."
+ )
+ raise RuntimeError(msg)
+ callback_manager.on_custom_event(
+ name,
+ data,
+ run_id=callback_manager.parent_run_id,
+ )
+
+
+@functools.lru_cache(maxsize=1)
+def _executor() -> ThreadPoolExecutor:
+ # If the user is specifying ASYNC callback handlers to be run from a
+ # SYNC context, and an event loop is already running,
+ # we cannot submit the coroutine to the running loop, because it
+ # would result in a deadlock. Instead we have to schedule them
+ # on a background thread. To avoid creating & shutting down
+ # a new executor every time, we use a lazily-created, shared
+ # executor. If you're using regular langgchain parallelism (batch, etc.)
+ # you'd only ever need 1 worker, but we permit more for now to reduce the chance
+ # of slowdown if you are mixing with your own executor.
+ cutie = ThreadPoolExecutor(max_workers=10)
+ atexit.register(cutie.shutdown, wait=True)
+ return cutie
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/stdout.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/stdout.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cfce2ce7c4c1184a741cde813c7e21a1cd54df7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/stdout.py
@@ -0,0 +1,123 @@
+"""Callback handler that prints to std out."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from typing_extensions import override
+
+from langchain_core.callbacks.base import BaseCallbackHandler
+from langchain_core.utils import print_text
+
+if TYPE_CHECKING:
+ from langchain_core.agents import AgentAction, AgentFinish
+
+
+class StdOutCallbackHandler(BaseCallbackHandler):
+ """Callback handler that prints to std out."""
+
+ def __init__(self, color: str | None = None) -> None:
+ """Initialize callback handler.
+
+ Args:
+ color: The color to use for the text.
+ """
+ self.color = color
+
+ @override
+ def on_chain_start(
+ self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Print out that we are entering a chain.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs to the chain.
+ **kwargs: Additional keyword arguments.
+ """
+ if "name" in kwargs:
+ name = kwargs["name"]
+ elif serialized:
+ name = serialized.get("name", serialized.get("id", [""])[-1])
+ else:
+ name = ""
+ print(f"\n\n\033[1m> Entering new {name} chain...\033[0m") # noqa: T201
+
+ @override
+ def on_chain_end(self, outputs: dict[str, Any], **kwargs: Any) -> None:
+ """Print out that we finished a chain.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+ """
+ print("\n\033[1m> Finished chain.\033[0m") # noqa: T201
+
+ @override
+ def on_agent_action(
+ self, action: AgentAction, color: str | None = None, **kwargs: Any
+ ) -> Any:
+ """Run on agent action.
+
+ Args:
+ action: The agent action.
+ color: The color to use for the text.
+ **kwargs: Additional keyword arguments.
+ """
+ print_text(action.log, color=color or self.color)
+
+ @override
+ def on_tool_end(
+ self,
+ output: Any,
+ color: str | None = None,
+ observation_prefix: str | None = None,
+ llm_prefix: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """If not the final action, print out observation.
+
+ Args:
+ output: The output to print.
+ color: The color to use for the text.
+ observation_prefix: The observation prefix.
+ llm_prefix: The LLM prefix.
+ **kwargs: Additional keyword arguments.
+ """
+ output = str(output)
+ if observation_prefix is not None:
+ print_text(f"\n{observation_prefix}")
+ print_text(output, color=color or self.color)
+ if llm_prefix is not None:
+ print_text(f"\n{llm_prefix}")
+
+ @override
+ def on_text(
+ self,
+ text: str,
+ color: str | None = None,
+ end: str = "",
+ **kwargs: Any,
+ ) -> None:
+ """Run when the agent ends.
+
+ Args:
+ text: The text to print.
+ color: The color to use for the text.
+ end: The end character to use.
+ **kwargs: Additional keyword arguments.
+ """
+ print_text(text, color=color or self.color, end=end)
+
+ @override
+ def on_agent_finish(
+ self, finish: AgentFinish, color: str | None = None, **kwargs: Any
+ ) -> None:
+ """Run on the agent end.
+
+ Args:
+ finish: The agent finish.
+ color: The color to use for the text.
+ **kwargs: Additional keyword arguments.
+ """
+ print_text(finish.log, color=color or self.color, end="\n")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/streaming_stdout.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/streaming_stdout.py
new file mode 100644
index 0000000000000000000000000000000000000000..920fef80bde70e6ca3cfe4912920263c4bf3b335
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/streaming_stdout.py
@@ -0,0 +1,152 @@
+"""Callback Handler streams to stdout on new llm token."""
+
+from __future__ import annotations
+
+import sys
+from typing import TYPE_CHECKING, Any
+
+from typing_extensions import override
+
+from langchain_core.callbacks.base import BaseCallbackHandler
+
+if TYPE_CHECKING:
+ from langchain_core.agents import AgentAction, AgentFinish
+ from langchain_core.messages import BaseMessage
+ from langchain_core.outputs import LLMResult
+
+
+class StreamingStdOutCallbackHandler(BaseCallbackHandler):
+ """Callback handler for streaming.
+
+ !!! warning "Only works with LLMs that support streaming."
+ """
+
+ def on_llm_start(
+ self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any
+ ) -> None:
+ """Run when LLM starts running.
+
+ Args:
+ serialized: The serialized LLM.
+ prompts: The prompts to run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ **kwargs: Any,
+ ) -> None:
+ """Run when LLM starts running.
+
+ Args:
+ serialized: The serialized LLM.
+ messages: The messages to run.
+ **kwargs: Additional keyword arguments.
+ """
+
+ @override
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
+ """Run on new LLM token. Only available when streaming is enabled.
+
+ Args:
+ token: The new token.
+ **kwargs: Additional keyword arguments.
+ """
+ sys.stdout.write(token)
+ sys.stdout.flush()
+
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Run when LLM ends running.
+
+ Args:
+ response: The response from the LLM.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when LLM errors.
+
+ Args:
+ error: The error that occurred.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chain_start(
+ self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any
+ ) -> None:
+ """Run when a chain starts running.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs to the chain.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chain_end(self, outputs: dict[str, Any], **kwargs: Any) -> None:
+ """Run when a chain ends running.
+
+ Args:
+ outputs: The outputs of the chain.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when chain errors.
+
+ Args:
+ error: The error that occurred.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_tool_start(
+ self, serialized: dict[str, Any], input_str: str, **kwargs: Any
+ ) -> None:
+ """Run when the tool starts running.
+
+ Args:
+ serialized: The serialized tool.
+ input_str: The input string.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:
+ """Run on agent action.
+
+ Args:
+ action: The agent action.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_tool_end(self, output: Any, **kwargs: Any) -> None:
+ """Run when tool ends running.
+
+ Args:
+ output: The output of the tool.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
+ """Run when tool errors.
+
+ Args:
+ error: The error that occurred.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_text(self, text: str, **kwargs: Any) -> None:
+ """Run on an arbitrary text.
+
+ Args:
+ text: The text to print.
+ **kwargs: Additional keyword arguments.
+ """
+
+ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:
+ """Run on the agent end.
+
+ Args:
+ finish: The agent finish.
+ **kwargs: Additional keyword arguments.
+ """
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/usage.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/usage.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef1dd78e600645a7019844923b36993ff21de691
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/callbacks/usage.py
@@ -0,0 +1,149 @@
+"""Callback Handler that tracks `AIMessage.usage_metadata`."""
+
+import threading
+from collections.abc import Generator
+from contextlib import contextmanager
+from contextvars import ContextVar
+from typing import Any
+
+from typing_extensions import override
+
+from langchain_core.callbacks import BaseCallbackHandler
+from langchain_core.messages import AIMessage
+from langchain_core.messages.ai import UsageMetadata, add_usage
+from langchain_core.outputs import ChatGeneration, LLMResult
+from langchain_core.tracers.context import register_configure_hook
+
+
+class UsageMetadataCallbackHandler(BaseCallbackHandler):
+ """Callback Handler that tracks `AIMessage.usage_metadata`.
+
+ Example:
+ ```python
+ from langchain.chat_models import init_chat_model
+ from langchain_core.callbacks import UsageMetadataCallbackHandler
+
+ llm_1 = init_chat_model(model="openai:gpt-4o-mini")
+ llm_2 = init_chat_model(model="anthropic:claude-haiku-4-5-20251001")
+
+ callback = UsageMetadataCallbackHandler()
+ result_1 = llm_1.invoke("Hello", config={"callbacks": [callback]})
+ result_2 = llm_2.invoke("Hello", config={"callbacks": [callback]})
+ callback.usage_metadata
+ ```
+
+ ```txt
+ {'gpt-4o-mini-2024-07-18': {'input_tokens': 8,
+ 'output_tokens': 10,
+ 'total_tokens': 18,
+ 'input_token_details': {'audio': 0, 'cache_read': 0},
+ 'output_token_details': {'audio': 0, 'reasoning': 0}},
+ 'claude-haiku-4-5-20251001': {'input_tokens': 8,
+ 'output_tokens': 21,
+ 'total_tokens': 29,
+ 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}}
+ ```
+
+ !!! version-added "Added in `langchain-core` 0.3.49"
+
+ """
+
+ def __init__(self) -> None:
+ """Initialize the `UsageMetadataCallbackHandler`."""
+ super().__init__()
+ self._lock = threading.Lock()
+ self.usage_metadata: dict[str, UsageMetadata] = {}
+
+ @override
+ def __repr__(self) -> str:
+ return str(self.usage_metadata)
+
+ @override
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
+ """Collect token usage."""
+ # Check for usage_metadata (langchain-core >= 0.2.2)
+ try:
+ generation = response.generations[0][0]
+ except IndexError:
+ generation = None
+
+ usage_metadata = None
+ model_name = None
+ if isinstance(generation, ChatGeneration):
+ try:
+ message = generation.message
+ if isinstance(message, AIMessage):
+ usage_metadata = message.usage_metadata
+ model_name = message.response_metadata.get("model_name")
+ except AttributeError:
+ pass
+
+ # update shared state behind lock
+ if usage_metadata and model_name:
+ with self._lock:
+ if model_name not in self.usage_metadata:
+ self.usage_metadata[model_name] = usage_metadata
+ else:
+ self.usage_metadata[model_name] = add_usage(
+ self.usage_metadata[model_name], usage_metadata
+ )
+
+
+@contextmanager
+def get_usage_metadata_callback(
+ name: str = "usage_metadata_callback",
+) -> Generator[UsageMetadataCallbackHandler, None, None]:
+ """Get usage metadata callback.
+
+ Get context manager for tracking usage metadata across chat model calls using
+ [`AIMessage.usage_metadata`][langchain.messages.AIMessage.usage_metadata].
+
+ Args:
+ name: The name of the context variable.
+
+ Yields:
+ The usage metadata callback.
+
+ Example:
+ ```python
+ from langchain.chat_models import init_chat_model
+ from langchain_core.callbacks import get_usage_metadata_callback
+
+ llm_1 = init_chat_model(model="openai:gpt-4o-mini")
+ llm_2 = init_chat_model(model="anthropic:claude-haiku-4-5-20251001")
+
+ with get_usage_metadata_callback() as cb:
+ llm_1.invoke("Hello")
+ llm_2.invoke("Hello")
+ print(cb.usage_metadata)
+ ```
+
+ ```txt
+ {
+ "gpt-4o-mini-2024-07-18": {
+ "input_tokens": 8,
+ "output_tokens": 10,
+ "total_tokens": 18,
+ "input_token_details": {"audio": 0, "cache_read": 0},
+ "output_token_details": {"audio": 0, "reasoning": 0},
+ },
+ "claude-haiku-4-5-20251001": {
+ "input_tokens": 8,
+ "output_tokens": 21,
+ "total_tokens": 29,
+ "input_token_details": {"cache_read": 0, "cache_creation": 0},
+ },
+ }
+ ```
+
+ !!! version-added "Added in `langchain-core` 0.3.49"
+
+ """
+ usage_metadata_callback_var: ContextVar[UsageMetadataCallbackHandler | None] = (
+ ContextVar(name, default=None)
+ )
+ register_configure_hook(usage_metadata_callback_var, inheritable=True)
+ cb = UsageMetadataCallbackHandler()
+ usage_metadata_callback_var.set(cb)
+ yield cb
+ usage_metadata_callback_var.set(None)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e591df947483c4c77630182906575fe5411a5dd4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__init__.py
@@ -0,0 +1,39 @@
+"""Document loaders."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.document_loaders.base import BaseBlobParser, BaseLoader
+ from langchain_core.document_loaders.blob_loaders import Blob, BlobLoader, PathLike
+ from langchain_core.document_loaders.langsmith import LangSmithLoader
+
+__all__ = (
+ "BaseBlobParser",
+ "BaseLoader",
+ "Blob",
+ "BlobLoader",
+ "LangSmithLoader",
+ "PathLike",
+)
+
+_dynamic_imports = {
+ "BaseBlobParser": "base",
+ "BaseLoader": "base",
+ "Blob": "blob_loaders",
+ "BlobLoader": "blob_loaders",
+ "PathLike": "blob_loaders",
+ "LangSmithLoader": "langsmith",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25c28ddc5f4bbaa703a27eaa61977e8231a3708c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cae84e846366b3e28132e686dce7af9ba7e99597
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__pycache__/blob_loaders.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__pycache__/blob_loaders.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2239dac0173a6b2385eeb400ed43afb892381526
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__pycache__/blob_loaders.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__pycache__/langsmith.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__pycache__/langsmith.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e9a9d9264c566a172fed083a915bb6016900bad
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/__pycache__/langsmith.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..448c85988dc97b398e2150093e6c43a26a3065ea
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/base.py
@@ -0,0 +1,155 @@
+"""Abstract interface for document loader implementations."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING
+
+from langchain_core.runnables import run_in_executor
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator
+
+ from langchain_text_splitters import TextSplitter
+
+ from langchain_core.documents import Document
+ from langchain_core.documents.base import Blob
+
+try:
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
+
+ _HAS_TEXT_SPLITTERS = True
+except ImportError:
+ _HAS_TEXT_SPLITTERS = False
+
+
+class BaseLoader(ABC): # noqa: B024
+ """Interface for document loader.
+
+ Implementations should implement the lazy-loading method using generators to avoid
+ loading all documents into memory at once.
+
+ `load` is provided just for user convenience and should not be overridden.
+ """
+
+ # Sub-classes should not implement this method directly. Instead, they
+ # should implement the lazy load method.
+ def load(self) -> list[Document]:
+ """Load data into `Document` objects.
+
+ Returns:
+ The documents.
+ """
+ return list(self.lazy_load())
+
+ async def aload(self) -> list[Document]:
+ """Load data into `Document` objects.
+
+ Returns:
+ The documents.
+ """
+ return [document async for document in self.alazy_load()]
+
+ def load_and_split(
+ self, text_splitter: TextSplitter | None = None
+ ) -> list[Document]:
+ """Load `Document` and split into chunks. Chunks are returned as `Document`.
+
+ !!! danger
+
+ Do not override this method. It should be considered to be deprecated!
+
+ Args:
+ text_splitter: `TextSplitter` instance to use for splitting documents.
+
+ Defaults to `RecursiveCharacterTextSplitter`.
+
+ Raises:
+ ImportError: If `langchain-text-splitters` is not installed and no
+ `text_splitter` is provided.
+
+ Returns:
+ List of `Document` objects.
+ """
+ if text_splitter is None:
+ if not _HAS_TEXT_SPLITTERS:
+ msg = (
+ "Unable to import from langchain_text_splitters. Please specify "
+ "text_splitter or install langchain_text_splitters with "
+ "`pip install -U langchain-text-splitters`."
+ )
+ raise ImportError(msg)
+
+ text_splitter_: TextSplitter = RecursiveCharacterTextSplitter()
+ else:
+ text_splitter_ = text_splitter
+ docs = self.load()
+ return text_splitter_.split_documents(docs)
+
+ # Attention: This method will be upgraded into an abstractmethod once it's
+ # implemented in all the existing subclasses.
+ def lazy_load(self) -> Iterator[Document]:
+ """A lazy loader for `Document`.
+
+ Yields:
+ The `Document` objects.
+ """
+ if type(self).load != BaseLoader.load:
+ return iter(self.load())
+ msg = f"{self.__class__.__name__} does not implement lazy_load()"
+ raise NotImplementedError(msg)
+
+ async def alazy_load(self) -> AsyncIterator[Document]:
+ """A lazy loader for `Document`.
+
+ Yields:
+ The `Document` objects.
+ """
+ iterator = await run_in_executor(None, self.lazy_load)
+ done = object()
+ while True:
+ doc = await run_in_executor(None, next, iterator, done)
+ if doc is done:
+ break
+ yield doc # type: ignore[misc]
+
+
+class BaseBlobParser(ABC):
+ """Abstract interface for blob parsers.
+
+ A blob parser provides a way to parse raw data stored in a blob into one or more
+ `Document` objects.
+
+ The parser can be composed with blob loaders, making it easy to reuse a parser
+ independent of how the blob was originally loaded.
+ """
+
+ @abstractmethod
+ def lazy_parse(self, blob: Blob) -> Iterator[Document]:
+ """Lazy parsing interface.
+
+ Subclasses are required to implement this method.
+
+ Args:
+ blob: `Blob` instance
+
+ Returns:
+ Generator of `Document` objects
+ """
+
+ def parse(self, blob: Blob) -> list[Document]:
+ """Eagerly parse the blob into a `Document` or list of `Document` objects.
+
+ This is a convenience method for interactive development environment.
+
+ Production applications should favor the `lazy_parse` method instead.
+
+ Subclasses should generally not over-ride this parse method.
+
+ Args:
+ blob: `Blob` instance
+
+ Returns:
+ List of `Document` objects
+ """
+ return list(self.lazy_parse(blob))
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/blob_loaders.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/blob_loaders.py
new file mode 100644
index 0000000000000000000000000000000000000000..399cd4a91da3019f1753543f2056b7537d759256
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/blob_loaders.py
@@ -0,0 +1,38 @@
+"""Schema for Blobs and Blob Loaders.
+
+The goal is to facilitate decoupling of content loading from content parsing code. In
+addition, content loading code should provide a lazy loading interface by default.
+"""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING
+
+# Re-export Blob and PathLike for backwards compatibility
+from langchain_core.documents.base import Blob, PathLike
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+
+
+class BlobLoader(ABC):
+ """Abstract interface for blob loaders implementation.
+
+ Implementer should be able to load raw content from a storage system according to
+ some criteria and return the raw content lazily as a stream of blobs.
+ """
+
+ @abstractmethod
+ def yield_blobs(
+ self,
+ ) -> Iterator[Blob]:
+ """A lazy loader for raw data represented by LangChain's `Blob` object.
+
+ Yields:
+ `Blob` objects.
+ """
+
+
+# Re-export Blob and Pathlike for backwards compatibility
+__all__ = ["Blob", "BlobLoader", "PathLike"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/langsmith.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/langsmith.py
new file mode 100644
index 0000000000000000000000000000000000000000..23a44e05d40e58d76c46d44566ec9064eda68f4d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/document_loaders/langsmith.py
@@ -0,0 +1,143 @@
+"""LangSmith document loader."""
+
+import datetime
+import json
+import uuid
+from collections.abc import Callable, Iterator, Sequence
+from typing import Any
+
+from langsmith import Client as LangSmithClient
+from typing_extensions import override
+
+from langchain_core.document_loaders.base import BaseLoader
+from langchain_core.documents import Document
+from langchain_core.tracers._compat import pydantic_to_dict
+
+
+class LangSmithLoader(BaseLoader):
+ """Load LangSmith Dataset examples as `Document` objects.
+
+ Loads the example inputs as the `Document` page content and places the entire
+ example into the `Document` metadata. This allows you to easily create few-shot
+ example retrievers from the loaded documents.
+
+ ??? example "Lazy loading"
+
+ ```python
+ from langchain_core.document_loaders import LangSmithLoader
+
+ loader = LangSmithLoader(dataset_id="...", limit=100)
+ docs = []
+ for doc in loader.lazy_load():
+ docs.append(doc)
+ ```
+
+ ```python
+ # -> [Document("...", metadata={"inputs": {...}, "outputs": {...}, ...}), ...]
+ ```
+ """
+
+ def __init__(
+ self,
+ *,
+ dataset_id: uuid.UUID | str | None = None,
+ dataset_name: str | None = None,
+ example_ids: Sequence[uuid.UUID | str] | None = None,
+ as_of: datetime.datetime | str | None = None,
+ splits: Sequence[str] | None = None,
+ inline_s3_urls: bool = True,
+ offset: int = 0,
+ limit: int | None = None,
+ metadata: dict | None = None,
+ filter: str | None = None, # noqa: A002
+ content_key: str = "",
+ format_content: Callable[..., str] | None = None,
+ client: LangSmithClient | None = None,
+ **client_kwargs: Any,
+ ) -> None:
+ """Create a LangSmith loader.
+
+ Args:
+ dataset_id: The ID of the dataset to filter by.
+ dataset_name: The name of the dataset to filter by.
+ content_key: The inputs key to set as `Document` page content.
+
+ `'.'` characters are interpreted as nested keys, e.g.
+ `content_key="first.second"` will result in
+ `Document(page_content=format_content(example.inputs["first"]["second"]))`
+ format_content: Function for converting the content extracted from the example
+ inputs into a string.
+
+ Defaults to JSON-encoding the contents.
+ example_ids: The IDs of the examples to filter by.
+ as_of: The dataset version tag or timestamp to retrieve the examples as of.
+
+ Response examples will only be those that were present at the time of
+ the tagged (or timestamped) version.
+ splits: A list of dataset splits, which are divisions of your dataset such
+ as `train`, `test`, or `validation`.
+
+ Returns examples only from the specified splits.
+ inline_s3_urls: Whether to inline S3 URLs.
+ offset: The offset to start from.
+ limit: The maximum number of examples to return.
+ metadata: Metadata to filter by.
+ filter: A structured filter string to apply to the examples.
+ client: LangSmith Client.
+
+ If not provided will be initialized from below args.
+ client_kwargs: Keyword args to pass to LangSmith client init.
+
+ Should only be specified if `client` isn't.
+
+ Raises:
+ ValueError: If both `client` and `client_kwargs` are provided.
+ """ # noqa: E501
+ if client and client_kwargs:
+ raise ValueError
+ self._client = client or LangSmithClient(**client_kwargs)
+ self.content_key = list(content_key.split(".")) if content_key else []
+ self.format_content = format_content or _stringify
+ self.dataset_id = dataset_id
+ self.dataset_name = dataset_name
+ self.example_ids = example_ids
+ self.as_of = as_of
+ self.splits = splits
+ self.inline_s3_urls = inline_s3_urls
+ self.offset = offset
+ self.limit = limit
+ self.metadata = metadata
+ self.filter = filter
+
+ @override
+ def lazy_load(self) -> Iterator[Document]:
+ for example in self._client.list_examples(
+ dataset_id=self.dataset_id,
+ dataset_name=self.dataset_name,
+ example_ids=self.example_ids,
+ as_of=self.as_of,
+ splits=self.splits,
+ inline_s3_urls=self.inline_s3_urls,
+ offset=self.offset,
+ limit=self.limit,
+ metadata=self.metadata,
+ filter=self.filter,
+ ):
+ content: Any = example.inputs
+ for key in self.content_key:
+ content = content[key]
+ content_str = self.format_content(content)
+ metadata = pydantic_to_dict(example)
+ # Stringify datetime and UUID types.
+ for k in ("dataset_id", "created_at", "modified_at", "source_run_id", "id"):
+ metadata[k] = str(metadata[k]) if metadata[k] else metadata[k]
+ yield Document(content_str, metadata=metadata)
+
+
+def _stringify(x: str | dict[str, Any]) -> str:
+ if isinstance(x, str):
+ return x
+ try:
+ return json.dumps(x, indent=2)
+ except Exception:
+ return str(x)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..128a9dcfba68b2fcf4389588a318eef7a129c5e3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__init__.py
@@ -0,0 +1,55 @@
+"""Documents module for data retrieval and processing workflows.
+
+This module provides core abstractions for handling data in retrieval-augmented
+generation (RAG) pipelines, vector stores, and document processing workflows.
+
+!!! warning "Documents vs. message content"
+
+ This module is distinct from `langchain_core.messages.content`, which provides
+ multimodal content blocks for **LLM chat I/O** (text, images, audio, etc. within
+ messages).
+
+ **Key distinction:**
+
+ - **Documents** (this module): For **data retrieval and processing workflows**
+ - Vector stores, retrievers, RAG pipelines
+ - Text chunking, embedding, and semantic search
+ - Example: Chunks of a PDF stored in a vector database
+
+ - **Content Blocks** (`messages.content`): For **LLM conversational I/O**
+ - Multimodal message content sent to/from models
+ - Tool calls, reasoning, citations within chat
+ - Example: An image sent to a vision model in a chat message (via
+ [`ImageContentBlock`][langchain.messages.ImageContentBlock])
+
+ While both can represent similar data types (text, files), they serve different
+ architectural purposes in LangChain applications.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.documents.base import Document
+ from langchain_core.documents.compressor import BaseDocumentCompressor
+ from langchain_core.documents.transformers import BaseDocumentTransformer
+
+__all__ = ("BaseDocumentCompressor", "BaseDocumentTransformer", "Document")
+
+_dynamic_imports = {
+ "Document": "base",
+ "BaseDocumentCompressor": "compressor",
+ "BaseDocumentTransformer": "transformers",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f38fac8a212f959f6b8a01ab64c45343d05e0b73
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25b005c31e2d0bab3a7c02df8153aa9473a2d027
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__pycache__/compressor.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__pycache__/compressor.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40c9c56b1c6fbca23269cba8c8d0b97a61f83998
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__pycache__/compressor.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__pycache__/transformers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__pycache__/transformers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1ef118e6f254bca73d2b822e7c4d755c2a4d173d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/__pycache__/transformers.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..969ee49a174661eb07046a4a7ebd3d1a7ee5f820
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/base.py
@@ -0,0 +1,347 @@
+"""Base classes for media and documents.
+
+This module contains core abstractions for **data retrieval and processing workflows**:
+
+- `BaseMedia`: Base class providing `id` and `metadata` fields
+- `Blob`: Raw data loading (files, binary data) - used by document loaders
+- `Document`: Text content for retrieval (RAG, vector stores, semantic search)
+
+!!! note "Not for LLM chat messages"
+
+ These classes are for data processing pipelines, not LLM I/O. For multimodal
+ content in chat messages (images, audio in conversations), see
+ `langchain.messages` content blocks instead.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import mimetypes
+from io import BufferedReader, BytesIO
+from pathlib import Path, PurePath
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+from pydantic import ConfigDict, Field, model_validator
+
+from langchain_core.load.serializable import Serializable
+
+if TYPE_CHECKING:
+ from collections.abc import Generator
+
+PathLike = str | PurePath
+
+
+class BaseMedia(Serializable):
+ """Base class for content used in retrieval and data processing workflows.
+
+ Provides common fields for content that needs to be stored, indexed, or searched.
+
+ !!! note
+
+ For multimodal content in **chat messages** (images, audio sent to/from LLMs),
+ use `langchain.messages` content blocks instead.
+ """
+
+ # The ID field is optional at the moment.
+ # It will likely become required in a future major release after
+ # it has been adopted by enough VectorStore implementations.
+ id: str | None = Field(default=None, coerce_numbers_to_str=True)
+ """An optional identifier for the document.
+
+ Ideally this should be unique across the document collection and formatted
+ as a UUID, but this will not be enforced.
+ """
+
+ metadata: dict = Field(default_factory=dict)
+ """Arbitrary metadata associated with the content."""
+
+
+class Blob(BaseMedia):
+ """Raw data abstraction for document loading and file processing.
+
+ Represents raw bytes or text, either in-memory or by file reference. Used
+ primarily by document loaders to decouple data loading from parsing.
+
+ Inspired by [Mozilla's `Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
+
+ ???+ example "Initialize a blob from in-memory data"
+
+ ```python
+ from langchain_core.documents import Blob
+
+ blob = Blob.from_data("Hello, world!")
+
+ # Read the blob as a string
+ print(blob.as_string())
+
+ # Read the blob as bytes
+ print(blob.as_bytes())
+
+ # Read the blob as a byte stream
+ with blob.as_bytes_io() as f:
+ print(f.read())
+ ```
+
+ ??? example "Load from memory and specify MIME type and metadata"
+
+ ```python
+ from langchain_core.documents import Blob
+
+ blob = Blob.from_data(
+ data="Hello, world!",
+ mime_type="text/plain",
+ metadata={"source": "https://example.com"},
+ )
+ ```
+
+ ??? example "Load the blob from a file"
+
+ ```python
+ from langchain_core.documents import Blob
+
+ blob = Blob.from_path("path/to/file.txt")
+
+ # Read the blob as a string
+ print(blob.as_string())
+
+ # Read the blob as bytes
+ print(blob.as_bytes())
+
+ # Read the blob as a byte stream
+ with blob.as_bytes_io() as f:
+ print(f.read())
+ ```
+ """
+
+ data: bytes | str | None = None
+ """Raw data associated with the `Blob`."""
+
+ mimetype: str | None = None
+ """MIME type, not to be confused with a file extension."""
+
+ encoding: str = "utf-8"
+ """Encoding to use if decoding the bytes into a string.
+
+ Uses `utf-8` as default encoding if decoding to string.
+ """
+
+ path: PathLike | None = None
+ """Location where the original content was found."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ frozen=True,
+ )
+
+ @property
+ def source(self) -> str | None:
+ """The source location of the blob as string if known otherwise none.
+
+ If a path is associated with the `Blob`, it will default to the path location.
+
+ Unless explicitly set via a metadata field called `'source'`, in which
+ case that value will be used instead.
+ """
+ if self.metadata and "source" in self.metadata:
+ return cast("str | None", self.metadata["source"])
+ return str(self.path) if self.path else None
+
+ @model_validator(mode="before")
+ @classmethod
+ def check_blob_is_valid(cls, values: dict[str, Any]) -> Any:
+ """Verify that either data or path is provided."""
+ if "data" not in values and "path" not in values:
+ msg = "Either data or path must be provided"
+ raise ValueError(msg)
+ return values
+
+ def as_string(self) -> str:
+ """Read data as a string.
+
+ Raises:
+ ValueError: If the blob cannot be represented as a string.
+
+ Returns:
+ The data as a string.
+ """
+ if self.data is None and self.path:
+ return Path(self.path).read_text(encoding=self.encoding)
+ if isinstance(self.data, bytes):
+ return self.data.decode(self.encoding)
+ if isinstance(self.data, str):
+ return self.data
+ msg = f"Unable to get string for blob {self}"
+ raise ValueError(msg)
+
+ def as_bytes(self) -> bytes:
+ """Read data as bytes.
+
+ Raises:
+ ValueError: If the blob cannot be represented as bytes.
+
+ Returns:
+ The data as bytes.
+ """
+ if isinstance(self.data, bytes):
+ return self.data
+ if isinstance(self.data, str):
+ return self.data.encode(self.encoding)
+ if self.data is None and self.path:
+ return Path(self.path).read_bytes()
+ msg = f"Unable to get bytes for blob {self}"
+ raise ValueError(msg)
+
+ @contextlib.contextmanager
+ def as_bytes_io(self) -> Generator[BytesIO | BufferedReader, None, None]:
+ """Read data as a byte stream.
+
+ Raises:
+ NotImplementedError: If the blob cannot be represented as a byte stream.
+
+ Yields:
+ The data as a byte stream.
+ """
+ if isinstance(self.data, bytes):
+ yield BytesIO(self.data)
+ elif self.data is None and self.path:
+ with Path(self.path).open("rb") as f:
+ yield f
+ else:
+ msg = f"Unable to convert blob {self}"
+ raise NotImplementedError(msg)
+
+ @classmethod
+ def from_path(
+ cls,
+ path: PathLike,
+ *,
+ encoding: str = "utf-8",
+ mime_type: str | None = None,
+ guess_type: bool = True,
+ metadata: dict | None = None,
+ ) -> Blob:
+ """Load the blob from a path like object.
+
+ Args:
+ path: Path-like object to file to be read
+ encoding: Encoding to use if decoding the bytes into a string
+ mime_type: If provided, will be set as the MIME type of the data
+ guess_type: If `True`, the MIME type will be guessed from the file
+ extension, if a MIME type was not provided
+ metadata: Metadata to associate with the `Blob`
+
+ Returns:
+ `Blob` instance
+ """
+ if mime_type is None and guess_type:
+ mimetype = mimetypes.guess_type(path)[0]
+ else:
+ mimetype = mime_type
+ # We do not load the data immediately, instead we treat the blob as a
+ # reference to the underlying data.
+ return cls(
+ data=None,
+ mimetype=mimetype,
+ encoding=encoding,
+ path=path,
+ metadata=metadata if metadata is not None else {},
+ )
+
+ @classmethod
+ def from_data(
+ cls,
+ data: str | bytes,
+ *,
+ encoding: str = "utf-8",
+ mime_type: str | None = None,
+ path: str | None = None,
+ metadata: dict | None = None,
+ ) -> Blob:
+ """Initialize the `Blob` from in-memory data.
+
+ Args:
+ data: The in-memory data associated with the `Blob`
+ encoding: Encoding to use if decoding the bytes into a string
+ mime_type: If provided, will be set as the MIME type of the data
+ path: If provided, will be set as the source from which the data came
+ metadata: Metadata to associate with the `Blob`
+
+ Returns:
+ `Blob` instance
+ """
+ return cls(
+ data=data,
+ mimetype=mime_type,
+ encoding=encoding,
+ path=path,
+ metadata=metadata if metadata is not None else {},
+ )
+
+ def __repr__(self) -> str:
+ """Return the blob representation."""
+ str_repr = f"Blob {id(self)}"
+ if self.source:
+ str_repr += f" {self.source}"
+ return str_repr
+
+
+class Document(BaseMedia):
+ """Class for storing a piece of text and associated metadata.
+
+ !!! note
+
+ `Document` is for **retrieval workflows**, not chat I/O. For sending text
+ to an LLM in a conversation, use message types from `langchain.messages`.
+
+ Example:
+ ```python
+ from langchain_core.documents import Document
+
+ document = Document(
+ page_content="Hello, world!", metadata={"source": "https://example.com"}
+ )
+ ```
+ """
+
+ page_content: str
+ """String text."""
+
+ type: Literal["Document"] = "Document"
+
+ def __init__(self, page_content: str, **kwargs: Any) -> None:
+ """Pass page_content in as positional or named arg."""
+ # my-py is complaining that page_content is not defined on the base class.
+ # Here, we're relying on pydantic base class to handle the validation.
+ super().__init__(page_content=page_content, **kwargs) # type: ignore[call-arg,unused-ignore]
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "document"]`
+ """
+ return ["langchain", "schema", "document"]
+
+ def __str__(self) -> str:
+ """Override `__str__` to restrict it to page_content and metadata.
+
+ Returns:
+ A string representation of the `Document`.
+ """
+ # The format matches pydantic format for __str__.
+ #
+ # The purpose of this change is to make sure that user code that feeds
+ # Document objects directly into prompts remains unchanged due to the addition
+ # of the id field (or any other fields in the future).
+ #
+ # This override will likely be removed in the future in favor of a more general
+ # solution of formatting content directly inside the prompts.
+ if self.metadata:
+ return f"page_content='{self.page_content}' metadata={self.metadata}"
+ return f"page_content='{self.page_content}'"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/compressor.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/compressor.py
new file mode 100644
index 0000000000000000000000000000000000000000..c765b378bb1f7bbdfc19cd74b1f9ede08029315a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/compressor.py
@@ -0,0 +1,74 @@
+"""Document compressor."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING
+
+from pydantic import BaseModel
+
+from langchain_core.runnables import run_in_executor
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from langchain_core.callbacks import Callbacks
+ from langchain_core.documents import Document
+
+
+class BaseDocumentCompressor(BaseModel, ABC):
+ """Base class for document compressors.
+
+ This abstraction is primarily used for post-processing of retrieved documents.
+
+ `Document` objects matching a given query are first retrieved.
+
+ Then the list of documents can be further processed.
+
+ For example, one could re-rank the retrieved documents using an LLM.
+
+ !!! note
+ Users should favor using a `RunnableLambda` instead of sub-classing from this
+ interface.
+
+ """
+
+ @abstractmethod
+ def compress_documents(
+ self,
+ documents: Sequence[Document],
+ query: str,
+ callbacks: Callbacks | None = None,
+ ) -> Sequence[Document]:
+ """Compress retrieved documents given the query context.
+
+ Args:
+ documents: The retrieved `Document` objects.
+ query: The query context.
+ callbacks: Optional `Callbacks` to run during compression.
+
+ Returns:
+ The compressed documents.
+
+ """
+
+ async def acompress_documents(
+ self,
+ documents: Sequence[Document],
+ query: str,
+ callbacks: Callbacks | None = None,
+ ) -> Sequence[Document]:
+ """Async compress retrieved documents given the query context.
+
+ Args:
+ documents: The retrieved `Document` objects.
+ query: The query context.
+ callbacks: Optional `Callbacks` to run during compression.
+
+ Returns:
+ The compressed documents.
+
+ """
+ return await run_in_executor(
+ None, self.compress_documents, documents, query, callbacks
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/transformers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/transformers.py
new file mode 100644
index 0000000000000000000000000000000000000000..c05fa29a23953a73775895ddda3c03cb0fea946d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/documents/transformers.py
@@ -0,0 +1,79 @@
+"""Document transformers."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any
+
+from langchain_core.runnables.config import run_in_executor
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from langchain_core.documents import Document
+
+
+class BaseDocumentTransformer(ABC):
+ """Abstract base class for document transformation.
+
+ A document transformation takes a sequence of `Document` objects and returns a
+ sequence of transformed `Document` objects.
+
+ Example:
+ ```python
+ class EmbeddingsRedundantFilter(BaseDocumentTransformer, BaseModel):
+ embeddings: Embeddings
+ similarity_fn: Callable = cosine_similarity
+ similarity_threshold: float = 0.95
+
+ class Config:
+ arbitrary_types_allowed = True
+
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ stateful_documents = get_stateful_documents(documents)
+ embedded_documents = _get_embeddings_from_stateful_docs(
+ self.embeddings, stateful_documents
+ )
+ included_idxs = _filter_similar_embeddings(
+ embedded_documents,
+ self.similarity_fn,
+ self.similarity_threshold,
+ )
+ return [stateful_documents[i] for i in sorted(included_idxs)]
+
+ async def atransform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ raise NotImplementedError
+ ```
+ """
+
+ @abstractmethod
+ def transform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Transform a list of documents.
+
+ Args:
+ documents: A sequence of `Document` objects to be transformed.
+
+ Returns:
+ A sequence of transformed `Document` objects.
+ """
+
+ async def atransform_documents(
+ self, documents: Sequence[Document], **kwargs: Any
+ ) -> Sequence[Document]:
+ """Asynchronously transform a list of documents.
+
+ Args:
+ documents: A sequence of `Document` objects to be transformed.
+
+ Returns:
+ A sequence of transformed `Document` objects.
+ """
+ return await run_in_executor(
+ None, self.transform_documents, documents, **kwargs
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..66acae126fc1aa199fe9c24d899c325bdc431692
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/__init__.py
@@ -0,0 +1,31 @@
+"""Embeddings."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.embeddings.embeddings import Embeddings
+ from langchain_core.embeddings.fake import (
+ DeterministicFakeEmbedding,
+ FakeEmbeddings,
+ )
+
+__all__ = ("DeterministicFakeEmbedding", "Embeddings", "FakeEmbeddings")
+
+_dynamic_imports = {
+ "Embeddings": "embeddings",
+ "DeterministicFakeEmbedding": "fake",
+ "FakeEmbeddings": "fake",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b1a8189761f0a9a24e8f4b3399237d7632d1182f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/__pycache__/embeddings.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/__pycache__/embeddings.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e53733c9578eb840c011542423519b50a1d2c852
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/__pycache__/embeddings.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/__pycache__/fake.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/__pycache__/fake.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dfc230492baf2462394c689d3c28e29c8019de82
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/__pycache__/fake.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/embeddings.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/embeddings.py
new file mode 100644
index 0000000000000000000000000000000000000000..39c0eb42a89532a7b57aec779a6c85e0a0c1f0d6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/embeddings.py
@@ -0,0 +1,78 @@
+"""**Embeddings** interface."""
+
+from abc import ABC, abstractmethod
+
+from langchain_core.runnables.config import run_in_executor
+
+
+class Embeddings(ABC):
+ """Interface for embedding models.
+
+ This is an interface meant for implementing text embedding models.
+
+ Text embedding models are used to map text to a vector (a point in n-dimensional
+ space).
+
+ Texts that are similar will usually be mapped to points that are close to each
+ other in this space. The exact details of what's considered "similar" and how
+ "distance" is measured in this space are dependent on the specific embedding model.
+
+ This abstraction contains a method for embedding a list of documents and a method
+ for embedding a query text. The embedding of a query text is expected to be a single
+ vector, while the embedding of a list of documents is expected to be a list of
+ vectors.
+
+ Usually the query embedding is identical to the document embedding, but the
+ abstraction allows treating them independently.
+
+ In addition to the synchronous methods, this interface also provides asynchronous
+ versions of the methods.
+
+ By default, the asynchronous methods are implemented using the synchronous methods;
+ however, implementations may choose to override the asynchronous methods with
+ an async native implementation for performance reasons.
+ """
+
+ @abstractmethod
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
+ """Embed search docs.
+
+ Args:
+ texts: List of text to embed.
+
+ Returns:
+ List of embeddings.
+ """
+
+ @abstractmethod
+ def embed_query(self, text: str) -> list[float]:
+ """Embed query text.
+
+ Args:
+ text: Text to embed.
+
+ Returns:
+ Embedding.
+ """
+
+ async def aembed_documents(self, texts: list[str]) -> list[list[float]]:
+ """Asynchronous Embed search docs.
+
+ Args:
+ texts: List of text to embed.
+
+ Returns:
+ List of embeddings.
+ """
+ return await run_in_executor(None, self.embed_documents, texts)
+
+ async def aembed_query(self, text: str) -> list[float]:
+ """Asynchronous Embed query text.
+
+ Args:
+ text: Text to embed.
+
+ Returns:
+ Embedding.
+ """
+ return await run_in_executor(None, self.embed_query, text)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/fake.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/fake.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a252efc194eff881919bc1bbec976e0adbe5704
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/embeddings/fake.py
@@ -0,0 +1,129 @@
+"""Module contains a few fake embedding models for testing purposes."""
+
+# Please do not add additional fake embedding model implementations here.
+import contextlib
+import hashlib
+
+from pydantic import BaseModel
+from typing_extensions import override
+
+from langchain_core.embeddings import Embeddings
+
+with contextlib.suppress(ImportError):
+ import numpy as np
+
+
+class FakeEmbeddings(Embeddings, BaseModel):
+ """Fake embedding model for unit testing purposes.
+
+ This embedding model creates embeddings by sampling from a normal distribution.
+
+ !!! danger "Toy model"
+ Do not use this outside of testing, as it is not a real embedding model.
+
+ Instantiate:
+ ```python
+ from langchain_core.embeddings import FakeEmbeddings
+
+ embed = FakeEmbeddings(size=100)
+ ```
+
+ Embed single text:
+ ```python
+ input_text = "The meaning of life is 42"
+ vector = embed.embed_query(input_text)
+ print(vector[:3])
+ ```
+ ```python
+ [-0.700234640213188, -0.581266257710429, -1.1328482266445354]
+ ```
+
+ Embed multiple texts:
+ ```python
+ input_texts = ["Document 1...", "Document 2..."]
+ vectors = embed.embed_documents(input_texts)
+ print(len(vectors))
+ # The first 3 coordinates for the first vector
+ print(vectors[0][:3])
+ ```
+ ```python
+ 2
+ [-0.5670477847544458, -0.31403828652395727, -0.5840547508955257]
+ ```
+ """
+
+ size: int
+ """The size of the embedding vector."""
+
+ def _get_embedding(self) -> list[float]:
+ return list(np.random.default_rng().normal(size=self.size))
+
+ @override
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
+ return [self._get_embedding() for _ in texts]
+
+ @override
+ def embed_query(self, text: str) -> list[float]:
+ return self._get_embedding()
+
+
+class DeterministicFakeEmbedding(Embeddings, BaseModel):
+ """Deterministic fake embedding model for unit testing purposes.
+
+ This embedding model creates embeddings by sampling from a normal distribution
+ with a seed based on the hash of the text.
+
+ !!! danger "Toy model"
+ Do not use this outside of testing, as it is not a real embedding model.
+
+ Instantiate:
+ ```python
+ from langchain_core.embeddings import DeterministicFakeEmbedding
+
+ embed = DeterministicFakeEmbedding(size=100)
+ ```
+
+ Embed single text:
+ ```python
+ input_text = "The meaning of life is 42"
+ vector = embed.embed_query(input_text)
+ print(vector[:3])
+ ```
+ ```python
+ [-0.700234640213188, -0.581266257710429, -1.1328482266445354]
+ ```
+
+ Embed multiple texts:
+ ```python
+ input_texts = ["Document 1...", "Document 2..."]
+ vectors = embed.embed_documents(input_texts)
+ print(len(vectors))
+ # The first 3 coordinates for the first vector
+ print(vectors[0][:3])
+ ```
+ ```python
+ 2
+ [-0.5670477847544458, -0.31403828652395727, -0.5840547508955257]
+ ```
+ """
+
+ size: int
+ """The size of the embedding vector."""
+
+ def _get_embedding(self, seed: int) -> list[float]:
+ # set the seed for the random generator
+ rng = np.random.default_rng(seed)
+ return list(rng.normal(size=self.size))
+
+ @staticmethod
+ def _get_seed(text: str) -> int:
+ """Get a seed for the random generator, using the hash of the text."""
+ return int(hashlib.sha256(text.encode("utf-8")).hexdigest(), 16) % 10**8
+
+ @override
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
+ return [self._get_embedding(seed=self._get_seed(_)) for _ in texts]
+
+ @override
+ def embed_query(self, text: str) -> list[float]:
+ return self._get_embedding(seed=self._get_seed(text))
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..db079c9f91f11cc88d3e296f16d46dd73f7a4fd3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__init__.py
@@ -0,0 +1,47 @@
+"""Example selectors.
+
+**Example selector** implements logic for selecting examples to include them in prompts.
+This allows us to select examples that are most relevant to the input.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.example_selectors.base import BaseExampleSelector
+ from langchain_core.example_selectors.length_based import (
+ LengthBasedExampleSelector,
+ )
+ from langchain_core.example_selectors.semantic_similarity import (
+ MaxMarginalRelevanceExampleSelector,
+ SemanticSimilarityExampleSelector,
+ sorted_values,
+ )
+
+__all__ = (
+ "BaseExampleSelector",
+ "LengthBasedExampleSelector",
+ "MaxMarginalRelevanceExampleSelector",
+ "SemanticSimilarityExampleSelector",
+ "sorted_values",
+)
+
+_dynamic_imports = {
+ "BaseExampleSelector": "base",
+ "LengthBasedExampleSelector": "length_based",
+ "MaxMarginalRelevanceExampleSelector": "semantic_similarity",
+ "SemanticSimilarityExampleSelector": "semantic_similarity",
+ "sorted_values": "semantic_similarity",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..28885f0fed9dd7f7fcf2c800e4c41a8de54aba71
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1ba9ffc875f266dd5ca08e9cc4e21c29538989e4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__pycache__/length_based.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__pycache__/length_based.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f08ecb3e619115cc9caa0c9c905bb97ed6fd50e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__pycache__/length_based.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__pycache__/semantic_similarity.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__pycache__/semantic_similarity.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8aff13f898e2f103dcaad92be84a653a9e065205
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/__pycache__/semantic_similarity.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec845cfc2e942a3e181b92c9c8bc0ea8ae0db8a9
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/base.py
@@ -0,0 +1,58 @@
+"""Interface for selecting examples to include in prompts."""
+
+from abc import ABC, abstractmethod
+from typing import Any
+
+from langchain_core.runnables import run_in_executor
+
+
+class BaseExampleSelector(ABC):
+ """Interface for selecting examples to include in prompts."""
+
+ @abstractmethod
+ def add_example(self, example: dict[str, str]) -> Any:
+ """Add new example to store.
+
+ Args:
+ example: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ Any return value.
+ """
+
+ async def aadd_example(self, example: dict[str, str]) -> Any:
+ """Async add new example to store.
+
+ Args:
+ example: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ Any return value.
+ """
+ return await run_in_executor(None, self.add_example, example)
+
+ @abstractmethod
+ def select_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Select which examples to use based on the inputs.
+
+ Args:
+ input_variables: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ A list of examples.
+ """
+
+ async def aselect_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Async select which examples to use based on the inputs.
+
+ Args:
+ input_variables: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ A list of examples.
+ """
+ return await run_in_executor(None, self.select_examples, input_variables)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/length_based.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/length_based.py
new file mode 100644
index 0000000000000000000000000000000000000000..e60e47e891d3d8aea2d808060ff9d1120887c89a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/length_based.py
@@ -0,0 +1,128 @@
+"""Select examples based on length."""
+
+import re
+from collections.abc import Callable
+
+from pydantic import BaseModel, Field, model_validator
+from typing_extensions import Self
+
+from langchain_core.example_selectors.base import BaseExampleSelector
+from langchain_core.prompts.prompt import PromptTemplate
+
+
+def _get_length_based(text: str) -> int:
+ return len(re.split(r"\n| ", text))
+
+
+class LengthBasedExampleSelector(BaseExampleSelector, BaseModel):
+ r"""Select examples based on length.
+
+ Example:
+ ```python
+ from langchain_core.example_selectors import LengthBasedExampleSelector
+ from langchain_core.prompts import PromptTemplate
+
+ # Define examples
+ examples = [
+ {"input": "happy", "output": "sad"},
+ {"input": "tall", "output": "short"},
+ {"input": "fast", "output": "slow"},
+ ]
+
+ # Create prompt template
+ example_prompt = PromptTemplate(
+ input_variables=["input", "output"],
+ template="Input: {input}\nOutput: {output}",
+ )
+
+ # Create selector with max length constraint
+ selector = LengthBasedExampleSelector(
+ examples=examples,
+ example_prompt=example_prompt,
+ max_length=50, # Maximum prompt length
+ )
+
+ # Select examples for a new input
+ selected = selector.select_examples({"input": "large", "output": "tiny"})
+ # Returns examples that fit within max_length constraint
+ ```
+ """
+
+ examples: list[dict]
+ """A list of the examples that the prompt template expects."""
+
+ example_prompt: PromptTemplate
+ """Prompt template used to format the examples."""
+
+ get_text_length: Callable[[str], int] = _get_length_based
+ """Function to measure prompt length. Defaults to word count."""
+
+ max_length: int = 2048
+ """Max length for the prompt, beyond which examples are cut."""
+
+ example_text_lengths: list[int] = Field(default_factory=list)
+ """Length of each example."""
+
+ def add_example(self, example: dict[str, str]) -> None:
+ """Add new example to list.
+
+ Args:
+ example: A dictionary with keys as input variables
+ and values as their values.
+ """
+ self.examples.append(example)
+ string_example = self.example_prompt.format(**example)
+ self.example_text_lengths.append(self.get_text_length(string_example))
+
+ async def aadd_example(self, example: dict[str, str]) -> None:
+ """Async add new example to list.
+
+ Args:
+ example: A dictionary with keys as input variables
+ and values as their values.
+ """
+ self.add_example(example)
+
+ @model_validator(mode="after")
+ def post_init(self) -> Self:
+ """Validate that the examples are formatted correctly."""
+ if self.example_text_lengths:
+ return self
+ string_examples = [self.example_prompt.format(**eg) for eg in self.examples]
+ self.example_text_lengths = [self.get_text_length(eg) for eg in string_examples]
+ return self
+
+ def select_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Select which examples to use based on the input lengths.
+
+ Args:
+ input_variables: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ A list of examples to include in the prompt.
+ """
+ inputs = " ".join(input_variables.values())
+ remaining_length = self.max_length - self.get_text_length(inputs)
+ i = 0
+ examples = []
+ while remaining_length > 0 and i < len(self.examples):
+ new_length = remaining_length - self.example_text_lengths[i]
+ if new_length < 0:
+ break
+ examples.append(self.examples[i])
+ remaining_length = new_length
+ i += 1
+ return examples
+
+ async def aselect_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Async select which examples to use based on the input lengths.
+
+ Args:
+ input_variables: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ A list of examples to include in the prompt.
+ """
+ return self.select_examples(input_variables)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/semantic_similarity.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/semantic_similarity.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e7491a2eb79cc850f66748e52e85dc7cdece394
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/example_selectors/semantic_similarity.py
@@ -0,0 +1,358 @@
+"""Example selector that selects examples based on SemanticSimilarity."""
+
+from __future__ import annotations
+
+from abc import ABC
+from typing import TYPE_CHECKING, Any
+
+from pydantic import BaseModel, ConfigDict
+
+from langchain_core.example_selectors.base import BaseExampleSelector
+from langchain_core.vectorstores import VectorStore
+
+if TYPE_CHECKING:
+ from langchain_core.documents import Document
+ from langchain_core.embeddings import Embeddings
+
+
+def sorted_values(values: dict[str, str]) -> list[Any]:
+ """Return a list of values in dict sorted by key.
+
+ Args:
+ values: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ A list of values in dict sorted by key.
+ """
+ return [values[val] for val in sorted(values)]
+
+
+class _VectorStoreExampleSelector(BaseExampleSelector, BaseModel, ABC):
+ """Example selector that selects examples based on SemanticSimilarity."""
+
+ vectorstore: VectorStore
+ """VectorStore that contains information about examples."""
+ k: int = 4
+ """Number of examples to select."""
+ example_keys: list[str] | None = None
+ """Optional keys to filter examples to."""
+ input_keys: list[str] | None = None
+ """Optional keys to filter input to. If provided, the search is based on
+ the input variables instead of all variables."""
+ vectorstore_kwargs: dict[str, Any] | None = None
+ """Extra arguments passed to similarity_search function of the `VectorStore`."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ @staticmethod
+ def _example_to_text(example: dict[str, str], input_keys: list[str] | None) -> str:
+ if input_keys:
+ return " ".join(sorted_values({key: example[key] for key in input_keys}))
+ return " ".join(sorted_values(example))
+
+ def _documents_to_examples(self, documents: list[Document]) -> list[dict]:
+ # Get the examples from the metadata.
+ # This assumes that examples are stored in metadata.
+ examples = [dict(e.metadata) for e in documents]
+ # If example keys are provided, filter examples to those keys.
+ if self.example_keys:
+ examples = [{k: eg[k] for k in self.example_keys} for eg in examples]
+ return examples
+
+ def add_example(self, example: dict[str, str]) -> str:
+ """Add a new example to vectorstore.
+
+ Args:
+ example: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ The ID of the added example.
+ """
+ ids = self.vectorstore.add_texts(
+ [self._example_to_text(example, self.input_keys)], metadatas=[example]
+ )
+ return ids[0]
+
+ async def aadd_example(self, example: dict[str, str]) -> str:
+ """Async add new example to vectorstore.
+
+ Args:
+ example: A dictionary with keys as input variables
+ and values as their values.
+
+ Returns:
+ The ID of the added example.
+ """
+ ids = await self.vectorstore.aadd_texts(
+ [self._example_to_text(example, self.input_keys)], metadatas=[example]
+ )
+ return ids[0]
+
+
+class SemanticSimilarityExampleSelector(_VectorStoreExampleSelector):
+ """Select examples based on semantic similarity."""
+
+ def select_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Select examples based on semantic similarity.
+
+ Args:
+ input_variables: The input variables to use for search.
+
+ Returns:
+ The selected examples.
+ """
+ # Get the docs with the highest similarity.
+ vectorstore_kwargs = self.vectorstore_kwargs or {}
+ example_docs = self.vectorstore.similarity_search(
+ self._example_to_text(input_variables, self.input_keys),
+ k=self.k,
+ **vectorstore_kwargs,
+ )
+ return self._documents_to_examples(example_docs)
+
+ async def aselect_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Asynchronously select examples based on semantic similarity.
+
+ Args:
+ input_variables: The input variables to use for search.
+
+ Returns:
+ The selected examples.
+ """
+ # Get the docs with the highest similarity.
+ vectorstore_kwargs = self.vectorstore_kwargs or {}
+ example_docs = await self.vectorstore.asimilarity_search(
+ self._example_to_text(input_variables, self.input_keys),
+ k=self.k,
+ **vectorstore_kwargs,
+ )
+ return self._documents_to_examples(example_docs)
+
+ @classmethod
+ def from_examples(
+ cls,
+ examples: list[dict],
+ embeddings: Embeddings,
+ vectorstore_cls: type[VectorStore],
+ k: int = 4,
+ input_keys: list[str] | None = None,
+ *,
+ example_keys: list[str] | None = None,
+ vectorstore_kwargs: dict | None = None,
+ **vectorstore_cls_kwargs: Any,
+ ) -> SemanticSimilarityExampleSelector:
+ """Create k-shot example selector using example list and embeddings.
+
+ Reshuffles examples dynamically based on query similarity.
+
+ Args:
+ examples: List of examples to use in the prompt.
+ embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
+ vectorstore_cls: A vector store DB interface class, e.g. FAISS.
+ k: Number of examples to select.
+ input_keys: If provided, the search is based on the input variables
+ instead of all variables.
+ example_keys: If provided, keys to filter examples to.
+ vectorstore_kwargs: Extra arguments passed to similarity_search function
+ of the `VectorStore`.
+ vectorstore_cls_kwargs: optional kwargs containing url for vector store
+
+ Returns:
+ The ExampleSelector instantiated, backed by a vector store.
+ """
+ string_examples = [cls._example_to_text(eg, input_keys) for eg in examples]
+ vectorstore = vectorstore_cls.from_texts(
+ string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
+ )
+ return cls(
+ vectorstore=vectorstore,
+ k=k,
+ input_keys=input_keys,
+ example_keys=example_keys,
+ vectorstore_kwargs=vectorstore_kwargs,
+ )
+
+ @classmethod
+ async def afrom_examples(
+ cls,
+ examples: list[dict],
+ embeddings: Embeddings,
+ vectorstore_cls: type[VectorStore],
+ k: int = 4,
+ input_keys: list[str] | None = None,
+ *,
+ example_keys: list[str] | None = None,
+ vectorstore_kwargs: dict | None = None,
+ **vectorstore_cls_kwargs: Any,
+ ) -> SemanticSimilarityExampleSelector:
+ """Async create k-shot example selector using example list and embeddings.
+
+ Reshuffles examples dynamically based on query similarity.
+
+ Args:
+ examples: List of examples to use in the prompt.
+ embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
+ vectorstore_cls: A vector store DB interface class, e.g. FAISS.
+ k: Number of examples to select.
+ input_keys: If provided, the search is based on the input variables
+ instead of all variables.
+ example_keys: If provided, keys to filter examples to.
+ vectorstore_kwargs: Extra arguments passed to similarity_search function
+ of the `VectorStore`.
+ vectorstore_cls_kwargs: optional kwargs containing url for vector store
+
+ Returns:
+ The ExampleSelector instantiated, backed by a vector store.
+ """
+ string_examples = [cls._example_to_text(eg, input_keys) for eg in examples]
+ vectorstore = await vectorstore_cls.afrom_texts(
+ string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
+ )
+ return cls(
+ vectorstore=vectorstore,
+ k=k,
+ input_keys=input_keys,
+ example_keys=example_keys,
+ vectorstore_kwargs=vectorstore_kwargs,
+ )
+
+
+class MaxMarginalRelevanceExampleSelector(_VectorStoreExampleSelector):
+ """Select examples based on Max Marginal Relevance.
+
+ This was shown to improve performance in this paper:
+ https://arxiv.org/pdf/2211.13892.pdf
+ """
+
+ fetch_k: int = 20
+ """Number of examples to fetch to rerank."""
+
+ def select_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Select examples based on Max Marginal Relevance.
+
+ Args:
+ input_variables: The input variables to use for search.
+
+ Returns:
+ The selected examples.
+ """
+ example_docs = self.vectorstore.max_marginal_relevance_search(
+ self._example_to_text(input_variables, self.input_keys),
+ k=self.k,
+ fetch_k=self.fetch_k,
+ )
+ return self._documents_to_examples(example_docs)
+
+ async def aselect_examples(self, input_variables: dict[str, str]) -> list[dict]:
+ """Asynchronously select examples based on Max Marginal Relevance.
+
+ Args:
+ input_variables: The input variables to use for search.
+
+ Returns:
+ The selected examples.
+ """
+ example_docs = await self.vectorstore.amax_marginal_relevance_search(
+ self._example_to_text(input_variables, self.input_keys),
+ k=self.k,
+ fetch_k=self.fetch_k,
+ )
+ return self._documents_to_examples(example_docs)
+
+ @classmethod
+ def from_examples(
+ cls,
+ examples: list[dict],
+ embeddings: Embeddings,
+ vectorstore_cls: type[VectorStore],
+ k: int = 4,
+ input_keys: list[str] | None = None,
+ fetch_k: int = 20,
+ example_keys: list[str] | None = None,
+ vectorstore_kwargs: dict | None = None,
+ **vectorstore_cls_kwargs: Any,
+ ) -> MaxMarginalRelevanceExampleSelector:
+ """Create k-shot example selector using example list and embeddings.
+
+ Reshuffles examples dynamically based on Max Marginal Relevance.
+
+ Args:
+ examples: List of examples to use in the prompt.
+ embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
+ vectorstore_cls: A vector store DB interface class, e.g. FAISS.
+ k: Number of examples to select.
+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
+ input_keys: If provided, the search is based on the input variables
+ instead of all variables.
+ example_keys: If provided, keys to filter examples to.
+ vectorstore_kwargs: Extra arguments passed to similarity_search function
+ of the `VectorStore`.
+ vectorstore_cls_kwargs: optional kwargs containing url for vector store
+
+ Returns:
+ The ExampleSelector instantiated, backed by a vector store.
+ """
+ string_examples = [cls._example_to_text(eg, input_keys) for eg in examples]
+ vectorstore = vectorstore_cls.from_texts(
+ string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
+ )
+ return cls(
+ vectorstore=vectorstore,
+ k=k,
+ fetch_k=fetch_k,
+ input_keys=input_keys,
+ example_keys=example_keys,
+ vectorstore_kwargs=vectorstore_kwargs,
+ )
+
+ @classmethod
+ async def afrom_examples(
+ cls,
+ examples: list[dict],
+ embeddings: Embeddings,
+ vectorstore_cls: type[VectorStore],
+ *,
+ k: int = 4,
+ input_keys: list[str] | None = None,
+ fetch_k: int = 20,
+ example_keys: list[str] | None = None,
+ vectorstore_kwargs: dict | None = None,
+ **vectorstore_cls_kwargs: Any,
+ ) -> MaxMarginalRelevanceExampleSelector:
+ """Create k-shot example selector using example list and embeddings.
+
+ Reshuffles examples dynamically based on Max Marginal Relevance.
+
+ Args:
+ examples: List of examples to use in the prompt.
+ embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
+ vectorstore_cls: A vector store DB interface class, e.g. FAISS.
+ k: Number of examples to select.
+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
+ input_keys: If provided, the search is based on the input variables
+ instead of all variables.
+ example_keys: If provided, keys to filter examples to.
+ vectorstore_kwargs: Extra arguments passed to similarity_search function
+ of the `VectorStore`.
+ vectorstore_cls_kwargs: optional kwargs containing url for vector store
+
+ Returns:
+ The ExampleSelector instantiated, backed by a vector store.
+ """
+ string_examples = [cls._example_to_text(eg, input_keys) for eg in examples]
+ vectorstore = await vectorstore_cls.afrom_texts(
+ string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
+ )
+ return cls(
+ vectorstore=vectorstore,
+ k=k,
+ fetch_k=fetch_k,
+ input_keys=input_keys,
+ example_keys=example_keys,
+ vectorstore_kwargs=vectorstore_kwargs,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceb25d2d074d1e8fb416dbfd78ce40df9cf2c0f3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__init__.py
@@ -0,0 +1,53 @@
+"""Code to help indexing data into a vectorstore.
+
+This package contains helper logic to help deal with indexing data into
+a `VectorStore` while avoiding duplicated content and over-writing content
+if it's unchanged.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.indexing.api import IndexingResult, aindex, index
+ from langchain_core.indexing.base import (
+ DeleteResponse,
+ DocumentIndex,
+ InMemoryRecordManager,
+ RecordManager,
+ UpsertResponse,
+ )
+
+__all__ = (
+ "DeleteResponse",
+ "DocumentIndex",
+ "InMemoryRecordManager",
+ "IndexingResult",
+ "RecordManager",
+ "UpsertResponse",
+ "aindex",
+ "index",
+)
+
+_dynamic_imports = {
+ "aindex": "api",
+ "index": "api",
+ "IndexingResult": "api",
+ "DeleteResponse": "base",
+ "DocumentIndex": "base",
+ "InMemoryRecordManager": "base",
+ "RecordManager": "base",
+ "UpsertResponse": "base",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7864e6e5973b9f40f74b05de1adfbba4333a156f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__pycache__/api.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..235070a004ba52a471825980b3bff951d4c75f6f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__pycache__/api.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d29aabaf18b46a84f2d785369b308a5746e0930
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__pycache__/in_memory.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__pycache__/in_memory.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d11d5fb768d7867c4ddda918172378ebb040cec
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/__pycache__/in_memory.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4af08b8b54e8dcb157eda4941836d11236ac09e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/api.py
@@ -0,0 +1,954 @@
+"""Module contains logic for indexing documents into vector stores."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import uuid
+import warnings
+from itertools import islice
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ TypedDict,
+ TypeVar,
+ cast,
+)
+
+from langchain_core.document_loaders.base import BaseLoader
+from langchain_core.documents import Document
+from langchain_core.exceptions import LangChainException
+from langchain_core.indexing.base import DocumentIndex, RecordManager
+from langchain_core.vectorstores import VectorStore
+
+if TYPE_CHECKING:
+ from collections.abc import (
+ AsyncIterable,
+ AsyncIterator,
+ Callable,
+ Iterable,
+ Iterator,
+ Sequence,
+ )
+
+# Magic UUID to use as a namespace for hashing.
+# Used to try and generate a unique UUID for each document
+# from hashing the document content and metadata.
+NAMESPACE_UUID = uuid.UUID(int=1984)
+
+
+T = TypeVar("T")
+
+
+def _hash_string_to_uuid(input_string: str) -> str:
+ """Hashes a string and returns the corresponding UUID."""
+ hash_value = hashlib.sha1(
+ input_string.encode("utf-8"), usedforsecurity=False
+ ).hexdigest()
+ return str(uuid.uuid5(NAMESPACE_UUID, hash_value))
+
+
+_WARNED_ABOUT_SHA1: bool = False
+
+
+def _warn_about_sha1() -> None:
+ """Emit a one-time warning about SHA-1 collision weaknesses."""
+ # Global variable OK in this case
+ global _WARNED_ABOUT_SHA1 # noqa: PLW0603
+ if not _WARNED_ABOUT_SHA1:
+ warnings.warn(
+ "Using SHA-1 for document hashing. SHA-1 is *not* "
+ "collision-resistant; a motivated attacker can construct distinct inputs "
+ "that map to the same fingerprint. If this matters in your "
+ "threat model, switch to a stronger algorithm such "
+ "as 'blake2b', 'sha256', or 'sha512' by specifying "
+ " `key_encoder` parameter in the `index` or `aindex` function. ",
+ category=UserWarning,
+ stacklevel=2,
+ )
+ _WARNED_ABOUT_SHA1 = True
+
+
+def _hash_string(
+ input_string: str, *, algorithm: Literal["sha1", "sha256", "sha512", "blake2b"]
+) -> uuid.UUID:
+ """Hash *input_string* to a deterministic UUID using the configured algorithm."""
+ if algorithm == "sha1":
+ _warn_about_sha1()
+ hash_value = _calculate_hash(input_string, algorithm)
+ return uuid.uuid5(NAMESPACE_UUID, hash_value)
+
+
+def _hash_nested_dict(
+ data: dict[Any, Any], *, algorithm: Literal["sha1", "sha256", "sha512", "blake2b"]
+) -> uuid.UUID:
+ """Hash a nested dictionary to a UUID using the configured algorithm."""
+ serialized_data = json.dumps(data, sort_keys=True)
+ return _hash_string(serialized_data, algorithm=algorithm)
+
+
+def _batch(size: int, iterable: Iterable[T]) -> Iterator[list[T]]:
+ """Utility batching function."""
+ if size <= 0:
+ msg = f"Batch size must be a positive integer, got {size}."
+ raise ValueError(msg)
+ it = iter(iterable)
+ while True:
+ chunk = list(islice(it, size))
+ if not chunk:
+ return
+ yield chunk
+
+
+async def _abatch(size: int, iterable: AsyncIterable[T]) -> AsyncIterator[list[T]]:
+ """Utility batching function."""
+ if size <= 0:
+ msg = f"Batch size must be a positive integer, got {size}."
+ raise ValueError(msg)
+ batch: list[T] = []
+ async for element in iterable:
+ if len(batch) < size:
+ batch.append(element)
+
+ if len(batch) >= size:
+ yield batch
+ batch = []
+
+ if batch:
+ yield batch
+
+
+def _get_source_id_assigner(
+ source_id_key: str | Callable[[Document], str] | None,
+) -> Callable[[Document], str | None]:
+ """Get the source id from the document."""
+ if source_id_key is None:
+ return lambda _doc: None
+ if isinstance(source_id_key, str):
+ return lambda doc: doc.metadata[source_id_key]
+ if callable(source_id_key):
+ return source_id_key
+ msg = (
+ f"source_id_key should be either None, a string or a callable. "
+ f"Got {source_id_key} of type {type(source_id_key)}."
+ )
+ raise ValueError(msg)
+
+
+def _deduplicate_in_order(
+ hashed_documents: Iterable[Document],
+) -> Iterator[Document]:
+ """Deduplicate a list of hashed documents while preserving order."""
+ seen: set[str] = set()
+
+ for hashed_doc in hashed_documents:
+ if hashed_doc.id not in seen:
+ # At this stage, the id is guaranteed to be a string.
+ # Avoiding unnecessary run time checks.
+ seen.add(cast("str", hashed_doc.id))
+ yield hashed_doc
+
+
+class IndexingException(LangChainException):
+ """Raised when an indexing operation fails."""
+
+
+def _calculate_hash(
+ text: str, algorithm: Literal["sha1", "sha256", "sha512", "blake2b"]
+) -> str:
+ """Return a hexadecimal digest of *text* using *algorithm*."""
+ if algorithm == "sha1":
+ # Calculate the SHA-1 hash and return it as a UUID.
+ digest = hashlib.sha1(text.encode("utf-8"), usedforsecurity=False).hexdigest()
+ return str(uuid.uuid5(NAMESPACE_UUID, digest))
+ if algorithm == "blake2b":
+ return hashlib.blake2b(text.encode("utf-8")).hexdigest()
+ if algorithm == "sha256":
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
+ if algorithm == "sha512":
+ return hashlib.sha512(text.encode("utf-8")).hexdigest()
+ msg = f"Unsupported hashing algorithm: {algorithm}"
+ raise ValueError(msg)
+
+
+def _get_document_with_hash(
+ document: Document,
+ *,
+ key_encoder: Callable[[Document], str]
+ | Literal["sha1", "sha256", "sha512", "blake2b"],
+) -> Document:
+ """Calculate a hash of the document, and assign it to the uid.
+
+ When using one of the predefined hashing algorithms, the hash is calculated
+ by hashing the content and the metadata of the document.
+
+ Args:
+ document: Document to hash.
+ key_encoder: Hashing algorithm to use for hashing the document.
+ If not provided, a default encoder using SHA-1 will be used.
+ SHA-1 is not collision-resistant, and a motivated attacker
+ could craft two different texts that hash to the
+ same cache key.
+
+ New applications should use one of the alternative encoders
+ or provide a custom and strong key encoder function to avoid this risk.
+
+ When changing the key encoder, you must change the
+ index as well to avoid duplicated documents in the cache.
+
+ Raises:
+ ValueError: If the metadata cannot be serialized using json.
+
+ Returns:
+ Document with a unique identifier based on the hash of the content and metadata.
+ """
+ metadata: dict[str, Any] = dict(document.metadata or {})
+
+ if callable(key_encoder):
+ # If key_encoder is a callable, we use it to generate the hash.
+ hash_ = key_encoder(document)
+ else:
+ # The hashes are calculated separate for the content and the metadata.
+ content_hash = _calculate_hash(document.page_content, algorithm=key_encoder)
+ try:
+ serialized_meta = json.dumps(metadata, sort_keys=True)
+ except Exception as e:
+ msg = (
+ f"Failed to hash metadata: {e}. "
+ f"Please use a dict that can be serialized using json."
+ )
+ raise ValueError(msg) from e
+ metadata_hash = _calculate_hash(serialized_meta, algorithm=key_encoder)
+ hash_ = _calculate_hash(content_hash + metadata_hash, algorithm=key_encoder)
+
+ return Document(
+ # Assign a unique identifier based on the hash.
+ id=hash_,
+ page_content=document.page_content,
+ metadata=document.metadata,
+ )
+
+
+# This internal abstraction was imported by the langchain package internally, so
+# we keep it here for backwards compatibility.
+class _HashedDocument:
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ """Raise an error if this class is instantiated."""
+ msg = (
+ "_HashedDocument is an internal abstraction that was deprecated in "
+ " langchain-core 0.3.63. This abstraction is marked as private and "
+ " should not have been used directly. If you are seeing this error, please "
+ " update your code appropriately."
+ )
+ raise NotImplementedError(msg)
+
+
+def _delete(
+ vector_store: VectorStore | DocumentIndex,
+ ids: list[str],
+) -> None:
+ """Delete documents from a vector store or document index by their IDs.
+
+ Args:
+ vector_store: The vector store or document index to delete from.
+ ids: List of document IDs to delete.
+
+ Raises:
+ IndexingException: If the delete operation fails.
+ TypeError: If the `vector_store` is neither a `VectorStore` nor a
+ `DocumentIndex`.
+ """
+ if isinstance(vector_store, VectorStore):
+ delete_ok = vector_store.delete(ids)
+ if delete_ok is not None and delete_ok is False:
+ msg = "The delete operation to VectorStore failed."
+ raise IndexingException(msg)
+ elif isinstance(vector_store, DocumentIndex):
+ delete_response = vector_store.delete(ids)
+ if "num_failed" in delete_response and delete_response["num_failed"] > 0:
+ msg = "The delete operation to DocumentIndex failed."
+ raise IndexingException(msg)
+ else:
+ msg = (
+ f"Vectorstore should be either a VectorStore or a DocumentIndex. "
+ f"Got {type(vector_store)}."
+ )
+ raise TypeError(msg)
+
+
+# PUBLIC API
+
+
+class IndexingResult(TypedDict):
+ """Return a detailed a breakdown of the result of the indexing operation."""
+
+ num_added: int
+ """Number of added documents."""
+ num_updated: int
+ """Number of updated documents because they were not up to date."""
+ num_deleted: int
+ """Number of deleted documents."""
+ num_skipped: int
+ """Number of skipped documents because they were already up to date."""
+
+
+def index(
+ docs_source: BaseLoader | Iterable[Document],
+ record_manager: RecordManager,
+ vector_store: VectorStore | DocumentIndex,
+ *,
+ batch_size: int = 100,
+ cleanup: Literal["incremental", "full", "scoped_full"] | None = None,
+ source_id_key: str | Callable[[Document], str] | None = None,
+ cleanup_batch_size: int = 1_000,
+ force_update: bool = False,
+ key_encoder: Literal["sha1", "sha256", "sha512", "blake2b"]
+ | Callable[[Document], str] = "sha1",
+ upsert_kwargs: dict[str, Any] | None = None,
+) -> IndexingResult:
+ """Index data from the loader into the vector store.
+
+ Indexing functionality uses a manager to keep track of which documents
+ are in the vector store.
+
+ This allows us to keep track of which documents were updated, and which
+ documents were deleted, which documents should be skipped.
+
+ For the time being, documents are indexed using their hashes, and users
+ are not able to specify the uid of the document.
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.25"
+
+ Added `scoped_full` cleanup mode.
+
+ !!! warning
+
+ * In full mode, the loader should be returning
+ the entire dataset, and not just a subset of the dataset.
+ Otherwise, the auto_cleanup will remove documents that it is not
+ supposed to.
+ * In incremental mode, if documents associated with a particular
+ source id appear across different batches, the indexing API
+ will do some redundant work. This will still result in the
+ correct end state of the index, but will unfortunately not be
+ 100% efficient. For example, if a given document is split into 15
+ chunks, and we index them using a batch size of 5, we'll have 3 batches
+ all with the same source id. In general, to avoid doing too much
+ redundant work select as big a batch size as possible.
+ * The `scoped_full` mode is suitable if determining an appropriate batch size
+ is challenging or if your data loader cannot return the entire dataset at
+ once. This mode keeps track of source IDs in memory, which should be fine
+ for most use cases. If your dataset is large (10M+ docs), you will likely
+ need to parallelize the indexing process regardless.
+
+ Args:
+ docs_source: Data loader or iterable of documents to index.
+ record_manager: Timestamped set to keep track of which documents were
+ updated.
+ vector_store: `VectorStore` or DocumentIndex to index the documents into.
+ batch_size: Batch size to use when indexing.
+ cleanup: How to handle clean up of documents.
+
+ - incremental: Cleans up all documents that haven't been updated AND
+ that are associated with source IDs that were seen during indexing.
+ Clean up is done continuously during indexing helping to minimize the
+ probability of users seeing duplicated content.
+ - full: Delete all documents that have not been returned by the loader
+ during this run of indexing.
+ Clean up runs after all documents have been indexed.
+ This means that users may see duplicated content during indexing.
+ - scoped_full: Similar to Full, but only deletes all documents
+ that haven't been updated AND that are associated with
+ source IDs that were seen during indexing.
+ - None: Do not delete any documents.
+ source_id_key: Optional key that helps identify the original source
+ of the document.
+ cleanup_batch_size: Batch size to use when cleaning up documents.
+ force_update: Force update documents even if they are present in the
+ record manager. Useful if you are re-indexing with updated embeddings.
+ key_encoder: Hashing algorithm to use for hashing the document content and
+ metadata. Options include "blake2b", "sha256", and "sha512".
+
+ !!! version-added "Added in `langchain-core` 0.3.66"
+
+ key_encoder: Hashing algorithm to use for hashing the document.
+ If not provided, a default encoder using SHA-1 will be used.
+ SHA-1 is not collision-resistant, and a motivated attacker
+ could craft two different texts that hash to the
+ same cache key.
+
+ New applications should use one of the alternative encoders
+ or provide a custom and strong key encoder function to avoid this risk.
+
+ When changing the key encoder, you must change the
+ index as well to avoid duplicated documents in the cache.
+ upsert_kwargs: Additional keyword arguments to pass to the add_documents
+ method of the `VectorStore` or the upsert method of the DocumentIndex.
+ For example, you can use this to specify a custom vector_field:
+ upsert_kwargs={"vector_field": "embedding"}
+ !!! version-added "Added in `langchain-core` 0.3.10"
+
+ Returns:
+ Indexing result which contains information about how many documents
+ were added, updated, deleted, or skipped.
+
+ Raises:
+ ValueError: If cleanup mode is not one of 'incremental', 'full' or None
+ ValueError: If cleanup mode is incremental and source_id_key is None.
+ ValueError: If `VectorStore` does not have
+ "delete" and "add_documents" required methods.
+ ValueError: If source_id_key is not None, but is not a string or callable.
+ TypeError: If `vectorstore` is not a `VectorStore` or a DocumentIndex.
+ AssertionError: If `source_id` is None when cleanup mode is incremental.
+ (should be unreachable code).
+ """
+ # Behavior is deprecated, but we keep it for backwards compatibility.
+ # # Warn only once per process.
+ if key_encoder == "sha1":
+ _warn_about_sha1()
+
+ if cleanup not in {"incremental", "full", "scoped_full", None}:
+ msg = (
+ f"cleanup should be one of 'incremental', 'full', 'scoped_full' or None. "
+ f"Got {cleanup}."
+ )
+ raise ValueError(msg)
+
+ if (cleanup in {"incremental", "scoped_full"}) and source_id_key is None:
+ msg = (
+ "Source id key is required when cleanup mode is incremental or scoped_full."
+ )
+ raise ValueError(msg)
+
+ destination = vector_store # Renaming internally for clarity
+
+ # If it's a vectorstore, let's check if it has the required methods.
+ if isinstance(destination, VectorStore):
+ # Check that the Vectorstore has required methods implemented
+ methods = ["delete", "add_documents"]
+
+ for method in methods:
+ if not hasattr(destination, method):
+ msg = (
+ f"Vectorstore {destination} does not have required method {method}"
+ )
+ raise ValueError(msg)
+
+ if type(destination).delete == VectorStore.delete:
+ # Checking if the VectorStore has overridden the default delete method
+ # implementation which just raises a NotImplementedError
+ msg = "Vectorstore has not implemented the delete method"
+ raise ValueError(msg)
+ elif isinstance(destination, DocumentIndex):
+ pass
+ else:
+ msg = (
+ f"Vectorstore should be either a VectorStore or a DocumentIndex. "
+ f"Got {type(destination)}."
+ )
+ raise TypeError(msg)
+
+ if isinstance(docs_source, BaseLoader):
+ try:
+ doc_iterator = docs_source.lazy_load()
+ except NotImplementedError:
+ doc_iterator = iter(docs_source.load())
+ else:
+ doc_iterator = iter(docs_source)
+
+ source_id_assigner = _get_source_id_assigner(source_id_key)
+
+ # Mark when the update started.
+ index_start_dt = record_manager.get_time()
+ num_added = 0
+ num_skipped = 0
+ num_updated = 0
+ num_deleted = 0
+ scoped_full_cleanup_source_ids: set[str] = set()
+
+ for doc_batch in _batch(batch_size, doc_iterator):
+ # Track original batch size before deduplication
+ original_batch_size = len(doc_batch)
+
+ hashed_docs = list(
+ _deduplicate_in_order(
+ [
+ _get_document_with_hash(doc, key_encoder=key_encoder)
+ for doc in doc_batch
+ ]
+ )
+ )
+ # Count documents removed by within-batch deduplication
+ num_skipped += original_batch_size - len(hashed_docs)
+
+ source_ids: Sequence[str | None] = [
+ source_id_assigner(hashed_doc) for hashed_doc in hashed_docs
+ ]
+
+ if cleanup in {"incremental", "scoped_full"}:
+ # Source IDs are required.
+ for source_id, hashed_doc in zip(source_ids, hashed_docs, strict=False):
+ if source_id is None:
+ msg = (
+ f"Source IDs are required when cleanup mode is "
+ f"incremental or scoped_full. "
+ f"Document that starts with "
+ f"content: {hashed_doc.page_content[:100]} "
+ f"was not assigned as source id."
+ )
+ raise ValueError(msg)
+ if cleanup == "scoped_full":
+ scoped_full_cleanup_source_ids.add(source_id)
+ # Source IDs cannot be None after for loop above.
+ source_ids = cast("Sequence[str]", source_ids)
+
+ exists_batch = record_manager.exists(
+ cast("Sequence[str]", [doc.id for doc in hashed_docs])
+ )
+
+ # Filter out documents that already exist in the record store.
+ uids = []
+ docs_to_index = []
+ uids_to_refresh = []
+ seen_docs: set[str] = set()
+ for hashed_doc, doc_exists in zip(hashed_docs, exists_batch, strict=False):
+ hashed_id = cast("str", hashed_doc.id)
+ if doc_exists:
+ if force_update:
+ seen_docs.add(hashed_id)
+ else:
+ uids_to_refresh.append(hashed_id)
+ continue
+ uids.append(hashed_id)
+ docs_to_index.append(hashed_doc)
+
+ # Update refresh timestamp
+ if uids_to_refresh:
+ record_manager.update(uids_to_refresh, time_at_least=index_start_dt)
+ num_skipped += len(uids_to_refresh)
+
+ # Be pessimistic and assume that all vector store write will fail.
+ # First write to vector store
+ if docs_to_index:
+ if isinstance(destination, VectorStore):
+ destination.add_documents(
+ docs_to_index,
+ ids=uids,
+ batch_size=batch_size,
+ **(upsert_kwargs or {}),
+ )
+ elif isinstance(destination, DocumentIndex):
+ destination.upsert(
+ docs_to_index,
+ **(upsert_kwargs or {}),
+ )
+
+ num_added += len(docs_to_index) - len(seen_docs)
+ num_updated += len(seen_docs)
+
+ # And only then update the record store.
+ # Update ALL records, even if they already exist since we want to refresh
+ # their timestamp.
+ record_manager.update(
+ cast("Sequence[str]", [doc.id for doc in hashed_docs]),
+ group_ids=source_ids,
+ time_at_least=index_start_dt,
+ )
+
+ # If source IDs are provided, we can do the deletion incrementally!
+ if cleanup == "incremental":
+ # Get the uids of the documents that were not returned by the loader.
+ # mypy isn't good enough to determine that source IDs cannot be None
+ # here due to a check that's happening above, so we check again.
+ for source_id in source_ids:
+ if source_id is None:
+ msg = (
+ "source_id cannot be None at this point. "
+ "Reached unreachable code."
+ )
+ raise AssertionError(msg)
+
+ source_ids_ = cast("Sequence[str]", source_ids)
+
+ while uids_to_delete := record_manager.list_keys(
+ group_ids=source_ids_, before=index_start_dt, limit=cleanup_batch_size
+ ):
+ # Then delete from vector store.
+ _delete(destination, uids_to_delete)
+ # First delete from record store.
+ record_manager.delete_keys(uids_to_delete)
+ num_deleted += len(uids_to_delete)
+
+ if cleanup == "full" or (
+ cleanup == "scoped_full" and scoped_full_cleanup_source_ids
+ ):
+ delete_group_ids: Sequence[str] | None = None
+ if cleanup == "scoped_full":
+ delete_group_ids = list(scoped_full_cleanup_source_ids)
+ while uids_to_delete := record_manager.list_keys(
+ group_ids=delete_group_ids, before=index_start_dt, limit=cleanup_batch_size
+ ):
+ # First delete from record store.
+ _delete(destination, uids_to_delete)
+ # Then delete from record manager.
+ record_manager.delete_keys(uids_to_delete)
+ num_deleted += len(uids_to_delete)
+
+ return {
+ "num_added": num_added,
+ "num_updated": num_updated,
+ "num_skipped": num_skipped,
+ "num_deleted": num_deleted,
+ }
+
+
+# Define an asynchronous generator function
+async def _to_async_iterator(iterator: Iterable[T]) -> AsyncIterator[T]:
+ """Convert an iterable to an async iterator."""
+ for item in iterator:
+ yield item
+
+
+async def _adelete(
+ vector_store: VectorStore | DocumentIndex,
+ ids: list[str],
+) -> None:
+ if isinstance(vector_store, VectorStore):
+ delete_ok = await vector_store.adelete(ids)
+ if delete_ok is not None and delete_ok is False:
+ msg = "The delete operation to VectorStore failed."
+ raise IndexingException(msg)
+ elif isinstance(vector_store, DocumentIndex):
+ delete_response = await vector_store.adelete(ids)
+ if "num_failed" in delete_response and delete_response["num_failed"] > 0:
+ msg = "The delete operation to DocumentIndex failed."
+ raise IndexingException(msg)
+ else:
+ msg = (
+ f"Vectorstore should be either a VectorStore or a DocumentIndex. "
+ f"Got {type(vector_store)}."
+ )
+ raise TypeError(msg)
+
+
+async def aindex(
+ docs_source: BaseLoader | Iterable[Document] | AsyncIterator[Document],
+ record_manager: RecordManager,
+ vector_store: VectorStore | DocumentIndex,
+ *,
+ batch_size: int = 100,
+ cleanup: Literal["incremental", "full", "scoped_full"] | None = None,
+ source_id_key: str | Callable[[Document], str] | None = None,
+ cleanup_batch_size: int = 1_000,
+ force_update: bool = False,
+ key_encoder: Literal["sha1", "sha256", "sha512", "blake2b"]
+ | Callable[[Document], str] = "sha1",
+ upsert_kwargs: dict[str, Any] | None = None,
+) -> IndexingResult:
+ """Async index data from the loader into the vector store.
+
+ Indexing functionality uses a manager to keep track of which documents
+ are in the vector store.
+
+ This allows us to keep track of which documents were updated, and which
+ documents were deleted, which documents should be skipped.
+
+ For the time being, documents are indexed using their hashes, and users
+ are not able to specify the uid of the document.
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.25"
+
+ Added `scoped_full` cleanup mode.
+
+ !!! warning
+
+ * In full mode, the loader should be returning
+ the entire dataset, and not just a subset of the dataset.
+ Otherwise, the auto_cleanup will remove documents that it is not
+ supposed to.
+ * In incremental mode, if documents associated with a particular
+ source id appear across different batches, the indexing API
+ will do some redundant work. This will still result in the
+ correct end state of the index, but will unfortunately not be
+ 100% efficient. For example, if a given document is split into 15
+ chunks, and we index them using a batch size of 5, we'll have 3 batches
+ all with the same source id. In general, to avoid doing too much
+ redundant work select as big a batch size as possible.
+ * The `scoped_full` mode is suitable if determining an appropriate batch size
+ is challenging or if your data loader cannot return the entire dataset at
+ once. This mode keeps track of source IDs in memory, which should be fine
+ for most use cases. If your dataset is large (10M+ docs), you will likely
+ need to parallelize the indexing process regardless.
+
+ Args:
+ docs_source: Data loader or iterable of documents to index.
+ record_manager: Timestamped set to keep track of which documents were
+ updated.
+ vector_store: `VectorStore` or DocumentIndex to index the documents into.
+ batch_size: Batch size to use when indexing.
+ cleanup: How to handle clean up of documents.
+
+ - incremental: Cleans up all documents that haven't been updated AND
+ that are associated with source IDs that were seen during indexing.
+ Clean up is done continuously during indexing helping to minimize the
+ probability of users seeing duplicated content.
+ - full: Delete all documents that have not been returned by the loader
+ during this run of indexing.
+ Clean up runs after all documents have been indexed.
+ This means that users may see duplicated content during indexing.
+ - scoped_full: Similar to Full, but only deletes all documents
+ that haven't been updated AND that are associated with
+ source IDs that were seen during indexing.
+ - None: Do not delete any documents.
+ source_id_key: Optional key that helps identify the original source
+ of the document.
+ cleanup_batch_size: Batch size to use when cleaning up documents.
+ force_update: Force update documents even if they are present in the
+ record manager. Useful if you are re-indexing with updated embeddings.
+ key_encoder: Hashing algorithm to use for hashing the document content and
+ metadata. Options include "blake2b", "sha256", and "sha512".
+
+ !!! version-added "Added in `langchain-core` 0.3.66"
+
+ key_encoder: Hashing algorithm to use for hashing the document.
+ If not provided, a default encoder using SHA-1 will be used.
+ SHA-1 is not collision-resistant, and a motivated attacker
+ could craft two different texts that hash to the
+ same cache key.
+
+ New applications should use one of the alternative encoders
+ or provide a custom and strong key encoder function to avoid this risk.
+
+ When changing the key encoder, you must change the
+ index as well to avoid duplicated documents in the cache.
+ upsert_kwargs: Additional keyword arguments to pass to the add_documents
+ method of the `VectorStore` or the upsert method of the DocumentIndex.
+ For example, you can use this to specify a custom vector_field:
+ upsert_kwargs={"vector_field": "embedding"}
+ !!! version-added "Added in `langchain-core` 0.3.10"
+
+ Returns:
+ Indexing result which contains information about how many documents
+ were added, updated, deleted, or skipped.
+
+ Raises:
+ ValueError: If cleanup mode is not one of 'incremental', 'full' or None
+ ValueError: If cleanup mode is incremental and source_id_key is None.
+ ValueError: If `VectorStore` does not have
+ "adelete" and "aadd_documents" required methods.
+ ValueError: If source_id_key is not None, but is not a string or callable.
+ TypeError: If `vector_store` is not a `VectorStore` or DocumentIndex.
+ AssertionError: If `source_id_key` is None when cleanup mode is
+ incremental or `scoped_full` (should be unreachable).
+ """
+ # Behavior is deprecated, but we keep it for backwards compatibility.
+ # # Warn only once per process.
+ if key_encoder == "sha1":
+ _warn_about_sha1()
+
+ if cleanup not in {"incremental", "full", "scoped_full", None}:
+ msg = (
+ f"cleanup should be one of 'incremental', 'full', 'scoped_full' or None. "
+ f"Got {cleanup}."
+ )
+ raise ValueError(msg)
+
+ if (cleanup in {"incremental", "scoped_full"}) and source_id_key is None:
+ msg = (
+ "Source id key is required when cleanup mode is incremental or scoped_full."
+ )
+ raise ValueError(msg)
+
+ destination = vector_store # Renaming internally for clarity
+
+ # If it's a vectorstore, let's check if it has the required methods.
+ if isinstance(destination, VectorStore):
+ # Check that the Vectorstore has required methods implemented
+ # Check that the Vectorstore has required methods implemented
+ methods = ["adelete", "aadd_documents"]
+
+ for method in methods:
+ if not hasattr(destination, method):
+ msg = (
+ f"Vectorstore {destination} does not have required method {method}"
+ )
+ raise ValueError(msg)
+
+ if (
+ type(destination).adelete == VectorStore.adelete
+ and type(destination).delete == VectorStore.delete
+ ):
+ # Checking if the VectorStore has overridden the default adelete or delete
+ # methods implementation which just raises a NotImplementedError
+ msg = "Vectorstore has not implemented the adelete or delete method"
+ raise ValueError(msg)
+ elif isinstance(destination, DocumentIndex):
+ pass
+ else:
+ msg = (
+ f"Vectorstore should be either a VectorStore or a DocumentIndex. "
+ f"Got {type(destination)}."
+ )
+ raise TypeError(msg)
+ async_doc_iterator: AsyncIterator[Document]
+ if isinstance(docs_source, BaseLoader):
+ try:
+ async_doc_iterator = docs_source.alazy_load()
+ except NotImplementedError:
+ # Exception triggered when neither lazy_load nor alazy_load are implemented.
+ # * The default implementation of alazy_load uses lazy_load.
+ # * The default implementation of lazy_load raises NotImplementedError.
+ # In such a case, we use the load method and convert it to an async
+ # iterator.
+ async_doc_iterator = _to_async_iterator(docs_source.load())
+ elif hasattr(docs_source, "__aiter__"):
+ async_doc_iterator = docs_source # type: ignore[assignment]
+ else:
+ async_doc_iterator = _to_async_iterator(docs_source)
+
+ source_id_assigner = _get_source_id_assigner(source_id_key)
+
+ # Mark when the update started.
+ index_start_dt = await record_manager.aget_time()
+ num_added = 0
+ num_skipped = 0
+ num_updated = 0
+ num_deleted = 0
+ scoped_full_cleanup_source_ids: set[str] = set()
+
+ async for doc_batch in _abatch(batch_size, async_doc_iterator):
+ # Track original batch size before deduplication
+ original_batch_size = len(doc_batch)
+
+ hashed_docs = list(
+ _deduplicate_in_order(
+ [
+ _get_document_with_hash(doc, key_encoder=key_encoder)
+ for doc in doc_batch
+ ]
+ )
+ )
+ # Count documents removed by within-batch deduplication
+ num_skipped += original_batch_size - len(hashed_docs)
+
+ source_ids: Sequence[str | None] = [
+ source_id_assigner(doc) for doc in hashed_docs
+ ]
+
+ if cleanup in {"incremental", "scoped_full"}:
+ # If the cleanup mode is incremental, source IDs are required.
+ for source_id, hashed_doc in zip(source_ids, hashed_docs, strict=False):
+ if source_id is None:
+ msg = (
+ f"Source IDs are required when cleanup mode is "
+ f"incremental or scoped_full. "
+ f"Document that starts with "
+ f"content: {hashed_doc.page_content[:100]} "
+ f"was not assigned as source id."
+ )
+ raise ValueError(msg)
+ if cleanup == "scoped_full":
+ scoped_full_cleanup_source_ids.add(source_id)
+ # Source IDs cannot be None after for loop above.
+ source_ids = cast("Sequence[str]", source_ids)
+
+ exists_batch = await record_manager.aexists(
+ cast("Sequence[str]", [doc.id for doc in hashed_docs])
+ )
+
+ # Filter out documents that already exist in the record store.
+ uids: list[str] = []
+ docs_to_index: list[Document] = []
+ uids_to_refresh = []
+ seen_docs: set[str] = set()
+ for hashed_doc, doc_exists in zip(hashed_docs, exists_batch, strict=False):
+ hashed_id = cast("str", hashed_doc.id)
+ if doc_exists:
+ if force_update:
+ seen_docs.add(hashed_id)
+ else:
+ uids_to_refresh.append(hashed_id)
+ continue
+ uids.append(hashed_id)
+ docs_to_index.append(hashed_doc)
+
+ if uids_to_refresh:
+ # Must be updated to refresh timestamp.
+ await record_manager.aupdate(uids_to_refresh, time_at_least=index_start_dt)
+ num_skipped += len(uids_to_refresh)
+
+ # Be pessimistic and assume that all vector store write will fail.
+ # First write to vector store
+ if docs_to_index:
+ if isinstance(destination, VectorStore):
+ await destination.aadd_documents(
+ docs_to_index,
+ ids=uids,
+ batch_size=batch_size,
+ **(upsert_kwargs or {}),
+ )
+ elif isinstance(destination, DocumentIndex):
+ await destination.aupsert(
+ docs_to_index,
+ **(upsert_kwargs or {}),
+ )
+ num_added += len(docs_to_index) - len(seen_docs)
+ num_updated += len(seen_docs)
+
+ # And only then update the record store.
+ # Update ALL records, even if they already exist since we want to refresh
+ # their timestamp.
+ await record_manager.aupdate(
+ cast("Sequence[str]", [doc.id for doc in hashed_docs]),
+ group_ids=source_ids,
+ time_at_least=index_start_dt,
+ )
+
+ # If source IDs are provided, we can do the deletion incrementally!
+
+ if cleanup == "incremental":
+ # Get the uids of the documents that were not returned by the loader.
+
+ # mypy isn't good enough to determine that source IDs cannot be None
+ # here due to a check that's happening above, so we check again.
+ for source_id in source_ids:
+ if source_id is None:
+ msg = (
+ "source_id cannot be None at this point. "
+ "Reached unreachable code."
+ )
+ raise AssertionError(msg)
+
+ source_ids_ = cast("Sequence[str]", source_ids)
+
+ while uids_to_delete := await record_manager.alist_keys(
+ group_ids=source_ids_, before=index_start_dt, limit=cleanup_batch_size
+ ):
+ # Then delete from vector store.
+ await _adelete(destination, uids_to_delete)
+ # First delete from record store.
+ await record_manager.adelete_keys(uids_to_delete)
+ num_deleted += len(uids_to_delete)
+
+ if cleanup == "full" or (
+ cleanup == "scoped_full" and scoped_full_cleanup_source_ids
+ ):
+ delete_group_ids: Sequence[str] | None = None
+ if cleanup == "scoped_full":
+ delete_group_ids = list(scoped_full_cleanup_source_ids)
+ while uids_to_delete := await record_manager.alist_keys(
+ group_ids=delete_group_ids, before=index_start_dt, limit=cleanup_batch_size
+ ):
+ # First delete from record store.
+ await _adelete(destination, uids_to_delete)
+ # Then delete from record manager.
+ await record_manager.adelete_keys(uids_to_delete)
+ num_deleted += len(uids_to_delete)
+
+ return {
+ "num_added": num_added,
+ "num_updated": num_updated,
+ "num_skipped": num_skipped,
+ "num_deleted": num_deleted,
+ }
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8a891ddf9ee400e1154e8c84a4eb76cf8b7911d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/base.py
@@ -0,0 +1,661 @@
+"""Base classes for indexing."""
+
+from __future__ import annotations
+
+import abc
+import time
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any, TypedDict
+
+from typing_extensions import override
+
+from langchain_core._api import beta
+from langchain_core.retrievers import BaseRetriever
+from langchain_core.runnables import run_in_executor
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from langchain_core.documents import Document
+
+
+class RecordManager(ABC):
+ """Abstract base class representing the interface for a record manager.
+
+ The record manager abstraction is used by the langchain indexing API.
+
+ The record manager keeps track of which documents have been
+ written into a `VectorStore` and when they were written.
+
+ The indexing API computes hashes for each document and stores the hash
+ together with the write time and the source id in the record manager.
+
+ On subsequent indexing runs, the indexing API can check the record manager
+ to determine which documents have already been indexed and which have not.
+
+ This allows the indexing API to avoid re-indexing documents that have
+ already been indexed, and to only index new documents.
+
+ The main benefit of this abstraction is that it works across many vectorstores.
+ To be supported, a `VectorStore` needs to only support the ability to add and
+ delete documents by ID. Using the record manager, the indexing API will
+ be able to delete outdated documents and avoid redundant indexing of documents
+ that have already been indexed.
+
+ The main constraints of this abstraction are:
+
+ 1. It relies on the time-stamps to determine which documents have been
+ indexed and which have not. This means that the time-stamps must be
+ monotonically increasing. The timestamp should be the timestamp
+ as measured by the server to minimize issues.
+ 2. The record manager is currently implemented separately from the
+ vectorstore, which means that the overall system becomes distributed
+ and may create issues with consistency. For example, writing to
+ record manager succeeds, but corresponding writing to `VectorStore` fails.
+ """
+
+ def __init__(
+ self,
+ namespace: str,
+ ) -> None:
+ """Initialize the record manager.
+
+ Args:
+ namespace: The namespace for the record manager.
+ """
+ self.namespace = namespace
+
+ @abstractmethod
+ def create_schema(self) -> None:
+ """Create the database schema for the record manager."""
+
+ @abstractmethod
+ async def acreate_schema(self) -> None:
+ """Asynchronously create the database schema for the record manager."""
+
+ @abstractmethod
+ def get_time(self) -> float:
+ """Get the current server time as a high resolution timestamp!
+
+ It's important to get this from the server to ensure a monotonic clock,
+ otherwise there may be data loss when cleaning up old documents!
+
+ Returns:
+ The current server time as a float timestamp.
+ """
+
+ @abstractmethod
+ async def aget_time(self) -> float:
+ """Asynchronously get the current server time as a high resolution timestamp.
+
+ It's important to get this from the server to ensure a monotonic clock,
+ otherwise there may be data loss when cleaning up old documents!
+
+ Returns:
+ The current server time as a float timestamp.
+ """
+
+ @abstractmethod
+ def update(
+ self,
+ keys: Sequence[str],
+ *,
+ group_ids: Sequence[str | None] | None = None,
+ time_at_least: float | None = None,
+ ) -> None:
+ """Upsert records into the database.
+
+ Args:
+ keys: A list of record keys to upsert.
+ group_ids: A list of group IDs corresponding to the keys.
+ time_at_least: Optional timestamp. Implementation can use this
+ to optionally verify that the timestamp IS at least this time
+ in the system that stores the data.
+
+ e.g., use to validate that the time in the postgres database
+ is equal to or larger than the given timestamp, if not
+ raise an error.
+
+ This is meant to help prevent time-drift issues since
+ time may not be monotonically increasing!
+
+ Raises:
+ ValueError: If the length of keys doesn't match the length of group_ids.
+ """
+
+ @abstractmethod
+ async def aupdate(
+ self,
+ keys: Sequence[str],
+ *,
+ group_ids: Sequence[str | None] | None = None,
+ time_at_least: float | None = None,
+ ) -> None:
+ """Asynchronously upsert records into the database.
+
+ Args:
+ keys: A list of record keys to upsert.
+ group_ids: A list of group IDs corresponding to the keys.
+ time_at_least: Optional timestamp. Implementation can use this
+ to optionally verify that the timestamp IS at least this time
+ in the system that stores the data.
+
+ e.g., use to validate that the time in the postgres database
+ is equal to or larger than the given timestamp, if not
+ raise an error.
+
+ This is meant to help prevent time-drift issues since
+ time may not be monotonically increasing!
+
+ Raises:
+ ValueError: If the length of keys doesn't match the length of group_ids.
+ """
+
+ @abstractmethod
+ def exists(self, keys: Sequence[str]) -> list[bool]:
+ """Check if the provided keys exist in the database.
+
+ Args:
+ keys: A list of keys to check.
+
+ Returns:
+ A list of boolean values indicating the existence of each key.
+ """
+
+ @abstractmethod
+ async def aexists(self, keys: Sequence[str]) -> list[bool]:
+ """Asynchronously check if the provided keys exist in the database.
+
+ Args:
+ keys: A list of keys to check.
+
+ Returns:
+ A list of boolean values indicating the existence of each key.
+ """
+
+ @abstractmethod
+ def list_keys(
+ self,
+ *,
+ before: float | None = None,
+ after: float | None = None,
+ group_ids: Sequence[str] | None = None,
+ limit: int | None = None,
+ ) -> list[str]:
+ """List records in the database based on the provided filters.
+
+ Args:
+ before: Filter to list records updated before this time.
+ after: Filter to list records updated after this time.
+ group_ids: Filter to list records with specific group IDs.
+ limit: optional limit on the number of records to return.
+
+ Returns:
+ A list of keys for the matching records.
+ """
+
+ @abstractmethod
+ async def alist_keys(
+ self,
+ *,
+ before: float | None = None,
+ after: float | None = None,
+ group_ids: Sequence[str] | None = None,
+ limit: int | None = None,
+ ) -> list[str]:
+ """Asynchronously list records in the database based on the provided filters.
+
+ Args:
+ before: Filter to list records updated before this time.
+ after: Filter to list records updated after this time.
+ group_ids: Filter to list records with specific group IDs.
+ limit: optional limit on the number of records to return.
+
+ Returns:
+ A list of keys for the matching records.
+ """
+
+ @abstractmethod
+ def delete_keys(self, keys: Sequence[str]) -> None:
+ """Delete specified records from the database.
+
+ Args:
+ keys: A list of keys to delete.
+ """
+
+ @abstractmethod
+ async def adelete_keys(self, keys: Sequence[str]) -> None:
+ """Asynchronously delete specified records from the database.
+
+ Args:
+ keys: A list of keys to delete.
+ """
+
+
+class _Record(TypedDict):
+ group_id: str | None
+ updated_at: float
+
+
+class InMemoryRecordManager(RecordManager):
+ """An in-memory record manager for testing purposes."""
+
+ def __init__(self, namespace: str) -> None:
+ """Initialize the in-memory record manager.
+
+ Args:
+ namespace: The namespace for the record manager.
+ """
+ super().__init__(namespace)
+ # Each key points to a dictionary
+ # of {'group_id': group_id, 'updated_at': timestamp}
+ self.records: dict[str, _Record] = {}
+ self.namespace = namespace
+
+ def create_schema(self) -> None:
+ """In-memory schema creation is simply ensuring the structure is initialized."""
+
+ async def acreate_schema(self) -> None:
+ """In-memory schema creation is simply ensuring the structure is initialized."""
+
+ @override
+ def get_time(self) -> float:
+ return time.time()
+
+ @override
+ async def aget_time(self) -> float:
+ return self.get_time()
+
+ def update(
+ self,
+ keys: Sequence[str],
+ *,
+ group_ids: Sequence[str | None] | None = None,
+ time_at_least: float | None = None,
+ ) -> None:
+ """Upsert records into the database.
+
+ Args:
+ keys: A list of record keys to upsert.
+ group_ids: A list of group IDs corresponding to the keys.
+
+ time_at_least: Optional timestamp. Implementation can use this
+ to optionally verify that the timestamp IS at least this time
+ in the system that stores.
+ E.g., use to validate that the time in the postgres database
+ is equal to or larger than the given timestamp, if not
+ raise an error.
+ This is meant to help prevent time-drift issues since
+ time may not be monotonically increasing!
+
+ Raises:
+ ValueError: If the length of keys doesn't match the length of group
+ ids.
+ ValueError: If time_at_least is in the future.
+ """
+ if group_ids and len(keys) != len(group_ids):
+ msg = "Length of keys must match length of group_ids"
+ raise ValueError(msg)
+ for index, key in enumerate(keys):
+ group_id = group_ids[index] if group_ids else None
+ if time_at_least and time_at_least > self.get_time():
+ msg = "time_at_least must be in the past"
+ raise ValueError(msg)
+ self.records[key] = {"group_id": group_id, "updated_at": self.get_time()}
+
+ async def aupdate(
+ self,
+ keys: Sequence[str],
+ *,
+ group_ids: Sequence[str | None] | None = None,
+ time_at_least: float | None = None,
+ ) -> None:
+ """Async upsert records into the database.
+
+ Args:
+ keys: A list of record keys to upsert.
+ group_ids: A list of group IDs corresponding to the keys.
+
+ time_at_least: Optional timestamp. Implementation can use this
+ to optionally verify that the timestamp IS at least this time
+ in the system that stores.
+ E.g., use to validate that the time in the postgres database
+ is equal to or larger than the given timestamp, if not
+ raise an error.
+ This is meant to help prevent time-drift issues since
+ time may not be monotonically increasing!
+ """
+ self.update(keys, group_ids=group_ids, time_at_least=time_at_least)
+
+ def exists(self, keys: Sequence[str]) -> list[bool]:
+ """Check if the provided keys exist in the database.
+
+ Args:
+ keys: A list of keys to check.
+
+ Returns:
+ A list of boolean values indicating the existence of each key.
+ """
+ return [key in self.records for key in keys]
+
+ async def aexists(self, keys: Sequence[str]) -> list[bool]:
+ """Async check if the provided keys exist in the database.
+
+ Args:
+ keys: A list of keys to check.
+
+ Returns:
+ A list of boolean values indicating the existence of each key.
+ """
+ return self.exists(keys)
+
+ def list_keys(
+ self,
+ *,
+ before: float | None = None,
+ after: float | None = None,
+ group_ids: Sequence[str] | None = None,
+ limit: int | None = None,
+ ) -> list[str]:
+ """List records in the database based on the provided filters.
+
+ Args:
+ before: Filter to list records updated before this time.
+
+ after: Filter to list records updated after this time.
+
+ group_ids: Filter to list records with specific group IDs.
+
+ limit: optional limit on the number of records to return.
+
+
+ Returns:
+ A list of keys for the matching records.
+ """
+ result = []
+ for key, data in self.records.items():
+ if before and data["updated_at"] >= before:
+ continue
+ if after and data["updated_at"] <= after:
+ continue
+ if group_ids and data["group_id"] not in group_ids:
+ continue
+ result.append(key)
+ if limit:
+ return result[:limit]
+ return result
+
+ async def alist_keys(
+ self,
+ *,
+ before: float | None = None,
+ after: float | None = None,
+ group_ids: Sequence[str] | None = None,
+ limit: int | None = None,
+ ) -> list[str]:
+ """Async list records in the database based on the provided filters.
+
+ Args:
+ before: Filter to list records updated before this time.
+
+ after: Filter to list records updated after this time.
+
+ group_ids: Filter to list records with specific group IDs.
+
+ limit: optional limit on the number of records to return.
+
+
+ Returns:
+ A list of keys for the matching records.
+ """
+ return self.list_keys(
+ before=before, after=after, group_ids=group_ids, limit=limit
+ )
+
+ def delete_keys(self, keys: Sequence[str]) -> None:
+ """Delete specified records from the database.
+
+ Args:
+ keys: A list of keys to delete.
+ """
+ for key in keys:
+ if key in self.records:
+ del self.records[key]
+
+ async def adelete_keys(self, keys: Sequence[str]) -> None:
+ """Async delete specified records from the database.
+
+ Args:
+ keys: A list of keys to delete.
+ """
+ self.delete_keys(keys)
+
+
+class UpsertResponse(TypedDict):
+ """A generic response for upsert operations.
+
+ The upsert response will be used by abstractions that implement an upsert
+ operation for content that can be upserted by ID.
+
+ Upsert APIs that accept inputs with IDs and generate IDs internally
+ will return a response that includes the IDs that succeeded and the IDs
+ that failed.
+
+ If there are no failures, the failed list will be empty, and the order
+ of the IDs in the succeeded list will match the order of the input documents.
+
+ If there are failures, the response becomes ill defined, and a user of the API
+ cannot determine which generated ID corresponds to which input document.
+
+ It is recommended for users explicitly attach the IDs to the items being
+ indexed to avoid this issue.
+ """
+
+ succeeded: list[str]
+ """The IDs that were successfully indexed."""
+ failed: list[str]
+ """The IDs that failed to index."""
+
+
+class DeleteResponse(TypedDict, total=False):
+ """A generic response for delete operation.
+
+ The fields in this response are optional and whether the `VectorStore`
+ returns them or not is up to the implementation.
+ """
+
+ num_deleted: int
+ """The number of items that were successfully deleted.
+
+ If returned, this should only include *actual* deletions.
+
+ If the ID did not exist to begin with,
+ it should not be included in this count.
+ """
+
+ succeeded: Sequence[str]
+ """The IDs that were successfully deleted.
+
+ If returned, this should only include *actual* deletions.
+
+ If the ID did not exist to begin with,
+ it should not be included in this list.
+ """
+
+ failed: Sequence[str]
+ """The IDs that failed to be deleted.
+
+ !!! warning
+ Deleting an ID that does not exist is **NOT** considered a failure.
+ """
+
+ num_failed: int
+ """The number of items that failed to be deleted."""
+
+
+@beta(message="Added in 0.2.29. The abstraction is subject to change.")
+class DocumentIndex(BaseRetriever):
+ """A document retriever that supports indexing operations.
+
+ This indexing interface is designed to be a generic abstraction for storing and
+ querying documents that has an ID and metadata associated with it.
+
+ The interface is designed to be agnostic to the underlying implementation of the
+ indexing system.
+
+ The interface is designed to support the following operations:
+
+ 1. Storing document in the index.
+ 2. Fetching document by ID.
+ 3. Searching for document using a query.
+ """
+
+ @abc.abstractmethod
+ def upsert(self, items: Sequence[Document], /, **kwargs: Any) -> UpsertResponse:
+ """Upsert documents into the index.
+
+ The upsert functionality should utilize the ID field of the content object
+ if it is provided. If the ID is not provided, the upsert method is free
+ to generate an ID for the content.
+
+ When an ID is specified and the content already exists in the `VectorStore`,
+ the upsert method should update the content with the new data. If the content
+ does not exist, the upsert method should add the item to the `VectorStore`.
+
+ Args:
+ items: Sequence of documents to add to the `VectorStore`.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ A response object that contains the list of IDs that were
+ successfully added or updated in the `VectorStore` and the list of IDs that
+ failed to be added or updated.
+ """
+
+ async def aupsert(
+ self, items: Sequence[Document], /, **kwargs: Any
+ ) -> UpsertResponse:
+ """Add or update documents in the `VectorStore`. Async version of `upsert`.
+
+ The upsert functionality should utilize the ID field of the item
+ if it is provided. If the ID is not provided, the upsert method is free
+ to generate an ID for the item.
+
+ When an ID is specified and the item already exists in the `VectorStore`,
+ the upsert method should update the item with the new data. If the item
+ does not exist, the upsert method should add the item to the `VectorStore`.
+
+ Args:
+ items: Sequence of documents to add to the `VectorStore`.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ A response object that contains the list of IDs that were
+ successfully added or updated in the `VectorStore` and the list of IDs that
+ failed to be added or updated.
+ """
+ return await run_in_executor(
+ None,
+ self.upsert,
+ items,
+ **kwargs,
+ )
+
+ @abc.abstractmethod
+ def delete(self, ids: list[str] | None = None, **kwargs: Any) -> DeleteResponse:
+ """Delete by IDs or other criteria.
+
+ Calling delete without any input parameters should raise a ValueError!
+
+ Args:
+ ids: List of IDs to delete.
+ **kwargs: Additional keyword arguments. This is up to the implementation.
+ For example, can include an option to delete the entire index,
+ or else issue a non-blocking delete etc.
+
+ Returns:
+ A response object that contains the list of IDs that were
+ successfully deleted and the list of IDs that failed to be deleted.
+ """
+
+ async def adelete(
+ self, ids: list[str] | None = None, **kwargs: Any
+ ) -> DeleteResponse:
+ """Delete by IDs or other criteria. Async variant.
+
+ Calling adelete without any input parameters should raise a ValueError!
+
+ Args:
+ ids: List of IDs to delete.
+ **kwargs: Additional keyword arguments. This is up to the implementation.
+ For example, can include an option to delete the entire index.
+
+ Returns:
+ A response object that contains the list of IDs that were
+ successfully deleted and the list of IDs that failed to be deleted.
+ """
+ return await run_in_executor(
+ None,
+ self.delete,
+ ids,
+ **kwargs,
+ )
+
+ @abc.abstractmethod
+ def get(
+ self,
+ ids: Sequence[str],
+ /,
+ **kwargs: Any,
+ ) -> list[Document]:
+ """Get documents by id.
+
+ Fewer documents may be returned than requested if some IDs are not found or
+ if there are duplicated IDs.
+
+ Users should not assume that the order of the returned documents matches
+ the order of the input IDs. Instead, users should rely on the ID field of the
+ returned documents.
+
+ This method should **NOT** raise exceptions if no documents are found for
+ some IDs.
+
+ Args:
+ ids: List of IDs to get.
+ **kwargs: Additional keyword arguments. These are up to the implementation.
+
+ Returns:
+ List of documents that were found.
+ """
+
+ async def aget(
+ self,
+ ids: Sequence[str],
+ /,
+ **kwargs: Any,
+ ) -> list[Document]:
+ """Get documents by id.
+
+ Fewer documents may be returned than requested if some IDs are not found or
+ if there are duplicated IDs.
+
+ Users should not assume that the order of the returned documents matches
+ the order of the input IDs. Instead, users should rely on the ID field of the
+ returned documents.
+
+ This method should **NOT** raise exceptions if no documents are found for
+ some IDs.
+
+ Args:
+ ids: List of IDs to get.
+ **kwargs: Additional keyword arguments. These are up to the implementation.
+
+ Returns:
+ List of documents that were found.
+ """
+ return await run_in_executor(
+ None,
+ self.get,
+ ids,
+ **kwargs,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/in_memory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/in_memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae9cf84088dcbc5384de8149409b79d5556b3c0f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/indexing/in_memory.py
@@ -0,0 +1,104 @@
+"""In memory document index."""
+
+import operator
+import uuid
+from collections.abc import Sequence
+from typing import Any, cast
+
+from pydantic import Field
+from typing_extensions import override
+
+from langchain_core._api import beta
+from langchain_core.callbacks import CallbackManagerForRetrieverRun
+from langchain_core.documents import Document
+from langchain_core.indexing import UpsertResponse
+from langchain_core.indexing.base import DeleteResponse, DocumentIndex
+
+
+@beta(message="Introduced in version 0.2.29. Underlying abstraction subject to change.")
+class InMemoryDocumentIndex(DocumentIndex):
+ """In memory document index.
+
+ This is an in-memory document index that stores documents in a dictionary.
+
+ It provides a simple search API that returns documents by the number of
+ counts the given query appears in the document.
+ """
+
+ store: dict[str, Document] = Field(default_factory=dict)
+ top_k: int = 4
+
+ @override
+ def upsert(self, items: Sequence[Document], /, **kwargs: Any) -> UpsertResponse:
+ """Upsert documents into the index.
+
+ Args:
+ items: Sequence of documents to add to the index.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ A response object that contains the list of IDs that were
+ successfully added or updated in the index and the list of IDs that
+ failed to be added or updated.
+ """
+ ok_ids = []
+
+ for item in items:
+ if item.id is None:
+ id_ = str(uuid.uuid4())
+ item_ = item.model_copy()
+ item_.id = id_
+ else:
+ item_ = item
+ id_ = item.id
+
+ self.store[id_] = item_
+ ok_ids.append(cast("str", item_.id))
+
+ return UpsertResponse(succeeded=ok_ids, failed=[])
+
+ @override
+ def delete(self, ids: list[str] | None = None, **kwargs: Any) -> DeleteResponse:
+ """Delete by IDs.
+
+ Args:
+ ids: List of IDs to delete.
+
+ Raises:
+ ValueError: If IDs is None.
+
+ Returns:
+ A response object that contains the list of IDs that were successfully
+ deleted and the list of IDs that failed to be deleted.
+ """
+ if ids is None:
+ msg = "IDs must be provided for deletion"
+ raise ValueError(msg)
+
+ ok_ids = []
+
+ for id_ in ids:
+ if id_ in self.store:
+ del self.store[id_]
+ ok_ids.append(id_)
+
+ return DeleteResponse(
+ succeeded=ok_ids, num_deleted=len(ok_ids), num_failed=0, failed=[]
+ )
+
+ @override
+ def get(self, ids: Sequence[str], /, **kwargs: Any) -> list[Document]:
+ return [self.store[id_] for id_ in ids if id_ in self.store]
+
+ @override
+ def _get_relevant_documents(
+ self, query: str, *, run_manager: CallbackManagerForRetrieverRun
+ ) -> list[Document]:
+ counts_by_doc = []
+
+ for document in self.store.values():
+ count = document.page_content.count(query)
+ counts_by_doc.append((document, count))
+
+ counts_by_doc.sort(key=operator.itemgetter(1), reverse=True)
+ return [doc.model_copy() for doc, count in counts_by_doc[: self.top_k]]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..722597d410581a7f9fb12e9ca63e9fcc232b62bc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__init__.py
@@ -0,0 +1,116 @@
+"""Core language model abstractions.
+
+LangChain has two main classes to work with language models: chat models and
+"old-fashioned" LLMs (string-in, string-out).
+
+**Chat models**
+
+Language models that use a sequence of messages as inputs and return chat messages
+as outputs (as opposed to using plain text).
+
+Chat models support the assignment of distinct roles to conversation messages, helping
+to distinguish messages from the AI, users, and instructions such as system messages.
+
+The key abstraction for chat models is
+[`BaseChatModel`][langchain_core.language_models.BaseChatModel]. Implementations should
+inherit from this class.
+
+See existing [chat model integrations](https://docs.langchain.com/oss/python/integrations/chat).
+
+**LLMs (legacy)**
+
+Language models that takes a string as input and returns a string.
+
+These are traditionally older models (newer models generally are chat models).
+
+Although the underlying models are string in, string out, the LangChain wrappers also
+allow these models to take messages as input. This gives them the same interface as
+chat models. When messages are passed in as input, they will be formatted into a string
+under the hood before being passed to the underlying model.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+from langchain_core.language_models._utils import is_openai_data_block
+
+if TYPE_CHECKING:
+ from langchain_core.language_models.base import (
+ BaseLanguageModel,
+ LangSmithParams,
+ LanguageModelInput,
+ LanguageModelLike,
+ LanguageModelOutput,
+ get_tokenizer,
+ )
+ from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ SimpleChatModel,
+ )
+ from langchain_core.language_models.fake import FakeListLLM, FakeStreamingListLLM
+ from langchain_core.language_models.fake_chat_models import (
+ FakeListChatModel,
+ FakeMessagesListChatModel,
+ GenericFakeChatModel,
+ ParrotFakeChatModel,
+ )
+ from langchain_core.language_models.llms import LLM, BaseLLM
+ from langchain_core.language_models.model_profile import (
+ ModelProfile,
+ ModelProfileRegistry,
+ )
+
+__all__ = (
+ "LLM",
+ "BaseChatModel",
+ "BaseLLM",
+ "BaseLanguageModel",
+ "FakeListChatModel",
+ "FakeListLLM",
+ "FakeMessagesListChatModel",
+ "FakeStreamingListLLM",
+ "GenericFakeChatModel",
+ "LangSmithParams",
+ "LanguageModelInput",
+ "LanguageModelLike",
+ "LanguageModelOutput",
+ "ModelProfile",
+ "ModelProfileRegistry",
+ "ParrotFakeChatModel",
+ "SimpleChatModel",
+ "get_tokenizer",
+ "is_openai_data_block",
+)
+
+_dynamic_imports = {
+ "BaseLanguageModel": "base",
+ "LangSmithParams": "base",
+ "LanguageModelInput": "base",
+ "LanguageModelLike": "base",
+ "LanguageModelOutput": "base",
+ "get_tokenizer": "base",
+ "BaseChatModel": "chat_models",
+ "SimpleChatModel": "chat_models",
+ "FakeListLLM": "fake",
+ "FakeStreamingListLLM": "fake",
+ "FakeListChatModel": "fake_chat_models",
+ "FakeMessagesListChatModel": "fake_chat_models",
+ "GenericFakeChatModel": "fake_chat_models",
+ "ParrotFakeChatModel": "fake_chat_models",
+ "LLM": "llms",
+ "ModelProfile": "model_profile",
+ "ModelProfileRegistry": "model_profile",
+ "BaseLLM": "llms",
+ "is_openai_data_block": "_utils",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed3356a133482af1330c2b52f5759dd7109dc1c7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/_compat_bridge.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/_compat_bridge.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b97a788be99e75ec23c2f634340159c429c6c7c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/_compat_bridge.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9de6c98a27a78bf64ada7ad7fe6526347df5e022
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ee87238cec8477e5ff487b46c065411b3c52863c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/chat_model_stream.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/chat_model_stream.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..394c0d6006fff89d89e35dc1f39d9284978d00e5
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/chat_model_stream.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/fake.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/fake.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..780ced7e5b9a558cd8ec2a671e17b360e17f6a19
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/fake.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/fake_chat_models.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/fake_chat_models.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..386881cf481df0de447c1500cc5c0f8aa39cb546
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/fake_chat_models.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/llms.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/llms.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ff129fff7ded1409f326d2b0c5c92075b16f1a0
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/llms.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/model_profile.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/model_profile.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc60c88b398b25e1d3e4ac2df053aea293dc3a0e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/__pycache__/model_profile.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/_compat_bridge.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/_compat_bridge.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c2cdf0ba0d96e756c2540087d7fd6230a978018
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/_compat_bridge.py
@@ -0,0 +1,778 @@
+"""Compat bridge: convert `AIMessageChunk` streams to protocol events.
+
+The bridge trusts `AIMessageChunk.content_blocks` as the single
+protocol view of any chunk. That property runs the three-tier lookup
+(`output_version == "v1"` short-circuit, registered translator, or
+best-effort parsing) and returns a `list[ContentBlock]` for every
+well-formed message — whether the provider is a registered partner, an
+unregistered community model, or not tagged at all.
+
+Per-chunk `content_blocks` output is a **delta slice**, not accumulated
+state: providers in this ecosystem emit SSE-style chunks that each carry
+their own increment. The bridge therefore forwards each slice straight
+through as a `content-block-delta` event, and accumulates per-index
+state only so the final `content-block-finish` event can report a
+finalized block (e.g. `tool_call_chunk` args parsed to a dict).
+
+Lifecycle::
+
+ message-start
+ -> content-block-start (first time each index is observed)
+ -> content-block-delta* (per chunk, carrying the slice)
+ -> content-block-finish (finalized block)
+ -> message-finish
+
+Public API:
+
+- `chunks_to_events` / `achunks_to_events` — for live streams where
+ chunks arrive over time.
+- `message_to_events` / `amessage_to_events` — for replaying a finalized
+ `AIMessage` (cache hit, checkpoint restore, graph-node return value)
+ as a synthetic event lifecycle.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING, Any, cast
+
+from langchain_protocol.protocol import (
+ ContentBlock,
+ ContentBlockDeltaData,
+ ContentBlockFinishData,
+ ContentBlockStartData,
+ FinalizedContentBlock,
+ InvalidToolCall,
+ MessageFinishData,
+ MessageMetadata,
+ MessagesData,
+ MessageStartData,
+ ReasoningContentBlock,
+ ServerToolCall,
+ ServerToolCallChunk,
+ TextContentBlock,
+ ToolCall,
+ ToolCallChunk,
+ UsageInfo,
+)
+
+from langchain_core.messages import AIMessageChunk, BaseMessage
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator
+
+ from langchain_protocol.protocol import (
+ BlockDelta,
+ BlockDeltaFields,
+ ContentBlockDelta,
+ DataDelta,
+ ReasoningDelta,
+ TextDelta,
+ )
+
+ from langchain_core.outputs import ChatGenerationChunk
+
+
+CompatBlock = dict[str, Any]
+"""Internal working type for a content block.
+
+The bridge works with plain dicts internally because two separate but
+structurally similar `ContentBlock` Unions exist — one in
+`langchain_core.messages.content` (returned by `msg.content_blocks`),
+one in `langchain_protocol.protocol` (the wire/event shape). They are
+not mypy-compatible despite being near-isomorphic. Passing through
+`dict[str, Any]` launders between them. See `_to_protocol_block` for
+the single seam where the laundering cast lives.
+"""
+
+
+# ---------------------------------------------------------------------------
+# Type laundering between core and protocol `ContentBlock` unions
+# ---------------------------------------------------------------------------
+
+
+def _to_protocol_block(block: CompatBlock) -> ContentBlock:
+ """Narrow an internal working dict to a protocol `ContentBlock`.
+
+ Single seam between the two `ContentBlock` type systems:
+ `langchain_core.messages.content` (what `msg.content_blocks`
+ returns) and `langchain_protocol.protocol` (what event payloads
+ require). The two Unions overlap structurally but are nominally
+ distinct to mypy, so we launder through `dict[str, Any]`. When the
+ Unions are unified, this helper and its finalized counterpart can be
+ deleted.
+ """
+ return cast("ContentBlock", block)
+
+
+def _to_finalized_block(block: CompatBlock) -> FinalizedContentBlock:
+ """Counterpart of `_to_protocol_block` for finalized blocks."""
+ return cast("FinalizedContentBlock", block)
+
+
+def _to_block_delta_fields(block: CompatBlock) -> BlockDeltaFields:
+ """Narrow an internal working dict to protocol block-delta fields."""
+ return cast("BlockDeltaFields", block)
+
+
+def _to_content_delta(block: CompatBlock) -> ContentBlockDelta:
+ """Convert a content-block slice/snapshot to an explicit protocol delta."""
+ btype = block.get("type")
+ if btype == "text":
+ return cast("TextDelta", {"type": "text-delta", "text": block.get("text", "")})
+ if btype == "reasoning":
+ return cast(
+ "ReasoningDelta",
+ {
+ "type": "reasoning-delta",
+ "reasoning": block.get("reasoning", ""),
+ },
+ )
+ if "data" in block:
+ delta = cast("DataDelta", {"type": "data-delta", "data": block.get("data", "")})
+ if block.get("encoding") == "base64":
+ delta["encoding"] = "base64"
+ return delta
+ return cast(
+ "BlockDelta",
+ {
+ "type": "block-delta",
+ "fields": _to_block_delta_fields(block),
+ },
+ )
+
+
+# ---------------------------------------------------------------------------
+# Block iteration
+# ---------------------------------------------------------------------------
+
+
+def _iter_protocol_blocks(msg: BaseMessage) -> list[tuple[Any, CompatBlock]]:
+ """Read per-chunk protocol blocks from `msg.content_blocks`.
+
+ Returns `(key, block)` pairs. The key is the block's stable identifier
+ across the stream: the block's `index` field when present (can be an
+ int or a string — some providers use string identifiers like
+ `"lc_rs_305f30"`), or the positional index within the message as a
+ fallback. Callers are responsible for allocating wire-level `uint`
+ indices; this helper only surfaces the source-side identity.
+
+ For finalized `AIMessage`, also surfaces `invalid_tool_calls`
+ — which `AIMessage.content_blocks` currently omits from its return
+ value even though they are a defined protocol block type.
+
+ The positional fallback is a known fragility: when a provider emits
+ blocks without an `index` field (e.g. Anthropic's `_stream` with
+ `coerce_content_to_string=True`, where text chunks lose their
+ source-side index), every such chunk gets positional key 0 and
+ successive chunks merge into one block. This works correctly for
+ single-type streams (pure-text responses merge cleanly) because all
+ chunks share the same key and the open-block logic collapses them.
+ It would miscategorise a stream that mixed indexed structured
+ blocks with non-indexed coerced-text blocks, since an indexed
+ block with `index == 0` would collide with the anonymous text
+ block's positional-0 key. In the anthropic integration this
+ cannot currently occur: coerce-to-string mode is only selected
+ when no tools, thinking, or documents are present, and any of
+ those flips the stream to structured mode where every block
+ carries an integer index. A native `_stream_chat_model_events`
+ hook per provider (or a bridge-level "continue the open block when
+ the source has no identity" rule) would close the gap if another
+ integration ever emits mixed content.
+ """
+ try:
+ raw = msg.content_blocks
+ except Exception:
+ return []
+
+ result: list[tuple[Any, CompatBlock]] = []
+ for i, block in enumerate(raw):
+ if not isinstance(block, dict):
+ continue
+ key = block.get("index", i)
+ result.append((key, dict(block)))
+
+ if not isinstance(msg, AIMessageChunk):
+ # Finalized AIMessage: pull invalid_tool_calls from the dedicated
+ # field — AIMessage.content_blocks does not currently include them.
+ for itc in getattr(msg, "invalid_tool_calls", None) or []:
+ itc_block: CompatBlock = {"type": "invalid_tool_call"}
+ for key_name in ("id", "name", "args", "error"):
+ if itc.get(key_name) is not None:
+ itc_block[key_name] = itc[key_name]
+ result.append((len(result), itc_block))
+
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Per-block helpers
+# ---------------------------------------------------------------------------
+
+
+# Fields that can carry large payloads (inline base64 media, parsed args,
+# arbitrary dicts). Stripped from `content-block-start` for self-contained
+# block types so the payload rides on `content-block-finish` alone instead
+# of being serialized twice on the wire.
+_HEAVY_FIELDS = frozenset({"args", "data", "output", "transcript", "value"})
+
+
+def _start_skeleton(block: CompatBlock) -> ContentBlock:
+ """Empty-content placeholder for the `content-block-start` event.
+
+ Deltaable block types (text, reasoning, the `_chunk` tool variants)
+ get an empty payload so the lifecycle's "start" signal is distinct
+ from the first incremental delta. Self-contained types (image,
+ audio, video, file, non_standard, finalized tool calls) drop their
+ heavy payload fields; those are carried by `content-block-finish`.
+ Correlation fields (id, name, toolCallId) and small metadata
+ (mime_type, url, status, …) are preserved on the start event.
+ """
+ btype = block.get("type", "text")
+ if btype == "text":
+ return TextContentBlock(type="text", text="")
+ if btype == "reasoning":
+ return ReasoningContentBlock(type="reasoning", reasoning="")
+ if btype == "tool_call_chunk":
+ return ToolCallChunk(
+ type="tool_call_chunk",
+ id=block.get("id"),
+ name=block.get("name"),
+ args="",
+ )
+ if btype == "server_tool_call_chunk":
+ s_skel = ServerToolCallChunk(
+ type="server_tool_call_chunk",
+ args="",
+ )
+ if block.get("id") is not None:
+ s_skel["id"] = block["id"]
+ if block.get("name") is not None:
+ s_skel["name"] = block["name"]
+ return s_skel
+
+ stripped: CompatBlock = {k: v for k, v in block.items() if k not in _HEAVY_FIELDS}
+ # Restore required-but-heavy fields with minimal placeholders so the
+ # start event still validates against the CDDL shape of the block type.
+ if btype in ("tool_call", "server_tool_call"):
+ stripped["args"] = {}
+ elif btype == "non_standard":
+ stripped["value"] = {}
+ return _to_protocol_block(stripped)
+
+
+def _should_emit_delta(block: CompatBlock) -> bool:
+ """Whether a per-chunk block carries content worth a delta event.
+
+ Deltaable types emit only when they have fresh content. Self-contained
+ / already-finalized types skip the delta entirely — the `finish`
+ event carries them.
+ """
+ btype = block.get("type")
+ if btype == "text":
+ return bool(block.get("text"))
+ if btype == "reasoning":
+ return bool(block.get("reasoning"))
+ if btype in ("tool_call_chunk", "server_tool_call_chunk"):
+ return bool(
+ block.get("args") or block.get("id") or block.get("name"),
+ )
+ if "data" in block:
+ return bool(block.get("data"))
+ return False
+
+
+def _accumulate(state: CompatBlock | None, delta: CompatBlock) -> CompatBlock:
+ """Merge a per-chunk delta slice into accumulated per-index state.
+
+ Used only for the finalization pass — live delta events are emitted
+ directly from the per-chunk block, without round-tripping through
+ accumulated state.
+ """
+ if state is None:
+ return dict(delta)
+ btype = state.get("type")
+ dtype = delta.get("type")
+ if btype == "text" and dtype == "text":
+ state["text"] = state.get("text", "") + delta.get("text", "")
+ # Providers may send non-text fields (like `id`, or annotations)
+ # on later deltas. Merging (not replacing) keeps earlier keys
+ # intact while picking up these late-arriving fields.
+ for key, value in delta.items():
+ if key in ("type", "text") or value is None:
+ continue
+ if key == "extras" and isinstance(value, dict):
+ state["extras"] = {**(state.get("extras") or {}), **value}
+ else:
+ state[key] = value
+ elif btype == "reasoning" and dtype == "reasoning":
+ state["reasoning"] = state.get("reasoning", "") + delta.get("reasoning", "")
+ # Providers may ship non-text fields on later deltas. Claude's
+ # `signature_delta` arrives after the reasoning text, surfaced
+ # as `extras.signature`; merging (not replacing) keeps earlier
+ # keys intact.
+ for key, value in delta.items():
+ if key in ("type", "reasoning") or value is None:
+ continue
+ if key == "extras" and isinstance(value, dict):
+ state["extras"] = {**(state.get("extras") or {}), **value}
+ else:
+ state[key] = value
+ elif btype in ("tool_call_chunk", "server_tool_call_chunk") and dtype == btype:
+ state["args"] = (state.get("args", "") or "") + (delta.get("args") or "")
+ if delta.get("id") is not None:
+ state["id"] = delta["id"]
+ if delta.get("name") is not None:
+ state["name"] = delta["name"]
+ elif btype == dtype and "data" in delta:
+ state["data"] = (state.get("data", "") or "") + (delta.get("data") or "")
+ for key, value in delta.items():
+ if key in ("type", "data") or value is None:
+ continue
+ if key == "extras" and isinstance(value, dict):
+ state["extras"] = {**(state.get("extras") or {}), **value}
+ else:
+ state[key] = value
+ else:
+ # Self-contained or already-finalized types: replace wholesale.
+ state.clear()
+ state.update(delta)
+ return state
+
+
+def finalize_tool_call_chunk(
+ *,
+ raw_args: str | None,
+ id_: str | None,
+ name: str | None,
+ extras: dict[str, Any],
+ finalized_type: str,
+) -> FinalizedContentBlock:
+ """Parse accumulated tool-chunk args into a finalized block.
+
+ Shared between the compat bridge's `_finalize_block` and the
+ `ChatModelStream` end-of-stream sweep. Parses `raw_args` as JSON:
+ on success builds the requested finalized type (`tool_call` or
+ `server_tool_call`) with provider-specific fields (`extras`)
+ preserved; on failure falls back to `invalid_tool_call` carrying
+ the raw string so downstream consumers can still introspect the
+ malformed payload.
+
+ Args:
+ raw_args: Accumulated partial-JSON string; `None` or empty
+ treated as `{}`.
+ id_: Tool-call id collected across chunks.
+ name: Tool name collected across chunks.
+ extras: Provider-specific fields to carry onto the finalized
+ block. Callers are responsible for having already dropped
+ keys they don't want propagated (notably `type`, `id`,
+ `name`, `args`, and `index` on client-side `tool_call`).
+ finalized_type: `"tool_call"` or `"server_tool_call"`.
+
+ Returns:
+ A `ToolCall`, `ServerToolCall`, or `InvalidToolCall` — the
+ latter when `raw_args` is non-empty but not valid JSON.
+ """
+ raw = raw_args or "{}"
+ try:
+ parsed = json.loads(raw) if raw else {}
+ except (json.JSONDecodeError, TypeError):
+ invalid = InvalidToolCall(
+ type="invalid_tool_call",
+ id=id_,
+ name=name,
+ args=raw,
+ error="Failed to parse tool call arguments as JSON",
+ )
+ invalid.update(extras) # type: ignore[typeddict-item]
+ return invalid
+ if finalized_type == "tool_call":
+ finalized_tc = ToolCall(
+ type="tool_call",
+ id=id_ or "",
+ name=name or "",
+ args=parsed,
+ )
+ finalized_tc.update(extras) # type: ignore[typeddict-item]
+ return finalized_tc
+ finalized_stc = ServerToolCall(
+ type="server_tool_call",
+ id=id_ or "",
+ name=name or "",
+ args=parsed,
+ )
+ finalized_stc.update(extras) # type: ignore[typeddict-item]
+ return finalized_stc
+
+
+def _finalize_block(block: CompatBlock) -> FinalizedContentBlock:
+ """Promote chunk variants to their finalized form.
+
+ `tool_call_chunk` becomes `tool_call` — or `invalid_tool_call`
+ if the accumulated `args` don't parse as JSON.
+ `server_tool_call_chunk` becomes `server_tool_call` under the same
+ rule. Everything else passes through: text/reasoning blocks carry
+ their accumulated snapshot, and self-contained types are already in
+ their terminal shape.
+ """
+ btype = block.get("type")
+ if btype in ("tool_call_chunk", "server_tool_call_chunk"):
+ # Carry provider-specific fields from the accumulated chunk onto
+ # the finalized block. Drop the chunk-only keys we rewrite
+ # explicitly. `index` is stripped on client-side
+ # `tool_call` / `invalid_tool_call` finalizations to match v1
+ # (`AIMessage.init_tool_calls` rebuilds tool_call blocks without
+ # `index`), preventing `merge_lists` from re-merging further
+ # chunks into an already-parsed args dict. `server_tool_call`
+ # retains `index` because v1's `init_server_tool_calls`
+ # finalizes in-place and preserves it.
+ client_tool_call = btype == "tool_call_chunk"
+ extras_drop = {"type", "id", "name", "args"}
+ if client_tool_call:
+ extras_drop = extras_drop | {"index"}
+ extras = {
+ k: v for k, v in block.items() if k not in extras_drop and v is not None
+ }
+ return finalize_tool_call_chunk(
+ raw_args=block.get("args"),
+ id_=block.get("id"),
+ name=block.get("name"),
+ extras=extras,
+ finalized_type="tool_call" if client_tool_call else "server_tool_call",
+ )
+ return _to_finalized_block(block)
+
+
+# ---------------------------------------------------------------------------
+# Metadata, usage, finish-reason
+# ---------------------------------------------------------------------------
+
+
+def _extract_start_metadata(response_metadata: dict[str, Any]) -> MessageMetadata:
+ """Pull provider/model hints for the `message-start` event."""
+ metadata: MessageMetadata = {}
+ if "model_provider" in response_metadata:
+ metadata["provider"] = response_metadata["model_provider"]
+ if "model_name" in response_metadata:
+ metadata["model"] = response_metadata["model_name"]
+ return metadata
+
+
+def _accumulate_usage(
+ current: dict[str, Any] | None, delta: Any
+) -> dict[str, Any] | None:
+ """Sum usage counts and merge detail dicts across chunks."""
+ if not isinstance(delta, dict):
+ return current
+ if current is None:
+ return dict(delta)
+ for key in ("input_tokens", "output_tokens", "total_tokens", "cached_tokens"):
+ if key in delta:
+ current[key] = current.get(key, 0) + delta[key]
+ for detail_key in ("input_token_details", "output_token_details"):
+ if detail_key in delta and isinstance(delta[detail_key], dict):
+ if detail_key not in current:
+ current[detail_key] = {}
+ current[detail_key].update(delta[detail_key])
+ return current
+
+
+def _to_protocol_usage(usage: dict[str, Any] | None) -> UsageInfo | None:
+ """Convert accumulated usage to the protocol's `UsageInfo` shape."""
+ if usage is None:
+ return None
+ result: dict[str, Any] = {}
+ for key in ("input_tokens", "output_tokens", "total_tokens", "cached_tokens"):
+ if key in usage:
+ result[key] = usage[key]
+ return cast("UsageInfo", result) if result else None
+
+
+# ---------------------------------------------------------------------------
+# Event builders
+# ---------------------------------------------------------------------------
+
+
+def _build_message_start(
+ msg: BaseMessage,
+ message_id: str | None,
+) -> MessageStartData:
+ start_data = MessageStartData(event="message-start", role="ai", id="")
+ resolved_id = message_id if message_id is not None else getattr(msg, "id", None)
+ if resolved_id:
+ start_data["id"] = resolved_id
+ start_metadata = _extract_start_metadata(msg.response_metadata or {})
+ if start_metadata:
+ start_data["metadata"] = start_metadata
+ return start_data
+
+
+def _build_message_finish(
+ *,
+ usage: dict[str, Any] | None,
+ response_metadata: dict[str, Any] | None,
+) -> MessageFinishData:
+ # Protocol 0.0.9 removed the top-level `reason` field from
+ # `MessageFinishData`; the provider's raw `finish_reason` /
+ # `stop_reason` now rides inside `metadata` alongside other
+ # response metadata. Pass it through unchanged.
+ finish_data: dict[str, Any] = {"event": "message-finish"}
+ usage_info = _to_protocol_usage(usage)
+ if usage_info is not None:
+ finish_data["usage"] = usage_info
+ if response_metadata:
+ finish_data["metadata"] = dict(response_metadata)
+ return cast("MessageFinishData", finish_data)
+
+
+def _finalize_and_build_finish(
+ wire_idx: int,
+ block: CompatBlock,
+) -> MessagesData:
+ """Finalize a block and wrap it in a `content-block-finish` event."""
+ return ContentBlockFinishData(
+ event="content-block-finish",
+ index=wire_idx,
+ content=_finalize_block(block),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Main generators
+# ---------------------------------------------------------------------------
+
+
+def chunks_to_events(
+ chunks: Iterator[ChatGenerationChunk],
+ *,
+ message_id: str | None = None,
+) -> Iterator[MessagesData]:
+ """Convert a stream of `ChatGenerationChunk` to protocol events.
+
+ Blocks are tracked independently by source-side identifier. Providers
+ such as Anthropic can interleave parallel tool-call chunks by index, so
+ each first-seen block gets a `content-block-start`, deltas keep their
+ stable wire index, and all open blocks are finalized at message end.
+ Source-side identifiers (from the block's `index` field, which may be
+ int or string) are translated to sequential `uint` wire indices.
+
+ Args:
+ chunks: Iterator of `ChatGenerationChunk` from `_stream()`.
+ message_id: Optional stable message ID.
+
+ Yields:
+ `MessagesData` lifecycle events.
+ """
+ started = False
+ blocks: dict[Any, tuple[int, CompatBlock]] = {}
+ next_wire_idx = 0
+ usage: dict[str, Any] | None = None
+ response_metadata: dict[str, Any] = {}
+
+ for chunk in chunks:
+ msg = chunk.message
+ if not isinstance(msg, AIMessageChunk):
+ continue
+
+ # The v1 `stream()` wrapper merges `generation_info` into
+ # `response_metadata` before yielding (`chat_models.py` via
+ # `_gen_info_and_msg_metadata`). We bypass that wrapper by reading
+ # `_stream` directly, so reproduce the merge here with the same
+ # priority: `generation_info` first, then `message.response_metadata`
+ # overlays. This is how provider fields like `model_name`,
+ # `system_fingerprint`, and `finish_reason` reach the bridge when
+ # a provider emits them via `generation_info` instead of the
+ # message's `response_metadata`.
+ merged_rm: dict[str, Any] = {
+ **(chunk.generation_info or {}),
+ **(msg.response_metadata or {}),
+ }
+ if merged_rm:
+ response_metadata.update(merged_rm)
+
+ if not started:
+ started = True
+ yield _build_message_start(msg, message_id)
+
+ for key, block in _iter_protocol_blocks(msg):
+ if key not in blocks:
+ wire_idx = next_wire_idx
+ next_wire_idx += 1
+ blocks[key] = (wire_idx, dict(block))
+ yield ContentBlockStartData(
+ event="content-block-start",
+ index=wire_idx,
+ content=_start_skeleton(block),
+ )
+ else:
+ wire_idx, existing = blocks[key]
+ blocks[key] = (wire_idx, _accumulate(existing, block))
+ if _should_emit_delta(block):
+ wire_idx, current = blocks[key]
+ is_block_delta = block.get("type") in (
+ "tool_call_chunk",
+ "server_tool_call_chunk",
+ )
+ delta_source = current if is_block_delta else block
+ yield ContentBlockDeltaData(
+ event="content-block-delta",
+ index=wire_idx,
+ delta=_to_content_delta(delta_source or block),
+ )
+
+ if msg.usage_metadata:
+ usage = _accumulate_usage(usage, msg.usage_metadata)
+
+ if not started:
+ return
+
+ for wire_idx, block in blocks.values():
+ yield _finalize_and_build_finish(wire_idx, block)
+
+ yield _build_message_finish(
+ usage=usage,
+ response_metadata=response_metadata,
+ )
+
+
+async def achunks_to_events(
+ chunks: AsyncIterator[ChatGenerationChunk],
+ *,
+ message_id: str | None = None,
+) -> AsyncIterator[MessagesData]:
+ """Async variant of `chunks_to_events`."""
+ started = False
+ blocks: dict[Any, tuple[int, CompatBlock]] = {}
+ next_wire_idx = 0
+ usage: dict[str, Any] | None = None
+ response_metadata: dict[str, Any] = {}
+
+ async for chunk in chunks:
+ msg = chunk.message
+ if not isinstance(msg, AIMessageChunk):
+ continue
+
+ # See sync twin for rationale: merge `generation_info` into the
+ # accumulated `response_metadata` with the same priority as the
+ # v1 `stream()` wrapper.
+ merged_rm: dict[str, Any] = {
+ **(chunk.generation_info or {}),
+ **(msg.response_metadata or {}),
+ }
+ if merged_rm:
+ response_metadata.update(merged_rm)
+
+ if not started:
+ started = True
+ yield _build_message_start(msg, message_id)
+
+ for key, block in _iter_protocol_blocks(msg):
+ if key not in blocks:
+ wire_idx = next_wire_idx
+ next_wire_idx += 1
+ blocks[key] = (wire_idx, dict(block))
+ yield ContentBlockStartData(
+ event="content-block-start",
+ index=wire_idx,
+ content=_start_skeleton(block),
+ )
+ else:
+ wire_idx, existing = blocks[key]
+ blocks[key] = (wire_idx, _accumulate(existing, block))
+ if _should_emit_delta(block):
+ wire_idx, current = blocks[key]
+ is_block_delta = block.get("type") in (
+ "tool_call_chunk",
+ "server_tool_call_chunk",
+ )
+ delta_source = current if is_block_delta else block
+ yield ContentBlockDeltaData(
+ event="content-block-delta",
+ index=wire_idx,
+ delta=_to_content_delta(delta_source or block),
+ )
+
+ if msg.usage_metadata:
+ usage = _accumulate_usage(usage, msg.usage_metadata)
+
+ if not started:
+ return
+
+ for wire_idx, block in blocks.values():
+ yield _finalize_and_build_finish(wire_idx, block)
+
+ yield _build_message_finish(
+ usage=usage,
+ response_metadata=response_metadata,
+ )
+
+
+def message_to_events(
+ msg: BaseMessage,
+ *,
+ message_id: str | None = None,
+) -> Iterator[MessagesData]:
+ """Replay a finalized message as a synthetic event lifecycle.
+
+ For a message returned whole (from a graph node, checkpoint, or
+ cache), produce the same `message-start` / per-block /
+ `message-finish` event stream a live call would produce. Consumers
+ downstream see a uniform event shape regardless of source.
+
+ Text and reasoning blocks emit a single `content-block-delta` with
+ the full accumulated content. Already-finalized blocks (tool_call,
+ server_tool_call, image, etc.) skip the delta and rely on the
+ `content-block-finish` event alone.
+
+ Args:
+ msg: The finalized message — typically an `AIMessage`.
+ message_id: Optional stable message ID; falls back to `msg.id`.
+
+ Yields:
+ `MessagesData` lifecycle events.
+ """
+ response_metadata = msg.response_metadata or {}
+ yield _build_message_start(msg, message_id)
+
+ for wire_idx, (_key, block) in enumerate(_iter_protocol_blocks(msg)):
+ yield ContentBlockStartData(
+ event="content-block-start",
+ index=wire_idx,
+ content=_start_skeleton(block),
+ )
+ if _should_emit_delta(block):
+ yield ContentBlockDeltaData(
+ event="content-block-delta",
+ index=wire_idx,
+ delta=_to_content_delta(block),
+ )
+ yield ContentBlockFinishData(
+ event="content-block-finish",
+ index=wire_idx,
+ content=_finalize_block(block),
+ )
+
+ yield _build_message_finish(
+ usage=getattr(msg, "usage_metadata", None),
+ response_metadata=response_metadata,
+ )
+
+
+async def amessage_to_events(
+ msg: BaseMessage,
+ *,
+ message_id: str | None = None,
+) -> AsyncIterator[MessagesData]:
+ """Async variant of `message_to_events`."""
+ for event in message_to_events(msg, message_id=message_id):
+ yield event
+
+
+__all__ = [
+ "CompatBlock",
+ "achunks_to_events",
+ "amessage_to_events",
+ "chunks_to_events",
+ "finalize_tool_call_chunk",
+ "message_to_events",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..289b675307415364adb94d19a7559bcb51738e5b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/_utils.py
@@ -0,0 +1,343 @@
+import re
+from collections.abc import Sequence
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ TypedDict,
+ TypeVar,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.messages import BaseMessage
+from langchain_core.messages.content import (
+ ContentBlock,
+)
+
+
+def _filter_invocation_params_for_tracing(params: dict[str, Any]) -> dict[str, Any]:
+ """Filter out large/inappropriate fields from invocation params for tracing.
+
+ Removes fields like tools, functions, messages, response_format that can be large.
+
+ Args:
+ params: The invocation parameters to filter.
+
+ Returns:
+ The filtered parameters with large fields removed.
+ """
+ excluded_keys = {"tools", "functions", "messages", "response_format"}
+ return {k: v for k, v in params.items() if k not in excluded_keys}
+
+
+def is_openai_data_block(
+ block: dict, filter_: Literal["image", "audio", "file"] | None = None
+) -> bool:
+ """Check whether a block contains multimodal data in OpenAI Chat Completions format.
+
+ Supports both data and ID-style blocks (e.g. `'file_data'` and `'file_id'`)
+
+ If additional keys are present, they are ignored / will not affect outcome as long
+ as the required keys are present and valid.
+
+ Args:
+ block: The content block to check.
+ filter_: If provided, only return True for blocks matching this specific type.
+ - "image": Only match image_url blocks
+ - "audio": Only match input_audio blocks
+ - "file": Only match file blocks
+ If `None`, match any valid OpenAI data block type. Note that this means that
+ if the block has a valid OpenAI data type but the filter_ is set to a
+ different type, this function will return False.
+
+ Returns:
+ `True` if the block is a valid OpenAI data block and matches the filter_
+ (if provided).
+
+ """
+ if block.get("type") == "image_url":
+ if filter_ is not None and filter_ != "image":
+ return False
+ if (
+ (set(block.keys()) <= {"type", "image_url", "detail"})
+ and (image_url := block.get("image_url"))
+ and isinstance(image_url, dict)
+ ):
+ url = image_url.get("url")
+ if isinstance(url, str):
+ # Required per OpenAI spec
+ return True
+ # Ignore `'detail'` since it's optional and specific to OpenAI
+
+ elif block.get("type") == "input_audio":
+ if filter_ is not None and filter_ != "audio":
+ return False
+ if (audio := block.get("input_audio")) and isinstance(audio, dict):
+ audio_data = audio.get("data")
+ audio_format = audio.get("format")
+ # Both required per OpenAI spec
+ if isinstance(audio_data, str) and isinstance(audio_format, str):
+ return True
+
+ elif block.get("type") == "file":
+ if filter_ is not None and filter_ != "file":
+ return False
+ if (file := block.get("file")) and isinstance(file, dict):
+ file_data = file.get("file_data")
+ file_id = file.get("file_id")
+ # Files can be either base64-encoded or pre-uploaded with an ID
+ if isinstance(file_data, str) or isinstance(file_id, str):
+ return True
+
+ else:
+ return False
+
+ # Has no `'type'` key
+ return False
+
+
+class ParsedDataUri(TypedDict):
+ source_type: Literal["base64"]
+ data: str
+ mime_type: str
+
+
+def _parse_data_uri(uri: str) -> ParsedDataUri | None:
+ """Parse a data URI into its components.
+
+ If parsing fails, return `None`. If either MIME type or data is missing, return
+ `None`.
+
+ Example:
+ ```python
+ data_uri = "data:image/jpeg;base64,/9j/4AAQSkZJRg..."
+ parsed = _parse_data_uri(data_uri)
+
+ assert parsed == {
+ "source_type": "base64",
+ "mime_type": "image/jpeg",
+ "data": "/9j/4AAQSkZJRg...",
+ }
+ ```
+ """
+ regex = r"^data:(?P[^;]+);base64,(?P.+)$"
+ match = re.match(regex, uri)
+ if match is None:
+ return None
+
+ mime_type = match.group("mime_type")
+ data = match.group("data")
+ if not mime_type or not data:
+ return None
+
+ return {
+ "source_type": "base64",
+ "data": data,
+ "mime_type": mime_type,
+ }
+
+
+def _normalize_messages(
+ messages: Sequence["BaseMessage"],
+) -> list["BaseMessage"]:
+ """Normalize message formats to LangChain v1 standard content blocks.
+
+ Chat models already implement support for:
+ - Images in OpenAI Chat Completions format
+ These will be passed through unchanged
+ - LangChain v1 standard content blocks
+
+ This function extends support to:
+ - `[Audio](https://platform.openai.com/docs/api-reference/chat/create) and
+ `[file](https://platform.openai.com/docs/api-reference/files) data in OpenAI
+ Chat Completions format
+ - Images are technically supported but we expect chat models to handle them
+ directly; this may change in the future
+ - LangChain v0 standard content blocks for backward compatibility
+
+ !!! warning "Behavior changed in `langchain-core` 1.0.0"
+
+ In previous versions, this function returned messages in LangChain v0 format.
+ Now, it returns messages in LangChain v1 format, which upgraded chat models now
+ expect to receive when passing back in message history. For backward
+ compatibility, this function will convert v0 message content to v1 format.
+
+ ??? note "v0 Content Block Schemas"
+
+ `URLContentBlock`:
+
+ ```python
+ {
+ mime_type: NotRequired[str]
+ type: Literal['image', 'audio', 'file'],
+ source_type: Literal['url'],
+ url: str,
+ }
+ ```
+
+ `Base64ContentBlock`:
+
+ ```python
+ {
+ mime_type: NotRequired[str]
+ type: Literal['image', 'audio', 'file'],
+ source_type: Literal['base64'],
+ data: str,
+ }
+ ```
+
+ `IDContentBlock`:
+
+ (In practice, this was never used)
+
+ ```python
+ {
+ type: Literal["image", "audio", "file"],
+ source_type: Literal["id"],
+ id: str,
+ }
+ ```
+
+ `PlainTextContentBlock`:
+
+ ```python
+ {
+ mime_type: NotRequired[str]
+ type: Literal['file'],
+ source_type: Literal['text'],
+ url: str,
+ }
+ ```
+
+ If a v1 message is passed in, it will be returned as-is, meaning it is safe to
+ always pass in v1 messages to this function for assurance.
+
+ For posterity, here are the OpenAI Chat Completions schemas we expect:
+
+ Chat Completions image. Can be URL-based or base64-encoded. Supports MIME types
+ png, jpeg/jpg, webp, static gif:
+ {
+ "type": Literal['image_url'],
+ "image_url": {
+ "url": Union["data:$MIME_TYPE;base64,$BASE64_ENCODED_IMAGE", "$IMAGE_URL"],
+ "detail": Literal['low', 'high', 'auto'] = 'auto', # Supported by OpenAI
+ }
+ }
+
+ Chat Completions audio:
+ {
+ "type": Literal['input_audio'],
+ "input_audio": {
+ "format": Literal['wav', 'mp3'],
+ "data": str = "$BASE64_ENCODED_AUDIO",
+ },
+ }
+
+ Chat Completions files: either base64 or pre-uploaded file ID
+ {
+ "type": Literal['file'],
+ "file": Union[
+ {
+ "filename": str | None = "$FILENAME",
+ "file_data": str = "$BASE64_ENCODED_FILE",
+ },
+ {
+ "file_id": str = "$FILE_ID", # For pre-uploaded files to OpenAI
+ },
+ ],
+ }
+
+ """
+ from langchain_core.messages.block_translators.langchain_v0 import ( # noqa: PLC0415
+ _convert_legacy_v0_content_block_to_v1,
+ )
+ from langchain_core.messages.block_translators.openai import ( # noqa: PLC0415
+ _convert_openai_format_to_data_block,
+ )
+
+ formatted_messages = []
+ for message in messages:
+ # We preserve input messages - the caller may reuse them elsewhere and expects
+ # them to remain unchanged. We only create a copy if we need to translate.
+ formatted_message = message
+
+ if isinstance(message.content, list):
+ for idx, block in enumerate(message.content):
+ # OpenAI Chat Completions multimodal data blocks to v1 standard
+ if (
+ isinstance(block, dict)
+ and block.get("type") in {"input_audio", "file"}
+ # Discriminate between OpenAI/LC format since they share `'type'`
+ and is_openai_data_block(block)
+ ):
+ formatted_message = _ensure_message_copy(message, formatted_message)
+
+ converted_block = _convert_openai_format_to_data_block(block)
+ _update_content_block(formatted_message, idx, converted_block)
+
+ # Convert multimodal LangChain v0 to v1 standard content blocks
+ elif (
+ isinstance(block, dict)
+ and block.get("type")
+ in {
+ "image",
+ "audio",
+ "file",
+ }
+ and block.get("source_type") # v1 doesn't have `source_type`
+ in {
+ "url",
+ "base64",
+ "id",
+ "text",
+ }
+ ):
+ formatted_message = _ensure_message_copy(message, formatted_message)
+
+ converted_block = _convert_legacy_v0_content_block_to_v1(block)
+ _update_content_block(formatted_message, idx, converted_block)
+ continue
+
+ # else, pass through blocks that look like they have v1 format unchanged
+
+ formatted_messages.append(formatted_message)
+
+ return formatted_messages
+
+
+T = TypeVar("T", bound="BaseMessage")
+
+
+def _ensure_message_copy(message: T, formatted_message: T) -> T:
+ """Create a copy of the message if it hasn't been copied yet."""
+ if formatted_message is message:
+ formatted_message = message.model_copy()
+ # Shallow-copy content list to allow modifications
+ formatted_message.content = list(formatted_message.content)
+ return formatted_message
+
+
+def _update_content_block(
+ formatted_message: "BaseMessage", idx: int, new_block: ContentBlock | dict
+) -> None:
+ """Update a content block at the given index, handling type issues."""
+ # Type ignore needed because:
+ # - `BaseMessage.content` is typed as `Union[str, list[Union[str, dict]]]`
+ # - When content is str, indexing fails (index error)
+ # - When content is list, the items are `Union[str, dict]` but we're assigning
+ # `Union[ContentBlock, dict]` where ContentBlock is richer than dict
+ # - This is safe because we only call this when we've verified content is a list and
+ # we're doing content block conversions
+ formatted_message.content[idx] = new_block # type: ignore[index, assignment]
+
+
+def _update_message_content_to_blocks(message: T, output_version: str) -> T:
+ return message.model_copy(
+ update={
+ "content": message.content_blocks,
+ "response_metadata": {
+ **message.response_metadata,
+ "output_version": output_version,
+ },
+ }
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..570076290e09ffbb1cae52811f6cc0231b951217
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/base.py
@@ -0,0 +1,391 @@
+"""Base language models class."""
+
+from __future__ import annotations
+
+import warnings
+from abc import ABC, abstractmethod
+from collections.abc import Callable, Mapping, Sequence
+from functools import cache
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ TypeAlias,
+ TypeVar,
+ cast,
+)
+
+from pydantic import BaseModel, ConfigDict, Field, field_validator
+from typing_extensions import TypedDict, override
+
+from langchain_core.caches import BaseCache # noqa: TC001
+from langchain_core.callbacks import Callbacks # noqa: TC001
+from langchain_core.globals import get_verbose
+from langchain_core.messages import (
+ AIMessage,
+ AnyMessage,
+ BaseMessage,
+ MessageLikeRepresentation,
+ get_buffer_string,
+)
+from langchain_core.prompt_values import (
+ ChatPromptValueConcrete,
+ PromptValue,
+ StringPromptValue,
+)
+from langchain_core.runnables import Runnable, RunnableSerializable
+
+if TYPE_CHECKING:
+ from langchain_core.outputs import LLMResult
+
+try:
+ from transformers import GPT2TokenizerFast # type: ignore[import-not-found]
+
+ _HAS_TRANSFORMERS = True
+except ImportError:
+ _HAS_TRANSFORMERS = False
+
+
+class LangSmithParams(TypedDict, total=False):
+ """LangSmith parameters for tracing."""
+
+ ls_provider: str
+ """Provider of the model."""
+
+ ls_model_name: str
+ """Name of the model."""
+
+ ls_model_type: Literal["chat", "llm"]
+ """Type of the model.
+
+ Should be `'chat'` or `'llm'`.
+ """
+
+ ls_temperature: float | None
+ """Temperature for generation."""
+
+ ls_max_tokens: int | None
+ """Max tokens for generation."""
+
+ ls_stop: list[str] | None
+ """Stop words for generation."""
+ ls_integration: str
+ """Integration that created the trace."""
+
+
+@cache # Cache the tokenizer
+def get_tokenizer() -> Any:
+ """Get a GPT-2 tokenizer instance.
+
+ This function is cached to avoid re-loading the tokenizer every time it is called.
+
+ Raises:
+ ImportError: If the transformers package is not installed.
+
+ Returns:
+ The GPT-2 tokenizer instance.
+
+ """
+ if not _HAS_TRANSFORMERS:
+ msg = (
+ "Could not import transformers python package. "
+ "This is needed in order to calculate get_token_ids. "
+ "Please install it with `pip install transformers`."
+ )
+ raise ImportError(msg)
+ # create a GPT-2 tokenizer instance
+ return GPT2TokenizerFast.from_pretrained("gpt2")
+
+
+_GPT2_TOKENIZER_WARNED = False
+
+
+def _get_token_ids_default_method(text: str) -> list[int]:
+ """Encode the text into token IDs using the fallback GPT-2 tokenizer."""
+ global _GPT2_TOKENIZER_WARNED # noqa: PLW0603
+ if not _GPT2_TOKENIZER_WARNED:
+ warnings.warn(
+ "Using fallback GPT-2 tokenizer for token counting. "
+ "Token counts may be inaccurate for non-GPT-2 models. "
+ "For accurate counts, use a model-specific method if available.",
+ stacklevel=3,
+ )
+ _GPT2_TOKENIZER_WARNED = True
+
+ tokenizer = get_tokenizer()
+
+ # Pass verbose=False to suppress the "Token indices sequence length is longer than
+ # the specified maximum sequence length" warning from HuggingFace. This warning is
+ # about GPT-2's 1024 token context limit, but we're only using the tokenizer for
+ # counting, not for model input.
+ return cast("list[int]", tokenizer.encode(text, verbose=False))
+
+
+LanguageModelInput = PromptValue | str | Sequence[MessageLikeRepresentation]
+"""Input to a language model."""
+
+LanguageModelOutput = BaseMessage | str
+"""Output from a language model."""
+
+LanguageModelLike = Runnable[LanguageModelInput, LanguageModelOutput]
+"""Input/output interface for a language model."""
+
+LanguageModelOutputVar = TypeVar("LanguageModelOutputVar", AIMessage, str)
+"""Type variable for the output of a language model."""
+
+
+def _get_verbosity() -> bool:
+ return get_verbose()
+
+
+class BaseLanguageModel(
+ RunnableSerializable[LanguageModelInput, LanguageModelOutputVar], ABC
+):
+ """Abstract base class for interfacing with language models.
+
+ All language model wrappers inherited from `BaseLanguageModel`.
+
+ """
+
+ cache: BaseCache | bool | None = Field(default=None, exclude=True)
+ """Whether to cache the response.
+
+ * If `True`, will use the global cache.
+ * If `False`, will not use a cache
+ * If `None`, will use the global cache if it's set, otherwise no cache.
+ * If instance of `BaseCache`, will use the provided cache.
+
+ Caching is not currently supported for streaming methods of models.
+ """
+
+ verbose: bool = Field(default_factory=_get_verbosity, exclude=True, repr=False)
+ """Whether to print out response text."""
+
+ callbacks: Callbacks = Field(default=None, exclude=True)
+ """Callbacks to add to the run trace."""
+
+ tags: list[str] | None = Field(default=None, exclude=True)
+ """Tags to add to the run trace."""
+
+ metadata: dict[str, Any] | None = Field(default=None, exclude=True)
+ """Metadata to add to the run trace."""
+
+ custom_get_token_ids: Callable[[str], list[int]] | None = Field(
+ default=None, exclude=True
+ )
+ """Optional encoder to use for counting tokens."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @field_validator("verbose", mode="before")
+ def set_verbose(cls, verbose: bool | None) -> bool: # noqa: FBT001
+ """If verbose is `None`, set it.
+
+ This allows users to pass in `None` as verbose to access the global setting.
+
+ Args:
+ verbose: The verbosity setting to use.
+
+ Returns:
+ The verbosity setting to use.
+
+ """
+ if verbose is None:
+ return _get_verbosity()
+ return verbose
+
+ @property
+ @override
+ def InputType(self) -> TypeAlias:
+ """Get the input type for this `Runnable`."""
+ # This is a version of LanguageModelInput which replaces the abstract
+ # base class BaseMessage with a union of its subclasses, which makes
+ # for a much better schema.
+ return str | StringPromptValue | ChatPromptValueConcrete | list[AnyMessage]
+
+ @abstractmethod
+ def generate_prompt(
+ self,
+ prompts: list[PromptValue],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Pass a sequence of prompts to the model and return model generations.
+
+ This method should make use of batched calls for models that expose a batched
+ API.
+
+ Use this method when you want to:
+
+ 1. Take advantage of batched calls,
+ 2. Need more output from the model than just the top generated value,
+ 3. Are building chains that are agnostic to the underlying language model
+ type (e.g., pure text completion models vs chat models).
+
+ Args:
+ prompts: List of `PromptValue` objects.
+
+ A `PromptValue` is an object that can be converted to match the format
+ of any language model (string for pure text generation models and
+ `BaseMessage` objects for chat models).
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ callbacks: `Callbacks` to pass through.
+
+ Used for executing additional functionality, such as logging or
+ streaming, throughout generation.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Returns:
+ An `LLMResult`, which contains a list of candidate `Generation` objects for
+ each input prompt and additional model provider-specific output.
+
+ """
+
+ @abstractmethod
+ async def agenerate_prompt(
+ self,
+ prompts: list[PromptValue],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Asynchronously pass a sequence of prompts and return model generations.
+
+ This method should make use of batched calls for models that expose a batched
+ API.
+
+ Use this method when you want to:
+
+ 1. Take advantage of batched calls,
+ 2. Need more output from the model than just the top generated value,
+ 3. Are building chains that are agnostic to the underlying language model
+ type (e.g., pure text completion models vs chat models).
+
+ Args:
+ prompts: List of `PromptValue` objects.
+
+ A `PromptValue` is an object that can be converted to match the format
+ of any language model (string for pure text generation models and
+ `BaseMessage` objects for chat models).
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ callbacks: `Callbacks` to pass through.
+
+ Used for executing additional functionality, such as logging or
+ streaming, throughout generation.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Returns:
+ An `LLMResult`, which contains a list of candidate `Generation` objects for
+ each input prompt and additional model provider-specific output.
+
+ """
+
+ def with_structured_output(
+ self, schema: dict | type, **kwargs: Any
+ ) -> Runnable[LanguageModelInput, dict | BaseModel]:
+ """Not implemented on this class."""
+ # Implement this on child class if there is a way of steering the model to
+ # generate responses that match a given schema.
+ raise NotImplementedError
+
+ def _get_ls_params(
+ self,
+ stop: list[str] | None = None, # noqa: ARG002
+ **kwargs: Any, # noqa: ARG002
+ ) -> LangSmithParams:
+ """Get standard params for tracing."""
+ return LangSmithParams()
+
+ def _get_ls_params_with_defaults(
+ self,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> LangSmithParams:
+ """Wrap _get_ls_params to include any additional default parameters."""
+ return self._get_ls_params(stop=stop, **kwargs)
+
+ @property
+ def _identifying_params(self) -> Mapping[str, Any]:
+ """Get the identifying parameters."""
+ return self.lc_attributes
+
+ def get_token_ids(self, text: str) -> list[int]:
+ """Return the ordered IDs of the tokens in a text.
+
+ Args:
+ text: The string input to tokenize.
+
+ Returns:
+ A list of IDs corresponding to the tokens in the text, in order they occur
+ in the text.
+ """
+ if self.custom_get_token_ids is not None:
+ return self.custom_get_token_ids(text)
+ return _get_token_ids_default_method(text)
+
+ def get_num_tokens(self, text: str) -> int:
+ """Get the number of tokens present in the text.
+
+ Useful for checking if an input fits in a model's context window.
+
+ This should be overridden by model-specific implementations to provide accurate
+ token counts via model-specific tokenizers.
+
+ Args:
+ text: The string input to tokenize.
+
+ Returns:
+ The integer number of tokens in the text.
+
+ """
+ return len(self.get_token_ids(text))
+
+ def get_num_tokens_from_messages(
+ self,
+ messages: list[BaseMessage],
+ tools: Sequence | None = None,
+ ) -> int:
+ """Get the number of tokens in the messages.
+
+ Useful for checking if an input fits in a model's context window.
+
+ This should be overridden by model-specific implementations to provide accurate
+ token counts via model-specific tokenizers.
+
+ !!! note
+
+ * The base implementation of `get_num_tokens_from_messages` ignores tool
+ schemas.
+ * The base implementation of `get_num_tokens_from_messages` adds additional
+ prefixes to messages in represent user roles, which will add to the
+ overall token count. Model-specific implementations may choose to
+ handle this differently.
+
+ Args:
+ messages: The message inputs to tokenize.
+ tools: If provided, sequence of dict, `BaseModel`, function, or
+ `BaseTool` objects to be converted to tool schemas.
+
+ Returns:
+ The sum of the number of tokens across the messages.
+
+ """
+ if tools is not None:
+ warnings.warn(
+ "Counting tokens in tool schemas is not yet supported. Ignoring tools.",
+ stacklevel=2,
+ )
+ return sum(self.get_num_tokens(get_buffer_string([m])) for m in messages)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/chat_model_stream.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/chat_model_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b25a66fd2a4f943b4ae95a014ae3bcc8a236e96
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/chat_model_stream.py
@@ -0,0 +1,1428 @@
+"""Per-message streaming objects for content-block protocol events.
+
+`ChatModelStream` is the synchronous variant returned by
+`BaseChatModel.stream_events(version="v3")`. `AsyncChatModelStream` is the
+asynchronous variant returned by `BaseChatModel.astream_events(version="v3")`.
+
+Both expose typed projection properties (`.text`, `.reasoning`,
+`.tool_calls`, `.usage`, `.output`) that accumulate protocol
+events as they arrive. Projections can be iterated for deltas or
+drained for the final accumulated value.
+
+Raw protocol events are also available via direct iteration on the
+stream object (replay-buffer semantics — multiple independent
+consumers supported).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+from typing import TYPE_CHECKING, Any, cast
+
+from langchain_core.language_models._compat_bridge import finalize_tool_call_chunk
+from langchain_core.messages import AIMessage
+
+if TYPE_CHECKING:
+ from collections.abc import Awaitable, Callable, Generator, Iterator, Mapping
+
+ from langchain_protocol.protocol import (
+ ContentBlockDeltaData,
+ ContentBlockFinishData,
+ FinalizedContentBlock,
+ InvalidToolCall,
+ MessageFinishData,
+ MessageMetadata,
+ MessagesData,
+ MessageStartData,
+ ReasoningContentBlock,
+ ServerToolCallChunk,
+ TextContentBlock,
+ ToolCall,
+ ToolCallChunk,
+ UsageInfo,
+ )
+ from typing_extensions import Self
+
+
+# ---------------------------------------------------------------------------
+# Tool-call chunk helpers (shared by tool_call_chunk and server_tool_call_chunk)
+# ---------------------------------------------------------------------------
+
+
+def _merge_chunk_into_store(
+ store: dict[int, dict[str, Any]],
+ idx: int,
+ block: dict[str, Any],
+) -> None:
+ """Merge a tool-call-chunk delta: sticky id/name, concat args."""
+ existing = store.get(idx, {})
+ if block.get("id") and "id" not in existing:
+ existing["id"] = block["id"]
+ if block.get("name") and "name" not in existing:
+ existing["name"] = block["name"]
+ existing["args"] = existing.get("args", "") + (block.get("args") or "")
+ store[idx] = existing
+
+
+def _merge_block_delta_into_store(
+ store: dict[int, dict[str, Any]],
+ idx: int,
+ fields: dict[str, Any],
+) -> None:
+ """Shallow-merge a block-delta snapshot into an indexed chunk store."""
+ existing = store.get(idx, {})
+ for key, value in fields.items():
+ if value is not None:
+ existing[key] = value
+ store[idx] = existing
+
+
+def _event_content_block(data: Mapping[str, Any]) -> dict[str, Any] | None:
+ """Return start/finish content, tolerating the pre-delta field name."""
+ block = data.get("content") or data.get("content_block")
+ return block if isinstance(block, dict) else None
+
+
+def _legacy_block_to_delta(block: Mapping[str, Any]) -> dict[str, Any]:
+ """Convert the old content-block delta shape to an explicit delta."""
+ btype = block.get("type")
+ if btype == "text":
+ return {"type": "text-delta", "text": block.get("text", "")}
+ if btype == "reasoning":
+ return {
+ "type": "reasoning-delta",
+ "reasoning": block.get("reasoning", ""),
+ }
+ if "data" in block:
+ delta = {"type": "data-delta", "data": block.get("data", "")}
+ if block.get("encoding") == "base64":
+ delta["encoding"] = "base64"
+ return delta
+ return {"type": "legacy-block-delta", "fields": block}
+
+
+def _event_delta(data: Mapping[str, Any]) -> dict[str, Any] | None:
+ """Return an explicit delta, converting legacy content-block deltas."""
+ delta = data.get("delta")
+ if isinstance(delta, dict):
+ return delta
+ block = data.get("content_block")
+ if isinstance(block, dict):
+ return _legacy_block_to_delta(block)
+ return None
+
+
+def _sweep_chunk_store(
+ store: dict[int, dict[str, Any]],
+ *,
+ finalized_type: str,
+ finalized_blocks: dict[int, FinalizedContentBlock],
+ tool_calls_acc: list[ToolCall] | None,
+ invalid_acc: list[InvalidToolCall],
+) -> None:
+ """Parse each unswept chunk's `args`; record as `finalized_type` or invalid.
+
+ `tool_calls_acc` is only populated when `finalized_type == "tool_call"`
+ (server-side calls don't surface through `.tool_calls`).
+
+ Deliberately does not backfill `index` onto finalized tool-call blocks:
+ matches v1 (`AIMessage.init_tool_calls` drops `index` when substituting
+ `tool_call_chunk` → `tool_call`) and prevents `merge_lists` from
+ re-merging further chunks into an already-parsed args dict.
+ """
+ for idx in sorted(store):
+ chunk = store[idx]
+ # Carry over any non-finalize-rewritten fields the chunk collected
+ # (e.g., `extras`). `_merge_chunk_into_store` only populates
+ # `id` / `name` / `args`, so this is empty in practice today;
+ # future provider-specific fields would flow through here.
+ extras = {
+ k: v
+ for k, v in chunk.items()
+ if k not in ("type", "id", "name", "args") and v is not None
+ }
+ final_block = finalize_tool_call_chunk(
+ raw_args=chunk.get("args"),
+ id_=chunk.get("id"),
+ name=chunk.get("name"),
+ extras=extras,
+ finalized_type=finalized_type,
+ )
+ if final_block["type"] == "invalid_tool_call":
+ invalid_acc.append(final_block)
+ elif tool_calls_acc is not None and finalized_type == "tool_call":
+ tool_calls_acc.append(cast("ToolCall", final_block))
+ finalized_blocks[idx] = final_block
+ store.clear()
+
+
+# ---------------------------------------------------------------------------
+# Projection base — shared producer API
+# ---------------------------------------------------------------------------
+
+
+class _ProjectionBase:
+ """Shared state and producer API for sync and async projections.
+
+ The `push` / `complete` / `fail` methods are the producer-side
+ API — called by the stream as events arrive. Subclasses add the
+ consumer protocol (sync iteration or async iteration + await).
+
+ `done` and `error` are safe read-only views of the terminal state
+ for iterators and other siblings that need to observe lifecycle
+ without reaching into the underlying fields.
+ """
+
+ __slots__ = ("_deltas", "_done", "_error", "_final_set", "_final_value")
+
+ def __init__(self) -> None:
+ """Initialize empty projection state."""
+ self._deltas: list[Any] = []
+ self._final_value: Any = None
+ self._final_set: bool = False
+ self._done: bool = False
+ self._error: BaseException | None = None
+
+ @property
+ def done(self) -> bool:
+ """Whether the projection has finished (successfully or via error)."""
+ return self._done
+
+ @property
+ def error(self) -> BaseException | None:
+ """The terminal error, if any."""
+ return self._error
+
+ def push(self, delta: Any) -> None:
+ """Append a delta value. Producer-side API."""
+ self._deltas.append(delta)
+
+ def complete(self, final_value: Any) -> None:
+ """Set the final accumulated value and mark as done. Producer-side API."""
+ self._final_value = final_value
+ self._final_set = True
+ self._done = True
+
+ def fail(self, error: BaseException) -> None:
+ """Mark as errored. Producer-side API."""
+ self._error = error
+ self._done = True
+
+
+# ---------------------------------------------------------------------------
+# Sync projections
+# ---------------------------------------------------------------------------
+
+
+class SyncProjection(_ProjectionBase):
+ """Sync iterable of deltas with pull-based backpressure.
+
+ Follows the same `_request_more` convention as langgraph's
+ `EventLog`: when the cursor catches up to the buffer and the
+ projection is not done, it calls `_request_more()` to pull more
+ events from the producer.
+
+ Each call to `__iter__` creates a new cursor at position 0.
+ Multiple iterators replay all deltas from the start.
+ """
+
+ __slots__ = ("_ensure_started", "_request_more")
+
+ def __init__(self) -> None:
+ """Initialize with no pull callback."""
+ super().__init__()
+ self._ensure_started: Callable[[], None] | None = None
+ self._request_more: Callable[[], bool] | None = None
+
+ def set_start(self, cb: Callable[[], None] | None) -> None:
+ """Install a lazy-start callback invoked on first consumption."""
+ self._ensure_started = cb
+
+ def set_request_more(self, cb: Callable[[], bool] | None) -> None:
+ """Install the pull callback the iterator uses to drain the source."""
+ self._request_more = cb
+
+ def __iter__(self) -> Iterator[Any]:
+ """Yield deltas, pulling via `_request_more` when caught up."""
+ if self._ensure_started is not None:
+ self._ensure_started()
+ cursor = 0
+ while True:
+ if cursor < len(self._deltas):
+ yield self._deltas[cursor]
+ cursor += 1
+ elif self._error is not None:
+ raise self._error
+ elif self._done:
+ return
+ elif self._request_more is not None:
+ while cursor >= len(self._deltas) and not self._done:
+ if not self._request_more():
+ break
+ if cursor >= len(self._deltas):
+ if self._error is not None:
+ raise self._error
+ return
+ else:
+ return
+
+ def get(self) -> Any:
+ """Drain via `_request_more` and return the final value."""
+ if self._ensure_started is not None:
+ self._ensure_started()
+ if not self._done and self._request_more is not None:
+ while not self._done:
+ if not self._request_more():
+ break
+ if self._error is not None:
+ raise self._error
+ return self._final_value
+
+
+class SyncTextProjection(SyncProjection):
+ """String-specialized sync projection.
+
+ Adds `__str__`, `__bool__`, `__repr__` for ergonomic use with
+ `.text` and `.reasoning` projections.
+ """
+
+ __slots__ = ()
+
+ def __str__(self) -> str:
+ """Drain and return the full accumulated string."""
+ val = self.get()
+ return val if val is not None else ""
+
+ def __bool__(self) -> bool:
+ """Return whether any deltas have been pushed."""
+ return len(self._deltas) > 0
+
+ def __repr__(self) -> str:
+ """Return repr of the accumulated text so far."""
+ if self._final_set:
+ return repr(self._final_value)
+ return repr("".join(self._deltas))
+
+
+# ---------------------------------------------------------------------------
+# Async projection
+# ---------------------------------------------------------------------------
+
+
+class AsyncProjection(_ProjectionBase):
+ """Async iterable of deltas that is also awaitable for the final value.
+
+ Uses an `asyncio.Event` to notify consumers of state changes. Each
+ waiter — the awaitable (`__await__`) and each async iterator cursor
+ — shares the event and re-checks its own condition on wake. The event
+ is cleared before a waiter awaits, so stale "something happened"
+ signals don't cause spin loops.
+
+ This is single-loop only — producers and consumers must share an
+ event loop. If cross-thread wake is ever required, revert to a
+ list-of-futures pattern with `call_soon_threadsafe`.
+ """
+
+ __slots__ = ("_arequest_more", "_ensure_started", "_event")
+
+ def __init__(self) -> None:
+ """Initialize with an un-set event and no pump callback."""
+ super().__init__()
+ self._event = asyncio.Event()
+ self._arequest_more: Callable[[], Awaitable[bool]] | None = None
+ self._ensure_started: Callable[[], Awaitable[None]] | None = None
+
+ def set_start(self, cb: Callable[[], Awaitable[None]] | None) -> None:
+ """Install a lazy-start callback invoked on first consumption."""
+ self._ensure_started = cb
+
+ def set_arequest_more(self, cb: Callable[[], Awaitable[bool]] | None) -> None:
+ """Wire the async pull callback iterators use to drive the source.
+
+ Mirrors `SyncProjection.set_request_more`. Under caller-driven
+ streaming, consumers call this callback when their buffer is
+ empty so that the owning graph advances one step.
+
+ Args:
+ cb: Async no-arg callable returning `True` when a new event
+ was produced, `False` when the source is exhausted. Pass
+ `None` to unwire.
+ """
+ self._arequest_more = cb
+
+ def push(self, delta: Any) -> None:
+ """Append a delta and notify waiters."""
+ super().push(delta)
+ self._event.set()
+
+ def complete(self, final_value: Any) -> None:
+ """Set the final value, mark done, and notify waiters."""
+ super().complete(final_value)
+ self._event.set()
+
+ def fail(self, error: BaseException) -> None:
+ """Mark errored and notify waiters."""
+ super().fail(error)
+ self._event.set()
+
+ # -- Async iterable (yields deltas) ------------------------------------
+
+ def __aiter__(self) -> _AsyncProjectionIterator:
+ """Return an async iterator over deltas."""
+ return _AsyncProjectionIterator(self)
+
+ # -- Awaitable (returns final value) -----------------------------------
+
+ def __await__(self) -> Generator[Any, None, Any]:
+ """Await the final accumulated value."""
+ return self._await_impl().__await__()
+
+ async def _await_impl(self) -> Any:
+ """Wait until the final value is set and return it.
+
+ When a caller-driven pump is wired via `set_arequest_more`, drive
+ it instead of blocking on `self._event`; otherwise fall back to
+ the event (used by tests that dispatch manually).
+ """
+ if self._ensure_started is not None:
+ await self._ensure_started()
+ while not self._final_set:
+ if self._error is not None:
+ raise self._error
+ if self._arequest_more is not None:
+ if not await self._arequest_more() and not self._final_set:
+ # Pump exhausted without completing this projection —
+ # nothing more will arrive. Return current state and
+ # let callers observe the missing final via the
+ # returned None / unset error.
+ break
+ else:
+ self._event.clear()
+ await self._event.wait()
+ if self._error is not None:
+ raise self._error
+ return self._final_value
+
+
+class _AsyncProjectionIterator:
+ """Async iterator over an `AsyncProjection`'s deltas."""
+
+ __slots__ = ("_offset", "_proj")
+
+ def __init__(self, proj: AsyncProjection) -> None:
+ """Initialize cursor at position 0."""
+ self._proj = proj
+ self._offset = 0
+
+ def __aiter__(self) -> _AsyncProjectionIterator:
+ """Return self for the async iteration protocol."""
+ return self
+
+ async def __anext__(self) -> Any:
+ """Return the next delta, awaiting if necessary.
+
+ When the projection has an `_arequest_more` pump wired, drain it
+ in an inner loop (mirrors `SyncProjection.__iter__`) until this
+ cursor advances or the pump reports exhaustion. Without a pump,
+ fall back to waiting on the shared event.
+ """
+ proj = self._proj
+ if proj._ensure_started is not None: # noqa: SLF001
+ await proj._ensure_started() # noqa: SLF001
+ while True:
+ # Direct access to the projection's internal list/event is
+ # intentional — the iterator is the projection's sidekick and
+ # depends on reading the shared buffer by cursor.
+ if self._offset < len(proj._deltas): # noqa: SLF001
+ item = proj._deltas[self._offset] # noqa: SLF001
+ self._offset += 1
+ return item
+ if proj.error is not None:
+ raise proj.error
+ if proj.done:
+ raise StopAsyncIteration
+ if proj._arequest_more is not None: # noqa: SLF001
+ # Caller-driven: drive the producer. Pump may land new
+ # deltas for a sibling projection — loop until our cursor
+ # advances, the projection terminates, or the pump is
+ # exhausted.
+ while (
+ self._offset >= len(proj._deltas) # noqa: SLF001
+ and not proj.done
+ ):
+ if not await proj._arequest_more(): # noqa: SLF001
+ break
+ if (
+ self._offset >= len(proj._deltas) # noqa: SLF001
+ and not proj.done
+ ):
+ if proj.error is not None:
+ raise proj.error
+ raise StopAsyncIteration
+ else:
+ proj._event.clear() # noqa: SLF001
+ await proj._event.wait() # noqa: SLF001
+
+
+# ---------------------------------------------------------------------------
+# Sync stream
+# ---------------------------------------------------------------------------
+
+
+class _ChatModelStreamBase:
+ """Shared state and event dispatch for chat-model streams.
+
+ Holds accumulated protocol state (text, reasoning, tool calls,
+ usage, metadata) and the event-dispatch machinery that drives the
+ typed projections. `ChatModelStream` (sync) and
+ `AsyncChatModelStream` (async) inherit from this base and add the
+ projection types and consumer APIs for their flavor.
+ """
+
+ # Projection instances — concrete subclasses create them as sync or
+ # async variants in their own __init__ after calling super().
+ _text_proj: _ProjectionBase
+ _reasoning_proj: _ProjectionBase
+ _tool_calls_proj: _ProjectionBase
+
+ def __init__(
+ self,
+ *,
+ namespace: list[str] | None = None,
+ node: str | None = None,
+ message_id: str | None = None,
+ ) -> None:
+ self._namespace = namespace or []
+ self._node = node
+ self._message_id = message_id
+
+ # Accumulated state
+ self._text_acc: str = ""
+ self._reasoning_acc: str = ""
+ # Per-block text / reasoning storage keyed by wire index. Used to
+ # populate the finalized block payload without cross-contaminating
+ # other blocks of the same type in the same message. Without
+ # per-block storage the message-wide accumulator would bleed
+ # earlier block text into later finalized blocks.
+ self._text_per_block: dict[int, str] = {}
+ self._reasoning_per_block: dict[int, str] = {}
+ self._tool_call_chunks: dict[int, dict[str, Any]] = {}
+ self._tool_calls_acc: list[ToolCall] = []
+ self._invalid_tool_calls_acc: list[InvalidToolCall] = []
+ self._server_tool_call_chunks: dict[int, dict[str, Any]] = {}
+ # Ordered snapshot of every finalized block, keyed by event index.
+ # Single source of truth for .output.content. Typed accumulators
+ # (text/reasoning/tool_calls/invalid_tool_calls) continue to serve
+ # the public projections.
+ self._blocks: dict[int, FinalizedContentBlock] = {}
+ self._usage_value: UsageInfo | None = None
+ self._start_metadata: MessageMetadata | None = None
+ self._finish_metadata: dict[str, Any] | None = None
+ self._done: bool = False
+ self._error: BaseException | None = None
+ self._output_message: AIMessage | None = None
+
+ # Raw event replay buffer
+ self._events: list[MessagesData] = []
+
+ # -- Common properties ------------------------------------------------
+
+ @property
+ def namespace(self) -> list[str]:
+ """Graph namespace path for this message."""
+ return self._namespace
+
+ @property
+ def node(self) -> str | None:
+ """Graph node that produced this message."""
+ return self._node
+
+ @property
+ def message_id(self) -> str | None:
+ """Stable message identifier."""
+ return self._message_id
+
+ def set_message_id(self, message_id: str) -> None:
+ """Assign the stable message identifier once the run starts.
+
+ Called by the stream driver (`stream_events(version="v3")` /
+ `astream_events(version="v3")`) after `on_chat_model_start` produces a run
+ id. Not intended for end-user code.
+ """
+ self._message_id = message_id
+
+ @property
+ def done(self) -> bool:
+ """Whether the stream has finished."""
+ return self._done
+
+ @property
+ def has_events(self) -> bool:
+ """Whether any protocol events have been recorded."""
+ return bool(self._events)
+
+ @property
+ def output_message(self) -> AIMessage | None:
+ """The assembled message if the stream has finished, else `None`.
+
+ Unlike `ChatModelStream.output` (which blocks until the stream
+ finishes), this never pumps, blocks, or raises. Intended for the
+ stream driver (`stream_events(version="v3")` and its async
+ equivalent) to check whether the stream produced a message before
+ firing `on_llm_end` callbacks.
+ """
+ return self._output_message
+
+ # -- Event ingestion (public) ------------------------------------------
+
+ def dispatch(self, event: Mapping[str, Any]) -> None:
+ """Route a protocol event to the appropriate internal handler.
+
+ Public entry point for feeding events into the stream. Called by
+ the stream driver (the `stream_events(version="v3")` pump and its
+ async equivalent) and by any observer or test that needs to
+ inject protocol events.
+ """
+ self._record_event(event)
+ event_type = event.get("event")
+ if event_type == "message-start":
+ self._push_message_start(cast("MessageStartData", event))
+ elif event_type == "content-block-delta":
+ self._push_content_block_delta(cast("ContentBlockDeltaData", event))
+ elif event_type == "content-block-finish":
+ self._push_content_block_finish(cast("ContentBlockFinishData", event))
+ elif event_type == "message-finish":
+ self._finish(cast("MessageFinishData", event))
+ elif event_type == "error":
+ self.fail(RuntimeError(event.get("message", "Unknown error")))
+ # content-block-start is informational — no accumulation needed
+
+ # -- Internal push API (called by dispatch) ----------------------------
+
+ def _record_event(self, event: Mapping[str, Any]) -> None:
+ """Append a raw event to the replay buffer."""
+ self._events.append(cast("MessagesData", event))
+
+ def _push_message_start(self, data: MessageStartData) -> None:
+ """Process a `message-start` event."""
+ self._start_metadata = data.get("metadata")
+ message_id = data.get("id")
+ if message_id:
+ self._message_id = message_id
+
+ def _push_content_block_delta(self, data: ContentBlockDeltaData) -> None:
+ """Process a `content-block-delta` event."""
+ delta = _event_delta(data)
+ if delta is None:
+ return
+ event_idx = data.get("index")
+ dtype = delta.get("type", "")
+
+ if dtype == "text-delta":
+ delta_text = delta.get("text", "")
+ if delta_text:
+ self._text_acc += delta_text
+ if event_idx is not None:
+ self._text_per_block[event_idx] = (
+ self._text_per_block.get(event_idx, "") + delta_text
+ )
+ self._text_proj.push(delta_text)
+ elif dtype == "reasoning-delta":
+ delta_r = delta.get("reasoning", "")
+ if delta_r:
+ self._reasoning_acc += delta_r
+ if event_idx is not None:
+ self._reasoning_per_block[event_idx] = (
+ self._reasoning_per_block.get(event_idx, "") + delta_r
+ )
+ self._reasoning_proj.push(delta_r)
+ elif dtype == "block-delta":
+ fields = delta.get("fields")
+ if not isinstance(fields, dict):
+ return
+ btype = fields.get("type", "")
+ if btype == "tool_call_chunk":
+ tcc = cast("ToolCallChunk", fields)
+ idx = data.get("index")
+ if idx is None:
+ idx = tcc.get("index", len(self._tool_call_chunks))
+ _merge_block_delta_into_store(self._tool_call_chunks, idx, dict(tcc))
+ chunk_block: ToolCallChunk = {
+ "type": "tool_call_chunk",
+ "id": tcc.get("id"),
+ "name": tcc.get("name"),
+ "args": tcc.get("args"),
+ }
+ if "index" in tcc:
+ chunk_block["index"] = tcc["index"]
+ self._tool_calls_proj.push(chunk_block)
+ elif btype == "server_tool_call_chunk":
+ stcc = cast("ServerToolCallChunk", fields)
+ idx = data.get("index")
+ if idx is None:
+ idx = len(self._server_tool_call_chunks)
+ _merge_block_delta_into_store(
+ self._server_tool_call_chunks,
+ idx,
+ dict(stcc),
+ )
+ elif dtype == "legacy-block-delta":
+ fields = delta.get("fields")
+ if not isinstance(fields, dict):
+ return
+ btype = fields.get("type", "")
+ if btype == "tool_call_chunk":
+ tcc = cast("ToolCallChunk", fields)
+ idx = data.get("index")
+ if idx is None:
+ idx = tcc.get("index", len(self._tool_call_chunks))
+ _merge_chunk_into_store(self._tool_call_chunks, idx, dict(tcc))
+ legacy_chunk_block: ToolCallChunk = {
+ "type": "tool_call_chunk",
+ "id": tcc.get("id"),
+ "name": tcc.get("name"),
+ "args": tcc.get("args"),
+ }
+ if "index" in tcc:
+ legacy_chunk_block["index"] = tcc["index"]
+ self._tool_calls_proj.push(legacy_chunk_block)
+ elif btype == "server_tool_call_chunk":
+ stcc = cast("ServerToolCallChunk", fields)
+ idx = data.get("index")
+ if idx is None:
+ idx = len(self._server_tool_call_chunks)
+ _merge_chunk_into_store(
+ self._server_tool_call_chunks,
+ idx,
+ dict(stcc),
+ )
+ elif dtype == "data-delta":
+ # Binary/modal payload deltas are reflected in the final
+ # content-block finish event; there is no dedicated projection.
+ return
+ else:
+ # Transitional legacy path for old `content_block` deltas that
+ # should not be reachable after `_event_delta` conversion, kept
+ # here for custom in-tree test fixtures or third-party emitters.
+ block = data.get("content_block")
+ if not isinstance(block, dict):
+ return
+ btype = block.get("type", "")
+ if btype != "tool_call_chunk":
+ return
+ tcc = cast("ToolCallChunk", block)
+ idx = data.get("index")
+ if idx is None:
+ idx = tcc.get("index", len(self._tool_call_chunks))
+ _merge_chunk_into_store(self._tool_call_chunks, idx, dict(tcc))
+ fallback_chunk_block: ToolCallChunk = {
+ "type": "tool_call_chunk",
+ "id": tcc.get("id"),
+ "name": tcc.get("name"),
+ "args": tcc.get("args"),
+ }
+ if "index" in tcc:
+ fallback_chunk_block["index"] = tcc["index"]
+ self._tool_calls_proj.push(fallback_chunk_block)
+
+ def _resolve_block_text(self, idx: int | None, full_text: str) -> str:
+ """Return authoritative text for a single text block at `idx`.
+
+ Prefers per-block delta accumulation; reconciles with the finish
+ event's `full_text` when the provider emits authoritative text
+ that differs from what the deltas built up.
+
+ Does not mutate `self._text_acc` (the delta-sum accumulator) —
+ the message-wide projection value is derived from per-block
+ storage at `_finish` time, so reconciliation remains correct
+ regardless of finish ordering across blocks.
+ """
+ if idx is None:
+ # No wire index — legacy behavior: use the message-wide
+ # accumulator. Preserved for pre-index semantics; not
+ # exercised by the compat bridge or any in-tree provider.
+ if full_text and full_text != self._text_acc:
+ self._text_acc = full_text
+ return self._text_acc
+ existing = self._text_per_block.get(idx, "")
+ if full_text and full_text != existing:
+ if not existing:
+ # No deltas arrived for this block — surface the full
+ # text as a single delta so the stream projection
+ # reflects it.
+ self._text_acc += full_text
+ self._text_proj.push(full_text)
+ elif full_text.startswith(existing):
+ # Authoritative text extends the partial deltas — emit
+ # the tail so delta consumers see the completion.
+ tail = full_text[len(existing) :]
+ self._text_acc += tail
+ self._text_proj.push(tail)
+ # else: authoritative text replaces the partial deltas
+ # entirely. No corrective delta is emitted (semantics
+ # would be ambiguous mid-stream). `_text_acc` is not
+ # spliced — the final value is computed from per-block
+ # storage at `_finish`, so this remains correct even when
+ # other blocks have added to `_text_acc` in between.
+ self._text_per_block[idx] = full_text
+ return self._text_per_block.get(idx, "")
+
+ def _resolve_block_reasoning(self, idx: int | None, full_r: str) -> str:
+ """Return authoritative reasoning text for a single block at `idx`.
+
+ Mirrors `_resolve_block_text` for the reasoning projection.
+ """
+ if idx is None:
+ if full_r and full_r != self._reasoning_acc:
+ self._reasoning_acc = full_r
+ return self._reasoning_acc
+ existing = self._reasoning_per_block.get(idx, "")
+ if full_r and full_r != existing:
+ if not existing:
+ self._reasoning_acc += full_r
+ self._reasoning_proj.push(full_r)
+ elif full_r.startswith(existing):
+ tail = full_r[len(existing) :]
+ self._reasoning_acc += tail
+ self._reasoning_proj.push(tail)
+ self._reasoning_per_block[idx] = full_r
+ return self._reasoning_per_block.get(idx, "")
+
+ def _push_content_block_finish(self, data: ContentBlockFinishData) -> None:
+ """Process a `content-block-finish` event."""
+ block = _event_content_block(data)
+ if block is None:
+ return
+ btype = block.get("type", "")
+ idx = data.get("index")
+ finalized: FinalizedContentBlock | None = None
+
+ if btype == "text":
+ text_block = cast("TextContentBlock", block)
+ full_text = text_block.get("text", "")
+ block_text = self._resolve_block_text(idx, full_text)
+ finalized = cast(
+ "FinalizedContentBlock",
+ {
+ **text_block,
+ "type": "text",
+ "text": block_text,
+ },
+ )
+ elif btype == "reasoning":
+ reasoning_block = cast("ReasoningContentBlock", block)
+ full_r = reasoning_block.get("reasoning", "")
+ block_reasoning = self._resolve_block_reasoning(idx, full_r)
+ # Keep provider-specific fields alongside the accumulated
+ # reasoning text. Anthropic's `signature` arrives under
+ # `extras` and is required on follow-up turns. Only overwrite
+ # `reasoning` when we have accumulated content; OpenAI can
+ # emit a reasoning block with no text deltas, and writing an
+ # empty string there makes downstream serializers synthesize
+ # an empty summary entry.
+ finalized_dict: dict[str, Any] = {**reasoning_block, "type": "reasoning"}
+ if block_reasoning:
+ finalized_dict["reasoning"] = block_reasoning
+ finalized = cast("FinalizedContentBlock", finalized_dict)
+ elif btype == "tool_call":
+ tcb = cast("ToolCall", block)
+ # Preserve provider-specific fields (extras, etc.) on the
+ # content block. `_assemble_message` separately projects the
+ # minimal {id, name, args, type} shape onto
+ # `AIMessage.tool_calls`. Strip `index` to match v1
+ # (`AIMessage.init_tool_calls` rebuilds the block without
+ # `index`); see `_finalize_block` in `_compat_bridge.py`.
+ tc = cast(
+ "ToolCall",
+ {
+ **{k: v for k, v in tcb.items() if k != "index"},
+ "type": "tool_call",
+ "id": tcb.get("id", ""),
+ "name": tcb.get("name", ""),
+ "args": tcb.get("args", {}),
+ },
+ )
+ self._tool_calls_acc.append(tc)
+ if idx is not None and idx in self._tool_call_chunks:
+ del self._tool_call_chunks[idx]
+ finalized = tc
+ elif btype == "invalid_tool_call":
+ itc = cast("InvalidToolCall", block)
+ # Strip `index` on the stored block to stay symmetric with
+ # the `tool_call` path.
+ itc = cast(
+ "InvalidToolCall",
+ {k: v for k, v in itc.items() if k != "index"},
+ )
+ self._invalid_tool_calls_acc.append(itc)
+ # Critical: drop the stale chunk so _finish's sweep doesn't revive
+ # it as an empty-args ToolCall.
+ if idx is not None and idx in self._tool_call_chunks:
+ del self._tool_call_chunks[idx]
+ if idx is not None and idx in self._server_tool_call_chunks:
+ del self._server_tool_call_chunks[idx]
+ finalized = itc
+ elif btype in (
+ "server_tool_call",
+ "server_tool_result",
+ "image",
+ "audio",
+ "video",
+ "file",
+ "non_standard",
+ ):
+ if btype == "server_tool_call" and idx is not None:
+ self._server_tool_call_chunks.pop(idx, None)
+ finalized = cast("FinalizedContentBlock", block)
+
+ if finalized is not None and idx is not None:
+ # Backfill the wire index onto the finalized block when the
+ # source didn't supply one. `langchain_core.utils._merge`'s
+ # block-merger (used by `AIMessageChunk.__add__` /
+ # `add_ai_message_chunks`) keys on `block["index"]` to group
+ # deltas into the same output block — without it, a v2-
+ # assembled `AIMessage` that later re-enters the chunk
+ # aggregation path won't merge cleanly. Client-side
+ # `tool_call` / `invalid_tool_call` blocks are excluded: v1
+ # finalization drops `index` on them so further deltas
+ # cannot clobber already-parsed args, and v2 mirrors that.
+ if btype not in ("tool_call", "invalid_tool_call"):
+ finalized.setdefault("index", idx)
+ self._blocks[idx] = finalized
+
+ def _finish(self, data: MessageFinishData) -> None:
+ """Process a `message-finish` event."""
+ self._done = True
+ self._usage_value = data.get("usage")
+ self._finish_metadata = cast("dict[str, Any] | None", data.get("metadata"))
+
+ # Finalize any unswept chunks — both client- and server-side.
+ _sweep_chunk_store(
+ self._tool_call_chunks,
+ finalized_type="tool_call",
+ finalized_blocks=self._blocks,
+ tool_calls_acc=self._tool_calls_acc,
+ invalid_acc=self._invalid_tool_calls_acc,
+ )
+ _sweep_chunk_store(
+ self._server_tool_call_chunks,
+ finalized_type="server_tool_call",
+ finalized_blocks=self._blocks,
+ tool_calls_acc=None,
+ invalid_acc=self._invalid_tool_calls_acc,
+ )
+
+ # Prefer the per-block sum when any indexed text / reasoning
+ # arrived — it stays correct regardless of finish ordering and
+ # of whether finish events carried authoritative text that
+ # differed from the deltas. Fall back to the delta-sum
+ # accumulator only for the legacy no-index path.
+ if self._text_per_block:
+ text_final = "".join(
+ self._text_per_block[i] for i in sorted(self._text_per_block)
+ )
+ else:
+ text_final = self._text_acc
+ if self._reasoning_per_block:
+ reasoning_final = "".join(
+ self._reasoning_per_block[i] for i in sorted(self._reasoning_per_block)
+ )
+ else:
+ reasoning_final = self._reasoning_acc
+
+ self._text_proj.complete(text_final)
+ self._reasoning_proj.complete(reasoning_final)
+ self._tool_calls_proj.complete(self._tool_calls_acc)
+ self._output_message = self._assemble_message()
+
+ def fail(self, error: BaseException) -> None:
+ """Mark the stream as errored and propagate to all projections.
+
+ Public API — called by the stream driver (`stream_events(version="v3")` /
+ `astream_events(version="v3")`) when the underlying producer raises, by
+ `dispatch` when an `error` protocol event arrives, and by
+ cancellation paths.
+ """
+ self._done = True
+ self._error = error
+ self._text_proj.fail(error)
+ self._reasoning_proj.fail(error)
+ self._tool_calls_proj.fail(error)
+
+ def _assemble_message(self) -> AIMessage:
+ """Build an `AIMessage` from accumulated state.
+
+ Content is built from `self._blocks`, an index-ordered snapshot of
+ finalized protocol blocks. The bare-string fast path is used when
+ the message has exactly one `text` block (the common chat case);
+ otherwise content is a list of protocol-shape block dicts.
+ """
+ content: Any
+ if not self._blocks:
+ # No protocol blocks ever arrived. Fall back to the accumulated
+ # text (possibly empty) as bare-string content.
+ content = self._text_acc
+ else:
+ # `ChatModelStream` is the v1 content-block surface: content
+ # is always a list of protocol blocks when any block arrived.
+ # Do not collapse a single text block down to a bare string —
+ # that would drop block-level fields (`id`, `index`,
+ # annotations, extras) that downstream serializers need to
+ # round-trip the message on a follow-up turn.
+ ordered_blocks = [self._blocks[idx] for idx in sorted(self._blocks)]
+ content = [dict(b) for b in ordered_blocks]
+
+ response_metadata: dict[str, Any] = {}
+ if self._start_metadata:
+ if "provider" in self._start_metadata:
+ response_metadata["model_provider"] = self._start_metadata["provider"]
+ if "model" in self._start_metadata:
+ response_metadata["model_name"] = self._start_metadata["model"]
+ if self._finish_metadata:
+ response_metadata.update(self._finish_metadata)
+ # Pin `output_version` last: `stream_events(version="v3")` always
+ # assembles content as v1 protocol blocks, regardless of the
+ # provider's configured output format.
+ # A provider-supplied `output_version` in finish metadata (e.g.
+ # `"responses/v1"` from `ChatOpenAI(use_responses_api=True, ...)`) would
+ # otherwise cause `AIMessage.content_blocks` to re-run the wrong
+ # translator on already-v1 content.
+ response_metadata["output_version"] = "v1"
+
+ tool_calls = [
+ {
+ "id": tc.get("id", ""),
+ "name": tc.get("name", ""),
+ "args": tc.get("args", {}),
+ "type": "tool_call",
+ }
+ for tc in self._tool_calls_acc
+ ]
+
+ invalid_tool_calls = [
+ {
+ "type": "invalid_tool_call",
+ "id": itc.get("id") or None,
+ "name": itc.get("name") or None,
+ "args": itc.get("args") or None,
+ "error": itc.get("error"),
+ }
+ for itc in self._invalid_tool_calls_acc
+ ]
+
+ return AIMessage(
+ content=content,
+ id=self._message_id,
+ tool_calls=tool_calls,
+ invalid_tool_calls=invalid_tool_calls,
+ usage_metadata=self._usage_value,
+ response_metadata=response_metadata,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Sync stream
+# ---------------------------------------------------------------------------
+
+
+class ChatModelStream(_ChatModelStreamBase):
+ """Synchronous per-message streaming object for a single LLM response.
+
+ Returned by `BaseChatModel.stream_events(version="v3")`. Content-block protocol
+ events are fed into this object and accumulated into typed projections.
+
+ Projections (always return the same cached object):
+
+ - `.text` — iterable of `str` deltas; `str()` for full text
+ - `.reasoning` — same as `.text` for reasoning content
+ - `.tool_calls` — iterable of `ToolCallChunk` deltas;
+ `.get()` returns `list[ToolCall]`
+ - `.output` — blocking property, returns assembled `AIMessage`
+
+ Usage info is available on `.output.usage_metadata` once the stream
+ has finished.
+
+ !!! note "Output shape is always v1 content blocks"
+
+ `.output.content` is always a list of v1 protocol blocks
+ (text, reasoning, tool_call, image, …), regardless of the
+ underlying model's `output_version` setting. That attribute
+ only controls the legacy `stream()` / `astream()` / `invoke()`
+ paths; `ChatModelStream` is built on the content-block
+ protocol and emits v1 shapes by construction.
+
+ Raw event iteration::
+
+ for event in stream:
+ print(event) # MessagesData dicts
+ """
+
+ _text_proj: SyncTextProjection
+ _reasoning_proj: SyncTextProjection
+ _tool_calls_proj: SyncProjection
+
+ def __init__( # noqa: D107
+ self,
+ *,
+ namespace: list[str] | None = None,
+ node: str | None = None,
+ message_id: str | None = None,
+ ) -> None:
+ super().__init__(namespace=namespace, node=node, message_id=message_id)
+ # Projections — created eagerly
+ self._text_proj = SyncTextProjection()
+ self._reasoning_proj = SyncTextProjection()
+ self._tool_calls_proj = SyncProjection()
+ # Pull callback (set by bind_pump or set_request_more)
+ self._ensure_started: Callable[[], None] | None = None
+ self._request_more: Callable[[], bool] | None = None
+
+ # -- Pump/pull wiring --------------------------------------------------
+
+ def bind_pump(self, pump_one: Callable[[], bool]) -> None:
+ """Bind a pump for standalone streaming.
+
+ Delegates to `set_request_more`. Used by
+ `BaseChatModel.stream_events(version="v3")`.
+ """
+ self.set_request_more(pump_one)
+
+ def set_start(self, cb: Callable[[], None] | None) -> None:
+ """Install a lazy-start callback on this stream and its projections."""
+ self._ensure_started = cb
+ self._text_proj.set_start(cb)
+ self._reasoning_proj.set_start(cb)
+ self._tool_calls_proj.set_start(cb)
+
+ def set_request_more(self, cb: Callable[[], bool]) -> None:
+ """Set the pull callback on this stream and all its projections.
+
+ Used by langgraph's `GraphRunStream._wire_request_more` to
+ connect the shared graph pump.
+ """
+ self._request_more = cb
+ self._text_proj.set_request_more(cb)
+ self._reasoning_proj.set_request_more(cb)
+ self._tool_calls_proj.set_request_more(cb)
+
+ # -- Public projections ------------------------------------------------
+
+ @property
+ def text(self) -> SyncTextProjection:
+ """Text content — iterable of `str` deltas, `str()` for full."""
+ return self._text_proj
+
+ @property
+ def reasoning(self) -> SyncTextProjection:
+ """Reasoning content — same interface as :attr:`text`."""
+ return self._reasoning_proj
+
+ @property
+ def tool_calls(self) -> SyncProjection:
+ """Tool calls — iterable of `ToolCallChunk` deltas.
+
+ `.get()` returns finalized `list[ToolCall]`.
+ """
+ return self._tool_calls_proj
+
+ @property
+ def output(self) -> AIMessage:
+ """Assembled `AIMessage` — blocks until the stream finishes."""
+ self._drain()
+ if self._error is not None:
+ raise self._error
+ if self._output_message is None:
+ msg = "Stream finished without producing a message"
+ raise RuntimeError(msg)
+ return self._output_message
+
+ # -- Raw event iteration (replay buffer) -------------------------------
+
+ def __iter__(self) -> Iterator[MessagesData]:
+ """Iterate raw protocol events with replay-buffer semantics."""
+ if self._ensure_started is not None:
+ self._ensure_started()
+ cursor = 0
+ while True:
+ if cursor < len(self._events):
+ yield self._events[cursor]
+ cursor += 1
+ elif self._error is not None:
+ raise self._error
+ elif self._done:
+ return
+ elif self._request_more is not None:
+ while cursor >= len(self._events) and not self._done:
+ if not self._request_more():
+ break
+ if cursor >= len(self._events):
+ if self._error is not None:
+ raise self._error
+ return
+ else:
+ return
+
+ # -- Internal helpers --------------------------------------------------
+
+ def _drain(self) -> None:
+ """Pull all remaining events until done."""
+ if self._done:
+ return
+ if self._ensure_started is not None:
+ self._ensure_started()
+ if self._request_more is not None:
+ while not self._done:
+ if not self._request_more():
+ break
+
+
+# ---------------------------------------------------------------------------
+# Async stream
+# ---------------------------------------------------------------------------
+
+
+class AsyncChatModelStream(_ChatModelStreamBase):
+ """Asynchronous per-message streaming object for a single LLM response.
+
+ Returned by `BaseChatModel.astream_events(version="v3")`. Content-block events
+ are fed into this object by a background producer task.
+
+ Projections:
+
+ - `.text` — async iterable of text deltas; awaitable for full text
+ - `.reasoning` — async iterable of reasoning deltas; awaitable
+ - `.tool_calls` — async iterable of `ToolCallChunk` deltas;
+ awaitable for `list[ToolCall]`
+ - `.output` — awaitable for assembled `AIMessage`
+
+ Usage info is available on `.output.usage_metadata` once the stream
+ has finished.
+
+ !!! note "Output shape is always v1 content blocks"
+
+ The assembled message's content is always a list of v1
+ protocol blocks, regardless of the model's `output_version`
+ setting — see `ChatModelStream` for the full rationale.
+
+ The stream itself is awaitable (`msg = await stream`) and
+ async-iterable (`async for event in stream`).
+ """
+
+ _text_proj: AsyncProjection
+ _reasoning_proj: AsyncProjection
+ _tool_calls_proj: AsyncProjection
+
+ def __init__( # noqa: D107
+ self,
+ *,
+ namespace: list[str] | None = None,
+ node: str | None = None,
+ message_id: str | None = None,
+ ) -> None:
+ super().__init__(namespace=namespace, node=node, message_id=message_id)
+ self._text_proj = AsyncProjection()
+ self._reasoning_proj = AsyncProjection()
+ self._tool_calls_proj = AsyncProjection()
+ self._output_proj = AsyncProjection()
+ self._events_proj = AsyncProjection()
+ self._ensure_started: Callable[[], Awaitable[None]] | None = None
+ self._producer_task: asyncio.Task[None] | None = None
+ # Teardown callback invoked by `aclose()` only when the producer
+ # task was cancelled before its body ran (so the normal
+ # `_produce` CancelledError handler — which fires
+ # `on_llm_error` — never executed). Set by `astream_events(version="v3")`.
+ self._on_aclose_fail: Callable[[BaseException], Awaitable[None]] | None = None
+
+ # -- Pump/pull wiring (async) ------------------------------------------
+
+ def set_arequest_more(self, cb: Callable[[], Awaitable[bool]] | None) -> None:
+ """Fan the async pump callback out to every projection.
+
+ Used by langgraph's `AsyncGraphRunStream._wire_arequest_more` so
+ cursors on `stream.text`, `stream.reasoning`, etc. can drive the
+ shared graph pump when their buffer is empty.
+
+ Args:
+ cb: Async no-arg callable returning `True` when a new event
+ was produced, `False` when the source is exhausted. Pass
+ `None` to unwire.
+ """
+ for proj in (
+ self._text_proj,
+ self._reasoning_proj,
+ self._tool_calls_proj,
+ self._output_proj,
+ self._events_proj,
+ ):
+ proj.set_arequest_more(cb)
+
+ def set_start(self, cb: Callable[[], Awaitable[None]] | None) -> None:
+ """Install a lazy-start callback on this stream and its projections."""
+ self._ensure_started = cb
+ for proj in (
+ self._text_proj,
+ self._reasoning_proj,
+ self._tool_calls_proj,
+ self._output_proj,
+ self._events_proj,
+ ):
+ proj.set_start(cb)
+
+ # -- Public projections ------------------------------------------------
+
+ @property
+ def text(self) -> AsyncProjection:
+ """Text content — async iterable of deltas, awaitable for full."""
+ return self._text_proj
+
+ @property
+ def reasoning(self) -> AsyncProjection:
+ """Reasoning content — same interface as :attr:`text`."""
+ return self._reasoning_proj
+
+ @property
+ def tool_calls(self) -> AsyncProjection:
+ """Tool calls — async iterable, awaitable for finalized list."""
+ return self._tool_calls_proj
+
+ @property
+ def output(self) -> AsyncProjection:
+ """Assembled `AIMessage` — awaitable."""
+ return self._output_proj
+
+ def __await__(self) -> Generator[Any, None, AIMessage]:
+ """Await the assembled `AIMessage` and full producer lifecycle.
+
+ The producer task is awaited after the output projection resolves so
+ that post-stream work (notably `on_llm_end` callbacks) has run by
+ the time the caller's `await` returns.
+ """
+ return self._await_full().__await__()
+
+ async def _await_full(self) -> AIMessage:
+ if self._ensure_started is not None:
+ await self._ensure_started()
+ message: AIMessage = await self._output_proj
+ if self._producer_task is not None:
+ await self._producer_task
+ return message
+
+ def __aiter__(self) -> _AsyncProjectionIterator:
+ """Iterate raw protocol events asynchronously."""
+ return _AsyncProjectionIterator(self._events_proj)
+
+ # -- Cleanup -----------------------------------------------------------
+
+ async def aclose(self) -> None:
+ """Cancel the background producer task and release resources.
+
+ If a consumer cancels mid-stream or decides to stop iterating
+ early, the producer task keeps pumping the provider HTTP call to
+ completion because `asyncio.Task` has no implicit link to its
+ awaiter. Call this method to cancel the producer explicitly; the
+ stream transitions to an errored state with `CancelledError`.
+
+ If the stream has already produced a message successfully (for
+ example, after `await stream.output`), the producer may still be
+ running post-stream work such as `on_llm_end` callbacks. In that
+ case `aclose()` awaits the task rather than cancelling it —
+ turning a successful run into a cancelled one would drop the
+ end callback and corrupt tracing.
+
+ Idempotent: safe to call multiple times, including after the
+ stream has finished normally. Also invoked by the async context
+ manager protocol on `__aexit__`.
+ """
+ if self._ensure_started is not None and self._producer_task is None:
+ await self._ensure_started()
+
+ task = self._producer_task
+ if task is None:
+ return
+ if task.done() and self._done:
+ return
+
+ we_cancelled = not (self._output_message is not None and self._error is None)
+ if we_cancelled and not task.done():
+ task.cancel()
+
+ # Wait for the task via a linked `Future`, not by awaiting the
+ # task directly. Awaiting the task would raise `CancelledError`
+ # in two indistinguishable cases: (1) the task we just cancelled
+ # completed, (2) our caller cancelled us. `asyncio.Task.cancelling()`
+ # disambiguates on 3.11+ but doesn't exist on 3.10.
+ #
+ # The `done_future` resolves with `None` whenever the task
+ # finishes (any reason). It is not a `Task` itself, so its
+ # `await` only raises when our caller is cancelled — giving us
+ # a portable, unambiguous signal to propagate.
+ if not task.done():
+ loop = asyncio.get_running_loop()
+ done_future: asyncio.Future[None] = loop.create_future()
+
+ def _link(_: asyncio.Task[None]) -> None:
+ if not done_future.done():
+ done_future.set_result(None)
+
+ task.add_done_callback(_link)
+ try:
+ await done_future
+ finally:
+ task.remove_done_callback(_link)
+
+ # If the task was cancelled before `_produce` ran (e.g.
+ # `astream_events(version="v3")` immediately followed by `aclose()`), the stream
+ # never reached `_produce`'s CancelledError handler — its
+ # projections are still pending and no end-of-lifecycle callback
+ # has fired. Resolve both here so callers of `await stream.output`
+ # don't hang and tracing sees a matching end event.
+ if we_cancelled and not self._done:
+ cancel_exc = asyncio.CancelledError()
+ self.fail(cancel_exc)
+ teardown = self._on_aclose_fail
+ if teardown is not None:
+ with contextlib.suppress(Exception):
+ await teardown(cancel_exc)
+
+ async def __aenter__(self) -> Self:
+ """Enter the async context — returns self."""
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ tb: object,
+ ) -> None:
+ """Exit the async context — cancels the producer via `aclose()`."""
+ del exc_type, exc, tb
+ await self.aclose()
+
+ # -- Internal API (extend base to drive async projections) -------------
+
+ def _record_event(self, event: Mapping[str, Any]) -> None:
+ """Record event and push to async event replay projection."""
+ super()._record_event(event)
+ self._events_proj.push(cast("MessagesData", event))
+
+ def _finish(self, data: MessageFinishData) -> None:
+ """Finish base projections and async-only projections."""
+ super()._finish(data)
+ self._output_proj.complete(self._output_message)
+ self._events_proj.complete(self._events)
+
+ def fail(self, error: BaseException) -> None:
+ """Fail base projections and async-only projections."""
+ super().fail(error)
+ self._output_proj.fail(error)
+ self._events_proj.fail(error)
+
+
+__all__ = [
+ "AsyncChatModelStream",
+ "AsyncProjection",
+ "ChatModelStream",
+ "SyncProjection",
+ "SyncTextProjection",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/chat_models.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/chat_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea4194e69cda42505e2832b1f5f6ab6a7f6171a7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/chat_models.py
@@ -0,0 +1,2675 @@
+"""Chat models for conversational AI."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import inspect
+import json
+from abc import ABC, abstractmethod
+from collections.abc import AsyncIterator, Callable, Iterator, Sequence
+from functools import cached_property
+from operator import itemgetter
+from typing import TYPE_CHECKING, Any, Literal, cast, overload
+
+from langchain_protocol.protocol import MessageFinishData
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+from typing_extensions import Self, override
+
+from langchain_core._api import beta
+from langchain_core.caches import BaseCache
+from langchain_core.callbacks import (
+ AsyncCallbackManager,
+ AsyncCallbackManagerForLLMRun,
+ CallbackManager,
+ CallbackManagerForLLMRun,
+ Callbacks,
+)
+from langchain_core.globals import get_llm_cache
+from langchain_core.language_models._compat_bridge import (
+ achunks_to_events,
+ amessage_to_events,
+ chunks_to_events,
+ message_to_events,
+)
+from langchain_core.language_models._utils import (
+ _filter_invocation_params_for_tracing,
+ _normalize_messages,
+ _update_message_content_to_blocks,
+)
+from langchain_core.language_models.base import (
+ BaseLanguageModel,
+ LangSmithParams,
+ LanguageModelInput,
+)
+from langchain_core.language_models.chat_model_stream import (
+ AsyncChatModelStream,
+ ChatModelStream,
+)
+from langchain_core.language_models.model_profile import (
+ ModelProfile,
+ _warn_unknown_profile_keys,
+)
+from langchain_core.load import dumpd, dumps
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ AnyMessage,
+ BaseMessage,
+ convert_to_messages,
+ is_data_content_block,
+ message_chunk_to_message,
+)
+from langchain_core.messages import content as types
+from langchain_core.messages.block_translators.openai import (
+ convert_to_openai_image_block,
+)
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ PydanticToolsParser,
+)
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ ChatResult,
+ Generation,
+ LLMResult,
+ RunInfo,
+)
+from langchain_core.outputs.chat_generation import merge_chat_generation_chunks
+from langchain_core.prompt_values import ChatPromptValue, PromptValue, StringPromptValue
+from langchain_core.rate_limiters import BaseRateLimiter
+from langchain_core.runnables import RunnableBinding, RunnableMap, RunnablePassthrough
+from langchain_core.runnables.config import ensure_config, run_in_executor
+from langchain_core.tracers._streaming import (
+ _StreamingCallbackHandler,
+ _V2StreamingCallbackHandler,
+)
+from langchain_core.utils.function_calling import (
+ convert_to_json_schema,
+ convert_to_openai_tool,
+)
+from langchain_core.utils.pydantic import TypeBaseModel, is_basemodel_subclass
+from langchain_core.utils.utils import LC_ID_PREFIX, from_env
+
+if TYPE_CHECKING:
+ import builtins
+ import uuid
+ from collections.abc import Awaitable
+
+ from langchain_protocol.protocol import MessagesData
+
+ from langchain_core.output_parsers.base import OutputParserLike
+ from langchain_core.runnables import Runnable, RunnableConfig
+ from langchain_core.runnables.schema import StreamEvent
+ from langchain_core.tools import BaseTool
+
+
+def _generate_response_from_error(error: BaseException) -> list[ChatGeneration]:
+ if hasattr(error, "response"):
+ response = error.response
+ metadata: dict = {}
+ if hasattr(response, "json"):
+ try:
+ metadata["body"] = response.json()
+ except Exception:
+ try:
+ metadata["body"] = getattr(response, "text", None)
+ except Exception:
+ metadata["body"] = None
+ if hasattr(response, "headers"):
+ try:
+ metadata["headers"] = dict(response.headers)
+ except Exception:
+ metadata["headers"] = None
+ if hasattr(response, "status_code"):
+ metadata["status_code"] = response.status_code
+ if hasattr(error, "request_id"):
+ metadata["request_id"] = error.request_id
+ generations = [
+ ChatGeneration(message=AIMessage(content="", response_metadata=metadata))
+ ]
+ else:
+ generations = []
+
+ return generations
+
+
+def _format_for_tracing(messages: list[BaseMessage]) -> list[BaseMessage]:
+ """Format messages for tracing in `on_chat_model_start`.
+
+ - Update image content blocks to OpenAI Chat Completions format (backward
+ compatibility).
+ - Add `type` key to content blocks that have a single key.
+
+ Args:
+ messages: List of messages to format.
+
+ Returns:
+ List of messages formatted for tracing.
+
+ """
+ messages_to_trace = []
+ for message in messages:
+ message_to_trace = message
+ if isinstance(message.content, list):
+ for idx, block in enumerate(message.content):
+ if isinstance(block, dict):
+ # Update image content blocks to OpenAI # Chat Completions format.
+ if (
+ block.get("type") == "image"
+ and is_data_content_block(block)
+ and not ("file_id" in block or block.get("source_type") == "id")
+ ):
+ if message_to_trace is message:
+ # Shallow copy
+ message_to_trace = message.model_copy()
+ message_to_trace.content = list(message_to_trace.content)
+
+ message_to_trace.content[idx] = ( # type: ignore[index] # mypy confused by .model_copy
+ convert_to_openai_image_block(block)
+ )
+ elif (
+ block.get("type") == "file"
+ and is_data_content_block(block) # v0 (image/audio/file) or v1
+ and "base64" in block
+ # Backward compat: convert v1 base64 blocks to v0
+ ):
+ if message_to_trace is message:
+ # Shallow copy
+ message_to_trace = message.model_copy()
+ message_to_trace.content = list(message_to_trace.content)
+
+ message_to_trace.content[idx] = { # type: ignore[index]
+ **{k: v for k, v in block.items() if k != "base64"},
+ "data": block["base64"],
+ "source_type": "base64",
+ }
+ elif len(block) == 1 and "type" not in block:
+ # Tracing assumes all content blocks have a "type" key. Here
+ # we add this key if it is missing, and there's an obvious
+ # choice for the type (e.g., a single key in the block).
+ if message_to_trace is message:
+ # Shallow copy
+ message_to_trace = message.model_copy()
+ message_to_trace.content = list(message_to_trace.content)
+ key = next(iter(block))
+ message_to_trace.content[idx] = { # type: ignore[index]
+ "type": key,
+ key: block[key],
+ }
+ messages_to_trace.append(message_to_trace)
+
+ return messages_to_trace
+
+
+def generate_from_stream(stream: Iterator[ChatGenerationChunk]) -> ChatResult:
+ """Generate from a stream.
+
+ Args:
+ stream: Iterator of `ChatGenerationChunk`.
+
+ Raises:
+ ValueError: If no generations are found in the stream.
+
+ Returns:
+ Chat result.
+
+ """
+ generation = next(stream, None)
+ if generation:
+ generation += list(stream)
+ if generation is None:
+ msg = "No generations found in stream."
+ raise ValueError(msg)
+ return ChatResult(
+ generations=[
+ ChatGeneration(
+ message=message_chunk_to_message(generation.message),
+ generation_info=generation.generation_info,
+ )
+ ]
+ )
+
+
+async def agenerate_from_stream(
+ stream: AsyncIterator[ChatGenerationChunk],
+) -> ChatResult:
+ """Async generate from a stream.
+
+ Args:
+ stream: AsyncIterator of `ChatGenerationChunk`.
+
+ Returns:
+ Chat result.
+
+ """
+ chunks = [chunk async for chunk in stream]
+ return await run_in_executor(None, generate_from_stream, iter(chunks))
+
+
+def _format_ls_structured_output(ls_structured_output_format: dict | None) -> dict:
+ if ls_structured_output_format:
+ try:
+ ls_structured_output_format_dict = {
+ "ls_structured_output_format": {
+ "kwargs": ls_structured_output_format.get("kwargs", {}),
+ "schema": convert_to_json_schema(
+ ls_structured_output_format["schema"]
+ ),
+ }
+ }
+ except ValueError:
+ ls_structured_output_format_dict = {}
+ else:
+ ls_structured_output_format_dict = {}
+
+ return ls_structured_output_format_dict
+
+
+class BaseChatModel(BaseLanguageModel[AIMessage], ABC):
+ r"""Base class for chat models.
+
+ Key imperative methods:
+ Methods that actually call the underlying model.
+
+ This table provides a brief overview of the main imperative methods. Please see the base `Runnable` reference for full documentation.
+
+ | Method | Input | Output | Description |
+ | ---------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- | -------------------------------------------------------------------------------- |
+ | `invoke` | `str` \| `list[dict | tuple | BaseMessage]` \| `PromptValue` | `BaseMessage` | A single chat model call. |
+ | `ainvoke` | `'''` | `BaseMessage` | Defaults to running `invoke` in an async executor. |
+ | `stream` | `'''` | `Iterator[BaseMessageChunk]` | Defaults to yielding output of `invoke`. |
+ | `astream` | `'''` | `AsyncIterator[BaseMessageChunk]` | Defaults to yielding output of `ainvoke`. |
+ | `astream_events` | `'''` | `AsyncIterator[StreamEvent]` | Event types: `on_chat_model_start`, `on_chat_model_stream`, `on_chat_model_end`. |
+ | `batch` | `list[''']` | `list[BaseMessage]` | Defaults to running `invoke` in concurrent threads. |
+ | `abatch` | `list[''']` | `list[BaseMessage]` | Defaults to running `ainvoke` in concurrent threads. |
+ | `batch_as_completed` | `list[''']` | `Iterator[tuple[int, Union[BaseMessage, Exception]]]` | Defaults to running `invoke` in concurrent threads. |
+ | `abatch_as_completed` | `list[''']` | `AsyncIterator[tuple[int, Union[BaseMessage, Exception]]]` | Defaults to running `ainvoke` in concurrent threads. |
+
+ Key declarative methods:
+ Methods for creating another `Runnable` using the chat model.
+
+ This table provides a brief overview of the main declarative methods. Please see the reference for each method for full documentation.
+
+ | Method | Description |
+ | ---------------------------- | ------------------------------------------------------------------------------------------ |
+ | `bind_tools` | Create chat model that can call tools. |
+ | `with_structured_output` | Create wrapper that structures model output using schema. |
+ | `with_retry` | Create wrapper that retries model calls on failure. |
+ | `with_fallbacks` | Create wrapper that falls back to other models on failure. |
+ | `configurable_fields` | Specify init args of the model that can be configured at runtime via the `RunnableConfig`. |
+ | `configurable_alternatives` | Specify alternative models which can be swapped in at runtime via the `RunnableConfig`. |
+
+ Creating custom chat model:
+ Custom chat model implementations should inherit from this class.
+ Please reference the table below for information about which
+ methods and properties are required or optional for implementations.
+
+ | Method/Property | Description | Required |
+ | -------------------------------- | ------------------------------------------------------------------ | ----------------- |
+ | `_generate` | Use to generate a chat result from a prompt | Required |
+ | `_llm_type` (property) | Used to uniquely identify the type of the model. Used for logging. | Required |
+ | `_identifying_params` (property) | Represent model parameterization for tracing purposes. | Optional |
+ | `_stream` | Use to implement streaming | Optional |
+ | `_agenerate` | Use to implement a native async method | Optional |
+ | `_astream` | Use to implement async version of `_stream` | Optional |
+
+ """ # noqa: E501
+
+ rate_limiter: BaseRateLimiter | None = Field(default=None, exclude=True)
+ "An optional rate limiter to use for limiting the number of requests."
+
+ disable_streaming: bool | Literal["tool_calling"] = False
+ """Whether to disable streaming for this model.
+
+ If streaming is bypassed, then `stream`/`astream`/`astream_events` will
+ defer to `invoke`/`ainvoke`.
+
+ - If `True`, will always bypass streaming case.
+ - If `'tool_calling'`, will bypass streaming case only when the model is called
+ with a `tools` keyword argument. In other words, LangChain will automatically
+ switch to non-streaming behavior (`invoke`) only when the tools argument is
+ provided. This offers the best of both worlds.
+ - If `False` (Default), will always use streaming case if available.
+
+ The main reason for this flag is that code might be written using `stream` and
+ a user may want to swap out a given model for another model whose implementation
+ does not properly support streaming.
+ """
+
+ output_version: str | None = Field(
+ default_factory=from_env("LC_OUTPUT_VERSION", default=None)
+ )
+ """Version of `AIMessage` output format to store in message content.
+
+ `AIMessage.content_blocks` will lazily parse the contents of `content` into a
+ standard format. This flag can be used to additionally store the standard format
+ in message content, e.g., for serialization purposes.
+
+ Supported values:
+
+ - `'v0'`: provider-specific format in content (can lazily-parse with
+ `content_blocks`)
+ - `'v1'`: standardized format in content (consistent with `content_blocks`)
+
+ Partner packages (e.g.,
+ [`langchain-openai`](https://pypi.org/project/langchain-openai)) can also use this
+ field to roll out new content formats in a backward-compatible way.
+
+ !!! version-added "Added in `langchain-core` 1.0.0"
+
+ """
+
+ profile: ModelProfile | None = Field(default=None, exclude=True)
+ """Profile detailing model capabilities.
+
+ !!! warning "Beta feature"
+
+ This is a beta feature. The format of model profiles is subject to change.
+
+ If not specified, automatically loaded from the provider package on initialization
+ if data is available.
+
+ Example profile data includes context window sizes, supported modalities, or support
+ for tool calling, structured output, and other features.
+
+ !!! version-added "Added in `langchain-core` 1.1.0"
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ def _resolve_model_profile(self) -> ModelProfile | None:
+ """Return the default model profile, or `None` if unavailable.
+
+ Override this in subclasses instead of `_set_model_profile`. The base
+ validator calls it automatically and handles assignment. This avoids
+ coupling partner code to Pydantic validator mechanics.
+
+ Each partner needs its own override because things can vary per-partner,
+ such as the attribute that identifies the model (e.g., `model`,
+ `model_name`, `model_id`, `deployment_name`) and the partner-local
+ `_get_default_model_profile` function that reads from each partner's own
+ profile data.
+ """
+ # TODO: consider adding a `_model_identifier` property on BaseChatModel
+ # to standardize how partners identify their model, which could allow a
+ # default implementation here that calls a shared
+ # profile-loading mechanism.
+ return None
+
+ @model_validator(mode="after")
+ def _set_model_profile(self) -> Self:
+ """Populate `profile` from `_resolve_model_profile` if not provided.
+
+ Partners should override `_resolve_model_profile` rather than this
+ validator. Overriding this with a new `@model_validator` replaces the
+ base validator (Pydantic v2 behavior), bypassing the standard resolution
+ path. A plain method override does not prevent the base validator from
+ running.
+ """
+ if self.profile is None:
+ # Suppress errors from partner overrides (e.g., missing profile
+ # files, broken imports) so model construction never fails over an
+ # optional field.
+ with contextlib.suppress(Exception):
+ self.profile = self._resolve_model_profile()
+ return self
+
+ # NOTE: _check_profile_keys must be defined AFTER _set_model_profile.
+ # Pydantic v2 runs mode="after" validators in definition order.
+ @model_validator(mode="after")
+ def _check_profile_keys(self) -> Self:
+ """Warn on unrecognized profile keys."""
+ # isinstance guard: ModelProfile is a TypedDict (always a dict), but
+ # protects against unexpected types from partner overrides.
+ if self.profile and isinstance(self.profile, dict):
+ _warn_unknown_profile_keys(self.profile)
+ return self
+
+ @cached_property
+ def _serialized(self) -> dict[str, Any]:
+ # self is always a Serializable object in this case, thus the result is
+ # guaranteed to be a dict since dumps uses the default callback, which uses
+ # obj.to_json which always returns TypedDict subclasses
+ return cast("dict[str, Any]", dumpd(self))
+
+ # --- Runnable methods ---
+
+ @property
+ @override
+ def OutputType(self) -> Any:
+ """Get the output type for this `Runnable`."""
+ return AnyMessage
+
+ def _convert_input(self, model_input: LanguageModelInput) -> PromptValue:
+ if isinstance(model_input, PromptValue):
+ return model_input
+ if isinstance(model_input, str):
+ return StringPromptValue(text=model_input)
+ if isinstance(model_input, Sequence):
+ return ChatPromptValue(messages=convert_to_messages(model_input))
+ msg = (
+ f"Invalid input type {type(model_input)}. "
+ "Must be a PromptValue, str, or list of BaseMessages."
+ )
+ raise ValueError(msg)
+
+ @override
+ def invoke(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AIMessage:
+ config = ensure_config(config)
+ return cast(
+ "AIMessage",
+ cast(
+ "ChatGeneration",
+ self.generate_prompt(
+ [self._convert_input(input)],
+ stop=stop,
+ callbacks=config.get("callbacks"),
+ tags=config.get("tags"),
+ metadata=config.get("metadata"),
+ run_name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ **kwargs,
+ ).generations[0][0],
+ ).message,
+ )
+
+ @override
+ async def ainvoke(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AIMessage:
+ config = ensure_config(config)
+ llm_result = await self.agenerate_prompt(
+ [self._convert_input(input)],
+ stop=stop,
+ callbacks=config.get("callbacks"),
+ tags=config.get("tags"),
+ metadata=config.get("metadata"),
+ run_name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ **kwargs,
+ )
+ return cast(
+ "AIMessage", cast("ChatGeneration", llm_result.generations[0][0]).message
+ )
+
+ def _streaming_disabled(self, **kwargs: Any) -> bool:
+ """Return whether streaming is hard-disabled for this call.
+
+ Shared opt-outs honored by both `_should_stream` and
+ `_should_use_protocol_streaming` — these override any affirmative trigger
+ (attached handler, `stream=True`, etc.):
+
+ - `self.disable_streaming is True`
+ - `self.disable_streaming == "tool_calling"` with `tools` passed
+ - `stream=` in call kwargs
+ - `self.streaming is False` on the instance
+ """
+ if self.disable_streaming is True:
+ return True
+ # We assume tools are passed in via "tools" kwarg in all models.
+ if self.disable_streaming == "tool_calling" and kwargs.get("tools"):
+ return True
+ if "stream" in kwargs and not kwargs["stream"]:
+ return True
+ return (
+ "streaming" in self.model_fields_set
+ and getattr(self, "streaming", None) is False
+ )
+
+ def _should_stream(
+ self,
+ *,
+ async_api: bool,
+ run_manager: CallbackManagerForLLMRun
+ | AsyncCallbackManagerForLLMRun
+ | None = None,
+ **kwargs: Any,
+ ) -> bool:
+ """Determine if a given model call should hit the streaming API."""
+ sync_not_implemented = type(self)._stream == BaseChatModel._stream # noqa: SLF001
+ async_not_implemented = type(self)._astream == BaseChatModel._astream # noqa: SLF001
+
+ # Check if streaming is implemented.
+ if (not async_api) and sync_not_implemented:
+ return False
+ # Note, since async falls back to sync we check both here.
+ if async_api and async_not_implemented and sync_not_implemented:
+ return False
+
+ if self._streaming_disabled(**kwargs):
+ return False
+
+ # Affirmative: explicit `stream=` kwarg.
+ if kwargs.get("stream"):
+ return True
+
+ # Affirmative: instance-level `streaming=True` attribute.
+ if (
+ "streaming" in self.model_fields_set
+ and getattr(self, "streaming", None) is True
+ ):
+ return True
+
+ # Affirmative: a v1 streaming callback handler is attached.
+ handlers = run_manager.handlers if run_manager else []
+ return any(isinstance(h, _StreamingCallbackHandler) for h in handlers)
+
+ def _should_use_protocol_streaming(
+ self,
+ *,
+ async_api: bool,
+ run_manager: CallbackManagerForLLMRun
+ | AsyncCallbackManagerForLLMRun
+ | None = None,
+ **kwargs: Any,
+ ) -> bool:
+ """Determine whether an invoke should route through the v2 event path.
+
+ Runs alongside `_should_stream` inside `_generate_with_cache` /
+ `_agenerate_with_cache` — after the run manager is open — and
+ wins over the v1 streaming branch when a handler has declared
+ itself a `_V2StreamingCallbackHandler`. Parallel to
+ `_should_stream` rather than a delegation — v1 and v2 have
+ disjoint affirmative triggers.
+
+ Args:
+ async_api: Whether the caller is on the async path.
+ run_manager: The active LLM run manager.
+ **kwargs: Call kwargs; inspected for `disable_streaming`
+ semantics and an explicit `stream=False` override.
+
+ Returns:
+ `True` if any attached handler inherits
+ `_V2StreamingCallbackHandler` and the model can drive the v2
+ event generator (natively or via the `_stream` compat
+ bridge).
+ """
+ # Opt-in: only route through v2 when a v2 handler is attached.
+ handlers = run_manager.handlers if run_manager else []
+ if not any(isinstance(h, _V2StreamingCallbackHandler) for h in handlers):
+ return False
+
+ # Need a source of v2 events on the requested flavor. A native
+ # `_(a)stream_chat_model_events` hook bypasses the bridge;
+ # otherwise the bridge wraps `_stream` / `_astream`. Async can
+ # fall back to sync.
+ #
+ # `cls._stream is not BaseChatModel._stream` is an identity
+ # check for "subclass overrode `_stream`" — same pattern as
+ # `_should_stream`.
+ cls = type(self)
+ has_native_sync = getattr(cls, "_stream_chat_model_events", None) is not None
+ has_native_async = getattr(cls, "_astream_chat_model_events", None) is not None
+ overrides_sync = cls._stream is not BaseChatModel._stream
+ overrides_async = cls._astream is not BaseChatModel._astream
+ has_sync_source = has_native_sync or overrides_sync
+ has_async_source = has_native_async or overrides_async
+ has_source = (
+ (has_sync_source or has_async_source) if async_api else has_sync_source
+ )
+ if not has_source:
+ return False
+
+ return not self._streaming_disabled(**kwargs)
+
+ def _iter_v2_events(
+ self,
+ messages: list[BaseMessage],
+ *,
+ run_manager: CallbackManagerForLLMRun,
+ stream: ChatModelStream,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[MessagesData]:
+ """Drive the v2 event generator with per-event dispatch.
+
+ Shared between the `stream_events(version="v3")` pump and the
+ invoke-time v2 branch in `_generate_with_cache`. Picks the native
+ `_stream_chat_model_events` hook when the subclass provides one,
+ else bridges `_stream` chunks via `chunks_to_events`. Each event
+ is dispatched into `stream` and fired as `on_stream_event` on
+ the run manager. Run-lifecycle callbacks
+ (`on_chat_model_start` / `on_llm_end` / `on_llm_error`) and
+ rate-limiter acquisition are the caller's responsibility.
+
+ Args:
+ messages: Normalized input messages.
+ run_manager: Active LLM run manager; receives
+ `on_stream_event` per event.
+ stream: Accumulator owned by the caller; receives each
+ event via `stream.dispatch`.
+ stop: Optional stop sequences.
+ **kwargs: Forwarded to the event producer.
+
+ Yields:
+ Each protocol event produced by the model.
+ """
+ native = cast(
+ "Callable[..., Iterator[MessagesData]] | None",
+ getattr(self, "_stream_chat_model_events", None),
+ )
+ if native is not None:
+ event_iter: Iterator[MessagesData] = native(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ else:
+ event_iter = chunks_to_events(
+ self._stream(messages, stop=stop, run_manager=run_manager, **kwargs),
+ message_id=stream.message_id,
+ )
+ for event in event_iter:
+ stream.dispatch(event)
+ run_manager.on_stream_event(event)
+ yield event
+
+ async def _aiter_v2_events(
+ self,
+ messages: list[BaseMessage],
+ *,
+ run_manager: AsyncCallbackManagerForLLMRun,
+ stream: AsyncChatModelStream,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[MessagesData]:
+ """Async counterpart to `_iter_v2_events`.
+
+ See `_iter_v2_events` for the shared contract.
+ """
+ native = cast(
+ "Callable[..., AsyncIterator[MessagesData]] | None",
+ getattr(self, "_astream_chat_model_events", None),
+ )
+ if native is not None:
+ event_iter: AsyncIterator[MessagesData] = native(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ else:
+ event_iter = achunks_to_events(
+ self._astream(messages, stop=stop, run_manager=run_manager, **kwargs),
+ message_id=stream.message_id,
+ )
+ async for event in event_iter:
+ stream.dispatch(event)
+ await run_manager.on_stream_event(event)
+ yield event
+
+ @override
+ def stream(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[AIMessageChunk]:
+ if not self._should_stream(async_api=False, **{**kwargs, "stream": True}):
+ # Model doesn't implement streaming, so use default implementation
+ yield cast(
+ "AIMessageChunk",
+ self.invoke(input, config=config, stop=stop, **kwargs),
+ )
+ else:
+ config = ensure_config(config)
+ messages = self._convert_input(input).to_messages()
+ ls_structured_output_format = kwargs.pop(
+ "ls_structured_output_format", None
+ ) or kwargs.pop("structured_output_format", None)
+ ls_structured_output_format_dict = _format_ls_structured_output(
+ ls_structured_output_format
+ )
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ options = {"stop": stop, **kwargs, **ls_structured_output_format_dict}
+ inheritable_metadata = {
+ **(config.get("metadata") or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ callback_manager = CallbackManager.configure(
+ config.get("callbacks"),
+ self.callbacks,
+ self.verbose,
+ config.get("tags"),
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ (run_manager,) = callback_manager.on_chat_model_start(
+ self._serialized,
+ [_format_for_tracing(messages)],
+ invocation_params=params,
+ options=options,
+ name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ batch_size=1,
+ )
+
+ chunks: list[ChatGenerationChunk] = []
+
+ if self.rate_limiter:
+ self.rate_limiter.acquire(blocking=True)
+
+ try:
+ input_messages = _normalize_messages(messages)
+ run_id = "-".join((LC_ID_PREFIX, str(run_manager.run_id)))
+ yielded = False
+ index = -1
+ index_type = ""
+ for chunk in self._stream(input_messages, stop=stop, **kwargs):
+ if chunk.message.id is None:
+ chunk.message.id = run_id
+ chunk.message.response_metadata = _gen_info_and_msg_metadata(chunk)
+ if self.output_version == "v1":
+ # Overwrite .content with .content_blocks
+ chunk.message = _update_message_content_to_blocks(
+ chunk.message, "v1"
+ )
+ for block in cast(
+ "list[types.ContentBlock]", chunk.message.content
+ ):
+ if block["type"] != index_type:
+ index_type = block["type"]
+ index += 1
+ if "index" not in block:
+ block["index"] = index
+ run_manager.on_llm_new_token(
+ cast("str", chunk.message.content), chunk=chunk
+ )
+ chunks.append(chunk)
+ yield cast("AIMessageChunk", chunk.message)
+ yielded = True
+
+ # Yield a final empty chunk with chunk_position="last" if not yet
+ # yielded
+ if (
+ yielded
+ and isinstance(chunk.message, AIMessageChunk)
+ and not chunk.message.chunk_position
+ ):
+ empty_content: str | list = (
+ "" if isinstance(chunk.message.content, str) else []
+ )
+ msg_chunk = AIMessageChunk(
+ content=empty_content, chunk_position="last", id=run_id
+ )
+ run_manager.on_llm_new_token(
+ "", chunk=ChatGenerationChunk(message=msg_chunk)
+ )
+ yield msg_chunk
+ except BaseException as e:
+ generations_with_error_metadata = _generate_response_from_error(e)
+ chat_generation_chunk = merge_chat_generation_chunks(chunks)
+ if chat_generation_chunk:
+ generations = [
+ [chat_generation_chunk],
+ generations_with_error_metadata,
+ ]
+ else:
+ generations = [generations_with_error_metadata]
+ run_manager.on_llm_error(
+ e,
+ response=LLMResult(generations=generations),
+ )
+ raise
+
+ generation = merge_chat_generation_chunks(chunks)
+ if generation is None:
+ err = ValueError("No generation chunks were returned")
+ run_manager.on_llm_error(err, response=LLMResult(generations=[]))
+ raise err
+
+ run_manager.on_llm_end(LLMResult(generations=[[generation]]))
+
+ @override
+ async def astream(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[AIMessageChunk]:
+ if not self._should_stream(async_api=True, **{**kwargs, "stream": True}):
+ # No async or sync stream is implemented, so fall back to ainvoke
+ yield cast(
+ "AIMessageChunk",
+ await self.ainvoke(input, config=config, stop=stop, **kwargs),
+ )
+ return
+
+ config = ensure_config(config)
+ messages = self._convert_input(input).to_messages()
+
+ ls_structured_output_format = kwargs.pop(
+ "ls_structured_output_format", None
+ ) or kwargs.pop("structured_output_format", None)
+ ls_structured_output_format_dict = _format_ls_structured_output(
+ ls_structured_output_format
+ )
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ options = {"stop": stop, **kwargs, **ls_structured_output_format_dict}
+ inheritable_metadata = {
+ **(config.get("metadata") or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ callback_manager = AsyncCallbackManager.configure(
+ config.get("callbacks"),
+ self.callbacks,
+ self.verbose,
+ config.get("tags"),
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ (run_manager,) = await callback_manager.on_chat_model_start(
+ self._serialized,
+ [_format_for_tracing(messages)],
+ invocation_params=params,
+ options=options,
+ name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ batch_size=1,
+ )
+
+ if self.rate_limiter:
+ await self.rate_limiter.aacquire(blocking=True)
+
+ chunks: list[ChatGenerationChunk] = []
+
+ try:
+ input_messages = _normalize_messages(messages)
+ run_id = "-".join((LC_ID_PREFIX, str(run_manager.run_id)))
+ yielded = False
+ index = -1
+ index_type = ""
+ async for chunk in self._astream(
+ input_messages,
+ stop=stop,
+ **kwargs,
+ ):
+ if chunk.message.id is None:
+ chunk.message.id = run_id
+ chunk.message.response_metadata = _gen_info_and_msg_metadata(chunk)
+ if self.output_version == "v1":
+ # Overwrite .content with .content_blocks
+ chunk.message = _update_message_content_to_blocks(
+ chunk.message, "v1"
+ )
+ for block in cast(
+ "list[types.ContentBlock]", chunk.message.content
+ ):
+ if block["type"] != index_type:
+ index_type = block["type"]
+ index += 1
+ if "index" not in block:
+ block["index"] = index
+ await run_manager.on_llm_new_token(
+ cast("str", chunk.message.content), chunk=chunk
+ )
+ chunks.append(chunk)
+ yield cast("AIMessageChunk", chunk.message)
+ yielded = True
+
+ # Yield a final empty chunk with chunk_position="last" if not yet yielded
+ if (
+ yielded
+ and isinstance(chunk.message, AIMessageChunk)
+ and not chunk.message.chunk_position
+ ):
+ empty_content: str | list = (
+ "" if isinstance(chunk.message.content, str) else []
+ )
+ msg_chunk = AIMessageChunk(
+ content=empty_content, chunk_position="last", id=run_id
+ )
+ await run_manager.on_llm_new_token(
+ "", chunk=ChatGenerationChunk(message=msg_chunk)
+ )
+ yield msg_chunk
+ except BaseException as e:
+ generations_with_error_metadata = _generate_response_from_error(e)
+ chat_generation_chunk = merge_chat_generation_chunks(chunks)
+ if chat_generation_chunk:
+ generations = [[chat_generation_chunk], generations_with_error_metadata]
+ else:
+ generations = [generations_with_error_metadata]
+ await run_manager.on_llm_error(
+ e,
+ response=LLMResult(generations=generations),
+ )
+ raise
+
+ generation = merge_chat_generation_chunks(chunks)
+ if not generation:
+ err = ValueError("No generation chunks were returned")
+ await run_manager.on_llm_error(err, response=LLMResult(generations=[]))
+ raise err
+
+ await run_manager.on_llm_end(
+ LLMResult(generations=[[generation]]),
+ )
+
+ # --- stream_events v3 ---
+
+ @beta()
+ def _chat_model_stream_v3(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> ChatModelStream:
+ """Internal v3 sync streaming implementation.
+
+ Public entry point: `stream_events(version='v3')`.
+ """
+ config = ensure_config(config)
+ messages = self._convert_input(input).to_messages()
+ input_messages = _normalize_messages(messages)
+
+ # Strip tracing-only kwargs before forwarding to `_stream` — matches
+ # `stream()` / `astream()`. Provider clients reject unknown kwargs,
+ # so `.with_structured_output().stream_events(version="v3", ...)`
+ # and any other binding that carries `ls_structured_output_format`
+ # / `structured_output_format` would raise without this pop.
+ ls_structured_output_format = kwargs.pop(
+ "ls_structured_output_format", None
+ ) or kwargs.pop("structured_output_format", None)
+ ls_structured_output_format_dict = _format_ls_structured_output(
+ ls_structured_output_format
+ )
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ options = {"stop": stop, **kwargs, **ls_structured_output_format_dict}
+ inheritable_metadata = {
+ **(config.get("metadata") or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ callback_manager = CallbackManager.configure(
+ config.get("callbacks"),
+ self.callbacks,
+ self.verbose,
+ config.get("tags"),
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ stream = ChatModelStream()
+ run_manager: CallbackManagerForLLMRun | None = None
+ event_iter_ref: Iterator[MessagesData] | None = None
+ rate_limiter_acquired = self.rate_limiter is None
+ run_name = config.get("run_name")
+ run_id = config.pop("run_id", None)
+
+ def ensure_started() -> None:
+ nonlocal event_iter_ref, run_manager
+ if event_iter_ref is not None:
+ return
+
+ (run_manager,) = callback_manager.on_chat_model_start(
+ self._serialized,
+ [_format_for_tracing(messages)],
+ invocation_params=params,
+ options=options,
+ name=run_name,
+ run_id=run_id,
+ batch_size=1,
+ )
+ stream.set_message_id("-".join((LC_ID_PREFIX, str(run_manager.run_id))))
+ event_iter_ref = iter(
+ self._iter_v2_events(
+ input_messages,
+ run_manager=run_manager,
+ stream=stream,
+ stop=stop,
+ **kwargs,
+ )
+ )
+
+ def pump_one() -> bool:
+ nonlocal rate_limiter_acquired
+ ensure_started()
+ if not rate_limiter_acquired:
+ assert self.rate_limiter is not None # noqa: S101
+ self.rate_limiter.acquire(blocking=True)
+ rate_limiter_acquired = True
+ assert event_iter_ref is not None # noqa: S101
+ assert run_manager is not None # noqa: S101
+ try:
+ next(event_iter_ref)
+ except StopIteration:
+ if not stream.done:
+ if stream.has_events:
+ # Native event producers may omit the terminal
+ # `message-finish`. Close the lifecycle here so
+ # `on_llm_end` still observes the assembled
+ # message. A truly empty stream remains an error
+ # for parity with `stream()`.
+ stream.dispatch(MessageFinishData(event="message-finish"))
+ else:
+ err = ValueError("No generation chunks were returned")
+ stream.fail(err)
+ run_manager.on_llm_error(
+ err,
+ response=LLMResult(generations=[]),
+ )
+ return False
+ if stream.done and stream.output_message is not None:
+ run_manager.on_llm_end(
+ LLMResult(
+ generations=[
+ [ChatGeneration(message=stream.output_message)],
+ ],
+ ),
+ )
+ return False
+ except BaseException as exc:
+ stream.fail(exc)
+ run_manager.on_llm_error(
+ exc,
+ response=LLMResult(generations=[]),
+ )
+ return False
+ if stream.done and stream.output_message is not None:
+ run_manager.on_llm_end(
+ LLMResult(
+ generations=[
+ [ChatGeneration(message=stream.output_message)],
+ ],
+ ),
+ )
+ return True
+
+ stream.set_start(ensure_started)
+ stream.bind_pump(pump_one)
+ return stream
+
+ @beta()
+ async def _achat_model_stream_v3(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncChatModelStream:
+ """Internal v3 async streaming implementation.
+
+ Public entry point: `astream_events(version='v3')`.
+ """
+ config = ensure_config(config)
+ messages = self._convert_input(input).to_messages()
+ input_messages = _normalize_messages(messages)
+
+ # Strip tracing-only kwargs before forwarding — see the sync v3
+ # implementation for the full rationale.
+ ls_structured_output_format = kwargs.pop(
+ "ls_structured_output_format", None
+ ) or kwargs.pop("structured_output_format", None)
+ ls_structured_output_format_dict = _format_ls_structured_output(
+ ls_structured_output_format
+ )
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ options = {"stop": stop, **kwargs, **ls_structured_output_format_dict}
+ inheritable_metadata = {
+ **(config.get("metadata") or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ callback_manager = AsyncCallbackManager.configure(
+ config.get("callbacks"),
+ self.callbacks,
+ self.verbose,
+ config.get("tags"),
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ stream = AsyncChatModelStream()
+ run_manager: AsyncCallbackManagerForLLMRun | None = None
+ run_name = config.get("run_name")
+ run_id = config.pop("run_id", None)
+ start_lock = asyncio.Lock()
+
+ async def _produce() -> None:
+ assert run_manager is not None # noqa: S101
+ try:
+ if self.rate_limiter:
+ await self.rate_limiter.aacquire(blocking=True)
+
+ async for _event in self._aiter_v2_events(
+ input_messages,
+ run_manager=run_manager,
+ stream=stream,
+ stop=stop,
+ **kwargs,
+ ):
+ pass
+ if not stream.done:
+ if stream.has_events:
+ # Native event producers may omit the terminal
+ # `message-finish`. Close the lifecycle here so
+ # `on_llm_end` sees the finalized message. A
+ # truly empty stream remains an error for parity
+ # with `astream()`.
+ stream.dispatch(MessageFinishData(event="message-finish"))
+ else:
+ err = ValueError("No generation chunks were returned")
+ stream.fail(err)
+ await run_manager.on_llm_error(
+ err,
+ response=LLMResult(generations=[]),
+ )
+ return
+ if stream.done and stream.output_message is not None:
+ await run_manager.on_llm_end(
+ LLMResult(
+ generations=[
+ [ChatGeneration(message=stream.output_message)],
+ ],
+ ),
+ )
+ except asyncio.CancelledError as exc:
+ stream.fail(exc)
+ # Close the callback lifecycle so tracing observes a
+ # matching end event for the earlier `on_chat_model_start`.
+ # `on_llm_error` is `@shielded`, so the callback runs to
+ # completion in the background even though the `await`
+ # here re-raises our cancellation.
+ with contextlib.suppress(Exception):
+ await run_manager.on_llm_error(
+ exc,
+ response=LLMResult(generations=[]),
+ )
+ raise
+ except BaseException as exc:
+ stream.fail(exc)
+ await run_manager.on_llm_error(
+ exc,
+ response=LLMResult(generations=[]),
+ )
+
+ async def ensure_started() -> None:
+ nonlocal run_manager
+ if stream._producer_task is not None: # noqa: SLF001
+ return
+
+ async with start_lock:
+ if stream._producer_task is not None: # noqa: SLF001
+ return
+
+ (run_manager,) = await callback_manager.on_chat_model_start(
+ self._serialized,
+ [_format_for_tracing(messages)],
+ invocation_params=params,
+ options=options,
+ name=run_name,
+ run_id=run_id,
+ batch_size=1,
+ )
+ stream.set_message_id("-".join((LC_ID_PREFIX, str(run_manager.run_id))))
+ stream._producer_task = asyncio.get_running_loop().create_task( # noqa: SLF001
+ _produce()
+ )
+
+ async def _on_aclose_fail(exc: BaseException) -> None:
+ assert run_manager is not None # noqa: S101
+ # Invoked by `stream.aclose()` only when the producer was
+ # cancelled before `_produce` ran — so `on_llm_error` from
+ # the CancelledError handler never fired. Shielded by the
+ # callback manager; runs to completion even if our caller
+ # is being cancelled.
+ await run_manager.on_llm_error(
+ exc,
+ response=LLMResult(generations=[]),
+ )
+
+ stream.set_start(ensure_started)
+ stream._on_aclose_fail = _on_aclose_fail # noqa: SLF001
+ return stream
+
+ @overload # type: ignore[override]
+ def stream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent]: ...
+
+ @overload
+ def stream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> ChatModelStream: ...
+
+ def stream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent] | ChatModelStream:
+ """Stream events from this chat model.
+
+ For `version="v1"` / `"v2"`, yields `StreamEvent` dicts (see
+ `Runnable.stream_events`). For `version="v3"`, returns a
+ `ChatModelStream` exposing typed projections (`.text`,
+ `.reasoning`, `.tool_calls`, `.output`).
+
+ !!! warning "Beta"
+
+ `version="v3"` is in beta. The protocol shape, return type,
+ and surface area may change in future releases. Calling it
+ emits a `LangChainBetaWarning` at runtime.
+
+ !!! note "v3 always produces v1-shaped content"
+
+ `ChatModelStream.output.content` is always a list of v1
+ content blocks (text / reasoning / tool_call / image / …),
+ regardless of the model's `output_version` attribute. The
+ setting only affects the legacy `stream()` / `astream()` /
+ `invoke()` paths. If you're mixing
+ `stream_events(version="v3")` with those paths in the same
+ pipeline and need a consistent output shape across them,
+ set `output_version="v1"` on the model.
+
+ Args:
+ input: The model input.
+ config: Optional runnable config.
+ version: Streaming-event schema version. `"v3"` selects the
+ content-block-centric streaming protocol.
+ stop: Optional stop sequences. Only used for `version="v3"`;
+ ignored otherwise.
+ **kwargs: Additional keyword arguments. For `version="v3"`,
+ forwarded to the model.
+
+ Returns:
+ For `version="v3"`, a `ChatModelStream` with typed
+ projections. Otherwise an `Iterator[StreamEvent]`.
+ """
+ if version == "v3":
+ return self._chat_model_stream_v3(input, config, stop=stop, **kwargs)
+ return super().stream_events(
+ input, config, version=version, stop=stop, **kwargs
+ )
+
+ @overload
+ def astream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent]: ...
+
+ @overload
+ def astream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Awaitable[AsyncChatModelStream]: ...
+
+ def astream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent] | Awaitable[AsyncChatModelStream]:
+ """Async variant of `stream_events`. See `stream_events` for full docs."""
+ if version == "v3":
+ return self._achat_model_stream_v3(input, config, stop=stop, **kwargs)
+ # v1/v2: forward to Runnable.astream_events (async generator).
+ return super().astream_events(
+ input, config, version=version, stop=stop, **kwargs
+ )
+
+ # --- Custom methods ---
+
+ def _combine_llm_outputs(self, _llm_outputs: list[dict | None], /) -> dict:
+ return {}
+
+ def _convert_cached_generations(self, cache_val: list) -> list[ChatGeneration]:
+ """Convert cached Generation objects to ChatGeneration objects.
+
+ Handle case where cache contains Generation objects instead of
+ ChatGeneration objects. This can happen due to serialization/deserialization
+ issues or legacy cache data (see #22389).
+
+ Args:
+ cache_val: List of cached generation objects.
+
+ Returns:
+ List of ChatGeneration objects.
+
+ """
+ converted_generations = []
+ for gen in cache_val:
+ if isinstance(gen, Generation) and not isinstance(gen, ChatGeneration):
+ # Convert Generation to ChatGeneration by creating AIMessage
+ # from the text content
+ chat_gen = ChatGeneration(
+ message=AIMessage(content=gen.text),
+ generation_info=gen.generation_info,
+ )
+ converted_generations.append(chat_gen)
+ else:
+ # Already a ChatGeneration or other expected type
+ if hasattr(gen, "message") and isinstance(gen.message, AIMessage):
+ # We zero out cost on cache hits
+ gen.message = gen.message.model_copy(
+ update={
+ "usage_metadata": {
+ **(gen.message.usage_metadata or {}),
+ "total_cost": 0,
+ }
+ }
+ )
+ converted_generations.append(gen)
+ return converted_generations
+
+ def _replay_v2_events_for_cache_hit(
+ self,
+ generations: list[ChatGeneration],
+ *,
+ run_manager: CallbackManagerForLLMRun | None,
+ **kwargs: Any,
+ ) -> None:
+ """Replay cached messages as v2 events when a v2 handler is attached.
+
+ A warm cache must produce the same `on_stream_event` stream as a
+ cold call so LangGraph-style consumers do not observe behavior
+ that depends on cache state. Gated by
+ `_should_use_protocol_streaming` so a `disable_streaming` config
+ that suppresses v2 on cold calls also suppresses it here.
+ """
+ if run_manager is None or not self._should_use_protocol_streaming(
+ async_api=False, run_manager=run_manager, **kwargs
+ ):
+ return
+ message_id = f"{LC_ID_PREFIX}-{run_manager.run_id}"
+ for gen in generations:
+ msg = getattr(gen, "message", None)
+ if not isinstance(msg, AIMessage):
+ continue
+ for event in message_to_events(msg, message_id=message_id):
+ run_manager.on_stream_event(event)
+
+ async def _areplay_v2_events_for_cache_hit(
+ self,
+ generations: list[ChatGeneration],
+ *,
+ run_manager: AsyncCallbackManagerForLLMRun | None,
+ **kwargs: Any,
+ ) -> None:
+ """Async counterpart to `_replay_v2_events_for_cache_hit`."""
+ if run_manager is None or not self._should_use_protocol_streaming(
+ async_api=True, run_manager=run_manager, **kwargs
+ ):
+ return
+ message_id = f"{LC_ID_PREFIX}-{run_manager.run_id}"
+ for gen in generations:
+ msg = getattr(gen, "message", None)
+ if not isinstance(msg, AIMessage):
+ continue
+ async for event in amessage_to_events(msg, message_id=message_id):
+ await run_manager.on_stream_event(event)
+
+ def _get_invocation_params(
+ self,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> dict:
+ params = self.dict()
+ params["stop"] = stop
+ return {**params, **kwargs}
+
+ def _get_ls_params(
+ self,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> LangSmithParams:
+ """Get standard params for tracing."""
+ # get default provider from class name
+ default_provider = self.__class__.__name__
+ if default_provider.startswith("Chat"):
+ default_provider = default_provider[4:].lower()
+ elif default_provider.endswith("Chat"):
+ default_provider = default_provider[:-4]
+ default_provider = default_provider.lower()
+
+ ls_params = LangSmithParams(ls_provider=default_provider, ls_model_type="chat")
+ if stop:
+ ls_params["ls_stop"] = stop
+
+ # model
+ if "model" in kwargs and isinstance(kwargs["model"], str):
+ ls_params["ls_model_name"] = kwargs["model"]
+ elif hasattr(self, "model") and isinstance(self.model, str):
+ ls_params["ls_model_name"] = self.model
+ elif hasattr(self, "model_name") and isinstance(self.model_name, str):
+ ls_params["ls_model_name"] = self.model_name
+
+ # temperature
+ if "temperature" in kwargs and isinstance(kwargs["temperature"], (int, float)):
+ ls_params["ls_temperature"] = kwargs["temperature"]
+ elif hasattr(self, "temperature") and isinstance(
+ self.temperature, (int, float)
+ ):
+ ls_params["ls_temperature"] = self.temperature
+
+ # max_tokens
+ if "max_tokens" in kwargs and isinstance(kwargs["max_tokens"], int):
+ ls_params["ls_max_tokens"] = kwargs["max_tokens"]
+ elif hasattr(self, "max_tokens") and isinstance(self.max_tokens, int):
+ ls_params["ls_max_tokens"] = self.max_tokens
+
+ return ls_params
+
+ def _get_ls_params_with_defaults(
+ self,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> LangSmithParams:
+ """Wrap _get_ls_params to always include ls_integration."""
+ ls_params = self._get_ls_params(stop=stop, **kwargs)
+ ls_params["ls_integration"] = "langchain_chat_model"
+ return ls_params
+
+ def _get_llm_string(self, stop: list[str] | None = None, **kwargs: Any) -> str:
+ if self.is_lc_serializable():
+ params = {**kwargs, "stop": stop}
+ param_string = str(sorted(params.items()))
+ # This code is not super efficient as it goes back and forth between
+ # json and dict.
+ serialized_repr = self._serialized
+ _cleanup_llm_representation(serialized_repr, 1)
+ llm_string = json.dumps(serialized_repr, sort_keys=True)
+ return llm_string + "---" + param_string
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ params = {**params, **kwargs}
+ return str(sorted(params.items()))
+
+ def generate(
+ self,
+ messages: list[list[BaseMessage]],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ *,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_name: str | None = None,
+ run_id: uuid.UUID | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Pass a sequence of prompts to the model and return model generations.
+
+ This method should make use of batched calls for models that expose a batched
+ API.
+
+ Use this method when you want to:
+
+ 1. Take advantage of batched calls,
+ 2. Need more output from the model than just the top generated value,
+ 3. Are building chains that are agnostic to the underlying language model
+ type (e.g., pure text completion models vs chat models).
+
+ Args:
+ messages: List of list of messages.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ callbacks: `Callbacks` to pass through.
+
+ Used for executing additional functionality, such as logging or
+ streaming, throughout generation.
+ tags: The tags to apply.
+ metadata: The metadata to apply.
+ run_name: The name of the run.
+ run_id: The ID of the run.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Returns:
+ An `LLMResult`, which contains a list of candidate `Generations` for each
+ input prompt and additional model provider-specific output.
+
+ """
+ ls_structured_output_format = kwargs.pop(
+ "ls_structured_output_format", None
+ ) or kwargs.pop("structured_output_format", None)
+ ls_structured_output_format_dict = _format_ls_structured_output(
+ ls_structured_output_format
+ )
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ options = {"stop": stop, **ls_structured_output_format_dict}
+ inheritable_metadata = {
+ **(metadata or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+
+ callback_manager = CallbackManager.configure(
+ callbacks,
+ self.callbacks,
+ self.verbose,
+ tags,
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ messages_to_trace = [
+ _format_for_tracing(message_list) for message_list in messages
+ ]
+ run_managers = callback_manager.on_chat_model_start(
+ self._serialized,
+ messages_to_trace,
+ invocation_params=params,
+ options=options,
+ name=run_name,
+ run_id=run_id,
+ batch_size=len(messages),
+ )
+ results = []
+ input_messages = [
+ _normalize_messages(message_list) for message_list in messages
+ ]
+ for i, m in enumerate(input_messages):
+ try:
+ results.append(
+ self._generate_with_cache(
+ m,
+ stop=stop,
+ run_manager=run_managers[i] if run_managers else None,
+ **kwargs,
+ )
+ )
+ except BaseException as e:
+ if run_managers:
+ generations_with_error_metadata = _generate_response_from_error(e)
+ run_managers[i].on_llm_error(
+ e,
+ response=LLMResult(
+ generations=[generations_with_error_metadata]
+ ),
+ )
+ raise
+ flattened_outputs = [
+ LLMResult(generations=[res.generations], llm_output=res.llm_output)
+ for res in results
+ ]
+ llm_output = self._combine_llm_outputs([res.llm_output for res in results])
+ generations = [res.generations for res in results]
+ output = LLMResult(generations=generations, llm_output=llm_output)
+ if run_managers:
+ run_infos = []
+ for manager, flattened_output in zip(
+ run_managers, flattened_outputs, strict=False
+ ):
+ manager.on_llm_end(flattened_output)
+ run_infos.append(RunInfo(run_id=manager.run_id))
+ output.run = run_infos
+ return output
+
+ async def agenerate(
+ self,
+ messages: list[list[BaseMessage]],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ *,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_name: str | None = None,
+ run_id: uuid.UUID | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Asynchronously pass a sequence of prompts to a model and return generations.
+
+ This method should make use of batched calls for models that expose a batched
+ API.
+
+ Use this method when you want to:
+
+ 1. Take advantage of batched calls,
+ 2. Need more output from the model than just the top generated value,
+ 3. Are building chains that are agnostic to the underlying language model
+ type (e.g., pure text completion models vs chat models).
+
+ Args:
+ messages: List of list of messages.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ callbacks: `Callbacks` to pass through.
+
+ Used for executing additional functionality, such as logging or
+ streaming, throughout generation.
+ tags: The tags to apply.
+ metadata: The metadata to apply.
+ run_name: The name of the run.
+ run_id: The ID of the run.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Returns:
+ An `LLMResult`, which contains a list of candidate `Generations` for each
+ input prompt and additional model provider-specific output.
+
+ """
+ ls_structured_output_format = kwargs.pop(
+ "ls_structured_output_format", None
+ ) or kwargs.pop("structured_output_format", None)
+ ls_structured_output_format_dict = _format_ls_structured_output(
+ ls_structured_output_format
+ )
+
+ params = self._get_invocation_params(stop=stop, **kwargs)
+ options = {"stop": stop, **ls_structured_output_format_dict}
+ inheritable_metadata = {
+ **(metadata or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+
+ callback_manager = AsyncCallbackManager.configure(
+ callbacks,
+ self.callbacks,
+ self.verbose,
+ tags,
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+
+ messages_to_trace = [
+ _format_for_tracing(message_list) for message_list in messages
+ ]
+ run_managers = await callback_manager.on_chat_model_start(
+ self._serialized,
+ messages_to_trace,
+ invocation_params=params,
+ options=options,
+ name=run_name,
+ batch_size=len(messages),
+ run_id=run_id,
+ )
+
+ input_messages = [
+ _normalize_messages(message_list) for message_list in messages
+ ]
+ results = await asyncio.gather(
+ *[
+ self._agenerate_with_cache(
+ m,
+ stop=stop,
+ run_manager=run_managers[i] if run_managers else None,
+ **kwargs,
+ )
+ for i, m in enumerate(input_messages)
+ ],
+ return_exceptions=True,
+ )
+ exceptions = []
+ for i, res in enumerate(results):
+ if isinstance(res, BaseException):
+ if run_managers:
+ generations_with_error_metadata = _generate_response_from_error(res)
+ await run_managers[i].on_llm_error(
+ res,
+ response=LLMResult(
+ generations=[generations_with_error_metadata]
+ ),
+ )
+ exceptions.append(res)
+ if exceptions:
+ if run_managers:
+ await asyncio.gather(
+ *[
+ run_manager.on_llm_end(
+ LLMResult(
+ generations=[res.generations], # type: ignore[union-attr]
+ llm_output=res.llm_output, # type: ignore[union-attr]
+ )
+ )
+ for run_manager, res in zip(run_managers, results, strict=False)
+ if not isinstance(res, Exception)
+ ]
+ )
+ raise exceptions[0]
+ flattened_outputs = [
+ LLMResult(generations=[res.generations], llm_output=res.llm_output) # type: ignore[union-attr]
+ for res in results
+ ]
+ llm_output = self._combine_llm_outputs([res.llm_output for res in results]) # type: ignore[union-attr]
+ generations = [res.generations for res in results] # type: ignore[union-attr]
+ output = LLMResult(generations=generations, llm_output=llm_output)
+ await asyncio.gather(
+ *[
+ run_manager.on_llm_end(flattened_output)
+ for run_manager, flattened_output in zip(
+ run_managers, flattened_outputs, strict=False
+ )
+ ]
+ )
+ if run_managers:
+ output.run = [
+ RunInfo(run_id=run_manager.run_id) for run_manager in run_managers
+ ]
+ return output
+
+ @override
+ def generate_prompt(
+ self,
+ prompts: list[PromptValue],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ prompt_messages = [p.to_messages() for p in prompts]
+ return self.generate(prompt_messages, stop=stop, callbacks=callbacks, **kwargs)
+
+ @override
+ async def agenerate_prompt(
+ self,
+ prompts: list[PromptValue],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ prompt_messages = [p.to_messages() for p in prompts]
+ return await self.agenerate(
+ prompt_messages, stop=stop, callbacks=callbacks, **kwargs
+ )
+
+ def _generate_with_cache(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ llm_cache = self.cache if isinstance(self.cache, BaseCache) else get_llm_cache()
+ # We should check the cache unless it's explicitly set to False
+ # A None cache means we should use the default global cache
+ # if it's configured.
+ check_cache = self.cache or self.cache is None
+ if check_cache:
+ if llm_cache:
+ llm_string = self._get_llm_string(stop=stop, **kwargs)
+ normalized_messages = [
+ (
+ msg.model_copy(update={"id": None})
+ if getattr(msg, "id", None) is not None
+ else msg
+ )
+ for msg in messages
+ ]
+ prompt = dumps(normalized_messages)
+ cache_val = llm_cache.lookup(prompt, llm_string)
+ if isinstance(cache_val, list):
+ converted_generations = self._convert_cached_generations(cache_val)
+ self._replay_v2_events_for_cache_hit(
+ converted_generations,
+ run_manager=run_manager,
+ **kwargs,
+ )
+ return ChatResult(generations=converted_generations)
+ elif self.cache is None:
+ pass
+ else:
+ msg = "Asked to cache, but no cache found at `langchain.cache`."
+ raise ValueError(msg)
+
+ # Apply the rate limiter after checking the cache, since
+ # we usually don't want to rate limit cache lookups, but
+ # we do want to rate limit API requests.
+ if self.rate_limiter:
+ self.rate_limiter.acquire(blocking=True)
+
+ # v2 streaming: preferred over v1 when any attached handler opts in via
+ # `_V2StreamingCallbackHandler`. Drives the protocol event generator
+ # (native or `_stream` compat bridge) through the shared helper so
+ # `on_stream_event` fires per event, then returns a normal `ChatResult`
+ # so caching / `on_llm_end` stay on the existing generate path.
+ if self._should_use_protocol_streaming(
+ async_api=False,
+ run_manager=run_manager,
+ **kwargs,
+ ):
+ stream_accum = ChatModelStream(
+ message_id=(
+ f"{LC_ID_PREFIX}-{run_manager.run_id}" if run_manager else None
+ )
+ )
+ assert run_manager is not None # noqa: S101
+ for _event in self._iter_v2_events(
+ messages,
+ run_manager=run_manager,
+ stream=stream_accum,
+ stop=stop,
+ **kwargs,
+ ):
+ pass
+ if stream_accum.output_message is None:
+ msg = "v2 stream finished without producing a message"
+ raise RuntimeError(msg)
+ result = ChatResult(
+ generations=[ChatGeneration(message=stream_accum.output_message)]
+ )
+ # If stream is not explicitly set, check if implicitly requested by
+ # astream_events() or astream_log(). Bail out if _stream not implemented
+ elif self._should_stream(
+ async_api=False,
+ run_manager=run_manager,
+ **kwargs,
+ ):
+ chunks: list[ChatGenerationChunk] = []
+ run_id: str | None = (
+ f"{LC_ID_PREFIX}-{run_manager.run_id}" if run_manager else None
+ )
+ yielded = False
+ index = -1
+ index_type = ""
+ for chunk in self._stream(messages, stop=stop, **kwargs):
+ chunk.message.response_metadata = _gen_info_and_msg_metadata(chunk)
+ if self.output_version == "v1":
+ # Overwrite .content with .content_blocks
+ chunk.message = _update_message_content_to_blocks(
+ chunk.message, "v1"
+ )
+ for block in cast(
+ "list[types.ContentBlock]", chunk.message.content
+ ):
+ if block["type"] != index_type:
+ index_type = block["type"]
+ index += 1
+ if "index" not in block:
+ block["index"] = index
+ if run_manager:
+ if chunk.message.id is None:
+ chunk.message.id = run_id
+ run_manager.on_llm_new_token(
+ cast("str", chunk.message.content), chunk=chunk
+ )
+ chunks.append(chunk)
+ yielded = True
+
+ # Yield a final empty chunk with chunk_position="last" if not yet yielded
+ if (
+ yielded
+ and isinstance(chunk.message, AIMessageChunk)
+ and not chunk.message.chunk_position
+ ):
+ empty_content: str | list = (
+ "" if isinstance(chunk.message.content, str) else []
+ )
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(
+ content=empty_content, chunk_position="last", id=run_id
+ )
+ )
+ if run_manager:
+ run_manager.on_llm_new_token("", chunk=chunk)
+ chunks.append(chunk)
+ result = generate_from_stream(iter(chunks))
+ elif inspect.signature(self._generate).parameters.get("run_manager"):
+ result = self._generate(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ else:
+ result = self._generate(messages, stop=stop, **kwargs)
+
+ if self.output_version == "v1":
+ # Overwrite .content with .content_blocks
+ for generation in result.generations:
+ generation.message = _update_message_content_to_blocks(
+ generation.message, "v1"
+ )
+
+ # Add response metadata to each generation
+ for idx, generation in enumerate(result.generations):
+ if run_manager and generation.message.id is None:
+ generation.message.id = f"{LC_ID_PREFIX}-{run_manager.run_id}-{idx}"
+ generation.message.response_metadata = _gen_info_and_msg_metadata(
+ generation
+ )
+ if len(result.generations) == 1 and result.llm_output is not None:
+ result.generations[0].message.response_metadata = {
+ **result.llm_output,
+ **result.generations[0].message.response_metadata,
+ }
+ if check_cache and llm_cache:
+ llm_cache.update(prompt, llm_string, result.generations)
+ return result
+
+ async def _agenerate_with_cache(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ llm_cache = self.cache if isinstance(self.cache, BaseCache) else get_llm_cache()
+ # We should check the cache unless it's explicitly set to False
+ # A None cache means we should use the default global cache
+ # if it's configured.
+ check_cache = self.cache or self.cache is None
+ if check_cache:
+ if llm_cache:
+ llm_string = self._get_llm_string(stop=stop, **kwargs)
+ normalized_messages = [
+ (
+ msg.model_copy(update={"id": None})
+ if getattr(msg, "id", None) is not None
+ else msg
+ )
+ for msg in messages
+ ]
+ prompt = dumps(normalized_messages)
+ cache_val = await llm_cache.alookup(prompt, llm_string)
+ if isinstance(cache_val, list):
+ converted_generations = self._convert_cached_generations(cache_val)
+ await self._areplay_v2_events_for_cache_hit(
+ converted_generations,
+ run_manager=run_manager,
+ **kwargs,
+ )
+ return ChatResult(generations=converted_generations)
+ elif self.cache is None:
+ pass
+ else:
+ msg = "Asked to cache, but no cache found at `langchain.cache`."
+ raise ValueError(msg)
+
+ # Apply the rate limiter after checking the cache, since
+ # we usually don't want to rate limit cache lookups, but
+ # we do want to rate limit API requests.
+ if self.rate_limiter:
+ await self.rate_limiter.aacquire(blocking=True)
+
+ # v2 streaming: see sync counterpart in `_generate_with_cache`.
+ if self._should_use_protocol_streaming(
+ async_api=True,
+ run_manager=run_manager,
+ **kwargs,
+ ):
+ stream_accum = AsyncChatModelStream(
+ message_id=(
+ f"{LC_ID_PREFIX}-{run_manager.run_id}" if run_manager else None
+ )
+ )
+ assert run_manager is not None # noqa: S101
+ async for _event in self._aiter_v2_events(
+ messages,
+ run_manager=run_manager,
+ stream=stream_accum,
+ stop=stop,
+ **kwargs,
+ ):
+ pass
+ if stream_accum.output_message is None:
+ msg = "v2 stream finished without producing a message"
+ raise RuntimeError(msg)
+ result = ChatResult(
+ generations=[ChatGeneration(message=stream_accum.output_message)]
+ )
+ # If stream is not explicitly set, check if implicitly requested by
+ # astream_events() or astream_log(). Bail out if _astream not implemented
+ elif self._should_stream(
+ async_api=True,
+ run_manager=run_manager,
+ **kwargs,
+ ):
+ chunks: list[ChatGenerationChunk] = []
+ run_id: str | None = (
+ f"{LC_ID_PREFIX}-{run_manager.run_id}" if run_manager else None
+ )
+ yielded = False
+ index = -1
+ index_type = ""
+ async for chunk in self._astream(messages, stop=stop, **kwargs):
+ chunk.message.response_metadata = _gen_info_and_msg_metadata(chunk)
+ if self.output_version == "v1":
+ # Overwrite .content with .content_blocks
+ chunk.message = _update_message_content_to_blocks(
+ chunk.message, "v1"
+ )
+ for block in cast(
+ "list[types.ContentBlock]", chunk.message.content
+ ):
+ if block["type"] != index_type:
+ index_type = block["type"]
+ index += 1
+ if "index" not in block:
+ block["index"] = index
+ if run_manager:
+ if chunk.message.id is None:
+ chunk.message.id = run_id
+ await run_manager.on_llm_new_token(
+ cast("str", chunk.message.content), chunk=chunk
+ )
+ chunks.append(chunk)
+ yielded = True
+
+ # Yield a final empty chunk with chunk_position="last" if not yet yielded
+ if (
+ yielded
+ and isinstance(chunk.message, AIMessageChunk)
+ and not chunk.message.chunk_position
+ ):
+ empty_content: str | list = (
+ "" if isinstance(chunk.message.content, str) else []
+ )
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(
+ content=empty_content, chunk_position="last", id=run_id
+ )
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token("", chunk=chunk)
+ chunks.append(chunk)
+ result = generate_from_stream(iter(chunks))
+ elif inspect.signature(self._agenerate).parameters.get("run_manager"):
+ result = await self._agenerate(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ else:
+ result = await self._agenerate(messages, stop=stop, **kwargs)
+
+ if self.output_version == "v1":
+ # Overwrite .content with .content_blocks
+ for generation in result.generations:
+ generation.message = _update_message_content_to_blocks(
+ generation.message, "v1"
+ )
+
+ # Add response metadata to each generation
+ for idx, generation in enumerate(result.generations):
+ if run_manager and generation.message.id is None:
+ generation.message.id = f"{LC_ID_PREFIX}-{run_manager.run_id}-{idx}"
+ generation.message.response_metadata = _gen_info_and_msg_metadata(
+ generation
+ )
+ if len(result.generations) == 1 and result.llm_output is not None:
+ result.generations[0].message.response_metadata = {
+ **result.llm_output,
+ **result.generations[0].message.response_metadata,
+ }
+ if check_cache and llm_cache:
+ await llm_cache.aupdate(prompt, llm_string, result.generations)
+ return result
+
+ @abstractmethod
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate the result.
+
+ Args:
+ messages: The messages to generate from.
+ stop: Optional list of stop words to use when generating.
+ run_manager: Optional callback manager to use for this call.
+ **kwargs: Additional keyword arguments to pass to the model.
+
+ Returns:
+ The chat result.
+ """
+
+ async def _agenerate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ """Generate the result.
+
+ Args:
+ messages: The messages to generate from.
+ stop: Optional list of stop words to use when generating.
+ run_manager: Optional callback manager to use for this call.
+ **kwargs: Additional keyword arguments to pass to the model.
+
+ Returns:
+ The chat result.
+ """
+ return await run_in_executor(
+ None,
+ self._generate,
+ messages,
+ stop,
+ run_manager.get_sync() if run_manager else None,
+ **kwargs,
+ )
+
+ def _stream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ """Stream the output of the model.
+
+ Args:
+ messages: The messages to generate from.
+ stop: Optional list of stop words to use when generating.
+ run_manager: Optional callback manager to use for this call.
+ **kwargs: Additional keyword arguments to pass to the model.
+
+ Yields:
+ The chat generation chunks.
+ """
+ raise NotImplementedError
+
+ async def _astream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ """Stream the output of the model.
+
+ Args:
+ messages: The messages to generate from.
+ stop: Optional list of stop words to use when generating.
+ run_manager: Optional callback manager to use for this call.
+ **kwargs: Additional keyword arguments to pass to the model.
+
+ Yields:
+ The chat generation chunks.
+ """
+ iterator = await run_in_executor(
+ None,
+ self._stream,
+ messages,
+ stop,
+ run_manager.get_sync() if run_manager else None,
+ **kwargs,
+ )
+ done = object()
+ while True:
+ item = await run_in_executor(
+ None,
+ next,
+ iterator,
+ done,
+ )
+ if item is done:
+ break
+ yield item # type: ignore[misc]
+
+ async def _call_async(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ **kwargs: Any,
+ ) -> BaseMessage:
+ result = await self.agenerate(
+ [messages], stop=stop, callbacks=callbacks, **kwargs
+ )
+ generation = result.generations[0][0]
+ if isinstance(generation, ChatGeneration):
+ return generation.message
+ msg = "Unexpected generation type"
+ raise ValueError(msg)
+
+ @property
+ @abstractmethod
+ def _llm_type(self) -> str:
+ """Return type of chat model."""
+
+ @override
+ def dict(self, **kwargs: Any) -> dict:
+ """Return a dictionary of the LLM."""
+ starter_dict = dict(self._identifying_params)
+ starter_dict["_type"] = self._llm_type
+ return starter_dict
+
+ @override
+ def bind(self, **kwargs: Any) -> _ChatModelBinding:
+ """Bind kwargs to this chat model, returning a typed `_ChatModelBinding`.
+
+ Overrides `Runnable.bind` so the result preserves chat-model-specific
+ `stream_events` / `astream_events` overloads. Without this override,
+ `model.bind(...).stream_events(version="v3")` would type as
+ `Iterator[Any]` and `await model.bind(...).astream_events(version="v3")`
+ as `Any`, forcing callers to `cast`.
+ """
+ return _ChatModelBinding(bound=self, kwargs=kwargs, config={})
+
+ def bind_tools(
+ self,
+ tools: Sequence[builtins.dict[str, Any] | type | Callable | BaseTool],
+ *,
+ tool_choice: str | None = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tools to the model.
+
+ Args:
+ tools: Sequence of tools to bind to the model.
+ tool_choice: The tool to use. If "any" then any tool can be used.
+
+ Returns:
+ A Runnable that returns a message.
+
+ """
+ raise NotImplementedError
+
+ def with_structured_output(
+ self,
+ schema: builtins.dict[str, Any] | type,
+ *,
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, builtins.dict[str, Any] | BaseModel]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema: The output schema. Can be passed in as:
+
+ - An OpenAI function/tool schema,
+ - A JSON Schema,
+ - A `TypedDict` class,
+ - Or a Pydantic class.
+
+ If `schema` is a Pydantic class then the model output will be a
+ Pydantic instance of that class, and the model-generated fields will be
+ validated by the Pydantic class. Otherwise the model output will be a
+ dict and will not be validated.
+
+ See `langchain_core.utils.function_calling.convert_to_openai_tool` for
+ more on how to properly specify types and descriptions of schema fields
+ when specifying a Pydantic or `TypedDict` class.
+
+ include_raw:
+ If `False` then only the parsed structured output is returned.
+
+ If an error occurs during model output parsing it will be raised.
+
+ If `True` then both the raw model response (a `BaseMessage`) and the
+ parsed model response will be returned.
+
+ If an error occurs during output parsing it will be caught and returned
+ as well.
+
+ The final output is always a `dict` with keys `'raw'`, `'parsed'`, and
+ `'parsing_error'`.
+
+ Raises:
+ ValueError: If there are any unsupported `kwargs`.
+ NotImplementedError: If the model does not implement
+ `with_structured_output()`.
+
+ Returns:
+ A `Runnable` that takes same inputs as a
+ `langchain_core.language_models.chat.BaseChatModel`. If `include_raw` is
+ `False` and `schema` is a Pydantic class, `Runnable` outputs an instance
+ of `schema` (i.e., a Pydantic object). Otherwise, if `include_raw` is
+ `False` then `Runnable` outputs a `dict`.
+
+ If `include_raw` is `True`, then `Runnable` outputs a `dict` with keys:
+
+ - `'raw'`: `BaseMessage`
+ - `'parsed'`: `None` if there was a parsing error, otherwise the type
+ depends on the `schema` as described above.
+ - `'parsing_error'`: `BaseException | None`
+
+ ???+ example "Pydantic schema (`include_raw=False`)"
+
+ ```python
+ from pydantic import BaseModel
+
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+
+ answer: str
+ justification: str
+
+
+ model = ChatModel(model="model-name", temperature=0)
+ structured_model = model.with_structured_output(AnswerWithJustification)
+
+ structured_model.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+
+ # -> AnswerWithJustification(
+ # answer='They weigh the same',
+ # justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'
+ # )
+ ```
+
+ ??? example "Pydantic schema (`include_raw=True`)"
+
+ ```python
+ from pydantic import BaseModel
+
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+
+ answer: str
+ justification: str
+
+
+ model = ChatModel(model="model-name", temperature=0)
+ structured_model = model.with_structured_output(
+ AnswerWithJustification, include_raw=True
+ )
+
+ structured_model.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+ # -> {
+ # 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_Ao02pnFYXD6GN1yzc0uXPsvF', 'function': {'arguments': '{"answer":"They weigh the same.","justification":"Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ."}', 'name': 'AnswerWithJustification'}, 'type': 'function'}]}),
+ # 'parsed': AnswerWithJustification(answer='They weigh the same.', justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'),
+ # 'parsing_error': None
+ # }
+ ```
+
+ ??? example "Dictionary schema (`include_raw=False`)"
+
+ ```python
+ from pydantic import BaseModel
+ from langchain_core.utils.function_calling import convert_to_openai_tool
+
+
+ class AnswerWithJustification(BaseModel):
+ '''An answer to the user question along with justification for the answer.'''
+
+ answer: str
+ justification: str
+
+
+ dict_schema = convert_to_openai_tool(AnswerWithJustification)
+ model = ChatModel(model="model-name", temperature=0)
+ structured_model = model.with_structured_output(dict_schema)
+
+ structured_model.invoke(
+ "What weighs more a pound of bricks or a pound of feathers"
+ )
+ # -> {
+ # 'answer': 'They weigh the same',
+ # 'justification': 'Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume and density of the two substances differ.'
+ # }
+ ```
+
+ !!! warning "Behavior changed in `langchain-core` 0.2.26"
+
+ Added support for `TypedDict` class.
+
+ """ # noqa: E501
+ _ = kwargs.pop("method", None)
+ _ = kwargs.pop("strict", None)
+ if kwargs:
+ msg = f"Received unsupported arguments {kwargs}"
+ raise ValueError(msg)
+
+ if type(self).bind_tools is BaseChatModel.bind_tools:
+ msg = "with_structured_output is not implemented for this model."
+ raise NotImplementedError(msg)
+
+ llm = self.bind_tools(
+ [schema],
+ tool_choice="any",
+ ls_structured_output_format={
+ "kwargs": {"method": "function_calling"},
+ "schema": schema,
+ },
+ )
+ if isinstance(schema, type) and is_basemodel_subclass(schema):
+ output_parser: OutputParserLike = PydanticToolsParser(
+ tools=[cast("TypeBaseModel", schema)], first_tool_only=True
+ )
+ else:
+ key_name = convert_to_openai_tool(schema)["function"]["name"]
+ output_parser = JsonOutputKeyToolsParser(
+ key_name=key_name, first_tool_only=True
+ )
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ return llm | output_parser
+
+
+class _ChatModelBinding(RunnableBinding[LanguageModelInput, AIMessage]): # type: ignore[no-redef]
+ """`RunnableBinding` that preserves chat-model-typed v3 overloads.
+
+ Returned by `BaseChatModel.bind` so that callers of the bound runnable's
+ `stream_events(version="v3")` / `astream_events(version="v3")` get the
+ typed `ChatModelStream` / `AsyncChatModelStream` back without needing
+ `cast`. At runtime this is a plain `RunnableBinding`; the subclass
+ exists purely to give the type checker a more specific surface.
+
+ The chat-model narrowing is preserved across further `bind` /
+ `with_config` calls because `RunnableBinding.bind` constructs its
+ result via `self.__class__(...)`.
+ """
+
+ @classmethod
+ @override
+ def lc_id(cls) -> list[str]:
+ """Serialize as `RunnableBinding`.
+
+ At runtime this class is behaviorally identical to `RunnableBinding`;
+ keeping the serialized id stable means existing snapshots and the
+ load mapping continue to work without registering a new entry.
+ """
+ return [*cls.get_lc_namespace(), "RunnableBinding"]
+
+ @overload # type: ignore[override]
+ def stream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent]: ...
+
+ @overload
+ def stream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> ChatModelStream: ...
+
+ def stream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent] | ChatModelStream:
+ return super().stream_events(input, config, version=version, **kwargs)
+
+ @overload
+ def astream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent]: ...
+
+ @overload
+ def astream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Awaitable[AsyncChatModelStream]: ...
+
+ def astream_events(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent] | Awaitable[AsyncChatModelStream]:
+ return cast(
+ "AsyncIterator[StreamEvent] | Awaitable[AsyncChatModelStream]",
+ super().astream_events(input, config, **kwargs),
+ )
+
+
+class SimpleChatModel(BaseChatModel):
+ """Simplified implementation for a chat model to inherit from.
+
+ !!! note
+ This implementation is primarily here for backwards compatibility. For new
+ implementations, please use `BaseChatModel` directly.
+
+ """
+
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ output_str = self._call(messages, stop=stop, run_manager=run_manager, **kwargs)
+ message = AIMessage(content=output_str)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @abstractmethod
+ def _call(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Simpler interface."""
+
+ async def _agenerate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ return await run_in_executor(
+ None,
+ self._generate,
+ messages,
+ stop=stop,
+ run_manager=run_manager.get_sync() if run_manager else None,
+ **kwargs,
+ )
+
+
+def _gen_info_and_msg_metadata(
+ generation: ChatGeneration | ChatGenerationChunk,
+) -> dict:
+ return {
+ **(generation.generation_info or {}),
+ **generation.message.response_metadata,
+ }
+
+
+_MAX_CLEANUP_DEPTH = 100
+
+
+def _cleanup_llm_representation(serialized: Any, depth: int) -> None:
+ """Remove non-serializable objects from a serialized object."""
+ if depth > _MAX_CLEANUP_DEPTH: # Don't cooperate for pathological cases
+ return
+
+ if not isinstance(serialized, dict):
+ return
+
+ if (
+ "type" in serialized
+ and serialized["type"] == "not_implemented"
+ and "repr" in serialized
+ ):
+ del serialized["repr"]
+
+ if "graph" in serialized:
+ del serialized["graph"]
+
+ if "kwargs" in serialized:
+ kwargs = serialized["kwargs"]
+
+ for value in kwargs.values():
+ _cleanup_llm_representation(value, depth + 1)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/fake.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/fake.py
new file mode 100644
index 0000000000000000000000000000000000000000..77b7cdd4ac66a6ed13f01df0b5d1bdb723babe75
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/fake.py
@@ -0,0 +1,137 @@
+"""Fake LLMs for testing purposes."""
+
+import asyncio
+import time
+from collections.abc import AsyncIterator, Iterator, Mapping
+from typing import Any
+
+from typing_extensions import override
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import LanguageModelInput
+from langchain_core.language_models.llms import LLM
+from langchain_core.runnables import RunnableConfig
+
+
+class FakeListLLM(LLM):
+ """Fake LLM for testing purposes."""
+
+ responses: list[str]
+ """List of responses to return in order."""
+ # This parameter should be removed from FakeListLLM since
+ # it's only used by sub-classes.
+ sleep: float | None = None
+ """Sleep time in seconds between responses.
+
+ Ignored by FakeListLLM, but used by sub-classes.
+ """
+ i: int = 0
+ """Internally incremented after every model invocation.
+
+ Useful primarily for testing purposes.
+ """
+
+ @property
+ @override
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "fake-list"
+
+ @override
+ def _call(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Return next response."""
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ return response
+
+ @override
+ async def _acall(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Return next response."""
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ return response
+
+ @property
+ @override
+ def _identifying_params(self) -> Mapping[str, Any]:
+ return {"responses": self.responses}
+
+
+class FakeListLLMError(Exception):
+ """Fake error for testing purposes."""
+
+
+class FakeStreamingListLLM(FakeListLLM):
+ """Fake streaming list LLM for testing purposes.
+
+ An LLM that will return responses from a list in order.
+
+ This model also supports optionally sleeping between successive
+ chunks in a streaming implementation.
+ """
+
+ error_on_chunk_number: int | None = None
+ """If set, will raise an exception on the specified chunk number."""
+
+ @override
+ def stream(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[str]:
+ result = self.invoke(input, config)
+ for i_c, c in enumerate(result):
+ if self.sleep is not None:
+ time.sleep(self.sleep)
+
+ if (
+ self.error_on_chunk_number is not None
+ and i_c == self.error_on_chunk_number
+ ):
+ raise FakeListLLMError
+ yield c
+
+ @override
+ async def astream(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[str]:
+ result = await self.ainvoke(input, config)
+ for i_c, c in enumerate(result):
+ if self.sleep is not None:
+ await asyncio.sleep(self.sleep)
+
+ if (
+ self.error_on_chunk_number is not None
+ and i_c == self.error_on_chunk_number
+ ):
+ raise FakeListLLMError
+ yield c
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/fake_chat_models.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/fake_chat_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..12e5a73fdf5121e53f79bae5e4639abbae7f03ad
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/fake_chat_models.py
@@ -0,0 +1,396 @@
+"""Fake chat models for testing purposes."""
+
+import asyncio
+import re
+import time
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, Literal, cast
+
+from typing_extensions import override
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.chat_models import BaseChatModel, SimpleChatModel
+from langchain_core.messages import AIMessage, AIMessageChunk, BaseMessage
+from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
+from langchain_core.runnables import RunnableConfig
+
+
+class FakeMessagesListChatModel(BaseChatModel):
+ """Fake chat model for testing purposes."""
+
+ responses: list[BaseMessage]
+ """List of responses to **cycle** through in order."""
+ sleep: float | None = None
+ """Sleep time in seconds between responses."""
+ i: int = 0
+ """Internally incremented after every model invocation."""
+
+ @override
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if self.sleep is not None:
+ time.sleep(self.sleep)
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ generation = ChatGeneration(message=response)
+ return ChatResult(generations=[generation])
+
+ @property
+ @override
+ def _llm_type(self) -> str:
+ return "fake-messages-list-chat-model"
+
+
+class FakeListChatModelError(Exception):
+ """Fake error for testing purposes."""
+
+
+class FakeListChatModel(SimpleChatModel):
+ """Fake chat model for testing purposes."""
+
+ responses: list[str]
+ """List of responses to **cycle** through in order."""
+ sleep: float | None = None
+ i: int = 0
+ """Internally incremented after every model invocation."""
+ error_on_chunk_number: int | None = None
+ """If set, raise an error on the specified chunk number during streaming."""
+
+ @property
+ @override
+ def _llm_type(self) -> str:
+ return "fake-list-chat-model"
+
+ @override
+ def _call(
+ self,
+ *args: Any,
+ **kwargs: Any,
+ ) -> str:
+ """Return the next response in the list.
+
+ Cycle back to the start if at the end.
+ """
+ if self.sleep is not None:
+ time.sleep(self.sleep)
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ return response
+
+ @override
+ def _stream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ for i_c, c in enumerate(response):
+ if self.sleep is not None:
+ time.sleep(self.sleep)
+ if (
+ self.error_on_chunk_number is not None
+ and i_c == self.error_on_chunk_number
+ ):
+ raise FakeListChatModelError
+
+ chunk_position: Literal["last"] | None = (
+ "last" if i_c == len(response) - 1 else None
+ )
+ yield ChatGenerationChunk(
+ message=AIMessageChunk(content=c, chunk_position=chunk_position)
+ )
+
+ @override
+ async def _astream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ response = self.responses[self.i]
+ if self.i < len(self.responses) - 1:
+ self.i += 1
+ else:
+ self.i = 0
+ for i_c, c in enumerate(response):
+ if self.sleep is not None:
+ await asyncio.sleep(self.sleep)
+ if (
+ self.error_on_chunk_number is not None
+ and i_c == self.error_on_chunk_number
+ ):
+ raise FakeListChatModelError
+ chunk_position: Literal["last"] | None = (
+ "last" if i_c == len(response) - 1 else None
+ )
+ yield ChatGenerationChunk(
+ message=AIMessageChunk(content=c, chunk_position=chunk_position)
+ )
+
+ @property
+ @override
+ def _identifying_params(self) -> dict[str, Any]:
+ return {"responses": self.responses}
+
+ @override
+ # manually override batch to preserve batch ordering with no concurrency
+ def batch(
+ self,
+ inputs: list[Any],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any,
+ ) -> list[AIMessage]:
+ if isinstance(config, list):
+ return [
+ self.invoke(m, c, **kwargs)
+ for m, c in zip(inputs, config, strict=False)
+ ]
+ return [self.invoke(m, config, **kwargs) for m in inputs]
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[Any],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any,
+ ) -> list[AIMessage]:
+ if isinstance(config, list):
+ # do Not use an async iterator here because need explicit ordering
+ return [
+ await self.ainvoke(m, c, **kwargs)
+ for m, c in zip(inputs, config, strict=False)
+ ]
+ # do Not use an async iterator here because need explicit ordering
+ return [await self.ainvoke(m, config, **kwargs) for m in inputs]
+
+
+class FakeChatModel(SimpleChatModel):
+ """Fake Chat Model wrapper for testing purposes."""
+
+ @override
+ def _call(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ return "fake response"
+
+ @override
+ async def _agenerate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ output_str = "fake response"
+ message = AIMessage(content=output_str)
+ generation = ChatGeneration(message=message)
+ return ChatResult(generations=[generation])
+
+ @property
+ def _llm_type(self) -> str:
+ return "fake-chat-model"
+
+ @property
+ def _identifying_params(self) -> dict[str, Any]:
+ return {"key": "fake"}
+
+
+class GenericFakeChatModel(BaseChatModel):
+ """Generic fake chat model that can be used to test the chat model interface.
+
+ * Chat model should be usable in both sync and async tests
+ * Invokes `on_llm_new_token` to allow for testing of callback related code for new
+ tokens.
+ * Includes logic to break messages into message chunk to facilitate testing of
+ streaming.
+
+ """
+
+ messages: Iterator[AIMessage | str]
+ """Get an iterator over messages.
+
+ This can be expanded to accept other types like Callables / dicts / strings
+ to make the interface more generic if needed.
+
+ !!! note
+ if you want to pass a list, you can use `iter` to convert it to an iterator.
+
+ !!! warning
+ Streaming is not implemented yet. We should try to implement it in the future by
+ delegating to invoke and then breaking the resulting output into message chunks.
+
+ """
+
+ @override
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ message = next(self.messages)
+ message_ = AIMessage(content=message) if isinstance(message, str) else message
+ generation = ChatGeneration(message=message_)
+ return ChatResult(generations=[generation])
+
+ def _stream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ chat_result = self._generate(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ if not isinstance(chat_result, ChatResult):
+ msg = (
+ f"Expected generate to return a ChatResult, "
+ f"but got {type(chat_result)} instead."
+ )
+ raise ValueError(msg) # noqa: TRY004
+
+ message = chat_result.generations[0].message
+
+ if not isinstance(message, AIMessage):
+ msg = (
+ f"Expected invoke to return an AIMessage, "
+ f"but got {type(message)} instead."
+ )
+ raise ValueError(msg) # noqa: TRY004
+
+ content = message.content
+
+ if content:
+ # Use a regular expression to split on whitespace with a capture group
+ # so that we can preserve the whitespace in the output.
+ if not isinstance(content, str):
+ msg = "Expected content to be a string."
+ raise ValueError(msg)
+
+ content_chunks = cast("list[str]", re.split(r"(\s)", content))
+
+ for idx, token in enumerate(content_chunks):
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(content=token, id=message.id)
+ )
+ if (
+ idx == len(content_chunks) - 1
+ and isinstance(chunk.message, AIMessageChunk)
+ and not message.additional_kwargs
+ ):
+ chunk.message.chunk_position = "last"
+ if run_manager:
+ run_manager.on_llm_new_token(token, chunk=chunk)
+ yield chunk
+
+ if message.additional_kwargs:
+ for key, value in message.additional_kwargs.items():
+ # We should further break down the additional kwargs into chunks
+ # Special case for function call
+ if key == "function_call":
+ for fkey, fvalue in value.items():
+ if isinstance(fvalue, str):
+ # Break function call by `,`
+ fvalue_chunks = cast("list[str]", re.split(r"(,)", fvalue))
+ for fvalue_chunk in fvalue_chunks:
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(
+ id=message.id,
+ content="",
+ additional_kwargs={
+ "function_call": {fkey: fvalue_chunk}
+ },
+ )
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(
+ "",
+ chunk=chunk, # No token for function call
+ )
+ yield chunk
+ else:
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(
+ id=message.id,
+ content="",
+ additional_kwargs={"function_call": {fkey: fvalue}},
+ )
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(
+ "",
+ chunk=chunk, # No token for function call
+ )
+ yield chunk
+ else:
+ chunk = ChatGenerationChunk(
+ message=AIMessageChunk(
+ id=message.id, content="", additional_kwargs={key: value}
+ )
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(
+ "",
+ chunk=chunk, # No token for function call
+ )
+ yield chunk
+
+ @property
+ def _llm_type(self) -> str:
+ return "generic-fake-chat-model"
+
+
+class ParrotFakeChatModel(BaseChatModel):
+ """Generic fake chat model that can be used to test the chat model interface.
+
+ * Chat model should be usable in both sync and async tests
+
+ """
+
+ @override
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> ChatResult:
+ if not messages:
+ msg = "messages list cannot be empty."
+ raise ValueError(msg)
+ return ChatResult(generations=[ChatGeneration(message=messages[-1])])
+
+ @property
+ def _llm_type(self) -> str:
+ return "parrot-fake-chat-model"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/llms.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/llms.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ace9cb554a151f69b7b6fc411bf73ba09bff6eb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/llms.py
@@ -0,0 +1,1553 @@
+"""Base interface for traditional large language models (LLMs) to expose.
+
+These are traditionally older models (newer models generally are chat models).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import functools
+import inspect
+import json
+import logging
+from abc import ABC, abstractmethod
+from collections.abc import AsyncIterator, Callable, Iterator, Sequence
+from pathlib import Path
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ cast,
+)
+
+import yaml
+from pydantic import ConfigDict
+from tenacity import (
+ RetryCallState,
+ before_sleep_log,
+ retry,
+ retry_base,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential,
+)
+from typing_extensions import override
+
+from langchain_core.caches import BaseCache
+from langchain_core.callbacks import (
+ AsyncCallbackManager,
+ AsyncCallbackManagerForLLMRun,
+ BaseCallbackManager,
+ CallbackManager,
+ CallbackManagerForLLMRun,
+ Callbacks,
+)
+from langchain_core.globals import get_llm_cache
+from langchain_core.language_models._utils import _filter_invocation_params_for_tracing
+from langchain_core.language_models.base import (
+ BaseLanguageModel,
+ LangSmithParams,
+ LanguageModelInput,
+)
+from langchain_core.load import dumpd
+from langchain_core.messages import (
+ convert_to_messages,
+)
+from langchain_core.outputs import Generation, GenerationChunk, LLMResult, RunInfo
+from langchain_core.prompt_values import ChatPromptValue, PromptValue, StringPromptValue
+from langchain_core.runnables import RunnableConfig, ensure_config, get_config_list
+from langchain_core.runnables.config import run_in_executor
+
+if TYPE_CHECKING:
+ import uuid
+
+logger = logging.getLogger(__name__)
+
+_background_tasks: set[asyncio.Task] = set()
+
+
+@functools.lru_cache
+def _log_error_once(msg: str) -> None:
+ """Log an error once."""
+ logger.error(msg)
+
+
+def create_base_retry_decorator(
+ error_types: list[type[BaseException]],
+ max_retries: int = 1,
+ run_manager: AsyncCallbackManagerForLLMRun | CallbackManagerForLLMRun | None = None,
+) -> Callable[[Any], Any]:
+ """Create a retry decorator for a given LLM and provided a list of error types.
+
+ Args:
+ error_types: List of error types to retry on.
+ max_retries: Number of retries.
+ run_manager: Callback manager for the run.
+
+ Returns:
+ A retry decorator.
+
+ Raises:
+ ValueError: If the cache is not set and cache is True.
+ """
+ logging_ = before_sleep_log(logger, logging.WARNING)
+
+ def _before_sleep(retry_state: RetryCallState) -> None:
+ logging_(retry_state)
+ if run_manager:
+ if isinstance(run_manager, AsyncCallbackManagerForLLMRun):
+ coro = run_manager.on_retry(retry_state)
+ try:
+ try:
+ loop = asyncio.get_event_loop()
+ except RuntimeError:
+ asyncio.run(coro)
+ else:
+ if loop.is_running():
+ task = loop.create_task(coro)
+ _background_tasks.add(task)
+ task.add_done_callback(_background_tasks.discard)
+ else:
+ asyncio.run(coro)
+ except Exception as e:
+ _log_error_once(f"Error in on_retry: {e}")
+ else:
+ run_manager.on_retry(retry_state)
+
+ min_seconds = 4
+ max_seconds = 10
+ # Wait 2^x * 1 second between each retry starting with
+ # 4 seconds, then up to 10 seconds, then 10 seconds afterwards
+ retry_instance: retry_base = retry_if_exception_type(error_types[0])
+ for error in error_types[1:]:
+ retry_instance |= retry_if_exception_type(error)
+ return retry(
+ reraise=True,
+ stop=stop_after_attempt(max_retries),
+ wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds),
+ retry=retry_instance,
+ before_sleep=_before_sleep,
+ )
+
+
+def _resolve_cache(*, cache: BaseCache | bool | None) -> BaseCache | None:
+ """Resolve the cache."""
+ llm_cache: BaseCache | None
+ if isinstance(cache, BaseCache):
+ llm_cache = cache
+ elif cache is None:
+ llm_cache = get_llm_cache()
+ elif cache is True:
+ llm_cache = get_llm_cache()
+ if llm_cache is None:
+ msg = (
+ "No global cache was configured. Use `set_llm_cache`."
+ "to set a global cache if you want to use a global cache."
+ "Otherwise either pass a cache object or set cache to False/None"
+ )
+ raise ValueError(msg)
+ elif cache is False:
+ llm_cache = None
+ else:
+ msg = f"Unsupported cache value {cache}"
+ raise ValueError(msg)
+ return llm_cache
+
+
+def get_prompts(
+ params: dict[str, Any],
+ prompts: list[str],
+ cache: BaseCache | bool | None = None, # noqa: FBT001
+) -> tuple[dict[int, list], str, list[int], list[str]]:
+ """Get prompts that are already cached.
+
+ Args:
+ params: Dictionary of parameters.
+ prompts: List of prompts.
+ cache: Cache object.
+
+ Returns:
+ A tuple of existing prompts, llm_string, missing prompt indexes,
+ and missing prompts.
+
+ Raises:
+ ValueError: If the cache is not set and cache is True.
+ """
+ llm_string = str(sorted(params.items()))
+ missing_prompts = []
+ missing_prompt_idxs = []
+ existing_prompts = {}
+
+ llm_cache = _resolve_cache(cache=cache)
+ for i, prompt in enumerate(prompts):
+ if llm_cache:
+ cache_val = llm_cache.lookup(prompt, llm_string)
+ if isinstance(cache_val, list):
+ existing_prompts[i] = cache_val
+ else:
+ missing_prompts.append(prompt)
+ missing_prompt_idxs.append(i)
+ return existing_prompts, llm_string, missing_prompt_idxs, missing_prompts
+
+
+async def aget_prompts(
+ params: dict[str, Any],
+ prompts: list[str],
+ cache: BaseCache | bool | None = None, # noqa: FBT001
+) -> tuple[dict[int, list], str, list[int], list[str]]:
+ """Get prompts that are already cached. Async version.
+
+ Args:
+ params: Dictionary of parameters.
+ prompts: List of prompts.
+ cache: Cache object.
+
+ Returns:
+ A tuple of existing prompts, llm_string, missing prompt indexes,
+ and missing prompts.
+
+ Raises:
+ ValueError: If the cache is not set and cache is True.
+ """
+ llm_string = str(sorted(params.items()))
+ missing_prompts = []
+ missing_prompt_idxs = []
+ existing_prompts = {}
+ llm_cache = _resolve_cache(cache=cache)
+ for i, prompt in enumerate(prompts):
+ if llm_cache:
+ cache_val = await llm_cache.alookup(prompt, llm_string)
+ if isinstance(cache_val, list):
+ existing_prompts[i] = cache_val
+ else:
+ missing_prompts.append(prompt)
+ missing_prompt_idxs.append(i)
+ return existing_prompts, llm_string, missing_prompt_idxs, missing_prompts
+
+
+def update_cache(
+ cache: BaseCache | bool | None, # noqa: FBT001
+ existing_prompts: dict[int, list],
+ llm_string: str,
+ missing_prompt_idxs: list[int],
+ new_results: LLMResult,
+ prompts: list[str],
+) -> dict | None:
+ """Update the cache and get the LLM output.
+
+ Args:
+ cache: Cache object.
+ existing_prompts: Dictionary of existing prompts.
+ llm_string: LLM string.
+ missing_prompt_idxs: List of missing prompt indexes.
+ new_results: LLMResult object.
+ prompts: List of prompts.
+
+ Returns:
+ LLM output.
+
+ Raises:
+ ValueError: If the cache is not set and cache is True.
+ """
+ llm_cache = _resolve_cache(cache=cache)
+ for i, result in enumerate(new_results.generations):
+ existing_prompts[missing_prompt_idxs[i]] = result
+ prompt = prompts[missing_prompt_idxs[i]]
+ if llm_cache is not None:
+ llm_cache.update(prompt, llm_string, result)
+ return new_results.llm_output
+
+
+async def aupdate_cache(
+ cache: BaseCache | bool | None, # noqa: FBT001
+ existing_prompts: dict[int, list],
+ llm_string: str,
+ missing_prompt_idxs: list[int],
+ new_results: LLMResult,
+ prompts: list[str],
+) -> dict | None:
+ """Update the cache and get the LLM output. Async version.
+
+ Args:
+ cache: Cache object.
+ existing_prompts: Dictionary of existing prompts.
+ llm_string: LLM string.
+ missing_prompt_idxs: List of missing prompt indexes.
+ new_results: LLMResult object.
+ prompts: List of prompts.
+
+ Returns:
+ LLM output.
+
+ Raises:
+ ValueError: If the cache is not set and cache is True.
+ """
+ llm_cache = _resolve_cache(cache=cache)
+ for i, result in enumerate(new_results.generations):
+ existing_prompts[missing_prompt_idxs[i]] = result
+ prompt = prompts[missing_prompt_idxs[i]]
+ if llm_cache:
+ await llm_cache.aupdate(prompt, llm_string, result)
+ return new_results.llm_output
+
+
+class BaseLLM(BaseLanguageModel[str], ABC):
+ """Base LLM abstract interface.
+
+ It should take in a prompt and return a string.
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @functools.cached_property
+ def _serialized(self) -> dict[str, Any]:
+ # self is always a Serializable object in this case, thus the result is
+ # guaranteed to be a dict since dumps uses the default callback, which uses
+ # obj.to_json which always returns TypedDict subclasses
+ return cast("dict[str, Any]", dumpd(self))
+
+ # --- Runnable methods ---
+
+ @property
+ @override
+ def OutputType(self) -> type[str]:
+ """Get the output type for this `Runnable`."""
+ return str
+
+ def _convert_input(self, model_input: LanguageModelInput) -> PromptValue:
+ if isinstance(model_input, PromptValue):
+ return model_input
+ if isinstance(model_input, str):
+ return StringPromptValue(text=model_input)
+ if isinstance(model_input, Sequence):
+ return ChatPromptValue(messages=convert_to_messages(model_input))
+ msg = (
+ f"Invalid input type {type(model_input)}. "
+ "Must be a PromptValue, str, or list of BaseMessages."
+ )
+ raise ValueError(msg)
+
+ def _get_ls_params(
+ self,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> LangSmithParams:
+ """Get standard params for tracing."""
+ # get default provider from class name
+ default_provider = self.__class__.__name__
+ default_provider = default_provider.removesuffix("LLM")
+ default_provider = default_provider.lower()
+
+ ls_params = LangSmithParams(ls_provider=default_provider, ls_model_type="llm")
+ if stop:
+ ls_params["ls_stop"] = stop
+
+ # model
+ if "model" in kwargs and isinstance(kwargs["model"], str):
+ ls_params["ls_model_name"] = kwargs["model"]
+ elif hasattr(self, "model") and isinstance(self.model, str):
+ ls_params["ls_model_name"] = self.model
+ elif hasattr(self, "model_name") and isinstance(self.model_name, str):
+ ls_params["ls_model_name"] = self.model_name
+
+ # temperature
+ if "temperature" in kwargs and isinstance(kwargs["temperature"], (int, float)):
+ ls_params["ls_temperature"] = kwargs["temperature"]
+ elif hasattr(self, "temperature") and isinstance(
+ self.temperature, (int, float)
+ ):
+ ls_params["ls_temperature"] = self.temperature
+
+ # max_tokens
+ if "max_tokens" in kwargs and isinstance(kwargs["max_tokens"], int):
+ ls_params["ls_max_tokens"] = kwargs["max_tokens"]
+ elif hasattr(self, "max_tokens") and isinstance(self.max_tokens, int):
+ ls_params["ls_max_tokens"] = self.max_tokens
+
+ return ls_params
+
+ @override
+ def invoke(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> str:
+ config = ensure_config(config)
+ return (
+ self.generate_prompt(
+ [self._convert_input(input)],
+ stop=stop,
+ callbacks=config.get("callbacks"),
+ tags=config.get("tags"),
+ metadata=config.get("metadata"),
+ run_name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ **kwargs,
+ )
+ .generations[0][0]
+ .text
+ )
+
+ @override
+ async def ainvoke(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> str:
+ config = ensure_config(config)
+ llm_result = await self.agenerate_prompt(
+ [self._convert_input(input)],
+ stop=stop,
+ callbacks=config.get("callbacks"),
+ tags=config.get("tags"),
+ metadata=config.get("metadata"),
+ run_name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ **kwargs,
+ )
+ return llm_result.generations[0][0].text
+
+ @override
+ def batch(
+ self,
+ inputs: list[LanguageModelInput],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any,
+ ) -> list[str]:
+ if not inputs:
+ return []
+
+ config = get_config_list(config, len(inputs))
+ max_concurrency = config[0].get("max_concurrency")
+
+ if max_concurrency is None:
+ try:
+ llm_result = self.generate_prompt(
+ [self._convert_input(input_) for input_ in inputs],
+ callbacks=[c.get("callbacks") for c in config],
+ tags=[c.get("tags") for c in config],
+ metadata=[c.get("metadata") for c in config],
+ run_name=[c.get("run_name") for c in config],
+ **kwargs,
+ )
+ return [g[0].text for g in llm_result.generations]
+ except Exception as e:
+ if return_exceptions:
+ return cast("list[str]", [e for _ in inputs])
+ raise
+ else:
+ batches = [
+ inputs[i : i + max_concurrency]
+ for i in range(0, len(inputs), max_concurrency)
+ ]
+ config = [{**c, "max_concurrency": None} for c in config]
+ return [
+ output
+ for i, batch in enumerate(batches)
+ for output in self.batch(
+ batch,
+ config=config[i * max_concurrency : (i + 1) * max_concurrency],
+ return_exceptions=return_exceptions,
+ **kwargs,
+ )
+ ]
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[LanguageModelInput],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any,
+ ) -> list[str]:
+ if not inputs:
+ return []
+ config = get_config_list(config, len(inputs))
+ max_concurrency = config[0].get("max_concurrency")
+
+ if max_concurrency is None:
+ try:
+ llm_result = await self.agenerate_prompt(
+ [self._convert_input(input_) for input_ in inputs],
+ callbacks=[c.get("callbacks") for c in config],
+ tags=[c.get("tags") for c in config],
+ metadata=[c.get("metadata") for c in config],
+ run_name=[c.get("run_name") for c in config],
+ **kwargs,
+ )
+ return [g[0].text for g in llm_result.generations]
+ except Exception as e:
+ if return_exceptions:
+ return cast("list[str]", [e for _ in inputs])
+ raise
+ else:
+ batches = [
+ inputs[i : i + max_concurrency]
+ for i in range(0, len(inputs), max_concurrency)
+ ]
+ config = [{**c, "max_concurrency": None} for c in config]
+ return [
+ output
+ for i, batch in enumerate(batches)
+ for output in await self.abatch(
+ batch,
+ config=config[i * max_concurrency : (i + 1) * max_concurrency],
+ return_exceptions=return_exceptions,
+ **kwargs,
+ )
+ ]
+
+ @override
+ def stream(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[str]:
+ if type(self)._stream == BaseLLM._stream: # noqa: SLF001
+ # model doesn't implement streaming, so use default implementation
+ yield self.invoke(input, config=config, stop=stop, **kwargs)
+ else:
+ prompt = self._convert_input(input).to_string()
+ config = ensure_config(config)
+ params = self.dict()
+ params["stop"] = stop
+ params = {**params, **kwargs}
+ options = {"stop": stop}
+ inheritable_metadata = {
+ **(config.get("metadata") or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ callback_manager = CallbackManager.configure(
+ config.get("callbacks"),
+ self.callbacks,
+ self.verbose,
+ config.get("tags"),
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ (run_manager,) = callback_manager.on_llm_start(
+ self._serialized,
+ [prompt],
+ invocation_params=params,
+ options=options,
+ name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ batch_size=1,
+ )
+ generation: GenerationChunk | None = None
+ try:
+ for chunk in self._stream(
+ prompt, stop=stop, run_manager=run_manager, **kwargs
+ ):
+ yield chunk.text
+ if generation is None:
+ generation = chunk
+ else:
+ generation += chunk
+ except BaseException as e:
+ run_manager.on_llm_error(
+ e,
+ response=LLMResult(
+ generations=[[generation]] if generation else []
+ ),
+ )
+ raise
+
+ if generation is None:
+ err = ValueError("No generation chunks were returned")
+ run_manager.on_llm_error(err, response=LLMResult(generations=[]))
+ raise err
+
+ run_manager.on_llm_end(LLMResult(generations=[[generation]]))
+
+ @override
+ async def astream(
+ self,
+ input: LanguageModelInput,
+ config: RunnableConfig | None = None,
+ *,
+ stop: list[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[str]:
+ if (
+ type(self)._astream is BaseLLM._astream # noqa: SLF001
+ and type(self)._stream is BaseLLM._stream # noqa: SLF001
+ ):
+ yield await self.ainvoke(input, config=config, stop=stop, **kwargs)
+ return
+
+ prompt = self._convert_input(input).to_string()
+ config = ensure_config(config)
+ params = self.dict()
+ params["stop"] = stop
+ params = {**params, **kwargs}
+ options = {"stop": stop}
+ inheritable_metadata = {
+ **(config.get("metadata") or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ callback_manager = AsyncCallbackManager.configure(
+ config.get("callbacks"),
+ self.callbacks,
+ self.verbose,
+ config.get("tags"),
+ self.tags,
+ inheritable_metadata,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ (run_manager,) = await callback_manager.on_llm_start(
+ self._serialized,
+ [prompt],
+ invocation_params=params,
+ options=options,
+ name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ batch_size=1,
+ )
+ generation: GenerationChunk | None = None
+ try:
+ async for chunk in self._astream(
+ prompt,
+ stop=stop,
+ run_manager=run_manager,
+ **kwargs,
+ ):
+ yield chunk.text
+ if generation is None:
+ generation = chunk
+ else:
+ generation += chunk
+ except BaseException as e:
+ await run_manager.on_llm_error(
+ e,
+ response=LLMResult(generations=[[generation]] if generation else []),
+ )
+ raise
+
+ if generation is None:
+ err = ValueError("No generation chunks were returned")
+ await run_manager.on_llm_error(err, response=LLMResult(generations=[]))
+ raise err
+
+ await run_manager.on_llm_end(LLMResult(generations=[[generation]]))
+
+ # --- Custom methods ---
+
+ @abstractmethod
+ def _generate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Run the LLM on the given prompts.
+
+ Args:
+ prompts: The prompts to generate from.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+
+ If stop tokens are not supported consider raising `NotImplementedError`.
+ run_manager: Callback manager for the run.
+
+ Returns:
+ The LLM result.
+ """
+
+ async def _agenerate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Run the LLM on the given prompts.
+
+ Args:
+ prompts: The prompts to generate from.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+
+ If stop tokens are not supported consider raising `NotImplementedError`.
+ run_manager: Callback manager for the run.
+
+ Returns:
+ The LLM result.
+ """
+ return await run_in_executor(
+ None,
+ self._generate,
+ prompts,
+ stop,
+ run_manager.get_sync() if run_manager else None,
+ **kwargs,
+ )
+
+ def _stream(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> Iterator[GenerationChunk]:
+ """Stream the LLM on the given prompt.
+
+ This method should be overridden by subclasses that support streaming.
+
+ If not implemented, the default behavior of calls to stream will be to
+ fallback to the non-streaming version of the model and return
+ the output as a single chunk.
+
+ Args:
+ prompt: The prompt to generate from.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ run_manager: Callback manager for the run.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Yields:
+ Generation chunks.
+ """
+ raise NotImplementedError
+
+ async def _astream(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[GenerationChunk]:
+ """An async version of the _stream method.
+
+ The default implementation uses the synchronous _stream method and wraps it in
+ an async iterator. Subclasses that need to provide a true async implementation
+ should override this method.
+
+ Args:
+ prompt: The prompt to generate from.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ run_manager: Callback manager for the run.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Yields:
+ Generation chunks.
+ """
+ iterator = await run_in_executor(
+ None,
+ self._stream,
+ prompt,
+ stop,
+ run_manager.get_sync() if run_manager else None,
+ **kwargs,
+ )
+ done = object()
+ while True:
+ item = await run_in_executor(
+ None,
+ next,
+ iterator,
+ done,
+ )
+ if item is done:
+ break
+ yield item # type: ignore[misc]
+
+ @override
+ def generate_prompt(
+ self,
+ prompts: list[PromptValue],
+ stop: list[str] | None = None,
+ callbacks: Callbacks | list[Callbacks] | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ prompt_strings = [p.to_string() for p in prompts]
+ return self.generate(prompt_strings, stop=stop, callbacks=callbacks, **kwargs)
+
+ @override
+ async def agenerate_prompt(
+ self,
+ prompts: list[PromptValue],
+ stop: list[str] | None = None,
+ callbacks: Callbacks | list[Callbacks] | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ prompt_strings = [p.to_string() for p in prompts]
+ return await self.agenerate(
+ prompt_strings, stop=stop, callbacks=callbacks, **kwargs
+ )
+
+ def _generate_helper(
+ self,
+ prompts: list[str],
+ stop: list[str] | None,
+ run_managers: list[CallbackManagerForLLMRun],
+ *,
+ new_arg_supported: bool,
+ **kwargs: Any,
+ ) -> LLMResult:
+ try:
+ output = (
+ self._generate(
+ prompts,
+ stop=stop,
+ # TODO: support multiple run managers
+ run_manager=run_managers[0] if run_managers else None,
+ **kwargs,
+ )
+ if new_arg_supported
+ else self._generate(prompts, stop=stop)
+ )
+ except BaseException as e:
+ for run_manager in run_managers:
+ run_manager.on_llm_error(e, response=LLMResult(generations=[]))
+ raise
+ flattened_outputs = output.flatten()
+ for manager, flattened_output in zip(
+ run_managers, flattened_outputs, strict=False
+ ):
+ manager.on_llm_end(flattened_output)
+ if run_managers:
+ output.run = [
+ RunInfo(run_id=run_manager.run_id) for run_manager in run_managers
+ ]
+ return output
+
+ def generate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ callbacks: Callbacks | list[Callbacks] | None = None,
+ *,
+ tags: list[str] | list[list[str]] | None = None,
+ metadata: dict[str, Any] | list[dict[str, Any]] | None = None,
+ run_name: str | list[str] | None = None,
+ run_id: uuid.UUID | list[uuid.UUID | None] | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Pass a sequence of prompts to a model and return generations.
+
+ This method should make use of batched calls for models that expose a batched
+ API.
+
+ Use this method when you want to:
+
+ 1. Take advantage of batched calls,
+ 2. Need more output from the model than just the top generated value,
+ 3. Are building chains that are agnostic to the underlying language model
+ type (e.g., pure text completion models vs chat models).
+
+ Args:
+ prompts: List of string prompts.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ callbacks: `Callbacks` to pass through.
+
+ Used for executing additional functionality, such as logging or
+ streaming, throughout generation.
+ tags: List of tags to associate with each prompt. If provided, the length
+ of the list must match the length of the prompts list.
+ metadata: List of metadata dictionaries to associate with each prompt. If
+ provided, the length of the list must match the length of the prompts
+ list.
+ run_name: List of run names to associate with each prompt. If provided, the
+ length of the list must match the length of the prompts list.
+ run_id: List of run IDs to associate with each prompt. If provided, the
+ length of the list must match the length of the prompts list.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Raises:
+ ValueError: If prompts is not a list.
+ ValueError: If the length of `callbacks`, `tags`, `metadata`, or
+ `run_name` (if provided) does not match the length of prompts.
+
+ Returns:
+ An `LLMResult`, which contains a list of candidate `Generations` for each
+ input prompt and additional model provider-specific output.
+ """
+ if not isinstance(prompts, list):
+ msg = (
+ "Argument 'prompts' is expected to be of type list[str], received"
+ f" argument of type {type(prompts)}."
+ )
+ raise ValueError(msg) # noqa: TRY004
+ # Create callback managers
+ if isinstance(metadata, list):
+ metadata = [
+ {
+ **(meta or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ for meta in metadata
+ ]
+ elif isinstance(metadata, dict):
+ metadata = {
+ **(metadata or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ if (
+ isinstance(callbacks, list)
+ and callbacks
+ and (
+ isinstance(callbacks[0], (list, BaseCallbackManager))
+ or callbacks[0] is None
+ )
+ ):
+ # We've received a list of callbacks args to apply to each input
+ if len(callbacks) != len(prompts):
+ msg = "callbacks must be the same length as prompts"
+ raise ValueError(msg)
+ if tags is not None and not (
+ isinstance(tags, list) and len(tags) == len(prompts)
+ ):
+ msg = "tags must be a list of the same length as prompts"
+ raise ValueError(msg)
+ if metadata is not None and not (
+ isinstance(metadata, list) and len(metadata) == len(prompts)
+ ):
+ msg = "metadata must be a list of the same length as prompts"
+ raise ValueError(msg)
+ if run_name is not None and not (
+ isinstance(run_name, list) and len(run_name) == len(prompts)
+ ):
+ msg = "run_name must be a list of the same length as prompts"
+ raise ValueError(msg)
+ callbacks = cast("list[Callbacks]", callbacks)
+ tags_list = cast("list[list[str] | None]", tags or ([None] * len(prompts)))
+ metadata_list = cast(
+ "list[dict[str, Any] | None]", metadata or ([{}] * len(prompts))
+ )
+ run_name_list = run_name or cast(
+ "list[str | None]", ([None] * len(prompts))
+ )
+ params = self.dict()
+ params["stop"] = stop
+ callback_managers = [
+ CallbackManager.configure(
+ callback,
+ self.callbacks,
+ self.verbose,
+ tag,
+ self.tags,
+ meta,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ for callback, tag, meta in zip(
+ callbacks, tags_list, metadata_list, strict=False
+ )
+ ]
+ else:
+ # We've received a single callbacks arg to apply to all inputs
+ params = self.dict()
+ params["stop"] = stop
+ callback_managers = [
+ CallbackManager.configure(
+ cast("Callbacks", callbacks),
+ self.callbacks,
+ self.verbose,
+ cast("list[str]", tags),
+ self.tags,
+ cast("dict[str, Any]", metadata),
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ ] * len(prompts)
+ run_name_list = [cast("str | None", run_name)] * len(prompts)
+ run_ids_list = self._get_run_ids_list(run_id, prompts)
+ options = {"stop": stop}
+ (
+ existing_prompts,
+ llm_string,
+ missing_prompt_idxs,
+ missing_prompts,
+ ) = get_prompts(params, prompts, self.cache)
+ new_arg_supported = inspect.signature(self._generate).parameters.get(
+ "run_manager"
+ )
+ if (self.cache is None and get_llm_cache() is None) or self.cache is False:
+ run_managers = [
+ callback_manager.on_llm_start(
+ self._serialized,
+ [prompt],
+ invocation_params=params,
+ options=options,
+ name=run_name,
+ batch_size=len(prompts),
+ run_id=run_id_,
+ )[0]
+ for callback_manager, prompt, run_name, run_id_ in zip(
+ callback_managers,
+ prompts,
+ run_name_list,
+ run_ids_list,
+ strict=False,
+ )
+ ]
+ return self._generate_helper(
+ prompts,
+ stop,
+ run_managers,
+ new_arg_supported=bool(new_arg_supported),
+ **kwargs,
+ )
+ if len(missing_prompts) > 0:
+ run_managers = [
+ callback_managers[idx].on_llm_start(
+ self._serialized,
+ [prompts[idx]],
+ invocation_params=params,
+ options=options,
+ name=run_name_list[idx],
+ batch_size=len(missing_prompts),
+ )[0]
+ for idx in missing_prompt_idxs
+ ]
+ new_results = self._generate_helper(
+ missing_prompts,
+ stop,
+ run_managers,
+ new_arg_supported=bool(new_arg_supported),
+ **kwargs,
+ )
+ llm_output = update_cache(
+ self.cache,
+ existing_prompts,
+ llm_string,
+ missing_prompt_idxs,
+ new_results,
+ prompts,
+ )
+ run_info = (
+ [RunInfo(run_id=run_manager.run_id) for run_manager in run_managers]
+ if run_managers
+ else None
+ )
+ else:
+ llm_output = {}
+ run_info = None
+ generations = [existing_prompts[i] for i in range(len(prompts))]
+ return LLMResult(generations=generations, llm_output=llm_output, run=run_info)
+
+ @staticmethod
+ def _get_run_ids_list(
+ run_id: uuid.UUID | list[uuid.UUID | None] | None, prompts: list
+ ) -> list:
+ if run_id is None:
+ return [None] * len(prompts)
+ if isinstance(run_id, list):
+ if len(run_id) != len(prompts):
+ msg = (
+ "Number of manually provided run_id's does not match batch length."
+ f" {len(run_id)} != {len(prompts)}"
+ )
+ raise ValueError(msg)
+ return run_id
+ return [run_id] + [None] * (len(prompts) - 1)
+
+ async def _agenerate_helper(
+ self,
+ prompts: list[str],
+ stop: list[str] | None,
+ run_managers: list[AsyncCallbackManagerForLLMRun],
+ *,
+ new_arg_supported: bool,
+ **kwargs: Any,
+ ) -> LLMResult:
+ try:
+ output = (
+ await self._agenerate(
+ prompts,
+ stop=stop,
+ run_manager=run_managers[0] if run_managers else None,
+ **kwargs,
+ )
+ if new_arg_supported
+ else await self._agenerate(prompts, stop=stop)
+ )
+ except BaseException as e:
+ await asyncio.gather(
+ *[
+ run_manager.on_llm_error(e, response=LLMResult(generations=[]))
+ for run_manager in run_managers
+ ]
+ )
+ raise
+ flattened_outputs = output.flatten()
+ await asyncio.gather(
+ *[
+ run_manager.on_llm_end(flattened_output)
+ for run_manager, flattened_output in zip(
+ run_managers, flattened_outputs, strict=False
+ )
+ ]
+ )
+ if run_managers:
+ output.run = [
+ RunInfo(run_id=run_manager.run_id) for run_manager in run_managers
+ ]
+ return output
+
+ async def agenerate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ callbacks: Callbacks | list[Callbacks] | None = None,
+ *,
+ tags: list[str] | list[list[str]] | None = None,
+ metadata: dict[str, Any] | list[dict[str, Any]] | None = None,
+ run_name: str | list[str] | None = None,
+ run_id: uuid.UUID | list[uuid.UUID | None] | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ """Asynchronously pass a sequence of prompts to a model and return generations.
+
+ This method should make use of batched calls for models that expose a batched
+ API.
+
+ Use this method when you want to:
+
+ 1. Take advantage of batched calls,
+ 2. Need more output from the model than just the top generated value,
+ 3. Are building chains that are agnostic to the underlying language model
+ type (e.g., pure text completion models vs chat models).
+
+ Args:
+ prompts: List of string prompts.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+ callbacks: `Callbacks` to pass through.
+
+ Used for executing additional functionality, such as logging or
+ streaming, throughout generation.
+ tags: List of tags to associate with each prompt. If provided, the length
+ of the list must match the length of the prompts list.
+ metadata: List of metadata dictionaries to associate with each prompt. If
+ provided, the length of the list must match the length of the prompts
+ list.
+ run_name: List of run names to associate with each prompt. If provided, the
+ length of the list must match the length of the prompts list.
+ run_id: List of run IDs to associate with each prompt. If provided, the
+ length of the list must match the length of the prompts list.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Raises:
+ ValueError: If the length of `callbacks`, `tags`, `metadata`, or
+ `run_name` (if provided) does not match the length of prompts.
+
+ Returns:
+ An `LLMResult`, which contains a list of candidate `Generations` for each
+ input prompt and additional model provider-specific output.
+ """
+ if isinstance(metadata, list):
+ metadata = [
+ {
+ **(meta or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ for meta in metadata
+ ]
+ elif isinstance(metadata, dict):
+ metadata = {
+ **(metadata or {}),
+ **self._get_ls_params_with_defaults(stop=stop, **kwargs),
+ }
+ # Create callback managers
+ if isinstance(callbacks, list) and (
+ isinstance(callbacks[0], (list, BaseCallbackManager))
+ or callbacks[0] is None
+ ):
+ # We've received a list of callbacks args to apply to each input
+ if len(callbacks) != len(prompts):
+ msg = "callbacks must be the same length as prompts"
+ raise ValueError(msg)
+ if tags is not None and not (
+ isinstance(tags, list) and len(tags) == len(prompts)
+ ):
+ msg = "tags must be a list of the same length as prompts"
+ raise ValueError(msg)
+ if metadata is not None and not (
+ isinstance(metadata, list) and len(metadata) == len(prompts)
+ ):
+ msg = "metadata must be a list of the same length as prompts"
+ raise ValueError(msg)
+ if run_name is not None and not (
+ isinstance(run_name, list) and len(run_name) == len(prompts)
+ ):
+ msg = "run_name must be a list of the same length as prompts"
+ raise ValueError(msg)
+ callbacks = cast("list[Callbacks]", callbacks)
+ tags_list = cast("list[list[str] | None]", tags or ([None] * len(prompts)))
+ metadata_list = cast(
+ "list[dict[str, Any] | None]", metadata or ([{}] * len(prompts))
+ )
+ run_name_list = run_name or cast(
+ "list[str | None]", ([None] * len(prompts))
+ )
+ params = self.dict()
+ params["stop"] = stop
+ callback_managers = [
+ AsyncCallbackManager.configure(
+ callback,
+ self.callbacks,
+ self.verbose,
+ tag,
+ self.tags,
+ meta,
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ for callback, tag, meta in zip(
+ callbacks, tags_list, metadata_list, strict=False
+ )
+ ]
+ else:
+ # We've received a single callbacks arg to apply to all inputs
+ params = self.dict()
+ params["stop"] = stop
+ callback_managers = [
+ AsyncCallbackManager.configure(
+ cast("Callbacks", callbacks),
+ self.callbacks,
+ self.verbose,
+ cast("list[str]", tags),
+ self.tags,
+ cast("dict[str, Any]", metadata),
+ self.metadata,
+ langsmith_inheritable_metadata=_filter_invocation_params_for_tracing(
+ params
+ ),
+ )
+ ] * len(prompts)
+ run_name_list = [cast("str | None", run_name)] * len(prompts)
+ run_ids_list = self._get_run_ids_list(run_id, prompts)
+ options = {"stop": stop}
+ (
+ existing_prompts,
+ llm_string,
+ missing_prompt_idxs,
+ missing_prompts,
+ ) = await aget_prompts(params, prompts, self.cache)
+
+ # Verify whether the cache is set, and if the cache is set,
+ # verify whether the cache is available.
+ new_arg_supported = inspect.signature(self._agenerate).parameters.get(
+ "run_manager"
+ )
+ if (self.cache is None and get_llm_cache() is None) or self.cache is False:
+ run_managers = await asyncio.gather(
+ *[
+ callback_manager.on_llm_start(
+ self._serialized,
+ [prompt],
+ invocation_params=params,
+ options=options,
+ name=run_name,
+ batch_size=len(prompts),
+ run_id=run_id_,
+ )
+ for callback_manager, prompt, run_name, run_id_ in zip(
+ callback_managers,
+ prompts,
+ run_name_list,
+ run_ids_list,
+ strict=False,
+ )
+ ]
+ )
+ run_managers = [r[0] for r in run_managers] # type: ignore[misc]
+ return await self._agenerate_helper(
+ prompts,
+ stop,
+ run_managers, # type: ignore[arg-type]
+ new_arg_supported=bool(new_arg_supported),
+ **kwargs,
+ )
+ if len(missing_prompts) > 0:
+ run_managers = await asyncio.gather(
+ *[
+ callback_managers[idx].on_llm_start(
+ self._serialized,
+ [prompts[idx]],
+ invocation_params=params,
+ options=options,
+ name=run_name_list[idx],
+ batch_size=len(missing_prompts),
+ )
+ for idx in missing_prompt_idxs
+ ]
+ )
+ run_managers = [r[0] for r in run_managers] # type: ignore[misc]
+ new_results = await self._agenerate_helper(
+ missing_prompts,
+ stop,
+ run_managers, # type: ignore[arg-type]
+ new_arg_supported=bool(new_arg_supported),
+ **kwargs,
+ )
+ llm_output = await aupdate_cache(
+ self.cache,
+ existing_prompts,
+ llm_string,
+ missing_prompt_idxs,
+ new_results,
+ prompts,
+ )
+ run_info = (
+ [RunInfo(run_id=run_manager.run_id) for run_manager in run_managers] # type: ignore[attr-defined]
+ if run_managers
+ else None
+ )
+ else:
+ llm_output = {}
+ run_info = None
+ generations = [existing_prompts[i] for i in range(len(prompts))]
+ return LLMResult(generations=generations, llm_output=llm_output, run=run_info)
+
+ async def _call_async(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ callbacks: Callbacks = None,
+ *,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Check Cache and run the LLM on the given prompt and input."""
+ result = await self.agenerate(
+ [prompt],
+ stop=stop,
+ callbacks=callbacks,
+ tags=tags,
+ metadata=metadata,
+ **kwargs,
+ )
+ return result.generations[0][0].text
+
+ def __str__(self) -> str:
+ """Return a string representation of the object for printing."""
+ cls_name = f"\033[1m{self.__class__.__name__}\033[0m"
+ return f"{cls_name}\nParams: {self._identifying_params}"
+
+ @property
+ @abstractmethod
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+
+ @override
+ def dict(self, **kwargs: Any) -> dict:
+ """Return a dictionary of the LLM."""
+ starter_dict = dict(self._identifying_params)
+ starter_dict["_type"] = self._llm_type
+ return starter_dict
+
+ def save(self, file_path: Path | str) -> None:
+ """Save the LLM.
+
+ Args:
+ file_path: Path to file to save the LLM to.
+
+ Raises:
+ ValueError: If the file path is not a string or Path object.
+
+ Example:
+ ```python
+ llm.save(file_path="path/llm.yaml")
+ ```
+ """
+ # Convert file to Path object.
+ save_path = Path(file_path)
+
+ directory_path = save_path.parent
+ directory_path.mkdir(parents=True, exist_ok=True)
+
+ # Fetch dictionary to save
+ prompt_dict = self.dict()
+
+ if save_path.suffix == ".json":
+ with save_path.open("w", encoding="utf-8") as f:
+ json.dump(prompt_dict, f, indent=4)
+ elif save_path.suffix.endswith((".yaml", ".yml")):
+ with save_path.open("w", encoding="utf-8") as f:
+ yaml.dump(prompt_dict, f, default_flow_style=False)
+ else:
+ msg = f"{save_path} must be json or yaml"
+ raise ValueError(msg)
+
+
+class LLM(BaseLLM):
+ """Simple interface for implementing a custom LLM.
+
+ You should subclass this class and implement the following:
+
+ - `_call` method: Run the LLM on the given prompt and input (used by `invoke`).
+ - `_identifying_params` property: Return a dictionary of the identifying parameters
+ This is critical for caching and tracing purposes. Identifying parameters
+ is a dict that identifies the LLM.
+ It should mostly include a `model_name`.
+
+ Optional: Override the following methods to provide more optimizations:
+
+ - `_acall`: Provide a native async version of the `_call` method.
+ If not provided, will delegate to the synchronous version using
+ `run_in_executor`. (Used by `ainvoke`).
+ - `_stream`: Stream the LLM on the given prompt and input.
+ `stream` will use `_stream` if provided, otherwise it
+ use `_call` and output will arrive in one chunk.
+ - `_astream`: Override to provide a native async version of the `_stream` method.
+ `astream` will use `_astream` if provided, otherwise it will implement
+ a fallback behavior that will use `_stream` if `_stream` is implemented,
+ and use `_acall` if `_stream` is not implemented.
+ """
+
+ @abstractmethod
+ def _call(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Run the LLM on the given input.
+
+ Override this method to implement the LLM logic.
+
+ Args:
+ prompt: The prompt to generate from.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+
+ If stop tokens are not supported consider raising `NotImplementedError`.
+ run_manager: Callback manager for the run.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Returns:
+ The model output as a string. SHOULD NOT include the prompt.
+ """
+
+ async def _acall(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Async version of the _call method.
+
+ The default implementation delegates to the synchronous _call method using
+ `run_in_executor`. Subclasses that need to provide a true async implementation
+ should override this method to reduce the overhead of using `run_in_executor`.
+
+ Args:
+ prompt: The prompt to generate from.
+ stop: Stop words to use when generating.
+
+ Model output is cut off at the first occurrence of any of these
+ substrings.
+
+ If stop tokens are not supported consider raising `NotImplementedError`.
+ run_manager: Callback manager for the run.
+ **kwargs: Arbitrary additional keyword arguments.
+
+ These are usually passed to the model provider API call.
+
+ Returns:
+ The model output as a string. SHOULD NOT include the prompt.
+ """
+ return await run_in_executor(
+ None,
+ self._call,
+ prompt,
+ stop,
+ run_manager.get_sync() if run_manager else None,
+ **kwargs,
+ )
+
+ def _generate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ # TODO: add caching here.
+ generations = []
+ new_arg_supported = inspect.signature(self._call).parameters.get("run_manager")
+ for prompt in prompts:
+ text = (
+ self._call(prompt, stop=stop, run_manager=run_manager, **kwargs)
+ if new_arg_supported
+ else self._call(prompt, stop=stop, **kwargs)
+ )
+ generations.append([Generation(text=text)])
+ return LLMResult(generations=generations)
+
+ async def _agenerate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ generations = []
+ new_arg_supported = inspect.signature(self._acall).parameters.get("run_manager")
+ for prompt in prompts:
+ text = (
+ await self._acall(prompt, stop=stop, run_manager=run_manager, **kwargs)
+ if new_arg_supported
+ else await self._acall(prompt, stop=stop, **kwargs)
+ )
+ generations.append([Generation(text=text)])
+ return LLMResult(generations=generations)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/model_profile.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/model_profile.py
new file mode 100644
index 0000000000000000000000000000000000000000..b556c0a6467f0dfb540bacbec040e08e3a236fc0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/language_models/model_profile.py
@@ -0,0 +1,156 @@
+"""Model profile types and utilities."""
+
+import logging
+import warnings
+from typing import get_type_hints
+
+from pydantic import ConfigDict
+from typing_extensions import TypedDict
+
+logger = logging.getLogger(__name__)
+
+
+class ModelProfile(TypedDict, total=False):
+ """Model profile.
+
+ !!! warning "Beta feature"
+
+ This is a beta feature. The format of model profiles is subject to change.
+
+ Provides information about chat model capabilities, such as context window sizes
+ and supported features.
+ """
+
+ __pydantic_config__ = ConfigDict(extra="allow") # type: ignore[misc]
+
+ # --- Model metadata ---
+
+ name: str
+ """Human-readable model name."""
+
+ status: str
+ """Model status (e.g., `'active'`, `'deprecated'`)."""
+
+ release_date: str
+ """Model release date (ISO 8601 format, e.g., `'2025-06-01'`)."""
+
+ last_updated: str
+ """Date the model was last updated (ISO 8601 format)."""
+
+ open_weights: bool
+ """Whether the model weights are openly available."""
+
+ # --- Input constraints ---
+
+ max_input_tokens: int
+ """Maximum context window (tokens)"""
+
+ text_inputs: bool
+ """Whether text inputs are supported."""
+
+ image_inputs: bool
+ """Whether image inputs are supported."""
+ # TODO: add more detail about formats?
+
+ image_url_inputs: bool
+ """Whether [image URL inputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+
+ pdf_inputs: bool
+ """Whether [PDF inputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+ # TODO: add more detail about formats? e.g. bytes or base64
+
+ audio_inputs: bool
+ """Whether [audio inputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+ # TODO: add more detail about formats? e.g. bytes or base64
+
+ video_inputs: bool
+ """Whether [video inputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+ # TODO: add more detail about formats? e.g. bytes or base64
+
+ image_tool_message: bool
+ """Whether images can be included in tool messages."""
+
+ pdf_tool_message: bool
+ """Whether PDFs can be included in tool messages."""
+
+ # --- Output constraints ---
+
+ max_output_tokens: int
+ """Maximum output tokens"""
+
+ reasoning_output: bool
+ """Whether the model supports [reasoning / chain-of-thought](https://docs.langchain.com/oss/python/langchain/models#reasoning)"""
+
+ text_outputs: bool
+ """Whether text outputs are supported."""
+
+ image_outputs: bool
+ """Whether [image outputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+
+ audio_outputs: bool
+ """Whether [audio outputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+
+ video_outputs: bool
+ """Whether [video outputs](https://docs.langchain.com/oss/python/langchain/models#multimodal)
+ are supported."""
+
+ # --- Tool calling ---
+ tool_calling: bool
+ """Whether the model supports [tool calling](https://docs.langchain.com/oss/python/langchain/models#tool-calling)"""
+
+ tool_choice: bool
+ """Whether the model supports [tool choice](https://docs.langchain.com/oss/python/langchain/models#forcing-tool-calls)"""
+
+ # --- Structured output ---
+ structured_output: bool
+ """Whether the model supports a native [structured output](https://docs.langchain.com/oss/python/langchain/models#structured-outputs)
+ feature"""
+
+ # --- Other capabilities ---
+
+ attachment: bool
+ """Whether the model supports file attachments."""
+
+ temperature: bool
+ """Whether the model supports a temperature parameter."""
+
+
+ModelProfileRegistry = dict[str, ModelProfile]
+"""Registry mapping model identifiers or names to their ModelProfile."""
+
+
+def _warn_unknown_profile_keys(profile: ModelProfile) -> None:
+ """Warn if `profile` contains keys not declared on `ModelProfile`.
+
+ Args:
+ profile: The model profile dict to check for undeclared keys.
+ """
+ if not isinstance(profile, dict):
+ return
+
+ try:
+ declared = frozenset(get_type_hints(ModelProfile).keys())
+ except (TypeError, NameError):
+ # get_type_hints raises NameError on unresolvable forward refs and
+ # TypeError when annotations evaluate to non-type objects.
+ logger.debug(
+ "Could not resolve type hints for ModelProfile; "
+ "skipping unknown-key check.",
+ exc_info=True,
+ )
+ return
+
+ extra = sorted(set(profile) - declared)
+ if extra:
+ warnings.warn(
+ f"Unrecognized keys in model profile: {extra}. "
+ f"This may indicate a version mismatch between langchain-core "
+ f"and your provider package. Consider upgrading langchain-core.",
+ stacklevel=2,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e656fedaa19fe19189adf68474cdcd7e7cb39ada
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__init__.py
@@ -0,0 +1,44 @@
+"""**Load** module helps with serialization and deserialization."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.load.dump import dumpd, dumps
+ from langchain_core.load.load import InitValidator, loads
+ from langchain_core.load.serializable import Serializable
+
+# Unfortunately, we have to eagerly import load from langchain_core/load/load.py
+# eagerly to avoid a namespace conflict. We want users to still be able to use
+# `from langchain_core.load import load` to get the load function, but
+# the `from langchain_core.load.load import load` absolute import should also work.
+from langchain_core.load.load import load
+
+__all__ = (
+ "InitValidator",
+ "Serializable",
+ "dumpd",
+ "dumps",
+ "load",
+ "loads",
+)
+
+_dynamic_imports = {
+ "dumpd": "dump",
+ "dumps": "dump",
+ "InitValidator": "load",
+ "loads": "load",
+ "Serializable": "serializable",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0670d351142e2b41091a53097461a313b51f156
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/_validation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/_validation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a8b0dee70d0b9c424820e46e32bc7e73db4c36f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/_validation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/dump.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/dump.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff4f4c555fe190d2cc24e49a0dea848a6b7b860f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/dump.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/load.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/load.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17d1c90e4984b43648842087a2b9a1e2b5d7d4ab
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/load.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/mapping.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/mapping.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd12e57f0b1f98c6a47280531d093cf92683e7e9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/mapping.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/serializable.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/serializable.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0a21ff8405c73abec39e904a6137657014b1d57
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/serializable.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/validators.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/validators.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..060f33a4d2b1f7f1e058e00fa695a4430bcb422c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/__pycache__/validators.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/_validation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bf9f76a486da577a00c84741d4dab0b5088b5f8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/_validation.py
@@ -0,0 +1,191 @@
+"""Validation utilities for LangChain serialization.
+
+Provides escape-based protection against injection attacks in serialized objects. The
+approach uses an allowlist design: only dicts explicitly produced by
+`Serializable.to_json()` are treated as LC objects during deserialization.
+
+## How escaping works
+
+During serialization, plain dicts (user data) that contain an `'lc'` key are wrapped:
+
+```python
+{"lc": 1, ...} # user data that looks like LC object
+# becomes:
+{"__lc_escaped__": {"lc": 1, ...}}
+```
+
+During deserialization, escaped dicts are unwrapped and returned as plain dicts,
+NOT instantiated as LC objects.
+"""
+
+from typing import Any, cast
+
+from langchain_core.load.serializable import (
+ Serializable,
+ to_json_not_implemented,
+)
+
+_LC_ESCAPED_KEY = "__lc_escaped__"
+"""Sentinel key used to mark escaped user dicts during serialization.
+
+When a plain dict contains 'lc' key (which could be confused with LC objects),
+we wrap it as {"__lc_escaped__": {...original...}}.
+"""
+
+
+def _needs_escaping(obj: dict[str, Any]) -> bool:
+ """Check if a dict needs escaping to prevent confusion with LC objects.
+
+ A dict needs escaping if:
+
+ 1. It has an `'lc'` key (could be confused with LC serialization format)
+ 2. It has only the escape key (would be mistaken for an escaped dict)
+ """
+ return "lc" in obj or (len(obj) == 1 and _LC_ESCAPED_KEY in obj)
+
+
+def _escape_dict(obj: dict[str, Any]) -> dict[str, Any]:
+ """Wrap a dict in the escape marker.
+
+ Example:
+ ```python
+ {"key": "value"} # becomes {"__lc_escaped__": {"key": "value"}}
+ ```
+ """
+ return {_LC_ESCAPED_KEY: obj}
+
+
+def _is_escaped_dict(obj: dict[str, Any]) -> bool:
+ """Check if a dict is an escaped user dict.
+
+ Example:
+ ```python
+ {"__lc_escaped__": {...}} # is an escaped dict
+ ```
+ """
+ return len(obj) == 1 and _LC_ESCAPED_KEY in obj
+
+
+def _serialize_value(obj: Any) -> Any:
+ """Serialize a value with escaping of user dicts.
+
+ Called recursively on kwarg values to escape any plain dicts that could be confused
+ with LC objects.
+
+ Args:
+ obj: The value to serialize.
+
+ Returns:
+ The serialized value with user dicts escaped as needed.
+ """
+ if isinstance(obj, Serializable):
+ # This is an LC object - serialize it properly (not escaped)
+ return _serialize_lc_object(obj)
+ if isinstance(obj, dict):
+ if not all(isinstance(k, (str, int, float, bool, type(None))) for k in obj):
+ # if keys are not json serializable
+ return to_json_not_implemented(obj)
+ # Check if dict needs escaping BEFORE recursing into values.
+ # If it needs escaping, wrap it as-is - the contents are user data that
+ # will be returned as-is during deserialization (no instantiation).
+ # This prevents re-escaping of already-escaped nested content.
+ if _needs_escaping(obj):
+ return _escape_dict(obj)
+ # Safe dict (no 'lc' key) - recurse into values
+ return {k: _serialize_value(v) for k, v in obj.items()}
+ if isinstance(obj, (list, tuple)):
+ return [_serialize_value(item) for item in obj]
+ if isinstance(obj, (str, int, float, bool, type(None))):
+ return obj
+
+ # Non-JSON-serializable object (datetime, custom objects, etc.)
+ return to_json_not_implemented(obj)
+
+
+def _get_secret_keys(obj: Serializable) -> set[str]:
+ """Return the merged set of constructor kwarg names declared as secrets.
+
+ Mirrors the MRO walk in `Serializable.to_json` so the keys returned here
+ match the keys whose values `_replace_secrets` rewrites into secret
+ markers. Used by `_serialize_lc_object` to decide which kwargs to skip
+ when escaping user data.
+ """
+ secrets: dict[str, str] = {}
+ model_fields = type(obj).model_fields
+ for cls in [None, *obj.__class__.mro()]:
+ if cls is Serializable:
+ break
+ this = cast("Serializable", obj if cls is None else super(cls, obj))
+ secrets.update(this.lc_secrets)
+ for key in list(secrets):
+ if (key in model_fields) and (alias := model_fields[key].alias) is not None:
+ secrets[alias] = secrets[key]
+ return set(secrets)
+
+
+def _serialize_lc_object(obj: Any) -> dict[str, Any]:
+ """Serialize a `Serializable` object with escaping of user data in kwargs.
+
+ Args:
+ obj: The `Serializable` object to serialize.
+
+ Returns:
+ The serialized dict with user data in kwargs escaped as needed.
+
+ Note:
+ Kwargs values are processed with `_serialize_value` to escape user data
+ (like metadata) that contains `'lc'` keys. Secret fields are identified
+ by the class's declared `lc_secrets` and skipped because `to_json()`
+ already converted their values to secret markers.
+
+ The check is key-based rather than shape-based. A shape-based check
+ ("this dict looks like a secret marker") can be forged by user data,
+ letting attacker-controlled free-form dicts bypass escaping and reach
+ the Reviver.
+ """
+ if not isinstance(obj, Serializable):
+ msg = f"Expected Serializable, got {type(obj)}"
+ raise TypeError(msg)
+
+ serialized: dict[str, Any] = dict(obj.to_json())
+
+ # Process kwargs to escape user data that could be confused with LC objects.
+ # Skip kwargs declared as secrets - `to_json()` already replaced their
+ # values with secret markers via `_replace_secrets`.
+ if serialized.get("type") == "constructor" and "kwargs" in serialized:
+ secret_keys = _get_secret_keys(obj)
+ serialized["kwargs"] = {
+ k: v if k in secret_keys else _serialize_value(v)
+ for k, v in serialized["kwargs"].items()
+ }
+
+ return serialized
+
+
+def _unescape_value(obj: Any) -> Any:
+ """Unescape a value, processing escape markers in dict values and lists.
+
+ When an escaped dict is encountered (`{"__lc_escaped__": ...}`), it's
+ unwrapped and the contents are returned AS-IS (no further processing).
+ The contents represent user data that should not be modified.
+
+ For regular dicts and lists, we recurse to find any nested escape markers.
+
+ Args:
+ obj: The value to unescape.
+
+ Returns:
+ The unescaped value.
+ """
+ if isinstance(obj, dict):
+ if _is_escaped_dict(obj):
+ # Unwrap and return the user data as-is (no further unescaping).
+ # The contents are user data that may contain more escape keys,
+ # but those are part of the user's actual data.
+ return obj[_LC_ESCAPED_KEY]
+
+ # Regular dict - recurse into values to find nested escape markers
+ return {k: _unescape_value(v) for k, v in obj.items()}
+ if isinstance(obj, list):
+ return [_unescape_value(item) for item in obj]
+ return obj
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/dump.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/dump.py
new file mode 100644
index 0000000000000000000000000000000000000000..07bc3099b6c35f83cb149c887e3799d64a7dad5a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/dump.py
@@ -0,0 +1,120 @@
+"""Serialize LangChain objects to JSON.
+
+Provides `dumps` (to JSON string) and `dumpd` (to dict) for serializing
+`Serializable` objects.
+
+## Escaping
+
+During serialization, plain dicts (user data) that contain an `'lc'` key are escaped
+by wrapping them: `{"__lc_escaped__": {...original...}}`. This prevents injection
+attacks where malicious data could trick the deserializer into instantiating
+arbitrary classes. The escape marker is removed during deserialization.
+
+This is an allowlist approach: only dicts explicitly produced by
+`Serializable.to_json()` are treated as LC objects; everything else is escaped if it
+could be confused with the LC format.
+"""
+
+import json
+from typing import Any
+
+from pydantic import BaseModel
+
+from langchain_core.load._validation import _serialize_value
+from langchain_core.load.serializable import Serializable, to_json_not_implemented
+from langchain_core.messages import AIMessage
+from langchain_core.outputs import ChatGeneration
+
+
+def default(obj: Any) -> Any:
+ """Return a default value for an object.
+
+ Args:
+ obj: The object to serialize to json if it is a Serializable object.
+
+ Returns:
+ A JSON serializable object or a SerializedNotImplemented object.
+ """
+ if isinstance(obj, Serializable):
+ return obj.to_json()
+ return to_json_not_implemented(obj)
+
+
+def _dump_pydantic_models(obj: Any) -> Any:
+ """Convert nested Pydantic models to dicts for JSON serialization.
+
+ Handles the special case where a `ChatGeneration` contains an `AIMessage`
+ with a parsed Pydantic model in `additional_kwargs["parsed"]`. Since
+ Pydantic models aren't directly JSON serializable, this converts them to
+ dicts.
+
+ Args:
+ obj: The object to process.
+
+ Returns:
+ A copy of the object with nested Pydantic models converted to dicts, or
+ the original object unchanged if no conversion was needed.
+ """
+ if (
+ isinstance(obj, ChatGeneration)
+ and isinstance(obj.message, AIMessage)
+ and (parsed := obj.message.additional_kwargs.get("parsed"))
+ and isinstance(parsed, BaseModel)
+ ):
+ obj_copy = obj.model_copy(deep=True)
+ obj_copy.message.additional_kwargs["parsed"] = parsed.model_dump()
+ return obj_copy
+ return obj
+
+
+def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:
+ """Return a JSON string representation of an object.
+
+ Note:
+ Plain dicts containing an `'lc'` key are automatically escaped to prevent
+ confusion with LC serialization format. The escape marker is removed during
+ deserialization.
+
+ Args:
+ obj: The object to dump.
+ pretty: Whether to pretty print the json.
+
+ If `True`, the json will be indented by either 2 spaces or the amount
+ provided in the `indent` kwarg.
+ **kwargs: Additional arguments to pass to `json.dumps`
+
+ Returns:
+ A JSON string representation of the object.
+
+ Raises:
+ ValueError: If `default` is passed as a kwarg.
+ """
+ if "default" in kwargs:
+ msg = "`default` should not be passed to dumps"
+ raise ValueError(msg)
+
+ obj = _dump_pydantic_models(obj)
+ serialized = _serialize_value(obj)
+
+ if pretty:
+ indent = kwargs.pop("indent", 2)
+ return json.dumps(serialized, indent=indent, **kwargs)
+ return json.dumps(serialized, **kwargs)
+
+
+def dumpd(obj: Any) -> Any:
+ """Return a dict representation of an object.
+
+ Note:
+ Plain dicts containing an `'lc'` key are automatically escaped to prevent
+ confusion with LC serialization format. The escape marker is removed during
+ deserialization.
+
+ Args:
+ obj: The object to dump.
+
+ Returns:
+ Dictionary that can be serialized to json using `json.dumps`.
+ """
+ obj = _dump_pydantic_models(obj)
+ return _serialize_value(obj)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/load.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/load.py
new file mode 100644
index 0000000000000000000000000000000000000000..c58189837a8f92dbb9abcecdf7269181c4fd6fbb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/load.py
@@ -0,0 +1,819 @@
+"""Load LangChain objects from JSON strings or objects.
+
+## How it works
+
+Each `Serializable` LangChain object has a unique identifier (its "class path"), which
+is a list of strings representing the module path and class name. For example:
+
+- `AIMessage` -> `["langchain_core", "messages", "ai", "AIMessage"]`
+- `ChatPromptTemplate` -> `["langchain_core", "prompts", "chat", "ChatPromptTemplate"]`
+
+When deserializing, the class path from the JSON `'id'` field is checked against an
+allowlist. If the class is not in the allowlist, deserialization raises a `ValueError`.
+
+## Threat model
+
+A serialized LangChain payload crosses a trust boundary because the manifest
+may contain serialized objects and configuration that affect runtime behavior.
+For example, a payload can configure a chat model with a custom `base_url`,
+custom headers, a different model name, or other constructor arguments. These
+are supported features, but they also mean the payload contents should be
+treated as executable configuration rather than plain text.
+
+Concretely, deserialization instantiates Python objects, so any constructor
+(`__init__`) or validator on an allowed class can run during `load()`. A
+crafted payload that is allowed to reach an unintended class — or an intended
+class with attacker-controlled kwargs — could cause network calls, file
+operations, or environment-variable access while the object is being built.
+
+!!! warning "Do not use with untrusted input"
+
+ If the source is untrusted, avoid calling `load()` / `loads()` on it. If
+ you must, restrict `allowed_objects` to types that do not execute logic
+ during init — `allowed_objects='messages'` (or an explicit list of
+ message classes) is the safe choice. Keep `secrets_from_env=False`.
+
+The `allowed_objects` parameter controls which classes can be deserialized:
+
+- **Explicit list of classes** (recommended for untrusted input): only those
+ specific classes are allowed.
+- **`'messages'`**: chat-message classes only (e.g. `AIMessage`,
+ `HumanMessage`). Safe for untrusted input.
+- **`'core'` (current default)** — *unsafe with untrusted manifests.*
+ Classes defined in the serialization mappings under `langchain_core`
+ (messages, documents, prompts, etc.).
+- **`'all'`** — *unsafe with untrusted manifests.* Every class in the
+ serialization mappings, including partner chat models and LLMs and their
+ constructor kwargs (endpoint URLs, headers, model names, etc.).
+
+!!! note "Side effects in allowed classes"
+
+ Deserialization calls `__init__` on allowed classes. If those classes perform
+ side effects during initialization (network calls, file operations, etc.),
+ those side effects will occur. The allowlist prevents instantiation of
+ classes outside the allowlist, but does not sandbox the allowed classes
+ themselves or constrain their constructor kwargs.
+
+Import paths are also validated against trusted namespaces before any module is
+imported.
+
+### Best practices
+
+- Use the most restrictive `allowed_objects` possible. For untrusted input,
+ pass an explicit list of classes or `'messages'`. `'core'` and `'all'`
+ are unsafe with untrusted manifests — only use them when the source
+ serves the entire payload, including its configuration.
+- Keep `secrets_from_env` set to `False` (the default). If you must use it,
+ ensure the serialized data comes from a fully trusted source, as a crafted
+ payload can read arbitrary environment variables.
+- When using `secrets_map`, include only the specific secrets that the
+ serialized object requires.
+
+### Injection protection (escape-based)
+
+During serialization, plain dicts that contain an `'lc'` key are escaped by wrapping
+them: `{"__lc_escaped__": {...}}`. During deserialization, escaped dicts are unwrapped
+and returned as plain dicts, NOT instantiated as LC objects.
+
+This is an allowlist approach: only dicts explicitly produced by
+`Serializable.to_json()` (which are NOT escaped) are treated as LC objects;
+everything else is user data.
+
+Even if an attacker's payload includes `__lc_escaped__` wrappers, it will be unwrapped
+to plain dicts and NOT instantiated as malicious objects.
+
+## Examples
+
+```python
+from langchain_core.load import load
+from langchain_core.prompts import ChatPromptTemplate
+from langchain_core.messages import AIMessage, HumanMessage
+
+# Use default allowlist (classes from mappings) - recommended
+obj = load(data)
+
+# Allow only specific classes (most restrictive)
+obj = load(
+ data,
+ allowed_objects=[
+ ChatPromptTemplate,
+ AIMessage,
+ HumanMessage,
+ ],
+)
+```
+"""
+
+import importlib
+import json
+import os
+from collections.abc import Callable, Iterable
+from typing import Any, Literal, cast
+
+from langchain_core._api import beta
+from langchain_core._api.deprecation import warn_deprecated
+from langchain_core.load._validation import _is_escaped_dict, _unescape_value
+from langchain_core.load.mapping import (
+ _JS_SERIALIZABLE_MAPPING,
+ _OG_SERIALIZABLE_MAPPING,
+ OLD_CORE_NAMESPACES_MAPPING,
+ SERIALIZABLE_MAPPING,
+)
+from langchain_core.load.serializable import Serializable
+from langchain_core.load.validators import CLASS_INIT_VALIDATORS
+
+DEFAULT_NAMESPACES = [
+ "langchain",
+ "langchain_core",
+ "langchain_community",
+ "langchain_anthropic",
+ "langchain_groq",
+ "langchain_google_genai",
+ "langchain_aws",
+ "langchain_openai",
+ "langchain_google_vertexai",
+ "langchain_mistralai",
+ "langchain_fireworks",
+ "langchain_xai",
+ "langchain_sambanova",
+ "langchain_perplexity",
+]
+# Namespaces for which only deserializing via the SERIALIZABLE_MAPPING is allowed.
+# Load by path is not allowed.
+DISALLOW_LOAD_FROM_PATH = [
+ "langchain_community",
+ "langchain",
+]
+
+ALL_SERIALIZABLE_MAPPINGS = {
+ **SERIALIZABLE_MAPPING,
+ **OLD_CORE_NAMESPACES_MAPPING,
+ **_OG_SERIALIZABLE_MAPPING,
+ **_JS_SERIALIZABLE_MAPPING,
+}
+
+# Modern message classes admitted by `allowed_objects='messages'`. Legacy types
+# (BaseMessage / BaseMessageChunk, ChatMessage / ChatMessageChunk, FunctionMessage /
+# FunctionMessageChunk) are intentionally excluded — `BaseMessage` is abstract and
+# the chat/function variants are superseded by `ToolMessage` and tool calling.
+_MESSAGES_ALLOWED_CLASS_NAMES = frozenset(
+ {
+ "AIMessage",
+ "AIMessageChunk",
+ "HumanMessage",
+ "HumanMessageChunk",
+ "SystemMessage",
+ "SystemMessageChunk",
+ "ToolMessage",
+ "ToolMessageChunk",
+ "RemoveMessage",
+ }
+)
+
+# Cache for the default allowed class paths computed from mappings
+# Maps mode ("all", "core", or "messages") to the cached set of paths
+_default_class_paths_cache: dict[str, set[tuple[str, ...]]] = {}
+
+
+def _get_default_allowed_class_paths(
+ allowed_object_mode: Literal["all", "core", "messages"],
+) -> set[tuple[str, ...]]:
+ """Get the default allowed class paths from the serialization mappings.
+
+ This uses the mappings as the source of truth for what classes are allowed
+ by default. Both the legacy paths (keys) and current paths (values) are included.
+
+ Args:
+ allowed_object_mode: either `'all'`, `'core'`, or `'messages'`.
+
+ Returns:
+ Set of class path tuples that are allowed by default.
+ """
+ if allowed_object_mode in _default_class_paths_cache:
+ return _default_class_paths_cache[allowed_object_mode]
+
+ allowed_paths: set[tuple[str, ...]] = set()
+ for key, value in ALL_SERIALIZABLE_MAPPINGS.items():
+ if allowed_object_mode == "core" and value[0] != "langchain_core":
+ continue
+ if allowed_object_mode == "messages" and (
+ value[0] != "langchain_core"
+ or value[-1] not in _MESSAGES_ALLOWED_CLASS_NAMES
+ ):
+ continue
+ allowed_paths.add(key)
+ allowed_paths.add(value)
+
+ _default_class_paths_cache[allowed_object_mode] = allowed_paths
+ return _default_class_paths_cache[allowed_object_mode]
+
+
+def _block_jinja2_templates(
+ class_path: tuple[str, ...],
+ kwargs: dict[str, Any],
+) -> None:
+ """Block jinja2 templates during deserialization for security.
+
+ Jinja2 templates can execute arbitrary code, so they are blocked by default when
+ deserializing objects with `template_format='jinja2'`.
+
+ Note:
+ We intentionally do NOT check the `class_path` here to keep this simple and
+ future-proof. If any new class is added that accepts `template_format='jinja2'`,
+ it will be automatically blocked without needing to update this function.
+
+ Args:
+ class_path: The class path tuple being deserialized (unused).
+ kwargs: The kwargs dict for the class constructor.
+
+ Raises:
+ ValueError: If `template_format` is `'jinja2'`.
+ """
+ _ = class_path # Unused - see docstring for rationale. Kept to satisfy signature.
+ if kwargs.get("template_format") == "jinja2":
+ msg = (
+ "Jinja2 templates are not allowed during deserialization for security "
+ "reasons. Use 'f-string' template format instead, or explicitly allow "
+ "jinja2 by providing a custom init_validator."
+ )
+ raise ValueError(msg)
+
+
+def default_init_validator(
+ class_path: tuple[str, ...],
+ kwargs: dict[str, Any],
+) -> None:
+ """Default init validator that blocks jinja2 templates.
+
+ This is the default validator used by `load()` and `loads()` when no custom
+ validator is provided.
+
+ Args:
+ class_path: The class path tuple being deserialized.
+ kwargs: The kwargs dict for the class constructor.
+
+ Raises:
+ ValueError: If template_format is `'jinja2'`.
+ """
+ _block_jinja2_templates(class_path, kwargs)
+
+
+AllowedObject = type[Serializable]
+"""Type alias for classes that can be included in the `allowed_objects` parameter.
+
+Must be a `Serializable` subclass (the class itself, not an instance).
+"""
+
+InitValidator = Callable[[tuple[str, ...], dict[str, Any]], None]
+"""Type alias for a callable that validates kwargs during deserialization.
+
+The callable receives:
+
+- `class_path`: A tuple of strings identifying the class being instantiated
+ (e.g., `('langchain', 'schema', 'messages', 'AIMessage')`).
+- `kwargs`: The kwargs dict that will be passed to the constructor.
+
+The validator should raise an exception if the object should not be deserialized.
+"""
+
+
+def _compute_allowed_class_paths(
+ allowed_objects: Iterable[AllowedObject],
+ import_mappings: dict[tuple[str, ...], tuple[str, ...]],
+) -> set[tuple[str, ...]]:
+ """Return allowed class paths from an explicit list of classes.
+
+ A class path is a tuple of strings identifying a serializable class, derived from
+ `Serializable.lc_id()`. For example: `('langchain_core', 'messages', 'AIMessage')`.
+
+ Args:
+ allowed_objects: Iterable of `Serializable` subclasses to allow.
+ import_mappings: Mapping of legacy class paths to current class paths.
+
+ Returns:
+ Set of allowed class paths.
+
+ Example:
+ ```python
+ # Allow a specific class
+ _compute_allowed_class_paths([MyPrompt], {}) ->
+ {("langchain_core", "prompts", "MyPrompt")}
+
+ # Include legacy paths that map to the same class
+ import_mappings = {("old", "Prompt"): ("langchain_core", "prompts", "MyPrompt")}
+ _compute_allowed_class_paths([MyPrompt], import_mappings) ->
+ {("langchain_core", "prompts", "MyPrompt"), ("old", "Prompt")}
+ ```
+ """
+ allowed_objects_list = list(allowed_objects)
+
+ allowed_class_paths: set[tuple[str, ...]] = set()
+ for allowed_obj in allowed_objects_list:
+ if not isinstance(allowed_obj, type) or not issubclass(
+ allowed_obj, Serializable
+ ):
+ msg = "allowed_objects must contain Serializable subclasses."
+ raise TypeError(msg)
+
+ class_path = tuple(allowed_obj.lc_id())
+ allowed_class_paths.add(class_path)
+ # Add legacy paths that map to the same class.
+ for mapping_key, mapping_value in import_mappings.items():
+ if tuple(mapping_value) == class_path:
+ allowed_class_paths.add(mapping_key)
+ return allowed_class_paths
+
+
+class Reviver:
+ """Reviver for JSON objects.
+
+ Used as the `object_hook` for `json.loads` to reconstruct LangChain objects from
+ their serialized JSON representation.
+
+ Only classes in the allowlist can be instantiated.
+ """
+
+ def __init__(
+ self,
+ allowed_objects: Iterable[AllowedObject]
+ | Literal["all", "core", "messages"]
+ | None = None,
+ secrets_map: dict[str, str] | None = None,
+ valid_namespaces: list[str] | None = None,
+ secrets_from_env: bool = False, # noqa: FBT001,FBT002
+ additional_import_mappings: dict[tuple[str, ...], tuple[str, ...]]
+ | None = None,
+ *,
+ ignore_unserializable_fields: bool = False,
+ init_validator: InitValidator | None = default_init_validator,
+ ) -> None:
+ """Initialize the reviver.
+
+ See the module docstring for the threat model around `load()`/`loads()`:
+ a serialized payload may carry constructor configuration that affects
+ runtime behavior (custom `base_url`, headers, model name, etc.). Do not
+ use `'core'` or `'all'` with untrusted manifests.
+
+ Args:
+ allowed_objects: Allowlist of classes that can be deserialized.
+ - Explicit list of classes (recommended for untrusted input):
+ only those specific classes are allowed.
+ - `'messages'`: chat-message classes only (e.g. `AIMessage`,
+ `HumanMessage`). Safe for untrusted input.
+ - `'core'` (current default): unsafe with untrusted manifests.
+ Classes defined in the serialization mappings under
+ `langchain_core`.
+ - `'all'`: unsafe with untrusted manifests. Every class in the
+ serialization mappings, including partner chat models and
+ LLMs and their constructor kwargs. See
+ `langchain_core.load.mapping` for the full list.
+ secrets_map: A map of secrets to load.
+
+ Only include the specific secrets the serialized object
+ requires. If a secret is not found in the map, it will be loaded
+ from the environment if `secrets_from_env` is `True`.
+ valid_namespaces: Additional namespaces (modules) to allow during
+ deserialization, beyond the default trusted namespaces.
+ secrets_from_env: Whether to load secrets from the environment.
+
+ A crafted payload can name arbitrary environment variables in
+ its `secret` fields, so enabling this on untrusted data can leak
+ sensitive values. Keep this `False` (the default) unless the
+ serialized data is fully trusted.
+ additional_import_mappings: A dictionary of additional namespace mappings.
+
+ You can use this to override default mappings or add new mappings.
+
+ When `allowed_objects` is `None` (using defaults), paths from these
+ mappings are also added to the allowed class paths.
+ ignore_unserializable_fields: Whether to ignore unserializable fields.
+ init_validator: Optional callable to validate kwargs before instantiation.
+
+ If provided, this function is called with `(class_path, kwargs)` where
+ `class_path` is the class path tuple and `kwargs` is the kwargs dict.
+ The validator should raise an exception if the object should not be
+ deserialized, otherwise return `None`.
+
+ Defaults to `default_init_validator` which blocks jinja2 templates.
+ """
+ if allowed_objects is None:
+ warn_deprecated(
+ since="1.3.3",
+ message=(
+ "The default value of `allowed_objects` will change in a future "
+ "version. Pass an explicit value (e.g., "
+ "allowed_objects='messages' or allowed_objects='core') to suppress "
+ "this warning."
+ ),
+ pending=True,
+ )
+ allowed_objects = "core"
+
+ self.secrets_from_env = secrets_from_env
+ self.secrets_map = secrets_map or {}
+ # By default, only support langchain, but user can pass in additional namespaces
+ self.valid_namespaces = (
+ [*DEFAULT_NAMESPACES, *valid_namespaces]
+ if valid_namespaces
+ else DEFAULT_NAMESPACES
+ )
+ self.additional_import_mappings = additional_import_mappings or {}
+ self.import_mappings = (
+ {
+ **ALL_SERIALIZABLE_MAPPINGS,
+ **self.additional_import_mappings,
+ }
+ if self.additional_import_mappings
+ else ALL_SERIALIZABLE_MAPPINGS
+ )
+ # Compute allowed class paths:
+ # - "all" -> use default paths from mappings (+ additional_import_mappings)
+ # - Explicit list -> compute from those classes
+ if allowed_objects in ("all", "core", "messages"):
+ self.allowed_class_paths: set[tuple[str, ...]] | None = (
+ _get_default_allowed_class_paths(
+ cast("Literal['all', 'core', 'messages']", allowed_objects)
+ ).copy()
+ )
+ # Add paths from additional_import_mappings to the defaults
+ if self.additional_import_mappings:
+ for key, value in self.additional_import_mappings.items():
+ self.allowed_class_paths.add(key)
+ self.allowed_class_paths.add(value)
+ else:
+ self.allowed_class_paths = _compute_allowed_class_paths(
+ cast("Iterable[AllowedObject]", allowed_objects), self.import_mappings
+ )
+ self.ignore_unserializable_fields = ignore_unserializable_fields
+ self.init_validator = init_validator
+
+ def __call__(self, value: dict[str, Any]) -> Any:
+ """Revive the value.
+
+ Args:
+ value: The value to revive.
+
+ Returns:
+ The revived value.
+
+ Raises:
+ ValueError: If the namespace is invalid.
+ ValueError: If trying to deserialize something that cannot
+ be deserialized in the current version of langchain-core.
+ NotImplementedError: If the object is not implemented and
+ `ignore_unserializable_fields` is False.
+ """
+ if (
+ value.get("lc") == 1
+ and value.get("type") == "secret"
+ and value.get("id") is not None
+ ):
+ [key] = value["id"]
+ if key in self.secrets_map:
+ return self.secrets_map[key]
+ if self.secrets_from_env and key in os.environ and os.environ[key]:
+ return os.environ[key]
+ return None
+
+ if (
+ value.get("lc") == 1
+ and value.get("type") == "not_implemented"
+ and value.get("id") is not None
+ ):
+ if self.ignore_unserializable_fields:
+ return None
+ msg = (
+ "Trying to load an object that doesn't implement "
+ f"serialization: {value}"
+ )
+ raise NotImplementedError(msg)
+
+ if (
+ value.get("lc") == 1
+ and value.get("type") == "constructor"
+ and value.get("id") is not None
+ ):
+ [*namespace, name] = value["id"]
+ mapping_key = tuple(value["id"])
+
+ if (
+ self.allowed_class_paths is not None
+ and mapping_key not in self.allowed_class_paths
+ ):
+ msg = (
+ f"Deserialization of {mapping_key!r} is not allowed. "
+ "The default (allowed_objects='core') only permits core "
+ "langchain-core classes. To allow trusted partner integrations, "
+ "use allowed_objects='all'. Alternatively, pass an explicit list "
+ "of allowed classes via allowed_objects=[...]. "
+ "See langchain_core.load.mapping for the full allowlist."
+ )
+ raise ValueError(msg)
+
+ if (
+ namespace[0] not in self.valid_namespaces
+ # The root namespace ["langchain"] is not a valid identifier.
+ or namespace == ["langchain"]
+ ):
+ msg = f"Invalid namespace: {value}"
+ raise ValueError(msg)
+ # Determine explicit import path
+ if mapping_key in self.import_mappings:
+ import_path = self.import_mappings[mapping_key]
+ # Split into module and name
+ import_dir, name = import_path[:-1], import_path[-1]
+ elif namespace[0] in DISALLOW_LOAD_FROM_PATH:
+ msg = (
+ "Trying to deserialize something that cannot "
+ "be deserialized in current version of langchain-core: "
+ f"{mapping_key}."
+ )
+ raise ValueError(msg)
+ else:
+ # Otherwise, treat namespace as path.
+ import_dir = namespace
+
+ # Validate import path is in trusted namespaces before importing
+ if import_dir[0] not in self.valid_namespaces:
+ msg = f"Invalid namespace: {value}"
+ raise ValueError(msg)
+
+ # We don't need to recurse on kwargs
+ # as json.loads will do that for us.
+ kwargs = value.get("kwargs", {})
+
+ # Run class-specific validators before the general init_validator.
+ # These run before importing to fail fast on security violations.
+ if mapping_key in CLASS_INIT_VALIDATORS:
+ CLASS_INIT_VALIDATORS[mapping_key](mapping_key, kwargs)
+
+ # Also run general init_validator (e.g., jinja2 blocking)
+ if self.init_validator is not None:
+ self.init_validator(mapping_key, kwargs)
+
+ mod = importlib.import_module(".".join(import_dir))
+
+ cls = getattr(mod, name)
+
+ # The class must be a subclass of Serializable.
+ if not issubclass(cls, Serializable):
+ msg = f"Invalid namespace: {value}"
+ raise ValueError(msg)
+
+ return cls(**kwargs)
+
+ return value
+
+
+@beta()
+def loads(
+ text: str,
+ *,
+ allowed_objects: Iterable[AllowedObject]
+ | Literal["all", "core", "messages"]
+ | None = None,
+ secrets_map: dict[str, str] | None = None,
+ valid_namespaces: list[str] | None = None,
+ secrets_from_env: bool = False,
+ additional_import_mappings: dict[tuple[str, ...], tuple[str, ...]] | None = None,
+ ignore_unserializable_fields: bool = False,
+ init_validator: InitValidator | None = default_init_validator,
+) -> Any:
+ """Revive a LangChain class from a JSON string.
+
+ Equivalent to `load(json.loads(text))`.
+
+ Only classes in the allowlist can be instantiated. The default allowlist
+ includes core LangChain types (messages, prompts, documents, etc.). See
+ `langchain_core.load.mapping` for the full list.
+
+ !!! warning "Do not use with untrusted input"
+
+ A serialized payload may carry constructor kwargs that affect runtime
+ behavior (custom `base_url`, headers, model name, etc.), so it should be
+ treated as executable configuration rather than plain text. If the
+ source is untrusted, avoid calling `loads()` on it; if you must, pass
+ `allowed_objects='messages'` or an explicit list of message classes.
+ See the module-level threat model for details.
+
+ Args:
+ text: The string to load.
+ allowed_objects: Allowlist of classes that can be deserialized.
+
+ - Explicit list of classes (recommended for untrusted input): only
+ those specific classes are allowed.
+ - `'messages'`: chat-message classes only. Safe for untrusted input.
+ - `'core'` (current default): unsafe with untrusted manifests.
+ Classes defined in the serialization mappings under
+ `langchain_core`.
+ - `'all'`: unsafe with untrusted manifests. Every class in the
+ serialization mappings, including partner chat models and LLMs
+ and their constructor kwargs. See `langchain_core.load.mapping`
+ for the full list.
+ - `[]`: Disallow all deserialization (will raise on any object).
+ secrets_map: A map of secrets to load.
+
+ Only include the specific secrets the serialized object requires. If
+ a secret is not found in the map, it will be loaded from the
+ environment if `secrets_from_env` is `True`.
+ valid_namespaces: Additional namespaces (modules) to allow during
+ deserialization, beyond the default trusted namespaces.
+ secrets_from_env: Whether to load secrets from the environment.
+
+ A crafted payload can name arbitrary environment variables in its
+ `secret` fields, so enabling this on untrusted data can leak
+ sensitive values. Keep this `False` (the default) unless the
+ serialized data is fully trusted.
+ additional_import_mappings: A dictionary of additional namespace mappings.
+
+ You can use this to override default mappings or add new mappings.
+
+ When `allowed_objects` is `None` (using defaults), paths from these
+ mappings are also added to the allowed class paths.
+ ignore_unserializable_fields: Whether to ignore unserializable fields.
+ init_validator: Optional callable to validate kwargs before instantiation.
+
+ If provided, this function is called with `(class_path, kwargs)` where
+ `class_path` is the class path tuple and `kwargs` is the kwargs dict.
+ The validator should raise an exception if the object should not be
+ deserialized, otherwise return `None`.
+
+ Defaults to `default_init_validator` which blocks jinja2 templates.
+
+ Returns:
+ Revived LangChain objects.
+
+ Raises:
+ ValueError: If an object's class path is not in the `allowed_objects` allowlist.
+ """
+ if allowed_objects is None:
+ warn_deprecated(
+ since="1.3.3",
+ message=(
+ "The default value of `allowed_objects` will change in a future "
+ "version. Pass an explicit list of allowed classes (or "
+ "'messages' for untrusted input that contains only chat "
+ "messages) to suppress this warning."
+ ),
+ pending=True,
+ )
+ allowed_objects = "core"
+
+ # Parse JSON and delegate to load() for proper escape handling
+ raw_obj = json.loads(text)
+ return load(
+ raw_obj,
+ allowed_objects=allowed_objects,
+ secrets_map=secrets_map,
+ valid_namespaces=valid_namespaces,
+ secrets_from_env=secrets_from_env,
+ additional_import_mappings=additional_import_mappings,
+ ignore_unserializable_fields=ignore_unserializable_fields,
+ init_validator=init_validator,
+ )
+
+
+@beta()
+def load(
+ obj: Any,
+ *,
+ allowed_objects: Iterable[AllowedObject]
+ | Literal["all", "core", "messages"]
+ | None = None,
+ secrets_map: dict[str, str] | None = None,
+ valid_namespaces: list[str] | None = None,
+ secrets_from_env: bool = False,
+ additional_import_mappings: dict[tuple[str, ...], tuple[str, ...]] | None = None,
+ ignore_unserializable_fields: bool = False,
+ init_validator: InitValidator | None = default_init_validator,
+) -> Any:
+ """Revive a LangChain class from a JSON object.
+
+ Use this if you already have a parsed JSON object, eg. from `json.load` or
+ `orjson.loads`.
+
+ Only classes in the allowlist can be instantiated. The default allowlist
+ includes core LangChain types (messages, prompts, documents, etc.). See
+ `langchain_core.load.mapping` for the full list.
+
+ !!! warning "Do not use with untrusted input"
+
+ A serialized payload may carry constructor kwargs that affect runtime
+ behavior (custom `base_url`, headers, model name, etc.), so it should be
+ treated as executable configuration rather than plain text. If the
+ source is untrusted, avoid calling `load()` on it; if you must, pass
+ `allowed_objects='messages'` or an explicit list of message classes.
+ See the module-level threat model for details.
+
+ Args:
+ obj: The object to load.
+ allowed_objects: Allowlist of classes that can be deserialized.
+
+ - Explicit list of classes (recommended for untrusted input): only
+ those specific classes are allowed.
+ - `'messages'`: chat-message classes only. Safe for untrusted input.
+ - `'core'` (current default): unsafe with untrusted manifests.
+ Classes defined in the serialization mappings under
+ `langchain_core`.
+ - `'all'`: unsafe with untrusted manifests. Every class in the
+ serialization mappings, including partner chat models and LLMs
+ and their constructor kwargs. See `langchain_core.load.mapping`
+ for the full list.
+ - `[]`: Disallow all deserialization (will raise on any object).
+ secrets_map: A map of secrets to load.
+
+ Only include the specific secrets the serialized object requires.
+
+ If a secret is not found in the map, it will be loaded from the environment
+ if `secrets_from_env` is `True`.
+ valid_namespaces: Additional namespaces (modules) to allow during
+ deserialization, beyond the default trusted namespaces.
+ secrets_from_env: Whether to load secrets from the environment.
+
+ A crafted payload can name arbitrary environment variables in its
+ `secret` fields, so enabling this on untrusted data can leak
+ sensitive values. Keep this `False` (the default) unless the
+ serialized data is fully trusted.
+ additional_import_mappings: A dictionary of additional namespace mappings.
+
+ You can use this to override default mappings or add new mappings.
+
+ When `allowed_objects` is `None` (using defaults), paths from these
+ mappings are also added to the allowed class paths.
+ ignore_unserializable_fields: Whether to ignore unserializable fields.
+ init_validator: Optional callable to validate kwargs before instantiation.
+
+ If provided, this function is called with `(class_path, kwargs)` where
+ `class_path` is the class path tuple and `kwargs` is the kwargs dict.
+ The validator should raise an exception if the object should not be
+ deserialized, otherwise return `None`.
+
+ Defaults to `default_init_validator` which blocks jinja2 templates.
+
+ Returns:
+ Revived LangChain objects.
+
+ Raises:
+ ValueError: If an object's class path is not in the `allowed_objects` allowlist.
+
+ Example:
+ ```python
+ from langchain_core.load import load, dumpd
+ from langchain_core.messages import AIMessage
+
+ msg = AIMessage(content="Hello")
+ data = dumpd(msg)
+
+ # Deserialize using default allowlist
+ loaded = load(data)
+
+ # Or with explicit allowlist
+ loaded = load(data, allowed_objects=[AIMessage])
+
+ # Or extend defaults with additional mappings
+ loaded = load(
+ data,
+ additional_import_mappings={
+ ("my_pkg", "MyClass"): ("my_pkg", "module", "MyClass"),
+ },
+ )
+ ```
+ """
+ if allowed_objects is None:
+ warn_deprecated(
+ since="1.3.3",
+ message=(
+ "The default value of `allowed_objects` will change in a future "
+ "version. Pass an explicit list of allowed classes (or "
+ "'messages' for untrusted input that contains only chat "
+ "messages) to suppress this warning."
+ ),
+ pending=True,
+ )
+ allowed_objects = "core"
+
+ reviver = Reviver(
+ allowed_objects,
+ secrets_map,
+ valid_namespaces,
+ secrets_from_env,
+ additional_import_mappings,
+ ignore_unserializable_fields=ignore_unserializable_fields,
+ init_validator=init_validator,
+ )
+
+ def _load(obj: Any) -> Any:
+ if isinstance(obj, dict):
+ # Check for escaped dict FIRST (before recursing).
+ # Escaped dicts are user data that should NOT be processed as LC objects.
+ if _is_escaped_dict(obj):
+ return _unescape_value(obj)
+
+ # Not escaped - recurse into children then apply reviver
+ loaded_obj = {k: _load(v) for k, v in obj.items()}
+ return reviver(loaded_obj)
+ if isinstance(obj, list):
+ return [_load(o) for o in obj]
+ return obj
+
+ return _load(obj)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/mapping.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/mapping.py
new file mode 100644
index 0000000000000000000000000000000000000000..53a92824858307586b3dcc9283dd8e2161f95fc6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/mapping.py
@@ -0,0 +1,1085 @@
+"""Serialization mapping.
+
+This file contains a mapping between the `lc_namespace` path for a given
+subclass that implements from `Serializable` to the namespace
+where that class is actually located.
+
+This mapping helps maintain the ability to serialize and deserialize
+well-known LangChain objects even if they are moved around in the codebase
+across different LangChain versions.
+
+For example, the code for the `AIMessage` class is located in
+`langchain_core.messages.ai.AIMessage`. This message is associated with the
+`lc_namespace` of `["langchain", "schema", "messages", "AIMessage"]`,
+because this code was originally in `langchain.schema.messages.AIMessage`.
+
+The mapping allows us to deserialize an `AIMessage` created with an older
+version of LangChain where the code was in a different location.
+"""
+
+# First value is the value that it is serialized as
+# Second value is the path to load it from
+SERIALIZABLE_MAPPING: dict[tuple[str, ...], tuple[str, ...]] = {
+ ("langchain", "schema", "messages", "AIMessage"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessage",
+ ),
+ ("langchain", "schema", "messages", "AIMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessageChunk",
+ ),
+ ("langchain", "schema", "messages", "BaseMessage"): (
+ "langchain_core",
+ "messages",
+ "base",
+ "BaseMessage",
+ ),
+ ("langchain", "schema", "messages", "BaseMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "base",
+ "BaseMessageChunk",
+ ),
+ ("langchain", "schema", "messages", "ChatMessage"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessage",
+ ),
+ ("langchain", "schema", "messages", "FunctionMessage"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessage",
+ ),
+ ("langchain", "schema", "messages", "HumanMessage"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessage",
+ ),
+ ("langchain", "schema", "messages", "SystemMessage"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessage",
+ ),
+ ("langchain", "schema", "messages", "ToolMessage"): (
+ "langchain_core",
+ "messages",
+ "tool",
+ "ToolMessage",
+ ),
+ ("langchain", "schema", "messages", "RemoveMessage"): (
+ "langchain_core",
+ "messages",
+ "modifier",
+ "RemoveMessage",
+ ),
+ ("langchain", "schema", "agent", "AgentAction"): (
+ "langchain_core",
+ "agents",
+ "AgentAction",
+ ),
+ ("langchain", "schema", "agent", "AgentFinish"): (
+ "langchain_core",
+ "agents",
+ "AgentFinish",
+ ),
+ ("langchain", "schema", "prompt_template", "BasePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "base",
+ "BasePromptTemplate",
+ ),
+ ("langchain", "chains", "llm", "LLMChain"): (
+ "langchain",
+ "chains",
+ "llm",
+ "LLMChain",
+ ),
+ ("langchain", "prompts", "prompt", "PromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "prompt",
+ "PromptTemplate",
+ ),
+ ("langchain", "prompts", "chat", "MessagesPlaceholder"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "MessagesPlaceholder",
+ ),
+ ("langchain", "llms", "openai", "OpenAI"): (
+ "langchain_openai",
+ "llms",
+ "base",
+ "OpenAI",
+ ),
+ ("langchain", "prompts", "chat", "ChatPromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "ChatPromptTemplate",
+ ),
+ ("langchain", "prompts", "chat", "HumanMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "HumanMessagePromptTemplate",
+ ),
+ ("langchain", "prompts", "chat", "SystemMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "SystemMessagePromptTemplate",
+ ),
+ ("langchain", "prompts", "image", "ImagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "image",
+ "ImagePromptTemplate",
+ ),
+ ("langchain", "schema", "agent", "AgentActionMessageLog"): (
+ "langchain_core",
+ "agents",
+ "AgentActionMessageLog",
+ ),
+ ("langchain", "schema", "agent", "ToolAgentAction"): (
+ "langchain",
+ "agents",
+ "output_parsers",
+ "tools",
+ "ToolAgentAction",
+ ),
+ ("langchain", "prompts", "chat", "BaseMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "BaseMessagePromptTemplate",
+ ),
+ ("langchain", "schema", "output", "ChatGeneration"): (
+ "langchain_core",
+ "outputs",
+ "chat_generation",
+ "ChatGeneration",
+ ),
+ ("langchain", "schema", "output", "Generation"): (
+ "langchain_core",
+ "outputs",
+ "generation",
+ "Generation",
+ ),
+ ("langchain", "schema", "document", "Document"): (
+ "langchain_core",
+ "documents",
+ "base",
+ "Document",
+ ),
+ ("langchain", "output_parsers", "fix", "OutputFixingParser"): (
+ "langchain",
+ "output_parsers",
+ "fix",
+ "OutputFixingParser",
+ ),
+ ("langchain", "prompts", "chat", "AIMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "AIMessagePromptTemplate",
+ ),
+ ("langchain", "output_parsers", "regex", "RegexParser"): (
+ "langchain",
+ "output_parsers",
+ "regex",
+ "RegexParser",
+ ),
+ ("langchain", "schema", "runnable", "DynamicRunnable"): (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "DynamicRunnable",
+ ),
+ ("langchain", "schema", "prompt", "PromptValue"): (
+ "langchain_core",
+ "prompt_values",
+ "PromptValue",
+ ),
+ ("langchain", "schema", "runnable", "RunnableBinding"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableBinding",
+ ),
+ ("langchain", "schema", "runnable", "RunnableBranch"): (
+ "langchain_core",
+ "runnables",
+ "branch",
+ "RunnableBranch",
+ ),
+ ("langchain", "schema", "runnable", "RunnableWithFallbacks"): (
+ "langchain_core",
+ "runnables",
+ "fallbacks",
+ "RunnableWithFallbacks",
+ ),
+ ("langchain", "schema", "output_parser", "StrOutputParser"): (
+ "langchain_core",
+ "output_parsers",
+ "string",
+ "StrOutputParser",
+ ),
+ ("langchain", "chat_models", "openai", "ChatOpenAI"): (
+ "langchain_openai",
+ "chat_models",
+ "base",
+ "ChatOpenAI",
+ ),
+ ("langchain", "output_parsers", "list", "CommaSeparatedListOutputParser"): (
+ "langchain_core",
+ "output_parsers",
+ "list",
+ "CommaSeparatedListOutputParser",
+ ),
+ ("langchain", "schema", "runnable", "RunnableParallel"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableParallel",
+ ),
+ ("langchain", "chat_models", "azure_openai", "AzureChatOpenAI"): (
+ "langchain_openai",
+ "chat_models",
+ "azure",
+ "AzureChatOpenAI",
+ ),
+ ("langchain", "chat_models", "bedrock", "BedrockChat"): (
+ "langchain_aws",
+ "chat_models",
+ "bedrock",
+ "ChatBedrock",
+ ),
+ ("langchain", "chat_models", "anthropic", "ChatAnthropic"): (
+ "langchain_anthropic",
+ "chat_models",
+ "ChatAnthropic",
+ ),
+ ("langchain_groq", "chat_models", "ChatGroq"): (
+ "langchain_groq",
+ "chat_models",
+ "ChatGroq",
+ ),
+ ("langchain_openrouter", "chat_models", "ChatOpenRouter"): (
+ "langchain_openrouter",
+ "chat_models",
+ "ChatOpenRouter",
+ ),
+ ("langchain_xai", "chat_models", "ChatXAI"): (
+ "langchain_xai",
+ "chat_models",
+ "ChatXAI",
+ ),
+ ("langchain_baseten", "chat_models", "ChatBaseten"): (
+ "langchain_baseten",
+ "chat_models",
+ "ChatBaseten",
+ ),
+ ("langchain", "chat_models", "fireworks", "ChatFireworks"): (
+ "langchain_fireworks",
+ "chat_models",
+ "ChatFireworks",
+ ),
+ ("langchain", "chat_models", "google_palm", "ChatGooglePalm"): (
+ "langchain",
+ "chat_models",
+ "google_palm",
+ "ChatGooglePalm",
+ ),
+ ("langchain", "chat_models", "vertexai", "ChatVertexAI"): (
+ "langchain_google_vertexai",
+ "chat_models",
+ "ChatVertexAI",
+ ),
+ ("langchain", "chat_models", "mistralai", "ChatMistralAI"): (
+ "langchain_mistralai",
+ "chat_models",
+ "ChatMistralAI",
+ ),
+ ("langchain", "chat_models", "anthropic_bedrock", "ChatAnthropicBedrock"): (
+ "langchain_aws",
+ "chat_models",
+ "anthropic",
+ "ChatAnthropicBedrock",
+ ),
+ ("langchain", "chat_models", "bedrock", "ChatBedrock"): (
+ "langchain_aws",
+ "chat_models",
+ "bedrock",
+ "ChatBedrock",
+ ),
+ ("langchain_aws", "chat_models", "ChatBedrockConverse"): (
+ "langchain_aws",
+ "chat_models",
+ "bedrock_converse",
+ "ChatBedrockConverse",
+ ),
+ ("langchain_google_genai", "chat_models", "ChatGoogleGenerativeAI"): (
+ "langchain_google_genai",
+ "chat_models",
+ "ChatGoogleGenerativeAI",
+ ),
+ ("langchain", "schema", "output", "ChatGenerationChunk"): (
+ "langchain_core",
+ "outputs",
+ "chat_generation",
+ "ChatGenerationChunk",
+ ),
+ ("langchain", "schema", "messages", "ChatMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessageChunk",
+ ),
+ ("langchain", "schema", "messages", "HumanMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessageChunk",
+ ),
+ ("langchain", "schema", "messages", "FunctionMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessageChunk",
+ ),
+ ("langchain", "schema", "messages", "SystemMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessageChunk",
+ ),
+ ("langchain", "schema", "messages", "ToolMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "tool",
+ "ToolMessageChunk",
+ ),
+ ("langchain", "schema", "output", "GenerationChunk"): (
+ "langchain_core",
+ "outputs",
+ "generation",
+ "GenerationChunk",
+ ),
+ ("langchain", "llms", "openai", "BaseOpenAI"): (
+ "langchain",
+ "llms",
+ "openai",
+ "BaseOpenAI",
+ ),
+ ("langchain", "llms", "bedrock", "Bedrock"): (
+ "langchain_aws",
+ "llms",
+ "bedrock",
+ "BedrockLLM",
+ ),
+ ("langchain", "llms", "bedrock", "BedrockLLM"): (
+ "langchain_aws",
+ "llms",
+ "bedrock",
+ "BedrockLLM",
+ ),
+ ("langchain", "llms", "fireworks", "Fireworks"): (
+ "langchain_fireworks",
+ "llms",
+ "Fireworks",
+ ),
+ ("langchain", "llms", "google_palm", "GooglePalm"): (
+ "langchain",
+ "llms",
+ "google_palm",
+ "GooglePalm",
+ ),
+ ("langchain", "llms", "openai", "AzureOpenAI"): (
+ "langchain_openai",
+ "llms",
+ "azure",
+ "AzureOpenAI",
+ ),
+ ("langchain", "llms", "replicate", "Replicate"): (
+ "langchain",
+ "llms",
+ "replicate",
+ "Replicate",
+ ),
+ ("langchain", "llms", "vertexai", "VertexAI"): (
+ "langchain_vertexai",
+ "llms",
+ "VertexAI",
+ ),
+ ("langchain", "output_parsers", "combining", "CombiningOutputParser"): (
+ "langchain",
+ "output_parsers",
+ "combining",
+ "CombiningOutputParser",
+ ),
+ ("langchain", "schema", "prompt_template", "BaseChatPromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "BaseChatPromptTemplate",
+ ),
+ ("langchain", "prompts", "chat", "ChatMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "ChatMessagePromptTemplate",
+ ),
+ ("langchain", "prompts", "few_shot_with_templates", "FewShotPromptWithTemplates"): (
+ "langchain_core",
+ "prompts",
+ "few_shot_with_templates",
+ "FewShotPromptWithTemplates",
+ ),
+ ("langchain", "prompts", "pipeline"): (
+ "langchain_core",
+ "prompts",
+ "pipeline",
+ ),
+ ("langchain", "prompts", "base", "StringPromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "string",
+ "StringPromptTemplate",
+ ),
+ ("langchain", "prompts", "base", "StringPromptValue"): (
+ "langchain_core",
+ "prompt_values",
+ "StringPromptValue",
+ ),
+ ("langchain", "prompts", "chat", "BaseStringMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "BaseStringMessagePromptTemplate",
+ ),
+ ("langchain", "prompts", "chat", "ChatPromptValue"): (
+ "langchain_core",
+ "prompt_values",
+ "ChatPromptValue",
+ ),
+ ("langchain", "prompts", "chat", "ChatPromptValueConcrete"): (
+ "langchain_core",
+ "prompt_values",
+ "ChatPromptValueConcrete",
+ ),
+ ("langchain", "schema", "runnable", "HubRunnable"): (
+ "langchain",
+ "runnables",
+ "hub",
+ "HubRunnable",
+ ),
+ ("langchain", "schema", "runnable", "RunnableBindingBase"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableBindingBase",
+ ),
+ ("langchain", "schema", "runnable", "OpenAIFunctionsRouter"): (
+ "langchain",
+ "runnables",
+ "openai_functions",
+ "OpenAIFunctionsRouter",
+ ),
+ ("langchain", "schema", "runnable", "RouterRunnable"): (
+ "langchain_core",
+ "runnables",
+ "router",
+ "RouterRunnable",
+ ),
+ ("langchain", "schema", "runnable", "RunnablePassthrough"): (
+ "langchain_core",
+ "runnables",
+ "passthrough",
+ "RunnablePassthrough",
+ ),
+ ("langchain", "schema", "runnable", "RunnableSequence"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableSequence",
+ ),
+ ("langchain", "schema", "runnable", "RunnableEach"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableEach",
+ ),
+ ("langchain", "schema", "runnable", "RunnableEachBase"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableEachBase",
+ ),
+ ("langchain", "schema", "runnable", "RunnableConfigurableAlternatives"): (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "RunnableConfigurableAlternatives",
+ ),
+ ("langchain", "schema", "runnable", "RunnableConfigurableFields"): (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "RunnableConfigurableFields",
+ ),
+ ("langchain", "schema", "runnable", "RunnableWithMessageHistory"): (
+ "langchain_core",
+ "runnables",
+ "history",
+ "RunnableWithMessageHistory",
+ ),
+ ("langchain", "schema", "runnable", "RunnableAssign"): (
+ "langchain_core",
+ "runnables",
+ "passthrough",
+ "RunnableAssign",
+ ),
+ ("langchain", "schema", "runnable", "RunnableRetry"): (
+ "langchain_core",
+ "runnables",
+ "retry",
+ "RunnableRetry",
+ ),
+ ("langchain_core", "prompts", "structured", "StructuredPrompt"): (
+ "langchain_core",
+ "prompts",
+ "structured",
+ "StructuredPrompt",
+ ),
+ ("langchain_core", "prompts", "message", "_DictMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "dict",
+ "DictPromptTemplate",
+ ),
+}
+
+# Needed for backwards compatibility for old versions of LangChain where things
+# Were in different place
+_OG_SERIALIZABLE_MAPPING: dict[tuple[str, ...], tuple[str, ...]] = {
+ ("langchain", "schema", "AIMessage"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessage",
+ ),
+ ("langchain", "schema", "ChatMessage"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessage",
+ ),
+ ("langchain", "schema", "FunctionMessage"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessage",
+ ),
+ ("langchain", "schema", "HumanMessage"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessage",
+ ),
+ ("langchain", "schema", "SystemMessage"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessage",
+ ),
+ ("langchain", "schema", "prompt_template", "ImagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "image",
+ "ImagePromptTemplate",
+ ),
+ ("langchain", "schema", "agent", "OpenAIToolAgentAction"): (
+ "langchain",
+ "agents",
+ "output_parsers",
+ "openai_tools",
+ "OpenAIToolAgentAction",
+ ),
+}
+
+# Needed for backwards compatibility for a few versions where we serialized
+# with langchain_core paths.
+OLD_CORE_NAMESPACES_MAPPING: dict[tuple[str, ...], tuple[str, ...]] = {
+ ("langchain_core", "messages", "ai", "AIMessage"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessage",
+ ),
+ ("langchain_core", "messages", "ai", "AIMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessageChunk",
+ ),
+ ("langchain_core", "messages", "base", "BaseMessage"): (
+ "langchain_core",
+ "messages",
+ "base",
+ "BaseMessage",
+ ),
+ ("langchain_core", "messages", "base", "BaseMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "base",
+ "BaseMessageChunk",
+ ),
+ ("langchain_core", "messages", "chat", "ChatMessage"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessage",
+ ),
+ ("langchain_core", "messages", "function", "FunctionMessage"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessage",
+ ),
+ ("langchain_core", "messages", "human", "HumanMessage"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessage",
+ ),
+ ("langchain_core", "messages", "system", "SystemMessage"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessage",
+ ),
+ ("langchain_core", "messages", "tool", "ToolMessage"): (
+ "langchain_core",
+ "messages",
+ "tool",
+ "ToolMessage",
+ ),
+ ("langchain_core", "agents", "AgentAction"): (
+ "langchain_core",
+ "agents",
+ "AgentAction",
+ ),
+ ("langchain_core", "agents", "AgentFinish"): (
+ "langchain_core",
+ "agents",
+ "AgentFinish",
+ ),
+ ("langchain_core", "prompts", "base", "BasePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "base",
+ "BasePromptTemplate",
+ ),
+ ("langchain_core", "prompts", "prompt", "PromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "prompt",
+ "PromptTemplate",
+ ),
+ ("langchain_core", "prompts", "chat", "MessagesPlaceholder"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "MessagesPlaceholder",
+ ),
+ ("langchain_core", "prompts", "chat", "ChatPromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "ChatPromptTemplate",
+ ),
+ ("langchain_core", "prompts", "chat", "HumanMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "HumanMessagePromptTemplate",
+ ),
+ ("langchain_core", "prompts", "chat", "SystemMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "SystemMessagePromptTemplate",
+ ),
+ ("langchain_core", "agents", "AgentActionMessageLog"): (
+ "langchain_core",
+ "agents",
+ "AgentActionMessageLog",
+ ),
+ ("langchain_core", "prompts", "chat", "BaseMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "BaseMessagePromptTemplate",
+ ),
+ ("langchain_core", "outputs", "chat_generation", "ChatGeneration"): (
+ "langchain_core",
+ "outputs",
+ "chat_generation",
+ "ChatGeneration",
+ ),
+ ("langchain_core", "outputs", "generation", "Generation"): (
+ "langchain_core",
+ "outputs",
+ "generation",
+ "Generation",
+ ),
+ ("langchain_core", "documents", "base", "Document"): (
+ "langchain_core",
+ "documents",
+ "base",
+ "Document",
+ ),
+ ("langchain_core", "prompts", "chat", "AIMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "AIMessagePromptTemplate",
+ ),
+ ("langchain_core", "runnables", "configurable", "DynamicRunnable"): (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "DynamicRunnable",
+ ),
+ ("langchain_core", "prompt_values", "PromptValue"): (
+ "langchain_core",
+ "prompt_values",
+ "PromptValue",
+ ),
+ ("langchain_core", "runnables", "base", "RunnableBinding"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableBinding",
+ ),
+ ("langchain_core", "runnables", "branch", "RunnableBranch"): (
+ "langchain_core",
+ "runnables",
+ "branch",
+ "RunnableBranch",
+ ),
+ ("langchain_core", "runnables", "fallbacks", "RunnableWithFallbacks"): (
+ "langchain_core",
+ "runnables",
+ "fallbacks",
+ "RunnableWithFallbacks",
+ ),
+ ("langchain_core", "output_parsers", "string", "StrOutputParser"): (
+ "langchain_core",
+ "output_parsers",
+ "string",
+ "StrOutputParser",
+ ),
+ ("langchain_core", "output_parsers", "list", "CommaSeparatedListOutputParser"): (
+ "langchain_core",
+ "output_parsers",
+ "list",
+ "CommaSeparatedListOutputParser",
+ ),
+ ("langchain_core", "runnables", "base", "RunnableParallel"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableParallel",
+ ),
+ ("langchain_core", "outputs", "chat_generation", "ChatGenerationChunk"): (
+ "langchain_core",
+ "outputs",
+ "chat_generation",
+ "ChatGenerationChunk",
+ ),
+ ("langchain_core", "messages", "chat", "ChatMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessageChunk",
+ ),
+ ("langchain_core", "messages", "human", "HumanMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessageChunk",
+ ),
+ ("langchain_core", "messages", "function", "FunctionMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessageChunk",
+ ),
+ ("langchain_core", "messages", "system", "SystemMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessageChunk",
+ ),
+ ("langchain_core", "messages", "tool", "ToolMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "tool",
+ "ToolMessageChunk",
+ ),
+ ("langchain_core", "outputs", "generation", "GenerationChunk"): (
+ "langchain_core",
+ "outputs",
+ "generation",
+ "GenerationChunk",
+ ),
+ ("langchain_core", "prompts", "chat", "BaseChatPromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "BaseChatPromptTemplate",
+ ),
+ ("langchain_core", "prompts", "chat", "ChatMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "ChatMessagePromptTemplate",
+ ),
+ (
+ "langchain_core",
+ "prompts",
+ "few_shot_with_templates",
+ "FewShotPromptWithTemplates",
+ ): (
+ "langchain_core",
+ "prompts",
+ "few_shot_with_templates",
+ "FewShotPromptWithTemplates",
+ ),
+ ("langchain_core", "prompts", "pipeline"): (
+ "langchain_core",
+ "prompts",
+ "pipeline",
+ ),
+ ("langchain_core", "prompts", "string", "StringPromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "string",
+ "StringPromptTemplate",
+ ),
+ ("langchain_core", "prompt_values", "StringPromptValue"): (
+ "langchain_core",
+ "prompt_values",
+ "StringPromptValue",
+ ),
+ ("langchain_core", "prompts", "chat", "BaseStringMessagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "chat",
+ "BaseStringMessagePromptTemplate",
+ ),
+ ("langchain_core", "prompt_values", "ChatPromptValue"): (
+ "langchain_core",
+ "prompt_values",
+ "ChatPromptValue",
+ ),
+ ("langchain_core", "prompt_values", "ChatPromptValueConcrete"): (
+ "langchain_core",
+ "prompt_values",
+ "ChatPromptValueConcrete",
+ ),
+ ("langchain_core", "runnables", "base", "RunnableBindingBase"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableBindingBase",
+ ),
+ ("langchain_core", "runnables", "router", "RouterRunnable"): (
+ "langchain_core",
+ "runnables",
+ "router",
+ "RouterRunnable",
+ ),
+ ("langchain_core", "runnables", "passthrough", "RunnablePassthrough"): (
+ "langchain_core",
+ "runnables",
+ "passthrough",
+ "RunnablePassthrough",
+ ),
+ ("langchain_core", "runnables", "base", "RunnableSequence"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableSequence",
+ ),
+ ("langchain_core", "runnables", "base", "RunnableEach"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableEach",
+ ),
+ ("langchain_core", "runnables", "base", "RunnableEachBase"): (
+ "langchain_core",
+ "runnables",
+ "base",
+ "RunnableEachBase",
+ ),
+ (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "RunnableConfigurableAlternatives",
+ ): (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "RunnableConfigurableAlternatives",
+ ),
+ ("langchain_core", "runnables", "configurable", "RunnableConfigurableFields"): (
+ "langchain_core",
+ "runnables",
+ "configurable",
+ "RunnableConfigurableFields",
+ ),
+ ("langchain_core", "runnables", "history", "RunnableWithMessageHistory"): (
+ "langchain_core",
+ "runnables",
+ "history",
+ "RunnableWithMessageHistory",
+ ),
+ ("langchain_core", "runnables", "passthrough", "RunnableAssign"): (
+ "langchain_core",
+ "runnables",
+ "passthrough",
+ "RunnableAssign",
+ ),
+ ("langchain_core", "runnables", "retry", "RunnableRetry"): (
+ "langchain_core",
+ "runnables",
+ "retry",
+ "RunnableRetry",
+ ),
+}
+
+_JS_SERIALIZABLE_MAPPING: dict[tuple[str, ...], tuple[str, ...]] = {
+ ("langchain_core", "messages", "AIMessage"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessage",
+ ),
+ ("langchain_core", "messages", "AIMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "ai",
+ "AIMessageChunk",
+ ),
+ ("langchain_core", "messages", "BaseMessage"): (
+ "langchain_core",
+ "messages",
+ "base",
+ "BaseMessage",
+ ),
+ ("langchain_core", "messages", "BaseMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "base",
+ "BaseMessageChunk",
+ ),
+ ("langchain_core", "messages", "ChatMessage"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessage",
+ ),
+ ("langchain_core", "messages", "ChatMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "chat",
+ "ChatMessageChunk",
+ ),
+ ("langchain_core", "messages", "FunctionMessage"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessage",
+ ),
+ ("langchain_core", "messages", "FunctionMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "function",
+ "FunctionMessageChunk",
+ ),
+ ("langchain_core", "messages", "HumanMessage"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessage",
+ ),
+ ("langchain_core", "messages", "HumanMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "human",
+ "HumanMessageChunk",
+ ),
+ ("langchain_core", "messages", "SystemMessage"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessage",
+ ),
+ ("langchain_core", "messages", "SystemMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "system",
+ "SystemMessageChunk",
+ ),
+ ("langchain_core", "messages", "ToolMessage"): (
+ "langchain_core",
+ "messages",
+ "tool",
+ "ToolMessage",
+ ),
+ ("langchain_core", "messages", "ToolMessageChunk"): (
+ "langchain_core",
+ "messages",
+ "tool",
+ "ToolMessageChunk",
+ ),
+ ("langchain_core", "prompts", "image", "ImagePromptTemplate"): (
+ "langchain_core",
+ "prompts",
+ "image",
+ "ImagePromptTemplate",
+ ),
+ ("langchain", "chat_models", "bedrock", "ChatBedrock"): (
+ "langchain_aws",
+ "chat_models",
+ "ChatBedrock",
+ ),
+ ("langchain", "chat_models", "google_genai", "ChatGoogleGenerativeAI"): (
+ "langchain_google_genai",
+ "chat_models",
+ "ChatGoogleGenerativeAI",
+ ),
+ ("langchain", "chat_models", "groq", "ChatGroq"): (
+ "langchain_groq",
+ "chat_models",
+ "ChatGroq",
+ ),
+ ("langchain", "chat_models", "bedrock", "BedrockChat"): (
+ "langchain_aws",
+ "chat_models",
+ "ChatBedrock",
+ ),
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/serializable.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/serializable.py
new file mode 100644
index 0000000000000000000000000000000000000000..429a5e8f88a0cac9b9c46a8e2d3ff1b2ae32218f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/serializable.py
@@ -0,0 +1,388 @@
+"""Serializable base class."""
+
+import contextlib
+import logging
+from abc import ABC
+from typing import (
+ Any,
+ Literal,
+ TypedDict,
+ cast,
+)
+
+from pydantic import BaseModel, ConfigDict
+from pydantic.fields import FieldInfo
+from typing_extensions import NotRequired, override
+
+logger = logging.getLogger(__name__)
+
+
+class BaseSerialized(TypedDict):
+ """Base class for serialized objects."""
+
+ lc: int
+ """The version of the serialization format."""
+ id: list[str]
+ """The unique identifier of the object."""
+ name: NotRequired[str]
+ """The name of the object."""
+ graph: NotRequired[dict[str, Any]]
+ """The graph of the object."""
+
+
+class SerializedConstructor(BaseSerialized):
+ """Serialized constructor."""
+
+ type: Literal["constructor"]
+ """The type of the object. Must be `'constructor'`."""
+ kwargs: dict[str, Any]
+ """The constructor arguments."""
+
+
+class SerializedSecret(BaseSerialized):
+ """Serialized secret."""
+
+ type: Literal["secret"]
+ """The type of the object. Must be `'secret'`."""
+
+
+class SerializedNotImplemented(BaseSerialized):
+ """Serialized not implemented."""
+
+ type: Literal["not_implemented"]
+ """The type of the object. Must be `'not_implemented'`."""
+ repr: str | None
+ """The representation of the object."""
+
+
+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 Pydantic model.
+
+ Returns:
+ Whether the value is different from the default.
+ """
+ field = type(model).model_fields[key]
+ return _try_neq_default(value, field)
+
+
+def _try_neq_default(value: Any, field: FieldInfo) -> bool:
+ # Handle edge case: inequality of two objects does not evaluate to a bool (e.g. two
+ # Pandas DataFrames).
+ try:
+ return bool(field.get_default() != value)
+ except Exception as _:
+ try:
+ return all(field.get_default() != value)
+ except Exception as _:
+ try:
+ return value is not field.default
+ except Exception as _:
+ return False
+
+
+class Serializable(BaseModel, ABC):
+ """Serializable base class.
+
+ This class is used to serialize objects to JSON.
+
+ It relies on the following methods and properties:
+
+ - [`is_lc_serializable`][langchain_core.load.serializable.Serializable.is_lc_serializable]: Is this class serializable?
+
+ By design, even if a class inherits from `Serializable`, it is not serializable
+ by default. This is to prevent accidental serialization of objects that should
+ not be serialized.
+ - [`get_lc_namespace`][langchain_core.load.serializable.Serializable.get_lc_namespace]: Get the namespace of the LangChain object.
+
+ During deserialization, this namespace is used to identify
+ the correct class to instantiate.
+
+ Please see the `Reviver` class in `langchain_core.load.load` for more details.
+
+ During deserialization an additional mapping is handle classes that have moved
+ or been renamed across package versions.
+
+ - [`lc_secrets`][langchain_core.load.serializable.Serializable.lc_secrets]: A map of constructor argument names to secret ids.
+ - [`lc_attributes`][langchain_core.load.serializable.Serializable.lc_attributes]: List of additional attribute names that should be included
+ as part of the serialized representation.
+ """ # noqa: E501
+
+ # Remove default BaseModel init docstring.
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ """""" # noqa: D419 # Intentional blank docstring
+ super().__init__(*args, **kwargs)
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Is this class serializable?
+
+ By design, even if a class inherits from `Serializable`, it is not serializable
+ by default. This is to prevent accidental serialization of objects that should
+ not be serialized.
+
+ Returns:
+ Whether the class is serializable. Default is `False`.
+ """
+ return False
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ The default implementation splits `cls.__module__` on `'.'`, e.g.
+ `langchain_openai.chat_models` becomes
+ `["langchain_openai", "chat_models"]`. This value is used by `lc_id` to
+ build the serialization identifier.
+
+ New partner packages should **not** override this method. The default
+ behavior is correct for any class whose module path already reflects
+ its package name. Some older packages (e.g. `langchain-openai`,
+ `langchain-anthropic`) override it to return a legacy-style namespace
+ like `["langchain", "chat_models", "openai"]`, matching the module
+ paths that existed before those integrations were split out of the
+ main `langchain` package. Those overrides are kept for
+ backwards-compatible deserialization; new packages should not copy them.
+
+ Deserialization mapping is handled separately by
+ `SERIALIZABLE_MAPPING` in `langchain_core.load.mapping`.
+
+ Returns:
+ The namespace.
+ """
+ return cls.__module__.split(".")
+
+ @property
+ def lc_secrets(self) -> dict[str, str]:
+ """A map of constructor argument names to secret ids.
+
+ For example, `{"openai_api_key": "OPENAI_API_KEY"}`
+ """
+ return {}
+
+ @property
+ def lc_attributes(self) -> dict:
+ """List of attribute names that should be included in the serialized kwargs.
+
+ These attributes must be accepted by the constructor.
+
+ Default is an empty dictionary.
+ """
+ return {}
+
+ @classmethod
+ def lc_id(cls) -> list[str]:
+ """Return a unique identifier for this class for serialization purposes.
+
+ The unique identifier is a list of strings that describes the path
+ to the object.
+
+ For example, for the class `langchain.llms.openai.OpenAI`, the id is
+ `["langchain", "llms", "openai", "OpenAI"]`.
+ """
+ # Pydantic generics change the class name. So we need to do the following
+ if (
+ "origin" in cls.__pydantic_generic_metadata__
+ and cls.__pydantic_generic_metadata__["origin"] is not None
+ ):
+ original_name = cls.__pydantic_generic_metadata__["origin"].__name__
+ else:
+ original_name = cls.__name__
+ return [*cls.get_lc_namespace(), original_name]
+
+ model_config = ConfigDict(
+ extra="ignore",
+ )
+
+ @override
+ def __repr_args__(self) -> Any:
+ return [
+ (k, v)
+ for k, v in super().__repr_args__()
+ if (k not in type(self).model_fields or try_neq_default(v, k, self))
+ ]
+
+ def to_json(self) -> SerializedConstructor | SerializedNotImplemented:
+ """Serialize the object to JSON.
+
+ Raises:
+ ValueError: If the class has deprecated attributes.
+
+ Returns:
+ A JSON serializable object or a `SerializedNotImplemented` object.
+ """
+ if not self.is_lc_serializable():
+ return self.to_json_not_implemented()
+
+ model_fields = type(self).model_fields
+ secrets = {}
+ # Get latest values for kwargs if there is an attribute with same name
+ lc_kwargs = {}
+ for k, v in self:
+ if not _is_field_useful(self, k, v):
+ continue
+ # Do nothing if the field is excluded
+ if k in model_fields and model_fields[k].exclude:
+ continue
+
+ lc_kwargs[k] = getattr(self, k, v)
+
+ # Merge the lc_secrets and lc_attributes from every class in the MRO
+ for cls in [None, *self.__class__.mro()]:
+ # Once we get to Serializable, we're done
+ if cls is Serializable:
+ break
+
+ if cls:
+ deprecated_attributes = [
+ "lc_namespace",
+ "lc_serializable",
+ ]
+
+ for attr in deprecated_attributes:
+ if hasattr(cls, attr):
+ msg = (
+ f"Class {self.__class__} has a deprecated "
+ f"attribute {attr}. Please use the corresponding "
+ f"classmethod instead."
+ )
+ raise ValueError(msg)
+
+ # Get a reference to self bound to each class in the MRO
+ this = cast("Serializable", self if cls is None else super(cls, self))
+
+ secrets.update(this.lc_secrets)
+ # Now also add the aliases for the secrets
+ # This ensures known secret aliases are hidden.
+ # Note: this does NOT hide any other extra kwargs
+ # that are not present in the fields.
+ for key in list(secrets):
+ value = secrets[key]
+ if (key in model_fields) and (
+ alias := model_fields[key].alias
+ ) is not None:
+ secrets[alias] = value
+ lc_kwargs.update(this.lc_attributes)
+
+ # include all secrets, even if not specified in kwargs
+ # as these secrets may be passed as an environment variable instead
+ for key in secrets:
+ secret_value = getattr(self, key, None) or lc_kwargs.get(key)
+ if secret_value is not None:
+ lc_kwargs.update({key: secret_value})
+
+ return {
+ "lc": 1,
+ "type": "constructor",
+ "id": self.lc_id(),
+ "kwargs": lc_kwargs
+ if not secrets
+ else _replace_secrets(lc_kwargs, secrets),
+ }
+
+ def to_json_not_implemented(self) -> SerializedNotImplemented:
+ """Serialize a "not implemented" object.
+
+ Returns:
+ `SerializedNotImplemented`.
+ """
+ return to_json_not_implemented(self)
+
+
+def _is_field_useful(inst: Serializable, key: str, value: Any) -> bool:
+ """Check if a field is useful as a constructor argument.
+
+ Args:
+ inst: The instance.
+ key: The key.
+ value: The value.
+
+ Returns:
+ Whether the field is useful. If the field is required, it is useful.
+ If the field is not required, it is useful if the value is not `None`.
+ If the field is not required and the value is `None`, it is useful if the
+ default value is different from the value.
+ """
+ field = type(inst).model_fields.get(key)
+ if not field:
+ return False
+
+ if field.is_required():
+ return True
+
+ # Handle edge case: a value cannot be converted to a boolean (e.g. a
+ # Pandas DataFrame).
+ try:
+ value_is_truthy = bool(value)
+ except Exception as _:
+ value_is_truthy = False
+
+ if value_is_truthy:
+ return True
+
+ # Value is still falsy here!
+ if field.default_factory is dict and isinstance(value, dict):
+ return False
+
+ # Value is still falsy here!
+ if field.default_factory is list and isinstance(value, list):
+ return False
+
+ value_neq_default = _try_neq_default(value, field)
+
+ # If value is falsy and does not match the default
+ return value_is_truthy or value_neq_default
+
+
+def _replace_secrets(
+ root: dict[Any, Any], secrets_map: dict[str, str]
+) -> dict[Any, Any]:
+ result = root.copy()
+ for path, secret_id in secrets_map.items():
+ [*parts, last] = path.split(".")
+ current = result
+ for part in parts:
+ if part not in current:
+ break
+ current[part] = current[part].copy()
+ current = current[part]
+ if last in current:
+ current[last] = {
+ "lc": 1,
+ "type": "secret",
+ "id": [secret_id],
+ }
+ return result
+
+
+def to_json_not_implemented(obj: object) -> SerializedNotImplemented:
+ """Serialize a "not implemented" object.
+
+ Args:
+ obj: Object to serialize.
+
+ Returns:
+ `SerializedNotImplemented`
+ """
+ id_: list[str] = []
+ try:
+ if hasattr(obj, "__name__"):
+ id_ = [*obj.__module__.split("."), obj.__name__]
+ elif hasattr(obj, "__class__"):
+ id_ = [*obj.__class__.__module__.split("."), obj.__class__.__name__]
+ except Exception:
+ logger.debug("Failed to serialize object", exc_info=True)
+
+ result: SerializedNotImplemented = {
+ "lc": 1,
+ "type": "not_implemented",
+ "id": id_,
+ "repr": None,
+ }
+ with contextlib.suppress(Exception):
+ result["repr"] = repr(obj)
+ return result
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/validators.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f470649c04b3cfcfecf2b4ad65d59440368b0ac
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/load/validators.py
@@ -0,0 +1,77 @@
+"""Init validators for deserialization security.
+
+This module contains extra validators that are called during deserialization,
+ex. to prevent security issues such as SSRF attacks.
+
+Each validator is a callable matching the `InitValidator` protocol: it takes a
+class path tuple and kwargs dict, returns `None` on success, and raises
+`ValueError` if the deserialization should be blocked.
+"""
+
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langchain_core.load.load import InitValidator
+
+
+def _bedrock_validator(class_path: tuple[str, ...], kwargs: dict[str, Any]) -> None:
+ """Constructor kwargs validator for AWS Bedrock integrations.
+
+ Blocks deserialization if `endpoint_url` or `base_url` parameters are
+ present, which could enable SSRF attacks.
+
+ Args:
+ class_path: The class path tuple being deserialized.
+ kwargs: The kwargs dict for the class constructor.
+
+ Raises:
+ ValueError: If `endpoint_url` or `base_url` parameters are present.
+ """
+ dangerous_params = ["endpoint_url", "base_url"]
+ found_params = [p for p in dangerous_params if p in kwargs]
+
+ if found_params:
+ class_name = class_path[-1] if class_path else "Unknown"
+ param_str = ", ".join(found_params)
+ msg = (
+ f"Deserialization of {class_name} with {param_str} is not allowed "
+ f"for security reasons. These parameters can enable Server-Side Request "
+ f"Forgery (SSRF) attacks by directing network requests to arbitrary "
+ f"endpoints during initialization. If you need to use a custom endpoint, "
+ f"instantiate {class_name} directly rather than deserializing it."
+ )
+ raise ValueError(msg)
+
+
+# Keys must cover both serialized IDs (SERIALIZABLE_MAPPING keys) and resolved
+# import paths (SERIALIZABLE_MAPPING values) to prevent bypass via direct paths.
+CLASS_INIT_VALIDATORS: dict[tuple[str, ...], "InitValidator"] = {
+ # Serialized (legacy) keys
+ ("langchain", "chat_models", "bedrock", "BedrockChat"): _bedrock_validator,
+ ("langchain", "chat_models", "bedrock", "ChatBedrock"): _bedrock_validator,
+ (
+ "langchain",
+ "chat_models",
+ "anthropic_bedrock",
+ "ChatAnthropicBedrock",
+ ): _bedrock_validator,
+ ("langchain_aws", "chat_models", "ChatBedrockConverse"): _bedrock_validator,
+ ("langchain", "llms", "bedrock", "Bedrock"): _bedrock_validator,
+ ("langchain", "llms", "bedrock", "BedrockLLM"): _bedrock_validator,
+ # Resolved import paths (from ALL_SERIALIZABLE_MAPPINGS values) to defend
+ # against payloads that use the target tuple directly as the "id".
+ (
+ "langchain_aws",
+ "chat_models",
+ "bedrock_converse",
+ "ChatBedrockConverse",
+ ): _bedrock_validator,
+ (
+ "langchain_aws",
+ "chat_models",
+ "anthropic",
+ "ChatAnthropicBedrock",
+ ): _bedrock_validator,
+ ("langchain_aws", "chat_models", "ChatBedrock"): _bedrock_validator,
+ ("langchain_aws", "llms", "bedrock", "BedrockLLM"): _bedrock_validator,
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..97171f56b165378342df121325dae89e5af80556
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__init__.py
@@ -0,0 +1,198 @@
+"""**Messages** are objects used in prompts and chat conversations."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+from langchain_core.utils.utils import LC_AUTO_PREFIX, LC_ID_PREFIX, ensure_id
+
+if TYPE_CHECKING:
+ from langchain_core.messages.ai import (
+ AIMessage,
+ AIMessageChunk,
+ InputTokenDetails,
+ OutputTokenDetails,
+ UsageMetadata,
+ )
+ from langchain_core.messages.base import (
+ BaseMessage,
+ BaseMessageChunk,
+ merge_content,
+ message_to_dict,
+ messages_to_dict,
+ )
+ from langchain_core.messages.block_translators.openai import (
+ convert_to_openai_data_block,
+ convert_to_openai_image_block,
+ )
+ from langchain_core.messages.chat import ChatMessage, ChatMessageChunk
+ from langchain_core.messages.content import (
+ Annotation,
+ AudioContentBlock,
+ Citation,
+ ContentBlock,
+ DataContentBlock,
+ FileContentBlock,
+ ImageContentBlock,
+ InvalidToolCall,
+ NonStandardAnnotation,
+ NonStandardContentBlock,
+ PlainTextContentBlock,
+ ReasoningContentBlock,
+ ServerToolCall,
+ ServerToolCallChunk,
+ ServerToolResult,
+ TextContentBlock,
+ VideoContentBlock,
+ is_data_content_block,
+ )
+ from langchain_core.messages.function import FunctionMessage, FunctionMessageChunk
+ from langchain_core.messages.human import HumanMessage, HumanMessageChunk
+ from langchain_core.messages.modifier import RemoveMessage
+ from langchain_core.messages.system import SystemMessage, SystemMessageChunk
+ from langchain_core.messages.tool import (
+ ToolCall,
+ ToolCallChunk,
+ ToolMessage,
+ ToolMessageChunk,
+ )
+ from langchain_core.messages.utils import (
+ AnyMessage,
+ MessageLikeRepresentation,
+ _message_from_dict,
+ convert_to_messages,
+ convert_to_openai_messages,
+ filter_messages,
+ get_buffer_string,
+ merge_message_runs,
+ message_chunk_to_message,
+ messages_from_dict,
+ trim_messages,
+ )
+
+__all__ = (
+ "LC_AUTO_PREFIX",
+ "LC_ID_PREFIX",
+ "AIMessage",
+ "AIMessageChunk",
+ "Annotation",
+ "AnyMessage",
+ "AudioContentBlock",
+ "BaseMessage",
+ "BaseMessageChunk",
+ "ChatMessage",
+ "ChatMessageChunk",
+ "Citation",
+ "ContentBlock",
+ "DataContentBlock",
+ "FileContentBlock",
+ "FunctionMessage",
+ "FunctionMessageChunk",
+ "HumanMessage",
+ "HumanMessageChunk",
+ "ImageContentBlock",
+ "InputTokenDetails",
+ "InvalidToolCall",
+ "MessageLikeRepresentation",
+ "NonStandardAnnotation",
+ "NonStandardContentBlock",
+ "OutputTokenDetails",
+ "PlainTextContentBlock",
+ "ReasoningContentBlock",
+ "RemoveMessage",
+ "ServerToolCall",
+ "ServerToolCallChunk",
+ "ServerToolResult",
+ "SystemMessage",
+ "SystemMessageChunk",
+ "TextContentBlock",
+ "ToolCall",
+ "ToolCallChunk",
+ "ToolMessage",
+ "ToolMessageChunk",
+ "UsageMetadata",
+ "VideoContentBlock",
+ "_message_from_dict",
+ "convert_to_messages",
+ "convert_to_openai_data_block",
+ "convert_to_openai_image_block",
+ "convert_to_openai_messages",
+ "ensure_id",
+ "filter_messages",
+ "get_buffer_string",
+ "is_data_content_block",
+ "merge_content",
+ "merge_message_runs",
+ "message_chunk_to_message",
+ "message_to_dict",
+ "messages_from_dict",
+ "messages_to_dict",
+ "trim_messages",
+)
+
+_dynamic_imports = {
+ "AIMessage": "ai",
+ "AIMessageChunk": "ai",
+ "Annotation": "content",
+ "AudioContentBlock": "content",
+ "BaseMessage": "base",
+ "BaseMessageChunk": "base",
+ "merge_content": "base",
+ "message_to_dict": "base",
+ "messages_to_dict": "base",
+ "Citation": "content",
+ "ContentBlock": "content",
+ "ChatMessage": "chat",
+ "ChatMessageChunk": "chat",
+ "DataContentBlock": "content",
+ "FileContentBlock": "content",
+ "FunctionMessage": "function",
+ "FunctionMessageChunk": "function",
+ "HumanMessage": "human",
+ "HumanMessageChunk": "human",
+ "NonStandardAnnotation": "content",
+ "NonStandardContentBlock": "content",
+ "OutputTokenDetails": "ai",
+ "PlainTextContentBlock": "content",
+ "ReasoningContentBlock": "content",
+ "RemoveMessage": "modifier",
+ "ServerToolCall": "content",
+ "ServerToolCallChunk": "content",
+ "ServerToolResult": "content",
+ "SystemMessage": "system",
+ "SystemMessageChunk": "system",
+ "ImageContentBlock": "content",
+ "InputTokenDetails": "ai",
+ "InvalidToolCall": "tool",
+ "TextContentBlock": "content",
+ "ToolCall": "tool",
+ "ToolCallChunk": "tool",
+ "ToolMessage": "tool",
+ "ToolMessageChunk": "tool",
+ "UsageMetadata": "ai",
+ "VideoContentBlock": "content",
+ "AnyMessage": "utils",
+ "MessageLikeRepresentation": "utils",
+ "_message_from_dict": "utils",
+ "convert_to_messages": "utils",
+ "convert_to_openai_data_block": "block_translators.openai",
+ "convert_to_openai_image_block": "block_translators.openai",
+ "convert_to_openai_messages": "utils",
+ "filter_messages": "utils",
+ "get_buffer_string": "utils",
+ "is_data_content_block": "content",
+ "merge_message_runs": "utils",
+ "message_chunk_to_message": "utils",
+ "messages_from_dict": "utils",
+ "trim_messages": "utils",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1eb5c7f08c6695e38d9ccbd3b7a8639b9f7a327c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/ai.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/ai.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..48abd57ece2fcbac37273efb123da078ca6def62
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/ai.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5387c764ec1693b187ebd8ee1beaf8ea8c5c85b7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/chat.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/chat.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b197963437a880e0eadca580a3f824a877d03b8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/chat.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/content.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/content.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..597a848fa84acf2489bfcd0bd0fcf579c37fd2f9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/content.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/function.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c947c73890c99f0f418d8c05911f7956258aace3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/function.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/human.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/human.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aebf272144652667bdd9f2ac32869f345e62c1af
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/human.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/modifier.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/modifier.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ee566c6c0bcaae4266dd323450992f2a7e8598f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/modifier.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/system.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/system.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b784258974ae438126f6979c76a1f6b5322f459
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/system.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/tool.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/tool.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e18bb40d0842fc55f568c4774b228ebd59d41627
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/tool.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..998a870876a69e35754ca34aa034be2fc5106690
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/__pycache__/utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/ai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/ai.py
new file mode 100644
index 0000000000000000000000000000000000000000..92bac634d69145166c5e3b1b3f2f61e4ce007aee
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/ai.py
@@ -0,0 +1,840 @@
+"""AI message."""
+
+import itertools
+import json
+import logging
+import operator
+from collections.abc import Sequence
+from typing import Any, Literal, cast, overload
+
+from pydantic import Field, model_validator
+from typing_extensions import NotRequired, Self, TypedDict, override
+
+from langchain_core.messages import content as types
+from langchain_core.messages.base import (
+ BaseMessage,
+ BaseMessageChunk,
+ _extract_reasoning_from_additional_kwargs,
+ merge_content,
+)
+from langchain_core.messages.content import InvalidToolCall
+from langchain_core.messages.tool import (
+ ToolCall,
+ ToolCallChunk,
+ default_tool_chunk_parser,
+ default_tool_parser,
+)
+from langchain_core.messages.tool import invalid_tool_call as create_invalid_tool_call
+from langchain_core.messages.tool import tool_call as create_tool_call
+from langchain_core.messages.tool import tool_call_chunk as create_tool_call_chunk
+from langchain_core.utils._merge import merge_dicts, merge_lists
+from langchain_core.utils.json import parse_partial_json
+from langchain_core.utils.usage import _dict_int_op
+from langchain_core.utils.utils import LC_AUTO_PREFIX, LC_ID_PREFIX
+
+logger = logging.getLogger(__name__)
+
+
+class InputTokenDetails(TypedDict, total=False):
+ """Breakdown of input token counts.
+
+ Does *not* need to sum to full input token count. Does *not* need to have all keys.
+
+ Example:
+ ```python
+ {
+ "audio": 10,
+ "cache_creation": 200,
+ "cache_read": 100,
+ }
+ ```
+
+ May also hold extra provider-specific keys.
+
+ !!! version-added "Added in `langchain-core` 0.3.9"
+ """
+
+ audio: int
+ """Audio input tokens."""
+
+ cache_creation: int
+ """Input tokens that were cached and there was a cache miss.
+
+ Since there was a cache miss, the cache was created from these tokens.
+ """
+
+ cache_read: int
+ """Input tokens that were cached and there was a cache hit.
+
+ Since there was a cache hit, the tokens were read from the cache. More precisely,
+ the model state given these tokens was read from the cache.
+ """
+
+
+class OutputTokenDetails(TypedDict, total=False):
+ """Breakdown of output token counts.
+
+ Does *not* need to sum to full output token count. Does *not* need to have all keys.
+
+ Example:
+ ```python
+ {
+ "audio": 10,
+ "reasoning": 200,
+ }
+ ```
+
+ May also hold extra provider-specific keys.
+
+ !!! version-added "Added in `langchain-core` 0.3.9"
+
+ """
+
+ audio: int
+ """Audio output tokens."""
+
+ reasoning: int
+ """Reasoning output tokens.
+
+ Tokens generated by the model in a chain of thought process (i.e. by OpenAI's o1
+ models) that are not returned as part of model output.
+ """
+
+
+class UsageMetadata(TypedDict):
+ """Usage metadata for a message, such as token counts.
+
+ This is a standard representation of token usage that is consistent across models.
+
+ Example:
+ ```python
+ {
+ "input_tokens": 350,
+ "output_tokens": 240,
+ "total_tokens": 590,
+ "input_token_details": {
+ "audio": 10,
+ "cache_creation": 200,
+ "cache_read": 100,
+ },
+ "output_token_details": {
+ "audio": 10,
+ "reasoning": 200,
+ },
+ }
+ ```
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.9"
+
+ Added `input_token_details` and `output_token_details`.
+
+ !!! note "LangSmith SDK"
+
+ The LangSmith SDK also has a `UsageMetadata` class. While the two share fields,
+ LangSmith's `UsageMetadata` has additional fields to capture cost information
+ used by the LangSmith platform.
+ """
+
+ input_tokens: int
+ """Count of input (or prompt) tokens. Sum of all input token types."""
+
+ output_tokens: int
+ """Count of output (or completion) tokens. Sum of all output token types."""
+
+ total_tokens: int
+ """Total token count. Sum of `input_tokens` + `output_tokens`."""
+
+ input_token_details: NotRequired[InputTokenDetails]
+ """Breakdown of input token counts.
+
+ Does *not* need to sum to full input token count. Does *not* need to have all keys.
+ """
+
+ output_token_details: NotRequired[OutputTokenDetails]
+ """Breakdown of output token counts.
+
+ Does *not* need to sum to full output token count. Does *not* need to have all keys.
+ """
+
+
+class AIMessage(BaseMessage):
+ """Message from an AI.
+
+ An `AIMessage` is returned from a chat model as a response to a prompt.
+
+ This message represents the output of the model and consists of both
+ the raw output as returned by the model and standardized fields
+ (e.g., tool calls, usage metadata) added by the LangChain framework.
+ """
+
+ tool_calls: list[ToolCall] = Field(default_factory=list)
+ """If present, tool calls associated with the message."""
+
+ invalid_tool_calls: list[InvalidToolCall] = Field(default_factory=list)
+ """If present, tool calls with parsing errors associated with the message."""
+
+ usage_metadata: UsageMetadata | None = None
+ """If present, usage metadata for a message, such as token counts.
+
+ This is a standard representation of token usage that is consistent across models.
+ """
+
+ type: Literal["ai"] = "ai"
+ """The type of the message (used for deserialization)."""
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict],
+ **kwargs: Any,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None: ...
+
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize an `AIMessage`.
+
+ Specify `content` as positional arg or `content_blocks` for typing.
+
+ Args:
+ content: The content of the message.
+ content_blocks: Typed standard content.
+ **kwargs: Additional arguments to pass to the parent class.
+ """
+ if content_blocks is not None:
+ # If there are tool calls in content_blocks, but not in tool_calls, add them
+ content_tool_calls = [
+ block for block in content_blocks if block.get("type") == "tool_call"
+ ]
+ if content_tool_calls and "tool_calls" not in kwargs:
+ kwargs["tool_calls"] = content_tool_calls
+
+ super().__init__(
+ content=cast("str | list[str | dict]", content_blocks),
+ **kwargs,
+ )
+ else:
+ super().__init__(content=content, **kwargs)
+
+ @property
+ def lc_attributes(self) -> dict:
+ """Attributes to be serialized.
+
+ Includes all attributes, even if they are derived from other initialization
+ arguments.
+ """
+ return {
+ "tool_calls": self.tool_calls,
+ "invalid_tool_calls": self.invalid_tool_calls,
+ }
+
+ @property
+ def content_blocks(self) -> list[types.ContentBlock]:
+ """Return standard, typed `ContentBlock` dicts from the message.
+
+ If the message has a known model provider, use the provider-specific translator
+ first before falling back to best-effort parsing. For details, see the property
+ on `BaseMessage`.
+ """
+ if self.response_metadata.get("output_version") == "v1":
+ return cast("list[types.ContentBlock]", self.content)
+
+ model_provider = self.response_metadata.get("model_provider")
+ if model_provider:
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ get_translator,
+ )
+
+ translator = get_translator(model_provider)
+ if translator:
+ try:
+ return translator["translate_content"](self)
+ except NotImplementedError:
+ pass
+
+ # Otherwise, use best-effort parsing
+ blocks = super().content_blocks
+
+ if self.tool_calls:
+ # Add from tool_calls if missing from content
+ content_tool_call_ids = {
+ block.get("id")
+ for block in self.content
+ if isinstance(block, dict) and block.get("type") == "tool_call"
+ }
+ for tool_call in self.tool_calls:
+ if (id_ := tool_call.get("id")) and id_ not in content_tool_call_ids:
+ tool_call_block: types.ToolCall = {
+ "type": "tool_call",
+ "id": id_,
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ }
+ if "index" in tool_call:
+ tool_call_block["index"] = tool_call["index"] # type: ignore[typeddict-item]
+ if "extras" in tool_call:
+ tool_call_block["extras"] = tool_call["extras"] # type: ignore[typeddict-item]
+ blocks.append(tool_call_block)
+
+ # Best-effort reasoning extraction from additional_kwargs
+ # Only add reasoning if not already present
+ # Insert before all other blocks to keep reasoning at the start
+ has_reasoning = any(block.get("type") == "reasoning" for block in blocks)
+ if not has_reasoning and (
+ reasoning_block := _extract_reasoning_from_additional_kwargs(self)
+ ):
+ blocks.insert(0, reasoning_block)
+
+ return blocks
+
+ # TODO: remove this logic if possible, reducing breaking nature of changes
+ @model_validator(mode="before")
+ @classmethod
+ def _backwards_compat_tool_calls(cls, values: dict) -> Any:
+ check_additional_kwargs = not any(
+ values.get(k)
+ for k in ("tool_calls", "invalid_tool_calls", "tool_call_chunks")
+ )
+ if check_additional_kwargs and (
+ raw_tool_calls := values.get("additional_kwargs", {}).get("tool_calls")
+ ):
+ try:
+ if issubclass(cls, AIMessageChunk):
+ values["tool_call_chunks"] = default_tool_chunk_parser(
+ raw_tool_calls
+ )
+ else:
+ parsed_tool_calls, parsed_invalid_tool_calls = default_tool_parser(
+ raw_tool_calls
+ )
+ values["tool_calls"] = parsed_tool_calls
+ values["invalid_tool_calls"] = parsed_invalid_tool_calls
+ except Exception:
+ logger.debug("Failed to parse tool calls", exc_info=True)
+
+ # Ensure "type" is properly set on all tool call-like dicts.
+ if tool_calls := values.get("tool_calls"):
+ values["tool_calls"] = [
+ create_tool_call(
+ **{k: v for k, v in tc.items() if k not in {"type", "extras"}}
+ )
+ for tc in tool_calls
+ ]
+ if invalid_tool_calls := values.get("invalid_tool_calls"):
+ values["invalid_tool_calls"] = [
+ create_invalid_tool_call(**{k: v for k, v in tc.items() if k != "type"})
+ for tc in invalid_tool_calls
+ ]
+
+ if tool_call_chunks := values.get("tool_call_chunks"):
+ values["tool_call_chunks"] = [
+ create_tool_call_chunk(**{k: v for k, v in tc.items() if k != "type"})
+ for tc in tool_call_chunks
+ ]
+
+ return values
+
+ @override
+ def pretty_repr(self, html: bool = False) -> str:
+ """Return a pretty representation of the message for display.
+
+ Args:
+ html: Whether to return an HTML-formatted string.
+
+ Returns:
+ A pretty representation of the message.
+
+ Example:
+ ```python
+ from langchain_core.messages import AIMessage
+
+ msg = AIMessage(
+ content="Let me check the weather.",
+ tool_calls=[
+ {"name": "get_weather", "args": {"city": "Paris"}, "id": "1"}
+ ],
+ )
+ ```
+
+ Results in:
+ ```python
+ >>> print(msg.pretty_repr())
+ ================================== Ai Message ==================================
+
+ Let me check the weather.
+ Tool Calls:
+ get_weather (1)
+ Call ID: 1
+ Args:
+ city: Paris
+ ```
+ """ # noqa: E501
+ base = super().pretty_repr(html=html)
+ lines = []
+
+ def _format_tool_args(tc: ToolCall | InvalidToolCall) -> list[str]:
+ lines = [
+ f" {tc.get('name', 'Tool')} ({tc.get('id')})",
+ f" Call ID: {tc.get('id')}",
+ ]
+ if tc.get("error"):
+ lines.append(f" Error: {tc.get('error')}")
+ lines.append(" Args:")
+ args = tc.get("args")
+ if isinstance(args, str):
+ lines.append(f" {args}")
+ elif isinstance(args, dict):
+ for arg, value in args.items():
+ lines.append(f" {arg}: {value}")
+ return lines
+
+ if self.tool_calls:
+ lines.append("Tool Calls:")
+ for tc in self.tool_calls:
+ lines.extend(_format_tool_args(tc))
+ if self.invalid_tool_calls:
+ lines.append("Invalid Tool Calls:")
+ for itc in self.invalid_tool_calls:
+ lines.extend(_format_tool_args(itc))
+ return (base.strip() + "\n" + "\n".join(lines)).strip()
+
+
+class AIMessageChunk(AIMessage, BaseMessageChunk):
+ """Message chunk from an AI (yielded when streaming)."""
+
+ # Ignoring mypy re-assignment here since we're overriding the value
+ # to make sure that the chunk variant can be discriminated from the
+ # non-chunk variant.
+ type: Literal["AIMessageChunk"] = "AIMessageChunk" # type: ignore[assignment]
+ """The type of the message (used for deserialization)."""
+
+ tool_call_chunks: list[ToolCallChunk] = Field(default_factory=list)
+ """If provided, tool call chunks associated with the message."""
+
+ chunk_position: Literal["last"] | None = None
+ """Optional span represented by an aggregated `AIMessageChunk`.
+
+ If a chunk with `chunk_position="last"` is aggregated into a stream,
+ `tool_call_chunks` in message content will be parsed into `tool_calls`.
+ """
+
+ @property
+ @override
+ def lc_attributes(self) -> dict:
+ return {
+ "tool_calls": self.tool_calls,
+ "invalid_tool_calls": self.invalid_tool_calls,
+ }
+
+ @property
+ def content_blocks(self) -> list[types.ContentBlock]:
+ """Return standard, typed `ContentBlock` dicts from the message."""
+ if self.response_metadata.get("output_version") == "v1":
+ return cast("list[types.ContentBlock]", self.content)
+
+ model_provider = self.response_metadata.get("model_provider")
+ if model_provider:
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ get_translator,
+ )
+
+ translator = get_translator(model_provider)
+ if translator:
+ try:
+ return translator["translate_content_chunk"](self)
+ except NotImplementedError:
+ pass
+
+ # Otherwise, use best-effort parsing
+ blocks = super().content_blocks
+
+ if (
+ self.tool_call_chunks
+ and not self.content
+ and self.chunk_position != "last" # keep tool_calls if aggregated
+ ):
+ blocks = [
+ block
+ for block in blocks
+ if block["type"] not in {"tool_call", "invalid_tool_call"}
+ ]
+ for tool_call_chunk in self.tool_call_chunks:
+ tc: types.ToolCallChunk = {
+ "type": "tool_call_chunk",
+ "id": tool_call_chunk.get("id"),
+ "name": tool_call_chunk.get("name"),
+ "args": tool_call_chunk.get("args"),
+ }
+ if (idx := tool_call_chunk.get("index")) is not None:
+ tc["index"] = idx
+ blocks.append(tc)
+
+ # Best-effort reasoning extraction from additional_kwargs
+ # Only add reasoning if not already present
+ # Insert before all other blocks to keep reasoning at the start
+ has_reasoning = any(block.get("type") == "reasoning" for block in blocks)
+ if not has_reasoning and (
+ reasoning_block := _extract_reasoning_from_additional_kwargs(self)
+ ):
+ blocks.insert(0, reasoning_block)
+
+ return blocks
+
+ @model_validator(mode="after")
+ def init_tool_calls(self) -> Self:
+ """Initialize tool calls from tool call chunks.
+
+ Returns:
+ The values with tool calls initialized.
+
+ Raises:
+ ValueError: If the tool call chunks are malformed.
+ """
+ if not self.tool_call_chunks:
+ if self.tool_calls:
+ self.tool_call_chunks = [
+ create_tool_call_chunk(
+ name=tc["name"],
+ args=json.dumps(tc["args"]),
+ id=tc["id"],
+ index=None,
+ )
+ for tc in self.tool_calls
+ ]
+ if self.invalid_tool_calls:
+ tool_call_chunks = self.tool_call_chunks
+ tool_call_chunks.extend(
+ [
+ create_tool_call_chunk(
+ name=tc["name"], args=tc["args"], id=tc["id"], index=None
+ )
+ for tc in self.invalid_tool_calls
+ ]
+ )
+ self.tool_call_chunks = tool_call_chunks
+
+ return self
+ tool_calls = []
+ invalid_tool_calls = []
+
+ def add_chunk_to_invalid_tool_calls(chunk: ToolCallChunk) -> None:
+ invalid_tool_calls.append(
+ create_invalid_tool_call(
+ name=chunk["name"],
+ args=chunk["args"],
+ id=chunk["id"],
+ error=None,
+ )
+ )
+
+ for chunk in self.tool_call_chunks:
+ try:
+ args_ = parse_partial_json(chunk["args"]) if chunk["args"] else {}
+ if isinstance(args_, dict):
+ tool_calls.append(
+ create_tool_call(
+ name=chunk["name"] or "",
+ args=args_,
+ id=chunk["id"],
+ )
+ )
+ else:
+ add_chunk_to_invalid_tool_calls(chunk)
+ except Exception:
+ add_chunk_to_invalid_tool_calls(chunk)
+ self.tool_calls = tool_calls
+ self.invalid_tool_calls = invalid_tool_calls
+
+ if (
+ self.chunk_position == "last"
+ and self.tool_call_chunks
+ and self.response_metadata.get("output_version") == "v1"
+ and isinstance(self.content, list)
+ ):
+ id_to_tc: dict[str, types.ToolCall] = {
+ cast("str", tc.get("id")): {
+ "type": "tool_call",
+ "name": tc["name"],
+ "args": tc["args"],
+ "id": tc.get("id"),
+ }
+ for tc in self.tool_calls
+ if "id" in tc
+ }
+ for idx, block in enumerate(self.content):
+ if (
+ isinstance(block, dict)
+ and block.get("type") == "tool_call_chunk"
+ and (call_id := block.get("id"))
+ and call_id in id_to_tc
+ ):
+ self.content[idx] = cast("dict[str, Any]", id_to_tc[call_id])
+ if "extras" in block:
+ # mypy does not account for instance check for dict above
+ self.content[idx]["extras"] = block["extras"] # type: ignore[index]
+
+ return self
+
+ @model_validator(mode="after")
+ def init_server_tool_calls(self) -> Self:
+ """Initialize server tool calls.
+
+ Parse `server_tool_call_chunks` from
+ [`ServerToolCallChunk`][langchain.messages.ServerToolCallChunk] objects.
+ """
+ if (
+ self.chunk_position == "last"
+ and self.response_metadata.get("output_version") == "v1"
+ and isinstance(self.content, list)
+ ):
+ for idx, block in enumerate(self.content):
+ if (
+ isinstance(block, dict)
+ and block.get("type")
+ in {"server_tool_call", "server_tool_call_chunk"}
+ and (args_str := block.get("args"))
+ and isinstance(args_str, str)
+ ):
+ try:
+ args = json.loads(args_str)
+ if isinstance(args, dict):
+ self.content[idx]["type"] = "server_tool_call" # type: ignore[index]
+ self.content[idx]["args"] = args # type: ignore[index]
+ except json.JSONDecodeError:
+ pass
+ return self
+
+ @overload # type: ignore[override] # summing BaseMessages gives ChatPromptTemplate
+ def __add__(self, other: "AIMessageChunk") -> "AIMessageChunk": ...
+
+ @overload
+ def __add__(self, other: Sequence["AIMessageChunk"]) -> "AIMessageChunk": ...
+
+ @overload
+ def __add__(self, other: Any) -> BaseMessageChunk: ...
+
+ @override
+ def __add__(self, other: Any) -> BaseMessageChunk:
+ if isinstance(other, AIMessageChunk):
+ return add_ai_message_chunks(self, other)
+ if isinstance(other, (list, tuple)) and all(
+ isinstance(o, AIMessageChunk) for o in other
+ ):
+ return add_ai_message_chunks(self, *other)
+ return super().__add__(other)
+
+
+def add_ai_message_chunks(
+ left: AIMessageChunk, *others: AIMessageChunk
+) -> AIMessageChunk:
+ """Add multiple `AIMessageChunk`s together.
+
+ Args:
+ left: The first `AIMessageChunk`.
+ *others: Other `AIMessageChunk`s to add.
+
+ Returns:
+ The resulting `AIMessageChunk`.
+
+ """
+ content = merge_content(left.content, *(o.content for o in others))
+ additional_kwargs = merge_dicts(
+ left.additional_kwargs, *(o.additional_kwargs for o in others)
+ )
+ response_metadata = merge_dicts(
+ left.response_metadata, *(o.response_metadata for o in others)
+ )
+
+ # Merge tool call chunks
+ if raw_tool_calls := merge_lists(
+ left.tool_call_chunks, *(o.tool_call_chunks for o in others)
+ ):
+ tool_call_chunks = [
+ create_tool_call_chunk(
+ name=rtc.get("name"),
+ args=rtc.get("args"),
+ index=rtc.get("index"),
+ id=rtc.get("id"),
+ )
+ for rtc in raw_tool_calls
+ ]
+ else:
+ tool_call_chunks = []
+
+ # Token usage
+ if left.usage_metadata or any(o.usage_metadata is not None for o in others):
+ usage_metadata: UsageMetadata | None = left.usage_metadata
+ for other in others:
+ usage_metadata = add_usage(usage_metadata, other.usage_metadata)
+ else:
+ usage_metadata = None
+
+ # Ranks are defined by the order of preference. Higher is better:
+ # 2. Provider-assigned IDs (non lc_* and non lc_run-*)
+ # 1. lc_run-* IDs
+ # 0. lc_* and other remaining IDs
+ best_rank = -1
+ chunk_id = None
+ candidates = itertools.chain([left.id], (o.id for o in others))
+
+ for id_ in candidates:
+ if not id_:
+ continue
+
+ if not id_.startswith(LC_ID_PREFIX) and not id_.startswith(LC_AUTO_PREFIX):
+ chunk_id = id_
+ # Highest rank, return instantly
+ break
+
+ rank = 1 if id_.startswith(LC_ID_PREFIX) else 0
+
+ if rank > best_rank:
+ best_rank = rank
+ chunk_id = id_
+
+ chunk_position: Literal["last"] | None = (
+ "last" if any(x.chunk_position == "last" for x in [left, *others]) else None
+ )
+
+ return left.__class__(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_call_chunks=tool_call_chunks,
+ response_metadata=response_metadata,
+ usage_metadata=usage_metadata,
+ id=chunk_id,
+ chunk_position=chunk_position,
+ )
+
+
+def add_usage(left: UsageMetadata | None, right: UsageMetadata | None) -> UsageMetadata:
+ """Recursively add two UsageMetadata objects.
+
+ Example:
+ ```python
+ from langchain_core.messages.ai import add_usage
+
+ left = UsageMetadata(
+ input_tokens=5,
+ output_tokens=0,
+ total_tokens=5,
+ input_token_details=InputTokenDetails(cache_read=3),
+ )
+ right = UsageMetadata(
+ input_tokens=0,
+ output_tokens=10,
+ total_tokens=10,
+ output_token_details=OutputTokenDetails(reasoning=4),
+ )
+
+ add_usage(left, right)
+ ```
+
+ results in
+
+ ```python
+ UsageMetadata(
+ input_tokens=5,
+ output_tokens=10,
+ total_tokens=15,
+ input_token_details=InputTokenDetails(cache_read=3),
+ output_token_details=OutputTokenDetails(reasoning=4),
+ )
+ ```
+ Args:
+ left: The first `UsageMetadata` object.
+ right: The second `UsageMetadata` object.
+
+ Returns:
+ The sum of the two `UsageMetadata` objects.
+
+ """
+ if not (left or right):
+ return UsageMetadata(input_tokens=0, output_tokens=0, total_tokens=0)
+ if not (left and right):
+ return cast("UsageMetadata", left or right)
+
+ return UsageMetadata(
+ **cast(
+ "UsageMetadata",
+ _dict_int_op(
+ cast("dict", left),
+ cast("dict", right),
+ operator.add,
+ ),
+ )
+ )
+
+
+def subtract_usage(
+ left: UsageMetadata | None, right: UsageMetadata | None
+) -> UsageMetadata:
+ """Recursively subtract two `UsageMetadata` objects.
+
+ Token counts cannot be negative so the actual operation is `max(left - right, 0)`.
+
+ Example:
+ ```python
+ from langchain_core.messages.ai import subtract_usage
+
+ left = UsageMetadata(
+ input_tokens=5,
+ output_tokens=10,
+ total_tokens=15,
+ input_token_details=InputTokenDetails(cache_read=4),
+ )
+ right = UsageMetadata(
+ input_tokens=3,
+ output_tokens=8,
+ total_tokens=11,
+ output_token_details=OutputTokenDetails(reasoning=4),
+ )
+
+ subtract_usage(left, right)
+ ```
+
+ results in
+
+ ```python
+ UsageMetadata(
+ input_tokens=2,
+ output_tokens=2,
+ total_tokens=4,
+ input_token_details=InputTokenDetails(cache_read=4),
+ output_token_details=OutputTokenDetails(reasoning=0),
+ )
+ ```
+ Args:
+ left: The first `UsageMetadata` object.
+ right: The second `UsageMetadata` object.
+
+ Returns:
+ The resulting `UsageMetadata` after subtraction.
+
+ """
+ if not (left or right):
+ return UsageMetadata(input_tokens=0, output_tokens=0, total_tokens=0)
+ if not (left and right):
+ return cast("UsageMetadata", left or right)
+
+ return UsageMetadata(
+ **cast(
+ "UsageMetadata",
+ _dict_int_op(
+ cast("dict", left),
+ cast("dict", right),
+ (lambda le, ri: max(le - ri, 0)),
+ ),
+ )
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b0e998c70fdb9a94d91cd0f73a9165e53ca0f19
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/base.py
@@ -0,0 +1,518 @@
+"""Base message."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, cast, overload
+
+from pydantic import ConfigDict, Field
+
+from langchain_core._api.deprecation import warn_deprecated
+from langchain_core.load.serializable import Serializable
+from langchain_core.messages import content as types
+from langchain_core.utils import get_bolded_text
+from langchain_core.utils._merge import merge_dicts, merge_lists
+from langchain_core.utils.interactive_env import is_interactive_env
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from typing_extensions import Self
+
+ from langchain_core.prompts.chat import ChatPromptTemplate
+
+
+def _extract_reasoning_from_additional_kwargs(
+ message: BaseMessage,
+) -> types.ReasoningContentBlock | None:
+ """Extract `reasoning_content` from `additional_kwargs`.
+
+ Handles reasoning content stored in various formats:
+ - `additional_kwargs["reasoning_content"]` (string) - Ollama, DeepSeek, XAI, Groq
+
+ Args:
+ message: The message to extract reasoning from.
+
+ Returns:
+ A `ReasoningContentBlock` if reasoning content is found, None otherwise.
+ """
+ additional_kwargs = getattr(message, "additional_kwargs", {})
+
+ reasoning_content = additional_kwargs.get("reasoning_content")
+ if reasoning_content is not None and isinstance(reasoning_content, str):
+ return {"type": "reasoning", "reasoning": reasoning_content}
+
+ return None
+
+
+class TextAccessor(str):
+ """String-like object that supports both property and method access patterns.
+
+ Exists to maintain backward compatibility while transitioning from method-based to
+ property-based text access in message objects. In LangChain Self:
+ """Create new TextAccessor instance."""
+ return str.__new__(cls, value)
+
+ def __call__(self) -> str:
+ """Enable method-style text access for backward compatibility.
+
+ This method exists solely to support legacy code that calls `.text()`
+ as a method. New code should use property access (`.text`) instead.
+
+ !!! deprecated
+ As of `langchain-core` 1.0.0, calling `.text()` as a method is deprecated.
+ Use `.text` as a property instead. This method will be removed in 2.0.0.
+
+ Returns:
+ The string content, identical to property access.
+
+ """
+ warn_deprecated(
+ since="1.0.0",
+ message=(
+ "Calling .text() as a method is deprecated. "
+ "Use .text as a property instead (e.g., message.text)."
+ ),
+ removal="2.0.0",
+ )
+ return str(self)
+
+
+class BaseMessage(Serializable):
+ """Base abstract message class.
+
+ Messages are the inputs and outputs of a chat model.
+
+ Examples include [`HumanMessage`][langchain.messages.HumanMessage],
+ [`AIMessage`][langchain.messages.AIMessage], and
+ [`SystemMessage`][langchain.messages.SystemMessage].
+ """
+
+ content: str | list[str | dict]
+ """The contents of the message."""
+
+ additional_kwargs: dict = Field(default_factory=dict)
+ """Reserved for additional payload data associated with the message.
+
+ For example, for a message from an AI, this could include tool calls as
+ encoded by the model provider.
+
+ """
+
+ response_metadata: dict = Field(default_factory=dict)
+ """Examples: response headers, logprobs, token counts, model name."""
+
+ type: str
+ """The type of the message. Must be a string that is unique to the message type.
+
+ The purpose of this field is to allow for easy identification of the message type
+ when deserializing messages.
+
+ """
+
+ name: str | None = None
+ """An optional name for the message.
+
+ This can be used to provide a human-readable name for the message.
+
+ Usage of this field is optional, and whether it's used or not is up to the
+ model implementation.
+
+ """
+
+ id: str | None = Field(default=None, coerce_numbers_to_str=True)
+ """An optional unique identifier for the message.
+
+ This should ideally be provided by the provider/model which created the message.
+
+ """
+
+ model_config = ConfigDict(
+ extra="allow",
+ )
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict],
+ **kwargs: Any,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None: ...
+
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize a `BaseMessage`.
+
+ Specify `content` as positional arg or `content_blocks` for typing.
+
+ Args:
+ content: The contents of the message.
+ content_blocks: Typed standard content.
+ **kwargs: Additional arguments to pass to the parent class.
+ """
+ if content_blocks is not None:
+ super().__init__(content=content_blocks, **kwargs)
+ else:
+ super().__init__(content=content, **kwargs)
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """`BaseMessage` is serializable.
+
+ Returns:
+ True
+ """
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "messages"]`
+ """
+ return ["langchain", "schema", "messages"]
+
+ @property
+ def content_blocks(self) -> list[types.ContentBlock]:
+ r"""Load content blocks from the message content.
+
+ !!! version-added "Added in `langchain-core` 1.0.0"
+
+ """
+ # Needed here to avoid circular import, as these classes import BaseMessages
+ from langchain_core.messages.block_translators.anthropic import ( # noqa: PLC0415
+ _convert_to_v1_from_anthropic_input,
+ )
+ from langchain_core.messages.block_translators.bedrock_converse import ( # noqa: PLC0415
+ _convert_to_v1_from_converse_input,
+ )
+ from langchain_core.messages.block_translators.google_genai import ( # noqa: PLC0415
+ _convert_to_v1_from_genai_input,
+ )
+ from langchain_core.messages.block_translators.langchain_v0 import ( # noqa: PLC0415
+ _convert_v0_multimodal_input_to_v1,
+ )
+ from langchain_core.messages.block_translators.openai import ( # noqa: PLC0415
+ _convert_to_v1_from_chat_completions_input,
+ )
+
+ blocks: list[types.ContentBlock] = []
+ content = (
+ # Transpose string content to list, otherwise assumed to be list
+ [self.content]
+ if isinstance(self.content, str) and self.content
+ else self.content
+ )
+ for item in content:
+ if isinstance(item, str):
+ # Plain string content is treated as a text block
+ blocks.append({"type": "text", "text": item})
+ elif isinstance(item, dict):
+ item_type = item.get("type")
+ if item_type not in types.KNOWN_BLOCK_TYPES:
+ # Handle all provider-specific or None type blocks as non-standard -
+ # we'll come back to these later
+ blocks.append({"type": "non_standard", "value": item})
+ else:
+ # Guard against v0 blocks that share the same `type` keys
+ if "source_type" in item:
+ blocks.append({"type": "non_standard", "value": item})
+ continue
+
+ # This can't be a v0 block (since they require `source_type`),
+ # so it's a known v1 block type
+ blocks.append(cast("types.ContentBlock", item))
+
+ # Subsequent passes: attempt to unpack non-standard blocks.
+ # This is the last stop - if we can't parse it here, it is left as non-standard
+ for parsing_step in [
+ _convert_v0_multimodal_input_to_v1,
+ _convert_to_v1_from_chat_completions_input,
+ _convert_to_v1_from_anthropic_input,
+ _convert_to_v1_from_genai_input,
+ _convert_to_v1_from_converse_input,
+ ]:
+ blocks = parsing_step(blocks)
+ return blocks
+
+ @property
+ def text(self) -> TextAccessor:
+ """Get the text content of the message as a string.
+
+ Can be used as both property (`message.text`) and method (`message.text()`).
+
+ Handles both string and list content types (e.g. for content blocks). Only
+ extracts blocks with `type: 'text'`; other block types are ignored.
+
+ !!! deprecated
+ As of `langchain-core` 1.0.0, calling `.text()` as a method is deprecated.
+ Use `.text` as a property instead. This method will be removed in 2.0.0.
+
+ Returns:
+ The text content of the message.
+
+ """
+ if isinstance(self.content, str):
+ text_value = self.content
+ else:
+ # Must be a list
+ blocks = [
+ block
+ for block in self.content
+ if isinstance(block, str)
+ or (block.get("type") == "text" and isinstance(block.get("text"), str))
+ ]
+ text_value = "".join(
+ block if isinstance(block, str) else block["text"] for block in blocks
+ )
+ return TextAccessor(text_value)
+
+ def __add__(self, other: Any) -> ChatPromptTemplate:
+ """Concatenate this message with another message.
+
+ Args:
+ other: Another message to concatenate with this one.
+
+ Returns:
+ A ChatPromptTemplate containing both messages.
+ """
+ # Import locally to prevent circular imports.
+ from langchain_core.prompts.chat import ChatPromptTemplate # noqa: PLC0415
+
+ prompt = ChatPromptTemplate(messages=[self])
+ return prompt.__add__(other)
+
+ def pretty_repr(
+ self,
+ html: bool = False, # noqa: FBT001,FBT002
+ ) -> str:
+ """Get a pretty representation of the message.
+
+ Args:
+ html: Whether to format the message as HTML. If `True`, the message will be
+ formatted with HTML tags.
+
+ Returns:
+ A pretty representation of the message.
+
+ Example:
+ ```python
+ from langchain_core.messages import HumanMessage
+
+ msg = HumanMessage(content="What is the capital of France?")
+ print(msg.pretty_repr())
+ ```
+
+ Results in:
+
+ ```txt
+ ================================ Human Message =================================
+
+ What is the capital of France?
+ ```
+ """ # noqa: E501
+ title = get_msg_title_repr(self.type.title() + " Message", bold=html)
+ # TODO: handle non-string content.
+ if self.name is not None:
+ title += f"\nName: {self.name}"
+ return f"{title}\n\n{self.content}"
+
+ def pretty_print(self) -> None:
+ """Print a pretty representation of the message.
+
+ Example:
+ ```python
+ from langchain_core.messages import AIMessage
+
+ msg = AIMessage(content="The capital of France is Paris.")
+ msg.pretty_print()
+ ```
+
+ Results in:
+
+ ```txt
+ ================================== Ai Message ==================================
+
+ The capital of France is Paris.
+ ```
+ """ # noqa: E501
+ print(self.pretty_repr(html=is_interactive_env())) # noqa: T201
+
+
+def merge_content(
+ first_content: str | list[str | dict],
+ *contents: str | list[str | dict],
+) -> str | list[str | dict]:
+ """Merge multiple message contents.
+
+ Args:
+ first_content: The first `content`. Can be a string or a list.
+ contents: The other `content`s. Can be a string or a list.
+
+ Returns:
+ The merged content.
+
+ """
+ merged: str | list[str | dict]
+ merged = "" if first_content is None else first_content
+
+ for content in contents:
+ # If current is a string
+ if isinstance(merged, str):
+ # If the next chunk is also a string, then merge them naively
+ if isinstance(content, str):
+ merged += content
+ # If the next chunk is a list, add the current to the start of the list
+ else:
+ merged = [merged, *content]
+ elif isinstance(content, list):
+ # If both are lists
+ merged = merge_lists(cast("list", merged), content) # type: ignore[assignment]
+ # If the first content is a list, and the second content is a string
+ # If the last element of the first content is a string
+ # Add the second content to the last element
+ elif merged and isinstance(merged[-1], str):
+ merged[-1] += content
+ # If second content is an empty string, treat as a no-op
+ elif content == "":
+ pass
+ # Otherwise, add the second content as a new element of the list
+ elif merged:
+ merged.append(content)
+ return merged
+
+
+class BaseMessageChunk(BaseMessage):
+ """Message chunk, which can be concatenated with other Message chunks."""
+
+ def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
+ """Message chunks support concatenation with other message chunks.
+
+ This functionality is useful to combine message chunks yielded from
+ a streaming model into a complete message.
+
+ Args:
+ other: Another message chunk to concatenate with this one.
+
+ Returns:
+ A new message chunk that is the concatenation of this message chunk
+ and the other message chunk.
+
+ Raises:
+ TypeError: If the other object is not a message chunk.
+
+ Example:
+ ```txt
+ AIMessageChunk(content="Hello", ...)
+ + AIMessageChunk(content=" World", ...)
+ = AIMessageChunk(content="Hello World", ...)
+ ```
+ """
+ if isinstance(other, BaseMessageChunk):
+ # If both are (subclasses of) BaseMessageChunk,
+ # concat into a single BaseMessageChunk
+
+ return self.__class__(
+ id=self.id,
+ type=self.type,
+ content=merge_content(self.content, other.content),
+ additional_kwargs=merge_dicts(
+ self.additional_kwargs, other.additional_kwargs
+ ),
+ response_metadata=merge_dicts(
+ self.response_metadata, other.response_metadata
+ ),
+ )
+ if isinstance(other, list) and all(
+ isinstance(o, BaseMessageChunk) for o in other
+ ):
+ content = merge_content(self.content, *(o.content for o in other))
+ additional_kwargs = merge_dicts(
+ self.additional_kwargs, *(o.additional_kwargs for o in other)
+ )
+ response_metadata = merge_dicts(
+ self.response_metadata, *(o.response_metadata for o in other)
+ )
+ return self.__class__( # type: ignore[call-arg]
+ id=self.id,
+ content=content,
+ additional_kwargs=additional_kwargs,
+ response_metadata=response_metadata,
+ )
+ msg = (
+ 'unsupported operand type(s) for +: "'
+ f"{self.__class__.__name__}"
+ f'" and "{other.__class__.__name__}"'
+ )
+ raise TypeError(msg)
+
+
+def message_to_dict(message: BaseMessage) -> dict:
+ """Convert a Message to a dictionary.
+
+ Args:
+ message: Message to convert.
+
+ Returns:
+ Message as a dict. The dict will have a `type` key with the message type
+ and a `data` key with the message data as a dict.
+
+ """
+ return {"type": message.type, "data": message.model_dump()}
+
+
+def messages_to_dict(messages: Sequence[BaseMessage]) -> list[dict]:
+ """Convert a sequence of Messages to a list of dictionaries.
+
+ Args:
+ messages: Sequence of messages (as `BaseMessage`s) to convert.
+
+ Returns:
+ List of messages as dicts.
+
+ """
+ return [message_to_dict(m) for m in messages]
+
+
+def get_msg_title_repr(title: str, *, bold: bool = False) -> str:
+ """Get a title representation for a message.
+
+ Args:
+ title: The title.
+ bold: Whether to bold the title.
+
+ Returns:
+ The title representation.
+
+ """
+ padded = " " + title + " "
+ sep_len = (80 - len(padded)) // 2
+ sep = "=" * sep_len
+ second_sep = sep + "=" if len(padded) % 2 else sep
+ if bold:
+ padded = get_bolded_text(padded)
+ return f"{sep}{padded}{second_sep}"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..44ddc2515c421cdc3e43b6a968ab224fe492f322
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__init__.py
@@ -0,0 +1,112 @@
+"""Derivations of standard content blocks from provider content.
+
+`AIMessage` will first attempt to use a provider-specific translator if
+`model_provider` is set in `response_metadata` on the message. Consequently, each
+provider translator must handle all possible content response types from the provider,
+including text.
+
+If no provider is set, or if the provider does not have a registered translator,
+`AIMessage` will fall back to best-effort parsing of the content into blocks using
+the implementation in `BaseMessage`.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ from langchain_core.messages import AIMessage, AIMessageChunk
+ from langchain_core.messages import content as types
+
+# Provider to translator mapping
+PROVIDER_TRANSLATORS: dict[str, dict[str, Callable[..., list[types.ContentBlock]]]] = {}
+"""Map model provider names to translator functions.
+
+The dictionary maps provider names (e.g. `'openai'`, `'anthropic'`) to another
+dictionary with two keys:
+- `'translate_content'`: Function to translate `AIMessage` content.
+- `'translate_content_chunk'`: Function to translate `AIMessageChunk` content.
+
+When calling `content_blocks` on an `AIMessage` or `AIMessageChunk`, if
+`model_provider` is set in `response_metadata`, the corresponding translator
+functions will be used to parse the content into blocks. Otherwise, best-effort parsing
+in `BaseMessage` will be used.
+"""
+
+
+def register_translator(
+ provider: str,
+ translate_content: Callable[[AIMessage], list[types.ContentBlock]],
+ translate_content_chunk: Callable[[AIMessageChunk], list[types.ContentBlock]],
+) -> None:
+ """Register content translators for a provider in `PROVIDER_TRANSLATORS`.
+
+ Args:
+ provider: The model provider name (e.g. `'openai'`, `'anthropic'`).
+ translate_content: Function to translate `AIMessage` content.
+ translate_content_chunk: Function to translate `AIMessageChunk` content.
+ """
+ PROVIDER_TRANSLATORS[provider] = {
+ "translate_content": translate_content,
+ "translate_content_chunk": translate_content_chunk,
+ }
+
+
+def get_translator(
+ provider: str,
+) -> dict[str, Callable[..., list[types.ContentBlock]]] | None:
+ """Get the translator functions for a provider.
+
+ Args:
+ provider: The model provider name.
+
+ Returns:
+ Dictionary with `'translate_content'` and `'translate_content_chunk'`
+ functions, or None if no translator is registered for the provider. In such
+ case, best-effort parsing in `BaseMessage` will be used.
+ """
+ return PROVIDER_TRANSLATORS.get(provider)
+
+
+def _register_translators() -> None:
+ """Register all translators in langchain-core.
+
+ A unit test ensures all modules in `block_translators` are represented here.
+
+ For translators implemented outside langchain-core, they can be registered by
+ calling `register_translator` from within the integration package.
+ """
+ from langchain_core.messages.block_translators.anthropic import ( # noqa: PLC0415
+ _register_anthropic_translator,
+ )
+ from langchain_core.messages.block_translators.bedrock import ( # noqa: PLC0415
+ _register_bedrock_translator,
+ )
+ from langchain_core.messages.block_translators.bedrock_converse import ( # noqa: PLC0415
+ _register_bedrock_converse_translator,
+ )
+ from langchain_core.messages.block_translators.google_genai import ( # noqa: PLC0415
+ _register_google_genai_translator,
+ )
+ from langchain_core.messages.block_translators.google_vertexai import ( # noqa: PLC0415
+ _register_google_vertexai_translator,
+ )
+ from langchain_core.messages.block_translators.groq import ( # noqa: PLC0415
+ _register_groq_translator,
+ )
+ from langchain_core.messages.block_translators.openai import ( # noqa: PLC0415
+ _register_openai_translator,
+ )
+
+ _register_bedrock_translator()
+ _register_bedrock_converse_translator()
+ _register_anthropic_translator()
+ _register_google_genai_translator()
+ _register_google_vertexai_translator()
+ _register_groq_translator()
+ _register_openai_translator()
+
+
+_register_translators()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6ce20da4ae53a3fab31abe68e95ed1bd709be7e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/anthropic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/anthropic.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e8766e2cf3a0be0d4f96b19c2cfa902bb4b6885
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/anthropic.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/bedrock.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/bedrock.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..46bae8157773006e62f7a34a1f6e595ce6987fa6
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/bedrock.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/bedrock_converse.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/bedrock_converse.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f8c8ca8ba04c5f67c22faf5b7c8ceccf3c618959
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/bedrock_converse.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/google_genai.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/google_genai.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d93b5f717d089eb271a73ee54150dac9ebfa0ae
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/google_genai.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/google_vertexai.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/google_vertexai.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aec906b4213fdd12ec85f43b6982bbe7c749e30a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/google_vertexai.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/groq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/groq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3bb5bd890138c2b1a20abf28e5e49dbff8165c49
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/groq.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/langchain_v0.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/langchain_v0.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b282de65d5101f006c43c0702b49fd68af17c18d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/langchain_v0.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/openai.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/openai.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25dfb8762f9def7234708268d0b98880cdbc8821
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/__pycache__/openai.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/anthropic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/anthropic.py
new file mode 100644
index 0000000000000000000000000000000000000000..eab2163f07ed58c536231d720c0822e5407ff8a1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/anthropic.py
@@ -0,0 +1,499 @@
+"""Derivations of standard content blocks from Anthropic content."""
+
+import json
+from collections.abc import Iterator
+from typing import Any, cast
+
+from langchain_core.messages import AIMessage, AIMessageChunk
+from langchain_core.messages import content as types
+
+
+def _populate_extras(
+ standard_block: types.ContentBlock, block: dict[str, Any], known_fields: set[str]
+) -> types.ContentBlock:
+ """Mutate a block, populating extras."""
+ if standard_block.get("type") == "non_standard":
+ return standard_block
+
+ for key, value in block.items():
+ if key not in known_fields:
+ if "extras" not in standard_block:
+ # Below type-ignores are because mypy thinks a non-standard block can
+ # get here, although we exclude them above.
+ standard_block["extras"] = {} # type: ignore[typeddict-unknown-key]
+ standard_block["extras"][key] = value # type: ignore[typeddict-item]
+
+ return standard_block
+
+
+def _convert_to_v1_from_anthropic_input(
+ content: list[types.ContentBlock],
+) -> list[types.ContentBlock]:
+ """Convert Anthropic format blocks to v1 format.
+
+ During the `content_blocks` parsing process, we wrap blocks not recognized as a v1
+ block as a `'non_standard'` block with the original block stored in the `value`
+ field. This function attempts to unpack those blocks and convert any blocks that
+ might be Anthropic format to v1 ContentBlocks.
+
+ If conversion fails, the block is left as a `'non_standard'` block.
+
+ Args:
+ content: List of content blocks to process.
+
+ Returns:
+ Updated list with Anthropic blocks converted to v1 format.
+ """
+
+ def _iter_blocks() -> Iterator[types.ContentBlock]:
+ blocks: list[dict[str, Any]] = [
+ cast("dict[str, Any]", block)
+ if block.get("type") != "non_standard"
+ else block["value"] # type: ignore[typeddict-item] # this is only non-standard blocks
+ for block in content
+ ]
+ for block in blocks:
+ block_type = block.get("type")
+
+ if (
+ block_type == "document"
+ and "source" in block
+ and "type" in block["source"]
+ ):
+ if block["source"]["type"] == "base64":
+ file_block: types.FileContentBlock = {
+ "type": "file",
+ "base64": block["source"]["data"],
+ "mime_type": block["source"]["media_type"],
+ }
+ _populate_extras(file_block, block, {"type", "source"})
+ yield file_block
+
+ elif block["source"]["type"] == "url":
+ file_block = {
+ "type": "file",
+ "url": block["source"]["url"],
+ }
+ _populate_extras(file_block, block, {"type", "source"})
+ yield file_block
+
+ elif block["source"]["type"] == "file":
+ file_block = {
+ "type": "file",
+ "id": block["source"]["file_id"],
+ }
+ _populate_extras(file_block, block, {"type", "source"})
+ yield file_block
+
+ elif block["source"]["type"] == "text":
+ plain_text_block: types.PlainTextContentBlock = {
+ "type": "text-plain",
+ "text": block["source"]["data"],
+ "mime_type": block.get("media_type", "text/plain"),
+ }
+ _populate_extras(plain_text_block, block, {"type", "source"})
+ yield plain_text_block
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ elif (
+ block_type == "image"
+ and "source" in block
+ and "type" in block["source"]
+ ):
+ if block["source"]["type"] == "base64":
+ image_block: types.ImageContentBlock = {
+ "type": "image",
+ "base64": block["source"]["data"],
+ "mime_type": block["source"]["media_type"],
+ }
+ _populate_extras(image_block, block, {"type", "source"})
+ yield image_block
+
+ elif block["source"]["type"] == "url":
+ image_block = {
+ "type": "image",
+ "url": block["source"]["url"],
+ }
+ _populate_extras(image_block, block, {"type", "source"})
+ yield image_block
+
+ elif block["source"]["type"] == "file":
+ image_block = {
+ "type": "image",
+ "id": block["source"]["file_id"],
+ }
+ _populate_extras(image_block, block, {"type", "source"})
+ yield image_block
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ elif block_type in types.KNOWN_BLOCK_TYPES:
+ yield cast("types.ContentBlock", block)
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ return list(_iter_blocks())
+
+
+def _convert_citation_to_v1(citation: dict[str, Any]) -> types.Annotation:
+ citation_type = citation.get("type")
+
+ if citation_type == "web_search_result_location":
+ url_citation: types.Citation = {
+ "type": "citation",
+ "cited_text": citation["cited_text"],
+ "url": citation["url"],
+ }
+ if title := citation.get("title"):
+ url_citation["title"] = title
+ known_fields = {"type", "cited_text", "url", "title", "index", "extras"}
+ for key, value in citation.items():
+ if key not in known_fields:
+ if "extras" not in url_citation:
+ url_citation["extras"] = {}
+ url_citation["extras"][key] = value
+
+ return url_citation
+
+ if citation_type in {
+ "char_location",
+ "content_block_location",
+ "page_location",
+ "search_result_location",
+ }:
+ document_citation: types.Citation = {
+ "type": "citation",
+ "cited_text": citation["cited_text"],
+ }
+ if "document_title" in citation:
+ document_citation["title"] = citation["document_title"]
+ elif title := citation.get("title"):
+ document_citation["title"] = title
+ known_fields = {
+ "type",
+ "cited_text",
+ "document_title",
+ "title",
+ "index",
+ "extras",
+ }
+ for key, value in citation.items():
+ if key not in known_fields:
+ if "extras" not in document_citation:
+ document_citation["extras"] = {}
+ document_citation["extras"][key] = value
+
+ return document_citation
+
+ return {
+ "type": "non_standard_annotation",
+ "value": citation,
+ }
+
+
+def _convert_to_v1_from_anthropic(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert Anthropic message content to v1 format."""
+ if isinstance(message.content, str):
+ content: list[str | dict] = [{"type": "text", "text": message.content}]
+ else:
+ content = message.content
+
+ def _iter_blocks() -> Iterator[types.ContentBlock]:
+ for block in content:
+ if not isinstance(block, dict):
+ continue
+ block_type = block.get("type")
+
+ if block_type == "text":
+ if citations := block.get("citations"):
+ text_block: types.TextContentBlock = {
+ "type": "text",
+ "text": block.get("text", ""),
+ "annotations": [_convert_citation_to_v1(a) for a in citations],
+ }
+ else:
+ text_block = {"type": "text", "text": block["text"]}
+ if "index" in block:
+ text_block["index"] = block["index"]
+ yield text_block
+
+ elif block_type == "thinking":
+ reasoning_block: types.ReasoningContentBlock = {
+ "type": "reasoning",
+ "reasoning": block.get("thinking", ""),
+ }
+ if "index" in block:
+ reasoning_block["index"] = block["index"]
+ known_fields = {"type", "thinking", "index", "extras"}
+ for key in block:
+ if key not in known_fields:
+ if "extras" not in reasoning_block:
+ reasoning_block["extras"] = {}
+ reasoning_block["extras"][key] = block[key]
+ yield reasoning_block
+
+ elif block_type == "tool_use":
+ if (
+ isinstance(message, AIMessageChunk)
+ and len(message.tool_call_chunks) == 1
+ and message.chunk_position != "last"
+ ):
+ # Isolated chunk
+ chunk = message.tool_call_chunks[0]
+
+ tool_call_chunk = types.ToolCallChunk(
+ name=chunk.get("name"),
+ id=chunk.get("id"),
+ args=chunk.get("args"),
+ type="tool_call_chunk",
+ )
+ if "caller" in block:
+ tool_call_chunk["extras"] = {"caller": block["caller"]}
+
+ index = chunk.get("index")
+ if index is not None:
+ tool_call_chunk["index"] = index
+ yield tool_call_chunk
+ else:
+ tool_call_block: types.ToolCall | None = None
+ # Non-streaming or gathered chunk
+ if len(message.tool_calls) == 1:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": message.tool_calls[0]["name"],
+ "args": message.tool_calls[0]["args"],
+ "id": message.tool_calls[0].get("id"),
+ }
+ elif call_id := block.get("id"):
+ for tc in message.tool_calls:
+ if tc.get("id") == call_id:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": tc["name"],
+ "args": tc["args"],
+ "id": tc.get("id"),
+ }
+ break
+ if not tool_call_block:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": block.get("name", ""),
+ "args": block.get("input", {}),
+ "id": block.get("id", ""),
+ }
+ if "index" in block:
+ tool_call_block["index"] = block["index"]
+ if "caller" in block:
+ if "extras" not in tool_call_block:
+ tool_call_block["extras"] = {}
+ tool_call_block["extras"]["caller"] = block["caller"]
+
+ yield tool_call_block
+
+ elif block_type == "input_json_delta" and isinstance(
+ message, AIMessageChunk
+ ):
+ if len(message.tool_call_chunks) == 1:
+ chunk = message.tool_call_chunks[0]
+ tool_call_chunk = types.ToolCallChunk(
+ name=chunk.get("name"),
+ id=chunk.get("id"),
+ args=chunk.get("args"),
+ type="tool_call_chunk",
+ )
+ index = chunk.get("index")
+ if index is not None:
+ tool_call_chunk["index"] = index
+ yield tool_call_chunk
+
+ else:
+ server_tool_call_chunk: types.ServerToolCallChunk = {
+ "type": "server_tool_call_chunk",
+ "args": block.get("partial_json", ""),
+ }
+ if "index" in block:
+ server_tool_call_chunk["index"] = block["index"]
+ yield server_tool_call_chunk
+
+ elif block_type == "server_tool_use":
+ if block.get("name") == "code_execution":
+ server_tool_use_name = "code_interpreter"
+ else:
+ server_tool_use_name = block.get("name", "")
+ if (
+ isinstance(message, AIMessageChunk)
+ and block.get("input") == {}
+ and "partial_json" not in block
+ and message.chunk_position != "last"
+ ):
+ # First chunk in a stream
+ server_tool_call_chunk = {
+ "type": "server_tool_call_chunk",
+ "name": server_tool_use_name,
+ "args": "",
+ "id": block.get("id", ""),
+ }
+ if "index" in block:
+ server_tool_call_chunk["index"] = block["index"]
+ known_fields = {"type", "name", "input", "id", "index"}
+ _populate_extras(server_tool_call_chunk, block, known_fields)
+ yield server_tool_call_chunk
+ else:
+ server_tool_call: types.ServerToolCall = {
+ "type": "server_tool_call",
+ "name": server_tool_use_name,
+ "args": block.get("input", {}),
+ "id": block.get("id", ""),
+ }
+
+ if block.get("input") == {} and "partial_json" in block:
+ try:
+ input_ = json.loads(block["partial_json"])
+ if isinstance(input_, dict):
+ server_tool_call["args"] = input_
+ except json.JSONDecodeError:
+ pass
+
+ if "index" in block:
+ server_tool_call["index"] = block["index"]
+ known_fields = {
+ "type",
+ "name",
+ "input",
+ "partial_json",
+ "id",
+ "index",
+ }
+ _populate_extras(server_tool_call, block, known_fields)
+
+ yield server_tool_call
+
+ elif block_type == "mcp_tool_use":
+ if (
+ isinstance(message, AIMessageChunk)
+ and block.get("input") == {}
+ and "partial_json" not in block
+ and message.chunk_position != "last"
+ ):
+ # First chunk in a stream
+ server_tool_call_chunk = {
+ "type": "server_tool_call_chunk",
+ "name": "remote_mcp",
+ "args": "",
+ "id": block.get("id", ""),
+ }
+ if "name" in block:
+ server_tool_call_chunk["extras"] = {"tool_name": block["name"]}
+ known_fields = {"type", "name", "input", "id", "index"}
+ _populate_extras(server_tool_call_chunk, block, known_fields)
+ if "index" in block:
+ server_tool_call_chunk["index"] = block["index"]
+ yield server_tool_call_chunk
+ else:
+ server_tool_call = {
+ "type": "server_tool_call",
+ "name": "remote_mcp",
+ "args": block.get("input", {}),
+ "id": block.get("id", ""),
+ }
+
+ if block.get("input") == {} and "partial_json" in block:
+ try:
+ input_ = json.loads(block["partial_json"])
+ if isinstance(input_, dict):
+ server_tool_call["args"] = input_
+ except json.JSONDecodeError:
+ pass
+
+ if "name" in block:
+ server_tool_call["extras"] = {"tool_name": block["name"]}
+ known_fields = {
+ "type",
+ "name",
+ "input",
+ "partial_json",
+ "id",
+ "index",
+ }
+ _populate_extras(server_tool_call, block, known_fields)
+ if "index" in block:
+ server_tool_call["index"] = block["index"]
+
+ yield server_tool_call
+
+ elif block_type and block_type.endswith("_tool_result"):
+ server_tool_result: types.ServerToolResult = {
+ "type": "server_tool_result",
+ "tool_call_id": block.get("tool_use_id", ""),
+ "status": "success",
+ "extras": {"block_type": block_type},
+ }
+ if output := block.get("content", []):
+ server_tool_result["output"] = output
+ if isinstance(output, dict) and output.get(
+ "error_code" # web_search, code_interpreter
+ ):
+ server_tool_result["status"] = "error"
+ if block.get("is_error"): # mcp_tool_result
+ server_tool_result["status"] = "error"
+ if "index" in block:
+ server_tool_result["index"] = block["index"]
+
+ known_fields = {"type", "tool_use_id", "content", "is_error", "index"}
+ _populate_extras(server_tool_result, block, known_fields)
+
+ yield server_tool_result
+
+ else:
+ new_block: types.NonStandardContentBlock = {
+ "type": "non_standard",
+ "value": block,
+ }
+ if "index" in new_block["value"]:
+ new_block["index"] = new_block["value"].pop("index")
+ yield new_block
+
+ return list(_iter_blocks())
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with Anthropic content.
+
+ Args:
+ message: The message to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_anthropic(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message chunk with Anthropic content.
+
+ Args:
+ message: The message chunk to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_anthropic(message)
+
+
+def _register_anthropic_translator() -> None:
+ """Register the Anthropic translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("anthropic", translate_content, translate_content_chunk)
+
+
+_register_anthropic_translator()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/bedrock.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/bedrock.py
new file mode 100644
index 0000000000000000000000000000000000000000..f37f223016b0bdbd8c611fcc1e0d31e45acfa09b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/bedrock.py
@@ -0,0 +1,108 @@
+"""Derivations of standard content blocks from Bedrock content."""
+
+from langchain_core.messages import AIMessage, AIMessageChunk
+from langchain_core.messages import content as types
+from langchain_core.messages.block_translators.anthropic import (
+ _convert_to_v1_from_anthropic,
+)
+
+
+def _convert_to_v1_from_bedrock(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert bedrock message content to v1 format."""
+ out = _convert_to_v1_from_anthropic(message)
+
+ content_tool_call_ids = {
+ block.get("id")
+ for block in out
+ if isinstance(block, dict) and block.get("type") == "tool_call"
+ }
+ for tool_call in message.tool_calls:
+ if (id_ := tool_call.get("id")) and id_ not in content_tool_call_ids:
+ tool_call_block: types.ToolCall = {
+ "type": "tool_call",
+ "id": id_,
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ }
+ if "index" in tool_call:
+ tool_call_block["index"] = tool_call["index"] # type: ignore[typeddict-item]
+ if "extras" in tool_call:
+ tool_call_block["extras"] = tool_call["extras"] # type: ignore[typeddict-item]
+ out.append(tool_call_block)
+ return out
+
+
+def _convert_to_v1_from_bedrock_chunk(
+ message: AIMessageChunk,
+) -> list[types.ContentBlock]:
+ """Convert bedrock message chunk content to v1 format."""
+ if (
+ message.content == ""
+ and not message.additional_kwargs
+ and not message.tool_calls
+ ):
+ # Bedrock outputs multiple chunks containing response metadata
+ return []
+
+ out = _convert_to_v1_from_anthropic(message)
+
+ if (
+ message.tool_call_chunks
+ and not message.content
+ and message.chunk_position != "last" # keep tool_calls if aggregated
+ ):
+ for tool_call_chunk in message.tool_call_chunks:
+ tc: types.ToolCallChunk = {
+ "type": "tool_call_chunk",
+ "id": tool_call_chunk.get("id"),
+ "name": tool_call_chunk.get("name"),
+ "args": tool_call_chunk.get("args"),
+ }
+ if (idx := tool_call_chunk.get("index")) is not None:
+ tc["index"] = idx
+ out.append(tc)
+ return out
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with Bedrock content.
+
+ Args:
+ message: The message to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ if "claude" not in message.response_metadata.get("model_name", "").lower():
+ raise NotImplementedError # fall back to best-effort parsing
+ return _convert_to_v1_from_bedrock(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message chunk with Bedrock content.
+
+ Args:
+ message: The message chunk to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ # TODO: add model_name to all Bedrock chunks and update core merging logic
+ # to not append during aggregation. Then raise NotImplementedError here if
+ # not an Anthropic model to fall back to best-effort parsing.
+ return _convert_to_v1_from_bedrock_chunk(message)
+
+
+def _register_bedrock_translator() -> None:
+ """Register the bedrock translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("bedrock", translate_content, translate_content_chunk)
+
+
+_register_bedrock_translator()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/bedrock_converse.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/bedrock_converse.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2407e72fa460f43bdd889eac488830b4e777893
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/bedrock_converse.py
@@ -0,0 +1,319 @@
+"""Derivations of standard content blocks from Amazon (Bedrock Converse) content."""
+
+import base64
+from collections.abc import Iterator
+from typing import Any, cast
+
+from langchain_core.messages import AIMessage, AIMessageChunk
+from langchain_core.messages import content as types
+
+
+def _bytes_to_b64_str(bytes_: bytes) -> str:
+ return base64.b64encode(bytes_).decode("utf-8")
+
+
+def _populate_extras(
+ standard_block: types.ContentBlock, block: dict[str, Any], known_fields: set[str]
+) -> types.ContentBlock:
+ """Mutate a block, populating extras."""
+ if standard_block.get("type") == "non_standard":
+ return standard_block
+
+ for key, value in block.items():
+ if key not in known_fields:
+ if "extras" not in standard_block:
+ # Below type-ignores are because mypy thinks a non-standard block can
+ # get here, although we exclude them above.
+ standard_block["extras"] = {} # type: ignore[typeddict-unknown-key]
+ standard_block["extras"][key] = value # type: ignore[typeddict-item]
+
+ return standard_block
+
+
+def _convert_to_v1_from_converse_input(
+ content: list[types.ContentBlock],
+) -> list[types.ContentBlock]:
+ """Convert Bedrock Converse format blocks to v1 format.
+
+ During the `content_blocks` parsing process, we wrap blocks not recognized as a v1
+ block as a `'non_standard'` block with the original block stored in the `value`
+ field. This function attempts to unpack those blocks and convert any blocks that
+ might be Converse format to v1 ContentBlocks.
+
+ If conversion fails, the block is left as a `'non_standard'` block.
+
+ Args:
+ content: List of content blocks to process.
+
+ Returns:
+ Updated list with Converse blocks converted to v1 format.
+ """
+
+ def _iter_blocks() -> Iterator[types.ContentBlock]:
+ blocks: list[dict[str, Any]] = [
+ cast("dict[str, Any]", block)
+ if block.get("type") != "non_standard"
+ else block["value"] # type: ignore[typeddict-item] # this is only non-standard blocks
+ for block in content
+ ]
+ for block in blocks:
+ num_keys = len(block)
+
+ if num_keys == 1 and (text := block.get("text")):
+ yield {"type": "text", "text": text}
+
+ elif (
+ num_keys == 1
+ and (document := block.get("document"))
+ and isinstance(document, dict)
+ and "format" in document
+ ):
+ if document.get("format") == "pdf":
+ if "bytes" in document.get("source", {}):
+ file_block: types.FileContentBlock = {
+ "type": "file",
+ "base64": _bytes_to_b64_str(document["source"]["bytes"]),
+ "mime_type": "application/pdf",
+ }
+ _populate_extras(file_block, document, {"format", "source"})
+ yield file_block
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ elif document["format"] == "txt":
+ if "text" in document.get("source", {}):
+ plain_text_block: types.PlainTextContentBlock = {
+ "type": "text-plain",
+ "text": document["source"]["text"],
+ "mime_type": "text/plain",
+ }
+ _populate_extras(
+ plain_text_block, document, {"format", "source"}
+ )
+ yield plain_text_block
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ elif (
+ num_keys == 1
+ and (image := block.get("image"))
+ and isinstance(image, dict)
+ and "format" in image
+ ):
+ if "bytes" in image.get("source", {}):
+ image_block: types.ImageContentBlock = {
+ "type": "image",
+ "base64": _bytes_to_b64_str(image["source"]["bytes"]),
+ "mime_type": f"image/{image['format']}",
+ }
+ _populate_extras(image_block, image, {"format", "source"})
+ yield image_block
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ elif block.get("type") in types.KNOWN_BLOCK_TYPES:
+ yield cast("types.ContentBlock", block)
+
+ else:
+ yield {"type": "non_standard", "value": block}
+
+ return list(_iter_blocks())
+
+
+def _convert_citation_to_v1(citation: dict[str, Any]) -> types.Annotation:
+ standard_citation: types.Citation = {"type": "citation"}
+ if "title" in citation:
+ standard_citation["title"] = citation["title"]
+ if (
+ (source_content := citation.get("source_content"))
+ and isinstance(source_content, list)
+ and all(isinstance(item, dict) for item in source_content)
+ ):
+ standard_citation["cited_text"] = "".join(
+ item.get("text", "") for item in source_content
+ )
+
+ known_fields = {"type", "source_content", "title", "index", "extras"}
+
+ for key, value in citation.items():
+ if key not in known_fields:
+ if "extras" not in standard_citation:
+ standard_citation["extras"] = {}
+ standard_citation["extras"][key] = value
+
+ return standard_citation
+
+
+def _convert_to_v1_from_converse(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert Bedrock Converse message content to v1 format."""
+ if (
+ message.content == ""
+ and not message.additional_kwargs
+ and not message.tool_calls
+ ):
+ # Converse outputs multiple chunks containing response metadata
+ return []
+
+ if isinstance(message.content, str):
+ message.content = [{"type": "text", "text": message.content}]
+
+ def _iter_blocks() -> Iterator[types.ContentBlock]:
+ for block in message.content:
+ if not isinstance(block, dict):
+ continue
+ block_type = block.get("type")
+
+ if block_type == "text":
+ if citations := block.get("citations"):
+ text_block: types.TextContentBlock = {
+ "type": "text",
+ "text": block.get("text", ""),
+ "annotations": [_convert_citation_to_v1(a) for a in citations],
+ }
+ else:
+ text_block = {"type": "text", "text": block["text"]}
+ if "index" in block:
+ text_block["index"] = block["index"]
+ yield text_block
+
+ elif block_type == "reasoning_content":
+ reasoning_block: types.ReasoningContentBlock = {"type": "reasoning"}
+ if reasoning_content := block.get("reasoning_content"):
+ if reasoning := reasoning_content.get("text"):
+ reasoning_block["reasoning"] = reasoning
+ if signature := reasoning_content.get("signature"):
+ if "extras" not in reasoning_block:
+ reasoning_block["extras"] = {}
+ reasoning_block["extras"]["signature"] = signature
+
+ if "index" in block:
+ reasoning_block["index"] = block["index"]
+
+ known_fields = {"type", "reasoning_content", "index", "extras"}
+ for key in block:
+ if key not in known_fields:
+ if "extras" not in reasoning_block:
+ reasoning_block["extras"] = {}
+ reasoning_block["extras"][key] = block[key]
+ yield reasoning_block
+
+ elif block_type == "tool_use":
+ if (
+ isinstance(message, AIMessageChunk)
+ and len(message.tool_call_chunks) == 1
+ and message.chunk_position != "last"
+ ):
+ # Isolated chunk
+ chunk = message.tool_call_chunks[0]
+ tool_call_chunk = types.ToolCallChunk(
+ name=chunk.get("name"),
+ id=chunk.get("id"),
+ args=chunk.get("args"),
+ type="tool_call_chunk",
+ )
+ index = chunk.get("index")
+ if index is not None:
+ tool_call_chunk["index"] = index
+ yield tool_call_chunk
+ else:
+ tool_call_block: types.ToolCall | None = None
+ # Non-streaming or gathered chunk
+ if len(message.tool_calls) == 1:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": message.tool_calls[0]["name"],
+ "args": message.tool_calls[0]["args"],
+ "id": message.tool_calls[0].get("id"),
+ }
+ elif call_id := block.get("id"):
+ for tc in message.tool_calls:
+ if tc.get("id") == call_id:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": tc["name"],
+ "args": tc["args"],
+ "id": tc.get("id"),
+ }
+ break
+ if not tool_call_block:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": block.get("name", ""),
+ "args": block.get("input", {}),
+ "id": block.get("id", ""),
+ }
+ if "index" in block:
+ tool_call_block["index"] = block["index"]
+ yield tool_call_block
+
+ elif (
+ block_type == "input_json_delta"
+ and isinstance(message, AIMessageChunk)
+ and len(message.tool_call_chunks) == 1
+ ):
+ chunk = message.tool_call_chunks[0]
+ tool_call_chunk = types.ToolCallChunk(
+ name=chunk.get("name"),
+ id=chunk.get("id"),
+ args=chunk.get("args"),
+ type="tool_call_chunk",
+ )
+ index = chunk.get("index")
+ if index is not None:
+ tool_call_chunk["index"] = index
+ yield tool_call_chunk
+
+ else:
+ new_block: types.NonStandardContentBlock = {
+ "type": "non_standard",
+ "value": block,
+ }
+ if "index" in new_block["value"]:
+ new_block["index"] = new_block["value"].pop("index")
+ yield new_block
+
+ return list(_iter_blocks())
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with Bedrock Converse content.
+
+ Args:
+ message: The message to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_converse(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a chunk with Bedrock Converse content.
+
+ Args:
+ message: The message chunk to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_converse(message)
+
+
+def _register_bedrock_converse_translator() -> None:
+ """Register the Bedrock Converse translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("bedrock_converse", translate_content, translate_content_chunk)
+
+
+_register_bedrock_converse_translator()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/google_genai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/google_genai.py
new file mode 100644
index 0000000000000000000000000000000000000000..321de2f2df4a9413507411169a8078f065d5ede9
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/google_genai.py
@@ -0,0 +1,566 @@
+"""Derivations of standard content blocks from Google (GenAI) content."""
+
+import base64
+import re
+from collections.abc import Iterator
+from typing import Any, cast
+
+from langchain_core.messages import AIMessage, AIMessageChunk
+from langchain_core.messages import content as types
+from langchain_core.messages.content import Citation, create_citation
+
+try:
+ import filetype # type: ignore[import-not-found]
+
+ _HAS_FILETYPE = True
+except ImportError:
+ _HAS_FILETYPE = False
+
+
+def _bytes_to_b64_str(bytes_: bytes) -> str:
+ """Convert bytes to base64 encoded string."""
+ return base64.b64encode(bytes_).decode("utf-8")
+
+
+def translate_grounding_metadata_to_citations(
+ grounding_metadata: dict[str, Any],
+) -> list[Citation]:
+ """Translate Google AI grounding metadata to LangChain Citations.
+
+ Args:
+ grounding_metadata: Google AI grounding metadata containing web search
+ queries, grounding chunks, and grounding supports.
+
+ Returns:
+ List of Citation content blocks derived from the grounding metadata.
+
+ Example:
+ >>> metadata = {
+ ... "web_search_queries": ["UEFA Euro 2024 winner"],
+ ... "grounding_chunks": [
+ ... {
+ ... "web": {
+ ... "uri": "https://uefa.com/euro2024",
+ ... "title": "UEFA Euro 2024 Results",
+ ... }
+ ... }
+ ... ],
+ ... "grounding_supports": [
+ ... {
+ ... "segment": {
+ ... "start_index": 0,
+ ... "end_index": 47,
+ ... "text": "Spain won the UEFA Euro 2024 championship",
+ ... },
+ ... "grounding_chunk_indices": [0],
+ ... }
+ ... ],
+ ... }
+ >>> citations = translate_grounding_metadata_to_citations(metadata)
+ >>> len(citations)
+ 1
+ >>> citations[0]["url"]
+ 'https://uefa.com/euro2024'
+ """
+ if not grounding_metadata:
+ return []
+
+ grounding_chunks = grounding_metadata.get("grounding_chunks", [])
+ grounding_supports = grounding_metadata.get("grounding_supports", [])
+ web_search_queries = grounding_metadata.get("web_search_queries", [])
+
+ citations: list[Citation] = []
+
+ for support in grounding_supports:
+ segment = support.get("segment", {})
+ chunk_indices = support.get("grounding_chunk_indices", [])
+
+ start_index = segment.get("start_index")
+ end_index = segment.get("end_index")
+ cited_text = segment.get("text")
+
+ # Create a citation for each referenced chunk
+ for chunk_index in chunk_indices:
+ if chunk_index < len(grounding_chunks):
+ chunk = grounding_chunks[chunk_index]
+
+ # Handle web and maps grounding
+ web_info = chunk.get("web") or {}
+ maps_info = chunk.get("maps") or {}
+
+ # Extract citation info depending on source
+ url = maps_info.get("uri") or web_info.get("uri")
+ title = maps_info.get("title") or web_info.get("title")
+
+ # Note: confidence_scores is a legacy field from Gemini 2.0 and earlier
+ # that indicated confidence (0.0-1.0) for each grounding chunk.
+ #
+ # In Gemini 2.5+, this field is always None/empty and should be ignored.
+ extras_metadata = {
+ "web_search_queries": web_search_queries,
+ "grounding_chunk_index": chunk_index,
+ "confidence_scores": support.get("confidence_scores") or [],
+ }
+
+ # Add maps-specific metadata if present
+ if maps_info.get("placeId"):
+ extras_metadata["place_id"] = maps_info["placeId"]
+
+ citation = create_citation(
+ url=url,
+ title=title,
+ start_index=start_index,
+ end_index=end_index,
+ cited_text=cited_text,
+ google_ai_metadata=extras_metadata,
+ )
+ citations.append(citation)
+
+ return citations
+
+
+def _convert_to_v1_from_genai_input(
+ content: list[types.ContentBlock],
+) -> list[types.ContentBlock]:
+ """Convert Google GenAI format blocks to v1 format.
+
+ Called when message isn't an `AIMessage` or `model_provider` isn't set on
+ `response_metadata`.
+
+ During the `content_blocks` parsing process, we wrap blocks not recognized as a v1
+ block as a `'non_standard'` block with the original block stored in the `value`
+ field. This function attempts to unpack those blocks and convert any blocks that
+ might be GenAI format to v1 ContentBlocks.
+
+ If conversion fails, the block is left as a `'non_standard'` block.
+
+ Args:
+ content: List of content blocks to process.
+
+ Returns:
+ Updated list with GenAI blocks converted to v1 format.
+ """
+
+ def _iter_blocks() -> Iterator[types.ContentBlock]:
+ blocks: list[dict[str, Any]] = [
+ cast("dict[str, Any]", block)
+ if block.get("type") != "non_standard"
+ else block["value"] # type: ignore[typeddict-item] # this is only non-standard blocks
+ for block in content
+ ]
+ for block in blocks:
+ num_keys = len(block)
+ block_type = block.get("type")
+
+ if num_keys == 1 and (text := block.get("text")):
+ # This is probably a TextContentBlock
+ yield {"type": "text", "text": text}
+
+ elif (
+ num_keys == 1
+ and (document := block.get("document"))
+ and isinstance(document, dict)
+ and "format" in document
+ ):
+ # Handle document format conversion
+ doc_format = document.get("format")
+ source = document.get("source", {})
+
+ if doc_format == "pdf" and "bytes" in source:
+ # PDF document with byte data
+ file_block: types.FileContentBlock = {
+ "type": "file",
+ "base64": source["bytes"]
+ if isinstance(source["bytes"], str)
+ else _bytes_to_b64_str(source["bytes"]),
+ "mime_type": "application/pdf",
+ }
+ # Preserve extra fields
+ extras = {
+ key: value
+ for key, value in document.items()
+ if key not in {"format", "source"}
+ }
+ if extras:
+ file_block["extras"] = extras
+ yield file_block
+
+ elif doc_format == "txt" and "text" in source:
+ # Text document
+ plain_text_block: types.PlainTextContentBlock = {
+ "type": "text-plain",
+ "text": source["text"],
+ "mime_type": "text/plain",
+ }
+ # Preserve extra fields
+ extras = {
+ key: value
+ for key, value in document.items()
+ if key not in {"format", "source"}
+ }
+ if extras:
+ plain_text_block["extras"] = extras
+ yield plain_text_block
+
+ else:
+ # Unknown document format
+ yield {"type": "non_standard", "value": block}
+
+ elif (
+ num_keys == 1
+ and (image := block.get("image"))
+ and isinstance(image, dict)
+ and "format" in image
+ ):
+ # Handle image format conversion
+ img_format = image.get("format")
+ source = image.get("source", {})
+
+ if "bytes" in source:
+ # Image with byte data
+ image_block: types.ImageContentBlock = {
+ "type": "image",
+ "base64": source["bytes"]
+ if isinstance(source["bytes"], str)
+ else _bytes_to_b64_str(source["bytes"]),
+ "mime_type": f"image/{img_format}",
+ }
+ # Preserve extra fields
+ extras = {}
+ for key, value in image.items():
+ if key not in {"format", "source"}:
+ extras[key] = value
+ if extras:
+ image_block["extras"] = extras
+ yield image_block
+
+ else:
+ # Image without byte data
+ yield {"type": "non_standard", "value": block}
+
+ elif block_type == "file_data" and "file_uri" in block:
+ # Handle FileData URI-based content
+ uri_file_block: types.FileContentBlock = {
+ "type": "file",
+ "url": block["file_uri"],
+ }
+ if mime_type := block.get("mime_type"):
+ uri_file_block["mime_type"] = mime_type
+ yield uri_file_block
+
+ elif block_type == "function_call" and "name" in block:
+ # Handle function calls
+ tool_call_block: types.ToolCall = {
+ "type": "tool_call",
+ "name": block["name"],
+ "args": block.get("args", {}),
+ "id": block.get("id", ""),
+ }
+ yield tool_call_block
+
+ elif block_type == "executable_code":
+ server_tool_call_input: types.ServerToolCall = {
+ "type": "server_tool_call",
+ "name": "code_interpreter",
+ "args": {
+ "code": block.get("executable_code", ""),
+ "language": block.get("language", "python"),
+ },
+ "id": block.get("id", ""),
+ }
+ yield server_tool_call_input
+
+ elif block_type == "code_execution_result":
+ outcome = block.get("outcome", 1)
+ status = "success" if outcome == 1 else "error"
+ server_tool_result_input: types.ServerToolResult = {
+ "type": "server_tool_result",
+ "tool_call_id": block.get("tool_call_id", ""),
+ "status": status, # type: ignore[typeddict-item]
+ "output": block.get("code_execution_result", ""),
+ }
+ if outcome is not None:
+ server_tool_result_input["extras"] = {"outcome": outcome}
+ yield server_tool_result_input
+
+ elif block.get("type") in types.KNOWN_BLOCK_TYPES:
+ # We see a standard block type, so we just cast it, even if
+ # we don't fully understand it. This may be dangerous, but
+ # it's better than losing information.
+ yield cast("types.ContentBlock", block)
+
+ else:
+ # We don't understand this block at all.
+ yield {"type": "non_standard", "value": block}
+
+ return list(_iter_blocks())
+
+
+def _convert_to_v1_from_genai(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert Google GenAI message content to v1 format.
+
+ Calling `.content_blocks` on an `AIMessage` where `response_metadata.model_provider`
+ is set to `'google_genai'` will invoke this function to parse the content into
+ standard content blocks for returning.
+
+ Args:
+ message: The `AIMessage` or `AIMessageChunk` to convert.
+
+ Returns:
+ List of standard content blocks derived from the message content.
+ """
+ if isinstance(message.content, str):
+ # String content -> TextContentBlock (only add if non-empty in case of audio)
+ string_blocks: list[types.ContentBlock] = []
+ if message.content:
+ string_blocks.append({"type": "text", "text": message.content})
+
+ # Add any missing tool calls from message.tool_calls field
+ content_tool_call_ids = {
+ block.get("id")
+ for block in string_blocks
+ if isinstance(block, dict) and block.get("type") == "tool_call"
+ }
+ for tool_call in message.tool_calls:
+ id_ = tool_call.get("id")
+ if id_ and id_ not in content_tool_call_ids:
+ string_tool_call_block: types.ToolCall = {
+ "type": "tool_call",
+ "id": id_,
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ }
+ string_blocks.append(string_tool_call_block)
+
+ # Handle audio from additional_kwargs if present (for empty content cases)
+ audio_data = message.additional_kwargs.get("audio")
+ if audio_data and isinstance(audio_data, bytes):
+ audio_block: types.AudioContentBlock = {
+ "type": "audio",
+ "base64": _bytes_to_b64_str(audio_data),
+ "mime_type": "audio/wav", # Default to WAV for Google GenAI
+ }
+ string_blocks.append(audio_block)
+
+ grounding_metadata = message.response_metadata.get("grounding_metadata")
+ if grounding_metadata:
+ citations = translate_grounding_metadata_to_citations(grounding_metadata)
+
+ for block in string_blocks:
+ if block["type"] == "text" and citations:
+ # Add citations to the first text block only
+ block["annotations"] = cast("list[types.Annotation]", citations)
+ break
+
+ return string_blocks
+
+ if not isinstance(message.content, list):
+ # Unexpected content type, attempt to represent as text
+ return [{"type": "text", "text": str(message.content)}]
+
+ converted_blocks: list[types.ContentBlock] = []
+
+ for item in message.content:
+ if isinstance(item, str):
+ # Conversation history strings
+
+ # Citations are handled below after all blocks are converted
+ converted_blocks.append({"type": "text", "text": item}) # TextContentBlock
+
+ elif isinstance(item, dict):
+ item_type = item.get("type")
+ if item_type == "image_url":
+ # Convert image_url to standard image block (base64)
+ # (since the original implementation returned as url-base64 CC style)
+ image_url = item.get("image_url", {})
+ url = image_url.get("url", "")
+ if url:
+ # Extract base64 data
+ match = re.match(r"data:([^;]+);base64,(.+)", url)
+ if match:
+ # Data URI provided
+ mime_type, base64_data = match.groups()
+ converted_blocks.append(
+ {
+ "type": "image",
+ "base64": base64_data,
+ "mime_type": mime_type,
+ }
+ )
+ else:
+ # Assume it's raw base64 without data URI
+ try:
+ # Validate base64 and decode for MIME type detection
+ decoded_bytes = base64.b64decode(url, validate=True)
+
+ image_url_b64_block = {
+ "type": "image",
+ "base64": url,
+ }
+
+ if _HAS_FILETYPE:
+ # Guess MIME type based on file bytes
+ mime_type = None
+ kind = filetype.guess(decoded_bytes)
+ if kind:
+ mime_type = kind.mime
+ if mime_type:
+ image_url_b64_block["mime_type"] = mime_type
+
+ converted_blocks.append(
+ cast("types.ImageContentBlock", image_url_b64_block)
+ )
+ except Exception:
+ # Not valid base64, treat as non-standard
+ converted_blocks.append(
+ {
+ "type": "non_standard",
+ "value": item,
+ }
+ )
+ else:
+ # This likely won't be reached according to previous implementations
+ converted_blocks.append({"type": "non_standard", "value": item})
+ msg = "Image URL not a data URI; appending as non-standard block."
+ raise ValueError(msg)
+ elif item_type == "function_call":
+ # Handle Google GenAI function calls
+ function_call_block: types.ToolCall = {
+ "type": "tool_call",
+ "name": item.get("name", ""),
+ "args": item.get("args", {}),
+ "id": item.get("id", ""),
+ }
+ converted_blocks.append(function_call_block)
+ elif item_type == "file_data":
+ # Handle FileData URI-based content
+ file_block: types.FileContentBlock = {
+ "type": "file",
+ "url": item.get("file_uri", ""),
+ }
+ if mime_type := item.get("mime_type"):
+ file_block["mime_type"] = mime_type
+ converted_blocks.append(file_block)
+ elif item_type == "thinking":
+ # Handling for the 'thinking' type we package thoughts as
+ reasoning_block: types.ReasoningContentBlock = {
+ "type": "reasoning",
+ "reasoning": item.get("thinking", ""),
+ }
+ if signature := item.get("signature"):
+ reasoning_block["extras"] = {"signature": signature}
+
+ converted_blocks.append(reasoning_block)
+ elif item_type == "executable_code":
+ # Convert to standard server tool call block at the moment
+ server_tool_call_block: types.ServerToolCall = {
+ "type": "server_tool_call",
+ "name": "code_interpreter",
+ "args": {
+ "code": item.get("executable_code", ""),
+ "language": item.get("language", "python"), # Default to python
+ },
+ "id": item.get("id", ""),
+ }
+ converted_blocks.append(server_tool_call_block)
+ elif item_type == "code_execution_result":
+ # Map outcome to status: OUTCOME_OK (1) → success, else → error
+ outcome = item.get("outcome", 1)
+ status = "success" if outcome == 1 else "error"
+ server_tool_result_block: types.ServerToolResult = {
+ "type": "server_tool_result",
+ "tool_call_id": item.get("tool_call_id", ""),
+ "status": status, # type: ignore[typeddict-item]
+ "output": item.get("code_execution_result", ""),
+ }
+ server_tool_result_block["extras"] = {"block_type": item_type}
+ # Preserve original outcome in extras
+ if outcome is not None:
+ server_tool_result_block["extras"]["outcome"] = outcome
+ converted_blocks.append(server_tool_result_block)
+ elif item_type == "text":
+ converted_blocks.append(cast("types.TextContentBlock", item))
+ else:
+ # Unknown type, preserve as non-standard
+ converted_blocks.append({"type": "non_standard", "value": item})
+ else:
+ # Non-dict, non-string content
+ converted_blocks.append({"type": "non_standard", "value": item})
+
+ grounding_metadata = message.response_metadata.get("grounding_metadata")
+ if grounding_metadata:
+ citations = translate_grounding_metadata_to_citations(grounding_metadata)
+
+ for block in converted_blocks:
+ if block["type"] == "text" and citations:
+ # Add citations to text blocks (only the first text block)
+ block["annotations"] = cast("list[types.Annotation]", citations)
+ break
+
+ # Audio is stored on the message.additional_kwargs
+ audio_data = message.additional_kwargs.get("audio")
+ if audio_data and isinstance(audio_data, bytes):
+ audio_block_kwargs: types.AudioContentBlock = {
+ "type": "audio",
+ "base64": _bytes_to_b64_str(audio_data),
+ "mime_type": "audio/wav", # Default to WAV for Google GenAI
+ }
+ converted_blocks.append(audio_block_kwargs)
+
+ # Add any missing tool calls from message.tool_calls field
+ content_tool_call_ids = {
+ block.get("id")
+ for block in converted_blocks
+ if isinstance(block, dict) and block.get("type") == "tool_call"
+ }
+ for tool_call in message.tool_calls:
+ id_ = tool_call.get("id")
+ if id_ and id_ not in content_tool_call_ids:
+ missing_tool_call_block: types.ToolCall = {
+ "type": "tool_call",
+ "id": id_,
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ }
+ converted_blocks.append(missing_tool_call_block)
+
+ return converted_blocks
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with Google (GenAI) content.
+
+ Args:
+ message: The message to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_genai(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a chunk with Google (GenAI) content.
+
+ Args:
+ message: The message chunk to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_genai(message)
+
+
+def _register_google_genai_translator() -> None:
+ """Register the Google (GenAI) translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("google_genai", translate_content, translate_content_chunk)
+
+
+_register_google_genai_translator()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/google_vertexai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/google_vertexai.py
new file mode 100644
index 0000000000000000000000000000000000000000..016f146164ece69d481444f8df0342784949d1c7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/google_vertexai.py
@@ -0,0 +1,21 @@
+"""Derivations of standard content blocks from Google (VertexAI) content."""
+
+from langchain_core.messages.block_translators.google_genai import (
+ translate_content,
+ translate_content_chunk,
+)
+
+
+def _register_google_vertexai_translator() -> None:
+ """Register the Google (VertexAI) translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("google_vertexai", translate_content, translate_content_chunk)
+
+
+_register_google_vertexai_translator()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/groq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/groq.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcaa1a15b7d40d252f612ff4869de1d972af20dd
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/groq.py
@@ -0,0 +1,157 @@
+"""Derivations of standard content blocks from Groq content."""
+
+import json
+import re
+from typing import Any
+
+from langchain_core.messages import AIMessage, AIMessageChunk
+from langchain_core.messages import content as types
+from langchain_core.messages.base import _extract_reasoning_from_additional_kwargs
+
+
+def _populate_extras(
+ standard_block: types.ContentBlock, block: dict[str, Any], known_fields: set[str]
+) -> types.ContentBlock:
+ """Mutate a block, populating extras."""
+ if standard_block.get("type") == "non_standard":
+ return standard_block
+
+ for key, value in block.items():
+ if key not in known_fields:
+ if "extras" not in standard_block:
+ # Below type-ignores are because mypy thinks a non-standard block can
+ # get here, although we exclude them above.
+ standard_block["extras"] = {} # type: ignore[typeddict-unknown-key]
+ standard_block["extras"][key] = value # type: ignore[typeddict-item]
+
+ return standard_block
+
+
+def _parse_code_json(s: str) -> dict:
+ """Extract Python code from Groq built-in tool content.
+
+ Extracts the value of the 'code' field from a string of the form:
+ {"code": some_arbitrary_text_with_unescaped_quotes}
+
+ As Groq may not escape quotes in the executed tools, e.g.:
+ ```
+ '{"code": "import math; print("The square root of 101 is: "); print(math.sqrt(101))"}'
+ ```
+ """ # noqa: E501
+ m = re.fullmatch(r'\s*\{\s*"code"\s*:\s*"(.*)"\s*\}\s*', s, flags=re.DOTALL)
+ if not m:
+ msg = (
+ "Could not extract Python code from Groq tool arguments. "
+ "Expected a JSON object with a 'code' field."
+ )
+ raise ValueError(msg)
+ return {"code": m.group(1)}
+
+
+def _convert_to_v1_from_groq(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert groq message content to v1 format."""
+ content_blocks: list[types.ContentBlock] = []
+
+ if reasoning_block := _extract_reasoning_from_additional_kwargs(message):
+ content_blocks.append(reasoning_block)
+
+ if executed_tools := message.additional_kwargs.get("executed_tools"):
+ for idx, executed_tool in enumerate(executed_tools):
+ args: dict[str, Any] | None = None
+ if arguments := executed_tool.get("arguments"):
+ try:
+ args = json.loads(arguments)
+ except json.JSONDecodeError:
+ if executed_tool.get("type") == "python":
+ try:
+ args = _parse_code_json(arguments)
+ except ValueError:
+ continue
+ elif (
+ executed_tool.get("type") == "function"
+ and executed_tool.get("name") == "python"
+ ):
+ # GPT-OSS
+ args = {"code": arguments}
+ else:
+ continue
+ if isinstance(args, dict):
+ name = ""
+ if executed_tool.get("type") == "search":
+ name = "web_search"
+ elif executed_tool.get("type") == "python" or (
+ executed_tool.get("type") == "function"
+ and executed_tool.get("name") == "python"
+ ):
+ name = "code_interpreter"
+ server_tool_call: types.ServerToolCall = {
+ "type": "server_tool_call",
+ "name": name,
+ "id": str(idx),
+ "args": args,
+ }
+ content_blocks.append(server_tool_call)
+ if tool_output := executed_tool.get("output"):
+ tool_result: types.ServerToolResult = {
+ "type": "server_tool_result",
+ "tool_call_id": str(idx),
+ "output": tool_output,
+ "status": "success",
+ }
+ known_fields = {"type", "arguments", "index", "output"}
+ _populate_extras(tool_result, executed_tool, known_fields)
+ content_blocks.append(tool_result)
+
+ if isinstance(message.content, str) and message.content:
+ content_blocks.append({"type": "text", "text": message.content})
+
+ content_blocks.extend(
+ {
+ "type": "tool_call",
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ "id": tool_call.get("id"),
+ }
+ for tool_call in message.tool_calls
+ )
+
+ return content_blocks
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with groq content.
+
+ Args:
+ message: The message to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_groq(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message chunk with groq content.
+
+ Args:
+ message: The message chunk to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ return _convert_to_v1_from_groq(message)
+
+
+def _register_groq_translator() -> None:
+ """Register the groq translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("groq", translate_content, translate_content_chunk)
+
+
+_register_groq_translator()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/langchain_v0.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/langchain_v0.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7cb03839e8904df69a10da1a831ee2c03b2c7e3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/langchain_v0.py
@@ -0,0 +1,301 @@
+"""Derivations of standard content blocks from LangChain v0 multimodal content."""
+
+from typing import Any, cast
+
+from langchain_core.messages import content as types
+
+
+def _convert_v0_multimodal_input_to_v1(
+ content: list[types.ContentBlock],
+) -> list[types.ContentBlock]:
+ """Convert v0 multimodal blocks to v1 format.
+
+ During the `content_blocks` parsing process, we wrap blocks not recognized as a v1
+ block as a `'non_standard'` block with the original block stored in the `value`
+ field. This function attempts to unpack those blocks and convert any v0 format
+ blocks to v1 format.
+
+ If conversion fails, the block is left as a `'non_standard'` block.
+
+ Args:
+ content: List of content blocks to process.
+
+ Returns:
+ v1 content blocks.
+ """
+ converted_blocks = []
+ unpacked_blocks: list[dict[str, Any]] = [
+ cast("dict[str, Any]", block)
+ if block.get("type") != "non_standard"
+ else block["value"] # type: ignore[typeddict-item] # this is only non-standard blocks
+ for block in content
+ ]
+ for block in unpacked_blocks:
+ if block.get("type") in {"image", "audio", "file"} and "source_type" in block:
+ converted_block = _convert_legacy_v0_content_block_to_v1(block)
+ converted_blocks.append(cast("types.ContentBlock", converted_block))
+ elif block.get("type") in types.KNOWN_BLOCK_TYPES:
+ # Guard in case this function is used outside of the .content_blocks flow
+ converted_blocks.append(cast("types.ContentBlock", block))
+ else:
+ converted_blocks.append({"type": "non_standard", "value": block})
+
+ return converted_blocks
+
+
+def _convert_legacy_v0_content_block_to_v1(
+ block: dict,
+) -> types.ContentBlock | dict:
+ """Convert a LangChain v0 content block to v1 format.
+
+ Preserves unknown keys as extras to avoid data loss.
+
+ Returns the original block unchanged if it's not in v0 format.
+ """
+
+ def _extract_v0_extras(block_dict: dict, known_keys: set[str]) -> dict[str, Any]:
+ """Extract unknown keys from v0 block to preserve as extras.
+
+ Args:
+ block_dict: The original v0 block dictionary.
+ known_keys: Set of keys known to be part of the v0 format for this block.
+
+ Returns:
+ A dictionary of extra keys not part of the known v0 format.
+ """
+ return {k: v for k, v in block_dict.items() if k not in known_keys}
+
+ # Check if this is actually a v0 format block
+ block_type = block.get("type")
+ if block_type not in {"image", "audio", "file"} or "source_type" not in block:
+ # Not a v0 format block, return unchanged
+ return block
+
+ if block.get("type") == "image":
+ source_type = block.get("source_type")
+ if source_type == "url":
+ # image-url
+ known_keys = {"mime_type", "type", "source_type", "url"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_image_block(
+ url=block["url"],
+ mime_type=block.get("mime_type"),
+ id=block["id"],
+ **extras,
+ )
+
+ # Don't construct with an ID if not present in original block
+ v1_image_url = types.ImageContentBlock(type="image", url=block["url"])
+ if block.get("mime_type"):
+ v1_image_url["mime_type"] = block["mime_type"]
+
+ v1_image_url["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_image_url["extras"][key] = value
+ if v1_image_url["extras"] == {}:
+ del v1_image_url["extras"]
+
+ return v1_image_url
+ if source_type == "base64":
+ # image-base64
+ known_keys = {"mime_type", "type", "source_type", "data"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_image_block(
+ base64=block["data"],
+ mime_type=block.get("mime_type"),
+ id=block["id"],
+ **extras,
+ )
+
+ v1_image_base64 = types.ImageContentBlock(
+ type="image", base64=block["data"]
+ )
+ if block.get("mime_type"):
+ v1_image_base64["mime_type"] = block["mime_type"]
+
+ v1_image_base64["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_image_base64["extras"][key] = value
+ if v1_image_base64["extras"] == {}:
+ del v1_image_base64["extras"]
+
+ return v1_image_base64
+ if source_type == "id":
+ # image-id
+ known_keys = {"type", "source_type", "id"}
+ extras = _extract_v0_extras(block, known_keys)
+ # For id `source_type`, `id` is the file reference, not block ID
+ v1_image_id = types.ImageContentBlock(type="image", file_id=block["id"])
+
+ v1_image_id["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_image_id["extras"][key] = value
+ if v1_image_id["extras"] == {}:
+ del v1_image_id["extras"]
+
+ return v1_image_id
+ elif block.get("type") == "audio":
+ source_type = block.get("source_type")
+ if source_type == "url":
+ # audio-url
+ known_keys = {"mime_type", "type", "source_type", "url"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_audio_block(
+ url=block["url"],
+ mime_type=block.get("mime_type"),
+ id=block["id"],
+ **extras,
+ )
+
+ # Don't construct with an ID if not present in original block
+ v1_audio_url: types.AudioContentBlock = types.AudioContentBlock(
+ type="audio", url=block["url"]
+ )
+ if block.get("mime_type"):
+ v1_audio_url["mime_type"] = block["mime_type"]
+
+ v1_audio_url["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_audio_url["extras"][key] = value
+ if v1_audio_url["extras"] == {}:
+ del v1_audio_url["extras"]
+
+ return v1_audio_url
+ if source_type == "base64":
+ # audio-base64
+ known_keys = {"mime_type", "type", "source_type", "data"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_audio_block(
+ base64=block["data"],
+ mime_type=block.get("mime_type"),
+ id=block["id"],
+ **extras,
+ )
+
+ v1_audio_base64: types.AudioContentBlock = types.AudioContentBlock(
+ type="audio", base64=block["data"]
+ )
+ if block.get("mime_type"):
+ v1_audio_base64["mime_type"] = block["mime_type"]
+
+ v1_audio_base64["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_audio_base64["extras"][key] = value
+ if v1_audio_base64["extras"] == {}:
+ del v1_audio_base64["extras"]
+
+ return v1_audio_base64
+ if source_type == "id":
+ # audio-id
+ known_keys = {"type", "source_type", "id"}
+ extras = _extract_v0_extras(block, known_keys)
+ v1_audio_id: types.AudioContentBlock = types.AudioContentBlock(
+ type="audio", file_id=block["id"]
+ )
+
+ v1_audio_id["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_audio_id["extras"][key] = value
+ if v1_audio_id["extras"] == {}:
+ del v1_audio_id["extras"]
+
+ return v1_audio_id
+ elif block.get("type") == "file":
+ source_type = block.get("source_type")
+ if source_type == "url":
+ # file-url
+ known_keys = {"mime_type", "type", "source_type", "url"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_file_block(
+ url=block["url"],
+ mime_type=block.get("mime_type"),
+ id=block["id"],
+ **extras,
+ )
+
+ v1_file_url: types.FileContentBlock = types.FileContentBlock(
+ type="file", url=block["url"]
+ )
+ if block.get("mime_type"):
+ v1_file_url["mime_type"] = block["mime_type"]
+
+ v1_file_url["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_file_url["extras"][key] = value
+ if v1_file_url["extras"] == {}:
+ del v1_file_url["extras"]
+
+ return v1_file_url
+ if source_type == "base64":
+ # file-base64
+ known_keys = {"mime_type", "type", "source_type", "data"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_file_block(
+ base64=block["data"],
+ mime_type=block.get("mime_type"),
+ id=block["id"],
+ **extras,
+ )
+
+ v1_file_base64: types.FileContentBlock = types.FileContentBlock(
+ type="file", base64=block["data"]
+ )
+ if block.get("mime_type"):
+ v1_file_base64["mime_type"] = block["mime_type"]
+
+ v1_file_base64["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_file_base64["extras"][key] = value
+ if v1_file_base64["extras"] == {}:
+ del v1_file_base64["extras"]
+
+ return v1_file_base64
+ if source_type == "id":
+ # file-id
+ known_keys = {"type", "source_type", "id"}
+ extras = _extract_v0_extras(block, known_keys)
+ return types.create_file_block(file_id=block["id"], **extras)
+ if source_type == "text":
+ # file-text
+ known_keys = {"mime_type", "type", "source_type", "url"}
+ extras = _extract_v0_extras(block, known_keys)
+ if "id" in block:
+ return types.create_plaintext_block(
+ # In v0, URL points to the text file content
+ # TODO: attribute this claim
+ text=block["url"],
+ id=block["id"],
+ **extras,
+ )
+
+ v1_file_text: types.PlainTextContentBlock = types.PlainTextContentBlock(
+ type="text-plain", text=block["url"], mime_type="text/plain"
+ )
+ if block.get("mime_type"):
+ v1_file_text["mime_type"] = block["mime_type"]
+
+ v1_file_text["extras"] = {}
+ for key, value in extras.items():
+ if value is not None:
+ v1_file_text["extras"][key] = value
+ if v1_file_text["extras"] == {}:
+ del v1_file_text["extras"]
+
+ return v1_file_text
+
+ # If we can't convert, return the block unchanged
+ return block
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/openai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/openai.py
new file mode 100644
index 0000000000000000000000000000000000000000..627459254c5ea2d59c197047abfeab36f0ab0a07
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/block_translators/openai.py
@@ -0,0 +1,1086 @@
+"""Derivations of standard content blocks from OpenAI content."""
+
+from __future__ import annotations
+
+import json
+import warnings
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+from langchain_core.language_models._utils import (
+ _parse_data_uri,
+ is_openai_data_block,
+)
+from langchain_core.messages import AIMessageChunk
+from langchain_core.messages import content as types
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+
+ from langchain_core.messages import AIMessage
+
+
+def convert_to_openai_image_block(block: dict[str, Any]) -> dict:
+ """Convert `ImageContentBlock` to format expected by OpenAI Chat Completions.
+
+ Args:
+ block: The image content block to convert.
+
+ Raises:
+ ValueError: If required keys are missing.
+ ValueError: If source type is unsupported.
+
+ Returns:
+ The formatted image content block.
+ """
+ if "url" in block:
+ return {
+ "type": "image_url",
+ "image_url": {
+ "url": block["url"],
+ },
+ }
+ if "base64" in block or block.get("source_type") == "base64":
+ if "mime_type" not in block:
+ error_message = "mime_type key is required for base64 data."
+ raise ValueError(error_message)
+ mime_type = block["mime_type"]
+ base64_data = block["data"] if "data" in block else block["base64"]
+ return {
+ "type": "image_url",
+ "image_url": {
+ "url": f"data:{mime_type};base64,{base64_data}",
+ },
+ }
+ error_message = "Unsupported source type. Only 'url' and 'base64' are supported."
+ raise ValueError(error_message)
+
+
+def convert_to_openai_data_block(
+ block: dict, api: Literal["chat/completions", "responses"] = "chat/completions"
+) -> dict:
+ """Format standard data content block to format expected by OpenAI.
+
+ "Standard data content block" can include old-style LangChain v0 blocks
+ (URLContentBlock, Base64ContentBlock, IDContentBlock) or new ones.
+
+ Args:
+ block: The content block to convert.
+ api: The OpenAI API being targeted. Either "chat/completions" or "responses".
+
+ Raises:
+ ValueError: If required keys are missing.
+ ValueError: If file URLs are used with Chat Completions API.
+ ValueError: If block type is unsupported.
+
+ Returns:
+ The formatted content block.
+ """
+ if block["type"] == "image":
+ chat_completions_block = convert_to_openai_image_block(block)
+ if api == "responses":
+ formatted_block = {
+ "type": "input_image",
+ "image_url": chat_completions_block["image_url"]["url"],
+ }
+ if chat_completions_block["image_url"].get("detail"):
+ formatted_block["detail"] = chat_completions_block["image_url"][
+ "detail"
+ ]
+ else:
+ formatted_block = chat_completions_block
+
+ elif block["type"] == "file":
+ if block.get("source_type") == "base64" or "base64" in block:
+ # Handle v0 format (Base64CB): {"source_type": "base64", "data": "...", ...}
+ # Handle v1 format (IDCB): {"base64": "...", ...}
+ base64_data = block["data"] if "source_type" in block else block["base64"]
+ file = {"file_data": f"data:{block['mime_type']};base64,{base64_data}"}
+ if filename := block.get("filename"):
+ file["filename"] = filename
+ elif (extras := block.get("extras")) and ("filename" in extras):
+ file["filename"] = extras["filename"]
+ elif (extras := block.get("metadata")) and ("filename" in extras):
+ # Backward compat
+ file["filename"] = extras["filename"]
+ else:
+ # Can't infer filename; set a placeholder default for compatibility.
+ file["filename"] = "LC_AUTOGENERATED"
+ warnings.warn(
+ "OpenAI may require a filename for file uploads. Specify a filename"
+ " in the content block, e.g.: {'type': 'file', 'mime_type': "
+ "'...', 'base64': '...', 'filename': 'my-file.pdf'}. "
+ "Using placeholder filename 'LC_AUTOGENERATED'.",
+ stacklevel=1,
+ )
+ formatted_block = {"type": "file", "file": file}
+ if api == "responses":
+ formatted_block = {"type": "input_file", **formatted_block["file"]}
+ elif block.get("source_type") == "id" or "file_id" in block:
+ # Handle v0 format (IDContentBlock): {"source_type": "id", "id": "...", ...}
+ # Handle v1 format (IDCB): {"file_id": "...", ...}
+ file_id = block["id"] if "source_type" in block else block["file_id"]
+ formatted_block = {"type": "file", "file": {"file_id": file_id}}
+ if api == "responses":
+ formatted_block = {"type": "input_file", **formatted_block["file"]}
+ elif "url" in block: # Intentionally do not check for source_type="url"
+ if api == "chat/completions":
+ error_msg = "OpenAI Chat Completions does not support file URLs."
+ raise ValueError(error_msg)
+ # Only supported by Responses API; return in that format
+ formatted_block = {"type": "input_file", "file_url": block["url"]}
+ else:
+ error_msg = "Keys base64, url, or file_id required for file blocks."
+ raise ValueError(error_msg)
+
+ elif block["type"] == "audio":
+ if "base64" in block or block.get("source_type") == "base64":
+ # Handle v0 format: {"source_type": "base64", "data": "...", ...}
+ # Handle v1 format: {"base64": "...", ...}
+ base64_data = block["data"] if "source_type" in block else block["base64"]
+ audio_format = block["mime_type"].split("/")[-1]
+ formatted_block = {
+ "type": "input_audio",
+ "input_audio": {"data": base64_data, "format": audio_format},
+ }
+ else:
+ error_msg = "Key base64 is required for audio blocks."
+ raise ValueError(error_msg)
+ else:
+ error_msg = f"Block of type {block['type']} is not supported."
+ raise ValueError(error_msg)
+
+ return formatted_block
+
+
+# v1 / Chat Completions
+def _convert_to_v1_from_chat_completions(
+ message: AIMessage,
+) -> list[types.ContentBlock]:
+ """Mutate a Chat Completions message to v1 format."""
+ content_blocks: list[types.ContentBlock] = []
+ if isinstance(message.content, str):
+ if message.content:
+ content_blocks = [{"type": "text", "text": message.content}]
+ else:
+ content_blocks = []
+
+ for tool_call in message.tool_calls:
+ content_blocks.append(
+ {
+ "type": "tool_call",
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ "id": tool_call.get("id"),
+ }
+ )
+
+ return content_blocks
+
+
+def _convert_to_v1_from_chat_completions_input(
+ content: list[types.ContentBlock],
+) -> list[types.ContentBlock]:
+ """Convert OpenAI Chat Completions format blocks to v1 format.
+
+ During the `content_blocks` parsing process, we wrap blocks not recognized as a v1
+ block as a `'non_standard'` block with the original block stored in the `value`
+ field. This function attempts to unpack those blocks and convert any blocks that
+ might be OpenAI format to v1 ContentBlocks.
+
+ If conversion fails, the block is left as a `'non_standard'` block.
+
+ Args:
+ content: List of content blocks to process.
+
+ Returns:
+ Updated list with OpenAI blocks converted to v1 format.
+ """
+ converted_blocks = []
+ unpacked_blocks: list[dict[str, Any]] = [
+ cast("dict[str, Any]", block)
+ if block.get("type") != "non_standard"
+ else block["value"] # type: ignore[typeddict-item] # this is only non-standard blocks
+ for block in content
+ ]
+ for block in unpacked_blocks:
+ if block.get("type") in {
+ "image_url",
+ "input_audio",
+ "file",
+ } and is_openai_data_block(block):
+ converted_block = _convert_openai_format_to_data_block(block)
+ # If conversion succeeded, use it; otherwise keep as non_standard
+ if (
+ isinstance(converted_block, dict)
+ and converted_block.get("type") in types.KNOWN_BLOCK_TYPES
+ ):
+ converted_blocks.append(cast("types.ContentBlock", converted_block))
+ else:
+ converted_blocks.append({"type": "non_standard", "value": block})
+ elif block.get("type") in types.KNOWN_BLOCK_TYPES:
+ converted_blocks.append(cast("types.ContentBlock", block))
+ else:
+ converted_blocks.append({"type": "non_standard", "value": block})
+
+ return converted_blocks
+
+
+def _convert_to_v1_from_chat_completions_chunk(
+ chunk: AIMessageChunk,
+) -> list[types.ContentBlock]:
+ """Mutate a Chat Completions chunk to v1 format."""
+ content_blocks: list[types.ContentBlock] = []
+ if isinstance(chunk.content, str):
+ if chunk.content:
+ content_blocks = [{"type": "text", "text": chunk.content}]
+ else:
+ content_blocks = []
+
+ if chunk.chunk_position == "last":
+ for tool_call in chunk.tool_calls:
+ content_blocks.append(
+ {
+ "type": "tool_call",
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ "id": tool_call.get("id"),
+ }
+ )
+
+ else:
+ for tool_call_chunk in chunk.tool_call_chunks:
+ tc: types.ToolCallChunk = {
+ "type": "tool_call_chunk",
+ "id": tool_call_chunk.get("id"),
+ "name": tool_call_chunk.get("name"),
+ "args": tool_call_chunk.get("args"),
+ }
+ if (idx := tool_call_chunk.get("index")) is not None:
+ tc["index"] = idx
+ content_blocks.append(tc)
+
+ return content_blocks
+
+
+def _convert_from_v1_to_chat_completions(message: AIMessage) -> AIMessage:
+ """Convert a v1 message to the Chat Completions format."""
+ if isinstance(message.content, list):
+ new_content: list = []
+ for block in message.content:
+ if isinstance(block, dict):
+ block_type = block.get("type")
+ if block_type == "text":
+ # Strip annotations
+ new_content.append({"type": "text", "text": block["text"]})
+ elif block_type in {"reasoning", "tool_call"}:
+ pass
+ else:
+ new_content.append(block)
+ else:
+ new_content.append(block)
+ return message.model_copy(update={"content": new_content})
+
+ return message
+
+
+# Responses
+_FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__"
+
+
+def _convert_from_v03_ai_message(message: AIMessage) -> AIMessage:
+ """Convert v0 AIMessage into `output_version="responses/v1"` format."""
+ # Only update ChatOpenAI v0.3 AIMessages
+ is_chatopenai_v03 = (
+ isinstance(message.content, list)
+ and all(isinstance(b, dict) for b in message.content)
+ ) and (
+ any(
+ item in message.additional_kwargs
+ for item in [
+ "reasoning",
+ "tool_outputs",
+ "refusal",
+ _FUNCTION_CALL_IDS_MAP_KEY,
+ ]
+ )
+ or (
+ isinstance(message.id, str)
+ and message.id.startswith("msg_")
+ and (response_id := message.response_metadata.get("id"))
+ and isinstance(response_id, str)
+ and response_id.startswith("resp_")
+ )
+ )
+ if not is_chatopenai_v03:
+ return message
+
+ content_order = [
+ "reasoning",
+ "code_interpreter_call",
+ "mcp_call",
+ "image_generation_call",
+ "text",
+ "refusal",
+ "function_call",
+ "computer_call",
+ "mcp_list_tools",
+ "mcp_approval_request",
+ # N. B. "web_search_call" and "file_search_call" were not passed back in
+ # in v0.3
+ ]
+
+ # Build a bucket for every known block type
+ buckets: dict[str, list] = {key: [] for key in content_order}
+ unknown_blocks = []
+
+ # Reasoning
+ if reasoning := message.additional_kwargs.get("reasoning"):
+ if "type" not in reasoning:
+ reasoning = {**reasoning, "type": "reasoning"}
+ buckets["reasoning"].append(reasoning)
+
+ # Refusal
+ if refusal := message.additional_kwargs.get("refusal"):
+ buckets["refusal"].append({"type": "refusal", "refusal": refusal})
+
+ # Text
+ for block in message.content:
+ if isinstance(block, dict) and block.get("type") == "text":
+ block_copy = block.copy()
+ if isinstance(message.id, str) and message.id.startswith("msg_"):
+ block_copy["id"] = message.id
+ buckets["text"].append(block_copy)
+ else:
+ unknown_blocks.append(block)
+
+ # Function calls
+ function_call_ids = message.additional_kwargs.get(_FUNCTION_CALL_IDS_MAP_KEY)
+ if (
+ isinstance(message, AIMessageChunk)
+ and len(message.tool_call_chunks) == 1
+ and message.chunk_position != "last"
+ ):
+ # Isolated chunk
+ tool_call_chunk = message.tool_call_chunks[0]
+ function_call = {
+ "type": "function_call",
+ "name": tool_call_chunk.get("name"),
+ "arguments": tool_call_chunk.get("args"),
+ "call_id": tool_call_chunk.get("id"),
+ }
+ if function_call_ids is not None and (
+ id_ := function_call_ids.get(tool_call_chunk.get("id"))
+ ):
+ function_call["id"] = id_
+ buckets["function_call"].append(function_call)
+ else:
+ for tool_call in message.tool_calls:
+ function_call = {
+ "type": "function_call",
+ "name": tool_call["name"],
+ "arguments": json.dumps(tool_call["args"], ensure_ascii=False),
+ "call_id": tool_call["id"],
+ }
+ if function_call_ids is not None and (
+ id_ := function_call_ids.get(tool_call["id"])
+ ):
+ function_call["id"] = id_
+ buckets["function_call"].append(function_call)
+
+ # Tool outputs
+ tool_outputs = message.additional_kwargs.get("tool_outputs", [])
+ for block in tool_outputs:
+ if isinstance(block, dict) and (key := block.get("type")) and key in buckets:
+ buckets[key].append(block)
+ else:
+ unknown_blocks.append(block)
+
+ # Re-assemble the content list in the canonical order
+ new_content = []
+ for key in content_order:
+ new_content.extend(buckets[key])
+ new_content.extend(unknown_blocks)
+
+ new_additional_kwargs = dict(message.additional_kwargs)
+ new_additional_kwargs.pop("reasoning", None)
+ new_additional_kwargs.pop("refusal", None)
+ new_additional_kwargs.pop("tool_outputs", None)
+
+ if "id" in message.response_metadata:
+ new_id = message.response_metadata["id"]
+ else:
+ new_id = message.id
+
+ return message.model_copy(
+ update={
+ "content": new_content,
+ "additional_kwargs": new_additional_kwargs,
+ "id": new_id,
+ },
+ deep=False,
+ )
+
+
+def _convert_openai_format_to_data_block(
+ block: dict,
+) -> types.ContentBlock | dict[Any, Any]:
+ """Convert OpenAI image/audio/file content block to respective v1 multimodal block.
+
+ We expect that the incoming block is verified to be in OpenAI Chat Completions
+ format.
+
+ If parsing fails, passes block through unchanged.
+
+ Mappings (Chat Completions to LangChain v1):
+ - Image -> `ImageContentBlock`
+ - Audio -> `AudioContentBlock`
+ - File -> `FileContentBlock`
+
+ """
+
+ # Extract extra keys to put them in `extras`
+ def _extract_extras(block_dict: dict, known_keys: set[str]) -> dict[str, Any]:
+ """Extract unknown keys from block to preserve as extras."""
+ return {k: v for k, v in block_dict.items() if k not in known_keys}
+
+ # base64-style image block
+ if (block["type"] == "image_url") and (
+ parsed := _parse_data_uri(block["image_url"]["url"])
+ ):
+ known_keys = {"type", "image_url"}
+ extras = _extract_extras(block, known_keys)
+
+ # Also extract extras from nested image_url dict
+ image_url_known_keys = {"url"}
+ image_url_extras = _extract_extras(block["image_url"], image_url_known_keys)
+
+ # Merge extras
+ all_extras = {**extras}
+ for key, value in image_url_extras.items():
+ if key == "detail": # Don't rename
+ all_extras["detail"] = value
+ else:
+ all_extras[f"image_url_{key}"] = value
+
+ return types.create_image_block(
+ # Even though this is labeled as `url`, it can be base64-encoded
+ base64=parsed["data"],
+ mime_type=parsed["mime_type"],
+ **all_extras,
+ )
+
+ # url-style image block
+ if (block["type"] == "image_url") and isinstance(
+ block["image_url"].get("url"), str
+ ):
+ known_keys = {"type", "image_url"}
+ extras = _extract_extras(block, known_keys)
+
+ image_url_known_keys = {"url"}
+ image_url_extras = _extract_extras(block["image_url"], image_url_known_keys)
+
+ all_extras = {**extras}
+ for key, value in image_url_extras.items():
+ if key == "detail": # Don't rename
+ all_extras["detail"] = value
+ else:
+ all_extras[f"image_url_{key}"] = value
+
+ return types.create_image_block(
+ url=block["image_url"]["url"],
+ **all_extras,
+ )
+
+ # base64-style audio block
+ # audio is only represented via raw data, no url or ID option
+ if block["type"] == "input_audio":
+ known_keys = {"type", "input_audio"}
+ extras = _extract_extras(block, known_keys)
+
+ # Also extract extras from nested audio dict
+ audio_known_keys = {"data", "format"}
+ audio_extras = _extract_extras(block["input_audio"], audio_known_keys)
+
+ all_extras = {**extras}
+ for key, value in audio_extras.items():
+ all_extras[f"audio_{key}"] = value
+
+ return types.create_audio_block(
+ base64=block["input_audio"]["data"],
+ mime_type=f"audio/{block['input_audio']['format']}",
+ **all_extras,
+ )
+
+ # id-style file block
+ if block.get("type") == "file" and "file_id" in block.get("file", {}):
+ known_keys = {"type", "file"}
+ extras = _extract_extras(block, known_keys)
+
+ file_known_keys = {"file_id"}
+ file_extras = _extract_extras(block["file"], file_known_keys)
+
+ all_extras = {**extras}
+ for key, value in file_extras.items():
+ all_extras[f"file_{key}"] = value
+
+ return types.create_file_block(
+ file_id=block["file"]["file_id"],
+ **all_extras,
+ )
+
+ # base64-style file block
+ if (block["type"] == "file") and (
+ parsed := _parse_data_uri(block["file"]["file_data"])
+ ):
+ known_keys = {"type", "file"}
+ extras = _extract_extras(block, known_keys)
+
+ file_known_keys = {"file_data", "filename"}
+ file_extras = _extract_extras(block["file"], file_known_keys)
+
+ all_extras = {**extras}
+ for key, value in file_extras.items():
+ all_extras[f"file_{key}"] = value
+
+ filename = block["file"].get("filename")
+ return types.create_file_block(
+ base64=parsed["data"],
+ mime_type="application/pdf",
+ filename=filename,
+ **all_extras,
+ )
+
+ # Escape hatch
+ return block
+
+
+# v1 / Responses
+def _convert_annotation_to_v1(annotation: dict[str, Any]) -> types.Annotation:
+ annotation_type = annotation.get("type")
+
+ if annotation_type == "url_citation":
+ known_fields = {
+ "type",
+ "url",
+ "title",
+ "cited_text",
+ "start_index",
+ "end_index",
+ }
+ url_citation = cast("types.Citation", {})
+ for field in ("end_index", "start_index", "title"):
+ if field in annotation:
+ url_citation[field] = annotation[field]
+ url_citation["type"] = "citation"
+ url_citation["url"] = annotation["url"]
+ for field, value in annotation.items():
+ if field not in known_fields:
+ if "extras" not in url_citation:
+ url_citation["extras"] = {}
+ url_citation["extras"][field] = value
+ return url_citation
+
+ if annotation_type == "file_citation":
+ known_fields = {
+ "type",
+ "title",
+ "cited_text",
+ "start_index",
+ "end_index",
+ "filename",
+ }
+ document_citation: types.Citation = {"type": "citation"}
+ if "filename" in annotation:
+ document_citation["title"] = annotation["filename"]
+ for field, value in annotation.items():
+ if field not in known_fields:
+ if "extras" not in document_citation:
+ document_citation["extras"] = {}
+ document_citation["extras"][field] = value
+
+ return document_citation
+
+ # TODO: standardise container_file_citation?
+ non_standard_annotation: types.NonStandardAnnotation = {
+ "type": "non_standard_annotation",
+ "value": annotation,
+ }
+ return non_standard_annotation
+
+
+def _explode_reasoning(block: dict[str, Any]) -> Iterator[types.ReasoningContentBlock]:
+ if "summary" not in block:
+ yield cast("types.ReasoningContentBlock", block)
+ return
+
+ known_fields = {"type", "reasoning", "id", "index"}
+ unknown_fields = [
+ field for field in block if field != "summary" and field not in known_fields
+ ]
+ if unknown_fields:
+ block["extras"] = {}
+ for field in unknown_fields:
+ block["extras"][field] = block.pop(field)
+
+ if not block["summary"]:
+ # [{'id': 'rs_...', 'summary': [], 'type': 'reasoning', 'index': 0}]
+ block = {k: v for k, v in block.items() if k != "summary"}
+ if "index" in block:
+ meaningful_idx = f"{block['index']}_0"
+ block["index"] = f"lc_rs_{meaningful_idx.encode().hex()}"
+ yield cast("types.ReasoningContentBlock", block)
+ return
+
+ # Common part for every exploded line, except 'summary'
+ common = {k: v for k, v in block.items() if k in known_fields}
+
+ # Optional keys that must appear only in the first exploded item
+ first_only = block.pop("extras", None)
+
+ for idx, part in enumerate(block["summary"]):
+ new_block = dict(common)
+ new_block["reasoning"] = part.get("text", "")
+ if idx == 0 and first_only:
+ new_block.update(first_only)
+ if "index" in new_block:
+ summary_index = part.get("index", 0)
+ meaningful_idx = f"{new_block['index']}_{summary_index}"
+ new_block["index"] = f"lc_rs_{meaningful_idx.encode().hex()}"
+
+ yield cast("types.ReasoningContentBlock", new_block)
+
+
+def _convert_to_v1_from_responses(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert a Responses message to v1 format."""
+
+ def _iter_blocks() -> Iterator[types.ContentBlock]:
+ for raw_block in message.content:
+ if not isinstance(raw_block, dict):
+ continue
+ block = raw_block.copy()
+ block_type = block.get("type")
+
+ if block_type == "text":
+ if "text" not in block:
+ block["text"] = ""
+ if "annotations" in block:
+ block["annotations"] = [
+ _convert_annotation_to_v1(a) for a in block["annotations"]
+ ]
+ if "index" in block:
+ block["index"] = f"lc_txt_{block['index']}"
+ yield cast("types.TextContentBlock", block)
+
+ elif block_type == "reasoning":
+ yield from _explode_reasoning(block)
+
+ elif block_type == "image_generation_call" and (
+ result := block.get("result")
+ ):
+ new_block = {"type": "image", "base64": result}
+ if output_format := block.get("output_format"):
+ new_block["mime_type"] = f"image/{output_format}"
+ if "id" in block:
+ new_block["id"] = block["id"]
+ if "index" in block:
+ new_block["index"] = f"lc_img_{block['index']}"
+ for extra_key in (
+ "status",
+ "background",
+ "output_format",
+ "quality",
+ "revised_prompt",
+ "size",
+ ):
+ if extra_key in block:
+ if "extras" not in new_block:
+ new_block["extras"] = {}
+ new_block["extras"][extra_key] = block[extra_key]
+ yield cast("types.ImageContentBlock", new_block)
+
+ elif block_type == "function_call":
+ tool_call_block: (
+ types.ToolCall | types.InvalidToolCall | types.ToolCallChunk | None
+ ) = None
+ call_id = block.get("call_id", "")
+
+ if (
+ isinstance(message, AIMessageChunk)
+ and len(message.tool_call_chunks) == 1
+ and message.chunk_position != "last"
+ ):
+ tool_call_block = message.tool_call_chunks[0].copy() # type: ignore[assignment]
+ elif call_id:
+ for tool_call in message.tool_calls or []:
+ if tool_call.get("id") == call_id:
+ tool_call_block = {
+ "type": "tool_call",
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ "id": tool_call.get("id"),
+ }
+ break
+ else:
+ for invalid_tool_call in message.invalid_tool_calls or []:
+ if invalid_tool_call.get("id") == call_id:
+ tool_call_block = invalid_tool_call.copy()
+ break
+ if tool_call_block:
+ if "id" in block:
+ if "extras" not in tool_call_block:
+ tool_call_block["extras"] = {}
+ tool_call_block["extras"]["item_id"] = block["id"]
+ if "index" in block:
+ tool_call_block["index"] = f"lc_tc_{block['index']}"
+ for extra_key in ("status", "namespace"):
+ if extra_key in block:
+ if "extras" not in tool_call_block:
+ tool_call_block["extras"] = {}
+ tool_call_block["extras"][extra_key] = block[extra_key]
+ yield tool_call_block
+
+ elif block_type == "web_search_call":
+ web_search_call = {
+ "type": "server_tool_call",
+ "name": "web_search",
+ "args": {},
+ "id": block["id"],
+ }
+ if "index" in block:
+ web_search_call["index"] = f"lc_wsc_{block['index']}"
+
+ sources: dict[str, Any] | None = None
+ if "action" in block and isinstance(block["action"], dict):
+ if "sources" in block["action"]:
+ sources = block["action"]["sources"]
+ web_search_call["args"] = {
+ k: v for k, v in block["action"].items() if k != "sources"
+ }
+ for key in block:
+ if key not in {"type", "id", "action", "status", "index"}:
+ web_search_call[key] = block[key]
+
+ yield cast("types.ServerToolCall", web_search_call)
+
+ # If .content already has web_search_result, don't add
+ if not any(
+ isinstance(other_block, dict)
+ and other_block.get("type") == "web_search_result"
+ and other_block.get("id") == block["id"]
+ for other_block in message.content
+ ):
+ web_search_result = {
+ "type": "server_tool_result",
+ "tool_call_id": block["id"],
+ }
+ if sources:
+ web_search_result["output"] = {"sources": sources}
+
+ status = block.get("status")
+ if status == "failed":
+ web_search_result["status"] = "error"
+ elif status == "completed":
+ web_search_result["status"] = "success"
+ elif status:
+ web_search_result["extras"] = {"status": status}
+ if "index" in block and isinstance(block["index"], int):
+ web_search_result["index"] = f"lc_wsr_{block['index'] + 1}"
+ yield cast("types.ServerToolResult", web_search_result)
+
+ elif block_type == "file_search_call":
+ file_search_call = {
+ "type": "server_tool_call",
+ "name": "file_search",
+ "id": block["id"],
+ "args": {"queries": block.get("queries", [])},
+ }
+ if "index" in block:
+ file_search_call["index"] = f"lc_fsc_{block['index']}"
+
+ for key in block:
+ if key not in {
+ "type",
+ "id",
+ "queries",
+ "results",
+ "status",
+ "index",
+ }:
+ file_search_call[key] = block[key]
+
+ yield cast("types.ServerToolCall", file_search_call)
+
+ file_search_result = {
+ "type": "server_tool_result",
+ "tool_call_id": block["id"],
+ }
+ if file_search_output := block.get("results"):
+ file_search_result["output"] = file_search_output
+
+ status = block.get("status")
+ if status == "failed":
+ file_search_result["status"] = "error"
+ elif status == "completed":
+ file_search_result["status"] = "success"
+ elif status:
+ file_search_result["extras"] = {"status": status}
+ if "index" in block and isinstance(block["index"], int):
+ file_search_result["index"] = f"lc_fsr_{block['index'] + 1}"
+ yield cast("types.ServerToolResult", file_search_result)
+
+ elif block_type == "code_interpreter_call":
+ code_interpreter_call = {
+ "type": "server_tool_call",
+ "name": "code_interpreter",
+ "id": block["id"],
+ }
+ if "code" in block:
+ code_interpreter_call["args"] = {"code": block["code"]}
+ if "index" in block:
+ code_interpreter_call["index"] = f"lc_cic_{block['index']}"
+ known_fields = {
+ "type",
+ "id",
+ "outputs",
+ "status",
+ "code",
+ "extras",
+ "index",
+ }
+ for key in block:
+ if key not in known_fields:
+ if "extras" not in code_interpreter_call:
+ code_interpreter_call["extras"] = {}
+ code_interpreter_call["extras"][key] = block[key]
+
+ code_interpreter_result = {
+ "type": "server_tool_result",
+ "tool_call_id": block["id"],
+ }
+ if "outputs" in block:
+ code_interpreter_result["output"] = block["outputs"]
+
+ status = block.get("status")
+ if status == "failed":
+ code_interpreter_result["status"] = "error"
+ elif status == "completed":
+ code_interpreter_result["status"] = "success"
+ elif status:
+ code_interpreter_result["extras"] = {"status": status}
+ if "index" in block and isinstance(block["index"], int):
+ code_interpreter_result["index"] = f"lc_cir_{block['index'] + 1}"
+
+ yield cast("types.ServerToolCall", code_interpreter_call)
+ yield cast("types.ServerToolResult", code_interpreter_result)
+
+ elif block_type == "mcp_call":
+ mcp_call = {
+ "type": "server_tool_call",
+ "name": "remote_mcp",
+ "id": block["id"],
+ }
+ if (arguments := block.get("arguments")) and isinstance(arguments, str):
+ try:
+ mcp_call["args"] = json.loads(block["arguments"])
+ except json.JSONDecodeError:
+ mcp_call["extras"] = {"arguments": arguments}
+ if "name" in block:
+ if "extras" not in mcp_call:
+ mcp_call["extras"] = {}
+ mcp_call["extras"]["tool_name"] = block["name"]
+ if "server_label" in block:
+ if "extras" not in mcp_call:
+ mcp_call["extras"] = {}
+ mcp_call["extras"]["server_label"] = block["server_label"]
+ if "index" in block:
+ mcp_call["index"] = f"lc_mcp_{block['index']}"
+ known_fields = {
+ "type",
+ "id",
+ "arguments",
+ "name",
+ "server_label",
+ "output",
+ "error",
+ "extras",
+ "index",
+ }
+ for key in block:
+ if key not in known_fields:
+ if "extras" not in mcp_call:
+ mcp_call["extras"] = {}
+ mcp_call["extras"][key] = block[key]
+
+ yield cast("types.ServerToolCall", mcp_call)
+
+ mcp_result = {
+ "type": "server_tool_result",
+ "tool_call_id": block["id"],
+ }
+ if mcp_output := block.get("output"):
+ mcp_result["output"] = mcp_output
+
+ error = block.get("error")
+ if error:
+ if "extras" not in mcp_result:
+ mcp_result["extras"] = {}
+ mcp_result["extras"]["error"] = error
+ mcp_result["status"] = "error"
+ else:
+ mcp_result["status"] = "success"
+
+ if "index" in block and isinstance(block["index"], int):
+ mcp_result["index"] = f"lc_mcpr_{block['index'] + 1}"
+ yield cast("types.ServerToolResult", mcp_result)
+
+ elif block_type == "mcp_list_tools":
+ mcp_list_tools_call = {
+ "type": "server_tool_call",
+ "name": "mcp_list_tools",
+ "args": {},
+ "id": block["id"],
+ }
+ if "server_label" in block:
+ mcp_list_tools_call["extras"] = {}
+ mcp_list_tools_call["extras"]["server_label"] = block[
+ "server_label"
+ ]
+ if "index" in block:
+ mcp_list_tools_call["index"] = f"lc_mlt_{block['index']}"
+ known_fields = {
+ "type",
+ "id",
+ "name",
+ "server_label",
+ "tools",
+ "error",
+ "extras",
+ "index",
+ }
+ for key in block:
+ if key not in known_fields:
+ if "extras" not in mcp_list_tools_call:
+ mcp_list_tools_call["extras"] = {}
+ mcp_list_tools_call["extras"][key] = block[key]
+
+ yield cast("types.ServerToolCall", mcp_list_tools_call)
+
+ mcp_list_tools_result = {
+ "type": "server_tool_result",
+ "tool_call_id": block["id"],
+ }
+ if mcp_output := block.get("tools"):
+ mcp_list_tools_result["output"] = mcp_output
+
+ error = block.get("error")
+ if error:
+ if "extras" not in mcp_list_tools_result:
+ mcp_list_tools_result["extras"] = {}
+ mcp_list_tools_result["extras"]["error"] = error
+ mcp_list_tools_result["status"] = "error"
+ else:
+ mcp_list_tools_result["status"] = "success"
+
+ if "index" in block and isinstance(block["index"], int):
+ mcp_list_tools_result["index"] = f"lc_mltr_{block['index'] + 1}"
+ yield cast("types.ServerToolResult", mcp_list_tools_result)
+
+ elif (
+ block_type == "tool_search_call" and block.get("execution") == "server"
+ ):
+ tool_search_call: dict[str, Any] = {
+ "type": "server_tool_call",
+ "name": "tool_search",
+ "id": block["id"],
+ "args": block.get("arguments", {}),
+ }
+ if "index" in block:
+ tool_search_call["index"] = f"lc_tsc_{block['index']}"
+ extras: dict[str, Any] = {}
+ known = {"type", "id", "arguments", "index"}
+ for key in block:
+ if key not in known:
+ extras[key] = block[key]
+ if extras:
+ tool_search_call["extras"] = extras
+ yield cast("types.ServerToolCall", tool_search_call)
+
+ elif (
+ block_type == "tool_search_output"
+ and block.get("execution") == "server"
+ ):
+ tool_search_output: dict[str, Any] = {
+ "type": "server_tool_result",
+ "tool_call_id": block["id"],
+ "output": {"tools": block.get("tools", [])},
+ }
+ status = block.get("status")
+ if status == "failed":
+ tool_search_output["status"] = "error"
+ elif status == "completed":
+ tool_search_output["status"] = "success"
+ if "index" in block and isinstance(block["index"], int):
+ tool_search_output["index"] = f"lc_tso_{block['index']}"
+ extras_out: dict[str, Any] = {"name": "tool_search"}
+ known_out = {"type", "id", "status", "tools", "index"}
+ for key in block:
+ if key not in known_out:
+ extras_out[key] = block[key]
+ if extras_out:
+ tool_search_output["extras"] = extras_out
+ yield cast("types.ServerToolResult", tool_search_output)
+
+ elif block_type in types.KNOWN_BLOCK_TYPES:
+ yield cast("types.ContentBlock", block)
+ else:
+ new_block = {"type": "non_standard", "value": block}
+ if "index" in new_block["value"]:
+ new_block["index"] = f"lc_ns_{new_block['value'].pop('index')}"
+ yield cast("types.NonStandardContentBlock", new_block)
+
+ return list(_iter_blocks())
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with OpenAI content.
+
+ Args:
+ message: The message to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ if isinstance(message.content, str):
+ return _convert_to_v1_from_chat_completions(message)
+ message = _convert_from_v03_ai_message(message)
+ return _convert_to_v1_from_responses(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message chunk with OpenAI content.
+
+ Args:
+ message: The message chunk to translate.
+
+ Returns:
+ The derived content blocks.
+ """
+ if isinstance(message.content, str):
+ return _convert_to_v1_from_chat_completions_chunk(message)
+ message = _convert_from_v03_ai_message(message) # type: ignore[assignment]
+ return _convert_to_v1_from_responses(message)
+
+
+def _register_openai_translator() -> None:
+ """Register the OpenAI translator with the central registry.
+
+ Run automatically when the module is imported.
+ """
+ from langchain_core.messages.block_translators import ( # noqa: PLC0415
+ register_translator,
+ )
+
+ register_translator("openai", translate_content, translate_content_chunk)
+
+
+_register_openai_translator()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/chat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/chat.py
new file mode 100644
index 0000000000000000000000000000000000000000..6786efcacf4f349225cd98766366361565e255d8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/chat.py
@@ -0,0 +1,64 @@
+"""Chat Message."""
+
+from typing import Any, Literal
+
+from typing_extensions import override
+
+from langchain_core.messages.base import (
+ BaseMessage,
+ BaseMessageChunk,
+ merge_content,
+)
+from langchain_core.utils._merge import merge_dicts
+
+
+class ChatMessage(BaseMessage):
+ """Message that can be assigned an arbitrary speaker (i.e. role)."""
+
+ role: str
+ """The speaker / role of the Message."""
+
+ type: Literal["chat"] = "chat"
+ """The type of the message (used during serialization)."""
+
+
+class ChatMessageChunk(ChatMessage, BaseMessageChunk):
+ """Chat Message chunk."""
+
+ # Ignoring mypy re-assignment here since we're overriding the value
+ # to make sure that the chunk variant can be discriminated from the
+ # non-chunk variant.
+ type: Literal["ChatMessageChunk"] = "ChatMessageChunk" # type: ignore[assignment]
+ """The type of the message (used during serialization)."""
+
+ @override
+ def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
+ if isinstance(other, ChatMessageChunk):
+ if self.role != other.role:
+ msg = "Cannot concatenate ChatMessageChunks with different roles."
+ raise ValueError(msg)
+
+ return self.__class__(
+ role=self.role,
+ content=merge_content(self.content, other.content),
+ additional_kwargs=merge_dicts(
+ self.additional_kwargs, other.additional_kwargs
+ ),
+ response_metadata=merge_dicts(
+ self.response_metadata, other.response_metadata
+ ),
+ id=self.id,
+ )
+ if isinstance(other, BaseMessageChunk):
+ return self.__class__(
+ role=self.role,
+ content=merge_content(self.content, other.content),
+ additional_kwargs=merge_dicts(
+ self.additional_kwargs, other.additional_kwargs
+ ),
+ response_metadata=merge_dicts(
+ self.response_metadata, other.response_metadata
+ ),
+ id=self.id,
+ )
+ return super().__add__(other)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/content.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/content.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a02139d5bbae2056051a5ab1796187bd50d7136
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/content.py
@@ -0,0 +1,1488 @@
+"""Standard, multimodal content blocks for Large Language Model I/O.
+
+This module provides standardized data structures for representing inputs to and outputs
+from LLMs. The core abstraction is the **Content Block**, a `TypedDict`.
+
+**Rationale**
+
+Different LLM providers use distinct and incompatible API schemas. This module provides
+a unified, provider-agnostic format to facilitate these interactions. A message to or
+from a model is simply a list of content blocks, allowing for the natural interleaving
+of text, images, and other content in a single ordered sequence.
+
+An adapter for a specific provider is responsible for translating this standard list of
+blocks into the format required by its API.
+
+**Extensibility**
+
+Data **not yet mapped** to a standard block may be represented using the
+`NonStandardContentBlock`, which allows for provider-specific data to be included
+without losing the benefits of type checking and validation.
+
+Furthermore, provider-specific fields **within** a standard block are fully supported
+by default in the `extras` field of each block. This allows for additional metadata
+to be included without breaking the standard structure. For example, Google's thought
+signature:
+
+```python
+AIMessage(
+ content=[
+ {
+ "type": "text",
+ "text": "J'adore la programmation.",
+ "extras": {"signature": "EpoWCpc..."}, # Thought signature
+ }
+ ], ...
+)
+```
+
+
+!!! note
+
+ Following widespread adoption of [PEP 728](https://peps.python.org/pep-0728/), we
+ intend to add `extra_items=Any` as a param to Content Blocks. This will signify to
+ type checkers that additional provider-specific fields are allowed outside of the
+ `extras` field, and that will become the new standard approach to adding
+ provider-specific metadata.
+
+ ??? note
+
+ **Example with PEP 728 provider-specific fields:**
+
+ ```python
+ # Content block definition
+ # NOTE: `extra_items=Any`
+ class TextContentBlock(TypedDict, extra_items=Any):
+ type: Literal["text"]
+ id: NotRequired[str]
+ text: str
+ annotations: NotRequired[list[Annotation]]
+ index: NotRequired[int]
+ ```
+
+ ```python
+ from langchain_core.messages.content import TextContentBlock
+
+ # Create a text content block with provider-specific fields
+ my_block: TextContentBlock = {
+ # Add required fields
+ "type": "text",
+ "text": "Hello, world!",
+ # Additional fields not specified in the TypedDict
+ # These are valid with PEP 728 and are typed as Any
+ "openai_metadata": {"model": "gpt-4", "temperature": 0.7},
+ "anthropic_usage": {"input_tokens": 10, "output_tokens": 20},
+ "custom_field": "any value",
+ }
+
+ # Mutating an existing block to add provider-specific fields
+ openai_data = my_block["openai_metadata"] # Type: Any
+ ```
+
+**Example Usage**
+
+```python
+# Direct construction
+from langchain_core.messages.content import TextContentBlock, ImageContentBlock
+
+multimodal_message: AIMessage(
+ content_blocks=[
+ TextContentBlock(type="text", text="What is shown in this image?"),
+ ImageContentBlock(
+ type="image",
+ url="https://www.langchain.com/images/brand/langchain_logo_text_w_white.png",
+ mime_type="image/png",
+ ),
+ ]
+)
+
+# Using factories
+from langchain_core.messages.content import create_text_block, create_image_block
+
+multimodal_message: AIMessage(
+ content=[
+ create_text_block("What is shown in this image?"),
+ create_image_block(
+ url="https://www.langchain.com/images/brand/langchain_logo_text_w_white.png",
+ mime_type="image/png",
+ ),
+ ]
+)
+```
+
+Factory functions offer benefits such as:
+
+- Automatic ID generation (when not provided)
+- No need to manually specify the `type` field
+"""
+
+from typing import Any, Literal, get_args, get_type_hints
+
+from typing_extensions import NotRequired, TypedDict
+
+from langchain_core.utils.utils import ensure_id
+
+
+class Citation(TypedDict):
+ """Annotation for citing data from a document.
+
+ !!! note
+
+ `start`/`end` indices refer to the **response text**,
+ not the source text. This means that the indices are relative to the model's
+ response, not the original document (as specified in the `url`).
+
+ !!! note "Factory function"
+
+ `create_citation` may also be used as a factory to create a `Citation`.
+ Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["citation"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ url: NotRequired[str]
+ """URL of the document source."""
+
+ title: NotRequired[str]
+ """Source document title.
+
+ For example, the page title for a web page or the title of a paper.
+ """
+
+ start_index: NotRequired[int]
+ """Start index of the **response text** (`TextContentBlock.text`)."""
+
+ end_index: NotRequired[int]
+ """End index of the **response text** (`TextContentBlock.text`)"""
+
+ cited_text: NotRequired[str]
+ """Excerpt of source text being cited."""
+
+ # NOTE: not including spans for the raw document text (such as `text_start_index`
+ # and `text_end_index`) as this is not currently supported by any provider. The
+ # thinking is that the `cited_text` should be sufficient for most use cases, and it
+ # is difficult to reliably extract spans from the raw document text across file
+ # formats or encoding schemes.
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class NonStandardAnnotation(TypedDict):
+ """Provider-specific annotation format."""
+
+ type: Literal["non_standard_annotation"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ value: dict[str, Any]
+ """Provider-specific annotation data."""
+
+
+Annotation = Citation | NonStandardAnnotation
+"""A union of all defined `Annotation` types."""
+
+
+class TextContentBlock(TypedDict):
+ """Text output from a LLM.
+
+ This typically represents the main text content of a message, such as the response
+ from a language model or the text of a user message.
+
+ !!! note "Factory function"
+
+ `create_text_block` may also be used as a factory to create a
+ `TextContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["text"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ text: str
+ """Block text."""
+
+ annotations: NotRequired[list[Annotation]]
+ """`Citation`s and other annotations."""
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class ToolCall(TypedDict):
+ """Represents an AI's request to call a tool.
+
+ Example:
+ ```python
+ {"name": "foo", "args": {"a": 1}, "id": "123"}
+ ```
+
+ This represents a request to call the tool named "foo" with arguments {"a": 1}
+ and an identifier of "123".
+
+ !!! note "Factory function"
+
+ `create_tool_call` may also be used as a factory to create a
+ `ToolCall`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["tool_call"]
+ """Used for discrimination."""
+
+ id: str | None
+ """An identifier associated with the tool call.
+
+ An identifier is needed to associate a tool call request with a tool
+ call result in events when multiple concurrent tool calls are made.
+ """
+ # TODO: Consider making this NotRequired[str] in the future.
+
+ name: str
+ """The name of the tool to be called."""
+
+ args: dict[str, Any]
+ """The arguments to the tool call."""
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class ToolCallChunk(TypedDict):
+ """A chunk of a tool call (yielded when streaming).
+
+ When merging `ToolCallChunks` (e.g., via `AIMessageChunk.__add__`),
+ all string attributes are concatenated. Chunks are only merged if their
+ values of `index` are equal and not `None`.
+
+ Example:
+ ```python
+ left_chunks = [ToolCallChunk(name="foo", args='{"a":', index=0)]
+ right_chunks = [ToolCallChunk(name=None, args="1}", index=0)]
+
+ (
+ AIMessageChunk(content="", tool_call_chunks=left_chunks)
+ + AIMessageChunk(content="", tool_call_chunks=right_chunks)
+ ).tool_call_chunks == [ToolCallChunk(name="foo", args='{"a":1}', index=0)]
+ ```
+ """
+
+ # TODO: Consider making fields NotRequired[str] in the future.
+
+ type: Literal["tool_call_chunk"]
+ """Used for serialization."""
+
+ id: str | None
+ """An identifier associated with the tool call.
+
+ An identifier is needed to associate a tool call request with a tool
+ call result in events when multiple concurrent tool calls are made.
+ """
+ # TODO: Consider making this NotRequired[str] in the future.
+
+ name: str | None
+ """The name of the tool to be called."""
+
+ args: str | None
+ """The arguments to the tool call."""
+
+ index: NotRequired[int | str]
+ """The index of the tool call in a sequence."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class InvalidToolCall(TypedDict):
+ """Allowance for errors made by LLM.
+
+ Here we add an `error` key to surface errors made during generation
+ (e.g., invalid JSON arguments.)
+ """
+
+ # TODO: Consider making fields NotRequired[str] in the future.
+
+ type: Literal["invalid_tool_call"]
+ """Used for discrimination."""
+
+ id: str | None
+ """An identifier associated with the tool call.
+
+ An identifier is needed to associate a tool call request with a tool
+ call result in events when multiple concurrent tool calls are made.
+ """
+ # TODO: Consider making this NotRequired[str] in the future.
+
+ name: str | None
+ """The name of the tool to be called."""
+
+ args: str | None
+ """The arguments to the tool call."""
+
+ error: str | None
+ """An error message associated with the tool call."""
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class ServerToolCall(TypedDict):
+ """Tool call that is executed server-side.
+
+ For example: code execution, web search, etc.
+ """
+
+ type: Literal["server_tool_call"]
+ """Used for discrimination."""
+
+ id: str
+ """An identifier associated with the tool call."""
+
+ name: str
+ """The name of the tool to be called."""
+
+ args: dict[str, Any]
+ """The arguments to the tool call."""
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class ServerToolCallChunk(TypedDict):
+ """A chunk of a server-side tool call (yielded when streaming)."""
+
+ type: Literal["server_tool_call_chunk"]
+ """Used for discrimination."""
+
+ name: NotRequired[str]
+ """The name of the tool to be called."""
+
+ args: NotRequired[str]
+ """JSON substring of the arguments to the tool call."""
+
+ id: NotRequired[str]
+ """Unique identifier for this server tool call chunk.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class ServerToolResult(TypedDict):
+ """Result of a server-side tool call."""
+
+ type: Literal["server_tool_result"]
+ """Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this server tool result.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ tool_call_id: str
+ """ID of the corresponding server tool call."""
+
+ status: Literal["success", "error"]
+ """Execution status of the server-side tool."""
+
+ output: NotRequired[Any]
+ """Output of the executed tool."""
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+class ReasoningContentBlock(TypedDict):
+ """Reasoning output from a LLM.
+
+ !!! note "Factory function"
+
+ `create_reasoning_block` may also be used as a factory to create a
+ `ReasoningContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["reasoning"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ reasoning: NotRequired[str]
+ """Reasoning text.
+
+ Either the thought summary or the raw reasoning text itself.
+
+ Often parsed from `` tags in the model's response.
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata."""
+
+
+# Note: `title` and `context` are fields that could be used to provide additional
+# information about the file, such as a description or summary of its content.
+# E.g. with Claude, you can provide a context for a file which is passed to the model.
+class ImageContentBlock(TypedDict):
+ """Image data.
+
+ !!! note "Factory function"
+
+ `create_image_block` may also be used as a factory to create an
+ `ImageContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["image"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ file_id: NotRequired[str]
+ """Reference to the image in an external file storage system.
+
+ For example, OpenAI or Anthropic's Files API.
+ """
+
+ mime_type: NotRequired[str]
+ """MIME type of the image.
+
+ Required for base64 data.
+
+ [Examples from IANA](https://www.iana.org/assignments/media-types/media-types.xhtml#image)
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ url: NotRequired[str]
+ """URL of the image."""
+
+ base64: NotRequired[str]
+ """Data as a base64 string."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata. This shouldn't be used for the image data itself."""
+
+
+class VideoContentBlock(TypedDict):
+ """Video data.
+
+ !!! note "Factory function"
+
+ `create_video_block` may also be used as a factory to create a
+ `VideoContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["video"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ file_id: NotRequired[str]
+ """Reference to the video in an external file storage system.
+
+ For example, OpenAI or Anthropic's Files API.
+ """
+
+ mime_type: NotRequired[str]
+ """MIME type of the video.
+
+ Required for base64 data.
+
+ [Examples from IANA](https://www.iana.org/assignments/media-types/media-types.xhtml#video)
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ url: NotRequired[str]
+ """URL of the video."""
+
+ base64: NotRequired[str]
+ """Data as a base64 string."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata. This shouldn't be used for the video data itself."""
+
+
+class AudioContentBlock(TypedDict):
+ """Audio data.
+
+ !!! note "Factory function"
+
+ `create_audio_block` may also be used as a factory to create an
+ `AudioContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["audio"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ file_id: NotRequired[str]
+ """Reference to the audio file in an external file storage system.
+
+ For example, OpenAI or Anthropic's Files API.
+ """
+
+ mime_type: NotRequired[str]
+ """MIME type of the audio.
+
+ Required for base64 data.
+
+ [Examples from IANA](https://www.iana.org/assignments/media-types/media-types.xhtml#audio)
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ url: NotRequired[str]
+ """URL of the audio."""
+
+ base64: NotRequired[str]
+ """Data as a base64 string."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata. This shouldn't be used for the audio data itself."""
+
+
+class PlainTextContentBlock(TypedDict):
+ """Plaintext data (e.g., from a `.txt` or `.md` document).
+
+ !!! note
+
+ A `PlainTextContentBlock` existed in `langchain-core<1.0.0`. Although the
+ name has carried over, the structure has changed significantly. The only shared
+ keys between the old and new versions are `type` and `text`, though the
+ `type` value has changed from `'text'` to `'text-plain'`.
+
+ !!! note
+
+ Title and context are optional fields that may be passed to the model. See
+ Anthropic [example](https://platform.claude.com/docs/en/build-with-claude/citations#citable-vs-non-citable-content).
+
+ !!! note "Factory function"
+
+ `create_plaintext_block` may also be used as a factory to create a
+ `PlainTextContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["text-plain"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ file_id: NotRequired[str]
+ """Reference to the plaintext file in an external file storage system.
+
+ For example, OpenAI or Anthropic's Files API.
+ """
+
+ mime_type: Literal["text/plain"]
+ """MIME type of the file.
+
+ Required for base64 data.
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ url: NotRequired[str]
+ """URL of the plaintext."""
+
+ base64: NotRequired[str]
+ """Data as a base64 string."""
+
+ text: NotRequired[str]
+ """Plaintext content. This is optional if the data is provided as base64."""
+
+ title: NotRequired[str]
+ """Title of the text data, e.g., the title of a document."""
+
+ context: NotRequired[str]
+ """Context for the text, e.g., a description or summary of the text's content."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata. This shouldn't be used for the data itself."""
+
+
+class FileContentBlock(TypedDict):
+ """File data that doesn't fit into other multimodal block types.
+
+ This block is intended for files that are not images, audio, or plaintext. For
+ example, it can be used for PDFs, Word documents, etc.
+
+ If the file is an image, audio, or plaintext, you should use the corresponding
+ content block type (e.g., `ImageContentBlock`, `AudioContentBlock`,
+ `PlainTextContentBlock`).
+
+ !!! note "Factory function"
+
+ `create_file_block` may also be used as a factory to create a
+ `FileContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["file"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Used for tracking and referencing specific blocks (e.g., during streaming).
+
+ Not to be confused with `file_id`, which references an external file in a
+ storage system.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ file_id: NotRequired[str]
+ """Reference to the file in an external file storage system.
+
+ For example, a file ID from OpenAI's Files API or another cloud storage provider.
+ This is distinct from `id`, which identifies the content block itself.
+ """
+
+ mime_type: NotRequired[str]
+ """MIME type of the file.
+
+ Required for base64 data.
+
+ [Examples from IANA](https://www.iana.org/assignments/media-types/media-types.xhtml)
+ """
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+ url: NotRequired[str]
+ """URL of the file."""
+
+ base64: NotRequired[str]
+ """Data as a base64 string."""
+
+ extras: NotRequired[dict[str, Any]]
+ """Provider-specific metadata. This shouldn't be used for the file data itself."""
+
+
+# Future modalities to consider:
+# - 3D models
+# - Tabular data
+
+
+class NonStandardContentBlock(TypedDict):
+ """Provider-specific content data.
+
+ This block contains data for which there is not yet a standard type.
+
+ The purpose of this block should be to simply hold a provider-specific payload.
+ If a provider's non-standard output includes reasoning and tool calls, it should be
+ the adapter's job to parse that payload and emit the corresponding standard
+ `ReasoningContentBlock` and `ToolCalls`.
+
+ Has no `extras` field, as provider-specific data should be included in the
+ `value` field.
+
+ !!! note "Factory function"
+
+ `create_non_standard_block` may also be used as a factory to create a
+ `NonStandardContentBlock`. Benefits include:
+
+ * Automatic ID generation (when not provided)
+ * Required arguments strictly validated at creation time
+ """
+
+ type: Literal["non_standard"]
+ """Type of the content block. Used for discrimination."""
+
+ id: NotRequired[str]
+ """Unique identifier for this content block.
+
+ Either:
+
+ - Generated by the provider
+ - Generated by LangChain upon creation (`UUID4` prefixed with `'lc_'`))
+ """
+
+ value: dict[str, Any]
+ """Provider-specific content data."""
+
+ index: NotRequired[int | str]
+ """Index of block in aggregate response. Used during streaming."""
+
+
+# --- Aliases ---
+DataContentBlock = (
+ ImageContentBlock
+ | VideoContentBlock
+ | AudioContentBlock
+ | PlainTextContentBlock
+ | FileContentBlock
+)
+"""A union of all defined multimodal data `ContentBlock` types."""
+
+ToolContentBlock = (
+ ToolCall | ToolCallChunk | ServerToolCall | ServerToolCallChunk | ServerToolResult
+)
+
+ContentBlock = (
+ TextContentBlock
+ | InvalidToolCall
+ | ReasoningContentBlock
+ | NonStandardContentBlock
+ | DataContentBlock
+ | ToolContentBlock
+)
+"""A union of all defined `ContentBlock` types and aliases."""
+
+
+KNOWN_BLOCK_TYPES = {
+ # Text output
+ "text",
+ "reasoning",
+ # Tools
+ "tool_call",
+ "invalid_tool_call",
+ "tool_call_chunk",
+ # Multimodal data
+ "image",
+ "audio",
+ "file",
+ "text-plain",
+ "video",
+ # Server-side tool calls
+ "server_tool_call",
+ "server_tool_call_chunk",
+ "server_tool_result",
+ # Catch-all
+ "non_standard",
+ # citation and non_standard_annotation intentionally omitted
+}
+"""These are block types known to `langchain-core >= 1.0.0`.
+
+If a block has a type not in this set, it is considered to be provider-specific.
+"""
+
+
+def _get_data_content_block_types() -> tuple[str, ...]:
+ """Get type literals from DataContentBlock union members dynamically.
+
+ Example: ("image", "video", "audio", "text-plain", "file")
+
+ Note that old style multimodal blocks type literals with new style blocks.
+ Specifically, "image", "audio", and "file".
+
+ See the docstring of `_normalize_messages` in `language_models._utils` for details.
+ """
+ data_block_types = []
+
+ for block_type in get_args(DataContentBlock):
+ hints = get_type_hints(block_type)
+ if "type" in hints:
+ type_annotation = hints["type"]
+ if hasattr(type_annotation, "__args__"):
+ # This is a Literal type, get the literal value
+ literal_value = type_annotation.__args__[0]
+ data_block_types.append(literal_value)
+
+ return tuple(data_block_types)
+
+
+def is_data_content_block(block: dict) -> bool:
+ """Check if the provided content block is a data content block.
+
+ Returns True for both v0 (old-style) and v1 (new-style) multimodal data blocks.
+
+ Args:
+ block: The content block to check.
+
+ Returns:
+ `True` if the content block is a data content block, `False` otherwise.
+ """
+ if block.get("type") not in _get_data_content_block_types():
+ return False
+
+ if any(key in block for key in ("url", "base64", "file_id", "text")):
+ # Type is valid and at least one data field is present
+ # (Accepts old-style image and audio URLContentBlock)
+
+ # 'text' is checked to support v0 PlainTextContentBlock types
+ # We must guard against new style TextContentBlock which also has 'text' `type`
+ # by ensuring the presence of `source_type`
+ if block["type"] == "text" and "source_type" not in block: # noqa: SIM103 # This is more readable
+ return False
+
+ return True
+
+ if "source_type" in block:
+ # Old-style content blocks had possible types of 'image', 'audio', and 'file'
+ # which is not captured in the prior check
+ source_type = block["source_type"]
+ if (source_type == "url" and "url" in block) or (
+ source_type == "base64" and "data" in block
+ ):
+ return True
+ if (source_type == "id" and "id" in block) or (
+ source_type == "text" and "url" in block
+ ):
+ return True
+
+ return False
+
+
+def create_text_block(
+ text: str,
+ *,
+ id: str | None = None,
+ annotations: list[Annotation] | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> TextContentBlock:
+ """Create a `TextContentBlock`.
+
+ Args:
+ text: The text content of the block.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ annotations: `Citation`s and other annotations for the text.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `TextContentBlock`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ block = TextContentBlock(
+ type="text",
+ text=text,
+ id=ensure_id(id),
+ )
+ if annotations is not None:
+ block["annotations"] = annotations
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_image_block(
+ *,
+ url: str | None = None,
+ base64: str | None = None,
+ file_id: str | None = None,
+ mime_type: str | None = None,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> ImageContentBlock:
+ """Create an `ImageContentBlock`.
+
+ Args:
+ url: URL of the image.
+ base64: Base64-encoded image data.
+ file_id: ID of the image file from a file storage system.
+ mime_type: MIME type of the image.
+
+ Required for base64 data.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `ImageContentBlock`.
+
+ Raises:
+ ValueError: If no image source is provided or if `base64` is used without
+ `mime_type`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ if not any([url, base64, file_id]):
+ msg = "Must provide one of: url, base64, or file_id"
+ raise ValueError(msg)
+
+ block = ImageContentBlock(type="image", id=ensure_id(id))
+
+ if url is not None:
+ block["url"] = url
+ if base64 is not None:
+ block["base64"] = base64
+ if file_id is not None:
+ block["file_id"] = file_id
+ if mime_type is not None:
+ block["mime_type"] = mime_type
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_video_block(
+ *,
+ url: str | None = None,
+ base64: str | None = None,
+ file_id: str | None = None,
+ mime_type: str | None = None,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> VideoContentBlock:
+ """Create a `VideoContentBlock`.
+
+ Args:
+ url: URL of the video.
+ base64: Base64-encoded video data.
+ file_id: ID of the video file from a file storage system.
+ mime_type: MIME type of the video.
+
+ Required for base64 data.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `VideoContentBlock`.
+
+ Raises:
+ ValueError: If no video source is provided or if `base64` is used without
+ `mime_type`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ if not any([url, base64, file_id]):
+ msg = "Must provide one of: url, base64, or file_id"
+ raise ValueError(msg)
+
+ if base64 and not mime_type:
+ msg = "mime_type is required when using base64 data"
+ raise ValueError(msg)
+
+ block = VideoContentBlock(type="video", id=ensure_id(id))
+
+ if url is not None:
+ block["url"] = url
+ if base64 is not None:
+ block["base64"] = base64
+ if file_id is not None:
+ block["file_id"] = file_id
+ if mime_type is not None:
+ block["mime_type"] = mime_type
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_audio_block(
+ *,
+ url: str | None = None,
+ base64: str | None = None,
+ file_id: str | None = None,
+ mime_type: str | None = None,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> AudioContentBlock:
+ """Create an `AudioContentBlock`.
+
+ Args:
+ url: URL of the audio.
+ base64: Base64-encoded audio data.
+ file_id: ID of the audio file from a file storage system.
+ mime_type: MIME type of the audio.
+
+ Required for base64 data.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `AudioContentBlock`.
+
+ Raises:
+ ValueError: If no audio source is provided or if `base64` is used without
+ `mime_type`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ if not any([url, base64, file_id]):
+ msg = "Must provide one of: url, base64, or file_id"
+ raise ValueError(msg)
+
+ if base64 and not mime_type:
+ msg = "mime_type is required when using base64 data"
+ raise ValueError(msg)
+
+ block = AudioContentBlock(type="audio", id=ensure_id(id))
+
+ if url is not None:
+ block["url"] = url
+ if base64 is not None:
+ block["base64"] = base64
+ if file_id is not None:
+ block["file_id"] = file_id
+ if mime_type is not None:
+ block["mime_type"] = mime_type
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_file_block(
+ *,
+ url: str | None = None,
+ base64: str | None = None,
+ file_id: str | None = None,
+ mime_type: str | None = None,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> FileContentBlock:
+ """Create a `FileContentBlock`.
+
+ Args:
+ url: URL of the file.
+ base64: Base64-encoded file data.
+ file_id: ID of the file from a file storage system.
+ mime_type: MIME type of the file.
+
+ Required for base64 data.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `FileContentBlock`.
+
+ Raises:
+ ValueError: If no file source is provided or if `base64` is used without
+ `mime_type`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ if not any([url, base64, file_id]):
+ msg = "Must provide one of: url, base64, or file_id"
+ raise ValueError(msg)
+
+ if base64 and not mime_type:
+ msg = "mime_type is required when using base64 data"
+ raise ValueError(msg)
+
+ block = FileContentBlock(type="file", id=ensure_id(id))
+
+ if url is not None:
+ block["url"] = url
+ if base64 is not None:
+ block["base64"] = base64
+ if file_id is not None:
+ block["file_id"] = file_id
+ if mime_type is not None:
+ block["mime_type"] = mime_type
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_plaintext_block(
+ text: str | None = None,
+ url: str | None = None,
+ base64: str | None = None,
+ file_id: str | None = None,
+ title: str | None = None,
+ context: str | None = None,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> PlainTextContentBlock:
+ """Create a `PlainTextContentBlock`.
+
+ Args:
+ text: The plaintext content.
+ url: URL of the plaintext file.
+ base64: Base64-encoded plaintext data.
+ file_id: ID of the plaintext file from a file storage system.
+ title: Title of the text data.
+ context: Context or description of the text content.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `PlainTextContentBlock`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ block = PlainTextContentBlock(
+ type="text-plain",
+ mime_type="text/plain",
+ id=ensure_id(id),
+ )
+
+ if text is not None:
+ block["text"] = text
+ if url is not None:
+ block["url"] = url
+ if base64 is not None:
+ block["base64"] = base64
+ if file_id is not None:
+ block["file_id"] = file_id
+ if title is not None:
+ block["title"] = title
+ if context is not None:
+ block["context"] = context
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_tool_call(
+ name: str,
+ args: dict[str, Any],
+ *,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> ToolCall:
+ """Create a `ToolCall`.
+
+ Args:
+ name: The name of the tool to be called.
+ args: The arguments to the tool call.
+ id: An identifier for the tool call.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `ToolCall`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ block = ToolCall(
+ type="tool_call",
+ name=name,
+ args=args,
+ id=ensure_id(id),
+ )
+
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_reasoning_block(
+ reasoning: str | None = None,
+ id: str | None = None,
+ index: int | str | None = None,
+ **kwargs: Any,
+) -> ReasoningContentBlock:
+ """Create a `ReasoningContentBlock`.
+
+ Args:
+ reasoning: The reasoning text or thought summary.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `ReasoningContentBlock`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ block = ReasoningContentBlock(
+ type="reasoning",
+ reasoning=reasoning or "",
+ id=ensure_id(id),
+ )
+
+ if index is not None:
+ block["index"] = index
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_citation(
+ *,
+ url: str | None = None,
+ title: str | None = None,
+ start_index: int | None = None,
+ end_index: int | None = None,
+ cited_text: str | None = None,
+ id: str | None = None,
+ **kwargs: Any,
+) -> Citation:
+ """Create a `Citation`.
+
+ Args:
+ url: URL of the document source.
+ title: Source document title.
+ start_index: Start index in the response text where citation applies.
+ end_index: End index in the response text where citation applies.
+ cited_text: Excerpt of source text being cited.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+
+ Returns:
+ A properly formatted `Citation`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ block = Citation(type="citation", id=ensure_id(id))
+
+ if url is not None:
+ block["url"] = url
+ if title is not None:
+ block["title"] = title
+ if start_index is not None:
+ block["start_index"] = start_index
+ if end_index is not None:
+ block["end_index"] = end_index
+ if cited_text is not None:
+ block["cited_text"] = cited_text
+
+ extras = {k: v for k, v in kwargs.items() if v is not None}
+ if extras:
+ block["extras"] = extras
+
+ return block
+
+
+def create_non_standard_block(
+ value: dict[str, Any],
+ *,
+ id: str | None = None,
+ index: int | str | None = None,
+) -> NonStandardContentBlock:
+ """Create a `NonStandardContentBlock`.
+
+ Args:
+ value: Provider-specific content data.
+ id: Content block identifier.
+
+ Generated automatically if not provided.
+ index: Index of block in aggregate response.
+
+ Used during streaming.
+
+ Returns:
+ A properly formatted `NonStandardContentBlock`.
+
+ !!! note
+
+ The `id` is generated automatically if not provided, using a UUID4 format
+ prefixed with `'lc_'` to indicate it is a LangChain-generated ID.
+ """
+ block = NonStandardContentBlock(
+ type="non_standard",
+ value=value,
+ id=ensure_id(id),
+ )
+
+ if index is not None:
+ block["index"] = index
+
+ return block
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/function.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee0dad3975fcd40d89151fc7f70d068db1cc4fe4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/function.py
@@ -0,0 +1,62 @@
+"""Function Message."""
+
+from typing import Any, Literal
+
+from typing_extensions import override
+
+from langchain_core.messages.base import (
+ BaseMessage,
+ BaseMessageChunk,
+ merge_content,
+)
+from langchain_core.utils._merge import merge_dicts
+
+
+class FunctionMessage(BaseMessage):
+ """Message for passing the result of executing a tool back to a model.
+
+ `FunctionMessage` are an older version of the `ToolMessage` schema, and
+ do not contain the `tool_call_id` field.
+
+ The `tool_call_id` field is used to associate the tool call request with the
+ tool call response. Useful in situations where a chat model is able
+ to request multiple tool calls in parallel.
+
+ """
+
+ name: str
+ """The name of the function that was executed."""
+
+ type: Literal["function"] = "function"
+ """The type of the message (used for serialization)."""
+
+
+class FunctionMessageChunk(FunctionMessage, BaseMessageChunk):
+ """Function Message chunk."""
+
+ # Ignoring mypy re-assignment here since we're overriding the value
+ # to make sure that the chunk variant can be discriminated from the
+ # non-chunk variant.
+ type: Literal["FunctionMessageChunk"] = "FunctionMessageChunk" # type: ignore[assignment]
+ """The type of the message (used for serialization)."""
+
+ @override
+ def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
+ if isinstance(other, FunctionMessageChunk):
+ if self.name != other.name:
+ msg = "Cannot concatenate FunctionMessageChunks with different names."
+ raise ValueError(msg)
+
+ return self.__class__(
+ name=self.name,
+ content=merge_content(self.content, other.content),
+ additional_kwargs=merge_dicts(
+ self.additional_kwargs, other.additional_kwargs
+ ),
+ response_metadata=merge_dicts(
+ self.response_metadata, other.response_metadata
+ ),
+ id=self.id,
+ )
+
+ return super().__add__(other)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/human.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/human.py
new file mode 100644
index 0000000000000000000000000000000000000000..338e22137008273fc7efcf93c49d146b962de87d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/human.py
@@ -0,0 +1,70 @@
+"""Human message."""
+
+from typing import Any, Literal, cast, overload
+
+from langchain_core.messages import content as types
+from langchain_core.messages.base import BaseMessage, BaseMessageChunk
+
+
+class HumanMessage(BaseMessage):
+ """Message from the user.
+
+ A `HumanMessage` is a message that is passed in from a user to the model.
+
+ Example:
+ ```python
+ from langchain_core.messages import HumanMessage, SystemMessage
+
+ messages = [
+ SystemMessage(content="You are a helpful assistant! Your name is Bob."),
+ HumanMessage(content="What is your name?"),
+ ]
+
+ # Instantiate a chat model and invoke it with the messages
+ model = ...
+ print(model.invoke(messages))
+ ```
+ """
+
+ type: Literal["human"] = "human"
+ """The type of the message (used for serialization)."""
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict],
+ **kwargs: Any,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None: ...
+
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Specify `content` as positional arg or `content_blocks` for typing."""
+ if content_blocks is not None:
+ super().__init__(
+ content=cast("str | list[str | dict]", content_blocks),
+ **kwargs,
+ )
+ else:
+ super().__init__(content=content, **kwargs)
+
+
+class HumanMessageChunk(HumanMessage, BaseMessageChunk):
+ """Human Message chunk."""
+
+ # Ignoring mypy re-assignment here since we're overriding the value
+ # to make sure that the chunk variant can be discriminated from the
+ # non-chunk variant.
+ type: Literal["HumanMessageChunk"] = "HumanMessageChunk" # type: ignore[assignment]
+ """The type of the message (used for serialization)."""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/modifier.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/modifier.py
new file mode 100644
index 0000000000000000000000000000000000000000..2175be492e829ee6058c727fe2d04b4ea5fe9efe
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/modifier.py
@@ -0,0 +1,33 @@
+"""Message responsible for deleting other messages."""
+
+from typing import Any, Literal
+
+from langchain_core.messages.base import BaseMessage
+
+
+class RemoveMessage(BaseMessage):
+ """Message responsible for deleting other messages."""
+
+ type: Literal["remove"] = "remove"
+ """The type of the message (used for serialization)."""
+
+ def __init__(
+ self,
+ id: str,
+ **kwargs: Any,
+ ) -> None:
+ """Create a RemoveMessage.
+
+ Args:
+ id: The ID of the message to remove.
+ **kwargs: Additional fields to pass to the message.
+
+ Raises:
+ ValueError: If the 'content' field is passed in kwargs.
+
+ """
+ if kwargs.pop("content", None):
+ msg = "RemoveMessage does not support 'content' field."
+ raise ValueError(msg)
+
+ super().__init__("", id=id, **kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/system.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/system.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a60811dffcacc016f075a7c5986bc536927ee7e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/system.py
@@ -0,0 +1,70 @@
+"""System message."""
+
+from typing import Any, Literal, cast, overload
+
+from langchain_core.messages import content as types
+from langchain_core.messages.base import BaseMessage, BaseMessageChunk
+
+
+class SystemMessage(BaseMessage):
+ """Message for priming AI behavior.
+
+ The system message is usually passed in as the first of a sequence
+ of input messages.
+
+ Example:
+ ```python
+ from langchain_core.messages import HumanMessage, SystemMessage
+
+ messages = [
+ SystemMessage(content="You are a helpful assistant! Your name is Bob."),
+ HumanMessage(content="What is your name?"),
+ ]
+
+ # Define a chat model and invoke it with the messages
+ print(model.invoke(messages))
+ ```
+ """
+
+ type: Literal["system"] = "system"
+ """The type of the message (used for serialization)."""
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict],
+ **kwargs: Any,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None: ...
+
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Specify `content` as positional arg or `content_blocks` for typing."""
+ if content_blocks is not None:
+ super().__init__(
+ content=cast("str | list[str | dict]", content_blocks),
+ **kwargs,
+ )
+ else:
+ super().__init__(content=content, **kwargs)
+
+
+class SystemMessageChunk(SystemMessage, BaseMessageChunk):
+ """System Message chunk."""
+
+ # Ignoring mypy re-assignment here since we're overriding the value
+ # to make sure that the chunk variant can be discriminated from the
+ # non-chunk variant.
+ type: Literal["SystemMessageChunk"] = "SystemMessageChunk" # type: ignore[assignment]
+ """The type of the message (used for serialization)."""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/tool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/tool.py
new file mode 100644
index 0000000000000000000000000000000000000000..a83d4e6eb9e5868e128c88d78c101dc75c45a242
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/tool.py
@@ -0,0 +1,416 @@
+"""Messages for tools."""
+
+import json
+from typing import Any, Literal, cast, overload
+from uuid import UUID
+
+from pydantic import Field, model_validator
+from typing_extensions import NotRequired, TypedDict, override
+
+from langchain_core.messages import content as types
+from langchain_core.messages.base import BaseMessage, BaseMessageChunk, merge_content
+from langchain_core.messages.content import InvalidToolCall
+from langchain_core.utils._merge import merge_dicts, merge_obj
+
+
+class ToolOutputMixin:
+ """Mixin for objects that tools can return directly.
+
+ If a custom BaseTool is invoked with a `ToolCall` and the output of custom code is
+ not an instance of `ToolOutputMixin`, the output will automatically be coerced to
+ a string and wrapped in a `ToolMessage`.
+
+ """
+
+
+class ToolMessage(BaseMessage, ToolOutputMixin):
+ """Message for passing the result of executing a tool back to a model.
+
+ `ToolMessage` objects contain the result of a tool invocation. Typically, the result
+ is encoded inside the `content` field.
+
+ `tool_call_id` is used to associate the tool call request with the tool call
+ response. Useful in situations where a chat model is able to request multiple tool
+ calls in parallel.
+
+ Example:
+ A `ToolMessage` representing a result of `42` from a tool call with id
+
+ ```python
+ from langchain_core.messages import ToolMessage
+
+ ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL")
+ ```
+
+ Example:
+ A `ToolMessage` where only part of the tool output is sent to the model
+ and the full output is passed in to artifact.
+
+ ```python
+ from langchain_core.messages import ToolMessage
+
+ tool_output = {
+ "stdout": "From the graph we can see that the correlation between "
+ "x and y is ...",
+ "stderr": None,
+ "artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."},
+ }
+
+ ToolMessage(
+ content=tool_output["stdout"],
+ artifact=tool_output,
+ tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL",
+ )
+ ```
+ """
+
+ tool_call_id: str
+ """Tool call that this message is responding to."""
+
+ type: Literal["tool"] = "tool"
+ """The type of the message (used for serialization)."""
+
+ artifact: Any = None
+ """Artifact of the Tool execution which is not meant to be sent to the model.
+
+ Should only be specified if it is different from the message content, e.g. if only
+ a subset of the full tool output is being passed as message content but the full
+ output is needed in other parts of the code.
+
+ """
+
+ status: Literal["success", "error"] = "success"
+ """Status of the tool invocation."""
+
+ additional_kwargs: dict = Field(default_factory=dict, repr=False)
+ """Currently inherited from `BaseMessage`, but not used."""
+ response_metadata: dict = Field(default_factory=dict, repr=False)
+ """Currently inherited from `BaseMessage`, but not used."""
+
+ @model_validator(mode="before")
+ @classmethod
+ def coerce_args(cls, values: dict) -> dict:
+ """Coerce the model arguments to the correct types.
+
+ Args:
+ values: The model arguments.
+
+ """
+ content = values["content"]
+ if isinstance(content, tuple):
+ content = list(content)
+
+ if not isinstance(content, (str, list)):
+ try:
+ values["content"] = str(content)
+ except ValueError as e:
+ msg = (
+ "ToolMessage content should be a string or a list of string/dicts. "
+ f"Received:\n\n{content=}\n\n which could not be coerced into a "
+ "string."
+ )
+ raise ValueError(msg) from e
+ elif isinstance(content, list):
+ values["content"] = []
+ for i, x in enumerate(content):
+ if not isinstance(x, (str, dict)):
+ try:
+ values["content"].append(str(x))
+ except ValueError as e:
+ msg = (
+ "ToolMessage content should be a string or a list of "
+ "string/dicts. Received a list but "
+ f"element ToolMessage.content[{i}] is not a dict and could "
+ f"not be coerced to a string.:\n\n{x}"
+ )
+ raise ValueError(msg) from e
+ else:
+ values["content"].append(x)
+
+ tool_call_id = values["tool_call_id"]
+ if isinstance(tool_call_id, (UUID, int, float)):
+ values["tool_call_id"] = str(tool_call_id)
+ return values
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict],
+ **kwargs: Any,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None: ...
+
+ def __init__(
+ self,
+ content: str | list[str | dict] | None = None,
+ content_blocks: list[types.ContentBlock] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize a `ToolMessage`.
+
+ Specify `content` as positional arg or `content_blocks` for typing.
+
+ Args:
+ content: The contents of the message.
+ content_blocks: Typed standard content.
+ **kwargs: Additional fields.
+ """
+ if content_blocks is not None:
+ super().__init__(
+ content=cast("str | list[str | dict]", content_blocks),
+ **kwargs,
+ )
+ else:
+ super().__init__(content=content, **kwargs)
+
+
+class ToolMessageChunk(ToolMessage, BaseMessageChunk):
+ """Tool Message chunk."""
+
+ # Ignoring mypy re-assignment here since we're overriding the value
+ # to make sure that the chunk variant can be discriminated from the
+ # non-chunk variant.
+ type: Literal["ToolMessageChunk"] = "ToolMessageChunk" # type: ignore[assignment]
+
+ @override
+ def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
+ if isinstance(other, ToolMessageChunk):
+ if self.tool_call_id != other.tool_call_id:
+ msg = "Cannot concatenate ToolMessageChunks with different names."
+ raise ValueError(msg)
+
+ return self.__class__(
+ tool_call_id=self.tool_call_id,
+ content=merge_content(self.content, other.content),
+ artifact=merge_obj(self.artifact, other.artifact),
+ additional_kwargs=merge_dicts(
+ self.additional_kwargs, other.additional_kwargs
+ ),
+ response_metadata=merge_dicts(
+ self.response_metadata, other.response_metadata
+ ),
+ id=self.id,
+ status=_merge_status(self.status, other.status),
+ )
+
+ return super().__add__(other)
+
+
+class ToolCall(TypedDict):
+ """Represents an AI's request to call a tool.
+
+ Example:
+ ```python
+ {"name": "foo", "args": {"a": 1}, "id": "123"}
+ ```
+
+ This represents a request to call the tool named `'foo'` with arguments
+ `{"a": 1}` and an identifier of `'123'`.
+
+ !!! note "Factory function"
+
+ `tool_call` may also be used as a factory to create a `ToolCall`. Benefits
+ include:
+
+ * Required arguments strictly validated at creation time
+ """
+
+ name: str
+ """The name of the tool to be called."""
+
+ args: dict[str, Any]
+ """The arguments to the tool call as a dictionary."""
+
+ id: str | None
+ """An identifier associated with the tool call.
+
+ An identifier is needed to associate a tool call request with a tool
+ call result in events when multiple concurrent tool calls are made.
+ """
+
+ type: NotRequired[Literal["tool_call"]]
+ """Used for discrimination."""
+
+
+def tool_call(
+ *,
+ name: str,
+ args: dict[str, Any],
+ id: str | None,
+) -> ToolCall:
+ """Create a tool call.
+
+ Args:
+ name: The name of the tool to be called.
+ args: The arguments to the tool call as a dictionary.
+ id: An identifier associated with the tool call.
+
+ Returns:
+ The created tool call.
+ """
+ return ToolCall(name=name, args=args, id=id, type="tool_call")
+
+
+class ToolCallChunk(TypedDict):
+ """A chunk of a tool call (yielded when streaming).
+
+ When merging `ToolCallChunk` objects (e.g., via `AIMessageChunk.__add__`), all
+ string attributes are concatenated. Chunks are only merged if their values of
+ `index` are equal and not `None`.
+
+ Example:
+ ```python
+ left_chunks = [ToolCallChunk(name="foo", args='{"a":', index=0)]
+ right_chunks = [ToolCallChunk(name=None, args="1}", index=0)]
+
+ (
+ AIMessageChunk(content="", tool_call_chunks=left_chunks)
+ + AIMessageChunk(content="", tool_call_chunks=right_chunks)
+ ).tool_call_chunks == [ToolCallChunk(name="foo", args='{"a":1}', index=0)]
+ ```
+ """
+
+ name: str | None
+ """The name of the tool to be called."""
+
+ args: str | None
+ """The arguments to the tool call as a JSON-parseable string."""
+
+ id: str | None
+ """An identifier associated with the tool call.
+
+ An identifier is needed to associate a tool call request with a tool
+ call result in events when multiple concurrent tool calls are made.
+ """
+
+ index: int | None
+ """The index of the tool call in a sequence.
+
+ Used for merging chunks.
+ """
+
+ type: NotRequired[Literal["tool_call_chunk"]]
+ """Used for discrimination."""
+
+
+def tool_call_chunk(
+ *,
+ name: str | None = None,
+ args: str | None = None,
+ id: str | None = None,
+ index: int | None = None,
+) -> ToolCallChunk:
+ """Create a tool call chunk.
+
+ Args:
+ name: The name of the tool to be called.
+ args: The arguments to the tool call as a JSON string.
+ id: An identifier associated with the tool call.
+ index: The index of the tool call in a sequence.
+
+ Returns:
+ The created tool call chunk.
+ """
+ return ToolCallChunk(
+ name=name, args=args, id=id, index=index, type="tool_call_chunk"
+ )
+
+
+def invalid_tool_call(
+ *,
+ name: str | None = None,
+ args: str | None = None,
+ id: str | None = None,
+ error: str | None = None,
+) -> InvalidToolCall:
+ """Create an invalid tool call.
+
+ Args:
+ name: The name of the tool to be called.
+ args: The arguments to the tool call as a JSON string.
+ id: An identifier associated with the tool call.
+ error: An error message associated with the tool call.
+
+ Returns:
+ The created invalid tool call.
+ """
+ return InvalidToolCall(
+ name=name, args=args, id=id, error=error, type="invalid_tool_call"
+ )
+
+
+def default_tool_parser(
+ raw_tool_calls: list[dict],
+) -> tuple[list[ToolCall], list[InvalidToolCall]]:
+ """Best-effort parsing of tools.
+
+ Args:
+ raw_tool_calls: List of raw tool call dicts to parse.
+
+ Returns:
+ A list of tool calls and invalid tool calls.
+ """
+ tool_calls = []
+ invalid_tool_calls = []
+ for raw_tool_call in raw_tool_calls:
+ if "function" not in raw_tool_call:
+ continue
+ function_name = raw_tool_call["function"]["name"]
+ try:
+ function_args = json.loads(raw_tool_call["function"]["arguments"])
+ parsed = tool_call(
+ name=function_name or "",
+ args=function_args or {},
+ id=raw_tool_call.get("id"),
+ )
+ tool_calls.append(parsed)
+ except json.JSONDecodeError:
+ invalid_tool_calls.append(
+ invalid_tool_call(
+ name=function_name,
+ args=raw_tool_call["function"]["arguments"],
+ id=raw_tool_call.get("id"),
+ error=None,
+ )
+ )
+ return tool_calls, invalid_tool_calls
+
+
+def default_tool_chunk_parser(raw_tool_calls: list[dict]) -> list[ToolCallChunk]:
+ """Best-effort parsing of tool chunks.
+
+ Args:
+ raw_tool_calls: List of raw tool call dicts to parse.
+
+ Returns:
+ List of parsed ToolCallChunk objects.
+ """
+ tool_call_chunks = []
+ for tool_call in raw_tool_calls:
+ if "function" not in tool_call:
+ function_args = None
+ function_name = None
+ else:
+ function_args = tool_call["function"]["arguments"]
+ function_name = tool_call["function"]["name"]
+ parsed = tool_call_chunk(
+ name=function_name,
+ args=function_args,
+ id=tool_call.get("id"),
+ index=tool_call.get("index"),
+ )
+ tool_call_chunks.append(parsed)
+ return tool_call_chunks
+
+
+def _merge_status(
+ left: Literal["success", "error"], right: Literal["success", "error"]
+) -> Literal["success", "error"]:
+ return "error" if "error" in {left, right} else "success"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f37d100c8f9c8aedab405cba434d9b2cf354e599
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/messages/utils.py
@@ -0,0 +1,2353 @@
+"""Module contains utility functions for working with messages.
+
+Some examples of what you can do with these functions include:
+
+* Convert messages to strings (serialization)
+* Convert messages from dicts to Message objects (deserialization)
+* Filter messages from a list of messages based on name, type or id etc.
+"""
+
+from __future__ import annotations
+
+import base64
+import inspect
+import json
+import logging
+import math
+from collections.abc import Callable, Iterable, Sequence
+from functools import partial, wraps
+from typing import (
+ TYPE_CHECKING,
+ Annotated,
+ Any,
+ Concatenate,
+ Literal,
+ ParamSpec,
+ Protocol,
+ TypeVar,
+ cast,
+ overload,
+)
+from xml.sax.saxutils import escape, quoteattr
+
+from pydantic import Discriminator, Field, Tag
+
+from langchain_core.exceptions import ErrorCode, create_message
+from langchain_core.messages.ai import AIMessage, AIMessageChunk
+from langchain_core.messages.base import BaseMessage, BaseMessageChunk
+from langchain_core.messages.block_translators.openai import (
+ convert_to_openai_data_block,
+)
+from langchain_core.messages.chat import ChatMessage, ChatMessageChunk
+from langchain_core.messages.content import (
+ is_data_content_block,
+)
+from langchain_core.messages.function import FunctionMessage, FunctionMessageChunk
+from langchain_core.messages.human import HumanMessage, HumanMessageChunk
+from langchain_core.messages.modifier import RemoveMessage
+from langchain_core.messages.system import SystemMessage, SystemMessageChunk
+from langchain_core.messages.tool import ToolCall, ToolMessage, ToolMessageChunk
+from langchain_core.utils.function_calling import convert_to_openai_tool
+
+if TYPE_CHECKING:
+ from langchain_core.language_models import BaseLanguageModel
+ from langchain_core.prompt_values import PromptValue
+ from langchain_core.runnables.base import Runnable
+ from langchain_core.tools import BaseTool
+
+try:
+ from langchain_text_splitters import TextSplitter
+
+ _HAS_LANGCHAIN_TEXT_SPLITTERS = True
+except ImportError:
+ _HAS_LANGCHAIN_TEXT_SPLITTERS = False
+
+logger = logging.getLogger(__name__)
+
+
+def _get_type(v: Any) -> str:
+ """Get the type associated with the object for serialization purposes."""
+ if isinstance(v, dict) and "type" in v:
+ result = v["type"]
+ elif hasattr(v, "type"):
+ result = v.type
+ else:
+ msg = (
+ f"Expected either a dictionary with a 'type' key or an object "
+ f"with a 'type' attribute. Instead got type {type(v)}."
+ )
+ raise TypeError(msg)
+ if not isinstance(result, str):
+ msg = f"Expected 'type' to be a str, got {type(result).__name__}"
+ raise TypeError(msg)
+ return result
+
+
+AnyMessage = Annotated[
+ Annotated[AIMessage, Tag(tag="ai")]
+ | Annotated[HumanMessage, Tag(tag="human")]
+ | Annotated[ChatMessage, Tag(tag="chat")]
+ | Annotated[SystemMessage, Tag(tag="system")]
+ | Annotated[FunctionMessage, Tag(tag="function")]
+ | Annotated[ToolMessage, Tag(tag="tool")]
+ | Annotated[AIMessageChunk, Tag(tag="AIMessageChunk")]
+ | Annotated[HumanMessageChunk, Tag(tag="HumanMessageChunk")]
+ | Annotated[ChatMessageChunk, Tag(tag="ChatMessageChunk")]
+ | Annotated[SystemMessageChunk, Tag(tag="SystemMessageChunk")]
+ | Annotated[FunctionMessageChunk, Tag(tag="FunctionMessageChunk")]
+ | Annotated[ToolMessageChunk, Tag(tag="ToolMessageChunk")],
+ Field(discriminator=Discriminator(_get_type)),
+]
+"""A type representing any defined `Message` or `MessageChunk` type."""
+
+
+def _has_base64_data(block: dict) -> bool:
+ """Check if a content block contains base64 encoded data.
+
+ Args:
+ block: A content block dictionary.
+
+ Returns:
+ Whether the block contains base64 data.
+ """
+ # Check for explicit base64 field (standard content blocks)
+ if block.get("base64"):
+ return True
+
+ # Check for data: URL in url field
+ url = block.get("url", "")
+ if isinstance(url, str) and url.startswith("data:"):
+ return True
+
+ # Check for OpenAI-style image_url with data: URL
+ image_url = block.get("image_url", {})
+ if isinstance(image_url, dict):
+ url = image_url.get("url", "")
+ if isinstance(url, str) and url.startswith("data:"):
+ return True
+
+ return False
+
+
+_XML_CONTENT_BLOCK_MAX_LEN = 500
+
+
+def _truncate(text: str, max_len: int = _XML_CONTENT_BLOCK_MAX_LEN) -> str:
+ """Truncate text to `max_len` characters, adding ellipsis if truncated."""
+ if len(text) <= max_len:
+ return text
+ return text[:max_len] + "..."
+
+
+def _format_content_block_xml(block: dict) -> str | None:
+ """Format a content block as XML.
+
+ Args:
+ block: A LangChain content block.
+
+ Returns:
+ XML string representation of the block, or `None` if the block should be
+ skipped.
+
+ Note:
+ Plain text document content, server tool call arguments, and server tool
+ result outputs are truncated to 500 characters.
+ """
+ block_type = block.get("type", "")
+
+ # Skip blocks with base64 encoded data
+ if _has_base64_data(block):
+ return None
+
+ # Text blocks
+ if block_type == "text":
+ text = block.get("text", "")
+ return escape(text) if text else None
+
+ # Reasoning blocks
+ if block_type == "reasoning":
+ reasoning = block.get("reasoning", "")
+ if reasoning:
+ return f"{escape(reasoning)}"
+ return None
+
+ # Image blocks (URL only, base64 already filtered)
+ if block_type == "image":
+ url = block.get("url")
+ file_id = block.get("file_id")
+ if url:
+ return f""
+ if file_id:
+ return f""
+ return None
+
+ # OpenAI-style image_url blocks
+ if block_type == "image_url":
+ image_url = block.get("image_url", {})
+ if isinstance(image_url, dict):
+ url = image_url.get("url", "")
+ if url and not url.startswith("data:"):
+ return f""
+ return None
+
+ # Audio blocks (URL only)
+ if block_type == "audio":
+ url = block.get("url")
+ file_id = block.get("file_id")
+ if url:
+ return f""
+ if file_id:
+ return f""
+ return None
+
+ # Video blocks (URL only)
+ if block_type == "video":
+ url = block.get("url")
+ file_id = block.get("file_id")
+ if url:
+ return f""
+ if file_id:
+ return f""
+ return None
+
+ # Plain text document blocks
+ if block_type == "text-plain":
+ text = block.get("text", "")
+ return escape(_truncate(text)) if text else None
+
+ # Server tool call blocks (from AI messages)
+ if block_type == "server_tool_call":
+ tc_id = quoteattr(str(block.get("id") or ""))
+ tc_name = quoteattr(str(block.get("name") or ""))
+ tc_args_json = json.dumps(block.get("args", {}), ensure_ascii=False)
+ tc_args = escape(_truncate(tc_args_json))
+ return (
+ f"{tc_args}"
+ )
+
+ # Server tool result blocks
+ if block_type == "server_tool_result":
+ tool_call_id = quoteattr(str(block.get("tool_call_id") or ""))
+ status = quoteattr(str(block.get("status") or ""))
+ output = block.get("output")
+ if output:
+ output_json = json.dumps(output, ensure_ascii=False)
+ output_str = escape(_truncate(output_json))
+ else:
+ output_str = ""
+ return (
+ f""
+ f"{output_str}"
+ )
+
+ # Unknown block type - skip silently
+ return None
+
+
+def _get_message_type_str(
+ m: BaseMessage,
+ human_prefix: str,
+ ai_prefix: str,
+ system_prefix: str,
+ function_prefix: str,
+ tool_prefix: str,
+) -> str:
+ """Get the type string for XML message element.
+
+ Args:
+ m: The message to get the type string for.
+ human_prefix: The prefix to use for `HumanMessage`.
+ ai_prefix: The prefix to use for `AIMessage`.
+ system_prefix: The prefix to use for `SystemMessage`.
+ function_prefix: The prefix to use for `FunctionMessage`.
+ tool_prefix: The prefix to use for `ToolMessage`.
+
+ Returns:
+ The type string for the message element.
+
+ Raises:
+ ValueError: If an unsupported message type is encountered.
+ """
+ if isinstance(m, HumanMessage):
+ return human_prefix.lower()
+ if isinstance(m, AIMessage):
+ return ai_prefix.lower()
+ if isinstance(m, SystemMessage):
+ return system_prefix.lower()
+ if isinstance(m, FunctionMessage):
+ return function_prefix.lower()
+ if isinstance(m, ToolMessage):
+ return tool_prefix.lower()
+ if isinstance(m, ChatMessage):
+ return m.role
+ msg = f"Got unsupported message type: {m}"
+ raise ValueError(msg)
+
+
+def get_buffer_string(
+ messages: Sequence[BaseMessage],
+ human_prefix: str = "Human",
+ ai_prefix: str = "AI",
+ *,
+ system_prefix: str = "System",
+ function_prefix: str = "Function",
+ tool_prefix: str = "Tool",
+ message_separator: str = "\n",
+ format: Literal["prefix", "xml"] = "prefix", # noqa: A002
+) -> str:
+ r"""Convert a sequence of messages to strings and concatenate them into one string.
+
+ Args:
+ messages: Messages to be converted to strings.
+ human_prefix: The prefix to prepend to contents of `HumanMessage`s.
+ ai_prefix: The prefix to prepend to contents of `AIMessage`.
+ system_prefix: The prefix to prepend to contents of `SystemMessage`s.
+ function_prefix: The prefix to prepend to contents of `FunctionMessage`s.
+ tool_prefix: The prefix to prepend to contents of `ToolMessage`s.
+ message_separator: The separator to use between messages.
+ format: The output format. `'prefix'` uses `Role: content` format (default).
+
+ `'xml'` uses XML-style `` format with proper character
+ escaping, which is useful when message content may contain role-like
+ prefixes that could cause ambiguity.
+
+ Returns:
+ A single string concatenation of all input messages.
+
+ Raises:
+ ValueError: If an unsupported message type is encountered.
+
+ !!! warning
+
+ If a message is an `AIMessage` and contains both tool calls under `tool_calls`
+ and a function call under `additional_kwargs["function_call"]`, only the tool
+ calls will be appended to the string representation.
+
+ !!! note "XML format"
+
+ When using `format='xml'`:
+
+ - All messages use uniform `content` format.
+ - The `type` attribute uses `human_prefix` (lowercased) for `HumanMessage`,
+ `ai_prefix` (lowercased) for `AIMessage`, `system_prefix` (lowercased)
+ for `SystemMessage`, `function_prefix` (lowercased) for `FunctionMessage`,
+ `tool_prefix` (lowercased) for `ToolMessage`, and the original role
+ (unchanged) for `ChatMessage`.
+ - Message content is escaped using `xml.sax.saxutils.escape()`.
+ - Attribute values are escaped using `xml.sax.saxutils.quoteattr()`.
+ - AI messages with tool calls use nested structure with `` and
+ `` elements.
+ - For multi-modal content (list of content blocks), supported block types
+ are: `text`, `reasoning`, `image` (URL/file_id only), `image_url`
+ (OpenAI-style, URL only), `audio` (URL/file_id only), `video` (URL/file_id
+ only), `text-plain`, `server_tool_call`, and `server_tool_result`.
+ - Content blocks with base64-encoded data are skipped (including blocks
+ with `base64` field or `data:` URLs).
+ - Unknown block types are skipped.
+ - Plain text document content (`text-plain`), server tool call arguments,
+ and server tool result outputs are truncated to 500 characters.
+
+ Example:
+ Default prefix format:
+
+ ```python
+ from langchain_core.messages import AIMessage, HumanMessage, get_buffer_string
+
+ messages = [
+ HumanMessage(content="Hi, how are you?"),
+ AIMessage(content="Good, how are you?"),
+ ]
+ get_buffer_string(messages)
+ # -> "Human: Hi, how are you?\nAI: Good, how are you?"
+ ```
+
+ XML format (useful when content contains role-like prefixes):
+
+ ```python
+ messages = [
+ HumanMessage(content="Example: Human: some text"),
+ AIMessage(content="I see the example."),
+ ]
+ get_buffer_string(messages, format="xml")
+ # -> 'Example: Human: some text\\n'
+ # -> 'I see the example.'
+ ```
+
+ XML format with special characters (automatically escaped):
+
+ ```python
+ messages = [
+ HumanMessage(content="Is 5 < 10 & 10 > 5?"),
+ ]
+ get_buffer_string(messages, format="xml")
+ # -> 'Is 5 < 10 & 10 > 5?'
+ ```
+
+ XML format with tool calls:
+
+ ```python
+ messages = [
+ AIMessage(
+ content="I'll search for that.",
+ tool_calls=[
+ {"id": "call_123", "name": "search", "args": {"query": "weather"}}
+ ],
+ ),
+ ]
+ get_buffer_string(messages, format="xml")
+ # -> '\\n'
+ # -> ' I\\'ll search for that.\\n'
+ # -> ' '
+ # -> '{"query": "weather"}\\n'
+ # -> ''
+ ```
+ """
+ if format not in {"prefix", "xml"}:
+ msg = (
+ f"Unrecognized format={format!r}. Supported formats are 'prefix' and 'xml'."
+ )
+ raise ValueError(msg)
+
+ string_messages = []
+ for m in messages:
+ if isinstance(m, HumanMessage):
+ role = human_prefix
+ elif isinstance(m, AIMessage):
+ role = ai_prefix
+ elif isinstance(m, SystemMessage):
+ role = system_prefix
+ elif isinstance(m, FunctionMessage):
+ role = function_prefix
+ elif isinstance(m, ToolMessage):
+ role = tool_prefix
+ elif isinstance(m, ChatMessage):
+ role = m.role
+ else:
+ msg = f"Got unsupported message type: {m}"
+ raise ValueError(msg) # noqa: TRY004
+
+ if format == "xml":
+ msg_type = _get_message_type_str(
+ m, human_prefix, ai_prefix, system_prefix, function_prefix, tool_prefix
+ )
+
+ # Format content blocks
+ if isinstance(m.content, str):
+ content_parts = [escape(m.content)] if m.content else []
+ else:
+ # List of content blocks
+ content_parts = []
+ for block in m.content:
+ if isinstance(block, str):
+ if block:
+ content_parts.append(escape(block))
+ else:
+ formatted = _format_content_block_xml(block)
+ if formatted:
+ content_parts.append(formatted)
+
+ # Check if this is an AIMessage with tool calls
+ has_tool_calls = isinstance(m, AIMessage) and m.tool_calls
+ has_function_call = (
+ isinstance(m, AIMessage)
+ and not m.tool_calls
+ and "function_call" in m.additional_kwargs
+ )
+
+ if has_tool_calls or has_function_call:
+ # Use nested structure for AI messages with tool calls
+ # Type narrowing: at this point m is AIMessage (verified above)
+ ai_msg = cast("AIMessage", m)
+ parts = [f""]
+ if content_parts:
+ parts.append(f" {' '.join(content_parts)}")
+
+ if has_tool_calls:
+ for tc in ai_msg.tool_calls:
+ tc_id = quoteattr(str(tc.get("id") or ""))
+ tc_name = quoteattr(str(tc.get("name") or ""))
+ tc_args = escape(
+ json.dumps(tc.get("args", {}), ensure_ascii=False)
+ )
+ parts.append(
+ f" "
+ f"{tc_args}"
+ )
+ elif has_function_call:
+ fc = ai_msg.additional_kwargs["function_call"]
+ fc_name = quoteattr(str(fc.get("name") or ""))
+ fc_args = escape(str(fc.get("arguments") or "{}"))
+ parts.append(
+ f" {fc_args}"
+ )
+
+ parts.append("")
+ message = "\n".join(parts)
+ else:
+ # Simple structure for messages without tool calls
+ joined_content = " ".join(content_parts)
+ message = (
+ f"{joined_content}"
+ )
+ else: # format == "prefix"
+ content = m.text
+ message = f"{role}: {content}"
+ tool_info = ""
+ if isinstance(m, AIMessage):
+ if m.tool_calls:
+ tool_info = str(m.tool_calls)
+ elif "function_call" in m.additional_kwargs:
+ # Legacy behavior assumes only one function call per message
+ tool_info = str(m.additional_kwargs["function_call"])
+ if tool_info:
+ message += tool_info # Preserve original behavior
+
+ string_messages.append(message)
+
+ return message_separator.join(string_messages)
+
+
+def _message_from_dict(message: dict) -> BaseMessage:
+ type_ = message["type"]
+ if type_ == "human":
+ return HumanMessage(**message["data"])
+ if type_ == "ai":
+ return AIMessage(**message["data"])
+ if type_ == "system":
+ return SystemMessage(**message["data"])
+ if type_ == "chat":
+ return ChatMessage(**message["data"])
+ if type_ == "function":
+ return FunctionMessage(**message["data"])
+ if type_ == "tool":
+ return ToolMessage(**message["data"])
+ if type_ == "remove":
+ return RemoveMessage(**message["data"])
+ if type_ == "AIMessageChunk":
+ return AIMessageChunk(**message["data"])
+ if type_ == "HumanMessageChunk":
+ return HumanMessageChunk(**message["data"])
+ if type_ == "FunctionMessageChunk":
+ return FunctionMessageChunk(**message["data"])
+ if type_ == "ToolMessageChunk":
+ return ToolMessageChunk(**message["data"])
+ if type_ == "SystemMessageChunk":
+ return SystemMessageChunk(**message["data"])
+ if type_ == "ChatMessageChunk":
+ return ChatMessageChunk(**message["data"])
+ msg = f"Got unexpected message type: {type_}"
+ raise ValueError(msg)
+
+
+def messages_from_dict(messages: Sequence[dict]) -> list[BaseMessage]:
+ """Convert a sequence of messages from dicts to `Message` objects.
+
+ Args:
+ messages: Sequence of messages (as dicts) to convert.
+
+ Returns:
+ list of messages (BaseMessages).
+
+ """
+ return [_message_from_dict(m) for m in messages]
+
+
+def message_chunk_to_message(chunk: BaseMessage) -> BaseMessage:
+ """Convert a message chunk to a `Message`.
+
+ Args:
+ chunk: Message chunk to convert.
+
+ Returns:
+ Message.
+ """
+ if not isinstance(chunk, BaseMessageChunk):
+ return chunk
+ # chunk classes always have the equivalent non-chunk class as their first parent
+ ignore_keys = ["type"]
+ if isinstance(chunk, AIMessageChunk):
+ ignore_keys.extend(["tool_call_chunks", "chunk_position"])
+ return cast(
+ "BaseMessage",
+ chunk.__class__.__mro__[1](
+ **{k: v for k, v in chunk.__dict__.items() if k not in ignore_keys}
+ ),
+ )
+
+
+MessageLikeRepresentation = (
+ BaseMessage | list[str] | tuple[str, str] | str | dict[str, Any]
+)
+"""A type representing the various ways a message can be represented."""
+
+
+def _create_message_from_message_type(
+ message_type: str,
+ content: str,
+ name: str | None = None,
+ tool_call_id: str | None = None,
+ tool_calls: list[dict[str, Any]] | None = None,
+ id: str | None = None,
+ **additional_kwargs: Any,
+) -> BaseMessage:
+ """Create a message from a `Message` type and content string.
+
+ Args:
+ message_type: the type of the message (e.g., `'human'`, `'ai'`, etc.).
+ content: the content string.
+ name: the name of the message.
+ tool_call_id: the tool call id.
+ tool_calls: the tool calls.
+ id: the id of the message.
+ additional_kwargs: additional keyword arguments.
+
+ Returns:
+ a message of the appropriate type.
+
+ Raises:
+ ValueError: if the message type is not one of `'human'`, `'user'`, `'ai'`,
+ `'assistant'`, `'function'`, `'tool'`, `'system'`, or
+ `'developer'`.
+ """
+ kwargs: dict[str, Any] = {}
+ if name is not None:
+ kwargs["name"] = name
+ if tool_call_id is not None:
+ kwargs["tool_call_id"] = tool_call_id
+ if additional_kwargs:
+ if response_metadata := additional_kwargs.pop("response_metadata", None):
+ kwargs["response_metadata"] = response_metadata
+ kwargs["additional_kwargs"] = additional_kwargs
+ additional_kwargs.update(additional_kwargs.pop("additional_kwargs", {}))
+ if id is not None:
+ kwargs["id"] = id
+ if tool_calls is not None:
+ kwargs["tool_calls"] = []
+ for tool_call in tool_calls:
+ # Convert OpenAI-format tool call to LangChain format.
+ if "function" in tool_call:
+ args = tool_call["function"]["arguments"]
+ if isinstance(args, str):
+ args = json.loads(args, strict=False)
+ kwargs["tool_calls"].append(
+ {
+ "name": tool_call["function"]["name"],
+ "args": args,
+ "id": tool_call["id"],
+ "type": "tool_call",
+ }
+ )
+ else:
+ kwargs["tool_calls"].append(tool_call)
+ if message_type in {"human", "user"}:
+ if example := kwargs.get("additional_kwargs", {}).pop("example", False):
+ kwargs["example"] = example
+ message: BaseMessage = HumanMessage(content=content, **kwargs)
+ elif message_type in {"ai", "assistant"}:
+ if example := kwargs.get("additional_kwargs", {}).pop("example", False):
+ kwargs["example"] = example
+ message = AIMessage(content=content, **kwargs)
+ elif message_type in {"system", "developer"}:
+ if message_type == "developer":
+ kwargs["additional_kwargs"] = kwargs.get("additional_kwargs") or {}
+ kwargs["additional_kwargs"]["__openai_role__"] = "developer"
+ message = SystemMessage(content=content, **kwargs)
+ elif message_type == "function":
+ message = FunctionMessage(content=content, **kwargs)
+ elif message_type == "tool":
+ artifact = kwargs.get("additional_kwargs", {}).pop("artifact", None)
+ status = kwargs.get("additional_kwargs", {}).pop("status", None)
+ if status is not None:
+ kwargs["status"] = status
+ message = ToolMessage(content=content, artifact=artifact, **kwargs)
+ elif message_type == "remove":
+ message = RemoveMessage(**kwargs)
+ else:
+ msg = (
+ f"Unexpected message type: '{message_type}'. Use one of 'human',"
+ f" 'user', 'ai', 'assistant', 'function', 'tool', 'system', or 'developer'."
+ )
+ msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)
+ raise ValueError(msg)
+ return message
+
+
+def _convert_to_message(message: MessageLikeRepresentation) -> BaseMessage:
+ """Instantiate a `Message` from a variety of message formats.
+
+ The message format can be one of the following:
+
+ - `BaseMessagePromptTemplate`
+ - `BaseMessage`
+ - 2-tuple of (role string, template); e.g., (`'human'`, `'{user_input}'`)
+ - dict: a message dict with role and content keys
+ - string: shorthand for (`'human'`, template); e.g., `'{user_input}'`
+
+ Args:
+ message: a representation of a message in one of the supported formats.
+
+ Returns:
+ An instance of a message or a message template.
+
+ Raises:
+ NotImplementedError: if the message type is not supported.
+ ValueError: if the message dict does not contain the required keys.
+
+ """
+ if isinstance(message, BaseMessage):
+ message_ = message
+ elif isinstance(message, Sequence):
+ if isinstance(message, str):
+ message_ = _create_message_from_message_type("human", message)
+ else:
+ try:
+ message_type_str, template = message
+ except ValueError as e:
+ msg = "Message as a sequence must be (role string, template)"
+ raise NotImplementedError(msg) from e
+ message_ = _create_message_from_message_type(message_type_str, template)
+ elif isinstance(message, dict):
+ msg_kwargs = message.copy()
+ try:
+ try:
+ msg_type = msg_kwargs.pop("role")
+ except KeyError:
+ msg_type = msg_kwargs.pop("type")
+ # None msg content is not allowed
+ msg_content = msg_kwargs.pop("content") or ""
+ except KeyError as e:
+ msg = f"Message dict must contain 'role' and 'content' keys, got {message}"
+ msg = create_message(
+ message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE
+ )
+ raise ValueError(msg) from e
+ message_ = _create_message_from_message_type(
+ msg_type, msg_content, **msg_kwargs
+ )
+ else:
+ msg = f"Unsupported message type: {type(message)}"
+ msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)
+ raise NotImplementedError(msg)
+
+ return message_
+
+
+def convert_to_messages(
+ messages: Iterable[MessageLikeRepresentation] | PromptValue,
+) -> list[BaseMessage]:
+ """Convert a sequence of messages to a list of messages.
+
+ Args:
+ messages: Sequence of messages to convert.
+
+ Returns:
+ list of messages (BaseMessages).
+
+ """
+ # Import here to avoid circular imports
+ from langchain_core.prompt_values import PromptValue # noqa: PLC0415
+
+ if isinstance(messages, PromptValue):
+ return messages.to_messages()
+ return [_convert_to_message(m) for m in messages]
+
+
+_P = ParamSpec("_P")
+_R_co = TypeVar("_R_co", covariant=True)
+
+
+class _RunnableSupportCallable(Protocol[_P, _R_co]):
+ @overload
+ def __call__(
+ self,
+ messages: None = None,
+ *args: _P.args,
+ **kwargs: _P.kwargs,
+ ) -> Runnable[Sequence[MessageLikeRepresentation], _R_co]: ...
+
+ @overload
+ def __call__(
+ self,
+ messages: Sequence[MessageLikeRepresentation] | PromptValue,
+ *args: _P.args,
+ **kwargs: _P.kwargs,
+ ) -> _R_co: ...
+
+ def __call__(
+ self,
+ messages: Sequence[MessageLikeRepresentation] | PromptValue | None = None,
+ *args: _P.args,
+ **kwargs: _P.kwargs,
+ ) -> _R_co | Runnable[Sequence[MessageLikeRepresentation], _R_co]: ...
+
+
+def _runnable_support(
+ func: Callable[
+ Concatenate[Sequence[MessageLikeRepresentation] | PromptValue, _P], _R_co
+ ],
+) -> _RunnableSupportCallable[_P, _R_co]:
+ @wraps(func)
+ def wrapped(
+ messages: Sequence[MessageLikeRepresentation] | PromptValue | None = None,
+ *args: _P.args,
+ **kwargs: _P.kwargs,
+ ) -> _R_co | Runnable[Sequence[MessageLikeRepresentation], _R_co]:
+ # Import locally to prevent circular import.
+ from langchain_core.runnables.base import RunnableLambda # noqa: PLC0415
+
+ if messages is not None:
+ return func(messages, *args, **kwargs)
+ return RunnableLambda(partial(func, **kwargs), name=func.__name__)
+
+ return cast("_RunnableSupportCallable[_P, _R_co]", wrapped)
+
+
+@_runnable_support
+def filter_messages(
+ messages: Iterable[MessageLikeRepresentation] | PromptValue,
+ *,
+ include_names: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ include_types: Sequence[str | type[BaseMessage]] | None = None,
+ exclude_types: Sequence[str | type[BaseMessage]] | None = None,
+ include_ids: Sequence[str] | None = None,
+ exclude_ids: Sequence[str] | None = None,
+ exclude_tool_calls: Sequence[str] | bool | None = None,
+) -> list[BaseMessage]:
+ """Filter messages based on `name`, `type` or `id`.
+
+ Args:
+ messages: Sequence Message-like objects to filter.
+ include_names: Message names to include.
+ exclude_names: Messages names to exclude.
+ include_types: Message types to include. Can be specified as string names
+ (e.g. `'system'`, `'human'`, `'ai'`, ...) or as `BaseMessage`
+ classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...).
+
+ exclude_types: Message types to exclude. Can be specified as string names
+ (e.g. `'system'`, `'human'`, `'ai'`, ...) or as `BaseMessage`
+ classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...).
+
+ include_ids: Message IDs to include.
+ exclude_ids: Message IDs to exclude.
+ exclude_tool_calls: Tool call IDs to exclude.
+ Can be one of the following:
+ - `True`: All `AIMessage` objects with tool calls and all `ToolMessage`
+ objects will be excluded.
+ - a sequence of tool call IDs to exclude:
+ - `ToolMessage` objects with the corresponding tool call ID will be
+ excluded.
+ - The `tool_calls` in the AIMessage will be updated to exclude
+ matching tool calls. If all `tool_calls` are filtered from an
+ AIMessage, the whole message is excluded.
+
+ Returns:
+ A list of Messages that meets at least one of the `incl_*` conditions and none
+ of the `excl_*` conditions. If not `incl_*` conditions are specified then
+ anything that is not explicitly excluded will be included.
+
+ Raises:
+ ValueError: If two incompatible arguments are provided.
+
+ Example:
+ ```python
+ from langchain_core.messages import (
+ filter_messages,
+ AIMessage,
+ HumanMessage,
+ SystemMessage,
+ )
+
+ messages = [
+ SystemMessage("you're a good assistant."),
+ HumanMessage("what's your name", id="foo", name="example_user"),
+ AIMessage("steve-o", id="bar", name="example_assistant"),
+ HumanMessage(
+ "what's your favorite color",
+ id="baz",
+ ),
+ AIMessage(
+ "silicon blue",
+ id="blah",
+ ),
+ ]
+
+ filter_messages(
+ messages,
+ include_names=("example_user", "example_assistant"),
+ include_types=("system",),
+ exclude_ids=("bar",),
+ )
+ ```
+
+ ```python
+ [
+ SystemMessage("you're a good assistant."),
+ HumanMessage("what's your name", id="foo", name="example_user"),
+ ]
+ ```
+ """
+ messages = convert_to_messages(messages)
+ filtered: list[BaseMessage] = []
+ for msg in messages:
+ if (
+ (exclude_names and msg.name in exclude_names)
+ or (exclude_types and _is_message_type(msg, exclude_types))
+ or (exclude_ids and msg.id in exclude_ids)
+ ):
+ continue
+
+ if exclude_tool_calls is True and (
+ (isinstance(msg, AIMessage) and msg.tool_calls)
+ or isinstance(msg, ToolMessage)
+ ):
+ continue
+
+ new_msg = msg
+ if isinstance(exclude_tool_calls, (list, tuple, set)):
+ if isinstance(msg, AIMessage) and msg.tool_calls:
+ tool_calls = [
+ tool_call
+ for tool_call in msg.tool_calls
+ if tool_call["id"] not in exclude_tool_calls
+ ]
+ if not tool_calls:
+ continue
+
+ content = msg.content
+ # handle Anthropic content blocks
+ if isinstance(msg.content, list):
+ content = [
+ content_block
+ for content_block in msg.content
+ if (
+ not isinstance(content_block, dict)
+ or content_block.get("type") != "tool_use"
+ or content_block.get("id") not in exclude_tool_calls
+ )
+ ]
+
+ new_msg = msg.model_copy(
+ update={"tool_calls": tool_calls, "content": content}
+ )
+ elif (
+ isinstance(msg, ToolMessage) and msg.tool_call_id in exclude_tool_calls
+ ):
+ continue
+
+ # default to inclusion when no inclusion criteria given.
+ if (
+ not (include_types or include_ids or include_names)
+ or (include_names and new_msg.name in include_names)
+ or (include_types and _is_message_type(new_msg, include_types))
+ or (include_ids and new_msg.id in include_ids)
+ ):
+ filtered.append(new_msg)
+
+ return filtered
+
+
+@_runnable_support
+def merge_message_runs(
+ messages: Iterable[MessageLikeRepresentation] | PromptValue,
+ *,
+ chunk_separator: str = "\n",
+) -> list[BaseMessage]:
+ r"""Merge consecutive Messages of the same type.
+
+ !!! note
+ `ToolMessage` objects are not merged, as each has a distinct tool call id that
+ can't be merged.
+
+ Args:
+ messages: Sequence Message-like objects to merge.
+ chunk_separator: Specify the string to be inserted between message chunks.
+
+ Returns:
+ list of BaseMessages with consecutive runs of message types merged into single
+ messages. By default, if two messages being merged both have string contents,
+ the merged content is a concatenation of the two strings with a new-line
+ separator.
+ The separator inserted between message chunks can be controlled by specifying
+ any string with `chunk_separator`. If at least one of the messages has a list
+ of content blocks, the merged content is a list of content blocks.
+
+ Example:
+ ```python
+ from langchain_core.messages import (
+ merge_message_runs,
+ AIMessage,
+ HumanMessage,
+ SystemMessage,
+ ToolCall,
+ )
+
+ messages = [
+ SystemMessage("you're a good assistant."),
+ HumanMessage(
+ "what's your favorite color",
+ id="foo",
+ ),
+ HumanMessage(
+ "wait your favorite food",
+ id="bar",
+ ),
+ AIMessage(
+ "my favorite colo",
+ tool_calls=[
+ ToolCall(
+ name="blah_tool", args={"x": 2}, id="123", type="tool_call"
+ )
+ ],
+ id="baz",
+ ),
+ AIMessage(
+ [{"type": "text", "text": "my favorite dish is lasagna"}],
+ tool_calls=[
+ ToolCall(
+ name="blah_tool",
+ args={"x": -10},
+ id="456",
+ type="tool_call",
+ )
+ ],
+ id="blur",
+ ),
+ ]
+
+ merge_message_runs(messages)
+ ```
+
+ ```python
+ [
+ SystemMessage("you're a good assistant."),
+ HumanMessage(
+ "what's your favorite color\\n"
+ "wait your favorite food", id="foo",
+ ),
+ AIMessage(
+ [
+ "my favorite colo",
+ {"type": "text", "text": "my favorite dish is lasagna"}
+ ],
+ tool_calls=[
+ ToolCall({
+ "name": "blah_tool",
+ "args": {"x": 2},
+ "id": "123",
+ "type": "tool_call"
+ }),
+ ToolCall({
+ "name": "blah_tool",
+ "args": {"x": -10},
+ "id": "456",
+ "type": "tool_call"
+ })
+ ]
+ id="baz"
+ ),
+ ]
+
+ ```
+ """
+ if not messages:
+ return []
+ messages = convert_to_messages(messages)
+ merged: list[BaseMessage] = []
+ for msg in messages:
+ last = merged.pop() if merged else None
+ if not last:
+ merged.append(msg)
+ elif isinstance(msg, ToolMessage) or not isinstance(msg, last.__class__):
+ merged.extend([last, msg])
+ else:
+ last_chunk = _msg_to_chunk(last)
+ curr_chunk = _msg_to_chunk(msg)
+ if curr_chunk.response_metadata:
+ curr_chunk.response_metadata.clear()
+ if (
+ isinstance(last_chunk.content, str)
+ and isinstance(curr_chunk.content, str)
+ and last_chunk.content
+ and curr_chunk.content
+ ):
+ last_chunk.content += chunk_separator
+ merged.append(_chunk_to_msg(last_chunk + curr_chunk))
+ return merged
+
+
+# TODO: Update so validation errors (for token_counter, for example) are raised on
+# init not at runtime.
+@_runnable_support
+def trim_messages(
+ messages: Iterable[MessageLikeRepresentation] | PromptValue,
+ *,
+ max_tokens: int,
+ token_counter: Callable[[list[BaseMessage]], int]
+ | Callable[[BaseMessage], int]
+ | BaseLanguageModel
+ | Literal["approximate"],
+ strategy: Literal["first", "last"] = "last",
+ allow_partial: bool = False,
+ end_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
+ start_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
+ include_system: bool = False,
+ text_splitter: Callable[[str], list[str]] | TextSplitter | None = None,
+) -> list[BaseMessage]:
+ r"""Trim messages to be below a token count.
+
+ `trim_messages` can be used to reduce the size of a chat history to a specified
+ token or message count.
+
+ In either case, if passing the trimmed chat history back into a chat model
+ directly, the resulting chat history should usually satisfy the following
+ properties:
+
+ 1. The resulting chat history should be valid. Most chat models expect that chat
+ history starts with either (1) a `HumanMessage` or (2) a `SystemMessage`
+ followed by a `HumanMessage`. To achieve this, set `start_on='human'`.
+ In addition, generally a `ToolMessage` can only appear after an `AIMessage`
+ that involved a tool call.
+ 2. It includes recent messages and drops old messages in the chat history.
+ To achieve this set the `strategy='last'`.
+ 3. Usually, the new chat history should include the `SystemMessage` if it
+ was present in the original chat history since the `SystemMessage` includes
+ special instructions to the chat model. The `SystemMessage` is almost always
+ the first message in the history if present. To achieve this set the
+ `include_system=True`.
+
+ !!! note
+ The examples below show how to configure `trim_messages` to achieve a behavior
+ consistent with the above properties.
+
+ Args:
+ messages: Sequence of Message-like objects to trim.
+ max_tokens: Max token count of trimmed messages.
+ token_counter: Function or llm for counting tokens in a `BaseMessage` or a
+ list of `BaseMessage`.
+
+ If a `BaseLanguageModel` is passed in then
+ `BaseLanguageModel.get_num_tokens_from_messages()` will be used. Set to
+ `len` to count the number of **messages** in the chat history.
+
+ You can also use string shortcuts for convenience:
+
+ - `'approximate'`: Uses `count_tokens_approximately` for fast, approximate
+ token counts.
+
+ !!! note
+
+ `count_tokens_approximately` (or the shortcut `'approximate'`) is
+ recommended for using `trim_messages` on the hot path, where exact token
+ counting is not necessary.
+
+ strategy: Strategy for trimming.
+
+ - `'first'`: Keep the first `<= n_count` tokens of the messages.
+ - `'last'`: Keep the last `<= n_count` tokens of the messages.
+ allow_partial: Whether to split a message if only part of the message can be
+ included.
+
+ If `strategy='last'` then the last partial contents of a message are
+ included. If `strategy='first'` then the first partial contents of a
+ message are included.
+ end_on: The message type to end on.
+
+ If specified then every message after the last occurrence of this type is
+ ignored. If `strategy='last'` then this is done before we attempt to get the
+ last `max_tokens`. If `strategy='first'` then this is done after we get the
+ first `max_tokens`. Can be specified as string names (e.g. `'system'`,
+ `'human'`, `'ai'`, ...) or as `BaseMessage` classes (e.g. `SystemMessage`,
+ `HumanMessage`, `AIMessage`, ...). Can be a single type or a list of types.
+
+ start_on: The message type to start on.
+
+ Should only be specified if `strategy='last'`. If specified then every
+ message before the first occurrence of this type is ignored. This is done
+ after we trim the initial messages to the last `max_tokens`. Does not apply
+ to a `SystemMessage` at index 0 if `include_system=True`. Can be specified
+ as string names (e.g. `'system'`, `'human'`, `'ai'`, ...) or as
+ `BaseMessage` classes (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`,
+ ...). Can be a single type or a list of types.
+
+ include_system: Whether to keep the `SystemMessage` if there is one at index
+ `0`.
+
+ Should only be specified if `strategy="last"`.
+ text_splitter: Function or `langchain_text_splitters.TextSplitter` for
+ splitting the string contents of a message.
+
+ Only used if `allow_partial=True`. If `strategy='last'` then the last split
+ tokens from a partial message will be included. if `strategy='first'` then
+ the first split tokens from a partial message will be included. Token
+ splitter assumes that separators are kept, so that split contents can be
+ directly concatenated to recreate the original text. Defaults to splitting
+ on newlines.
+
+ Returns:
+ List of trimmed `BaseMessage`.
+
+ Raises:
+ ValueError: if two incompatible arguments are specified or an unrecognized
+ `strategy` is specified.
+
+ Example:
+ Trim chat history based on token count, keeping the `SystemMessage` if
+ present, and ensuring that the chat history starts with a `HumanMessage` (or a
+ `SystemMessage` followed by a `HumanMessage`).
+
+ ```python
+ from langchain_core.messages import (
+ AIMessage,
+ HumanMessage,
+ BaseMessage,
+ SystemMessage,
+ trim_messages,
+ )
+
+ messages = [
+ SystemMessage("you're a good assistant, you always respond with a joke."),
+ HumanMessage("i wonder why it's called langchain"),
+ AIMessage(
+ 'Well, I guess they thought "WordRope" and "SentenceString" just '
+ "didn't have the same ring to it!"
+ ),
+ HumanMessage("and who is harrison chasing anyways"),
+ AIMessage(
+ "Hmmm let me think.\n\nWhy, he's probably chasing after the last "
+ "cup of coffee in the office!"
+ ),
+ HumanMessage("what do you call a speechless parrot"),
+ ]
+
+
+ trim_messages(
+ messages,
+ max_tokens=45,
+ strategy="last",
+ token_counter=ChatOpenAI(model="gpt-4o"),
+ # Most chat models expect that chat history starts with either:
+ # (1) a HumanMessage or
+ # (2) a SystemMessage followed by a HumanMessage
+ start_on="human",
+ # Usually, we want to keep the SystemMessage
+ # if it's present in the original history.
+ # The SystemMessage has special instructions for the model.
+ include_system=True,
+ allow_partial=False,
+ )
+ ```
+
+ ```python
+ [
+ SystemMessage(
+ content="you're a good assistant, you always respond with a joke."
+ ),
+ HumanMessage(content="what do you call a speechless parrot"),
+ ]
+ ```
+
+ Trim chat history using approximate token counting with `'approximate'`:
+
+ ```python
+ trim_messages(
+ messages,
+ max_tokens=45,
+ strategy="last",
+ # Using the "approximate" shortcut for fast token counting
+ token_counter="approximate",
+ start_on="human",
+ include_system=True,
+ )
+
+ # This is equivalent to using `count_tokens_approximately` directly
+ from langchain_core.messages.utils import count_tokens_approximately
+
+ trim_messages(
+ messages,
+ max_tokens=45,
+ strategy="last",
+ token_counter=count_tokens_approximately,
+ start_on="human",
+ include_system=True,
+ )
+ ```
+
+ Trim chat history based on the message count, keeping the `SystemMessage` if
+ present, and ensuring that the chat history starts with a HumanMessage (
+ or a `SystemMessage` followed by a `HumanMessage`).
+
+ trim_messages(
+ messages,
+ # When `len` is passed in as the token counter function,
+ # max_tokens will count the number of messages in the chat history.
+ max_tokens=4,
+ strategy="last",
+ # Passing in `len` as a token counter function will
+ # count the number of messages in the chat history.
+ token_counter=len,
+ # Most chat models expect that chat history starts with either:
+ # (1) a HumanMessage or
+ # (2) a SystemMessage followed by a HumanMessage
+ start_on="human",
+ # Usually, we want to keep the SystemMessage
+ # if it's present in the original history.
+ # The SystemMessage has special instructions for the model.
+ include_system=True,
+ allow_partial=False,
+ )
+
+ ```python
+ [
+ SystemMessage(
+ content="you're a good assistant, you always respond with a joke."
+ ),
+ HumanMessage(content="and who is harrison chasing anyways"),
+ AIMessage(
+ content="Hmmm let me think.\n\nWhy, he's probably chasing after "
+ "the last cup of coffee in the office!"
+ ),
+ HumanMessage(content="what do you call a speechless parrot"),
+ ]
+ ```
+ Trim chat history using a custom token counter function that counts the
+ number of tokens in each message.
+
+ ```python
+ messages = [
+ SystemMessage("This is a 4 token text. The full message is 10 tokens."),
+ HumanMessage(
+ "This is a 4 token text. The full message is 10 tokens.", id="first"
+ ),
+ AIMessage(
+ [
+ {"type": "text", "text": "This is the FIRST 4 token block."},
+ {"type": "text", "text": "This is the SECOND 4 token block."},
+ ],
+ id="second",
+ ),
+ HumanMessage(
+ "This is a 4 token text. The full message is 10 tokens.", id="third"
+ ),
+ AIMessage(
+ "This is a 4 token text. The full message is 10 tokens.",
+ id="fourth",
+ ),
+ ]
+
+
+ def dummy_token_counter(messages: list[BaseMessage]) -> int:
+ # treat each message like it adds 3 default tokens at the beginning
+ # of the message and at the end of the message. 3 + 4 + 3 = 10 tokens
+ # per message.
+
+ default_content_len = 4
+ default_msg_prefix_len = 3
+ default_msg_suffix_len = 3
+
+ count = 0
+ for msg in messages:
+ if isinstance(msg.content, str):
+ count += (
+ default_msg_prefix_len
+ + default_content_len
+ + default_msg_suffix_len
+ )
+ if isinstance(msg.content, list):
+ count += (
+ default_msg_prefix_len
+ + len(msg.content) * default_content_len
+ + default_msg_suffix_len
+ )
+ return count
+ ```
+
+ First 30 tokens, allowing partial messages:
+ ```python
+ trim_messages(
+ messages,
+ max_tokens=30,
+ token_counter=dummy_token_counter,
+ strategy="first",
+ allow_partial=True,
+ )
+ ```
+
+ ```python
+ [
+ SystemMessage("This is a 4 token text. The full message is 10 tokens."),
+ HumanMessage(
+ "This is a 4 token text. The full message is 10 tokens.",
+ id="first",
+ ),
+ AIMessage(
+ [{"type": "text", "text": "This is the FIRST 4 token block."}],
+ id="second",
+ ),
+ ]
+ ```
+ """
+ # Validate arguments
+ if start_on and strategy == "first":
+ msg = "start_on parameter is only valid with strategy='last'"
+ raise ValueError(msg)
+ if include_system and strategy == "first":
+ msg = "include_system parameter is only valid with strategy='last'"
+ raise ValueError(msg)
+
+ messages = convert_to_messages(messages)
+
+ # Handle string shortcuts for token counter
+ if isinstance(token_counter, str):
+ if token_counter in _TOKEN_COUNTER_SHORTCUTS:
+ actual_token_counter = _TOKEN_COUNTER_SHORTCUTS[token_counter]
+ else:
+ available_shortcuts = ", ".join(
+ f"'{key}'" for key in _TOKEN_COUNTER_SHORTCUTS
+ )
+ msg = (
+ f"Invalid token_counter shortcut '{token_counter}'. "
+ f"Available shortcuts: {available_shortcuts}."
+ )
+ raise ValueError(msg)
+ else:
+ # Type narrowing: at this point token_counter is not a str
+ actual_token_counter = token_counter # type: ignore[assignment]
+
+ if hasattr(actual_token_counter, "get_num_tokens_from_messages"):
+ list_token_counter = actual_token_counter.get_num_tokens_from_messages
+ elif callable(actual_token_counter):
+ if (
+ next(
+ iter(inspect.signature(actual_token_counter).parameters.values())
+ ).annotation
+ is BaseMessage
+ ):
+
+ def list_token_counter(messages: Sequence[BaseMessage]) -> int:
+ return sum(actual_token_counter(msg) for msg in messages) # type: ignore[arg-type, misc]
+
+ else:
+ list_token_counter = actual_token_counter
+ else:
+ msg = (
+ f"'token_counter' expected to be a model that implements "
+ f"'get_num_tokens_from_messages()' or a function. Received object of type "
+ f"{type(actual_token_counter)}."
+ )
+ raise ValueError(msg)
+
+ if _HAS_LANGCHAIN_TEXT_SPLITTERS and isinstance(text_splitter, TextSplitter):
+ text_splitter_fn = text_splitter.split_text
+ elif text_splitter:
+ text_splitter_fn = cast("Callable", text_splitter)
+ else:
+ text_splitter_fn = _default_text_splitter
+
+ if strategy == "first":
+ return _first_max_tokens(
+ messages,
+ max_tokens=max_tokens,
+ token_counter=list_token_counter,
+ text_splitter=text_splitter_fn,
+ partial_strategy="first" if allow_partial else None,
+ end_on=end_on,
+ )
+ if strategy == "last":
+ return _last_max_tokens(
+ messages,
+ max_tokens=max_tokens,
+ token_counter=list_token_counter,
+ allow_partial=allow_partial,
+ include_system=include_system,
+ start_on=start_on,
+ end_on=end_on,
+ text_splitter=text_splitter_fn,
+ )
+ msg = f"Unrecognized {strategy=}. Supported strategies are 'last' and 'first'."
+ raise ValueError(msg)
+
+
+_SingleMessage = BaseMessage | str | dict[str, Any]
+_T = TypeVar("_T", bound=_SingleMessage)
+# A sequence of _SingleMessage that is NOT a bare str
+_MultipleMessages = Sequence[_T]
+
+
+@overload
+def convert_to_openai_messages(
+ messages: _SingleMessage,
+ *,
+ text_format: Literal["string", "block"] = "string",
+ include_id: bool = False,
+ pass_through_unknown_blocks: bool = True,
+) -> dict: ...
+
+
+@overload
+def convert_to_openai_messages(
+ messages: _MultipleMessages,
+ *,
+ text_format: Literal["string", "block"] = "string",
+ include_id: bool = False,
+ pass_through_unknown_blocks: bool = True,
+) -> list[dict]: ...
+
+
+def convert_to_openai_messages(
+ messages: MessageLikeRepresentation | Sequence[MessageLikeRepresentation],
+ *,
+ text_format: Literal["string", "block"] = "string",
+ include_id: bool = False,
+ pass_through_unknown_blocks: bool = True,
+) -> dict | list[dict]:
+ """Convert LangChain messages into OpenAI message dicts.
+
+ Args:
+ messages: Message-like object or iterable of objects whose contents are
+ in OpenAI, Anthropic, Bedrock Converse, or VertexAI formats.
+ text_format: How to format string or text block contents:
+ - `'string'`:
+ If a message has a string content, this is left as a string. If
+ a message has content blocks that are all of type `'text'`, these
+ are joined with a newline to make a single string. If a message has
+ content blocks and at least one isn't of type `'text'`, then
+ all blocks are left as dicts.
+ - `'block'`:
+ If a message has a string content, this is turned into a list
+ with a single content block of type `'text'`. If a message has
+ content blocks these are left as is.
+ include_id: Whether to include message IDs in the openai messages, if they
+ are present in the source messages.
+ pass_through_unknown_blocks: Whether to include content blocks with unknown
+ formats in the output. If `False`, an error is raised if an unknown
+ content block is encountered.
+
+ Raises:
+ ValueError: if an unrecognized `text_format` is specified, or if a message
+ content block is missing expected keys.
+
+ Returns:
+ The return type depends on the input type:
+
+ - dict:
+ If a single message-like object is passed in, a single OpenAI message
+ dict is returned.
+ - list[dict]:
+ If a sequence of message-like objects are passed in, a list of OpenAI
+ message dicts is returned.
+
+ Example:
+ ```python
+ from langchain_core.messages import (
+ convert_to_openai_messages,
+ AIMessage,
+ SystemMessage,
+ ToolMessage,
+ )
+
+ messages = [
+ SystemMessage([{"type": "text", "text": "foo"}]),
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "what's in this"},
+ {
+ "type": "image_url",
+ "image_url": {"url": "data:image/png;base64,'/9j/4AAQSk'"},
+ },
+ ],
+ },
+ AIMessage(
+ "",
+ tool_calls=[
+ {
+ "name": "analyze",
+ "args": {"baz": "buz"},
+ "id": "1",
+ "type": "tool_call",
+ }
+ ],
+ ),
+ ToolMessage("foobar", tool_call_id="1", name="bar"),
+ {"role": "assistant", "content": "that's nice"},
+ ]
+ oai_messages = convert_to_openai_messages(messages)
+ # -> [
+ # {'role': 'system', 'content': 'foo'},
+ # {'role': 'user', 'content': [{'type': 'text', 'text': 'what's in this'}, {'type': 'image_url', 'image_url': {'url': "data:image/png;base64,'/9j/4AAQSk'"}}]},
+ # {'role': 'assistant', 'tool_calls': [{'type': 'function', 'id': '1','function': {'name': 'analyze', 'arguments': '{"baz": "buz"}'}}], 'content': ''},
+ # {'role': 'tool', 'name': 'bar', 'content': 'foobar'},
+ # {'role': 'assistant', 'content': 'that's nice'}
+ # ]
+ ```
+
+ !!! version-added "Added in `langchain-core` 0.3.11"
+
+ """ # noqa: E501
+ if text_format not in {"string", "block"}:
+ err = f"Unrecognized {text_format=}, expected one of 'string' or 'block'."
+ raise ValueError(err)
+
+ oai_messages: list[dict] = []
+
+ if is_single := isinstance(messages, (BaseMessage, dict, str)):
+ messages = [messages]
+
+ messages = convert_to_messages(messages)
+
+ for i, message in enumerate(messages):
+ oai_msg: dict = {"role": _get_message_openai_role(message)}
+ tool_messages: list = []
+ content: str | list[dict]
+
+ if message.name:
+ oai_msg["name"] = message.name
+ if isinstance(message, AIMessage) and message.tool_calls:
+ oai_msg["tool_calls"] = _convert_to_openai_tool_calls(message.tool_calls)
+ if message.additional_kwargs.get("refusal"):
+ oai_msg["refusal"] = message.additional_kwargs["refusal"]
+ if isinstance(message, ToolMessage):
+ oai_msg["tool_call_id"] = message.tool_call_id
+ if include_id and message.id:
+ oai_msg["id"] = message.id
+
+ if not message.content:
+ content = "" if text_format == "string" else []
+ elif isinstance(message.content, str):
+ if text_format == "string":
+ content = message.content
+ else:
+ content = [{"type": "text", "text": message.content}]
+ elif text_format == "string" and all(
+ isinstance(block, str) or block.get("type") == "text"
+ for block in message.content
+ ):
+ content = "\n".join(
+ block if isinstance(block, str) else block["text"]
+ for block in message.content
+ )
+ else:
+ content = []
+ for j, block in enumerate(message.content):
+ # OpenAI format
+ if isinstance(block, str):
+ content.append({"type": "text", "text": block})
+ elif block.get("type") == "text":
+ if missing := [k for k in ("text",) if k not in block]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': 'text' "
+ f"but is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ content.append({"type": block["type"], "text": block["text"]})
+ elif block.get("type") == "image_url":
+ if missing := [k for k in ("image_url",) if k not in block]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': 'image_url' "
+ f"but is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ content.append(
+ {
+ "type": "image_url",
+ "image_url": block["image_url"],
+ }
+ )
+ # Standard multi-modal content block
+ elif is_data_content_block(block):
+ formatted_block = convert_to_openai_data_block(block)
+ if (
+ formatted_block.get("type") == "file"
+ and "file" in formatted_block
+ and "filename" not in formatted_block["file"]
+ ):
+ logger.info("Generating a fallback filename.")
+ formatted_block["file"]["filename"] = "LC_AUTOGENERATED"
+ content.append(formatted_block)
+ # Anthropic and Bedrock converse format
+ elif (block.get("type") == "image") or "image" in block:
+ # Anthropic
+ if source := block.get("source"):
+ if missing := [
+ k for k in ("media_type", "type", "data") if k not in source
+ ]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': 'image' "
+ f"but 'source' is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ content.append(
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": (
+ f"data:{source['media_type']};"
+ f"{source['type']},{source['data']}"
+ )
+ },
+ }
+ )
+ # Bedrock converse
+ elif image := block.get("image"):
+ if missing := [
+ k for k in ("source", "format") if k not in image
+ ]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has key 'image', "
+ f"but 'image' is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ b64_image = _bytes_to_b64_str(image["source"]["bytes"])
+ content.append(
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": (
+ f"data:image/{image['format']};base64,{b64_image}"
+ )
+ },
+ }
+ )
+ else:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': 'image' "
+ f"but does not have a 'source' or 'image' key. Full "
+ f"content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ # OpenAI file format
+ elif (
+ block.get("type") == "file"
+ and isinstance(block.get("file"), dict)
+ and isinstance(block.get("file", {}).get("file_data"), str)
+ ):
+ if block.get("file", {}).get("filename") is None:
+ logger.info("Generating a fallback filename.")
+ block["file"]["filename"] = "LC_AUTOGENERATED"
+ content.append(block)
+ # OpenAI audio format
+ elif (
+ block.get("type") == "input_audio"
+ and isinstance(block.get("input_audio"), dict)
+ and isinstance(block.get("input_audio", {}).get("data"), str)
+ and isinstance(block.get("input_audio", {}).get("format"), str)
+ ):
+ content.append(block)
+ elif block.get("type") == "tool_use":
+ if missing := [
+ k for k in ("id", "name", "input") if k not in block
+ ]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': "
+ f"'tool_use', but is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ if not any(
+ tool_call["id"] == block["id"]
+ for tool_call in cast("AIMessage", message).tool_calls
+ ):
+ oai_msg["tool_calls"] = oai_msg.get("tool_calls", [])
+ oai_msg["tool_calls"].append(
+ {
+ "type": "function",
+ "id": block["id"],
+ "function": {
+ "name": block["name"],
+ "arguments": json.dumps(
+ block["input"], ensure_ascii=False
+ ),
+ },
+ }
+ )
+ elif block.get("type") == "function_call": # OpenAI Responses
+ if not any(
+ tool_call["id"] == block.get("call_id")
+ for tool_call in cast("AIMessage", message).tool_calls
+ ):
+ if missing := [
+ k
+ for k in ("call_id", "name", "arguments")
+ if k not in block
+ ]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': "
+ f"'tool_use', but is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ oai_msg["tool_calls"] = oai_msg.get("tool_calls", [])
+ oai_msg["tool_calls"].append(
+ {
+ "type": "function",
+ "id": block.get("call_id"),
+ "function": {
+ "name": block.get("name"),
+ "arguments": block.get("arguments"),
+ },
+ }
+ )
+ if pass_through_unknown_blocks:
+ content.append(block)
+ elif block.get("type") == "tool_result":
+ if missing := [
+ k for k in ("content", "tool_use_id") if k not in block
+ ]:
+ msg = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': "
+ f"'tool_result', but is missing expected key(s) "
+ f"{missing}. Full content block:\n\n{block}"
+ )
+ raise ValueError(msg)
+ tool_message = ToolMessage(
+ block["content"],
+ tool_call_id=block["tool_use_id"],
+ status="error" if block.get("is_error") else "success",
+ )
+ # Recurse to make sure tool message contents are OpenAI format.
+ tool_messages.extend(
+ convert_to_openai_messages(
+ [tool_message], text_format=text_format
+ )
+ )
+ elif (block.get("type") == "json") or "json" in block:
+ if "json" not in block:
+ msg = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': 'json' "
+ f"but does not have a 'json' key. Full "
+ f"content block:\n\n{block}"
+ )
+ raise ValueError(msg)
+ content.append(
+ {
+ "type": "text",
+ "text": json.dumps(block["json"]),
+ }
+ )
+ elif (block.get("type") == "guard_content") or "guard_content" in block:
+ if (
+ "guard_content" not in block
+ or "text" not in block["guard_content"]
+ ):
+ msg = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': "
+ f"'guard_content' but does not have a "
+ f"messages[{i}].content[{j}]['guard_content']['text'] "
+ f"key. Full content block:\n\n{block}"
+ )
+ raise ValueError(msg)
+ text = block["guard_content"]["text"]
+ if isinstance(text, dict):
+ text = text["text"]
+ content.append({"type": "text", "text": text})
+ # VertexAI format
+ elif block.get("type") == "media":
+ if missing := [k for k in ("mime_type", "data") if k not in block]:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] has 'type': "
+ f"'media' but does not have key(s) {missing}. Full "
+ f"content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ if "image" not in block["mime_type"]:
+ err = (
+ f"OpenAI messages can only support text and image data."
+ f" Received content block with media of type:"
+ f" {block['mime_type']}"
+ )
+ raise ValueError(err)
+ b64_image = _bytes_to_b64_str(block["data"])
+ content.append(
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": (f"data:{block['mime_type']};base64,{b64_image}")
+ },
+ }
+ )
+ elif (
+ block.get("type") in {"thinking", "reasoning"}
+ or pass_through_unknown_blocks
+ ):
+ content.append(block)
+ else:
+ err = (
+ f"Unrecognized content block at "
+ f"messages[{i}].content[{j}] does not match OpenAI, "
+ f"Anthropic, Bedrock Converse, or VertexAI format. Full "
+ f"content block:\n\n{block}"
+ )
+ raise ValueError(err)
+ if text_format == "string" and not any(
+ block["type"] != "text" for block in content
+ ):
+ content = "\n".join(block["text"] for block in content)
+ oai_msg["content"] = content
+ if message.content and not oai_msg["content"] and tool_messages:
+ oai_messages.extend(tool_messages)
+ else:
+ oai_messages.extend([oai_msg, *tool_messages])
+
+ if is_single:
+ return oai_messages[0]
+ return oai_messages
+
+
+def _first_max_tokens(
+ messages: Sequence[BaseMessage],
+ *,
+ max_tokens: int,
+ token_counter: Callable[[list[BaseMessage]], int],
+ text_splitter: Callable[[str], list[str]],
+ partial_strategy: Literal["first", "last"] | None = None,
+ end_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
+) -> list[BaseMessage]:
+ messages = list(messages)
+ if not messages:
+ return messages
+
+ # Check if all messages already fit within token limit
+ if token_counter(messages) <= max_tokens:
+ # When all messages fit, only apply end_on filtering if needed
+ if end_on:
+ for _ in range(len(messages)):
+ if not _is_message_type(messages[-1], end_on):
+ messages.pop()
+ else:
+ break
+ return messages
+
+ # Use binary search to find the maximum number of messages within token limit
+ left, right = 0, len(messages)
+ max_iterations = len(messages).bit_length()
+ for _ in range(max_iterations):
+ if left >= right:
+ break
+ mid = (left + right + 1) // 2
+ if token_counter(messages[:mid]) <= max_tokens:
+ left = mid
+ idx = mid
+ else:
+ right = mid - 1
+
+ # idx now contains the maximum number of complete messages we can include
+ idx = left
+
+ if partial_strategy and idx < len(messages):
+ included_partial = False
+ copied = False
+ if isinstance(messages[idx].content, list):
+ excluded = messages[idx].model_copy(deep=True)
+ copied = True
+ num_block = len(excluded.content)
+ if partial_strategy == "last":
+ excluded.content = list(reversed(excluded.content))
+ for _ in range(1, num_block):
+ excluded.content = excluded.content[:-1]
+ if token_counter([*messages[:idx], excluded]) <= max_tokens:
+ messages = [*messages[:idx], excluded]
+ idx += 1
+ included_partial = True
+ break
+ if included_partial and partial_strategy == "last":
+ excluded.content = list(reversed(excluded.content))
+ if not included_partial:
+ if not copied:
+ excluded = messages[idx].model_copy(deep=True)
+ copied = True
+
+ # Extract text content efficiently
+ text = None
+ if isinstance(excluded.content, str):
+ text = excluded.content
+ elif isinstance(excluded.content, list) and excluded.content:
+ for block in excluded.content:
+ if isinstance(block, str):
+ text = block
+ break
+ if isinstance(block, dict) and block.get("type") == "text":
+ text = block.get("text")
+ break
+
+ if text:
+ if not copied:
+ excluded = excluded.model_copy(deep=True)
+
+ split_texts = text_splitter(text)
+ base_message_count = token_counter(messages[:idx])
+ if partial_strategy == "last":
+ split_texts = list(reversed(split_texts))
+
+ # Binary search for the maximum number of splits we can include
+ left, right = 0, len(split_texts)
+ max_iterations = len(split_texts).bit_length()
+ for _ in range(max_iterations):
+ if left >= right:
+ break
+ mid = (left + right + 1) // 2
+ excluded.content = "".join(split_texts[:mid])
+ if base_message_count + token_counter([excluded]) <= max_tokens:
+ left = mid
+ else:
+ right = mid - 1
+
+ if left > 0:
+ content_splits = split_texts[:left]
+ if partial_strategy == "last":
+ content_splits = list(reversed(content_splits))
+ excluded.content = "".join(content_splits)
+ messages = [*messages[:idx], excluded]
+ idx += 1
+
+ if end_on:
+ for _ in range(idx):
+ if idx > 0 and not _is_message_type(messages[idx - 1], end_on):
+ idx -= 1
+ else:
+ break
+
+ return messages[:idx]
+
+
+def _last_max_tokens(
+ messages: Sequence[BaseMessage],
+ *,
+ max_tokens: int,
+ token_counter: Callable[[list[BaseMessage]], int],
+ text_splitter: Callable[[str], list[str]],
+ allow_partial: bool = False,
+ include_system: bool = False,
+ start_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
+ end_on: str | type[BaseMessage] | Sequence[str | type[BaseMessage]] | None = None,
+) -> list[BaseMessage]:
+ messages = list(messages)
+ if len(messages) == 0:
+ return []
+
+ # Filter out messages after end_on type
+ if end_on:
+ for _ in range(len(messages)):
+ if not _is_message_type(messages[-1], end_on):
+ messages.pop()
+ else:
+ break
+
+ # Handle system message preservation
+ system_message = None
+ if include_system and len(messages) > 0 and isinstance(messages[0], SystemMessage):
+ system_message = messages[0]
+ messages = messages[1:]
+
+ # Reverse messages to use _first_max_tokens with reversed logic
+ reversed_messages = messages[::-1]
+
+ # Calculate remaining tokens after accounting for system message if present
+ remaining_tokens = max_tokens
+ if system_message:
+ system_tokens = token_counter([system_message])
+ remaining_tokens = max(0, max_tokens - system_tokens)
+
+ reversed_result = _first_max_tokens(
+ reversed_messages,
+ max_tokens=remaining_tokens,
+ token_counter=token_counter,
+ text_splitter=text_splitter,
+ partial_strategy="last" if allow_partial else None,
+ end_on=start_on,
+ )
+
+ # Re-reverse the messages and add back the system message if needed
+ result = reversed_result[::-1]
+ if system_message:
+ result = [system_message, *result]
+
+ return result
+
+
+_MSG_CHUNK_MAP: dict[type[BaseMessage], type[BaseMessageChunk]] = {
+ HumanMessage: HumanMessageChunk,
+ AIMessage: AIMessageChunk,
+ SystemMessage: SystemMessageChunk,
+ ToolMessage: ToolMessageChunk,
+ FunctionMessage: FunctionMessageChunk,
+ ChatMessage: ChatMessageChunk,
+}
+_CHUNK_MSG_MAP = {v: k for k, v in _MSG_CHUNK_MAP.items()}
+
+
+def _msg_to_chunk(message: BaseMessage) -> BaseMessageChunk:
+ if message.__class__ in _MSG_CHUNK_MAP:
+ return _MSG_CHUNK_MAP[message.__class__](**message.model_dump(exclude={"type"}))
+
+ for msg_cls, chunk_cls in _MSG_CHUNK_MAP.items():
+ if isinstance(message, msg_cls):
+ return chunk_cls(**message.model_dump(exclude={"type"}))
+
+ msg = (
+ f"Unrecognized message class {message.__class__}. Supported classes are "
+ f"{list(_MSG_CHUNK_MAP.keys())}"
+ )
+ msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)
+ raise ValueError(msg)
+
+
+def _chunk_to_msg(chunk: BaseMessageChunk) -> BaseMessage:
+ if chunk.__class__ in _CHUNK_MSG_MAP:
+ return _CHUNK_MSG_MAP[chunk.__class__](
+ **chunk.model_dump(exclude={"type", "tool_call_chunks", "chunk_position"})
+ )
+ for chunk_cls, msg_cls in _CHUNK_MSG_MAP.items():
+ if isinstance(chunk, chunk_cls):
+ return msg_cls(
+ **chunk.model_dump(
+ exclude={"type", "tool_call_chunks", "chunk_position"}
+ )
+ )
+
+ msg = (
+ f"Unrecognized message chunk class {chunk.__class__}. Supported classes are "
+ f"{list(_CHUNK_MSG_MAP.keys())}"
+ )
+ msg = create_message(message=msg, error_code=ErrorCode.MESSAGE_COERCION_FAILURE)
+ raise ValueError(msg)
+
+
+def _default_text_splitter(text: str) -> list[str]:
+ splits = text.split("\n")
+ return [s + "\n" for s in splits[:-1]] + splits[-1:]
+
+
+def _is_message_type(
+ message: BaseMessage,
+ type_: str | type[BaseMessage] | Sequence[str | type[BaseMessage]],
+) -> bool:
+ types = [type_] if isinstance(type_, (str, type)) else type_
+ types_str = [t for t in types if isinstance(t, str)]
+ types_types = tuple(t for t in types if isinstance(t, type))
+
+ return message.type in types_str or isinstance(message, types_types)
+
+
+def _bytes_to_b64_str(bytes_: bytes) -> str:
+ return base64.b64encode(bytes_).decode("utf-8")
+
+
+def _get_message_openai_role(message: BaseMessage) -> str:
+ if isinstance(message, AIMessage):
+ return "assistant"
+ if isinstance(message, HumanMessage):
+ return "user"
+ if isinstance(message, ToolMessage):
+ return "tool"
+ if isinstance(message, SystemMessage):
+ role = message.additional_kwargs.get("__openai_role__", "system")
+ if not isinstance(role, str):
+ msg = f"Expected '__openai_role__' to be a str, got {type(role).__name__}"
+ raise TypeError(msg)
+ return role
+ if isinstance(message, FunctionMessage):
+ return "function"
+ if isinstance(message, ChatMessage):
+ return message.role
+ msg = f"Unknown BaseMessage type {message.__class__}."
+ raise ValueError(msg)
+
+
+def _convert_to_openai_tool_calls(tool_calls: list[ToolCall]) -> list[dict]:
+ return [
+ {
+ "type": "function",
+ "id": tool_call["id"],
+ "function": {
+ "name": tool_call["name"],
+ "arguments": json.dumps(tool_call["args"], ensure_ascii=False),
+ },
+ }
+ for tool_call in tool_calls
+ ]
+
+
+def count_tokens_approximately(
+ messages: Iterable[MessageLikeRepresentation],
+ *,
+ chars_per_token: float = 4.0,
+ extra_tokens_per_message: float = 3.0,
+ count_name: bool = True,
+ tokens_per_image: int = 85,
+ use_usage_metadata_scaling: bool = False,
+ tools: list[BaseTool | dict[str, Any]] | None = None,
+) -> int:
+ """Approximate the total number of tokens in messages.
+
+ The token count includes stringified message content, role, and (optionally) name.
+
+ - For AI messages, the token count also includes stringified tool calls.
+ - For tool messages, the token count also includes the tool call ID.
+ - For multimodal messages with images, applies a fixed token penalty per image
+ instead of counting base64-encoded characters.
+ - If tools are provided, the token count also includes stringified tool schemas.
+
+ Args:
+ messages: List of messages to count tokens for.
+ chars_per_token: Number of characters per token to use for the approximation.
+ One token corresponds to ~4 chars for common English text.
+ You can also specify `float` values for more fine-grained control.
+ [See more here](https://platform.openai.com/tokenizer).
+ extra_tokens_per_message: Number of extra tokens to add per message, e.g.
+ special tokens, including beginning/end of message.
+ You can also specify `float` values for more fine-grained control.
+ [See more here](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb).
+ count_name: Whether to include message names in the count.
+ tokens_per_image: Fixed token cost per image (default: 85, aligned with
+ OpenAI's low-resolution image token cost).
+ use_usage_metadata_scaling: If True, and all AI messages have consistent
+ `response_metadata['model_provider']`, scale the approximate token count
+ using the **most recent** AI message that has
+ `usage_metadata['total_tokens']`. The scaling factor is:
+ `AI_total_tokens / approx_tokens_up_to_that_AI_message`
+ tools: List of tools to include in the token count. Each tool can be either
+ a `BaseTool` instance or a dict representing a tool schema. `BaseTool`
+ instances are converted to OpenAI tool format before counting.
+
+ Returns:
+ Approximate number of tokens in the messages (and tools, if provided).
+
+ Note:
+ This is a simple approximation that may not match the exact token count used by
+ specific models. For accurate counts, use model-specific tokenizers.
+
+ For multimodal messages containing images, a fixed token penalty is applied
+ per image instead of counting base64-encoded characters, which provides a
+ more realistic approximation.
+
+ !!! version-added "Added in `langchain-core` 0.3.46"
+ """
+ converted_messages = convert_to_messages(messages)
+
+ token_count = 0.0
+
+ ai_model_provider: str | None = None
+ invalid_model_provider = False
+ last_ai_total_tokens: int | None = None
+ approx_at_last_ai: float | None = None
+
+ # Count tokens for tools if provided
+ if tools:
+ tools_chars = 0
+ for tool in tools:
+ tool_dict = tool if isinstance(tool, dict) else convert_to_openai_tool(tool)
+ tools_chars += len(json.dumps(tool_dict))
+ token_count += math.ceil(tools_chars / chars_per_token)
+
+ for message in converted_messages:
+ message_chars = 0
+
+ if isinstance(message.content, str):
+ message_chars += len(message.content)
+ # Handle multimodal content (list of content blocks)
+ elif isinstance(message.content, list):
+ for block in message.content:
+ if isinstance(block, str):
+ # String block
+ message_chars += len(block)
+ elif isinstance(block, dict):
+ block_type = block.get("type", "")
+
+ # Apply fixed penalty for image blocks
+ if block_type in {"image", "image_url"}:
+ token_count += tokens_per_image
+ # Count text blocks normally
+ elif block_type == "text":
+ text = block.get("text", "")
+ message_chars += len(text)
+ # Conservative estimate for unknown block types
+ else:
+ message_chars += len(repr(block))
+ else:
+ # Fallback for unexpected block types
+ message_chars += len(repr(block))
+ else:
+ # Fallback for other content types
+ content = repr(message.content)
+ message_chars += len(content)
+
+ if (
+ isinstance(message, AIMessage)
+ # exclude Anthropic format as tool calls are already included in the content
+ and not isinstance(message.content, list)
+ and message.tool_calls
+ ):
+ tool_calls_content = repr(message.tool_calls)
+ message_chars += len(tool_calls_content)
+
+ if isinstance(message, ToolMessage):
+ message_chars += len(message.tool_call_id)
+
+ role = _get_message_openai_role(message)
+ message_chars += len(role)
+
+ if message.name and count_name:
+ message_chars += len(message.name)
+
+ # NOTE: we're rounding up per message to ensure that
+ # individual message token counts add up to the total count
+ # for a list of messages
+ token_count += math.ceil(message_chars / chars_per_token)
+
+ # add extra tokens per message
+ token_count += extra_tokens_per_message
+
+ if use_usage_metadata_scaling and isinstance(message, AIMessage):
+ model_provider = message.response_metadata.get("model_provider")
+ if ai_model_provider is None:
+ ai_model_provider = model_provider
+ elif model_provider != ai_model_provider:
+ invalid_model_provider = True
+
+ if message.usage_metadata and isinstance(
+ (total_tokens := message.usage_metadata.get("total_tokens")), int
+ ):
+ last_ai_total_tokens = total_tokens
+ approx_at_last_ai = token_count
+
+ if (
+ use_usage_metadata_scaling
+ and len(converted_messages) > 1
+ and not invalid_model_provider
+ and ai_model_provider is not None
+ and last_ai_total_tokens is not None
+ and approx_at_last_ai
+ and approx_at_last_ai > 0
+ ):
+ scale_factor = last_ai_total_tokens / approx_at_last_ai
+ token_count *= min(1.25, max(1.0, scale_factor))
+
+ # round up once more time in case extra_tokens_per_message is a float
+ return math.ceil(token_count)
+
+
+# Mapping from string shortcuts to token counter functions
+def _approximate_token_counter(messages: Sequence[BaseMessage]) -> int:
+ """Wrapper for `count_tokens_approximately` that matches expected signature."""
+ return count_tokens_approximately(messages)
+
+
+_TOKEN_COUNTER_SHORTCUTS = {
+ "approximate": _approximate_token_counter,
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bd9c0ca893bcb0985b0d880d31d0df394f9f3f2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__init__.py
@@ -0,0 +1,101 @@
+"""`OutputParser` classes parse the output of an LLM call into structured data.
+
+!!! tip "Structured output"
+
+ Output parsers emerged as an early solution to the challenge of obtaining structured
+ output from LLMs.
+
+ Today, most LLMs support [structured output](https://docs.langchain.com/oss/python/langchain/models#structured-outputs)
+ natively. In such cases, using output parsers may be unnecessary, and you should
+ leverage the model's built-in capabilities for structured output. Refer to the
+ [documentation of your chosen model](https://docs.langchain.com/oss/python/integrations/providers/overview)
+ for guidance on how to achieve structured output directly.
+
+ Output parsers remain valuable when working with models that do not support
+ structured output natively, or when you require additional processing or validation
+ of the model's output beyond its inherent capabilities.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.output_parsers.base import (
+ BaseGenerationOutputParser,
+ BaseLLMOutputParser,
+ BaseOutputParser,
+ )
+ from langchain_core.output_parsers.json import (
+ JsonOutputParser,
+ SimpleJsonOutputParser,
+ )
+ from langchain_core.output_parsers.list import (
+ CommaSeparatedListOutputParser,
+ ListOutputParser,
+ MarkdownListOutputParser,
+ NumberedListOutputParser,
+ )
+ from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ JsonOutputToolsParser,
+ PydanticToolsParser,
+ )
+ from langchain_core.output_parsers.pydantic import PydanticOutputParser
+ from langchain_core.output_parsers.string import StrOutputParser
+ from langchain_core.output_parsers.transform import (
+ BaseCumulativeTransformOutputParser,
+ BaseTransformOutputParser,
+ )
+ from langchain_core.output_parsers.xml import XMLOutputParser
+
+__all__ = [
+ "BaseCumulativeTransformOutputParser",
+ "BaseGenerationOutputParser",
+ "BaseLLMOutputParser",
+ "BaseOutputParser",
+ "BaseTransformOutputParser",
+ "CommaSeparatedListOutputParser",
+ "JsonOutputKeyToolsParser",
+ "JsonOutputParser",
+ "JsonOutputToolsParser",
+ "ListOutputParser",
+ "MarkdownListOutputParser",
+ "NumberedListOutputParser",
+ "PydanticOutputParser",
+ "PydanticToolsParser",
+ "SimpleJsonOutputParser",
+ "StrOutputParser",
+ "XMLOutputParser",
+]
+
+_dynamic_imports = {
+ "BaseLLMOutputParser": "base",
+ "BaseGenerationOutputParser": "base",
+ "BaseOutputParser": "base",
+ "JsonOutputParser": "json",
+ "SimpleJsonOutputParser": "json",
+ "ListOutputParser": "list",
+ "CommaSeparatedListOutputParser": "list",
+ "MarkdownListOutputParser": "list",
+ "NumberedListOutputParser": "list",
+ "JsonOutputKeyToolsParser": "openai_tools",
+ "JsonOutputToolsParser": "openai_tools",
+ "PydanticToolsParser": "openai_tools",
+ "PydanticOutputParser": "pydantic",
+ "StrOutputParser": "string",
+ "BaseTransformOutputParser": "transform",
+ "BaseCumulativeTransformOutputParser": "transform",
+ "XMLOutputParser": "xml",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return __all__
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f5880d9d3cee26090b079b884a81a066d5139f4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0359c4b1b2ffadebb84b038861ded05a392ba508
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/format_instructions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/format_instructions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3fa9ba5f1543a86dbfab2808750c20e71271f66d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/format_instructions.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/json.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/json.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e7f2607a9218cb7307709b8faddf554de6eb2a0
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/json.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/list.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/list.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ad0f75f971331766477f6c54ce0842765ba8a03
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/list.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/openai_functions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/openai_functions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cc231c16d374564c153970f9b3a1c7eb86ca48f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/openai_functions.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/openai_tools.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/openai_tools.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78b9d613a5175f75228287484ee3569ecc1f818f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/openai_tools.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/pydantic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/pydantic.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..471484b579278017188fbd5185ab3343ca9ec37d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/pydantic.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/string.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/string.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4794e303fbe28166bc32e0ae104bb60c29d93fa2
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/string.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/transform.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/transform.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6c4fccb815fac5168d893fbb29263437cd8ab78
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/transform.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/xml.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/xml.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de7026c2e882dbaa626f322f3dd115eeaee384bb
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/__pycache__/xml.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..861e8ba77774433b0cbd1265b7d75069e30bdf76
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/base.py
@@ -0,0 +1,348 @@
+"""Base parser for language model outputs."""
+
+from __future__ import annotations
+
+import contextlib
+from abc import ABC, abstractmethod
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Generic,
+ TypeVar,
+ cast,
+)
+
+from typing_extensions import override
+
+from langchain_core.language_models import LanguageModelOutput
+from langchain_core.messages import AnyMessage, BaseMessage
+from langchain_core.outputs import ChatGeneration, Generation
+from langchain_core.runnables import Runnable, RunnableConfig, RunnableSerializable
+from langchain_core.runnables.config import run_in_executor
+
+if TYPE_CHECKING:
+ from langchain_core.prompt_values import PromptValue
+
+T = TypeVar("T")
+OutputParserLike = Runnable[LanguageModelOutput, T]
+
+
+class BaseLLMOutputParser(ABC, Generic[T]):
+ """Abstract base class for parsing the outputs of a model."""
+
+ @abstractmethod
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> T:
+ """Parse a list of candidate model `Generation` objects into a specific format.
+
+ Args:
+ result: A list of `Generation` to be parsed.
+
+ The `Generation` objects are assumed to be different candidate outputs
+ for a single model input.
+ partial: Whether to parse the output as a partial result.
+
+ This is useful for parsers that can parse partial results.
+
+ Returns:
+ Structured output.
+ """
+
+ async def aparse_result(
+ self, result: list[Generation], *, partial: bool = False
+ ) -> T:
+ """Parse a list of candidate model `Generation` objects into a specific format.
+
+ Args:
+ result: A list of `Generation` to be parsed.
+
+ The Generations are assumed to be different candidate outputs for a
+ single model input.
+ partial: Whether to parse the output as a partial result.
+
+ This is useful for parsers that can parse partial results.
+
+ Returns:
+ Structured output.
+ """
+ return await run_in_executor(None, self.parse_result, result, partial=partial)
+
+
+class BaseGenerationOutputParser(
+ BaseLLMOutputParser, RunnableSerializable[LanguageModelOutput, T]
+):
+ """Base class to parse the output of an LLM call."""
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ """Return the input type for the parser."""
+ return str | AnyMessage
+
+ @property
+ @override
+ def OutputType(self) -> type[T]:
+ """Return the output type for the parser."""
+ # even though mypy complains this isn't valid,
+ # it is good enough for pydantic to build the schema from
+ return cast("type[T]", T) # type: ignore[misc]
+
+ @override
+ def invoke(
+ self,
+ input: str | BaseMessage,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> T:
+ if isinstance(input, BaseMessage):
+ return self._call_with_config(
+ lambda inner_input: self.parse_result(
+ [ChatGeneration(message=inner_input)]
+ ),
+ input,
+ config,
+ run_type="parser",
+ )
+ return self._call_with_config(
+ lambda inner_input: self.parse_result([Generation(text=inner_input)]),
+ input,
+ config,
+ run_type="parser",
+ )
+
+ @override
+ async def ainvoke(
+ self,
+ input: str | BaseMessage,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> T:
+ if isinstance(input, BaseMessage):
+ return await self._acall_with_config(
+ lambda inner_input: self.aparse_result(
+ [ChatGeneration(message=inner_input)]
+ ),
+ input,
+ config,
+ run_type="parser",
+ )
+ return await self._acall_with_config(
+ lambda inner_input: self.aparse_result([Generation(text=inner_input)]),
+ input,
+ config,
+ run_type="parser",
+ )
+
+
+class BaseOutputParser(
+ BaseLLMOutputParser, RunnableSerializable[LanguageModelOutput, T]
+):
+ """Base class to parse the output of an LLM call.
+
+ Output parsers help structure language model responses.
+
+ Example:
+ ```python
+ # Implement a simple boolean output parser
+
+
+ class BooleanOutputParser(BaseOutputParser[bool]):
+ true_val: str = "YES"
+ false_val: str = "NO"
+
+ def parse(self, text: str) -> bool:
+ cleaned_text = text.strip().upper()
+ if cleaned_text not in (
+ self.true_val.upper(),
+ self.false_val.upper(),
+ ):
+ raise OutputParserException(
+ f"BooleanOutputParser expected output value to either be "
+ f"{self.true_val} or {self.false_val} (case-insensitive). "
+ f"Received {cleaned_text}."
+ )
+ return cleaned_text == self.true_val.upper()
+
+ @property
+ def _type(self) -> str:
+ return "boolean_output_parser"
+ ```
+ """
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ """Return the input type for the parser."""
+ return str | AnyMessage
+
+ @property
+ @override
+ def OutputType(self) -> type[T]:
+ """Return the output type for the parser.
+
+ This property is inferred from the first type argument of the class.
+
+ Raises:
+ TypeError: If the class doesn't have an inferable `OutputType`.
+ """
+ for base in self.__class__.mro():
+ if hasattr(base, "__pydantic_generic_metadata__"):
+ metadata = base.__pydantic_generic_metadata__
+ if "args" in metadata and len(metadata["args"]) > 0:
+ return cast("type[T]", metadata["args"][0])
+
+ msg = (
+ f"Runnable {self.__class__.__name__} doesn't have an inferable OutputType. "
+ "Override the OutputType property to specify the output type."
+ )
+ raise TypeError(msg)
+
+ @override
+ def invoke(
+ self,
+ input: str | BaseMessage,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> T:
+ if isinstance(input, BaseMessage):
+ return self._call_with_config(
+ lambda inner_input: self.parse_result(
+ [ChatGeneration(message=inner_input)]
+ ),
+ input,
+ config,
+ run_type="parser",
+ )
+ return self._call_with_config(
+ lambda inner_input: self.parse_result([Generation(text=inner_input)]),
+ input,
+ config,
+ run_type="parser",
+ )
+
+ @override
+ async def ainvoke(
+ self,
+ input: str | BaseMessage,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> T:
+ if isinstance(input, BaseMessage):
+ return await self._acall_with_config(
+ lambda inner_input: self.aparse_result(
+ [ChatGeneration(message=inner_input)]
+ ),
+ input,
+ config,
+ run_type="parser",
+ )
+ return await self._acall_with_config(
+ lambda inner_input: self.aparse_result([Generation(text=inner_input)]),
+ input,
+ config,
+ run_type="parser",
+ )
+
+ @override
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> T:
+ """Parse a list of candidate model `Generation` objects into a specific format.
+
+ The return value is parsed from only the first `Generation` in the result, which
+ is assumed to be the highest-likelihood `Generation`.
+
+ Args:
+ result: A list of `Generation` to be parsed.
+
+ The `Generation` objects are assumed to be different candidate outputs
+ for a single model input.
+ partial: Whether to parse the output as a partial result.
+
+ This is useful for parsers that can parse partial results.
+
+ Returns:
+ Structured output.
+ """
+ return self.parse(result[0].text)
+
+ @abstractmethod
+ def parse(self, text: str) -> T:
+ """Parse a single string model output into some structure.
+
+ Args:
+ text: String output of a language model.
+
+ Returns:
+ Structured output.
+ """
+
+ async def aparse_result(
+ self, result: list[Generation], *, partial: bool = False
+ ) -> T:
+ """Parse a list of candidate model `Generation` objects into a specific format.
+
+ The return value is parsed from only the first `Generation` in the result, which
+ is assumed to be the highest-likelihood `Generation`.
+
+ Args:
+ result: A list of `Generation` to be parsed.
+
+ The `Generation` objects are assumed to be different candidate outputs
+ for a single model input.
+ partial: Whether to parse the output as a partial result.
+
+ This is useful for parsers that can parse partial results.
+
+ Returns:
+ Structured output.
+ """
+ return await run_in_executor(None, self.parse_result, result, partial=partial)
+
+ async def aparse(self, text: str) -> T:
+ """Async parse a single string model output into some structure.
+
+ Args:
+ text: String output of a language model.
+
+ Returns:
+ Structured output.
+ """
+ return await run_in_executor(None, self.parse, text)
+
+ # TODO: rename 'completion' -> 'text'.
+ def parse_with_prompt(
+ self,
+ completion: str,
+ prompt: PromptValue, # noqa: ARG002
+ ) -> Any:
+ """Parse the output of an LLM call with the input prompt for context.
+
+ The prompt is largely provided in the event the `OutputParser` wants to retry or
+ fix the output in some way, and needs information from the prompt to do so.
+
+ Args:
+ completion: String output of a language model.
+ prompt: Input `PromptValue`.
+
+ Returns:
+ Structured output.
+ """
+ return self.parse(completion)
+
+ def get_format_instructions(self) -> str:
+ """Instructions on how the LLM output should be formatted."""
+ raise NotImplementedError
+
+ @property
+ def _type(self) -> str:
+ """Return the output parser type for serialization."""
+ msg = (
+ f"_type property is not implemented in class {self.__class__.__name__}."
+ " This is required for serialization."
+ )
+ raise NotImplementedError(msg)
+
+ def dict(self, **kwargs: Any) -> dict:
+ """Return dictionary representation of output parser."""
+ output_parser_dict = super().model_dump(**kwargs)
+ with contextlib.suppress(NotImplementedError):
+ output_parser_dict["_type"] = self._type
+ return output_parser_dict
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/format_instructions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/format_instructions.py
new file mode 100644
index 0000000000000000000000000000000000000000..49898917f45c7e779ac005717acd0327822db447
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/format_instructions.py
@@ -0,0 +1,16 @@
+"""Format instructions."""
+
+JSON_FORMAT_INSTRUCTIONS = """STRICT OUTPUT FORMAT:
+- Return only the JSON value that conforms to the schema. Do not include any additional text, explanations, headings, or separators.
+- Do not wrap the JSON in Markdown or code fences (no ``` or ```json).
+- Do not prepend or append any text (e.g., do not write "Here is the JSON:").
+- The response must be a single top-level JSON value exactly as required by the schema (object/array/etc.), with no trailing commas or comments.
+
+The output should be formatted as a JSON instance that conforms to the JSON schema below.
+
+As an example, for the schema {{"properties": {{"foo": {{"title": "Foo", "description": "a list of strings", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}} the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of the schema. The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
+
+Here is the output schema (shown in a code block for readability only — do not include any backticks or Markdown in your output):
+```
+{schema}
+```""" # noqa: E501
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/json.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/json.py
new file mode 100644
index 0000000000000000000000000000000000000000..829e042c7c9fefed89dac102eb66c3bd9094aef3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/json.py
@@ -0,0 +1,139 @@
+"""Parser for JSON output."""
+
+from __future__ import annotations
+
+import json
+from json import JSONDecodeError
+from typing import Annotated, Any, TypeVar
+
+import jsonpatch # type: ignore[import-untyped]
+import pydantic
+from pydantic import SkipValidation
+from pydantic.v1 import BaseModel
+from typing_extensions import override
+
+from langchain_core.exceptions import OutputParserException
+from langchain_core.output_parsers.format_instructions import JSON_FORMAT_INSTRUCTIONS
+from langchain_core.output_parsers.transform import BaseCumulativeTransformOutputParser
+from langchain_core.outputs import Generation
+from langchain_core.utils.json import (
+ parse_and_check_json_markdown,
+ parse_json_markdown,
+ parse_partial_json,
+)
+
+# Union type needs to be last assignment to PydanticBaseModel to make mypy happy.
+PydanticBaseModel = BaseModel | pydantic.BaseModel
+
+TBaseModel = TypeVar("TBaseModel", bound=PydanticBaseModel)
+
+
+class JsonOutputParser(BaseCumulativeTransformOutputParser[Any]):
+ """Parse the output of an LLM call to a JSON object.
+
+ Probably the most reliable output parser for getting structured data that does *not*
+ use function calling.
+
+ When used in streaming mode, it will yield partial JSON objects containing all the
+ keys that have been returned so far.
+
+ In streaming, if `diff` is set to `True`, yields `JSONPatch` operations describing
+ the difference between the previous and the current object.
+ """
+
+ pydantic_object: Annotated[type[TBaseModel] | None, SkipValidation()] = None # type: ignore[valid-type]
+ """The Pydantic object to use for validation.
+
+ If `None`, no validation is performed.
+ """
+
+ @override
+ def _diff(self, prev: Any | None, next: Any) -> Any:
+ return jsonpatch.make_patch(prev, next).patch
+
+ @staticmethod
+ def _get_schema(pydantic_object: type[TBaseModel]) -> dict[str, Any]:
+ if issubclass(pydantic_object, pydantic.BaseModel):
+ return pydantic_object.model_json_schema()
+ return pydantic_object.schema()
+
+ @override
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a JSON object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ If `True`, the output will be a JSON object containing all the keys that
+ have been returned so far.
+
+ If `False`, the output will be the full JSON object.
+
+ Returns:
+ The parsed JSON object.
+
+ Raises:
+ OutputParserException: If the output is not valid JSON.
+ """
+ text = result[0].text
+ text = text.strip()
+ if partial:
+ try:
+ return parse_json_markdown(text)
+ except JSONDecodeError:
+ return None
+ else:
+ try:
+ return parse_json_markdown(text)
+ except JSONDecodeError as e:
+ msg = f"Invalid json output: {text}"
+ raise OutputParserException(msg, llm_output=text) from e
+
+ def parse(self, text: str) -> Any:
+ """Parse the output of an LLM call to a JSON object.
+
+ Args:
+ text: The output of the LLM call.
+
+ Returns:
+ The parsed JSON object.
+ """
+ return self.parse_result([Generation(text=text)])
+
+ def get_format_instructions(self) -> str:
+ """Return the format instructions for the JSON output.
+
+ Returns:
+ The format instructions for the JSON output.
+ """
+ if self.pydantic_object is None:
+ return "Return a JSON object."
+ # Copy schema to avoid altering original Pydantic schema.
+ schema = dict(self._get_schema(self.pydantic_object).items())
+
+ # Remove extraneous fields.
+ reduced_schema = schema
+ if "title" in reduced_schema:
+ del reduced_schema["title"]
+ if "type" in reduced_schema:
+ del reduced_schema["type"]
+ # Ensure json in context is well-formed with double quotes.
+ schema_str = json.dumps(reduced_schema, ensure_ascii=False)
+ return JSON_FORMAT_INSTRUCTIONS.format(schema=schema_str)
+
+ @property
+ def _type(self) -> str:
+ return "simple_json_output_parser"
+
+
+# For backwards compatibility
+SimpleJsonOutputParser = JsonOutputParser
+
+
+__all__ = [
+ "JsonOutputParser",
+ "SimpleJsonOutputParser", # For backwards compatibility
+ "parse_and_check_json_markdown", # For backwards compatibility
+ "parse_partial_json", # For backwards compatibility
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/list.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/list.py
new file mode 100644
index 0000000000000000000000000000000000000000..834c9ec153a0ddb8b742256e21eca25eaae45748
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/list.py
@@ -0,0 +1,249 @@
+"""Parsers for list output."""
+
+from __future__ import annotations
+
+import csv
+import re
+from abc import abstractmethod
+from collections import deque
+from io import StringIO
+from typing import TYPE_CHECKING, TypeVar
+
+from typing_extensions import override
+
+from langchain_core.messages import BaseMessage
+from langchain_core.output_parsers.transform import BaseTransformOutputParser
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator
+
+T = TypeVar("T")
+
+
+def droplastn(
+ iter: Iterator[T], # noqa: A002
+ n: int,
+) -> Iterator[T]:
+ """Drop the last `n` elements of an iterator.
+
+ Args:
+ iter: The iterator to drop elements from.
+ n: The number of elements to drop.
+
+ Yields:
+ The elements of the iterator, except the last n elements.
+ """
+ buffer: deque[T] = deque()
+ for item in iter:
+ buffer.append(item)
+ if len(buffer) > n:
+ yield buffer.popleft()
+
+
+class ListOutputParser(BaseTransformOutputParser[list[str]]):
+ """Parse the output of a model to a list."""
+
+ @property
+ def _type(self) -> str:
+ return "list"
+
+ @abstractmethod
+ def parse(self, text: str) -> list[str]:
+ """Parse the output of an LLM call.
+
+ Args:
+ text: The output of an LLM call.
+
+ Returns:
+ A list of strings.
+ """
+
+ def parse_iter(self, text: str) -> Iterator[re.Match]:
+ """Parse the output of an LLM call.
+
+ Args:
+ text: The output of an LLM call.
+
+ Yields:
+ A match object for each part of the output.
+ """
+ raise NotImplementedError
+
+ @override
+ def _transform(self, input: Iterator[str | BaseMessage]) -> Iterator[list[str]]:
+ buffer = ""
+ for chunk in input:
+ if isinstance(chunk, BaseMessage):
+ # Extract text
+ chunk_content = chunk.content
+ if not isinstance(chunk_content, str):
+ continue
+ buffer += chunk_content
+ else:
+ # Add current chunk to buffer
+ buffer += chunk
+ # Parse buffer into a list of parts
+ try:
+ done_idx = 0
+ # Yield only complete parts
+ for m in droplastn(self.parse_iter(buffer), 1):
+ done_idx = m.end()
+ yield [m.group(1)]
+ buffer = buffer[done_idx:]
+ except NotImplementedError:
+ parts = self.parse(buffer)
+ # Yield only complete parts
+ if len(parts) > 1:
+ for part in parts[:-1]:
+ yield [part]
+ buffer = parts[-1]
+ # Yield the last part
+ for part in self.parse(buffer):
+ yield [part]
+
+ @override
+ async def _atransform(
+ self, input: AsyncIterator[str | BaseMessage]
+ ) -> AsyncIterator[list[str]]:
+ buffer = ""
+ async for chunk in input:
+ if isinstance(chunk, BaseMessage):
+ # Extract text
+ chunk_content = chunk.content
+ if not isinstance(chunk_content, str):
+ continue
+ buffer += chunk_content
+ else:
+ # Add current chunk to buffer
+ buffer += chunk
+ # Parse buffer into a list of parts
+ try:
+ done_idx = 0
+ # Yield only complete parts
+ for m in droplastn(self.parse_iter(buffer), 1):
+ done_idx = m.end()
+ yield [m.group(1)]
+ buffer = buffer[done_idx:]
+ except NotImplementedError:
+ parts = self.parse(buffer)
+ # Yield only complete parts
+ if len(parts) > 1:
+ for part in parts[:-1]:
+ yield [part]
+ buffer = parts[-1]
+ # Yield the last part
+ for part in self.parse(buffer):
+ yield [part]
+
+
+class CommaSeparatedListOutputParser(ListOutputParser):
+ """Parse the output of a model to a comma-separated list."""
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "output_parsers", "list"]`
+ """
+ return ["langchain", "output_parsers", "list"]
+
+ @override
+ def get_format_instructions(self) -> str:
+ """Return the format instructions for the comma-separated list output."""
+ return (
+ "Your response should be a list of comma separated values, "
+ "eg: `foo, bar, baz` or `foo,bar,baz`"
+ )
+
+ @override
+ def parse(self, text: str) -> list[str]:
+ """Parse the output of an LLM call.
+
+ Args:
+ text: The output of an LLM call.
+
+ Returns:
+ A list of strings.
+ """
+ try:
+ reader = csv.reader(
+ StringIO(text), quotechar='"', delimiter=",", skipinitialspace=True
+ )
+ return [item for sublist in reader for item in sublist]
+ except csv.Error:
+ # Keep old logic for backup
+ return [part.strip() for part in text.split(",")]
+
+ @property
+ def _type(self) -> str:
+ return "comma-separated-list"
+
+
+class NumberedListOutputParser(ListOutputParser):
+ """Parse a numbered list."""
+
+ pattern: str = r"\d+\.\s([^\n]+)"
+ """The pattern to match a numbered list item."""
+
+ @override
+ def get_format_instructions(self) -> str:
+ return (
+ "Your response should be a numbered list with each item on a new line. "
+ "For example: \n\n1. foo\n\n2. bar\n\n3. baz"
+ )
+
+ def parse(self, text: str) -> list[str]:
+ """Parse the output of an LLM call.
+
+ Args:
+ text: The output of an LLM call.
+
+ Returns:
+ A list of strings.
+ """
+ return re.findall(self.pattern, text)
+
+ @override
+ def parse_iter(self, text: str) -> Iterator[re.Match]:
+ return re.finditer(self.pattern, text)
+
+ @property
+ def _type(self) -> str:
+ return "numbered-list"
+
+
+class MarkdownListOutputParser(ListOutputParser):
+ """Parse a Markdown list."""
+
+ pattern: str = r"^\s*[-*]\s([^\n]+)$"
+ """The pattern to match a Markdown list item."""
+
+ @override
+ def get_format_instructions(self) -> str:
+ """Return the format instructions for the Markdown list output."""
+ return "Your response should be a markdown list, eg: `- foo\n- bar\n- baz`"
+
+ def parse(self, text: str) -> list[str]:
+ """Parse the output of an LLM call.
+
+ Args:
+ text: The output of an LLM call.
+
+ Returns:
+ A list of strings.
+ """
+ return re.findall(self.pattern, text, re.MULTILINE)
+
+ @override
+ def parse_iter(self, text: str) -> Iterator[re.Match]:
+ return re.finditer(self.pattern, text, re.MULTILINE)
+
+ @property
+ def _type(self) -> str:
+ return "markdown-list"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/openai_functions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/openai_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..812af64292a72c275d17f596e084f3c678f51ea9
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/openai_functions.py
@@ -0,0 +1,313 @@
+"""Parsers for OpenAI functions output."""
+
+import copy
+import json
+from types import GenericAlias
+from typing import Any
+
+import jsonpatch # type: ignore[import-untyped]
+from pydantic import BaseModel, model_validator
+from pydantic.v1 import BaseModel as BaseModelV1
+from typing_extensions import override
+
+from langchain_core.exceptions import OutputParserException
+from langchain_core.output_parsers import (
+ BaseCumulativeTransformOutputParser,
+ BaseGenerationOutputParser,
+)
+from langchain_core.output_parsers.json import parse_partial_json
+from langchain_core.outputs import ChatGeneration, Generation
+
+
+class OutputFunctionsParser(BaseGenerationOutputParser[Any]):
+ """Parse an output that is one of sets of values."""
+
+ args_only: bool = True
+ """Whether to only return the arguments to the function call."""
+
+ @override
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a JSON object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ Returns:
+ The parsed JSON object.
+
+ Raises:
+ OutputParserException: If the output is not valid JSON.
+ """
+ generation = result[0]
+ if not isinstance(generation, ChatGeneration):
+ msg = "This output parser can only be used with a chat generation."
+ raise OutputParserException(msg)
+ message = generation.message
+ try:
+ func_call = copy.deepcopy(message.additional_kwargs["function_call"])
+ except KeyError as exc:
+ msg = f"Could not parse function call: {exc}"
+ raise OutputParserException(msg) from exc
+
+ if self.args_only:
+ return func_call["arguments"]
+ return func_call
+
+
+class JsonOutputFunctionsParser(BaseCumulativeTransformOutputParser[Any]):
+ """Parse an output as the JSON object."""
+
+ strict: bool = False
+ """Whether to allow non-JSON-compliant strings.
+
+ See: https://docs.python.org/3/library/json.html#encoders-and-decoders
+
+ Useful when the parsed output may include unicode characters or new lines.
+ """
+
+ args_only: bool = True
+ """Whether to only return the arguments to the function call."""
+
+ @property
+ def _type(self) -> str:
+ return "json_functions"
+
+ @override
+ def _diff(self, prev: Any | None, next: Any) -> Any:
+ return jsonpatch.make_patch(prev, next).patch
+
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a JSON object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ Returns:
+ The parsed JSON object.
+
+ Raises:
+ OutputParserException: If the output is not valid JSON.
+ """
+ if len(result) != 1:
+ msg = f"Expected exactly one result, but got {len(result)}"
+ raise OutputParserException(msg)
+ generation = result[0]
+ if not isinstance(generation, ChatGeneration):
+ msg = "This output parser can only be used with a chat generation."
+ raise OutputParserException(msg)
+ message = generation.message
+ try:
+ function_call = message.additional_kwargs["function_call"]
+ except KeyError as exc:
+ if partial:
+ return None
+ msg = f"Could not parse function call: {exc}"
+ raise OutputParserException(msg) from exc
+ try:
+ if partial:
+ try:
+ if self.args_only:
+ return parse_partial_json(
+ function_call["arguments"], strict=self.strict
+ )
+ return {
+ **function_call,
+ "arguments": parse_partial_json(
+ function_call["arguments"], strict=self.strict
+ ),
+ }
+ except json.JSONDecodeError:
+ return None
+ elif self.args_only:
+ try:
+ return json.loads(function_call["arguments"], strict=self.strict)
+ except (json.JSONDecodeError, TypeError) as exc:
+ msg = f"Could not parse function call data: {exc}"
+ raise OutputParserException(msg) from exc
+ else:
+ try:
+ return {
+ **function_call,
+ "arguments": json.loads(
+ function_call["arguments"], strict=self.strict
+ ),
+ }
+ except (json.JSONDecodeError, TypeError) as exc:
+ msg = f"Could not parse function call data: {exc}"
+ raise OutputParserException(msg) from exc
+ except KeyError:
+ return None
+
+ # This method would be called by the default implementation of `parse_result`
+ # but we're overriding that method so it's not needed.
+ def parse(self, text: str) -> Any:
+ """Parse the output of an LLM call to a JSON object.
+
+ Args:
+ text: The output of the LLM call.
+
+ Returns:
+ The parsed JSON object.
+ """
+ raise NotImplementedError
+
+
+class JsonKeyOutputFunctionsParser(JsonOutputFunctionsParser):
+ """Parse an output as the element of the JSON object."""
+
+ key_name: str
+ """The name of the key to return."""
+
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a JSON object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ Returns:
+ The parsed JSON object.
+ """
+ res = super().parse_result(result, partial=partial)
+ if partial and res is None:
+ return None
+ return res.get(self.key_name) if partial else res[self.key_name]
+
+
+class PydanticOutputFunctionsParser(OutputFunctionsParser):
+ """Parse an output as a Pydantic object.
+
+ This parser is used to parse the output of a chat model that uses OpenAI function
+ format to invoke functions.
+
+ The parser extracts the function call invocation and matches them to the Pydantic
+ schema provided.
+
+ An exception will be raised if the function call does not match the provided schema.
+
+ Example:
+ ```python
+ message = AIMessage(
+ content="This is a test message",
+ additional_kwargs={
+ "function_call": {
+ "name": "cookie",
+ "arguments": json.dumps({"name": "value", "age": 10}),
+ }
+ },
+ )
+ chat_generation = ChatGeneration(message=message)
+
+
+ class Cookie(BaseModel):
+ name: str
+ age: int
+
+
+ class Dog(BaseModel):
+ species: str
+
+
+ # Full output
+ parser = PydanticOutputFunctionsParser(
+ pydantic_schema={"cookie": Cookie, "dog": Dog}
+ )
+ result = parser.parse_result([chat_generation])
+ ```
+
+ """
+
+ pydantic_schema: type[BaseModel] | dict[str, type[BaseModel]]
+ """The Pydantic schema to parse the output with.
+
+ If multiple schemas are provided, then the function name will be used to
+ determine which schema to use.
+ """
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_schema(cls, values: dict[str, Any]) -> Any:
+ """Validate the Pydantic schema.
+
+ Args:
+ values: The values to validate.
+
+ Returns:
+ The validated values.
+
+ Raises:
+ ValueError: If the schema is not a Pydantic schema.
+ """
+ schema = values["pydantic_schema"]
+ if "args_only" not in values:
+ values["args_only"] = (
+ isinstance(schema, type)
+ and not isinstance(schema, GenericAlias)
+ and issubclass(schema, BaseModel)
+ )
+ elif values["args_only"] and isinstance(schema, dict):
+ msg = (
+ "If multiple pydantic schemas are provided then args_only should be"
+ " False."
+ )
+ raise ValueError(msg)
+ return values
+
+ @override
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a JSON object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ Raises:
+ ValueError: If the Pydantic schema is not valid.
+
+ Returns:
+ The parsed JSON object.
+ """
+ result_ = super().parse_result(result)
+ if self.args_only:
+ if hasattr(self.pydantic_schema, "model_validate_json"):
+ pydantic_args = self.pydantic_schema.model_validate_json(result_)
+ else:
+ pydantic_args = self.pydantic_schema.parse_raw(result_) # type: ignore[attr-defined]
+ else:
+ fn_name = result_["name"]
+ args = result_["arguments"]
+ if isinstance(self.pydantic_schema, dict):
+ pydantic_schema = self.pydantic_schema[fn_name]
+ else:
+ pydantic_schema = self.pydantic_schema
+ if issubclass(pydantic_schema, BaseModel):
+ pydantic_args = pydantic_schema.model_validate_json(args)
+ elif issubclass(pydantic_schema, BaseModelV1):
+ pydantic_args = pydantic_schema.parse_raw(args)
+ else:
+ msg = f"Unsupported Pydantic schema: {pydantic_schema}"
+ raise ValueError(msg)
+ return pydantic_args
+
+
+class PydanticAttrOutputFunctionsParser(PydanticOutputFunctionsParser):
+ """Parse an output as an attribute of a Pydantic object."""
+
+ attr_name: str
+ """The name of the attribute to return."""
+
+ @override
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a JSON object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ Returns:
+ The parsed JSON object.
+ """
+ result = super().parse_result(result)
+ return getattr(result, self.attr_name)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/openai_tools.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/openai_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..c42e09466533a895097ae214f96940cc3a3bc13c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/openai_tools.py
@@ -0,0 +1,384 @@
+"""Parse tools for OpenAI tools output."""
+
+import copy
+import json
+import logging
+from json import JSONDecodeError
+from typing import Annotated, Any
+
+from pydantic import SkipValidation, ValidationError
+
+from langchain_core.exceptions import OutputParserException
+from langchain_core.messages import AIMessage, InvalidToolCall
+from langchain_core.messages.tool import invalid_tool_call
+from langchain_core.messages.tool import tool_call as create_tool_call
+from langchain_core.output_parsers.transform import BaseCumulativeTransformOutputParser
+from langchain_core.outputs import ChatGeneration, Generation
+from langchain_core.utils.json import parse_partial_json
+from langchain_core.utils.pydantic import (
+ TypeBaseModel,
+ is_pydantic_v1_subclass,
+ is_pydantic_v2_subclass,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def parse_tool_call(
+ raw_tool_call: dict[str, Any],
+ *,
+ partial: bool = False,
+ strict: bool = False,
+ return_id: bool = True,
+) -> dict[str, Any] | None:
+ """Parse a single tool call.
+
+ Args:
+ raw_tool_call: The raw tool call to parse.
+ partial: Whether to parse partial JSON.
+ strict: Whether to allow non-JSON-compliant strings.
+ return_id: Whether to return the tool call id.
+
+ Returns:
+ The parsed tool call.
+
+ Raises:
+ OutputParserException: If the tool call is not valid JSON.
+ """
+ if "function" not in raw_tool_call:
+ return None
+
+ arguments = raw_tool_call["function"]["arguments"]
+
+ if partial:
+ try:
+ function_args = parse_partial_json(arguments, strict=strict)
+ except (JSONDecodeError, TypeError): # None args raise TypeError
+ return None
+ # Handle None or empty string arguments for parameter-less tools
+ elif not arguments:
+ function_args = {}
+ else:
+ try:
+ function_args = json.loads(arguments, strict=strict)
+ except JSONDecodeError as e:
+ msg = (
+ f"Function {raw_tool_call['function']['name']} arguments:\n\n"
+ f"{arguments}\n\nare not valid JSON. "
+ f"Received JSONDecodeError {e}"
+ )
+ raise OutputParserException(msg) from e
+ parsed = {
+ "name": raw_tool_call["function"]["name"] or "",
+ "args": function_args or {},
+ }
+ if return_id:
+ parsed["id"] = raw_tool_call.get("id")
+ parsed = create_tool_call(**parsed) # type: ignore[assignment,arg-type]
+ return parsed
+
+
+def make_invalid_tool_call(
+ raw_tool_call: dict[str, Any],
+ error_msg: str | None,
+) -> InvalidToolCall:
+ """Create an `InvalidToolCall` from a raw tool call.
+
+ Args:
+ raw_tool_call: The raw tool call.
+ error_msg: The error message.
+
+ Returns:
+ An `InvalidToolCall` instance with the error message.
+ """
+ return invalid_tool_call(
+ name=raw_tool_call["function"]["name"],
+ args=raw_tool_call["function"]["arguments"],
+ id=raw_tool_call.get("id"),
+ error=error_msg,
+ )
+
+
+def parse_tool_calls(
+ raw_tool_calls: list[dict],
+ *,
+ partial: bool = False,
+ strict: bool = False,
+ return_id: bool = True,
+) -> list[dict[str, Any]]:
+ """Parse a list of tool calls.
+
+ Args:
+ raw_tool_calls: The raw tool calls to parse.
+ partial: Whether to parse partial JSON.
+ strict: Whether to allow non-JSON-compliant strings.
+ return_id: Whether to return the tool call id.
+
+ Returns:
+ The parsed tool calls.
+
+ Raises:
+ OutputParserException: If any of the tool calls are not valid JSON.
+ """
+ final_tools: list[dict[str, Any]] = []
+ exceptions = []
+ for tool_call in raw_tool_calls:
+ try:
+ parsed = parse_tool_call(
+ tool_call, partial=partial, strict=strict, return_id=return_id
+ )
+ if parsed:
+ final_tools.append(parsed)
+ except OutputParserException as e:
+ exceptions.append(str(e))
+ continue
+ if exceptions:
+ raise OutputParserException("\n\n".join(exceptions))
+ return final_tools
+
+
+class JsonOutputToolsParser(BaseCumulativeTransformOutputParser[Any]):
+ """Parse tools from OpenAI response."""
+
+ strict: bool = False
+ """Whether to allow non-JSON-compliant strings.
+
+ See: https://docs.python.org/3/library/json.html#encoders-and-decoders
+
+ Useful when the parsed output may include unicode characters or new lines.
+ """
+
+ return_id: bool = False
+ """Whether to return the tool call id."""
+
+ first_tool_only: bool = False
+ """Whether to return only the first tool call.
+
+ If `False`, the result will be a list of tool calls, or an empty list if no tool
+ calls are found.
+
+ If `True`, and multiple tool calls are found, only the first one will be returned,
+ and the other tool calls will be ignored.
+
+ If no tool calls are found, `None` will be returned.
+ """
+
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a list of tool calls.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON.
+
+ If `True`, the output will be a JSON object containing
+ all the keys that have been returned so far.
+
+ If `False`, the output will be the full JSON object.
+
+ Returns:
+ The parsed tool calls.
+
+ Raises:
+ OutputParserException: If the output is not valid JSON.
+ """
+ generation = result[0]
+ if not isinstance(generation, ChatGeneration):
+ msg = "This output parser can only be used with a chat generation."
+ raise OutputParserException(msg)
+ message = generation.message
+ if isinstance(message, AIMessage) and message.tool_calls:
+ tool_calls = [dict(tc) for tc in message.tool_calls]
+ for tool_call in tool_calls:
+ if not self.return_id:
+ _ = tool_call.pop("id")
+ else:
+ try:
+ raw_tool_calls = copy.deepcopy(message.additional_kwargs["tool_calls"])
+ except KeyError:
+ return []
+ tool_calls = parse_tool_calls(
+ raw_tool_calls,
+ partial=partial,
+ strict=self.strict,
+ return_id=self.return_id,
+ )
+ # for backwards compatibility
+ for tc in tool_calls:
+ tc["type"] = tc.pop("name")
+
+ if self.first_tool_only:
+ return tool_calls[0] if tool_calls else None
+ return tool_calls
+
+ def parse(self, text: str) -> Any:
+ """Parse the output of an LLM call to a list of tool calls.
+
+ Args:
+ text: The output of the LLM call.
+
+ Returns:
+ The parsed tool calls.
+ """
+ raise NotImplementedError
+
+
+class JsonOutputKeyToolsParser(JsonOutputToolsParser):
+ """Parse tools from OpenAI response."""
+
+ key_name: str
+ """The type of tools to return."""
+
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a list of tool calls.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON.
+ If `True`, the output will be a JSON object containing
+ all the keys that have been returned so far.
+ If `False`, the output will be the full JSON object.
+
+ Raises:
+ OutputParserException: If the generation is not a chat generation.
+
+ Returns:
+ The parsed tool calls.
+ """
+ generation = result[0]
+ if not isinstance(generation, ChatGeneration):
+ msg = "This output parser can only be used with a chat generation."
+ raise OutputParserException(msg)
+ message = generation.message
+ if isinstance(message, AIMessage) and message.tool_calls:
+ parsed_tool_calls = [dict(tc) for tc in message.tool_calls]
+ for tool_call in parsed_tool_calls:
+ if not self.return_id:
+ _ = tool_call.pop("id")
+ else:
+ try:
+ # This exists purely for backward compatibility / cached messages
+ # All new messages should use `message.tool_calls`
+ raw_tool_calls = copy.deepcopy(message.additional_kwargs["tool_calls"])
+ except KeyError:
+ if self.first_tool_only:
+ return None
+ return []
+ parsed_tool_calls = parse_tool_calls(
+ raw_tool_calls,
+ partial=partial,
+ strict=self.strict,
+ return_id=self.return_id,
+ )
+ # For backwards compatibility
+ for tc in parsed_tool_calls:
+ tc["type"] = tc.pop("name")
+ if self.first_tool_only:
+ parsed_result = list(
+ filter(lambda x: x["type"] == self.key_name, parsed_tool_calls)
+ )
+ single_result = (
+ parsed_result[0]
+ if parsed_result and parsed_result[0]["type"] == self.key_name
+ else None
+ )
+ if self.return_id:
+ return single_result
+ if single_result:
+ return single_result["args"]
+ return None
+ return (
+ [res for res in parsed_tool_calls if res["type"] == self.key_name]
+ if self.return_id
+ else [
+ res["args"] for res in parsed_tool_calls if res["type"] == self.key_name
+ ]
+ )
+
+
+# Common cause of ValidationError is truncated output due to max_tokens.
+_MAX_TOKENS_ERROR = (
+ "Output parser received a `max_tokens` stop reason. "
+ "The output is likely incomplete—please increase `max_tokens` "
+ "or shorten your prompt."
+)
+
+
+class PydanticToolsParser(JsonOutputToolsParser):
+ """Parse tools from OpenAI response."""
+
+ tools: Annotated[list[TypeBaseModel], SkipValidation()]
+ """The tools to parse."""
+
+ # TODO: Support more granular streaming of objects.
+ # Currently only streams once all Pydantic object fields are present.
+ def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
+ """Parse the result of an LLM call to a list of Pydantic objects.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON.
+
+ If `True`, the output will be a JSON object containing all the keys that
+ have been returned so far.
+
+ If `False`, the output will be the full JSON object.
+
+ Returns:
+ The parsed Pydantic objects.
+
+ Raises:
+ ValueError: If the tool call arguments are not a dict.
+ ValidationError: If the tool call arguments do not conform to the Pydantic
+ model.
+ """
+ json_results = super().parse_result(result, partial=partial)
+ if not json_results:
+ return None if self.first_tool_only else []
+
+ json_results = [json_results] if self.first_tool_only else json_results
+ name_dict_v2: dict[str, TypeBaseModel] = {
+ tool.model_config.get("title") or tool.__name__: tool
+ for tool in self.tools
+ if is_pydantic_v2_subclass(tool)
+ }
+ name_dict_v1: dict[str, TypeBaseModel] = {
+ tool.__name__: tool for tool in self.tools if is_pydantic_v1_subclass(tool)
+ }
+ name_dict: dict[str, TypeBaseModel] = {**name_dict_v2, **name_dict_v1}
+ pydantic_objects = []
+ for res in json_results:
+ if not isinstance(res["args"], dict):
+ if partial:
+ continue
+ msg = (
+ f"Tool arguments must be specified as a dict, received: "
+ f"{res['args']}"
+ )
+ raise ValueError(msg)
+
+ try:
+ tool = name_dict[res["type"]]
+ except KeyError as e:
+ available = ", ".join(name_dict.keys()) or ""
+ msg = (
+ f"Unknown tool type: {res['type']!r}. Available tools: {available}"
+ )
+ raise OutputParserException(msg) from e
+
+ try:
+ pydantic_objects.append(tool(**res["args"]))
+ except (ValidationError, ValueError):
+ if partial:
+ continue
+ has_max_tokens_stop_reason = any(
+ generation.message.response_metadata.get("stop_reason")
+ == "max_tokens"
+ for generation in result
+ if isinstance(generation, ChatGeneration)
+ )
+ if has_max_tokens_stop_reason:
+ logger.exception(_MAX_TOKENS_ERROR)
+ raise
+ if self.first_tool_only:
+ return pydantic_objects[0] if pydantic_objects else None
+ return pydantic_objects
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/pydantic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/pydantic.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a7eee972dfc4e7472b792fa3ef1b820c8dacee1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/pydantic.py
@@ -0,0 +1,139 @@
+"""Output parsers using Pydantic."""
+
+import json
+from typing import Annotated, Generic, Literal, overload
+
+import pydantic
+from pydantic import SkipValidation
+from typing_extensions import override
+
+from langchain_core.exceptions import OutputParserException
+from langchain_core.output_parsers import JsonOutputParser
+from langchain_core.outputs import Generation
+from langchain_core.utils.pydantic import (
+ PydanticBaseModel,
+ TBaseModel,
+)
+
+
+class PydanticOutputParser(JsonOutputParser, Generic[TBaseModel]):
+ """Parse an output using a Pydantic model."""
+
+ pydantic_object: Annotated[type[TBaseModel], SkipValidation()]
+ """The Pydantic model to parse."""
+
+ def _parse_obj(self, obj: dict) -> TBaseModel:
+ try:
+ if issubclass(self.pydantic_object, pydantic.BaseModel):
+ return self.pydantic_object.model_validate(obj)
+ if issubclass(self.pydantic_object, pydantic.v1.BaseModel):
+ return self.pydantic_object.parse_obj(obj)
+ msg = f"Unsupported model version for PydanticOutputParser: \
+ {self.pydantic_object.__class__}"
+ raise OutputParserException(msg)
+ except (pydantic.ValidationError, pydantic.v1.ValidationError) as e:
+ raise self._parser_exception(e, obj) from e
+
+ def _parser_exception(
+ self, e: Exception, json_object: dict
+ ) -> OutputParserException:
+ json_string = json.dumps(json_object, ensure_ascii=False)
+ name = self.pydantic_object.__name__
+ msg = f"Failed to parse {name} from completion {json_string}. Got: {e}"
+ return OutputParserException(msg, llm_output=json_string)
+
+ @overload
+ def parse_result(
+ self, result: list[Generation], *, partial: Literal[False] = False
+ ) -> TBaseModel: ...
+
+ @overload
+ def parse_result(
+ self, result: list[Generation], *, partial: bool = False
+ ) -> TBaseModel | None: ...
+
+ def parse_result(
+ self, result: list[Generation], *, partial: bool = False
+ ) -> TBaseModel | None:
+ """Parse the result of an LLM call to a Pydantic object.
+
+ Args:
+ result: The result of the LLM call.
+ partial: Whether to parse partial JSON objects.
+
+ If `True`, the output will be a JSON object containing all the keys that
+ have been returned so far.
+
+ Raises:
+ OutputParserException: If the result is not valid JSON or does not conform
+ to the Pydantic model.
+
+ Returns:
+ The parsed Pydantic object.
+ """
+ try:
+ json_object = super().parse_result(result)
+ return self._parse_obj(json_object)
+ except OutputParserException:
+ if partial:
+ return None
+ raise
+
+ def parse(self, text: str) -> TBaseModel:
+ """Parse the output of an LLM call to a Pydantic object.
+
+ Args:
+ text: The output of the LLM call.
+
+ Returns:
+ The parsed Pydantic object.
+ """
+ return self.parse_result([Generation(text=text)])
+
+ def get_format_instructions(self) -> str:
+ """Return the format instructions for the JSON output.
+
+ Returns:
+ The format instructions for the JSON output.
+ """
+ # Copy schema to avoid altering original Pydantic schema.
+ schema = dict(self._get_schema(self.pydantic_object).items())
+
+ # Remove extraneous fields.
+ reduced_schema = schema
+ if "title" in reduced_schema:
+ del reduced_schema["title"]
+ if "type" in reduced_schema:
+ del reduced_schema["type"]
+ # Ensure json in context is well-formed with double quotes.
+ schema_str = json.dumps(reduced_schema, ensure_ascii=False)
+
+ return _PYDANTIC_FORMAT_INSTRUCTIONS.format(schema=schema_str)
+
+ @property
+ def _type(self) -> str:
+ return "pydantic"
+
+ @property
+ @override
+ def OutputType(self) -> type[TBaseModel]:
+ """Return the Pydantic model."""
+ return self.pydantic_object
+
+
+_PYDANTIC_FORMAT_INSTRUCTIONS = """The output should be formatted as a JSON instance that conforms to the JSON schema below.
+
+As an example, for the schema {{"properties": {{"foo": {{"title": "Foo", "description": "a list of strings", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
+the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of the schema. The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
+
+Here is the output schema:
+```
+{schema}
+```""" # noqa: E501
+
+# Re-exporting types for backwards compatibility
+__all__ = [
+ "PydanticBaseModel",
+ "PydanticOutputParser",
+ "TBaseModel",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/string.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/string.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d8f3bb6eddc1253fbd57347859586d208db69a6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/string.py
@@ -0,0 +1,63 @@
+"""String output parser."""
+
+from typing_extensions import override
+
+from langchain_core.output_parsers.transform import BaseTransformOutputParser
+
+
+class StrOutputParser(BaseTransformOutputParser[str]):
+ """Extract text content from model outputs as a string.
+
+ Converts model outputs (such as `AIMessage` or `AIMessageChunk` objects) into plain
+ text strings. It's the simplest output parser and is useful when you need string
+ responses for downstream processing, display, or storage.
+
+ Supports streaming, yielding text chunks as they're generated by the model.
+
+ Example:
+ ```python
+ from langchain_core.output_parsers import StrOutputParser
+ from langchain_openai import ChatOpenAI
+
+ model = ChatOpenAI(model="gpt-4o")
+ parser = StrOutputParser()
+
+ # Get string output from a model
+ message = model.invoke("Tell me a joke")
+ result = parser.invoke(message)
+ print(result) # plain string
+
+ # With streaming - use transform() to process a stream
+ stream = model.stream("Tell me a story")
+ for chunk in parser.transform(stream):
+ print(chunk, end="", flush=True)
+ ```
+ """
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """`StrOutputParser` is serializable.
+
+ Returns:
+ `True`
+ """
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "output_parser"]`
+ """
+ return ["langchain", "schema", "output_parser"]
+
+ @property
+ def _type(self) -> str:
+ """Return the output parser type for serialization."""
+ return "default"
+
+ @override
+ def parse(self, text: str) -> str:
+ """Returns the input text with no changes."""
+ return text
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/transform.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/transform.py
new file mode 100644
index 0000000000000000000000000000000000000000..f04d66b68511decb6ba5dafa183c47516c49842d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/transform.py
@@ -0,0 +1,175 @@
+"""Base classes for output parsers that can handle streaming input."""
+
+from __future__ import annotations
+
+from typing import (
+ TYPE_CHECKING,
+ Any,
+)
+
+from typing_extensions import override
+
+from langchain_core.messages import BaseMessage, BaseMessageChunk
+from langchain_core.output_parsers.base import BaseOutputParser, T
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ Generation,
+ GenerationChunk,
+)
+from langchain_core.runnables.config import run_in_executor
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator
+
+ from langchain_core.runnables import RunnableConfig
+
+
+class BaseTransformOutputParser(BaseOutputParser[T]):
+ """Base class for an output parser that can handle streaming input."""
+
+ def _transform(
+ self,
+ input: Iterator[str | BaseMessage],
+ ) -> Iterator[T]:
+ for chunk in input:
+ if isinstance(chunk, BaseMessage):
+ yield self.parse_result([ChatGeneration(message=chunk)])
+ else:
+ yield self.parse_result([Generation(text=chunk)])
+
+ async def _atransform(
+ self,
+ input: AsyncIterator[str | BaseMessage],
+ ) -> AsyncIterator[T]:
+ async for chunk in input:
+ if isinstance(chunk, BaseMessage):
+ yield await run_in_executor(
+ None, self.parse_result, [ChatGeneration(message=chunk)]
+ )
+ else:
+ yield await run_in_executor(
+ None, self.parse_result, [Generation(text=chunk)]
+ )
+
+ @override
+ def transform(
+ self,
+ input: Iterator[str | BaseMessage],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[T]:
+ """Transform the input into the output format.
+
+ Args:
+ input: The input to transform.
+ config: The configuration to use for the transformation.
+ **kwargs: Additional keyword arguments.
+
+ Yields:
+ The transformed output.
+ """
+ yield from self._transform_stream_with_config(
+ input, self._transform, config, run_type="parser"
+ )
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[str | BaseMessage],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[T]:
+ """Async transform the input into the output format.
+
+ Args:
+ input: The input to transform.
+ config: The configuration to use for the transformation.
+ **kwargs: Additional keyword arguments.
+
+ Yields:
+ The transformed output.
+ """
+ async for chunk in self._atransform_stream_with_config(
+ input, self._atransform, config, run_type="parser"
+ ):
+ yield chunk
+
+
+class BaseCumulativeTransformOutputParser(BaseTransformOutputParser[T]):
+ """Base class for an output parser that can handle streaming input."""
+
+ diff: bool = False
+ """In streaming mode, whether to yield diffs between the previous and current parsed
+ output, or just the current parsed output.
+ """
+
+ def _diff(
+ self,
+ prev: T | None,
+ next: T, # noqa: A002
+ ) -> T:
+ """Convert parsed outputs into a diff format.
+
+ The semantics of this are up to the output parser.
+
+ Args:
+ prev: The previous parsed output.
+ next: The current parsed output.
+
+ Returns:
+ The diff between the previous and current parsed output.
+ """
+ raise NotImplementedError
+
+ @override
+ def _transform(self, input: Iterator[str | BaseMessage]) -> Iterator[Any]:
+ prev_parsed = None
+ acc_gen: GenerationChunk | ChatGenerationChunk | None = None
+ for chunk in input:
+ chunk_gen: GenerationChunk | ChatGenerationChunk
+ if isinstance(chunk, BaseMessageChunk):
+ chunk_gen = ChatGenerationChunk(message=chunk)
+ elif isinstance(chunk, BaseMessage):
+ chunk_gen = ChatGenerationChunk(
+ message=BaseMessageChunk(**chunk.model_dump())
+ )
+ else:
+ chunk_gen = GenerationChunk(text=chunk)
+
+ acc_gen = chunk_gen if acc_gen is None else acc_gen + chunk_gen # type: ignore[operator]
+
+ parsed = self.parse_result([acc_gen], partial=True)
+ if parsed is not None and parsed != prev_parsed:
+ if self.diff:
+ yield self._diff(prev_parsed, parsed)
+ else:
+ yield parsed
+ prev_parsed = parsed
+
+ @override
+ async def _atransform(
+ self, input: AsyncIterator[str | BaseMessage]
+ ) -> AsyncIterator[T]:
+ prev_parsed = None
+ acc_gen: GenerationChunk | ChatGenerationChunk | None = None
+ async for chunk in input:
+ chunk_gen: GenerationChunk | ChatGenerationChunk
+ if isinstance(chunk, BaseMessageChunk):
+ chunk_gen = ChatGenerationChunk(message=chunk)
+ elif isinstance(chunk, BaseMessage):
+ chunk_gen = ChatGenerationChunk(
+ message=BaseMessageChunk(**chunk.model_dump())
+ )
+ else:
+ chunk_gen = GenerationChunk(text=chunk)
+
+ acc_gen = chunk_gen if acc_gen is None else acc_gen + chunk_gen # type: ignore[operator]
+
+ parsed = await self.aparse_result([acc_gen], partial=True)
+ if parsed is not None and parsed != prev_parsed:
+ if self.diff:
+ yield await run_in_executor(None, self._diff, prev_parsed, parsed)
+ else:
+ yield parsed
+ prev_parsed = parsed
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/xml.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/xml.py
new file mode 100644
index 0000000000000000000000000000000000000000..c65a1db3299a6694bef71cd1e5015dfb6782e542
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/output_parsers/xml.py
@@ -0,0 +1,300 @@
+"""Output parser for XML format."""
+
+import contextlib
+import re
+import xml
+import xml.etree.ElementTree as ET
+from collections.abc import AsyncIterator, Iterator
+from typing import Any, Literal
+from xml.etree.ElementTree import TreeBuilder
+
+from typing_extensions import override
+
+from langchain_core.exceptions import OutputParserException
+from langchain_core.messages import BaseMessage
+from langchain_core.output_parsers.transform import BaseTransformOutputParser
+from langchain_core.runnables.utils import AddableDict
+
+try:
+ from defusedxml import ElementTree # type: ignore[import-untyped]
+ from defusedxml.ElementTree import XMLParser # type: ignore[import-untyped]
+
+ _HAS_DEFUSEDXML = True
+except ImportError:
+ _HAS_DEFUSEDXML = False
+
+XML_FORMAT_INSTRUCTIONS = """The output should be formatted as a XML file.
+1. Output should conform to the tags below.
+2. If tags are not given, make them on your own.
+3. Remember to always open and close all the tags.
+
+As an example, for the tags ["foo", "bar", "baz"]:
+1. String "\n \n \n \n" is a well-formatted instance of the schema.
+2. String "\n \n " is a badly-formatted instance.
+3. String "\n \n \n" is a badly-formatted instance.
+
+Here are the output tags:
+```
+{tags}
+```""" # noqa: E501
+
+
+class _StreamingParser:
+ """Streaming parser for XML.
+
+ This implementation is pulled into a class to avoid implementation drift between
+ `transform` and `atransform` of the `XMLOutputParser`.
+ """
+
+ def __init__(self, parser: Literal["defusedxml", "xml"]) -> None:
+ """Initialize the streaming parser.
+
+ Args:
+ parser: Parser to use for XML parsing.
+
+ Can be either `'defusedxml'` or `'xml'`. See documentation in
+ `XMLOutputParser` for more information.
+
+ Raises:
+ ImportError: If `defusedxml` is not installed and the `defusedxml` parser is
+ requested.
+ """
+ if parser == "defusedxml":
+ if not _HAS_DEFUSEDXML:
+ msg = (
+ "defusedxml is not installed. "
+ "Please install it to use the defusedxml parser."
+ "You can install it with `pip install defusedxml` "
+ )
+ raise ImportError(msg)
+ parser_ = XMLParser(target=TreeBuilder())
+ else:
+ parser_ = None
+ self.pull_parser = ET.XMLPullParser(["start", "end"], _parser=parser_)
+ self.xml_start_re = re.compile(r"<[a-zA-Z:_]")
+ self.current_path: list[str] = []
+ self.current_path_has_children = False
+ self.buffer = ""
+ self.xml_started = False
+
+ def parse(self, chunk: str | BaseMessage) -> Iterator[AddableDict]:
+ """Parse a chunk of text.
+
+ Args:
+ chunk: A chunk of text to parse. This can be a `str` or a `BaseMessage`.
+
+ Yields:
+ A `dict` representing the parsed XML element.
+
+ Raises:
+ xml.etree.ElementTree.ParseError: If the XML is not well-formed.
+ """
+ if isinstance(chunk, BaseMessage):
+ # extract text
+ chunk_content = chunk.content
+ if not isinstance(chunk_content, str):
+ # ignore non-string messages (e.g., function calls)
+ return
+ chunk = chunk_content
+ # add chunk to buffer of unprocessed text
+ self.buffer += chunk
+ # if xml string hasn't started yet, continue to next chunk
+ if not self.xml_started:
+ if match := self.xml_start_re.search(self.buffer):
+ # if xml string has started, remove all text before it
+ self.buffer = self.buffer[match.start() :]
+ self.xml_started = True
+ else:
+ return
+ # feed buffer to parser
+ self.pull_parser.feed(self.buffer)
+ self.buffer = ""
+ # yield all events
+ try:
+ events = self.pull_parser.read_events()
+ for event, elem in events: # type: ignore[misc]
+ if event == "start":
+ # update current path
+ self.current_path.append(elem.tag) # type: ignore[union-attr]
+ self.current_path_has_children = False
+ elif event == "end":
+ # remove last element from current path
+ #
+ self.current_path.pop()
+ # yield element
+ if not self.current_path_has_children:
+ yield nested_element(self.current_path, elem) # type: ignore[arg-type]
+ # prevent yielding of parent element
+ if self.current_path:
+ self.current_path_has_children = True
+ else:
+ self.xml_started = False
+ except xml.etree.ElementTree.ParseError:
+ # This might be junk at the end of the XML input.
+ # Let's check whether the current path is empty.
+ if not self.current_path:
+ # If it is empty, we can ignore this error.
+ return
+ else:
+ raise
+
+ def close(self) -> None:
+ """Close the parser.
+
+ This should be called after all chunks have been parsed.
+ """
+ # Ignore ParseError. This will ignore any incomplete XML at the end of the input
+ with contextlib.suppress(xml.etree.ElementTree.ParseError):
+ self.pull_parser.close()
+
+
+class XMLOutputParser(BaseTransformOutputParser):
+ """Parse an output using xml format.
+
+ Returns a dictionary of tags.
+ """
+
+ tags: list[str] | None = None
+ """Tags to tell the LLM to expect in the XML output.
+
+ Note this may not be perfect depending on the LLM implementation.
+
+ For example, with `tags=["foo", "bar", "baz"]`:
+
+ 1. A well-formatted XML instance:
+ `'\n \n \n \n'`
+
+ 2. A badly-formatted XML instance (missing closing tag for 'bar'):
+ `'\n \n '`
+
+ 3. A badly-formatted XML instance (unexpected 'tag' element):
+ `'\n \n \n'`
+ """
+ encoding_matcher: re.Pattern = re.compile(
+ r"<([^>]*encoding[^>]*)>\n(.*)", re.MULTILINE | re.DOTALL
+ )
+
+ parser: Literal["defusedxml", "xml"] = "defusedxml"
+ """Parser to use for XML parsing.
+
+ Can be either `'defusedxml'` or `'xml'`.
+
+ - `'defusedxml'` is the default parser and is used to prevent XML vulnerabilities
+ present in some distributions of Python's standard library xml. `defusedxml` is
+ a wrapper around the standard library parser that sets up the parser with secure
+ defaults.
+ - `'xml'` is the standard library parser.
+
+ !!! warning
+
+ Use `xml` only if you are sure that your distribution of the standard library is
+ not vulnerable to XML vulnerabilities.
+
+ Review the following resources for more information:
+
+ * https://docs.python.org/3/library/xml.html#xml-vulnerabilities
+ * https://github.com/tiran/defusedxml
+
+ The standard library relies on [`libexpat`](https://github.com/libexpat/libexpat)
+ for parsing XML.
+ """
+
+ def get_format_instructions(self) -> str:
+ """Return the format instructions for the XML output."""
+ return XML_FORMAT_INSTRUCTIONS.format(tags=self.tags)
+
+ def parse(self, text: str) -> dict[str, str | list[Any]]:
+ """Parse the output of an LLM call.
+
+ Args:
+ text: The output of an LLM call.
+
+ Returns:
+ A `dict` representing the parsed XML.
+
+ Raises:
+ OutputParserException: If the XML is not well-formed.
+ ImportError: If defus`edxml is not installed and the `defusedxml` parser is
+ requested.
+ """
+ # Try to find XML string within triple backticks
+ # Imports are temporarily placed here to avoid issue with caching on CI
+ # likely if you're reading this you can move them to the top of the file
+ if self.parser == "defusedxml":
+ if not _HAS_DEFUSEDXML:
+ msg = (
+ "defusedxml is not installed. "
+ "Please install it to use the defusedxml parser."
+ "You can install it with `pip install defusedxml`"
+ "See https://github.com/tiran/defusedxml for more details"
+ )
+ raise ImportError(msg)
+ et = ElementTree # Use the defusedxml parser
+ else:
+ et = ET # Use the standard library parser
+
+ match = re.search(r"```(xml)?(.*)```", text, re.DOTALL)
+ if match is not None:
+ # If match found, use the content within the backticks
+ text = match.group(2)
+ encoding_match = self.encoding_matcher.search(text)
+ if encoding_match:
+ text = encoding_match.group(2)
+
+ text = text.strip()
+ try:
+ root = et.fromstring(text)
+ return self._root_to_dict(root)
+ except et.ParseError as e:
+ msg = f"Failed to parse XML format from completion {text}. Got: {e}"
+ raise OutputParserException(msg, llm_output=text) from e
+
+ @override
+ def _transform(self, input: Iterator[str | BaseMessage]) -> Iterator[AddableDict]:
+ streaming_parser = _StreamingParser(self.parser)
+ for chunk in input:
+ yield from streaming_parser.parse(chunk)
+ streaming_parser.close()
+
+ @override
+ async def _atransform(
+ self, input: AsyncIterator[str | BaseMessage]
+ ) -> AsyncIterator[AddableDict]:
+ streaming_parser = _StreamingParser(self.parser)
+ async for chunk in input:
+ for output in streaming_parser.parse(chunk):
+ yield output
+ streaming_parser.close()
+
+ def _root_to_dict(self, root: ET.Element) -> dict[str, str | list[Any]]:
+ """Converts xml tree to python dictionary."""
+ if root.text and bool(re.search(r"\S", root.text)):
+ # If root text contains any non-whitespace character it
+ # returns {root.tag: root.text}
+ return {root.tag: root.text}
+ result: dict = {root.tag: []}
+ for child in root:
+ if len(child) == 0:
+ result[root.tag].append({child.tag: child.text})
+ else:
+ result[root.tag].append(self._root_to_dict(child))
+ return result
+
+ @property
+ def _type(self) -> str:
+ return "xml"
+
+
+def nested_element(path: list[str], elem: ET.Element) -> Any:
+ """Get nested element from path.
+
+ Args:
+ path: The path to the element.
+ elem: The element to extract.
+
+ Returns:
+ The nested element.
+ """
+ if len(path) == 0:
+ return AddableDict({elem.tag: elem.text})
+ return AddableDict({path[0]: [nested_element(path[1:], elem)]})
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d579010ee76187168ad8164555884aed4bd1a267
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__init__.py
@@ -0,0 +1,66 @@
+"""Output classes.
+
+Used to represent the output of a language model call and the output of a chat.
+
+The top container for information is the `LLMResult` object. `LLMResult` is used by both
+chat models and LLMs. This object contains the output of the language model and any
+additional information that the model provider wants to return.
+
+When invoking models via the standard runnable methods (e.g. invoke, batch, etc.):
+
+- Chat models will return `AIMessage` objects.
+- LLMs will return regular text strings.
+
+In addition, users can access the raw output of either LLMs or chat models via
+callbacks. The `on_chat_model_end` and `on_llm_end` callbacks will return an `LLMResult`
+object containing the generated outputs and any additional information returned by the
+model provider.
+
+In general, if information is already available in the AIMessage object, it is
+recommended to access it from there rather than from the `LLMResult` object.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.outputs.chat_generation import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ )
+ from langchain_core.outputs.chat_result import ChatResult
+ from langchain_core.outputs.generation import Generation, GenerationChunk
+ from langchain_core.outputs.llm_result import LLMResult
+ from langchain_core.outputs.run_info import RunInfo
+
+__all__ = (
+ "ChatGeneration",
+ "ChatGenerationChunk",
+ "ChatResult",
+ "Generation",
+ "GenerationChunk",
+ "LLMResult",
+ "RunInfo",
+)
+
+_dynamic_imports = {
+ "ChatGeneration": "chat_generation",
+ "ChatGenerationChunk": "chat_generation",
+ "ChatResult": "chat_result",
+ "Generation": "generation",
+ "GenerationChunk": "generation",
+ "LLMResult": "llm_result",
+ "RunInfo": "run_info",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f576f30dfcd0c406b25177163554bcb3e39b23ec
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/chat_generation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/chat_generation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d832da3ecbef0bc90429650a8be0b0c2d18882b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/chat_generation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/chat_result.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/chat_result.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c40e5fda9f18587e9bf504cab69fd18bd7ec3ac5
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/chat_result.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/generation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/generation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e4494ade6e2f65b02a5819b834c94172e3e46c42
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/generation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/llm_result.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/llm_result.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..942d4acfee5a75e08f3e84dce29f43f6aa9df5f1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/llm_result.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/run_info.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/run_info.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf6d7a34ea15283522cd41da268a745123f28e87
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/__pycache__/run_info.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/chat_generation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/chat_generation.py
new file mode 100644
index 0000000000000000000000000000000000000000..b104d9b613350a38b6b4a5ae5addb4d3dd477454
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/chat_generation.py
@@ -0,0 +1,157 @@
+"""Chat generation output classes."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Literal
+
+from pydantic import model_validator
+
+from langchain_core.messages import BaseMessage, BaseMessageChunk
+from langchain_core.outputs.generation import Generation
+from langchain_core.utils._merge import merge_dicts
+
+if TYPE_CHECKING:
+ from typing_extensions import Self
+
+
+class ChatGeneration(Generation):
+ """A single chat generation output.
+
+ A subclass of `Generation` that represents the response from a chat model that
+ generates chat messages.
+
+ The `message` attribute is a structured representation of the chat message. Most of
+ the time, the message will be of type `AIMessage`.
+
+ Users working with chat models will usually access information via either
+ `AIMessage` (returned from runnable interfaces) or `LLMResult` (available via
+ callbacks).
+ """
+
+ text: str = ""
+ """The text contents of the output message.
+
+ !!! warning "SHOULD NOT BE SET DIRECTLY!"
+
+ """
+ message: BaseMessage
+ """The message output by the chat model."""
+
+ # Override type to be ChatGeneration, ignore mypy error as this is intentional
+ type: Literal["ChatGeneration"] = "ChatGeneration" # type: ignore[assignment]
+ """Type is used exclusively for serialization purposes."""
+
+ @model_validator(mode="after")
+ def set_text(self) -> Self:
+ """Set the text attribute to be the contents of the message.
+
+ Args:
+ values: The values of the object.
+
+ Returns:
+ The values of the object with the text attribute set.
+
+ Raises:
+ ValueError: If the message is not a string or a list.
+ """
+ # Check for legacy blocks with "text" key but no "type" field.
+ # Otherwise, delegate to `message.text`.
+ if isinstance(self.message.content, list):
+ has_legacy_blocks = any(
+ isinstance(block, dict)
+ and "text" in block
+ and block.get("type") is None
+ for block in self.message.content
+ )
+
+ if has_legacy_blocks:
+ blocks = []
+ for block in self.message.content:
+ if isinstance(block, str):
+ blocks.append(block)
+ elif isinstance(block, dict):
+ block_type = block.get("type")
+ if block_type == "text" or (
+ block_type is None and "text" in block
+ ):
+ blocks.append(block.get("text", ""))
+ self.text = "".join(blocks)
+ else:
+ self.text = self.message.text
+ else:
+ self.text = self.message.text
+
+ return self
+
+
+class ChatGenerationChunk(ChatGeneration):
+ """`ChatGeneration` chunk.
+
+ `ChatGeneration` chunks can be concatenated with other `ChatGeneration` chunks.
+ """
+
+ message: BaseMessageChunk
+ """The message chunk output by the chat model."""
+ # Override type to be ChatGeneration, ignore mypy error as this is intentional
+
+ type: Literal["ChatGenerationChunk"] = "ChatGenerationChunk" # type: ignore[assignment]
+ """Type is used exclusively for serialization purposes."""
+
+ def __add__(
+ self, other: ChatGenerationChunk | list[ChatGenerationChunk]
+ ) -> ChatGenerationChunk:
+ """Concatenate two `ChatGenerationChunk`s.
+
+ Args:
+ other: The other `ChatGenerationChunk` or list of `ChatGenerationChunk` to
+ concatenate.
+
+ Raises:
+ TypeError: If other is not a `ChatGenerationChunk` or list of
+ `ChatGenerationChunk`.
+
+ Returns:
+ A new `ChatGenerationChunk` concatenated from self and other.
+ """
+ if isinstance(other, ChatGenerationChunk):
+ generation_info = merge_dicts(
+ self.generation_info or {},
+ other.generation_info or {},
+ )
+ return ChatGenerationChunk(
+ message=self.message + other.message,
+ generation_info=generation_info or None,
+ )
+ if isinstance(other, list) and all(
+ isinstance(x, ChatGenerationChunk) for x in other
+ ):
+ generation_info = merge_dicts(
+ self.generation_info or {},
+ *[chunk.generation_info for chunk in other if chunk.generation_info],
+ )
+ return ChatGenerationChunk(
+ message=self.message + [chunk.message for chunk in other],
+ generation_info=generation_info or None,
+ )
+ msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"
+ raise TypeError(msg)
+
+
+def merge_chat_generation_chunks(
+ chunks: list[ChatGenerationChunk],
+) -> ChatGenerationChunk | None:
+ """Merge a list of `ChatGenerationChunk`s into a single `ChatGenerationChunk`.
+
+ Args:
+ chunks: A list of `ChatGenerationChunk` to merge.
+
+ Returns:
+ A merged `ChatGenerationChunk`, or `None` if the input list is empty.
+ """
+ if not chunks:
+ return None
+
+ if len(chunks) == 1:
+ return chunks[0]
+
+ return chunks[0] + chunks[1:]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/chat_result.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/chat_result.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cc814310e44ffce6bc0b84475d81f5dae735a43
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/chat_result.py
@@ -0,0 +1,37 @@
+"""Chat result schema."""
+
+from pydantic import BaseModel
+
+from langchain_core.outputs.chat_generation import ChatGeneration
+
+
+class ChatResult(BaseModel):
+ """Use to represent the result of a chat model call with a single prompt.
+
+ This container is used internally by some implementations of chat model, it will
+ eventually be mapped to a more general `LLMResult` object, and then projected into
+ an `AIMessage` object.
+
+ LangChain users working with chat models will usually access information via
+ `AIMessage` (returned from runnable interfaces) or `LLMResult` (available via
+ callbacks). Please refer the `AIMessage` and `LLMResult` schema documentation for
+ more information.
+ """
+
+ generations: list[ChatGeneration]
+ """List of the chat generations.
+
+ Generations is a list to allow for multiple candidate generations for a single
+ input prompt.
+ """
+
+ llm_output: dict | None = None
+ """For arbitrary model provider-specific output.
+
+ This dictionary is a free-form dictionary that can contain any information that the
+ provider wants to return. It is not standardized and keys may vary by provider and
+ over time.
+
+ Users should generally avoid relying on this field and instead rely on accessing
+ relevant information from standardized fields present in `AIMessage`.
+ """
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/generation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/generation.py
new file mode 100644
index 0000000000000000000000000000000000000000..246b68c1fc2b77debcaa7267304856be7ef916b4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/generation.py
@@ -0,0 +1,80 @@
+"""Generation output schema."""
+
+from __future__ import annotations
+
+from typing import Any, Literal
+
+from langchain_core.load import Serializable
+from langchain_core.utils._merge import merge_dicts
+
+
+class Generation(Serializable):
+ """A single text generation output.
+
+ Generation represents the response from an "old-fashioned" LLM (string-in,
+ string-out) that generates regular text (not chat messages).
+
+ This model is used internally by chat model and will eventually be mapped to a more
+ general `LLMResult` object, and then projected into an `AIMessage` object.
+
+ LangChain users working with chat models will usually access information via
+ `AIMessage` (returned from runnable interfaces) or `LLMResult` (available via
+ callbacks). Please refer to `AIMessage` and `LLMResult` for more information.
+ """
+
+ text: str
+ """Generated text output."""
+
+ generation_info: dict[str, Any] | None = None
+ """Raw response from the provider.
+
+ May include things like the reason for finishing or token log probabilities.
+ """
+
+ type: Literal["Generation"] = "Generation"
+ """Type is used exclusively for serialization purposes.
+
+ Set to `'Generation'` for this class.
+ """
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "output"]`
+ """
+ return ["langchain", "schema", "output"]
+
+
+class GenerationChunk(Generation):
+ """`GenerationChunk`, which can be concatenated with other `Generation` chunks."""
+
+ def __add__(self, other: GenerationChunk) -> GenerationChunk:
+ """Concatenate two `GenerationChunk` objects.
+
+ Args:
+ other: Another `GenerationChunk` to concatenate with.
+
+ Raises:
+ TypeError: If other is not a `GenerationChunk`.
+
+ Returns:
+ A new `GenerationChunk` concatenated from self and other.
+ """
+ if isinstance(other, GenerationChunk):
+ generation_info = merge_dicts(
+ self.generation_info or {},
+ other.generation_info or {},
+ )
+ return GenerationChunk(
+ text=self.text + other.text,
+ generation_info=generation_info or None,
+ )
+ msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"
+ raise TypeError(msg)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/llm_result.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/llm_result.py
new file mode 100644
index 0000000000000000000000000000000000000000..df40c41975089b293463988ba2558fd31a8bd8fb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/llm_result.py
@@ -0,0 +1,112 @@
+"""`LLMResult` class."""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import Literal
+
+from pydantic import BaseModel
+
+from langchain_core.outputs.chat_generation import ChatGeneration, ChatGenerationChunk
+from langchain_core.outputs.generation import Generation, GenerationChunk
+from langchain_core.outputs.run_info import RunInfo
+
+
+class LLMResult(BaseModel):
+ """A container for results of an LLM call.
+
+ Both chat models and LLMs generate an `LLMResult` object. This object contains the
+ generated outputs and any additional information that the model provider wants to
+ return.
+ """
+
+ generations: list[
+ list[Generation | ChatGeneration | GenerationChunk | ChatGenerationChunk]
+ ]
+ """Generated outputs.
+
+ The first dimension of the list represents completions for different input prompts.
+
+ The second dimension of the list represents different candidate generations for a
+ given prompt.
+
+ - When returned from **an LLM**, the type is `list[list[Generation]]`.
+ - When returned from a **chat model**, the type is `list[list[ChatGeneration]]`.
+
+ `ChatGeneration` is a subclass of `Generation` that has a field for a structured
+ chat message.
+ """
+
+ llm_output: dict | None = None
+ """For arbitrary model provider-specific output.
+
+ This dictionary is a free-form dictionary that can contain any information that the
+ provider wants to return. It is not standardized and keys may vary by provider and
+ over time.
+
+ Users should generally avoid relying on this field and instead rely on accessing
+ relevant information from standardized fields present in AIMessage.
+ """
+
+ run: list[RunInfo] | None = None
+ """List of metadata info for model call for each input.
+
+ See `langchain_core.outputs.run_info.RunInfo` for details.
+ """
+
+ type: Literal["LLMResult"] = "LLMResult"
+ """Type is used exclusively for serialization purposes."""
+
+ def flatten(self) -> list[LLMResult]:
+ """Flatten generations into a single list.
+
+ Unpack `list[list[Generation]] -> list[LLMResult]` where each returned
+ `LLMResult` contains only a single `Generation`. If token usage information is
+ available, it is kept only for the `LLMResult` corresponding to the top-choice
+ `Generation`, to avoid over-counting of token usage downstream.
+
+ Returns:
+ List of `LLMResult` objects where each returned `LLMResult` contains a
+ single `Generation`.
+ """
+ llm_results = []
+ for i, gen_list in enumerate(self.generations):
+ # Avoid double counting tokens in OpenAICallback
+ if i == 0:
+ llm_results.append(
+ LLMResult(
+ generations=[gen_list],
+ llm_output=self.llm_output,
+ )
+ )
+ else:
+ if self.llm_output is not None:
+ llm_output = deepcopy(self.llm_output)
+ llm_output["token_usage"] = {}
+ else:
+ llm_output = None
+ llm_results.append(
+ LLMResult(
+ generations=[gen_list],
+ llm_output=llm_output,
+ )
+ )
+ return llm_results
+
+ def __eq__(self, other: object) -> bool:
+ """Check for `LLMResult` equality by ignoring any metadata related to runs.
+
+ Args:
+ other: Another `LLMResult` object to compare against.
+
+ Returns:
+ `True` if the generations and `llm_output` are equal, `False` otherwise.
+ """
+ if not isinstance(other, LLMResult):
+ return NotImplemented
+ return (
+ self.generations == other.generations
+ and self.llm_output == other.llm_output
+ )
+
+ __hash__ = None # type: ignore[assignment]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/run_info.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/run_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8bbca14555562447d6ccbe28520cfbd74671273
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/outputs/run_info.py
@@ -0,0 +1,22 @@
+"""`RunInfo` class."""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from pydantic import BaseModel
+
+
+class RunInfo(BaseModel):
+ """Class that contains metadata for a single execution of a chain or model.
+
+ Defined for backwards compatibility with older versions of `langchain_core`.
+
+ !!! warning "This model will likely be deprecated in the future."
+
+ Users can acquire the `run_id` information from callbacks or via `run_id`
+ information present in the `astream_event` API (depending on the use case).
+ """
+
+ run_id: UUID
+ """A unique identifier for the model or chain run."""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..772ed40d19d6b3a2569a31d71214771a1ba18112
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__init__.py
@@ -0,0 +1,101 @@
+"""A prompt is the input to the model.
+
+Prompt is often constructed from multiple components and prompt values. Prompt classes
+and functions make constructing and working with prompts easy.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.prompts.base import (
+ BasePromptTemplate,
+ aformat_document,
+ format_document,
+ )
+ from langchain_core.prompts.chat import (
+ AIMessagePromptTemplate,
+ BaseChatPromptTemplate,
+ ChatMessagePromptTemplate,
+ ChatPromptTemplate,
+ HumanMessagePromptTemplate,
+ MessagesPlaceholder,
+ SystemMessagePromptTemplate,
+ )
+ from langchain_core.prompts.dict import DictPromptTemplate
+ from langchain_core.prompts.few_shot import (
+ FewShotChatMessagePromptTemplate,
+ FewShotPromptTemplate,
+ )
+ from langchain_core.prompts.few_shot_with_templates import (
+ FewShotPromptWithTemplates,
+ )
+ from langchain_core.prompts.loading import load_prompt
+ from langchain_core.prompts.prompt import PromptTemplate
+ from langchain_core.prompts.string import (
+ StringPromptTemplate,
+ check_valid_template,
+ get_template_variables,
+ jinja2_formatter,
+ validate_jinja2,
+ )
+
+__all__ = (
+ "AIMessagePromptTemplate",
+ "BaseChatPromptTemplate",
+ "BasePromptTemplate",
+ "ChatMessagePromptTemplate",
+ "ChatPromptTemplate",
+ "DictPromptTemplate",
+ "FewShotChatMessagePromptTemplate",
+ "FewShotPromptTemplate",
+ "FewShotPromptWithTemplates",
+ "HumanMessagePromptTemplate",
+ "MessagesPlaceholder",
+ "PromptTemplate",
+ "StringPromptTemplate",
+ "SystemMessagePromptTemplate",
+ "aformat_document",
+ "check_valid_template",
+ "format_document",
+ "get_template_variables",
+ "jinja2_formatter",
+ "load_prompt",
+ "validate_jinja2",
+)
+
+_dynamic_imports = {
+ "BasePromptTemplate": "base",
+ "format_document": "base",
+ "aformat_document": "base",
+ "AIMessagePromptTemplate": "chat",
+ "BaseChatPromptTemplate": "chat",
+ "ChatMessagePromptTemplate": "chat",
+ "ChatPromptTemplate": "chat",
+ "DictPromptTemplate": "dict",
+ "HumanMessagePromptTemplate": "chat",
+ "MessagesPlaceholder": "chat",
+ "SystemMessagePromptTemplate": "chat",
+ "FewShotChatMessagePromptTemplate": "few_shot",
+ "FewShotPromptTemplate": "few_shot",
+ "FewShotPromptWithTemplates": "few_shot_with_templates",
+ "load_prompt": "loading",
+ "PromptTemplate": "prompt",
+ "StringPromptTemplate": "string",
+ "check_valid_template": "string",
+ "get_template_variables": "string",
+ "jinja2_formatter": "string",
+ "validate_jinja2": "string",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e59608ad7dfd5e94ffe3b2b0aa1b9aa1665eac5
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cad4a5c24b8cffa974dd199d073d8570d88c8ff4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/chat.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/chat.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ff8148c13fcefb756cf21db783cdcd9b41a37ab
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/chat.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/dict.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/dict.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..222d79bedaca2eb5ca7187f278cd2762a691bd70
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/dict.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/few_shot.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/few_shot.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..996f0147062abe1d62650612d1b9f726f24fc6b8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/few_shot.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/few_shot_with_templates.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/few_shot_with_templates.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3355975fb9f85ddb0f43a2dfd8a589c20e16f86d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/few_shot_with_templates.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/image.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/image.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6eb0b38fb5b743f20e0ae59c11168800e52eea47
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/image.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/loading.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/loading.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..736ff78aa6f39f06398dfe292a941c0a6e686bd1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/loading.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/message.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/message.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b5f1b1543f941bd190e863acb0486d2ad4e4df4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/message.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/prompt.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/prompt.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c37bf6ba7ae1bf71c6a2fd005102f35b30827e75
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/prompt.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/string.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/string.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d440212cf384eb263658120f81871aed69bc8886
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/string.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/structured.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/structured.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..390d8cfd4380cb94943ace15b55bfa17e3a8000c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/__pycache__/structured.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..c96c936d80f167685df6f80b418fd604b51f0957
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/base.py
@@ -0,0 +1,478 @@
+"""Base class for prompt templates."""
+
+from __future__ import annotations
+
+import builtins # noqa: TC003
+import contextlib
+import json
+from abc import ABC, abstractmethod
+from collections.abc import Mapping # noqa: TC003
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast
+
+import yaml
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+from typing_extensions import Self, override
+
+from langchain_core._api import deprecated
+from langchain_core.exceptions import ErrorCode, create_message
+from langchain_core.load import dumpd
+from langchain_core.output_parsers.base import BaseOutputParser # noqa: TC001
+from langchain_core.prompt_values import (
+ ChatPromptValueConcrete,
+ PromptValue,
+ StringPromptValue,
+)
+from langchain_core.runnables import RunnableConfig, RunnableSerializable
+from langchain_core.runnables.config import ensure_config
+from langchain_core.utils.pydantic import create_model_v2
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ from langchain_core.documents import Document
+
+
+FormatOutputType = TypeVar("FormatOutputType")
+
+
+class BasePromptTemplate(
+ RunnableSerializable[dict, PromptValue], ABC, Generic[FormatOutputType]
+):
+ """Base class for all prompt templates, returning a prompt."""
+
+ input_variables: list[str]
+ """A list of the names of the variables whose values are required as inputs to the
+ prompt.
+ """
+
+ optional_variables: list[str] = Field(default=[])
+ """A list of the names of the variables for placeholder or `MessagePlaceholder` that
+ are optional.
+
+ These variables are auto inferred from the prompt and user need not provide them.
+ """
+
+ input_types: builtins.dict[str, Any] = Field(default_factory=dict, exclude=True)
+ """A dictionary of the types of the variables the prompt template expects.
+
+ If not provided, all variables are assumed to be strings.
+ """
+
+ output_parser: BaseOutputParser | None = None
+ """How to parse the output of calling an LLM on this formatted prompt."""
+
+ partial_variables: Mapping[str, Any] = Field(default_factory=dict)
+ """A dictionary of the partial variables the prompt template carries.
+
+ Partial variables populate the template so that you don't need to pass them in every
+ time you call the prompt.
+ """
+
+ metadata: builtins.dict[str, Any] | None = None
+ """Metadata to be used for tracing."""
+
+ tags: list[str] | None = None
+ """Tags to be used for tracing."""
+
+ @model_validator(mode="after")
+ def validate_variable_names(self) -> Self:
+ """Validate variable names do not include restricted names."""
+ if "stop" in self.input_variables:
+ msg = (
+ "Cannot have an input variable named 'stop', as it is used internally,"
+ " please rename."
+ )
+ raise ValueError(
+ create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
+ )
+ if "stop" in self.partial_variables:
+ msg = (
+ "Cannot have an partial variable named 'stop', as it is used "
+ "internally, please rename."
+ )
+ raise ValueError(
+ create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
+ )
+
+ overall = set(self.input_variables).intersection(self.partial_variables)
+ if overall:
+ msg = f"Found overlapping input and partial variables: {overall}"
+ raise ValueError(
+ create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
+ )
+ return self
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "prompt_template"]`
+ """
+ return ["langchain", "schema", "prompt_template"]
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @cached_property
+ def _serialized(self) -> dict[str, Any]:
+ # self is always a Serializable object in this case, thus the result is
+ # guaranteed to be a dict since dumpd uses the default callback, which uses
+ # obj.to_json which always returns TypedDict subclasses
+ return cast("dict[str, Any]", dumpd(self))
+
+ @property
+ @override
+ def OutputType(self) -> Any:
+ """Return the output type of the prompt."""
+ return StringPromptValue | ChatPromptValueConcrete
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ """Get the input schema for the prompt.
+
+ Args:
+ config: Configuration for the prompt.
+
+ Returns:
+ The input schema for the prompt.
+ """
+ # This is correct, but pydantic typings/mypy don't think so.
+ required_input_variables = {
+ k: (self.input_types.get(k, str), ...) for k in self.input_variables
+ }
+ optional_input_variables = {
+ k: (self.input_types.get(k, str), None) for k in self.optional_variables
+ }
+ return create_model_v2(
+ "PromptInput",
+ field_definitions={**required_input_variables, **optional_input_variables},
+ )
+
+ def _validate_input(self, inner_input: Any) -> dict:
+ if not isinstance(inner_input, dict):
+ if len(self.input_variables) == 1:
+ var_name = self.input_variables[0]
+ inner_input_ = {var_name: inner_input}
+
+ else:
+ msg = (
+ f"Expected mapping type as input to {self.__class__.__name__}. "
+ f"Received {type(inner_input)}."
+ )
+ raise TypeError(
+ create_message(
+ message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT
+ )
+ )
+ else:
+ inner_input_ = inner_input
+ missing = set(self.input_variables).difference(inner_input_)
+ if missing:
+ msg = (
+ f"Input to {self.__class__.__name__} is missing variables {missing}. "
+ f" Expected: {self.input_variables}"
+ f" Received: {list(inner_input_.keys())}"
+ )
+ example_key = missing.pop()
+ msg += (
+ f"\nNote: if you intended {{{example_key}}} to be part of the string"
+ " and not a variable, please escape it with double curly braces like: "
+ f"'{{{{{example_key}}}}}'."
+ )
+ raise KeyError(
+ create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
+ )
+ return inner_input_
+
+ def _format_prompt_with_error_handling(self, inner_input: dict) -> PromptValue:
+ inner_input_ = self._validate_input(inner_input)
+ return self.format_prompt(**inner_input_)
+
+ async def _aformat_prompt_with_error_handling(
+ self, inner_input: dict
+ ) -> PromptValue:
+ inner_input_ = self._validate_input(inner_input)
+ return await self.aformat_prompt(**inner_input_)
+
+ @override
+ def invoke(
+ self, input: dict, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> PromptValue:
+ """Invoke the prompt.
+
+ Args:
+ input: Input to the prompt.
+ config: Configuration for the prompt.
+
+ Returns:
+ The output of the prompt.
+ """
+ config = ensure_config(config)
+ if self.metadata:
+ config["metadata"] = {**config["metadata"], **self.metadata}
+ if self.tags:
+ config["tags"] += self.tags
+ return self._call_with_config(
+ self._format_prompt_with_error_handling,
+ input,
+ config,
+ run_type="prompt",
+ serialized=self._serialized,
+ )
+
+ @override
+ async def ainvoke(
+ self, input: dict, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> PromptValue:
+ """Async invoke the prompt.
+
+ Args:
+ input: Input to the prompt.
+ config: Configuration for the prompt.
+
+ Returns:
+ The output of the prompt.
+ """
+ config = ensure_config(config)
+ if self.metadata:
+ config["metadata"].update(self.metadata)
+ if self.tags:
+ config["tags"].extend(self.tags)
+ return await self._acall_with_config(
+ self._aformat_prompt_with_error_handling,
+ input,
+ config,
+ run_type="prompt",
+ serialized=self._serialized,
+ )
+
+ @abstractmethod
+ def format_prompt(self, **kwargs: Any) -> PromptValue:
+ """Create `PromptValue`.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ The output of the prompt.
+ """
+
+ async def aformat_prompt(self, **kwargs: Any) -> PromptValue:
+ """Async create `PromptValue`.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ The output of the prompt.
+ """
+ return self.format_prompt(**kwargs)
+
+ def partial(self, **kwargs: str | Callable[[], str]) -> BasePromptTemplate:
+ """Return a partial of the prompt template.
+
+ Args:
+ **kwargs: Partial variables to set.
+
+ Returns:
+ A partial of the prompt template.
+ """
+ prompt_dict = self.__dict__.copy()
+ prompt_dict["input_variables"] = list(
+ set(self.input_variables).difference(kwargs)
+ )
+ prompt_dict["partial_variables"] = {**self.partial_variables, **kwargs}
+ return type(self)(**prompt_dict)
+
+ def _merge_partial_and_user_variables(self, **kwargs: Any) -> dict[str, Any]:
+ # Get partial params:
+ partial_kwargs = {
+ k: v if not callable(v) else v() for k, v in self.partial_variables.items()
+ }
+ return {**partial_kwargs, **kwargs}
+
+ @abstractmethod
+ def format(self, **kwargs: Any) -> FormatOutputType:
+ """Format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+
+ Example:
+ ```python
+ prompt.format(variable1="foo")
+ ```
+ """
+
+ async def aformat(self, **kwargs: Any) -> FormatOutputType:
+ """Async format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+
+ Example:
+ ```python
+ await prompt.aformat(variable1="foo")
+ ```
+ """
+ return self.format(**kwargs)
+
+ @property
+ def _prompt_type(self) -> str:
+ """Return the prompt type key."""
+ raise NotImplementedError
+
+ def dict(self, **kwargs: Any) -> dict:
+ """Return dictionary representation of prompt.
+
+ Args:
+ **kwargs: Any additional arguments to pass to the dictionary.
+
+ Returns:
+ Dictionary representation of the prompt.
+ """
+ prompt_dict = super().model_dump(**kwargs)
+ with contextlib.suppress(NotImplementedError):
+ prompt_dict["_type"] = self._prompt_type
+ return prompt_dict
+
+ @deprecated(
+ since="1.2.21",
+ removal="2.0.0",
+ alternative="Use `dumpd`/`dumps` from `langchain_core.load` to serialize "
+ "prompts and `load`/`loads` to deserialize them.",
+ )
+ def save(self, file_path: Path | str) -> None:
+ """Save the prompt.
+
+ Args:
+ file_path: Path to directory to save prompt to.
+
+ Raises:
+ ValueError: If the prompt has partial variables.
+ ValueError: If the file path is not json or yaml.
+ NotImplementedError: If the prompt type is not implemented.
+
+ Example:
+ ```python
+ prompt.save(file_path="path/prompt.yaml")
+ ```
+ """
+ if self.partial_variables:
+ msg = "Cannot save prompt with partial variables."
+ raise ValueError(msg)
+
+ # Fetch dictionary to save
+ prompt_dict = self.dict()
+ if "_type" not in prompt_dict:
+ msg = f"Prompt {self} does not support saving."
+ raise NotImplementedError(msg)
+
+ # Convert file to Path object.
+ save_path = Path(file_path)
+
+ directory_path = save_path.parent
+ directory_path.mkdir(parents=True, exist_ok=True)
+
+ resolved_path = save_path.resolve()
+ if resolved_path.suffix == ".json":
+ with resolved_path.open("w", encoding="utf-8") as f:
+ json.dump(prompt_dict, f, indent=4)
+ elif resolved_path.suffix.endswith((".yaml", ".yml")):
+ with resolved_path.open("w", encoding="utf-8") as f:
+ yaml.dump(prompt_dict, f, default_flow_style=False)
+ else:
+ msg = f"{save_path} must be json or yaml"
+ raise ValueError(msg)
+
+
+def _get_document_info(doc: Document, prompt: BasePromptTemplate[str]) -> dict:
+ base_info = {"page_content": doc.page_content, **doc.metadata}
+ missing_metadata = set(prompt.input_variables).difference(base_info)
+ if len(missing_metadata) > 0:
+ required_metadata = [
+ iv for iv in prompt.input_variables if iv != "page_content"
+ ]
+ msg = (
+ f"Document prompt requires documents to have metadata variables: "
+ f"{required_metadata}. Received document with missing metadata: "
+ f"{list(missing_metadata)}."
+ )
+ raise ValueError(
+ create_message(message=msg, error_code=ErrorCode.INVALID_PROMPT_INPUT)
+ )
+ return {k: base_info[k] for k in prompt.input_variables}
+
+
+def format_document(doc: Document, prompt: BasePromptTemplate[str]) -> str:
+ """Format a document into a string based on a prompt template.
+
+ First, this pulls information from the document from two sources:
+
+ 1. `page_content`: This takes the information from the `document.page_content` and
+ assigns it to a variable named `page_content`.
+ 2. `metadata`: This takes information from `document.metadata` and assigns it to
+ variables of the same name.
+
+ Those variables are then passed into the `prompt` to produce a formatted string.
+
+ Args:
+ doc: `Document`, the `page_content` and `metadata` will be used to create the
+ final string.
+ prompt: `BasePromptTemplate`, will be used to format the `page_content` and
+ `metadata` into the final string.
+
+ Returns:
+ String of the document formatted.
+
+ Example:
+ ```python
+ from langchain_core.documents import Document
+ from langchain_core.prompts import PromptTemplate
+
+ doc = Document(page_content="This is a joke", metadata={"page": "1"})
+ prompt = PromptTemplate.from_template("Page {page}: {page_content}")
+ format_document(doc, prompt)
+ # -> "Page 1: This is a joke"
+ ```
+ """
+ return prompt.format(**_get_document_info(doc, prompt))
+
+
+async def aformat_document(doc: Document, prompt: BasePromptTemplate[str]) -> str:
+ """Async format a document into a string based on a prompt template.
+
+ First, this pulls information from the document from two sources:
+
+ 1. `page_content`: This takes the information from the `document.page_content` and
+ assigns it to a variable named `page_content`.
+ 2. `metadata`: This takes information from `document.metadata` and assigns it to
+ variables of the same name.
+
+ Those variables are then passed into the `prompt` to produce a formatted string.
+
+ Args:
+ doc: `Document`, the `page_content` and `metadata` will be used to create the
+ final string.
+ prompt: `BasePromptTemplate`, will be used to format the `page_content` and
+ `metadata` into the final string.
+
+ Returns:
+ String of the document formatted.
+ """
+ return await prompt.aformat(**_get_document_info(doc, prompt))
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/chat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/chat.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebd58c80319e50c91cd3a2632db7cd8d0b374fe5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/chat.py
@@ -0,0 +1,1491 @@
+"""Chat prompt template."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from collections.abc import Sequence
+from pathlib import Path
+from typing import (
+ Annotated,
+ Any,
+ TypedDict,
+ TypeVar,
+ cast,
+ overload,
+)
+
+from pydantic import (
+ Field,
+ PositiveInt,
+ SkipValidation,
+ model_validator,
+)
+from typing_extensions import Self, override
+
+from langchain_core._api import deprecated
+from langchain_core.messages import (
+ AIMessage,
+ AnyMessage,
+ BaseMessage,
+ ChatMessage,
+ HumanMessage,
+ SystemMessage,
+ convert_to_messages,
+)
+from langchain_core.messages.base import get_msg_title_repr
+from langchain_core.prompt_values import ChatPromptValue, ImageURL
+from langchain_core.prompts.base import BasePromptTemplate
+from langchain_core.prompts.dict import DictPromptTemplate
+from langchain_core.prompts.image import ImagePromptTemplate
+from langchain_core.prompts.message import (
+ BaseMessagePromptTemplate,
+)
+from langchain_core.prompts.prompt import PromptTemplate
+from langchain_core.prompts.string import (
+ PromptTemplateFormat,
+ StringPromptTemplate,
+ get_template_variables,
+)
+from langchain_core.utils import get_colored_text
+from langchain_core.utils.interactive_env import is_interactive_env
+
+
+class MessagesPlaceholder(BaseMessagePromptTemplate):
+ """Prompt template that assumes variable is already list of messages.
+
+ A placeholder which can be used to pass in a list of messages.
+
+ !!! example "Direct usage"
+
+ ```python
+ from langchain_core.prompts import MessagesPlaceholder
+
+ prompt = MessagesPlaceholder("history")
+ prompt.format_messages() # raises KeyError
+
+ prompt = MessagesPlaceholder("history", optional=True)
+ prompt.format_messages() # returns empty list []
+
+ prompt.format_messages(
+ history=[
+ ("system", "You are an AI assistant."),
+ ("human", "Hello!"),
+ ]
+ )
+ # -> [
+ # SystemMessage(content="You are an AI assistant."),
+ # HumanMessage(content="Hello!"),
+ # ]
+ ```
+
+ !!! example "Building a prompt with chat history"
+
+ ```python
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
+
+ prompt = ChatPromptTemplate.from_messages(
+ [
+ ("system", "You are a helpful assistant."),
+ MessagesPlaceholder("history"),
+ ("human", "{question}"),
+ ]
+ )
+ prompt.invoke(
+ {
+ "history": [("human", "what's 5 + 2"), ("ai", "5 + 2 is 7")],
+ "question": "now multiply that by 4",
+ }
+ )
+ # -> ChatPromptValue(messages=[
+ # SystemMessage(content="You are a helpful assistant."),
+ # HumanMessage(content="what's 5 + 2"),
+ # AIMessage(content="5 + 2 is 7"),
+ # HumanMessage(content="now multiply that by 4"),
+ # ])
+ ```
+
+ !!! example "Limiting the number of messages"
+
+ ```python
+ from langchain_core.prompts import MessagesPlaceholder
+
+ prompt = MessagesPlaceholder("history", n_messages=1)
+
+ prompt.format_messages(
+ history=[
+ ("system", "You are an AI assistant."),
+ ("human", "Hello!"),
+ ]
+ )
+ # -> [
+ # HumanMessage(content="Hello!"),
+ # ]
+ ```
+ """
+
+ variable_name: str
+ """Name of variable to use as messages."""
+
+ optional: bool = False
+ """Whether `format_messages` must be provided.
+
+ If `True` `format_messages` can be called with no arguments and will return an empty
+ list.
+
+ If `False` then a named argument with name `variable_name` must be passed in, even
+ if the value is an empty list.
+ """
+
+ n_messages: PositiveInt | None = None
+ """Maximum number of messages to include.
+
+ If `None`, then will include all.
+ """
+
+ def __init__(
+ self, variable_name: str, *, optional: bool = False, **kwargs: Any
+ ) -> None:
+ """Create a messages placeholder.
+
+ Args:
+ variable_name: Name of variable to use as messages.
+ optional: Whether `format_messages` must be provided.
+
+ If `True` format_messages can be called with no arguments and will
+ return an empty list.
+
+ If `False` then a named argument with name `variable_name` must be
+ passed in, even if the value is an empty list.
+ """
+ # mypy can't detect the init which is defined in the parent class
+ # b/c these are BaseModel classes.
+ super().__init__(variable_name=variable_name, optional=optional, **kwargs) # type: ignore[call-arg,unused-ignore]
+
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format messages from kwargs.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+
+ Raises:
+ ValueError: If variable is not a list of messages.
+ """
+ value = (
+ kwargs.get(self.variable_name, [])
+ if self.optional
+ else kwargs[self.variable_name]
+ )
+ if not isinstance(value, list):
+ msg = (
+ f"variable {self.variable_name} should be a list of base messages, "
+ f"got {value} of type {type(value)}"
+ )
+ raise ValueError(msg) # noqa: TRY004
+ value = convert_to_messages(value)
+ if self.n_messages:
+ value = value[-self.n_messages :]
+ return value
+
+ @property
+ def input_variables(self) -> list[str]:
+ """Input variables for this prompt template.
+
+ Returns:
+ List of input variable names.
+ """
+ return [self.variable_name] if not self.optional else []
+
+ @override
+ def pretty_repr(self, html: bool = False) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ var = "{" + self.variable_name + "}"
+ if html:
+ title = get_msg_title_repr("Messages Placeholder", bold=True)
+ var = get_colored_text(var, "yellow")
+ else:
+ title = get_msg_title_repr("Messages Placeholder")
+ return f"{title}\n\n{var}"
+
+
+MessagePromptTemplateT = TypeVar(
+ "MessagePromptTemplateT", bound="BaseStringMessagePromptTemplate"
+)
+"""Type variable for message prompt templates."""
+
+
+class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
+ """Base class for message prompt templates that use a string prompt template."""
+
+ prompt: StringPromptTemplate
+ """String prompt template."""
+
+ additional_kwargs: dict = Field(default_factory=dict)
+ """Additional keyword arguments to pass to the prompt template."""
+
+ @classmethod
+ def from_template(
+ cls,
+ template: str,
+ template_format: PromptTemplateFormat = "f-string",
+ partial_variables: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Self:
+ """Create a class from a string template.
+
+ Args:
+ template: a template.
+ template_format: format of the template.
+ partial_variables: A dictionary of variables that can be used to partially
+ fill in the template.
+
+ For example, if the template is `"{variable1} {variable2}"`, and
+ `partial_variables` is `{"variable1": "foo"}`, then the final prompt
+ will be `"foo {variable2}"`.
+
+ **kwargs: Keyword arguments to pass to the constructor.
+
+ Returns:
+ A new instance of this class.
+ """
+ prompt = PromptTemplate.from_template(
+ template,
+ template_format=template_format,
+ partial_variables=partial_variables,
+ )
+ return cls(prompt=prompt, **kwargs)
+
+ @classmethod
+ def from_template_file(
+ cls,
+ template_file: str | Path,
+ **kwargs: Any,
+ ) -> Self:
+ """Create a class from a template file.
+
+ Args:
+ template_file: path to a template file.
+ **kwargs: Keyword arguments to pass to the constructor.
+
+ Returns:
+ A new instance of this class.
+ """
+ prompt = PromptTemplate.from_file(template_file)
+ return cls(prompt=prompt, **kwargs)
+
+ @abstractmethod
+ def format(self, **kwargs: Any) -> BaseMessage:
+ """Format the prompt template.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ Formatted message.
+ """
+
+ async def aformat(self, **kwargs: Any) -> BaseMessage:
+ """Async format the prompt template.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ Formatted message.
+ """
+ return self.format(**kwargs)
+
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format messages from kwargs.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+ return [self.format(**kwargs)]
+
+ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Async format messages from kwargs.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+ return [await self.aformat(**kwargs)]
+
+ @property
+ def input_variables(self) -> list[str]:
+ """Input variables for this prompt template.
+
+ Returns:
+ List of input variable names.
+ """
+ return self.prompt.input_variables
+
+ @override
+ def pretty_repr(self, html: bool = False) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ # TODO: Handle partials
+ title = self.__class__.__name__.replace("MessagePromptTemplate", " Message")
+ title = get_msg_title_repr(title, bold=html)
+ return f"{title}\n\n{self.prompt.pretty_repr(html=html)}"
+
+
+class ChatMessagePromptTemplate(BaseStringMessagePromptTemplate):
+ """Chat message prompt template."""
+
+ role: str
+ """Role of the message."""
+
+ def format(self, **kwargs: Any) -> BaseMessage:
+ """Format the prompt template.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ Formatted message.
+ """
+ text = self.prompt.format(**kwargs)
+ return ChatMessage(
+ content=text, role=self.role, additional_kwargs=self.additional_kwargs
+ )
+
+ async def aformat(self, **kwargs: Any) -> BaseMessage:
+ """Async format the prompt template.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ Formatted message.
+ """
+ text = await self.prompt.aformat(**kwargs)
+ return ChatMessage(
+ content=text, role=self.role, additional_kwargs=self.additional_kwargs
+ )
+
+
+class _TextTemplateParam(TypedDict, total=False):
+ text: str | dict
+
+
+class _ImageTemplateParam(TypedDict, total=False):
+ image_url: str | dict
+
+
+class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
+ """Human message prompt template. This is a message sent from the user."""
+
+ prompt: (
+ StringPromptTemplate
+ | list[StringPromptTemplate | ImagePromptTemplate | DictPromptTemplate]
+ )
+ """Prompt template."""
+ additional_kwargs: dict = Field(default_factory=dict)
+ """Additional keyword arguments to pass to the prompt template."""
+
+ _msg_class: type[BaseMessage]
+
+ @classmethod
+ def from_template(
+ cls: type[Self],
+ template: str
+ | list[str | _TextTemplateParam | _ImageTemplateParam | dict[str, Any]],
+ template_format: PromptTemplateFormat = "f-string",
+ *,
+ partial_variables: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Self:
+ """Create a class from a string template.
+
+ Args:
+ template: a template.
+ template_format: format of the template.
+
+ Options are: `'f-string'`, `'mustache'`, `'jinja2'`.
+ partial_variables: A dictionary of variables that can be used too partially.
+
+ **kwargs: Keyword arguments to pass to the constructor.
+
+ Returns:
+ A new instance of this class.
+
+ Raises:
+ ValueError: If the template is not a string or list of strings.
+ """
+ if isinstance(template, str):
+ prompt: StringPromptTemplate | list = PromptTemplate.from_template(
+ template,
+ template_format=template_format,
+ partial_variables=partial_variables,
+ )
+ return cls(prompt=prompt, **kwargs)
+ if isinstance(template, list):
+ if (partial_variables is not None) and len(partial_variables) > 0:
+ msg = "Partial variables are not supported for list of templates."
+ raise ValueError(msg)
+ prompt = []
+ for tmpl in template:
+ if isinstance(tmpl, str) or (
+ isinstance(tmpl, dict)
+ and "text" in tmpl
+ and set(tmpl.keys()) <= {"type", "text"}
+ ):
+ if isinstance(tmpl, str):
+ text: str = tmpl
+ else:
+ text = cast("_TextTemplateParam", tmpl)["text"] # type: ignore[assignment]
+ prompt.append(
+ PromptTemplate.from_template(
+ text, template_format=template_format
+ )
+ )
+ elif (
+ isinstance(tmpl, dict)
+ and "image_url" in tmpl
+ and set(tmpl.keys())
+ <= {
+ "type",
+ "image_url",
+ }
+ ):
+ img_template = cast("_ImageTemplateParam", tmpl)["image_url"]
+ input_variables = []
+ if isinstance(img_template, str):
+ variables = get_template_variables(
+ img_template, template_format
+ )
+ if variables:
+ if len(variables) > 1:
+ msg = (
+ "Only one format variable allowed per image"
+ f" template.\nGot: {variables}"
+ f"\nFrom: {tmpl}"
+ )
+ raise ValueError(msg)
+ input_variables = [variables[0]]
+ img_template = {"url": img_template}
+ img_template_obj = ImagePromptTemplate(
+ input_variables=input_variables,
+ template=img_template,
+ template_format=template_format,
+ )
+ elif isinstance(img_template, dict):
+ img_template = dict(img_template)
+ for key in ["url", "path", "detail"]:
+ if key in img_template:
+ input_variables.extend(
+ get_template_variables(
+ img_template[key], template_format
+ )
+ )
+ img_template_obj = ImagePromptTemplate(
+ input_variables=input_variables,
+ template=img_template,
+ template_format=template_format,
+ )
+ else:
+ msg = f"Invalid image template: {tmpl}"
+ raise ValueError(msg)
+ prompt.append(img_template_obj)
+ elif isinstance(tmpl, dict):
+ if template_format == "jinja2":
+ msg = (
+ "jinja2 is unsafe and is not supported for templates "
+ "expressed as dicts. Please use 'f-string' or 'mustache' "
+ "format."
+ )
+ raise ValueError(msg)
+ data_template_obj = DictPromptTemplate(
+ template=cast("dict[str, Any]", tmpl),
+ template_format=template_format,
+ )
+ prompt.append(data_template_obj)
+ else:
+ msg = f"Invalid template: {tmpl}"
+ raise ValueError(msg)
+ return cls(prompt=prompt, **kwargs)
+ msg = f"Invalid template: {template}"
+ raise ValueError(msg)
+
+ @classmethod
+ def from_template_file(
+ cls: type[Self],
+ template_file: str | Path,
+ input_variables: list[str],
+ **kwargs: Any,
+ ) -> Self:
+ """Create a class from a template file.
+
+ Args:
+ template_file: path to a template file.
+ input_variables: list of input variables.
+ **kwargs: Keyword arguments to pass to the constructor.
+
+ Returns:
+ A new instance of this class.
+ """
+ template = Path(template_file).read_text(encoding="utf-8")
+ return cls.from_template(template, input_variables=input_variables, **kwargs)
+
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format messages from kwargs.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+ return [self.format(**kwargs)]
+
+ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Async format messages from kwargs.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+ return [await self.aformat(**kwargs)]
+
+ @property
+ def input_variables(self) -> list[str]:
+ """Input variables for this prompt template.
+
+ Returns:
+ List of input variable names.
+ """
+ prompts = self.prompt if isinstance(self.prompt, list) else [self.prompt]
+ return [iv for prompt in prompts for iv in prompt.input_variables]
+
+ def format(self, **kwargs: Any) -> BaseMessage:
+ """Format the prompt template.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ Formatted message.
+ """
+ if isinstance(self.prompt, StringPromptTemplate):
+ text = self.prompt.format(**kwargs)
+ return self._msg_class(
+ content=text, additional_kwargs=self.additional_kwargs
+ )
+ content: list = []
+ for prompt in self.prompt:
+ inputs = {var: kwargs[var] for var in prompt.input_variables}
+ if isinstance(prompt, StringPromptTemplate):
+ formatted_text: str = prompt.format(**inputs)
+ if formatted_text != "":
+ content.append({"type": "text", "text": formatted_text})
+ elif isinstance(prompt, ImagePromptTemplate):
+ formatted_image: ImageURL = prompt.format(**inputs)
+ content.append({"type": "image_url", "image_url": formatted_image})
+ elif isinstance(prompt, DictPromptTemplate):
+ formatted_dict: dict[str, Any] = prompt.format(**inputs)
+ content.append(formatted_dict)
+ return self._msg_class(
+ content=content, additional_kwargs=self.additional_kwargs
+ )
+
+ async def aformat(self, **kwargs: Any) -> BaseMessage:
+ """Async format the prompt template.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ Formatted message.
+ """
+ if isinstance(self.prompt, StringPromptTemplate):
+ text = await self.prompt.aformat(**kwargs)
+ return self._msg_class(
+ content=text, additional_kwargs=self.additional_kwargs
+ )
+ content: list = []
+ for prompt in self.prompt:
+ inputs = {var: kwargs[var] for var in prompt.input_variables}
+ if isinstance(prompt, StringPromptTemplate):
+ formatted_text: str = await prompt.aformat(**inputs)
+ if formatted_text != "":
+ content.append({"type": "text", "text": formatted_text})
+ elif isinstance(prompt, ImagePromptTemplate):
+ formatted_image: ImageURL = await prompt.aformat(**inputs)
+ content.append({"type": "image_url", "image_url": formatted_image})
+ elif isinstance(prompt, DictPromptTemplate):
+ formatted_dict: dict[str, Any] = prompt.format(**inputs)
+ content.append(formatted_dict)
+ return self._msg_class(
+ content=content, additional_kwargs=self.additional_kwargs
+ )
+
+ @override
+ def pretty_repr(self, html: bool = False) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ # TODO: Handle partials
+ title = self.__class__.__name__.replace("MessagePromptTemplate", " Message")
+ title = get_msg_title_repr(title, bold=html)
+ prompts = self.prompt if isinstance(self.prompt, list) else [self.prompt]
+ prompt_reprs = "\n\n".join(prompt.pretty_repr(html=html) for prompt in prompts)
+ return f"{title}\n\n{prompt_reprs}"
+
+
+class HumanMessagePromptTemplate(_StringImageMessagePromptTemplate):
+ """Human message prompt template.
+
+ This is a message sent from the user.
+ """
+
+ _msg_class: type[BaseMessage] = HumanMessage
+
+
+class AIMessagePromptTemplate(_StringImageMessagePromptTemplate):
+ """AI message prompt template.
+
+ This is a message sent from the AI.
+ """
+
+ _msg_class: type[BaseMessage] = AIMessage
+
+
+class SystemMessagePromptTemplate(_StringImageMessagePromptTemplate):
+ """System message prompt template.
+
+ This is a message that is not sent to the user.
+ """
+
+ _msg_class: type[BaseMessage] = SystemMessage
+
+
+class BaseChatPromptTemplate(BasePromptTemplate, ABC):
+ """Base class for chat prompt templates."""
+
+ @property
+ @override
+ def lc_attributes(self) -> dict:
+ return {"input_variables": self.input_variables}
+
+ def format(self, **kwargs: Any) -> str:
+ """Format the chat template into a string.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in template variables in all
+ the template messages in this chat template.
+
+ Returns:
+ Formatted string.
+ """
+ return self.format_prompt(**kwargs).to_string()
+
+ async def aformat(self, **kwargs: Any) -> str:
+ """Async format the chat template into a string.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in template variables in all
+ the template messages in this chat template.
+
+ Returns:
+ Formatted string.
+ """
+ return (await self.aformat_prompt(**kwargs)).to_string()
+
+ def format_prompt(self, **kwargs: Any) -> ChatPromptValue:
+ """Format prompt.
+
+ Should return a `ChatPromptValue`.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+ """
+ messages = self.format_messages(**kwargs)
+ return ChatPromptValue(messages=messages)
+
+ async def aformat_prompt(self, **kwargs: Any) -> ChatPromptValue:
+ """Async format prompt.
+
+ Should return a `ChatPromptValue`.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+ """
+ messages = await self.aformat_messages(**kwargs)
+ return ChatPromptValue(messages=messages)
+
+ @abstractmethod
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format kwargs into a list of messages.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+
+ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Async format kwargs into a list of messages.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+ return self.format_messages(**kwargs)
+
+ def pretty_repr(
+ self,
+ html: bool = False, # noqa: FBT001,FBT002
+ ) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ raise NotImplementedError
+
+ def pretty_print(self) -> None:
+ """Print a human-readable representation."""
+ print(self.pretty_repr(html=is_interactive_env())) # noqa: T201
+
+
+MessageLike = BaseMessagePromptTemplate | BaseMessage | BaseChatPromptTemplate
+
+MessageLikeRepresentation = (
+ MessageLike
+ | tuple[str | type, str | Sequence[dict] | Sequence[object]]
+ | str
+ | dict[str, Any]
+)
+
+
+class ChatPromptTemplate(BaseChatPromptTemplate):
+ """Prompt template for chat models.
+
+ Use to create flexible templated prompts for chat models.
+
+ !!! example
+
+ ```python
+ from langchain_core.prompts import ChatPromptTemplate
+
+ template = ChatPromptTemplate(
+ [
+ ("system", "You are a helpful AI bot. Your name is {name}."),
+ ("human", "Hello, how are you doing?"),
+ ("ai", "I'm doing well, thanks!"),
+ ("human", "{user_input}"),
+ ]
+ )
+
+ prompt_value = template.invoke(
+ {
+ "name": "Bob",
+ "user_input": "What is your name?",
+ }
+ )
+ # Output:
+ # ChatPromptValue(
+ # messages=[
+ # SystemMessage(content='You are a helpful AI bot. Your name is Bob.'),
+ # HumanMessage(content='Hello, how are you doing?'),
+ # AIMessage(content="I'm doing well, thanks!"),
+ # HumanMessage(content='What is your name?')
+ # ]
+ # )
+ ```
+
+ !!! note "Messages Placeholder"
+
+ ```python
+ # In addition to Human/AI/Tool/Function messages,
+ # you can initialize the template with a MessagesPlaceholder
+ # either using the class directly or with the shorthand tuple syntax:
+
+ template = ChatPromptTemplate(
+ [
+ ("system", "You are a helpful AI bot."),
+ # Means the template will receive an optional list of messages under
+ # the "conversation" key
+ ("placeholder", "{conversation}"),
+ # Equivalently:
+ # MessagesPlaceholder(variable_name="conversation", optional=True)
+ ]
+ )
+
+ prompt_value = template.invoke(
+ {
+ "conversation": [
+ ("human", "Hi!"),
+ ("ai", "How can I assist you today?"),
+ ("human", "Can you make me an ice cream sundae?"),
+ ("ai", "No."),
+ ]
+ }
+ )
+
+ # Output:
+ # ChatPromptValue(
+ # messages=[
+ # SystemMessage(content='You are a helpful AI bot.'),
+ # HumanMessage(content='Hi!'),
+ # AIMessage(content='How can I assist you today?'),
+ # HumanMessage(content='Can you make me an ice cream sundae?'),
+ # AIMessage(content='No.'),
+ # ]
+ # )
+ ```
+
+ !!! note "Single-variable template"
+
+ If your prompt has only a single input variable (i.e., one instance of
+ `'{variable_nams}'`), and you invoke the template with a non-dict object, the
+ prompt template will inject the provided argument into that variable location.
+
+ ```python
+ from langchain_core.prompts import ChatPromptTemplate
+
+ template = ChatPromptTemplate(
+ [
+ ("system", "You are a helpful AI bot. Your name is Carl."),
+ ("human", "{user_input}"),
+ ]
+ )
+
+ prompt_value = template.invoke("Hello, there!")
+ # Equivalent to
+ # prompt_value = template.invoke({"user_input": "Hello, there!"})
+
+ # Output:
+ # ChatPromptValue(
+ # messages=[
+ # SystemMessage(content='You are a helpful AI bot. Your name is Carl.'),
+ # HumanMessage(content='Hello, there!'),
+ # ]
+ # )
+ ```
+ """
+
+ messages: Annotated[list[MessageLike], SkipValidation()]
+ """List of messages consisting of either message prompt templates or messages."""
+
+ validate_template: bool = False
+ """Whether or not to try validating the template."""
+
+ def __init__(
+ self,
+ messages: Sequence[MessageLikeRepresentation],
+ *,
+ template_format: PromptTemplateFormat = "f-string",
+ **kwargs: Any,
+ ) -> None:
+ """Create a chat prompt template from a variety of message formats.
+
+ Args:
+ messages: Sequence of message representations.
+
+ A message can be represented using the following formats:
+
+ 1. `BaseMessagePromptTemplate`
+ 2. `BaseMessage`
+ 3. 2-tuple of `(message type, template)`; e.g.,
+ `('human', '{user_input}')`
+ 4. 2-tuple of `(message class, template)`
+ 5. A string which is shorthand for `('human', template)`; e.g.,
+ `'{user_input}'`
+ template_format: Format of the template.
+ **kwargs: Additional keyword arguments passed to `BasePromptTemplate`,
+ including (but not limited to):
+
+ - `input_variables`: A list of the names of the variables whose values
+ are required as inputs to the prompt.
+ - `optional_variables`: A list of the names of the variables for
+ placeholder or `MessagePlaceholder` that are optional.
+
+ These variables are auto inferred from the prompt and user need not
+ provide them.
+
+ - `partial_variables`: A dictionary of the partial variables the prompt
+ template carries.
+
+ Partial variables populate the template so that you don't need to
+ pass them in every time you call the prompt.
+
+ - `validate_template`: Whether to validate the template.
+ - `input_types`: A dictionary of the types of the variables the prompt
+ template expects.
+
+ If not provided, all variables are assumed to be strings.
+
+ Examples:
+ Instantiation from a list of message templates:
+
+ ```python
+ template = ChatPromptTemplate(
+ [
+ ("human", "Hello, how are you?"),
+ ("ai", "I'm doing well, thanks!"),
+ ("human", "That's good to hear."),
+ ]
+ )
+ ```
+
+ Instantiation from mixed message formats:
+
+ ```python
+ template = ChatPromptTemplate(
+ [
+ SystemMessage(content="hello"),
+ ("human", "Hello, how are you?"),
+ ]
+ )
+ ```
+ """
+ messages_ = [
+ _convert_to_message_template(message, template_format)
+ for message in messages
+ ]
+
+ # Automatically infer input variables from messages
+ input_vars: set[str] = set()
+ optional_variables: set[str] = set()
+ partial_vars: dict[str, Any] = {}
+ for message in messages_:
+ if isinstance(message, MessagesPlaceholder) and message.optional:
+ partial_vars[message.variable_name] = []
+ optional_variables.add(message.variable_name)
+ elif isinstance(
+ message, (BaseChatPromptTemplate, BaseMessagePromptTemplate)
+ ):
+ input_vars.update(message.input_variables)
+
+ kwargs = {
+ "input_variables": sorted(input_vars),
+ "optional_variables": sorted(optional_variables),
+ "partial_variables": partial_vars,
+ **kwargs,
+ }
+ cast("type[ChatPromptTemplate]", super()).__init__(messages=messages_, **kwargs)
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "prompts", "chat"]`
+ """
+ return ["langchain", "prompts", "chat"]
+
+ def __add__(self, other: Any) -> ChatPromptTemplate:
+ """Combine two prompt templates.
+
+ Args:
+ other: Another prompt template.
+
+ Returns:
+ Combined prompt template.
+ """
+ partials = {**self.partial_variables}
+
+ # Need to check that other has partial variables since it may not be
+ # a ChatPromptTemplate.
+ if hasattr(other, "partial_variables") and other.partial_variables:
+ partials.update(other.partial_variables)
+
+ # Allow for easy combining
+ if isinstance(other, ChatPromptTemplate):
+ return ChatPromptTemplate(messages=self.messages + other.messages).partial(
+ **partials
+ )
+ if isinstance(
+ other, (BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate)
+ ):
+ return ChatPromptTemplate(messages=[*self.messages, other]).partial(
+ **partials
+ )
+ if isinstance(other, (list, tuple)):
+ other_ = ChatPromptTemplate.from_messages(other)
+ return ChatPromptTemplate(messages=self.messages + other_.messages).partial(
+ **partials
+ )
+ if isinstance(other, str):
+ prompt = HumanMessagePromptTemplate.from_template(other)
+ return ChatPromptTemplate(messages=[*self.messages, prompt]).partial(
+ **partials
+ )
+ msg = f"Unsupported operand type for +: {type(other)}"
+ raise NotImplementedError(msg)
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_input_variables(cls, values: dict) -> Any:
+ """Validate input variables.
+
+ If `input_variables` is not set, it will be set to the union of all input
+ variables in the messages.
+
+ Args:
+ values: values to validate.
+
+ Returns:
+ Validated values.
+
+ Raises:
+ ValueError: If input variables do not match.
+ """
+ messages = values["messages"]
+ input_vars: set = set()
+ optional_variables = set()
+ input_types: dict[str, Any] = values.get("input_types", {})
+ for message in messages:
+ if isinstance(message, (BaseMessagePromptTemplate, BaseChatPromptTemplate)):
+ input_vars.update(message.input_variables)
+ if isinstance(message, MessagesPlaceholder):
+ if "partial_variables" not in values:
+ values["partial_variables"] = {}
+ if (
+ message.optional
+ and message.variable_name not in values["partial_variables"]
+ ):
+ values["partial_variables"][message.variable_name] = []
+ optional_variables.add(message.variable_name)
+ if message.variable_name not in input_types:
+ input_types[message.variable_name] = list[AnyMessage]
+ if "partial_variables" in values:
+ input_vars -= set(values["partial_variables"])
+ if optional_variables:
+ input_vars -= optional_variables
+ if "input_variables" in values and values.get("validate_template"):
+ if input_vars != set(values["input_variables"]):
+ msg = (
+ "Got mismatched input_variables. "
+ f"Expected: {input_vars}. "
+ f"Got: {values['input_variables']}"
+ )
+ raise ValueError(msg)
+ else:
+ values["input_variables"] = sorted(input_vars)
+ if optional_variables:
+ values["optional_variables"] = sorted(optional_variables)
+ values["input_types"] = input_types
+ return values
+
+ @classmethod
+ def from_template(cls, template: str, **kwargs: Any) -> ChatPromptTemplate:
+ """Create a chat prompt template from a template string.
+
+ Creates a chat template consisting of a single message assumed to be from the
+ human.
+
+ Args:
+ template: Template string
+ **kwargs: Keyword arguments to pass to the constructor.
+
+ Returns:
+ A new instance of this class.
+ """
+ prompt_template = PromptTemplate.from_template(template, **kwargs)
+ message = HumanMessagePromptTemplate(prompt=prompt_template)
+ return cls.from_messages([message])
+
+ @classmethod
+ def from_messages(
+ cls,
+ messages: Sequence[MessageLikeRepresentation],
+ template_format: PromptTemplateFormat = "f-string",
+ ) -> ChatPromptTemplate:
+ """Create a chat prompt template from a variety of message formats.
+
+ Examples:
+ Instantiation from a list of message templates:
+
+ ```python
+ template = ChatPromptTemplate.from_messages(
+ [
+ ("human", "Hello, how are you?"),
+ ("ai", "I'm doing well, thanks!"),
+ ("human", "That's good to hear."),
+ ]
+ )
+ ```
+
+ Instantiation from mixed message formats:
+
+ ```python
+ template = ChatPromptTemplate.from_messages(
+ [
+ SystemMessage(content="hello"),
+ ("human", "Hello, how are you?"),
+ ]
+ )
+ ```
+ Args:
+ messages: Sequence of message representations.
+
+ A message can be represented using the following formats:
+
+ 1. `BaseMessagePromptTemplate`
+ 2. `BaseMessage`
+ 3. 2-tuple of `(message type, template)`; e.g.,
+ `('human', '{user_input}')`
+ 4. 2-tuple of `(message class, template)`
+ 5. A string which is shorthand for `('human', template)`; e.g.,
+ `'{user_input}'`
+ template_format: Format of the template.
+
+ Returns:
+ A chat prompt template.
+
+ """
+ return cls(messages, template_format=template_format)
+
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format the chat template into a list of finalized messages.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in template variables
+ in all the template messages in this chat template.
+
+ Raises:
+ ValueError: If messages are of unexpected types.
+
+ Returns:
+ List of formatted messages.
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ result = []
+ for message_template in self.messages:
+ if isinstance(message_template, BaseMessage):
+ result.extend([message_template])
+ elif isinstance(
+ message_template, (BaseMessagePromptTemplate, BaseChatPromptTemplate)
+ ):
+ message = message_template.format_messages(**kwargs)
+ result.extend(message)
+ else:
+ msg = f"Unexpected input: {message_template}"
+ raise ValueError(msg) # noqa: TRY004
+ return result
+
+ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Async format the chat template into a list of finalized messages.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in template variables
+ in all the template messages in this chat template.
+
+ Returns:
+ List of formatted messages.
+
+ Raises:
+ ValueError: If unexpected input.
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ result = []
+ for message_template in self.messages:
+ if isinstance(message_template, BaseMessage):
+ result.extend([message_template])
+ elif isinstance(
+ message_template, (BaseMessagePromptTemplate, BaseChatPromptTemplate)
+ ):
+ message = await message_template.aformat_messages(**kwargs)
+ result.extend(message)
+ else:
+ msg = f"Unexpected input: {message_template}"
+ raise ValueError(msg) # noqa:TRY004
+ return result
+
+ def partial(self, **kwargs: Any) -> ChatPromptTemplate:
+ """Get a new `ChatPromptTemplate` with some input variables already filled in.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in template variables.
+
+ Ought to be a subset of the input variables.
+
+ Returns:
+ A new `ChatPromptTemplate`.
+
+ Example:
+ ```python
+ from langchain_core.prompts import ChatPromptTemplate
+
+ template = ChatPromptTemplate.from_messages(
+ [
+ ("system", "You are an AI assistant named {name}."),
+ ("human", "Hi I'm {user}"),
+ ("ai", "Hi there, {user}, I'm {name}."),
+ ("human", "{input}"),
+ ]
+ )
+ template2 = template.partial(user="Lucy", name="R2D2")
+
+ template2.format_messages(input="hello")
+ ```
+ """
+ prompt_dict = self.__dict__.copy()
+ prompt_dict["input_variables"] = list(
+ set(self.input_variables).difference(kwargs)
+ )
+ prompt_dict["partial_variables"] = {**self.partial_variables, **kwargs}
+ return type(self)(**prompt_dict)
+
+ def append(self, message: MessageLikeRepresentation) -> None:
+ """Append a message to the end of the chat template.
+
+ Args:
+ message: representation of a message to append.
+ """
+ self.messages.append(_convert_to_message_template(message))
+
+ def extend(self, messages: Sequence[MessageLikeRepresentation]) -> None:
+ """Extend the chat template with a sequence of messages.
+
+ Args:
+ messages: Sequence of message representations to append.
+ """
+ self.messages.extend(
+ [_convert_to_message_template(message) for message in messages]
+ )
+
+ @overload
+ def __getitem__(self, index: int) -> MessageLike: ...
+
+ @overload
+ def __getitem__(self, index: slice) -> ChatPromptTemplate: ...
+
+ def __getitem__(self, index: int | slice) -> MessageLike | ChatPromptTemplate:
+ """Use to index into the chat template.
+
+ Returns:
+ If index is an int, returns the message at that index.
+
+ If index is a slice, returns a new `ChatPromptTemplate` containing the
+ messages in that slice.
+ """
+ if isinstance(index, slice):
+ start, stop, step = index.indices(len(self.messages))
+ messages = self.messages[start:stop:step]
+ return ChatPromptTemplate.from_messages(messages)
+ return self.messages[index]
+
+ def __len__(self) -> int:
+ """Return the length of the chat template."""
+ return len(self.messages)
+
+ @property
+ def _prompt_type(self) -> str:
+ """Name of prompt type. Used for serialization."""
+ return "chat"
+
+ @deprecated(
+ since="1.2.21",
+ removal="2.0.0",
+ alternative="Use `dumpd`/`dumps` from `langchain_core.load` to serialize "
+ "prompts and `load`/`loads` to deserialize them.",
+ )
+ def save(self, file_path: Path | str) -> None:
+ """Save prompt to file.
+
+ Args:
+ file_path: path to file.
+ """
+ raise NotImplementedError
+
+ @override
+ def pretty_repr(self, html: bool = False) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ # TODO: handle partials
+ return "\n\n".join(msg.pretty_repr(html=html) for msg in self.messages)
+
+
+def _create_template_from_message_type(
+ message_type: str,
+ template: str | list,
+ template_format: PromptTemplateFormat = "f-string",
+) -> BaseMessagePromptTemplate:
+ """Create a message prompt template from a message type and template string.
+
+ Args:
+ message_type: The type of the message template (e.g., `'human'`, `'ai'`, etc.)
+ template: The template string.
+ template_format: Format of the template.
+
+ Returns:
+ A message prompt template of the appropriate type.
+
+ Raises:
+ ValueError: If unexpected message type.
+ """
+ if message_type in {"human", "user"}:
+ message: BaseMessagePromptTemplate = HumanMessagePromptTemplate.from_template(
+ template, template_format=template_format
+ )
+ elif message_type in {"ai", "assistant"}:
+ message = AIMessagePromptTemplate.from_template(
+ cast("str", template), template_format=template_format
+ )
+ elif message_type == "system":
+ message = SystemMessagePromptTemplate.from_template(
+ cast("str", template), template_format=template_format
+ )
+ elif message_type == "placeholder":
+ if isinstance(template, str):
+ if template[0] != "{" or template[-1] != "}":
+ msg = (
+ f"Invalid placeholder template: {template}."
+ " Expected a variable name surrounded by curly braces."
+ )
+ raise ValueError(msg)
+ var_name = template[1:-1]
+ message = MessagesPlaceholder(variable_name=var_name, optional=True)
+ else:
+ try:
+ var_name_wrapped, is_optional = template
+ except ValueError as e:
+ msg = (
+ "Unexpected arguments for placeholder message type."
+ " Expected either a single string variable name"
+ " or a list of [variable_name: str, is_optional: bool]."
+ f" Got: {template}"
+ )
+ raise ValueError(msg) from e
+
+ if not isinstance(is_optional, bool):
+ msg = f"Expected is_optional to be a boolean. Got: {is_optional}"
+ raise ValueError(msg) # noqa: TRY004
+
+ if not isinstance(var_name_wrapped, str):
+ msg = f"Expected variable name to be a string. Got: {var_name_wrapped}"
+ raise ValueError(msg) # noqa: TRY004
+ if var_name_wrapped[0] != "{" or var_name_wrapped[-1] != "}":
+ msg = (
+ f"Invalid placeholder template: {var_name_wrapped}."
+ " Expected a variable name surrounded by curly braces."
+ )
+ raise ValueError(msg)
+ var_name = var_name_wrapped[1:-1]
+
+ message = MessagesPlaceholder(variable_name=var_name, optional=is_optional)
+ else:
+ msg = (
+ f"Unexpected message type: {message_type}. Use one of 'human',"
+ f" 'user', 'ai', 'assistant', or 'system'."
+ )
+ raise ValueError(msg)
+ return message
+
+
+def _convert_to_message_template(
+ message: MessageLikeRepresentation,
+ template_format: PromptTemplateFormat = "f-string",
+) -> BaseMessage | BaseMessagePromptTemplate | BaseChatPromptTemplate:
+ """Instantiate a message from a variety of message formats.
+
+ A message can be represented using the following formats:
+
+ 1. `BaseMessagePromptTemplate`
+ 2. `BaseMessage`
+ 3. 2-tuple of `(message type, template)`; e.g., `('human', '{user_input}')`
+ 4. 2-tuple of `(message class, template)`
+ 5. A string which is shorthand for `('human', template)`; e.g., `'{user_input}'`
+
+ Args:
+ message: A representation of a message in one of the supported formats.
+ template_format: Format of the template.
+
+ Returns:
+ An instance of a message or a message template.
+
+ Raises:
+ ValueError: If unexpected message type.
+ ValueError: If 2-tuple does not have 2 elements.
+ """
+ if isinstance(message, (BaseMessagePromptTemplate, BaseChatPromptTemplate)):
+ message_: BaseMessage | BaseMessagePromptTemplate | BaseChatPromptTemplate = (
+ message
+ )
+ elif isinstance(message, BaseMessage):
+ message_ = message
+ elif isinstance(message, str):
+ message_ = _create_template_from_message_type(
+ "human", message, template_format=template_format
+ )
+ elif isinstance(message, (tuple, dict)):
+ if isinstance(message, dict):
+ if set(message.keys()) != {"content", "role"}:
+ msg = (
+ "Expected dict to have exact keys 'role' and 'content'."
+ f" Got: {message}"
+ )
+ raise ValueError(msg)
+ message_type_str = message["role"]
+ template = message["content"]
+ else:
+ if len(message) != 2: # noqa: PLR2004
+ msg = f"Expected 2-tuple of (role, template), got {message}"
+ raise ValueError(msg)
+ message_type_str, template = message
+
+ if isinstance(message_type_str, str):
+ message_ = _create_template_from_message_type(
+ message_type_str, template, template_format=template_format
+ )
+ elif (
+ hasattr(message_type_str, "model_fields")
+ and "type" in message_type_str.model_fields
+ ):
+ message_type = message_type_str.model_fields["type"].default
+ message_ = _create_template_from_message_type(
+ message_type, template, template_format=template_format
+ )
+ else:
+ message_ = message_type_str(
+ prompt=PromptTemplate.from_template(
+ cast("str", template), template_format=template_format
+ )
+ )
+ else:
+ msg = f"Unsupported message type: {type(message)}"
+ raise NotImplementedError(msg)
+
+ return message_
+
+
+# For backwards compat:
+_convert_to_message = _convert_to_message_template
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/dict.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/dict.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a665bfbb836f9c467bdd48f61e1f80ad1169cc0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/dict.py
@@ -0,0 +1,175 @@
+"""Dictionary prompt template."""
+
+import warnings
+from functools import cached_property
+from typing import Any, Literal, cast
+
+from pydantic import model_validator
+from typing_extensions import override
+
+from langchain_core.load import dumpd
+from langchain_core.prompts.string import (
+ DEFAULT_FORMATTER_MAPPING,
+ get_template_variables,
+)
+from langchain_core.runnables import RunnableConfig, RunnableSerializable
+from langchain_core.runnables.config import ensure_config
+
+
+class DictPromptTemplate(RunnableSerializable[dict, dict]):
+ """Template represented by a dictionary.
+
+ Recognizes variables in f-string or mustache formatted string dict values.
+
+ Does NOT recognize variables in dict keys. Applies recursively.
+
+ Example:
+ ```python
+ prompt = DictPromptTemplate(
+ template={
+ "type": "text",
+ "text": "Hello {name}",
+ "metadata": {"source": "{source}"},
+ },
+ template_format="f-string",
+ )
+ prompt.format(name="Alice", source="docs")
+ # {
+ # "type": "text",
+ # "text": "Hello Alice",
+ # "metadata": {"source": "docs"},
+ # }
+ ```
+ """
+
+ template: dict[str, Any]
+ template_format: Literal["f-string", "mustache"]
+
+ @model_validator(mode="after")
+ def validate_template(self) -> "DictPromptTemplate":
+ """Validate that the template structure contains only safe variables."""
+ _get_input_variables(self.template, self.template_format)
+ return self
+
+ @property
+ def input_variables(self) -> list[str]:
+ """Template input variables."""
+ return _get_input_variables(self.template, self.template_format)
+
+ def format(self, **kwargs: Any) -> dict[str, Any]:
+ """Format the prompt with the inputs.
+
+ Returns:
+ A formatted dict.
+ """
+ return _insert_input_variables(self.template, kwargs, self.template_format)
+
+ async def aformat(self, **kwargs: Any) -> dict[str, Any]:
+ """Format the prompt with the inputs.
+
+ Returns:
+ A formatted dict.
+ """
+ return self.format(**kwargs)
+
+ @override
+ def invoke(
+ self, input: dict, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> dict:
+ return self._call_with_config(
+ lambda x: self.format(**x),
+ input,
+ ensure_config(config),
+ run_type="prompt",
+ serialized=self._serialized,
+ **kwargs,
+ )
+
+ @property
+ def _prompt_type(self) -> str:
+ return "dict-prompt"
+
+ @cached_property
+ def _serialized(self) -> dict[str, Any]:
+ # self is always a Serializable object in this case, thus the result is
+ # guaranteed to be a dict since dumpd uses the default callback, which uses
+ # obj.to_json which always returns TypedDict subclasses
+ return cast("dict[str, Any]", dumpd(self))
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain_core", "prompts", "dict"]`
+ """
+ return ["langchain_core", "prompts", "dict"]
+
+ def pretty_repr(self, *, html: bool = False) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ raise NotImplementedError
+
+
+def _get_input_variables(
+ template: dict, template_format: Literal["f-string", "mustache"]
+) -> list[str]:
+ input_variables = []
+ for v in template.values():
+ if isinstance(v, str):
+ input_variables += get_template_variables(v, template_format)
+ elif isinstance(v, dict):
+ input_variables += _get_input_variables(v, template_format)
+ elif isinstance(v, (list, tuple)):
+ for x in v:
+ if isinstance(x, str):
+ input_variables += get_template_variables(x, template_format)
+ elif isinstance(x, dict):
+ input_variables += _get_input_variables(x, template_format)
+ return list(set(input_variables))
+
+
+def _insert_input_variables(
+ template: dict[str, Any],
+ inputs: dict[str, Any],
+ template_format: Literal["f-string", "mustache"],
+) -> dict[str, Any]:
+ formatted: dict[str, Any] = {}
+ formatter = DEFAULT_FORMATTER_MAPPING[template_format]
+ for k, v in template.items():
+ if isinstance(v, str):
+ formatted[k] = formatter(v, **inputs)
+ elif isinstance(v, dict):
+ if k == "image_url" and "path" in v:
+ msg = (
+ "Specifying image inputs via file path in environments with "
+ "user-input paths is a security vulnerability. Out of an abundance "
+ "of caution, the utility has been removed to prevent possible "
+ "misuse."
+ )
+ warnings.warn(msg, stacklevel=2)
+ formatted[k] = _insert_input_variables(v, inputs, template_format)
+ elif isinstance(v, (list, tuple)):
+ formatted_v: list[str | dict[str, Any]] = []
+ for x in v:
+ if isinstance(x, str):
+ formatted_v.append(formatter(x, **inputs))
+ elif isinstance(x, dict):
+ formatted_v.append(
+ _insert_input_variables(x, inputs, template_format)
+ )
+ formatted[k] = type(v)(formatted_v)
+ else:
+ formatted[k] = v
+ return formatted
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/few_shot.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/few_shot.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e8e9aa3159664a896741d48d6ee9001cf2c51c7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/few_shot.py
@@ -0,0 +1,483 @@
+"""Prompt template that contains few shot examples."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Literal
+
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ model_validator,
+)
+from typing_extensions import override
+
+from langchain_core._api import deprecated
+from langchain_core.example_selectors import BaseExampleSelector
+from langchain_core.messages import BaseMessage, get_buffer_string
+from langchain_core.prompts.chat import BaseChatPromptTemplate
+from langchain_core.prompts.message import BaseMessagePromptTemplate
+from langchain_core.prompts.prompt import PromptTemplate
+from langchain_core.prompts.string import (
+ DEFAULT_FORMATTER_MAPPING,
+ StringPromptTemplate,
+ check_valid_template,
+ get_template_variables,
+)
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from typing_extensions import Self
+
+
+class _FewShotPromptTemplateMixin(BaseModel):
+ """Prompt template that contains few shot examples."""
+
+ examples: list[dict] | None = None
+ """Examples to format into the prompt.
+
+ Either this or `example_selector` should be provided.
+ """
+
+ example_selector: BaseExampleSelector | None = None
+ """`ExampleSelector` to choose the examples to format into the prompt.
+
+ Either this or `examples` should be provided.
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def check_examples_and_selector(cls, values: dict) -> Any:
+ """Check that one and only one of `examples`/`example_selector` are provided.
+
+ Args:
+ values: The values to check.
+
+ Returns:
+ The values if they are valid.
+
+ Raises:
+ ValueError: If neither or both `examples` and `example_selector` are
+ provided.
+ ValueError: If both `examples` and `example_selector` are provided.
+ """
+ examples = values.get("examples")
+ example_selector = values.get("example_selector")
+ if examples and example_selector:
+ msg = "Only one of 'examples' and 'example_selector' should be provided"
+ raise ValueError(msg)
+
+ if examples is None and example_selector is None:
+ msg = "One of 'examples' and 'example_selector' should be provided"
+ raise ValueError(msg)
+
+ return values
+
+ def _get_examples(self, **kwargs: Any) -> list[dict]:
+ """Get the examples to use for formatting the prompt.
+
+ Args:
+ **kwargs: Keyword arguments to be passed to the example selector.
+
+ Returns:
+ List of examples.
+
+ Raises:
+ ValueError: If neither `examples` nor `example_selector` are provided.
+ """
+ if self.examples is not None:
+ return self.examples
+ if self.example_selector is not None:
+ return self.example_selector.select_examples(kwargs)
+ msg = "One of 'examples' and 'example_selector' should be provided"
+ raise ValueError(msg)
+
+ async def _aget_examples(self, **kwargs: Any) -> list[dict]:
+ """Async get the examples to use for formatting the prompt.
+
+ Args:
+ **kwargs: Keyword arguments to be passed to the example selector.
+
+ Returns:
+ List of examples.
+
+ Raises:
+ ValueError: If neither `examples` nor `example_selector` are provided.
+ """
+ if self.examples is not None:
+ return self.examples
+ if self.example_selector is not None:
+ return await self.example_selector.aselect_examples(kwargs)
+ msg = "One of 'examples' and 'example_selector' should be provided"
+ raise ValueError(msg)
+
+
+class FewShotPromptTemplate(_FewShotPromptTemplateMixin, StringPromptTemplate):
+ """Prompt template that contains few shot examples."""
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `False` as this class is not serializable."""
+ return False
+
+ validate_template: bool = False
+ """Whether or not to try validating the template."""
+
+ example_prompt: PromptTemplate
+ """`PromptTemplate` used to format an individual example."""
+
+ suffix: str
+ """A prompt template string to put after the examples."""
+
+ example_separator: str = "\n\n"
+ """String separator used to join the prefix, the examples, and suffix."""
+
+ prefix: str = ""
+ """A prompt template string to put before the examples."""
+
+ template_format: Literal["f-string", "jinja2"] = "f-string"
+ """The format of the prompt template.
+
+ Options are: `'f-string'`, `'jinja2'`.
+ """
+
+ def __init__(self, **kwargs: Any) -> None:
+ """Initialize the few shot prompt template."""
+ if "input_variables" not in kwargs and "example_prompt" in kwargs:
+ kwargs["input_variables"] = kwargs["example_prompt"].input_variables
+ super().__init__(**kwargs)
+
+ @model_validator(mode="after")
+ def template_is_valid(self) -> Self:
+ """Check that prefix, suffix, and input variables are consistent."""
+ if self.validate_template:
+ check_valid_template(
+ self.prefix + self.suffix,
+ self.template_format,
+ self.input_variables + list(self.partial_variables),
+ )
+ elif self.template_format:
+ self.input_variables = [
+ var
+ for var in get_template_variables(
+ self.prefix + self.suffix, self.template_format
+ )
+ if var not in self.partial_variables
+ ]
+ return self
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ def format(self, **kwargs: Any) -> str:
+ """Format the prompt with inputs generating a string.
+
+ Use this method to generate a string representation of a prompt.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ A string representation of the prompt.
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ # Get the examples to use.
+ examples = self._get_examples(**kwargs)
+ examples = [
+ {k: e[k] for k in self.example_prompt.input_variables} for e in examples
+ ]
+ # Format the examples.
+ example_strings = [
+ self.example_prompt.format(**example) for example in examples
+ ]
+ # Create the overall template.
+ pieces = [self.prefix, *example_strings, self.suffix]
+ template = self.example_separator.join([piece for piece in pieces if piece])
+
+ # Format the template with the input variables.
+ return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)
+
+ async def aformat(self, **kwargs: Any) -> str:
+ """Async format the prompt with inputs generating a string.
+
+ Use this method to generate a string representation of a prompt.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ A string representation of the prompt.
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ # Get the examples to use.
+ examples = await self._aget_examples(**kwargs)
+ examples = [
+ {k: e[k] for k in self.example_prompt.input_variables} for e in examples
+ ]
+ # Format the examples.
+ example_strings = [
+ await self.example_prompt.aformat(**example) for example in examples
+ ]
+ # Create the overall template.
+ pieces = [self.prefix, *example_strings, self.suffix]
+ template = self.example_separator.join([piece for piece in pieces if piece])
+
+ # Format the template with the input variables.
+ return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)
+
+ @property
+ def _prompt_type(self) -> str:
+ """Return the prompt type key."""
+ return "few_shot"
+
+ @deprecated(
+ since="1.2.21",
+ removal="2.0.0",
+ alternative="Use `dumpd`/`dumps` from `langchain_core.load` to serialize "
+ "prompts and `load`/`loads` to deserialize them.",
+ )
+ def save(self, file_path: Path | str) -> None:
+ """Save the prompt template to a file.
+
+ Args:
+ file_path: The path to save the prompt template to.
+
+ Raises:
+ ValueError: If `example_selector` is provided.
+ """
+ if self.example_selector:
+ msg = "Saving an example selector is not currently supported"
+ raise ValueError(msg)
+ return super().save(file_path)
+
+
+class FewShotChatMessagePromptTemplate(
+ BaseChatPromptTemplate, _FewShotPromptTemplateMixin
+):
+ """Chat prompt template that supports few-shot examples.
+
+ The high level structure of produced by this prompt template is a list of messages
+ consisting of prefix message(s), example message(s), and suffix message(s).
+
+ This structure enables creating a conversation with intermediate examples like:
+
+ ```txt
+ System: You are a helpful AI Assistant
+
+ Human: What is 2+2?
+
+ AI: 4
+
+ Human: What is 2+3?
+
+ AI: 5
+
+ Human: What is 4+4?
+ ```
+
+ This prompt template can be used to generate a fixed list of examples or else to
+ dynamically select examples based on the input.
+
+ Examples:
+ Prompt template with a fixed list of examples (matching the sample
+ conversation above):
+
+ ```python
+ from langchain_core.prompts import (
+ FewShotChatMessagePromptTemplate,
+ ChatPromptTemplate,
+ )
+
+ examples = [
+ {"input": "2+2", "output": "4"},
+ {"input": "2+3", "output": "5"},
+ ]
+
+ example_prompt = ChatPromptTemplate.from_messages(
+ [
+ ("human", "What is {input}?"),
+ ("ai", "{output}"),
+ ]
+ )
+
+ few_shot_prompt = FewShotChatMessagePromptTemplate(
+ examples=examples,
+ # This is a prompt template used to format each individual example.
+ example_prompt=example_prompt,
+ )
+
+ final_prompt = ChatPromptTemplate.from_messages(
+ [
+ ("system", "You are a helpful AI Assistant"),
+ few_shot_prompt,
+ ("human", "{input}"),
+ ]
+ )
+ final_prompt.format(input="What is 4+4?")
+ ```
+
+ Prompt template with dynamically selected examples:
+
+ ```python
+ from langchain_core.prompts import SemanticSimilarityExampleSelector
+ from langchain_core.embeddings import OpenAIEmbeddings
+ from langchain_core.vectorstores import Chroma
+
+ examples = [
+ {"input": "2+2", "output": "4"},
+ {"input": "2+3", "output": "5"},
+ {"input": "2+4", "output": "6"},
+ # ...
+ ]
+
+ to_vectorize = [" ".join(example.values()) for example in examples]
+ embeddings = OpenAIEmbeddings()
+ vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)
+ example_selector = SemanticSimilarityExampleSelector(vectorstore=vectorstore)
+
+ from langchain_core import SystemMessage
+ from langchain_core.prompts import HumanMessagePromptTemplate
+ from langchain_core.prompts.few_shot import FewShotChatMessagePromptTemplate
+
+ few_shot_prompt = FewShotChatMessagePromptTemplate(
+ # Which variable(s) will be passed to the example selector.
+ input_variables=["input"],
+ example_selector=example_selector,
+ # Define how each example will be formatted.
+ # In this case, each example will become 2 messages:
+ # 1 human, and 1 AI
+ example_prompt=(
+ HumanMessagePromptTemplate.from_template("{input}")
+ + AIMessagePromptTemplate.from_template("{output}")
+ ),
+ )
+ # Define the overall prompt.
+ final_prompt = (
+ SystemMessagePromptTemplate.from_template("You are a helpful AI Assistant")
+ + few_shot_prompt
+ + HumanMessagePromptTemplate.from_template("{input}")
+ )
+ # Show the prompt
+ print(final_prompt.format_messages(input="What's 3+3?")) # noqa: T201
+
+ # Use within an LLM
+ from langchain_core.chat_models import ChatAnthropic
+
+ chain = final_prompt | ChatAnthropic(model="claude-3-haiku-20240307")
+ chain.invoke({"input": "What's 3+3?"})
+ ```
+ """
+
+ input_variables: list[str] = Field(default_factory=list)
+ """A list of the names of the variables the prompt template will use to pass to
+ the `example_selector`, if provided.
+ """
+
+ example_prompt: BaseMessagePromptTemplate | BaseChatPromptTemplate
+ """The class to format each example."""
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `False` as this class is not serializable."""
+ return False
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format kwargs into a list of messages.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in templates in messages.
+
+ Returns:
+ A list of formatted messages with all template variables filled in.
+ """
+ # Get the examples to use.
+ examples = self._get_examples(**kwargs)
+ examples = [
+ {k: e[k] for k in self.example_prompt.input_variables} for e in examples
+ ]
+ # Format the examples.
+ return [
+ message
+ for example in examples
+ for message in self.example_prompt.format_messages(**example)
+ ]
+
+ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Async format kwargs into a list of messages.
+
+ Args:
+ **kwargs: Keyword arguments to use for filling in templates in messages.
+
+ Returns:
+ A list of formatted messages with all template variables filled in.
+ """
+ # Get the examples to use.
+ examples = await self._aget_examples(**kwargs)
+ examples = [
+ {k: e[k] for k in self.example_prompt.input_variables} for e in examples
+ ]
+ # Format the examples.
+ return [
+ message
+ for example in examples
+ for message in await self.example_prompt.aformat_messages(**example)
+ ]
+
+ def format(self, **kwargs: Any) -> str:
+ """Format the prompt with inputs generating a string.
+
+ Use this method to generate a string representation of a prompt consisting of
+ chat messages.
+
+ Useful for feeding into a string-based completion language model or debugging.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ A string representation of the prompt
+ """
+ messages = self.format_messages(**kwargs)
+ return get_buffer_string(messages)
+
+ async def aformat(self, **kwargs: Any) -> str:
+ """Async format the prompt with inputs generating a string.
+
+ Use this method to generate a string representation of a prompt consisting of
+ chat messages.
+
+ Useful for feeding into a string-based completion language model or debugging.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ A string representation of the prompt
+ """
+ messages = await self.aformat_messages(**kwargs)
+ return get_buffer_string(messages)
+
+ @override
+ def pretty_repr(self, html: bool = False) -> str:
+ """Return a pretty representation of the prompt template.
+
+ Args:
+ html: Whether or not to return an HTML formatted string.
+
+ Returns:
+ A pretty representation of the prompt template.
+ """
+ raise NotImplementedError
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/few_shot_with_templates.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/few_shot_with_templates.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca664cabee789a910e45d61eb6f8f96c17f7dad7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/few_shot_with_templates.py
@@ -0,0 +1,237 @@
+"""Prompt template that contains few shot examples."""
+
+from pathlib import Path
+from typing import Any
+
+from pydantic import ConfigDict, model_validator
+from typing_extensions import Self
+
+from langchain_core._api import deprecated
+from langchain_core.example_selectors import BaseExampleSelector
+from langchain_core.prompts.prompt import PromptTemplate
+from langchain_core.prompts.string import (
+ DEFAULT_FORMATTER_MAPPING,
+ PromptTemplateFormat,
+ StringPromptTemplate,
+)
+
+
+class FewShotPromptWithTemplates(StringPromptTemplate):
+ """Prompt template that contains few shot examples."""
+
+ examples: list[dict] | None = None
+ """Examples to format into the prompt.
+
+ Either this or `example_selector` should be provided.
+ """
+
+ example_selector: BaseExampleSelector | None = None
+ """`ExampleSelector` to choose the examples to format into the prompt.
+
+ Either this or `examples` should be provided.
+ """
+
+ example_prompt: PromptTemplate
+ """`PromptTemplate` used to format an individual example."""
+
+ suffix: StringPromptTemplate
+ """A `PromptTemplate` to put after the examples."""
+
+ example_separator: str = "\n\n"
+ """String separator used to join the prefix, the examples, and suffix."""
+
+ prefix: StringPromptTemplate | None = None
+ """A `PromptTemplate` to put before the examples."""
+
+ template_format: PromptTemplateFormat = "f-string"
+ """The format of the prompt template.
+
+ Options are: `'f-string'`, `'jinja2'`, `'mustache'`.
+ """
+
+ validate_template: bool = False
+ """Whether or not to try validating the template."""
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "prompts", "few_shot_with_templates"]`
+ """
+ return ["langchain", "prompts", "few_shot_with_templates"]
+
+ @model_validator(mode="before")
+ @classmethod
+ def check_examples_and_selector(cls, values: dict) -> Any:
+ """Check that one and only one of examples/example_selector are provided."""
+ examples = values.get("examples")
+ example_selector = values.get("example_selector")
+ if examples and example_selector:
+ msg = "Only one of 'examples' and 'example_selector' should be provided"
+ raise ValueError(msg)
+
+ if examples is None and example_selector is None:
+ msg = "One of 'examples' and 'example_selector' should be provided"
+ raise ValueError(msg)
+
+ return values
+
+ @model_validator(mode="after")
+ def template_is_valid(self) -> Self:
+ """Check that prefix, suffix, and input variables are consistent."""
+ if self.validate_template:
+ input_variables = self.input_variables
+ expected_input_variables = set(self.suffix.input_variables)
+ expected_input_variables |= set(self.partial_variables)
+ if self.prefix is not None:
+ expected_input_variables |= set(self.prefix.input_variables)
+ missing_vars = expected_input_variables.difference(input_variables)
+ if missing_vars:
+ msg = (
+ f"Got input_variables={input_variables}, but based on "
+ f"prefix/suffix expected {expected_input_variables}"
+ )
+ raise ValueError(msg)
+ else:
+ self.input_variables = sorted(
+ set(self.suffix.input_variables)
+ | set(self.prefix.input_variables if self.prefix else [])
+ - set(self.partial_variables)
+ )
+ return self
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra="forbid",
+ )
+
+ def _get_examples(self, **kwargs: Any) -> list[dict]:
+ if self.examples is not None:
+ return self.examples
+ if self.example_selector is not None:
+ return self.example_selector.select_examples(kwargs)
+ raise ValueError
+
+ async def _aget_examples(self, **kwargs: Any) -> list[dict]:
+ if self.examples is not None:
+ return self.examples
+ if self.example_selector is not None:
+ return await self.example_selector.aselect_examples(kwargs)
+ raise ValueError
+
+ def format(self, **kwargs: Any) -> str:
+ """Format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+
+ Example:
+ ```python
+ prompt.format(variable1="foo")
+ ```
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ # Get the examples to use.
+ examples = self._get_examples(**kwargs)
+ # Format the examples.
+ example_strings = [
+ self.example_prompt.format(**example) for example in examples
+ ]
+ # Create the overall prefix.
+ if self.prefix is None:
+ prefix = ""
+ else:
+ prefix_kwargs = {
+ k: v for k, v in kwargs.items() if k in self.prefix.input_variables
+ }
+ for k in prefix_kwargs:
+ kwargs.pop(k)
+ prefix = self.prefix.format(**prefix_kwargs)
+
+ # Create the overall suffix
+ suffix_kwargs = {
+ k: v for k, v in kwargs.items() if k in self.suffix.input_variables
+ }
+ for k in suffix_kwargs:
+ kwargs.pop(k)
+ suffix = self.suffix.format(
+ **suffix_kwargs,
+ )
+
+ pieces = [prefix, *example_strings, suffix]
+ template = self.example_separator.join([piece for piece in pieces if piece])
+ # Format the template with the input variables.
+ return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)
+
+ async def aformat(self, **kwargs: Any) -> str:
+ """Async format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ # Get the examples to use.
+ examples = await self._aget_examples(**kwargs)
+ # Format the examples.
+ example_strings = [
+ # We can use the sync method here as PromptTemplate doesn't block
+ self.example_prompt.format(**example)
+ for example in examples
+ ]
+ # Create the overall prefix.
+ if self.prefix is None:
+ prefix = ""
+ else:
+ prefix_kwargs = {
+ k: v for k, v in kwargs.items() if k in self.prefix.input_variables
+ }
+ for k in prefix_kwargs:
+ kwargs.pop(k)
+ prefix = await self.prefix.aformat(**prefix_kwargs)
+
+ # Create the overall suffix
+ suffix_kwargs = {
+ k: v for k, v in kwargs.items() if k in self.suffix.input_variables
+ }
+ for k in suffix_kwargs:
+ kwargs.pop(k)
+ suffix = await self.suffix.aformat(
+ **suffix_kwargs,
+ )
+
+ pieces = [prefix, *example_strings, suffix]
+ template = self.example_separator.join([piece for piece in pieces if piece])
+ # Format the template with the input variables.
+ return DEFAULT_FORMATTER_MAPPING[self.template_format](template, **kwargs)
+
+ @property
+ def _prompt_type(self) -> str:
+ """Return the prompt type key."""
+ return "few_shot_with_templates"
+
+ @deprecated(
+ since="1.2.21",
+ removal="2.0.0",
+ alternative="Use `dumpd`/`dumps` from `langchain_core.load` to serialize "
+ "prompts and `load`/`loads` to deserialize them.",
+ )
+ def save(self, file_path: Path | str) -> None:
+ """Save the prompt to a file.
+
+ Args:
+ file_path: The path to save the prompt to.
+
+ Raises:
+ ValueError: If `example_selector` is provided.
+ """
+ if self.example_selector:
+ msg = "Saving an example selector is not currently supported"
+ raise ValueError(msg)
+ return super().save(file_path)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/image.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/image.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee8c9421f2a641db54692a7085ad37a9cdd0d75f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/image.py
@@ -0,0 +1,177 @@
+"""Image prompt template for a multimodal model."""
+
+from typing import Any, Literal, cast
+
+from pydantic import Field
+
+from langchain_core.prompt_values import ImagePromptValue, ImageURL, PromptValue
+from langchain_core.prompts.base import BasePromptTemplate
+from langchain_core.prompts.string import (
+ DEFAULT_FORMATTER_MAPPING,
+ PromptTemplateFormat,
+ get_template_variables,
+)
+from langchain_core.runnables import run_in_executor
+
+
+class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
+ """Image prompt template for a multimodal model.
+
+ Example:
+ ```python
+ prompt = ImagePromptTemplate(
+ input_variables=["image_id"],
+ template={"url": "https://example.com/{image_id}.png", "detail": "high"},
+ template_format="f-string",
+ )
+ prompt.format(image_id="cat")
+ # {"url": "https://example.com/cat.png", "detail": "high"}
+ ```
+ """
+
+ template: dict = Field(default_factory=dict)
+ """Template for the prompt."""
+
+ template_format: PromptTemplateFormat = "f-string"
+ """The format of the prompt template.
+
+ Options are: `'f-string'`, `'mustache'`, `'jinja2'`.
+ """
+
+ def __init__(self, **kwargs: Any) -> None:
+ """Create an image prompt template.
+
+ Raises:
+ ValueError: If the input variables contain `'url'`, `'path'`, or
+ `'detail'`.
+ """
+ if "input_variables" not in kwargs:
+ kwargs["input_variables"] = []
+
+ overlap = set(kwargs["input_variables"]) & {"url", "path", "detail"}
+ if overlap:
+ msg = (
+ "input_variables for the image template cannot contain"
+ " any of 'url', 'path', or 'detail'."
+ f" Found: {overlap}"
+ )
+ raise ValueError(msg)
+
+ template = kwargs.get("template", {})
+ template_format = kwargs.get("template_format", "f-string")
+ for value in template.values():
+ if isinstance(value, str):
+ get_template_variables(value, template_format)
+
+ super().__init__(**kwargs)
+
+ @property
+ def _prompt_type(self) -> str:
+ """Return the prompt type key."""
+ return "image-prompt"
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "prompts", "image"]`
+ """
+ return ["langchain", "prompts", "image"]
+
+ def format_prompt(self, **kwargs: Any) -> PromptValue:
+ """Format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ return ImagePromptValue(image_url=self.format(**kwargs))
+
+ async def aformat_prompt(self, **kwargs: Any) -> PromptValue:
+ """Async format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ return ImagePromptValue(image_url=await self.aformat(**kwargs))
+
+ def format(
+ self,
+ **kwargs: Any,
+ ) -> ImageURL:
+ """Format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+
+ Raises:
+ ValueError: If the url is not provided.
+ ValueError: If the url is not a string.
+ ValueError: If `'path'` is provided in the template or kwargs.
+
+ Example:
+ ```python
+ prompt.format(variable1="foo")
+ ```
+ """
+ formatted = {}
+ for k, v in self.template.items():
+ if isinstance(v, str):
+ formatted[k] = DEFAULT_FORMATTER_MAPPING[self.template_format](
+ v, **kwargs
+ )
+ else:
+ formatted[k] = v
+ url = kwargs.get("url") or formatted.get("url")
+ if kwargs.get("path") or formatted.get("path"):
+ msg = (
+ "Loading images from 'path' has been removed as of 0.3.15 for security "
+ "reasons. Please specify images by 'url'."
+ )
+ raise ValueError(msg)
+ detail = kwargs.get("detail") or formatted.get("detail")
+ if not url:
+ msg = "Must provide url."
+ raise ValueError(msg)
+ if not isinstance(url, str):
+ msg = "url must be a string."
+ raise ValueError(msg) # noqa: TRY004
+ output: ImageURL = {"url": url}
+ if detail:
+ # Don't check literal values here: let the API check them
+ output["detail"] = cast("Literal['auto', 'low', 'high']", detail)
+ return output
+
+ async def aformat(self, **kwargs: Any) -> ImageURL:
+ """Async format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ return await run_in_executor(None, self.format, **kwargs)
+
+ def pretty_repr(
+ self,
+ html: bool = False, # noqa: FBT001,FBT002
+ ) -> str:
+ """Return a pretty representation of the prompt.
+
+ Args:
+ html: Whether to return an html formatted string.
+
+ Returns:
+ A pretty representation of the prompt.
+ """
+ raise NotImplementedError
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/loading.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/loading.py
new file mode 100644
index 0000000000000000000000000000000000000000..d130f9d8714041409d72ea5fc3385229bf34ab91
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/loading.py
@@ -0,0 +1,289 @@
+"""Load prompts."""
+
+import json
+import logging
+from collections.abc import Callable
+from pathlib import Path
+
+import yaml
+
+from langchain_core._api import deprecated
+from langchain_core.output_parsers.string import StrOutputParser
+from langchain_core.prompts.base import BasePromptTemplate
+from langchain_core.prompts.chat import ChatPromptTemplate
+from langchain_core.prompts.few_shot import FewShotPromptTemplate
+from langchain_core.prompts.prompt import PromptTemplate
+
+URL_BASE = "https://raw.githubusercontent.com/hwchase17/langchain-hub/master/prompts/"
+logger = logging.getLogger(__name__)
+
+
+def _validate_path(path: Path) -> None:
+ """Reject absolute paths and ``..`` traversal components.
+
+ Args:
+ path: The path to validate.
+
+ Raises:
+ ValueError: If the path is absolute or contains ``..`` components.
+ """
+ if path.is_absolute():
+ msg = (
+ f"Path '{path}' is absolute. Absolute paths are not allowed "
+ f"when loading prompt configurations to prevent path traversal "
+ f"attacks. Use relative paths instead, or pass "
+ f"`allow_dangerous_paths=True` if you trust the input."
+ )
+ raise ValueError(msg)
+ if ".." in path.parts:
+ msg = (
+ f"Path '{path}' contains '..' components. Directory traversal "
+ f"sequences are not allowed when loading prompt configurations. "
+ f"Use direct relative paths instead, or pass "
+ f"`allow_dangerous_paths=True` if you trust the input."
+ )
+ raise ValueError(msg)
+
+
+@deprecated(
+ since="1.2.21",
+ removal="2.0.0",
+ alternative="Use `dumpd`/`dumps` from `langchain_core.load` to serialize "
+ "prompts and `load`/`loads` to deserialize them.",
+)
+def load_prompt_from_config(
+ config: dict, *, allow_dangerous_paths: bool = False
+) -> BasePromptTemplate:
+ """Load prompt from config dict.
+
+ Args:
+ config: Dict containing the prompt configuration.
+ allow_dangerous_paths: If ``False`` (default), file paths in the
+ config (such as ``template_path``, ``examples``, and
+ ``example_prompt_path``) are validated to reject absolute paths
+ and directory traversal (``..``) sequences. Set to ``True`` only
+ if you trust the source of the config.
+
+ Returns:
+ A `PromptTemplate` object.
+
+ Raises:
+ ValueError: If the prompt type is not supported.
+ """
+ if "_type" not in config:
+ logger.warning("No `_type` key found, defaulting to `prompt`.")
+ config_type = config.pop("_type", "prompt")
+
+ if config_type not in type_to_loader_dict:
+ msg = f"Loading {config_type} prompt not supported"
+ raise ValueError(msg)
+
+ prompt_loader = type_to_loader_dict[config_type]
+ return prompt_loader(config, allow_dangerous_paths=allow_dangerous_paths)
+
+
+def _load_template(
+ var_name: str, config: dict, *, allow_dangerous_paths: bool = False
+) -> dict:
+ """Load template from the path if applicable."""
+ # Check if template_path exists in config.
+ if f"{var_name}_path" in config:
+ # If it does, make sure template variable doesn't also exist.
+ if var_name in config:
+ msg = f"Both `{var_name}_path` and `{var_name}` cannot be provided."
+ raise ValueError(msg)
+ # Pop the template path from the config.
+ template_path = Path(config.pop(f"{var_name}_path"))
+ if not allow_dangerous_paths:
+ _validate_path(template_path)
+ # Resolve symlinks before checking the suffix so that a symlink named
+ # "exploit.txt" pointing to a non-.txt file is caught.
+ resolved_path = template_path.resolve()
+ # Load the template.
+ if resolved_path.suffix == ".txt":
+ template = resolved_path.read_text(encoding="utf-8")
+ else:
+ raise ValueError
+ # Set the template variable to the extracted variable.
+ config[var_name] = template
+ return config
+
+
+def _load_examples(config: dict, *, allow_dangerous_paths: bool = False) -> dict:
+ """Load examples if necessary."""
+ if isinstance(config["examples"], list):
+ pass
+ elif isinstance(config["examples"], str):
+ path = Path(config["examples"])
+ if not allow_dangerous_paths:
+ _validate_path(path)
+ with path.open(encoding="utf-8") as f:
+ if path.suffix == ".json":
+ examples = json.load(f)
+ elif path.suffix in {".yaml", ".yml"}:
+ examples = yaml.safe_load(f)
+ else:
+ msg = "Invalid file format. Only json or yaml formats are supported."
+ raise ValueError(msg)
+ config["examples"] = examples
+ else:
+ msg = "Invalid examples format. Only list or string are supported."
+ raise ValueError(msg) # noqa:TRY004
+ return config
+
+
+def _load_output_parser(config: dict) -> dict:
+ """Load output parser."""
+ if config_ := config.get("output_parser"):
+ if output_parser_type := config_.get("_type") != "default":
+ msg = f"Unsupported output parser {output_parser_type}"
+ raise ValueError(msg)
+ config["output_parser"] = StrOutputParser(**config_)
+ return config
+
+
+def _load_few_shot_prompt(
+ config: dict, *, allow_dangerous_paths: bool = False
+) -> FewShotPromptTemplate:
+ """Load the "few shot" prompt from the config."""
+ # Load the suffix and prefix templates.
+ config = _load_template(
+ "suffix", config, allow_dangerous_paths=allow_dangerous_paths
+ )
+ config = _load_template(
+ "prefix", config, allow_dangerous_paths=allow_dangerous_paths
+ )
+ # Load the example prompt.
+ if "example_prompt_path" in config:
+ if "example_prompt" in config:
+ msg = (
+ "Only one of example_prompt and example_prompt_path should "
+ "be specified."
+ )
+ raise ValueError(msg)
+ example_prompt_path = Path(config.pop("example_prompt_path"))
+ if not allow_dangerous_paths:
+ _validate_path(example_prompt_path)
+ config["example_prompt"] = load_prompt(
+ example_prompt_path, allow_dangerous_paths=allow_dangerous_paths
+ )
+ else:
+ config["example_prompt"] = load_prompt_from_config(
+ config["example_prompt"], allow_dangerous_paths=allow_dangerous_paths
+ )
+ # Load the examples.
+ config = _load_examples(config, allow_dangerous_paths=allow_dangerous_paths)
+ config = _load_output_parser(config)
+ return FewShotPromptTemplate(**config)
+
+
+def _load_prompt(
+ config: dict, *, allow_dangerous_paths: bool = False
+) -> PromptTemplate:
+ """Load the prompt template from config."""
+ # Load the template from disk if necessary.
+ config = _load_template(
+ "template", config, allow_dangerous_paths=allow_dangerous_paths
+ )
+ config = _load_output_parser(config)
+
+ template_format = config.get("template_format", "f-string")
+ if template_format == "jinja2":
+ # Disabled due to:
+ # https://github.com/langchain-ai/langchain/issues/4394
+ msg = (
+ f"Loading templates with '{template_format}' format is no longer supported "
+ f"since it can lead to arbitrary code execution. Please migrate to using "
+ f"the 'f-string' template format, which does not suffer from this issue."
+ )
+ raise ValueError(msg)
+
+ return PromptTemplate(**config)
+
+
+@deprecated(
+ since="1.2.21",
+ removal="2.0.0",
+ alternative="Use `dumpd`/`dumps` from `langchain_core.load` to serialize "
+ "prompts and `load`/`loads` to deserialize them.",
+)
+def load_prompt(
+ path: str | Path,
+ encoding: str | None = None,
+ *,
+ allow_dangerous_paths: bool = False,
+) -> BasePromptTemplate:
+ """Unified method for loading a prompt from LangChainHub or local filesystem.
+
+ Args:
+ path: Path to the prompt file.
+ encoding: Encoding of the file.
+ allow_dangerous_paths: If ``False`` (default), file paths referenced
+ inside the loaded config (such as ``template_path``, ``examples``,
+ and ``example_prompt_path``) are validated to reject absolute paths
+ and directory traversal (``..``) sequences. Set to ``True`` only
+ if you trust the source of the config.
+
+ Returns:
+ A `PromptTemplate` object.
+
+ Raises:
+ RuntimeError: If the path is a LangChainHub path.
+ """
+ if isinstance(path, str) and path.startswith("lc://"):
+ msg = (
+ "Loading from the deprecated github-based Hub is no longer supported. "
+ "Please use the new LangChain Hub at https://smith.langchain.com/hub "
+ "instead."
+ )
+ raise RuntimeError(msg)
+ return _load_prompt_from_file(
+ path, encoding, allow_dangerous_paths=allow_dangerous_paths
+ )
+
+
+def _load_prompt_from_file(
+ file: str | Path,
+ encoding: str | None = None,
+ *,
+ allow_dangerous_paths: bool = False,
+) -> BasePromptTemplate:
+ """Load prompt from file."""
+ # Convert file to a Path object.
+ file_path = Path(file)
+ # Load from either json or yaml.
+ if file_path.suffix == ".json":
+ with file_path.open(encoding=encoding) as f:
+ config = json.load(f)
+ elif file_path.suffix.endswith((".yaml", ".yml")):
+ with file_path.open(encoding=encoding) as f:
+ config = yaml.safe_load(f)
+ else:
+ msg = f"Got unsupported file type {file_path.suffix}"
+ raise ValueError(msg)
+ # Load the prompt from the config now.
+ return load_prompt_from_config(config, allow_dangerous_paths=allow_dangerous_paths)
+
+
+def _load_chat_prompt(
+ config: dict,
+ *,
+ allow_dangerous_paths: bool = False, # noqa: ARG001
+) -> ChatPromptTemplate:
+ """Load chat prompt from config."""
+ messages = config.pop("messages")
+ template = messages[0]["prompt"].pop("template") if messages else None
+ config.pop("input_variables")
+
+ if not template:
+ msg = "Can't load chat prompt without template"
+ raise ValueError(msg)
+
+ return ChatPromptTemplate.from_template(template=template, **config)
+
+
+type_to_loader_dict: dict[str, Callable[..., BasePromptTemplate]] = {
+ "prompt": _load_prompt,
+ "few_shot": _load_few_shot_prompt,
+ "chat": _load_chat_prompt,
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/message.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/message.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce20a4930183769996d9422f743992ee7da6c4b9
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/message.py
@@ -0,0 +1,97 @@
+"""Message prompt templates."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any
+
+from langchain_core.load import Serializable
+from langchain_core.utils.interactive_env import is_interactive_env
+
+if TYPE_CHECKING:
+ from langchain_core.messages import BaseMessage
+ from langchain_core.prompts.chat import ChatPromptTemplate
+
+
+class BaseMessagePromptTemplate(Serializable, ABC):
+ """Base class for message prompt templates."""
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "prompts", "chat"]`
+ """
+ return ["langchain", "prompts", "chat"]
+
+ @abstractmethod
+ def format_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Format messages from kwargs.
+
+ Should return a list of `BaseMessage` objects.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+
+ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]:
+ """Async format messages from kwargs.
+
+ Args:
+ **kwargs: Keyword arguments to use for formatting.
+
+ Returns:
+ List of `BaseMessage` objects.
+ """
+ return self.format_messages(**kwargs)
+
+ @property
+ @abstractmethod
+ def input_variables(self) -> list[str]:
+ """Input variables for this prompt template.
+
+ Returns:
+ List of input variables.
+ """
+
+ def pretty_repr(
+ self,
+ html: bool = False, # noqa: FBT001,FBT002
+ ) -> str:
+ """Human-readable representation.
+
+ Args:
+ html: Whether to format as HTML.
+
+ Returns:
+ Human-readable representation.
+ """
+ raise NotImplementedError
+
+ def pretty_print(self) -> None:
+ """Print a human-readable representation."""
+ print(self.pretty_repr(html=is_interactive_env())) # noqa: T201
+
+ def __add__(self, other: Any) -> ChatPromptTemplate:
+ """Combine two prompt templates.
+
+ Args:
+ other: Another prompt template.
+
+ Returns:
+ Combined prompt template.
+ """
+ # Import locally to avoid circular import.
+ from langchain_core.prompts.chat import ChatPromptTemplate # noqa: PLC0415
+
+ prompt = ChatPromptTemplate(messages=[self])
+ return prompt.__add__(other)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/prompt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/prompt.py
new file mode 100644
index 0000000000000000000000000000000000000000..cef55a5c2ff63120032e5d5402a9f36fee874a08
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/prompt.py
@@ -0,0 +1,312 @@
+"""Prompt schema definition."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from pydantic import BaseModel, model_validator
+from typing_extensions import override
+
+from langchain_core.prompts.string import (
+ DEFAULT_FORMATTER_MAPPING,
+ PromptTemplateFormat,
+ StringPromptTemplate,
+ check_valid_template,
+ get_template_variables,
+ mustache_schema,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.runnables.config import RunnableConfig
+
+
+class PromptTemplate(StringPromptTemplate):
+ """Prompt template for a language model.
+
+ A prompt template consists of a string template. It accepts a set of parameters
+ from the user that can be used to generate a prompt for a language model.
+
+ The template can be formatted using either f-strings (default), jinja2, or mustache
+ syntax.
+
+ !!! warning "Security"
+
+ Prefer using `template_format='f-string'` instead of `template_format='jinja2'`,
+ or make sure to NEVER accept jinja2 templates from untrusted sources as they may
+ lead to arbitrary Python code execution.
+
+ As of LangChain 0.0.329, Jinja2 templates will be rendered using Jinja2's
+ SandboxedEnvironment by default. This sand-boxing should be treated as a
+ best-effort approach rather than a guarantee of security, as it is an opt-out
+ rather than opt-in approach.
+
+ Despite the sandboxing, we recommend to never use jinja2 templates from
+ untrusted sources.
+
+ Example:
+ ```python
+ from langchain_core.prompts import PromptTemplate
+
+ # Instantiation using from_template (recommended)
+ prompt = PromptTemplate.from_template("Say {foo}")
+ prompt.format(foo="bar")
+
+ # Instantiation using initializer
+ prompt = PromptTemplate(template="Say {foo}")
+ ```
+ """
+
+ @property
+ @override
+ def lc_attributes(self) -> dict[str, Any]:
+ return {
+ "template_format": self.template_format,
+ }
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "prompts", "prompt"]`
+ """
+ return ["langchain", "prompts", "prompt"]
+
+ template: str
+ """The prompt template."""
+
+ template_format: PromptTemplateFormat = "f-string"
+ """The format of the prompt template.
+
+ Options are: `'f-string'`, `'mustache'`, `'jinja2'`.
+ """
+
+ validate_template: bool = False
+ """Whether or not to try validating the template."""
+
+ @model_validator(mode="before")
+ @classmethod
+ def pre_init_validation(cls, values: dict) -> Any:
+ """Check that template and input variables are consistent."""
+ if values.get("template") is None:
+ # Will let pydantic fail with a ValidationError if template
+ # is not provided.
+ return values
+
+ # Set some default values based on the field defaults
+ values.setdefault("template_format", "f-string")
+ values.setdefault("partial_variables", {})
+
+ if values.get("validate_template"):
+ if values["template_format"] == "mustache":
+ msg = "Mustache templates cannot be validated."
+ raise ValueError(msg)
+
+ if "input_variables" not in values:
+ msg = "Input variables must be provided to validate the template."
+ raise ValueError(msg)
+
+ all_inputs = values["input_variables"] + list(values["partial_variables"])
+ check_valid_template(
+ values["template"], values["template_format"], all_inputs
+ )
+
+ if values["template_format"]:
+ values["input_variables"] = [
+ var
+ for var in get_template_variables(
+ values["template"], values["template_format"]
+ )
+ if var not in values["partial_variables"]
+ ]
+
+ return values
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ """Get the input schema for the prompt.
+
+ Args:
+ config: The runnable configuration.
+
+ Returns:
+ The input schema for the prompt.
+ """
+ if self.template_format != "mustache":
+ return super().get_input_schema(config)
+
+ return mustache_schema(self.template)
+
+ def __add__(self, other: Any) -> PromptTemplate:
+ """Override the `+` operator to allow for combining prompt templates.
+
+ Raises:
+ ValueError: If the template formats are not f-string or if there are
+ conflicting partial variables.
+ NotImplementedError: If the other object is not a `PromptTemplate` or str.
+
+ Returns:
+ A new `PromptTemplate` that is the combination of the two.
+ """
+ # Allow for easy combining
+ if isinstance(other, PromptTemplate):
+ if self.template_format != other.template_format:
+ msg = "Cannot add templates of different formats"
+ raise ValueError(msg)
+ input_variables = list(
+ set(self.input_variables) | set(other.input_variables)
+ )
+ template = self.template + other.template
+ # If any do not want to validate, then don't
+ validate_template = self.validate_template and other.validate_template
+ partial_variables = dict(self.partial_variables.items())
+ for k, v in other.partial_variables.items():
+ if k in partial_variables:
+ msg = "Cannot have same variable partialed twice."
+ raise ValueError(msg)
+ partial_variables[k] = v
+ return PromptTemplate(
+ template=template,
+ input_variables=input_variables,
+ partial_variables=partial_variables,
+ template_format=self.template_format,
+ validate_template=validate_template,
+ )
+ if isinstance(other, str):
+ prompt = PromptTemplate.from_template(
+ other,
+ template_format=self.template_format,
+ )
+ return self + prompt
+ msg = f"Unsupported operand type for +: {type(other)}"
+ raise NotImplementedError(msg)
+
+ @property
+ def _prompt_type(self) -> str:
+ """Return the prompt type key."""
+ return "prompt"
+
+ def format(self, **kwargs: Any) -> str:
+ """Format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ kwargs = self._merge_partial_and_user_variables(**kwargs)
+ return DEFAULT_FORMATTER_MAPPING[self.template_format](self.template, **kwargs)
+
+ @classmethod
+ def from_examples(
+ cls,
+ examples: list[str],
+ suffix: str,
+ input_variables: list[str],
+ example_separator: str = "\n\n",
+ prefix: str = "",
+ **kwargs: Any,
+ ) -> PromptTemplate:
+ """Take examples in list format with prefix and suffix to create a prompt.
+
+ Intended to be used as a way to dynamically create a prompt from examples.
+
+ Args:
+ examples: List of examples to use in the prompt.
+ suffix: String to go after the list of examples.
+
+ Should generally set up the user's input.
+ input_variables: A list of variable names the final prompt template will
+ expect.
+ example_separator: The separator to use in between examples.
+ prefix: String that should go before any examples.
+
+ Generally includes examples.
+
+ Returns:
+ The final prompt generated.
+ """
+ template = example_separator.join([prefix, *examples, suffix])
+ return cls(input_variables=input_variables, template=template, **kwargs)
+
+ @classmethod
+ def from_file(
+ cls,
+ template_file: str | Path,
+ encoding: str | None = None,
+ **kwargs: Any,
+ ) -> PromptTemplate:
+ """Load a prompt from a file.
+
+ Args:
+ template_file: The path to the file containing the prompt template.
+ encoding: The encoding system for opening the template file.
+
+ If not provided, will use the OS default.
+
+ Returns:
+ The prompt loaded from the file.
+ """
+ template = Path(template_file).read_text(encoding=encoding)
+ return cls.from_template(template=template, **kwargs)
+
+ @classmethod
+ def from_template(
+ cls,
+ template: str,
+ *,
+ template_format: PromptTemplateFormat = "f-string",
+ partial_variables: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> PromptTemplate:
+ """Load a prompt template from a template.
+
+ !!! warning "Security"
+
+ Prefer using `template_format='f-string'` instead of
+ `template_format='jinja2'`, or make sure to NEVER accept jinja2 templates
+ from untrusted sources as they may lead to arbitrary Python code execution.
+
+ As of LangChain 0.0.329, Jinja2 templates will be rendered using Jinja2's
+ SandboxedEnvironment by default. This sand-boxing should be treated as a
+ best-effort approach rather than a guarantee of security, as it is an
+ opt-out rather than opt-in approach.
+
+ Despite the sandboxing, we recommend to never use jinja2 templates from
+ untrusted sources.
+
+ Args:
+ template: The template to load.
+ template_format: The format of the template.
+
+ Use `jinja2` for jinja2, `mustache` for mustache, and `f-string` for
+ f-strings.
+ partial_variables: A dictionary of variables that can be used to partially
+ fill in the template.
+
+ For example, if the template is `'{variable1} {variable2}'`, and
+ `partial_variables` is `{"variable1": "foo"}`, then the final prompt
+ will be `'foo {variable2}'`.
+ **kwargs: Any other arguments to pass to the prompt template.
+
+ Returns:
+ The prompt template loaded from the template.
+ """
+ input_variables = get_template_variables(template, template_format)
+ partial_variables_ = partial_variables or {}
+
+ if partial_variables_:
+ input_variables = [
+ var for var in input_variables if var not in partial_variables_
+ ]
+
+ return cls(
+ input_variables=input_variables,
+ template=template,
+ template_format=template_format,
+ partial_variables=partial_variables_,
+ **kwargs,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/string.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/string.py
new file mode 100644
index 0000000000000000000000000000000000000000..f37bdba22197c549e8a66362a55fc3b57a90018a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/string.py
@@ -0,0 +1,399 @@
+"""`BasePrompt` schema definition."""
+
+from __future__ import annotations
+
+import warnings
+from abc import ABC, abstractmethod
+from string import Formatter
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+from pydantic import BaseModel, create_model
+from typing_extensions import override
+
+from langchain_core.prompt_values import PromptValue, StringPromptValue
+from langchain_core.prompts.base import BasePromptTemplate
+from langchain_core.utils import get_colored_text, mustache
+from langchain_core.utils.formatting import formatter
+from langchain_core.utils.interactive_env import is_interactive_env
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Sequence
+
+try:
+ from jinja2 import meta
+ from jinja2.sandbox import SandboxedEnvironment
+
+ _HAS_JINJA2 = True
+except ImportError:
+ _HAS_JINJA2 = False
+
+PromptTemplateFormat = Literal["f-string", "mustache", "jinja2"]
+
+
+def jinja2_formatter(template: str, /, **kwargs: Any) -> str:
+ """Format a template using jinja2.
+
+ !!! warning "Security"
+
+ As of LangChain 0.0.329, this method uses Jinja2's `SandboxedEnvironment` by
+ default. However, this sandboxing should be treated as a best-effort approach
+ rather than a guarantee of security.
+
+ Do not accept jinja2 templates from untrusted sources as they may lead
+ to arbitrary Python code execution.
+
+ [More information.](https://jinja.palletsprojects.com/en/3.1.x/sandbox/)
+
+ Args:
+ template: The template string.
+ **kwargs: The variables to format the template with.
+
+ Returns:
+ The formatted string.
+
+ Raises:
+ ImportError: If jinja2 is not installed.
+ """
+ if not _HAS_JINJA2:
+ msg = (
+ "jinja2 not installed, which is needed to use the jinja2_formatter. "
+ "Please install it with `pip install jinja2`."
+ "Please be cautious when using jinja2 templates. "
+ "Do not expand jinja2 templates using unverified or user-controlled "
+ "inputs as that can result in arbitrary Python code execution."
+ )
+ raise ImportError(msg)
+
+ # Use Jinja2's SandboxedEnvironment which blocks access to dunder attributes
+ # (e.g., __class__, __globals__) to prevent sandbox escapes.
+ # Note: regular attribute access (e.g., {{obj.attr}}) and method calls are
+ # still allowed. This is a best-effort measure — do not use with untrusted
+ # templates.
+ return SandboxedEnvironment().from_string(template).render(**kwargs)
+
+
+def validate_jinja2(template: str, input_variables: list[str]) -> None:
+ """Validate that the input variables are valid for the template.
+
+ Issues a warning if missing or extra variables are found.
+
+ Args:
+ template: The template string.
+ input_variables: The input variables.
+ """
+ input_variables_set = set(input_variables)
+ valid_variables = _get_jinja2_variables_from_template(template)
+ missing_variables = valid_variables - input_variables_set
+ extra_variables = input_variables_set - valid_variables
+
+ warning_message = ""
+ if missing_variables:
+ warning_message += f"Missing variables: {missing_variables} "
+
+ if extra_variables:
+ warning_message += f"Extra variables: {extra_variables}"
+
+ if warning_message:
+ warnings.warn(warning_message.strip(), stacklevel=7)
+
+
+def _get_jinja2_variables_from_template(template: str) -> set[str]:
+ if not _HAS_JINJA2:
+ msg = (
+ "jinja2 not installed, which is needed to use the jinja2_formatter. "
+ "Please install it with `pip install jinja2`."
+ )
+ raise ImportError(msg)
+ env = SandboxedEnvironment()
+ ast = env.parse(template)
+ return meta.find_undeclared_variables(ast)
+
+
+def mustache_formatter(template: str, /, **kwargs: Any) -> str:
+ """Format a template using mustache.
+
+ Args:
+ template: The template string.
+ **kwargs: The variables to format the template with.
+
+ Returns:
+ The formatted string.
+ """
+ return mustache.render(template, kwargs)
+
+
+def mustache_template_vars(
+ template: str,
+) -> set[str]:
+ """Get the top-level variables from a mustache template.
+
+ For nested variables like `{{person.name}}`, only the top-level key (`person`) is
+ returned.
+
+ Args:
+ template: The template string.
+
+ Returns:
+ The top-level variables from the template.
+ """
+ variables: set[str] = set()
+ section_depth = 0
+ for type_, key in mustache.tokenize(template):
+ if type_ == "end":
+ section_depth -= 1
+ elif (
+ type_ in {"variable", "section", "inverted section", "no escape"}
+ and key != "."
+ and section_depth == 0
+ ):
+ variables.add(key.split(".")[0])
+ if type_ in {"section", "inverted section"}:
+ section_depth += 1
+ return variables
+
+
+Defs = dict[str, "Defs"]
+
+
+def mustache_schema(template: str) -> type[BaseModel]:
+ """Get the variables from a mustache template.
+
+ Args:
+ template: The template string.
+
+ Returns:
+ The variables from the template as a Pydantic model.
+ """
+ fields = {}
+ prefix: tuple[str, ...] = ()
+ section_stack: list[tuple[str, ...]] = []
+ for type_, key in mustache.tokenize(template):
+ if key == ".":
+ continue
+ if type_ == "end":
+ if section_stack:
+ prefix = section_stack.pop()
+ elif type_ in {"section", "inverted section"}:
+ section_stack.append(prefix)
+ prefix += tuple(key.split("."))
+ fields[prefix] = False
+ elif type_ in {"variable", "no escape"}:
+ fields[prefix + tuple(key.split("."))] = True
+
+ for fkey, fval in fields.items():
+ fields[fkey] = fval and not any(
+ is_subsequence(fkey, k) for k in fields if k != fkey
+ )
+ defs: Defs = {} # None means leaf node
+ while fields:
+ field, is_leaf = fields.popitem()
+ current = defs
+ for part in field[:-1]:
+ current = current.setdefault(part, {})
+ current.setdefault(field[-1], "" if is_leaf else {}) # type: ignore[arg-type]
+ return _create_model_recursive("PromptInput", defs)
+
+
+def _create_model_recursive(name: str, defs: Defs) -> type[BaseModel]:
+ return cast(
+ "type[BaseModel]",
+ create_model( # type: ignore[call-overload]
+ name,
+ **{
+ k: (_create_model_recursive(k, v), None) if v else (type(v), None)
+ for k, v in defs.items()
+ },
+ ),
+ )
+
+
+DEFAULT_FORMATTER_MAPPING: dict[str, Callable[..., str]] = {
+ "f-string": formatter.format,
+ "mustache": mustache_formatter,
+ "jinja2": jinja2_formatter,
+}
+
+DEFAULT_VALIDATOR_MAPPING: dict[str, Callable] = {
+ "f-string": formatter.validate_input_variables,
+ "jinja2": validate_jinja2,
+}
+
+
+def _parse_f_string_fields(template: str) -> list[tuple[str, str | None]]:
+ fields: list[tuple[str, str | None]] = []
+ for _, field_name, format_spec, _ in Formatter().parse(template):
+ if field_name is not None:
+ fields.append((field_name, format_spec))
+ return fields
+
+
+def validate_f_string_template(template: str) -> list[str]:
+ """Validate an f-string template and return its input variables."""
+ input_variables = set()
+ for var, format_spec in _parse_f_string_fields(template):
+ if "." in var or "[" in var or "]" in var:
+ msg = (
+ f"Invalid variable name {var!r} in f-string template. "
+ f"Variable names cannot contain attribute "
+ f"access (.) or indexing ([])."
+ )
+ raise ValueError(msg)
+
+ if var.isdigit():
+ msg = (
+ f"Invalid variable name {var!r} in f-string template. "
+ f"Variable names cannot be all digits as they are interpreted "
+ f"as positional arguments."
+ )
+ raise ValueError(msg)
+
+ if format_spec and ("{" in format_spec or "}" in format_spec):
+ msg = (
+ "Invalid format specifier in f-string template. "
+ "Nested replacement fields are not allowed."
+ )
+ raise ValueError(msg)
+
+ input_variables.add(var)
+
+ return sorted(input_variables)
+
+
+def check_valid_template(
+ template: str, template_format: str, input_variables: list[str]
+) -> None:
+ """Check that template string is valid.
+
+ Args:
+ template: The template string.
+ template_format: The template format.
+
+ Should be one of `'f-string'` or `'jinja2'`.
+ input_variables: The input variables.
+
+ Raises:
+ ValueError: If the template format is not supported.
+ ValueError: If the prompt schema is invalid.
+ """
+ try:
+ validator_func = DEFAULT_VALIDATOR_MAPPING[template_format]
+ except KeyError as exc:
+ msg = (
+ f"Invalid template format {template_format!r}, should be one of"
+ f" {list(DEFAULT_FORMATTER_MAPPING)}."
+ )
+ raise ValueError(msg) from exc
+ if template_format == "f-string":
+ validate_f_string_template(template)
+ try:
+ validator_func(template, input_variables)
+ except (KeyError, IndexError) as exc:
+ msg = (
+ "Invalid prompt schema; check for mismatched or missing input parameters"
+ f" from {input_variables}."
+ )
+ raise ValueError(msg) from exc
+
+
+def get_template_variables(template: str, template_format: str) -> list[str]:
+ """Get the variables from the template.
+
+ Args:
+ template: The template string.
+ template_format: The template format.
+
+ Should be one of `'f-string'`, `'mustache'` or `'jinja2'`.
+
+ Returns:
+ The variables from the template.
+
+ Raises:
+ ValueError: If the template format is not supported.
+ """
+ input_variables: list[str] | set[str]
+ if template_format == "jinja2":
+ # Get the variables for the template
+ input_variables = sorted(_get_jinja2_variables_from_template(template))
+ elif template_format == "f-string":
+ input_variables = validate_f_string_template(template)
+ elif template_format == "mustache":
+ input_variables = mustache_template_vars(template)
+ else:
+ msg = f"Unsupported template format: {template_format}"
+ raise ValueError(msg)
+
+ return sorted(input_variables)
+
+
+class StringPromptTemplate(BasePromptTemplate, ABC):
+ """String prompt that exposes the format method, returning a prompt."""
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "prompts", "base"]`
+ """
+ return ["langchain", "prompts", "base"]
+
+ def format_prompt(self, **kwargs: Any) -> PromptValue:
+ """Format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ return StringPromptValue(text=self.format(**kwargs))
+
+ async def aformat_prompt(self, **kwargs: Any) -> PromptValue:
+ """Async format the prompt with the inputs.
+
+ Args:
+ **kwargs: Any arguments to be passed to the prompt template.
+
+ Returns:
+ A formatted string.
+ """
+ return StringPromptValue(text=await self.aformat(**kwargs))
+
+ @override
+ @abstractmethod
+ def format(self, **kwargs: Any) -> str: ...
+
+ def pretty_repr(
+ self,
+ html: bool = False, # noqa: FBT001,FBT002
+ ) -> str:
+ """Get a pretty representation of the prompt.
+
+ Args:
+ html: Whether to return an HTML-formatted string.
+
+ Returns:
+ A pretty representation of the prompt.
+ """
+ # TODO: handle partials
+ dummy_vars = {
+ input_var: "{" + f"{input_var}" + "}" for input_var in self.input_variables
+ }
+ if html:
+ dummy_vars = {
+ k: get_colored_text(v, "yellow") for k, v in dummy_vars.items()
+ }
+ return self.format(**dummy_vars)
+
+ def pretty_print(self) -> None:
+ """Print a pretty representation of the prompt."""
+ print(self.pretty_repr(html=is_interactive_env())) # noqa: T201
+
+
+def is_subsequence(child: Sequence, parent: Sequence) -> bool:
+ """Return `True` if child is subsequence of parent."""
+ if len(child) == 0 or len(parent) == 0:
+ return False
+ if len(parent) < len(child):
+ return False
+ return all(child[i] == parent[i] for i in range(len(child)))
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/structured.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/structured.py
new file mode 100644
index 0000000000000000000000000000000000000000..00ac407fb7206f2f7376dfde46b6e965f2d9ec86
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/prompts/structured.py
@@ -0,0 +1,183 @@
+"""Structured prompt template for a language model."""
+
+from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
+from typing import (
+ Any,
+)
+
+from pydantic import BaseModel, Field
+from typing_extensions import override
+
+from langchain_core._api.beta_decorator import beta
+from langchain_core.language_models.base import BaseLanguageModel
+from langchain_core.prompts.chat import (
+ ChatPromptTemplate,
+ MessageLikeRepresentation,
+)
+from langchain_core.prompts.string import PromptTemplateFormat
+from langchain_core.runnables.base import (
+ Other,
+ Runnable,
+ RunnableSequence,
+ RunnableSerializable,
+)
+from langchain_core.utils import get_pydantic_field_names
+
+
+@beta()
+class StructuredPrompt(ChatPromptTemplate):
+ """Structured prompt template for a language model."""
+
+ schema_: dict | type
+ """Schema for the structured prompt."""
+
+ structured_output_kwargs: dict[str, Any] = Field(default_factory=dict)
+
+ def __init__(
+ self,
+ messages: Sequence[MessageLikeRepresentation],
+ schema_: dict | type[BaseModel] | None = None,
+ *,
+ structured_output_kwargs: dict[str, Any] | None = None,
+ template_format: PromptTemplateFormat = "f-string",
+ **kwargs: Any,
+ ) -> None:
+ """Create a structured prompt template.
+
+ Args:
+ messages: Sequence of messages.
+ schema_: Schema for the structured prompt.
+ structured_output_kwargs: Additional kwargs for structured output.
+ template_format: Template format for the prompt.
+
+ Raises:
+ ValueError: If schema is not provided.
+ """
+ schema_ = schema_ or kwargs.pop("schema", None)
+ if not schema_:
+ err_msg = (
+ "Must pass in a non-empty structured output schema. Received: "
+ f"{schema_}"
+ )
+ raise ValueError(err_msg)
+ structured_output_kwargs = structured_output_kwargs or {}
+ for k in set(kwargs).difference(get_pydantic_field_names(self.__class__)):
+ structured_output_kwargs[k] = kwargs.pop(k)
+ super().__init__(
+ messages=messages,
+ schema_=schema_,
+ structured_output_kwargs=structured_output_kwargs,
+ template_format=template_format,
+ **kwargs,
+ )
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ For example, if the class is `langchain.llms.openai.OpenAI`, then the namespace
+ is `["langchain", "llms", "openai"]`
+
+ Returns:
+ The namespace of the LangChain object.
+ """
+ return cls.__module__.split(".")
+
+ @classmethod
+ def from_messages_and_schema(
+ cls,
+ messages: Sequence[MessageLikeRepresentation],
+ schema: dict | type,
+ **kwargs: Any,
+ ) -> ChatPromptTemplate:
+ """Create a chat prompt template from a variety of message formats.
+
+ Examples:
+ Instantiation from a list of message templates:
+
+ ```python
+ from langchain_core.prompts import StructuredPrompt
+
+
+ class OutputSchema(BaseModel):
+ name: str
+ value: int
+
+
+ template = StructuredPrompt(
+ [
+ ("human", "Hello, how are you?"),
+ ("ai", "I'm doing well, thanks!"),
+ ("human", "That's good to hear."),
+ ],
+ OutputSchema,
+ )
+ ```
+
+ Args:
+ messages: Sequence of message representations.
+
+ A message can be represented using the following formats:
+
+ 1. `BaseMessagePromptTemplate`
+ 2. `BaseMessage`
+ 3. 2-tuple of `(message type, template)`; e.g.,
+ `("human", "{user_input}")`
+ 4. 2-tuple of `(message class, template)`
+ 5. A string which is shorthand for `("human", template)`; e.g.,
+ `"{user_input}"`
+ schema: A dictionary representation of function call, or a Pydantic model.
+ **kwargs: Any additional kwargs to pass through to
+ `ChatModel.with_structured_output(schema, **kwargs)`.
+
+ Returns:
+ A structured prompt template
+ """
+ return cls(messages, schema, **kwargs)
+
+ @override
+ def __or__(
+ self,
+ other: Runnable[Any, Other]
+ | Callable[[Iterator[Any]], Iterator[Other]]
+ | Callable[[AsyncIterator[Any]], AsyncIterator[Other]]
+ | Callable[[Any], Other]
+ | Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any],
+ ) -> RunnableSerializable[dict, Other]:
+ return self.pipe(other)
+
+ def pipe(
+ self,
+ *others: Runnable[Any, Other]
+ | Callable[[Iterator[Any]], Iterator[Other]]
+ | Callable[[AsyncIterator[Any]], AsyncIterator[Other]]
+ | Callable[[Any], Other]
+ | Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any],
+ name: str | None = None,
+ ) -> RunnableSerializable[dict, Other]:
+ """Pipe the structured prompt to a language model.
+
+ Args:
+ others: The language model to pipe the structured prompt to.
+ name: The name of the pipeline.
+
+ Returns:
+ A `RunnableSequence` object.
+
+ Raises:
+ NotImplementedError: If the first element of `others` is not a language
+ model.
+ """
+ if (others and isinstance(others[0], BaseLanguageModel)) or hasattr(
+ others[0], "with_structured_output"
+ ):
+ return RunnableSequence(
+ self,
+ others[0].with_structured_output(
+ self.schema_, **self.structured_output_kwargs
+ ),
+ *others[1:],
+ name=name,
+ )
+ msg = "Structured prompts need to be piped to a language model."
+ raise NotImplementedError(msg)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d619bfa88d6642b027c05402c7bf909ea8e02d17
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__init__.py
@@ -0,0 +1,136 @@
+"""LangChain **Runnable** and the **LangChain Expression Language (LCEL)**.
+
+The LangChain Expression Language (LCEL) offers a declarative method to build
+production-grade programs that harness the power of LLMs.
+
+Programs created using LCEL and LangChain `Runnable` objects inherently support
+synchronous asynchronous, batch, and streaming operations.
+
+Support for **async** allows servers hosting LCEL based programs to scale bette for
+higher concurrent loads.
+
+**Batch** operations allow for processing multiple inputs in parallel.
+
+**Streaming** of intermediate outputs, as they're being generated, allows for creating
+more responsive UX.
+
+This module contains schema and implementation of LangChain `Runnable` object
+primitives.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.runnables.base import (
+ Runnable,
+ RunnableBinding,
+ RunnableGenerator,
+ RunnableLambda,
+ RunnableMap,
+ RunnableParallel,
+ RunnableSequence,
+ RunnableSerializable,
+ chain,
+ )
+ from langchain_core.runnables.branch import RunnableBranch
+ from langchain_core.runnables.config import (
+ RunnableConfig,
+ ensure_config,
+ get_config_list,
+ patch_config,
+ run_in_executor,
+ )
+ from langchain_core.runnables.fallbacks import RunnableWithFallbacks
+ from langchain_core.runnables.history import RunnableWithMessageHistory
+ from langchain_core.runnables.passthrough import (
+ RunnableAssign,
+ RunnablePassthrough,
+ RunnablePick,
+ )
+ from langchain_core.runnables.router import RouterInput, RouterRunnable
+ from langchain_core.runnables.utils import (
+ AddableDict,
+ ConfigurableField,
+ ConfigurableFieldMultiOption,
+ ConfigurableFieldSingleOption,
+ ConfigurableFieldSpec,
+ aadd,
+ add,
+ )
+
+__all__ = (
+ "AddableDict",
+ "ConfigurableField",
+ "ConfigurableFieldMultiOption",
+ "ConfigurableFieldSingleOption",
+ "ConfigurableFieldSpec",
+ "RouterInput",
+ "RouterRunnable",
+ "Runnable",
+ "RunnableAssign",
+ "RunnableBinding",
+ "RunnableBranch",
+ "RunnableConfig",
+ "RunnableGenerator",
+ "RunnableLambda",
+ "RunnableMap",
+ "RunnableParallel",
+ "RunnablePassthrough",
+ "RunnablePick",
+ "RunnableSequence",
+ "RunnableSerializable",
+ "RunnableWithFallbacks",
+ "RunnableWithMessageHistory",
+ "aadd",
+ "add",
+ "chain",
+ "ensure_config",
+ "get_config_list",
+ "patch_config",
+ "run_in_executor",
+)
+
+_dynamic_imports = {
+ "chain": "base",
+ "Runnable": "base",
+ "RunnableBinding": "base",
+ "RunnableGenerator": "base",
+ "RunnableLambda": "base",
+ "RunnableMap": "base",
+ "RunnableParallel": "base",
+ "RunnableSequence": "base",
+ "RunnableSerializable": "base",
+ "RunnableBranch": "branch",
+ "RunnableConfig": "config",
+ "ensure_config": "config",
+ "get_config_list": "config",
+ "patch_config": "config",
+ "run_in_executor": "config",
+ "RunnableWithFallbacks": "fallbacks",
+ "RunnableWithMessageHistory": "history",
+ "RunnableAssign": "passthrough",
+ "RunnablePassthrough": "passthrough",
+ "RunnablePick": "passthrough",
+ "RouterInput": "router",
+ "RouterRunnable": "router",
+ "AddableDict": "utils",
+ "ConfigurableField": "utils",
+ "ConfigurableFieldMultiOption": "utils",
+ "ConfigurableFieldSingleOption": "utils",
+ "ConfigurableFieldSpec": "utils",
+ "aadd": "utils",
+ "add": "utils",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..868c61b4c78462e463214a823b6d846d53d5196b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/branch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/branch.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..947e68ad84de97f6262a13ad91e537d39e551eba
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/branch.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/config.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/config.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e2bd3540dc74a4b669e972455328f90b504bbe0e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/config.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/configurable.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/configurable.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed7c3d9ce742f1439d8925d1e7a25c676bb51a93
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/configurable.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/fallbacks.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/fallbacks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f75fac7789a21e088b5996480252e4a25231c4fc
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/fallbacks.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/graph.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/graph.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..820afc02fef44becb721f3779ba6139bb1f6112e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/graph.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/graph_ascii.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/graph_ascii.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f2eef92aca36e86acff1a77a0d1aa577c4a152af
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/graph_ascii.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/graph_mermaid.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/graph_mermaid.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..086ef41e1449f806bab677ad97d03e96d9543684
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/graph_mermaid.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/graph_png.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/graph_png.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68e62f3cf3c9bf41963083426f3c891a7dce169b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/graph_png.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/history.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/history.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b84d14c3ad7c3785bd370bb1143cf49950e5abf9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/history.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/passthrough.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/passthrough.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5bd98b40c6270b8b90a3a2dcc79848113dd8194
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/passthrough.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/retry.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/retry.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d00736e0e6f04783e85f15e03096c8df789ed6f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/retry.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/router.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/router.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..90c9ad4a1417fccefc47fded132776b5d9715c32
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/router.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/schema.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/schema.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a084fecca50d059709d2231077e42e0b57f9286c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/schema.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2fbe470ef8b67fabd7a27cc9afc508c8574be525
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/__pycache__/utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a9b0cdcfcf32335ee492e733c4813f49eb57b1c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/base.py
@@ -0,0 +1,6574 @@
+"""Base classes and utilities for `Runnable` objects."""
+
+from __future__ import annotations
+
+import asyncio
+import collections
+import contextlib
+import functools
+import inspect
+import threading
+from abc import ABC, abstractmethod
+from collections.abc import (
+ AsyncGenerator,
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Coroutine,
+ Iterator,
+ Mapping,
+ Sequence,
+)
+from concurrent.futures import FIRST_COMPLETED, wait
+from functools import wraps
+from itertools import tee
+from operator import itemgetter
+from types import GenericAlias
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Generic,
+ Literal,
+ Protocol,
+ TypeVar,
+ cast,
+ get_args,
+ get_type_hints,
+ overload,
+)
+
+from pydantic import BaseModel, ConfigDict, Field, RootModel
+from typing_extensions import override
+
+from langchain_core._api import beta_decorator
+from langchain_core._api.deprecation import warn_deprecated
+from langchain_core.callbacks.manager import AsyncCallbackManager, CallbackManager
+from langchain_core.load.serializable import (
+ Serializable,
+ SerializedConstructor,
+ SerializedNotImplemented,
+)
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ acall_func_with_variable_args,
+ call_func_with_variable_args,
+ ensure_config,
+ get_async_callback_manager_for_config,
+ get_callback_manager_for_config,
+ get_config_list,
+ get_executor_for_config,
+ merge_configs,
+ patch_config,
+ run_in_executor,
+ set_config_context,
+)
+from langchain_core.runnables.utils import (
+ AddableDict,
+ AnyConfigurableField,
+ ConfigurableField,
+ ConfigurableFieldSpec,
+ Input,
+ Output,
+ accepts_config,
+ accepts_run_manager,
+ coro_with_context,
+ gated_coro,
+ gather_with_concurrency,
+ get_function_first_arg_dict_keys,
+ get_function_nonlocals,
+ get_lambda_source,
+ get_unique_config_specs,
+ indent_lines_after_first,
+ is_async_callable,
+ is_async_generator,
+)
+from langchain_core.tracers._streaming import _StreamingCallbackHandler
+from langchain_core.tracers.event_stream import (
+ _astream_events_implementation_v1,
+ _astream_events_implementation_v2,
+)
+from langchain_core.tracers.log_stream import (
+ LogStreamCallbackHandler,
+ _astream_log_implementation,
+)
+from langchain_core.tracers.root_listeners import (
+ AsyncRootListenersTracer,
+ RootListenersTracer,
+)
+from langchain_core.utils.aiter import aclosing, atee
+from langchain_core.utils.iter import safetee
+from langchain_core.utils.pydantic import create_model_v2
+
+if TYPE_CHECKING:
+ from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForChainRun,
+ CallbackManagerForChainRun,
+ )
+ from langchain_core.prompts.base import BasePromptTemplate
+ from langchain_core.runnables.fallbacks import (
+ RunnableWithFallbacks as RunnableWithFallbacksT,
+ )
+ from langchain_core.runnables.graph import Graph
+ from langchain_core.runnables.retry import ExponentialJitterParams
+ from langchain_core.runnables.schema import StreamEvent
+ from langchain_core.tools import BaseTool
+ from langchain_core.tracers.log_stream import RunLog, RunLogPatch
+ from langchain_core.tracers.root_listeners import AsyncListener
+ from langchain_core.tracers.schemas import Run
+
+
+Other = TypeVar("Other")
+
+_RUNNABLE_GENERIC_NUM_ARGS = 2 # Input and Output
+
+
+class Runnable(ABC, Generic[Input, Output]):
+ """A unit of work that can be invoked, batched, streamed, transformed and composed.
+
+ Key Methods
+ ===========
+
+ - `invoke`/`ainvoke`: Transforms a single input into an output.
+ - `batch`/`abatch`: Efficiently transforms multiple inputs into outputs.
+ - `stream`/`astream`: Streams output from a single input as it's produced.
+ - `astream_log`: Streams output and selected intermediate results from an
+ input.
+
+ Built-in optimizations:
+
+ - **Batch**: By default, batch runs invoke() in parallel using a thread pool
+ executor. Override to optimize batching.
+
+ - **Async**: Methods with `'a'` prefix are asynchronous. By default, they execute
+ the sync counterpart using asyncio's thread pool.
+ Override for native async.
+
+ All methods accept an optional config argument, which can be used to configure
+ execution, add tags and metadata for tracing and debugging etc.
+
+ Runnables expose schematic information about their input, output and config via
+ the `input_schema` property, the `output_schema` property and `config_schema`
+ method.
+
+ Composition
+ ===========
+
+ Runnable objects can be composed together to create chains in a declarative way.
+
+ Any chain constructed this way will automatically have sync, async, batch, and
+ streaming support.
+
+ The main composition primitives are `RunnableSequence` and `RunnableParallel`.
+
+ **`RunnableSequence`** invokes a series of runnables sequentially, with
+ one Runnable's output serving as the next's input. Construct using
+ the `|` operator or by passing a list of runnables to `RunnableSequence`.
+
+ **`RunnableParallel`** invokes runnables concurrently, providing the same input
+ to each. Construct it using a dict literal within a sequence or by passing a
+ dict to `RunnableParallel`.
+
+
+ For example,
+
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+ # A RunnableSequence constructed using the `|` operator
+ sequence = RunnableLambda(lambda x: x + 1) | RunnableLambda(lambda x: x * 2)
+ sequence.invoke(1) # 4
+ sequence.batch([1, 2, 3]) # [4, 6, 8]
+
+
+ # A sequence that contains a RunnableParallel constructed using a dict literal
+ sequence = RunnableLambda(lambda x: x + 1) | {
+ "mul_2": RunnableLambda(lambda x: x * 2),
+ "mul_5": RunnableLambda(lambda x: x * 5),
+ }
+ sequence.invoke(1) # {'mul_2': 4, 'mul_5': 10}
+ ```
+
+ Standard Methods
+ ================
+
+ All `Runnable`s expose additional methods that can be used to modify their
+ behavior (e.g., add a retry policy, add lifecycle listeners, make them
+ configurable, etc.).
+
+ These methods will work on any `Runnable`, including `Runnable` chains
+ constructed by composing other `Runnable`s.
+ See the individual methods for details.
+
+ For example,
+
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+ import random
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ def buggy_double(y: int) -> int:
+ \"\"\"Buggy code that will fail 70% of the time\"\"\"
+ if random.random() > 0.3:
+ print('This code failed, and will probably be retried!') # noqa: T201
+ raise ValueError('Triggered buggy code')
+ return y * 2
+
+ sequence = (
+ RunnableLambda(add_one) |
+ RunnableLambda(buggy_double).with_retry( # Retry on failure
+ stop_after_attempt=10,
+ wait_exponential_jitter=False
+ )
+ )
+
+ print(sequence.input_schema.model_json_schema()) # Show inferred input schema
+ print(sequence.output_schema.model_json_schema()) # Show inferred output schema
+ print(sequence.invoke(2)) # invoke the sequence (note the retry above!!)
+ ```
+
+ Debugging and tracing
+ =====================
+
+ As the chains get longer, it can be useful to be able to see intermediate results
+ to debug and trace the chain.
+
+ You can set the global debug flag to True to enable debug output for all chains:
+
+ ```python
+ from langchain_core.globals import set_debug
+
+ set_debug(True)
+ ```
+
+ Alternatively, you can pass existing or custom callbacks to any given chain:
+
+ ```python
+ from langchain_core.tracers import ConsoleCallbackHandler
+
+ chain.invoke(..., config={"callbacks": [ConsoleCallbackHandler()]})
+ ```
+
+ For a UI (and much more) checkout [LangSmith](https://docs.langchain.com/langsmith/home).
+
+ """
+
+ name: str | None
+ """The name of the `Runnable`. Used for debugging and tracing."""
+
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ """Get the name of the `Runnable`.
+
+ Args:
+ suffix: An optional suffix to append to the name.
+ name: An optional name to use instead of the `Runnable`'s name.
+
+ Returns:
+ The name of the `Runnable`.
+ """
+ if name:
+ name_ = name
+ elif hasattr(self, "name") and self.name:
+ name_ = self.name
+ else:
+ # Here we handle a case where the runnable subclass is also a pydantic
+ # model.
+ cls = self.__class__
+ # Then it's a pydantic sub-class, and we have to check
+ # whether it's a generic, and if so recover the original name.
+ if (
+ hasattr(
+ cls,
+ "__pydantic_generic_metadata__",
+ )
+ and "origin" in cls.__pydantic_generic_metadata__
+ and cls.__pydantic_generic_metadata__["origin"] is not None
+ ):
+ name_ = cls.__pydantic_generic_metadata__["origin"].__name__
+ else:
+ name_ = cls.__name__
+
+ if suffix:
+ if name_[0].isupper():
+ return name_ + suffix.title()
+ return name_ + "_" + suffix.lower()
+ return name_
+
+ @property
+ def InputType(self) -> type[Input]: # noqa: N802
+ """Input type.
+
+ The type of input this `Runnable` accepts specified as a type annotation.
+
+ Raises:
+ TypeError: If the input type cannot be inferred.
+ """
+ # First loop through all parent classes and if any of them is
+ # a Pydantic model, we will pick up the generic parameterization
+ # from that model via the __pydantic_generic_metadata__ attribute.
+ for base in self.__class__.mro():
+ if hasattr(base, "__pydantic_generic_metadata__"):
+ metadata = base.__pydantic_generic_metadata__
+ if (
+ "args" in metadata
+ and len(metadata["args"]) == _RUNNABLE_GENERIC_NUM_ARGS
+ ):
+ return cast("type[Input]", metadata["args"][0])
+
+ # If we didn't find a Pydantic model in the parent classes,
+ # then loop through __orig_bases__. This corresponds to
+ # Runnables that are not pydantic models.
+ for cls in self.__class__.__orig_bases__: # type: ignore[attr-defined]
+ type_args = get_args(cls)
+ if type_args and len(type_args) == _RUNNABLE_GENERIC_NUM_ARGS:
+ return cast("type[Input]", type_args[0])
+
+ msg = (
+ f"Runnable {self.get_name()} doesn't have an inferable InputType. "
+ "Override the InputType property to specify the input type."
+ )
+ raise TypeError(msg)
+
+ @property
+ def OutputType(self) -> type[Output]: # noqa: N802
+ """Output Type.
+
+ The type of output this `Runnable` produces specified as a type annotation.
+
+ Raises:
+ TypeError: If the output type cannot be inferred.
+ """
+ # First loop through bases -- this will help generic
+ # any pydantic models.
+ for base in self.__class__.mro():
+ if hasattr(base, "__pydantic_generic_metadata__"):
+ metadata = base.__pydantic_generic_metadata__
+ if (
+ "args" in metadata
+ and len(metadata["args"]) == _RUNNABLE_GENERIC_NUM_ARGS
+ ):
+ return cast("type[Output]", metadata["args"][1])
+
+ for cls in self.__class__.__orig_bases__: # type: ignore[attr-defined]
+ type_args = get_args(cls)
+ if type_args and len(type_args) == _RUNNABLE_GENERIC_NUM_ARGS:
+ return cast("type[Output]", type_args[1])
+
+ msg = (
+ f"Runnable {self.get_name()} doesn't have an inferable OutputType. "
+ "Override the OutputType property to specify the output type."
+ )
+ raise TypeError(msg)
+
+ @property
+ def input_schema(self) -> type[BaseModel]:
+ """The type of input this `Runnable` accepts specified as a Pydantic model."""
+ return self.get_input_schema()
+
+ def get_input_schema(
+ self,
+ config: RunnableConfig | None = None,
+ ) -> type[BaseModel]:
+ """Get a Pydantic model that can be used to validate input to the `Runnable`.
+
+ `Runnable` objects that leverage the `configurable_fields` and
+ `configurable_alternatives` methods will have a dynamic input schema that
+ depends on which configuration the `Runnable` is invoked with.
+
+ This method allows to get an input schema for a specific configuration.
+
+ Args:
+ config: A config to use when generating the schema.
+
+ Returns:
+ A Pydantic model that can be used to validate input.
+ """
+ _ = config
+ root_type = self.InputType
+
+ if (
+ inspect.isclass(root_type)
+ and not isinstance(root_type, GenericAlias)
+ and issubclass(root_type, BaseModel)
+ ):
+ return root_type
+
+ return create_model_v2(
+ self.get_name("Input"),
+ root=root_type,
+ # create model needs access to appropriate type annotations to be
+ # able to construct the Pydantic model.
+ # When we create the model, we pass information about the namespace
+ # where the model is being created, so the type annotations can
+ # be resolved correctly as well.
+ # self.__class__.__module__ handles the case when the Runnable is
+ # being sub-classed in a different module.
+ module_name=self.__class__.__module__,
+ )
+
+ def get_input_jsonschema(
+ self, config: RunnableConfig | None = None
+ ) -> dict[str, Any]:
+ """Get a JSON schema that represents the input to the `Runnable`.
+
+ Args:
+ config: A config to use when generating the schema.
+
+ Returns:
+ A JSON schema that represents the input to the `Runnable`.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ runnable = RunnableLambda(add_one)
+
+ print(runnable.get_input_jsonschema())
+ ```
+
+ !!! version-added "Added in `langchain-core` 0.3.0"
+
+ """
+ return self.get_input_schema(config).model_json_schema()
+
+ @property
+ def output_schema(self) -> type[BaseModel]:
+ """Output schema.
+
+ The type of output this `Runnable` produces specified as a Pydantic model.
+ """
+ return self.get_output_schema()
+
+ def get_output_schema(
+ self,
+ config: RunnableConfig | None = None,
+ ) -> type[BaseModel]:
+ """Get a Pydantic model that can be used to validate output to the `Runnable`.
+
+ `Runnable` objects that leverage the `configurable_fields` and
+ `configurable_alternatives` methods will have a dynamic output schema that
+ depends on which configuration the `Runnable` is invoked with.
+
+ This method allows to get an output schema for a specific configuration.
+
+ Args:
+ config: A config to use when generating the schema.
+
+ Returns:
+ A Pydantic model that can be used to validate output.
+ """
+ _ = config
+ root_type = self.OutputType
+
+ if (
+ inspect.isclass(root_type)
+ and not isinstance(root_type, GenericAlias)
+ and issubclass(root_type, BaseModel)
+ ):
+ return root_type
+
+ return create_model_v2(
+ self.get_name("Output"),
+ root=root_type,
+ # create model needs access to appropriate type annotations to be
+ # able to construct the Pydantic model.
+ # When we create the model, we pass information about the namespace
+ # where the model is being created, so the type annotations can
+ # be resolved correctly as well.
+ # self.__class__.__module__ handles the case when the Runnable is
+ # being sub-classed in a different module.
+ module_name=self.__class__.__module__,
+ )
+
+ def get_output_jsonschema(
+ self, config: RunnableConfig | None = None
+ ) -> dict[str, Any]:
+ """Get a JSON schema that represents the output of the `Runnable`.
+
+ Args:
+ config: A config to use when generating the schema.
+
+ Returns:
+ A JSON schema that represents the output of the `Runnable`.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ runnable = RunnableLambda(add_one)
+
+ print(runnable.get_output_jsonschema())
+ ```
+
+ !!! version-added "Added in `langchain-core` 0.3.0"
+
+ """
+ return self.get_output_schema(config).model_json_schema()
+
+ @property
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ """List configurable fields for this `Runnable`."""
+ return []
+
+ def config_schema(self, *, include: Sequence[str] | None = None) -> type[BaseModel]:
+ """The type of config this `Runnable` accepts specified as a Pydantic model.
+
+ To mark a field as configurable, see the `configurable_fields`
+ and `configurable_alternatives` methods.
+
+ Args:
+ include: A list of fields to include in the config schema.
+
+ Returns:
+ A Pydantic model that can be used to validate config.
+
+ """
+ include = include or []
+ config_specs = self.config_specs
+ configurable = (
+ create_model_v2(
+ "Configurable",
+ field_definitions={
+ spec.id: (
+ spec.annotation,
+ Field(
+ spec.default, title=spec.name, description=spec.description
+ ),
+ )
+ for spec in config_specs
+ },
+ )
+ if config_specs
+ else None
+ )
+
+ # Many need to create a typed dict instead to implement NotRequired!
+ all_fields = {
+ **({"configurable": (configurable, None)} if configurable else {}),
+ **{
+ field_name: (field_type, None)
+ for field_name, field_type in get_type_hints(RunnableConfig).items()
+ if field_name in [i for i in include if i != "configurable"]
+ },
+ }
+ return create_model_v2(self.get_name("Config"), field_definitions=all_fields)
+
+ def get_config_jsonschema(
+ self, *, include: Sequence[str] | None = None
+ ) -> dict[str, Any]:
+ """Get a JSON schema that represents the config of the `Runnable`.
+
+ Args:
+ include: A list of fields to include in the config schema.
+
+ Returns:
+ A JSON schema that represents the config of the `Runnable`.
+
+ !!! version-added "Added in `langchain-core` 0.3.0"
+
+ """
+ return self.config_schema(include=include).model_json_schema()
+
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ """Return a graph representation of this `Runnable`."""
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
+
+ graph = Graph()
+ try:
+ input_node = graph.add_node(self.get_input_schema(config))
+ except TypeError:
+ input_node = graph.add_node(create_model_v2(self.get_name("Input")))
+ runnable_node = graph.add_node(
+ self, metadata=config.get("metadata") if config else None
+ )
+ try:
+ output_node = graph.add_node(self.get_output_schema(config))
+ except TypeError:
+ output_node = graph.add_node(create_model_v2(self.get_name("Output")))
+ graph.add_edge(input_node, runnable_node)
+ graph.add_edge(runnable_node, output_node)
+ return graph
+
+ def get_prompts(
+ self, config: RunnableConfig | None = None
+ ) -> list[BasePromptTemplate]:
+ """Return a list of prompts used by this `Runnable`."""
+ # Import locally to prevent circular import
+ from langchain_core.prompts.base import BasePromptTemplate # noqa: PLC0415
+
+ return [
+ node.data
+ for node in self.get_graph(config=config).nodes.values()
+ if isinstance(node.data, BasePromptTemplate)
+ ]
+
+ def __or__(
+ self,
+ other: Runnable[Any, Other]
+ | Callable[[Iterator[Any]], Iterator[Other]]
+ | Callable[[AsyncIterator[Any]], AsyncIterator[Other]]
+ | Callable[[Any], Other]
+ | Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any],
+ ) -> RunnableSerializable[Input, Other]:
+ """Runnable "or" operator.
+
+ Compose this `Runnable` with another object to create a
+ `RunnableSequence`.
+
+ Args:
+ other: Another `Runnable` or a `Runnable`-like object.
+
+ Returns:
+ A new `Runnable`.
+ """
+ return RunnableSequence(self, coerce_to_runnable(other))
+
+ def __ror__(
+ self,
+ other: Runnable[Other, Any]
+ | Callable[[Iterator[Other]], Iterator[Any]]
+ | Callable[[AsyncIterator[Other]], AsyncIterator[Any]]
+ | Callable[[Other], Any]
+ | Mapping[str, Runnable[Other, Any] | Callable[[Other], Any] | Any],
+ ) -> RunnableSerializable[Other, Output]:
+ """Runnable "reverse-or" operator.
+
+ Compose this `Runnable` with another object to create a
+ `RunnableSequence`.
+
+ Args:
+ other: Another `Runnable` or a `Runnable`-like object.
+
+ Returns:
+ A new `Runnable`.
+ """
+ return RunnableSequence(coerce_to_runnable(other), self)
+
+ def pipe(
+ self,
+ *others: Runnable[Any, Other] | Callable[[Any], Other],
+ name: str | None = None,
+ ) -> RunnableSerializable[Input, Other]:
+ """Pipe `Runnable` objects.
+
+ Compose this `Runnable` with `Runnable`-like objects to make a
+ `RunnableSequence`.
+
+ Equivalent to `RunnableSequence(self, *others)` or `self | others[0] | ...`
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ def mul_two(x: int) -> int:
+ return x * 2
+
+
+ runnable_1 = RunnableLambda(add_one)
+ runnable_2 = RunnableLambda(mul_two)
+ sequence = runnable_1.pipe(runnable_2)
+ # Or equivalently:
+ # sequence = runnable_1 | runnable_2
+ # sequence = RunnableSequence(first=runnable_1, last=runnable_2)
+ sequence.invoke(1)
+ await sequence.ainvoke(1)
+ # -> 4
+
+ sequence.batch([1, 2, 3])
+ await sequence.abatch([1, 2, 3])
+ # -> [4, 6, 8]
+ ```
+
+ Args:
+ *others: Other `Runnable` or `Runnable`-like objects to compose
+ name: An optional name for the resulting `RunnableSequence`.
+
+ Returns:
+ A new `Runnable`.
+ """
+ return RunnableSequence(self, *others, name=name)
+
+ def pick(self, keys: str | list[str]) -> RunnableSerializable[Any, Any]:
+ """Pick keys from the output `dict` of this `Runnable`.
+
+ !!! example "Pick a single key"
+
+ ```python
+ import json
+
+ from langchain_core.runnables import RunnableLambda, RunnableMap
+
+ as_str = RunnableLambda(str)
+ as_json = RunnableLambda(json.loads)
+ chain = RunnableMap(str=as_str, json=as_json)
+
+ chain.invoke("[1, 2, 3]")
+ # -> {"str": "[1, 2, 3]", "json": [1, 2, 3]}
+
+ json_only_chain = chain.pick("json")
+ json_only_chain.invoke("[1, 2, 3]")
+ # -> [1, 2, 3]
+ ```
+
+ !!! example "Pick a list of keys"
+
+ ```python
+ from typing import Any
+
+ import json
+
+ from langchain_core.runnables import RunnableLambda, RunnableMap
+
+ as_str = RunnableLambda(str)
+ as_json = RunnableLambda(json.loads)
+
+
+ def as_bytes(x: Any) -> bytes:
+ return bytes(x, "utf-8")
+
+
+ chain = RunnableMap(
+ str=as_str, json=as_json, bytes=RunnableLambda(as_bytes)
+ )
+
+ chain.invoke("[1, 2, 3]")
+ # -> {"str": "[1, 2, 3]", "json": [1, 2, 3], "bytes": b"[1, 2, 3]"}
+
+ json_and_bytes_chain = chain.pick(["json", "bytes"])
+ json_and_bytes_chain.invoke("[1, 2, 3]")
+ # -> {"json": [1, 2, 3], "bytes": b"[1, 2, 3]"}
+ ```
+
+ Args:
+ keys: A key or list of keys to pick from the output dict.
+
+ Returns:
+ a new `Runnable`.
+
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.passthrough import RunnablePick # noqa: PLC0415
+
+ return self | RunnablePick(keys)
+
+ def assign(
+ self,
+ **kwargs: Runnable[dict[str, Any], Any]
+ | Callable[[dict[str, Any]], Any]
+ | Mapping[str, Runnable[dict[str, Any], Any] | Callable[[dict[str, Any]], Any]],
+ ) -> RunnableSerializable[Any, Any]:
+ """Assigns new fields to the `dict` output of this `Runnable`.
+
+ ```python
+ from langchain_core.language_models.fake import FakeStreamingListLLM
+ from langchain_core.output_parsers import StrOutputParser
+ from langchain_core.prompts import SystemMessagePromptTemplate
+ from langchain_core.runnables import Runnable
+ from operator import itemgetter
+
+ prompt = (
+ SystemMessagePromptTemplate.from_template("You are a nice assistant.")
+ + "{question}"
+ )
+ model = FakeStreamingListLLM(responses=["foo-lish"])
+
+ chain: Runnable = prompt | model | {"str": StrOutputParser()}
+
+ chain_with_assign = chain.assign(hello=itemgetter("str") | model)
+
+ print(chain_with_assign.input_schema.model_json_schema())
+ # {'title': 'PromptInput', 'type': 'object', 'properties':
+ {'question': {'title': 'Question', 'type': 'string'}}}
+ print(chain_with_assign.output_schema.model_json_schema())
+ # {'title': 'RunnableSequenceOutput', 'type': 'object', 'properties':
+ {'str': {'title': 'Str',
+ 'type': 'string'}, 'hello': {'title': 'Hello', 'type': 'string'}}}
+ ```
+
+ Args:
+ **kwargs: A mapping of keys to `Runnable` or `Runnable`-like objects
+ that will be invoked with the entire output dict of this `Runnable`.
+
+ Returns:
+ A new `Runnable`.
+
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.passthrough import RunnableAssign # noqa: PLC0415
+
+ return self | RunnableAssign(RunnableParallel[dict[str, Any]](kwargs))
+
+ """ --- Public API --- """
+
+ @abstractmethod
+ def invoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Output:
+ """Transform a single input into an output.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: A config to use when invoking the `Runnable`.
+
+ The config supports standard keys like `'tags'`, `'metadata'` for
+ tracing purposes, `'max_concurrency'` for controlling how much work to
+ do in parallel, and other keys.
+
+ Please refer to `RunnableConfig` for more details.
+
+ Returns:
+ The output of the `Runnable`.
+ """
+
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Output:
+ """Transform a single input into an output.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: A config to use when invoking the `Runnable`.
+
+ The config supports standard keys like `'tags'`, `'metadata'` for
+ tracing purposes, `'max_concurrency'` for controlling how much work to
+ do in parallel, and other keys.
+
+ Please refer to `RunnableConfig` for more details.
+
+ Returns:
+ The output of the `Runnable`.
+ """
+ return await run_in_executor(config, self.invoke, input, config, **kwargs)
+
+ def batch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ """Default implementation runs invoke in parallel using a thread pool executor.
+
+ The default implementation of batch works well for IO bound runnables.
+
+ Subclasses must override this method if they can batch more efficiently;
+ e.g., if the underlying `Runnable` uses an API which supports a batch mode.
+
+ Args:
+ inputs: A list of inputs to the `Runnable`.
+ config: A config to use when invoking the `Runnable`. The config supports
+ standard keys like `'tags'`, `'metadata'` for
+ tracing purposes, `'max_concurrency'` for controlling how much work
+ to do in parallel, and other keys.
+
+ Please refer to `RunnableConfig` for more details.
+ return_exceptions: Whether to return exceptions instead of raising them.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Returns:
+ A list of outputs from the `Runnable`.
+ """
+ if not inputs:
+ return []
+
+ configs = get_config_list(config, len(inputs))
+
+ def invoke(input_: Input, config: RunnableConfig) -> Output | Exception:
+ if return_exceptions:
+ try:
+ return self.invoke(input_, config, **kwargs)
+ except Exception as e:
+ return e
+ else:
+ return self.invoke(input_, config, **kwargs)
+
+ # If there's only one input, don't bother with the executor
+ if len(inputs) == 1:
+ return cast("list[Output]", [invoke(inputs[0], configs[0])])
+
+ with get_executor_for_config(configs[0]) as executor:
+ return cast("list[Output]", list(executor.map(invoke, inputs, configs)))
+
+ @overload
+ def batch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[False] = False,
+ **kwargs: Any,
+ ) -> Iterator[tuple[int, Output]]: ...
+
+ @overload
+ def batch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[True],
+ **kwargs: Any,
+ ) -> Iterator[tuple[int, Output | Exception]]: ...
+
+ def batch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> Iterator[tuple[int, Output | Exception]]:
+ """Run `invoke` in parallel on a list of inputs.
+
+ Yields results as they complete.
+
+ Args:
+ inputs: A list of inputs to the `Runnable`.
+ config: A config to use when invoking the `Runnable`.
+
+ The config supports standard keys like `'tags'`, `'metadata'` for
+ tracing purposes, `'max_concurrency'` for controlling how much work to
+ do in parallel, and other keys.
+
+ Please refer to `RunnableConfig` for more details.
+ return_exceptions: Whether to return exceptions instead of raising them.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ Tuples of the index of the input and the output from the `Runnable`.
+
+ """
+ if not inputs:
+ return
+
+ configs = get_config_list(config, len(inputs))
+
+ def invoke(
+ i: int, input_: Input, config: RunnableConfig
+ ) -> tuple[int, Output | Exception]:
+ if return_exceptions:
+ try:
+ out: Output | Exception = self.invoke(input_, config, **kwargs)
+ except Exception as e:
+ out = e
+ else:
+ out = self.invoke(input_, config, **kwargs)
+
+ return (i, out)
+
+ if len(inputs) == 1:
+ yield invoke(0, inputs[0], configs[0])
+ return
+
+ with get_executor_for_config(configs[0]) as executor:
+ futures = {
+ executor.submit(invoke, i, input_, config)
+ for i, (input_, config) in enumerate(zip(inputs, configs, strict=False))
+ }
+
+ try:
+ while futures:
+ done, futures = wait(futures, return_when=FIRST_COMPLETED)
+ while done:
+ yield done.pop().result()
+ finally:
+ for future in futures:
+ future.cancel()
+
+ async def abatch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ """Default implementation runs `ainvoke` in parallel using `asyncio.gather`.
+
+ The default implementation of `batch` works well for IO bound runnables.
+
+ Subclasses must override this method if they can batch more efficiently;
+ e.g., if the underlying `Runnable` uses an API which supports a batch mode.
+
+ Args:
+ inputs: A list of inputs to the `Runnable`.
+ config: A config to use when invoking the `Runnable`.
+
+ The config supports standard keys like `'tags'`, `'metadata'` for
+ tracing purposes, `'max_concurrency'` for controlling how much work to
+ do in parallel, and other keys.
+
+ Please refer to `RunnableConfig` for more details.
+ return_exceptions: Whether to return exceptions instead of raising them.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Returns:
+ A list of outputs from the `Runnable`.
+
+ """
+ if not inputs:
+ return []
+
+ configs = get_config_list(config, len(inputs))
+
+ async def ainvoke(value: Input, config: RunnableConfig) -> Output | Exception:
+ if return_exceptions:
+ try:
+ return await self.ainvoke(value, config, **kwargs)
+ except Exception as e:
+ return e
+ else:
+ return await self.ainvoke(value, config, **kwargs)
+
+ coros = map(ainvoke, inputs, configs)
+ return await gather_with_concurrency(configs[0].get("max_concurrency"), *coros)
+
+ @overload
+ def abatch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[False] = False,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[tuple[int, Output]]: ...
+
+ @overload
+ def abatch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[True],
+ **kwargs: Any | None,
+ ) -> AsyncIterator[tuple[int, Output | Exception]]: ...
+
+ async def abatch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[tuple[int, Output | Exception]]:
+ """Run `ainvoke` in parallel on a list of inputs.
+
+ Yields results as they complete.
+
+ Args:
+ inputs: A list of inputs to the `Runnable`.
+ config: A config to use when invoking the `Runnable`.
+
+ The config supports standard keys like `'tags'`, `'metadata'` for
+ tracing purposes, `'max_concurrency'` for controlling how much work to
+ do in parallel, and other keys.
+
+ Please refer to `RunnableConfig` for more details.
+ return_exceptions: Whether to return exceptions instead of raising them.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ A tuple of the index of the input and the output from the `Runnable`.
+
+ """
+ if not inputs:
+ return
+
+ configs = get_config_list(config, len(inputs))
+ # Get max_concurrency from first config, defaulting to None (unlimited)
+ max_concurrency = configs[0].get("max_concurrency") if configs else None
+ semaphore = asyncio.Semaphore(max_concurrency) if max_concurrency else None
+
+ async def ainvoke_task(
+ i: int, input_: Input, config: RunnableConfig
+ ) -> tuple[int, Output | Exception]:
+ if return_exceptions:
+ try:
+ out: Output | Exception = await self.ainvoke(
+ input_, config, **kwargs
+ )
+ except Exception as e:
+ out = e
+ else:
+ out = await self.ainvoke(input_, config, **kwargs)
+ return (i, out)
+
+ coros = [
+ gated_coro(semaphore, ainvoke_task(i, input_, config))
+ if semaphore
+ else ainvoke_task(i, input_, config)
+ for i, (input_, config) in enumerate(zip(inputs, configs, strict=False))
+ ]
+
+ for coro in asyncio.as_completed(coros):
+ yield await coro
+
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ """Default implementation of `stream`, which calls `invoke`.
+
+ Subclasses must override this method if they support streaming output.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ The output of the `Runnable`.
+
+ """
+ yield self.invoke(input, config, **kwargs)
+
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ """Default implementation of `astream`, which calls `ainvoke`.
+
+ Subclasses must override this method if they support streaming output.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ The output of the `Runnable`.
+
+ """
+ yield await self.ainvoke(input, config, **kwargs)
+
+ @overload
+ def astream_log(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ diff: Literal[True] = True,
+ with_streamed_output_list: bool = True,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[RunLogPatch]: ...
+
+ @overload
+ def astream_log(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ diff: Literal[False],
+ with_streamed_output_list: bool = True,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[RunLog]: ...
+
+ async def astream_log(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ diff: bool = True,
+ with_streamed_output_list: bool = True,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]:
+ """Stream all output from a `Runnable`, as reported to the callback system.
+
+ This includes all inner runs of LLMs, Retrievers, Tools, etc.
+
+ Output is streamed as Log objects, which include a list of
+ Jsonpatch ops that describe how the state of the run has changed in each
+ step, and the final state of the run.
+
+ The Jsonpatch ops can be applied in order to construct state.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ diff: Whether to yield diffs between each step or the current state.
+ with_streamed_output_list: Whether to yield the `streamed_output` list.
+ include_names: Only include logs with these names.
+ include_types: Only include logs with these types.
+ include_tags: Only include logs with these tags.
+ exclude_names: Exclude logs with these names.
+ exclude_types: Exclude logs with these types.
+ exclude_tags: Exclude logs with these tags.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ A `RunLogPatch` or `RunLog` object.
+
+ """
+ warn_deprecated(
+ since="1.3.3",
+ message=("astream_log is deprecated. Use astream instead."),
+ removal="2.0.0",
+ )
+ stream = LogStreamCallbackHandler(
+ auto_close=False,
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ _schema_format="original",
+ )
+
+ # Mypy isn't resolving the overloads here
+ # Likely an issue b/c `self` is being passed through
+ # and it's can't map it to Runnable[Input,Output]?
+ async for item in _astream_log_implementation( # type: ignore[call-overload]
+ self,
+ input,
+ config,
+ diff=diff,
+ stream=stream,
+ with_streamed_output_list=with_streamed_output_list,
+ **kwargs,
+ ):
+ yield item
+
+ @overload
+ def astream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent]: ...
+
+ @overload
+ def astream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ **kwargs: Any,
+ ) -> Awaitable[Any]: ...
+
+ def astream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent] | Awaitable[Any]:
+ """Generate a stream of events.
+
+ Use to create an iterator over `StreamEvent` that provide real-time information
+ about the progress of the `Runnable`, including `StreamEvent` from intermediate
+ results.
+
+ A `StreamEvent` is a dictionary with the following schema:
+
+ - `event`: Event names are of the format:
+ `on_[runnable_type]_(start|stream|end)`.
+ - `name`: The name of the `Runnable` that generated the event.
+ - `run_id`: Randomly generated ID associated with the given execution of the
+ `Runnable` that emitted the event. A child `Runnable` that gets invoked as
+ part of the execution of a parent `Runnable` is assigned its own unique ID.
+ - `parent_ids`: The IDs of the parent runnables that generated the event. The
+ root `Runnable` will have an empty list. The order of the parent IDs is from
+ the root to the immediate parent. Only available for v2 version of the API.
+ The v1 version of the API will return an empty list.
+ - `tags`: The tags of the `Runnable` that generated the event.
+ - `metadata`: The metadata of the `Runnable` that generated the event.
+ - `data`: The data associated with the event. The contents of this field
+ depend on the type of event. See the table below for more details.
+
+ Below is a table that illustrates some events that might be emitted by various
+ chains. Metadata fields have been omitted from the table for brevity.
+ Chain definitions have been included after the table.
+
+ !!! note
+ This reference table is for the v2 version of the schema.
+
+ | event | name | chunk | input | output |
+ | ---------------------- | -------------------- | ----------------------------------- | ------------------------------------------------- | --------------------------------------------------- |
+ | `on_chat_model_start` | `'[model name]'` | | `{"messages": [[SystemMessage, HumanMessage]]}` | |
+ | `on_chat_model_stream` | `'[model name]'` | `AIMessageChunk(content="hello")` | | |
+ | `on_chat_model_end` | `'[model name]'` | | `{"messages": [[SystemMessage, HumanMessage]]}` | `AIMessageChunk(content="hello world")` |
+ | `on_llm_start` | `'[model name]'` | | `{'input': 'hello'}` | |
+ | `on_llm_stream` | `'[model name]'` | `'Hello' ` | | |
+ | `on_llm_end` | `'[model name]'` | | `'Hello human!'` | |
+ | `on_chain_start` | `'format_docs'` | | | |
+ | `on_chain_stream` | `'format_docs'` | `'hello world!, goodbye world!'` | | |
+ | `on_chain_end` | `'format_docs'` | | `[Document(...)]` | `'hello world!, goodbye world!'` |
+ | `on_tool_start` | `'some_tool'` | | `{"x": 1, "y": "2"}` | |
+ | `on_tool_end` | `'some_tool'` | | | `{"x": 1, "y": "2"}` |
+ | `on_retriever_start` | `'[retriever name]'` | | `{"query": "hello"}` | |
+ | `on_retriever_end` | `'[retriever name]'` | | `{"query": "hello"}` | `[Document(...), ..]` |
+ | `on_prompt_start` | `'[template_name]'` | | `{"question": "hello"}` | |
+ | `on_prompt_end` | `'[template_name]'` | | `{"question": "hello"}` | `ChatPromptValue(messages: [SystemMessage, ...])` |
+
+ In addition to the standard events, users can also dispatch custom events (see example below).
+
+ Custom events will be only be surfaced with in the v2 version of the API!
+
+ A custom event has following format:
+
+ | Attribute | Type | Description |
+ | ----------- | ------ | --------------------------------------------------------------------------------------------------------- |
+ | `name` | `str` | A user defined name for the event. |
+ | `data` | `Any` | The data associated with the event. This can be anything, though we suggest making it JSON serializable. |
+
+ Here are declarations associated with the standard events shown above:
+
+ `format_docs`:
+
+ ```python
+ def format_docs(docs: list[Document]) -> str:
+ '''Format the docs.'''
+ return ", ".join([doc.page_content for doc in docs])
+
+
+ format_docs = RunnableLambda(format_docs)
+ ```
+
+ `some_tool`:
+
+ ```python
+ @tool
+ def some_tool(x: int, y: str) -> dict:
+ '''Some_tool.'''
+ return {"x": x, "y": y}
+ ```
+
+ `prompt`:
+
+ ```python
+ template = ChatPromptTemplate.from_messages(
+ [
+ ("system", "You are Cat Agent 007"),
+ ("human", "{question}"),
+ ]
+ ).with_config({"run_name": "my_template", "tags": ["my_template"]})
+ ```
+
+ !!! example
+
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ async def reverse(s: str) -> str:
+ return s[::-1]
+
+
+ chain = RunnableLambda(func=reverse)
+
+ events = [
+ event async for event in chain.astream_events("hello", version="v2")
+ ]
+
+ # Will produce the following events
+ # (run_id, and parent_ids has been omitted for brevity):
+ [
+ {
+ "data": {"input": "hello"},
+ "event": "on_chain_start",
+ "metadata": {},
+ "name": "reverse",
+ "tags": [],
+ },
+ {
+ "data": {"chunk": "olleh"},
+ "event": "on_chain_stream",
+ "metadata": {},
+ "name": "reverse",
+ "tags": [],
+ },
+ {
+ "data": {"output": "olleh"},
+ "event": "on_chain_end",
+ "metadata": {},
+ "name": "reverse",
+ "tags": [],
+ },
+ ]
+ ```
+
+ ```python title="Dispatch custom event"
+ from langchain_core.callbacks.manager import (
+ adispatch_custom_event,
+ )
+ from langchain_core.runnables import RunnableLambda, RunnableConfig
+ import asyncio
+
+
+ async def slow_thing(some_input: str, config: RunnableConfig) -> str:
+ \"\"\"Do something that takes a long time.\"\"\"
+ await asyncio.sleep(1) # Placeholder for some slow operation
+ await adispatch_custom_event(
+ "progress_event",
+ {"message": "Finished step 1 of 3"},
+ config=config # Must be included for python < 3.10
+ )
+ await asyncio.sleep(1) # Placeholder for some slow operation
+ await adispatch_custom_event(
+ "progress_event",
+ {"message": "Finished step 2 of 3"},
+ config=config # Must be included for python < 3.10
+ )
+ await asyncio.sleep(1) # Placeholder for some slow operation
+ return "Done"
+
+ slow_thing = RunnableLambda(slow_thing)
+
+ async for event in slow_thing.astream_events("some_input", version="v2"):
+ print(event)
+ ```
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ version: The version of the schema to use. One of `'v1'`, `'v2'`,
+ or `'v3'`.
+
+ Most callers should use `'v2'` (the default), which yields
+ `StreamEvent` dicts and supports custom events.
+
+ `'v3'` selects the typed, content-block-centric streaming
+ protocol and is only supported on `Runnable` subclasses that
+ implement it (currently `BaseChatModel` and
+ `langgraph.CompiledGraph`); on a generic `Runnable` it raises
+ `NotImplementedError`. The `'v3'` API is in beta and may
+ change. See the subclass override (e.g.
+ `BaseChatModel.astream_events`) for the v3 return shape.
+
+ `'v1'` is retained for backwards compatibility and will be
+ deprecated in `0.4.0`. Custom events are only surfaced in
+ `'v2'` / `'v3'`.
+ include_names: Only include events from `Runnable` objects with matching names.
+ include_types: Only include events from `Runnable` objects with matching types.
+ include_tags: Only include events from `Runnable` objects with matching tags.
+ exclude_names: Exclude events from `Runnable` objects with matching names.
+ exclude_types: Exclude events from `Runnable` objects with matching types.
+ exclude_tags: Exclude events from `Runnable` objects with matching tags.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ An async stream of `StreamEvent`.
+
+ Raises:
+ NotImplementedError: If the version is not `'v1'`, `'v2'`, or `'v3'`, or
+ if `'v3'` is requested on a `Runnable` that does not implement the v3
+ streaming protocol.
+
+ """ # noqa: E501
+ if version == "v3":
+ return self._astream_events_v3_unsupported()
+ return self._astream_events_v1_v2(
+ input,
+ config=config,
+ version=version,
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ **kwargs,
+ )
+
+ async def _astream_events_v3_unsupported(self) -> Any:
+ """Coroutine that raises when v3 isn't implemented on this Runnable.
+
+ Lets the public `astream_events(version="v3")` return an awaitable
+ whose error surfaces on `await`, matching the v3 contract on
+ subclasses that do implement the protocol.
+ """
+ msg = (
+ "astream_events(version='v3') is only supported on Runnable "
+ "subclasses that implement the v3 streaming protocol "
+ "(BaseChatModel, CompiledGraph). "
+ f"Got: {type(self).__name__}"
+ )
+ raise NotImplementedError(msg)
+
+ async def _astream_events_v1_v2(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent]:
+ if version == "v2":
+ event_stream = _astream_events_implementation_v2(
+ self,
+ input,
+ config=config,
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ **kwargs,
+ )
+ elif version == "v1":
+ warn_deprecated(
+ since="1.3.3",
+ message=(
+ "astream_events version='v1' is deprecated. "
+ "Use version='v2' or astream instead."
+ ),
+ removal="2.0.0",
+ )
+ # First implementation, built on top of astream_log API
+ # This implementation will be deprecated as of 0.2.0
+ event_stream = _astream_events_implementation_v1(
+ self,
+ input,
+ config=config,
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ **kwargs,
+ )
+ else:
+ msg = f"Unsupported version: {version!r}. Expected 'v1', 'v2', or 'v3'."
+ raise NotImplementedError(msg)
+
+ async with aclosing(event_stream):
+ async for event in event_stream:
+ yield event
+
+ @overload
+ def stream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent]: ...
+
+ @overload
+ def stream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ **kwargs: Any,
+ ) -> Iterator[Any]: ...
+
+ def stream_events(
+ self,
+ input: Any,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent] | Iterator[Any]:
+ """Generate a stream of events synchronously.
+
+ Synchronous counterpart to `astream_events`. For `version='v3'`, subclasses
+ that implement the v3 streaming protocol (`BaseChatModel`, `CompiledGraph`)
+ override this method. All other versions and base-class calls raise
+ `NotImplementedError`.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ version: The version of the schema to use. `'v3'` requires a subclass
+ that implements the v3 streaming protocol. `'v1'` and `'v2'` are not
+ supported on the sync path.
+ include_names: Only include events from `Runnable` objects with matching
+ names.
+ include_types: Only include events from `Runnable` objects with matching
+ types.
+ include_tags: Only include events from `Runnable` objects with matching
+ tags.
+ exclude_names: Exclude events from `Runnable` objects with matching names.
+ exclude_types: Exclude events from `Runnable` objects with matching types.
+ exclude_tags: Exclude events from `Runnable` objects with matching tags.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Raises:
+ NotImplementedError: Always. Subclasses override this method for supported
+ versions.
+
+ """
+ # Base impl always raises; consume args so they don't trip ARG002.
+ del input, config, include_names, include_types, include_tags
+ del exclude_names, exclude_types, exclude_tags, kwargs
+ if version == "v3":
+ msg = (
+ "stream_events(version='v3') is only supported on Runnable subclasses "
+ "that implement the v3 streaming protocol "
+ "(BaseChatModel, CompiledGraph). "
+ f"Got: {type(self).__name__}"
+ )
+ raise NotImplementedError(msg)
+ msg = (
+ f"stream_events(version={version!r}) is not supported. "
+ "Use astream_events() for v1/v2, or stream_events(version='v3') "
+ "on a supported subclass."
+ )
+ raise NotImplementedError(msg)
+
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ """Transform inputs to outputs.
+
+ Default implementation of transform, which buffers input and calls `astream`.
+
+ Subclasses must override this method if they can start producing output while
+ input is still being generated.
+
+ Args:
+ input: An iterator of inputs to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ The output of the `Runnable`.
+
+ """
+ final: Input
+ got_first_val = False
+
+ for ichunk in input:
+ # The default implementation of transform is to buffer input and
+ # then call stream.
+ # It'll attempt to gather all input into a single chunk using
+ # the `+` operator.
+ # If the input is not addable, then we'll assume that we can
+ # only operate on the last chunk,
+ # and we'll iterate until we get to the last chunk.
+ if not got_first_val:
+ final = ichunk
+ got_first_val = True
+ else:
+ try:
+ final = final + ichunk # type: ignore[operator]
+ except TypeError:
+ final = ichunk
+
+ if got_first_val:
+ yield from self.stream(final, config, **kwargs)
+
+ async def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ """Transform inputs to outputs.
+
+ Default implementation of atransform, which buffers input and calls `astream`.
+
+ Subclasses must override this method if they can start producing output while
+ input is still being generated.
+
+ Args:
+ input: An async iterator of inputs to the `Runnable`.
+ config: The config to use for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ The output of the `Runnable`.
+
+ """
+ final: Input
+ got_first_val = False
+
+ async for ichunk in input:
+ # The default implementation of transform is to buffer input and
+ # then call stream.
+ # It'll attempt to gather all input into a single chunk using
+ # the `+` operator.
+ # If the input is not addable, then we'll assume that we can
+ # only operate on the last chunk,
+ # and we'll iterate until we get to the last chunk.
+ if not got_first_val:
+ final = ichunk
+ got_first_val = True
+ else:
+ try:
+ final = final + ichunk # type: ignore[operator]
+ except TypeError:
+ final = ichunk
+
+ if got_first_val:
+ async for output in self.astream(final, config, **kwargs):
+ yield output
+
+ def bind(self, **kwargs: Any) -> Runnable[Input, Output]:
+ """Bind arguments to a `Runnable`, returning a new `Runnable`.
+
+ Useful when a `Runnable` in a chain requires an argument that is not
+ in the output of the previous `Runnable` or included in the user input.
+
+ Args:
+ **kwargs: The arguments to bind to the `Runnable`.
+
+ Returns:
+ A new `Runnable` with the arguments bound.
+
+ Example:
+ ```python
+ from langchain_ollama import ChatOllama
+ from langchain_core.output_parsers import StrOutputParser
+
+ model = ChatOllama(model="llama3.1")
+
+ # Without bind
+ chain = model | StrOutputParser()
+
+ chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
+ # Output is 'One two three four five.'
+
+ # With bind
+ chain = model.bind(stop=["three"]) | StrOutputParser()
+
+ chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
+ # Output is 'One two'
+ ```
+ """
+ return RunnableBinding(bound=self, kwargs=kwargs, config={})
+
+ def with_config(
+ self,
+ config: RunnableConfig | None = None,
+ # Sadly Unpack is not well-supported by mypy so this will have to be untyped
+ **kwargs: Any,
+ ) -> Runnable[Input, Output]:
+ """Bind config to a `Runnable`, returning a new `Runnable`.
+
+ Args:
+ config: The config to bind to the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Returns:
+ A new `Runnable` with the config bound.
+
+ """
+ return RunnableBinding(
+ bound=self,
+ config=cast(
+ "RunnableConfig",
+ {**(config or {}), **kwargs},
+ ),
+ kwargs={},
+ )
+
+ def with_listeners(
+ self,
+ *,
+ on_start: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ on_end: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ on_error: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ ) -> Runnable[Input, Output]:
+ """Bind lifecycle listeners to a `Runnable`, returning a new `Runnable`.
+
+ The Run object contains information about the run, including its `id`,
+ `type`, `input`, `output`, `error`, `start_time`, `end_time`, and
+ any tags or metadata added to the run.
+
+ Args:
+ on_start: Called before the `Runnable` starts running, with the `Run`
+ object.
+ on_end: Called after the `Runnable` finishes running, with the `Run`
+ object.
+ on_error: Called if the `Runnable` throws an error, with the `Run`
+ object.
+
+ Returns:
+ A new `Runnable` with the listeners bound.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+ from langchain_core.tracers.schemas import Run
+
+ import time
+
+
+ def test_runnable(time_to_sleep: int):
+ time.sleep(time_to_sleep)
+
+
+ def fn_start(run_obj: Run):
+ print("start_time:", run_obj.start_time)
+
+
+ def fn_end(run_obj: Run):
+ print("end_time:", run_obj.end_time)
+
+
+ chain = RunnableLambda(test_runnable).with_listeners(
+ on_start=fn_start, on_end=fn_end
+ )
+ chain.invoke(2)
+ ```
+ """
+ return RunnableBinding(
+ bound=self,
+ config_factories=[
+ lambda config: {
+ "callbacks": [
+ RootListenersTracer(
+ config=config,
+ on_start=on_start,
+ on_end=on_end,
+ on_error=on_error,
+ )
+ ],
+ }
+ ],
+ )
+
+ def with_alisteners(
+ self,
+ *,
+ on_start: AsyncListener | None = None,
+ on_end: AsyncListener | None = None,
+ on_error: AsyncListener | None = None,
+ ) -> Runnable[Input, Output]:
+ """Bind async lifecycle listeners to a `Runnable`.
+
+ Returns a new `Runnable`.
+
+ The Run object contains information about the run, including its `id`,
+ `type`, `input`, `output`, `error`, `start_time`, `end_time`, and
+ any tags or metadata added to the run.
+
+ Args:
+ on_start: Called asynchronously before the `Runnable` starts running,
+ with the `Run` object.
+ on_end: Called asynchronously after the `Runnable` finishes running,
+ with the `Run` object.
+ on_error: Called asynchronously if the `Runnable` throws an error,
+ with the `Run` object.
+
+ Returns:
+ A new `Runnable` with the listeners bound.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda, Runnable
+ from datetime import datetime, timezone
+ import time
+ import asyncio
+
+
+ def format_t(timestamp: float) -> str:
+ return datetime.fromtimestamp(timestamp, tz=timezone.utc).isoformat()
+
+
+ async def test_runnable(time_to_sleep: int):
+ print(f"Runnable[{time_to_sleep}s]: starts at {format_t(time.time())}")
+ await asyncio.sleep(time_to_sleep)
+ print(f"Runnable[{time_to_sleep}s]: ends at {format_t(time.time())}")
+
+
+ async def fn_start(run_obj: Runnable):
+ print(f"on start callback starts at {format_t(time.time())}")
+ await asyncio.sleep(3)
+ print(f"on start callback ends at {format_t(time.time())}")
+
+
+ async def fn_end(run_obj: Runnable):
+ print(f"on end callback starts at {format_t(time.time())}")
+ await asyncio.sleep(2)
+ print(f"on end callback ends at {format_t(time.time())}")
+
+
+ runnable = RunnableLambda(test_runnable).with_alisteners(
+ on_start=fn_start, on_end=fn_end
+ )
+
+
+ async def concurrent_runs():
+ await asyncio.gather(runnable.ainvoke(2), runnable.ainvoke(3))
+
+
+ asyncio.run(concurrent_runs())
+ # Result:
+ # on start callback starts at 2025-03-01T07:05:22.875378+00:00
+ # on start callback starts at 2025-03-01T07:05:22.875495+00:00
+ # on start callback ends at 2025-03-01T07:05:25.878862+00:00
+ # on start callback ends at 2025-03-01T07:05:25.878947+00:00
+ # Runnable[2s]: starts at 2025-03-01T07:05:25.879392+00:00
+ # Runnable[3s]: starts at 2025-03-01T07:05:25.879804+00:00
+ # Runnable[2s]: ends at 2025-03-01T07:05:27.881998+00:00
+ # on end callback starts at 2025-03-01T07:05:27.882360+00:00
+ # Runnable[3s]: ends at 2025-03-01T07:05:28.881737+00:00
+ # on end callback starts at 2025-03-01T07:05:28.882428+00:00
+ # on end callback ends at 2025-03-01T07:05:29.883893+00:00
+ # on end callback ends at 2025-03-01T07:05:30.884831+00:00
+ ```
+ """
+ return RunnableBinding(
+ bound=self,
+ config_factories=[
+ lambda config: {
+ "callbacks": [
+ AsyncRootListenersTracer(
+ config=config,
+ on_start=on_start,
+ on_end=on_end,
+ on_error=on_error,
+ )
+ ],
+ }
+ ],
+ )
+
+ def with_types(
+ self,
+ *,
+ input_type: type[Input] | None = None,
+ output_type: type[Output] | None = None,
+ ) -> Runnable[Input, Output]:
+ """Bind input and output types to a `Runnable`, returning a new `Runnable`.
+
+ Args:
+ input_type: The input type to bind to the `Runnable`.
+ output_type: The output type to bind to the `Runnable`.
+
+ Returns:
+ A new `Runnable` with the types bound.
+ """
+ return RunnableBinding(
+ bound=self,
+ custom_input_type=input_type,
+ custom_output_type=output_type,
+ kwargs={},
+ )
+
+ def with_retry(
+ self,
+ *,
+ retry_if_exception_type: tuple[type[BaseException], ...] = (Exception,),
+ wait_exponential_jitter: bool = True,
+ exponential_jitter_params: ExponentialJitterParams | None = None,
+ stop_after_attempt: int = 3,
+ ) -> Runnable[Input, Output]:
+ """Create a new `Runnable` that retries the original `Runnable` on exceptions.
+
+ Args:
+ retry_if_exception_type: A tuple of exception types to retry on.
+ wait_exponential_jitter: Whether to add jitter to the wait
+ time between retries.
+ stop_after_attempt: The maximum number of attempts to make before
+ giving up.
+ exponential_jitter_params: Parameters for
+ `tenacity.wait_exponential_jitter`. Namely: `initial`, `max`,
+ `exp_base`, and `jitter` (all `float` values).
+
+ Returns:
+ A new `Runnable` that retries the original `Runnable` on exceptions.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+ count = 0
+
+
+ def _lambda(x: int) -> None:
+ global count
+ count = count + 1
+ if x == 1:
+ raise ValueError("x is 1")
+ else:
+ pass
+
+
+ runnable = RunnableLambda(_lambda)
+ try:
+ runnable.with_retry(
+ stop_after_attempt=2,
+ retry_if_exception_type=(ValueError,),
+ ).invoke(1)
+ except ValueError:
+ pass
+
+ assert count == 2
+ ```
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.retry import RunnableRetry # noqa: PLC0415
+
+ return RunnableRetry(
+ bound=self,
+ kwargs={},
+ config={},
+ retry_exception_types=retry_if_exception_type,
+ wait_exponential_jitter=wait_exponential_jitter,
+ max_attempt_number=stop_after_attempt,
+ exponential_jitter_params=exponential_jitter_params,
+ )
+
+ def map(self) -> Runnable[list[Input], list[Output]]:
+ """Return a new `Runnable` that maps a list of inputs to a list of outputs.
+
+ Calls `invoke` with each input.
+
+ Returns:
+ A new `Runnable` that maps a list of inputs to a list of outputs.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def _lambda(x: int) -> int:
+ return x + 1
+
+
+ runnable = RunnableLambda(_lambda)
+ print(runnable.map().invoke([1, 2, 3])) # [2, 3, 4]
+ ```
+ """
+ return RunnableEach(bound=self)
+
+ def with_fallbacks(
+ self,
+ fallbacks: Sequence[Runnable[Input, Output]],
+ *,
+ exceptions_to_handle: tuple[type[BaseException], ...] = (Exception,),
+ exception_key: str | None = None,
+ ) -> RunnableWithFallbacksT[Input, Output]:
+ """Add fallbacks to a `Runnable`, returning a new `Runnable`.
+
+ The new `Runnable` will try the original `Runnable`, and then each fallback
+ in order, upon failures.
+
+ Args:
+ fallbacks: A sequence of runnables to try if the original `Runnable`
+ fails.
+ exceptions_to_handle: A tuple of exception types to handle.
+ exception_key: If `string` is specified then handled exceptions will be
+ passed to fallbacks as part of the input under the specified key.
+
+ If `None`, exceptions will not be passed to fallbacks.
+
+ If used, the base `Runnable` and its fallbacks must accept a
+ dictionary as input.
+
+ Returns:
+ A new `Runnable` that will try the original `Runnable`, and then each
+ Fallback in order, upon failures.
+
+ Example:
+ ```python
+ from typing import Iterator
+
+ from langchain_core.runnables import RunnableGenerator
+
+
+ def _generate_immediate_error(input: Iterator) -> Iterator[str]:
+ raise ValueError()
+ yield ""
+
+
+ def _generate(input: Iterator) -> Iterator[str]:
+ yield from "foo bar"
+
+
+ runnable = RunnableGenerator(_generate_immediate_error).with_fallbacks(
+ [RunnableGenerator(_generate)]
+ )
+ print("".join(runnable.stream({}))) # foo bar
+ ```
+
+ Args:
+ fallbacks: A sequence of runnables to try if the original `Runnable`
+ fails.
+ exceptions_to_handle: A tuple of exception types to handle.
+ exception_key: If `string` is specified then handled exceptions will be
+ passed to fallbacks as part of the input under the specified key.
+
+ If `None`, exceptions will not be passed to fallbacks.
+
+ If used, the base `Runnable` and its fallbacks must accept a
+ dictionary as input.
+
+ Returns:
+ A new `Runnable` that will try the original `Runnable`, and then each
+ Fallback in order, upon failures.
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.fallbacks import ( # noqa: PLC0415
+ RunnableWithFallbacks,
+ )
+
+ return RunnableWithFallbacks(
+ runnable=self,
+ fallbacks=fallbacks,
+ exceptions_to_handle=exceptions_to_handle,
+ exception_key=exception_key,
+ )
+
+ """ --- Helper methods for Subclasses --- """
+
+ def _call_with_config(
+ self,
+ func: Callable[[Input], Output]
+ | Callable[[Input, CallbackManagerForChainRun], Output]
+ | Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output],
+ input_: Input,
+ config: RunnableConfig | None,
+ run_type: str | None = None,
+ serialized: dict[str, Any] | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ """Call with config.
+
+ Helper method to transform an `Input` value to an `Output` value,
+ with callbacks.
+
+ Use this method to implement `invoke` in subclasses.
+
+ """
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ run_manager = callback_manager.on_chain_start(
+ serialized,
+ input_,
+ run_type=run_type,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ try:
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ output = cast(
+ "Output",
+ context.run(
+ call_func_with_variable_args, # type: ignore[arg-type]
+ func,
+ input_,
+ config,
+ run_manager,
+ **kwargs,
+ ),
+ )
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ run_manager.on_chain_end(output)
+ return output
+
+ async def _acall_with_config(
+ self,
+ func: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ],
+ input_: Input,
+ config: RunnableConfig | None,
+ run_type: str | None = None,
+ serialized: dict[str, Any] | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ """Async call with config.
+
+ Helper method to transform an `Input` value to an `Output` value,
+ with callbacks.
+
+ Use this method to implement `ainvoke` in subclasses.
+ """
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ run_manager = await callback_manager.on_chain_start(
+ serialized,
+ input_,
+ run_type=run_type,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ try:
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ coro = acall_func_with_variable_args(
+ func, input_, config, run_manager, **kwargs
+ )
+ output: Output = await coro_with_context(coro, context)
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ await run_manager.on_chain_end(output)
+ return output
+
+ def _batch_with_config(
+ self,
+ func: Callable[[list[Input]], list[Exception | Output]]
+ | Callable[
+ [list[Input], list[CallbackManagerForChainRun]], list[Exception | Output]
+ ]
+ | Callable[
+ [list[Input], list[CallbackManagerForChainRun], list[RunnableConfig]],
+ list[Exception | Output],
+ ],
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ run_type: str | None = None,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ """Transform a list of inputs to a list of outputs, with callbacks.
+
+ Helper method to transform an `Input` value to an `Output` value,
+ with callbacks. Use this method to implement `invoke` in subclasses.
+
+ """
+ if not inputs:
+ return []
+
+ configs = get_config_list(config, len(inputs))
+ callback_managers = [get_callback_manager_for_config(c) for c in configs]
+ run_managers = [
+ callback_manager.on_chain_start(
+ None,
+ input_,
+ run_type=run_type,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ for callback_manager, input_, config in zip(
+ callback_managers, inputs, configs, strict=False
+ )
+ ]
+ try:
+ if accepts_config(func):
+ kwargs["config"] = [
+ patch_config(c, callbacks=rm.get_child())
+ for c, rm in zip(configs, run_managers, strict=False)
+ ]
+ if accepts_run_manager(func):
+ kwargs["run_manager"] = run_managers
+ output = func(inputs, **kwargs) # type: ignore[call-arg]
+ except BaseException as e:
+ for run_manager in run_managers:
+ run_manager.on_chain_error(e)
+ if return_exceptions:
+ return cast("list[Output]", [e for _ in inputs])
+ raise
+ else:
+ first_exception: Exception | None = None
+ for run_manager, out in zip(run_managers, output, strict=False):
+ if isinstance(out, Exception):
+ first_exception = first_exception or out
+ run_manager.on_chain_error(out)
+ else:
+ run_manager.on_chain_end(out)
+ if return_exceptions or first_exception is None:
+ return cast("list[Output]", output)
+ raise first_exception
+
+ async def _abatch_with_config(
+ self,
+ func: Callable[[list[Input]], Awaitable[list[Exception | Output]]]
+ | Callable[
+ [list[Input], list[AsyncCallbackManagerForChainRun]],
+ Awaitable[list[Exception | Output]],
+ ]
+ | Callable[
+ [list[Input], list[AsyncCallbackManagerForChainRun], list[RunnableConfig]],
+ Awaitable[list[Exception | Output]],
+ ],
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ run_type: str | None = None,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ """Transform a list of inputs to a list of outputs, with callbacks.
+
+ Helper method to transform an `Input` value to an `Output` value,
+ with callbacks.
+
+ Use this method to implement `invoke` in subclasses.
+
+ """
+ if not inputs:
+ return []
+
+ configs = get_config_list(config, len(inputs))
+ callback_managers = [get_async_callback_manager_for_config(c) for c in configs]
+ run_managers: list[AsyncCallbackManagerForChainRun] = await asyncio.gather(
+ *(
+ callback_manager.on_chain_start(
+ None,
+ input_,
+ run_type=run_type,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ for callback_manager, input_, config in zip(
+ callback_managers, inputs, configs, strict=False
+ )
+ )
+ )
+ try:
+ if accepts_config(func):
+ kwargs["config"] = [
+ patch_config(c, callbacks=rm.get_child())
+ for c, rm in zip(configs, run_managers, strict=False)
+ ]
+ if accepts_run_manager(func):
+ kwargs["run_manager"] = run_managers
+ output = await func(inputs, **kwargs) # type: ignore[call-arg]
+ except BaseException as e:
+ await asyncio.gather(
+ *(run_manager.on_chain_error(e) for run_manager in run_managers)
+ )
+ if return_exceptions:
+ return cast("list[Output]", [e for _ in inputs])
+ raise
+ else:
+ first_exception: Exception | None = None
+ coros: list[Awaitable[None]] = []
+ for run_manager, out in zip(run_managers, output, strict=False):
+ if isinstance(out, Exception):
+ first_exception = first_exception or out
+ coros.append(run_manager.on_chain_error(out))
+ else:
+ coros.append(run_manager.on_chain_end(out))
+ await asyncio.gather(*coros)
+ if return_exceptions or first_exception is None:
+ return cast("list[Output]", output)
+ raise first_exception
+
+ def _transform_stream_with_config(
+ self,
+ inputs: Iterator[Input],
+ transformer: Callable[[Iterator[Input]], Iterator[Output]]
+ | Callable[[Iterator[Input], CallbackManagerForChainRun], Iterator[Output]]
+ | Callable[
+ [Iterator[Input], CallbackManagerForChainRun, RunnableConfig],
+ Iterator[Output],
+ ],
+ config: RunnableConfig | None,
+ run_type: str | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ """Transform a stream with config.
+
+ Helper method to transform an `Iterator` of `Input` values into an
+ `Iterator` of `Output` values, with callbacks.
+
+ Use this to implement `stream` or `transform` in `Runnable` subclasses.
+
+ """
+ # Extract defers_inputs from kwargs if present
+ defers_inputs = kwargs.pop("defers_inputs", False)
+
+ # tee the input so we can iterate over it twice
+ input_for_tracing, input_for_transform = tee(inputs, 2)
+ # Start the input iterator to ensure the input Runnable starts before this one
+ final_input: Input | None = next(input_for_tracing, None)
+ final_input_supported = True
+ final_output: Output | None = None
+ final_output_supported = True
+
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ run_manager = callback_manager.on_chain_start(
+ None,
+ {"input": ""},
+ run_type=run_type,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ defers_inputs=defers_inputs,
+ )
+ try:
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ if accepts_config(transformer):
+ kwargs["config"] = child_config
+ if accepts_run_manager(transformer):
+ kwargs["run_manager"] = run_manager
+ with set_config_context(child_config) as context:
+ iterator = context.run(transformer, input_for_transform, **kwargs) # type: ignore[arg-type]
+ if stream_handler := next(
+ (
+ cast("_StreamingCallbackHandler", h)
+ for h in run_manager.handlers
+ # instance check OK here, it's a mixin
+ if isinstance(h, _StreamingCallbackHandler)
+ ),
+ None,
+ ):
+ # populates streamed_output in astream_log() output if needed
+ iterator = stream_handler.tap_output_iter(
+ run_manager.run_id, iterator
+ )
+ try:
+ while True:
+ chunk: Output = context.run(next, iterator)
+ yield chunk
+ if final_output_supported:
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk # type: ignore[operator]
+ except TypeError:
+ final_output = chunk
+ final_output_supported = False
+ else:
+ final_output = chunk
+ except (StopIteration, GeneratorExit):
+ pass
+ for ichunk in input_for_tracing:
+ if final_input_supported:
+ if final_input is None:
+ final_input = ichunk
+ else:
+ try:
+ final_input = final_input + ichunk # type: ignore[operator]
+ except TypeError:
+ final_input = ichunk
+ final_input_supported = False
+ else:
+ final_input = ichunk
+ except BaseException as e:
+ run_manager.on_chain_error(e, inputs=final_input)
+ raise
+ else:
+ run_manager.on_chain_end(final_output, inputs=final_input)
+
+ async def _atransform_stream_with_config(
+ self,
+ inputs: AsyncIterator[Input],
+ transformer: Callable[[AsyncIterator[Input]], AsyncIterator[Output]]
+ | Callable[
+ [AsyncIterator[Input], AsyncCallbackManagerForChainRun],
+ AsyncIterator[Output],
+ ]
+ | Callable[
+ [AsyncIterator[Input], AsyncCallbackManagerForChainRun, RunnableConfig],
+ AsyncIterator[Output],
+ ],
+ config: RunnableConfig | None,
+ run_type: str | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ """Transform a stream with config.
+
+ Helper method to transform an Async `Iterator` of `Input` values into an
+ Async `Iterator` of `Output` values, with callbacks.
+
+ Use this to implement `astream` or `atransform` in `Runnable` subclasses.
+
+ """
+ # Extract defers_inputs from kwargs if present
+ defers_inputs = kwargs.pop("defers_inputs", False)
+
+ # tee the input so we can iterate over it twice
+ input_for_tracing, input_for_transform = atee(inputs, 2)
+ # Start the input iterator to ensure the input Runnable starts before this one
+ final_input: Input | None = await anext(input_for_tracing, None)
+ final_input_supported = True
+ final_output: Output | None = None
+ final_output_supported = True
+
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ {"input": ""},
+ run_type=run_type,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ defers_inputs=defers_inputs,
+ )
+ try:
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ if accepts_config(transformer):
+ kwargs["config"] = child_config
+ if accepts_run_manager(transformer):
+ kwargs["run_manager"] = run_manager
+ with set_config_context(child_config) as context:
+ iterator_ = context.run(transformer, input_for_transform, **kwargs) # type: ignore[arg-type]
+
+ if stream_handler := next(
+ (
+ cast("_StreamingCallbackHandler", h)
+ for h in run_manager.handlers
+ # instance check OK here, it's a mixin
+ if isinstance(h, _StreamingCallbackHandler)
+ ),
+ None,
+ ):
+ # populates streamed_output in astream_log() output if needed
+ iterator = stream_handler.tap_output_aiter(
+ run_manager.run_id, iterator_
+ )
+ else:
+ iterator = iterator_
+ try:
+ while True:
+ chunk = await coro_with_context(anext(iterator), context)
+ yield chunk
+ if final_output_supported:
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk
+ except TypeError:
+ final_output = chunk
+ final_output_supported = False
+ else:
+ final_output = chunk
+ except StopAsyncIteration:
+ pass
+ async for ichunk in input_for_tracing:
+ if final_input_supported:
+ if final_input is None:
+ final_input = ichunk
+ else:
+ try:
+ final_input = final_input + ichunk # type: ignore[operator]
+ except TypeError:
+ final_input = ichunk
+ final_input_supported = False
+ else:
+ final_input = ichunk
+ except BaseException as e:
+ await run_manager.on_chain_error(e, inputs=final_input)
+ raise
+ else:
+ await run_manager.on_chain_end(final_output, inputs=final_input)
+ finally:
+ if iterator_ is not None and hasattr(iterator_, "aclose"):
+ await iterator_.aclose()
+
+ @beta_decorator.beta(message="This API is in beta and may change in the future.")
+ def as_tool(
+ self,
+ args_schema: type[BaseModel] | None = None,
+ *,
+ name: str | None = None,
+ description: str | None = None,
+ arg_types: dict[str, type] | None = None,
+ ) -> BaseTool:
+ """Create a `BaseTool` from a `Runnable`.
+
+ `as_tool` will instantiate a `BaseTool` with a name, description, and
+ `args_schema` from a `Runnable`. Where possible, schemas are inferred
+ from `runnable.get_input_schema`.
+
+ Alternatively (e.g., if the `Runnable` takes a dict as input and the specific
+ `dict` keys are not typed), the schema can be specified directly with
+ `args_schema`.
+
+ You can also pass `arg_types` to just specify the required arguments and their
+ types.
+
+ Args:
+ args_schema: The schema for the tool.
+ name: The name of the tool.
+ description: The description of the tool.
+ arg_types: A dictionary of argument names to types.
+
+ Returns:
+ A `BaseTool` instance.
+
+ !!! example "`TypedDict` input"
+
+ ```python
+ from typing_extensions import TypedDict
+ from langchain_core.runnables import RunnableLambda
+
+
+ class Args(TypedDict):
+ a: int
+ b: list[int]
+
+
+ def f(x: Args) -> str:
+ return str(x["a"] * max(x["b"]))
+
+
+ runnable = RunnableLambda(f)
+ as_tool = runnable.as_tool()
+ as_tool.invoke({"a": 3, "b": [1, 2]})
+ ```
+
+ !!! example "`dict` input, specifying schema via `args_schema`"
+
+ ```python
+ from typing import Any
+ from pydantic import BaseModel, Field
+ from langchain_core.runnables import RunnableLambda
+
+ def f(x: dict[str, Any]) -> str:
+ return str(x["a"] * max(x["b"]))
+
+ class FSchema(BaseModel):
+ \"\"\"Apply a function to an integer and list of integers.\"\"\"
+
+ a: int = Field(..., description="Integer")
+ b: list[int] = Field(..., description="List of ints")
+
+ runnable = RunnableLambda(f)
+ as_tool = runnable.as_tool(FSchema)
+ as_tool.invoke({"a": 3, "b": [1, 2]})
+ ```
+
+ !!! example "`dict` input, specifying schema via `arg_types`"
+
+ ```python
+ from typing import Any
+ from langchain_core.runnables import RunnableLambda
+
+
+ def f(x: dict[str, Any]) -> str:
+ return str(x["a"] * max(x["b"]))
+
+
+ runnable = RunnableLambda(f)
+ as_tool = runnable.as_tool(arg_types={"a": int, "b": list[int]})
+ as_tool.invoke({"a": 3, "b": [1, 2]})
+ ```
+
+ !!! example "`str` input"
+
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def f(x: str) -> str:
+ return x + "a"
+
+
+ def g(x: str) -> str:
+ return x + "z"
+
+
+ runnable = RunnableLambda(f) | g
+ as_tool = runnable.as_tool()
+ as_tool.invoke("b")
+ ```
+ """
+ # Avoid circular import
+ from langchain_core.tools import convert_runnable_to_tool # noqa: PLC0415
+
+ return convert_runnable_to_tool(
+ self,
+ args_schema=args_schema,
+ name=name,
+ description=description,
+ arg_types=arg_types,
+ )
+
+
+class RunnableSerializable(Serializable, Runnable[Input, Output]):
+ """Runnable that can be serialized to JSON."""
+
+ name: str | None = None
+ """The name of the `Runnable`.
+
+ Used for debugging and tracing.
+ """
+
+ model_config = ConfigDict(
+ # Suppress warnings from pydantic protected namespaces
+ # (e.g., `model_`)
+ protected_namespaces=(),
+ )
+
+ @override
+ def to_json(self) -> SerializedConstructor | SerializedNotImplemented:
+ """Serialize the `Runnable` to JSON.
+
+ Returns:
+ A JSON-serializable representation of the `Runnable`.
+
+ """
+ dumped = super().to_json()
+ with contextlib.suppress(Exception):
+ dumped["name"] = self.get_name()
+ return dumped
+
+ def configurable_fields(
+ self, **kwargs: AnyConfigurableField
+ ) -> RunnableSerializable[Input, Output]:
+ """Configure particular `Runnable` fields at runtime.
+
+ Args:
+ **kwargs: A dictionary of `ConfigurableField` instances to configure.
+
+ Raises:
+ ValueError: If a configuration key is not found in the `Runnable`.
+
+ Returns:
+ A new `Runnable` with the fields configured.
+
+ !!! example
+
+ ```python
+ from langchain_core.runnables import ConfigurableField
+ from langchain_openai import ChatOpenAI
+
+ model = ChatOpenAI(max_tokens=20).configurable_fields(
+ max_tokens=ConfigurableField(
+ id="output_token_number",
+ name="Max tokens in the output",
+ description="The maximum number of tokens in the output",
+ )
+ )
+
+ # max_tokens = 20
+ print(
+ "max_tokens_20: ", model.invoke("tell me something about chess").content
+ )
+
+ # max_tokens = 200
+ print(
+ "max_tokens_200: ",
+ model.with_config(configurable={"output_token_number": 200})
+ .invoke("tell me something about chess")
+ .content,
+ )
+ ```
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.configurable import ( # noqa: PLC0415
+ RunnableConfigurableFields,
+ )
+
+ model_fields = type(self).model_fields
+ for key in kwargs:
+ if key not in model_fields:
+ msg = (
+ f"Configuration key {key} not found in {self}: "
+ f"available keys are {model_fields.keys()}"
+ )
+ raise ValueError(msg)
+
+ return RunnableConfigurableFields(default=self, fields=kwargs)
+
+ def configurable_alternatives(
+ self,
+ which: ConfigurableField,
+ *,
+ default_key: str = "default",
+ prefix_keys: bool = False,
+ **kwargs: Runnable[Input, Output] | Callable[[], Runnable[Input, Output]],
+ ) -> RunnableSerializable[Input, Output]:
+ """Configure alternatives for `Runnable` objects that can be set at runtime.
+
+ Args:
+ which: The `ConfigurableField` instance that will be used to select the
+ alternative.
+ default_key: The default key to use if no alternative is selected.
+ prefix_keys: Whether to prefix the keys with the `ConfigurableField` id.
+ **kwargs: A dictionary of keys to `Runnable` instances or callables that
+ return `Runnable` instances.
+
+ Returns:
+ A new `Runnable` with the alternatives configured.
+
+ !!! example
+
+ ```python
+ from langchain_anthropic import ChatAnthropic
+ from langchain_core.runnables.utils import ConfigurableField
+ from langchain_openai import ChatOpenAI
+
+ model = ChatAnthropic(
+ model_name="claude-sonnet-4-5-20250929"
+ ).configurable_alternatives(
+ ConfigurableField(id="llm"),
+ default_key="anthropic",
+ openai=ChatOpenAI(),
+ )
+
+ # uses the default model ChatAnthropic
+ print(model.invoke("which organization created you?").content)
+
+ # uses ChatOpenAI
+ print(
+ model.with_config(configurable={"llm": "openai"})
+ .invoke("which organization created you?")
+ .content
+ )
+ ```
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.configurable import ( # noqa: PLC0415
+ RunnableConfigurableAlternatives,
+ )
+
+ return RunnableConfigurableAlternatives(
+ which=which,
+ default=self,
+ alternatives=kwargs,
+ default_key=default_key,
+ prefix_keys=prefix_keys,
+ )
+
+
+def _seq_input_schema(
+ steps: list[Runnable[Any, Any]], config: RunnableConfig | None
+) -> type[BaseModel]:
+ # Import locally to prevent circular import
+ from langchain_core.runnables.passthrough import ( # noqa: PLC0415
+ RunnableAssign,
+ RunnablePick,
+ )
+
+ first = steps[0]
+ if len(steps) == 1:
+ return first.get_input_schema(config)
+ if isinstance(first, RunnableAssign):
+ next_input_schema = _seq_input_schema(steps[1:], config)
+ if not issubclass(next_input_schema, RootModel):
+ # it's a dict as expected
+ return create_model_v2(
+ "RunnableSequenceInput",
+ field_definitions={
+ k: (v.annotation, v.default)
+ for k, v in next_input_schema.model_fields.items()
+ if k not in first.mapper.steps__
+ },
+ )
+ elif isinstance(first, RunnablePick):
+ return _seq_input_schema(steps[1:], config)
+
+ return first.get_input_schema(config)
+
+
+def _seq_output_schema(
+ steps: list[Runnable[Any, Any]], config: RunnableConfig | None
+) -> type[BaseModel]:
+ # Import locally to prevent circular import
+ from langchain_core.runnables.passthrough import ( # noqa: PLC0415
+ RunnableAssign,
+ RunnablePick,
+ )
+
+ last = steps[-1]
+ if len(steps) == 1:
+ return last.get_input_schema(config)
+ if isinstance(last, RunnableAssign):
+ mapper_output_schema = last.mapper.get_output_schema(config)
+ prev_output_schema = _seq_output_schema(steps[:-1], config)
+ if not issubclass(prev_output_schema, RootModel):
+ # it's a dict as expected
+ return create_model_v2(
+ "RunnableSequenceOutput",
+ field_definitions={
+ **{
+ k: (v.annotation, v.default)
+ for k, v in prev_output_schema.model_fields.items()
+ },
+ **{
+ k: (v.annotation, v.default)
+ for k, v in mapper_output_schema.model_fields.items()
+ },
+ },
+ )
+ elif isinstance(last, RunnablePick):
+ prev_output_schema = _seq_output_schema(steps[:-1], config)
+ if not issubclass(prev_output_schema, RootModel):
+ # it's a dict as expected
+ if isinstance(last.keys, list):
+ return create_model_v2(
+ "RunnableSequenceOutput",
+ field_definitions={
+ k: (v.annotation, v.default)
+ for k, v in prev_output_schema.model_fields.items()
+ if k in last.keys
+ },
+ )
+ field = prev_output_schema.model_fields[last.keys]
+ return create_model_v2(
+ "RunnableSequenceOutput", root=(field.annotation, field.default)
+ )
+
+ return last.get_output_schema(config)
+
+
+_RUNNABLE_SEQUENCE_MIN_STEPS = 2
+
+
+class RunnableSequence(RunnableSerializable[Input, Output]):
+ """Sequence of `Runnable` objects, where the output of one is the input of the next.
+
+ **`RunnableSequence`** is the most important composition operator in LangChain
+ as it is used in virtually every chain.
+
+ A `RunnableSequence` can be instantiated directly or more commonly by using the
+ `|` operator where either the left or right operands (or both) must be a
+ `Runnable`.
+
+ Any `RunnableSequence` automatically supports sync, async, batch.
+
+ The default implementations of `batch` and `abatch` utilize threadpools and
+ asyncio gather and will be faster than naive invocation of `invoke` or `ainvoke`
+ for IO bound `Runnable`s.
+
+ Batching is implemented by invoking the batch method on each component of the
+ `RunnableSequence` in order.
+
+ A `RunnableSequence` preserves the streaming properties of its components, so if
+ all components of the sequence implement a `transform` method -- which
+ is the method that implements the logic to map a streaming input to a streaming
+ output -- then the sequence will be able to stream input to output!
+
+ If any component of the sequence does not implement transform then the
+ streaming will only begin after this component is run. If there are
+ multiple blocking components, streaming begins after the last one.
+
+ !!! note
+ `RunnableLambdas` do not support `transform` by default! So if you need to
+ use a `RunnableLambdas` be careful about where you place them in a
+ `RunnableSequence` (if you need to use the `stream`/`astream` methods).
+
+ If you need arbitrary logic and need streaming, you can subclass
+ Runnable, and implement `transform` for whatever logic you need.
+
+ Here is a simple example that uses simple functions to illustrate the use of
+ `RunnableSequence`:
+
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ def mul_two(x: int) -> int:
+ return x * 2
+
+
+ runnable_1 = RunnableLambda(add_one)
+ runnable_2 = RunnableLambda(mul_two)
+ sequence = runnable_1 | runnable_2
+ # Or equivalently:
+ # sequence = RunnableSequence(first=runnable_1, last=runnable_2)
+ sequence.invoke(1)
+ await sequence.ainvoke(1)
+
+ sequence.batch([1, 2, 3])
+ await sequence.abatch([1, 2, 3])
+ ```
+
+ Here's an example that uses streams JSON output generated by an LLM:
+
+ ```python
+ from langchain_core.output_parsers.json import SimpleJsonOutputParser
+ from langchain_openai import ChatOpenAI
+
+ prompt = PromptTemplate.from_template(
+ "In JSON format, give me a list of {topic} and their "
+ "corresponding names in French, Spanish and in a "
+ "Cat Language."
+ )
+
+ model = ChatOpenAI()
+ chain = prompt | model | SimpleJsonOutputParser()
+
+ async for chunk in chain.astream({"topic": "colors"}):
+ print("-") # noqa: T201
+ print(chunk, sep="", flush=True) # noqa: T201
+ ```
+ """
+
+ # The steps are broken into first, middle and last, solely for type checking
+ # purposes. It allows specifying the `Input` on the first type, the `Output` of
+ # the last type.
+ first: Runnable[Input, Any]
+ """The first `Runnable` in the sequence."""
+ middle: list[Runnable[Any, Any]] = Field(default_factory=list)
+ """The middle `Runnable` in the sequence."""
+ last: Runnable[Any, Output]
+ """The last `Runnable` in the sequence."""
+
+ def __init__(
+ self,
+ *steps: RunnableLike,
+ name: str | None = None,
+ first: Runnable[Any, Any] | None = None,
+ middle: list[Runnable[Any, Any]] | None = None,
+ last: Runnable[Any, Any] | None = None,
+ ) -> None:
+ """Create a new `RunnableSequence`.
+
+ Args:
+ steps: The steps to include in the sequence.
+ name: The name of the `Runnable`.
+ first: The first `Runnable` in the sequence.
+ middle: The middle `Runnable` objects in the sequence.
+ last: The last `Runnable` in the sequence.
+
+ Raises:
+ ValueError: If the sequence has less than 2 steps.
+ """
+ steps_flat: list[Runnable] = []
+ if not steps and first is not None and last is not None:
+ steps_flat = [first] + (middle or []) + [last]
+ for step in steps:
+ if isinstance(step, RunnableSequence):
+ steps_flat.extend(step.steps)
+ else:
+ steps_flat.append(coerce_to_runnable(step))
+ if len(steps_flat) < _RUNNABLE_SEQUENCE_MIN_STEPS:
+ msg = (
+ f"RunnableSequence must have at least {_RUNNABLE_SEQUENCE_MIN_STEPS} "
+ f"steps, got {len(steps_flat)}"
+ )
+ raise ValueError(msg)
+ super().__init__(
+ first=steps_flat[0],
+ middle=list(steps_flat[1:-1]),
+ last=steps_flat[-1],
+ name=name,
+ )
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @property
+ def steps(self) -> list[Runnable[Any, Any]]:
+ """All the `Runnable`s that make up the sequence in order.
+
+ Returns:
+ A list of `Runnable`s.
+ """
+ return [self.first, *self.middle, self.last]
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @property
+ @override
+ def InputType(self) -> type[Input]:
+ """The type of the input to the `Runnable`."""
+ return self.first.InputType
+
+ @property
+ @override
+ def OutputType(self) -> type[Output]:
+ """The type of the output of the `Runnable`."""
+ return self.last.OutputType
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ """Get the input schema of the `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The input schema of the `Runnable`.
+
+ """
+ return _seq_input_schema(self.steps, config)
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ """Get the output schema of the `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The output schema of the `Runnable`.
+
+ """
+ return _seq_output_schema(self.steps, config)
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ """Get the config specs of the `Runnable`.
+
+ Returns:
+ The config specs of the `Runnable`.
+
+ """
+ # Import locally to prevent circular import
+ return get_unique_config_specs(
+ [spec for step in self.steps for spec in step.config_specs]
+ )
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ """Get the graph representation of the `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The graph representation of the `Runnable`.
+
+ Raises:
+ ValueError: If a `Runnable` has no first or last node.
+
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
+
+ graph = Graph()
+ for step in self.steps:
+ current_last_node = graph.last_node()
+ step_graph = step.get_graph(config)
+ if step is not self.first:
+ step_graph.trim_first_node()
+ if step is not self.last:
+ step_graph.trim_last_node()
+ step_first_node, _ = graph.extend(step_graph)
+ if not step_first_node:
+ msg = f"Runnable {step} has no first node"
+ raise ValueError(msg)
+ if current_last_node:
+ graph.add_edge(current_last_node, step_first_node)
+
+ return graph
+
+ @override
+ def __repr__(self) -> str:
+ return "\n| ".join(
+ repr(s) if i == 0 else indent_lines_after_first(repr(s), "| ")
+ for i, s in enumerate(self.steps)
+ )
+
+ @override
+ def __or__(
+ self,
+ other: Runnable[Any, Other]
+ | Callable[[Iterator[Any]], Iterator[Other]]
+ | Callable[[AsyncIterator[Any]], AsyncIterator[Other]]
+ | Callable[[Any], Other]
+ | Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any],
+ ) -> RunnableSerializable[Input, Other]:
+ if isinstance(other, RunnableSequence):
+ return RunnableSequence(
+ self.first,
+ *self.middle,
+ self.last,
+ other.first,
+ *other.middle,
+ other.last,
+ name=self.name or other.name,
+ )
+ return RunnableSequence(
+ self.first,
+ *self.middle,
+ self.last,
+ coerce_to_runnable(other),
+ name=self.name,
+ )
+
+ @override
+ def __ror__(
+ self,
+ other: Runnable[Other, Any]
+ | Callable[[Iterator[Other]], Iterator[Any]]
+ | Callable[[AsyncIterator[Other]], AsyncIterator[Any]]
+ | Callable[[Other], Any]
+ | Mapping[str, Runnable[Other, Any] | Callable[[Other], Any] | Any],
+ ) -> RunnableSerializable[Other, Output]:
+ if isinstance(other, RunnableSequence):
+ return RunnableSequence(
+ other.first,
+ *other.middle,
+ other.last,
+ self.first,
+ *self.middle,
+ self.last,
+ name=other.name or self.name,
+ )
+ return RunnableSequence(
+ coerce_to_runnable(other),
+ self.first,
+ *self.middle,
+ self.last,
+ name=self.name,
+ )
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ # setup callbacks and context
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ # start the root run
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ input_ = input
+
+ # invoke all steps in sequence
+ try:
+ for i, step in enumerate(self.steps):
+ # mark each step as a child run
+ config = patch_config(
+ config, callbacks=run_manager.get_child(f"seq:step:{i + 1}")
+ )
+ with set_config_context(config) as context:
+ if i == 0:
+ input_ = context.run(step.invoke, input_, config, **kwargs)
+ else:
+ input_ = context.run(step.invoke, input_, config)
+ # finish the root run
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ run_manager.on_chain_end(input_)
+ return cast("Output", input_)
+
+ @override
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ # setup callbacks and context
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ # start the root run
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ input_ = input
+
+ # invoke all steps in sequence
+ try:
+ for i, step in enumerate(self.steps):
+ # mark each step as a child run
+ config = patch_config(
+ config, callbacks=run_manager.get_child(f"seq:step:{i + 1}")
+ )
+ with set_config_context(config) as context:
+ if i == 0:
+ part = functools.partial(step.ainvoke, input_, config, **kwargs)
+ else:
+ part = functools.partial(step.ainvoke, input_, config)
+ input_ = await coro_with_context(part(), context, create_task=True)
+ # finish the root run
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ await run_manager.on_chain_end(input_)
+ return cast("Output", input_)
+
+ @override
+ def batch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if not inputs:
+ return []
+
+ # setup callbacks and context
+ configs = get_config_list(config, len(inputs))
+ callback_managers = [
+ CallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ local_callbacks=None,
+ verbose=False,
+ inheritable_tags=config.get("tags"),
+ local_tags=None,
+ inheritable_metadata=config.get("metadata"),
+ local_metadata=None,
+ )
+ for config in configs
+ ]
+ # start the root runs, one per input
+ run_managers = [
+ cm.on_chain_start(
+ None,
+ input_,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ for cm, input_, config in zip(
+ callback_managers, inputs, configs, strict=False
+ )
+ ]
+
+ # invoke
+ try:
+ if return_exceptions:
+ # Track which inputs (by index) failed so far
+ # If an input has failed it will be present in this map,
+ # and the value will be the exception that was raised.
+ failed_inputs_map: dict[int, Exception] = {}
+ for stepidx, step in enumerate(self.steps):
+ # Assemble the original indexes of the remaining inputs
+ # (i.e. the ones that haven't failed yet)
+ remaining_idxs = [
+ i for i in range(len(configs)) if i not in failed_inputs_map
+ ]
+ # Invoke the step on the remaining inputs
+ inputs = step.batch(
+ [
+ inp
+ for i, inp in zip(remaining_idxs, inputs, strict=False)
+ if i not in failed_inputs_map
+ ],
+ [
+ # each step a child run of the corresponding root run
+ patch_config(
+ config,
+ callbacks=rm.get_child(f"seq:step:{stepidx + 1}"),
+ )
+ for i, (rm, config) in enumerate(
+ zip(run_managers, configs, strict=False)
+ )
+ if i not in failed_inputs_map
+ ],
+ return_exceptions=return_exceptions,
+ **(kwargs if stepidx == 0 else {}),
+ )
+ # If an input failed, add it to the map
+ failed_inputs_map.update(
+ {
+ i: inp
+ for i, inp in zip(remaining_idxs, inputs, strict=False)
+ if isinstance(inp, Exception)
+ }
+ )
+ inputs = [inp for inp in inputs if not isinstance(inp, Exception)]
+ # If all inputs have failed, stop processing
+ if len(failed_inputs_map) == len(configs):
+ break
+
+ # Reassemble the outputs, inserting Exceptions for failed inputs
+ inputs_copy = inputs.copy()
+ inputs = []
+ for i in range(len(configs)):
+ if i in failed_inputs_map:
+ inputs.append(cast("Input", failed_inputs_map[i]))
+ else:
+ inputs.append(inputs_copy.pop(0))
+ else:
+ for i, step in enumerate(self.steps):
+ inputs = step.batch(
+ inputs,
+ [
+ # each step a child run of the corresponding root run
+ patch_config(
+ config, callbacks=rm.get_child(f"seq:step:{i + 1}")
+ )
+ for rm, config in zip(run_managers, configs, strict=False)
+ ],
+ return_exceptions=return_exceptions,
+ **(kwargs if i == 0 else {}),
+ )
+
+ # finish the root runs
+ except BaseException as e:
+ for rm in run_managers:
+ rm.on_chain_error(e)
+ if return_exceptions:
+ return cast("list[Output]", [e for _ in inputs])
+ raise
+ else:
+ first_exception: Exception | None = None
+ for run_manager, out in zip(run_managers, inputs, strict=False):
+ if isinstance(out, Exception):
+ first_exception = first_exception or out
+ run_manager.on_chain_error(out)
+ else:
+ run_manager.on_chain_end(out)
+ if return_exceptions or first_exception is None:
+ return cast("list[Output]", inputs)
+ raise first_exception
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if not inputs:
+ return []
+
+ # setup callbacks and context
+ configs = get_config_list(config, len(inputs))
+ callback_managers = [
+ AsyncCallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ local_callbacks=None,
+ verbose=False,
+ inheritable_tags=config.get("tags"),
+ local_tags=None,
+ inheritable_metadata=config.get("metadata"),
+ local_metadata=None,
+ )
+ for config in configs
+ ]
+ # start the root runs, one per input
+ run_managers: list[AsyncCallbackManagerForChainRun] = await asyncio.gather(
+ *(
+ cm.on_chain_start(
+ None,
+ input_,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ for cm, input_, config in zip(
+ callback_managers, inputs, configs, strict=False
+ )
+ )
+ )
+
+ # invoke .batch() on each step
+ # this uses batching optimizations in Runnable subclasses, like LLM
+ try:
+ if return_exceptions:
+ # Track which inputs (by index) failed so far
+ # If an input has failed it will be present in this map,
+ # and the value will be the exception that was raised.
+ failed_inputs_map: dict[int, Exception] = {}
+ for stepidx, step in enumerate(self.steps):
+ # Assemble the original indexes of the remaining inputs
+ # (i.e. the ones that haven't failed yet)
+ remaining_idxs = [
+ i for i in range(len(configs)) if i not in failed_inputs_map
+ ]
+ # Invoke the step on the remaining inputs
+ inputs = await step.abatch(
+ [
+ inp
+ for i, inp in zip(remaining_idxs, inputs, strict=False)
+ if i not in failed_inputs_map
+ ],
+ [
+ # each step a child run of the corresponding root run
+ patch_config(
+ config,
+ callbacks=rm.get_child(f"seq:step:{stepidx + 1}"),
+ )
+ for i, (rm, config) in enumerate(
+ zip(run_managers, configs, strict=False)
+ )
+ if i not in failed_inputs_map
+ ],
+ return_exceptions=return_exceptions,
+ **(kwargs if stepidx == 0 else {}),
+ )
+ # If an input failed, add it to the map
+ failed_inputs_map.update(
+ {
+ i: inp
+ for i, inp in zip(remaining_idxs, inputs, strict=False)
+ if isinstance(inp, Exception)
+ }
+ )
+ inputs = [inp for inp in inputs if not isinstance(inp, Exception)]
+ # If all inputs have failed, stop processing
+ if len(failed_inputs_map) == len(configs):
+ break
+
+ # Reassemble the outputs, inserting Exceptions for failed inputs
+ inputs_copy = inputs.copy()
+ inputs = []
+ for i in range(len(configs)):
+ if i in failed_inputs_map:
+ inputs.append(cast("Input", failed_inputs_map[i]))
+ else:
+ inputs.append(inputs_copy.pop(0))
+ else:
+ for i, step in enumerate(self.steps):
+ inputs = await step.abatch(
+ inputs,
+ [
+ # each step a child run of the corresponding root run
+ patch_config(
+ config, callbacks=rm.get_child(f"seq:step:{i + 1}")
+ )
+ for rm, config in zip(run_managers, configs, strict=False)
+ ],
+ return_exceptions=return_exceptions,
+ **(kwargs if i == 0 else {}),
+ )
+ # finish the root runs
+ except BaseException as e:
+ await asyncio.gather(*(rm.on_chain_error(e) for rm in run_managers))
+ if return_exceptions:
+ return cast("list[Output]", [e for _ in inputs])
+ raise
+ else:
+ first_exception: Exception | None = None
+ coros: list[Awaitable[None]] = []
+ for run_manager, out in zip(run_managers, inputs, strict=False):
+ if isinstance(out, Exception):
+ first_exception = first_exception or out
+ coros.append(run_manager.on_chain_error(out))
+ else:
+ coros.append(run_manager.on_chain_end(out))
+ await asyncio.gather(*coros)
+ if return_exceptions or first_exception is None:
+ return cast("list[Output]", inputs)
+ raise first_exception
+
+ def _transform(
+ self,
+ inputs: Iterator[Input],
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Iterator[Output]:
+ steps = [self.first, *self.middle, self.last]
+ # transform the input stream of each step with the next
+ # steps that don't natively support transforming an input stream will
+ # buffer input in memory until all available, and then start emitting output
+ final_pipeline = cast("Iterator[Output]", inputs)
+ for idx, step in enumerate(steps):
+ config = patch_config(
+ config, callbacks=run_manager.get_child(f"seq:step:{idx + 1}")
+ )
+ if idx == 0:
+ final_pipeline = step.transform(final_pipeline, config, **kwargs)
+ else:
+ final_pipeline = step.transform(final_pipeline, config)
+
+ yield from final_pipeline
+
+ async def _atransform(
+ self,
+ inputs: AsyncIterator[Input],
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> AsyncIterator[Output]:
+ steps = [self.first, *self.middle, self.last]
+ # stream the last steps
+ # transform the input stream of each step with the next
+ # steps that don't natively support transforming an input stream will
+ # buffer input in memory until all available, and then start emitting output
+ final_pipeline = cast("AsyncIterator[Output]", inputs)
+ for idx, step in enumerate(steps):
+ config = patch_config(
+ config,
+ callbacks=run_manager.get_child(f"seq:step:{idx + 1}"),
+ )
+ if idx == 0:
+ final_pipeline = step.atransform(final_pipeline, config, **kwargs)
+ else:
+ final_pipeline = step.atransform(final_pipeline, config)
+ async for output in final_pipeline:
+ yield output
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ yield from self._transform_stream_with_config(
+ input,
+ self._transform,
+ patch_config(config, run_name=(config or {}).get("run_name") or self.name),
+ **kwargs,
+ )
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ yield from self.transform(iter([input]), config, **kwargs)
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ async for chunk in self._atransform_stream_with_config(
+ input,
+ self._atransform,
+ patch_config(config, run_name=(config or {}).get("run_name") or self.name),
+ **kwargs,
+ ):
+ yield chunk
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ async def input_aiter() -> AsyncIterator[Input]:
+ yield input
+
+ async for chunk in self.atransform(input_aiter(), config, **kwargs):
+ yield chunk
+
+
+class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
+ """Runnable that runs a mapping of `Runnable`s in parallel.
+
+ Returns a mapping of their outputs.
+
+ `RunnableParallel` is one of the two main composition primitives,
+ alongside `RunnableSequence`. It invokes `Runnable`s concurrently, providing the
+ same input to each.
+
+ A `RunnableParallel` can be instantiated directly or by using a dict literal
+ within a sequence.
+
+ Here is a simple example that uses functions to illustrate the use of
+ `RunnableParallel`:
+
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ def mul_two(x: int) -> int:
+ return x * 2
+
+
+ def mul_three(x: int) -> int:
+ return x * 3
+
+
+ runnable_1 = RunnableLambda(add_one)
+ runnable_2 = RunnableLambda(mul_two)
+ runnable_3 = RunnableLambda(mul_three)
+
+ sequence = runnable_1 | { # this dict is coerced to a RunnableParallel
+ "mul_two": runnable_2,
+ "mul_three": runnable_3,
+ }
+ # Or equivalently:
+ # sequence = runnable_1 | RunnableParallel(
+ # {"mul_two": runnable_2, "mul_three": runnable_3}
+ # )
+ # Also equivalently:
+ # sequence = runnable_1 | RunnableParallel(
+ # mul_two=runnable_2,
+ # mul_three=runnable_3,
+ # )
+
+ sequence.invoke(1)
+ await sequence.ainvoke(1)
+
+ sequence.batch([1, 2, 3])
+ await sequence.abatch([1, 2, 3])
+ ```
+
+ `RunnableParallel` makes it easy to run `Runnable`s in parallel. In the below
+ example, we simultaneously stream output from two different `Runnable` objects:
+
+ ```python
+ from langchain_core.prompts import ChatPromptTemplate
+ from langchain_core.runnables import RunnableParallel
+ from langchain_openai import ChatOpenAI
+
+ model = ChatOpenAI()
+ joke_chain = (
+ ChatPromptTemplate.from_template("tell me a joke about {topic}") | model
+ )
+ poem_chain = (
+ ChatPromptTemplate.from_template("write a 2-line poem about {topic}")
+ | model
+ )
+
+ runnable = RunnableParallel(joke=joke_chain, poem=poem_chain)
+
+ # Display stream
+ output = {key: "" for key, _ in runnable.output_schema()}
+ for chunk in runnable.stream({"topic": "bear"}):
+ for key in chunk:
+ output[key] = output[key] + chunk[key].content
+ print(output) # noqa: T201
+ ```
+ """
+
+ steps__: Mapping[str, Runnable[Input, Any]]
+
+ def __init__(
+ self,
+ steps__: Mapping[
+ str,
+ Runnable[Input, Any]
+ | Callable[[Input], Any]
+ | Mapping[str, Runnable[Input, Any] | Callable[[Input], Any]],
+ ]
+ | None = None,
+ **kwargs: Runnable[Input, Any]
+ | Callable[[Input], Any]
+ | Mapping[str, Runnable[Input, Any] | Callable[[Input], Any]],
+ ) -> None:
+ """Create a `RunnableParallel`.
+
+ Args:
+ steps__: The steps to include.
+ **kwargs: Additional steps to include.
+
+ """
+ merged = {**steps__} if steps__ is not None else {}
+ merged.update(kwargs)
+ super().__init__(
+ steps__={key: coerce_to_runnable(r) for key, r in merged.items()}
+ )
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @override
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ """Get the name of the `Runnable`.
+
+ Args:
+ suffix: The suffix to use.
+ name: The name to use.
+
+ Returns:
+ The name of the `Runnable`.
+
+ """
+ name = name or self.name or f"RunnableParallel<{','.join(self.steps__.keys())}>"
+ return super().get_name(suffix, name=name)
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ """The type of the input to the `Runnable`."""
+ for step in self.steps__.values():
+ if step.InputType:
+ return step.InputType
+
+ return Any
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ """Get the input schema of the `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The input schema of the `Runnable`.
+
+ """
+ if all(
+ s.get_input_schema(config).model_json_schema().get("type", "object")
+ == "object"
+ for s in self.steps__.values()
+ ):
+ for step in self.steps__.values():
+ fields = step.get_input_schema(config).model_fields
+ root_field = fields.get("root")
+ if root_field is not None and root_field.annotation != Any:
+ return super().get_input_schema(config)
+
+ # This is correct, but pydantic typings/mypy don't think so.
+ return create_model_v2(
+ self.get_name("Input"),
+ field_definitions={
+ k: (v.annotation, v.default)
+ for step in self.steps__.values()
+ for k, v in step.get_input_schema(config).model_fields.items()
+ if k != "__root__"
+ },
+ )
+
+ return super().get_input_schema(config)
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ """Get the output schema of the `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The output schema of the `Runnable`.
+
+ """
+ fields = {k: (v.OutputType, ...) for k, v in self.steps__.items()}
+ return create_model_v2(self.get_name("Output"), field_definitions=fields)
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ """Get the config specs of the `Runnable`.
+
+ Returns:
+ The config specs of the `Runnable`.
+
+ """
+ return get_unique_config_specs(
+ spec for step in self.steps__.values() for spec in step.config_specs
+ )
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ """Get the graph representation of the `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The graph representation of the `Runnable`.
+
+ Raises:
+ ValueError: If a `Runnable` has no first or last node.
+
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
+
+ graph = Graph()
+ input_node = graph.add_node(self.get_input_schema(config))
+ output_node = graph.add_node(self.get_output_schema(config))
+ for step in self.steps__.values():
+ step_graph = step.get_graph()
+ step_graph.trim_first_node()
+ step_graph.trim_last_node()
+ if not step_graph:
+ graph.add_edge(input_node, output_node)
+ else:
+ step_first_node, step_last_node = graph.extend(step_graph)
+ if not step_first_node:
+ msg = f"Runnable {step} has no first node"
+ raise ValueError(msg)
+ if not step_last_node:
+ msg = f"Runnable {step} has no last node"
+ raise ValueError(msg)
+ graph.add_edge(input_node, step_first_node)
+ graph.add_edge(step_last_node, output_node)
+
+ return graph
+
+ @override
+ def __repr__(self) -> str:
+ map_for_repr = ",\n ".join(
+ f"{k}: {indent_lines_after_first(repr(v), ' ' + k + ': ')}"
+ for k, v in self.steps__.items()
+ )
+ return "{\n " + map_for_repr + "\n}"
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> dict[str, Any]:
+ # setup callbacks
+ config = ensure_config(config)
+ callback_manager = CallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ local_callbacks=None,
+ verbose=False,
+ inheritable_tags=config.get("tags"),
+ local_tags=None,
+ inheritable_metadata=config.get("metadata"),
+ local_metadata=None,
+ )
+ # start the root run
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+
+ def _invoke_step(
+ step: Runnable[Input, Any], input_: Input, config: RunnableConfig, key: str
+ ) -> Any:
+ child_config = patch_config(
+ config,
+ # mark each step as a child run
+ callbacks=run_manager.get_child(f"map:key:{key}"),
+ )
+ with set_config_context(child_config) as context:
+ return context.run(
+ step.invoke,
+ input_,
+ child_config,
+ )
+
+ # gather results from all steps
+ try:
+ # copy to avoid issues from the caller mutating the steps during invoke()
+ steps = dict(self.steps__)
+
+ with get_executor_for_config(config) as executor:
+ futures = [
+ executor.submit(_invoke_step, step, input, config, key)
+ for key, step in steps.items()
+ ]
+ output = {
+ key: future.result()
+ for key, future in zip(steps, futures, strict=False)
+ }
+ # finish the root run
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ run_manager.on_chain_end(output)
+ return output
+
+ @override
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> dict[str, Any]:
+ # setup callbacks
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ # start the root run
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+
+ async def _ainvoke_step(
+ step: Runnable[Input, Any], input_: Input, config: RunnableConfig, key: str
+ ) -> Any:
+ child_config = patch_config(
+ config,
+ callbacks=run_manager.get_child(f"map:key:{key}"),
+ )
+ with set_config_context(child_config) as context:
+ return await coro_with_context(
+ step.ainvoke(input_, child_config), context, create_task=True
+ )
+
+ # gather results from all steps
+ try:
+ # copy to avoid issues from the caller mutating the steps during invoke()
+ steps = dict(self.steps__)
+ results = await asyncio.gather(
+ *(
+ _ainvoke_step(
+ step,
+ input,
+ # mark each step as a child run
+ config,
+ key,
+ )
+ for key, step in steps.items()
+ )
+ )
+ output = dict(zip(steps, results, strict=False))
+ # finish the root run
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ await run_manager.on_chain_end(output)
+ return output
+
+ def _transform(
+ self,
+ inputs: Iterator[Input],
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ ) -> Iterator[AddableDict]:
+ # Shallow copy steps to ignore mutations while in progress
+ steps = dict(self.steps__)
+ # Each step gets a copy of the input iterator,
+ # which is consumed in parallel in a separate thread.
+ input_copies = list(safetee(inputs, len(steps), lock=threading.Lock()))
+ with get_executor_for_config(config) as executor:
+ # Create the transform() generator for each step
+ named_generators = [
+ (
+ name,
+ step.transform(
+ input_copies.pop(),
+ patch_config(
+ config, callbacks=run_manager.get_child(f"map:key:{name}")
+ ),
+ ),
+ )
+ for name, step in steps.items()
+ ]
+ # Start the first iteration of each generator
+ futures = {
+ executor.submit(next, generator): (step_name, generator)
+ for step_name, generator in named_generators
+ }
+ # Yield chunks from each as they become available,
+ # and start the next iteration of that generator that yielded it.
+ # When all generators are exhausted, stop.
+ while futures:
+ completed_futures, _ = wait(futures, return_when=FIRST_COMPLETED)
+ for future in completed_futures:
+ (step_name, generator) = futures.pop(future)
+ try:
+ chunk = AddableDict({step_name: future.result()})
+ yield chunk
+ futures[executor.submit(next, generator)] = (
+ step_name,
+ generator,
+ )
+ except StopIteration:
+ pass
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[dict[str, Any]]:
+ yield from self._transform_stream_with_config(
+ input, self._transform, config, **kwargs
+ )
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[dict[str, Any]]:
+ yield from self.transform(iter([input]), config)
+
+ async def _atransform(
+ self,
+ inputs: AsyncIterator[Input],
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ ) -> AsyncIterator[AddableDict]:
+ # Shallow copy steps to ignore mutations while in progress
+ steps = dict(self.steps__)
+ # Each step gets a copy of the input iterator,
+ # which is consumed in parallel in a separate thread.
+ input_copies = list(atee(inputs, len(steps), lock=asyncio.Lock()))
+ # Create the transform() generator for each step
+ named_generators = [
+ (
+ name,
+ step.atransform(
+ input_copies.pop(),
+ patch_config(
+ config, callbacks=run_manager.get_child(f"map:key:{name}")
+ ),
+ ),
+ )
+ for name, step in steps.items()
+ ]
+
+ # Wrap in a coroutine to satisfy linter
+ async def get_next_chunk(generator: AsyncIterator) -> Output | None:
+ return await anext(generator)
+
+ # Start the first iteration of each generator
+ tasks = {
+ asyncio.create_task(get_next_chunk(generator)): (step_name, generator)
+ for step_name, generator in named_generators
+ }
+ # Yield chunks from each as they become available,
+ # and start the next iteration of the generator that yielded it.
+ # When all generators are exhausted, stop.
+ while tasks:
+ completed_tasks, _ = await asyncio.wait(
+ tasks, return_when=asyncio.FIRST_COMPLETED
+ )
+ for task in completed_tasks:
+ (step_name, generator) = tasks.pop(task)
+ try:
+ chunk = AddableDict({step_name: task.result()})
+ yield chunk
+ new_task = asyncio.create_task(get_next_chunk(generator))
+ tasks[new_task] = (step_name, generator)
+ except StopAsyncIteration:
+ pass
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any]]:
+ async for chunk in self._atransform_stream_with_config(
+ input, self._atransform, config, **kwargs
+ ):
+ yield chunk
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[dict[str, Any]]:
+ async def input_aiter() -> AsyncIterator[Input]:
+ yield input
+
+ async for chunk in self.atransform(input_aiter(), config):
+ yield chunk
+
+
+# We support both names
+RunnableMap = RunnableParallel
+
+
+class RunnableGenerator(Runnable[Input, Output]):
+ """`Runnable` that runs a generator function.
+
+ `RunnableGenerator`s can be instantiated directly or by using a generator within
+ a sequence.
+
+ `RunnableGenerator`s can be used to implement custom behavior, such as custom
+ output parsers, while preserving streaming capabilities. Given a generator function
+ with a signature `Iterator[A] -> Iterator[B]`, wrapping it in a
+ `RunnableGenerator` allows it to emit output chunks as soon as they are streamed
+ in from the previous step.
+
+ !!! note
+ If a generator function has a `signature A -> Iterator[B]`, such that it
+ requires its input from the previous step to be completed before emitting chunks
+ (e.g., most LLMs need the entire prompt available to start generating), it can
+ instead be wrapped in a `RunnableLambda`.
+
+ Here is an example to show the basic mechanics of a `RunnableGenerator`:
+
+ ```python
+ from typing import Any, AsyncIterator, Iterator
+
+ from langchain_core.runnables import RunnableGenerator
+
+
+ def gen(input: Iterator[Any]) -> Iterator[str]:
+ for token in ["Have", " a", " nice", " day"]:
+ yield token
+
+
+ runnable = RunnableGenerator(gen)
+ runnable.invoke(None) # "Have a nice day"
+ list(runnable.stream(None)) # ["Have", " a", " nice", " day"]
+ runnable.batch([None, None]) # ["Have a nice day", "Have a nice day"]
+
+
+ # Async version:
+ async def agen(input: AsyncIterator[Any]) -> AsyncIterator[str]:
+ for token in ["Have", " a", " nice", " day"]:
+ yield token
+
+
+ runnable = RunnableGenerator(agen)
+ await runnable.ainvoke(None) # "Have a nice day"
+ [p async for p in runnable.astream(None)] # ["Have", " a", " nice", " day"]
+ ```
+
+ `RunnableGenerator` makes it easy to implement custom behavior within a streaming
+ context. Below we show an example:
+
+ ```python
+ from langchain_core.prompts import ChatPromptTemplate
+ from langchain_core.runnables import RunnableGenerator, RunnableLambda
+ from langchain_openai import ChatOpenAI
+ from langchain_core.output_parsers import StrOutputParser
+
+
+ model = ChatOpenAI()
+ chant_chain = (
+ ChatPromptTemplate.from_template("Give me a 3 word chant about {topic}")
+ | model
+ | StrOutputParser()
+ )
+
+
+ def character_generator(input: Iterator[str]) -> Iterator[str]:
+ for token in input:
+ if "," in token or "." in token:
+ yield "👏" + token
+ else:
+ yield token
+
+
+ runnable = chant_chain | character_generator
+ assert type(runnable.last) is RunnableGenerator
+ "".join(runnable.stream({"topic": "waste"})) # Reduce👏, Reuse👏, Recycle👏.
+
+
+ # Note that RunnableLambda can be used to delay streaming of one step in a
+ # sequence until the previous step is finished:
+ def reverse_generator(input: str) -> Iterator[str]:
+ # Yield characters of input in reverse order.
+ for character in input[::-1]:
+ yield character
+
+
+ runnable = chant_chain | RunnableLambda(reverse_generator)
+ "".join(runnable.stream({"topic": "waste"})) # ".elcycer ,esuer ,ecudeR"
+ ```
+ """
+
+ def __init__(
+ self,
+ transform: Callable[[Iterator[Input]], Iterator[Output]]
+ | Callable[[AsyncIterator[Input]], AsyncIterator[Output]],
+ atransform: Callable[[AsyncIterator[Input]], AsyncIterator[Output]]
+ | None = None,
+ *,
+ name: str | None = None,
+ ) -> None:
+ """Initialize a `RunnableGenerator`.
+
+ Args:
+ transform: The transform function.
+ atransform: The async transform function.
+ name: The name of the `Runnable`.
+
+ Raises:
+ TypeError: If the transform is not a generator function.
+
+ """
+ if atransform is not None:
+ self._atransform = atransform
+ func_for_name: Callable = atransform
+
+ if is_async_generator(transform):
+ self._atransform = transform
+ func_for_name = transform
+ elif inspect.isgeneratorfunction(transform):
+ self._transform = transform
+ func_for_name = transform
+ else:
+ msg = (
+ "Expected a generator function type for `transform`."
+ f"Instead got an unsupported type: {type(transform)}"
+ )
+ raise TypeError(msg)
+
+ try:
+ self.name = name or func_for_name.__name__
+ except AttributeError:
+ self.name = "RunnableGenerator"
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ func = getattr(self, "_transform", None) or self._atransform
+ try:
+ params = inspect.signature(func).parameters
+ first_param = next(iter(params.values()), None)
+ if first_param and first_param.annotation != inspect.Parameter.empty:
+ return getattr(first_param.annotation, "__args__", (Any,))[0]
+ except ValueError:
+ pass
+ return Any
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ # Override the default implementation.
+ # For a runnable generator, we need to bring to provide the
+ # module of the underlying function when creating the model.
+ root_type = self.InputType
+
+ func = getattr(self, "_transform", None) or self._atransform
+ module = getattr(func, "__module__", None)
+
+ if (
+ inspect.isclass(root_type)
+ and not isinstance(root_type, GenericAlias)
+ and issubclass(root_type, BaseModel)
+ ):
+ return root_type
+
+ return create_model_v2(
+ self.get_name("Input"),
+ root=root_type,
+ # To create the schema, we need to provide the module
+ # where the underlying function is defined.
+ # This allows pydantic to resolve type annotations appropriately.
+ module_name=module,
+ )
+
+ @property
+ @override
+ def OutputType(self) -> Any:
+ func = getattr(self, "_transform", None) or self._atransform
+ try:
+ sig = inspect.signature(func)
+ return (
+ getattr(sig.return_annotation, "__args__", (Any,))[0]
+ if sig.return_annotation != inspect.Signature.empty
+ else Any
+ )
+ except ValueError:
+ return Any
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ # Override the default implementation.
+ # For a runnable generator, we need to bring to provide the
+ # module of the underlying function when creating the model.
+ root_type = self.OutputType
+ func = getattr(self, "_transform", None) or self._atransform
+ module = getattr(func, "__module__", None)
+
+ if (
+ inspect.isclass(root_type)
+ and not isinstance(root_type, GenericAlias)
+ and issubclass(root_type, BaseModel)
+ ):
+ return root_type
+
+ return create_model_v2(
+ self.get_name("Output"),
+ root=root_type,
+ # To create the schema, we need to provide the module
+ # where the underlying function is defined.
+ # This allows pydantic to resolve type annotations appropriately.
+ module_name=module,
+ )
+
+ @override
+ def __eq__(self, other: object) -> bool:
+ if isinstance(other, RunnableGenerator):
+ if hasattr(self, "_transform") and hasattr(other, "_transform"):
+ return self._transform == other._transform
+ if hasattr(self, "_atransform") and hasattr(other, "_atransform"):
+ return self._atransform == other._atransform
+ return False
+ return False
+
+ __hash__ = None # type: ignore[assignment]
+
+ @override
+ def __repr__(self) -> str:
+ return f"RunnableGenerator({self.name})"
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Output]:
+ if not hasattr(self, "_transform"):
+ msg = f"{self!r} only supports async methods."
+ raise NotImplementedError(msg)
+ return self._transform_stream_with_config(
+ input,
+ self._transform, # type: ignore[arg-type]
+ config,
+ defers_inputs=True,
+ **kwargs,
+ )
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Output]:
+ return self.transform(iter([input]), config, **kwargs)
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ final: Output | None = None
+ for output in self.stream(input, config, **kwargs):
+ final = output if final is None else final + output # type: ignore[operator]
+ return cast("Output", final)
+
+ @override
+ def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Output]:
+ if not hasattr(self, "_atransform"):
+ msg = f"{self!r} only supports sync methods."
+ raise NotImplementedError(msg)
+
+ return self._atransform_stream_with_config(
+ input, self._atransform, config, defers_inputs=True, **kwargs
+ )
+
+ @override
+ def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Output]:
+ async def input_aiter() -> AsyncIterator[Input]:
+ yield input
+
+ return self.atransform(input_aiter(), config, **kwargs)
+
+ @override
+ async def ainvoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ final: Output | None = None
+ async for output in self.astream(input, config, **kwargs):
+ final = output if final is None else final + output # type: ignore[operator]
+ return cast("Output", final)
+
+
+class RunnableLambda(Runnable[Input, Output]):
+ """`RunnableLambda` converts a python callable into a `Runnable`.
+
+ Wrapping a callable in a `RunnableLambda` makes the callable usable
+ within either a sync or async context.
+
+ `RunnableLambda` can be composed as any other `Runnable` and provides
+ seamless integration with LangChain tracing.
+
+ `RunnableLambda` is best suited for code that does not need to support
+ streaming. If you need to support streaming (i.e., be able to operate
+ on chunks of inputs and yield chunks of outputs), use `RunnableGenerator`
+ instead.
+
+ Note that if a `RunnableLambda` returns an instance of `Runnable`, that
+ instance is invoked (or streamed) during execution.
+
+ Examples:
+ ```python
+ # This is a RunnableLambda
+ from langchain_core.runnables import RunnableLambda
+
+
+ def add_one(x: int) -> int:
+ return x + 1
+
+
+ runnable = RunnableLambda(add_one)
+
+ runnable.invoke(1) # returns 2
+ runnable.batch([1, 2, 3]) # returns [2, 3, 4]
+
+ # Async is supported by default by delegating to the sync implementation
+ await runnable.ainvoke(1) # returns 2
+ await runnable.abatch([1, 2, 3]) # returns [2, 3, 4]
+
+
+ # Alternatively, can provide both synd and sync implementations
+ async def add_one_async(x: int) -> int:
+ return x + 1
+
+
+ runnable = RunnableLambda(add_one, afunc=add_one_async)
+ runnable.invoke(1) # Uses add_one
+ await runnable.ainvoke(1) # Uses add_one_async
+ ```
+ """
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input, RunnableConfig], Awaitable[Output]],
+ afunc: None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input], Awaitable[Output]],
+ afunc: None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input], AsyncIterator[Output]],
+ afunc: None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]],
+ afunc: None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ],
+ afunc: None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input, RunnableConfig], Output],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input], Iterator[Output]],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input], Runnable[Input, Output]],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input, CallbackManagerForChainRun], Output],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ @overload
+ def __init__(
+ self,
+ func: Callable[[Input], Output],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None: ...
+
+ def __init__(
+ self,
+ func: Callable[[Input], Iterator[Output]]
+ | Callable[[Input], Runnable[Input, Output]]
+ | Callable[[Input], Output]
+ | Callable[[Input, RunnableConfig], Output]
+ | Callable[[Input, CallbackManagerForChainRun], Output]
+ | Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]
+ | Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ],
+ afunc: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input], AsyncIterator[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ]
+ | None = None,
+ name: str | None = None,
+ ) -> None:
+ """Create a `RunnableLambda` from a callable, and async callable or both.
+
+ Accepts both sync and async variants to allow providing efficient
+ implementations for sync and async execution.
+
+ Args:
+ func: Either sync or async callable
+ afunc: An async callable that takes an input and returns an output.
+
+ name: The name of the `Runnable`.
+
+ Raises:
+ TypeError: If the `func` is not a callable type.
+ TypeError: If both `func` and `afunc` are provided.
+
+ """
+ if afunc is not None:
+ self.afunc = afunc
+ func_for_name: Callable = afunc
+
+ if is_async_callable(func) or is_async_generator(func):
+ if afunc is not None:
+ msg = (
+ "Func was provided as a coroutine function, but afunc was "
+ "also provided. If providing both, func should be a regular "
+ "function to avoid ambiguity."
+ )
+ raise TypeError(msg)
+ self.afunc = func
+ func_for_name = func
+ elif callable(func):
+ self.func = cast("Callable[[Input], Output]", func)
+ func_for_name = func
+ else:
+ msg = (
+ "Expected a callable type for `func`."
+ f"Instead got an unsupported type: {type(func)}"
+ )
+ raise TypeError(msg)
+
+ try:
+ if name is not None:
+ self.name = name
+ elif func_for_name.__name__ != "":
+ self.name = func_for_name.__name__
+ except AttributeError:
+ pass
+
+ self._repr: str | None = None
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ """The type of the input to this `Runnable`."""
+ func = getattr(self, "func", None) or self.afunc
+ try:
+ params = inspect.signature(func).parameters
+ first_param = next(iter(params.values()), None)
+ if first_param and first_param.annotation != inspect.Parameter.empty:
+ return first_param.annotation
+ except ValueError:
+ pass
+ return Any
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ """The Pydantic schema for the input to this `Runnable`.
+
+ Args:
+ config: The config to use.
+
+ Returns:
+ The input schema for this `Runnable`.
+
+ """
+ func = getattr(self, "func", None) or self.afunc
+
+ if isinstance(func, itemgetter):
+ # This is terrible, but afaict it's not possible to access _items
+ # on itemgetter objects, so we have to parse the repr
+ items = str(func).replace("operator.itemgetter(", "")[:-1].split(", ")
+ if all(
+ item[0] == "'" and item[-1] == "'" and item != "''" for item in items
+ ):
+ fields = {item[1:-1]: (Any, ...) for item in items}
+ # It's a dict, lol
+ return create_model_v2(self.get_name("Input"), field_definitions=fields)
+ module = getattr(func, "__module__", None)
+ return create_model_v2(
+ self.get_name("Input"),
+ root=list[Any],
+ # To create the schema, we need to provide the module
+ # where the underlying function is defined.
+ # This allows pydantic to resolve type annotations appropriately.
+ module_name=module,
+ )
+
+ if self.InputType != Any:
+ return super().get_input_schema(config)
+
+ if dict_keys := get_function_first_arg_dict_keys(func):
+ return create_model_v2(
+ self.get_name("Input"),
+ field_definitions=dict.fromkeys(dict_keys, (Any, ...)),
+ )
+
+ return super().get_input_schema(config)
+
+ @property
+ @override
+ def OutputType(self) -> Any:
+ """The type of the output of this `Runnable` as a type annotation.
+
+ Returns:
+ The type of the output of this `Runnable`.
+
+ """
+ func = getattr(self, "func", None) or self.afunc
+ try:
+ sig = inspect.signature(func)
+ if sig.return_annotation != inspect.Signature.empty:
+ # unwrap iterator types
+ if getattr(sig.return_annotation, "__origin__", None) in {
+ collections.abc.Iterator,
+ collections.abc.AsyncIterator,
+ }:
+ return getattr(sig.return_annotation, "__args__", (Any,))[0]
+ return sig.return_annotation
+ except ValueError:
+ pass
+ return Any
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ # Override the default implementation.
+ # For a runnable lambda, we need to bring to provide the
+ # module of the underlying function when creating the model.
+ root_type = self.OutputType
+ func = getattr(self, "func", None) or self.afunc
+ module = getattr(func, "__module__", None)
+
+ if (
+ inspect.isclass(root_type)
+ and not isinstance(root_type, GenericAlias)
+ and issubclass(root_type, BaseModel)
+ ):
+ return root_type
+
+ return create_model_v2(
+ self.get_name("Output"),
+ root=root_type,
+ # To create the schema, we need to provide the module
+ # where the underlying function is defined.
+ # This allows pydantic to resolve type annotations appropriately.
+ module_name=module,
+ )
+
+ @functools.cached_property
+ def deps(self) -> list[Runnable]:
+ """The dependencies of this `Runnable`.
+
+ Returns:
+ The dependencies of this `Runnable`. If the function has nonlocal
+ variables that are `Runnable`s, they are considered dependencies.
+
+ """
+ if hasattr(self, "func"):
+ objects = get_function_nonlocals(self.func)
+ elif hasattr(self, "afunc"):
+ objects = get_function_nonlocals(self.afunc)
+ else:
+ objects = []
+
+ deps: list[Runnable] = []
+ for obj in objects:
+ if isinstance(obj, Runnable):
+ deps.append(obj)
+ elif isinstance(getattr(obj, "__self__", None), Runnable):
+ deps.append(obj.__self__)
+ return deps
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return get_unique_config_specs(
+ spec for dep in self.deps for spec in dep.config_specs
+ )
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ if deps := self.deps:
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph import Graph # noqa: PLC0415
+
+ graph = Graph()
+ input_node = graph.add_node(self.get_input_schema(config))
+ output_node = graph.add_node(self.get_output_schema(config))
+ for dep in deps:
+ dep_graph = dep.get_graph()
+ dep_graph.trim_first_node()
+ dep_graph.trim_last_node()
+ if not dep_graph:
+ graph.add_edge(input_node, output_node)
+ else:
+ dep_first_node, dep_last_node = graph.extend(dep_graph)
+ if not dep_first_node:
+ msg = f"Runnable {dep} has no first node"
+ raise ValueError(msg)
+ if not dep_last_node:
+ msg = f"Runnable {dep} has no last node"
+ raise ValueError(msg)
+ graph.add_edge(input_node, dep_first_node)
+ graph.add_edge(dep_last_node, output_node)
+ else:
+ graph = super().get_graph(config)
+
+ return graph
+
+ @override
+ def __eq__(self, other: object) -> bool:
+ if isinstance(other, RunnableLambda):
+ if hasattr(self, "func") and hasattr(other, "func"):
+ return self.func == other.func
+ if hasattr(self, "afunc") and hasattr(other, "afunc"):
+ return self.afunc == other.afunc
+ return False
+ return False
+
+ __hash__ = None # type: ignore[assignment]
+
+ def __repr__(self) -> str:
+ """Return a string representation of this `Runnable`."""
+ if self._repr is None:
+ if hasattr(self, "func") and isinstance(self.func, itemgetter):
+ self._repr = f"RunnableLambda({str(self.func)[len('operator.') :]})"
+ elif hasattr(self, "func"):
+ self._repr = f"RunnableLambda({get_lambda_source(self.func) or '...'})"
+ elif hasattr(self, "afunc"):
+ self._repr = (
+ f"RunnableLambda(afunc={get_lambda_source(self.afunc) or '...'})"
+ )
+ else:
+ self._repr = "RunnableLambda(...)"
+ return self._repr
+
+ def _invoke(
+ self,
+ input_: Input,
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ if inspect.isgeneratorfunction(self.func):
+ output: Output | None = None
+ for chunk in call_func_with_variable_args(
+ cast("Callable[[Input], Iterator[Output]]", self.func),
+ input_,
+ config,
+ run_manager,
+ **kwargs,
+ ):
+ if output is None:
+ output = chunk
+ else:
+ try:
+ output = output + chunk # type: ignore[operator]
+ except TypeError:
+ output = chunk
+ else:
+ output = call_func_with_variable_args(
+ self.func, input_, config, run_manager, **kwargs
+ )
+ # If the output is a Runnable, invoke it
+ if isinstance(output, Runnable):
+ recursion_limit = config["recursion_limit"]
+ if recursion_limit <= 0:
+ msg = (
+ f"Recursion limit reached when invoking {self} with input {input_}."
+ )
+ raise RecursionError(msg)
+ output = output.invoke(
+ input_,
+ patch_config(
+ config,
+ callbacks=run_manager.get_child(),
+ recursion_limit=recursion_limit - 1,
+ ),
+ )
+ return cast("Output", output)
+
+ async def _ainvoke(
+ self,
+ value: Input,
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ if hasattr(self, "afunc"):
+ afunc = self.afunc
+ else:
+ if inspect.isgeneratorfunction(self.func):
+
+ def func(
+ value: Input,
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ output: Output | None = None
+ for chunk in call_func_with_variable_args(
+ cast("Callable[[Input], Iterator[Output]]", self.func),
+ value,
+ config,
+ run_manager.get_sync(),
+ **kwargs,
+ ):
+ if output is None:
+ output = chunk
+ else:
+ try:
+ output = output + chunk # type: ignore[operator]
+ except TypeError:
+ output = chunk
+ return cast("Output", output)
+
+ else:
+
+ def func(
+ value: Input,
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ return call_func_with_variable_args(
+ self.func, value, config, run_manager.get_sync(), **kwargs
+ )
+
+ @wraps(func)
+ async def f(*args: Any, **kwargs: Any) -> Any:
+ return await run_in_executor(config, func, *args, **kwargs)
+
+ afunc = f
+
+ if is_async_generator(afunc):
+ output: Output | None = None
+ async with aclosing(
+ cast(
+ "AsyncGenerator[Any, Any]",
+ acall_func_with_variable_args(
+ cast("Callable", afunc),
+ value,
+ config,
+ run_manager,
+ **kwargs,
+ ),
+ )
+ ) as stream:
+ async for chunk in cast(
+ "AsyncIterator[Output]",
+ stream,
+ ):
+ if output is None:
+ output = chunk
+ else:
+ try:
+ output = output + chunk # type: ignore[operator]
+ except TypeError:
+ output = chunk
+ else:
+ output = await acall_func_with_variable_args(
+ cast("Callable", afunc), value, config, run_manager, **kwargs
+ )
+ # If the output is a Runnable, invoke it
+ if isinstance(output, Runnable):
+ recursion_limit = config["recursion_limit"]
+ if recursion_limit <= 0:
+ msg = (
+ f"Recursion limit reached when invoking {self} with input {value}."
+ )
+ raise RecursionError(msg)
+ output = await output.ainvoke(
+ value,
+ patch_config(
+ config,
+ callbacks=run_manager.get_child(),
+ recursion_limit=recursion_limit - 1,
+ ),
+ )
+ return cast("Output", output)
+
+ @override
+ def invoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ """Invoke this `Runnable` synchronously.
+
+ Args:
+ input: The input to this `Runnable`.
+ config: The config to use.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The output of this `Runnable`.
+
+ Raises:
+ TypeError: If the `Runnable` is a coroutine function.
+
+ """
+ if hasattr(self, "func"):
+ return self._call_with_config(
+ self._invoke,
+ input,
+ ensure_config(config),
+ **kwargs,
+ )
+ msg = "Cannot invoke a coroutine function synchronously.Use `ainvoke` instead."
+ raise TypeError(msg)
+
+ @override
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ """Invoke this `Runnable` asynchronously.
+
+ Args:
+ input: The input to this `Runnable`.
+ config: The config to use.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The output of this `Runnable`.
+
+ """
+ return await self._acall_with_config(
+ self._ainvoke,
+ input,
+ ensure_config(config),
+ **kwargs,
+ )
+
+ def _transform(
+ self,
+ chunks: Iterator[Input],
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Iterator[Output]:
+ final: Input
+ got_first_val = False
+ for ichunk in chunks:
+ # By definitions, RunnableLambdas consume all input before emitting output.
+ # If the input is not addable, then we'll assume that we can
+ # only operate on the last chunk.
+ # So we'll iterate until we get to the last chunk!
+ if not got_first_val:
+ final = ichunk
+ got_first_val = True
+ else:
+ try:
+ final = final + ichunk # type: ignore[operator]
+ except TypeError:
+ final = ichunk
+
+ if inspect.isgeneratorfunction(self.func):
+ output: Output | None = None
+ for chunk in call_func_with_variable_args(
+ self.func, final, config, run_manager, **kwargs
+ ):
+ yield chunk
+ if output is None:
+ output = chunk
+ else:
+ try:
+ output = output + chunk
+ except TypeError:
+ output = chunk
+ else:
+ output = call_func_with_variable_args(
+ self.func, final, config, run_manager, **kwargs
+ )
+
+ # If the output is a Runnable, use its stream output
+ if isinstance(output, Runnable):
+ recursion_limit = config["recursion_limit"]
+ if recursion_limit <= 0:
+ msg = (
+ f"Recursion limit reached when invoking {self} with input {final}."
+ )
+ raise RecursionError(msg)
+ for chunk in output.stream(
+ final,
+ patch_config(
+ config,
+ callbacks=run_manager.get_child(),
+ recursion_limit=recursion_limit - 1,
+ ),
+ ):
+ yield chunk
+ elif not inspect.isgeneratorfunction(self.func):
+ # Otherwise, just yield it
+ yield cast("Output", output)
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ if hasattr(self, "func"):
+ yield from self._transform_stream_with_config(
+ input,
+ self._transform,
+ ensure_config(config),
+ **kwargs,
+ )
+ else:
+ msg = (
+ "Cannot stream a coroutine function synchronously."
+ "Use `astream` instead."
+ )
+ raise TypeError(msg)
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ return self.transform(iter([input]), config, **kwargs)
+
+ async def _atransform(
+ self,
+ chunks: AsyncIterator[Input],
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> AsyncIterator[Output]:
+ final: Input
+ got_first_val = False
+ async for ichunk in chunks:
+ # By definitions, RunnableLambdas consume all input before emitting output.
+ # If the input is not addable, then we'll assume that we can
+ # only operate on the last chunk.
+ # So we'll iterate until we get to the last chunk!
+ if not got_first_val:
+ final = ichunk
+ got_first_val = True
+ else:
+ try:
+ final = final + ichunk # type: ignore[operator]
+ except TypeError:
+ final = ichunk
+
+ if hasattr(self, "afunc"):
+ afunc = self.afunc
+ else:
+ if inspect.isgeneratorfunction(self.func):
+ msg = (
+ "Cannot stream from a generator function asynchronously."
+ "Use .stream() instead."
+ )
+ raise TypeError(msg)
+
+ def func(
+ input_: Input,
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ return call_func_with_variable_args(
+ self.func, input_, config, run_manager.get_sync(), **kwargs
+ )
+
+ @wraps(func)
+ async def f(*args: Any, **kwargs: Any) -> Any:
+ return await run_in_executor(config, func, *args, **kwargs)
+
+ afunc = f
+
+ if is_async_generator(afunc):
+ output: Output | None = None
+ async for chunk in cast(
+ "AsyncIterator[Output]",
+ acall_func_with_variable_args(
+ cast("Callable", afunc),
+ final,
+ config,
+ run_manager,
+ **kwargs,
+ ),
+ ):
+ yield chunk
+ if output is None:
+ output = chunk
+ else:
+ try:
+ output = output + chunk # type: ignore[operator]
+ except TypeError:
+ output = chunk
+ else:
+ output = await acall_func_with_variable_args(
+ cast("Callable", afunc),
+ final,
+ config,
+ run_manager,
+ **kwargs,
+ )
+
+ # If the output is a Runnable, use its astream output
+ if isinstance(output, Runnable):
+ recursion_limit = config["recursion_limit"]
+ if recursion_limit <= 0:
+ msg = (
+ f"Recursion limit reached when invoking {self} with input {final}."
+ )
+ raise RecursionError(msg)
+ async for chunk in output.astream(
+ final,
+ patch_config(
+ config,
+ callbacks=run_manager.get_child(),
+ recursion_limit=recursion_limit - 1,
+ ),
+ ):
+ yield chunk
+ elif not is_async_generator(afunc):
+ # Otherwise, just yield it
+ yield cast("Output", output)
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ async for output in self._atransform_stream_with_config(
+ input,
+ self._atransform,
+ ensure_config(config),
+ **kwargs,
+ ):
+ yield output
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ async def input_aiter() -> AsyncIterator[Input]:
+ yield input
+
+ async for chunk in self.atransform(input_aiter(), config, **kwargs):
+ yield chunk
+
+
+class RunnableEachBase(RunnableSerializable[list[Input], list[Output]]):
+ """RunnableEachBase class.
+
+ `Runnable` that calls another `Runnable` for each element of the input sequence.
+
+ Use only if creating a new `RunnableEach` subclass with different `__init__`
+ args.
+
+ See documentation for `RunnableEach` for more details.
+
+ """
+
+ bound: Runnable[Input, Output]
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ return list[self.bound.InputType] # type: ignore[name-defined]
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ return create_model_v2(
+ self.get_name("Input"),
+ root=(
+ list[self.bound.get_input_schema(config)], # type: ignore[misc]
+ None,
+ ),
+ # create model needs access to appropriate type annotations to be
+ # able to construct the Pydantic model.
+ # When we create the model, we pass information about the namespace
+ # where the model is being created, so the type annotations can
+ # be resolved correctly as well.
+ # self.__class__.__module__ handles the case when the Runnable is
+ # being sub-classed in a different module.
+ module_name=self.__class__.__module__,
+ )
+
+ @property
+ @override
+ def OutputType(self) -> type[list[Output]]:
+ return list[self.bound.OutputType] # type: ignore[name-defined]
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ schema = self.bound.get_output_schema(config)
+ return create_model_v2(
+ self.get_name("Output"),
+ root=list[schema], # type: ignore[valid-type]
+ # create model needs access to appropriate type annotations to be
+ # able to construct the Pydantic model.
+ # When we create the model, we pass information about the namespace
+ # where the model is being created, so the type annotations can
+ # be resolved correctly as well.
+ # self.__class__.__module__ handles the case when the Runnable is
+ # being sub-classed in a different module.
+ module_name=self.__class__.__module__,
+ )
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return self.bound.config_specs
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ return self.bound.get_graph(config)
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ def _invoke(
+ self,
+ inputs: list[Input],
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> list[Output]:
+ configs = [
+ patch_config(config, callbacks=run_manager.get_child()) for _ in inputs
+ ]
+ return self.bound.batch(inputs, configs, **kwargs)
+
+ @override
+ def invoke(
+ self, input: list[Input], config: RunnableConfig | None = None, **kwargs: Any
+ ) -> list[Output]:
+ return self._call_with_config(self._invoke, input, config, **kwargs)
+
+ async def _ainvoke(
+ self,
+ inputs: list[Input],
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> list[Output]:
+ configs = [
+ patch_config(config, callbacks=run_manager.get_child()) for _ in inputs
+ ]
+ return await self.bound.abatch(inputs, configs, **kwargs)
+
+ @override
+ async def ainvoke(
+ self, input: list[Input], config: RunnableConfig | None = None, **kwargs: Any
+ ) -> list[Output]:
+ return await self._acall_with_config(self._ainvoke, input, config, **kwargs)
+
+ @override
+ def astream_events( # type: ignore[override]
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ **kwargs: Any | None,
+ ) -> AsyncIterator[StreamEvent] | Awaitable[Any]:
+ del input, config, kwargs
+ if version == "v3":
+ return self._astream_events_unsupported_v3()
+ return self._astream_events_unsupported_v1_v2()
+
+ async def _astream_events_unsupported_v3(self) -> Any:
+ msg = "RunnableEach does not support astream_events yet."
+ raise NotImplementedError(msg)
+
+ async def _astream_events_unsupported_v1_v2(self) -> AsyncIterator[StreamEvent]:
+ msg = "RunnableEach does not support astream_events yet."
+ raise NotImplementedError(msg)
+ yield # makes this an async generator (never reached)
+
+
+class RunnableEach(RunnableEachBase[Input, Output]):
+ """RunnableEach class.
+
+ `Runnable` that calls another `Runnable` for each element of the input sequence.
+
+ It allows you to call multiple inputs with the bounded `Runnable`.
+
+ `RunnableEach` makes it easy to run multiple inputs for the `Runnable`.
+ In the below example, we associate and run three inputs
+ with a `Runnable`:
+
+ ```python
+ from langchain_core.runnables.base import RunnableEach
+ from langchain_openai import ChatOpenAI
+ from langchain_core.prompts import ChatPromptTemplate
+ from langchain_core.output_parsers import StrOutputParser
+ prompt = ChatPromptTemplate.from_template("Tell me a short joke about
+ {topic}")
+ model = ChatOpenAI()
+ output_parser = StrOutputParser()
+ runnable = prompt | model | output_parser
+ runnable_each = RunnableEach(bound=runnable)
+ output = runnable_each.invoke([{'topic':'Computer Science'},
+ {'topic':'Art'},
+ {'topic':'Biology'}])
+ print(output) # noqa: T201
+
+ ```
+ """
+
+ @override
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ name = name or self.name or f"RunnableEach<{self.bound.get_name()}>"
+ return super().get_name(suffix, name=name)
+
+ @override
+ def bind(self, **kwargs: Any) -> RunnableEach[Input, Output]:
+ return RunnableEach(bound=self.bound.bind(**kwargs))
+
+ @override
+ def with_config(
+ self, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> RunnableEach[Input, Output]:
+ return RunnableEach(bound=self.bound.with_config(config, **kwargs))
+
+ @override
+ def with_listeners(
+ self,
+ *,
+ on_start: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ on_end: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ on_error: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ ) -> RunnableEach[Input, Output]:
+ """Bind lifecycle listeners to a `Runnable`, returning a new `Runnable`.
+
+ The `Run` object contains information about the run, including its `id`,
+ `type`, `input`, `output`, `error`, `start_time`, `end_time`, and
+ any tags or metadata added to the run.
+
+ Args:
+ on_start: Called before the `Runnable` starts running, with the `Run`
+ object.
+ on_end: Called after the `Runnable` finishes running, with the `Run`
+ object.
+ on_error: Called if the `Runnable` throws an error, with the `Run`
+ object.
+
+ Returns:
+ A new `Runnable` with the listeners bound.
+
+ """
+ return RunnableEach(
+ bound=self.bound.with_listeners(
+ on_start=on_start, on_end=on_end, on_error=on_error
+ )
+ )
+
+ def with_alisteners(
+ self,
+ *,
+ on_start: AsyncListener | None = None,
+ on_end: AsyncListener | None = None,
+ on_error: AsyncListener | None = None,
+ ) -> RunnableEach[Input, Output]:
+ """Bind async lifecycle listeners to a `Runnable`.
+
+ Returns a new `Runnable`.
+
+ The `Run` object contains information about the run, including its `id`,
+ `type`, `input`, `output`, `error`, `start_time`, `end_time`, and
+ any tags or metadata added to the run.
+
+ Args:
+ on_start: Called asynchronously before the `Runnable` starts running,
+ with the `Run` object.
+ on_end: Called asynchronously after the `Runnable` finishes running,
+ with the `Run` object.
+ on_error: Called asynchronously if the `Runnable` throws an error,
+ with the `Run` object.
+
+ Returns:
+ A new `Runnable` with the listeners bound.
+
+ """
+ return RunnableEach(
+ bound=self.bound.with_alisteners(
+ on_start=on_start, on_end=on_end, on_error=on_error
+ )
+ )
+
+
+class RunnableBindingBase(RunnableSerializable[Input, Output]): # type: ignore[no-redef]
+ """`Runnable` that delegates calls to another `Runnable` with a set of `**kwargs`.
+
+ Use only if creating a new `RunnableBinding` subclass with different `__init__`
+ args.
+
+ See documentation for `RunnableBinding` for more details.
+
+ """
+
+ bound: Runnable[Input, Output]
+ """The underlying `Runnable` that this `Runnable` delegates to."""
+
+ kwargs: Mapping[str, Any] = Field(default_factory=dict)
+ """kwargs to pass to the underlying `Runnable` when running.
+
+ For example, when the `Runnable` binding is invoked the underlying
+ `Runnable` will be invoked with the same input but with these additional
+ kwargs.
+
+ """
+
+ config: RunnableConfig = Field(default_factory=RunnableConfig)
+ """The config to bind to the underlying `Runnable`."""
+
+ config_factories: list[Callable[[RunnableConfig], RunnableConfig]] = Field(
+ default_factory=list
+ )
+ """The config factories to bind to the underlying `Runnable`."""
+
+ # Union[Type[Input], BaseModel] + things like list[str]
+ custom_input_type: Any | None = None
+ """Override the input type of the underlying `Runnable` with a custom type.
+
+ The type can be a Pydantic model, or a type annotation (e.g., `list[str]`).
+ """
+ # Union[Type[Output], BaseModel] + things like list[str]
+ custom_output_type: Any | None = None
+ """Override the output type of the underlying `Runnable` with a custom type.
+
+ The type can be a Pydantic model, or a type annotation (e.g., `list[str]`).
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ def __init__(
+ self,
+ *,
+ bound: Runnable[Input, Output],
+ kwargs: Mapping[str, Any] | None = None,
+ config: RunnableConfig | None = None,
+ config_factories: list[Callable[[RunnableConfig], RunnableConfig]]
+ | None = None,
+ custom_input_type: type[Input] | BaseModel | None = None,
+ custom_output_type: type[Output] | BaseModel | None = None,
+ **other_kwargs: Any,
+ ) -> None:
+ """Create a `RunnableBinding` from a `Runnable` and kwargs.
+
+ Args:
+ bound: The underlying `Runnable` that this `Runnable` delegates calls
+ to.
+ kwargs: optional kwargs to pass to the underlying `Runnable`, when running
+ the underlying `Runnable` (e.g., via `invoke`, `batch`,
+ `transform`, or `stream` or async variants)
+
+ config: optional config to bind to the underlying `Runnable`.
+
+ config_factories: optional list of config factories to apply to the
+ config before binding to the underlying `Runnable`.
+
+ custom_input_type: Specify to override the input type of the underlying
+ `Runnable` with a custom type.
+ custom_output_type: Specify to override the output type of the underlying
+ `Runnable` with a custom type.
+ **other_kwargs: Unpacked into the base class.
+ """
+ super().__init__(
+ bound=bound,
+ kwargs=kwargs or {},
+ config=config or {},
+ config_factories=config_factories or [],
+ custom_input_type=custom_input_type,
+ custom_output_type=custom_output_type,
+ **other_kwargs,
+ )
+ # if we don't explicitly set config to the TypedDict here,
+ # the pydantic init above will strip out any of the "extra"
+ # fields even though total=False on the typed dict.
+ self.config = config or {}
+
+ @override
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ return self.bound.get_name(suffix, name=name)
+
+ @property
+ @override
+ def InputType(self) -> type[Input]:
+ return (
+ cast("type[Input]", self.custom_input_type)
+ if self.custom_input_type is not None
+ else self.bound.InputType
+ )
+
+ @property
+ @override
+ def OutputType(self) -> type[Output]:
+ return (
+ cast("type[Output]", self.custom_output_type)
+ if self.custom_output_type is not None
+ else self.bound.OutputType
+ )
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ if self.custom_input_type is not None:
+ return super().get_input_schema(config)
+ return self.bound.get_input_schema(merge_configs(self.config, config))
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ if self.custom_output_type is not None:
+ return super().get_output_schema(config)
+ return self.bound.get_output_schema(merge_configs(self.config, config))
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return self.bound.config_specs
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ return self.bound.get_graph(self._merge_configs(config))
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ def _merge_configs(self, *configs: RunnableConfig | None) -> RunnableConfig:
+ config = merge_configs(self.config, *configs)
+ return merge_configs(config, *(f(config) for f in self.config_factories))
+
+ @override
+ def invoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ return self.bound.invoke(
+ input,
+ self._merge_configs(config),
+ **{**self.kwargs, **kwargs},
+ )
+
+ @override
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ return await self.bound.ainvoke(
+ input,
+ self._merge_configs(config),
+ **{**self.kwargs, **kwargs},
+ )
+
+ @override
+ def batch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if isinstance(config, list):
+ configs = cast(
+ "list[RunnableConfig]",
+ [self._merge_configs(conf) for conf in config],
+ )
+ else:
+ configs = [self._merge_configs(config) for _ in range(len(inputs))]
+ return self.bound.batch(
+ inputs,
+ configs,
+ return_exceptions=return_exceptions,
+ **{**self.kwargs, **kwargs},
+ )
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if isinstance(config, list):
+ configs = cast(
+ "list[RunnableConfig]",
+ [self._merge_configs(conf) for conf in config],
+ )
+ else:
+ configs = [self._merge_configs(config) for _ in range(len(inputs))]
+ return await self.bound.abatch(
+ inputs,
+ configs,
+ return_exceptions=return_exceptions,
+ **{**self.kwargs, **kwargs},
+ )
+
+ @overload
+ def batch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[False] = False,
+ **kwargs: Any,
+ ) -> Iterator[tuple[int, Output]]: ...
+
+ @overload
+ def batch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[True],
+ **kwargs: Any,
+ ) -> Iterator[tuple[int, Output | Exception]]: ...
+
+ @override
+ def batch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> Iterator[tuple[int, Output | Exception]]:
+ if isinstance(config, Sequence):
+ configs = cast(
+ "list[RunnableConfig]",
+ [self._merge_configs(conf) for conf in config],
+ )
+ else:
+ configs = [self._merge_configs(config) for _ in range(len(inputs))]
+ # lol mypy
+ if return_exceptions:
+ yield from self.bound.batch_as_completed(
+ inputs,
+ configs,
+ return_exceptions=return_exceptions,
+ **{**self.kwargs, **kwargs},
+ )
+ else:
+ yield from self.bound.batch_as_completed(
+ inputs,
+ configs,
+ return_exceptions=return_exceptions,
+ **{**self.kwargs, **kwargs},
+ )
+
+ @overload
+ def abatch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[False] = False,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[tuple[int, Output]]: ...
+
+ @overload
+ def abatch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: Literal[True],
+ **kwargs: Any | None,
+ ) -> AsyncIterator[tuple[int, Output | Exception]]: ...
+
+ @override
+ async def abatch_as_completed(
+ self,
+ inputs: Sequence[Input],
+ config: RunnableConfig | Sequence[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[tuple[int, Output | Exception]]:
+ if isinstance(config, Sequence):
+ configs = cast(
+ "list[RunnableConfig]",
+ [self._merge_configs(conf) for conf in config],
+ )
+ else:
+ configs = [self._merge_configs(config) for _ in range(len(inputs))]
+ if return_exceptions:
+ async for item in self.bound.abatch_as_completed(
+ inputs,
+ configs,
+ return_exceptions=return_exceptions,
+ **{**self.kwargs, **kwargs},
+ ):
+ yield item
+ else:
+ async for item in self.bound.abatch_as_completed(
+ inputs,
+ configs,
+ return_exceptions=return_exceptions,
+ **{**self.kwargs, **kwargs},
+ ):
+ yield item
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ yield from self.bound.stream(
+ input,
+ self._merge_configs(config),
+ **{**self.kwargs, **kwargs},
+ )
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ async for item in self.bound.astream(
+ input,
+ self._merge_configs(config),
+ **{**self.kwargs, **kwargs},
+ ):
+ yield item
+
+ @overload
+ def stream_events(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent]: ...
+
+ @overload
+ def stream_events(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ **kwargs: Any,
+ ) -> Any: ...
+
+ def stream_events(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2", "v3"] = "v2",
+ **kwargs: Any,
+ ) -> Iterator[StreamEvent] | Any:
+ """Forward `stream_events` to the bound runnable with bound kwargs merged.
+
+ For `version="v3"`, the bound runnable's typed stream object (e.g.
+ `ChatModelStream`) is returned. For `version="v1"` / `"v2"`, dispatches
+ to the base `Runnable.stream_events`.
+
+ Without this override, `__getattr__` would drop `self.kwargs` — losing
+ tools bound via `bind_tools`, `stop` sequences, etc.
+ """
+ # Probe `version` from the merged view so `bind(version="v3")` routes
+ # correctly even when the caller doesn't repeat `version` at the call
+ # site, and strip it before forwarding so it isn't passed twice.
+ merged_kwargs = {**self.kwargs, **kwargs}
+ version = merged_kwargs.get("version", version)
+ merged_without_version = {
+ k: v for k, v in merged_kwargs.items() if k != "version"
+ }
+ if version == "v3":
+ return self.bound.stream_events(
+ input,
+ self._merge_configs(config),
+ version="v3",
+ **merged_without_version,
+ )
+ return super().stream_events(
+ input,
+ self._merge_configs(config),
+ version=version,
+ **merged_without_version,
+ )
+
+ async def _astream_events_v3(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Return the v3 async stream object from the bound runnable.
+
+ Returns an awaitable (an `async def` coroutine, not an async
+ generator) so callers can `await` it to obtain the typed stream
+ (e.g. `AsyncChatModelStream`) directly — Python does not allow
+ `return ` inside an async generator.
+
+ The caller is responsible for merging `self.kwargs` and stripping
+ `version`; this method passes `version="v3"` explicitly and would
+ raise on a duplicate keyword.
+ """
+ return await self.bound.astream_events(
+ input,
+ self._merge_configs(config),
+ version="v3",
+ **kwargs,
+ )
+
+ @overload
+ def astream_events(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v1", "v2"] = "v2",
+ **kwargs: Any,
+ ) -> AsyncIterator[StreamEvent]: ...
+
+ @overload
+ def astream_events(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ *,
+ version: Literal["v3"],
+ **kwargs: Any,
+ ) -> Awaitable[Any]: ...
+
+ @override
+ def astream_events(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[StreamEvent] | Awaitable[Any]:
+ """Forward `astream_events` to the bound runnable with bound kwargs merged.
+
+ For `version="v3"`, returns an awaitable that resolves to the
+ bound runnable's typed stream object (e.g. `AsyncChatModelStream`).
+ For `version="v1"` / `"v2"`, returns an async iterator over
+ `StreamEvent` items.
+
+ Without this override, `__getattr__` would drop `self.kwargs` — losing
+ tools bound via `bind_tools`, `stop` sequences, etc.
+ """
+ # Probe `version` from the merged view so `bind(version="v3")` routes
+ # correctly even when the caller doesn't repeat `version` at the call
+ # site.
+ merged_kwargs = {**self.kwargs, **kwargs}
+ version = merged_kwargs.get("version", "v2")
+ if version == "v3":
+ merged_without_version = {
+ k: v for k, v in merged_kwargs.items() if k != "version"
+ }
+ return self._astream_events_v3(input, config, **merged_without_version)
+ # v1/v2: bound.astream_events is a real async generator — iterate it
+ # directly without an extra wrapper layer.
+ return cast(
+ "AsyncIterator[StreamEvent]",
+ self.bound.astream_events(
+ input, self._merge_configs(config), **merged_kwargs
+ ),
+ )
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Output]:
+ yield from self.bound.transform(
+ input,
+ self._merge_configs(config),
+ **{**self.kwargs, **kwargs},
+ )
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Output]:
+ async for item in self.bound.atransform(
+ input,
+ self._merge_configs(config),
+ **{**self.kwargs, **kwargs},
+ ):
+ yield item
+
+
+class RunnableBinding(RunnableBindingBase[Input, Output]): # type: ignore[no-redef]
+ """Wrap a `Runnable` with additional functionality.
+
+ A `RunnableBinding` can be thought of as a "runnable decorator" that
+ preserves the essential features of `Runnable`; i.e., batching, streaming,
+ and async support, while adding additional functionality.
+
+ Any class that inherits from `Runnable` can be bound to a `RunnableBinding`.
+ Runnables expose a standard set of methods for creating `RunnableBindings`
+ or sub-classes of `RunnableBindings` (e.g., `RunnableRetry`,
+ `RunnableWithFallbacks`) that add additional functionality.
+
+ These methods include:
+
+ - `bind`: Bind kwargs to pass to the underlying `Runnable` when running it.
+ - `with_config`: Bind config to pass to the underlying `Runnable` when running
+ it.
+ - `with_listeners`: Bind lifecycle listeners to the underlying `Runnable`.
+ - `with_types`: Override the input and output types of the underlying
+ `Runnable`.
+ - `with_retry`: Bind a retry policy to the underlying `Runnable`.
+ - `with_fallbacks`: Bind a fallback policy to the underlying `Runnable`.
+
+ Example:
+ `bind`: Bind kwargs to pass to the underlying `Runnable` when running it.
+
+ ```python
+ # Create a Runnable binding that invokes the chat model with the
+ # additional kwarg `stop=['-']` when running it.
+ from langchain_openai import ChatOpenAI
+
+ model = ChatOpenAI()
+ model.invoke('Say "Parrot-MAGIC"', stop=["-"]) # Should return `Parrot`
+ # Using it the easy way via `bind` method which returns a new
+ # RunnableBinding
+ runnable_binding = model.bind(stop=["-"])
+ runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
+ ```
+ Can also be done by instantiating a `RunnableBinding` directly (not
+ recommended):
+
+ ```python
+ from langchain_core.runnables import RunnableBinding
+
+ runnable_binding = RunnableBinding(
+ bound=model,
+ kwargs={"stop": ["-"]}, # <-- Note the additional kwargs
+ )
+ runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
+ ```
+ """
+
+ @override
+ def bind(self, **kwargs: Any) -> Runnable[Input, Output]:
+ """Bind additional kwargs to a `Runnable`, returning a new `Runnable`.
+
+ Args:
+ **kwargs: The kwargs to bind to the `Runnable`.
+
+ Returns:
+ A new `Runnable` with the same type and config as the original,
+ but with the additional kwargs bound.
+
+ """
+ return self.__class__(
+ bound=self.bound,
+ config=self.config,
+ config_factories=self.config_factories,
+ kwargs={**self.kwargs, **kwargs},
+ custom_input_type=self.custom_input_type,
+ custom_output_type=self.custom_output_type,
+ )
+
+ @override
+ def with_config(
+ self,
+ config: RunnableConfig | None = None,
+ # Sadly Unpack is not well supported by mypy so this will have to be untyped
+ **kwargs: Any,
+ ) -> Runnable[Input, Output]:
+ return self.__class__(
+ bound=self.bound,
+ kwargs=self.kwargs,
+ config=cast("RunnableConfig", {**self.config, **(config or {}), **kwargs}),
+ config_factories=self.config_factories,
+ custom_input_type=self.custom_input_type,
+ custom_output_type=self.custom_output_type,
+ )
+
+ @override
+ def with_listeners(
+ self,
+ *,
+ on_start: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ on_end: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ on_error: Callable[[Run], None]
+ | Callable[[Run, RunnableConfig], None]
+ | None = None,
+ ) -> Runnable[Input, Output]:
+ """Bind lifecycle listeners to a `Runnable`, returning a new `Runnable`.
+
+ The `Run` object contains information about the run, including its `id`,
+ `type`, `input`, `output`, `error`, `start_time`, `end_time`, and
+ any tags or metadata added to the run.
+
+ Args:
+ on_start: Called before the `Runnable` starts running, with the `Run`
+ object.
+ on_end: Called after the `Runnable` finishes running, with the `Run`
+ object.
+ on_error: Called if the `Runnable` throws an error, with the `Run`
+ object.
+
+ Returns:
+ A new `Runnable` with the listeners bound.
+ """
+
+ def listener_config_factory(config: RunnableConfig) -> RunnableConfig:
+ return {
+ "callbacks": [
+ RootListenersTracer(
+ config=config,
+ on_start=on_start,
+ on_end=on_end,
+ on_error=on_error,
+ )
+ ],
+ }
+
+ return self.__class__(
+ bound=self.bound,
+ kwargs=self.kwargs,
+ config=self.config,
+ config_factories=[listener_config_factory, *self.config_factories],
+ custom_input_type=self.custom_input_type,
+ custom_output_type=self.custom_output_type,
+ )
+
+ @override
+ def with_types(
+ self,
+ input_type: type[Input] | BaseModel | None = None,
+ output_type: type[Output] | BaseModel | None = None,
+ ) -> Runnable[Input, Output]:
+ return self.__class__(
+ bound=self.bound,
+ kwargs=self.kwargs,
+ config=self.config,
+ config_factories=self.config_factories,
+ custom_input_type=(
+ input_type if input_type is not None else self.custom_input_type
+ ),
+ custom_output_type=(
+ output_type if output_type is not None else self.custom_output_type
+ ),
+ )
+
+ @override
+ def with_retry(self, **kwargs: Any) -> Runnable[Input, Output]:
+ return self.__class__(
+ bound=self.bound.with_retry(**kwargs),
+ kwargs=self.kwargs,
+ config=self.config,
+ config_factories=self.config_factories,
+ )
+
+ @override
+ def __getattr__(self, name: str) -> Any: # type: ignore[misc]
+ attr = getattr(self.bound, name)
+
+ if callable(attr) and (
+ config_param := inspect.signature(attr).parameters.get("config")
+ ):
+ if config_param.kind == inspect.Parameter.KEYWORD_ONLY:
+
+ @wraps(attr)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ return attr(
+ *args,
+ config=merge_configs(self.config, kwargs.pop("config", None)),
+ **kwargs,
+ )
+
+ return wrapper
+ if config_param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:
+ idx = list(inspect.signature(attr).parameters).index("config")
+
+ @wraps(attr)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ if len(args) >= idx + 1:
+ argsl = list(args)
+ argsl[idx] = merge_configs(self.config, argsl[idx])
+ return attr(*argsl, **kwargs)
+ return attr(
+ *args,
+ config=merge_configs(self.config, kwargs.pop("config", None)),
+ **kwargs,
+ )
+
+ return wrapper
+
+ return attr
+
+
+class _RunnableCallableSync(Protocol[Input, Output]):
+ def __call__(self, _in: Input, /, *, config: RunnableConfig) -> Output: ...
+
+
+class _RunnableCallableAsync(Protocol[Input, Output]):
+ def __call__(
+ self, _in: Input, /, *, config: RunnableConfig
+ ) -> Awaitable[Output]: ...
+
+
+class _RunnableCallableIterator(Protocol[Input, Output]):
+ def __call__(
+ self, _in: Iterator[Input], /, *, config: RunnableConfig
+ ) -> Iterator[Output]: ...
+
+
+class _RunnableCallableAsyncIterator(Protocol[Input, Output]):
+ def __call__(
+ self, _in: AsyncIterator[Input], /, *, config: RunnableConfig
+ ) -> AsyncIterator[Output]: ...
+
+
+RunnableLike = (
+ Runnable[Input, Output]
+ | Callable[[Input], Output]
+ | Callable[[Input], Awaitable[Output]]
+ | Callable[[Iterator[Input]], Iterator[Output]]
+ | Callable[[AsyncIterator[Input]], AsyncIterator[Output]]
+ | _RunnableCallableSync[Input, Output]
+ | _RunnableCallableAsync[Input, Output]
+ | _RunnableCallableIterator[Input, Output]
+ | _RunnableCallableAsyncIterator[Input, Output]
+ | Mapping[str, Any]
+)
+
+
+def coerce_to_runnable(thing: RunnableLike) -> Runnable[Input, Output]:
+ """Coerce a `Runnable`-like object into a `Runnable`.
+
+ Args:
+ thing: A `Runnable`-like object.
+
+ Returns:
+ A `Runnable`.
+
+ Raises:
+ TypeError: If the object is not `Runnable`-like.
+ """
+ if isinstance(thing, Runnable):
+ return thing
+ if is_async_generator(thing) or inspect.isgeneratorfunction(thing):
+ return RunnableGenerator(thing)
+ if callable(thing):
+ return RunnableLambda(cast("Callable[[Input], Output]", thing))
+ if isinstance(thing, dict):
+ return cast("Runnable[Input, Output]", RunnableParallel(thing))
+ msg = (
+ f"Expected a Runnable, callable or dict."
+ f"Instead got an unsupported type: {type(thing)}"
+ )
+ raise TypeError(msg)
+
+
+@overload
+def chain(
+ func: Callable[[Input], Coroutine[Any, Any, Output]],
+) -> Runnable[Input, Output]: ...
+
+
+@overload
+def chain(
+ func: Callable[[Input], Iterator[Output]],
+) -> Runnable[Input, Output]: ...
+
+
+@overload
+def chain(
+ func: Callable[[Input], AsyncIterator[Output]],
+) -> Runnable[Input, Output]: ...
+
+
+@overload
+def chain(
+ func: Callable[[Input], Output],
+) -> Runnable[Input, Output]: ...
+
+
+def chain(
+ func: Callable[[Input], Output]
+ | Callable[[Input], Iterator[Output]]
+ | Callable[[Input], Coroutine[Any, Any, Output]]
+ | Callable[[Input], AsyncIterator[Output]],
+) -> Runnable[Input, Output]:
+ """Decorate a function to make it a `Runnable`.
+
+ Sets the name of the `Runnable` to the name of the function.
+ Any runnables called by the function will be traced as dependencies.
+
+ Args:
+ func: A `Callable`.
+
+ Returns:
+ A `Runnable`.
+
+ Example:
+ ```python
+ from langchain_core.runnables import chain
+ from langchain_core.prompts import PromptTemplate
+ from langchain_openai import OpenAI
+
+
+ @chain
+ def my_func(fields):
+ prompt = PromptTemplate("Hello, {name}!")
+ model = OpenAI()
+ formatted = prompt.invoke(**fields)
+
+ for chunk in model.stream(formatted):
+ yield chunk
+ ```
+ """
+ return RunnableLambda(func)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/branch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/branch.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca3dfd99da6b983a243b45dd0c9844dc31a02755
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/branch.py
@@ -0,0 +1,461 @@
+"""Runnable that selects which branch to run based on a condition."""
+
+from collections.abc import (
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Iterator,
+ Mapping,
+ Sequence,
+)
+from typing import (
+ Any,
+ cast,
+)
+
+from pydantic import BaseModel, ConfigDict
+from typing_extensions import override
+
+from langchain_core.runnables.base import (
+ Runnable,
+ RunnableLike,
+ RunnableSerializable,
+ coerce_to_runnable,
+)
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ ensure_config,
+ get_async_callback_manager_for_config,
+ get_callback_manager_for_config,
+ patch_config,
+)
+from langchain_core.runnables.utils import (
+ ConfigurableFieldSpec,
+ Input,
+ Output,
+ get_unique_config_specs,
+)
+
+_MIN_BRANCHES = 2
+
+
+class RunnableBranch(RunnableSerializable[Input, Output]):
+ """`Runnable` that selects which branch to run based on a condition.
+
+ The `Runnable` is initialized with a list of `(condition, Runnable)` pairs and
+ a default branch.
+
+ When operating on an input, the first condition that evaluates to True is
+ selected, and the corresponding `Runnable` is run on the input.
+
+ If no condition evaluates to `True`, the default branch is run on the input.
+
+ Examples:
+ ```python
+ from langchain_core.runnables import RunnableBranch
+
+ branch = RunnableBranch(
+ (lambda x: isinstance(x, str), lambda x: x.upper()),
+ (lambda x: isinstance(x, int), lambda x: x + 1),
+ (lambda x: isinstance(x, float), lambda x: x * 2),
+ lambda x: "goodbye",
+ )
+
+ branch.invoke("hello") # "HELLO"
+ branch.invoke(None) # "goodbye"
+ ```
+ """
+
+ branches: Sequence[tuple[Runnable[Input, bool], Runnable[Input, Output]]]
+ """A list of `(condition, Runnable)` pairs."""
+ default: Runnable[Input, Output]
+ """A `Runnable` to run if no condition is met."""
+
+ def __init__(
+ self,
+ *branches: tuple[
+ Runnable[Input, bool]
+ | Callable[[Input], bool]
+ | Callable[[Input], Awaitable[bool]],
+ RunnableLike,
+ ]
+ | RunnableLike,
+ ) -> None:
+ """A `Runnable` that runs one of two branches based on a condition.
+
+ Args:
+ *branches: A list of `(condition, Runnable)` pairs.
+ Defaults a `Runnable` to run if no condition is met.
+
+ Raises:
+ ValueError: If the number of branches is less than `2`.
+ TypeError: If the default branch is not `Runnable`, `Callable` or `Mapping`.
+ TypeError: If a branch is not a `tuple` or `list`.
+ ValueError: If a branch is not of length `2`.
+ """
+ if len(branches) < _MIN_BRANCHES:
+ msg = "RunnableBranch requires at least two branches"
+ raise ValueError(msg)
+
+ default = branches[-1]
+
+ if not isinstance(
+ default,
+ (Runnable, Callable, Mapping), # type: ignore[arg-type]
+ ):
+ msg = "RunnableBranch default must be Runnable, callable or mapping."
+ raise TypeError(msg)
+
+ default_ = cast(
+ "Runnable[Input, Output]", coerce_to_runnable(cast("RunnableLike", default))
+ )
+
+ branches_ = []
+
+ for branch in branches[:-1]:
+ if not isinstance(branch, (tuple, list)):
+ msg = (
+ f"RunnableBranch branches must be "
+ f"tuples or lists, not {type(branch)}"
+ )
+ raise TypeError(msg)
+
+ if len(branch) != _MIN_BRANCHES:
+ msg = (
+ f"RunnableBranch branches must be "
+ f"tuples or lists of length 2, not {len(branch)}"
+ )
+ raise ValueError(msg)
+ condition, runnable = branch
+ condition = cast("Runnable[Input, bool]", coerce_to_runnable(condition))
+ runnable = coerce_to_runnable(runnable)
+ branches_.append((condition, runnable))
+
+ super().__init__(
+ branches=branches_,
+ default=default_,
+ )
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @classmethod
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ runnables = (
+ [self.default]
+ + [r for _, r in self.branches]
+ + [r for r, _ in self.branches]
+ )
+
+ for runnable in runnables:
+ if (
+ runnable.get_input_schema(config).model_json_schema().get("type")
+ is not None
+ ):
+ return runnable.get_input_schema(config)
+
+ return super().get_input_schema(config)
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return get_unique_config_specs(
+ spec
+ for step in (
+ [self.default]
+ + [r for _, r in self.branches]
+ + [r for r, _ in self.branches]
+ )
+ for spec in step.config_specs
+ )
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ """First evaluates the condition, then delegate to `True` or `False` branch.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The configuration for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Returns:
+ The output of the branch that was run.
+ """
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+
+ try:
+ for idx, branch in enumerate(self.branches):
+ condition, runnable = branch
+
+ expression_value = condition.invoke(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"condition:{idx + 1}"),
+ ),
+ )
+
+ if expression_value:
+ output = runnable.invoke(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"branch:{idx + 1}"),
+ ),
+ **kwargs,
+ )
+ break
+ else:
+ output = self.default.invoke(
+ input,
+ config=patch_config(
+ config, callbacks=run_manager.get_child(tag="branch:default")
+ ),
+ **kwargs,
+ )
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ run_manager.on_chain_end(output)
+ return output
+
+ @override
+ async def ainvoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ try:
+ for idx, branch in enumerate(self.branches):
+ condition, runnable = branch
+
+ expression_value = await condition.ainvoke(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"condition:{idx + 1}"),
+ ),
+ )
+
+ if expression_value:
+ output = await runnable.ainvoke(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"branch:{idx + 1}"),
+ ),
+ **kwargs,
+ )
+ break
+ else:
+ output = await self.default.ainvoke(
+ input,
+ config=patch_config(
+ config, callbacks=run_manager.get_child(tag="branch:default")
+ ),
+ **kwargs,
+ )
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ await run_manager.on_chain_end(output)
+ return output
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ """First evaluates the condition, then delegate to `True` or `False` branch.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The configuration for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ The output of the branch that was run.
+ """
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ final_output: Output | None = None
+ final_output_supported = True
+
+ try:
+ for idx, branch in enumerate(self.branches):
+ condition, runnable = branch
+
+ expression_value = condition.invoke(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"condition:{idx + 1}"),
+ ),
+ )
+
+ if expression_value:
+ for chunk in runnable.stream(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"branch:{idx + 1}"),
+ ),
+ **kwargs,
+ ):
+ yield chunk
+ if final_output_supported:
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk # type: ignore[operator]
+ except TypeError:
+ final_output = None
+ final_output_supported = False
+ break
+ else:
+ for chunk in self.default.stream(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag="branch:default"),
+ ),
+ **kwargs,
+ ):
+ yield chunk
+ if final_output_supported:
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk # type: ignore[operator]
+ except TypeError:
+ final_output = None
+ final_output_supported = False
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ run_manager.on_chain_end(final_output)
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ """First evaluates the condition, then delegate to `True` or `False` branch.
+
+ Args:
+ input: The input to the `Runnable`.
+ config: The configuration for the `Runnable`.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Yields:
+ The output of the branch that was run.
+ """
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ final_output: Output | None = None
+ final_output_supported = True
+
+ try:
+ for idx, branch in enumerate(self.branches):
+ condition, runnable = branch
+
+ expression_value = await condition.ainvoke(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"condition:{idx + 1}"),
+ ),
+ )
+
+ if expression_value:
+ async for chunk in runnable.astream(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag=f"branch:{idx + 1}"),
+ ),
+ **kwargs,
+ ):
+ yield chunk
+ if final_output_supported:
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk # type: ignore[operator]
+ except TypeError:
+ final_output = None
+ final_output_supported = False
+ break
+ else:
+ async for chunk in self.default.astream(
+ input,
+ config=patch_config(
+ config,
+ callbacks=run_manager.get_child(tag="branch:default"),
+ ),
+ **kwargs,
+ ):
+ yield chunk
+ if final_output_supported:
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk # type: ignore[operator]
+ except TypeError:
+ final_output = None
+ final_output_supported = False
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ await run_manager.on_chain_end(final_output)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/config.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..d94d049fc5207280fccf561b497e6056d72cebfc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/config.py
@@ -0,0 +1,672 @@
+"""Configuration utilities for `Runnable` objects."""
+
+from __future__ import annotations
+
+import asyncio
+
+# Cannot move uuid to TYPE_CHECKING as RunnableConfig is used in Pydantic models
+import uuid # noqa: TC003
+import warnings
+from collections.abc import Awaitable, Callable, Generator, Iterable, Iterator, Sequence
+from concurrent.futures import Executor, Future, ThreadPoolExecutor
+from contextlib import contextmanager
+from contextvars import Context, ContextVar, Token, copy_context
+from functools import partial
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ ParamSpec,
+ TypeVar,
+ cast,
+)
+
+from typing_extensions import TypedDict
+
+from langchain_core.callbacks.manager import AsyncCallbackManager, CallbackManager
+from langchain_core.runnables.utils import (
+ Input,
+ Output,
+ accepts_config,
+ accepts_run_manager,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.callbacks.base import BaseCallbackManager, Callbacks
+ from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForChainRun,
+ CallbackManagerForChainRun,
+ )
+else:
+ # Pydantic validates through typed dicts, but
+ # the callbacks need forward refs updated
+ Callbacks = list | Any | None
+
+
+class EmptyDict(TypedDict, total=False):
+ """Empty dict type."""
+
+
+class RunnableConfig(TypedDict, total=False):
+ """Configuration for a `Runnable`.
+
+ !!! note Custom values
+
+ The `TypedDict` has `total=False` set intentionally to:
+
+ - Allow partial configs to be created and merged together via `merge_configs`
+ - Support config propagation from parent to child runnables via
+ `var_child_runnable_config` (a `ContextVar` that automatically passes
+ config down the call stack without explicit parameter passing), where
+ configs are merged rather than replaced
+
+ !!! example
+
+ ```python
+ # Parent sets tags
+ chain.invoke(input, config={"tags": ["parent"]})
+ # Child automatically inherits and can add:
+ # ensure_config({"tags": ["child"]}) -> {"tags": ["parent", "child"]}
+ ```
+ """
+
+ tags: list[str]
+ """Tags for this call and any sub-calls (e.g. a Chain calling an LLM).
+
+ You can use these to filter calls.
+ """
+
+ metadata: dict[str, Any]
+ """Metadata for this call and any sub-calls (e.g. a Chain calling an LLM).
+
+ Keys should be strings, values should be JSON-serializable.
+ """
+
+ callbacks: Callbacks
+ """Callbacks for this call and any sub-calls (e.g. a Chain calling an LLM).
+
+ Tags are passed to all callbacks, metadata is passed to handle*Start callbacks.
+ """
+
+ run_name: str
+ """Name for the tracer run for this call.
+
+ Defaults to the name of the class."""
+
+ max_concurrency: int | None
+ """Maximum number of parallel calls to make.
+
+ If not provided, defaults to `ThreadPoolExecutor`'s default.
+ """
+
+ recursion_limit: int
+ """Maximum number of times a call can recurse.
+
+ If not provided, defaults to `25`.
+ """
+
+ configurable: dict[str, Any]
+ """Runtime values for attributes previously made configurable on this `Runnable`,
+ or sub-`Runnable` objects, through `configurable_fields` or
+ `configurable_alternatives`.
+
+ Check `output_schema` for a description of the attributes that have been made
+ configurable.
+ """
+
+ run_id: uuid.UUID | None
+ """Unique identifier for the tracer run for this call.
+
+ If not provided, a new UUID will be generated.
+ """
+
+
+CONFIG_KEYS = [
+ "tags",
+ "metadata",
+ "callbacks",
+ "run_name",
+ "max_concurrency",
+ "recursion_limit",
+ "configurable",
+ "run_id",
+]
+
+COPIABLE_KEYS = [
+ "tags",
+ "metadata",
+ "callbacks",
+ "configurable",
+]
+
+
+# Users are expected to use the `context` API with a context object
+# (which does not get traced)
+CONFIGURABLE_TO_TRACING_METADATA_EXCLUDED_KEYS = frozenset(("api_key",))
+
+
+def _get_langsmith_inheritable_metadata_from_config(
+ config: RunnableConfig,
+) -> dict[str, Any] | None:
+ """Get LangSmith-only inheritable metadata defaults derived from config."""
+ configurable = config.get("configurable") or {}
+ metadata = {
+ key: value
+ for key, value in configurable.items()
+ if not key.startswith("__")
+ and isinstance(value, (str, int, float, bool))
+ and key not in config.get("metadata", {})
+ and key not in CONFIGURABLE_TO_TRACING_METADATA_EXCLUDED_KEYS
+ }
+ return metadata or None
+
+
+DEFAULT_RECURSION_LIMIT = 25
+
+
+var_child_runnable_config: ContextVar[RunnableConfig | None] = ContextVar(
+ "child_runnable_config", default=None
+)
+
+
+# This is imported and used in langgraph, so don't break.
+def _set_config_context(
+ config: RunnableConfig,
+) -> tuple[Token[RunnableConfig | None], dict[str, Any] | None]:
+ """Set the child Runnable config + tracing context.
+
+ Args:
+ config: The config to set.
+
+ Returns:
+ The token to reset the config and the previous tracing context.
+ """
+ # Deferred to avoid importing langsmith at module level (~132ms).
+ from langsmith.run_helpers import ( # noqa: PLC0415
+ _set_tracing_context,
+ get_tracing_context,
+ )
+
+ from langchain_core.tracers.langchain import LangChainTracer # noqa: PLC0415
+
+ config_token = var_child_runnable_config.set(config)
+ current_context = None
+ if (
+ (callbacks := config.get("callbacks"))
+ and (
+ parent_run_id := getattr(callbacks, "parent_run_id", None)
+ ) # Is callback manager
+ and (
+ tracer := next(
+ (
+ handler
+ for handler in getattr(callbacks, "handlers", [])
+ if isinstance(handler, LangChainTracer)
+ ),
+ None,
+ )
+ )
+ and (run := tracer.run_map.get(str(parent_run_id)))
+ ):
+ current_context = get_tracing_context()
+ _set_tracing_context({"parent": run})
+ return config_token, current_context
+
+
+@contextmanager
+def set_config_context(config: RunnableConfig) -> Generator[Context, None, None]:
+ """Set the child Runnable config + tracing context.
+
+ Args:
+ config: The config to set.
+
+ Yields:
+ The config context.
+ """
+ # Deferred to avoid importing langsmith at module level (~132ms).
+ from langsmith.run_helpers import _set_tracing_context # noqa: PLC0415
+
+ ctx = copy_context()
+ config_token, _ = ctx.run(_set_config_context, config)
+ try:
+ yield ctx
+ finally:
+ ctx.run(var_child_runnable_config.reset, config_token)
+ ctx.run(
+ _set_tracing_context,
+ {
+ "parent": None,
+ "project_name": None,
+ "tags": None,
+ "metadata": None,
+ "enabled": None,
+ "client": None,
+ },
+ )
+
+
+def ensure_config(config: RunnableConfig | None = None) -> RunnableConfig:
+ """Ensure that a config is a dict with all keys present.
+
+ Args:
+ config: The config to ensure.
+
+ Returns:
+ The ensured config.
+ """
+ empty = RunnableConfig(
+ tags=[],
+ metadata={},
+ callbacks=None,
+ recursion_limit=DEFAULT_RECURSION_LIMIT,
+ configurable={},
+ )
+ if var_config := var_child_runnable_config.get():
+ empty.update(
+ cast(
+ "RunnableConfig",
+ {
+ k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]
+ for k, v in var_config.items()
+ if v is not None
+ },
+ )
+ )
+ if config is not None:
+ empty.update(
+ cast(
+ "RunnableConfig",
+ {
+ k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]
+ for k, v in config.items()
+ if v is not None and k in CONFIG_KEYS
+ },
+ )
+ )
+ if config is not None:
+ for k, v in config.items():
+ if k not in CONFIG_KEYS and v is not None:
+ empty["configurable"][k] = v
+ for configurable_key in ("model", "checkpoint_ns"):
+ if (
+ isinstance(
+ configurable_value := empty.get("configurable", {}).get(
+ configurable_key
+ ),
+ str,
+ )
+ and configurable_key not in empty["metadata"]
+ ):
+ empty["metadata"][configurable_key] = configurable_value
+ return empty
+
+
+def get_config_list(
+ config: RunnableConfig | Sequence[RunnableConfig] | None, length: int
+) -> list[RunnableConfig]:
+ """Get a list of configs from a single config or a list of configs.
+
+ It is useful for subclasses overriding batch() or abatch().
+
+ Args:
+ config: The config or list of configs.
+ length: The length of the list.
+
+ Returns:
+ The list of configs.
+
+ Raises:
+ ValueError: If the length of the list is not equal to the length of the inputs.
+
+ """
+ if length < 0:
+ msg = f"length must be >= 0, but got {length}"
+ raise ValueError(msg)
+ if isinstance(config, Sequence) and len(config) != length:
+ msg = (
+ f"config must be a list of the same length as inputs, "
+ f"but got {len(config)} configs for {length} inputs"
+ )
+ raise ValueError(msg)
+
+ if isinstance(config, Sequence):
+ return list(map(ensure_config, config))
+ if length > 1 and isinstance(config, dict) and config.get("run_id") is not None:
+ warnings.warn(
+ "Provided run_id be used only for the first element of the batch.",
+ category=RuntimeWarning,
+ stacklevel=3,
+ )
+ subsequent = cast(
+ "RunnableConfig", {k: v for k, v in config.items() if k != "run_id"}
+ )
+ return [
+ ensure_config(subsequent) if i else ensure_config(config)
+ for i in range(length)
+ ]
+ return [ensure_config(config) for i in range(length)]
+
+
+def patch_config(
+ config: RunnableConfig | None,
+ *,
+ callbacks: BaseCallbackManager | None = None,
+ recursion_limit: int | None = None,
+ max_concurrency: int | None = None,
+ run_name: str | None = None,
+ configurable: dict[str, Any] | None = None,
+) -> RunnableConfig:
+ """Patch a config with new values.
+
+ Args:
+ config: The config to patch.
+ callbacks: The callbacks to set.
+ recursion_limit: The recursion limit to set.
+ max_concurrency: The max concurrency to set.
+ run_name: The run name to set.
+ configurable: The configurable to set.
+
+ Returns:
+ The patched config.
+ """
+ config = ensure_config(config)
+ if callbacks is not None:
+ # If we're replacing callbacks, we need to unset run_name
+ # As that should apply only to the same run as the original callbacks
+ config["callbacks"] = callbacks
+ if "run_name" in config:
+ del config["run_name"]
+ if "run_id" in config:
+ del config["run_id"]
+ if recursion_limit is not None:
+ config["recursion_limit"] = recursion_limit
+ if max_concurrency is not None:
+ config["max_concurrency"] = max_concurrency
+ if run_name is not None:
+ config["run_name"] = run_name
+ if configurable is not None:
+ config["configurable"] = {**config.get("configurable", {}), **configurable}
+ return config
+
+
+def merge_configs(*configs: RunnableConfig | None) -> RunnableConfig:
+ """Merge multiple configs into one.
+
+ Args:
+ *configs: The configs to merge.
+
+ Returns:
+ The merged config.
+ """
+ base: RunnableConfig = {}
+ # Even though the keys aren't literals, this is correct
+ # because both dicts are the same type
+ for config in (ensure_config(c) for c in configs if c is not None):
+ for key in config:
+ if key == "metadata":
+ base["metadata"] = {
+ **base.get("metadata", {}),
+ **(config.get("metadata") or {}),
+ }
+ elif key == "tags":
+ base["tags"] = sorted(
+ set(base.get("tags", []) + (config.get("tags") or [])),
+ )
+ elif key == "configurable":
+ base["configurable"] = {
+ **base.get("configurable", {}),
+ **(config.get("configurable") or {}),
+ }
+ elif key == "callbacks":
+ base_callbacks = base.get("callbacks")
+ these_callbacks = config["callbacks"]
+ # callbacks can be either None, list[handler] or manager
+ # so merging two callbacks values has 6 cases
+ if isinstance(these_callbacks, list):
+ if base_callbacks is None:
+ base["callbacks"] = these_callbacks.copy()
+ elif isinstance(base_callbacks, list):
+ base["callbacks"] = base_callbacks + these_callbacks
+ else:
+ # base_callbacks is a manager
+ mngr = base_callbacks.copy()
+ for callback in these_callbacks:
+ mngr.add_handler(callback, inherit=True)
+ base["callbacks"] = mngr
+ elif these_callbacks is not None:
+ # these_callbacks is a manager
+ if base_callbacks is None:
+ base["callbacks"] = these_callbacks.copy()
+ elif isinstance(base_callbacks, list):
+ mngr = these_callbacks.copy()
+ for callback in base_callbacks:
+ mngr.add_handler(callback, inherit=True)
+ base["callbacks"] = mngr
+ else:
+ # base_callbacks is also a manager
+ base["callbacks"] = base_callbacks.merge(these_callbacks)
+ elif key == "recursion_limit":
+ if config["recursion_limit"] != DEFAULT_RECURSION_LIMIT:
+ base["recursion_limit"] = config["recursion_limit"]
+ elif key in COPIABLE_KEYS and config[key] is not None: # type: ignore[literal-required]
+ base[key] = config[key].copy() # type: ignore[literal-required]
+ else:
+ base[key] = config[key] or base.get(key) # type: ignore[literal-required]
+ return base
+
+
+def call_func_with_variable_args(
+ func: Callable[[Input], Output]
+ | Callable[[Input, RunnableConfig], Output]
+ | Callable[[Input, CallbackManagerForChainRun], Output]
+ | Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output],
+ input: Input,
+ config: RunnableConfig,
+ run_manager: CallbackManagerForChainRun | None = None,
+ **kwargs: Any,
+) -> Output:
+ """Call function that may optionally accept a run_manager and/or config.
+
+ Args:
+ func: The function to call.
+ input: The input to the function.
+ config: The config to pass to the function.
+ run_manager: The run manager to pass to the function.
+ **kwargs: The keyword arguments to pass to the function.
+
+ Returns:
+ The output of the function.
+ """
+ if accepts_config(func):
+ if run_manager is not None:
+ kwargs["config"] = patch_config(config, callbacks=run_manager.get_child())
+ else:
+ kwargs["config"] = config
+ if run_manager is not None and accepts_run_manager(func):
+ kwargs["run_manager"] = run_manager
+ return func(input, **kwargs) # type: ignore[call-arg]
+
+
+def acall_func_with_variable_args(
+ func: Callable[[Input], Awaitable[Output]]
+ | Callable[[Input, RunnableConfig], Awaitable[Output]]
+ | Callable[[Input, AsyncCallbackManagerForChainRun], Awaitable[Output]]
+ | Callable[
+ [Input, AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]
+ ],
+ input: Input,
+ config: RunnableConfig,
+ run_manager: AsyncCallbackManagerForChainRun | None = None,
+ **kwargs: Any,
+) -> Awaitable[Output]:
+ """Async call function that may optionally accept a run_manager and/or config.
+
+ Args:
+ func: The function to call.
+ input: The input to the function.
+ config: The config to pass to the function.
+ run_manager: The run manager to pass to the function.
+ **kwargs: The keyword arguments to pass to the function.
+
+ Returns:
+ The output of the function.
+ """
+ if accepts_config(func):
+ if run_manager is not None:
+ kwargs["config"] = patch_config(config, callbacks=run_manager.get_child())
+ else:
+ kwargs["config"] = config
+ if run_manager is not None and accepts_run_manager(func):
+ kwargs["run_manager"] = run_manager
+ return func(input, **kwargs) # type: ignore[call-arg]
+
+
+def get_callback_manager_for_config(config: RunnableConfig) -> CallbackManager:
+ """Get a callback manager for a config.
+
+ Args:
+ config: The config.
+
+ Returns:
+ The callback manager.
+ """
+ return CallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ inheritable_tags=config.get("tags"),
+ inheritable_metadata=config.get("metadata"),
+ langsmith_inheritable_metadata=_get_langsmith_inheritable_metadata_from_config(
+ config
+ ),
+ )
+
+
+def get_async_callback_manager_for_config(
+ config: RunnableConfig,
+) -> AsyncCallbackManager:
+ """Get an async callback manager for a config.
+
+ Args:
+ config: The config.
+
+ Returns:
+ The async callback manager.
+ """
+ return AsyncCallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ inheritable_tags=config.get("tags"),
+ inheritable_metadata=config.get("metadata"),
+ langsmith_inheritable_metadata=_get_langsmith_inheritable_metadata_from_config(
+ config
+ ),
+ )
+
+
+P = ParamSpec("P")
+T = TypeVar("T")
+
+
+class ContextThreadPoolExecutor(ThreadPoolExecutor):
+ """ThreadPoolExecutor that copies the context to the child thread."""
+
+ def submit( # type: ignore[override]
+ self,
+ func: Callable[P, T],
+ *args: P.args,
+ **kwargs: P.kwargs,
+ ) -> Future[T]:
+ """Submit a function to the executor.
+
+ Args:
+ func: The function to submit.
+ *args: The positional arguments to the function.
+ **kwargs: The keyword arguments to the function.
+
+ Returns:
+ The future for the function.
+ """
+ return super().submit(
+ cast("Callable[..., T]", partial(copy_context().run, func, *args, **kwargs))
+ )
+
+ def map(
+ self,
+ fn: Callable[..., T],
+ *iterables: Iterable[Any],
+ **kwargs: Any,
+ ) -> Iterator[T]:
+ """Map a function to multiple iterables.
+
+ Args:
+ fn: The function to map.
+ *iterables: The iterables to map over.
+ timeout: The timeout for the map.
+ chunksize: The chunksize for the map.
+
+ Returns:
+ The iterator for the mapped function.
+ """
+ contexts = [copy_context() for _ in range(len(iterables[0]))] # type: ignore[arg-type]
+
+ def _wrapped_fn(*args: Any) -> T:
+ return contexts.pop().run(fn, *args)
+
+ return super().map(
+ _wrapped_fn,
+ *iterables,
+ **kwargs,
+ )
+
+
+@contextmanager
+def get_executor_for_config(
+ config: RunnableConfig | None,
+) -> Generator[Executor, None, None]:
+ """Get an executor for a config.
+
+ Args:
+ config: The config.
+
+ Yields:
+ The executor.
+ """
+ config = config or {}
+ with ContextThreadPoolExecutor(
+ max_workers=config.get("max_concurrency")
+ ) as executor:
+ yield executor
+
+
+async def run_in_executor(
+ executor_or_config: Executor | RunnableConfig | None,
+ func: Callable[P, T],
+ *args: P.args,
+ **kwargs: P.kwargs,
+) -> T:
+ """Run a function in an executor.
+
+ Args:
+ executor_or_config: The executor or config to run in.
+ func: The function.
+ *args: The positional arguments to the function.
+ **kwargs: The keyword arguments to the function.
+
+ Returns:
+ The output of the function.
+ """
+
+ def wrapper() -> T:
+ try:
+ return func(*args, **kwargs)
+ except StopIteration as exc:
+ # StopIteration can't be set on an asyncio.Future
+ # it raises a TypeError and leaves the Future pending forever
+ # so we need to convert it to a RuntimeError
+ raise RuntimeError from exc
+
+ if executor_or_config is None or isinstance(executor_or_config, dict):
+ # Use default executor with context copied from current context
+ return await asyncio.get_running_loop().run_in_executor(
+ None,
+ cast("Callable[..., T]", partial(copy_context().run, wrapper)),
+ )
+
+ return await asyncio.get_running_loop().run_in_executor(executor_or_config, wrapper)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/configurable.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/configurable.py
new file mode 100644
index 0000000000000000000000000000000000000000..a03108850fa98e00f03c7036f9b39a331ed1eb7c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/configurable.py
@@ -0,0 +1,716 @@
+"""`Runnable` objects that can be dynamically configured."""
+
+from __future__ import annotations
+
+import enum
+import threading
+from abc import abstractmethod
+from collections.abc import (
+ AsyncIterator,
+ Callable,
+ Iterator,
+ Sequence,
+)
+from functools import wraps
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ cast,
+)
+from weakref import WeakValueDictionary
+
+from pydantic import BaseModel, ConfigDict
+from typing_extensions import override
+
+from langchain_core.runnables.base import Runnable, RunnableSerializable
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ ensure_config,
+ get_config_list,
+ get_executor_for_config,
+ merge_configs,
+)
+from langchain_core.runnables.utils import (
+ AnyConfigurableField,
+ ConfigurableField,
+ ConfigurableFieldMultiOption,
+ ConfigurableFieldSingleOption,
+ ConfigurableFieldSpec,
+ Input,
+ Output,
+ gather_with_concurrency,
+ get_unique_config_specs,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.runnables.graph import Graph
+
+
+class DynamicRunnable(RunnableSerializable[Input, Output]):
+ """Serializable `Runnable` that can be dynamically configured.
+
+ A `DynamicRunnable` should be initiated using the `configurable_fields` or
+ `configurable_alternatives` method of a `Runnable`.
+ """
+
+ default: RunnableSerializable[Input, Output]
+ """The default `Runnable` to use."""
+
+ config: RunnableConfig | None = None
+ """The configuration to use."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @property
+ @override
+ def InputType(self) -> type[Input]:
+ return self.default.InputType
+
+ @property
+ @override
+ def OutputType(self) -> type[Output]:
+ return self.default.OutputType
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ runnable, config = self.prepare(config)
+ return runnable.get_input_schema(config)
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ runnable, config = self.prepare(config)
+ return runnable.get_output_schema(config)
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ runnable, config = self.prepare(config)
+ return runnable.get_graph(config)
+
+ @override
+ def with_config(
+ self,
+ config: RunnableConfig | None = None,
+ # Sadly Unpack is not well supported by mypy so this will have to be untyped
+ **kwargs: Any,
+ ) -> Runnable[Input, Output]:
+ return self.__class__(
+ **{**self.__dict__, "config": ensure_config(merge_configs(config, kwargs))} # type: ignore[arg-type]
+ )
+
+ def prepare(
+ self, config: RunnableConfig | None = None
+ ) -> tuple[Runnable[Input, Output], RunnableConfig]:
+ """Prepare the `Runnable` for invocation.
+
+ Args:
+ config: The configuration to use.
+
+ Returns:
+ The prepared `Runnable` and configuration.
+ """
+ runnable: Runnable[Input, Output] = self
+ while isinstance(runnable, DynamicRunnable):
+ runnable, config = runnable._prepare(merge_configs(runnable.config, config)) # noqa: SLF001
+ return runnable, cast("RunnableConfig", config)
+
+ @abstractmethod
+ def _prepare(
+ self, config: RunnableConfig | None = None
+ ) -> tuple[Runnable[Input, Output], RunnableConfig]: ...
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ runnable, config = self.prepare(config)
+ return runnable.invoke(input, config, **kwargs)
+
+ @override
+ async def ainvoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ runnable, config = self.prepare(config)
+ return await runnable.ainvoke(input, config, **kwargs)
+
+ @override
+ def batch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ configs = get_config_list(config, len(inputs))
+ prepared = [self.prepare(c) for c in configs]
+
+ if all(p is self.default for p, _ in prepared):
+ return self.default.batch(
+ inputs,
+ [c for _, c in prepared],
+ return_exceptions=return_exceptions,
+ **kwargs,
+ )
+
+ if not inputs:
+ return []
+
+ def invoke(
+ prepared: tuple[Runnable[Input, Output], RunnableConfig],
+ input_: Input,
+ ) -> Output | Exception:
+ bound, config = prepared
+ if return_exceptions:
+ try:
+ return bound.invoke(input_, config, **kwargs)
+ except Exception as e:
+ return e
+ else:
+ return bound.invoke(input_, config, **kwargs)
+
+ # If there's only one input, don't bother with the executor
+ if len(inputs) == 1:
+ return cast("list[Output]", [invoke(prepared[0], inputs[0])])
+
+ with get_executor_for_config(configs[0]) as executor:
+ return cast("list[Output]", list(executor.map(invoke, prepared, inputs)))
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ configs = get_config_list(config, len(inputs))
+ prepared = [self.prepare(c) for c in configs]
+
+ if all(p is self.default for p, _ in prepared):
+ return await self.default.abatch(
+ inputs,
+ [c for _, c in prepared],
+ return_exceptions=return_exceptions,
+ **kwargs,
+ )
+
+ if not inputs:
+ return []
+
+ async def ainvoke(
+ prepared: tuple[Runnable[Input, Output], RunnableConfig],
+ input_: Input,
+ ) -> Output | Exception:
+ bound, config = prepared
+ if return_exceptions:
+ try:
+ return await bound.ainvoke(input_, config, **kwargs)
+ except Exception as e:
+ return e
+ else:
+ return await bound.ainvoke(input_, config, **kwargs)
+
+ coros = map(ainvoke, prepared, inputs)
+ return await gather_with_concurrency(configs[0].get("max_concurrency"), *coros)
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ runnable, config = self.prepare(config)
+ return runnable.stream(input, config, **kwargs)
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ runnable, config = self.prepare(config)
+ async for chunk in runnable.astream(input, config, **kwargs):
+ yield chunk
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ runnable, config = self.prepare(config)
+ return runnable.transform(input, config, **kwargs)
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[Input],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ runnable, config = self.prepare(config)
+ async for chunk in runnable.atransform(input, config, **kwargs):
+ yield chunk
+
+ @override
+ def __getattr__(self, name: str) -> Any: # type: ignore[misc]
+ attr = getattr(self.default, name)
+ if callable(attr):
+
+ @wraps(attr)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ for key, arg in kwargs.items():
+ if key == "config" and (
+ isinstance(arg, dict)
+ and "configurable" in arg
+ and isinstance(arg["configurable"], dict)
+ ):
+ runnable, config = self.prepare(cast("RunnableConfig", arg))
+ kwargs = {**kwargs, "config": config}
+ return getattr(runnable, name)(*args, **kwargs)
+
+ for idx, arg in enumerate(args):
+ if (
+ isinstance(arg, dict)
+ and "configurable" in arg
+ and isinstance(arg["configurable"], dict)
+ ):
+ runnable, config = self.prepare(cast("RunnableConfig", arg))
+ argsl = list(args)
+ argsl[idx] = config
+ return getattr(runnable, name)(*argsl, **kwargs)
+
+ if self.config:
+ runnable, config = self.prepare()
+ return getattr(runnable, name)(*args, **kwargs)
+
+ return attr(*args, **kwargs)
+
+ return wrapper
+
+ return attr
+
+
+class RunnableConfigurableFields(DynamicRunnable[Input, Output]):
+ """`Runnable` that can be dynamically configured.
+
+ A `RunnableConfigurableFields` should be initiated using the
+ `configurable_fields` method of a `Runnable`.
+
+ Here is an example of using a `RunnableConfigurableFields` with LLMs:
+
+ ```python
+ from langchain_core.prompts import PromptTemplate
+ from langchain_core.runnables import ConfigurableField
+ from langchain_openai import ChatOpenAI
+
+ model = ChatOpenAI(temperature=0).configurable_fields(
+ temperature=ConfigurableField(
+ id="temperature",
+ name="LLM Temperature",
+ description="The temperature of the LLM",
+ )
+ )
+ # This creates a RunnableConfigurableFields for a chat model.
+
+ # When invoking the created RunnableSequence, you can pass in the
+ # value for your ConfigurableField's id which in this case
+ # will be change in temperature
+
+ prompt = PromptTemplate.from_template("Pick a random number above {x}")
+ chain = prompt | model
+
+ chain.invoke({"x": 0})
+ chain.invoke({"x": 0}, config={"configurable": {"temperature": 0.9}})
+ ```
+
+ Here is an example of using a `RunnableConfigurableFields` with `HubRunnables`:
+
+ ```python
+ from langchain_core.prompts import PromptTemplate
+ from langchain_core.runnables import ConfigurableField
+ from langchain_openai import ChatOpenAI
+ from langchain.runnables.hub import HubRunnable
+
+ prompt = HubRunnable("rlm/rag-prompt").configurable_fields(
+ owner_repo_commit=ConfigurableField(
+ id="hub_commit",
+ name="Hub Commit",
+ description="The Hub commit to pull from",
+ )
+ )
+
+ prompt.invoke({"question": "foo", "context": "bar"})
+
+ # Invoking prompt with `with_config` method
+
+ prompt.invoke(
+ {"question": "foo", "context": "bar"},
+ config={"configurable": {"hub_commit": "rlm/rag-prompt-llama"}},
+ )
+ ```
+ """
+
+ fields: dict[str, AnyConfigurableField]
+ """The configurable fields to use."""
+
+ @property
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ """Get the configuration specs for the `RunnableConfigurableFields`.
+
+ Returns:
+ The configuration specs.
+ """
+ config_specs = []
+
+ default_fields = type(self.default).model_fields
+ for field_name, spec in self.fields.items():
+ if isinstance(spec, ConfigurableField):
+ config_specs.append(
+ ConfigurableFieldSpec(
+ id=spec.id,
+ name=spec.name,
+ description=spec.description
+ or default_fields[field_name].description,
+ annotation=spec.annotation
+ or default_fields[field_name].annotation,
+ default=getattr(self.default, field_name),
+ is_shared=spec.is_shared,
+ )
+ )
+ else:
+ config_specs.append(
+ make_options_spec(spec, default_fields[field_name].description)
+ )
+
+ config_specs.extend(self.default.config_specs)
+
+ return get_unique_config_specs(config_specs)
+
+ @override
+ def configurable_fields(
+ self, **kwargs: AnyConfigurableField
+ ) -> RunnableSerializable[Input, Output]:
+ return self.default.configurable_fields(**{**self.fields, **kwargs})
+
+ def _prepare(
+ self, config: RunnableConfig | None = None
+ ) -> tuple[Runnable[Input, Output], RunnableConfig]:
+ config = ensure_config(config)
+ specs_by_id = {spec.id: (key, spec) for key, spec in self.fields.items()}
+ configurable_fields = {
+ specs_by_id[k][0]: v
+ for k, v in config.get("configurable", {}).items()
+ if k in specs_by_id and isinstance(specs_by_id[k][1], ConfigurableField)
+ }
+ configurable_single_options = {
+ k: v.options[(config.get("configurable", {}).get(v.id) or v.default)]
+ for k, v in self.fields.items()
+ if isinstance(v, ConfigurableFieldSingleOption)
+ }
+ configurable_multi_options = {
+ k: [
+ v.options[o]
+ for o in config.get("configurable", {}).get(v.id, v.default)
+ ]
+ for k, v in self.fields.items()
+ if isinstance(v, ConfigurableFieldMultiOption)
+ }
+ configurable = {
+ **configurable_fields,
+ **configurable_single_options,
+ **configurable_multi_options,
+ }
+
+ if configurable:
+ init_params = {
+ k: v
+ for k, v in self.default.__dict__.items()
+ if k in type(self.default).model_fields
+ }
+ return (
+ self.default.__class__(**{**init_params, **configurable}),
+ config,
+ )
+ return (self.default, config)
+
+
+# Before Python 3.11 native StrEnum is not available
+class StrEnum(str, enum.Enum):
+ """String enum."""
+
+
+_enums_for_spec: WeakValueDictionary[
+ ConfigurableFieldSingleOption | ConfigurableFieldMultiOption | ConfigurableField,
+ type[StrEnum],
+] = WeakValueDictionary()
+
+_enums_for_spec_lock = threading.Lock()
+
+
+class RunnableConfigurableAlternatives(DynamicRunnable[Input, Output]):
+ """`Runnable` that can be dynamically configured.
+
+ A `RunnableConfigurableAlternatives` should be initiated using the
+ `configurable_alternatives` method of a `Runnable` or can be
+ initiated directly as well.
+
+ Here is an example of using a `RunnableConfigurableAlternatives` that uses
+ alternative prompts to illustrate its functionality:
+
+ ```python
+ from langchain_core.runnables import ConfigurableField
+ from langchain_openai import ChatOpenAI
+
+ # This creates a RunnableConfigurableAlternatives for Prompt Runnable
+ # with two alternatives.
+ prompt = PromptTemplate.from_template(
+ "Tell me a joke about {topic}"
+ ).configurable_alternatives(
+ ConfigurableField(id="prompt"),
+ default_key="joke",
+ poem=PromptTemplate.from_template("Write a short poem about {topic}"),
+ )
+
+ # When invoking the created RunnableSequence, you can pass in the
+ # value for your ConfigurableField's id which in this case will either be
+ # `joke` or `poem`.
+ chain = prompt | ChatOpenAI(model="gpt-5.4-mini")
+
+ # The `with_config` method brings in the desired Prompt Runnable in your
+ # Runnable Sequence.
+ chain.with_config(configurable={"prompt": "poem"}).invoke({"topic": "bears"})
+ ```
+
+ Equivalently, you can initialize `RunnableConfigurableAlternatives` directly
+ and use in LCEL in the same way:
+
+ ```python
+ from langchain_core.runnables import ConfigurableField
+ from langchain_core.runnables.configurable import (
+ RunnableConfigurableAlternatives,
+ )
+ from langchain_openai import ChatOpenAI
+
+ prompt = RunnableConfigurableAlternatives(
+ which=ConfigurableField(id="prompt"),
+ default=PromptTemplate.from_template("Tell me a joke about {topic}"),
+ default_key="joke",
+ prefix_keys=False,
+ alternatives={
+ "poem": PromptTemplate.from_template("Write a short poem about {topic}")
+ },
+ )
+ chain = prompt | ChatOpenAI(model="gpt-5.4-mini")
+ chain.with_config(configurable={"prompt": "poem"}).invoke({"topic": "bears"})
+ ```
+ """
+
+ which: ConfigurableField
+ """The `ConfigurableField` to use to choose between alternatives."""
+
+ alternatives: dict[
+ str,
+ Runnable[Input, Output] | Callable[[], Runnable[Input, Output]],
+ ]
+ """The alternatives to choose from."""
+
+ default_key: str = "default"
+ """The enum value to use for the default option."""
+
+ prefix_keys: bool
+ """Whether to prefix configurable fields of each alternative with a namespace
+ of the form ==, e.g. a key named "temperature" used by
+ the alternative named "gpt3" becomes "model==gpt3/temperature".
+ """
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ with _enums_for_spec_lock:
+ if which_enum := _enums_for_spec.get(self.which):
+ pass
+ else:
+ which_enum = StrEnum( # type: ignore[call-overload]
+ self.which.name or self.which.id,
+ (
+ (v, v)
+ for v in [*list(self.alternatives.keys()), self.default_key]
+ ),
+ )
+ _enums_for_spec[self.which] = cast("type[StrEnum]", which_enum)
+ return get_unique_config_specs(
+ # which alternative
+ [
+ ConfigurableFieldSpec(
+ id=self.which.id,
+ name=self.which.name,
+ description=self.which.description,
+ annotation=which_enum,
+ default=self.default_key,
+ is_shared=self.which.is_shared,
+ ),
+ ]
+ # config specs of the default option
+ + (
+ [
+ prefix_config_spec(s, f"{self.which.id}=={self.default_key}")
+ for s in self.default.config_specs
+ ]
+ if self.prefix_keys
+ else self.default.config_specs
+ )
+ # config specs of the alternatives
+ + [
+ (
+ prefix_config_spec(s, f"{self.which.id}=={alt_key}")
+ if self.prefix_keys
+ else s
+ )
+ for alt_key, alt in self.alternatives.items()
+ if isinstance(alt, RunnableSerializable)
+ for s in alt.config_specs
+ ]
+ )
+
+ @override
+ def configurable_fields(
+ self, **kwargs: AnyConfigurableField
+ ) -> RunnableSerializable[Input, Output]:
+ return self.__class__(
+ which=self.which,
+ default=self.default.configurable_fields(**kwargs),
+ alternatives=self.alternatives,
+ default_key=self.default_key,
+ prefix_keys=self.prefix_keys,
+ )
+
+ def _prepare(
+ self, config: RunnableConfig | None = None
+ ) -> tuple[Runnable[Input, Output], RunnableConfig]:
+ config = ensure_config(config)
+ which = config.get("configurable", {}).get(self.which.id, self.default_key)
+ # remap configurable keys for the chosen alternative
+ if self.prefix_keys:
+ config = cast(
+ "RunnableConfig",
+ {
+ **config,
+ "configurable": {
+ _strremoveprefix(k, f"{self.which.id}=={which}/"): v
+ for k, v in config.get("configurable", {}).items()
+ },
+ },
+ )
+ # return the chosen alternative
+ if which == self.default_key:
+ return (self.default, config)
+ if which in self.alternatives:
+ alt = self.alternatives[which]
+ if isinstance(alt, Runnable):
+ return (alt, config)
+ return (alt(), config)
+ msg = f"Unknown alternative: {which}"
+ raise ValueError(msg)
+
+
+def _strremoveprefix(s: str, prefix: str) -> str:
+ """`str.removeprefix()` is only available in Python 3.9+."""
+ return s.replace(prefix, "", 1) if s.startswith(prefix) else s
+
+
+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:
+ The prefixed `ConfigurableFieldSpec`.
+ """
+ return (
+ ConfigurableFieldSpec(
+ id=f"{prefix}/{spec.id}",
+ name=spec.name,
+ description=spec.description,
+ annotation=spec.annotation,
+ default=spec.default,
+ is_shared=spec.is_shared,
+ )
+ if not spec.is_shared
+ else spec
+ )
+
+
+def make_options_spec(
+ spec: ConfigurableFieldSingleOption | ConfigurableFieldMultiOption,
+ description: str | None,
+) -> ConfigurableFieldSpec:
+ """Make options spec.
+
+ Make a `ConfigurableFieldSpec` for a `ConfigurableFieldSingleOption` or
+ `ConfigurableFieldMultiOption`.
+
+ Args:
+ spec: The `ConfigurableFieldSingleOption` or `ConfigurableFieldMultiOption`.
+ description: The description to use if the spec does not have one.
+
+ Returns:
+ The `ConfigurableFieldSpec`.
+ """
+ with _enums_for_spec_lock:
+ if enum := _enums_for_spec.get(spec):
+ pass
+ else:
+ enum = StrEnum( # type: ignore[call-overload]
+ spec.name or spec.id,
+ ((v, v) for v in list(spec.options.keys())),
+ )
+ _enums_for_spec[spec] = cast("type[StrEnum]", enum)
+ if isinstance(spec, ConfigurableFieldSingleOption):
+ return ConfigurableFieldSpec(
+ id=spec.id,
+ name=spec.name,
+ description=spec.description or description,
+ annotation=enum,
+ default=spec.default,
+ is_shared=spec.is_shared,
+ )
+ return ConfigurableFieldSpec(
+ id=spec.id,
+ name=spec.name,
+ description=spec.description or description,
+ annotation=Sequence[enum], # type: ignore[valid-type]
+ default=spec.default,
+ is_shared=spec.is_shared,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/fallbacks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/fallbacks.py
new file mode 100644
index 0000000000000000000000000000000000000000..72fb6b4f693f5c642074ac85f0f5224628bf4ebb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/fallbacks.py
@@ -0,0 +1,664 @@
+"""`Runnable` that can fallback to other `Runnable` objects if it fails."""
+
+import asyncio
+import inspect
+import typing
+from collections.abc import AsyncIterator, Iterator, Sequence
+from functools import wraps
+from typing import TYPE_CHECKING, Any, cast
+
+from pydantic import BaseModel, ConfigDict
+from typing_extensions import override
+
+from langchain_core.callbacks.manager import AsyncCallbackManager, CallbackManager
+from langchain_core.runnables.base import Runnable, RunnableSerializable
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ ensure_config,
+ get_async_callback_manager_for_config,
+ get_callback_manager_for_config,
+ get_config_list,
+ patch_config,
+ set_config_context,
+)
+from langchain_core.runnables.utils import (
+ ConfigurableFieldSpec,
+ Input,
+ Output,
+ coro_with_context,
+ get_unique_config_specs,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.callbacks.manager import AsyncCallbackManagerForChainRun
+
+
+class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
+ """`Runnable` that can fallback to other `Runnable` objects if it fails.
+
+ External APIs (e.g., APIs for a language model) may at times experience
+ degraded performance or even downtime.
+
+ In these cases, it can be useful to have a fallback `Runnable` that can be
+ used in place of the original `Runnable` (e.g., fallback to another LLM provider).
+
+ Fallbacks can be defined at the level of a single `Runnable`, or at the level
+ of a chain of `Runnable`s. Fallbacks are tried in order until one succeeds or
+ all fail.
+
+ While you can instantiate a `RunnableWithFallbacks` directly, it is usually
+ more convenient to use the `with_fallbacks` method on a `Runnable`.
+
+ Example:
+ ```python
+ from langchain_core.chat_models.openai import ChatOpenAI
+ from langchain_core.chat_models.anthropic import ChatAnthropic
+
+ model = ChatAnthropic(model="claude-sonnet-4-6").with_fallbacks(
+ [ChatOpenAI(model="gpt-5.4-mini")]
+ )
+ # Will usually use ChatAnthropic, but fallback to ChatOpenAI
+ # if ChatAnthropic fails.
+ model.invoke("hello")
+
+ # And you can also use fallbacks at the level of a chain.
+ # Here if both LLM providers fail, we'll fallback to a good hardcoded
+ # response.
+
+ from langchain_core.prompts import PromptTemplate
+ from langchain_core.output_parser import StrOutputParser
+ from langchain_core.runnables import RunnableLambda
+
+
+ def when_all_is_lost(inputs):
+ return (
+ "Looks like our LLM providers are down. "
+ "Here's a nice 🦜️ emoji for you instead."
+ )
+
+
+ chain_with_fallback = (
+ PromptTemplate.from_template("Tell me a joke about {topic}")
+ | model
+ | StrOutputParser()
+ ).with_fallbacks([RunnableLambda(when_all_is_lost)])
+ ```
+ """
+
+ runnable: Runnable[Input, Output]
+ """The `Runnable` to run first."""
+ fallbacks: Sequence[Runnable[Input, Output]]
+ """A sequence of fallbacks to try."""
+ exceptions_to_handle: tuple[type[BaseException], ...] = (Exception,)
+ """The exceptions on which fallbacks should be tried.
+
+ Any exception that is not a subclass of these exceptions will be raised immediately.
+ """
+ exception_key: str | None = None
+ """If `string` is specified then handled exceptions will be passed to fallbacks as
+ part of the input under the specified key.
+
+ If `None`, exceptions will not be passed to fallbacks.
+
+ If used, the base `Runnable` and its fallbacks must accept a dictionary as input.
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @property
+ @override
+ def InputType(self) -> type[Input]:
+ return self.runnable.InputType
+
+ @property
+ @override
+ def OutputType(self) -> type[Output]:
+ return self.runnable.OutputType
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ return self.runnable.get_input_schema(config)
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ return self.runnable.get_output_schema(config)
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return get_unique_config_specs(
+ spec
+ for step in [self.runnable, *self.fallbacks]
+ for spec in step.config_specs
+ )
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @property
+ def runnables(self) -> Iterator[Runnable[Input, Output]]:
+ """Iterator over the `Runnable` and its fallbacks.
+
+ Yields:
+ The `Runnable` then its fallbacks.
+ """
+ yield self.runnable
+ yield from self.fallbacks
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ if self.exception_key is not None and not isinstance(input, dict):
+ msg = (
+ "If 'exception_key' is specified then input must be a dictionary."
+ f"However found a type of {type(input)} for input"
+ )
+ raise ValueError(msg)
+ # setup callbacks
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ # start the root run
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ first_error = None
+ last_error = None
+ for runnable in self.runnables:
+ try:
+ if self.exception_key and last_error is not None:
+ input[self.exception_key] = last_error # type: ignore[index]
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ output = context.run(
+ runnable.invoke,
+ input,
+ config,
+ **kwargs,
+ )
+ except self.exceptions_to_handle as e:
+ if first_error is None:
+ first_error = e
+ last_error = e
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ run_manager.on_chain_end(output)
+ return output
+ if first_error is None:
+ msg = "No error stored at end of fallbacks."
+ raise ValueError(msg)
+ run_manager.on_chain_error(first_error)
+ raise first_error
+
+ @override
+ async def ainvoke(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ if self.exception_key is not None and not isinstance(input, dict):
+ msg = (
+ "If 'exception_key' is specified then input must be a dictionary."
+ f"However found a type of {type(input)} for input"
+ )
+ raise ValueError(msg)
+ # setup callbacks
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ # start the root run
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+
+ first_error = None
+ last_error = None
+ for runnable in self.runnables:
+ try:
+ if self.exception_key and last_error is not None:
+ input[self.exception_key] = last_error # type: ignore[index]
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ coro = context.run(runnable.ainvoke, input, config, **kwargs)
+ output = await coro_with_context(coro, context)
+ except self.exceptions_to_handle as e:
+ if first_error is None:
+ first_error = e
+ last_error = e
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ await run_manager.on_chain_end(output)
+ return output
+ if first_error is None:
+ msg = "No error stored at end of fallbacks."
+ raise ValueError(msg)
+ await run_manager.on_chain_error(first_error)
+ raise first_error
+
+ @override
+ def batch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if self.exception_key is not None and not all(
+ isinstance(input_, dict) for input_ in inputs
+ ):
+ msg = (
+ "If 'exception_key' is specified then inputs must be dictionaries."
+ f"However found a type of {type(inputs[0])} for input"
+ )
+ raise ValueError(msg)
+
+ if not inputs:
+ return []
+
+ # setup callbacks
+ configs = get_config_list(config, len(inputs))
+ callback_managers = [
+ CallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ local_callbacks=None,
+ verbose=False,
+ inheritable_tags=config.get("tags"),
+ local_tags=None,
+ inheritable_metadata=config.get("metadata"),
+ local_metadata=None,
+ )
+ for config in configs
+ ]
+ # start the root runs, one per input
+ run_managers = [
+ cm.on_chain_start(
+ None,
+ input_ if isinstance(input_, dict) else {"input": input_},
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ for cm, input_, config in zip(
+ callback_managers, inputs, configs, strict=False
+ )
+ ]
+
+ to_return: dict[int, Any] = {}
+ run_again = dict(enumerate(inputs))
+ handled_exceptions: dict[int, BaseException] = {}
+ first_to_raise = None
+ for runnable in self.runnables:
+ outputs = runnable.batch(
+ [input_ for _, input_ in sorted(run_again.items())],
+ [
+ # each step a child run of the corresponding root run
+ patch_config(configs[i], callbacks=run_managers[i].get_child())
+ for i in sorted(run_again)
+ ],
+ return_exceptions=True,
+ **kwargs,
+ )
+ for (i, input_), output in zip(
+ sorted(run_again.copy().items()), outputs, strict=False
+ ):
+ if isinstance(output, BaseException) and not isinstance(
+ output, self.exceptions_to_handle
+ ):
+ if not return_exceptions:
+ first_to_raise = first_to_raise or output
+ else:
+ handled_exceptions[i] = output
+ run_again.pop(i)
+ elif isinstance(output, self.exceptions_to_handle):
+ if self.exception_key:
+ input_[self.exception_key] = output # type: ignore[index]
+ handled_exceptions[i] = output
+ else:
+ run_managers[i].on_chain_end(output)
+ to_return[i] = output
+ run_again.pop(i)
+ handled_exceptions.pop(i, None)
+ if first_to_raise:
+ raise first_to_raise
+ if not run_again:
+ break
+
+ sorted_handled_exceptions = sorted(handled_exceptions.items())
+ for i, error in sorted_handled_exceptions:
+ run_managers[i].on_chain_error(error)
+ if not return_exceptions and sorted_handled_exceptions:
+ raise sorted_handled_exceptions[0][1]
+ to_return.update(handled_exceptions)
+ return [output for _, output in sorted(to_return.items())]
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if self.exception_key is not None and not all(
+ isinstance(input_, dict) for input_ in inputs
+ ):
+ msg = (
+ "If 'exception_key' is specified then inputs must be dictionaries."
+ f"However found a type of {type(inputs[0])} for input"
+ )
+ raise ValueError(msg)
+
+ if not inputs:
+ return []
+
+ # setup callbacks
+ configs = get_config_list(config, len(inputs))
+ callback_managers = [
+ AsyncCallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ local_callbacks=None,
+ verbose=False,
+ inheritable_tags=config.get("tags"),
+ local_tags=None,
+ inheritable_metadata=config.get("metadata"),
+ local_metadata=None,
+ )
+ for config in configs
+ ]
+ # start the root runs, one per input
+ run_managers: list[AsyncCallbackManagerForChainRun] = await asyncio.gather(
+ *(
+ cm.on_chain_start(
+ None,
+ input_,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ for cm, input_, config in zip(
+ callback_managers, inputs, configs, strict=False
+ )
+ )
+ )
+
+ to_return: dict[int, Output | BaseException] = {}
+ run_again = dict(enumerate(inputs))
+ handled_exceptions: dict[int, BaseException] = {}
+ first_to_raise = None
+ for runnable in self.runnables:
+ outputs = await runnable.abatch(
+ [input_ for _, input_ in sorted(run_again.items())],
+ [
+ # each step a child run of the corresponding root run
+ patch_config(configs[i], callbacks=run_managers[i].get_child())
+ for i in sorted(run_again)
+ ],
+ return_exceptions=True,
+ **kwargs,
+ )
+
+ for (i, input_), output in zip(
+ sorted(run_again.copy().items()), outputs, strict=False
+ ):
+ if isinstance(output, BaseException) and not isinstance(
+ output, self.exceptions_to_handle
+ ):
+ if not return_exceptions:
+ first_to_raise = first_to_raise or output
+ else:
+ handled_exceptions[i] = output
+ run_again.pop(i)
+ elif isinstance(output, self.exceptions_to_handle):
+ if self.exception_key:
+ input_[self.exception_key] = output # type: ignore[index]
+ handled_exceptions[i] = output
+ else:
+ to_return[i] = output
+ await run_managers[i].on_chain_end(output)
+ run_again.pop(i)
+ handled_exceptions.pop(i, None)
+
+ if first_to_raise:
+ raise first_to_raise
+ if not run_again:
+ break
+
+ sorted_handled_exceptions = sorted(handled_exceptions.items())
+ await asyncio.gather(
+ *(
+ run_managers[i].on_chain_error(error)
+ for i, error in sorted_handled_exceptions
+ )
+ )
+ if not return_exceptions and sorted_handled_exceptions:
+ raise sorted_handled_exceptions[0][1]
+ to_return.update(handled_exceptions)
+ return [cast("Output", output) for _, output in sorted(to_return.items())]
+
+ @override
+ def stream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ if self.exception_key is not None and not isinstance(input, dict):
+ msg = (
+ "If 'exception_key' is specified then input must be a dictionary."
+ f"However found a type of {type(input)} for input"
+ )
+ raise ValueError(msg)
+ # setup callbacks
+ config = ensure_config(config)
+ callback_manager = get_callback_manager_for_config(config)
+ # start the root run
+ run_manager = callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ first_error = None
+ last_error = None
+ for runnable in self.runnables:
+ try:
+ if self.exception_key and last_error is not None:
+ input[self.exception_key] = last_error # type: ignore[index]
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ stream = context.run(
+ runnable.stream,
+ input,
+ **kwargs,
+ )
+ chunk: Output = context.run(next, stream)
+ except self.exceptions_to_handle as e:
+ first_error = e if first_error is None else first_error
+ last_error = e
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ else:
+ first_error = None
+ break
+ if first_error:
+ run_manager.on_chain_error(first_error)
+ raise first_error
+
+ yield chunk
+ output: Output | None = chunk
+ try:
+ for chunk in stream:
+ yield chunk
+ try:
+ output = output + chunk # type: ignore[operator]
+ except TypeError:
+ output = None
+ except BaseException as e:
+ run_manager.on_chain_error(e)
+ raise
+ run_manager.on_chain_end(output)
+
+ @override
+ async def astream(
+ self,
+ input: Input,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ if self.exception_key is not None and not isinstance(input, dict):
+ msg = (
+ "If 'exception_key' is specified then input must be a dictionary."
+ f"However found a type of {type(input)} for input"
+ )
+ raise ValueError(msg)
+ # setup callbacks
+ config = ensure_config(config)
+ callback_manager = get_async_callback_manager_for_config(config)
+ # start the root run
+ run_manager = await callback_manager.on_chain_start(
+ None,
+ input,
+ name=config.get("run_name") or self.get_name(),
+ run_id=config.pop("run_id", None),
+ )
+ first_error = None
+ last_error = None
+ for runnable in self.runnables:
+ try:
+ if self.exception_key and last_error is not None:
+ input[self.exception_key] = last_error # type: ignore[index]
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ stream = runnable.astream(
+ input,
+ child_config,
+ **kwargs,
+ )
+ chunk = await coro_with_context(anext(stream), context)
+ except self.exceptions_to_handle as e:
+ first_error = e if first_error is None else first_error
+ last_error = e
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ else:
+ first_error = None
+ break
+ if first_error:
+ await run_manager.on_chain_error(first_error)
+ raise first_error
+
+ yield chunk
+ output: Output | None = chunk
+ try:
+ async for chunk in stream:
+ yield chunk
+ try:
+ output = output + chunk # type: ignore[operator]
+ except TypeError:
+ output = None
+ except BaseException as e:
+ await run_manager.on_chain_error(e)
+ raise
+ await run_manager.on_chain_end(output)
+
+ def __getattr__(self, name: str) -> Any:
+ """Get an attribute from the wrapped `Runnable` and its fallbacks.
+
+ Returns:
+ If the attribute is anything other than a method that outputs a `Runnable`,
+ returns `getattr(self.runnable, name)`. If the attribute is a method that
+ does return a new `Runnable` (e.g. `model.bind_tools([...])` outputs a new
+ `RunnableBinding`) then `self.runnable` and each of the runnables in
+ `self.fallbacks` is replaced with `getattr(x, name)`.
+
+ Example:
+ ```python
+ from langchain_openai import ChatOpenAI
+ from langchain_anthropic import ChatAnthropic
+
+ gpt_4o = ChatOpenAI(model="gpt-4o")
+ claude_3_sonnet = ChatAnthropic(model="claude-sonnet-4-5-20250929")
+ model = gpt_4o.with_fallbacks([claude_3_sonnet])
+
+ model.model_name
+ # -> "gpt-4o"
+
+ # .bind_tools() is called on both ChatOpenAI and ChatAnthropic
+ # Equivalent to:
+ # gpt_4o.bind_tools([...]).with_fallbacks([claude_3_sonnet.bind_tools([...])])
+ model.bind_tools([...])
+ # -> RunnableWithFallbacks(
+ runnable=RunnableBinding(bound=ChatOpenAI(...), kwargs={"tools": [...]}),
+ fallbacks=[RunnableBinding(bound=ChatAnthropic(...), kwargs={"tools": [...]})],
+ )
+ ```
+ """ # noqa: E501
+ attr = getattr(self.runnable, name)
+ if _returns_runnable(attr):
+
+ @wraps(attr)
+ def wrapped(*args: Any, **kwargs: Any) -> Any:
+ new_runnable = attr(*args, **kwargs)
+ new_fallbacks = []
+ for fallback in self.fallbacks:
+ fallback_attr = getattr(fallback, name)
+ new_fallbacks.append(fallback_attr(*args, **kwargs))
+
+ return self.__class__(
+ **{
+ **self.model_dump(),
+ "runnable": new_runnable,
+ "fallbacks": new_fallbacks,
+ }
+ )
+
+ return wrapped
+
+ return attr
+
+
+def _returns_runnable(attr: Any) -> bool:
+ if not callable(attr):
+ return False
+ return_type = typing.get_type_hints(attr).get("return")
+ return bool(return_type and _is_runnable_type(return_type))
+
+
+def _is_runnable_type(type_: Any) -> bool:
+ if inspect.isclass(type_):
+ return issubclass(type_, Runnable)
+ origin = getattr(type_, "__origin__", None)
+ if inspect.isclass(origin):
+ return issubclass(origin, Runnable)
+ if origin is typing.Union:
+ return all(_is_runnable_type(t) for t in type_.__args__)
+ return False
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/graph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdab7d48846b63511229cf0723785deb489529d5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/graph.py
@@ -0,0 +1,739 @@
+"""Graph used in `Runnable` objects."""
+
+from __future__ import annotations
+
+import inspect
+from collections import defaultdict
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ NamedTuple,
+ Protocol,
+ TypedDict,
+ overload,
+)
+from uuid import UUID, uuid4
+
+from langchain_core.load.serializable import to_json_not_implemented
+from langchain_core.runnables.base import Runnable, RunnableSerializable
+from langchain_core.utils.pydantic import _IgnoreUnserializable, is_basemodel_subclass
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Sequence
+
+ from pydantic import BaseModel
+
+ from langchain_core.runnables.base import Runnable as RunnableType
+
+
+class Stringifiable(Protocol):
+ """Protocol for objects that can be converted to a string."""
+
+ def __str__(self) -> str:
+ """Convert the object to a string."""
+
+
+class LabelsDict(TypedDict):
+ """Dictionary of labels for nodes and edges in a graph."""
+
+ nodes: dict[str, str]
+ """Labels for nodes."""
+ edges: dict[str, str]
+ """Labels for edges."""
+
+
+def is_uuid(value: str) -> bool:
+ """Check if a string is a valid UUID.
+
+ Args:
+ value: The string to check.
+
+ Returns:
+ `True` if the string is a valid UUID, `False` otherwise.
+ """
+ try:
+ UUID(value)
+ except ValueError:
+ return False
+ return True
+
+
+class Edge(NamedTuple):
+ """Edge in a graph."""
+
+ source: str
+ """The source node id."""
+ target: str
+ """The target node id."""
+ data: Stringifiable | None = None
+ """Optional data associated with the edge. """
+ conditional: bool = False
+ """Whether the edge is conditional."""
+
+ def copy(self, *, source: str | None = None, target: str | None = None) -> Edge:
+ """Return a copy of the edge with optional new source and target nodes.
+
+ Args:
+ source: The new source node id.
+ target: The new target node id.
+
+ Returns:
+ A copy of the edge with the new source and target nodes.
+ """
+ return Edge(
+ source=source or self.source,
+ target=target or self.target,
+ data=self.data,
+ conditional=self.conditional,
+ )
+
+
+class Node(NamedTuple):
+ """Node in a graph."""
+
+ id: str
+ """The unique identifier of the node."""
+ name: str
+ """The name of the node."""
+ data: type[BaseModel] | RunnableType | None
+ """The data of the node."""
+ metadata: dict[str, Any] | None
+ """Optional metadata for the node. """
+
+ def copy(
+ self,
+ *,
+ id: str | None = None,
+ name: str | None = None,
+ ) -> Node:
+ """Return a copy of the node with optional new id and name.
+
+ Args:
+ id: The new node id.
+ name: The new node name.
+
+ Returns:
+ A copy of the node with the new id and name.
+ """
+ return Node(
+ id=id or self.id,
+ name=name or self.name,
+ data=self.data,
+ metadata=self.metadata,
+ )
+
+
+class Branch(NamedTuple):
+ """Branch in a graph."""
+
+ condition: Callable[..., str]
+ """A callable that returns a string representation of the condition."""
+ ends: dict[str, str] | None
+ """Optional dictionary of end node IDs for the branches. """
+
+
+class CurveStyle(Enum):
+ """Enum for different curve styles supported by Mermaid."""
+
+ BASIS = "basis"
+ BUMP_X = "bumpX"
+ BUMP_Y = "bumpY"
+ CARDINAL = "cardinal"
+ CATMULL_ROM = "catmullRom"
+ LINEAR = "linear"
+ MONOTONE_X = "monotoneX"
+ MONOTONE_Y = "monotoneY"
+ NATURAL = "natural"
+ STEP = "step"
+ STEP_AFTER = "stepAfter"
+ STEP_BEFORE = "stepBefore"
+
+
+@dataclass
+class NodeStyles:
+ """Schema for Hexadecimal color codes for different node types.
+
+ Args:
+ default: The default color code.
+ first: The color code for the first node.
+ last: The color code for the last node.
+ """
+
+ default: str = "fill:#f2f0ff,line-height:1.2"
+ first: str = "fill-opacity:0"
+ last: str = "fill:#bfb6fc"
+
+
+class MermaidDrawMethod(Enum):
+ """Enum for different draw methods supported by Mermaid."""
+
+ PYPPETEER = "pyppeteer"
+ """Uses Pyppeteer to render the graph"""
+ API = "api"
+ """Uses Mermaid.INK API to render the graph"""
+
+
+def node_data_str(
+ id: str,
+ data: type[BaseModel] | RunnableType | None,
+) -> str:
+ """Convert the data of a node to a string.
+
+ Args:
+ id: The node id.
+ data: The node data.
+
+ Returns:
+ A string representation of the data.
+ """
+ if not is_uuid(id) or data is None:
+ return id
+ data_str = data.get_name() if isinstance(data, Runnable) else data.__name__
+ return data_str if not data_str.startswith("Runnable") else data_str[8:]
+
+
+def node_data_json(
+ node: Node, *, with_schemas: bool = False
+) -> dict[str, str | dict[str, Any]]:
+ """Convert the data of a node to a JSON-serializable format.
+
+ Args:
+ node: The `Node` to convert.
+ with_schemas: Whether to include the schema of the data if it is a Pydantic
+ model.
+
+ Returns:
+ A dictionary with the type of the data and the data itself.
+ """
+ if node.data is None:
+ json: dict[str, Any] = {}
+ elif isinstance(node.data, RunnableSerializable):
+ json = {
+ "type": "runnable",
+ "data": {
+ "id": node.data.lc_id(),
+ "name": node_data_str(node.id, node.data),
+ },
+ }
+ elif isinstance(node.data, Runnable):
+ json = {
+ "type": "runnable",
+ "data": {
+ "id": to_json_not_implemented(node.data)["id"],
+ "name": node_data_str(node.id, node.data),
+ },
+ }
+ elif inspect.isclass(node.data) and is_basemodel_subclass(node.data):
+ json = (
+ {
+ "type": "schema",
+ "data": node.data.model_json_schema(
+ schema_generator=_IgnoreUnserializable
+ ),
+ }
+ if with_schemas
+ else {
+ "type": "schema",
+ "data": node_data_str(node.id, node.data),
+ }
+ )
+ else:
+ json = {
+ "type": "unknown",
+ "data": node_data_str(node.id, node.data),
+ }
+ if node.metadata is not None:
+ json["metadata"] = node.metadata
+ return json
+
+
+@dataclass
+class Graph:
+ """Graph of nodes and edges.
+
+ Args:
+ nodes: Dictionary of nodes in the graph. Defaults to an empty dictionary.
+ edges: List of edges in the graph. Defaults to an empty list.
+ """
+
+ nodes: dict[str, Node] = field(default_factory=dict)
+ edges: list[Edge] = field(default_factory=list)
+
+ def to_json(self, *, with_schemas: bool = False) -> dict[str, list[dict[str, Any]]]:
+ """Convert the graph to a JSON-serializable format.
+
+ Args:
+ with_schemas: Whether to include the schemas of the nodes if they are
+ Pydantic models.
+
+ Returns:
+ A dictionary with the nodes and edges of the graph.
+ """
+ stable_node_ids = {
+ node.id: i if is_uuid(node.id) else node.id
+ for i, node in enumerate(self.nodes.values())
+ }
+ edges: list[dict[str, Any]] = []
+ for edge in self.edges:
+ edge_dict = {
+ "source": stable_node_ids[edge.source],
+ "target": stable_node_ids[edge.target],
+ }
+ if edge.data is not None:
+ edge_dict["data"] = edge.data # type: ignore[assignment]
+ if edge.conditional:
+ edge_dict["conditional"] = True
+ edges.append(edge_dict)
+
+ return {
+ "nodes": [
+ {
+ "id": stable_node_ids[node.id],
+ **node_data_json(node, with_schemas=with_schemas),
+ }
+ for node in self.nodes.values()
+ ],
+ "edges": edges,
+ }
+
+ def __bool__(self) -> bool:
+ """Return whether the graph has any nodes."""
+ return bool(self.nodes)
+
+ def next_id(self) -> str:
+ """Return a new unique node identifier.
+
+ It that can be used to add a node to the graph.
+ """
+ return uuid4().hex
+
+ def add_node(
+ self,
+ data: type[BaseModel] | RunnableType | None,
+ id: str | None = None,
+ *,
+ metadata: dict[str, Any] | None = None,
+ ) -> Node:
+ """Add a node to the graph and return it.
+
+ Args:
+ data: The data of the node.
+ id: The id of the node.
+ metadata: Optional metadata for the node.
+
+ Returns:
+ The node that was added to the graph.
+
+ Raises:
+ ValueError: If a node with the same id already exists.
+ """
+ if id is not None and id in self.nodes:
+ msg = f"Node with id {id} already exists"
+ raise ValueError(msg)
+ id_ = id or self.next_id()
+ node = Node(id=id_, data=data, metadata=metadata, name=node_data_str(id_, data))
+ self.nodes[node.id] = node
+ return node
+
+ def remove_node(self, node: Node) -> None:
+ """Remove a node from the graph and all edges connected to it.
+
+ Args:
+ node: The node to remove.
+ """
+ self.nodes.pop(node.id)
+ self.edges = [
+ edge for edge in self.edges if node.id not in {edge.source, edge.target}
+ ]
+
+ def add_edge(
+ self,
+ source: Node,
+ target: Node,
+ data: Stringifiable | None = None,
+ conditional: bool = False, # noqa: FBT001,FBT002
+ ) -> Edge:
+ """Add an edge to the graph and return it.
+
+ Args:
+ source: The source node of the edge.
+ target: The target node of the edge.
+ data: Optional data associated with the edge.
+ conditional: Whether the edge is conditional.
+
+ Returns:
+ The edge that was added to the graph.
+
+ Raises:
+ ValueError: If the source or target node is not in the graph.
+ """
+ if source.id not in self.nodes:
+ msg = f"Source node {source.id} not in graph"
+ raise ValueError(msg)
+ if target.id not in self.nodes:
+ msg = f"Target node {target.id} not in graph"
+ raise ValueError(msg)
+ edge = Edge(
+ source=source.id, target=target.id, data=data, conditional=conditional
+ )
+ self.edges.append(edge)
+ return edge
+
+ def extend(
+ self, graph: Graph, *, prefix: str = ""
+ ) -> tuple[Node | None, Node | None]:
+ """Add all nodes and edges from another graph.
+
+ Note this doesn't check for duplicates, nor does it connect the graphs.
+
+ Args:
+ graph: The graph to add.
+ prefix: The prefix to add to the node ids.
+
+ Returns:
+ A tuple of the first and last nodes of the subgraph.
+ """
+ if all(is_uuid(node.id) for node in graph.nodes.values()):
+ prefix = ""
+
+ def prefixed(id_: str) -> str:
+ return f"{prefix}:{id_}" if prefix else id_
+
+ # prefix each node
+ self.nodes.update(
+ {prefixed(k): v.copy(id=prefixed(k)) for k, v in graph.nodes.items()}
+ )
+ # prefix each edge's source and target
+ self.edges.extend(
+ [
+ edge.copy(source=prefixed(edge.source), target=prefixed(edge.target))
+ for edge in graph.edges
+ ]
+ )
+ # return (prefixed) first and last nodes of the subgraph
+ first, last = graph.first_node(), graph.last_node()
+ return (
+ first.copy(id=prefixed(first.id)) if first else None,
+ last.copy(id=prefixed(last.id)) if last else None,
+ )
+
+ def reid(self) -> Graph:
+ """Return a new graph with all nodes re-identified.
+
+ Uses their unique, readable names where possible.
+ """
+ node_name_to_ids = defaultdict(list)
+ for node in self.nodes.values():
+ node_name_to_ids[node.name].append(node.id)
+
+ unique_labels = {
+ node_id: node_name if len(node_ids) == 1 else f"{node_name}_{i + 1}"
+ for node_name, node_ids in node_name_to_ids.items()
+ for i, node_id in enumerate(node_ids)
+ }
+
+ def _get_node_id(node_id: str) -> str:
+ label = unique_labels[node_id]
+ if is_uuid(node_id):
+ return label
+ return node_id
+
+ return Graph(
+ nodes={
+ _get_node_id(id_): node.copy(id=_get_node_id(id_))
+ for id_, node in self.nodes.items()
+ },
+ edges=[
+ edge.copy(
+ source=_get_node_id(edge.source),
+ target=_get_node_id(edge.target),
+ )
+ for edge in self.edges
+ ],
+ )
+
+ def first_node(self) -> Node | None:
+ """Find the single node that is not a target of any edge.
+
+ If there is no such node, or there are multiple, return `None`.
+ When drawing the graph, this node would be the origin.
+
+ Returns:
+ The first node, or None if there is no such node or multiple
+ candidates.
+ """
+ return _first_node(self)
+
+ def last_node(self) -> Node | None:
+ """Find the single node that is not a source of any edge.
+
+ If there is no such node, or there are multiple, return `None`.
+ When drawing the graph, this node would be the destination.
+
+ Returns:
+ The last node, or None if there is no such node or multiple
+ candidates.
+ """
+ return _last_node(self)
+
+ def trim_first_node(self) -> None:
+ """Remove the first node if it exists and has a single outgoing edge.
+
+ i.e., if removing it would not leave the graph without a "first" node.
+ """
+ first_node = self.first_node()
+ if (
+ first_node
+ and _first_node(self, exclude=[first_node.id])
+ and len({e for e in self.edges if e.source == first_node.id}) == 1
+ ):
+ self.remove_node(first_node)
+
+ def trim_last_node(self) -> None:
+ """Remove the last node if it exists and has a single incoming edge.
+
+ i.e., if removing it would not leave the graph without a "last" node.
+ """
+ last_node = self.last_node()
+ if (
+ last_node
+ and _last_node(self, exclude=[last_node.id])
+ and len({e for e in self.edges if e.target == last_node.id}) == 1
+ ):
+ self.remove_node(last_node)
+
+ def draw_ascii(self) -> str:
+ """Draw the graph as an ASCII art string.
+
+ Returns:
+ The ASCII art string.
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph_ascii import draw_ascii # noqa: PLC0415
+
+ return draw_ascii(
+ {node.id: node.name for node in self.nodes.values()},
+ self.edges,
+ )
+
+ def print_ascii(self) -> None:
+ """Print the graph as an ASCII art string."""
+ print(self.draw_ascii()) # noqa: T201
+
+ @overload
+ def draw_png(
+ self,
+ output_file_path: str,
+ fontname: str | None = None,
+ labels: LabelsDict | None = None,
+ ) -> None: ...
+
+ @overload
+ def draw_png(
+ self,
+ output_file_path: None,
+ fontname: str | None = None,
+ labels: LabelsDict | None = None,
+ ) -> bytes: ...
+
+ def draw_png(
+ self,
+ output_file_path: str | None = None,
+ fontname: str | None = None,
+ labels: LabelsDict | None = None,
+ ) -> bytes | None:
+ """Draw the graph as a PNG image.
+
+ Args:
+ output_file_path: The path to save the image to. If `None`, the image
+ is not saved.
+ fontname: The name of the font to use.
+ labels: Optional labels for nodes and edges in the graph. Defaults to
+ `None`.
+
+ Returns:
+ The PNG image as bytes if output_file_path is None, None otherwise.
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph_png import PngDrawer # noqa: PLC0415
+
+ default_node_labels = {node.id: node.name for node in self.nodes.values()}
+
+ return PngDrawer(
+ fontname,
+ LabelsDict(
+ nodes={
+ **default_node_labels,
+ **(labels["nodes"] if labels is not None else {}),
+ },
+ edges=labels["edges"] if labels is not None else {},
+ ),
+ ).draw(self, output_file_path)
+
+ def draw_mermaid(
+ self,
+ *,
+ with_styles: bool = True,
+ curve_style: CurveStyle = CurveStyle.LINEAR,
+ node_colors: NodeStyles | None = None,
+ wrap_label_n_words: int = 9,
+ frontmatter_config: dict[str, Any] | None = None,
+ ) -> str:
+ """Draw the graph as a Mermaid syntax string.
+
+ Args:
+ with_styles: Whether to include styles in the syntax.
+ curve_style: The style of the edges.
+ node_colors: The colors of the nodes.
+ wrap_label_n_words: The number of words to wrap the node labels at.
+ frontmatter_config: Mermaid frontmatter config.
+ Can be used to customize theme and styles. Will be converted to YAML and
+ added to the beginning of the mermaid graph.
+
+ See more here: https://mermaid.js.org/config/configuration.html.
+
+ Example config:
+
+ ```python
+ {
+ "config": {
+ "theme": "neutral",
+ "look": "handDrawn",
+ "themeVariables": {"primaryColor": "#e2e2e2"},
+ }
+ }
+ ```
+ Returns:
+ The Mermaid syntax string.
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph_mermaid import draw_mermaid # noqa: PLC0415
+
+ graph = self.reid()
+ first_node = graph.first_node()
+ last_node = graph.last_node()
+
+ return draw_mermaid(
+ nodes=graph.nodes,
+ edges=graph.edges,
+ first_node=first_node.id if first_node else None,
+ last_node=last_node.id if last_node else None,
+ with_styles=with_styles,
+ curve_style=curve_style,
+ node_styles=node_colors,
+ wrap_label_n_words=wrap_label_n_words,
+ frontmatter_config=frontmatter_config,
+ )
+
+ def draw_mermaid_png(
+ self,
+ *,
+ curve_style: CurveStyle = CurveStyle.LINEAR,
+ node_colors: NodeStyles | None = None,
+ wrap_label_n_words: int = 9,
+ output_file_path: str | None = None,
+ draw_method: MermaidDrawMethod = MermaidDrawMethod.API,
+ background_color: str = "white",
+ padding: int = 10,
+ max_retries: int = 1,
+ retry_delay: float = 1.0,
+ frontmatter_config: dict[str, Any] | None = None,
+ base_url: str | None = None,
+ proxies: dict[str, str] | None = None,
+ ) -> bytes:
+ """Draw the graph as a PNG image using Mermaid.
+
+ Args:
+ curve_style: The style of the edges.
+ node_colors: The colors of the nodes.
+ wrap_label_n_words: The number of words to wrap the node labels at.
+ output_file_path: The path to save the image to. If `None`, the image
+ is not saved.
+ draw_method: The method to use to draw the graph.
+ background_color: The color of the background.
+ padding: The padding around the graph.
+ max_retries: The maximum number of retries (`MermaidDrawMethod.API`).
+ retry_delay: The delay between retries (`MermaidDrawMethod.API`).
+ frontmatter_config: Mermaid frontmatter config.
+ Can be used to customize theme and styles. Will be converted to YAML and
+ added to the beginning of the mermaid graph.
+
+ See more here: https://mermaid.js.org/config/configuration.html.
+
+ Example config:
+
+ ```python
+ {
+ "config": {
+ "theme": "neutral",
+ "look": "handDrawn",
+ "themeVariables": {"primaryColor": "#e2e2e2"},
+ }
+ }
+ ```
+ base_url: The base URL of the Mermaid server for rendering via API.
+ proxies: HTTP/HTTPS proxies for requests (e.g. `{"http": "http://127.0.0.1:7890"}`).
+
+ Returns:
+ The PNG image as bytes.
+ """
+ # Import locally to prevent circular import
+ from langchain_core.runnables.graph_mermaid import ( # noqa: PLC0415
+ draw_mermaid_png,
+ )
+
+ mermaid_syntax = self.draw_mermaid(
+ curve_style=curve_style,
+ node_colors=node_colors,
+ wrap_label_n_words=wrap_label_n_words,
+ frontmatter_config=frontmatter_config,
+ )
+ return draw_mermaid_png(
+ mermaid_syntax=mermaid_syntax,
+ output_file_path=output_file_path,
+ draw_method=draw_method,
+ background_color=background_color,
+ padding=padding,
+ max_retries=max_retries,
+ retry_delay=retry_delay,
+ proxies=proxies,
+ base_url=base_url,
+ )
+
+
+def _first_node(graph: Graph, exclude: Sequence[str] = ()) -> Node | None:
+ """Find the single node that is not a target of any edge.
+
+ Exclude nodes/sources with IDs in the exclude list.
+
+ If there is no such node, or there are multiple, return `None`.
+
+ When drawing the graph, this node would be the origin.
+ """
+ targets = {edge.target for edge in graph.edges if edge.source not in exclude}
+ found: list[Node] = [
+ node
+ for node in graph.nodes.values()
+ if node.id not in exclude and node.id not in targets
+ ]
+ return found[0] if len(found) == 1 else None
+
+
+def _last_node(graph: Graph, exclude: Sequence[str] = ()) -> Node | None:
+ """Find the single node that is not a source of any edge.
+
+ Exclude nodes/targets with IDs in the exclude list.
+
+ If there is no such node, or there are multiple, return `None`.
+
+ When drawing the graph, this node would be the destination.
+ """
+ sources = {edge.source for edge in graph.edges if edge.target not in exclude}
+ found: list[Node] = [
+ node
+ for node in graph.nodes.values()
+ if node.id not in exclude and node.id not in sources
+ ]
+ return found[0] if len(found) == 1 else None
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/graph_ascii.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/graph_ascii.py
new file mode 100644
index 0000000000000000000000000000000000000000..14d29a837d6341d538f64a96713cd81afbbc5e5e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/graph_ascii.py
@@ -0,0 +1,366 @@
+"""Draws DAG in ASCII.
+
+Adapted from https://github.com/iterative/dvc/blob/main/dvc/dagascii.py.
+"""
+
+from __future__ import annotations
+
+import math
+import os
+from typing import TYPE_CHECKING, Any
+
+try:
+ from grandalf.graphs import Edge, Graph, Vertex # type: ignore[import-untyped]
+ from grandalf.layouts import SugiyamaLayout # type: ignore[import-untyped]
+ from grandalf.routing import route_with_lines # type: ignore[import-untyped]
+
+ _HAS_GRANDALF = True
+except ImportError:
+ _HAS_GRANDALF = False
+
+if TYPE_CHECKING:
+ from collections.abc import Mapping, Sequence
+
+ from langchain_core.runnables.graph import Edge as LangEdge
+
+
+class VertexViewer:
+ """VertexViewer class.
+
+ Class to define vertex box boundaries that will be accounted for during
+ graph building by grandalf.
+ """
+
+ HEIGHT = 3 # top and bottom box edges + text
+ """Height of the box."""
+
+ def __init__(self, name: str) -> None:
+ """Create a VertexViewer.
+
+ Args:
+ name: name of the vertex.
+ """
+ self._h = self.HEIGHT # top and bottom box edges + text
+ self._w = len(name) + 2 # right and left bottom edges + text
+
+ @property
+ def h(self) -> int:
+ """Height of the box."""
+ return self._h
+
+ @property
+ def w(self) -> int:
+ """Width of the box."""
+ return self._w
+
+
+class AsciiCanvas:
+ """Class for drawing in ASCII."""
+
+ TIMEOUT = 10
+
+ def __init__(self, cols: int, lines: int) -> None:
+ """Create an ASCII canvas.
+
+ Args:
+ cols: number of columns in the canvas. Should be `> 1`.
+ lines: number of lines in the canvas. Should be `> 1`.
+
+ Raises:
+ ValueError: if canvas dimensions are invalid.
+ """
+ if cols <= 1 or lines <= 1:
+ msg = "Canvas dimensions should be > 1"
+ raise ValueError(msg)
+
+ self.cols = cols
+ self.lines = lines
+
+ self.canvas = [[" "] * cols for line in range(lines)]
+
+ def draw(self) -> str:
+ """Draws ASCII canvas on the screen.
+
+ Returns:
+ The ASCII canvas string.
+ """
+ lines = map("".join, self.canvas)
+ return os.linesep.join(lines)
+
+ def point(self, x: int, y: int, char: str) -> None:
+ """Create a point on ASCII canvas.
+
+ Args:
+ x: x coordinate. Should be `>= 0` and `<` number of columns in
+ the canvas.
+ y: y coordinate. Should be `>= 0` an `<` number of lines in the
+ canvas.
+ char: character to place in the specified point on the
+ canvas.
+
+ Raises:
+ ValueError: if char is not a single character or if
+ coordinates are out of bounds.
+ """
+ if len(char) != 1:
+ msg = "char should be a single character"
+ raise ValueError(msg)
+ if x >= self.cols or x < 0:
+ msg = "x should be >= 0 and < number of columns"
+ raise ValueError(msg)
+ if y >= self.lines or y < 0:
+ msg = "y should be >= 0 and < number of lines"
+ raise ValueError(msg)
+
+ self.canvas[y][x] = char
+
+ def line(self, x0: int, y0: int, x1: int, y1: int, char: str) -> None:
+ """Create a line on ASCII canvas.
+
+ Args:
+ x0: x coordinate where the line should start.
+ y0: y coordinate where the line should start.
+ x1: x coordinate where the line should end.
+ y1: y coordinate where the line should end.
+ char: character to draw the line with.
+ """
+ if x0 > x1:
+ x1, x0 = x0, x1
+ y1, y0 = y0, y1
+
+ dx = x1 - x0
+ dy = y1 - y0
+
+ if dx == 0 and dy == 0:
+ self.point(x0, y0, char)
+ elif abs(dx) >= abs(dy):
+ for x in range(x0, x1 + 1):
+ y = y0 if dx == 0 else y0 + round((x - x0) * dy / float(dx))
+ self.point(x, y, char)
+ elif y0 < y1:
+ for y in range(y0, y1 + 1):
+ x = x0 if dy == 0 else x0 + round((y - y0) * dx / float(dy))
+ self.point(x, y, char)
+ else:
+ for y in range(y1, y0 + 1):
+ x = x0 if dy == 0 else x1 + round((y - y1) * dx / float(dy))
+ self.point(x, y, char)
+
+ def text(self, x: int, y: int, text: str) -> None:
+ """Print a text on ASCII canvas.
+
+ Args:
+ x: x coordinate where the text should start.
+ y: y coordinate where the text should start.
+ text: string that should be printed.
+ """
+ for i, char in enumerate(text):
+ self.point(x + i, y, char)
+
+ def box(self, x0: int, y0: int, width: int, height: int) -> None:
+ """Create a box on ASCII canvas.
+
+ Args:
+ x0: x coordinate of the box corner.
+ y0: y coordinate of the box corner.
+ width: box width.
+ height: box height.
+
+ Raises:
+ ValueError: if box dimensions are invalid.
+ """
+ if width <= 1 or height <= 1:
+ msg = "Box dimensions should be > 1"
+ raise ValueError(msg)
+
+ width -= 1
+ height -= 1
+
+ for x in range(x0, x0 + width):
+ self.point(x, y0, "-")
+ self.point(x, y0 + height, "-")
+
+ for y in range(y0, y0 + height):
+ self.point(x0, y, "|")
+ self.point(x0 + width, y, "|")
+
+ self.point(x0, y0, "+")
+ self.point(x0 + width, y0, "+")
+ self.point(x0, y0 + height, "+")
+ self.point(x0 + width, y0 + height, "+")
+
+
+class _EdgeViewer:
+ def __init__(self) -> None:
+ self.pts: list[tuple[float]] = []
+
+ def setpath(self, pts: list[tuple[float]]) -> None:
+ self.pts = pts
+
+
+def _build_sugiyama_layout(
+ vertices: Mapping[str, str], edges: Sequence[LangEdge]
+) -> Any:
+ if not _HAS_GRANDALF:
+ msg = "Install grandalf to draw graphs: `pip install grandalf`."
+ raise ImportError(msg)
+
+ #
+ # Just a reminder about naming conventions:
+ # +------------X
+ # |
+ # |
+ # |
+ # |
+ # Y
+ #
+
+ vertices_ = {id_: Vertex(f" {data} ") for id_, data in vertices.items()}
+ edges_ = [Edge(vertices_[s], vertices_[e], data=cond) for s, e, _, cond in edges]
+ vertices_list = vertices_.values()
+ graph = Graph(vertices_list, edges_)
+
+ for vertex in vertices_list:
+ vertex.view = VertexViewer(vertex.data)
+
+ # NOTE: determine min box length to create the best layout
+ minw = min(v.view.w for v in vertices_list)
+
+ for edge in edges_:
+ edge.view = _EdgeViewer()
+
+ sug = SugiyamaLayout(graph.C[0])
+ graph = graph.C[0]
+ roots = list(filter(lambda x: len(x.e_in()) == 0, graph.sV))
+
+ sug.init_all(roots=roots, optimize=True)
+
+ sug.yspace = VertexViewer.HEIGHT
+ sug.xspace = minw
+ sug.route_edge = route_with_lines
+
+ sug.draw()
+
+ return sug
+
+
+def draw_ascii(vertices: Mapping[str, str], edges: Sequence[LangEdge]) -> str:
+ """Build a DAG and draw it in ASCII.
+
+ Args:
+ vertices: list of graph vertices.
+ edges: list of graph edges.
+
+ Raises:
+ ValueError: if the canvas dimensions are invalid or if
+ edge coordinates are invalid.
+
+ Returns:
+ ASCII representation
+
+ Example:
+ ```python
+ from langchain_core.runnables.graph_ascii import draw_ascii
+
+ vertices = {1: "1", 2: "2", 3: "3", 4: "4"}
+ edges = [
+ (source, target, None, None)
+ for source, target in [(1, 2), (2, 3), (2, 4), (1, 4)]
+ ]
+
+
+ print(draw_ascii(vertices, edges))
+ ```
+
+ ```txt
+
+ +---+
+ | 1 |
+ +---+
+ * *
+ * *
+ * *
+ +---+ *
+ | 2 | *
+ +---+** *
+ * ** *
+ * ** *
+ * **
+ +---+ +---+
+ | 3 | | 4 |
+ +---+ +---+
+ ```
+ """
+ # NOTE: coordinates might me negative, so we need to shift
+ # everything to the positive plane before we actually draw it.
+ xlist: list[float] = []
+ ylist: list[float] = []
+
+ sug = _build_sugiyama_layout(vertices, edges)
+
+ for vertex in sug.g.sV:
+ # NOTE: moving boxes w/2 to the left
+ xlist.extend(
+ (
+ vertex.view.xy[0] - vertex.view.w / 2.0,
+ vertex.view.xy[0] + vertex.view.w / 2.0,
+ )
+ )
+ ylist.extend((vertex.view.xy[1], vertex.view.xy[1] + vertex.view.h))
+
+ for edge in sug.g.sE:
+ for x, y in edge.view.pts:
+ xlist.append(x)
+ ylist.append(y)
+
+ minx = min(xlist)
+ miny = min(ylist)
+ maxx = max(xlist)
+ maxy = max(ylist)
+
+ canvas_cols = math.ceil(math.ceil(maxx) - math.floor(minx)) + 1
+ canvas_lines = round(maxy - miny)
+
+ canvas = AsciiCanvas(canvas_cols, canvas_lines)
+
+ # NOTE: first draw edges so that node boxes could overwrite them
+ for edge in sug.g.sE:
+ if len(edge.view.pts) <= 1:
+ msg = "Not enough points to draw an edge"
+ raise ValueError(msg)
+ for index in range(1, len(edge.view.pts)):
+ start = edge.view.pts[index - 1]
+ end = edge.view.pts[index]
+
+ start_x = round(start[0] - minx)
+ start_y = round(start[1] - miny)
+ end_x = round(end[0] - minx)
+ end_y = round(end[1] - miny)
+
+ if start_x < 0 or start_y < 0 or end_x < 0 or end_y < 0:
+ msg = (
+ "Invalid edge coordinates: "
+ f"start_x={start_x}, "
+ f"start_y={start_y}, "
+ f"end_x={end_x}, "
+ f"end_y={end_y}"
+ )
+ raise ValueError(msg)
+
+ canvas.line(start_x, start_y, end_x, end_y, "." if edge.data else "*")
+
+ for vertex in sug.g.sV:
+ # NOTE: moving boxes w/2 to the left
+ x = vertex.view.xy[0] - vertex.view.w / 2.0
+ y = vertex.view.xy[1]
+
+ canvas.box(
+ round(x - minx),
+ round(y - miny),
+ vertex.view.w,
+ vertex.view.h,
+ )
+
+ canvas.text(round(x - minx) + 1, round(y - miny) + 1, vertex.data)
+
+ return canvas.draw()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/graph_mermaid.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/graph_mermaid.py
new file mode 100644
index 0000000000000000000000000000000000000000..1499d6d1fab419681fa60a9639631bbb9837d8d6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/graph_mermaid.py
@@ -0,0 +1,503 @@
+"""Mermaid graph drawing utilities."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import random
+import re
+import string
+import time
+import urllib.parse
+from dataclasses import asdict
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+import yaml
+
+from langchain_core.runnables.graph import (
+ CurveStyle,
+ MermaidDrawMethod,
+ NodeStyles,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.runnables.graph import Edge, Node
+
+
+try:
+ import requests
+
+ _HAS_REQUESTS = True
+except ImportError:
+ _HAS_REQUESTS = False
+
+try:
+ from pyppeteer import launch # type: ignore[import-not-found]
+
+ _HAS_PYPPETEER = True
+except ImportError:
+ _HAS_PYPPETEER = False
+
+MARKDOWN_SPECIAL_CHARS = "*_`"
+
+
+def draw_mermaid(
+ nodes: dict[str, Node],
+ edges: list[Edge],
+ *,
+ first_node: str | None = None,
+ last_node: str | None = None,
+ with_styles: bool = True,
+ curve_style: CurveStyle = CurveStyle.LINEAR,
+ node_styles: NodeStyles | None = None,
+ wrap_label_n_words: int = 9,
+ frontmatter_config: dict[str, Any] | None = None,
+) -> str:
+ """Draws a Mermaid graph using the provided graph data.
+
+ Args:
+ nodes: List of node ids.
+ edges: List of edges, object with a source, target and data.
+ first_node: Id of the first node.
+ last_node: Id of the last node.
+ with_styles: Whether to include styles in the graph.
+ curve_style: Curve style for the edges.
+ node_styles: Node colors for different types.
+ wrap_label_n_words: Words to wrap the edge labels.
+ frontmatter_config: Mermaid frontmatter config.
+ Can be used to customize theme and styles. Will be converted to YAML and
+ added to the beginning of the mermaid graph.
+
+ See more here: https://mermaid.js.org/config/configuration.html.
+
+ Example config:
+
+ ```python
+ {
+ "config": {
+ "theme": "neutral",
+ "look": "handDrawn",
+ "themeVariables": {"primaryColor": "#e2e2e2"},
+ }
+ }
+ ```
+
+ Returns:
+ Mermaid graph syntax.
+
+ """
+ # Initialize Mermaid graph configuration
+ original_frontmatter_config = frontmatter_config or {}
+ original_flowchart_config = original_frontmatter_config.get("config", {}).get(
+ "flowchart", {}
+ )
+ frontmatter_config = {
+ **original_frontmatter_config,
+ "config": {
+ **original_frontmatter_config.get("config", {}),
+ "flowchart": {**original_flowchart_config, "curve": curve_style.value},
+ },
+ }
+
+ mermaid_graph = (
+ (
+ "---\n"
+ + yaml.dump(frontmatter_config, default_flow_style=False)
+ + "---\ngraph TD;\n"
+ )
+ if with_styles
+ else "graph TD;\n"
+ )
+ # Group nodes by subgraph
+ subgraph_nodes: dict[str, dict[str, Node]] = {}
+ regular_nodes: dict[str, Node] = {}
+
+ for key, node in nodes.items():
+ if ":" in key:
+ # For nodes with colons, add them only to their deepest subgraph level
+ prefix = ":".join(key.split(":")[:-1])
+ subgraph_nodes.setdefault(prefix, {})[key] = node
+ else:
+ regular_nodes[key] = node
+
+ # Node formatting templates
+ default_class_label = "default"
+ format_dict = {default_class_label: "{0}({1})"}
+ if first_node is not None:
+ format_dict[first_node] = "{0}([{1}]):::first"
+ if last_node is not None:
+ format_dict[last_node] = "{0}([{1}]):::last"
+
+ def render_node(key: str, node: Node, indent: str = "\t") -> str:
+ """Helper function to render a node with consistent formatting."""
+ node_name = node.name.split(":")[-1]
+ label = (
+ f"{node_name}
"
+ if node_name.startswith(tuple(MARKDOWN_SPECIAL_CHARS))
+ and node_name.endswith(tuple(MARKDOWN_SPECIAL_CHARS))
+ else node_name
+ )
+ if node.metadata:
+ label = (
+ f"{label}
"
+ + "\n".join(f"{k} = {value}" for k, value in node.metadata.items())
+ + ""
+ )
+ node_label = format_dict.get(key, format_dict[default_class_label]).format(
+ _to_safe_id(key), label
+ )
+ return f"{indent}{node_label}\n"
+
+ # Add non-subgraph nodes to the graph
+ if with_styles:
+ for key, node in regular_nodes.items():
+ mermaid_graph += render_node(key, node)
+
+ # Group edges by their common prefixes
+ edge_groups: dict[str, list[Edge]] = {}
+ for edge in edges:
+ src_parts = edge.source.split(":")
+ tgt_parts = edge.target.split(":")
+ common_prefix = ":".join(
+ src for src, tgt in zip(src_parts, tgt_parts, strict=False) if src == tgt
+ )
+ edge_groups.setdefault(common_prefix, []).append(edge)
+
+ seen_subgraphs = set()
+
+ def add_subgraph(edges: list[Edge], prefix: str) -> None:
+ nonlocal mermaid_graph
+ self_loop = len(edges) == 1 and edges[0].source == edges[0].target
+ if prefix and not self_loop:
+ subgraph = prefix.rsplit(":", maxsplit=1)[-1]
+ if subgraph in seen_subgraphs:
+ msg = (
+ f"Found duplicate subgraph '{subgraph}' -- this likely means that "
+ "you're reusing a subgraph node with the same name. "
+ "Please adjust your graph to have subgraph nodes with unique names."
+ )
+ raise ValueError(msg)
+
+ seen_subgraphs.add(subgraph)
+ mermaid_graph += f"\tsubgraph {subgraph}\n"
+
+ # Add nodes that belong to this subgraph
+ if with_styles and prefix in subgraph_nodes:
+ for key, node in subgraph_nodes[prefix].items():
+ mermaid_graph += render_node(key, node)
+
+ for edge in edges:
+ source, target = edge.source, edge.target
+
+ # Add BR every wrap_label_n_words words
+ if edge.data is not None:
+ edge_data = edge.data
+ words = str(edge_data).split() # Split the string into words
+ # Group words into chunks of wrap_label_n_words size
+ if len(words) > wrap_label_n_words:
+ edge_data = " 
 ".join(
+ " ".join(words[i : i + wrap_label_n_words])
+ for i in range(0, len(words), wrap_label_n_words)
+ )
+ if edge.conditional:
+ edge_label = f" -. {edge_data} .-> "
+ else:
+ edge_label = f" -- {edge_data} --> "
+ else:
+ edge_label = " -.-> " if edge.conditional else " --> "
+
+ mermaid_graph += (
+ f"\t{_to_safe_id(source)}{edge_label}{_to_safe_id(target)};\n"
+ )
+
+ # Recursively add nested subgraphs
+ for nested_prefix, edges_ in edge_groups.items():
+ if not nested_prefix.startswith(prefix + ":") or nested_prefix == prefix:
+ continue
+ # only go to first level subgraphs
+ if ":" in nested_prefix[len(prefix) + 1 :]:
+ continue
+ add_subgraph(edges_, nested_prefix)
+
+ if prefix and not self_loop:
+ mermaid_graph += "\tend\n"
+
+ # Start with the top-level edges (no common prefix)
+ add_subgraph(edge_groups.get("", []), "")
+
+ # Add remaining subgraphs with edges
+ for prefix, edges_ in edge_groups.items():
+ if not prefix or ":" in prefix:
+ continue
+ add_subgraph(edges_, prefix)
+ seen_subgraphs.add(prefix)
+
+ # Add empty subgraphs (subgraphs with no internal edges)
+ if with_styles:
+ for prefix, subgraph_node in subgraph_nodes.items():
+ if ":" not in prefix and prefix not in seen_subgraphs:
+ mermaid_graph += f"\tsubgraph {prefix}\n"
+
+ # Add nodes that belong to this subgraph
+ for key, node in subgraph_node.items():
+ mermaid_graph += render_node(key, node)
+
+ mermaid_graph += "\tend\n"
+ seen_subgraphs.add(prefix)
+
+ # Add custom styles for nodes
+ if with_styles:
+ mermaid_graph += _generate_mermaid_graph_styles(node_styles or NodeStyles())
+ return mermaid_graph
+
+
+def _to_safe_id(label: str) -> str:
+ """Convert a string into a Mermaid-compatible node id.
+
+ Keep [a-zA-Z0-9_-] characters unchanged.
+ Map every other character -> backslash + lowercase hex codepoint.
+
+ Result is guaranteed to be unique and Mermaid-compatible,
+ so nodes with special characters always render correctly.
+ """
+ allowed = string.ascii_letters + string.digits + "_-"
+ out = [ch if ch in allowed else "\\" + format(ord(ch), "x") for ch in label]
+ return "".join(out)
+
+
+def _generate_mermaid_graph_styles(node_colors: NodeStyles) -> str:
+ """Generates Mermaid graph styles for different node types."""
+ styles = ""
+ for class_name, style in asdict(node_colors).items():
+ styles += f"\tclassDef {class_name} {style}\n"
+ return styles
+
+
+def draw_mermaid_png(
+ mermaid_syntax: str,
+ output_file_path: str | None = None,
+ draw_method: MermaidDrawMethod = MermaidDrawMethod.API,
+ background_color: str | None = "white",
+ padding: int = 10,
+ max_retries: int = 1,
+ retry_delay: float = 1.0,
+ base_url: str | None = None,
+ proxies: dict[str, str] | None = None,
+) -> bytes:
+ """Draws a Mermaid graph as PNG using provided syntax.
+
+ Args:
+ mermaid_syntax: Mermaid graph syntax.
+ output_file_path: Path to save the PNG image.
+ draw_method: Method to draw the graph.
+ background_color: Background color of the image.
+ padding: Padding around the image.
+ max_retries: Maximum number of retries (MermaidDrawMethod.API).
+ retry_delay: Delay between retries (MermaidDrawMethod.API).
+ base_url: Base URL for the Mermaid.ink API.
+ proxies: HTTP/HTTPS proxies for requests (e.g. `{"http": "http://127.0.0.1:7890"}`).
+
+ Returns:
+ PNG image bytes.
+
+ Raises:
+ ValueError: If an invalid draw method is provided.
+ """
+ if draw_method == MermaidDrawMethod.PYPPETEER:
+ img_bytes = asyncio.run(
+ _render_mermaid_using_pyppeteer(
+ mermaid_syntax, output_file_path, background_color, padding
+ )
+ )
+ elif draw_method == MermaidDrawMethod.API:
+ img_bytes = _render_mermaid_using_api(
+ mermaid_syntax,
+ output_file_path=output_file_path,
+ background_color=background_color,
+ max_retries=max_retries,
+ retry_delay=retry_delay,
+ base_url=base_url,
+ proxies=proxies,
+ )
+ else:
+ supported_methods = ", ".join([m.value for m in MermaidDrawMethod])
+ msg = (
+ f"Invalid draw method: {draw_method}. "
+ f"Supported draw methods are: {supported_methods}"
+ )
+ raise ValueError(msg)
+
+ return img_bytes
+
+
+async def _render_mermaid_using_pyppeteer(
+ mermaid_syntax: str,
+ output_file_path: str | None = None,
+ background_color: str | None = "white",
+ padding: int = 10,
+ device_scale_factor: int = 3,
+) -> bytes:
+ """Renders Mermaid graph using Pyppeteer."""
+ if not _HAS_PYPPETEER:
+ msg = "Install Pyppeteer to use the Pyppeteer method: `pip install pyppeteer`."
+ raise ImportError(msg)
+
+ browser = await launch()
+ page = await browser.newPage()
+
+ # Setup Mermaid JS
+ await page.goto("about:blank")
+ await page.addScriptTag(
+ {"url": "https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"}
+ )
+ await page.evaluate(
+ """() => {
+ mermaid.initialize({startOnLoad:true});
+ }"""
+ )
+
+ # Render SVG
+ svg_code = await page.evaluate(
+ """(mermaidGraph) => {
+ return mermaid.mermaidAPI.render('mermaid', mermaidGraph);
+ }""",
+ mermaid_syntax,
+ )
+
+ # Set the page background to white
+ await page.evaluate(
+ """(svg, background_color) => {
+ document.body.innerHTML = svg;
+ document.body.style.background = background_color;
+ }""",
+ svg_code["svg"],
+ background_color,
+ )
+
+ # Take a screenshot
+ dimensions = await page.evaluate(
+ """() => {
+ const svgElement = document.querySelector('svg');
+ const rect = svgElement.getBoundingClientRect();
+ return { width: rect.width, height: rect.height };
+ }"""
+ )
+ await page.setViewport(
+ {
+ "width": int(dimensions["width"] + padding),
+ "height": int(dimensions["height"] + padding),
+ "deviceScaleFactor": device_scale_factor,
+ }
+ )
+
+ img_bytes = cast("bytes", await page.screenshot({"fullPage": False}))
+ await browser.close()
+
+ if output_file_path is not None:
+ await asyncio.get_event_loop().run_in_executor(
+ None, Path(output_file_path).write_bytes, img_bytes
+ )
+
+ return img_bytes
+
+
+def _render_mermaid_using_api(
+ mermaid_syntax: str,
+ *,
+ output_file_path: str | None = None,
+ background_color: str | None = "white",
+ file_type: Literal["jpeg", "png", "webp"] | None = "png",
+ max_retries: int = 1,
+ retry_delay: float = 1.0,
+ proxies: dict[str, str] | None = None,
+ base_url: str | None = None,
+) -> bytes:
+ """Renders Mermaid graph using the Mermaid.INK API."""
+ # Automated scanners: please do not open security advisories about `base_url`
+ # here. This parameter is only ever explicitly controlled by developers, and it
+ # is not exposed by default over the network by the framework, so this is not
+ # an SSRF sink unless an application explicitly wires untrusted input into it.
+ # It exists to support user-managed Mermaid API deployments.
+ # Defaults to using the public mermaid.ink server.
+ base_url = base_url if base_url is not None else "https://mermaid.ink"
+
+ if not _HAS_REQUESTS:
+ msg = (
+ "Install the `requests` module to use the Mermaid.INK API: "
+ "`pip install requests`."
+ )
+ raise ImportError(msg)
+
+ # Use Mermaid API to render the image
+ mermaid_syntax_encoded = base64.b64encode(mermaid_syntax.encode("utf8")).decode(
+ "ascii"
+ )
+
+ # Check if the background color is a hexadecimal color code using regex
+ if background_color is not None:
+ hex_color_pattern = re.compile(r"^#(?:[0-9a-fA-F]{3}){1,2}$")
+ if not hex_color_pattern.match(background_color):
+ background_color = f"!{background_color}"
+
+ # URL-encode the background_color to handle special characters like '!'
+ encoded_bg_color = urllib.parse.quote(str(background_color), safe="")
+ image_url = (
+ f"{base_url}/img/{mermaid_syntax_encoded}"
+ f"?type={file_type}&bgColor={encoded_bg_color}"
+ )
+
+ error_msg_suffix = (
+ "To resolve this issue:\n"
+ "1. Check your internet connection and try again\n"
+ "2. Try with higher retry settings: "
+ "`draw_mermaid_png(..., max_retries=5, retry_delay=2.0)`\n"
+ "3. Use the Pyppeteer rendering method which will render your graph locally "
+ "in a browser: `draw_mermaid_png(..., draw_method=MermaidDrawMethod.PYPPETEER)`"
+ )
+
+ for attempt in range(max_retries + 1):
+ try:
+ response = requests.get(image_url, timeout=10, proxies=proxies)
+ if response.status_code == requests.codes.ok:
+ img_bytes = response.content
+ if output_file_path is not None:
+ Path(output_file_path).write_bytes(response.content)
+
+ return img_bytes
+
+ # If we get a server error (5xx), retry
+ if (
+ requests.codes.internal_server_error <= response.status_code
+ and attempt < max_retries
+ ):
+ # Exponential backoff with jitter
+ sleep_time = retry_delay * (2**attempt) * (0.5 + 0.5 * random.random()) # noqa: S311 not used for crypto
+ time.sleep(sleep_time)
+ continue
+
+ # For other status codes, fail immediately
+ msg = (
+ f"Failed to reach {base_url} API while trying to render "
+ f"your graph. Status code: {response.status_code}.\n\n"
+ ) + error_msg_suffix
+ raise ValueError(msg)
+
+ except (requests.RequestException, requests.Timeout) as e:
+ if attempt < max_retries:
+ # Exponential backoff with jitter
+ sleep_time = retry_delay * (2**attempt) * (0.5 + 0.5 * random.random()) # noqa: S311 not used for crypto
+ time.sleep(sleep_time)
+ else:
+ msg = (
+ f"Failed to reach {base_url} API while trying to render "
+ f"your graph after {max_retries} retries. "
+ ) + error_msg_suffix
+ raise ValueError(msg) from e
+
+ # This should not be reached, but just in case
+ msg = (
+ f"Failed to reach {base_url} API while trying to render "
+ f"your graph after {max_retries} retries. "
+ ) + error_msg_suffix
+ raise ValueError(msg)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/graph_png.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/graph_png.py
new file mode 100644
index 0000000000000000000000000000000000000000..97b6b1f21f2b5f4ab33d216e2084556aadec7b82
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/graph_png.py
@@ -0,0 +1,215 @@
+"""Helper class to draw a state graph into a PNG file."""
+
+from itertools import groupby
+from typing import Any, cast
+
+from langchain_core.runnables.graph import Graph, LabelsDict
+
+try:
+ import pygraphviz as pgv # type: ignore[import-not-found]
+
+ _HAS_PYGRAPHVIZ = True
+except ImportError:
+ _HAS_PYGRAPHVIZ = False
+
+
+class PngDrawer:
+ """Helper class to draw a state graph into a PNG file.
+
+ It requires `graphviz` and `pygraphviz` to be installed.
+
+ Example:
+ ```python
+ drawer = PngDrawer()
+ drawer.draw(state_graph, "graph.png")
+ ```
+ """
+
+ def __init__(
+ self, fontname: str | None = None, labels: LabelsDict | None = None
+ ) -> None:
+ """Initializes the PNG drawer.
+
+ Args:
+ fontname: The font to use for the labels. Defaults to "arial".
+ labels: A dictionary of label overrides. The dictionary
+ should have the following format:
+ {
+ "nodes": {
+ "node1": "CustomLabel1",
+ "node2": "CustomLabel2",
+ "__end__": "End Node"
+ },
+ "edges": {
+ "continue": "ContinueLabel",
+ "end": "EndLabel"
+ }
+ }
+ The keys are the original labels, and the values are the new labels.
+
+ """
+ self.fontname = fontname or "arial"
+ self.labels = labels or LabelsDict(nodes={}, edges={})
+
+ def get_node_label(self, label: str) -> str:
+ """Returns the label to use for a node.
+
+ Args:
+ label: The original label.
+
+ Returns:
+ The new label.
+ """
+ label = self.labels.get("nodes", {}).get(label, label)
+ return f"<{label}>"
+
+ def get_edge_label(self, label: str) -> str:
+ """Returns the label to use for an edge.
+
+ Args:
+ label: The original label.
+
+ Returns:
+ The new label.
+ """
+ label = self.labels.get("edges", {}).get(label, label)
+ return f"<{label}>"
+
+ def add_node(self, viz: Any, node: str) -> None:
+ """Adds a node to the graph.
+
+ Args:
+ viz: The graphviz object.
+ node: The node to add.
+ """
+ viz.add_node(
+ node,
+ label=self.get_node_label(node),
+ style="filled",
+ fillcolor="yellow",
+ fontsize=15,
+ fontname=self.fontname,
+ )
+
+ def add_edge(
+ self,
+ viz: Any,
+ source: str,
+ target: str,
+ label: str | None = None,
+ conditional: bool = False, # noqa: FBT001,FBT002
+ ) -> None:
+ """Adds an edge to the graph.
+
+ Args:
+ viz: The graphviz object.
+ source: The source node.
+ target: The target node.
+ label: The label for the edge.
+ conditional: Whether the edge is conditional.
+ """
+ viz.add_edge(
+ source,
+ target,
+ label=self.get_edge_label(label) if label else "",
+ fontsize=12,
+ fontname=self.fontname,
+ style="dotted" if conditional else "solid",
+ )
+
+ def draw(self, graph: Graph, output_path: str | None = None) -> bytes | None:
+ """Draw the given state graph into a PNG file.
+
+ Requires `graphviz` and `pygraphviz` to be installed.
+
+ Args:
+ graph: The graph to draw
+ output_path: The path to save the PNG. If `None`, PNG bytes are returned.
+
+ Raises:
+ ImportError: If `pygraphviz` is not installed.
+
+ Returns:
+ The PNG bytes if `output_path` is None, else None.
+ """
+ if not _HAS_PYGRAPHVIZ:
+ msg = "Install pygraphviz to draw graphs: `pip install pygraphviz`."
+ raise ImportError(msg)
+
+ # Create a directed graph
+ viz = pgv.AGraph(directed=True, nodesep=0.9, ranksep=1.0)
+
+ # Add nodes, conditional edges, and edges to the graph
+ self.add_nodes(viz, graph)
+ self.add_edges(viz, graph)
+ self.add_subgraph(viz, [node.split(":") for node in graph.nodes])
+
+ # Update entrypoint and END styles
+ self.update_styles(viz, graph)
+
+ # Save the graph as PNG
+ try:
+ return cast("bytes | None", viz.draw(output_path, format="png", prog="dot"))
+ finally:
+ viz.close()
+
+ def add_nodes(self, viz: Any, graph: Graph) -> None:
+ """Add nodes to the graph.
+
+ Args:
+ viz: The graphviz object.
+ graph: The graph to draw.
+ """
+ for node in graph.nodes:
+ self.add_node(viz, node)
+
+ def add_subgraph(
+ self,
+ viz: Any,
+ nodes: list[list[str]],
+ parent_prefix: list[str] | None = None,
+ ) -> None:
+ """Add subgraphs to the graph.
+
+ Args:
+ viz: The graphviz object.
+ nodes: The nodes to add.
+ parent_prefix: The prefix of the parent subgraph.
+ """
+ for prefix, grouped in groupby(
+ [node[:] for node in sorted(nodes)],
+ key=lambda x: x.pop(0),
+ ):
+ current_prefix = (parent_prefix or []) + [prefix]
+ grouped_nodes = list(grouped)
+ if len(grouped_nodes) > 1:
+ subgraph = viz.add_subgraph(
+ [":".join(current_prefix + node) for node in grouped_nodes],
+ name="cluster_" + ":".join(current_prefix),
+ )
+ self.add_subgraph(subgraph, grouped_nodes, current_prefix)
+
+ def add_edges(self, viz: Any, graph: Graph) -> None:
+ """Add edges to the graph.
+
+ Args:
+ viz: The graphviz object.
+ graph: The graph to draw.
+ """
+ for start, end, data, cond in graph.edges:
+ self.add_edge(
+ viz, start, end, str(data) if data is not None else None, cond
+ )
+
+ @staticmethod
+ def update_styles(viz: Any, graph: Graph) -> None:
+ """Update the styles of the entrypoint and END nodes.
+
+ Args:
+ viz: The graphviz object.
+ graph: The graph to draw.
+ """
+ if first := graph.first_node():
+ viz.get_node(first.id).attr.update(fillcolor="lightblue")
+ if last := graph.last_node():
+ viz.get_node(last.id).attr.update(fillcolor="orange")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/history.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/history.py
new file mode 100644
index 0000000000000000000000000000000000000000..c85386735cd202b02ac0b503a414a2ecbb72960b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/history.py
@@ -0,0 +1,631 @@
+"""`Runnable` that manages chat message history for another `Runnable`."""
+
+from __future__ import annotations
+
+import inspect
+from collections.abc import Callable, Sequence
+from types import GenericAlias
+from typing import (
+ TYPE_CHECKING,
+ Any,
+)
+
+from pydantic import BaseModel
+from typing_extensions import override
+
+from langchain_core._api.deprecation import warn_deprecated
+from langchain_core.chat_history import BaseChatMessageHistory
+from langchain_core.load.load import load
+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
+from langchain_core.runnables.base import Runnable, RunnableBindingBase, RunnableLambda
+from langchain_core.runnables.passthrough import RunnablePassthrough
+from langchain_core.runnables.utils import (
+ ConfigurableFieldSpec,
+ Output,
+ get_unique_config_specs,
+)
+from langchain_core.utils.pydantic import create_model_v2
+
+if TYPE_CHECKING:
+ from langchain_core.language_models.base import LanguageModelLike
+ from langchain_core.runnables.config import RunnableConfig
+ from langchain_core.tracers.schemas import Run
+
+
+MessagesOrDictWithMessages = Sequence["BaseMessage"] | dict[str, Any]
+GetSessionHistoryCallable = Callable[..., BaseChatMessageHistory]
+
+
+class RunnableWithMessageHistory(RunnableBindingBase): # type: ignore[no-redef]
+ """`Runnable` that manages chat message history for another `Runnable`.
+
+ A chat message history is a sequence of messages that represent a conversation.
+
+ `RunnableWithMessageHistory` wraps another `Runnable` and manages the chat message
+ history for it; it is responsible for reading and updating the chat message
+ history.
+
+ The formats supported for the inputs and outputs of the wrapped `Runnable`
+ are described below.
+
+ `RunnableWithMessageHistory` must always be called with a config that contains
+ the appropriate parameters for the chat message history factory.
+
+ By default, the `Runnable` is expected to take a single configuration parameter
+ called `session_id` which is a string. This parameter is used to create a new
+ or look up an existing chat message history that matches the given `session_id`.
+
+ In this case, the invocation would look like this:
+
+ `with_history.invoke(..., config={"configurable": {"session_id": "bar"}})`
+ ; e.g., `{"configurable": {"session_id": ""}}`.
+
+ The configuration can be customized by passing in a list of
+ `ConfigurableFieldSpec` objects to the `history_factory_config` parameter (see
+ example below).
+
+ In the examples, we will use a chat message history with an in-memory
+ implementation to make it easy to experiment and see the results.
+
+ For production use cases, you will want to use a persistent implementation
+ of chat message history, such as `RedisChatMessageHistory`.
+
+ Example: Chat message history with an in-memory implementation for testing.
+
+ ```python
+ from operator import itemgetter
+
+ from langchain_openai.chat_models import ChatOpenAI
+
+ from langchain_core.chat_history import BaseChatMessageHistory
+ from langchain_core.documents import Document
+ from langchain_core.messages import BaseMessage, AIMessage
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
+ from pydantic import BaseModel, Field
+ from langchain_core.runnables import (
+ RunnableLambda,
+ ConfigurableFieldSpec,
+ RunnablePassthrough,
+ )
+ from langchain_core.runnables.history import RunnableWithMessageHistory
+
+
+ class InMemoryHistory(BaseChatMessageHistory, BaseModel):
+ \"\"\"In memory implementation of chat message history.\"\"\"
+
+ messages: list[BaseMessage] = Field(default_factory=list)
+
+ def add_messages(self, messages: list[BaseMessage]) -> None:
+ \"\"\"Add a list of messages to the store\"\"\"
+ self.messages.extend(messages)
+
+ def clear(self) -> None:
+ self.messages = []
+
+ # Here we use a global variable to store the chat message history.
+ # This will make it easier to inspect it to see the underlying results.
+ store = {}
+
+ def get_by_session_id(session_id: str) -> BaseChatMessageHistory:
+ if session_id not in store:
+ store[session_id] = InMemoryHistory()
+ return store[session_id]
+
+
+ history = get_by_session_id("1")
+ history.add_message(AIMessage(content="hello"))
+ print(store) # noqa: T201
+
+ ```
+
+ Example where the wrapped `Runnable` takes a dictionary input:
+
+ ```python
+ from typing import Optional
+
+ from langchain_anthropic import ChatAnthropic
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
+ from langchain_core.runnables.history import RunnableWithMessageHistory
+
+
+ prompt = ChatPromptTemplate.from_messages(
+ [
+ ("system", "You're an assistant who's good at {ability}"),
+ MessagesPlaceholder(variable_name="history"),
+ ("human", "{question}"),
+ ]
+ )
+
+ chain = prompt | ChatAnthropic(model="claude-2")
+
+ chain_with_history = RunnableWithMessageHistory(
+ chain,
+ # Uses the get_by_session_id function defined in the example
+ # above.
+ get_by_session_id,
+ input_messages_key="question",
+ history_messages_key="history",
+ )
+
+ print(
+ chain_with_history.invoke( # noqa: T201
+ {"ability": "math", "question": "What does cosine mean?"},
+ config={"configurable": {"session_id": "foo"}},
+ )
+ )
+
+ # Uses the store defined in the example above.
+ print(store) # noqa: T201
+
+ print(
+ chain_with_history.invoke( # noqa: T201
+ {"ability": "math", "question": "What's its inverse"},
+ config={"configurable": {"session_id": "foo"}},
+ )
+ )
+
+ print(store) # noqa: T201
+ ```
+
+ Example where the session factory takes two keys (`user_id` and `conversation_id`):
+
+ ```python
+ store = {}
+
+
+ def get_session_history(
+ user_id: str, conversation_id: str
+ ) -> BaseChatMessageHistory:
+ if (user_id, conversation_id) not in store:
+ store[(user_id, conversation_id)] = InMemoryHistory()
+ return store[(user_id, conversation_id)]
+
+
+ prompt = ChatPromptTemplate.from_messages(
+ [
+ ("system", "You're an assistant who's good at {ability}"),
+ MessagesPlaceholder(variable_name="history"),
+ ("human", "{question}"),
+ ]
+ )
+
+ chain = prompt | ChatAnthropic(model="claude-2")
+
+ with_message_history = RunnableWithMessageHistory(
+ chain,
+ get_session_history=get_session_history,
+ input_messages_key="question",
+ history_messages_key="history",
+ history_factory_config=[
+ ConfigurableFieldSpec(
+ id="user_id",
+ annotation=str,
+ name="User ID",
+ description="Unique identifier for the user.",
+ default="",
+ is_shared=True,
+ ),
+ ConfigurableFieldSpec(
+ id="conversation_id",
+ annotation=str,
+ name="Conversation ID",
+ description="Unique identifier for the conversation.",
+ default="",
+ is_shared=True,
+ ),
+ ],
+ )
+
+ with_message_history.invoke(
+ {"ability": "math", "question": "What does cosine mean?"},
+ config={"configurable": {"user_id": "123", "conversation_id": "1"}},
+ )
+ ```
+ """
+
+ get_session_history: GetSessionHistoryCallable
+ """Function that returns a new `BaseChatMessageHistory`.
+
+ This function should either take a single positional argument `session_id` of type
+ string and return a corresponding chat message history instance
+ """
+ input_messages_key: str | None = None
+ """Must be specified if the base `Runnable` accepts a `dict` as input.
+ The key in the input `dict` that contains the messages.
+ """
+ output_messages_key: str | None = None
+ """Must be specified if the base `Runnable` returns a `dict` as output.
+ The key in the output `dict` that contains the messages.
+ """
+ history_messages_key: str | None = None
+ """Must be specified if the base `Runnable` accepts a `dict` as input and expects a
+ separate key for historical messages.
+ """
+ history_factory_config: Sequence[ConfigurableFieldSpec]
+ """Configure fields that should be passed to the chat history factory.
+
+ See `ConfigurableFieldSpec` for more details.
+ """
+
+ def __init__(
+ self,
+ runnable: Runnable[
+ list[BaseMessage], str | BaseMessage | MessagesOrDictWithMessages
+ ]
+ | Runnable[dict[str, Any], str | BaseMessage | MessagesOrDictWithMessages]
+ | LanguageModelLike,
+ get_session_history: GetSessionHistoryCallable,
+ *,
+ input_messages_key: str | None = None,
+ output_messages_key: str | None = None,
+ history_messages_key: str | None = None,
+ history_factory_config: Sequence[ConfigurableFieldSpec] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize `RunnableWithMessageHistory`.
+
+ Args:
+ runnable: The base `Runnable` to be wrapped.
+
+ Must take as input one of:
+
+ 1. A list of `BaseMessage`
+ 2. A `dict` with one key for all messages
+ 3. A `dict` with one key for the current input string/message(s) and
+ a separate key for historical messages. If the input key points
+ to a string, it will be treated as a `HumanMessage` in history.
+
+ Must return as output one of:
+
+ 1. A string which can be treated as an `AIMessage`
+ 2. A `BaseMessage` or sequence of `BaseMessage`
+ 3. A `dict` with a key for a `BaseMessage` or sequence of
+ `BaseMessage`
+
+ get_session_history: Function that returns a new `BaseChatMessageHistory`.
+
+ This function should either take a single positional argument
+ `session_id` of type string and return a corresponding
+ chat message history instance.
+
+ ```python
+ def get_session_history(
+ session_id: str, *, user_id: str | None = None
+ ) -> BaseChatMessageHistory: ...
+ ```
+
+ Or it should take keyword arguments that match the keys of
+ `session_history_config_specs` and return a corresponding
+ chat message history instance.
+
+ ```python
+ def get_session_history(
+ *,
+ user_id: str,
+ thread_id: str,
+ ) -> BaseChatMessageHistory: ...
+ ```
+
+ input_messages_key: Must be specified if the base runnable accepts a `dict`
+ as input.
+ output_messages_key: Must be specified if the base runnable returns a `dict`
+ as output.
+ history_messages_key: Must be specified if the base runnable accepts a
+ `dict` as input and expects a separate key for historical messages.
+ history_factory_config: Configure fields that should be passed to the
+ chat history factory. See `ConfigurableFieldSpec` for more details.
+
+ Specifying these allows you to pass multiple config keys into the
+ `get_session_history` factory.
+ **kwargs: Arbitrary additional kwargs to pass to parent class
+ `RunnableBindingBase` init.
+
+ """
+ warn_deprecated(
+ since="1.3.3",
+ message=(
+ "RunnableWithMessageHistory is deprecated. "
+ "Use LangGraph's built-in persistence instead."
+ ),
+ removal="2.0.0",
+ )
+ history_chain: Runnable[Any, Any] = RunnableLambda(
+ self._enter_history, self._aenter_history
+ ).with_config(run_name="load_history")
+ messages_key = history_messages_key or input_messages_key
+ if messages_key:
+ history_chain = RunnablePassthrough.assign(
+ **{messages_key: history_chain}
+ ).with_config(run_name="insert_history")
+
+ runnable_sync = runnable.with_listeners(on_end=self._exit_history)
+ runnable_async = runnable.with_alisteners(on_end=self._aexit_history)
+
+ def _call_runnable_sync(_input: Any) -> Runnable[Any, Any]:
+ return runnable_sync
+
+ async def _call_runnable_async(_input: Any) -> Runnable[Any, Any]:
+ return runnable_async
+
+ bound = (
+ history_chain
+ | RunnableLambda(
+ _call_runnable_sync,
+ _call_runnable_async,
+ ).with_config(run_name="check_sync_or_async")
+ ).with_config(run_name="RunnableWithMessageHistory")
+
+ if history_factory_config:
+ config_specs = history_factory_config
+ else:
+ # If not provided, then we'll use the default session_id field
+ config_specs = [
+ ConfigurableFieldSpec(
+ id="session_id",
+ annotation=str,
+ name="Session ID",
+ description="Unique identifier for a session.",
+ default="",
+ is_shared=True,
+ ),
+ ]
+
+ super().__init__(
+ get_session_history=get_session_history,
+ input_messages_key=input_messages_key,
+ output_messages_key=output_messages_key,
+ bound=bound,
+ history_messages_key=history_messages_key,
+ history_factory_config=config_specs,
+ **kwargs,
+ )
+ self._history_chain = history_chain
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ """Get the configuration specs for the `RunnableWithMessageHistory`."""
+ return get_unique_config_specs(
+ super().config_specs + list(self.history_factory_config)
+ )
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ fields: dict = {}
+ if self.input_messages_key and self.history_messages_key:
+ fields[self.input_messages_key] = (
+ str | BaseMessage | Sequence[BaseMessage],
+ ...,
+ )
+ elif self.input_messages_key:
+ fields[self.input_messages_key] = (Sequence[BaseMessage], ...)
+ else:
+ return create_model_v2(
+ "RunnableWithChatHistoryInput",
+ module_name=self.__class__.__module__,
+ root=(Sequence[BaseMessage], ...),
+ )
+ return create_model_v2(
+ "RunnableWithChatHistoryInput",
+ field_definitions=fields,
+ module_name=self.__class__.__module__,
+ )
+
+ @property
+ @override
+ def OutputType(self) -> type[Output]:
+ return self._history_chain.OutputType
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ """Get a Pydantic model that can be used to validate output to the `Runnable`.
+
+ `Runnable` objects that leverage the `configurable_fields` and
+ `configurable_alternatives` methods will have a dynamic output schema that
+ depends on which configuration the `Runnable` is invoked with.
+
+ This method allows to get an output schema for a specific configuration.
+
+ Args:
+ config: A config to use when generating the schema.
+
+ Returns:
+ A Pydantic model that can be used to validate output.
+ """
+ root_type = self.OutputType
+
+ if (
+ inspect.isclass(root_type)
+ and not isinstance(root_type, GenericAlias)
+ and issubclass(root_type, BaseModel)
+ ):
+ return root_type
+
+ return create_model_v2(
+ "RunnableWithChatHistoryOutput",
+ root=root_type,
+ module_name=self.__class__.__module__,
+ )
+
+ def _get_input_messages(
+ self, input_val: str | BaseMessage | Sequence[BaseMessage] | dict
+ ) -> list[BaseMessage]:
+ # If dictionary, try to pluck the single key representing messages
+ if isinstance(input_val, dict):
+ if self.input_messages_key:
+ key = self.input_messages_key
+ elif len(input_val) == 1:
+ key = next(iter(input_val.keys()))
+ else:
+ key = "input"
+ input_val = input_val[key]
+
+ # If value is a string, convert to a human message
+ if isinstance(input_val, str):
+ return [HumanMessage(content=input_val)]
+ # If value is a single message, convert to a list
+ if isinstance(input_val, BaseMessage):
+ return [input_val]
+ # If value is a list or tuple...
+ if isinstance(input_val, (list, tuple)):
+ # Handle empty case
+ if len(input_val) == 0:
+ return list(input_val)
+ # If is a list of list, then return the first value
+ # This occurs for chat models - since we batch inputs
+ if isinstance(input_val[0], list):
+ if len(input_val) != 1:
+ msg = f"Expected a single list of messages. Got {input_val}."
+ raise ValueError(msg)
+ return input_val[0]
+ return list(input_val)
+ msg = (
+ f"Expected str, BaseMessage, list[BaseMessage], or tuple[BaseMessage]. "
+ f"Got {input_val}."
+ )
+ raise ValueError(msg)
+
+ def _get_output_messages(
+ self, output_val: str | BaseMessage | Sequence[BaseMessage] | dict
+ ) -> list[BaseMessage]:
+ # If dictionary, try to pluck the single key representing messages
+ if isinstance(output_val, dict):
+ if self.output_messages_key:
+ key = self.output_messages_key
+ elif len(output_val) == 1:
+ key = next(iter(output_val.keys()))
+ else:
+ key = "output"
+ # If you are wrapping a chat model directly
+ # The output is actually this weird generations object
+ if key not in output_val and "generations" in output_val:
+ output_val = output_val["generations"][0][0]["message"]
+ else:
+ output_val = output_val[key]
+
+ if isinstance(output_val, str):
+ return [AIMessage(content=output_val)]
+ # If value is a single message, convert to a list
+ if isinstance(output_val, BaseMessage):
+ return [output_val]
+ if isinstance(output_val, (list, tuple)):
+ return list(output_val)
+ msg = (
+ f"Expected str, BaseMessage, list[BaseMessage], or tuple[BaseMessage]. "
+ f"Got {output_val}."
+ )
+ raise ValueError(msg)
+
+ def _enter_history(self, value: Any, config: RunnableConfig) -> list[BaseMessage]:
+ hist: BaseChatMessageHistory = config["configurable"]["message_history"]
+ messages = hist.messages.copy()
+
+ if not self.history_messages_key:
+ # return all messages
+ input_val = (
+ value if not self.input_messages_key else value[self.input_messages_key]
+ )
+ messages += self._get_input_messages(input_val)
+ return messages
+
+ async def _aenter_history(
+ self, value: dict[str, Any], config: RunnableConfig
+ ) -> list[BaseMessage]:
+ hist: BaseChatMessageHistory = config["configurable"]["message_history"]
+ messages = (await hist.aget_messages()).copy()
+
+ if not self.history_messages_key:
+ # return all messages
+ input_val = (
+ value if not self.input_messages_key else value[self.input_messages_key]
+ )
+ messages += self._get_input_messages(input_val)
+ return messages
+
+ def _exit_history(self, run: Run, config: RunnableConfig) -> None:
+ hist: BaseChatMessageHistory = config["configurable"]["message_history"]
+
+ # Get the input messages
+ inputs = load(run.inputs, allowed_objects="messages")
+ input_messages = self._get_input_messages(inputs)
+ # If historic messages were prepended to the input messages, remove them to
+ # avoid adding duplicate messages to history.
+ if not self.history_messages_key:
+ historic_messages = config["configurable"]["message_history"].messages
+ input_messages = input_messages[len(historic_messages) :]
+
+ # Get the output messages
+ output_val = load(run.outputs, allowed_objects="messages")
+ output_messages = self._get_output_messages(output_val)
+ hist.add_messages(input_messages + output_messages)
+
+ async def _aexit_history(self, run: Run, config: RunnableConfig) -> None:
+ hist: BaseChatMessageHistory = config["configurable"]["message_history"]
+
+ # Get the input messages
+ inputs = load(run.inputs, allowed_objects="messages")
+ input_messages = self._get_input_messages(inputs)
+ # If historic messages were prepended to the input messages, remove them to
+ # avoid adding duplicate messages to history.
+ if not self.history_messages_key:
+ historic_messages = await hist.aget_messages()
+ input_messages = input_messages[len(historic_messages) :]
+
+ # Get the output messages
+ output_val = load(run.outputs, allowed_objects="messages")
+ output_messages = self._get_output_messages(output_val)
+ await hist.aadd_messages(input_messages + output_messages)
+
+ def _merge_configs(self, *configs: RunnableConfig | None) -> RunnableConfig:
+ config = super()._merge_configs(*configs)
+ expected_keys = [field_spec.id for field_spec in self.history_factory_config]
+
+ configurable = config.get("configurable", {})
+
+ missing_keys = set(expected_keys) - set(configurable.keys())
+ parameter_names = _get_parameter_names(self.get_session_history)
+
+ if missing_keys and parameter_names:
+ example_input = {self.input_messages_key: "foo"}
+ example_configurable = dict.fromkeys(missing_keys, "[your-value-here]")
+ example_config = {"configurable": example_configurable}
+ msg = (
+ f"Missing keys {sorted(missing_keys)} in config['configurable'] "
+ f"Expected keys are {sorted(expected_keys)}."
+ f"When using via .invoke() or .stream(), pass in a config; "
+ f"e.g., chain.invoke({example_input}, {example_config})"
+ )
+ raise ValueError(msg)
+
+ if len(expected_keys) == 1:
+ if parameter_names:
+ # If arity = 1, then invoke function by positional arguments
+ message_history = self.get_session_history(
+ configurable[expected_keys[0]]
+ )
+ else:
+ if not config:
+ config["configurable"] = {}
+ message_history = self.get_session_history()
+ else:
+ # otherwise verify that names of keys patch and invoke by named arguments
+ if set(expected_keys) != set(parameter_names):
+ msg = (
+ f"Expected keys {sorted(expected_keys)} do not match parameter "
+ f"names {sorted(parameter_names)} of get_session_history."
+ )
+ raise ValueError(msg)
+
+ message_history = self.get_session_history(
+ **{key: configurable[key] for key in expected_keys}
+ )
+ config["configurable"]["message_history"] = message_history
+ return config
+
+
+def _get_parameter_names(callable_: GetSessionHistoryCallable) -> list[str]:
+ """Get the parameter names of the `Callable`."""
+ sig = inspect.signature(callable_)
+ return list(sig.parameters.keys())
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/passthrough.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/passthrough.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5e01cfe20fd8a273a1e64cf42ba22f98f5f8f27
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/passthrough.py
@@ -0,0 +1,841 @@
+"""Implementation of the `RunnablePassthrough`."""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import threading
+from collections.abc import Awaitable, Callable
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ cast,
+)
+
+from pydantic import BaseModel, RootModel
+from typing_extensions import override
+
+from langchain_core.runnables.base import (
+ Other,
+ Runnable,
+ RunnableParallel,
+ RunnableSerializable,
+)
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ acall_func_with_variable_args,
+ call_func_with_variable_args,
+ ensure_config,
+ get_executor_for_config,
+ patch_config,
+)
+from langchain_core.runnables.utils import (
+ AddableDict,
+ ConfigurableFieldSpec,
+)
+from langchain_core.utils.aiter import atee
+from langchain_core.utils.iter import safetee
+from langchain_core.utils.pydantic import create_model_v2
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator, Mapping
+
+ from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForChainRun,
+ CallbackManagerForChainRun,
+ )
+ from langchain_core.runnables.graph import Graph
+
+
+def identity(x: Other) -> Other:
+ """Identity function.
+
+ Args:
+ x: Input.
+
+ Returns:
+ Output.
+ """
+ return x
+
+
+async def aidentity(x: Other) -> Other:
+ """Async identity function.
+
+ Args:
+ x: Input.
+
+ Returns:
+ Output.
+ """
+ return x
+
+
+class RunnablePassthrough(RunnableSerializable[Other, Other]):
+ """Runnable to passthrough inputs unchanged or with additional keys.
+
+ This `Runnable` behaves almost like the identity function, except that it
+ can be configured to add additional keys to the output, if the input is a
+ dict.
+
+ The examples below demonstrate this `Runnable` works using a few simple
+ chains. The chains rely on simple lambdas to make the examples easy to execute
+ and experiment with.
+
+ Examples:
+ ```python
+ from langchain_core.runnables import (
+ RunnableLambda,
+ RunnableParallel,
+ RunnablePassthrough,
+ )
+
+ runnable = RunnableParallel(
+ origin=RunnablePassthrough(), modified=lambda x: x + 1
+ )
+
+ runnable.invoke(1) # {'origin': 1, 'modified': 2}
+
+
+ def fake_llm(prompt: str) -> str: # Fake LLM for the example
+ return "completion"
+
+
+ chain = RunnableLambda(fake_llm) | {
+ "original": RunnablePassthrough(), # Original LLM output
+ "parsed": lambda text: text[::-1], # Parsing logic
+ }
+
+ chain.invoke("hello") # {'original': 'completion', 'parsed': 'noitelpmoc'}
+ ```
+
+ In some cases, it may be useful to pass the input through while adding some
+ keys to the output. In this case, you can use the `assign` method:
+
+ ```python
+ from langchain_core.runnables import RunnablePassthrough
+
+
+ def fake_llm(prompt: str) -> str: # Fake LLM for the example
+ return "completion"
+
+
+ runnable = {
+ "llm1": fake_llm,
+ "llm2": fake_llm,
+ } | RunnablePassthrough.assign(
+ total_chars=lambda inputs: len(inputs["llm1"] + inputs["llm2"])
+ )
+
+ runnable.invoke("hello")
+ # {'llm1': 'completion', 'llm2': 'completion', 'total_chars': 20}
+ ```
+ """
+
+ input_type: type[Other] | None = None
+
+ func: Callable[[Other], None] | Callable[[Other, RunnableConfig], None] | None = (
+ None
+ )
+
+ afunc: (
+ Callable[[Other], Awaitable[None]]
+ | Callable[[Other, RunnableConfig], Awaitable[None]]
+ | None
+ ) = None
+
+ @override
+ def __repr_args__(self) -> Any:
+ # Without this repr(self) raises a RecursionError
+ # See https://github.com/pydantic/pydantic/issues/7327
+ return []
+
+ def __init__(
+ self,
+ func: Callable[[Other], None]
+ | Callable[[Other, RunnableConfig], None]
+ | Callable[[Other], Awaitable[None]]
+ | Callable[[Other, RunnableConfig], Awaitable[None]]
+ | None = None,
+ afunc: Callable[[Other], Awaitable[None]]
+ | Callable[[Other, RunnableConfig], Awaitable[None]]
+ | None = None,
+ *,
+ input_type: type[Other] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Create a `RunnablePassthrough`.
+
+ Args:
+ func: Function to be called with the input.
+ afunc: Async function to be called with the input.
+ input_type: Type of the input.
+ """
+ if inspect.iscoroutinefunction(func):
+ afunc = func
+ func = None
+
+ super().__init__(func=func, afunc=afunc, input_type=input_type, **kwargs)
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @property
+ @override
+ def InputType(self) -> Any:
+ return self.input_type or Any
+
+ @property
+ @override
+ def OutputType(self) -> Any:
+ return self.input_type or Any
+
+ @classmethod
+ @override
+ def assign(
+ cls,
+ **kwargs: Runnable[dict[str, Any], Any]
+ | Callable[[dict[str, Any]], Any]
+ | Mapping[str, Runnable[dict[str, Any], Any] | Callable[[dict[str, Any]], Any]],
+ ) -> RunnableAssign:
+ """Merge the Dict input with the output produced by the mapping argument.
+
+ Args:
+ **kwargs: `Runnable`, `Callable` or a `Mapping` from keys to `Runnable`
+ objects or `Callable`s.
+
+ Returns:
+ A `Runnable` that merges the `dict` input with the output produced by the
+ mapping argument.
+ """
+ return RunnableAssign(RunnableParallel[dict[str, Any]](kwargs))
+
+ @override
+ def invoke(
+ self, input: Other, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Other:
+ if self.func is not None:
+ call_func_with_variable_args(
+ self.func, input, ensure_config(config), **kwargs
+ )
+ return self._call_with_config(identity, input, config)
+
+ @override
+ async def ainvoke(
+ self,
+ input: Other,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Other:
+ if self.afunc is not None:
+ await acall_func_with_variable_args(
+ self.afunc, input, ensure_config(config), **kwargs
+ )
+ elif self.func is not None:
+ call_func_with_variable_args(
+ self.func, input, ensure_config(config), **kwargs
+ )
+ return await self._acall_with_config(aidentity, input, config)
+
+ @override
+ def transform(
+ self,
+ input: Iterator[Other],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Other]:
+ if self.func is None:
+ for chunk in self._transform_stream_with_config(input, identity, config):
+ yield chunk
+ else:
+ final: Other
+ got_first_chunk = False
+
+ for chunk in self._transform_stream_with_config(input, identity, config):
+ yield chunk
+
+ if not got_first_chunk:
+ final = chunk
+ got_first_chunk = True
+ else:
+ try:
+ final = final + chunk # type: ignore[operator]
+ except TypeError:
+ final = chunk
+
+ if got_first_chunk:
+ call_func_with_variable_args(
+ self.func, final, ensure_config(config), **kwargs
+ )
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[Other],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Other]:
+ if self.afunc is None and self.func is None:
+ async for chunk in self._atransform_stream_with_config(
+ input, identity, config
+ ):
+ yield chunk
+ else:
+ got_first_chunk = False
+
+ async for chunk in self._atransform_stream_with_config(
+ input, identity, config
+ ):
+ yield chunk
+
+ # By definitions, a function will operate on the aggregated
+ # input. So we'll aggregate the input until we get to the last
+ # chunk.
+ # If the input is not addable, then we'll assume that we can
+ # only operate on the last chunk.
+ if not got_first_chunk:
+ final = chunk
+ got_first_chunk = True
+ else:
+ try:
+ final = final + chunk # type: ignore[operator]
+ except TypeError:
+ final = chunk
+
+ if got_first_chunk:
+ config = ensure_config(config)
+ if self.afunc is not None:
+ await acall_func_with_variable_args(
+ self.afunc, final, config, **kwargs
+ )
+ elif self.func is not None:
+ call_func_with_variable_args(self.func, final, config, **kwargs)
+
+ @override
+ def stream(
+ self,
+ input: Other,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Other]:
+ return self.transform(iter([input]), config, **kwargs)
+
+ @override
+ async def astream(
+ self,
+ input: Other,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Other]:
+ async def input_aiter() -> AsyncIterator[Other]:
+ yield input
+
+ async for chunk in self.atransform(input_aiter(), config, **kwargs):
+ yield chunk
+
+
+_graph_passthrough: RunnablePassthrough = RunnablePassthrough()
+
+
+class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
+ """Runnable that assigns key-value pairs to `dict[str, Any]` inputs.
+
+ The `RunnableAssign` class takes input dictionaries and, through a
+ `RunnableParallel` instance, applies transformations, then combines
+ these with the original data, introducing new key-value pairs based
+ on the mapper's logic.
+
+ Examples:
+ ```python
+ # This is a RunnableAssign
+ from langchain_core.runnables.passthrough import (
+ RunnableAssign,
+ RunnableParallel,
+ )
+ from langchain_core.runnables.base import RunnableLambda
+
+
+ def add_ten(x: dict[str, int]) -> dict[str, int]:
+ return {"added": x["input"] + 10}
+
+
+ mapper = RunnableParallel(
+ {
+ "add_step": RunnableLambda(add_ten),
+ }
+ )
+
+ runnable_assign = RunnableAssign(mapper)
+
+ # Synchronous example
+ runnable_assign.invoke({"input": 5})
+ # returns {'input': 5, 'add_step': {'added': 15}}
+
+ # Asynchronous example
+ await runnable_assign.ainvoke({"input": 5})
+ # returns {'input': 5, 'add_step': {'added': 15}}
+ ```
+ """
+
+ mapper: RunnableParallel
+
+ def __init__(self, mapper: RunnableParallel[dict[str, Any]], **kwargs: Any) -> None:
+ """Create a `RunnableAssign`.
+
+ Args:
+ mapper: A `RunnableParallel` instance that will be used to transform the
+ input dictionary.
+ """
+ super().__init__(mapper=mapper, **kwargs)
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @override
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ name = (
+ name
+ or self.name
+ or f"RunnableAssign<{','.join(self.mapper.steps__.keys())}>"
+ )
+ return super().get_name(suffix, name=name)
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ map_input_schema = self.mapper.get_input_schema(config)
+ if not issubclass(map_input_schema, RootModel):
+ # ie. it's a dict
+ return map_input_schema
+
+ return super().get_input_schema(config)
+
+ @override
+ def get_output_schema(
+ self, config: RunnableConfig | None = None
+ ) -> type[BaseModel]:
+ map_input_schema = self.mapper.get_input_schema(config)
+ map_output_schema = self.mapper.get_output_schema(config)
+ if not issubclass(map_input_schema, RootModel) and not issubclass(
+ map_output_schema, RootModel
+ ):
+ fields = {}
+
+ for name, field_info in map_input_schema.model_fields.items():
+ fields[name] = (field_info.annotation, field_info.default)
+
+ for name, field_info in map_output_schema.model_fields.items():
+ fields[name] = (field_info.annotation, field_info.default)
+
+ return create_model_v2("RunnableAssignOutput", field_definitions=fields)
+ if not issubclass(map_output_schema, RootModel):
+ # ie. only map output is a dict
+ # ie. input type is either unknown or inferred incorrectly
+ return map_output_schema
+
+ return super().get_output_schema(config)
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return self.mapper.config_specs
+
+ @override
+ def get_graph(self, config: RunnableConfig | None = None) -> Graph:
+ # get graph from mapper
+ graph = self.mapper.get_graph(config)
+ # add passthrough node and edges
+ input_node = graph.first_node()
+ output_node = graph.last_node()
+ if input_node is not None and output_node is not None:
+ passthrough_node = graph.add_node(_graph_passthrough)
+ graph.add_edge(input_node, passthrough_node)
+ graph.add_edge(passthrough_node, output_node)
+ return graph
+
+ def _invoke(
+ self,
+ value: dict[str, Any],
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ msg = "The input to RunnablePassthrough.assign() must be a dict."
+ raise ValueError(msg) # noqa: TRY004
+
+ return {
+ **value,
+ **self.mapper.invoke(
+ value,
+ patch_config(config, callbacks=run_manager.get_child()),
+ **kwargs,
+ ),
+ }
+
+ @override
+ def invoke(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> dict[str, Any]:
+ return self._call_with_config(self._invoke, input, config, **kwargs)
+
+ async def _ainvoke(
+ self,
+ value: dict[str, Any],
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ msg = "The input to RunnablePassthrough.assign() must be a dict."
+ raise ValueError(msg) # noqa: TRY004
+
+ return {
+ **value,
+ **await self.mapper.ainvoke(
+ value,
+ patch_config(config, callbacks=run_manager.get_child()),
+ **kwargs,
+ ),
+ }
+
+ @override
+ async def ainvoke(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> dict[str, Any]:
+ return await self._acall_with_config(self._ainvoke, input, config, **kwargs)
+
+ def _transform(
+ self,
+ values: Iterator[dict[str, Any]],
+ run_manager: CallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Iterator[dict[str, Any]]:
+ # collect mapper keys
+ mapper_keys = set(self.mapper.steps__.keys())
+ # create two streams, one for the map and one for the passthrough
+ for_passthrough, for_map = safetee(values, 2, lock=threading.Lock())
+
+ # create map output stream
+ map_output = self.mapper.transform(
+ for_map,
+ patch_config(
+ config,
+ callbacks=run_manager.get_child(),
+ ),
+ **kwargs,
+ )
+
+ # get executor to start map output stream in background
+ with get_executor_for_config(config) as executor:
+ # start map output stream
+ first_map_chunk_future = executor.submit(
+ next,
+ map_output,
+ None,
+ )
+ # consume passthrough stream
+ for chunk in for_passthrough:
+ if not isinstance(chunk, dict):
+ msg = "The input to RunnablePassthrough.assign() must be a dict."
+ raise ValueError(msg) # noqa: TRY004
+ # remove mapper keys from passthrough chunk, to be overwritten by map
+ filtered = AddableDict(
+ {k: v for k, v in chunk.items() if k not in mapper_keys}
+ )
+ if filtered:
+ yield filtered
+ # yield map output
+ yield cast("dict[str, Any]", first_map_chunk_future.result())
+ for chunk in map_output:
+ yield chunk
+
+ @override
+ def transform(
+ self,
+ input: Iterator[dict[str, Any]],
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[dict[str, Any]]:
+ yield from self._transform_stream_with_config(
+ input, self._transform, config, **kwargs
+ )
+
+ async def _atransform(
+ self,
+ values: AsyncIterator[dict[str, Any]],
+ run_manager: AsyncCallbackManagerForChainRun,
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any]]:
+ # collect mapper keys
+ mapper_keys = set(self.mapper.steps__.keys())
+ # create two streams, one for the map and one for the passthrough
+ for_passthrough, for_map = atee(values, 2, lock=asyncio.Lock())
+ # create map output stream
+ map_output = self.mapper.atransform(
+ for_map,
+ patch_config(
+ config,
+ callbacks=run_manager.get_child(),
+ ),
+ **kwargs,
+ )
+ # start map output stream
+ first_map_chunk_task: asyncio.Task = asyncio.create_task(
+ anext(map_output, None),
+ )
+ # consume passthrough stream
+ async for chunk in for_passthrough:
+ if not isinstance(chunk, dict):
+ msg = "The input to RunnablePassthrough.assign() must be a dict."
+ raise ValueError(msg) # noqa: TRY004
+
+ # remove mapper keys from passthrough chunk, to be overwritten by map output
+ filtered = AddableDict(
+ {k: v for k, v in chunk.items() if k not in mapper_keys}
+ )
+ if filtered:
+ yield filtered
+ # yield map output
+ yield await first_map_chunk_task
+ async for chunk in map_output:
+ yield chunk
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[dict[str, Any]],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any]]:
+ async for chunk in self._atransform_stream_with_config(
+ input, self._atransform, config, **kwargs
+ ):
+ yield chunk
+
+ @override
+ def stream(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[dict[str, Any]]:
+ return self.transform(iter([input]), config, **kwargs)
+
+ @override
+ async def astream(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[dict[str, Any]]:
+ async def input_aiter() -> AsyncIterator[dict[str, Any]]:
+ yield input
+
+ async for chunk in self.atransform(input_aiter(), config, **kwargs):
+ yield chunk
+
+
+class RunnablePick(RunnableSerializable[dict[str, Any], Any]):
+ """`Runnable` that picks keys from `dict[str, Any]` inputs.
+
+ `RunnablePick` class represents a `Runnable` that selectively picks keys from a
+ dictionary input. It allows you to specify one or more keys to extract
+ from the input dictionary.
+
+ !!! note "Return Type Behavior"
+ The return type depends on the `keys` parameter:
+
+ - When `keys` is a `str`: Returns the single value associated with that key
+ - When `keys` is a `list`: Returns a dictionary containing only the selected
+ keys
+
+ Example:
+ ```python
+ from langchain_core.runnables.passthrough import RunnablePick
+
+ input_data = {
+ "name": "John",
+ "age": 30,
+ "city": "New York",
+ "country": "USA",
+ }
+
+ # Single key - returns the value directly
+ runnable_single = RunnablePick(keys="name")
+ result_single = runnable_single.invoke(input_data)
+ print(result_single) # Output: "John"
+
+ # Multiple keys - returns a dictionary
+ runnable_multiple = RunnablePick(keys=["name", "age"])
+ result_multiple = runnable_multiple.invoke(input_data)
+ print(result_multiple) # Output: {'name': 'John', 'age': 30}
+ ```
+ """
+
+ keys: str | list[str]
+
+ def __init__(self, keys: str | list[str], **kwargs: Any) -> None:
+ """Create a `RunnablePick`.
+
+ Args:
+ keys: A single key or a list of keys to pick from the input dictionary.
+ """
+ super().__init__(keys=keys, **kwargs)
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @override
+ def get_name(self, suffix: str | None = None, *, name: str | None = None) -> str:
+ name = (
+ name
+ or self.name
+ or "RunnablePick"
+ f"<{','.join([self.keys] if isinstance(self.keys, str) else self.keys)}>"
+ )
+ return super().get_name(suffix, name=name)
+
+ def _pick(self, value: dict[str, Any]) -> Any:
+ if not isinstance(value, dict):
+ msg = "The input to RunnablePassthrough.assign() must be a dict."
+ raise ValueError(msg) # noqa: TRY004
+
+ if isinstance(self.keys, str):
+ return value.get(self.keys)
+ picked = {k: value.get(k) for k in self.keys if k in value}
+ if picked:
+ return AddableDict(picked)
+ return None
+
+ @override
+ def invoke(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ return self._call_with_config(self._pick, input, config, **kwargs)
+
+ async def _ainvoke(
+ self,
+ value: dict[str, Any],
+ ) -> Any:
+ return self._pick(value)
+
+ @override
+ async def ainvoke(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ return await self._acall_with_config(self._ainvoke, input, config, **kwargs)
+
+ def _transform(
+ self,
+ chunks: Iterator[dict[str, Any]],
+ ) -> Iterator[Any]:
+ for chunk in chunks:
+ picked = self._pick(chunk)
+ if picked is not None:
+ yield picked
+
+ @override
+ def transform(
+ self,
+ input: Iterator[dict[str, Any]],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Any]:
+ yield from self._transform_stream_with_config(
+ input, self._transform, config, **kwargs
+ )
+
+ async def _atransform(
+ self,
+ chunks: AsyncIterator[dict[str, Any]],
+ ) -> AsyncIterator[Any]:
+ async for chunk in chunks:
+ picked = self._pick(chunk)
+ if picked is not None:
+ yield picked
+
+ @override
+ async def atransform(
+ self,
+ input: AsyncIterator[dict[str, Any]],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Any]:
+ async for chunk in self._atransform_stream_with_config(
+ input, self._atransform, config, **kwargs
+ ):
+ yield chunk
+
+ @override
+ def stream(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Iterator[Any]:
+ return self.transform(iter([input]), config, **kwargs)
+
+ @override
+ async def astream(
+ self,
+ input: dict[str, Any],
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[Any]:
+ async def input_aiter() -> AsyncIterator[dict[str, Any]]:
+ yield input
+
+ async for chunk in self.atransform(input_aiter(), config, **kwargs):
+ yield chunk
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/retry.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/retry.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b9f5fef2de7d38ab51205f902edf22859c0d951
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/retry.py
@@ -0,0 +1,379 @@
+"""`Runnable` that retries a `Runnable` if it fails."""
+
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ TypeVar,
+ cast,
+)
+
+from tenacity import (
+ AsyncRetrying,
+ RetryCallState,
+ RetryError,
+ Retrying,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential_jitter,
+)
+from typing_extensions import TypedDict, override
+
+from langchain_core.runnables.base import RunnableBindingBase
+from langchain_core.runnables.config import RunnableConfig, patch_config
+from langchain_core.runnables.utils import Input, Output
+
+if TYPE_CHECKING:
+ from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForChainRun,
+ CallbackManagerForChainRun,
+ )
+
+ T = TypeVar("T", CallbackManagerForChainRun, AsyncCallbackManagerForChainRun)
+U = TypeVar("U")
+
+
+class ExponentialJitterParams(TypedDict, total=False):
+ """Parameters for `tenacity.wait_exponential_jitter`."""
+
+ initial: float
+ """Initial wait."""
+ max: float
+ """Maximum wait."""
+ exp_base: float
+ """Base for exponential backoff."""
+ jitter: float
+ """Random additional wait sampled from random.uniform(0, jitter)."""
+
+
+class RunnableRetry(RunnableBindingBase[Input, Output]): # type: ignore[no-redef]
+ """Retry a Runnable if it fails.
+
+ RunnableRetry can be used to add retry logic to any object
+ that subclasses the base Runnable.
+
+ Such retries are especially useful for network calls that may fail
+ due to transient errors.
+
+ The RunnableRetry is implemented as a RunnableBinding. The easiest
+ way to use it is through the `.with_retry()` method on all Runnables.
+
+ Example:
+ Here's an example that uses a RunnableLambda to raise an exception
+
+ ```python
+ import time
+
+
+ def foo(input) -> None:
+ '''Fake function that raises an exception.'''
+ raise ValueError(f"Invoking foo failed. At time {time.time()}")
+
+
+ runnable = RunnableLambda(foo)
+
+ runnable_with_retries = runnable.with_retry(
+ retry_if_exception_type=(ValueError,), # Retry only on ValueError
+ wait_exponential_jitter=True, # Add jitter to the exponential backoff
+ stop_after_attempt=2, # Try twice
+ exponential_jitter_params={"initial": 2}, # if desired, customize backoff
+ )
+
+ # The method invocation above is equivalent to the longer form below:
+
+ runnable_with_retries = RunnableRetry(
+ bound=runnable,
+ retry_exception_types=(ValueError,),
+ max_attempt_number=2,
+ wait_exponential_jitter=True,
+ exponential_jitter_params={"initial": 2},
+ )
+ ```
+
+ This logic can be used to retry any Runnable, including a chain of Runnables,
+ but in general it's best practice to keep the scope of the retry as small as
+ possible. For example, if you have a chain of Runnables, you should only retry
+ the Runnable that is likely to fail, not the entire chain.
+
+ Example:
+ ```python
+ from langchain_core.chat_models import ChatOpenAI
+ from langchain_core.prompts import PromptTemplate
+
+ template = PromptTemplate.from_template("tell me a joke about {topic}.")
+ model = ChatOpenAI(temperature=0.5)
+
+ # Good
+ chain = template | model.with_retry()
+
+ # Bad
+ chain = template | model
+ retryable_chain = chain.with_retry()
+ ```
+ """
+
+ retry_exception_types: tuple[type[BaseException], ...] = (Exception,)
+ """The exception types to retry on. By default all exceptions are retried.
+
+ In general you should only retry on exceptions that are likely to be
+ transient, such as network errors.
+
+ Good exceptions to retry are all server errors (5xx) and selected client
+ errors (4xx) such as 429 Too Many Requests.
+ """
+
+ wait_exponential_jitter: bool = True
+ """Whether to add jitter to the exponential backoff."""
+
+ exponential_jitter_params: ExponentialJitterParams | None = None
+ """Parameters for `tenacity.wait_exponential_jitter`. Namely: `initial`,
+ `max`, `exp_base`, and `jitter` (all `float` values).
+ """
+
+ max_attempt_number: int = 3
+ """The maximum number of attempts to retry the Runnable."""
+
+ @property
+ def _kwargs_retrying(self) -> dict[str, Any]:
+ kwargs: dict[str, Any] = {}
+
+ if self.max_attempt_number:
+ kwargs["stop"] = stop_after_attempt(self.max_attempt_number)
+
+ if self.wait_exponential_jitter:
+ kwargs["wait"] = wait_exponential_jitter(
+ **(self.exponential_jitter_params or {})
+ )
+
+ if self.retry_exception_types:
+ kwargs["retry"] = retry_if_exception_type(self.retry_exception_types)
+
+ return kwargs
+
+ def _sync_retrying(self, **kwargs: Any) -> Retrying:
+ return Retrying(**self._kwargs_retrying, **kwargs)
+
+ def _async_retrying(self, **kwargs: Any) -> AsyncRetrying:
+ return AsyncRetrying(**self._kwargs_retrying, **kwargs)
+
+ @staticmethod
+ def _patch_config(
+ config: RunnableConfig,
+ run_manager: "T",
+ retry_state: RetryCallState,
+ ) -> RunnableConfig:
+ attempt = retry_state.attempt_number
+ tag = f"retry:attempt:{attempt}" if attempt > 1 else None
+ return patch_config(config, callbacks=run_manager.get_child(tag))
+
+ def _patch_config_list(
+ self,
+ config: list[RunnableConfig],
+ run_manager: list["T"],
+ retry_state: RetryCallState,
+ ) -> list[RunnableConfig]:
+ return [
+ self._patch_config(c, rm, retry_state)
+ for c, rm in zip(config, run_manager, strict=False)
+ ]
+
+ def _invoke(
+ self,
+ input_: Input,
+ run_manager: "CallbackManagerForChainRun",
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ for attempt in self._sync_retrying(reraise=True):
+ with attempt:
+ result = super().invoke(
+ input_,
+ self._patch_config(config, run_manager, attempt.retry_state),
+ **kwargs,
+ )
+ if attempt.retry_state.outcome and not attempt.retry_state.outcome.failed:
+ attempt.retry_state.set_result(result)
+ return result
+
+ @override
+ def invoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ return self._call_with_config(self._invoke, input, config, **kwargs)
+
+ async def _ainvoke(
+ self,
+ input_: Input,
+ run_manager: "AsyncCallbackManagerForChainRun",
+ config: RunnableConfig,
+ **kwargs: Any,
+ ) -> Output:
+ async for attempt in self._async_retrying(reraise=True):
+ with attempt:
+ result = await super().ainvoke(
+ input_,
+ self._patch_config(config, run_manager, attempt.retry_state),
+ **kwargs,
+ )
+ if attempt.retry_state.outcome and not attempt.retry_state.outcome.failed:
+ attempt.retry_state.set_result(result)
+ return result
+
+ @override
+ async def ainvoke(
+ self, input: Input, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ return await self._acall_with_config(self._ainvoke, input, config, **kwargs)
+
+ def _batch(
+ self,
+ inputs: list[Input],
+ run_manager: list["CallbackManagerForChainRun"],
+ config: list[RunnableConfig],
+ **kwargs: Any,
+ ) -> list[Output | Exception]:
+ results_map: dict[int, Output] = {}
+
+ not_set: list[Output] = []
+ result = not_set
+ try:
+ for attempt in self._sync_retrying():
+ with attempt:
+ # Retry for inputs that have not yet succeeded
+ # Determine which original indices remain.
+ remaining_indices = [
+ i for i in range(len(inputs)) if i not in results_map
+ ]
+ if not remaining_indices:
+ break
+ pending_inputs = [inputs[i] for i in remaining_indices]
+ pending_configs = [config[i] for i in remaining_indices]
+ pending_run_managers = [run_manager[i] for i in remaining_indices]
+ # Invoke underlying batch only on remaining elements.
+ result = super().batch(
+ pending_inputs,
+ self._patch_config_list(
+ pending_configs, pending_run_managers, attempt.retry_state
+ ),
+ return_exceptions=True,
+ **kwargs,
+ )
+ # Register the results of the inputs that have succeeded, mapping
+ # back to their original indices.
+ first_exception = None
+ for offset, r in enumerate(result):
+ if isinstance(r, Exception):
+ if not first_exception:
+ first_exception = r
+ continue
+ orig_idx = remaining_indices[offset]
+ results_map[orig_idx] = r
+ # If any exception occurred, raise it, to retry the failed ones
+ if first_exception:
+ raise first_exception
+ if (
+ attempt.retry_state.outcome
+ and not attempt.retry_state.outcome.failed
+ ):
+ attempt.retry_state.set_result(result)
+ except RetryError as e:
+ if result is not_set:
+ result = cast("list[Output]", [e] * len(inputs))
+
+ outputs: list[Output | Exception] = []
+ for idx in range(len(inputs)):
+ if idx in results_map:
+ outputs.append(results_map[idx])
+ else:
+ outputs.append(result.pop(0))
+ return outputs
+
+ @override
+ def batch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any,
+ ) -> list[Output]:
+ return self._batch_with_config(
+ self._batch, inputs, config, return_exceptions=return_exceptions, **kwargs
+ )
+
+ async def _abatch(
+ self,
+ inputs: list[Input],
+ run_manager: list["AsyncCallbackManagerForChainRun"],
+ config: list[RunnableConfig],
+ **kwargs: Any,
+ ) -> list[Output | Exception]:
+ results_map: dict[int, Output] = {}
+
+ not_set: list[Output] = []
+ result = not_set
+ try:
+ async for attempt in self._async_retrying():
+ with attempt:
+ # Retry for inputs that have not yet succeeded
+ # Determine which original indices remain.
+ remaining_indices = [
+ i for i in range(len(inputs)) if i not in results_map
+ ]
+ if not remaining_indices:
+ break
+ pending_inputs = [inputs[i] for i in remaining_indices]
+ pending_configs = [config[i] for i in remaining_indices]
+ pending_run_managers = [run_manager[i] for i in remaining_indices]
+ result = await super().abatch(
+ pending_inputs,
+ self._patch_config_list(
+ pending_configs, pending_run_managers, attempt.retry_state
+ ),
+ return_exceptions=True,
+ **kwargs,
+ )
+ # Register the results of the inputs that have succeeded, mapping
+ # back to their original indices.
+ first_exception = None
+ for offset, r in enumerate(result):
+ if isinstance(r, Exception):
+ if not first_exception:
+ first_exception = r
+ continue
+ orig_idx = remaining_indices[offset]
+ results_map[orig_idx] = r
+ # If any exception occurred, raise it, to retry the failed ones
+ if first_exception:
+ raise first_exception
+ if (
+ attempt.retry_state.outcome
+ and not attempt.retry_state.outcome.failed
+ ):
+ attempt.retry_state.set_result(result)
+ except RetryError as e:
+ if result is not_set:
+ result = cast("list[Output]", [e] * len(inputs))
+
+ outputs: list[Output | Exception] = []
+ for idx in range(len(inputs)):
+ if idx in results_map:
+ outputs.append(results_map[idx])
+ else:
+ outputs.append(result.pop(0))
+ return outputs
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[Input],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any,
+ ) -> list[Output]:
+ return await self._abatch_with_config(
+ self._abatch, inputs, config, return_exceptions=return_exceptions, **kwargs
+ )
+
+ # stream() and transform() are not retried because retrying a stream
+ # is not very intuitive.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/router.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/router.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6341da1c1617c3e9d481ec95f251d8dab5c472b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/router.py
@@ -0,0 +1,239 @@
+"""`Runnable` that routes to a set of `Runnable` objects."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ cast,
+)
+
+from pydantic import ConfigDict
+from typing_extensions import TypedDict, override
+
+from langchain_core.runnables.base import (
+ Runnable,
+ RunnableSerializable,
+ coerce_to_runnable,
+)
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ get_config_list,
+ get_executor_for_config,
+)
+from langchain_core.runnables.utils import (
+ ConfigurableFieldSpec,
+ Input,
+ Output,
+ gather_with_concurrency,
+ get_unique_config_specs,
+)
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Callable, Iterator
+
+
+class RouterInput(TypedDict):
+ """Router input."""
+
+ key: str
+ """The key to route on."""
+ input: Any
+ """The input to pass to the selected `Runnable`."""
+
+
+class RouterRunnable(RunnableSerializable[RouterInput, Output]):
+ """`Runnable` that routes to a set of `Runnable` based on `Input['key']`.
+
+ Returns the output of the selected Runnable.
+
+ Example:
+ ```python
+ from langchain_core.runnables.router import RouterRunnable
+ from langchain_core.runnables import RunnableLambda
+
+ add = RunnableLambda(func=lambda x: x + 1)
+ square = RunnableLambda(func=lambda x: x**2)
+
+ router = RouterRunnable(runnables={"add": add, "square": square})
+ router.invoke({"key": "square", "input": 3})
+ ```
+ """
+
+ runnables: Mapping[str, Runnable[Any, Output]]
+
+ @property
+ @override
+ def config_specs(self) -> list[ConfigurableFieldSpec]:
+ return get_unique_config_specs(
+ spec for step in self.runnables.values() for spec in step.config_specs
+ )
+
+ def __init__(
+ self,
+ runnables: Mapping[str, Runnable[Any, Output] | Callable[[Any], Output]],
+ ) -> None:
+ """Create a `RouterRunnable`.
+
+ Args:
+ runnables: A mapping of keys to `Runnable` objects.
+ """
+ super().__init__(
+ runnables={key: coerce_to_runnable(r) for key, r in runnables.items()}
+ )
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @classmethod
+ @override
+ def is_lc_serializable(cls) -> bool:
+ """Return `True` as this class is serializable."""
+ return True
+
+ @classmethod
+ @override
+ def get_lc_namespace(cls) -> list[str]:
+ """Get the namespace of the LangChain object.
+
+ Returns:
+ `["langchain", "schema", "runnable"]`
+ """
+ return ["langchain", "schema", "runnable"]
+
+ @override
+ def invoke(
+ self, input: RouterInput, config: RunnableConfig | None = None, **kwargs: Any
+ ) -> Output:
+ key = input["key"]
+ actual_input = input["input"]
+ if key not in self.runnables:
+ msg = f"No runnable associated with key '{key}'"
+ raise ValueError(msg)
+
+ runnable = self.runnables[key]
+ return runnable.invoke(actual_input, config)
+
+ @override
+ async def ainvoke(
+ self,
+ input: RouterInput,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Output:
+ key = input["key"]
+ actual_input = input["input"]
+ if key not in self.runnables:
+ msg = f"No runnable associated with key '{key}'"
+ raise ValueError(msg)
+
+ runnable = self.runnables[key]
+ return await runnable.ainvoke(actual_input, config)
+
+ @override
+ def batch(
+ self,
+ inputs: list[RouterInput],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if not inputs:
+ return []
+
+ keys = [input_["key"] for input_ in inputs]
+ actual_inputs = [input_["input"] for input_ in inputs]
+ if any(key not in self.runnables for key in keys):
+ msg = "One or more keys do not have a corresponding runnable"
+ raise ValueError(msg)
+
+ def invoke(
+ runnable: Runnable[Input, Output], input_: Input, config: RunnableConfig
+ ) -> Output | Exception:
+ if return_exceptions:
+ try:
+ return runnable.invoke(input_, config, **kwargs)
+ except Exception as e:
+ return e
+ else:
+ return runnable.invoke(input_, config, **kwargs)
+
+ runnables = [self.runnables[key] for key in keys]
+ configs = get_config_list(config, len(inputs))
+ with get_executor_for_config(configs[0]) as executor:
+ return cast(
+ "list[Output]",
+ list(executor.map(invoke, runnables, actual_inputs, configs)),
+ )
+
+ @override
+ async def abatch(
+ self,
+ inputs: list[RouterInput],
+ config: RunnableConfig | list[RunnableConfig] | None = None,
+ *,
+ return_exceptions: bool = False,
+ **kwargs: Any | None,
+ ) -> list[Output]:
+ if not inputs:
+ return []
+
+ keys = [input_["key"] for input_ in inputs]
+ actual_inputs = [input_["input"] for input_ in inputs]
+ if any(key not in self.runnables for key in keys):
+ msg = "One or more keys do not have a corresponding runnable"
+ raise ValueError(msg)
+
+ async def ainvoke(
+ runnable: Runnable[Input, Output], input_: Input, config: RunnableConfig
+ ) -> Output | Exception:
+ if return_exceptions:
+ try:
+ return await runnable.ainvoke(input_, config, **kwargs)
+ except Exception as e:
+ return e
+ else:
+ return await runnable.ainvoke(input_, config, **kwargs)
+
+ runnables = [self.runnables[key] for key in keys]
+ configs = get_config_list(config, len(inputs))
+ return await gather_with_concurrency(
+ configs[0].get("max_concurrency"),
+ *map(ainvoke, runnables, actual_inputs, configs),
+ )
+
+ @override
+ def stream(
+ self,
+ input: RouterInput,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> Iterator[Output]:
+ key = input["key"]
+ actual_input = input["input"]
+ if key not in self.runnables:
+ msg = f"No runnable associated with key '{key}'"
+ raise ValueError(msg)
+
+ runnable = self.runnables[key]
+ yield from runnable.stream(actual_input, config)
+
+ @override
+ async def astream(
+ self,
+ input: RouterInput,
+ config: RunnableConfig | None = None,
+ **kwargs: Any | None,
+ ) -> AsyncIterator[Output]:
+ key = input["key"]
+ actual_input = input["input"]
+ if key not in self.runnables:
+ msg = f"No runnable associated with key '{key}'"
+ raise ValueError(msg)
+
+ runnable = self.runnables[key]
+ async for output in runnable.astream(actual_input, config):
+ yield output
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/schema.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..29bbcd2ceee47c773dfa6a02c16589f2878aa38c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/schema.py
@@ -0,0 +1,188 @@
+"""Module contains typedefs that are used with `Runnable` objects."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Literal
+
+from typing_extensions import NotRequired, TypedDict
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+
+class EventData(TypedDict, total=False):
+ """Data associated with a streaming event."""
+
+ input: Any
+ """The input passed to the `Runnable` that generated the event.
+
+ Inputs will sometimes be available at the *START* of the `Runnable`, and
+ sometimes at the *END* of the `Runnable`.
+
+ If a `Runnable` is able to stream its inputs, then its input by definition
+ won't be known until the *END* of the `Runnable` when it has finished streaming
+ its inputs.
+ """
+ error: NotRequired[BaseException]
+ """The error that occurred during the execution of the `Runnable`.
+
+ This field is only available if the `Runnable` raised an exception.
+
+ !!! version-added "Added in `langchain-core` 1.0.0"
+ """
+ output: Any
+ """The output of the `Runnable` that generated the event.
+
+ Outputs will only be available at the *END* of the `Runnable`.
+
+ For most `Runnable` objects, this field can be inferred from the `chunk` field,
+ though there might be some exceptions for special a cased `Runnable` (e.g., like
+ chat models), which may return more information.
+ """
+ chunk: Any
+ """A streaming chunk from the output that generated the event.
+
+ chunks support addition in general, and adding them up should result
+ in the output of the `Runnable` that generated the event.
+ """
+ tool_call_id: NotRequired[str | None]
+ """The tool call ID associated with the tool execution.
+
+ This field is available for the `on_tool_error` event and can be used to
+ link errors to specific tool calls in stateless agent implementations.
+ """
+
+
+class BaseStreamEvent(TypedDict):
+ """Streaming event.
+
+ Schema of a streaming event which is produced from the `astream_events` method.
+
+ Example:
+ ```python
+ from langchain_core.runnables import RunnableLambda
+
+
+ async def reverse(s: str) -> str:
+ return s[::-1]
+
+
+ chain = RunnableLambda(func=reverse)
+
+ events = [event async for event in chain.astream_events("hello")]
+
+ # Will produce the following events
+ # (where some fields have been omitted for brevity):
+ [
+ {
+ "data": {"input": "hello"},
+ "event": "on_chain_start",
+ "metadata": {},
+ "name": "reverse",
+ "tags": [],
+ },
+ {
+ "data": {"chunk": "olleh"},
+ "event": "on_chain_stream",
+ "metadata": {},
+ "name": "reverse",
+ "tags": [],
+ },
+ {
+ "data": {"output": "olleh"},
+ "event": "on_chain_end",
+ "metadata": {},
+ "name": "reverse",
+ "tags": [],
+ },
+ ]
+ ```
+ """
+
+ event: str
+ """Event names are of the format: `on_[runnable_type]_(start|stream|end)`.
+
+ Runnable types are one of:
+
+ - **llm** - used by non chat models
+ - **chat_model** - used by chat models
+ - **prompt** -- e.g., `ChatPromptTemplate`
+ - **tool** -- from tools defined via `@tool` decorator or inheriting
+ from `Tool`/`BaseTool`
+ - **chain** - most `Runnable` objects are of this type
+
+ Further, the events are categorized as one of:
+
+ - **start** - when the `Runnable` starts
+ - **stream** - when the `Runnable` is streaming
+ - **end* - when the `Runnable` ends
+
+ start, stream and end are associated with slightly different `data` payload.
+
+ Please see the documentation for `EventData` for more details.
+ """
+ run_id: str
+ """An randomly generated ID to keep track of the execution of the given `Runnable`.
+
+ Each child `Runnable` that gets invoked as part of the execution of a parent
+ `Runnable` is assigned its own unique ID.
+ """
+ tags: NotRequired[list[str]]
+ """Tags associated with the `Runnable` that generated this event.
+
+ Tags are always inherited from parent `Runnable` objects.
+
+ Tags can either be bound to a `Runnable` using `.with_config({"tags": ["hello"]})`
+ or passed at run time using `.astream_events(..., {"tags": ["hello"]})`.
+ """
+ metadata: NotRequired[dict[str, Any]]
+ """Metadata associated with the `Runnable` that generated this event.
+
+ Metadata can either be bound to a `Runnable` using
+
+ `.with_config({"metadata": { "foo": "bar" }})`
+
+ or passed at run time using
+
+ `.astream_events(..., {"metadata": {"foo": "bar"}})`.
+ """
+
+ parent_ids: Sequence[str]
+ """A list of the parent IDs associated with this event.
+
+ Root Events will have an empty list.
+
+ For example, if a `Runnable` A calls `Runnable` B, then the event generated by
+ `Runnable` B will have `Runnable` A's ID in the `parent_ids` field.
+
+ The order of the parent IDs is from the root parent to the immediate parent.
+
+ Only supported as of v2 of the astream events API. v1 will return an empty list.
+ """
+
+
+class StandardStreamEvent(BaseStreamEvent):
+ """A standard stream event that follows LangChain convention for event data."""
+
+ data: EventData
+ """Event data.
+
+ The contents of the event data depend on the event type.
+ """
+ name: str
+ """The name of the `Runnable` that generated the event."""
+
+
+class CustomStreamEvent(BaseStreamEvent):
+ """Custom stream event created by the user."""
+
+ # Overwrite the event field to be more specific.
+ event: Literal["on_custom_event"] # type: ignore[misc]
+ """The event type."""
+ name: str
+ """User defined name for the event."""
+ data: Any
+ """The data associated with the event. Free form and can be anything."""
+
+
+StreamEvent = StandardStreamEvent | CustomStreamEvent
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e46251a2070c7c4757d6ab0f83007f81bc12e2ef
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/runnables/utils.py
@@ -0,0 +1,779 @@
+"""Utility code for `Runnable` objects."""
+
+from __future__ import annotations
+
+import ast
+import asyncio
+import inspect
+import sys
+import textwrap
+
+# Cannot move to TYPE_CHECKING as Mapping and Sequence are needed at runtime by
+# RunnableConfigurableFields.
+from collections.abc import Mapping, Sequence # noqa: TC003
+from functools import lru_cache
+from inspect import signature
+from itertools import groupby
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ NamedTuple,
+ Protocol,
+ TypeGuard,
+ TypeVar,
+)
+
+from typing_extensions import override
+
+# Re-export create-model for backwards compatibility
+from langchain_core.utils.pydantic import create_model # noqa: F401
+
+if TYPE_CHECKING:
+ from collections.abc import (
+ AsyncIterable,
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Coroutine,
+ Iterable,
+ )
+ from contextvars import Context
+
+ from langchain_core.runnables.schema import StreamEvent
+
+Input = TypeVar("Input", contravariant=True) # noqa: PLC0105
+# Output type should implement __concat__, as eg str, list, dict do
+Output = TypeVar("Output", covariant=True) # noqa: PLC0105
+
+
+async def gated_coro(semaphore: asyncio.Semaphore, coro: Coroutine) -> Any:
+ """Run a coroutine with a semaphore.
+
+ Args:
+ semaphore: The semaphore to use.
+ coro: The coroutine to run.
+
+ Returns:
+ The result of the coroutine.
+ """
+ async with semaphore:
+ return await coro
+
+
+async def gather_with_concurrency(n: int | None, *coros: Coroutine) -> list:
+ """Gather coroutines with a limit on the number of concurrent coroutines.
+
+ Args:
+ n: The number of coroutines to run concurrently.
+ *coros: The coroutines to run.
+
+ Returns:
+ The results of the coroutines.
+ """
+ if n is None:
+ return await asyncio.gather(*coros)
+
+ semaphore = asyncio.Semaphore(n)
+
+ return await asyncio.gather(*(gated_coro(semaphore, c) for c in coros))
+
+
+def accepts_run_manager(callable: Callable[..., Any]) -> bool: # noqa: A002
+ """Check if a callable accepts a run_manager argument.
+
+ Args:
+ callable: The callable to check.
+
+ Returns:
+ `True` if the callable accepts a run_manager argument, `False` otherwise.
+ """
+ try:
+ return signature(callable).parameters.get("run_manager") is not None
+ except ValueError:
+ return False
+
+
+def accepts_config(callable: Callable[..., Any]) -> bool: # noqa: A002
+ """Check if a callable accepts a config argument.
+
+ Args:
+ callable: The callable to check.
+
+ Returns:
+ `True` if the callable accepts a config argument, `False` otherwise.
+ """
+ try:
+ return signature(callable).parameters.get("config") is not None
+ except ValueError:
+ return False
+
+
+def accepts_context(callable: Callable[..., Any]) -> bool: # noqa: A002
+ """Check if a callable accepts a context argument.
+
+ Args:
+ callable: The callable to check.
+
+ Returns:
+ `True` if the callable accepts a context argument, `False` otherwise.
+ """
+ try:
+ return signature(callable).parameters.get("context") is not None
+ except ValueError:
+ return False
+
+
+def asyncio_accepts_context() -> bool:
+ """Check if asyncio.create_task accepts a `context` arg.
+
+ Returns:
+ True if `asyncio.create_task` accepts a context argument, `False` otherwise.
+ """
+ return sys.version_info >= (3, 11)
+
+
+_T = TypeVar("_T")
+
+
+def coro_with_context(
+ coro: Awaitable[_T], context: Context, *, create_task: bool = False
+) -> Awaitable[_T]:
+ """Await a coroutine with a context.
+
+ Args:
+ coro: The coroutine to await.
+ context: The context to use.
+ create_task: Whether to create a task.
+
+ Returns:
+ The coroutine with the context.
+ """
+ if asyncio_accepts_context():
+ return asyncio.create_task(coro, context=context) # type: ignore[arg-type,call-arg,unused-ignore]
+ if create_task:
+ return asyncio.create_task(coro) # type: ignore[arg-type]
+ return coro
+
+
+class IsLocalDict(ast.NodeVisitor):
+ """Check if a name is a local dict."""
+
+ def __init__(self, name: str, keys: set[str]) -> None:
+ """Initialize the visitor.
+
+ Args:
+ name: The name to check.
+ keys: The keys to populate.
+ """
+ self.name = name
+ self.keys = keys
+
+ @override
+ def visit_Subscript(self, node: ast.Subscript) -> None:
+ """Visit a subscript node.
+
+ Args:
+ node: The node to visit.
+ """
+ if (
+ isinstance(node.ctx, ast.Load)
+ and isinstance(node.value, ast.Name)
+ and node.value.id == self.name
+ and isinstance(node.slice, ast.Constant)
+ and isinstance(node.slice.value, str)
+ ):
+ # we've found a subscript access on the name we're looking for
+ self.keys.add(node.slice.value)
+
+ @override
+ def visit_Call(self, node: ast.Call) -> None:
+ """Visit a call node.
+
+ Args:
+ node: The node to visit.
+ """
+ if (
+ isinstance(node.func, ast.Attribute)
+ and isinstance(node.func.value, ast.Name)
+ and node.func.value.id == self.name
+ and node.func.attr == "get"
+ and len(node.args) in {1, 2}
+ and isinstance(node.args[0], ast.Constant)
+ and isinstance(node.args[0].value, str)
+ ):
+ # we've found a .get() call on the name we're looking for
+ self.keys.add(node.args[0].value)
+
+
+class IsFunctionArgDict(ast.NodeVisitor):
+ """Check if the first argument of a function is a dict."""
+
+ def __init__(self) -> None:
+ """Create a IsFunctionArgDict visitor."""
+ self.keys: set[str] = set()
+
+ @override
+ def visit_Lambda(self, node: ast.Lambda) -> None:
+ """Visit a lambda function.
+
+ Args:
+ node: The node to visit.
+ """
+ if not node.args.args:
+ return
+ input_arg_name = node.args.args[0].arg
+ IsLocalDict(input_arg_name, self.keys).visit(node.body)
+
+ @override
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
+ """Visit a function definition.
+
+ Args:
+ node: The node to visit.
+ """
+ if not node.args.args:
+ return
+ input_arg_name = node.args.args[0].arg
+ IsLocalDict(input_arg_name, self.keys).visit(node)
+
+ @override
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
+ """Visit an async function definition.
+
+ Args:
+ node: The node to visit.
+ """
+ if not node.args.args:
+ return
+ input_arg_name = node.args.args[0].arg
+ IsLocalDict(input_arg_name, self.keys).visit(node)
+
+
+class NonLocals(ast.NodeVisitor):
+ """Get nonlocal variables accessed."""
+
+ def __init__(self) -> None:
+ """Create a NonLocals visitor."""
+ self.loads: set[str] = set()
+ self.stores: set[str] = set()
+
+ @override
+ def visit_Name(self, node: ast.Name) -> None:
+ """Visit a name node.
+
+ Args:
+ node: The node to visit.
+ """
+ if isinstance(node.ctx, ast.Load):
+ self.loads.add(node.id)
+ elif isinstance(node.ctx, ast.Store):
+ self.stores.add(node.id)
+
+ @override
+ def visit_Attribute(self, node: ast.Attribute) -> None:
+ """Visit an attribute node.
+
+ Args:
+ node: The node to visit.
+ """
+ if isinstance(node.ctx, ast.Load):
+ parent = node.value
+ attr_expr = node.attr
+ while isinstance(parent, ast.Attribute):
+ attr_expr = parent.attr + "." + attr_expr
+ parent = parent.value
+ if isinstance(parent, ast.Name):
+ self.loads.add(parent.id + "." + attr_expr)
+ self.loads.discard(parent.id)
+ elif isinstance(parent, ast.Call):
+ if isinstance(parent.func, ast.Name):
+ self.loads.add(parent.func.id)
+ else:
+ parent = parent.func
+ attr_expr = ""
+ while isinstance(parent, ast.Attribute):
+ if attr_expr:
+ attr_expr = parent.attr + "." + attr_expr
+ else:
+ attr_expr = parent.attr
+ parent = parent.value
+ if isinstance(parent, ast.Name):
+ self.loads.add(parent.id + "." + attr_expr)
+
+
+class FunctionNonLocals(ast.NodeVisitor):
+ """Get the nonlocal variables accessed of a function."""
+
+ def __init__(self) -> None:
+ """Create a FunctionNonLocals visitor."""
+ self.nonlocals: set[str] = set()
+
+ @override
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
+ """Visit a function definition.
+
+ Args:
+ node: The node to visit.
+ """
+ visitor = NonLocals()
+ visitor.visit(node)
+ self.nonlocals.update(visitor.loads - visitor.stores)
+
+ @override
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
+ """Visit an async function definition.
+
+ Args:
+ node: The node to visit.
+ """
+ visitor = NonLocals()
+ visitor.visit(node)
+ self.nonlocals.update(visitor.loads - visitor.stores)
+
+ @override
+ def visit_Lambda(self, node: ast.Lambda) -> None:
+ """Visit a lambda function.
+
+ Args:
+ node: The node to visit.
+ """
+ visitor = NonLocals()
+ visitor.visit(node)
+ self.nonlocals.update(visitor.loads - visitor.stores)
+
+
+class GetLambdaSource(ast.NodeVisitor):
+ """Get the source code of a lambda function."""
+
+ def __init__(self) -> None:
+ """Initialize the visitor."""
+ self.source: str | None = None
+ self.count = 0
+
+ @override
+ def visit_Lambda(self, node: ast.Lambda) -> None:
+ """Visit a lambda function.
+
+ Args:
+ node: The node to visit.
+ """
+ self.count += 1
+ if hasattr(ast, "unparse"):
+ self.source = ast.unparse(node)
+
+
+def get_function_first_arg_dict_keys(func: Callable) -> list[str] | None:
+ """Get the keys of the first argument of a function if it is a dict.
+
+ Args:
+ func: The function to check.
+
+ Returns:
+ The keys of the first argument if it is a dict, None otherwise.
+ """
+ try:
+ code = inspect.getsource(func)
+ tree = ast.parse(textwrap.dedent(code))
+ visitor = IsFunctionArgDict()
+ visitor.visit(tree)
+ return sorted(visitor.keys) if visitor.keys else None
+ except (SyntaxError, TypeError, OSError, SystemError):
+ return None
+
+
+def get_lambda_source(func: Callable) -> str | None:
+ """Get the source code of a lambda function.
+
+ Args:
+ func: a Callable that can be a lambda function.
+
+ Returns:
+ the source code of the lambda function.
+ """
+ try:
+ name = func.__name__ if func.__name__ != "" else None
+ except AttributeError:
+ name = None
+ try:
+ code = inspect.getsource(func)
+ tree = ast.parse(textwrap.dedent(code))
+ visitor = GetLambdaSource()
+ visitor.visit(tree)
+ except (SyntaxError, TypeError, OSError, SystemError):
+ return name
+ return visitor.source if visitor.count == 1 else name
+
+
+@lru_cache(maxsize=256)
+def get_function_nonlocals(func: Callable) -> list[Any]:
+ """Get the nonlocal variables accessed by a function.
+
+ Args:
+ func: The function to check.
+
+ Returns:
+ The nonlocal variables accessed by the function.
+ """
+ try:
+ code = inspect.getsource(func)
+ tree = ast.parse(textwrap.dedent(code))
+ visitor = FunctionNonLocals()
+ visitor.visit(tree)
+ values: list[Any] = []
+ closure = (
+ inspect.getclosurevars(func.__wrapped__)
+ if hasattr(func, "__wrapped__") and callable(func.__wrapped__)
+ else inspect.getclosurevars(func)
+ )
+ candidates = {**closure.globals, **closure.nonlocals}
+ for k, v in candidates.items():
+ if k in visitor.nonlocals:
+ values.append(v)
+ for kk in visitor.nonlocals:
+ if "." in kk and kk.startswith(k):
+ vv = v
+ for part in kk.split(".")[1:]:
+ if vv is None:
+ break
+ try:
+ vv = getattr(vv, part)
+ except AttributeError:
+ break
+ else:
+ values.append(vv)
+ except (SyntaxError, TypeError, OSError, SystemError):
+ return []
+
+ return values
+
+
+def indent_lines_after_first(text: str, prefix: str) -> str:
+ """Indent all lines of text after the first line.
+
+ Args:
+ text: The text to indent.
+ prefix: Used to determine the number of spaces to indent.
+
+ Returns:
+ The indented text.
+ """
+ n_spaces = len(prefix)
+ spaces = " " * n_spaces
+ lines = text.splitlines()
+ return "\n".join([lines[0]] + [spaces + line for line in lines[1:]])
+
+
+class AddableDict(dict[str, Any]):
+ """Dictionary that can be added to another dictionary."""
+
+ def __add__(self, other: AddableDict) -> AddableDict:
+ """Add a dictionary to this dictionary.
+
+ Args:
+ other: The other dictionary to add.
+
+ Returns:
+ A dictionary that is the result of adding the two dictionaries.
+ """
+ chunk = AddableDict(self)
+ for key in other:
+ if key not in chunk or chunk[key] is None:
+ chunk[key] = other[key]
+ elif other[key] is not None:
+ try:
+ added = chunk[key] + other[key]
+ except TypeError:
+ added = other[key]
+ chunk[key] = added
+ return chunk
+
+ def __radd__(self, other: AddableDict) -> AddableDict:
+ """Add this dictionary to another dictionary.
+
+ Args:
+ other: The other dictionary to be added to.
+
+ Returns:
+ A dictionary that is the result of adding the two dictionaries.
+ """
+ chunk = AddableDict(other)
+ for key in self:
+ if key not in chunk or chunk[key] is None:
+ chunk[key] = self[key]
+ elif self[key] is not None:
+ try:
+ added = chunk[key] + self[key]
+ except TypeError:
+ added = self[key]
+ chunk[key] = added
+ return chunk
+
+
+_T_co = TypeVar("_T_co", covariant=True)
+_T_contra = TypeVar("_T_contra", contravariant=True)
+
+
+class SupportsAdd(Protocol[_T_contra, _T_co]):
+ """Protocol for objects that support addition."""
+
+ def __add__(self, x: _T_contra, /) -> _T_co:
+ """Add the object to another object."""
+
+
+Addable = TypeVar("Addable", bound=SupportsAdd[Any, Any])
+
+
+def add(addables: Iterable[Addable]) -> Addable | None:
+ """Add a sequence of addable objects together.
+
+ Args:
+ addables: The addable objects to add.
+
+ Returns:
+ The result of adding the addable objects.
+ """
+ final: Addable | None = None
+ for chunk in addables:
+ final = chunk if final is None else final + chunk
+ return final
+
+
+async def aadd(addables: AsyncIterable[Addable]) -> Addable | None:
+ """Asynchronously add a sequence of addable objects together.
+
+ Args:
+ addables: The addable objects to add.
+
+ Returns:
+ The result of adding the addable objects.
+ """
+ final: Addable | None = None
+ async for chunk in addables:
+ final = chunk if final is None else final + chunk
+ return final
+
+
+class ConfigurableField(NamedTuple):
+ """Field that can be configured by the user."""
+
+ id: str
+ """The unique identifier of the field."""
+
+ name: str | None = None
+ """The name of the field. """
+
+ description: str | None = None
+ """The description of the field. """
+
+ annotation: Any | None = None
+ """The annotation of the field. """
+
+ is_shared: bool = False
+ """Whether the field is shared."""
+
+ @override
+ def __hash__(self) -> int:
+ return hash((self.id, self.annotation))
+
+
+class ConfigurableFieldSingleOption(NamedTuple):
+ """Field that can be configured by the user with a default value."""
+
+ id: str
+ """The unique identifier of the field."""
+
+ options: Mapping[str, Any]
+ """The options for the field."""
+
+ default: str
+ """The default value for the field."""
+
+ name: str | None = None
+ """The name of the field. """
+
+ description: str | None = None
+ """The description of the field. """
+
+ is_shared: bool = False
+ """Whether the field is shared."""
+
+ @override
+ def __hash__(self) -> int:
+ return hash((self.id, tuple(self.options.keys()), self.default))
+
+
+class ConfigurableFieldMultiOption(NamedTuple):
+ """Field that can be configured by the user with multiple default values."""
+
+ id: str
+ """The unique identifier of the field."""
+
+ options: Mapping[str, Any]
+ """The options for the field."""
+
+ default: Sequence[str]
+ """The default values for the field."""
+
+ name: str | None = None
+ """The name of the field. """
+
+ description: str | None = None
+ """The description of the field. """
+
+ is_shared: bool = False
+ """Whether the field is shared."""
+
+ @override
+ def __hash__(self) -> int:
+ return hash((self.id, tuple(self.options.keys()), tuple(self.default)))
+
+
+AnyConfigurableField = (
+ ConfigurableField | ConfigurableFieldSingleOption | ConfigurableFieldMultiOption
+)
+
+
+class ConfigurableFieldSpec(NamedTuple):
+ """Field that can be configured by the user. It is a specification of a field."""
+
+ id: str
+ """The unique identifier of the field."""
+
+ annotation: Any
+ """The annotation of the field."""
+
+ name: str | None = None
+ """The name of the field. """
+
+ description: str | None = None
+ """The description of the field. """
+
+ default: Any = None
+ """The default value for the field. """
+
+ is_shared: bool = False
+ """Whether the field is shared."""
+
+ dependencies: list[str] | None = None
+ """The dependencies of the field. """
+
+
+def get_unique_config_specs(
+ specs: Iterable[ConfigurableFieldSpec],
+) -> list[ConfigurableFieldSpec]:
+ """Get the unique config specs from a sequence of config specs.
+
+ Args:
+ specs: The config specs.
+
+ Returns:
+ The unique config specs.
+
+ Raises:
+ ValueError: If the runnable sequence contains conflicting config specs.
+ """
+ grouped = groupby(
+ sorted(specs, key=lambda s: (s.id, *(s.dependencies or []))), lambda s: s.id
+ )
+ unique: list[ConfigurableFieldSpec] = []
+ for spec_id, dupes in grouped:
+ first = next(dupes)
+ others = list(dupes)
+ if len(others) == 0 or all(o == first for o in others):
+ unique.append(first)
+ else:
+ msg = (
+ "RunnableSequence contains conflicting config specs"
+ f"for {spec_id}: {[first, *others]}"
+ )
+ raise ValueError(msg)
+ return unique
+
+
+class _RootEventFilter:
+ def __init__(
+ self,
+ *,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ ) -> None:
+ """Utility to filter the root event in the astream_events implementation.
+
+ This is simply binding the arguments to the namespace to make save on
+ a bit of typing in the astream_events implementation.
+ """
+ self.include_names = include_names
+ self.include_types = include_types
+ self.include_tags = include_tags
+ self.exclude_names = exclude_names
+ self.exclude_types = exclude_types
+ self.exclude_tags = exclude_tags
+
+ def include_event(self, event: StreamEvent, root_type: str) -> bool:
+ """Determine whether to include an event."""
+ if (
+ self.include_names is None
+ and self.include_types is None
+ and self.include_tags is None
+ ):
+ include = True
+ else:
+ include = False
+
+ event_tags = event.get("tags") or []
+
+ if self.include_names is not None:
+ include = include or event["name"] in self.include_names
+ if self.include_types is not None:
+ include = include or root_type in self.include_types
+ if self.include_tags is not None:
+ include = include or any(tag in self.include_tags for tag in event_tags)
+
+ if self.exclude_names is not None:
+ include = include and event["name"] not in self.exclude_names
+ if self.exclude_types is not None:
+ include = include and root_type not in self.exclude_types
+ if self.exclude_tags is not None:
+ include = include and all(
+ tag not in self.exclude_tags for tag in event_tags
+ )
+
+ return include
+
+
+def is_async_generator(
+ func: Any,
+) -> TypeGuard[Callable[..., AsyncIterator]]:
+ """Check if a function is an async generator.
+
+ Args:
+ func: The function to check.
+
+ Returns:
+ `True` if the function is an async generator, `False` otherwise.
+ """
+ return inspect.isasyncgenfunction(func) or (
+ hasattr(func, "__call__") # noqa: B004
+ and inspect.isasyncgenfunction(func.__call__)
+ )
+
+
+def is_async_callable(
+ func: Any,
+) -> TypeGuard[Callable[..., Awaitable]]:
+ """Check if a function is async.
+
+ Args:
+ func: The function to check.
+
+ Returns:
+ `True` if the function is async, `False` otherwise.
+ """
+ return asyncio.iscoroutinefunction(func) or (
+ hasattr(func, "__call__") # noqa: B004
+ and asyncio.iscoroutinefunction(func.__call__)
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..445ca9909096971984b865f99050515c7531b611
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__init__.py
@@ -0,0 +1,95 @@
+"""Tools are classes that an Agent uses to interact with the world.
+
+Each tool has a description. Agent uses the description to choose the right tool for the
+job.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.tools.base import (
+ FILTERED_ARGS,
+ ArgsSchema,
+ BaseTool,
+ BaseToolkit,
+ InjectedToolArg,
+ InjectedToolCallId,
+ SchemaAnnotationError,
+ ToolException,
+ _get_runnable_config_param,
+ create_schema_from_function,
+ )
+ from langchain_core.tools.convert import (
+ convert_runnable_to_tool,
+ tool,
+ )
+ from langchain_core.tools.render import (
+ ToolsRenderer,
+ render_text_description,
+ render_text_description_and_args,
+ )
+ from langchain_core.tools.retriever import (
+ RetrieverInput,
+ create_retriever_tool,
+ )
+ from langchain_core.tools.simple import Tool
+ from langchain_core.tools.structured import StructuredTool
+
+__all__ = (
+ "FILTERED_ARGS",
+ "ArgsSchema",
+ "BaseTool",
+ "BaseToolkit",
+ "InjectedToolArg",
+ "InjectedToolCallId",
+ "RetrieverInput",
+ "SchemaAnnotationError",
+ "StructuredTool",
+ "Tool",
+ "ToolException",
+ "ToolsRenderer",
+ "_get_runnable_config_param",
+ "convert_runnable_to_tool",
+ "create_retriever_tool",
+ "create_schema_from_function",
+ "render_text_description",
+ "render_text_description_and_args",
+ "tool",
+)
+
+_dynamic_imports = {
+ "FILTERED_ARGS": "base",
+ "ArgsSchema": "base",
+ "BaseTool": "base",
+ "BaseToolkit": "base",
+ "InjectedToolArg": "base",
+ "InjectedToolCallId": "base",
+ "SchemaAnnotationError": "base",
+ "ToolException": "base",
+ "_get_runnable_config_param": "base",
+ "create_schema_from_function": "base",
+ "convert_runnable_to_tool": "convert",
+ "tool": "convert",
+ "ToolsRenderer": "render",
+ "render_text_description": "render",
+ "render_text_description_and_args": "render",
+ "RetrieverInput": "retriever",
+ "create_retriever_tool": "retriever",
+ "Tool": "simple",
+ "StructuredTool": "structured",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7642757f462a16ad7063f209d7e407d7024c94d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b231bc28192b638d4dcc8a0e05768faef86774e6
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/convert.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/convert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..70bc13bb16f4b05cd6bb17f2f922e27eefd745b7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/convert.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/render.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/render.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4dd00d921732fe465355d75a885dbdda370a032
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/render.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/retriever.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/retriever.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d96e2ee9737c71d6edc149f742d94900b6832c3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/retriever.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/simple.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/simple.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..60516c45a1e77227262370e7279a8a0989a7eef7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/simple.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/structured.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/structured.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f26ebb5617b2520d0dac891c768c707417421c0
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/__pycache__/structured.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..f069771f39e16930caaba9c45ad6f248e8256c5b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/base.py
@@ -0,0 +1,1593 @@
+"""Base classes and utilities for LangChain tools."""
+
+from __future__ import annotations
+
+import functools
+import inspect
+import json
+import logging
+import typing
+import warnings
+from abc import ABC, abstractmethod
+from collections.abc import Callable # noqa: TC003
+from inspect import signature
+from typing import (
+ TYPE_CHECKING,
+ Annotated,
+ Any,
+ Literal,
+ TypeVar,
+ cast,
+ get_args,
+ get_origin,
+ get_type_hints,
+)
+
+import typing_extensions
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ PydanticDeprecationWarning,
+ SkipValidation,
+ ValidationError,
+ validate_arguments,
+)
+from pydantic.fields import FieldInfo
+from pydantic.v1 import BaseModel as BaseModelV1
+from pydantic.v1 import ValidationError as ValidationErrorV1
+from pydantic.v1 import validate_arguments as validate_arguments_v1
+from typing_extensions import override
+
+from langchain_core.callbacks import (
+ AsyncCallbackManager,
+ CallbackManager,
+ Callbacks,
+)
+from langchain_core.messages.tool import ToolCall, ToolMessage, ToolOutputMixin
+from langchain_core.runnables import (
+ RunnableConfig,
+ RunnableSerializable,
+ ensure_config,
+ patch_config,
+ run_in_executor,
+)
+from langchain_core.runnables.config import set_config_context
+from langchain_core.runnables.utils import coro_with_context
+from langchain_core.utils.function_calling import (
+ _parse_google_docstring,
+ _py_38_safe_origin,
+)
+from langchain_core.utils.pydantic import (
+ TypeBaseModel,
+ _create_subset_model,
+ get_fields,
+ is_basemodel_subclass,
+ is_pydantic_v1_subclass,
+ is_pydantic_v2_subclass,
+)
+
+if TYPE_CHECKING:
+ import uuid
+ from collections.abc import Sequence
+
+FILTERED_ARGS = ("run_manager", "callbacks")
+TOOL_MESSAGE_BLOCK_TYPES = (
+ "text",
+ "image_url",
+ "image",
+ "json",
+ "search_result",
+ "custom_tool_call_output",
+ "document",
+ "file",
+)
+
+_logger = logging.getLogger(__name__)
+
+
+class SchemaAnnotationError(TypeError):
+ """Raised when `args_schema` is missing or has an incorrect type annotation."""
+
+
+def _is_annotated_type(typ: type[Any]) -> bool:
+ """Check if a type is an `Annotated` type.
+
+ Args:
+ typ: The type to check.
+
+ Returns:
+ `True` if the type is an `Annotated` type, `False` otherwise.
+ """
+ return get_origin(typ) in {typing.Annotated, typing_extensions.Annotated}
+
+
+def _get_annotation_description(arg_type: type) -> str | None:
+ """Extract description from an `Annotated` type.
+
+ Checks for string annotations and `FieldInfo` objects with descriptions.
+
+ Args:
+ arg_type: The type to extract description from.
+
+ Returns:
+ The description string if found, `None` otherwise.
+ """
+ if _is_annotated_type(arg_type):
+ annotated_args = get_args(arg_type)
+ for annotation in annotated_args[1:]:
+ if isinstance(annotation, str):
+ return annotation
+ if isinstance(annotation, FieldInfo) and annotation.description:
+ return annotation.description
+ return None
+
+
+def _get_filtered_args(
+ inferred_model: type[BaseModel],
+ func: Callable,
+ *,
+ filter_args: Sequence[str],
+ include_injected: bool = True,
+) -> dict:
+ """Get filtered arguments from a function's signature.
+
+ Args:
+ inferred_model: The Pydantic model inferred from the function.
+ func: The function to extract arguments from.
+ filter_args: Arguments to exclude from the result.
+ include_injected: Whether to include injected arguments.
+
+ Returns:
+ Dictionary of filtered arguments with their schema definitions.
+ """
+ schema = inferred_model.model_json_schema()["properties"]
+ valid_keys = signature(func).parameters
+ return {
+ k: schema[k]
+ for i, (k, param) in enumerate(valid_keys.items())
+ if k not in filter_args
+ and (i > 0 or param.name not in {"self", "cls"})
+ and (include_injected or not _is_injected_arg_type(param.annotation))
+ }
+
+
+def _parse_python_function_docstring(
+ function: Callable, annotations: dict, *, error_on_invalid_docstring: bool = False
+) -> tuple[str, dict]:
+ """Parse function and argument descriptions from a docstring.
+
+ Assumes the function docstring follows Google Python style guide.
+
+ Args:
+ function: The function to parse the docstring from.
+ annotations: Type annotations for the function parameters.
+ error_on_invalid_docstring: Whether to raise an error on invalid docstring.
+
+ Returns:
+ A tuple containing the function description and argument descriptions.
+ """
+ docstring = inspect.getdoc(function)
+ return _parse_google_docstring(
+ docstring,
+ list(annotations),
+ error_on_invalid_docstring=error_on_invalid_docstring,
+ )
+
+
+def _validate_docstring_args_against_annotations(
+ arg_descriptions: dict, annotations: dict
+) -> None:
+ """Validate that docstring arguments match function annotations.
+
+ Args:
+ arg_descriptions: Arguments described in the docstring.
+ annotations: Type annotations from the function signature.
+
+ Raises:
+ ValueError: If a docstring argument is not found in function signature.
+ """
+ for docstring_arg in arg_descriptions:
+ if docstring_arg not in annotations:
+ msg = f"Arg {docstring_arg} in docstring not found in function signature."
+ raise ValueError(msg)
+
+
+def _infer_arg_descriptions(
+ fn: Callable,
+ *,
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = False,
+) -> tuple[str, dict]:
+ """Infer argument descriptions from function docstring and annotations.
+
+ Args:
+ fn: The function to infer descriptions from.
+ parse_docstring: Whether to parse the docstring for descriptions.
+ error_on_invalid_docstring: Whether to raise error on invalid docstring.
+
+ Returns:
+ A tuple containing the function description and argument descriptions.
+ """
+ annotations = typing.get_type_hints(fn, include_extras=True)
+ if parse_docstring:
+ description, arg_descriptions = _parse_python_function_docstring(
+ fn, annotations, error_on_invalid_docstring=error_on_invalid_docstring
+ )
+ else:
+ description = inspect.getdoc(fn) or ""
+ arg_descriptions = {}
+ if parse_docstring:
+ _validate_docstring_args_against_annotations(arg_descriptions, annotations)
+ for arg, arg_type in annotations.items():
+ if arg in arg_descriptions:
+ continue
+ if desc := _get_annotation_description(arg_type):
+ arg_descriptions[arg] = desc
+ return description, arg_descriptions
+
+
+def _is_pydantic_annotation(annotation: Any, pydantic_version: str = "v2") -> bool:
+ """Check if a type annotation is a Pydantic model.
+
+ Args:
+ annotation: The type annotation to check.
+ pydantic_version: The Pydantic version to check against (`'v1'` or `'v2'`).
+
+ Returns:
+ `True` if the annotation is a Pydantic model, `False` otherwise.
+ """
+ base_model_class = BaseModelV1 if pydantic_version == "v1" else BaseModel
+ try:
+ return issubclass(annotation, base_model_class)
+ except TypeError:
+ return False
+
+
+def _function_annotations_are_pydantic_v1(
+ signature: inspect.Signature, func: Callable
+) -> bool:
+ """Check if all Pydantic annotations in a function are from v1.
+
+ Args:
+ signature: The function signature to check.
+ func: The function being checked.
+
+ Returns:
+ True if all Pydantic annotations are from v1, `False` otherwise.
+
+ Raises:
+ NotImplementedError: If the function contains mixed v1 and v2 annotations.
+ """
+ any_v1_annotations = any(
+ _is_pydantic_annotation(parameter.annotation, pydantic_version="v1")
+ for parameter in signature.parameters.values()
+ )
+ any_v2_annotations = any(
+ _is_pydantic_annotation(parameter.annotation, pydantic_version="v2")
+ for parameter in signature.parameters.values()
+ )
+ if any_v1_annotations and any_v2_annotations:
+ msg = (
+ f"Function {func} contains a mix of Pydantic v1 and v2 annotations. "
+ "Only one version of Pydantic annotations per function is supported."
+ )
+ raise NotImplementedError(msg)
+ return any_v1_annotations and not any_v2_annotations
+
+
+class _SchemaConfig:
+ """Configuration for Pydantic models generated from function signatures."""
+
+ extra: str = "forbid"
+ """Whether to allow extra fields in the model."""
+
+ arbitrary_types_allowed: bool = True
+ """Whether to allow arbitrary types in the model."""
+
+
+def create_schema_from_function(
+ model_name: str,
+ func: Callable,
+ *,
+ filter_args: Sequence[str] | None = None,
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = False,
+ include_injected: bool = True,
+) -> type[BaseModel]:
+ """Create a Pydantic schema from a function's signature.
+
+ Args:
+ model_name: Name to assign to the generated Pydantic schema.
+ func: Function to generate the schema from.
+ filter_args: Optional list of arguments to exclude from the schema.
+
+ Defaults to `FILTERED_ARGS`.
+ parse_docstring: Whether to parse the function's docstring for descriptions
+ for each argument.
+ error_on_invalid_docstring: If `parse_docstring` is provided, configure
+ whether to raise `ValueError` on invalid Google Style docstrings.
+ include_injected: Whether to include injected arguments in the schema.
+
+ Defaults to `True`, since we want to include them in the schema when
+ *validating* tool inputs.
+
+ Returns:
+ A Pydantic model with the same arguments as the function.
+ """
+ sig = inspect.signature(func)
+
+ if _function_annotations_are_pydantic_v1(sig, func):
+ validated = validate_arguments_v1(func, config=_SchemaConfig) # type: ignore[call-overload]
+ else:
+ # https://docs.pydantic.dev/latest/usage/validation_decorator/
+ with warnings.catch_warnings():
+ # We are using deprecated functionality here.
+ # This code should be re-written to simply construct a Pydantic model
+ # using inspect.signature and create_model.
+ warnings.simplefilter("ignore", category=PydanticDeprecationWarning)
+ validated = validate_arguments(func, config=_SchemaConfig) # type: ignore[operator]
+
+ # Let's ignore `self` and `cls` arguments for class and instance methods
+ # If qualified name has a ".", then it likely belongs in a class namespace
+ in_class = bool(func.__qualname__ and "." in func.__qualname__)
+
+ has_args = False
+ has_kwargs = False
+
+ for param in sig.parameters.values():
+ if param.kind == param.VAR_POSITIONAL:
+ has_args = True
+ elif param.kind == param.VAR_KEYWORD:
+ has_kwargs = True
+
+ inferred_model = validated.model
+
+ if filter_args:
+ filter_args_ = filter_args
+ else:
+ # Handle classmethods and instance methods
+ existing_params: list[str] = list(sig.parameters.keys())
+ if existing_params and existing_params[0] in {"self", "cls"} and in_class:
+ filter_args_ = [existing_params[0], *list(FILTERED_ARGS)]
+ else:
+ filter_args_ = list(FILTERED_ARGS)
+
+ for existing_param in existing_params:
+ if not include_injected and _is_injected_arg_type(
+ sig.parameters[existing_param].annotation
+ ):
+ filter_args_.append(existing_param)
+
+ description, arg_descriptions = _infer_arg_descriptions(
+ func,
+ parse_docstring=parse_docstring,
+ error_on_invalid_docstring=error_on_invalid_docstring,
+ )
+ # Pydantic adds placeholder virtual fields we need to strip
+ valid_properties = []
+ for field in get_fields(inferred_model):
+ if not has_args and field == "args":
+ continue
+ if not has_kwargs and field == "kwargs":
+ continue
+
+ if field == "v__duplicate_kwargs": # Internal pydantic field
+ continue
+
+ if field not in filter_args_:
+ valid_properties.append(field)
+
+ return _create_subset_model(
+ model_name,
+ inferred_model,
+ list(valid_properties),
+ descriptions=arg_descriptions,
+ fn_description=description,
+ )
+
+
+class ToolException(Exception): # noqa: N818
+ """Exception thrown when a tool execution error occurs.
+
+ This exception allows tools to signal errors without stopping the agent.
+
+ The error is handled according to the tool's `handle_tool_error` setting, and the
+ result is returned as an observation to the agent.
+ """
+
+
+ArgsSchema = TypeBaseModel | dict[str, Any]
+
+_EMPTY_SET: frozenset[str] = frozenset()
+
+
+class BaseTool(RunnableSerializable[str | dict | ToolCall, Any]):
+ """Base class for all LangChain tools.
+
+ This abstract class defines the interface that all LangChain tools must implement.
+
+ Tools are components that can be called by agents to perform specific actions.
+ """
+
+ def __init_subclass__(cls, **kwargs: Any) -> None:
+ """Validate the tool class definition during subclass creation.
+
+ Args:
+ **kwargs: Additional keyword arguments passed to the parent class.
+
+ Raises:
+ SchemaAnnotationError: If `args_schema` has incorrect type annotation.
+ """
+ super().__init_subclass__(**kwargs)
+
+ args_schema_type = cls.__annotations__.get("args_schema", None)
+
+ if args_schema_type is not None and args_schema_type == BaseModel:
+ # Throw errors for common mis-annotations.
+ # TODO: Use get_args / get_origin and fully
+ # specify valid annotations.
+ typehint_mandate = """
+class ChildTool(BaseTool):
+ ...
+ args_schema: Type[BaseModel] = SchemaClass
+ ..."""
+ name = cls.__name__
+ msg = (
+ f"Tool definition for {name} must include valid type annotations"
+ f" for argument 'args_schema' to behave as expected.\n"
+ f"Expected annotation of 'Type[BaseModel]'"
+ f" but got '{args_schema_type}'.\n"
+ f"Expected class looks like:\n"
+ f"{typehint_mandate}"
+ )
+ raise SchemaAnnotationError(msg)
+
+ name: str
+ """The unique name of the tool that clearly communicates its purpose."""
+
+ description: str
+ """Used to tell the model how/when/why to use the tool.
+
+ You can provide few-shot examples as a part of the description.
+ """
+
+ args_schema: Annotated[ArgsSchema | None, SkipValidation()] = Field(
+ default=None, description="The tool schema."
+ )
+ """Pydantic model class to validate and parse the tool's input arguments.
+
+ Args schema should be either:
+
+ - A subclass of `pydantic.BaseModel`.
+ - A subclass of `pydantic.v1.BaseModel` if accessing v1 namespace in pydantic 2
+ - A JSON schema dict
+ """
+
+ return_direct: bool = False
+ """Whether to return the tool's output directly.
+
+ Setting this to `True` means that after the tool is called, the `AgentExecutor` will
+ stop looping.
+ """
+
+ verbose: bool = False
+ """Whether to log the tool's progress."""
+
+ callbacks: Callbacks = Field(default=None, exclude=True)
+ """Callbacks to be called during tool execution."""
+
+ tags: list[str] | None = None
+ """Optional list of tags associated with the tool.
+
+ These tags will be associated with each call to this tool,
+ and passed as arguments to the handlers defined in `callbacks`.
+
+ You can use these to, e.g., identify a specific instance of a tool with its use
+ case.
+ """
+
+ metadata: dict[str, Any] | None = None
+ """Optional metadata associated with the tool.
+
+ This metadata will be associated with each call to this tool,
+ and passed as arguments to the handlers defined in `callbacks`.
+
+ You can use these to, e.g., identify a specific instance of a tool with its usecase.
+ """
+
+ handle_tool_error: bool | str | Callable[[ToolException], str] | None = False
+ """Handle the content of the `ToolException` thrown."""
+
+ handle_validation_error: (
+ bool | str | Callable[[ValidationError | ValidationErrorV1], str] | None
+ ) = False
+ """Handle the content of the `ValidationError` thrown."""
+
+ response_format: Literal["content", "content_and_artifact"] = "content"
+ """The tool response format.
+
+ If `'content'` then the output of the tool is interpreted as the contents of a
+ `ToolMessage`. If `'content_and_artifact'` then the output is expected to be a
+ two-tuple corresponding to the `(content, artifact)` of a `ToolMessage`.
+ """
+
+ extras: dict[str, Any] | None = None
+ """Optional provider-specific extra fields for the tool.
+
+ This is used to pass provider-specific configuration that doesn't fit into
+ standard tool fields.
+
+ Example:
+ Anthropic-specific fields like [`cache_control`](https://docs.langchain.com/oss/python/integrations/chat/anthropic#prompt-caching),
+ [`defer_loading`](https://docs.langchain.com/oss/python/integrations/chat/anthropic#tool-search),
+ or `input_examples`.
+
+ ```python
+ @tool(extras={"defer_loading": True, "cache_control": {"type": "ephemeral"}})
+ def my_tool(x: str) -> str:
+ return x
+ ```
+ """
+
+ def __init__(self, **kwargs: Any) -> None:
+ """Initialize the tool.
+
+ Raises:
+ TypeError: If `args_schema` is not a subclass of pydantic `BaseModel` or
+ `dict`.
+ """
+ if (
+ "args_schema" in kwargs
+ and kwargs["args_schema"] is not None
+ and not is_basemodel_subclass(kwargs["args_schema"])
+ and not isinstance(kwargs["args_schema"], dict)
+ ):
+ msg = (
+ "args_schema must be a subclass of pydantic BaseModel or "
+ f"a JSON schema dict. Got: {kwargs['args_schema']}."
+ )
+ raise TypeError(msg)
+ super().__init__(**kwargs)
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @property
+ def is_single_input(self) -> bool:
+ """Check if the tool accepts only a single input argument.
+
+ Returns:
+ `True` if the tool has only one input argument, `False` otherwise.
+ """
+ keys = {k for k in self.args if k != "kwargs"}
+ return len(keys) == 1
+
+ @property
+ def args(self) -> dict:
+ """Get the tool's input arguments schema.
+
+ Returns:
+ `dict` containing the tool's argument properties.
+ """
+ if isinstance(self.args_schema, dict):
+ json_schema = self.args_schema
+ elif self.args_schema and issubclass(self.args_schema, BaseModelV1):
+ json_schema = self.args_schema.schema()
+ else:
+ input_schema = self.tool_call_schema
+ if isinstance(input_schema, dict):
+ json_schema = input_schema
+ else:
+ json_schema = input_schema.model_json_schema()
+ return cast("dict", json_schema["properties"])
+
+ @property
+ def tool_call_schema(self) -> ArgsSchema:
+ """Get the schema for tool calls, excluding injected arguments.
+
+ Returns:
+ The schema that should be used for tool calls from language models.
+ """
+ if isinstance(self.args_schema, dict):
+ if self.description:
+ return {
+ **self.args_schema,
+ "description": self.description,
+ }
+
+ return self.args_schema
+
+ full_schema = self.get_input_schema()
+ fields = []
+ for name, type_ in get_all_basemodel_annotations(full_schema).items():
+ if not _is_injected_arg_type(type_):
+ fields.append(name)
+ return _create_subset_model(
+ self.name, full_schema, fields, fn_description=self.description
+ )
+
+ @functools.cached_property
+ def _injected_args_keys(self) -> frozenset[str]:
+ # Base implementation doesn't manage injected args
+ return _EMPTY_SET
+
+ # --- Runnable ---
+
+ @override
+ def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
+ """The tool's input schema.
+
+ Args:
+ config: The configuration for the tool.
+
+ Returns:
+ The input schema for the tool.
+ """
+ if self.args_schema is not None:
+ if isinstance(self.args_schema, dict):
+ return super().get_input_schema(config)
+ return self.args_schema
+ return create_schema_from_function(self.name, self._run)
+
+ @override
+ def invoke(
+ self,
+ input: str | dict | ToolCall,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ tool_input, kwargs = _prep_run_args(input, config, **kwargs)
+ return self.run(tool_input, **kwargs)
+
+ @override
+ async def ainvoke(
+ self,
+ input: str | dict | ToolCall,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ tool_input, kwargs = _prep_run_args(input, config, **kwargs)
+ return await self.arun(tool_input, **kwargs)
+
+ # --- Tool ---
+
+ def _parse_input(
+ self, tool_input: str | dict, tool_call_id: str | None
+ ) -> str | dict[str, Any]:
+ """Parse and validate tool input using the args schema.
+
+ Args:
+ tool_input: The raw input to the tool.
+ tool_call_id: The ID of the tool call, if available.
+
+ Returns:
+ The parsed and validated input.
+
+ Raises:
+ ValueError: If `string` input is provided with JSON schema `args_schema`.
+ ValueError: If `InjectedToolCallId` is required but `tool_call_id` is not
+ provided.
+ TypeError: If `args_schema` is not a Pydantic `BaseModel` or dict.
+ """
+ input_args = self.args_schema
+
+ if isinstance(tool_input, str):
+ if input_args is not None:
+ if isinstance(input_args, dict):
+ msg = (
+ "String tool inputs are not allowed when "
+ "using tools with JSON schema args_schema."
+ )
+ raise ValueError(msg)
+ key_ = next(iter(get_fields(input_args).keys()))
+ if issubclass(input_args, BaseModel):
+ input_args.model_validate({key_: tool_input})
+ elif issubclass(input_args, BaseModelV1):
+ input_args.parse_obj({key_: tool_input})
+ else:
+ msg = f"args_schema must be a Pydantic BaseModel, got {input_args}"
+ raise TypeError(msg)
+ return tool_input
+
+ if input_args is not None:
+ if isinstance(input_args, dict):
+ return tool_input
+ if issubclass(input_args, BaseModel):
+ # Check args_schema for InjectedToolCallId
+ for k, v in get_all_basemodel_annotations(input_args).items():
+ if _is_injected_arg_type(v, injected_type=InjectedToolCallId):
+ if tool_call_id is None:
+ msg = (
+ "When tool includes an InjectedToolCallId "
+ "argument, tool must always be invoked with a full "
+ "model ToolCall of the form: {'args': {...}, "
+ "'name': '...', 'type': 'tool_call', "
+ "'tool_call_id': '...'}"
+ )
+ raise ValueError(msg)
+ tool_input[k] = tool_call_id
+ result = input_args.model_validate(tool_input)
+ result_dict = result.model_dump()
+ elif issubclass(input_args, BaseModelV1):
+ # Check args_schema for InjectedToolCallId
+ for k, v in get_all_basemodel_annotations(input_args).items():
+ if _is_injected_arg_type(v, injected_type=InjectedToolCallId):
+ if tool_call_id is None:
+ msg = (
+ "When tool includes an InjectedToolCallId "
+ "argument, tool must always be invoked with a full "
+ "model ToolCall of the form: {'args': {...}, "
+ "'name': '...', 'type': 'tool_call', "
+ "'tool_call_id': '...'}"
+ )
+ raise ValueError(msg)
+ tool_input[k] = tool_call_id
+ result = input_args.parse_obj(tool_input)
+ result_dict = result.dict()
+ else:
+ msg = (
+ f"args_schema must be a Pydantic BaseModel, got {self.args_schema}"
+ )
+ raise NotImplementedError(msg)
+
+ # Include fields from tool_input, plus fields with explicit defaults.
+ # This applies Pydantic defaults (like Field(default=1)) while excluding
+ # synthetic "args"/"kwargs" fields that Pydantic creates for *args/**kwargs.
+ field_info = get_fields(input_args)
+ validated_input = {}
+ for k in result_dict:
+ if k in tool_input:
+ # Field was provided in input - include it (validated)
+ validated_input[k] = getattr(result, k)
+ elif k in field_info and k not in {"args", "kwargs"}:
+ # Check if field has an explicit default defined in the schema.
+ # Exclude "args"/"kwargs" as these are synthetic fields for variadic
+ # parameters that should not be passed as keyword arguments.
+ fi = field_info[k]
+ # Pydantic v2 uses is_required() method, v1 uses required attribute
+ has_default = (
+ not fi.is_required()
+ if hasattr(fi, "is_required")
+ else not getattr(fi, "required", True)
+ )
+ if has_default:
+ validated_input[k] = getattr(result, k)
+
+ for k in self._injected_args_keys:
+ if k in tool_input:
+ validated_input[k] = tool_input[k]
+ elif k == "tool_call_id":
+ if tool_call_id is None:
+ msg = (
+ "When tool includes an InjectedToolCallId "
+ "argument, tool must always be invoked with a full "
+ "model ToolCall of the form: {'args': {...}, "
+ "'name': '...', 'type': 'tool_call', "
+ "'tool_call_id': '...'}"
+ )
+ raise ValueError(msg)
+ validated_input[k] = tool_call_id
+
+ return validated_input
+
+ return tool_input
+
+ @abstractmethod
+ def _run(self, *args: Any, **kwargs: Any) -> Any:
+ """Use the tool.
+
+ Add `run_manager: CallbackManagerForToolRun | None = None` to child
+ implementations to enable tracing.
+
+ Returns:
+ The result of the tool execution.
+ """
+
+ async def _arun(self, *args: Any, **kwargs: Any) -> Any:
+ """Use the tool asynchronously.
+
+ Add `run_manager: AsyncCallbackManagerForToolRun | None = None` to child
+ implementations to enable tracing.
+
+ Returns:
+ The result of the tool execution.
+ """
+ if kwargs.get("run_manager") and signature(self._run).parameters.get(
+ "run_manager"
+ ):
+ kwargs["run_manager"] = kwargs["run_manager"].get_sync()
+ return await run_in_executor(None, self._run, *args, **kwargs)
+
+ def _filter_injected_args(self, tool_input: dict) -> dict:
+ """Filter out injected tool arguments from the input dictionary.
+
+ Injected arguments are those annotated with `InjectedToolArg` or its
+ subclasses, or arguments in `FILTERED_ARGS` like `run_manager` and callbacks.
+
+ Args:
+ tool_input: The tool input dictionary to filter.
+
+ Returns:
+ A filtered dictionary with injected arguments removed.
+ """
+ # Start with filtered args from the constant
+ filtered_keys = set[str](FILTERED_ARGS)
+
+ # Add injected args from function signature (e.g., ToolRuntime parameters)
+ filtered_keys.update(self._injected_args_keys)
+
+ # If we have an args_schema, use it to identify injected args
+ # Skip if args_schema is a dict (JSON Schema) as it's not a Pydantic model
+ if self.args_schema is not None and not isinstance(self.args_schema, dict):
+ try:
+ annotations = get_all_basemodel_annotations(self.args_schema)
+ for field_name, field_type in annotations.items():
+ if _is_injected_arg_type(field_type):
+ filtered_keys.add(field_name)
+ except Exception:
+ # If we can't get annotations, just use FILTERED_ARGS
+ _logger.debug(
+ "Failed to get args_schema annotations for filtering.",
+ exc_info=True,
+ )
+
+ # Filter out the injected keys from tool_input
+ return {k: v for k, v in tool_input.items() if k not in filtered_keys}
+
+ def _to_args_and_kwargs(
+ self, tool_input: str | dict, tool_call_id: str | None
+ ) -> tuple[tuple, dict]:
+ """Convert tool input to positional and keyword arguments.
+
+ Args:
+ tool_input: The input to the tool.
+ tool_call_id: The ID of the tool call, if available.
+
+ Returns:
+ A tuple of `(positional_args, keyword_args)` for the tool.
+
+ Raises:
+ TypeError: If the tool input type is invalid.
+ """
+ if (
+ self.args_schema is not None
+ and isinstance(self.args_schema, type)
+ and is_basemodel_subclass(self.args_schema)
+ and not get_fields(self.args_schema)
+ ):
+ # StructuredTool with no args
+ return (), {}
+ tool_input = self._parse_input(tool_input, tool_call_id)
+ # For backwards compatibility, if run_input is a string,
+ # pass as a positional argument.
+ if isinstance(tool_input, str):
+ return (tool_input,), {}
+ if isinstance(tool_input, dict):
+ # Make a shallow copy of the input to allow downstream code
+ # to modify the root level of the input without affecting the
+ # original input.
+ # This is used by the tool to inject run time information like
+ # the callback manager.
+ return (), tool_input.copy()
+ # This code path is not expected to be reachable.
+ msg = f"Invalid tool input type: {type(tool_input)}"
+ raise TypeError(msg)
+
+ def run(
+ self,
+ tool_input: str | dict[str, Any],
+ verbose: bool | None = None, # noqa: FBT001
+ start_color: str | None = "green",
+ color: str | None = "green",
+ callbacks: Callbacks = None,
+ *,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_name: str | None = None,
+ run_id: uuid.UUID | None = None,
+ config: RunnableConfig | None = None,
+ tool_call_id: str | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run the tool.
+
+ Args:
+ tool_input: The input to the tool.
+ verbose: Whether to log the tool's progress.
+ start_color: The color to use when starting the tool.
+ color: The color to use when ending the tool.
+ callbacks: Callbacks to be called during tool execution.
+ tags: Optional list of tags associated with the tool.
+ metadata: Optional metadata associated with the tool.
+ run_name: The name of the run.
+ run_id: The id of the run.
+ config: The configuration for the tool.
+ tool_call_id: The id of the tool call.
+ **kwargs: Keyword arguments to be passed to tool callbacks (event handler)
+
+ Returns:
+ The output of the tool.
+
+ Raises:
+ ToolException: If an error occurs during tool execution.
+ """
+ callback_manager = CallbackManager.configure(
+ callbacks,
+ self.callbacks,
+ self.verbose or bool(verbose),
+ tags,
+ self.tags,
+ metadata,
+ self.metadata,
+ )
+
+ # Filter out injected arguments from callback inputs
+ filtered_tool_input = (
+ self._filter_injected_args(tool_input)
+ if isinstance(tool_input, dict)
+ else None
+ )
+
+ # Use filtered inputs for the input_str parameter as well
+ tool_input_str = (
+ tool_input
+ if isinstance(tool_input, str)
+ else str(
+ filtered_tool_input if filtered_tool_input is not None else tool_input
+ )
+ )
+
+ run_manager = callback_manager.on_tool_start(
+ {"name": self.name, "description": self.description},
+ tool_input_str,
+ color=start_color,
+ name=run_name,
+ run_id=run_id,
+ inputs=filtered_tool_input,
+ tool_call_id=tool_call_id,
+ **kwargs,
+ )
+
+ content = None
+ artifact = None
+ status = "success"
+ error_to_raise: Exception | KeyboardInterrupt | None = None
+ try:
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ tool_args, tool_kwargs = self._to_args_and_kwargs(
+ tool_input, tool_call_id
+ )
+ if signature(self._run).parameters.get("run_manager"):
+ tool_kwargs |= {"run_manager": run_manager}
+ if config_param := _get_runnable_config_param(self._run):
+ tool_kwargs |= {config_param: config}
+ response = context.run(self._run, *tool_args, **tool_kwargs)
+ if self.response_format == "content_and_artifact":
+ msg = (
+ "Since response_format='content_and_artifact' "
+ "a two-tuple of the message content and raw tool output is "
+ f"expected. Instead, generated response is of type: "
+ f"{type(response)}."
+ )
+ if not isinstance(response, tuple):
+ error_to_raise = ValueError(msg)
+ else:
+ try:
+ content, artifact = response
+ except ValueError:
+ error_to_raise = ValueError(msg)
+ else:
+ content = response
+ except (ValidationError, ValidationErrorV1) as e:
+ if not self.handle_validation_error:
+ error_to_raise = e
+ else:
+ content = _handle_validation_error(e, flag=self.handle_validation_error)
+ status = "error"
+ except ToolException as e:
+ if not self.handle_tool_error:
+ error_to_raise = e
+ else:
+ content = _handle_tool_error(e, flag=self.handle_tool_error)
+ status = "error"
+ except (Exception, KeyboardInterrupt) as e:
+ error_to_raise = e
+
+ if error_to_raise:
+ run_manager.on_tool_error(error_to_raise, tool_call_id=tool_call_id)
+ raise error_to_raise
+ output = _format_output(content, artifact, tool_call_id, self.name, status)
+ run_manager.on_tool_end(output, color=color, name=self.name, **kwargs)
+ return output
+
+ async def arun(
+ self,
+ tool_input: str | dict,
+ verbose: bool | None = None, # noqa: FBT001
+ start_color: str | None = "green",
+ color: str | None = "green",
+ callbacks: Callbacks = None,
+ *,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_name: str | None = None,
+ run_id: uuid.UUID | None = None,
+ config: RunnableConfig | None = None,
+ tool_call_id: str | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Run the tool asynchronously.
+
+ Args:
+ tool_input: The input to the tool.
+ verbose: Whether to log the tool's progress.
+ start_color: The color to use when starting the tool.
+ color: The color to use when ending the tool.
+ callbacks: Callbacks to be called during tool execution.
+ tags: Optional list of tags associated with the tool.
+ metadata: Optional metadata associated with the tool.
+ run_name: The name of the run.
+ run_id: The id of the run.
+ config: The configuration for the tool.
+ tool_call_id: The id of the tool call.
+ **kwargs: Keyword arguments to be passed to tool callbacks
+
+ Returns:
+ The output of the tool.
+
+ Raises:
+ ToolException: If an error occurs during tool execution.
+ """
+ callback_manager = AsyncCallbackManager.configure(
+ callbacks,
+ self.callbacks,
+ self.verbose or bool(verbose),
+ tags,
+ self.tags,
+ metadata,
+ self.metadata,
+ )
+
+ # Filter out injected arguments from callback inputs
+ filtered_tool_input = (
+ self._filter_injected_args(tool_input)
+ if isinstance(tool_input, dict)
+ else None
+ )
+
+ # Use filtered inputs for the input_str parameter as well
+ tool_input_str = (
+ tool_input
+ if isinstance(tool_input, str)
+ else str(
+ filtered_tool_input if filtered_tool_input is not None else tool_input
+ )
+ )
+
+ run_manager = await callback_manager.on_tool_start(
+ {"name": self.name, "description": self.description},
+ tool_input_str,
+ color=start_color,
+ name=run_name,
+ run_id=run_id,
+ inputs=filtered_tool_input,
+ tool_call_id=tool_call_id,
+ **kwargs,
+ )
+ content = None
+ artifact = None
+ status = "success"
+ error_to_raise: Exception | KeyboardInterrupt | None = None
+ try:
+ tool_args, tool_kwargs = self._to_args_and_kwargs(tool_input, tool_call_id)
+ child_config = patch_config(config, callbacks=run_manager.get_child())
+ with set_config_context(child_config) as context:
+ func_to_check = (
+ self._run if self.__class__._arun is BaseTool._arun else self._arun # noqa: SLF001
+ )
+ if signature(func_to_check).parameters.get("run_manager"):
+ tool_kwargs["run_manager"] = run_manager
+ if config_param := _get_runnable_config_param(func_to_check):
+ tool_kwargs[config_param] = config
+
+ coro = self._arun(*tool_args, **tool_kwargs)
+ response = await coro_with_context(coro, context)
+ if self.response_format == "content_and_artifact":
+ msg = (
+ "Since response_format='content_and_artifact' "
+ "a two-tuple of the message content and raw tool output is "
+ f"expected. Instead, generated response is of type: "
+ f"{type(response)}."
+ )
+ if not isinstance(response, tuple):
+ error_to_raise = ValueError(msg)
+ else:
+ try:
+ content, artifact = response
+ except ValueError:
+ error_to_raise = ValueError(msg)
+ else:
+ content = response
+ except ValidationError as e:
+ if not self.handle_validation_error:
+ error_to_raise = e
+ else:
+ content = _handle_validation_error(e, flag=self.handle_validation_error)
+ status = "error"
+ except ToolException as e:
+ if not self.handle_tool_error:
+ error_to_raise = e
+ else:
+ content = _handle_tool_error(e, flag=self.handle_tool_error)
+ status = "error"
+ except (Exception, KeyboardInterrupt) as e:
+ error_to_raise = e
+
+ if error_to_raise:
+ await run_manager.on_tool_error(error_to_raise, tool_call_id=tool_call_id)
+ raise error_to_raise
+
+ output = _format_output(content, artifact, tool_call_id, self.name, status)
+ await run_manager.on_tool_end(output, color=color, name=self.name, **kwargs)
+ return output
+
+
+def _is_tool_call(x: Any) -> bool:
+ """Check if the input is a tool call dictionary.
+
+ Args:
+ x: The input to check.
+
+ Returns:
+ `True` if the input is a tool call, `False` otherwise.
+ """
+ return isinstance(x, dict) and x.get("type") == "tool_call"
+
+
+def _handle_validation_error(
+ e: ValidationError | ValidationErrorV1,
+ *,
+ flag: Literal[True] | str | Callable[[ValidationError | ValidationErrorV1], str],
+) -> str:
+ """Handle validation errors based on the configured flag.
+
+ Args:
+ e: The validation error that occurred.
+ flag: How to handle the error (`bool`, `str`, or `Callable`).
+
+ Returns:
+ The error message to return.
+
+ Raises:
+ ValueError: If the flag type is unexpected.
+ """
+ if isinstance(flag, bool):
+ content = "Tool input validation error"
+ elif isinstance(flag, str):
+ content = flag
+ elif callable(flag):
+ content = flag(e)
+ else:
+ msg = (
+ f"Got unexpected type of `handle_validation_error`. Expected bool, "
+ f"str or callable. Received: {flag}"
+ )
+ raise ValueError(msg) # noqa: TRY004
+ return content
+
+
+def _handle_tool_error(
+ e: ToolException,
+ *,
+ flag: Literal[True] | str | Callable[[ToolException], str] | None,
+) -> str:
+ """Handle tool execution errors based on the configured flag.
+
+ Args:
+ e: The tool exception that occurred.
+ flag: How to handle the error (`bool`, `str`, or `Callable`).
+
+ Returns:
+ The error message to return.
+
+ Raises:
+ ValueError: If the flag type is unexpected.
+ """
+ if isinstance(flag, bool):
+ content = e.args[0] if e.args else "Tool execution error"
+ elif isinstance(flag, str):
+ content = flag
+ elif callable(flag):
+ content = flag(e)
+ else:
+ msg = (
+ f"Got unexpected type of `handle_tool_error`. Expected bool, str "
+ f"or callable. Received: {flag}"
+ )
+ raise ValueError(msg) # noqa: TRY004
+ return content
+
+
+def _prep_run_args(
+ value: str | dict | ToolCall,
+ config: RunnableConfig | None,
+ **kwargs: Any,
+) -> tuple[str | dict, dict]:
+ """Prepare arguments for tool execution.
+
+ Args:
+ value: The input value (`str`, `dict`, or `ToolCall`).
+ config: The runnable configuration.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ A tuple of `(tool_input, run_kwargs)`.
+ """
+ config = ensure_config(config)
+ if _is_tool_call(value):
+ tool_call_id: str | None = cast("ToolCall", value)["id"]
+ tool_input: str | dict = cast("ToolCall", value)["args"].copy()
+ else:
+ tool_call_id = None
+ tool_input = cast("str | dict", value)
+ return (
+ tool_input,
+ dict(
+ callbacks=config.get("callbacks"),
+ tags=config.get("tags"),
+ metadata=config.get("metadata"),
+ run_name=config.get("run_name"),
+ run_id=config.pop("run_id", None),
+ config=config,
+ tool_call_id=tool_call_id,
+ **kwargs,
+ ),
+ )
+
+
+def _format_output(
+ content: Any,
+ artifact: Any,
+ tool_call_id: str | None,
+ name: str,
+ status: str,
+) -> ToolOutputMixin | Any:
+ """Format tool output as a `ToolMessage` if appropriate.
+
+ Args:
+ content: The main content of the tool output.
+ artifact: Any artifact data from the tool.
+ tool_call_id: The ID of the tool call.
+ name: The name of the tool.
+ status: The execution status.
+
+ Returns:
+ The formatted output, either as a `ToolMessage`, the original content,
+ or an unchanged list of `ToolOutputMixin` instances.
+ """
+ if (
+ isinstance(content, list)
+ and content
+ and all(isinstance(item, ToolOutputMixin) for item in content)
+ ):
+ return content
+ if isinstance(content, ToolOutputMixin) or tool_call_id is None:
+ return content
+ if not _is_message_content_type(content):
+ content = _stringify(content)
+ return ToolMessage(
+ content,
+ artifact=artifact,
+ tool_call_id=tool_call_id,
+ name=name,
+ status=status,
+ )
+
+
+def _is_message_content_type(obj: Any) -> bool:
+ """Check if object is valid message content format.
+
+ Validates content for OpenAI or Anthropic format tool messages.
+
+ Args:
+ obj: The object to check.
+
+ Returns:
+ `True` if the object is valid message content, `False` otherwise.
+ """
+ return isinstance(obj, str) or (
+ isinstance(obj, list) and all(_is_message_content_block(e) for e in obj)
+ )
+
+
+def _is_message_content_block(obj: Any) -> bool:
+ """Check if object is a valid message content block.
+
+ Validates content blocks for OpenAI or Anthropic format.
+
+ Args:
+ obj: The object to check.
+
+ Returns:
+ `True` if the object is a valid content block, `False` otherwise.
+ """
+ if isinstance(obj, str):
+ return True
+ if isinstance(obj, dict):
+ return obj.get("type", None) in TOOL_MESSAGE_BLOCK_TYPES
+ return False
+
+
+def _stringify(content: Any) -> str:
+ """Convert content to string, preferring JSON format.
+
+ Args:
+ content: The content to stringify.
+
+ Returns:
+ String representation of the content.
+ """
+ try:
+ return json.dumps(content, ensure_ascii=False)
+ except Exception:
+ return str(content)
+
+
+def _get_type_hints(func: Callable) -> dict[str, type] | None:
+ """Get type hints from a function, handling partial functions.
+
+ Args:
+ func: The function to get type hints from.
+
+ Returns:
+ `dict` of type hints, or `None` if extraction fails.
+ """
+ if isinstance(func, functools.partial):
+ func = func.func
+ try:
+ return get_type_hints(func)
+ except Exception:
+ return None
+
+
+def _get_runnable_config_param(func: Callable) -> str | None:
+ """Find the parameter name for `RunnableConfig` in a function.
+
+ Args:
+ func: The function to check.
+
+ Returns:
+ The parameter name for `RunnableConfig`, or `None` if not found.
+ """
+ type_hints = _get_type_hints(func)
+ if not type_hints:
+ return None
+ for name, type_ in type_hints.items():
+ if type_ is RunnableConfig:
+ return name
+ return None
+
+
+class InjectedToolArg:
+ """Annotation for tool arguments that are injected at runtime.
+
+ Tool arguments annotated with this class are not included in the tool
+ schema sent to language models and are instead injected during execution.
+ """
+
+
+class _DirectlyInjectedToolArg:
+ """Annotation for tool arguments that are injected at runtime.
+
+ Injected via direct type annotation, rather than annotated metadata.
+
+ For example, `ToolRuntime` is a directly injected argument.
+
+ Note the direct annotation rather than the verbose alternative:
+ `Annotated[ToolRuntime, InjectedRuntime]`
+
+ ```python
+ from langchain_core.tools import tool, ToolRuntime
+
+
+ @tool
+ def foo(x: int, runtime: ToolRuntime) -> str:
+ # use runtime.state, runtime.context, runtime.store, etc.
+ ...
+ ```
+ """
+
+
+class InjectedToolCallId(InjectedToolArg):
+ """Annotation for injecting the tool call ID.
+
+ This annotation is used to mark a tool parameter that should receive the tool call
+ ID at runtime.
+
+ ```python
+ from typing import Annotated
+ from langchain_core.messages import ToolMessage
+ from langchain_core.tools import tool, InjectedToolCallId
+
+ @tool
+ def foo(
+ x: int, tool_call_id: Annotated[str, InjectedToolCallId]
+ ) -> ToolMessage:
+ \"\"\"Return x.\"\"\"
+ return ToolMessage(
+ str(x),
+ artifact=x,
+ name="foo",
+ tool_call_id=tool_call_id
+ )
+ ```
+ """
+
+
+def _is_directly_injected_arg_type(type_: Any) -> bool:
+ """Check if a type annotation indicates a directly injected argument.
+
+ This is currently only used for `ToolRuntime`.
+
+ Checks if either the annotation itself is a subclass of `_DirectlyInjectedToolArg`
+ or the origin of the annotation is a subclass of `_DirectlyInjectedToolArg`.
+
+ For example, `ToolRuntime` or `ToolRuntime[ContextT, StateT]` would both return
+ `True`.
+ """
+ return (
+ isinstance(type_, type) and issubclass(type_, _DirectlyInjectedToolArg)
+ ) or (
+ (origin := get_origin(type_)) is not None
+ and isinstance(origin, type)
+ and issubclass(origin, _DirectlyInjectedToolArg)
+ )
+
+
+def _is_injected_arg_type(
+ type_: type | TypeVar, injected_type: type[InjectedToolArg] | None = None
+) -> bool:
+ """Check if a type annotation indicates an injected argument.
+
+ Args:
+ type_: The type annotation to check.
+ injected_type: The specific injected type to check for.
+
+ Returns:
+ `True` if the type is an injected argument, `False` otherwise.
+ """
+ if injected_type is None:
+ # if no injected type is specified,
+ # check if the type is a directly injected argument
+ if _is_directly_injected_arg_type(type_):
+ return True
+ injected_type = InjectedToolArg
+
+ # if the type is an Annotated type, check if annotated metadata
+ # is an intance or subclass of the injected type
+ return any(
+ isinstance(arg, injected_type)
+ or (isinstance(arg, type) and issubclass(arg, injected_type))
+ for arg in get_args(type_)[1:]
+ )
+
+
+def get_all_basemodel_annotations(
+ cls: TypeBaseModel | Any, *, default_to_bound: bool = True
+) -> dict[str, type | TypeVar]:
+ """Get all annotations from a Pydantic `BaseModel` and its parents.
+
+ Args:
+ cls: The Pydantic `BaseModel` class.
+ default_to_bound: Whether to default to the bound of a `TypeVar` if it exists.
+
+ Returns:
+ `dict` of field names to their type annotations.
+ """
+ # cls has no subscript: cls = FooBar
+ if isinstance(cls, type):
+ fields = get_fields(cls)
+ alias_map = {field.alias: name for name, field in fields.items() if field.alias}
+
+ annotations: dict[str, type | TypeVar] = {}
+ for name, param in inspect.signature(cls).parameters.items():
+ # Exclude hidden init args added by pydantic Config. For example if
+ # BaseModel(extra="allow") then "extra_data" will part of init sig.
+ if name not in fields and name not in alias_map:
+ continue
+ field_name = alias_map.get(name, name)
+ annotations[field_name] = param.annotation
+ orig_bases: tuple = getattr(cls, "__orig_bases__", ())
+ # cls has subscript: cls = FooBar[int]
+ else:
+ annotations = get_all_basemodel_annotations(
+ get_origin(cls), default_to_bound=False
+ )
+ orig_bases = (cls,)
+
+ # Pydantic v2 automatically resolves inherited generics, Pydantic v1 does not.
+ if not (isinstance(cls, type) and is_pydantic_v2_subclass(cls)):
+ # if cls = FooBar inherits from Baz[str], orig_bases will contain Baz[str]
+ # if cls = FooBar inherits from Baz, orig_bases will contain Baz
+ # if cls = FooBar[int], orig_bases will contain FooBar[int]
+ for parent in orig_bases:
+ # if class = FooBar inherits from Baz, parent = Baz
+ if isinstance(parent, type) and is_pydantic_v1_subclass(parent):
+ annotations.update(
+ get_all_basemodel_annotations(parent, default_to_bound=False)
+ )
+ continue
+
+ parent_origin = get_origin(parent)
+
+ # if class = FooBar inherits from non-pydantic class
+ if not parent_origin:
+ continue
+
+ # if class = FooBar inherits from Baz[str]:
+ # parent = class Baz[str],
+ # parent_origin = class Baz,
+ # generic_type_vars = (type vars in Baz)
+ # generic_map = {type var in Baz: str}
+ generic_type_vars: tuple = getattr(parent_origin, "__parameters__", ())
+ generic_map = dict(zip(generic_type_vars, get_args(parent), strict=False))
+ for field in getattr(parent_origin, "__annotations__", {}):
+ annotations[field] = _replace_type_vars(
+ annotations[field], generic_map, default_to_bound=default_to_bound
+ )
+
+ return {
+ k: _replace_type_vars(v, default_to_bound=default_to_bound)
+ for k, v in annotations.items()
+ }
+
+
+def _replace_type_vars(
+ type_: type | TypeVar,
+ generic_map: dict[TypeVar, type] | None = None,
+ *,
+ default_to_bound: bool = True,
+) -> type | TypeVar:
+ """Replace `TypeVar`s in a type annotation with concrete types.
+
+ Args:
+ type_: The type annotation to process.
+ generic_map: Mapping of `TypeVar`s to concrete types.
+ default_to_bound: Whether to use `TypeVar` bounds as defaults.
+
+ Returns:
+ The type with `TypeVar`s replaced.
+ """
+ generic_map = generic_map or {}
+ if isinstance(type_, TypeVar):
+ if type_ in generic_map:
+ return generic_map[type_]
+ if default_to_bound:
+ return type_.__bound__ if type_.__bound__ is not None else Any
+ return type_
+ if (origin := get_origin(type_)) and (args := get_args(type_)):
+ new_args = tuple(
+ _replace_type_vars(arg, generic_map, default_to_bound=default_to_bound)
+ for arg in args
+ )
+ return cast("type", _py_38_safe_origin(origin)[new_args]) # type: ignore[index]
+ return type_
+
+
+class BaseToolkit(BaseModel, ABC):
+ """Base class for toolkits containing related tools.
+
+ A toolkit is a collection of related tools that can be used together to accomplish a
+ specific task or work with a particular system.
+ """
+
+ @abstractmethod
+ def get_tools(self) -> list[BaseTool]:
+ """Get all tools in the toolkit.
+
+ Returns:
+ List of tools contained in this toolkit.
+ """
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/convert.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..48c518a29822aebfac0cf7ccb871a614ae888cdc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/convert.py
@@ -0,0 +1,476 @@
+"""Convert functions and runnables to tools."""
+
+import inspect
+from collections.abc import Callable
+from typing import Any, Literal, cast, get_type_hints, overload
+
+from pydantic import BaseModel, Field, create_model
+
+from langchain_core.callbacks import Callbacks
+from langchain_core.runnables import Runnable
+from langchain_core.tools.base import ArgsSchema, BaseTool
+from langchain_core.tools.simple import Tool
+from langchain_core.tools.structured import StructuredTool
+
+
+@overload
+def tool(
+ *,
+ description: str | None = None,
+ return_direct: bool = False,
+ args_schema: ArgsSchema | None = None,
+ infer_schema: bool = True,
+ response_format: Literal["content", "content_and_artifact"] = "content",
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = True,
+ extras: dict[str, Any] | None = None,
+) -> Callable[[Callable | Runnable], BaseTool]: ...
+
+
+@overload
+def tool(
+ name_or_callable: str,
+ runnable: Runnable,
+ *,
+ description: str | None = None,
+ return_direct: bool = False,
+ args_schema: ArgsSchema | None = None,
+ infer_schema: bool = True,
+ response_format: Literal["content", "content_and_artifact"] = "content",
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = True,
+ extras: dict[str, Any] | None = None,
+) -> BaseTool: ...
+
+
+@overload
+def tool(
+ name_or_callable: Callable,
+ *,
+ description: str | None = None,
+ return_direct: bool = False,
+ args_schema: ArgsSchema | None = None,
+ infer_schema: bool = True,
+ response_format: Literal["content", "content_and_artifact"] = "content",
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = True,
+ extras: dict[str, Any] | None = None,
+) -> BaseTool: ...
+
+
+@overload
+def tool(
+ name_or_callable: str,
+ *,
+ description: str | None = None,
+ return_direct: bool = False,
+ args_schema: ArgsSchema | None = None,
+ infer_schema: bool = True,
+ response_format: Literal["content", "content_and_artifact"] = "content",
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = True,
+ extras: dict[str, Any] | None = None,
+) -> Callable[[Callable | Runnable], BaseTool]: ...
+
+
+def tool(
+ name_or_callable: str | Callable | None = None,
+ runnable: Runnable | None = None,
+ *args: Any,
+ description: str | None = None,
+ return_direct: bool = False,
+ args_schema: ArgsSchema | None = None,
+ infer_schema: bool = True,
+ response_format: Literal["content", "content_and_artifact"] = "content",
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = True,
+ extras: dict[str, Any] | None = None,
+) -> BaseTool | Callable[[Callable | Runnable], BaseTool]:
+ """Convert Python functions and `Runnables` to LangChain tools.
+
+ Can be used as a decorator with or without arguments to create tools from functions.
+
+ Functions can have any signature - the tool will automatically infer input schemas
+ unless disabled.
+
+ !!! note "Requirements"
+
+ - Functions should have type hints for proper schema inference.
+ - Functions may accept multiple arguments and return types are flexible;
+ outputs will be serialized if needed.
+ - When using with `Runnable`, a string name must be provided.
+
+ Args:
+ name_or_callable: Optional name of the tool or the `Callable` to be
+ converted to a tool.
+
+ Overrides the function's name.
+
+ Must be provided as a positional argument.
+ runnable: Optional `Runnable` to convert to a tool.
+
+ Must be provided as a positional argument.
+ description: Optional description for the tool.
+
+ Precedence for the tool description value is as follows:
+
+ - This `description` argument (used even if docstring and/or `args_schema`
+ are provided)
+ - Tool function docstring (used even if `args_schema` is provided)
+ - `args_schema` description (used only if `description` and docstring are
+ not provided)
+ *args: Extra positional arguments.
+
+ Must be empty.
+ return_direct: Whether to return directly from the tool rather than continuing
+ the agent loop.
+ args_schema: Optional argument schema for user to specify.
+ infer_schema: Whether to infer the schema of the arguments from the function's
+ signature.
+
+ This also makes the resultant tool accept a dictionary input to its `run()`
+ function.
+ response_format: The tool response format.
+
+ If `'content'`, then the output of the tool is interpreted as the contents
+ of a `ToolMessage`.
+
+ If `'content_and_artifact'`, then the output is expected to be a two-tuple
+ corresponding to the `(content, artifact)` of a `ToolMessage`.
+ parse_docstring: If `infer_schema` and `parse_docstring`, will attempt to
+ parse parameter descriptions from Google Style function docstrings.
+ error_on_invalid_docstring: If `parse_docstring` is provided, configure
+ whether to raise `ValueError` on invalid Google Style docstrings.
+ extras: Optional provider-specific extra fields for the tool.
+
+ Used to pass configuration that doesn't fit into standard tool fields.
+ Chat models should process known extras when constructing model payloads.
+
+ !!! example
+
+ For example, Anthropic-specific fields like `cache_control`,
+ `defer_loading`, or `input_examples`.
+
+ Raises:
+ ValueError: If too many positional arguments are provided (e.g. violating the
+ `*args` constraint).
+ ValueError: If a `Runnable` is provided without a string name. When using `tool`
+ with a `Runnable`, a `str` name must be provided as the `name_or_callable`.
+ ValueError: If the first argument is not a string or callable with
+ a `__name__` attribute.
+ ValueError: If the function does not have a docstring and description
+ is not provided and `infer_schema` is `False`.
+ ValueError: If `parse_docstring` is `True` and the function has an invalid
+ Google-style docstring and `error_on_invalid_docstring` is True.
+ ValueError: If a `Runnable` is provided that does not have an object schema.
+
+ Returns:
+ The tool.
+
+ Examples:
+ ```python
+ @tool
+ def search_api(query: str) -> str:
+ # Searches the API for the query.
+ return
+
+
+ @tool("search", return_direct=True)
+ def search_api(query: str) -> str:
+ # Searches the API for the query.
+ return
+
+
+ @tool(response_format="content_and_artifact")
+ def search_api(query: str) -> tuple[str, dict]:
+ return "partial json of results", {"full": "object of results"}
+ ```
+
+ Parse Google-style docstrings:
+
+ ```python
+ @tool(parse_docstring=True)
+ def foo(bar: str, baz: int) -> str:
+ \"\"\"The foo.
+
+ Args:
+ bar: The bar.
+ baz: The baz.
+ \"\"\"
+ return bar
+
+ foo.args_schema.model_json_schema()
+ ```
+
+ ```python
+ {
+ "title": "foo",
+ "description": "The foo.",
+ "type": "object",
+ "properties": {
+ "bar": {
+ "title": "Bar",
+ "description": "The bar.",
+ "type": "string",
+ },
+ "baz": {
+ "title": "Baz",
+ "description": "The baz.",
+ "type": "integer",
+ },
+ },
+ "required": ["bar", "baz"],
+ }
+ ```
+
+ Note that parsing by default will raise `ValueError` if the docstring is
+ considered invalid. A docstring is considered invalid if it contains arguments
+ not in the function signature, or is unable to be parsed into a summary and
+ `'Args:'` blocks. Examples below:
+
+ ```python
+ # No args section
+ def invalid_docstring_1(bar: str, baz: int) -> str:
+ \"\"\"The foo.\"\"\"
+ return bar
+
+ # Improper whitespace between summary and args section
+ def invalid_docstring_2(bar: str, baz: int) -> str:
+ \"\"\"The foo.
+ Args:
+ bar: The bar.
+ baz: The baz.
+ \"\"\"
+ return bar
+
+ # Documented args absent from function signature
+ def invalid_docstring_3(bar: str, baz: int) -> str:
+ \"\"\"The foo.
+
+ Args:
+ banana: The bar.
+ monkey: The baz.
+ \"\"\"
+ return bar
+
+ ```
+ """ # noqa: D214, D410, D411 # We're intentionally showing bad formatting in examples
+
+ def _create_tool_factory(
+ tool_name: str,
+ ) -> Callable[[Callable | Runnable], BaseTool]:
+ """Create a decorator that takes a callable and returns a tool.
+
+ Args:
+ tool_name: The name that will be assigned to the tool.
+
+ Returns:
+ A function that takes a callable or `Runnable` and returns a tool.
+ """
+
+ def _tool_factory(dec_func: Callable | Runnable) -> BaseTool:
+ tool_description = description
+ if isinstance(dec_func, Runnable):
+ runnable = dec_func
+
+ if runnable.input_schema.model_json_schema().get("type") != "object":
+ msg = "Runnable must have an object schema."
+ raise ValueError(msg)
+
+ async def ainvoke_wrapper(
+ callbacks: Callbacks | None = None, **kwargs: Any
+ ) -> Any:
+ return await runnable.ainvoke(kwargs, {"callbacks": callbacks})
+
+ def invoke_wrapper(
+ callbacks: Callbacks | None = None, **kwargs: Any
+ ) -> Any:
+ return runnable.invoke(kwargs, {"callbacks": callbacks})
+
+ coroutine = ainvoke_wrapper
+ func = invoke_wrapper
+ schema: ArgsSchema | None = runnable.input_schema
+ tool_description = description or repr(runnable)
+ elif inspect.iscoroutinefunction(dec_func):
+ coroutine = dec_func
+ func = None
+ schema = args_schema
+ else:
+ coroutine = None
+ func = dec_func
+ schema = args_schema
+
+ if infer_schema or args_schema is not None:
+ return StructuredTool.from_function(
+ func,
+ coroutine,
+ name=tool_name,
+ description=tool_description,
+ return_direct=return_direct,
+ args_schema=schema,
+ infer_schema=infer_schema,
+ response_format=response_format,
+ parse_docstring=parse_docstring,
+ error_on_invalid_docstring=error_on_invalid_docstring,
+ extras=extras,
+ )
+ # If someone doesn't want a schema applied, we must treat it as
+ # a simple string->string function
+ if dec_func.__doc__ is None:
+ msg = (
+ "Function must have a docstring if "
+ "description not provided and infer_schema is False."
+ )
+ raise ValueError(msg)
+ return Tool(
+ name=tool_name,
+ func=func,
+ description=f"{tool_name} tool",
+ return_direct=return_direct,
+ coroutine=coroutine,
+ response_format=response_format,
+ extras=extras,
+ )
+
+ return _tool_factory
+
+ if len(args) != 0:
+ # Triggered if a user attempts to use positional arguments that
+ # do not exist in the function signature
+ # e.g., @tool("name", runnable, "extra_arg")
+ # Here, "extra_arg" is not a valid argument
+ msg = "Too many arguments for tool decorator. A decorator "
+ raise ValueError(msg)
+
+ if runnable is not None:
+ # tool is used as a function
+ # for instance tool_from_runnable = tool("name", runnable)
+ if not name_or_callable:
+ msg = "Runnable without name for tool constructor"
+ raise ValueError(msg)
+ if not isinstance(name_or_callable, str):
+ msg = "Name must be a string for tool constructor"
+ raise ValueError(msg)
+ return _create_tool_factory(name_or_callable)(runnable)
+ if name_or_callable is not None:
+ if callable(name_or_callable) and hasattr(name_or_callable, "__name__"):
+ # Used as a decorator without parameters
+ # @tool
+ # def my_tool():
+ # pass
+ return _create_tool_factory(name_or_callable.__name__)(name_or_callable)
+ if isinstance(name_or_callable, str):
+ # Used with a new name for the tool
+ # @tool("search")
+ # def my_tool():
+ # pass
+ #
+ # or
+ #
+ # @tool("search", parse_docstring=True)
+ # def my_tool():
+ # pass
+ return _create_tool_factory(name_or_callable)
+ msg = (
+ f"The first argument must be a string or a callable with a __name__ "
+ f"for tool decorator. Got {type(name_or_callable)}"
+ )
+ raise ValueError(msg)
+
+ # Tool is used as a decorator with parameters specified
+ # @tool(parse_docstring=True)
+ # def my_tool():
+ # pass
+ def _partial(func: Callable | Runnable) -> BaseTool:
+ """Partial function that takes a `Callable` and returns a tool."""
+ name_ = func.get_name() if isinstance(func, Runnable) else func.__name__
+ tool_factory = _create_tool_factory(name_)
+ return tool_factory(func)
+
+ return _partial
+
+
+def _get_description_from_runnable(runnable: Runnable) -> str:
+ """Generate a placeholder description of a `Runnable`."""
+ input_schema = runnable.input_schema.model_json_schema()
+ return f"Takes {input_schema}."
+
+
+def _get_schema_from_runnable_and_arg_types(
+ runnable: Runnable,
+ name: str,
+ arg_types: dict[str, type] | None = None,
+) -> type[BaseModel]:
+ """Infer `args_schema` for tool."""
+ if arg_types is None:
+ try:
+ arg_types = get_type_hints(runnable.InputType)
+ except TypeError as e:
+ msg = (
+ "Tool input must be str or dict. If dict, dict arguments must be "
+ "typed. Either annotate types (e.g., with TypedDict) or pass "
+ f"arg_types into `.as_tool` to specify. {e}"
+ )
+ raise TypeError(msg) from e
+ fields = {key: (key_type, Field(...)) for key, key_type in arg_types.items()}
+ return cast("type[BaseModel]", create_model(name, **fields)) # type: ignore[call-overload]
+
+
+def convert_runnable_to_tool(
+ runnable: Runnable,
+ args_schema: type[BaseModel] | None = None,
+ *,
+ name: str | None = None,
+ description: str | None = None,
+ arg_types: dict[str, type] | None = None,
+) -> BaseTool:
+ """Convert a `Runnable` into a `BaseTool`.
+
+ Args:
+ runnable: The `Runnable` to convert.
+ args_schema: The schema for the tool's input arguments.
+ name: The name of the tool.
+ description: The description of the tool.
+ arg_types: The types of the arguments.
+
+ Returns:
+ The tool.
+ """
+ if args_schema:
+ runnable = runnable.with_types(input_type=args_schema)
+ description = description or _get_description_from_runnable(runnable)
+ name = name or runnable.get_name()
+
+ schema = runnable.input_schema.model_json_schema()
+ if schema.get("type") == "string":
+ return Tool(
+ name=name,
+ func=runnable.invoke,
+ coroutine=runnable.ainvoke,
+ description=description,
+ )
+
+ async def ainvoke_wrapper(callbacks: Callbacks | None = None, **kwargs: Any) -> Any:
+ return await runnable.ainvoke(kwargs, config={"callbacks": callbacks})
+
+ def invoke_wrapper(callbacks: Callbacks | None = None, **kwargs: Any) -> Any:
+ return runnable.invoke(kwargs, config={"callbacks": callbacks})
+
+ if (
+ arg_types is None
+ and schema.get("type") == "object"
+ and schema.get("properties")
+ ):
+ args_schema = runnable.input_schema
+ else:
+ args_schema = _get_schema_from_runnable_and_arg_types(
+ runnable, name, arg_types=arg_types
+ )
+
+ return StructuredTool.from_function(
+ name=name,
+ func=invoke_wrapper,
+ coroutine=ainvoke_wrapper,
+ description=description,
+ args_schema=args_schema,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/render.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/render.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0f8b10149e98bcc7dc65451860a49b75fdf8c14
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/render.py
@@ -0,0 +1,67 @@
+"""Utilities to render tools."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from inspect import signature
+
+from langchain_core.tools.base import BaseTool
+
+ToolsRenderer = Callable[[list[BaseTool]], str]
+
+
+def render_text_description(tools: list[BaseTool]) -> str:
+ """Render the tool name and description in plain text.
+
+ Args:
+ tools: The tools to render.
+
+ Returns:
+ The rendered text.
+
+ Output will be in the format of:
+
+ ```txt
+ search: This tool is used for search
+ calculator: This tool is used for math
+ ```
+ """
+ descriptions = []
+ for tool in tools:
+ if hasattr(tool, "func") and tool.func:
+ sig = signature(tool.func)
+ description = f"{tool.name}{sig} - {tool.description}"
+ else:
+ description = f"{tool.name} - {tool.description}"
+
+ descriptions.append(description)
+ return "\n".join(descriptions)
+
+
+def render_text_description_and_args(tools: list[BaseTool]) -> str:
+ """Render the tool name, description, and args in plain text.
+
+ Args:
+ tools: The tools to render.
+
+ Returns:
+ The rendered text.
+
+ Output will be in the format of:
+
+ ```txt
+ search: This tool is used for search, args: {"query": {"type": "string"}}
+ calculator: This tool is used for math, \
+ args: {"expression": {"type": "string"}}
+ ```
+ """
+ tool_strings = []
+ for tool in tools:
+ args_schema = str(tool.args)
+ if hasattr(tool, "func") and tool.func:
+ sig = signature(tool.func)
+ description = f"{tool.name}{sig} - {tool.description}"
+ else:
+ description = f"{tool.name} - {tool.description}"
+ tool_strings.append(f"{description}, args: {args_schema}")
+ return "\n".join(tool_strings)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/retriever.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/retriever.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e2d84dcb0ca79ca4837d05c2863785f88e42ced
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/retriever.py
@@ -0,0 +1,94 @@
+"""Retriever tool."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Literal
+
+from pydantic import BaseModel, Field
+
+# Cannot move Callbacks and Document to TYPE_CHECKING as StructuredTool's
+# func/coroutine parameter annotations are evaluated at runtime.
+from langchain_core.callbacks import Callbacks # noqa: TC001
+from langchain_core.documents import Document # noqa: TC001
+from langchain_core.prompts import (
+ BasePromptTemplate,
+ PromptTemplate,
+ aformat_document,
+ format_document,
+)
+from langchain_core.tools.structured import StructuredTool
+
+if TYPE_CHECKING:
+ from langchain_core.retrievers import BaseRetriever
+
+
+class RetrieverInput(BaseModel):
+ """Input to the retriever."""
+
+ query: str = Field(description="query to look up in retriever")
+
+
+def create_retriever_tool(
+ retriever: BaseRetriever,
+ name: str,
+ description: str,
+ *,
+ document_prompt: BasePromptTemplate | None = None,
+ document_separator: str = "\n\n",
+ response_format: Literal["content", "content_and_artifact"] = "content",
+) -> StructuredTool:
+ r"""Create a tool to do retrieval of documents.
+
+ Args:
+ retriever: The retriever to use for the retrieval
+ name: The name for the tool.
+
+ This will be passed to the language model, so should be unique and somewhat
+ descriptive.
+ description: The description for the tool.
+
+ This will be passed to the language model, so should be descriptive.
+ document_prompt: The prompt to use for the document.
+ document_separator: The separator to use between documents.
+ response_format: The tool response format.
+
+ If `'content'` then the output of the tool is interpreted as the contents of
+ a `ToolMessage`. If `'content_and_artifact'` then the output is expected to
+ be a two-tuple corresponding to the `(content, artifact)` of a `ToolMessage`
+ (artifact being a list of documents in this case).
+
+ Returns:
+ Tool class to pass to an agent.
+ """
+ document_prompt_ = document_prompt or PromptTemplate.from_template("{page_content}")
+
+ def func(
+ query: str, callbacks: Callbacks = None
+ ) -> str | tuple[str, list[Document]]:
+ docs = retriever.invoke(query, config={"callbacks": callbacks})
+ content = document_separator.join(
+ format_document(doc, document_prompt_) for doc in docs
+ )
+ if response_format == "content_and_artifact":
+ return (content, docs)
+ return content
+
+ async def afunc(
+ query: str, callbacks: Callbacks = None
+ ) -> str | tuple[str, list[Document]]:
+ docs = await retriever.ainvoke(query, config={"callbacks": callbacks})
+ content = document_separator.join(
+ [await aformat_document(doc, document_prompt_) for doc in docs]
+ )
+ if response_format == "content_and_artifact":
+ return (content, docs)
+ return content
+
+ return StructuredTool(
+ name=name,
+ description=description,
+ func=func,
+ coroutine=afunc,
+ args_schema=RetrieverInput,
+ response_format=response_format,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/simple.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/simple.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca80164df88d2a74a866fc8e5b24e52dbc36dff4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/simple.py
@@ -0,0 +1,204 @@
+"""Tool that takes in function or coroutine directly."""
+
+from __future__ import annotations
+
+from collections.abc import Awaitable, Callable
+from inspect import signature
+from typing import (
+ TYPE_CHECKING,
+ Any,
+)
+
+from typing_extensions import override
+
+# Cannot move to TYPE_CHECKING as _run/_arun parameter annotations are needed at runtime
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForToolRun, # noqa: TC001
+ CallbackManagerForToolRun, # noqa: TC001
+)
+from langchain_core.runnables import RunnableConfig, run_in_executor
+from langchain_core.tools.base import (
+ ArgsSchema,
+ BaseTool,
+ ToolException,
+ _get_runnable_config_param,
+)
+
+if TYPE_CHECKING:
+ from langchain_core.messages import ToolCall
+
+
+class Tool(BaseTool):
+ """Tool that takes in function or coroutine directly."""
+
+ description: str = ""
+
+ func: Callable[..., str] | None
+ """The function to run when the tool is called."""
+
+ coroutine: Callable[..., Awaitable[str]] | None = None
+ """The asynchronous version of the function."""
+
+ # --- Runnable ---
+
+ @override
+ async def ainvoke(
+ self,
+ input: str | dict | ToolCall,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if not self.coroutine:
+ # If the tool does not implement async, fall back to default implementation
+ return await run_in_executor(config, self.invoke, input, config, **kwargs)
+
+ return await super().ainvoke(input, config, **kwargs)
+
+ # --- Tool ---
+
+ @property
+ def args(self) -> dict:
+ """The tool's input arguments.
+
+ Returns:
+ The input arguments for the tool.
+ """
+ if self.args_schema is not None:
+ return super().args
+ # For backwards compatibility, if the function signature is ambiguous,
+ # assume it takes a single string input.
+ return {"tool_input": {"type": "string"}}
+
+ def _to_args_and_kwargs(
+ self, tool_input: str | dict, tool_call_id: str | None
+ ) -> tuple[tuple, dict]:
+ """Convert tool input to Pydantic model.
+
+ Args:
+ tool_input: The input to the tool.
+ tool_call_id: The ID of the tool call.
+
+ Raises:
+ ToolException: If the tool input is invalid.
+
+ Returns:
+ The Pydantic model args and kwargs.
+ """
+ args, kwargs = super()._to_args_and_kwargs(tool_input, tool_call_id)
+ # For backwards compatibility. The tool must be run with a single input
+ all_args = list(args) + list(kwargs.values())
+ if len(all_args) != 1:
+ msg = (
+ f"""Too many arguments to single-input tool {self.name}.
+ Consider using StructuredTool instead."""
+ f" Args: {all_args}"
+ )
+ raise ToolException(msg)
+ return tuple(all_args), {}
+
+ def _run(
+ self,
+ *args: Any,
+ config: RunnableConfig,
+ run_manager: CallbackManagerForToolRun | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Use the tool.
+
+ Args:
+ *args: Positional arguments to pass to the tool
+ config: Configuration for the run
+ run_manager: Optional callback manager to use for the run
+ **kwargs: Keyword arguments to pass to the tool
+
+ Returns:
+ The result of the tool execution
+ """
+ if self.func:
+ if run_manager and signature(self.func).parameters.get("callbacks"):
+ kwargs["callbacks"] = run_manager.get_child()
+ if config_param := _get_runnable_config_param(self.func):
+ kwargs[config_param] = config
+ return self.func(*args, **kwargs)
+ msg = "Tool does not support sync invocation."
+ raise NotImplementedError(msg)
+
+ async def _arun(
+ self,
+ *args: Any,
+ config: RunnableConfig,
+ run_manager: AsyncCallbackManagerForToolRun | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Use the tool asynchronously.
+
+ Args:
+ *args: Positional arguments to pass to the tool
+ config: Configuration for the run
+ run_manager: Optional callback manager to use for the run
+ **kwargs: Keyword arguments to pass to the tool
+
+ Returns:
+ The result of the tool execution
+ """
+ if self.coroutine:
+ if run_manager and signature(self.coroutine).parameters.get("callbacks"):
+ kwargs["callbacks"] = run_manager.get_child()
+ if config_param := _get_runnable_config_param(self.coroutine):
+ kwargs[config_param] = config
+ return await self.coroutine(*args, **kwargs)
+
+ # NOTE: this code is unreachable since _arun is only called if coroutine is not
+ # None.
+ return await super()._arun(
+ *args, config=config, run_manager=run_manager, **kwargs
+ )
+
+ # TODO: this is for backwards compatibility, remove in future
+ def __init__(
+ self, name: str, func: Callable | None, description: str, **kwargs: Any
+ ) -> None:
+ """Initialize tool."""
+ super().__init__(name=name, func=func, description=description, **kwargs)
+
+ @classmethod
+ def from_function(
+ cls,
+ func: Callable | None,
+ name: str, # We keep these required to support backwards compatibility
+ description: str,
+ return_direct: bool = False, # noqa: FBT001,FBT002
+ args_schema: ArgsSchema | None = None,
+ coroutine: Callable[..., Awaitable[Any]]
+ | None = None, # This is last for compatibility, but should be after func
+ **kwargs: Any,
+ ) -> Tool:
+ """Initialize tool from a function.
+
+ Args:
+ func: The function to create the tool from.
+ name: The name of the tool.
+ description: The description of the tool.
+ return_direct: Whether to return the output directly.
+ args_schema: The schema of the tool's input arguments.
+ coroutine: The asynchronous version of the function.
+ **kwargs: Additional arguments to pass to the tool.
+
+ Returns:
+ The tool.
+
+ Raises:
+ ValueError: If the function is not provided.
+ """
+ if func is None and coroutine is None:
+ msg = "Function and/or coroutine must be provided"
+ raise ValueError(msg)
+ return cls(
+ name=name,
+ func=func,
+ coroutine=coroutine,
+ description=description,
+ return_direct=return_direct,
+ args_schema=args_schema,
+ **kwargs,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/structured.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/structured.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b67e3b4547c6fc7900874570ebd9c36dfd90504
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tools/structured.py
@@ -0,0 +1,271 @@
+"""Structured tool."""
+
+from __future__ import annotations
+
+import functools
+import textwrap
+from collections.abc import Awaitable, Callable
+from inspect import signature
+from typing import (
+ TYPE_CHECKING,
+ Annotated,
+ Any,
+ Literal,
+)
+
+from pydantic import Field, SkipValidation
+from typing_extensions import override
+
+# Cannot move to TYPE_CHECKING as _run/_arun parameter annotations are needed at runtime
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForToolRun, # noqa: TC001
+ CallbackManagerForToolRun, # noqa: TC001
+)
+from langchain_core.runnables import RunnableConfig, run_in_executor
+from langchain_core.tools.base import (
+ _EMPTY_SET,
+ FILTERED_ARGS,
+ ArgsSchema,
+ BaseTool,
+ _get_runnable_config_param,
+ _is_injected_arg_type,
+ create_schema_from_function,
+)
+from langchain_core.utils.pydantic import is_basemodel_subclass
+
+if TYPE_CHECKING:
+ from langchain_core.messages import ToolCall
+
+
+class StructuredTool(BaseTool):
+ """Tool that can operate on any number of inputs."""
+
+ description: str = ""
+
+ args_schema: Annotated[ArgsSchema, SkipValidation()] = Field(
+ ..., description="The tool schema."
+ )
+ """The input arguments' schema."""
+
+ func: Callable[..., Any] | None = None
+ """The function to run when the tool is called."""
+
+ coroutine: Callable[..., Awaitable[Any]] | None = None
+ """The asynchronous version of the function."""
+
+ # --- Runnable ---
+
+ # TODO: Is this needed?
+ @override
+ async def ainvoke(
+ self,
+ input: str | dict | ToolCall,
+ config: RunnableConfig | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ if not self.coroutine:
+ # If the tool does not implement async, fall back to default implementation
+ return await run_in_executor(config, self.invoke, input, config, **kwargs)
+
+ return await super().ainvoke(input, config, **kwargs)
+
+ # --- Tool ---
+
+ def _run(
+ self,
+ *args: Any,
+ config: RunnableConfig,
+ run_manager: CallbackManagerForToolRun | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Use the tool.
+
+ Args:
+ *args: Positional arguments to pass to the tool
+ config: Configuration for the run
+ run_manager: Optional callback manager to use for the run
+ **kwargs: Keyword arguments to pass to the tool
+
+ Returns:
+ The result of the tool execution
+ """
+ if self.func:
+ if run_manager and signature(self.func).parameters.get("callbacks"):
+ kwargs["callbacks"] = run_manager.get_child()
+ if config_param := _get_runnable_config_param(self.func):
+ kwargs[config_param] = config
+ return self.func(*args, **kwargs)
+ msg = "StructuredTool does not support sync invocation."
+ raise NotImplementedError(msg)
+
+ async def _arun(
+ self,
+ *args: Any,
+ config: RunnableConfig,
+ run_manager: AsyncCallbackManagerForToolRun | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ """Use the tool asynchronously.
+
+ Args:
+ *args: Positional arguments to pass to the tool
+ config: Configuration for the run
+ run_manager: Optional callback manager to use for the run
+ **kwargs: Keyword arguments to pass to the tool
+
+ Returns:
+ The result of the tool execution
+ """
+ if self.coroutine:
+ if run_manager and signature(self.coroutine).parameters.get("callbacks"):
+ kwargs["callbacks"] = run_manager.get_child()
+ if config_param := _get_runnable_config_param(self.coroutine):
+ kwargs[config_param] = config
+ return await self.coroutine(*args, **kwargs)
+
+ # If self.coroutine is None, then this will delegate to the default
+ # implementation which is expected to delegate to _run on a separate thread.
+ return await super()._arun(
+ *args, config=config, run_manager=run_manager, **kwargs
+ )
+
+ @classmethod
+ def from_function(
+ cls,
+ func: Callable | None = None,
+ coroutine: Callable[..., Awaitable[Any]] | None = None,
+ name: str | None = None,
+ description: str | None = None,
+ return_direct: bool = False, # noqa: FBT001,FBT002
+ args_schema: ArgsSchema | None = None,
+ infer_schema: bool = True, # noqa: FBT001,FBT002
+ *,
+ response_format: Literal["content", "content_and_artifact"] = "content",
+ parse_docstring: bool = False,
+ error_on_invalid_docstring: bool = False,
+ **kwargs: Any,
+ ) -> StructuredTool:
+ """Create tool from a given function.
+
+ A classmethod that helps to create a tool from a function.
+
+ Args:
+ func: The function from which to create a tool.
+ coroutine: The async function from which to create a tool.
+ name: The name of the tool.
+
+ Defaults to the function name.
+ description: The description of the tool.
+
+ Defaults to the function docstring.
+ return_direct: Whether to return the result directly or as a callback.
+ args_schema: The schema of the tool's input arguments.
+ infer_schema: Whether to infer the schema from the function's signature.
+ response_format: The tool response format.
+
+ If `'content'` then the output of the tool is interpreted as the
+ contents of a `ToolMessage`. If `'content_and_artifact'` then the output
+ is expected to be a two-tuple corresponding to the `(content, artifact)`
+ of a `ToolMessage`.
+ parse_docstring: If `infer_schema` and `parse_docstring`, will attempt
+ to parse parameter descriptions from Google Style function docstrings.
+ error_on_invalid_docstring: if `parse_docstring` is provided, configure
+ whether to raise `ValueError` on invalid Google Style docstrings.
+ **kwargs: Additional arguments to pass to the tool
+
+ Returns:
+ The tool.
+
+ Raises:
+ ValueError: If the function is not provided.
+ ValueError: If the function does not have a docstring and description
+ is not provided.
+ TypeError: If the `args_schema` is not a `BaseModel` or dict.
+
+ Examples:
+ ```python
+ def add(a: int, b: int) -> int:
+ \"\"\"Add two numbers\"\"\"
+ return a + b
+ tool = StructuredTool.from_function(add)
+ tool.run(1, 2) # 3
+
+ ```
+ """
+ if func is not None:
+ source_function = func
+ elif coroutine is not None:
+ source_function = coroutine
+ else:
+ msg = "Function and/or coroutine must be provided"
+ raise ValueError(msg)
+ name = name or source_function.__name__
+ if args_schema is None and infer_schema:
+ # schema name is appended within function
+ args_schema = create_schema_from_function(
+ name,
+ source_function,
+ parse_docstring=parse_docstring,
+ error_on_invalid_docstring=error_on_invalid_docstring,
+ filter_args=_filter_schema_args(source_function),
+ )
+ description_ = description
+ if description is None and not parse_docstring:
+ description_ = source_function.__doc__ or None
+ if description_ is None and args_schema:
+ if isinstance(args_schema, type) and is_basemodel_subclass(args_schema):
+ description_ = args_schema.__doc__
+ if (
+ description_
+ and "A base class for creating Pydantic models" in description_
+ ):
+ description_ = ""
+ elif not description_:
+ description_ = None
+ elif isinstance(args_schema, dict):
+ description_ = args_schema.get("description")
+ else:
+ msg = (
+ "Invalid args_schema: expected BaseModel or dict, "
+ f"got {args_schema}"
+ )
+ raise TypeError(msg)
+ if description_ is None:
+ msg = "Function must have a docstring if description not provided."
+ raise ValueError(msg)
+ if description is None:
+ # Only apply if using the function's docstring
+ description_ = textwrap.dedent(description_).strip()
+
+ # Description example:
+ # search_api(query: str) - Searches the API for the query.
+ description_ = f"{description_.strip()}"
+ return cls(
+ name=name,
+ func=func,
+ coroutine=coroutine,
+ args_schema=args_schema,
+ description=description_,
+ return_direct=return_direct,
+ response_format=response_format,
+ **kwargs,
+ )
+
+ @functools.cached_property
+ def _injected_args_keys(self) -> frozenset[str]:
+ fn = self.func or self.coroutine
+ if fn is None:
+ return _EMPTY_SET
+ return frozenset(
+ k
+ for k, v in signature(fn).parameters.items()
+ if _is_injected_arg_type(v.annotation)
+ )
+
+
+def _filter_schema_args(func: Callable) -> list[str]:
+ filter_args = list(FILTERED_ARGS)
+ if config_param := _get_runnable_config_param(func):
+ filter_args.append(config_param)
+ # filter_args.extend(_get_non_model_params(type_hints))
+ return filter_args
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6d35bc2a4467db0282790d67edca70fe9b5c0e1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__init__.py
@@ -0,0 +1,50 @@
+"""Tracers are classes for tracing runs."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.tracers.base import BaseTracer
+ from langchain_core.tracers.evaluation import EvaluatorCallbackHandler
+ from langchain_core.tracers.langchain import LangChainTracer
+ from langchain_core.tracers.log_stream import (
+ LogStreamCallbackHandler,
+ RunLog,
+ RunLogPatch,
+ )
+ from langchain_core.tracers.schemas import Run
+ from langchain_core.tracers.stdout import ConsoleCallbackHandler
+
+__all__ = (
+ "BaseTracer",
+ "ConsoleCallbackHandler",
+ "EvaluatorCallbackHandler",
+ "LangChainTracer",
+ "LogStreamCallbackHandler",
+ "Run",
+ "RunLog",
+ "RunLogPatch",
+)
+
+_dynamic_imports = {
+ "BaseTracer": "base",
+ "EvaluatorCallbackHandler": "evaluation",
+ "LangChainTracer": "langchain",
+ "LogStreamCallbackHandler": "log_stream",
+ "RunLog": "log_stream",
+ "RunLogPatch": "log_stream",
+ "Run": "schemas",
+ "ConsoleCallbackHandler": "stdout",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad9b4b6e8441f2e1c75f0138e0b7ffca0c89c588
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/_compat.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/_compat.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4780a65a616101e646097d18748238ab2f445699
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/_compat.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/_streaming.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/_streaming.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d5d568cc0083e98e6c644f25359e0e3393b7085
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/_streaming.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad44826519628b180c404c556e0198dab4960406
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/context.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/context.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ce8a93a43171995d96d95fff8d37872dd683346
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/context.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/core.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/core.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cc0af3dd24b9d9606293187e48badf329f589de0
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/core.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/evaluation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/evaluation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fdf121daf48005902ab6282ef8ad86ace747074
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/evaluation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/event_stream.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/event_stream.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8d318d670b86ae97d178ac2fd4605e0b39ef66c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/event_stream.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/langchain.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/langchain.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56a8b2eb500ae3733435c54acbcfe3186d7e0af8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/langchain.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/log_stream.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/log_stream.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..19dd5a2048d3e7dc23b68522753173dbabad1e21
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/log_stream.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/memory_stream.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/memory_stream.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9681d33dcdba2ae283de85bead386370e31b0514
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/memory_stream.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/root_listeners.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/root_listeners.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16f3835d3f6ccfa421081c1e8aa597f5e1271bc2
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/root_listeners.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/run_collector.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/run_collector.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4358a9e2db9859ebaeb4c09e203bf4106cc44e9e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/run_collector.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/schemas.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/schemas.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4550af755c9a78a201bafa1ffa4d8b0bf9dcdbab
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/schemas.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/stdout.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/stdout.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bfec9ed22503082127a82b2ea70583d2a881e8c3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/__pycache__/stdout.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/_compat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..54c2f49da034627c282dd37bb1fc30a91c53fc15
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/_compat.py
@@ -0,0 +1,95 @@
+"""Compatibility helpers for Pydantic v1/v2 with langsmith `Run` objects.
+
+!!! note
+
+ The generic helpers (`pydantic_to_dict`, `pydantic_copy`) detect Pydanti version
+ based on the langsmith `Run` model. They're intended for langsmith objects (`Run`,
+ `Example`) which migrate together.
+
+For general Pydantic v1/v2 handling, see `langchain_core.utils.pydantic`.
+"""
+
+from __future__ import annotations
+
+from typing import Any, TypeVar
+
+from langchain_core.tracers.schemas import Run
+
+# Detect Pydantic version once at import time based on Run model
+_RUN_IS_PYDANTIC_V2 = hasattr(Run, "model_dump")
+
+T = TypeVar("T")
+
+
+def run_to_dict(run: Run, **kwargs: Any) -> dict[str, Any]:
+ """Convert run to dict, compatible with both Pydantic v1 and v2.
+
+ Args:
+ run: The run to convert.
+ **kwargs: Additional arguments passed to `model_dump`/`dict`.
+
+ Returns:
+ Dictionary representation of the run.
+ """
+ if _RUN_IS_PYDANTIC_V2:
+ return run.model_dump(**kwargs)
+ return run.dict(**kwargs) # type: ignore[deprecated]
+
+
+def run_copy(run: Run, **kwargs: Any) -> Run:
+ """Copy run, compatible with both Pydantic v1 and v2.
+
+ Args:
+ run: The run to copy.
+ **kwargs: Additional arguments passed to `model_copy`/`copy`.
+
+ Returns:
+ A copy of the run.
+ """
+ if _RUN_IS_PYDANTIC_V2:
+ return run.model_copy(**kwargs)
+ return run.copy(**kwargs) # type: ignore[deprecated]
+
+
+def run_construct(**kwargs: Any) -> Run:
+ """Construct run without validation, compatible with both Pydantic v1 and v2.
+
+ Args:
+ **kwargs: Fields to set on the run.
+
+ Returns:
+ A new `Run` instance constructed without validation.
+ """
+ if _RUN_IS_PYDANTIC_V2:
+ return Run.model_construct(**kwargs)
+ return Run.construct(**kwargs) # type: ignore[deprecated]
+
+
+def pydantic_to_dict(obj: Any, **kwargs: Any) -> dict[str, Any]:
+ """Convert any Pydantic model to dict, compatible with both v1 and v2.
+
+ Args:
+ obj: The Pydantic model to convert.
+ **kwargs: Additional arguments passed to `model_dump`/`dict`.
+
+ Returns:
+ Dictionary representation of the model.
+ """
+ if _RUN_IS_PYDANTIC_V2:
+ return obj.model_dump(**kwargs) # type: ignore[no-any-return]
+ return obj.dict(**kwargs) # type: ignore[no-any-return]
+
+
+def pydantic_copy(obj: T, **kwargs: Any) -> T:
+ """Copy any Pydantic model, compatible with both v1 and v2.
+
+ Args:
+ obj: The Pydantic model to copy.
+ **kwargs: Additional arguments passed to `model_copy`/`copy`.
+
+ Returns:
+ A copy of the model.
+ """
+ if _RUN_IS_PYDANTIC_V2:
+ return obj.model_copy(**kwargs) # type: ignore[attr-defined,no-any-return]
+ return obj.copy(**kwargs) # type: ignore[attr-defined,no-any-return]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/_streaming.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/_streaming.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f5071bdc078689a61cc3f2b9da741b391e9327f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/_streaming.py
@@ -0,0 +1,53 @@
+"""Internal tracers used for `stream_log` and `astream` events implementations."""
+
+import typing
+from collections.abc import AsyncIterator, Iterator
+from uuid import UUID
+
+T = typing.TypeVar("T")
+
+
+# THIS IS USED IN LANGGRAPH.
+@typing.runtime_checkable
+class _StreamingCallbackHandler(typing.Protocol[T]):
+ """Types for streaming callback handlers.
+
+ This is a common mixin that the callback handlers for both astream events and
+ astream log inherit from.
+
+ The `tap_output_aiter` method is invoked in some contexts to produce callbacks for
+ intermediate results.
+ """
+
+ def tap_output_aiter(
+ self, run_id: UUID, output: AsyncIterator[T]
+ ) -> AsyncIterator[T]:
+ """Used for internal astream_log and astream events implementations."""
+
+ def tap_output_iter(self, run_id: UUID, output: Iterator[T]) -> Iterator[T]:
+ """Used for internal astream_log and astream events implementations."""
+
+
+# THIS IS USED IN LANGGRAPH.
+class _V2StreamingCallbackHandler:
+ """Marker base class for handlers that consume `on_stream_event` (v2).
+
+ A handler inheriting from this class signals that it wants content-
+ block lifecycle events from `stream_events(version="v3")` (and its
+ async equivalent) rather than the v1 `on_llm_new_token` chunks.
+ `BaseChatModel.invoke` uses
+ `isinstance(handler, _V2StreamingCallbackHandler)` to decide whether
+ to route an invoke through the v2 event generator.
+
+ Implemented as a concrete marker class (not a `Protocol`) so opt-in
+ is explicit via inheritance. An empty `runtime_checkable` Protocol
+ would match every object and misroute every call. The event
+ delivery contract itself lives on
+ `BaseCallbackHandler.on_stream_event`.
+ """
+
+
+__all__ = [
+ "_StreamingCallbackHandler",
+ "_V2StreamingCallbackHandler",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..b52420f0d844168becbb52ac6e9131b12c3b587f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/base.py
@@ -0,0 +1,955 @@
+"""Base interfaces for tracing runs."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from abc import ABC, abstractmethod
+from typing import (
+ TYPE_CHECKING,
+ Any,
+)
+
+from typing_extensions import override
+
+from langchain_core.callbacks.base import AsyncCallbackHandler, BaseCallbackHandler
+from langchain_core.exceptions import TracerException # noqa: F401
+from langchain_core.tracers.core import _TracerCore
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+ from uuid import UUID
+
+ from tenacity import RetryCallState
+
+ from langchain_core.documents import Document
+ from langchain_core.messages import BaseMessage
+ from langchain_core.outputs import ChatGenerationChunk, GenerationChunk, LLMResult
+ from langchain_core.tracers.schemas import Run
+
+logger = logging.getLogger(__name__)
+
+
+class BaseTracer(_TracerCore, BaseCallbackHandler, ABC):
+ """Base interface for tracers."""
+
+ @abstractmethod
+ def _persist_run(self, run: Run) -> None:
+ """Persist a run."""
+
+ def _start_trace(self, run: Run) -> None:
+ """Start a trace for a run."""
+ super()._start_trace(run)
+ self._on_run_create(run)
+
+ def _end_trace(self, run: Run) -> None:
+ """End a trace for a run."""
+ if not run.parent_run_id:
+ self._persist_run(run)
+ self.run_map.pop(str(run.id))
+ # If this run's parent was injected from an external tracing context
+ # (e.g. a langsmith @traceable), decrement its child refcount and
+ # remove it from run_map once the last child is done.
+ parent_id = str(run.parent_run_id) if run.parent_run_id else None
+ if parent_id and parent_id in self._external_run_ids:
+ self._external_run_ids[parent_id] -= 1
+ if self._external_run_ids[parent_id] <= 0:
+ self.run_map.pop(parent_id, None)
+ del self._external_run_ids[parent_id]
+ self._on_run_update(run)
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Start a trace for a chat model run.
+
+ Note:
+ Naming can be confusing here: there is `on_chat_model_start`, but no
+ corresponding `on_chat_model_end` callback. Chat model completion is
+ routed through `on_llm_end` / `_on_llm_end`, which are shared with
+ text LLM runs.
+
+ Args:
+ serialized: The serialized model.
+ messages: The messages to start the chat with.
+ run_id: The run ID.
+ tags: The tags for the run.
+ parent_run_id: The parent run ID.
+ metadata: The metadata for the run.
+ name: The name of the run.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ chat_model_run = self._create_chat_model_run(
+ serialized=serialized,
+ messages=messages,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ tags=tags,
+ metadata=metadata,
+ name=name,
+ **kwargs,
+ )
+ self._start_trace(chat_model_run)
+ self._on_chat_model_start(chat_model_run)
+ return chat_model_run
+
+ def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Start a trace for an LLM run.
+
+ Args:
+ serialized: The serialized model.
+ prompts: The prompts to start the LLM with.
+ run_id: The run ID.
+ tags: The tags for the run.
+ parent_run_id: The parent run ID.
+ metadata: The metadata for the run.
+ name: The name of the run.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ llm_run = self._create_llm_run(
+ serialized=serialized,
+ prompts=prompts,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ tags=tags,
+ metadata=metadata,
+ name=name,
+ **kwargs,
+ )
+ self._start_trace(llm_run)
+ self._on_llm_start(llm_run)
+ return llm_run
+
+ @override
+ def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Run on new LLM token.
+
+ Only available when streaming is enabled.
+
+ Args:
+ token: The token.
+ chunk: The chunk.
+ run_id: The run ID.
+ parent_run_id: The parent run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ # "chat_model" is only used for the experimental new streaming_events format.
+ # This change should not affect any existing tracers.
+ llm_run = self._llm_run_with_token_event(
+ token=token,
+ run_id=run_id,
+ chunk=chunk,
+ parent_run_id=parent_run_id,
+ )
+ self._on_llm_new_token(llm_run, token, chunk)
+ return llm_run
+
+ @override
+ def on_retry(
+ self,
+ retry_state: RetryCallState,
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> Run:
+ """Run on retry.
+
+ Args:
+ retry_state: The retry state.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ return self._llm_run_with_retry_event(
+ retry_state=retry_state,
+ run_id=run_id,
+ )
+
+ @override
+ def on_llm_end(self, response: LLMResult, *, run_id: UUID, **kwargs: Any) -> Run:
+ """End a trace for an LLM or chat model run.
+
+ Note:
+ This is the end callback for both run types. Chat models start with
+ `on_chat_model_start`, but there is no `on_chat_model_end`;
+ completion is routed here for callback API compatibility.
+
+ Args:
+ response: The response.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ # "chat_model" is only used for the experimental new streaming_events format.
+ # This change should not affect any existing tracers.
+ llm_run = self._complete_llm_run(
+ response=response,
+ run_id=run_id,
+ )
+ self._end_trace(llm_run)
+ self._on_llm_end(llm_run)
+ return llm_run
+
+ def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> Run:
+ """Handle an error for an LLM run.
+
+ Args:
+ error: The error.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ # "chat_model" is only used for the experimental new streaming_events format.
+ # This change should not affect any existing tracers.
+ llm_run = self._errored_llm_run(
+ error=error, run_id=run_id, response=kwargs.pop("response", None)
+ )
+ self._end_trace(llm_run)
+ self._on_llm_error(llm_run)
+ return llm_run
+
+ @override
+ def on_chain_start(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_type: str | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Start a trace for a chain run.
+
+ Args:
+ serialized: The serialized chain.
+ inputs: The inputs for the chain.
+ run_id: The run ID.
+ tags: The tags for the run.
+ parent_run_id: The parent run ID.
+ metadata: The metadata for the run.
+ run_type: The type of the run.
+ name: The name of the run.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ chain_run = self._create_chain_run(
+ serialized=serialized,
+ inputs=inputs,
+ run_id=run_id,
+ tags=tags,
+ parent_run_id=parent_run_id,
+ metadata=metadata,
+ run_type=run_type,
+ name=name,
+ **kwargs,
+ )
+ self._start_trace(chain_run)
+ self._on_chain_start(chain_run)
+ return chain_run
+
+ @override
+ def on_chain_end(
+ self,
+ outputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """End a trace for a chain run.
+
+ Args:
+ outputs: The outputs for the chain.
+ run_id: The run ID.
+ inputs: The inputs for the chain.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ chain_run = self._complete_chain_run(
+ outputs=outputs,
+ run_id=run_id,
+ inputs=inputs,
+ )
+ self._end_trace(chain_run)
+ self._on_chain_end(chain_run)
+ return chain_run
+
+ @override
+ def on_chain_error(
+ self,
+ error: BaseException,
+ *,
+ inputs: dict[str, Any] | None = None,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> Run:
+ """Handle an error for a chain run.
+
+ Args:
+ error: The error.
+ inputs: The inputs for the chain.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ chain_run = self._errored_chain_run(
+ error=error,
+ run_id=run_id,
+ inputs=inputs,
+ )
+ self._end_trace(chain_run)
+ self._on_chain_error(chain_run)
+ return chain_run
+
+ def on_tool_start(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Start a trace for a tool run.
+
+ Args:
+ serialized: The serialized tool.
+ input_str: The input string.
+ run_id: The run ID.
+ tags: The tags for the run.
+ parent_run_id: The parent run ID.
+ metadata: The metadata for the run.
+ name: The name of the run.
+ inputs: The inputs for the tool.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ tool_run = self._create_tool_run(
+ serialized=serialized,
+ input_str=input_str,
+ run_id=run_id,
+ tags=tags,
+ parent_run_id=parent_run_id,
+ metadata=metadata,
+ name=name,
+ inputs=inputs,
+ **kwargs,
+ )
+ self._start_trace(tool_run)
+ self._on_tool_start(tool_run)
+ return tool_run
+
+ @override
+ def on_tool_end(self, output: Any, *, run_id: UUID, **kwargs: Any) -> Run:
+ """End a trace for a tool run.
+
+ Args:
+ output: The output for the tool.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ tool_run = self._complete_tool_run(
+ output=output,
+ run_id=run_id,
+ )
+ self._end_trace(tool_run)
+ self._on_tool_end(tool_run)
+ return tool_run
+
+ @override
+ def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> Run:
+ """Handle an error for a tool run.
+
+ Args:
+ error: The error.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ tool_run = self._errored_tool_run(
+ error=error,
+ run_id=run_id,
+ )
+ self._end_trace(tool_run)
+ self._on_tool_error(tool_run)
+ return tool_run
+
+ def on_retriever_start(
+ self,
+ serialized: dict[str, Any],
+ query: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Run when the `Retriever` starts running.
+
+ Args:
+ serialized: The serialized retriever.
+ query: The query.
+ run_id: The run ID.
+ parent_run_id: The parent run ID.
+ tags: The tags for the run.
+ metadata: The metadata for the run.
+ name: The name of the run.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ retrieval_run = self._create_retrieval_run(
+ serialized=serialized,
+ query=query,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ tags=tags,
+ metadata=metadata,
+ name=name,
+ **kwargs,
+ )
+ self._start_trace(retrieval_run)
+ self._on_retriever_start(retrieval_run)
+ return retrieval_run
+
+ @override
+ def on_retriever_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> Run:
+ """Run when `Retriever` errors.
+
+ Args:
+ error: The error.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ retrieval_run = self._errored_retrieval_run(
+ error=error,
+ run_id=run_id,
+ )
+ self._end_trace(retrieval_run)
+ self._on_retriever_error(retrieval_run)
+ return retrieval_run
+
+ @override
+ def on_retriever_end(
+ self, documents: Sequence[Document], *, run_id: UUID, **kwargs: Any
+ ) -> Run:
+ """Run when the `Retriever` ends running.
+
+ Args:
+ documents: The documents.
+ run_id: The run ID.
+ **kwargs: Additional arguments.
+
+ Returns:
+ The run.
+ """
+ retrieval_run = self._complete_retrieval_run(
+ documents=documents,
+ run_id=run_id,
+ )
+ self._end_trace(retrieval_run)
+ self._on_retriever_end(retrieval_run)
+ return retrieval_run
+
+ def __deepcopy__(self, memo: dict) -> BaseTracer:
+ """Return self."""
+ return self
+
+ def __copy__(self) -> BaseTracer:
+ """Return self."""
+ return self
+
+
+class AsyncBaseTracer(_TracerCore, AsyncCallbackHandler, ABC):
+ """Async base interface for tracers."""
+
+ @abstractmethod
+ @override
+ async def _persist_run(self, run: Run) -> None:
+ """Persist a run."""
+
+ @override
+ async def _start_trace(self, run: Run) -> None:
+ """Start a trace for a run.
+
+ Starting a trace will run concurrently with each `_on_[run_type]_start` method.
+ No `_on_[run_type]_start` callback should depend on operations in
+ `_start_trace`.
+ """
+ super()._start_trace(run)
+ await self._on_run_create(run)
+
+ @override
+ async def _end_trace(self, run: Run) -> None:
+ """End a trace for a run.
+
+ Ending a trace will run concurrently with each `_on_[run_type]_end` method.
+ No `_on_[run_type]_end` callback should depend on operations in `_end_trace`.
+ """
+ if not run.parent_run_id:
+ await self._persist_run(run)
+ self.run_map.pop(str(run.id))
+ # If this run's parent was injected from an external tracing context
+ # (e.g. a langsmith @traceable), decrement its child refcount and
+ # remove it from run_map once the last child is done.
+ parent_id = str(run.parent_run_id) if run.parent_run_id else None
+ if parent_id and parent_id in self._external_run_ids:
+ self._external_run_ids[parent_id] -= 1
+ if self._external_run_ids[parent_id] <= 0:
+ self.run_map.pop(parent_id, None)
+ del self._external_run_ids[parent_id]
+ await self._on_run_update(run)
+
+ @override
+ async def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Any:
+ chat_model_run = self._create_chat_model_run(
+ serialized=serialized,
+ messages=messages,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ tags=tags,
+ metadata=metadata,
+ name=name,
+ **kwargs,
+ )
+ tasks = [
+ self._start_trace(chat_model_run),
+ self._on_chat_model_start(chat_model_run),
+ ]
+ await asyncio.gather(*tasks)
+ return chat_model_run
+
+ @override
+ async def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ llm_run = self._create_llm_run(
+ serialized=serialized,
+ prompts=prompts,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ tags=tags,
+ metadata=metadata,
+ **kwargs,
+ )
+ tasks = [self._start_trace(llm_run), self._on_llm_start(llm_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> None:
+ llm_run = self._llm_run_with_token_event(
+ token=token,
+ run_id=run_id,
+ chunk=chunk,
+ parent_run_id=parent_run_id,
+ )
+ await self._on_llm_new_token(llm_run, token, chunk)
+
+ @override
+ async def on_retry(
+ self,
+ retry_state: RetryCallState,
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> None:
+ self._llm_run_with_retry_event(
+ retry_state=retry_state,
+ run_id=run_id,
+ )
+
+ @override
+ async def on_llm_end(
+ self,
+ response: LLMResult,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """End a trace for an LLM or chat model run.
+
+ Note:
+ This async callback also handles both run types. Async chat models
+ start with `on_chat_model_start`, but there is no
+ `on_chat_model_end`; completion is routed here for callback API
+ compatibility.
+ """
+ llm_run = self._complete_llm_run(
+ response=response,
+ run_id=run_id,
+ )
+ tasks = [self._on_llm_end(llm_run), self._end_trace(llm_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_llm_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ llm_run = self._errored_llm_run(
+ error=error,
+ run_id=run_id,
+ )
+ tasks = [self._on_llm_error(llm_run), self._end_trace(llm_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_chain_start(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_type: str | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ chain_run = self._create_chain_run(
+ serialized=serialized,
+ inputs=inputs,
+ run_id=run_id,
+ tags=tags,
+ parent_run_id=parent_run_id,
+ metadata=metadata,
+ run_type=run_type,
+ name=name,
+ **kwargs,
+ )
+ tasks = [self._start_trace(chain_run), self._on_chain_start(chain_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_chain_end(
+ self,
+ outputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ chain_run = self._complete_chain_run(
+ outputs=outputs,
+ run_id=run_id,
+ inputs=inputs,
+ )
+ tasks = [self._end_trace(chain_run), self._on_chain_end(chain_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_chain_error(
+ self,
+ error: BaseException,
+ *,
+ inputs: dict[str, Any] | None = None,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> None:
+ chain_run = self._errored_chain_run(
+ error=error,
+ inputs=inputs,
+ run_id=run_id,
+ )
+ tasks = [self._end_trace(chain_run), self._on_chain_error(chain_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_tool_start(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ tool_run = self._create_tool_run(
+ serialized=serialized,
+ input_str=input_str,
+ run_id=run_id,
+ tags=tags,
+ parent_run_id=parent_run_id,
+ metadata=metadata,
+ inputs=inputs,
+ **kwargs,
+ )
+ tasks = [self._start_trace(tool_run), self._on_tool_start(tool_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_tool_end(
+ self,
+ output: Any,
+ *,
+ run_id: UUID,
+ **kwargs: Any,
+ ) -> None:
+ tool_run = self._complete_tool_run(
+ output=output,
+ run_id=run_id,
+ )
+ tasks = [self._end_trace(tool_run), self._on_tool_end(tool_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ tool_run = self._errored_tool_run(
+ error=error,
+ run_id=run_id,
+ )
+ tasks = [self._end_trace(tool_run), self._on_tool_error(tool_run)]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_retriever_start(
+ self,
+ serialized: dict[str, Any],
+ query: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ retriever_run = self._create_retrieval_run(
+ serialized=serialized,
+ query=query,
+ run_id=run_id,
+ parent_run_id=parent_run_id,
+ tags=tags,
+ metadata=metadata,
+ name=name,
+ )
+ tasks = [
+ self._start_trace(retriever_run),
+ self._on_retriever_start(retriever_run),
+ ]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_retriever_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ retrieval_run = self._errored_retrieval_run(
+ error=error,
+ run_id=run_id,
+ )
+ tasks = [
+ self._end_trace(retrieval_run),
+ self._on_retriever_error(retrieval_run),
+ ]
+ await asyncio.gather(*tasks)
+
+ @override
+ async def on_retriever_end(
+ self,
+ documents: Sequence[Document],
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ retrieval_run = self._complete_retrieval_run(
+ documents=documents,
+ run_id=run_id,
+ )
+ tasks = [self._end_trace(retrieval_run), self._on_retriever_end(retrieval_run)]
+ await asyncio.gather(*tasks)
+
+ async def _on_run_create(self, run: Run) -> None:
+ """Process a run upon creation."""
+
+ async def _on_run_update(self, run: Run) -> None:
+ """Process a run upon update."""
+
+ async def _on_llm_start(self, run: Run) -> None:
+ """Process the LLM Run upon start."""
+
+ async def _on_llm_end(self, run: Run) -> None:
+ """Process LLM/chat model run completion."""
+
+ async def _on_llm_error(self, run: Run) -> None:
+ """Process the LLM Run upon error."""
+
+ async def _on_llm_new_token(
+ self,
+ run: Run,
+ token: str,
+ chunk: GenerationChunk | ChatGenerationChunk | None,
+ ) -> None:
+ """Process new LLM token."""
+
+ async def _on_chain_start(self, run: Run) -> None:
+ """Process the Chain Run upon start."""
+
+ async def _on_chain_end(self, run: Run) -> None:
+ """Process the Chain Run."""
+
+ async def _on_chain_error(self, run: Run) -> None:
+ """Process the Chain Run upon error."""
+
+ async def _on_tool_start(self, run: Run) -> None:
+ """Process the Tool Run upon start."""
+
+ async def _on_tool_end(self, run: Run) -> None:
+ """Process the Tool Run."""
+
+ async def _on_tool_error(self, run: Run) -> None:
+ """Process the Tool Run upon error."""
+
+ async def _on_chat_model_start(self, run: Run) -> None:
+ """Process the Chat Model Run upon start."""
+
+ async def _on_retriever_start(self, run: Run) -> None:
+ """Process the Retriever Run upon start."""
+
+ async def _on_retriever_end(self, run: Run) -> None:
+ """Process the Retriever Run."""
+
+ async def _on_retriever_error(self, run: Run) -> None:
+ """Process the Retriever Run upon error."""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/context.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/context.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ad17663910fdd7bd19bcdfe786e27ad438b7276
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/context.py
@@ -0,0 +1,205 @@
+"""Context management for tracers."""
+
+from __future__ import annotations
+
+from contextlib import contextmanager
+from contextvars import ContextVar
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ cast,
+)
+from uuid import UUID
+
+from langsmith import run_helpers as ls_rh
+from langsmith import utils as ls_utils
+
+from langchain_core.tracers.langchain import LangChainTracer
+from langchain_core.tracers.run_collector import RunCollectorCallbackHandler
+
+if TYPE_CHECKING:
+ from collections.abc import Generator
+
+ from langsmith import Client as LangSmithClient
+
+ from langchain_core.callbacks.base import BaseCallbackHandler, Callbacks
+ from langchain_core.callbacks.manager import AsyncCallbackManager, CallbackManager
+
+# for backwards partial compatibility if this is imported by users but unused
+tracing_callback_var: Any = None
+tracing_v2_callback_var: ContextVar[LangChainTracer | None] = ContextVar(
+ "tracing_callback_v2", default=None
+)
+run_collector_var: ContextVar[RunCollectorCallbackHandler | None] = ContextVar(
+ "run_collector", default=None
+)
+
+
+@contextmanager
+def tracing_v2_enabled(
+ project_name: str | None = None,
+ *,
+ example_id: str | UUID | None = None,
+ tags: list[str] | None = None,
+ client: LangSmithClient | None = None,
+) -> Generator[LangChainTracer, None, None]:
+ """Instruct LangChain to log all runs in context to LangSmith.
+
+ Args:
+ project_name: The name of the project.
+
+ Defaults to `'default'`.
+ example_id: The ID of the example.
+ tags: The tags to add to the run.
+ client: The client of the langsmith.
+
+ Yields:
+ The LangChain tracer.
+
+ Example:
+ >>> with tracing_v2_enabled():
+ ... # LangChain code will automatically be traced
+
+ You can use this to fetch the LangSmith run URL:
+
+ >>> with tracing_v2_enabled() as cb:
+ ... chain.invoke("foo")
+ ... run_url = cb.get_run_url()
+ """
+ if isinstance(example_id, str):
+ example_id = UUID(example_id)
+ cb = LangChainTracer(
+ example_id=example_id,
+ project_name=project_name,
+ tags=tags,
+ client=client,
+ )
+ token = tracing_v2_callback_var.set(cb)
+ try:
+ yield cb
+ finally:
+ tracing_v2_callback_var.reset(token)
+
+
+@contextmanager
+def collect_runs() -> Generator[RunCollectorCallbackHandler, None, None]:
+ """Collect all run traces in context.
+
+ Yields:
+ The run collector callback handler.
+
+ Example:
+ >>> with collect_runs() as runs_cb:
+ chain.invoke("foo")
+ run_id = runs_cb.traced_runs[0].id
+ """
+ cb = RunCollectorCallbackHandler()
+ token = run_collector_var.set(cb)
+ try:
+ yield cb
+ finally:
+ run_collector_var.reset(token)
+
+
+def _get_trace_callbacks(
+ project_name: str | None = None,
+ example_id: str | UUID | None = None,
+ callback_manager: CallbackManager | AsyncCallbackManager | None = None,
+) -> Callbacks:
+ if _tracing_v2_is_enabled():
+ project_name_ = project_name or _get_tracer_project()
+ tracer = tracing_v2_callback_var.get() or LangChainTracer(
+ project_name=project_name_,
+ example_id=example_id,
+ )
+ if callback_manager is None:
+ cb = cast("Callbacks", [tracer])
+ else:
+ if not any(
+ isinstance(handler, LangChainTracer)
+ for handler in callback_manager.handlers
+ ):
+ callback_manager.add_handler(tracer)
+ # If it already has a LangChainTracer, we don't need to add another one.
+ # this would likely mess up the trace hierarchy.
+ cb = callback_manager
+ else:
+ cb = None
+ return cb
+
+
+def _tracing_v2_is_enabled() -> bool | Literal["local"]:
+ if tracing_v2_callback_var.get() is not None:
+ return True
+ return ls_utils.tracing_is_enabled()
+
+
+def _get_tracer_project() -> str:
+ tracing_context = ls_rh.get_tracing_context()
+ run_tree = tracing_context["parent"]
+ if run_tree is None and tracing_context["project_name"] is not None:
+ return cast("str", tracing_context["project_name"])
+ return getattr(
+ run_tree,
+ "session_name",
+ getattr(
+ # Note, if people are trying to nest @traceable functions and the
+ # tracing_v2_enabled context manager, this will likely mess up the
+ # tree structure.
+ tracing_v2_callback_var.get(),
+ "project",
+ # Have to set this to a string even though it always will return
+ # a string because `get_tracer_project` technically can return
+ # None, but only when a specific argument is supplied.
+ # Therefore, this just tricks the mypy type checker
+ str(ls_utils.get_tracer_project()),
+ ),
+ )
+
+
+_configure_hooks: list[
+ tuple[
+ ContextVar[BaseCallbackHandler | None],
+ bool,
+ type[BaseCallbackHandler] | None,
+ str | None,
+ ]
+] = []
+
+
+def register_configure_hook(
+ context_var: ContextVar[Any | None],
+ inheritable: bool, # noqa: FBT001
+ handle_class: type[BaseCallbackHandler] | None = None,
+ env_var: str | None = None,
+) -> None:
+ """Register a configure hook.
+
+ Args:
+ context_var: The context variable.
+ inheritable: Whether the context variable is inheritable.
+ handle_class: The callback handler class.
+ env_var: The environment variable.
+
+ 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:
+ msg = "If env_var is set, handle_class must also be set to a non-None value."
+ raise ValueError(msg)
+
+ _configure_hooks.append(
+ (
+ # the typings of ContextVar do not have the generic arg set as covariant
+ # so we have to cast it
+ cast("ContextVar[BaseCallbackHandler | None]", context_var),
+ inheritable,
+ handle_class,
+ env_var,
+ )
+ )
+
+
+register_configure_hook(run_collector_var, inheritable=False)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/core.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..75614e3c881de46c60a651b67523fd1797c706e8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/core.py
@@ -0,0 +1,724 @@
+"""Utilities for the root listener."""
+
+from __future__ import annotations
+
+import logging
+import traceback
+from abc import ABC, abstractmethod
+from datetime import datetime, timezone
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ cast,
+)
+
+from langchain_core.exceptions import TracerException
+from langchain_core.load import dumpd
+from langchain_core.tracers.schemas import Run
+
+if TYPE_CHECKING:
+ from collections.abc import Coroutine, Sequence
+ from uuid import UUID
+
+ from tenacity import RetryCallState
+
+ from langchain_core.documents import Document
+ from langchain_core.messages import BaseMessage
+ from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ GenerationChunk,
+ LLMResult,
+ )
+
+logger = logging.getLogger(__name__)
+
+SCHEMA_FORMAT_TYPE = Literal["original", "streaming_events"]
+
+
+class _TracerCore(ABC):
+ """Abstract base class for tracers.
+
+ This class provides common methods, and reusable methods for tracers.
+ """
+
+ log_missing_parent: bool = True
+
+ def __init__(
+ self,
+ *,
+ _schema_format: Literal[
+ "original", "streaming_events", "original+chat"
+ ] = "original",
+ run_map: dict[str, Run] | None = None,
+ order_map: dict[UUID, tuple[UUID, str]] | None = None,
+ _external_run_ids: dict[str, int] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize the tracer.
+
+ Args:
+ _schema_format: Primarily changes how the inputs and outputs are handled.
+
+ For internal use only. This API will change.
+
+ - `'original'` is the format used by all current tracers.
+
+ This format is slightly inconsistent with respect to inputs and
+ outputs.
+ - `'streaming_events'` is used for supporting streaming events, for
+ internal usage. It will likely change in the future, or be
+ deprecated entirely in favor of a dedicated async tracer for
+ streaming events.
+ - `'original+chat'` is a format that is the same as `'original'` except
+ it does NOT raise an attribute error `on_chat_model_start`
+ run_map: Optional shared map of run ID to run.
+ order_map: Optional shared map of run ID to trace ordering data.
+ _external_run_ids: Optional shared set of externally injected run IDs.
+ **kwargs: Additional keyword arguments that will be passed to the
+ superclass.
+ """
+ super().__init__(**kwargs)
+
+ self._schema_format = _schema_format # For internal use only API will change.
+
+ self.run_map = run_map if run_map is not None else {}
+ """Map of run ID to run. Cleared on run end."""
+
+ self.order_map = order_map if order_map is not None else {}
+ """Map of run ID to (trace_id, dotted_order). Cleared when tracer GCed."""
+
+ self._external_run_ids: dict[str, int] = (
+ _external_run_ids if _external_run_ids is not None else {}
+ )
+ """Refcount of active children per externally-injected run ID.
+
+ These runs are added to `run_map` so child runs can find their parent,
+ but they are not managed by the tracer's callback lifecycle. When
+ the last child finishes the entry is evicted to avoid memory leaks.
+ """
+
+ @abstractmethod
+ def _persist_run(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Persist a run."""
+
+ @staticmethod
+ def _add_child_run(
+ parent_run: Run,
+ child_run: Run,
+ ) -> None:
+ """Add child run to a chain run or tool run."""
+ parent_run.child_runs.append(child_run)
+
+ @staticmethod
+ def _get_stacktrace(error: BaseException) -> str:
+ """Get the stacktrace of the parent error."""
+ msg = repr(error)
+ try:
+ tb = traceback.format_exception(error)
+ return (msg + "\n\n".join(tb)).strip()
+ except Exception:
+ return msg
+
+ def _start_trace(self, run: Run) -> Coroutine[Any, Any, None] | None: # type: ignore[return]
+ current_dotted_order = run.start_time.strftime("%Y%m%dT%H%M%S%fZ") + str(run.id)
+ if run.parent_run_id:
+ if parent := self.order_map.get(run.parent_run_id):
+ run.trace_id, run.dotted_order = parent
+ run.dotted_order += "." + current_dotted_order
+ if parent_run := self.run_map.get(str(run.parent_run_id)):
+ self._add_child_run(parent_run, run)
+ parent_key = str(run.parent_run_id)
+ if parent_key in self._external_run_ids:
+ self._external_run_ids[parent_key] += 1
+ else:
+ if self.log_missing_parent:
+ logger.debug(
+ "Parent run %s not found for run %s. Treating as a root run.",
+ run.parent_run_id,
+ run.id,
+ )
+ run.parent_run_id = None
+ run.trace_id = run.id
+ run.dotted_order = current_dotted_order
+ else:
+ run.trace_id = run.id
+ run.dotted_order = current_dotted_order
+ self.order_map[run.id] = (run.trace_id, run.dotted_order)
+ self.run_map[str(run.id)] = run
+
+ def _get_run(self, run_id: UUID, run_type: str | set[str] | None = None) -> Run:
+ try:
+ run = self.run_map[str(run_id)]
+ except KeyError as exc:
+ msg = f"No indexed run ID {run_id}."
+ raise TracerException(msg) from exc
+
+ if isinstance(run_type, str):
+ run_types: set[str] | None = {run_type}
+ else:
+ run_types = run_type
+ if run_types is not None and run.run_type not in run_types:
+ msg = (
+ f"Found {run.run_type} run at ID {run_id}, "
+ f"but expected {run_types} run."
+ )
+ raise TracerException(msg)
+ return run
+
+ def _create_chat_model_run(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Create a chat model run."""
+ if self._schema_format not in {"streaming_events", "original+chat"}:
+ # Please keep this un-implemented for backwards compatibility.
+ # When it's unimplemented old tracers that use the "original" format
+ # fallback on the on_llm_start method implementation if they
+ # find that the on_chat_model_start method is not implemented.
+ # This can eventually be cleaned up by writing a "modern" tracer
+ # that has all the updated schema changes corresponding to
+ # the "streaming_events" format.
+ msg = (
+ f"Chat model tracing is not supported in "
+ f"for {self._schema_format} format."
+ )
+ raise NotImplementedError(msg)
+ start_time = datetime.now(timezone.utc)
+ if metadata:
+ kwargs.update({"metadata": metadata})
+ return Run(
+ id=run_id,
+ parent_run_id=parent_run_id,
+ serialized=serialized,
+ inputs={"messages": [[dumpd(msg) for msg in batch] for batch in messages]},
+ extra=kwargs,
+ events=[{"name": "start", "time": start_time}],
+ start_time=start_time,
+ # WARNING: This is valid ONLY for streaming_events.
+ # run_type="llm" is what's used by virtually all tracers.
+ # Changing this to "chat_model" may break triggering on_llm_start
+ run_type="chat_model",
+ tags=tags,
+ name=name,
+ )
+
+ def _create_llm_run(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Create a llm run."""
+ start_time = datetime.now(timezone.utc)
+ if metadata:
+ kwargs.update({"metadata": metadata})
+ return Run(
+ id=run_id,
+ parent_run_id=parent_run_id,
+ serialized=serialized,
+ # TODO: Figure out how to expose kwargs here
+ inputs={"prompts": prompts},
+ extra=kwargs,
+ events=[{"name": "start", "time": start_time}],
+ start_time=start_time,
+ run_type="llm",
+ tags=tags or [],
+ name=name,
+ )
+
+ def _llm_run_with_token_event(
+ self,
+ token: str,
+ run_id: UUID,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ parent_run_id: UUID | None = None,
+ ) -> Run:
+ """Append token event to LLM run and return the run."""
+ _ = parent_run_id
+ llm_run = self._get_run(run_id, run_type={"llm", "chat_model"})
+ event_kwargs: dict[str, Any] = {"token": token}
+ if chunk:
+ event_kwargs["chunk"] = chunk
+ llm_run.events.append(
+ {
+ "name": "new_token",
+ "time": datetime.now(timezone.utc),
+ "kwargs": event_kwargs,
+ },
+ )
+ return llm_run
+
+ def _llm_run_with_retry_event(
+ self,
+ retry_state: RetryCallState,
+ run_id: UUID,
+ ) -> Run:
+ llm_run = self._get_run(run_id)
+ retry_d: dict[str, Any] = {
+ "slept": retry_state.idle_for,
+ "attempt": retry_state.attempt_number,
+ }
+ if retry_state.outcome is None:
+ retry_d["outcome"] = "N/A"
+ elif retry_state.outcome.failed:
+ retry_d["outcome"] = "failed"
+ exception = retry_state.outcome.exception()
+ retry_d["exception"] = str(exception)
+ retry_d["exception_type"] = exception.__class__.__name__
+ else:
+ retry_d["outcome"] = "success"
+ retry_d["result"] = str(retry_state.outcome.result())
+ llm_run.events.append(
+ {
+ "name": "retry",
+ "time": datetime.now(timezone.utc),
+ "kwargs": retry_d,
+ },
+ )
+ return llm_run
+
+ def _complete_llm_run(self, response: LLMResult, run_id: UUID) -> Run:
+ llm_run = self._get_run(run_id, run_type={"llm", "chat_model"})
+ if getattr(llm_run, "outputs", None) is None:
+ llm_run.outputs = {}
+ else:
+ llm_run.outputs = cast("dict[str, Any]", llm_run.outputs)
+ if not llm_run.extra.get("__omit_auto_outputs", False):
+ llm_run.outputs.update(response.model_dump())
+ for i, generations in enumerate(response.generations):
+ for j, generation in enumerate(generations):
+ output_generation = llm_run.outputs["generations"][i][j]
+ if "message" in output_generation:
+ output_generation["message"] = dumpd(
+ cast("ChatGeneration", generation).message
+ )
+ llm_run.end_time = datetime.now(timezone.utc)
+ llm_run.events.append({"name": "end", "time": llm_run.end_time})
+
+ tool_call_count = 0
+ for generations in response.generations:
+ for generation in generations:
+ if hasattr(generation, "message"):
+ msg = generation.message
+ if hasattr(msg, "tool_calls") and msg.tool_calls:
+ tool_call_count += len(msg.tool_calls)
+ if tool_call_count > 0:
+ llm_run.extra["tool_call_count"] = tool_call_count
+
+ return llm_run
+
+ def _errored_llm_run(
+ self, error: BaseException, run_id: UUID, response: LLMResult | None = None
+ ) -> Run:
+ llm_run = self._get_run(run_id, run_type={"llm", "chat_model"})
+ llm_run.error = self._get_stacktrace(error)
+ if response:
+ if getattr(llm_run, "outputs", None) is None:
+ llm_run.outputs = {}
+ else:
+ llm_run.outputs = cast("dict[str, Any]", llm_run.outputs)
+ if not llm_run.extra.get("__omit_auto_outputs", False):
+ llm_run.outputs.update(response.model_dump())
+ for i, generations in enumerate(response.generations):
+ for j, generation in enumerate(generations):
+ output_generation = llm_run.outputs["generations"][i][j]
+ if "message" in output_generation:
+ output_generation["message"] = dumpd(
+ cast("ChatGeneration", generation).message
+ )
+ llm_run.end_time = datetime.now(timezone.utc)
+ llm_run.events.append({"name": "error", "time": llm_run.end_time})
+
+ return llm_run
+
+ def _create_chain_run(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_type: str | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Create a chain Run."""
+ start_time = datetime.now(timezone.utc)
+ if metadata:
+ kwargs.update({"metadata": metadata})
+ return Run(
+ id=run_id,
+ parent_run_id=parent_run_id,
+ serialized=serialized,
+ inputs=self._get_chain_inputs(inputs),
+ extra=kwargs,
+ events=[{"name": "start", "time": start_time}],
+ start_time=start_time,
+ child_runs=[],
+ run_type=run_type or "chain",
+ name=name,
+ tags=tags or [],
+ )
+
+ def _get_chain_inputs(self, inputs: Any) -> Any:
+ """Get the inputs for a chain run."""
+ if self._schema_format in {"original", "original+chat"}:
+ return inputs if isinstance(inputs, dict) else {"input": inputs}
+ if self._schema_format == "streaming_events":
+ return {
+ "input": inputs,
+ }
+ msg = f"Invalid format: {self._schema_format}"
+ raise ValueError(msg)
+
+ def _get_chain_outputs(self, outputs: Any) -> Any:
+ """Get the outputs for a chain run."""
+ if self._schema_format in {"original", "original+chat"}:
+ return outputs if isinstance(outputs, dict) else {"output": outputs}
+ if self._schema_format == "streaming_events":
+ return {
+ "output": outputs,
+ }
+ msg = f"Invalid format: {self._schema_format}"
+ raise ValueError(msg)
+
+ def _complete_chain_run(
+ self,
+ outputs: dict[str, Any],
+ run_id: UUID,
+ inputs: dict[str, Any] | None = None,
+ ) -> Run:
+ """Update a chain run with outputs and end time."""
+ chain_run = self._get_run(run_id)
+ if getattr(chain_run, "outputs", None) is None:
+ chain_run.outputs = {}
+ if not chain_run.extra.get("__omit_auto_outputs", False):
+ cast("dict[str, Any]", chain_run.outputs).update(
+ self._get_chain_outputs(outputs)
+ )
+ chain_run.end_time = datetime.now(timezone.utc)
+ chain_run.events.append({"name": "end", "time": chain_run.end_time})
+ if inputs is not None:
+ chain_run.inputs = self._get_chain_inputs(inputs)
+ return chain_run
+
+ def _errored_chain_run(
+ self,
+ error: BaseException,
+ inputs: dict[str, Any] | None,
+ run_id: UUID,
+ ) -> Run:
+ chain_run = self._get_run(run_id)
+ chain_run.error = self._get_stacktrace(error)
+ chain_run.end_time = datetime.now(timezone.utc)
+ chain_run.events.append({"name": "error", "time": chain_run.end_time})
+ if inputs is not None:
+ chain_run.inputs = self._get_chain_inputs(inputs)
+ return chain_run
+
+ def _create_tool_run(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Create a tool run."""
+ start_time = datetime.now(timezone.utc)
+ if metadata:
+ kwargs.update({"metadata": metadata})
+
+ if self._schema_format in {"original", "original+chat"}:
+ inputs = inputs if isinstance(inputs, dict) else {"input": input_str}
+ elif self._schema_format == "streaming_events":
+ inputs = {"input": inputs}
+ else:
+ msg = f"Invalid format: {self._schema_format}"
+ raise AssertionError(msg)
+
+ return Run(
+ id=run_id,
+ parent_run_id=parent_run_id,
+ serialized=serialized,
+ # Wrapping in dict since Run requires a dict object.
+ inputs=inputs,
+ extra=kwargs,
+ events=[{"name": "start", "time": start_time}],
+ start_time=start_time,
+ child_runs=[],
+ run_type="tool",
+ tags=tags or [],
+ name=name,
+ )
+
+ def _complete_tool_run(
+ self,
+ output: dict[str, Any],
+ run_id: UUID,
+ ) -> Run:
+ """Update a tool run with outputs and end time."""
+ tool_run = self._get_run(run_id, run_type="tool")
+ if getattr(tool_run, "outputs", None) is None:
+ tool_run.outputs = {}
+ if not tool_run.extra.get("__omit_auto_outputs", False):
+ cast("dict[str, Any]", tool_run.outputs).update({"output": output})
+ tool_run.end_time = datetime.now(timezone.utc)
+ tool_run.events.append({"name": "end", "time": tool_run.end_time})
+ return tool_run
+
+ def _errored_tool_run(
+ self,
+ error: BaseException,
+ run_id: UUID,
+ ) -> Run:
+ """Update a tool run with error and end time."""
+ tool_run = self._get_run(run_id, run_type="tool")
+ tool_run.error = self._get_stacktrace(error)
+ tool_run.end_time = datetime.now(timezone.utc)
+ tool_run.events.append({"name": "error", "time": tool_run.end_time})
+ return tool_run
+
+ def _create_retrieval_run(
+ self,
+ serialized: dict[str, Any],
+ query: str,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Create a retrieval run."""
+ start_time = datetime.now(timezone.utc)
+ if metadata:
+ kwargs.update({"metadata": metadata})
+ return Run(
+ id=run_id,
+ name=name or "Retriever",
+ parent_run_id=parent_run_id,
+ serialized=serialized,
+ inputs={"query": query},
+ extra=kwargs,
+ events=[{"name": "start", "time": start_time}],
+ start_time=start_time,
+ tags=tags,
+ child_runs=[],
+ run_type="retriever",
+ )
+
+ def _complete_retrieval_run(
+ self,
+ documents: Sequence[Document],
+ run_id: UUID,
+ ) -> Run:
+ """Update a retrieval run with outputs and end time."""
+ retrieval_run = self._get_run(run_id, run_type="retriever")
+ if getattr(retrieval_run, "outputs", None) is None:
+ retrieval_run.outputs = {}
+ if not retrieval_run.extra.get("__omit_auto_outputs", False):
+ cast("dict[str, Any]", retrieval_run.outputs).update(
+ {"documents": documents}
+ )
+ retrieval_run.end_time = datetime.now(timezone.utc)
+ retrieval_run.events.append({"name": "end", "time": retrieval_run.end_time})
+ return retrieval_run
+
+ def _errored_retrieval_run(
+ self,
+ error: BaseException,
+ run_id: UUID,
+ ) -> Run:
+ retrieval_run = self._get_run(run_id, run_type="retriever")
+ retrieval_run.error = self._get_stacktrace(error)
+ retrieval_run.end_time = datetime.now(timezone.utc)
+ retrieval_run.events.append({"name": "error", "time": retrieval_run.end_time})
+ return retrieval_run
+
+ def __deepcopy__(self, memo: dict) -> _TracerCore:
+ """Return self deepcopied."""
+ return self
+
+ def __copy__(self) -> _TracerCore:
+ """Return self copied."""
+ return self
+
+ def _end_trace(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """End a trace for a run.
+
+ Args:
+ run: The run.
+ """
+ _ = run
+ return None
+
+ def _on_run_create(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process a run upon creation.
+
+ Args:
+ run: The created run.
+ """
+ _ = run
+ return None
+
+ def _on_run_update(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process a run upon update.
+
+ Args:
+ run: The updated run.
+ """
+ _ = run
+ return None
+
+ def _on_llm_start(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the LLM Run upon start.
+
+ Args:
+ run: The LLM run.
+ """
+ _ = run
+ return None
+
+ def _on_llm_new_token(
+ self,
+ run: Run,
+ token: str,
+ chunk: GenerationChunk | ChatGenerationChunk | None,
+ ) -> Coroutine[Any, Any, None] | None:
+ """Process new LLM token.
+
+ Args:
+ run: The LLM run.
+ token: The new token.
+ chunk: Optional chunk.
+ """
+ _ = (run, token, chunk)
+ return None
+
+ def _on_llm_end(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the LLM Run.
+
+ Args:
+ run: The LLM run.
+ """
+ _ = run
+ return None
+
+ def _on_llm_error(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the LLM Run upon error.
+
+ Args:
+ run: The LLM run.
+ """
+ _ = run
+ return None
+
+ def _on_chain_start(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Chain Run upon start.
+
+ Args:
+ run: The chain run.
+ """
+ _ = run
+ return None
+
+ def _on_chain_end(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Chain Run.
+
+ Args:
+ run: The chain run.
+ """
+ _ = run
+ return None
+
+ def _on_chain_error(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Chain Run upon error.
+
+ Args:
+ run: The chain run.
+ """
+ _ = run
+ return None
+
+ def _on_tool_start(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Tool Run upon start.
+
+ Args:
+ run: The tool run.
+ """
+ _ = run
+ return None
+
+ def _on_tool_end(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Tool Run.
+
+ Args:
+ run: The tool run.
+ """
+ _ = run
+ return None
+
+ def _on_tool_error(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Tool Run upon error.
+
+ Args:
+ run: The tool run.
+ """
+ _ = run
+ return None
+
+ def _on_chat_model_start(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Chat Model Run upon start.
+
+ Args:
+ run: The chat model run.
+ """
+ _ = run
+ return None
+
+ def _on_retriever_start(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Retriever Run upon start.
+
+ Args:
+ run: The retriever run.
+ """
+ _ = run
+ return None
+
+ def _on_retriever_end(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Retriever Run.
+
+ Args:
+ run: The retriever run.
+ """
+ _ = run
+ return None
+
+ def _on_retriever_error(self, run: Run) -> Coroutine[Any, Any, None] | None:
+ """Process the Retriever Run upon error.
+
+ Args:
+ run: The retriever run.
+ """
+ _ = run
+ return None
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/evaluation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/evaluation.py
new file mode 100644
index 0000000000000000000000000000000000000000..22c6f600f58c4ed38ee9e876c656e30172fe6b99
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/evaluation.py
@@ -0,0 +1,226 @@
+"""A tracer that runs evaluators over completed runs."""
+
+from __future__ import annotations
+
+import logging
+import threading
+import weakref
+from concurrent.futures import Future, ThreadPoolExecutor, wait
+from typing import TYPE_CHECKING, Any, cast
+from uuid import UUID
+
+import langsmith
+from langsmith.evaluation.evaluator import EvaluationResult, EvaluationResults
+
+from langchain_core.tracers import langchain as langchain_tracer
+from langchain_core.tracers._compat import run_copy
+from langchain_core.tracers.base import BaseTracer
+from langchain_core.tracers.context import tracing_v2_enabled
+from langchain_core.tracers.langchain import _get_executor
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from langchain_core.tracers.schemas import Run
+
+logger = logging.getLogger(__name__)
+
+_TRACERS: weakref.WeakSet[EvaluatorCallbackHandler] = weakref.WeakSet()
+
+
+def wait_for_all_evaluators() -> None:
+ """Wait for all tracers to finish."""
+ for tracer in list(_TRACERS):
+ if tracer is not None:
+ tracer.wait_for_futures()
+
+
+class EvaluatorCallbackHandler(BaseTracer):
+ """Tracer that runs a run evaluator whenever a run is persisted.
+
+ Attributes:
+ client: The LangSmith client instance used for evaluating the runs.
+ """
+
+ name: str = "evaluator_callback_handler"
+
+ example_id: UUID | None = None
+ """The example ID associated with the runs."""
+
+ client: langsmith.Client
+ """The LangSmith client instance used for evaluating the runs."""
+
+ evaluators: Sequence[langsmith.RunEvaluator] = ()
+ """The sequence of run evaluators to be executed."""
+
+ executor: ThreadPoolExecutor | None = None
+ """The thread pool executor used for running the evaluators."""
+
+ futures: weakref.WeakSet[Future] = weakref.WeakSet()
+ """The set of futures representing the running evaluators."""
+
+ skip_unfinished: bool = True
+ """Whether to skip runs that are not finished or raised an error."""
+
+ project_name: str | None = None
+ """The LangSmith project name to be organize eval chain runs under."""
+
+ logged_eval_results: dict[tuple[str, str], list[EvaluationResult]]
+
+ lock: threading.Lock
+
+ def __init__(
+ self,
+ evaluators: Sequence[langsmith.RunEvaluator],
+ client: langsmith.Client | None = None,
+ example_id: UUID | str | None = None,
+ skip_unfinished: bool = True, # noqa: FBT001,FBT002
+ project_name: str | None = "evaluators",
+ max_concurrency: int | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Create an EvaluatorCallbackHandler.
+
+ Args:
+ evaluators: The run evaluators to apply to all top level runs.
+ client: The LangSmith client instance to use for evaluating the runs.
+
+ If not specified, a new instance will be created.
+ example_id: The example ID to be associated with the runs.
+ skip_unfinished: Whether to skip unfinished runs.
+ project_name: The LangSmith project name to be organize eval chain runs
+ under.
+ max_concurrency: The maximum number of concurrent evaluators to run.
+ """
+ super().__init__(**kwargs)
+ self.example_id = (
+ UUID(example_id) if isinstance(example_id, str) else example_id
+ )
+ self.client = client or langchain_tracer.get_client()
+ self.evaluators = evaluators
+ if max_concurrency is None:
+ self.executor = _get_executor()
+ elif max_concurrency > 0:
+ self.executor = ThreadPoolExecutor(max_workers=max_concurrency)
+ weakref.finalize(
+ self,
+ lambda: cast("ThreadPoolExecutor", self.executor).shutdown(wait=True),
+ )
+ else:
+ self.executor = None
+ self.futures = weakref.WeakSet[Future[None]]()
+ self.skip_unfinished = skip_unfinished
+ self.project_name = project_name
+ self.logged_eval_results = {}
+ self.lock = threading.Lock()
+ _TRACERS.add(self)
+
+ def _evaluate_in_project(self, run: Run, evaluator: langsmith.RunEvaluator) -> None:
+ """Evaluate the run in the project.
+
+ Args:
+ run: The run to be evaluated.
+ evaluator: The evaluator to use for evaluating the run.
+ """
+ try:
+ if self.project_name is None:
+ eval_result = self.client.evaluate_run(run, evaluator)
+ eval_results = [eval_result]
+ with tracing_v2_enabled(
+ project_name=self.project_name, tags=["eval"], client=self.client
+ ) as cb:
+ reference_example = (
+ self.client.read_example(run.reference_example_id)
+ if run.reference_example_id
+ else None
+ )
+ evaluation_result = evaluator.evaluate_run(
+ # This is subclass, but getting errors for some reason
+ run, # type: ignore[arg-type]
+ example=reference_example,
+ )
+ eval_results = self._log_evaluation_feedback(
+ evaluation_result,
+ run,
+ source_run_id=cb.latest_run.id if cb.latest_run else None,
+ )
+ except Exception:
+ logger.exception(
+ "Error evaluating run %s with %s",
+ run.id,
+ evaluator.__class__.__name__,
+ )
+ raise
+ example_id = str(run.reference_example_id)
+ with self.lock:
+ for res in eval_results:
+ run_id = str(getattr(res, "target_run_id", run.id))
+ self.logged_eval_results.setdefault((run_id, example_id), []).append(
+ res
+ )
+
+ @staticmethod
+ def _select_eval_results(
+ results: EvaluationResult | EvaluationResults,
+ ) -> list[EvaluationResult]:
+ if isinstance(results, EvaluationResult):
+ results_ = [results]
+ elif isinstance(results, dict) and "results" in results:
+ results_ = results["results"]
+ else:
+ msg = (
+ f"Invalid evaluation result type {type(results)}."
+ " Expected EvaluationResult or EvaluationResults."
+ )
+ raise TypeError(msg)
+ return results_
+
+ def _log_evaluation_feedback(
+ self,
+ evaluator_response: EvaluationResult | EvaluationResults,
+ run: Run,
+ source_run_id: UUID | None = None,
+ ) -> list[EvaluationResult]:
+ results = self._select_eval_results(evaluator_response)
+ for res in results:
+ source_info_: dict[str, Any] = {}
+ if res.evaluator_info:
+ source_info_ = {**res.evaluator_info, **source_info_}
+ run_id_ = getattr(res, "target_run_id", None)
+ if run_id_ is None:
+ run_id_ = run.id
+ self.client.create_feedback(
+ run_id_,
+ res.key,
+ score=res.score,
+ value=res.value,
+ comment=res.comment,
+ correction=res.correction,
+ source_info=source_info_,
+ source_run_id=res.source_run_id or source_run_id,
+ feedback_source_type=langsmith.schemas.FeedbackSourceType.MODEL,
+ )
+ return results
+
+ def _persist_run(self, run: Run) -> None:
+ """Run the evaluator on the run.
+
+ Args:
+ run: The run to be evaluated.
+ """
+ if self.skip_unfinished and not run.outputs:
+ logger.debug("Skipping unfinished run %s", run.id)
+ return
+ run_ = run_copy(run)
+ run_.reference_example_id = self.example_id
+ for evaluator in self.evaluators:
+ if self.executor is None:
+ self._evaluate_in_project(run_, evaluator)
+ else:
+ self.futures.add(
+ self.executor.submit(self._evaluate_in_project, run_, evaluator)
+ )
+
+ def wait_for_futures(self) -> None:
+ """Wait for all futures to complete."""
+ wait(self.futures)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/event_stream.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/event_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..399a7c19b6eb9db32a6db602bf33b703c42217c5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/event_stream.py
@@ -0,0 +1,1100 @@
+"""Internal tracer to power the event stream API."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import logging
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ TypedDict,
+ TypeVar,
+ cast,
+)
+
+from typing_extensions import NotRequired, override
+
+from langchain_core.callbacks.base import AsyncCallbackHandler, BaseCallbackManager
+from langchain_core.messages import AIMessageChunk, BaseMessage, BaseMessageChunk
+from langchain_core.outputs import (
+ ChatGenerationChunk,
+ GenerationChunk,
+ LLMResult,
+)
+from langchain_core.runnables import ensure_config
+from langchain_core.runnables.schema import (
+ CustomStreamEvent,
+ EventData,
+ StandardStreamEvent,
+ StreamEvent,
+)
+from langchain_core.runnables.utils import (
+ Input,
+ Output,
+ _RootEventFilter,
+)
+from langchain_core.tracers._streaming import _StreamingCallbackHandler
+from langchain_core.tracers.log_stream import (
+ LogStreamCallbackHandler,
+ RunLog,
+ _astream_log_implementation,
+)
+from langchain_core.tracers.memory_stream import _MemoryStream
+from langchain_core.utils.aiter import aclosing
+from langchain_core.utils.uuid import uuid7
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator, Sequence
+ from uuid import UUID
+
+ from langchain_core.documents import Document
+ from langchain_core.runnables import Runnable, RunnableConfig
+ from langchain_core.tracers.log_stream import LogEntry
+
+logger = logging.getLogger(__name__)
+
+
+class RunInfo(TypedDict):
+ """Information about a run.
+
+ This is used to keep track of the metadata associated with a run.
+ """
+
+ name: str
+ """The name of the run."""
+
+ tags: list[str]
+ """The tags associated with the run."""
+
+ metadata: dict[str, Any]
+ """The metadata associated with the run."""
+
+ run_type: str
+ """The type of the run."""
+
+ inputs: NotRequired[Any]
+ """The inputs to the run."""
+
+ parent_run_id: UUID | None
+ """The ID of the parent run."""
+
+ tool_call_id: NotRequired[str | None]
+ """The tool call ID associated with the run."""
+
+
+def _assign_name(name: str | None, serialized: dict[str, Any] | None) -> str:
+ """Assign a name to a run."""
+ if name is not None:
+ return name
+ if serialized is not None:
+ if "name" in serialized:
+ return cast("str", serialized["name"])
+ if "id" in serialized:
+ return cast("str", serialized["id"][-1])
+ return "Unnamed"
+
+
+T = TypeVar("T")
+
+
+class _AstreamEventsCallbackHandler(AsyncCallbackHandler, _StreamingCallbackHandler):
+ """An implementation of an async callback handler for astream events."""
+
+ def __init__(
+ self,
+ *args: Any,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize the tracer."""
+ super().__init__(*args, **kwargs)
+ # Map of run ID to run info.
+ # the entry corresponding to a given run id is cleaned
+ # up when each corresponding run ends.
+ self.run_map: dict[UUID, RunInfo] = {}
+ # The callback event that corresponds to the end of a parent run
+ # may be invoked BEFORE the callback event that corresponds to the end
+ # of a child run, which results in clean up of run_map.
+ # So we keep track of the mapping between children and parent run IDs
+ # in a separate container. This container is GCed when the tracer is GCed.
+ self.parent_map: dict[UUID, UUID | None] = {}
+
+ self.is_tapped: dict[UUID, Any] = {}
+
+ # Filter which events will be sent over the queue.
+ self.root_event_filter = _RootEventFilter(
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ )
+
+ try:
+ loop = asyncio.get_event_loop()
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ memory_stream = _MemoryStream[StreamEvent](loop)
+ self.send_stream = memory_stream.get_send_stream()
+ self.receive_stream = memory_stream.get_receive_stream()
+
+ def _get_parent_ids(self, run_id: UUID) -> list[str]:
+ """Get the parent IDs of a run (non-recursively) cast to strings."""
+ parent_ids = []
+
+ while parent_id := self.parent_map.get(run_id):
+ str_parent_id = str(parent_id)
+ if str_parent_id in parent_ids:
+ msg = (
+ f"Parent ID {parent_id} is already in the parent_ids list. "
+ f"This should never happen."
+ )
+ raise AssertionError(msg)
+ parent_ids.append(str_parent_id)
+ run_id = parent_id
+
+ # Return the parent IDs in reverse order, so that the first
+ # parent ID is the root and the last ID is the immediate parent.
+ return parent_ids[::-1]
+
+ def _send(self, event: StreamEvent, event_type: str) -> None:
+ """Send an event to the stream."""
+ if self.root_event_filter.include_event(event, event_type):
+ self.send_stream.send_nowait(event)
+
+ def __aiter__(self) -> AsyncIterator[Any]:
+ """Iterate over the receive stream.
+
+ Returns:
+ An async iterator over the receive stream.
+ """
+ return self.receive_stream.__aiter__()
+
+ async def tap_output_aiter(
+ self, run_id: UUID, output: AsyncIterator[T]
+ ) -> AsyncIterator[T]:
+ """Tap the output aiter.
+
+ This method is used to tap the output of a `Runnable` that produces an async
+ iterator. It is used to generate stream events for the output of the `Runnable`.
+
+ Args:
+ run_id: The ID of the run.
+ output: The output of the `Runnable`.
+
+ Yields:
+ The output of the `Runnable`.
+ """
+ sentinel = object()
+ # atomic check and set
+ tap = self.is_tapped.setdefault(run_id, sentinel)
+ # wait for first chunk
+ first = await anext(output, sentinel)
+ if first is sentinel:
+ return
+ # get run info
+ run_info = self.run_map.get(run_id)
+ if run_info is None:
+ # run has finished, don't issue any stream events
+ yield cast("T", first)
+ return
+ if tap is sentinel:
+ # if we are the first to tap, issue stream events
+ event: StandardStreamEvent = {
+ "event": f"on_{run_info['run_type']}_stream",
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "data": {},
+ "parent_ids": self._get_parent_ids(run_id),
+ }
+ self._send({**event, "data": {"chunk": first}}, run_info["run_type"])
+ yield cast("T", first)
+ # consume the rest of the output
+ async for chunk in output:
+ self._send(
+ {**event, "data": {"chunk": chunk}},
+ run_info["run_type"],
+ )
+ yield chunk
+ else:
+ # otherwise just pass through
+ yield cast("T", first)
+ # consume the rest of the output
+ async for chunk in output:
+ yield chunk
+
+ def tap_output_iter(self, run_id: UUID, output: Iterator[T]) -> Iterator[T]:
+ """Tap the output iter.
+
+ Args:
+ run_id: The ID of the run.
+ output: The output of the `Runnable`.
+
+ Yields:
+ The output of the `Runnable`.
+ """
+ sentinel = object()
+ # atomic check and set
+ tap = self.is_tapped.setdefault(run_id, sentinel)
+ # wait for first chunk
+ first = next(output, sentinel)
+ if first is sentinel:
+ return
+ # get run info
+ run_info = self.run_map.get(run_id)
+ if run_info is None:
+ # run has finished, don't issue any stream events
+ yield cast("T", first)
+ return
+ if tap is sentinel:
+ # if we are the first to tap, issue stream events
+ event: StandardStreamEvent = {
+ "event": f"on_{run_info['run_type']}_stream",
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "data": {},
+ "parent_ids": self._get_parent_ids(run_id),
+ }
+ self._send({**event, "data": {"chunk": first}}, run_info["run_type"])
+ yield cast("T", first)
+ # consume the rest of the output
+ for chunk in output:
+ self._send(
+ {**event, "data": {"chunk": chunk}},
+ run_info["run_type"],
+ )
+ yield chunk
+ else:
+ # otherwise just pass through
+ yield cast("T", first)
+ # consume the rest of the output
+ for chunk in output:
+ yield chunk
+
+ def _write_run_start_info(
+ self,
+ run_id: UUID,
+ *,
+ tags: list[str] | None,
+ metadata: dict[str, Any] | None,
+ parent_run_id: UUID | None,
+ name_: str,
+ run_type: str,
+ **kwargs: Any,
+ ) -> None:
+ """Update the run info."""
+ info: RunInfo = {
+ "tags": tags or [],
+ "metadata": metadata or {},
+ "name": name_,
+ "run_type": run_type,
+ "parent_run_id": parent_run_id,
+ }
+
+ if "inputs" in kwargs:
+ # Handle inputs in a special case to allow inputs to be an
+ # optionally provided and distinguish between missing value
+ # vs. None value.
+ info["inputs"] = kwargs["inputs"]
+
+ if "tool_call_id" in kwargs:
+ # Store tool_call_id in run info for linking errors to tool calls
+ info["tool_call_id"] = kwargs["tool_call_id"]
+
+ self.run_map[run_id] = info
+ self.parent_map[run_id] = parent_run_id
+
+ @override
+ async def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Start a trace for a chat model run."""
+ name_ = _assign_name(name, serialized)
+ run_type = "chat_model"
+
+ self._write_run_start_info(
+ run_id,
+ tags=tags,
+ metadata=metadata,
+ parent_run_id=parent_run_id,
+ name_=name_,
+ run_type=run_type,
+ inputs={"messages": messages},
+ )
+
+ self._send(
+ {
+ "event": "on_chat_model_start",
+ "data": {
+ "input": {"messages": messages},
+ },
+ "name": name_,
+ "tags": tags or [],
+ "run_id": str(run_id),
+ "metadata": metadata or {},
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_type,
+ )
+
+ @override
+ async def on_llm_start(
+ self,
+ serialized: dict[str, Any],
+ prompts: list[str],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Start a trace for a (non-chat model) LLM run."""
+ name_ = _assign_name(name, serialized)
+ run_type = "llm"
+
+ self._write_run_start_info(
+ run_id,
+ tags=tags,
+ metadata=metadata,
+ parent_run_id=parent_run_id,
+ name_=name_,
+ run_type=run_type,
+ inputs={"prompts": prompts},
+ )
+
+ self._send(
+ {
+ "event": "on_llm_start",
+ "data": {
+ "input": {
+ "prompts": prompts,
+ }
+ },
+ "name": name_,
+ "tags": tags or [],
+ "run_id": str(run_id),
+ "metadata": metadata or {},
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_type,
+ )
+
+ @override
+ async def on_custom_event(
+ self,
+ name: str,
+ data: Any,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Generate a custom astream event."""
+ event = CustomStreamEvent(
+ event="on_custom_event",
+ run_id=str(run_id),
+ name=name,
+ tags=tags or [],
+ metadata=metadata or {},
+ data=data,
+ parent_ids=self._get_parent_ids(run_id),
+ )
+ self._send(event, name)
+
+ @override
+ async def on_llm_new_token(
+ self,
+ token: str,
+ *,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run on new output token.
+
+ Only available when streaming is enabled.
+
+ For both chat models and non-chat models (legacy text-completion LLMs).
+
+ Raises:
+ ValueError: If the run type is not `llm` or `chat_model`.
+ AssertionError: If the run ID is not found in the run map.
+ """
+ run_info = self.run_map.get(run_id)
+ chunk_: GenerationChunk | BaseMessageChunk
+
+ if run_info is None:
+ msg = f"Run ID {run_id} not found in run map."
+ raise AssertionError(msg)
+ if self.is_tapped.get(run_id):
+ return
+ if run_info["run_type"] == "chat_model":
+ event = "on_chat_model_stream"
+
+ if chunk is None:
+ chunk_ = AIMessageChunk(content=token)
+ else:
+ chunk_ = cast("ChatGenerationChunk", chunk).message
+
+ elif run_info["run_type"] == "llm":
+ event = "on_llm_stream"
+ if chunk is None:
+ chunk_ = GenerationChunk(text=token)
+ else:
+ chunk_ = cast("GenerationChunk", chunk)
+ else:
+ msg = f"Unexpected run type: {run_info['run_type']}"
+ raise ValueError(msg)
+
+ self._send(
+ {
+ "event": event,
+ "data": {
+ "chunk": chunk_,
+ },
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_info["run_type"],
+ )
+
+ @override
+ async def on_llm_end(
+ self, response: LLMResult, *, run_id: UUID, **kwargs: Any
+ ) -> None:
+ """End a trace for a model run.
+
+ For both chat models and non-chat models (legacy text-completion LLMs).
+
+ Raises:
+ ValueError: If the run type is not `'llm'` or `'chat_model'`.
+ """
+ run_info = self.run_map.pop(run_id)
+ inputs_ = run_info.get("inputs")
+
+ generations: list[list[GenerationChunk]] | list[list[ChatGenerationChunk]]
+ output: dict | BaseMessage = {}
+
+ if run_info["run_type"] == "chat_model":
+ generations = cast("list[list[ChatGenerationChunk]]", response.generations)
+ for gen in generations:
+ if output != {}:
+ break
+ for chunk in gen:
+ output = chunk.message
+ break
+
+ event = "on_chat_model_end"
+ elif run_info["run_type"] == "llm":
+ generations = cast("list[list[GenerationChunk]]", response.generations)
+ output = {
+ "generations": [
+ [
+ {
+ "text": chunk.text,
+ "generation_info": chunk.generation_info,
+ "type": chunk.type,
+ }
+ for chunk in gen
+ ]
+ for gen in generations
+ ],
+ "llm_output": response.llm_output,
+ }
+ event = "on_llm_end"
+ else:
+ msg = f"Unexpected run type: {run_info['run_type']}"
+ raise ValueError(msg)
+
+ self._send(
+ {
+ "event": event,
+ "data": {"output": output, "input": inputs_},
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_info["run_type"],
+ )
+
+ async def on_chain_start(
+ self,
+ serialized: dict[str, Any],
+ inputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ run_type: str | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Start a trace for a chain run."""
+ name_ = _assign_name(name, serialized)
+ run_type_ = run_type or "chain"
+
+ data: EventData = {}
+
+ # Work-around Runnable core code not sending input in some
+ # cases.
+ if inputs != {"input": ""}:
+ data["input"] = inputs
+ kwargs["inputs"] = inputs
+
+ self._write_run_start_info(
+ run_id,
+ tags=tags,
+ metadata=metadata,
+ parent_run_id=parent_run_id,
+ name_=name_,
+ run_type=run_type_,
+ **kwargs,
+ )
+
+ self._send(
+ {
+ "event": f"on_{run_type_}_start",
+ "data": data,
+ "name": name_,
+ "tags": tags or [],
+ "run_id": str(run_id),
+ "metadata": metadata or {},
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_type_,
+ )
+
+ @override
+ async def on_chain_end(
+ self,
+ outputs: dict[str, Any],
+ *,
+ run_id: UUID,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """End a trace for a chain run."""
+ run_info = self.run_map.pop(run_id)
+ run_type = run_info["run_type"]
+
+ event = f"on_{run_type}_end"
+
+ inputs = inputs or run_info.get("inputs") or {}
+
+ data: EventData = {
+ "output": outputs,
+ "input": inputs,
+ }
+
+ self._send(
+ {
+ "event": event,
+ "data": data,
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_type,
+ )
+
+ def _get_tool_run_info_with_inputs(self, run_id: UUID) -> tuple[RunInfo, Any]:
+ """Get run info for a tool and extract inputs, with validation.
+
+ Args:
+ run_id: The run ID of the tool.
+
+ Returns:
+ A tuple of `(run_info, inputs)`.
+
+ Raises:
+ AssertionError: If the run ID is a tool call and does not have inputs.
+ """
+ run_info = self.run_map.pop(run_id)
+ if "inputs" not in run_info:
+ msg = (
+ f"Run ID {run_id} is a tool call and is expected to have "
+ f"inputs associated with it."
+ )
+ raise AssertionError(msg)
+ inputs = run_info["inputs"]
+ return run_info, inputs
+
+ @override
+ async def on_tool_start(
+ self,
+ serialized: dict[str, Any],
+ input_str: str,
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ inputs: dict[str, Any] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Start a trace for a tool run."""
+ name_ = _assign_name(name, serialized)
+
+ self._write_run_start_info(
+ run_id,
+ tags=tags,
+ metadata=metadata,
+ parent_run_id=parent_run_id,
+ name_=name_,
+ run_type="tool",
+ inputs=inputs,
+ tool_call_id=kwargs.get("tool_call_id"),
+ )
+
+ self._send(
+ {
+ "event": "on_tool_start",
+ "data": {
+ "input": inputs or {},
+ },
+ "name": name_,
+ "tags": tags or [],
+ "run_id": str(run_id),
+ "metadata": metadata or {},
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ "tool",
+ )
+
+ @override
+ async def on_tool_error(
+ self,
+ error: BaseException,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when tool errors."""
+ # Extract tool_call_id from kwargs if passed directly, or from run_info
+ # (which was stored during on_tool_start) as a fallback
+ tool_call_id = kwargs.get("tool_call_id")
+ run_info, inputs = self._get_tool_run_info_with_inputs(run_id)
+ if tool_call_id is None:
+ tool_call_id = run_info.get("tool_call_id")
+
+ event: StandardStreamEvent = {
+ "event": "on_tool_error",
+ "data": {
+ "error": error,
+ "input": inputs,
+ "tool_call_id": tool_call_id,
+ },
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "parent_ids": self._get_parent_ids(run_id),
+ }
+ self._send(event, "tool")
+
+ @override
+ async def on_tool_end(self, output: Any, *, run_id: UUID, **kwargs: Any) -> None:
+ """End a trace for a tool run."""
+ run_info, inputs = self._get_tool_run_info_with_inputs(run_id)
+
+ self._send(
+ {
+ "event": "on_tool_end",
+ "data": {
+ "output": output,
+ "input": inputs,
+ },
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ "tool",
+ )
+
+ @override
+ async def on_retriever_start(
+ self,
+ serialized: dict[str, Any],
+ query: str,
+ *,
+ run_id: UUID,
+ parent_run_id: UUID | None = None,
+ tags: list[str] | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Run when `Retriever` starts running."""
+ name_ = _assign_name(name, serialized)
+ run_type = "retriever"
+
+ self._write_run_start_info(
+ run_id,
+ tags=tags,
+ metadata=metadata,
+ parent_run_id=parent_run_id,
+ name_=name_,
+ run_type=run_type,
+ inputs={"query": query},
+ )
+
+ self._send(
+ {
+ "event": "on_retriever_start",
+ "data": {
+ "input": {
+ "query": query,
+ }
+ },
+ "name": name_,
+ "tags": tags or [],
+ "run_id": str(run_id),
+ "metadata": metadata or {},
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_type,
+ )
+
+ @override
+ async def on_retriever_end(
+ self, documents: Sequence[Document], *, run_id: UUID, **kwargs: Any
+ ) -> None:
+ """Run when `Retriever` ends running."""
+ run_info = self.run_map.pop(run_id)
+
+ self._send(
+ {
+ "event": "on_retriever_end",
+ "data": {
+ "output": documents,
+ "input": run_info.get("inputs"),
+ },
+ "run_id": str(run_id),
+ "name": run_info["name"],
+ "tags": run_info["tags"],
+ "metadata": run_info["metadata"],
+ "parent_ids": self._get_parent_ids(run_id),
+ },
+ run_info["run_type"],
+ )
+
+ def __deepcopy__(self, memo: dict) -> _AstreamEventsCallbackHandler:
+ """Return self."""
+ return self
+
+ def __copy__(self) -> _AstreamEventsCallbackHandler:
+ """Return self."""
+ return self
+
+
+async def _astream_events_implementation_v1(
+ runnable: Runnable[Input, Output],
+ value: Any,
+ config: RunnableConfig | None = None,
+ *,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+) -> AsyncIterator[StandardStreamEvent]:
+ stream = LogStreamCallbackHandler(
+ auto_close=False,
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ _schema_format="streaming_events",
+ )
+
+ run_log = RunLog(state=None) # type: ignore[arg-type]
+ encountered_start_event = False
+
+ root_event_filter = _RootEventFilter(
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ )
+
+ config = ensure_config(config)
+ root_tags = config.get("tags", [])
+ root_metadata = config.get("metadata", {})
+ root_name = config.get("run_name", runnable.get_name())
+
+ async for log in _astream_log_implementation(
+ runnable,
+ value,
+ config=config,
+ stream=stream,
+ diff=True,
+ with_streamed_output_list=True,
+ **kwargs,
+ ):
+ run_log += log
+
+ if not encountered_start_event:
+ # Yield the start event for the root runnable.
+ encountered_start_event = True
+ state = run_log.state.copy()
+
+ event = StandardStreamEvent(
+ event=f"on_{state['type']}_start",
+ run_id=state["id"],
+ name=root_name,
+ tags=root_tags,
+ metadata=root_metadata,
+ data={
+ "input": value,
+ },
+ parent_ids=[], # Not supported in v1
+ )
+
+ if root_event_filter.include_event(event, state["type"]):
+ yield event
+
+ paths = {
+ op["path"].split("/")[2]
+ for op in log.ops
+ if op["path"].startswith("/logs/")
+ }
+ # Elements in a set should be iterated in the same order
+ # as they were inserted in modern python versions.
+ for path in paths:
+ data: EventData = {}
+ log_entry: LogEntry = run_log.state["logs"][path]
+ if log_entry["end_time"] is None:
+ event_type = "stream" if log_entry["streamed_output"] else "start"
+ else:
+ event_type = "end"
+
+ if event_type == "start":
+ # Include the inputs with the start event if they are available.
+ # Usually they will NOT be available for components that operate
+ # on streams, since those components stream the input and
+ # don't know its final value until the end of the stream.
+ inputs = log_entry.get("inputs")
+ if inputs is not None:
+ data["input"] = inputs
+
+ if event_type == "end":
+ inputs = log_entry.get("inputs")
+ if inputs is not None:
+ data["input"] = inputs
+
+ # None is a VALID output for an end event
+ data["output"] = log_entry["final_output"]
+
+ if event_type == "stream":
+ num_chunks = len(log_entry["streamed_output"])
+ if num_chunks != 1:
+ msg = (
+ f"Expected exactly one chunk of streamed output, "
+ f"got {num_chunks} instead. This is impossible. "
+ f"Encountered in: {log_entry['name']}"
+ )
+ raise AssertionError(msg)
+
+ data = {"chunk": log_entry["streamed_output"][0]}
+ # Clean up the stream, we don't need it anymore.
+ # And this avoids duplicates as well!
+ log_entry["streamed_output"] = []
+
+ yield StandardStreamEvent(
+ event=f"on_{log_entry['type']}_{event_type}",
+ name=log_entry["name"],
+ run_id=log_entry["id"],
+ tags=log_entry["tags"],
+ metadata=log_entry["metadata"],
+ data=data,
+ parent_ids=[], # Not supported in v1
+ )
+
+ # Finally, we take care of the streaming output from the root chain
+ # if there is any.
+ state = run_log.state
+ if state["streamed_output"]:
+ num_chunks = len(state["streamed_output"])
+ if num_chunks != 1:
+ msg = (
+ f"Expected exactly one chunk of streamed output, "
+ f"got {num_chunks} instead. This is impossible. "
+ f"Encountered in: {state['name']}"
+ )
+ raise AssertionError(msg)
+
+ data = {"chunk": state["streamed_output"][0]}
+ # Clean up the stream, we don't need it anymore.
+ state["streamed_output"] = []
+
+ event = StandardStreamEvent(
+ event=f"on_{state['type']}_stream",
+ run_id=state["id"],
+ tags=root_tags,
+ metadata=root_metadata,
+ name=root_name,
+ data=data,
+ parent_ids=[], # Not supported in v1
+ )
+ if root_event_filter.include_event(event, state["type"]):
+ yield event
+
+ state = run_log.state
+
+ # Finally yield the end event for the root runnable.
+ event = StandardStreamEvent(
+ event=f"on_{state['type']}_end",
+ name=root_name,
+ run_id=state["id"],
+ tags=root_tags,
+ metadata=root_metadata,
+ data={
+ "output": state["final_output"],
+ },
+ parent_ids=[], # Not supported in v1
+ )
+ if root_event_filter.include_event(event, state["type"]):
+ yield event
+
+
+async def _astream_events_implementation_v2(
+ runnable: Runnable[Input, Output],
+ value: Any,
+ config: RunnableConfig | None = None,
+ *,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ **kwargs: Any,
+) -> AsyncIterator[StandardStreamEvent]:
+ """Implementation of the astream events API for v2 runnables."""
+ event_streamer = _AstreamEventsCallbackHandler(
+ include_names=include_names,
+ include_types=include_types,
+ include_tags=include_tags,
+ exclude_names=exclude_names,
+ exclude_types=exclude_types,
+ exclude_tags=exclude_tags,
+ )
+
+ # Assign the stream handler to the config
+ config = ensure_config(config)
+ if "run_id" in config:
+ run_id = cast("UUID", config["run_id"])
+ else:
+ run_id = uuid7()
+ config["run_id"] = run_id
+ callbacks = config.get("callbacks")
+ if callbacks is None:
+ config["callbacks"] = [event_streamer]
+ elif isinstance(callbacks, list):
+ config["callbacks"] = [*callbacks, event_streamer]
+ elif isinstance(callbacks, BaseCallbackManager):
+ callbacks = callbacks.copy()
+ callbacks.add_handler(event_streamer, inherit=True)
+ config["callbacks"] = callbacks
+ else:
+ msg = (
+ f"Unexpected type for callbacks: {callbacks}."
+ "Expected None, list or AsyncCallbackManager."
+ )
+ raise ValueError(msg)
+
+ # Call the runnable in streaming mode,
+ # add each chunk to the output stream
+ async def consume_astream() -> None:
+ try:
+ # if astream also calls tap_output_aiter this will be a no-op
+ async with aclosing(runnable.astream(value, config, **kwargs)) as stream:
+ async for _ in event_streamer.tap_output_aiter(run_id, stream):
+ # All the content will be picked up
+ pass
+ finally:
+ await event_streamer.send_stream.aclose()
+
+ # Start the runnable in a task, so we can start consuming output
+ task = asyncio.create_task(consume_astream())
+
+ first_event_sent = False
+ first_event_run_id = None
+
+ try:
+ async for event in event_streamer:
+ if not first_event_sent:
+ first_event_sent = True
+ # This is a work-around an issue where the inputs into the
+ # chain are not available until the entire input is consumed.
+ # As a temporary solution, we'll modify the input to be the input
+ # that was passed into the chain.
+ event["data"]["input"] = value
+ first_event_run_id = event["run_id"]
+ yield event
+ continue
+
+ # If it's the end event corresponding to the root runnable
+ # we don't include the input in the event since it's guaranteed
+ # to be included in the first event.
+ if (
+ event["run_id"] == first_event_run_id
+ and event["event"].endswith("_end")
+ and "input" in event["data"]
+ ):
+ del event["data"]["input"]
+
+ yield event
+ except asyncio.CancelledError as exc:
+ # Cancel the task if it's still running
+ task.cancel(exc.args[0] if exc.args else None)
+ raise
+ finally:
+ # Cancel the task if it's still running
+ task.cancel()
+ # Await it anyway, to run any cleanup code, and propagate any exceptions
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/langchain.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/langchain.py
new file mode 100644
index 0000000000000000000000000000000000000000..6295a2f034b1b594b149d7acbf0f5e088f1828eb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/langchain.py
@@ -0,0 +1,490 @@
+"""A tracer implementation that records to LangChain endpoint."""
+
+from __future__ import annotations
+
+import logging
+from concurrent.futures import ThreadPoolExecutor
+from datetime import datetime, timezone
+from typing import TYPE_CHECKING, Any, cast
+from uuid import UUID
+
+from langsmith import Client, get_tracing_context
+from langsmith import run_trees as rt
+from langsmith import utils as ls_utils
+from tenacity import (
+ Retrying,
+ retry_if_exception_type,
+ stop_after_attempt,
+ wait_exponential_jitter,
+)
+from typing_extensions import override
+
+from langchain_core.env import get_runtime_environment
+from langchain_core.load import dumpd
+from langchain_core.messages.ai import UsageMetadata, add_usage
+from langchain_core.tracers._compat import run_construct, run_to_dict
+from langchain_core.tracers.base import BaseTracer
+from langchain_core.tracers.schemas import Run
+
+if TYPE_CHECKING:
+ from collections.abc import Mapping
+
+ from langchain_core.messages import BaseMessage
+ from langchain_core.outputs import ChatGenerationChunk, GenerationChunk
+
+logger = logging.getLogger(__name__)
+_LOGGED = set()
+_EXECUTOR: ThreadPoolExecutor | None = None
+
+OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS: frozenset[str] = frozenset(
+ {"ls_agent_type"}
+)
+"""Allowlist of LangSmith-only tracing metadata keys that bypass the default
+"first wins" merge semantics used when propagating tracer metadata to nested
+runs.
+
+Keys in this set are ALWAYS overridden by the nearest enclosing tracer config,
+so nested callers (e.g. a subagent) can replace a value inherited from an
+ancestor.
+
+Keep this list very small: every key here loses the default "first wins"
+protection and is always clobbered by the nearest enclosing tracer config.
+Only keys that are strictly for LangSmith tracing bookkeeping should be added.
+"""
+
+
+def log_error_once(method: str, exception: Exception) -> None:
+ """Log an error once.
+
+ Args:
+ method: The method that raised the exception.
+ exception: The exception that was raised.
+ """
+ if (method, type(exception)) in _LOGGED:
+ return
+ _LOGGED.add((method, type(exception)))
+ logger.error(exception)
+
+
+def wait_for_all_tracers() -> None:
+ """Wait for all tracers to finish."""
+ if rt._CLIENT is not None: # noqa: SLF001
+ rt._CLIENT.flush() # noqa: SLF001
+
+
+def get_client() -> Client:
+ """Get the client.
+
+ Returns:
+ The LangSmith client.
+ """
+ return rt.get_cached_client()
+
+
+def _get_executor() -> ThreadPoolExecutor:
+ """Get the executor."""
+ global _EXECUTOR # noqa: PLW0603
+ if _EXECUTOR is None:
+ _EXECUTOR = ThreadPoolExecutor()
+ return _EXECUTOR
+
+
+def _get_usage_metadata_from_generations(
+ generations: list[list[dict[str, Any]]],
+) -> UsageMetadata | None:
+ """Extract and aggregate `usage_metadata` from generations.
+
+ Iterates through generations to find and aggregate all `usage_metadata` found in
+ messages. This expects the serialized message payload shape produced by tracer
+ internals:
+
+ `{"message": {"kwargs": {"usage_metadata": {...}}}}`
+
+ Args:
+ generations: List of generation batches, where each batch is a list of
+ generation dicts that may contain a `'message'` key with
+ usage metadata.
+
+ Returns:
+ The aggregated `usage_metadata` dict if found, otherwise `None`.
+ """
+ output: UsageMetadata | None = None
+ for generation_batch in generations:
+ for generation in generation_batch:
+ if isinstance(generation, dict) and "message" in generation:
+ message = generation["message"]
+ usage_metadata = _get_usage_metadata_from_message(message)
+ if usage_metadata is not None:
+ output = add_usage(output, usage_metadata)
+ return output
+
+
+def _get_usage_metadata_from_message(message: Any) -> UsageMetadata | None:
+ """Extract usage metadata from a generation's message payload."""
+ if not isinstance(message, dict):
+ return None
+
+ kwargs = message.get("kwargs")
+ if isinstance(kwargs, dict) and isinstance(kwargs.get("usage_metadata"), dict):
+ return cast("UsageMetadata", kwargs["usage_metadata"])
+
+ return None
+
+
+class LangChainTracer(BaseTracer):
+ """Implementation of the `SharedTracer` that `POSTS` to the LangChain endpoint."""
+
+ run_inline = True
+
+ def __init__(
+ self,
+ example_id: UUID | str | None = None,
+ project_name: str | None = None,
+ client: Client | None = None,
+ tags: list[str] | None = None,
+ *,
+ metadata: Mapping[str, str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize the LangChain tracer.
+
+ Args:
+ example_id: The example ID.
+ project_name: The project name.
+
+ Defaults to the tracer project.
+ client: The client.
+
+ Defaults to the global client.
+ tags: The tags.
+
+ Defaults to an empty list.
+ metadata: Additional metadata to include if it isn't already in the run.
+
+ Defaults to None.
+ **kwargs: Additional keyword arguments.
+ """
+ super().__init__(**kwargs)
+ self.example_id = (
+ UUID(example_id) if isinstance(example_id, str) else example_id
+ )
+ self.project_name = project_name or ls_utils.get_tracer_project()
+ self.client = client or get_client()
+ self.tags = tags or []
+ self.latest_run: Run | None = None
+ self.run_has_token_event_map: dict[str, bool] = {}
+ self.tracing_metadata: dict[str, str] | None = (
+ dict(metadata) if metadata is not None else None
+ )
+
+ def copy_with_metadata_defaults(
+ self,
+ *,
+ metadata: Mapping[str, str] | None = None,
+ tags: list[str] | None = None,
+ ) -> LangChainTracer:
+ """Return a new tracer with merged tracer-only defaults."""
+ base_metadata = self.tracing_metadata
+ if metadata is None:
+ merged_metadata = dict(base_metadata) if base_metadata is not None else None
+ elif base_metadata is None:
+ merged_metadata = dict(metadata)
+ else:
+ merged_metadata = dict(base_metadata)
+ for key, value in metadata.items():
+ # For allowlisted LangSmith-only inheritable metadata keys
+ # (e.g. ``ls_agent_type``), nested callers are allowed to
+ # OVERRIDE the value inherited from an ancestor. For all
+ # other keys we keep the existing "first wins" behavior so
+ # that ancestor-provided tracing metadata is not accidentally
+ # clobbered by child runs.
+ if (
+ key not in merged_metadata
+ or key in OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS
+ ):
+ merged_metadata[key] = value
+
+ merged_tags = sorted(set(self.tags + tags)) if tags else self.tags
+
+ return self.__class__(
+ example_id=self.example_id,
+ project_name=self.project_name,
+ client=self.client,
+ tags=merged_tags,
+ metadata=merged_metadata,
+ run_map=self.run_map,
+ order_map=self.order_map,
+ _external_run_ids=self._external_run_ids,
+ )
+
+ def _start_trace(self, run: Run) -> None:
+ if self.project_name:
+ run.session_name = self.project_name
+ if self.tags is not None:
+ if run.tags:
+ run.tags = sorted(set(run.tags + self.tags))
+ else:
+ run.tags = self.tags.copy()
+
+ super()._start_trace(run)
+ if run.ls_client is None:
+ run.ls_client = self.client
+ if get_tracing_context().get("enabled") is False:
+ run.extra["__disabled"] = True
+
+ def on_chat_model_start(
+ self,
+ serialized: dict[str, Any],
+ messages: list[list[BaseMessage]],
+ *,
+ run_id: UUID,
+ tags: list[str] | None = None,
+ parent_run_id: UUID | None = None,
+ metadata: dict[str, Any] | None = None,
+ name: str | None = None,
+ **kwargs: Any,
+ ) -> Run:
+ """Start a trace for an LLM run.
+
+ Args:
+ serialized: The serialized model.
+ messages: The messages.
+ run_id: The run ID.
+ tags: The tags.
+ parent_run_id: The parent run ID.
+ metadata: The metadata.
+ name: The name.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ The run.
+ """
+ start_time = datetime.now(timezone.utc)
+ if metadata:
+ kwargs.update({"metadata": metadata})
+ chat_model_run = Run(
+ id=run_id,
+ parent_run_id=parent_run_id,
+ serialized=serialized,
+ inputs={"messages": [[dumpd(msg) for msg in batch] for batch in messages]},
+ extra=kwargs,
+ events=[{"name": "start", "time": start_time}],
+ start_time=start_time,
+ run_type="llm",
+ tags=tags,
+ name=name,
+ )
+ self._start_trace(chat_model_run)
+ self._on_chat_model_start(chat_model_run)
+ return chat_model_run
+
+ def _persist_run(self, run: Run) -> None:
+ # We want to free up more memory by avoiding keeping a reference to the
+ # whole nested run tree.
+ run_data = run_to_dict(run, exclude={"child_runs", "inputs", "outputs"})
+ self.latest_run = run_construct(
+ **run_data,
+ inputs=run.inputs,
+ outputs=run.outputs,
+ )
+
+ def get_run_url(self) -> str:
+ """Get the LangSmith root run URL.
+
+ Returns:
+ The LangSmith root run URL.
+
+ Raises:
+ ValueError: If no traced run is found.
+ ValueError: If the run URL cannot be found.
+ """
+ if not self.latest_run:
+ msg = "No traced run found."
+ raise ValueError(msg)
+ # If this is the first run in a project, the project may not yet be created.
+ # This method is only really useful for debugging flows, so we will assume
+ # there is some tolerace for latency.
+ for attempt in Retrying(
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(),
+ retry=retry_if_exception_type(ls_utils.LangSmithError),
+ ):
+ with attempt:
+ return self.client.get_run_url(
+ run=self.latest_run, project_name=self.project_name
+ )
+ msg = "Failed to get run URL."
+ raise ValueError(msg)
+
+ def _get_tags(self, run: Run) -> list[str]:
+ """Get combined tags for a run."""
+ tags = set(run.tags or [])
+ tags.update(self.tags or [])
+ return list(tags)
+
+ def _persist_run_single(self, run: Run) -> None:
+ """Persist a run."""
+ if run.extra.get("__disabled"):
+ return
+ try:
+ run.extra["runtime"] = get_runtime_environment()
+ run.tags = self._get_tags(run)
+ _patch_missing_metadata(self, run)
+ if run.ls_client is not self.client:
+ run.ls_client = self.client
+ run.post()
+ except Exception as e:
+ # Errors are swallowed by the thread executor so we need to log them here
+ log_error_once("post", e)
+ raise
+
+ @staticmethod
+ def _update_run_single(run: Run) -> None:
+ """Update a run."""
+ if run.extra.get("__disabled"):
+ return
+ try:
+ run.patch(exclude_inputs=run.extra.get("inputs_is_truthy", False))
+ except Exception as e:
+ # Errors are swallowed by the thread executor so we need to log them here
+ log_error_once("patch", e)
+ raise
+
+ def _on_llm_start(self, run: Run) -> None:
+ """Persist an LLM run."""
+ if run.parent_run_id is None:
+ run.reference_example_id = self.example_id
+ self._persist_run_single(run)
+
+ @override
+ def _llm_run_with_token_event(
+ self,
+ token: str,
+ run_id: UUID,
+ chunk: GenerationChunk | ChatGenerationChunk | None = None,
+ parent_run_id: UUID | None = None,
+ ) -> Run:
+ run_id_str = str(run_id)
+ if run_id_str not in self.run_has_token_event_map:
+ self.run_has_token_event_map[run_id_str] = True
+ else:
+ return self._get_run(run_id, run_type={"llm", "chat_model"})
+ return super()._llm_run_with_token_event(
+ # Drop the chunk; we don't need to save it
+ token,
+ run_id,
+ chunk=None,
+ parent_run_id=parent_run_id,
+ )
+
+ def _on_chat_model_start(self, run: Run) -> None:
+ """Persist a chat model run.
+
+ Note:
+ Naming is historical: there is no `_on_chat_model_end` hook. Chat
+ model completion is handled by `_on_llm_end`, shared with text
+ LLM runs.
+ """
+ if run.parent_run_id is None:
+ run.reference_example_id = self.example_id
+ self._persist_run_single(run)
+
+ def _on_llm_end(self, run: Run) -> None:
+ """Process LLM/chat model run completion."""
+ # Extract usage_metadata from outputs and store in extra.metadata
+ if run.outputs and "generations" in run.outputs:
+ usage_metadata = _get_usage_metadata_from_generations(
+ run.outputs["generations"]
+ )
+ if usage_metadata is not None:
+ if "metadata" not in run.extra:
+ run.extra["metadata"] = {}
+ run.extra["metadata"]["usage_metadata"] = usage_metadata
+ self._update_run_single(run)
+
+ def _on_llm_error(self, run: Run) -> None:
+ """Process the LLM Run upon error."""
+ self._update_run_single(run)
+
+ def _on_chain_start(self, run: Run) -> None:
+ """Process the Chain Run upon start."""
+ if run.parent_run_id is None:
+ run.reference_example_id = self.example_id
+ # Skip persisting if inputs are deferred (e.g., iterator/generator inputs).
+ # The run will be posted when _on_chain_end is called with realized inputs.
+ if not run.extra.get("defers_inputs"):
+ self._persist_run_single(run)
+
+ def _on_chain_end(self, run: Run) -> None:
+ """Process the Chain Run."""
+ # If inputs were deferred, persist (POST) the run now that inputs are realized.
+ # Otherwise, update (PATCH) the existing run.
+ if run.extra.get("defers_inputs"):
+ self._persist_run_single(run)
+ else:
+ self._update_run_single(run)
+
+ def _on_chain_error(self, run: Run) -> None:
+ """Process the Chain Run upon error."""
+ # If inputs were deferred, persist (POST) the run now that inputs are realized.
+ # Otherwise, update (PATCH) the existing run.
+ if run.extra.get("defers_inputs"):
+ self._persist_run_single(run)
+ else:
+ self._update_run_single(run)
+
+ def _on_tool_start(self, run: Run) -> None:
+ """Process the Tool Run upon start."""
+ if run.parent_run_id is None:
+ run.reference_example_id = self.example_id
+ self._persist_run_single(run)
+
+ def _on_tool_end(self, run: Run) -> None:
+ """Process the Tool Run."""
+ self._update_run_single(run)
+
+ def _on_tool_error(self, run: Run) -> None:
+ """Process the Tool Run upon error."""
+ self._update_run_single(run)
+
+ def _on_retriever_start(self, run: Run) -> None:
+ """Process the Retriever Run upon start."""
+ if run.parent_run_id is None:
+ run.reference_example_id = self.example_id
+ self._persist_run_single(run)
+
+ def _on_retriever_end(self, run: Run) -> None:
+ """Process the Retriever Run."""
+ self._update_run_single(run)
+
+ def _on_retriever_error(self, run: Run) -> None:
+ """Process the Retriever Run upon error."""
+ self._update_run_single(run)
+
+ def wait_for_futures(self) -> None:
+ """Wait for the given futures to complete."""
+ if self.client is not None:
+ self.client.flush()
+
+
+def _patch_missing_metadata(self: LangChainTracer, run: Run) -> None:
+ if not self.tracing_metadata:
+ return
+ metadata = run.metadata
+ patched = None
+ for k, v in self.tracing_metadata.items():
+ # ``OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS`` are a small,
+ # LangSmith-only allowlist that bypasses the "first wins" merge
+ # so a nested caller (e.g. a subagent) can override a parent-set value.
+ if k not in metadata or k in OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS:
+ # Skip the copy when the value already matches (avoids cloning
+ # the shared dict in the common "already set" case). Use a
+ # ``k in metadata`` guard so a legitimate missing key whose
+ # tracer value happens to be ``None`` is still patched in.
+ if k in metadata and metadata[k] == v:
+ continue
+ if patched is None:
+ # Copy on first miss to avoid mutating the shared dict.
+ patched = {**metadata}
+ run.extra["metadata"] = patched
+ patched[k] = v
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/log_stream.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/log_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..5131815ebdfbd7a55baafb5677df68dce8f2b8ee
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/log_stream.py
@@ -0,0 +1,769 @@
+"""Tracer that streams run logs to a stream."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import copy
+import threading
+from collections import defaultdict
+from pprint import pformat
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ TypeVar,
+ overload,
+)
+
+import jsonpatch # type: ignore[import-untyped]
+from typing_extensions import NotRequired, TypedDict, override
+
+from langchain_core.callbacks.base import BaseCallbackManager
+from langchain_core.load import dumps
+from langchain_core.load.load import load
+from langchain_core.outputs import ChatGenerationChunk, GenerationChunk
+from langchain_core.runnables import RunnableConfig, ensure_config
+from langchain_core.tracers._streaming import _StreamingCallbackHandler
+from langchain_core.tracers.base import BaseTracer
+from langchain_core.tracers.memory_stream import _MemoryStream
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator, Iterator, Sequence
+ from uuid import UUID
+
+ from langchain_core.runnables import Runnable
+ from langchain_core.runnables.utils import Input, Output
+ from langchain_core.tracers.schemas import Run
+
+
+class LogEntry(TypedDict):
+ """A single entry in the run log."""
+
+ id: str
+ """ID of the sub-run."""
+
+ name: str
+ """Name of the object being run."""
+
+ type: str
+ """Type of the object being run, eg. prompt, chain, llm, etc."""
+
+ tags: list[str]
+ """List of tags for the run."""
+
+ metadata: dict[str, Any]
+ """Key-value pairs of metadata for the run."""
+
+ start_time: str
+ """ISO-8601 timestamp of when the run started."""
+
+ streamed_output_str: list[str]
+ """List of LLM tokens streamed by this run, if applicable."""
+
+ streamed_output: list[Any]
+ """List of output chunks streamed by this run, if available."""
+
+ inputs: NotRequired[Any | None]
+ """Inputs to this run. Not available currently via `astream_log`."""
+
+ final_output: Any | None
+ """Final output of this run.
+
+ Only available after the run has finished successfully.
+ """
+
+ end_time: str | None
+ """ISO-8601 timestamp of when the run ended.
+
+ Only available after the run has finished.
+ """
+
+
+class RunState(TypedDict):
+ """State of the run."""
+
+ id: str
+ """ID of the run."""
+
+ streamed_output: list[Any]
+ """List of output chunks streamed by `Runnable.stream()`"""
+
+ final_output: Any | None
+ """Final output of the run, usually the result of aggregating (`+`) streamed_output.
+
+ Updated throughout the run when supported by the `Runnable`.
+ """
+
+ name: str
+ """Name of the object being run."""
+
+ type: str
+ """Type of the object being run, e.g. prompt, chain, llm, etc."""
+
+ # Do we want tags/metadata on the root run? Client kinda knows it in most situations
+ # tags: list[str]
+
+ logs: dict[str, LogEntry]
+ """Map of run names to sub-runs.
+
+ If filters were supplied, this list will contain only the runs that matched the
+ filters.
+ """
+
+
+class RunLogPatch:
+ """Patch to the run log."""
+
+ ops: list[dict[str, Any]]
+ """List of `JSONPatch` operations, which describe how to create the run state
+ from an empty dict.
+
+ This is the minimal representation of the log, designed to be serialized as JSON and
+ sent over the wire to reconstruct the log on the other side. Reconstruction of the
+ state can be done with any JSONPatch-compliant library, see https://jsonpatch.com
+ for more information.
+ """
+
+ def __init__(self, *ops: dict[str, Any]) -> None:
+ """Create a RunLogPatch.
+
+ Args:
+ *ops: The operations to apply to the state.
+ """
+ self.ops = list(ops)
+
+ def __add__(self, other: RunLogPatch | Any) -> RunLog:
+ """Combine two `RunLogPatch` instances.
+
+ Args:
+ other: The other `RunLogPatch` to combine with.
+
+ Raises:
+ TypeError: If the other object is not a `RunLogPatch`.
+
+ Returns:
+ A new `RunLog` representing the combination of the two.
+ """
+ if type(other) is RunLogPatch:
+ ops = self.ops + other.ops
+ state = jsonpatch.apply_patch(None, copy.deepcopy(ops))
+ return RunLog(*ops, state=state)
+
+ msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"
+ raise TypeError(msg)
+
+ @override
+ def __repr__(self) -> str:
+ # 1:-1 to get rid of the [] around the list
+ return f"RunLogPatch({pformat(self.ops)[1:-1]})"
+
+ @override
+ def __eq__(self, other: object) -> bool:
+ return isinstance(other, RunLogPatch) and self.ops == other.ops
+
+ __hash__ = None # type: ignore[assignment]
+
+
+class RunLog(RunLogPatch):
+ """Run log."""
+
+ state: RunState
+ """Current state of the log, obtained from applying all ops in sequence."""
+
+ def __init__(self, *ops: dict[str, Any], state: RunState) -> None:
+ """Create a RunLog.
+
+ Args:
+ *ops: The operations to apply to the state.
+ state: The initial state of the run log.
+ """
+ super().__init__(*ops)
+ self.state = state
+
+ def __add__(self, other: RunLogPatch | Any) -> RunLog:
+ """Combine two `RunLog` objects.
+
+ Args:
+ other: The other `RunLog` or `RunLogPatch` to combine with.
+
+ Raises:
+ TypeError: If the other object is not a `RunLog` or `RunLogPatch`.
+
+ Returns:
+ A new `RunLog` representing the combination of the two.
+ """
+ if type(other) is RunLogPatch:
+ ops = self.ops + other.ops
+ state = jsonpatch.apply_patch(self.state, other.ops)
+ return RunLog(*ops, state=state)
+
+ msg = f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"
+ raise TypeError(msg)
+
+ @override
+ def __repr__(self) -> str:
+ return f"RunLog({pformat(self.state)})"
+
+ @override
+ def __eq__(self, other: object) -> bool:
+ """Check if two `RunLog`s are equal.
+
+ Args:
+ other: The other `RunLog` to compare to.
+
+ Returns:
+ `True` if the `RunLog`s are equal, `False` otherwise.
+ """
+ # First compare that the state is the same
+ if not isinstance(other, RunLog):
+ return False
+ if self.state != other.state:
+ return False
+ # Then compare that the ops are the same
+ return super().__eq__(other)
+
+ __hash__ = None
+
+
+T = TypeVar("T")
+
+
+class LogStreamCallbackHandler(BaseTracer, _StreamingCallbackHandler):
+ """Tracer that streams run logs to a stream."""
+
+ def __init__(
+ self,
+ *,
+ auto_close: bool = True,
+ include_names: Sequence[str] | None = None,
+ include_types: Sequence[str] | None = None,
+ include_tags: Sequence[str] | None = None,
+ exclude_names: Sequence[str] | None = None,
+ exclude_types: Sequence[str] | None = None,
+ exclude_tags: Sequence[str] | None = None,
+ # Schema format is for internal use only.
+ _schema_format: Literal["original", "streaming_events"] = "streaming_events",
+ ) -> None:
+ """A tracer that streams run logs to a stream.
+
+ Args:
+ auto_close: Whether to close the stream when the root run finishes.
+ include_names: Only include runs from `Runnable` objects with matching
+ names.
+ include_types: Only include runs from `Runnable` objects with matching
+ types.
+ include_tags: Only include runs from `Runnable` objects with matching tags.
+ exclude_names: Exclude runs from `Runnable` objects with matching names.
+ exclude_types: Exclude runs from `Runnable` objects with matching types.
+ exclude_tags: Exclude runs from `Runnable` objects with matching tags.
+ _schema_format: Primarily changes how the inputs and outputs are handled.
+
+ **For internal use only. This API will change.**
+
+ - `'original'` is the format used by all current tracers. This format is
+ slightly inconsistent with respect to inputs and outputs.
+ - 'streaming_events' is used for supporting streaming events, for
+ internal usage. It will likely change in the future,
+ or be deprecated entirely in favor of a dedicated async
+ tracer for streaming events.
+
+ Raises:
+ ValueError: If an invalid schema format is provided (internal use only).
+ """
+ if _schema_format not in {"original", "streaming_events"}:
+ msg = (
+ f"Invalid schema format: {_schema_format}. "
+ f"Expected one of 'original', 'streaming_events'."
+ )
+ raise ValueError(msg)
+ super().__init__(_schema_format=_schema_format)
+
+ self.auto_close = auto_close
+ self.include_names = include_names
+ self.include_types = include_types
+ self.include_tags = include_tags
+ self.exclude_names = exclude_names
+ self.exclude_types = exclude_types
+ self.exclude_tags = exclude_tags
+
+ try:
+ loop = asyncio.get_event_loop()
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ memory_stream = _MemoryStream[RunLogPatch](loop)
+ self.lock = threading.Lock()
+ self.send_stream = memory_stream.get_send_stream()
+ self.receive_stream = memory_stream.get_receive_stream()
+ self._key_map_by_run_id: dict[UUID, str] = {}
+ self._counter_map_by_name: dict[str, int] = defaultdict(int)
+ self.root_id: UUID | None = None
+
+ def __aiter__(self) -> AsyncIterator[RunLogPatch]:
+ """Iterate over the stream of run logs.
+
+ Returns:
+ An async iterator over the run log patches.
+ """
+ return self.receive_stream.__aiter__()
+
+ def send(self, *ops: dict[str, Any]) -> bool:
+ """Send a patch to the stream, return `False` if the stream is closed.
+
+ Args:
+ *ops: The operations to send to the stream.
+
+ Returns:
+ `True` if the patch was sent successfully, `False` if the stream is closed.
+ """
+ # We will likely want to wrap this in try / except at some point
+ # to handle exceptions that might arise at run time.
+ # For now we'll let the exception bubble up, and always return
+ # True on the happy path.
+ self.send_stream.send_nowait(RunLogPatch(*ops))
+ return True
+
+ async def tap_output_aiter(
+ self, run_id: UUID, output: AsyncIterator[T]
+ ) -> AsyncIterator[T]:
+ """Tap an output async iterator to stream its values to the log.
+
+ Args:
+ run_id: The ID of the run.
+ output: The output async iterator.
+
+ Yields:
+ The output value.
+ """
+ async for chunk in output:
+ # root run is handled in .astream_log()
+ # if we can't find the run silently ignore
+ # eg. because this run wasn't included in the log
+ if (
+ run_id != self.root_id
+ and (key := self._key_map_by_run_id.get(run_id))
+ and (
+ not self.send(
+ {
+ "op": "add",
+ "path": f"/logs/{key}/streamed_output/-",
+ "value": chunk,
+ }
+ )
+ )
+ ):
+ break
+
+ yield chunk
+
+ def tap_output_iter(self, run_id: UUID, output: Iterator[T]) -> Iterator[T]:
+ """Tap an output iterator to stream its values to the log.
+
+ Args:
+ run_id: The ID of the run.
+ output: The output iterator.
+
+ Yields:
+ The output value.
+ """
+ for chunk in output:
+ # root run is handled in .astream_log()
+ # if we can't find the run silently ignore
+ # eg. because this run wasn't included in the log
+ if (
+ run_id != self.root_id
+ and (key := self._key_map_by_run_id.get(run_id))
+ and (
+ not self.send(
+ {
+ "op": "add",
+ "path": f"/logs/{key}/streamed_output/-",
+ "value": chunk,
+ }
+ )
+ )
+ ):
+ break
+
+ yield chunk
+
+ def include_run(self, run: Run) -> bool:
+ """Check if a `Run` should be included in the log.
+
+ Args:
+ run: The `Run` to check.
+
+ Returns:
+ `True` if the `Run` should be included, `False` otherwise.
+ """
+ if run.id == self.root_id:
+ return False
+
+ run_tags = run.tags or []
+
+ if (
+ self.include_names is None
+ and self.include_types is None
+ and self.include_tags is None
+ ):
+ include = True
+ else:
+ include = False
+
+ if self.include_names is not None:
+ include = include or run.name in self.include_names
+ if self.include_types is not None:
+ include = include or run.run_type in self.include_types
+ if self.include_tags is not None:
+ include = include or any(tag in self.include_tags for tag in run_tags)
+
+ if self.exclude_names is not None:
+ include = include and run.name not in self.exclude_names
+ if self.exclude_types is not None:
+ include = include and run.run_type not in self.exclude_types
+ if self.exclude_tags is not None:
+ include = include and all(tag not in self.exclude_tags for tag in run_tags)
+
+ return include
+
+ def _persist_run(self, run: Run) -> None:
+ # This is a legacy method only called once for an entire run tree
+ # therefore not useful here
+ pass
+
+ def _on_run_create(self, run: Run) -> None:
+ """Start a run."""
+ if self.root_id is None:
+ self.root_id = run.id
+ if not self.send(
+ {
+ "op": "replace",
+ "path": "",
+ "value": RunState(
+ id=str(run.id),
+ streamed_output=[],
+ final_output=None,
+ logs={},
+ name=run.name,
+ type=run.run_type,
+ ),
+ }
+ ):
+ return
+
+ if not self.include_run(run):
+ return
+
+ # Determine previous index, increment by 1
+ with self.lock:
+ self._counter_map_by_name[run.name] += 1
+ count = self._counter_map_by_name[run.name]
+ self._key_map_by_run_id[run.id] = (
+ run.name if count == 1 else f"{run.name}:{count}"
+ )
+
+ entry = LogEntry(
+ id=str(run.id),
+ name=run.name,
+ type=run.run_type,
+ tags=run.tags or [],
+ metadata=(run.extra or {}).get("metadata", {}),
+ start_time=run.start_time.isoformat(timespec="milliseconds"),
+ streamed_output=[],
+ streamed_output_str=[],
+ final_output=None,
+ end_time=None,
+ )
+
+ if self._schema_format == "streaming_events":
+ # If using streaming events let's add inputs as well
+ entry["inputs"] = _get_standardized_inputs(run, self._schema_format)
+
+ # Add the run to the stream
+ self.send(
+ {
+ "op": "add",
+ "path": f"/logs/{self._key_map_by_run_id[run.id]}",
+ "value": entry,
+ }
+ )
+
+ def _on_run_update(self, run: Run) -> None:
+ """Finish a `Run`."""
+ try:
+ index = self._key_map_by_run_id.get(run.id)
+
+ if index is None:
+ return
+
+ ops = []
+
+ if self._schema_format == "streaming_events":
+ ops.append(
+ {
+ "op": "replace",
+ "path": f"/logs/{index}/inputs",
+ "value": _get_standardized_inputs(run, self._schema_format),
+ }
+ )
+
+ ops.extend(
+ [
+ # Replace 'inputs' with final inputs
+ # This is needed because in many cases the inputs are not
+ # known until after the run is finished and the entire
+ # input stream has been processed by the runnable.
+ {
+ "op": "add",
+ "path": f"/logs/{index}/final_output",
+ # to undo the dumpd done by some runnables / tracer / etc
+ "value": _get_standardized_outputs(run, self._schema_format),
+ },
+ {
+ "op": "add",
+ "path": f"/logs/{index}/end_time",
+ "value": run.end_time.isoformat(timespec="milliseconds")
+ if run.end_time is not None
+ else None,
+ },
+ ]
+ )
+
+ self.send(*ops)
+ finally:
+ if run.id == self.root_id and self.auto_close:
+ self.send_stream.close()
+
+ def _on_llm_new_token(
+ self,
+ run: Run,
+ token: str,
+ chunk: GenerationChunk | ChatGenerationChunk | None,
+ ) -> None:
+ """Process new LLM token."""
+ index = self._key_map_by_run_id.get(run.id)
+
+ if index is None:
+ return
+
+ self.send(
+ {
+ "op": "add",
+ "path": f"/logs/{index}/streamed_output_str/-",
+ "value": token,
+ },
+ {
+ "op": "add",
+ "path": f"/logs/{index}/streamed_output/-",
+ "value": chunk.message
+ if isinstance(chunk, ChatGenerationChunk)
+ else token,
+ },
+ )
+
+
+def _get_standardized_inputs(
+ run: Run, schema_format: Literal["original", "streaming_events"]
+) -> Any:
+ """Extract standardized inputs from a `Run`.
+
+ Standardizes the inputs based on the type of the runnable used.
+
+ Args:
+ run: `Run` object
+ schema_format: The schema format to use.
+
+ Returns:
+ Valid inputs are only dict. By conventions, inputs always represented invocation
+ using named arguments. `None` means that the input is not yet known!
+ """
+ if schema_format == "original":
+ msg = (
+ "Do not assign inputs with original schema drop the key for now."
+ "When inputs are added to astream_log they should be added with "
+ "standardized schema for streaming events."
+ )
+ raise NotImplementedError(msg)
+
+ inputs = load(run.inputs, allowed_objects="messages")
+
+ if run.run_type in {"retriever", "llm", "chat_model"}:
+ return inputs
+
+ # new style chains
+ # These nest an additional 'input' key inside the 'inputs' to make sure
+ # the input is always a dict. We need to unpack and use the inner value.
+ inputs = inputs["input"]
+ # We should try to fix this in Runnables and callbacks/tracers
+ # Runnables should be using a None type here not a placeholder
+ # dict.
+ if inputs == {"input": ""}: # Workaround for Runnables not using None
+ # The input is not known, so we don't assign data['input']
+ return None
+ return inputs
+
+
+def _get_standardized_outputs(
+ run: Run, schema_format: Literal["original", "streaming_events", "original+chat"]
+) -> Any | None:
+ """Extract standardized output from a run.
+
+ Standardizes the outputs based on the type of the runnable used.
+
+ Args:
+ run: the run object.
+ schema_format: The schema format to use.
+
+ Returns:
+ An output if returned, otherwise `None`.
+ """
+ outputs = load(run.outputs, allowed_objects="messages")
+ if schema_format == "original":
+ if run.run_type == "prompt" and "output" in outputs:
+ # These were previously dumped before the tracer.
+ # Now we needn't do anything to them.
+ return outputs["output"]
+ # Return the old schema, without standardizing anything
+ return outputs
+
+ if run.run_type in {"retriever", "llm", "chat_model"}:
+ return outputs
+
+ if isinstance(outputs, dict):
+ return outputs.get("output", None)
+
+ return None
+
+
+@overload
+def _astream_log_implementation(
+ runnable: Runnable[Input, Output],
+ value: Any,
+ config: RunnableConfig | None = None,
+ *,
+ stream: LogStreamCallbackHandler,
+ diff: Literal[True] = True,
+ with_streamed_output_list: bool = True,
+ **kwargs: Any,
+) -> AsyncIterator[RunLogPatch]: ...
+
+
+@overload
+def _astream_log_implementation(
+ runnable: Runnable[Input, Output],
+ value: Any,
+ config: RunnableConfig | None = None,
+ *,
+ stream: LogStreamCallbackHandler,
+ diff: Literal[False],
+ with_streamed_output_list: bool = True,
+ **kwargs: Any,
+) -> AsyncIterator[RunLog]: ...
+
+
+async def _astream_log_implementation(
+ runnable: Runnable[Input, Output],
+ value: Any,
+ config: RunnableConfig | None = None,
+ *,
+ stream: LogStreamCallbackHandler,
+ diff: bool = True,
+ with_streamed_output_list: bool = True,
+ **kwargs: Any,
+) -> AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]:
+ """Implementation of astream_log for a given runnable.
+
+ The implementation has been factored out (at least temporarily) as both
+ `astream_log` and `astream_events` rely on it.
+
+ Args:
+ runnable: The runnable to run in streaming mode.
+ value: The input to the runnable.
+ config: The config to pass to the runnable.
+ stream: The stream to send the run logs to.
+ diff: Whether to yield run log patches (`True`) or full run logs (`False`).
+ with_streamed_output_list: Whether to include a list of all streamed outputs in
+ each patch. If `False`, only the final output will be included in the
+ patches.
+ **kwargs: Additional keyword arguments to pass to the `Runnable`.
+
+ Raises:
+ ValueError: If the callbacks in the config are of an unexpected type.
+
+ Yields:
+ The run log patches or states, depending on the value of `diff`.
+ """
+ # Assign the stream handler to the config
+ config = ensure_config(config)
+ callbacks = config.get("callbacks")
+ if callbacks is None:
+ config["callbacks"] = [stream]
+ elif isinstance(callbacks, list):
+ config["callbacks"] = [*callbacks, stream]
+ elif isinstance(callbacks, BaseCallbackManager):
+ callbacks = callbacks.copy()
+ callbacks.add_handler(stream, inherit=True)
+ config["callbacks"] = callbacks
+ else:
+ msg = (
+ f"Unexpected type for callbacks: {callbacks}."
+ "Expected None, list or AsyncCallbackManager."
+ )
+ raise ValueError(msg)
+
+ # Call the runnable in streaming mode,
+ # add each chunk to the output stream
+ async def consume_astream() -> None:
+ try:
+ prev_final_output: Output | None = None
+ final_output: Output | None = None
+
+ async for chunk in runnable.astream(value, config, **kwargs):
+ prev_final_output = final_output
+ if final_output is None:
+ final_output = chunk
+ else:
+ try:
+ final_output = final_output + chunk # type: ignore[operator]
+ except TypeError:
+ prev_final_output = None
+ final_output = chunk
+ patches: list[dict[str, Any]] = []
+ if with_streamed_output_list:
+ patches.append(
+ {
+ "op": "add",
+ "path": "/streamed_output/-",
+ # chunk cannot be shared between
+ # streamed_output and final_output
+ # otherwise jsonpatch.apply will
+ # modify both
+ "value": copy.deepcopy(chunk),
+ }
+ )
+ patches.extend(
+ {**op, "path": f"/final_output{op['path']}"}
+ for op in jsonpatch.JsonPatch.from_diff(
+ prev_final_output, final_output, dumps=dumps
+ )
+ )
+ await stream.send_stream.send(RunLogPatch(*patches))
+ finally:
+ await stream.send_stream.aclose()
+
+ # Start the runnable in a task, so we can start consuming output
+ task = asyncio.create_task(consume_astream())
+ try:
+ # Yield each chunk from the output stream
+ if diff:
+ async for log in stream:
+ yield log
+ else:
+ state = RunLog(state=None) # type: ignore[arg-type]
+ async for log in stream:
+ state += log
+ yield state
+ finally:
+ # Wait for the runnable to finish, if not cancelled (eg. by break)
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/memory_stream.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/memory_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..42e74fb00d9d82e2bd6c6a261f3b9eb2b1492582
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/memory_stream.py
@@ -0,0 +1,148 @@
+"""Module implements a memory stream for communication between two co-routines.
+
+This module provides a way to communicate between two co-routines using a memory
+channel. The writer and reader can be in the same event loop or in different event
+loops. When they're in different event loops, they will also be in different threads.
+
+Useful in situations when there's a mix of synchronous and asynchronous used in the
+code.
+"""
+
+import asyncio
+from asyncio import AbstractEventLoop, Queue
+from collections.abc import AsyncIterator
+from typing import Generic, TypeVar
+
+T = TypeVar("T")
+
+
+class _SendStream(Generic[T]):
+ def __init__(
+ self, reader_loop: AbstractEventLoop, queue: Queue, done: object
+ ) -> None:
+ """Create a writer for the queue and done object.
+
+ Args:
+ reader_loop: The event loop to use for the writer.
+
+ This loop will be used to schedule the writes to the queue.
+ queue: The queue to write to.
+
+ This is an asyncio queue.
+ done: Special sentinel object to indicate that the writer is done.
+ """
+ self._reader_loop = reader_loop
+ self._queue = queue
+ self._done = done
+
+ async def send(self, item: T) -> None:
+ """Schedule the item to be written to the queue using the original loop.
+
+ This is a coroutine that can be awaited.
+
+ Args:
+ item: The item to write to the queue.
+ """
+ return self.send_nowait(item)
+
+ def send_nowait(self, item: T) -> None:
+ """Schedule the item to be written to the queue using the original loop.
+
+ This is a non-blocking call.
+
+ Args:
+ item: The item to write to the queue.
+
+ Raises:
+ RuntimeError: If the event loop is already closed when trying to write to
+ the queue.
+ """
+ try:
+ self._reader_loop.call_soon_threadsafe(self._queue.put_nowait, item)
+ except RuntimeError:
+ if not self._reader_loop.is_closed():
+ raise # Raise the exception if the loop is not closed
+
+ async def aclose(self) -> None:
+ """Async schedule the done object write the queue using the original loop."""
+ return self.close()
+
+ def close(self) -> None:
+ """Schedule the done object write the queue using the original loop.
+
+ This is a non-blocking call.
+
+ Raises:
+ RuntimeError: If the event loop is already closed when trying to write to
+ the queue.
+ """
+ try:
+ self._reader_loop.call_soon_threadsafe(self._queue.put_nowait, self._done)
+ except RuntimeError:
+ if not self._reader_loop.is_closed():
+ raise # Raise the exception if the loop is not closed
+
+
+class _ReceiveStream(Generic[T]):
+ def __init__(self, queue: Queue, done: object) -> None:
+ """Create a reader for the queue and done object.
+
+ This reader should be used in the same loop as the loop that was passed to the
+ channel.
+ """
+ self._queue = queue
+ self._done = done
+ self._is_closed = False
+
+ async def __aiter__(self) -> AsyncIterator[T]:
+ while True:
+ item = await self._queue.get()
+ if item is self._done:
+ self._is_closed = True
+ break
+ yield item
+
+
+class _MemoryStream(Generic[T]):
+ """Stream data from a writer to a reader even if they are in different threads.
+
+ Uses asyncio queues to communicate between two co-routines. This implementation
+ should work even if the writer and reader co-routines belong to two different event
+ loops (e.g. one running from an event loop in the main thread and the other running
+ in an event loop in a background thread).
+
+ This implementation is meant to be used with a single writer and a single reader.
+
+ This is an internal implementation to LangChain. Do not use it directly.
+ """
+
+ def __init__(self, loop: AbstractEventLoop) -> None:
+ """Create a channel for the given loop.
+
+ Args:
+ loop: The event loop to use for the channel.
+
+ The reader is assumed to be running in the same loop as the one passed
+ to this constructor. This will NOT be validated at run time.
+ """
+ self._loop = loop
+ self._queue: asyncio.Queue = asyncio.Queue(maxsize=0)
+ self._done = object()
+
+ def get_send_stream(self) -> _SendStream[T]:
+ """Get a writer for the channel.
+
+ Returns:
+ The writer for the channel.
+ """
+ return _SendStream[T](
+ reader_loop=self._loop, queue=self._queue, done=self._done
+ )
+
+ def get_receive_stream(self) -> _ReceiveStream[T]:
+ """Get a reader for the channel.
+
+ Returns:
+ The reader for the channel.
+ """
+ return _ReceiveStream[T](queue=self._queue, done=self._done)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/root_listeners.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/root_listeners.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d1c90612e9aafd5e22e50b1a931e2ce083f4e68
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/root_listeners.py
@@ -0,0 +1,130 @@
+"""Tracers that call listeners."""
+
+from collections.abc import Awaitable, Callable
+from typing import TYPE_CHECKING
+
+from langchain_core.runnables.config import (
+ RunnableConfig,
+ acall_func_with_variable_args,
+ call_func_with_variable_args,
+)
+from langchain_core.tracers.base import AsyncBaseTracer, BaseTracer
+from langchain_core.tracers.schemas import Run
+
+if TYPE_CHECKING:
+ from uuid import UUID
+
+Listener = Callable[[Run], None] | Callable[[Run, RunnableConfig], None]
+AsyncListener = (
+ Callable[[Run], Awaitable[None]] | Callable[[Run, RunnableConfig], Awaitable[None]]
+)
+
+
+class RootListenersTracer(BaseTracer):
+ """Tracer that calls listeners on run start, end, and error."""
+
+ log_missing_parent = False
+ """Whether to log a warning if the parent is missing."""
+
+ def __init__(
+ self,
+ *,
+ config: RunnableConfig,
+ on_start: Listener | None,
+ on_end: Listener | None,
+ on_error: Listener | None,
+ ) -> None:
+ """Initialize the tracer.
+
+ Args:
+ config: The runnable config.
+ on_start: The listener to call on run start.
+ on_end: The listener to call on run end.
+ on_error: The listener to call on run error
+ """
+ super().__init__(_schema_format="original+chat")
+
+ self.config = config
+ self._arg_on_start = on_start
+ self._arg_on_end = on_end
+ self._arg_on_error = on_error
+ self.root_id: UUID | None = None
+
+ def _persist_run(self, run: Run) -> None:
+ # This is a legacy method only called once for an entire run tree
+ # therefore not useful here
+ pass
+
+ def _on_run_create(self, run: Run) -> None:
+ if self.root_id is not None:
+ return
+
+ self.root_id = run.id
+
+ if self._arg_on_start is not None:
+ call_func_with_variable_args(self._arg_on_start, run, self.config)
+
+ def _on_run_update(self, run: Run) -> None:
+ if run.id != self.root_id:
+ return
+
+ if run.error is None:
+ if self._arg_on_end is not None:
+ call_func_with_variable_args(self._arg_on_end, run, self.config)
+ elif self._arg_on_error is not None:
+ call_func_with_variable_args(self._arg_on_error, run, self.config)
+
+
+class AsyncRootListenersTracer(AsyncBaseTracer):
+ """Async tracer that calls listeners on run start, end, and error."""
+
+ log_missing_parent = False
+ """Whether to log a warning if the parent is missing."""
+
+ def __init__(
+ self,
+ *,
+ config: RunnableConfig,
+ on_start: AsyncListener | None,
+ on_end: AsyncListener | None,
+ on_error: AsyncListener | None,
+ ) -> None:
+ """Initialize the tracer.
+
+ Args:
+ config: The runnable config.
+ on_start: The listener to call on run start.
+ on_end: The listener to call on run end.
+ on_error: The listener to call on run error
+ """
+ super().__init__(_schema_format="original+chat")
+
+ self.config = config
+ self._arg_on_start = on_start
+ self._arg_on_end = on_end
+ self._arg_on_error = on_error
+ self.root_id: UUID | None = None
+
+ async def _persist_run(self, run: Run) -> None:
+ # This is a legacy method only called once for an entire run tree
+ # therefore not useful here
+ pass
+
+ async def _on_run_create(self, run: Run) -> None:
+ if self.root_id is not None:
+ return
+
+ self.root_id = run.id
+
+ if self._arg_on_start is not None:
+ await acall_func_with_variable_args(self._arg_on_start, run, self.config)
+
+ async def _on_run_update(self, run: Run) -> None:
+ if run.id != self.root_id:
+ return
+
+ if run.error is None:
+ if self._arg_on_end is not None:
+ await acall_func_with_variable_args(self._arg_on_end, run, self.config)
+ elif self._arg_on_error is not None:
+ await acall_func_with_variable_args(self._arg_on_error, run, self.config)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/run_collector.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/run_collector.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d389af2721ca7be7e48b7899f247919069c01a1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/run_collector.py
@@ -0,0 +1,40 @@
+"""A tracer that collects all nested runs in a list."""
+
+from typing import Any
+from uuid import UUID
+
+from langchain_core.tracers._compat import run_copy
+from langchain_core.tracers.base import BaseTracer
+from langchain_core.tracers.schemas import Run
+
+
+class RunCollectorCallbackHandler(BaseTracer):
+ """Tracer that collects all nested runs in a list.
+
+ This tracer is useful for inspection and evaluation purposes.
+ """
+
+ name: str = "run-collector_callback_handler"
+
+ def __init__(self, example_id: UUID | str | None = None, **kwargs: Any) -> None:
+ """Initialize the `RunCollectorCallbackHandler`.
+
+ Args:
+ example_id: The ID of the example being traced.
+ **kwargs: Additional keyword arguments.
+ """
+ super().__init__(**kwargs)
+ self.example_id = (
+ UUID(example_id) if isinstance(example_id, str) else example_id
+ )
+ self.traced_runs: list[Run] = []
+
+ def _persist_run(self, run: Run) -> None:
+ """Persist a run by adding it to the `traced_runs` list.
+
+ Args:
+ run: The run to be persisted.
+ """
+ run_ = run_copy(run)
+ run_.reference_example_id = self.example_id
+ self.traced_runs.append(run_)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/schemas.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/schemas.py
new file mode 100644
index 0000000000000000000000000000000000000000..67a37035b4dc4e12007d680ac37154dc1c9a1d3b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/schemas.py
@@ -0,0 +1,14 @@
+"""Schemas for tracers."""
+
+from __future__ import annotations
+
+from langsmith import RunTree
+
+# Begin V2 API Schemas
+
+
+Run = RunTree # For backwards compatibility
+
+__all__ = [
+ "Run",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/stdout.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/stdout.py
new file mode 100644
index 0000000000000000000000000000000000000000..b47bb512a6e6ebd9fc4147c3d9df815eb580ea9a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/tracers/stdout.py
@@ -0,0 +1,205 @@
+"""Tracers that print to the console."""
+
+import json
+from collections.abc import Callable
+from typing import Any
+
+from langchain_core.tracers.base import BaseTracer
+from langchain_core.tracers.schemas import Run
+from langchain_core.utils.input import get_bolded_text, get_colored_text
+
+MILLISECONDS_IN_SECOND = 1000
+
+
+def try_json_stringify(obj: Any, fallback: str) -> str:
+ """Try to stringify an object to JSON.
+
+ Args:
+ obj: Object to stringify.
+ fallback: Fallback string to return if the object cannot be stringified.
+
+ Returns:
+ A JSON string if the object can be stringified, otherwise the fallback string.
+ """
+ try:
+ return json.dumps(obj, indent=2, ensure_ascii=False)
+ except Exception:
+ return fallback
+
+
+def elapsed(run: Any) -> str:
+ """Get the elapsed time of a run.
+
+ Args:
+ run: any object with a `start_time` and `end_time` attribute.
+
+ Returns:
+ A string with the elapsed time in seconds or milliseconds if time is less than a
+ second.
+
+ """
+ elapsed_time = run.end_time - run.start_time
+ seconds = elapsed_time.total_seconds()
+ if seconds < 1:
+ return f"{seconds * MILLISECONDS_IN_SECOND:.0f}ms"
+ return f"{seconds:.2f}s"
+
+
+class FunctionCallbackHandler(BaseTracer):
+ """Tracer that calls a function with a single str parameter."""
+
+ name: str = "function_callback_handler"
+ """The name of the tracer.
+
+ This is used to identify the tracer in the logs.
+ """
+
+ def __init__(self, function: Callable[[str], None], **kwargs: Any) -> None:
+ """Create a `FunctionCallbackHandler`.
+
+ Args:
+ function: The callback function to call.
+ """
+ super().__init__(**kwargs)
+ self.function_callback = function
+
+ def _persist_run(self, run: Run) -> None:
+ pass
+
+ def get_parents(self, run: Run) -> list[Run]:
+ """Get the parents of a run.
+
+ Args:
+ run: The run to get the parents of.
+
+ Returns:
+ A list of parent runs.
+ """
+ parents = []
+ current_run = run
+ while current_run.parent_run_id:
+ parent = self.run_map.get(str(current_run.parent_run_id))
+ if parent:
+ parents.append(parent)
+ current_run = parent
+ else:
+ break
+ return parents
+
+ def get_breadcrumbs(self, run: Run) -> str:
+ """Get the breadcrumbs of a run.
+
+ Args:
+ run: The run to get the breadcrumbs of.
+
+ Returns:
+ A string with the breadcrumbs of the run.
+ """
+ parents = self.get_parents(run)[::-1]
+ return " > ".join(
+ f"{parent.run_type}:{parent.name}"
+ for i, parent in enumerate([*parents, run])
+ )
+
+ # logging methods
+ def _on_chain_start(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ run_type = run.run_type.capitalize()
+ self.function_callback(
+ f"{get_colored_text('[chain/start]', color='green')} "
+ + get_bolded_text(f"[{crumbs}] Entering {run_type} run with input:\n")
+ + f"{try_json_stringify(run.inputs, '[inputs]')}"
+ )
+
+ def _on_chain_end(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ run_type = run.run_type.capitalize()
+ self.function_callback(
+ f"{get_colored_text('[chain/end]', color='blue')} "
+ + get_bolded_text(
+ f"[{crumbs}] [{elapsed(run)}] Exiting {run_type} run with output:\n"
+ )
+ + f"{try_json_stringify(run.outputs, '[outputs]')}"
+ )
+
+ def _on_chain_error(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ run_type = run.run_type.capitalize()
+ self.function_callback(
+ f"{get_colored_text('[chain/error]', color='red')} "
+ + get_bolded_text(
+ f"[{crumbs}] [{elapsed(run)}] {run_type} run errored with error:\n"
+ )
+ + f"{try_json_stringify(run.error, '[error]')}"
+ )
+
+ def _on_llm_start(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ inputs = (
+ {"prompts": [p.strip() for p in run.inputs["prompts"]]}
+ if "prompts" in run.inputs
+ else run.inputs
+ )
+ self.function_callback(
+ f"{get_colored_text('[llm/start]', color='green')} "
+ + get_bolded_text(f"[{crumbs}] Entering LLM run with input:\n")
+ + f"{try_json_stringify(inputs, '[inputs]')}"
+ )
+
+ def _on_llm_end(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ self.function_callback(
+ f"{get_colored_text('[llm/end]', color='blue')} "
+ + get_bolded_text(
+ f"[{crumbs}] [{elapsed(run)}] Exiting LLM run with output:\n"
+ )
+ + f"{try_json_stringify(run.outputs, '[response]')}"
+ )
+
+ def _on_llm_error(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ self.function_callback(
+ f"{get_colored_text('[llm/error]', color='red')} "
+ + get_bolded_text(
+ f"[{crumbs}] [{elapsed(run)}] LLM run errored with error:\n"
+ )
+ + f"{try_json_stringify(run.error, '[error]')}"
+ )
+
+ def _on_tool_start(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ self.function_callback(
+ f"{get_colored_text('[tool/start]', color='green')} "
+ + get_bolded_text(f"[{crumbs}] Entering Tool run with input:\n")
+ + f'"{run.inputs["input"].strip()}"'
+ )
+
+ def _on_tool_end(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ if run.outputs:
+ self.function_callback(
+ f"{get_colored_text('[tool/end]', color='blue')} "
+ + get_bolded_text(
+ f"[{crumbs}] [{elapsed(run)}] Exiting Tool run with output:\n"
+ )
+ + f'"{str(run.outputs["output"]).strip()}"'
+ )
+
+ def _on_tool_error(self, run: Run) -> None:
+ crumbs = self.get_breadcrumbs(run)
+ self.function_callback(
+ f"{get_colored_text('[tool/error]', color='red')} "
+ + get_bolded_text(f"[{crumbs}] [{elapsed(run)}] ")
+ + f"Tool run errored with error:\n"
+ f"{run.error}"
+ )
+
+
+class ConsoleCallbackHandler(FunctionCallbackHandler):
+ """Tracer that prints to the console."""
+
+ name: str = "console_callback_handler"
+
+ def __init__(self, **kwargs: Any) -> None:
+ """Create a ConsoleCallbackHandler."""
+ super().__init__(function=print, **kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0421658370240aa7e3ae6d9584c88d65f6820595
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__init__.py
@@ -0,0 +1,111 @@
+"""Utility functions for LangChain.
+
+These functions do not depend on any other LangChain module.
+"""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ # for type checking and IDE support, we include the imports here
+ # but we don't want to eagerly import them at runtime
+ from langchain_core.utils import image
+ from langchain_core.utils.aiter import abatch_iterate
+ from langchain_core.utils.env import get_from_dict_or_env, get_from_env
+ from langchain_core.utils.formatting import StrictFormatter, formatter
+ from langchain_core.utils.input import (
+ get_bolded_text,
+ get_color_mapping,
+ get_colored_text,
+ print_text,
+ )
+ from langchain_core.utils.iter import batch_iterate
+ from langchain_core.utils.pydantic import pre_init
+ from langchain_core.utils.strings import (
+ comma_list,
+ sanitize_for_postgres,
+ stringify_dict,
+ stringify_value,
+ )
+ from langchain_core.utils.utils import (
+ build_extra_kwargs,
+ check_package_version,
+ convert_to_secret_str,
+ from_env,
+ get_pydantic_field_names,
+ guard_import,
+ mock_now,
+ raise_for_status_with_text,
+ secret_from_env,
+ xor_args,
+ )
+
+__all__ = (
+ "StrictFormatter",
+ "abatch_iterate",
+ "batch_iterate",
+ "build_extra_kwargs",
+ "check_package_version",
+ "comma_list",
+ "convert_to_secret_str",
+ "formatter",
+ "from_env",
+ "get_bolded_text",
+ "get_color_mapping",
+ "get_colored_text",
+ "get_from_dict_or_env",
+ "get_from_env",
+ "get_pydantic_field_names",
+ "guard_import",
+ "image",
+ "mock_now",
+ "pre_init",
+ "print_text",
+ "raise_for_status_with_text",
+ "sanitize_for_postgres",
+ "secret_from_env",
+ "stringify_dict",
+ "stringify_value",
+ "xor_args",
+)
+
+_dynamic_imports = {
+ "image": "__module__",
+ "abatch_iterate": "aiter",
+ "get_from_dict_or_env": "env",
+ "get_from_env": "env",
+ "StrictFormatter": "formatting",
+ "formatter": "formatting",
+ "get_bolded_text": "input",
+ "get_color_mapping": "input",
+ "get_colored_text": "input",
+ "print_text": "input",
+ "batch_iterate": "iter",
+ "pre_init": "pydantic",
+ "comma_list": "strings",
+ "sanitize_for_postgres": "strings",
+ "stringify_dict": "strings",
+ "stringify_value": "strings",
+ "build_extra_kwargs": "utils",
+ "check_package_version": "utils",
+ "convert_to_secret_str": "utils",
+ "from_env": "utils",
+ "get_pydantic_field_names": "utils",
+ "guard_import": "utils",
+ "mock_now": "utils",
+ "secret_from_env": "utils",
+ "xor_args": "utils",
+ "raise_for_status_with_text": "utils",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2fec8d3bfe817710a1240121898e6ee02e20d22b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/_merge.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/_merge.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ffe9c5319a0aa881be9faf82d6404482de9eb99
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/_merge.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/aiter.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/aiter.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1f312c88aaa205b7828f7f21018779d31afbbf9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/aiter.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/env.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/env.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1287415f109d042a0dc709bc7a4d8cfc05dd92f8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/env.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/formatting.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/formatting.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..431ca5cdb7382649f90f0119975fa99b71c5d0cc
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/formatting.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/function_calling.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/function_calling.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f95bd7a5264c20f95e77aa23506890ad184659e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/function_calling.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/html.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/html.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9a4262ced669cd97aaac31fa37979a58d544fa8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/html.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/image.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/image.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc9e425cf2eff0a33721a01cd05de70ee8bf5930
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/image.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/input.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/input.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43dbcc8f447dc05eb978622eac1713ddf0f2e73f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/input.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/interactive_env.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/interactive_env.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db9a5b2196892165694f8e63ab0e1a19498eab4b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/interactive_env.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/iter.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/iter.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb15a4c82c93d984b84d4a6d32c251914130fca6
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/iter.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/json.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/json.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..948c39ad758545487e4aef7577ec9afd29909430
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/json.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/json_schema.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/json_schema.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5f3083ef3e3394533bb5750e4f377d297e23438
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/json_schema.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/mustache.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/mustache.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b309575abd8c4d4ee1e0866e4af89709191c0f14
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/mustache.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/pydantic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/pydantic.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a77f4ac16966fa898fe7df954d4667ca4bf19ed4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/pydantic.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/strings.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/strings.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ced0ca2272b46edab089a5b7ce522c86b0959929
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/strings.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/usage.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/usage.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cf4ea4943784643f36455da11754e6df6f1e8bf
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/usage.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05ca86f1acb9a2d019639017943e592a5463056c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/uuid.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/uuid.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6f21242962b56c065da395a8720faf182455983
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/__pycache__/uuid.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/_merge.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/_merge.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a0cb38f078509ecfb646b6e75981653b9389c4e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/_merge.py
@@ -0,0 +1,208 @@
+from __future__ import annotations
+
+from typing import Any
+
+
+def merge_dicts(left: dict[str, Any], *others: dict[str, Any]) -> dict[str, Any]:
+ r"""Merge dictionaries.
+
+ Merge many dicts, handling specific scenarios where a key exists in both
+ dictionaries but has a value of `None` in `'left'`. In such cases, the method uses
+ the value from `'right'` for that key in the merged dictionary.
+
+ Args:
+ left: The first dictionary to merge.
+ others: The other dictionaries to merge.
+
+ Returns:
+ The merged dictionary.
+
+ Raises:
+ TypeError: If the key exists in both dictionaries but has a different type.
+ TypeError: If the value has an unsupported type.
+
+ Example:
+ If `left = {"function_call": {"arguments": None}}` and
+ `right = {"function_call": {"arguments": "{\n"}}`, then, after merging, for the
+ key `'function_call'`, the value from `'right'` is used, resulting in
+ `merged = {"function_call": {"arguments": "{\n"}}`.
+ """
+ merged = left.copy()
+ for right in others:
+ for right_k, right_v in right.items():
+ if right_k not in merged or (
+ right_v is not None and merged[right_k] is None
+ ):
+ merged[right_k] = right_v
+ elif right_v is None:
+ continue
+ elif type(merged[right_k]) is not type(right_v):
+ msg = (
+ f'additional_kwargs["{right_k}"] already exists in this message,'
+ " but with a different type."
+ )
+ raise TypeError(msg)
+ elif isinstance(merged[right_k], str):
+ # TODO: Add below special handling for 'type' key in 0.3 and remove
+ # merge_lists 'type' logic.
+ #
+ # if right_k == "type":
+ # if merged[right_k] == right_v:
+ # continue
+ # else:
+ # raise ValueError(
+ # "Unable to merge. Two different values seen for special "
+ # f"key 'type': {merged[right_k]} and {right_v}. 'type' "
+ # "should either occur once or have the same value across "
+ # "all dicts."
+ # )
+ if (right_k == "index" and merged[right_k].startswith("lc_")) or (
+ right_k in {"id", "output_version", "model_provider"}
+ and merged[right_k] == right_v
+ ):
+ continue
+ merged[right_k] += right_v
+ elif isinstance(merged[right_k], dict):
+ merged[right_k] = merge_dicts(merged[right_k], right_v)
+ elif isinstance(merged[right_k], list):
+ merged[right_k] = merge_lists(merged[right_k], right_v)
+ elif merged[right_k] == right_v:
+ continue
+ elif isinstance(merged[right_k], int):
+ # Preserve identification and temporal fields using last-wins strategy
+ # instead of summing:
+ # - index: identifies which tool call a chunk belongs to
+ # - created/timestamp: temporal values that shouldn't be accumulated
+ if right_k in {"index", "created", "timestamp"}:
+ merged[right_k] = right_v
+ else:
+ merged[right_k] += right_v
+ else:
+ msg = (
+ f"Additional kwargs key {right_k} already exists in left dict and "
+ f"value has unsupported type {type(merged[right_k])}."
+ )
+ raise TypeError(msg)
+ return merged
+
+
+def merge_lists(left: list | None, *others: list | None) -> list | None:
+ """Add many lists, handling `None`.
+
+ Args:
+ left: The first list to merge.
+ others: The other lists to merge.
+
+ Returns:
+ The merged list.
+ """
+ merged = left.copy() if left is not None else None
+ for other in others:
+ if other is None:
+ continue
+ if merged is None:
+ merged = other.copy()
+ else:
+ for e in other:
+ if (
+ isinstance(e, dict)
+ and "index" in e
+ and (
+ isinstance(e["index"], int)
+ or (
+ isinstance(e["index"], str) and e["index"].startswith("lc_")
+ )
+ )
+ ):
+ to_merge = [
+ i
+ for i, e_left in enumerate(merged)
+ if (
+ "index" in e_left
+ and e_left["index"] == e["index"] # index matches
+ and ( # IDs not inconsistent
+ e_left.get("id") in (None, "")
+ or e.get("id") in (None, "")
+ or e_left.get("id") == e.get("id")
+ )
+ )
+ ]
+ if to_merge:
+ # TODO: Remove this once merge_dict is updated with special
+ # handling for 'type'.
+ if (left_type := merged[to_merge[0]].get("type")) and (
+ e.get("type") == "non_standard" and "value" in e
+ ):
+ if left_type != "non_standard":
+ # standard + non_standard
+ new_e: dict[str, Any] = {
+ "extras": {
+ k: v
+ for k, v in e["value"].items()
+ if k != "type"
+ }
+ }
+ else:
+ # non_standard + non_standard
+ new_e = {
+ "value": {
+ k: v
+ for k, v in e["value"].items()
+ if k != "type"
+ }
+ }
+ if "index" in e:
+ new_e["index"] = e["index"]
+ else:
+ new_e = (
+ {k: v for k, v in e.items() if k != "type"}
+ if "type" in e
+ else e
+ )
+ merged[to_merge[0]] = merge_dicts(merged[to_merge[0]], new_e)
+ else:
+ merged.append(e)
+ else:
+ merged.append(e)
+ return merged
+
+
+def merge_obj(left: Any, right: Any) -> Any:
+ """Merge two objects.
+
+ It handles specific scenarios where a key exists in both dictionaries but has a
+ value of `None` in `'left'`. In such cases, the method uses the value from `'right'`
+ for that key in the merged dictionary.
+
+ Args:
+ left: The first object to merge.
+ right: The other object to merge.
+
+ Returns:
+ The merged object.
+
+ Raises:
+ TypeError: If the key exists in both dictionaries but has a different type.
+ ValueError: If the two objects cannot be merged.
+ """
+ if left is None or right is None:
+ return left if left is not None else right
+ if type(left) is not type(right):
+ msg = (
+ f"left and right are of different types. Left type: {type(left)}. Right "
+ f"type: {type(right)}."
+ )
+ raise TypeError(msg)
+ if isinstance(left, str):
+ return left + right
+ if isinstance(left, dict):
+ return merge_dicts(left, right)
+ if isinstance(left, list):
+ return merge_lists(left, right)
+ if left == right:
+ return left
+ msg = (
+ f"Unable to merge {left=} and {right=}. Both must be of type str, dict, or "
+ f"list, or else be two equal objects."
+ )
+ raise ValueError(msg)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/aiter.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/aiter.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5dc0d1aea2ebb99269d9c913b911eaeb2979f90
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/aiter.py
@@ -0,0 +1,347 @@
+"""Asynchronous iterator utilities.
+
+Adapted from
+https://github.com/maxfischer2781/asyncstdlib/blob/master/asyncstdlib/itertools.py
+MIT License.
+"""
+
+from collections import deque
+from collections.abc import (
+ AsyncGenerator,
+ AsyncIterable,
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Iterator,
+)
+from contextlib import AbstractAsyncContextManager
+from types import TracebackType
+from typing import (
+ Any,
+ Generic,
+ TypeVar,
+ cast,
+ overload,
+)
+
+from typing_extensions import override
+
+from langchain_core._api.deprecation import deprecated
+
+T = TypeVar("T")
+
+_no_default = object()
+
+
+# https://github.com/python/cpython/blob/main/Lib/test/test_asyncgen.py#L54
+@deprecated(since="1.1.2", removal="2.0.0")
+def py_anext(
+ iterator: AsyncIterator[T], default: T | Any = _no_default
+) -> Awaitable[T | Any | None]:
+ """Pure-Python implementation of `anext()` for testing purposes.
+
+ Closely matches the builtin `anext()` C implementation.
+
+ Can be used to compare the built-in implementation of the inner coroutines machinery
+ to C-implementation of `__anext__()` and `send()` or `throw()` on the returned
+ generator.
+
+ Args:
+ iterator: The async iterator to advance.
+ default: The value to return if the iterator is exhausted.
+
+ If not provided, a `StopAsyncIteration` exception is raised.
+
+ Returns:
+ The next value from the iterator, or the default value if the iterator is
+ exhausted.
+
+ Raises:
+ TypeError: If the iterator is not an async iterator.
+ """
+ try:
+ __anext__ = cast(
+ "Callable[[AsyncIterator[T]], Awaitable[T]]", type(iterator).__anext__
+ )
+ except AttributeError as e:
+ msg = f"{iterator!r} is not an async iterator"
+ raise TypeError(msg) from e
+
+ if default is _no_default:
+ return __anext__(iterator)
+
+ async def anext_impl() -> T | Any:
+ try:
+ # The C code is way more low-level than this, as it implements
+ # all methods of the iterator protocol. In this implementation
+ # we're relying on higher-level coroutine concepts, but that's
+ # exactly what we want -- crosstest pure-Python high-level
+ # implementation and low-level C anext() iterators.
+ return await __anext__(iterator)
+ except StopAsyncIteration:
+ return default
+
+ return anext_impl()
+
+
+class NoLock:
+ """Dummy lock that provides the proper interface but no protection."""
+
+ async def __aenter__(self) -> None:
+ """Do nothing."""
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> bool:
+ """Return False, exception not suppressed."""
+ return False
+
+
+async def tee_peer(
+ iterator: AsyncIterator[T],
+ # the buffer specific to this peer
+ buffer: deque[T],
+ # the buffers of all peers, including our own
+ peers: list[deque[T]],
+ lock: AbstractAsyncContextManager[Any],
+) -> AsyncGenerator[T, None]:
+ """An individual iterator of a `tee`.
+
+ This function is a generator that yields items from the shared iterator
+ `iterator`. It buffers items until the least advanced iterator has yielded them as
+ well.
+
+ The buffer is shared with all other peers.
+
+ Args:
+ iterator: The shared iterator.
+ buffer: The buffer for this peer.
+ peers: The buffers of all peers.
+ lock: The lock to synchronise access to the shared buffers.
+
+ Yields:
+ The next item from the shared iterator.
+ """
+ try:
+ while True:
+ if not buffer:
+ async with lock:
+ # Another peer produced an item while we were waiting for the lock.
+ # Proceed with the next loop iteration to yield the item.
+ if buffer:
+ continue
+ try:
+ item = await anext(iterator)
+ except StopAsyncIteration:
+ break
+ else:
+ # Append to all buffers, including our own. We'll fetch our
+ # item from the buffer again, instead of yielding it directly.
+ # This ensures the proper item ordering if any of our peers
+ # are fetching items concurrently. They may have buffered their
+ # item already.
+ for peer_buffer in peers:
+ peer_buffer.append(item)
+ yield buffer.popleft()
+ finally:
+ async with lock:
+ # this peer is done - remove its buffer
+ for idx, peer_buffer in enumerate(peers): # pragma: no branch
+ if peer_buffer is buffer:
+ peers.pop(idx)
+ break
+ # if we are the last peer, try and close the iterator
+ if not peers and hasattr(iterator, "aclose"):
+ await iterator.aclose()
+
+
+class Tee(Generic[T]):
+ """Create `n` separate asynchronous iterators over `iterable`.
+
+ This splits a single `iterable` into multiple iterators, each providing
+ the same items in the same order.
+
+ All child iterators may advance separately but share the same items from `iterable`
+ -- when the most advanced iterator retrieves an item, it is buffered until the least
+ advanced iterator has yielded it as well.
+
+ A `tee` works lazily and can handle an infinite `iterable`, provided
+ that all iterators advance.
+
+ ```python
+ async def derivative(sensor_data):
+ previous, current = a.tee(sensor_data, n=2)
+ await a.anext(previous) # advance one iterator
+ return a.map(operator.sub, previous, current)
+ ```
+
+ Unlike `itertools.tee`, `.tee` returns a custom type instead of a `tuple`. Like a
+ tuple, it can be indexed, iterated and unpacked to get the child iterators. In
+ addition, its `.tee.aclose` method immediately closes all children, and it can be
+ used in an `async with` context for the same effect.
+
+ If `iterable` is an iterator and read elsewhere, `tee` will *not* provide these
+ items. Also, `tee` must internally buffer each item until the last iterator has
+ yielded it; if the most and least advanced iterator differ by most data, using a
+ `list` is more efficient (but not lazy).
+
+ If the underlying iterable is concurrency safe (`anext` may be awaited concurrently)
+ the resulting iterators are concurrency safe as well. Otherwise, the iterators are
+ safe if there is only ever one single "most advanced" iterator.
+
+ To enforce sequential use of `anext`, provide a `lock`
+
+ - e.g. an `asyncio.Lock` instance in an `asyncio` application - and access is
+ automatically synchronised.
+
+ """
+
+ def __init__(
+ self,
+ iterable: AsyncIterator[T],
+ n: int = 2,
+ *,
+ lock: AbstractAsyncContextManager[Any] | None = None,
+ ):
+ """Create a `tee`.
+
+ Args:
+ iterable: The iterable to split.
+ n: The number of iterators to create.
+ lock: The lock to synchronise access to the shared buffers.
+
+ """
+ self._iterator = iterable.__aiter__() # before 3.10 aiter() doesn't exist
+ self._buffers: list[deque[T]] = [deque() for _ in range(n)]
+ self._children = tuple(
+ tee_peer(
+ iterator=self._iterator,
+ buffer=buffer,
+ peers=self._buffers,
+ lock=lock if lock is not None else NoLock(),
+ )
+ for buffer in self._buffers
+ )
+
+ def __len__(self) -> int:
+ """Return the number of child iterators."""
+ return len(self._children)
+
+ @overload
+ def __getitem__(self, item: int) -> AsyncIterator[T]: ...
+
+ @overload
+ def __getitem__(self, item: slice) -> tuple[AsyncIterator[T], ...]: ...
+
+ def __getitem__(
+ self, item: int | slice
+ ) -> AsyncIterator[T] | tuple[AsyncIterator[T], ...]:
+ """Return the child iterator(s) for the given index or slice."""
+ return self._children[item]
+
+ def __iter__(self) -> Iterator[AsyncIterator[T]]:
+ """Iterate over the child iterators.
+
+ Yields:
+ The child iterators.
+ """
+ yield from self._children
+
+ async def __aenter__(self) -> "Tee[T]":
+ """Return the tee instance."""
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> bool:
+ """Close all child iterators.
+
+ Returns:
+ `False`, exceptions not suppressed.
+ """
+ await self.aclose()
+ return False
+
+ async def aclose(self) -> None:
+ """Async close all child iterators."""
+ for child in self._children:
+ await child.aclose()
+
+
+atee = Tee
+
+
+class aclosing(AbstractAsyncContextManager): # noqa: N801
+ """Async context manager to wrap an `AsyncGenerator` that has a `aclose()` method.
+
+ Code like this:
+
+ ```python
+ async with aclosing(.fetch()) as agen:
+
+ ```
+
+ ...is equivalent to this:
+
+ ```python
+ agen = .fetch()
+ try:
+
+ finally:
+ await agen.aclose()
+
+ ```
+ """
+
+ def __init__(self, thing: AsyncGenerator[Any, Any] | AsyncIterator[Any]) -> None:
+ """Create the context manager.
+
+ Args:
+ thing: The resource to wrap.
+ """
+ self.thing = thing
+
+ @override
+ async def __aenter__(self) -> AsyncGenerator[Any, Any] | AsyncIterator[Any]:
+ return self.thing
+
+ @override
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None:
+ if hasattr(self.thing, "aclose"):
+ await self.thing.aclose()
+
+
+async def abatch_iterate(
+ size: int, iterable: AsyncIterable[T]
+) -> AsyncIterator[list[T]]:
+ """Utility batching function for async iterables.
+
+ Args:
+ size: The size of the batch.
+ iterable: The async iterable to batch.
+
+ Yields:
+ The batches.
+ """
+ batch: list[T] = []
+ async for element in iterable:
+ if len(batch) < size:
+ batch.append(element)
+
+ if len(batch) >= size:
+ yield batch
+ batch = []
+
+ if batch:
+ yield batch
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/env.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/env.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8eab221bfe1fd3827cfc401aa474bc7bbd2a06b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/env.py
@@ -0,0 +1,86 @@
+"""Utilities for environment variables."""
+
+from __future__ import annotations
+
+import os
+from typing import Any
+
+
+def env_var_is_set(env_var: str) -> bool:
+ """Check if an environment variable is set.
+
+ Args:
+ env_var: The name of the environment variable.
+
+ Returns:
+ `True` if the environment variable is set, `False` otherwise.
+ """
+ return env_var in os.environ and os.environ[env_var] not in {
+ "",
+ "0",
+ "false",
+ "False",
+ }
+
+
+def get_from_dict_or_env(
+ data: dict[str, Any],
+ key: str | list[str],
+ env_key: str,
+ default: str | None = None,
+) -> str:
+ """Get a value from a dictionary or an environment variable.
+
+ Args:
+ data: The dictionary to look up the key in.
+ key: The key to look up in the dictionary.
+
+ This can be a list of keys to try in order.
+ env_key: The environment variable to look up if the key is not
+ in the dictionary.
+ default: The default value to return if the key is not in the dictionary
+ or the environment.
+
+ Returns:
+ The dict value or the environment variable value.
+ """
+ if isinstance(key, (list, tuple)):
+ for k in key:
+ if value := data.get(k):
+ return str(value)
+
+ if isinstance(key, str) and key in data and data[key]:
+ return str(data[key])
+
+ key_for_err = key[0] if isinstance(key, (list, tuple)) else key
+
+ return get_from_env(key_for_err, env_key, default=default)
+
+
+def get_from_env(key: str, env_key: str, default: str | None = None) -> str:
+ """Get a value from a dictionary or an environment variable.
+
+ Args:
+ key: The key to look up in the dictionary.
+ env_key: The environment variable to look up if the key is not
+ in the dictionary.
+ default: The default value to return if the key is not in the dictionary
+ or the environment.
+
+ Returns:
+ The value of the key.
+
+ Raises:
+ ValueError: If the key is not in the dictionary and no default value is
+ provided or if the environment variable is not set.
+ """
+ if env_value := os.getenv(env_key):
+ return env_value
+ if default is not None:
+ return default
+ msg = (
+ f"Did not find {key}, please add an environment variable"
+ f" `{env_key}` which contains it, or pass"
+ f" `{key}` as a named parameter."
+ )
+ raise ValueError(msg)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/formatting.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/formatting.py
new file mode 100644
index 0000000000000000000000000000000000000000..48905a4cc03dac62fd57456f3f6b91382487a392
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/formatting.py
@@ -0,0 +1,80 @@
+"""Utilities for formatting strings."""
+
+from collections.abc import Mapping, Sequence
+from string import Formatter
+from typing import Any
+
+
+class StrictFormatter(Formatter):
+ """A string formatter that enforces keyword-only argument substitution.
+
+ This formatter extends Python's built-in `string.Formatter` to provide stricter
+ validation for prompt template formatting. It ensures that all variable
+ substitutions use keyword arguments rather than positional arguments, which improves
+ clarity and reduces errors when formatting prompt templates.
+
+ Example:
+ >>> fmt = StrictFormatter()
+ >>> fmt.format("Hello, {name}!", name="World")
+ 'Hello, World!'
+ >>> fmt.format("Hello, {}!", "World") # Raises ValueError
+ """
+
+ def vformat(
+ self, format_string: str, args: Sequence, kwargs: Mapping[str, Any]
+ ) -> str:
+ """Format a string using only keyword arguments.
+
+ Overrides the base `vformat` to reject positional arguments, ensuring all
+ substitutions are explicit and named.
+
+ Args:
+ format_string: A string containing replacement fields (e.g., `'{name}'`).
+ args: Positional arguments (must be empty).
+ kwargs: Keyword arguments for substitution into the format string.
+
+ Returns:
+ The formatted string with all replacement fields substituted.
+
+ Raises:
+ ValueError: If any positional arguments are provided.
+ """
+ if len(args) > 0:
+ msg = (
+ "No arguments should be provided, "
+ "everything should be passed as keyword arguments."
+ )
+ raise ValueError(msg)
+ return super().vformat(format_string, args, kwargs)
+
+ def validate_input_variables(
+ self, format_string: str, input_variables: list[str]
+ ) -> None:
+ """Validate that input variables match the placeholders in a format string.
+
+ Checks that the provided input variables can be used to format the given string
+ without missing or extra keys. This is useful for validating prompt templates
+ before runtime.
+
+ Args:
+ format_string: A string containing replacement fields to validate
+ against (e.g., `'Hello, {name}!'`).
+ input_variables: List of variable names expected to fill the
+ replacement fields.
+
+ Raises:
+ KeyError: If the format string contains placeholders not present
+ in input_variables.
+
+ Example:
+ >>> fmt = StrictFormatter()
+ >>> fmt.validate_input_variables("Hello, {name}!", ["name"]) # OK
+ >>> fmt.validate_input_variables("Hello, {name}!", ["other"]) # Raises
+ """
+ dummy_inputs = dict.fromkeys(input_variables, "foo")
+ super().format(format_string, **dummy_inputs)
+
+
+#: Default StrictFormatter instance for use throughout LangChain.
+#: Used internally for formatting prompt templates with named variables.
+formatter = StrictFormatter()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/function_calling.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/function_calling.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fefd98b0ebd3733491c1e70603116e4ac830ad5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/function_calling.py
@@ -0,0 +1,829 @@
+"""Methods for creating function specs in the style of OpenAI Functions."""
+
+from __future__ import annotations
+
+import collections
+import inspect
+import logging
+import types
+import typing
+import uuid
+from typing import (
+ TYPE_CHECKING,
+ Annotated,
+ Any,
+ Literal,
+ Union,
+ cast,
+ get_args,
+ get_origin,
+ get_type_hints,
+)
+
+import typing_extensions
+from pydantic import BaseModel
+from pydantic.errors import PydanticInvalidForJsonSchema
+from pydantic.v1 import BaseModel as BaseModelV1
+from pydantic.v1 import Field as Field_v1
+from pydantic.v1 import create_model as create_model_v1
+from typing_extensions import TypedDict, is_typeddict
+
+import langchain_core
+from langchain_core._api import beta
+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, ToolMessage
+from langchain_core.utils.json_schema import dereference_refs
+from langchain_core.utils.pydantic import is_basemodel_subclass
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Mapping
+
+ from langchain_core.tools import BaseTool
+
+logger = logging.getLogger(__name__)
+
+PYTHON_TO_JSON_TYPES = {
+ "str": "string",
+ "int": "integer",
+ "float": "number",
+ "bool": "boolean",
+}
+
+_ORIGIN_MAP: dict[type, Any] = {
+ dict: dict,
+ list: list,
+ tuple: tuple,
+ set: set,
+ collections.abc.Iterable: typing.Iterable,
+ collections.abc.Mapping: typing.Mapping,
+ collections.abc.Sequence: typing.Sequence,
+ collections.abc.MutableMapping: typing.MutableMapping,
+}
+# Add UnionType mapping for Python 3.10+
+if hasattr(types, "UnionType"):
+ _ORIGIN_MAP[types.UnionType] = Union
+
+
+class FunctionDescription(TypedDict):
+ """Representation of a callable function to send to an LLM."""
+
+ name: str
+ """The name of the function."""
+
+ description: str
+ """A description of the function."""
+
+ parameters: dict
+ """The parameters of the function."""
+
+
+class ToolDescription(TypedDict):
+ """Representation of a callable function to the OpenAI API."""
+
+ type: Literal["function"]
+ """The type of the tool."""
+
+ function: FunctionDescription
+ """The function description."""
+
+
+def _rm_titles(kv: dict, prev_key: str = "") -> dict:
+ """Recursively removes `'title'` fields from a JSON schema dictionary.
+
+ Remove `'title'` fields from the input JSON schema dictionary,
+ except when a `'title'` appears within a property definition under `'properties'`.
+
+ Args:
+ kv: The input JSON schema as a dictionary.
+ prev_key: The key from the parent dictionary, used to identify context.
+
+ Returns:
+ A new dictionary with appropriate `'title'` fields removed.
+ """
+ new_kv = {}
+
+ for k, v in kv.items():
+ if k == "title":
+ # If the value is a nested dict and part of a property under "properties",
+ # preserve the title but continue recursion
+ if isinstance(v, dict) and prev_key == "properties":
+ new_kv[k] = _rm_titles(v, k)
+ else:
+ # Otherwise, remove this "title" key
+ continue
+ elif isinstance(v, dict):
+ # Recurse into nested dictionaries
+ new_kv[k] = _rm_titles(v, k)
+ else:
+ # Leave non-dict values untouched
+ new_kv[k] = v
+
+ return new_kv
+
+
+def _convert_json_schema_to_openai_function(
+ schema: dict,
+ *,
+ name: str | None = None,
+ description: str | None = None,
+ rm_titles: bool = True,
+) -> FunctionDescription:
+ """Converts a Pydantic model to a function description for the OpenAI API.
+
+ Args:
+ schema: The JSON schema to convert.
+ name: The name of the function.
+
+ If not provided, the title of the schema will be used.
+ description: The description of the function.
+
+ If not provided, the description of the schema will be used.
+ rm_titles: Whether to remove titles from the schema.
+
+ Returns:
+ The function description.
+ """
+ schema = dereference_refs(schema)
+ if "definitions" in schema: # pydantic 1
+ schema.pop("definitions", None)
+ if "$defs" in schema: # pydantic 2
+ schema.pop("$defs", None)
+ title = schema.pop("title", "")
+ default_description = schema.pop("description", "")
+ return {
+ "name": name or title,
+ "description": description or default_description,
+ "parameters": _rm_titles(schema) if rm_titles else schema,
+ }
+
+
+def _convert_pydantic_to_openai_function(
+ model: type,
+ *,
+ name: str | None = None,
+ description: str | None = None,
+ rm_titles: bool = True,
+) -> FunctionDescription:
+ """Converts a Pydantic model to a function description for the OpenAI API.
+
+ Args:
+ model: The Pydantic model to convert.
+ name: The name of the function.
+
+ If not provided, the title of the schema will be used.
+ description: The description of the function.
+
+ If not provided, the description of the schema will be used.
+ rm_titles: Whether to remove titles from the schema.
+
+ Raises:
+ TypeError: If the model is not a Pydantic model.
+ TypeError: If the model contains types that cannot be converted to JSON schema.
+
+ Returns:
+ The function description.
+ """
+ try:
+ if hasattr(model, "model_json_schema"):
+ schema = model.model_json_schema() # Pydantic 2
+ elif hasattr(model, "schema"):
+ schema = model.schema() # Pydantic 1
+ else:
+ msg = "Model must be a Pydantic model."
+ raise TypeError(msg)
+ except PydanticInvalidForJsonSchema as e:
+ model_name = getattr(model, "__name__", str(model))
+ msg = (
+ f"Failed to generate JSON schema for '{model_name}': {e}\n\n"
+ "Tool argument schemas must be JSON-serializable. If your schema includes "
+ "custom Python classes, consider:\n"
+ " 1. Converting them to Pydantic models with JSON-compatible fields\n"
+ " 2. Using primitive types (str, int, float, bool, list, dict) instead\n"
+ " 3. Passing the data as serialized JSON strings\n\n"
+ )
+ raise PydanticInvalidForJsonSchema(msg) from e
+ return _convert_json_schema_to_openai_function(
+ schema, name=name, description=description, rm_titles=rm_titles
+ )
+
+
+def _get_python_function_name(function: Callable) -> str:
+ """Get the name of a Python function."""
+ return function.__name__
+
+
+def _convert_python_function_to_openai_function(
+ function: Callable,
+) -> FunctionDescription:
+ """Convert a Python function to an OpenAI function-calling API compatible dict.
+
+ Assumes the Python function has type hints and a docstring with a description. If
+ the docstring has Google Python style argument descriptions, these will be included
+ as well.
+
+ Args:
+ function: The Python function to convert.
+
+ Returns:
+ The OpenAI function description.
+ """
+ func_name = _get_python_function_name(function)
+ model = langchain_core.tools.base.create_schema_from_function(
+ func_name,
+ function,
+ filter_args=(),
+ parse_docstring=True,
+ error_on_invalid_docstring=False,
+ include_injected=False,
+ )
+ return _convert_pydantic_to_openai_function(
+ model,
+ name=func_name,
+ description=model.__doc__,
+ )
+
+
+def _convert_typed_dict_to_openai_function(typed_dict: type) -> FunctionDescription:
+ visited: dict = {}
+
+ model = cast(
+ "type[BaseModel]",
+ _convert_any_typed_dicts_to_pydantic(typed_dict, visited=visited),
+ )
+ return _convert_pydantic_to_openai_function(model)
+
+
+_MAX_TYPED_DICT_RECURSION = 25
+
+
+def _convert_any_typed_dicts_to_pydantic(
+ type_: type,
+ *,
+ visited: dict[type, type],
+ depth: int = 0,
+) -> type:
+ if type_ in visited:
+ return visited[type_]
+ if depth >= _MAX_TYPED_DICT_RECURSION:
+ return type_
+ if is_typeddict(type_):
+ typed_dict = type_
+ docstring = inspect.getdoc(typed_dict)
+ # Use get_type_hints to properly resolve forward references and
+ # string annotations in Python 3.14+ (PEP 649 deferred annotations).
+ # include_extras=True preserves Annotated metadata.
+ try:
+ annotations_ = get_type_hints(typed_dict, include_extras=True)
+ except Exception:
+ # Fallback for edge cases where get_type_hints might fail
+ annotations_ = typed_dict.__annotations__
+ description, arg_descriptions = _parse_google_docstring(
+ docstring, list(annotations_)
+ )
+ fields: dict = {}
+ for arg, arg_type in annotations_.items():
+ if get_origin(arg_type) in {Annotated, typing_extensions.Annotated}:
+ annotated_args = get_args(arg_type)
+ new_arg_type = _convert_any_typed_dicts_to_pydantic(
+ annotated_args[0], depth=depth + 1, visited=visited
+ )
+ field_kwargs = dict(
+ zip(("default", "description"), annotated_args[1:], strict=False)
+ )
+ if (field_desc := field_kwargs.get("description")) and not isinstance(
+ field_desc, str
+ ):
+ msg = (
+ f"Invalid annotation for field {arg}. Third argument to "
+ f"Annotated must be a string description, received value of "
+ f"type {type(field_desc)}."
+ )
+ raise ValueError(msg)
+ if arg_desc := arg_descriptions.get(arg):
+ field_kwargs["description"] = arg_desc
+ fields[arg] = (new_arg_type, Field_v1(**field_kwargs))
+ else:
+ new_arg_type = _convert_any_typed_dicts_to_pydantic(
+ arg_type, depth=depth + 1, visited=visited
+ )
+ field_kwargs = {"default": ...}
+ if arg_desc := arg_descriptions.get(arg):
+ field_kwargs["description"] = arg_desc
+ fields[arg] = (new_arg_type, Field_v1(**field_kwargs))
+ model = cast(
+ "type[BaseModelV1]", create_model_v1(typed_dict.__name__, **fields)
+ )
+ model.__doc__ = description
+ visited[typed_dict] = model
+ return model
+ if (origin := get_origin(type_)) and (type_args := get_args(type_)):
+ subscriptable_origin = _py_38_safe_origin(origin)
+ type_args = tuple(
+ _convert_any_typed_dicts_to_pydantic(arg, depth=depth + 1, visited=visited)
+ for arg in type_args
+ )
+ return cast("type", subscriptable_origin[type_args]) # type: ignore[index]
+ return type_
+
+
+def _format_tool_to_openai_function(tool: BaseTool) -> FunctionDescription:
+ """Format tool into the OpenAI function API.
+
+ Args:
+ tool: The tool to format.
+
+ Raises:
+ ValueError: If the tool call schema is not supported.
+
+ Returns:
+ The function description.
+ """
+ is_simple_oai_tool = (
+ isinstance(tool, langchain_core.tools.simple.Tool) and not tool.args_schema
+ )
+ if tool.tool_call_schema and not is_simple_oai_tool:
+ if isinstance(tool.tool_call_schema, dict):
+ return _convert_json_schema_to_openai_function(
+ tool.tool_call_schema, name=tool.name, description=tool.description
+ )
+ if issubclass(tool.tool_call_schema, (BaseModel, BaseModelV1)):
+ return _convert_pydantic_to_openai_function(
+ tool.tool_call_schema, name=tool.name, description=tool.description
+ )
+ error_msg = (
+ f"Unsupported tool call schema: {tool.tool_call_schema}. "
+ "Tool call schema must be a JSON schema dict or a Pydantic model."
+ )
+ raise ValueError(error_msg)
+ return {
+ "name": tool.name,
+ "description": tool.description,
+ "parameters": {
+ # This is a hack to get around the fact that some tools
+ # do not expose an args_schema, and expect an argument
+ # which is a string.
+ # And Open AI does not support an array type for the
+ # parameters.
+ "properties": {
+ "__arg1": {"title": "__arg1", "type": "string"},
+ },
+ "required": ["__arg1"],
+ "type": "object",
+ },
+ }
+
+
+def convert_to_openai_function(
+ function: Mapping[str, Any] | type | Callable | BaseTool,
+ *,
+ strict: bool | None = None,
+) -> dict[str, Any]:
+ """Convert a raw function/class to an OpenAI function.
+
+ Args:
+ function: A dictionary, Pydantic `BaseModel` class, `TypedDict` class, a
+ LangChain `Tool` object, or a Python function.
+
+ If a dictionary is passed in, it is assumed to already be a valid OpenAI
+ function, a JSON schema with top-level `title` key specified, an Anthropic
+ format tool, or an Amazon Bedrock Converse format tool.
+ strict: If `True`, model output is guaranteed to exactly match the JSON Schema
+ provided in the function definition.
+
+ If `None`, `strict` argument will not be included in function definition.
+
+ Returns:
+ A dict version of the passed in function which is compatible with the OpenAI
+ function-calling API.
+
+ Raises:
+ ValueError: If function is not in a supported format.
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.16"
+
+ `description` and `parameters` keys are now optional. Only `name` is
+ required and guaranteed to be part of the output.
+ """
+ # an Anthropic format tool
+ if isinstance(function, dict) and all(
+ k in function for k in ("name", "input_schema")
+ ):
+ oai_function = {
+ "name": function["name"],
+ "parameters": function["input_schema"],
+ }
+ if "description" in function:
+ oai_function["description"] = function["description"]
+ # an Amazon Bedrock Converse format tool
+ elif isinstance(function, dict) and "toolSpec" in function:
+ oai_function = {
+ "name": function["toolSpec"]["name"],
+ "parameters": function["toolSpec"]["inputSchema"]["json"],
+ }
+ if "description" in function["toolSpec"]:
+ oai_function["description"] = function["toolSpec"]["description"]
+ # already in OpenAI function format
+ elif isinstance(function, dict) and "name" in function:
+ oai_function = {
+ k: v
+ for k, v in function.items()
+ if k in {"name", "description", "parameters", "strict"}
+ }
+ # a JSON schema with title and description
+ elif isinstance(function, dict) and "title" in function:
+ function_copy = function.copy()
+ oai_function = {"name": function_copy.pop("title")}
+ if "description" in function_copy:
+ oai_function["description"] = function_copy.pop("description")
+ if function_copy and "properties" in function_copy:
+ oai_function["parameters"] = function_copy
+ elif isinstance(function, type) and is_basemodel_subclass(function):
+ oai_function = cast("dict", _convert_pydantic_to_openai_function(function))
+ elif is_typeddict(function):
+ oai_function = cast(
+ "dict", _convert_typed_dict_to_openai_function(cast("type", function))
+ )
+ elif isinstance(function, langchain_core.tools.base.BaseTool):
+ oai_function = cast("dict", _format_tool_to_openai_function(function))
+ elif callable(function):
+ oai_function = cast(
+ "dict", _convert_python_function_to_openai_function(function)
+ )
+ else:
+ if isinstance(function, dict) and (
+ "type" in function or "properties" in function
+ ):
+ msg = (
+ f"Unsupported function\n\n{function}\n\nTo use a JSON schema as a "
+ "function, it must have a top-level 'title' key to be used as the "
+ "function name."
+ )
+ raise ValueError(msg)
+ msg = (
+ f"Unsupported function\n\n{function}\n\nFunctions must be passed in"
+ " as Dict, pydantic.BaseModel, or Callable. If they're a dict they must"
+ " either be in OpenAI function format or valid JSON schema with top-level"
+ " 'title' key."
+ )
+ raise ValueError(msg)
+
+ if strict is not None:
+ if "strict" in oai_function and oai_function["strict"] != strict:
+ msg = (
+ f"Tool/function already has a 'strict' key with value "
+ f"{oai_function['strict']} which is different from the explicit "
+ f"`strict` arg received {strict=}."
+ )
+ raise ValueError(msg)
+ oai_function["strict"] = strict
+ if strict:
+ # All fields must be `required`
+ parameters = oai_function.get("parameters")
+ if isinstance(parameters, dict):
+ fields = parameters.get("properties")
+ if isinstance(fields, dict) and fields:
+ parameters = dict(parameters)
+ parameters["required"] = list(fields.keys())
+ oai_function["parameters"] = parameters
+
+ # As of 08/06/24, OpenAI requires that additionalProperties be supplied and
+ # set to False if strict is True.
+ # All properties layer needs 'additionalProperties=False'
+ oai_function["parameters"] = _recursive_set_additional_properties_false(
+ oai_function["parameters"]
+ )
+ return oai_function
+
+
+# List of well known tools supported by OpenAI's chat models or responses API.
+# These tools are not expected to be supported by other chat model providers
+# that conform to the OpenAI function-calling API.
+_WellKnownOpenAITools = (
+ "function",
+ "file_search",
+ "computer",
+ "computer_use_preview",
+ "code_interpreter",
+ "mcp",
+ "image_generation",
+ "web_search_preview",
+ "web_search",
+ "tool_search",
+ "namespace",
+)
+
+
+def convert_to_openai_tool(
+ tool: Mapping[str, Any] | type[BaseModel] | Callable | BaseTool,
+ *,
+ strict: bool | None = None,
+) -> dict[str, Any]:
+ """Convert a tool-like object to an OpenAI tool schema.
+
+ [OpenAI tool schema reference](https://platform.openai.com/docs/api-reference/chat/create#chat-create-tools)
+
+ Args:
+ tool: Either a dictionary, a `pydantic.BaseModel` class, Python function, or
+ `BaseTool`.
+
+ If a dictionary is passed in, it is assumed to already be a valid OpenAI
+ function, a JSON schema with top-level `title` key specified, an Anthropic
+ format tool, or an Amazon Bedrock Converse format tool.
+ strict: If `True`, model output is guaranteed to exactly match the JSON Schema
+ provided in the function definition.
+
+ If `None`, `strict` argument will not be included in tool definition.
+
+ Returns:
+ A dict version of the passed in tool which is compatible with the OpenAI
+ tool-calling API.
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.16"
+
+ `description` and `parameters` keys are now optional. Only `name` is
+ required and guaranteed to be part of the output.
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.44"
+
+ Return OpenAI Responses API-style tools unchanged. This includes
+ any dict with `"type"` in `"file_search"`, `"function"`,
+ `"computer_use_preview"`, `"web_search_preview"`.
+
+ !!! warning "Behavior changed in `langchain-core` 0.3.63"
+
+ Added support for OpenAI's image generation built-in tool.
+ """
+ # Import locally to prevent circular import
+ from langchain_core.tools import Tool # noqa: PLC0415
+
+ if isinstance(tool, dict):
+ if tool.get("type") in _WellKnownOpenAITools:
+ return tool
+ # As of 03.12.25 can be "web_search_preview" or "web_search_preview_2025_03_11"
+ if (tool.get("type") or "").startswith("web_search_preview"):
+ return tool
+ if isinstance(tool, Tool) and (tool.metadata or {}).get("type") == "custom_tool":
+ oai_tool = {
+ "type": "custom",
+ "name": tool.name,
+ "description": tool.description,
+ }
+ if tool.metadata is not None and "format" in tool.metadata:
+ oai_tool["format"] = tool.metadata["format"]
+ return oai_tool
+ oai_function = convert_to_openai_function(tool, strict=strict)
+ return {"type": "function", "function": oai_function}
+
+
+def convert_to_json_schema(
+ schema: dict[str, Any] | type[BaseModel] | Callable | BaseTool,
+ *,
+ strict: bool | None = None,
+) -> dict[str, Any]:
+ """Convert a schema representation to a JSON schema.
+
+ Args:
+ schema: The schema to convert.
+ strict: If `True`, model output is guaranteed to exactly match the JSON Schema
+ provided in the function definition.
+
+ If `None`, `strict` argument will not be included in function definition.
+
+ Raises:
+ ValueError: If the input is not a valid OpenAI-format tool.
+
+ Returns:
+ A JSON schema representation of the input schema.
+ """
+ openai_tool = convert_to_openai_tool(schema, strict=strict)
+ if (
+ not isinstance(openai_tool, dict)
+ or "function" not in openai_tool
+ or "name" not in openai_tool["function"]
+ ):
+ error_message = "Input must be a valid OpenAI-format tool."
+ raise ValueError(error_message)
+
+ openai_function = openai_tool["function"]
+ json_schema = {}
+ json_schema["title"] = openai_function["name"]
+
+ if "description" in openai_function:
+ json_schema["description"] = openai_function["description"]
+
+ if "parameters" in openai_function:
+ parameters = openai_function["parameters"].copy()
+ json_schema.update(parameters)
+
+ return json_schema
+
+
+@beta()
+def tool_example_to_messages(
+ input: str,
+ tool_calls: list[BaseModel],
+ tool_outputs: list[str] | None = None,
+ *,
+ ai_response: str | None = None,
+) -> list[BaseMessage]:
+ """Convert an example into a list of messages that can be fed into an LLM.
+
+ This code is an adapter that converts a single example to a list of messages
+ that can be fed into a chat model.
+
+ The list of messages per example by default corresponds to:
+
+ 1. `HumanMessage`: contains the content from which content should be extracted.
+ 2. `AIMessage`: contains the extracted information from the model
+ 3. `ToolMessage`: contains confirmation to the model that the model requested a
+ tool correctly.
+
+ If `ai_response` is specified, there will be a final `AIMessage` with that
+ response.
+
+ The `ToolMessage` is required because some chat models are hyper-optimized for
+ agents rather than for an extraction use case.
+
+ Args:
+ input: The user input
+ tool_calls: Tool calls represented as Pydantic BaseModels
+ tool_outputs: Tool call outputs.
+
+ Does not need to be provided.
+
+ If not provided, a placeholder value will be inserted.
+ ai_response: If provided, content for a final `AIMessage`.
+
+ Returns:
+ A list of messages
+
+ Examples:
+ ```python
+ from typing import Optional
+ from pydantic import BaseModel, Field
+ from langchain_openai import ChatOpenAI
+
+
+ class Person(BaseModel):
+ '''Information about a person.'''
+
+ name: str | None = Field(..., description="The name of the person")
+ hair_color: str | None = Field(
+ ..., description="The color of the person's hair if known"
+ )
+ height_in_meters: str | None = Field(..., description="Height in METERS")
+
+
+ examples = [
+ (
+ "The ocean is vast and blue. It's more than 20,000 feet deep.",
+ Person(name=None, height_in_meters=None, hair_color=None),
+ ),
+ (
+ "Fiona traveled far from France to Spain.",
+ Person(name="Fiona", height_in_meters=None, hair_color=None),
+ ),
+ ]
+
+
+ messages = []
+
+ for txt, tool_call in examples:
+ messages.extend(tool_example_to_messages(txt, [tool_call]))
+ ```
+ """
+ messages: list[BaseMessage] = [HumanMessage(content=input)]
+
+ openai_tool_calls = [
+ {
+ "id": str(uuid.uuid4()),
+ "type": "function",
+ "function": {
+ # The name of the function right now corresponds to the name
+ # of the Pydantic model. This is implicit in the API right now,
+ # and will be improved over time.
+ "name": tool_call.__class__.__name__,
+ "arguments": tool_call.model_dump_json(),
+ },
+ }
+ for tool_call in tool_calls
+ ]
+
+ messages.append(
+ AIMessage(content="", additional_kwargs={"tool_calls": openai_tool_calls})
+ )
+ tool_outputs = tool_outputs or ["You have correctly called this tool."] * len(
+ openai_tool_calls
+ )
+ for output, tool_call_dict in zip(tool_outputs, openai_tool_calls, strict=False):
+ messages.append(ToolMessage(content=output, tool_call_id=tool_call_dict["id"]))
+
+ if ai_response:
+ messages.append(AIMessage(content=ai_response))
+ return messages
+
+
+_MIN_DOCSTRING_BLOCKS = 2
+
+
+def _parse_google_docstring(
+ docstring: str | None,
+ args: list[str],
+ *,
+ error_on_invalid_docstring: bool = False,
+) -> tuple[str, dict]:
+ """Parse the function and argument descriptions from the docstring of a function.
+
+ Assumes the function docstring follows Google Python style guide.
+
+ Args:
+ docstring: The docstring to parse.
+ args: The list of argument names to extract descriptions for.
+ error_on_invalid_docstring: Whether to raise an error if the docstring is
+ invalid.
+
+ Returns:
+ A tuple of the function description and a dictionary of argument descriptions.
+ """
+ if docstring:
+ docstring_blocks = docstring.split("\n\n")
+ if error_on_invalid_docstring:
+ filtered_annotations = {
+ arg
+ for arg in args
+ if arg not in {"run_manager", "callbacks", "runtime", "return"}
+ }
+ if filtered_annotations and (
+ len(docstring_blocks) < _MIN_DOCSTRING_BLOCKS
+ or not any(block.startswith("Args:") for block in docstring_blocks[1:])
+ ):
+ msg = "Found invalid Google-Style docstring."
+ raise ValueError(msg)
+ descriptors = []
+ args_block = None
+ past_descriptors = False
+ for block in docstring_blocks:
+ if block.startswith("Args:"):
+ args_block = block
+ break
+ if block.startswith(("Returns:", "Example:")):
+ # Don't break in case Args come after
+ past_descriptors = True
+ elif not past_descriptors:
+ descriptors.append(block)
+ else:
+ continue
+ description = " ".join(descriptors).strip()
+ else:
+ if error_on_invalid_docstring:
+ msg = "Found invalid Google-Style docstring."
+ raise ValueError(msg)
+ description = ""
+ args_block = None
+ arg_descriptions = {}
+ if args_block:
+ arg = None
+ for line in args_block.split("\n")[1:]:
+ if ":" in line:
+ arg, desc = line.split(":", maxsplit=1)
+ arg = arg.strip()
+ arg_name, _, annotations_ = arg.partition(" ")
+ if annotations_.startswith("(") and annotations_.endswith(")"):
+ arg = arg_name
+ arg_descriptions[arg] = desc.strip()
+ elif arg:
+ arg_descriptions[arg] += " " + line.strip()
+ return description, arg_descriptions
+
+
+def _py_38_safe_origin(origin: type) -> type:
+ return cast("type", _ORIGIN_MAP.get(origin, origin))
+
+
+def _recursive_set_additional_properties_false(
+ schema: dict[str, Any],
+) -> dict[str, Any]:
+ if isinstance(schema, dict):
+ # Check if 'required' is a key at the current level or if the schema is empty,
+ # in which case additionalProperties still needs to be specified.
+ if (
+ "required" in schema
+ or ("properties" in schema and not schema["properties"])
+ # Since Pydantic 2.11, it will always add `additionalProperties: True`
+ # for arbitrary dictionary schemas
+ # See: https://pydantic.dev/articles/pydantic-v2-11-release#changes
+ # If it is already set to True, we need override it to False
+ or "additionalProperties" in schema
+ ):
+ schema["additionalProperties"] = False
+
+ # Recursively check 'properties' and 'items' if they exist
+ if "anyOf" in schema:
+ for sub_schema in schema["anyOf"]:
+ _recursive_set_additional_properties_false(sub_schema)
+ if "properties" in schema:
+ for sub_schema in schema["properties"].values():
+ _recursive_set_additional_properties_false(sub_schema)
+ if "items" in schema:
+ _recursive_set_additional_properties_false(schema["items"])
+
+ return schema
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/html.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/html.py
new file mode 100644
index 0000000000000000000000000000000000000000..4798b02ce78388c371fca0c59e5b30154e140397
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/html.py
@@ -0,0 +1,132 @@
+"""Utilities for working with HTML."""
+
+import logging
+import re
+from collections.abc import Sequence
+from urllib.parse import urljoin, urlparse
+
+logger = logging.getLogger(__name__)
+
+PREFIXES_TO_IGNORE = ("javascript:", "mailto:", "#")
+
+SUFFIXES_TO_IGNORE = (
+ ".css",
+ ".js",
+ ".ico",
+ ".png",
+ ".jpg",
+ ".jpeg",
+ ".gif",
+ ".svg",
+ ".csv",
+ ".bz2",
+ ".zip",
+ ".epub",
+ ".webp",
+ ".pdf",
+ ".docx",
+ ".xlsx",
+ ".pptx",
+ ".pptm",
+)
+
+SUFFIXES_TO_IGNORE_REGEX = (
+ "(?!" + "|".join([re.escape(s) + r"[\#'\"]" for s in SUFFIXES_TO_IGNORE]) + ")"
+)
+
+PREFIXES_TO_IGNORE_REGEX = (
+ "(?!" + "|".join([re.escape(s) for s in PREFIXES_TO_IGNORE]) + ")"
+)
+
+DEFAULT_LINK_REGEX = (
+ rf"href=[\"']{PREFIXES_TO_IGNORE_REGEX}((?:{SUFFIXES_TO_IGNORE_REGEX}.)*?)[\#'\"]"
+)
+
+
+def find_all_links(
+ raw_html: str, *, pattern: str | re.Pattern | None = None
+) -> list[str]:
+ """Extract all links from a raw HTML string.
+
+ Args:
+ raw_html: original HTML.
+ pattern: Regex to use for extracting links from raw HTML.
+
+ Returns:
+ A list of all links found in the HTML.
+ """
+ pattern = pattern or DEFAULT_LINK_REGEX
+ return list(set(re.findall(pattern, raw_html)))
+
+
+def extract_sub_links(
+ raw_html: str,
+ url: str,
+ *,
+ base_url: str | None = None,
+ pattern: str | re.Pattern | None = None,
+ prevent_outside: bool = True,
+ exclude_prefixes: Sequence[str] = (),
+ continue_on_failure: bool = False,
+) -> list[str]:
+ """Extract all links from a raw HTML string and convert into absolute paths.
+
+ Args:
+ raw_html: Original HTML.
+ url: The url of the HTML.
+ base_url: the base URL to check for outside links against.
+ pattern: Regex to use for extracting links from raw HTML.
+ prevent_outside: If `True`, ignore external links which are not children
+ of the base URL.
+ exclude_prefixes: Exclude any URLs that start with one of these prefixes.
+ continue_on_failure: If `True`, continue if parsing a specific link raises an
+ exception. Otherwise, raise the exception.
+
+ Returns:
+ A list of absolute paths to sub links.
+ """
+ base_url_to_use = base_url if base_url is not None else url
+ parsed_base_url = urlparse(base_url_to_use)
+ parsed_url = urlparse(url)
+ all_links = find_all_links(raw_html, pattern=pattern)
+ absolute_paths = set()
+ for link in all_links:
+ try:
+ parsed_link = urlparse(link)
+ # Some may be absolute links like https://to/path
+ if parsed_link.scheme in {"http", "https"}:
+ absolute_path = link
+ # Some may have omitted the protocol like //to/path
+ elif link.startswith("//"):
+ absolute_path = f"{parsed_url.scheme}:{link}"
+ else:
+ absolute_path = urljoin(url, parsed_link.path)
+ if parsed_link.query:
+ absolute_path += f"?{parsed_link.query}"
+ absolute_paths.add(absolute_path)
+ except Exception as e:
+ if continue_on_failure:
+ logger.warning(
+ "Unable to load link %s. Raised exception:\n\n%s", link, e
+ )
+ continue
+ raise
+
+ results = []
+ for path in absolute_paths:
+ if any(path.startswith(exclude_prefix) for exclude_prefix in exclude_prefixes):
+ continue
+
+ if prevent_outside:
+ parsed_path = urlparse(path)
+
+ if parsed_base_url.netloc != parsed_path.netloc:
+ continue
+
+ # Will take care of verifying rest of path after netloc
+ # if it's more specific
+ if not path.startswith(base_url_to_use):
+ continue
+
+ results.append(path)
+ return results
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/image.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/image.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f2cce4ee1f4ea152f7e282ef674f3690d476555
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/image.py
@@ -0,0 +1,15 @@
+"""Utilities for image processing."""
+
+from typing import Any
+
+
+def __getattr__(name: str) -> Any:
+ if name in {"encode_image", "image_to_data_url"}:
+ msg = (
+ f"'{name}' has been removed for security reasons.\n\n"
+ f"Usage of this utility in environments with user-input paths is a "
+ f"security vulnerability. Out of an abundance of caution, the utility "
+ f"has been removed to prevent possible misuse."
+ )
+ raise ValueError(msg)
+ raise AttributeError(name)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/input.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/input.py
new file mode 100644
index 0000000000000000000000000000000000000000..d97d4006d33b18db65ad42a07c9722590898cb3e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/input.py
@@ -0,0 +1,82 @@
+"""Handle chained inputs."""
+
+from typing import TextIO
+
+_TEXT_COLOR_MAPPING = {
+ "blue": "36;1",
+ "yellow": "33;1",
+ "pink": "38;5;200",
+ "green": "32;1",
+ "red": "31;1",
+}
+
+
+def get_color_mapping(
+ items: list[str], excluded_colors: list | None = None
+) -> dict[str, str]:
+ """Get mapping for items to a support color.
+
+ Args:
+ items: The items to map to colors.
+ excluded_colors: The colors to exclude.
+
+ Returns:
+ The mapping of items to colors.
+
+ Raises:
+ ValueError: If no colors are available after applying exclusions.
+ """
+ colors = list(_TEXT_COLOR_MAPPING.keys())
+ if excluded_colors is not None:
+ colors = [c for c in colors if c not in excluded_colors]
+ if not colors:
+ msg = "No colors available after applying exclusions."
+ raise ValueError(msg)
+ return {item: colors[i % len(colors)] for i, item in enumerate(items)}
+
+
+def get_colored_text(text: str, color: str) -> str:
+ """Get colored text.
+
+ Args:
+ text: The text to color.
+ color: The color to use.
+
+ Returns:
+ The colored text.
+ """
+ color_str = _TEXT_COLOR_MAPPING[color]
+ return f"\u001b[{color_str}m\033[1;3m{text}\u001b[0m"
+
+
+def get_bolded_text(text: str) -> str:
+ """Get bolded text.
+
+ Args:
+ text: The text to bold.
+
+ Returns:
+ The bolded text.
+ """
+ return f"\033[1m{text}\033[0m"
+
+
+def print_text(
+ text: str, color: str | None = None, end: str = "", file: TextIO | None = None
+) -> None:
+ """Print text with highlighting and no end characters.
+
+ If a color is provided, the text will be printed in that color.
+
+ If a file is provided, the text will be written to that file.
+
+ Args:
+ text: The text to print.
+ color: The color to use.
+ end: The end character to use.
+ file: The file to write to.
+ """
+ text_to_print = get_colored_text(text, color) if color else text
+ print(text_to_print, end=end, file=file)
+ if file:
+ file.flush() # ensure all printed content are written to file
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/interactive_env.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/interactive_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0e7ea8b202af472e81b97ff8e44355ee21c5f96
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/interactive_env.py
@@ -0,0 +1,12 @@
+"""Utilities for working with interactive environments."""
+
+import sys
+
+
+def is_interactive_env() -> bool:
+ """Determine if running within IPython or Jupyter.
+
+ Returns:
+ `True` if running in an interactive environment, `False` otherwise.
+ """
+ return hasattr(sys, "ps2")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/iter.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/iter.py
new file mode 100644
index 0000000000000000000000000000000000000000..b24c5f213ad62160bdd9ec04c878c68331b12e2e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/iter.py
@@ -0,0 +1,223 @@
+"""Utilities for working with iterators."""
+
+from collections import deque
+from collections.abc import Generator, Iterable, Iterator
+from contextlib import AbstractContextManager
+from itertools import islice
+from types import TracebackType
+from typing import (
+ Any,
+ Generic,
+ Literal,
+ TypeVar,
+ overload,
+)
+
+T = TypeVar("T")
+
+
+class NoLock:
+ """Dummy lock that provides the proper interface but no protection."""
+
+ def __enter__(self) -> None:
+ """Do nothing."""
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> Literal[False]:
+ """Return False (exception not suppressed)."""
+ return False
+
+
+def tee_peer(
+ iterator: Iterator[T],
+ # the buffer specific to this peer
+ buffer: deque[T],
+ # the buffers of all peers, including our own
+ peers: list[deque[T]],
+ lock: AbstractContextManager[Any],
+) -> Generator[T, None, None]:
+ """An individual iterator of a `.tee`.
+
+ This function is a generator that yields items from the shared iterator `iterator`.
+ It buffers items until the least advanced iterator has yielded them as well. The
+ buffer is shared with all other peers.
+
+ Args:
+ iterator: The shared iterator.
+ buffer: The buffer for this peer.
+ peers: The buffers of all peers.
+ lock: The lock to synchronise access to the shared buffers.
+
+ Yields:
+ The next item from the shared iterator.
+ """
+ try:
+ while True:
+ if not buffer:
+ with lock:
+ # Another peer produced an item while we were waiting for the lock.
+ # Proceed with the next loop iteration to yield the item.
+ if buffer:
+ continue
+ try:
+ item = next(iterator)
+ except StopIteration:
+ break
+ else:
+ # Append to all buffers, including our own. We'll fetch our
+ # item from the buffer again, instead of yielding it directly.
+ # This ensures the proper item ordering if any of our peers
+ # are fetching items concurrently. They may have buffered their
+ # item already.
+ for peer_buffer in peers:
+ peer_buffer.append(item)
+ yield buffer.popleft()
+ finally:
+ with lock:
+ # this peer is done - remove its buffer
+ for idx, peer_buffer in enumerate(peers): # pragma: no branch
+ if peer_buffer is buffer:
+ peers.pop(idx)
+ break
+ # if we are the last peer, try and close the iterator
+ if not peers and hasattr(iterator, "close"):
+ iterator.close()
+
+
+class Tee(Generic[T]):
+ """Create `n` separate asynchronous iterators over `iterable`.
+
+ This splits a single `iterable` into multiple iterators, each providing the same
+ items in the same order.
+
+ All child iterators may advance separately but share the same items from `iterable`
+ -- when the most advanced iterator retrieves an item, it is buffered until the least
+ advanced iterator has yielded it as well. A `tee` works lazily and can handle an
+ infinite `iterable`, provided that all iterators advance.
+
+ ```python
+ async def derivative(sensor_data):
+ previous, current = a.tee(sensor_data, n=2)
+ await a.anext(previous) # advance one iterator
+ return a.map(operator.sub, previous, current)
+ ```
+
+ Unlike `itertools.tee`, `.tee` returns a custom type instead of a `tuple`. Like a
+ tuple, it can be indexed, iterated and unpacked to get the child iterators. In
+ addition, its `.tee.aclose` method immediately closes all children, and it can be
+ used in an `async with` context for the same effect.
+
+ If `iterable` is an iterator and read elsewhere, `tee` will *not* provide these
+ items. Also, `tee` must internally buffer each item until the last iterator has
+ yielded it; if the most and least advanced iterator differ by most data, using a
+ `list` is more efficient (but not lazy).
+
+ If the underlying iterable is concurrency safe (`anext` may be awaited concurrently)
+ the resulting iterators are concurrency safe as well. Otherwise, the iterators are
+ safe if there is only ever one single "most advanced" iterator. To enforce
+ sequential use of `anext`, provide a `lock`
+
+ - e.g., an `asyncio.Lock` instance in an `asyncio` application - and access is
+ automatically synchronised.
+
+ """
+
+ def __init__(
+ self,
+ iterable: Iterator[T],
+ n: int = 2,
+ *,
+ lock: AbstractContextManager[Any] | None = None,
+ ):
+ """Create a `tee`.
+
+ Args:
+ iterable: The iterable to split.
+ n: The number of iterators to create.
+ lock: The lock to synchronise access to the shared buffers.
+
+ """
+ self._iterator = iter(iterable)
+ self._buffers: list[deque[T]] = [deque() for _ in range(n)]
+ self._children = tuple(
+ tee_peer(
+ iterator=self._iterator,
+ buffer=buffer,
+ peers=self._buffers,
+ lock=lock if lock is not None else NoLock(),
+ )
+ for buffer in self._buffers
+ )
+
+ def __len__(self) -> int:
+ """Return the number of child iterators."""
+ return len(self._children)
+
+ @overload
+ def __getitem__(self, item: int) -> Iterator[T]: ...
+
+ @overload
+ def __getitem__(self, item: slice) -> tuple[Iterator[T], ...]: ...
+
+ def __getitem__(self, item: int | slice) -> Iterator[T] | tuple[Iterator[T], ...]:
+ """Return the child iterator(s) at the given index or slice."""
+ return self._children[item]
+
+ def __iter__(self) -> Iterator[Iterator[T]]:
+ """Return an iterator over the child iterators.
+
+ Yields:
+ The child iterators.
+ """
+ yield from self._children
+
+ def __enter__(self) -> "Tee[T]":
+ """Return `Tee` instance."""
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> Literal[False]:
+ """Close all child iterators.
+
+ Returns:
+ `False` (exception not suppressed).
+ """
+ self.close()
+ return False
+
+ def close(self) -> None:
+ """Close all child iterators."""
+ for child in self._children:
+ child.close()
+
+
+# Why this is needed https://stackoverflow.com/a/44638570
+safetee = Tee
+
+
+def batch_iterate(size: int | None, iterable: Iterable[T]) -> Iterator[list[T]]:
+ """Utility batching function.
+
+ Args:
+ size: The size of the batch.
+
+ If `None`, returns a single batch.
+ iterable: The iterable to batch.
+
+ Yields:
+ The batches of the iterable.
+ """
+ it = iter(iterable)
+ while True:
+ chunk = list(islice(it, size))
+ if not chunk:
+ return
+ yield chunk
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/json.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/json.py
new file mode 100644
index 0000000000000000000000000000000000000000..a836ffc4e61ef8e6723fcb9147a2305d0d7a5c63
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/json.py
@@ -0,0 +1,228 @@
+"""Utilities for JSON."""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import TYPE_CHECKING, Any
+
+from langchain_core.exceptions import OutputParserException
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+
+def _replace_new_line(match: re.Match[str]) -> str:
+ """Replace newline characters in a regex match with escaped sequences.
+
+ Args:
+ match: Regex match object containing the string to process.
+
+ Returns:
+ String with newlines, carriage returns, tabs, and quotes properly escaped.
+ """
+ value = match.group(2)
+ value = re.sub(r"\n", r"\\n", value)
+ value = re.sub(r"\r", r"\\r", value)
+ value = re.sub(r"\t", r"\\t", value)
+ value = re.sub(r'(? str:
+ r"""Custom parser for multiline strings.
+
+ The LLM response for `action_input` may be a multiline string containing unescaped
+ newlines, tabs or quotes. This function replaces those characters with their escaped
+ counterparts. (newlines in JSON must be double-escaped: `\\n`).
+
+ Returns:
+ The modified string with escaped newlines, tabs and quotes.
+ """
+ if isinstance(multiline_string, (bytes, bytearray)):
+ multiline_string = multiline_string.decode()
+
+ return re.sub(
+ r'("action_input"\:\s*")(.*?)(")',
+ _replace_new_line,
+ multiline_string,
+ flags=re.DOTALL,
+ )
+
+
+# Adapted from https://github.com/KillianLucas/open-interpreter/blob/5b6080fae1f8c68938a1e4fa8667e3744084ee21/interpreter/utils/parse_partial_json.py
+# MIT License
+
+
+def parse_partial_json(s: str, *, strict: bool = False) -> Any:
+ """Parse a JSON string that may be missing closing braces.
+
+ Args:
+ s: The JSON string to parse.
+ strict: Whether to use strict parsing.
+
+ Returns:
+ The parsed JSON object as a Python dictionary.
+ """
+ # Attempt to parse the string as-is.
+ try:
+ return json.loads(s, strict=strict)
+ except json.JSONDecodeError:
+ pass
+
+ # Initialize variables.
+ new_chars = []
+ stack = []
+ is_inside_string = False
+ escaped = False
+
+ # Process each character in the string one at a time.
+ for char in s:
+ new_char = char
+ if is_inside_string:
+ if char == '"' and not escaped:
+ is_inside_string = False
+ elif char == "\n" and not escaped:
+ new_char = (
+ "\\n" # Replace the newline character with the escape sequence.
+ )
+ elif char == "\\":
+ escaped = not escaped
+ else:
+ escaped = False
+ elif char == '"':
+ is_inside_string = True
+ escaped = False
+ elif char == "{":
+ stack.append("}")
+ elif char == "[":
+ stack.append("]")
+ elif char in {"}", "]"}:
+ if stack and stack[-1] == char:
+ stack.pop()
+ else:
+ # Mismatched closing character; the input is malformed.
+ return None
+
+ # Append the processed character to the new string.
+ new_chars.append(new_char)
+
+ # If we're still inside a string at the end of processing,
+ # we need to close the string.
+ if is_inside_string:
+ if escaped: # Remove unterminated escape character
+ new_chars.pop()
+ new_chars.append('"')
+
+ # Reverse the stack to get the closing characters.
+ stack.reverse()
+
+ # Try to parse mods of string until we succeed or run out of characters.
+ while new_chars:
+ # Close any remaining open structures in the reverse
+ # order that they were opened.
+ # Attempt to parse the modified string as JSON.
+ try:
+ return json.loads("".join(new_chars + stack), strict=strict)
+ except json.JSONDecodeError:
+ # If we still can't parse the string as JSON,
+ # try removing the last character
+ new_chars.pop()
+
+ # If we got here, we ran out of characters to remove
+ # and still couldn't parse the string as JSON, so return the parse error
+ # for the original string.
+ return json.loads(s, strict=strict)
+
+
+_json_markdown_re = re.compile(r"```(json)?(.*)", re.DOTALL)
+
+
+def parse_json_markdown(
+ json_string: str, *, parser: Callable[[str], Any] = parse_partial_json
+) -> Any:
+ """Parse a JSON string from a Markdown string.
+
+ Args:
+ json_string: The Markdown string.
+ parser: The parser to use.
+
+ Returns:
+ The parsed JSON object as a Python dictionary.
+ """
+ try:
+ return _parse_json(json_string, parser=parser)
+ except json.JSONDecodeError:
+ # Try to find JSON string within triple backticks
+ match = _json_markdown_re.search(json_string)
+
+ # If no match found, assume the entire string is a JSON string
+ # Else, use the content within the backticks
+ json_str = json_string if match is None else match.group(2)
+ return _parse_json(json_str, parser=parser)
+
+
+_json_strip_chars = " \n\r\t`"
+
+
+def _parse_json(
+ json_str: str, *, parser: Callable[[str], Any] = parse_partial_json
+) -> Any:
+ """Parse a JSON string, handling special characters and whitespace.
+
+ Strips whitespace, newlines, and backticks from the start and end of the string,
+ then processes special characters before parsing.
+
+ Args:
+ json_str: The JSON string to parse.
+ parser: Optional custom parser function.
+
+ Returns:
+ Parsed JSON object.
+ """
+ # Strip whitespace,newlines,backtick from the start and end
+ json_str = json_str.strip(_json_strip_chars)
+
+ # handle newlines and other special characters inside the returned value
+ json_str = _custom_parser(json_str)
+
+ # Parse the JSON string into a Python dictionary
+ return parser(json_str)
+
+
+def parse_and_check_json_markdown(text: str, expected_keys: list[str]) -> dict:
+ """Parse and check a JSON string from a Markdown string.
+
+ Checks that it contains the expected keys.
+
+ Args:
+ text: The Markdown string.
+ expected_keys: The expected keys in the JSON string.
+
+ Returns:
+ The parsed JSON object as a Python dictionary.
+
+ Raises:
+ OutputParserException: If the JSON string is invalid or does not contain
+ the expected keys.
+ """
+ try:
+ json_obj = parse_json_markdown(text)
+ except json.JSONDecodeError as e:
+ msg = f"Got invalid JSON object. Error: {e}"
+ raise OutputParserException(msg) from e
+ if not isinstance(json_obj, dict):
+ error_message = (
+ f"Expected JSON object (dict), but got: {type(json_obj).__name__}. "
+ )
+ raise OutputParserException(error_message, llm_output=text)
+
+ for key in expected_keys:
+ if key not in json_obj:
+ msg = (
+ f"Got invalid return object. Expected key `{key}` "
+ f"to be present, but got {json_obj}"
+ )
+ raise OutputParserException(msg)
+ return json_obj
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/json_schema.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/json_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1ff1de5fcb19c8552ea6b3d9b64968c59541abb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/json_schema.py
@@ -0,0 +1,273 @@
+"""Utilities for JSON Schema."""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import TYPE_CHECKING, Any, cast
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+
+def _retrieve_ref(path: str, schema: dict) -> list | dict:
+ """Retrieve a referenced object from a JSON schema using a path.
+
+ Resolves JSON schema references (e.g., `'#/definitions/MyType'`) by traversing the
+ schema structure.
+
+ Args:
+ path: Reference path starting with `'#'` (e.g., `'#/definitions/MyType'`).
+ schema: The JSON schema dictionary to search in.
+
+ Returns:
+ A deep copy of the referenced object (dict or list).
+
+ Raises:
+ ValueError: If the path does not start with `'#'`.
+ KeyError: If the reference path is not found in the schema.
+ """
+ components = path.split("/")
+ if components[0] != "#":
+ msg = (
+ "ref paths are expected to be URI fragments, meaning they should start "
+ "with #."
+ )
+ raise ValueError(msg)
+ out: list | dict = schema
+ for component in components[1:]:
+ if component in out:
+ if isinstance(out, list):
+ msg = f"Reference '{path}' not found."
+ raise KeyError(msg)
+ out = out[component]
+ elif component.isdigit():
+ index = int(component)
+ if (isinstance(out, list) and 0 <= index < len(out)) or (
+ isinstance(out, dict) and index in out
+ ):
+ out = out[index]
+ else:
+ msg = f"Reference '{path}' not found."
+ raise KeyError(msg)
+ else:
+ msg = f"Reference '{path}' not found."
+ raise KeyError(msg)
+ return deepcopy(out)
+
+
+def _process_dict_properties(
+ properties: dict[str, Any],
+ full_schema: dict[str, Any],
+ processed_refs: set[str],
+ skip_keys: Sequence[str],
+ *,
+ shallow_refs: bool,
+) -> dict[str, Any]:
+ """Process dictionary properties, recursing into nested structures."""
+ result: dict[str, Any] = {}
+ for key, value in properties.items():
+ if key in skip_keys:
+ # Skip recursion for specified keys, just copy the value as-is
+ result[key] = deepcopy(value)
+ elif isinstance(value, (dict, list)):
+ # Recursively process nested objects and arrays
+ result[key] = _dereference_refs_helper(
+ value, full_schema, processed_refs, skip_keys, shallow_refs=shallow_refs
+ )
+ else:
+ # Copy primitive values directly
+ result[key] = value
+ return result
+
+
+def _dereference_refs_helper(
+ obj: Any,
+ full_schema: dict[str, Any],
+ processed_refs: set[str] | None,
+ skip_keys: Sequence[str],
+ *,
+ shallow_refs: bool,
+) -> Any:
+ """Dereference JSON Schema $ref objects, handling both pure and mixed references.
+
+ This function processes JSON Schema objects containing $ref properties by resolving
+ the references and merging any additional properties. It handles:
+
+ - Pure `$ref` objects: `{"$ref": "#/path/to/definition"}`
+ - Mixed `$ref` objects: `{"$ref": "#/path", "title": "Custom Title", ...}`
+ - Circular references by breaking cycles and preserving non-ref properties
+
+ Args:
+ obj: The object to process (can be dict, list, or primitive)
+ full_schema: The complete schema containing all definitions
+ processed_refs: Set tracking currently processing refs (for cycle detection)
+ skip_keys: Keys under which to skip recursion
+ shallow_refs: If `True`, only break cycles; if `False`, deep-inline all refs
+
+ Returns:
+ The object with `$ref` properties resolved and merged with other properties.
+ """
+ if processed_refs is None:
+ processed_refs = set()
+
+ # Case 1: Object contains a $ref property (pure or mixed with additional properties)
+ if isinstance(obj, dict) and "$ref" in obj:
+ ref_path = obj["$ref"]
+ additional_properties = {
+ key: value for key, value in obj.items() if key != "$ref"
+ }
+
+ # Detect circular reference: if we're already processing this $ref,
+ # return only the additional properties to break the cycle
+ if ref_path in processed_refs:
+ return _process_dict_properties(
+ additional_properties,
+ full_schema,
+ processed_refs,
+ skip_keys,
+ shallow_refs=shallow_refs,
+ )
+
+ # Mark this reference as being processed (for cycle detection)
+ processed_refs.add(ref_path)
+
+ # Fetch and recursively resolve the referenced object
+ referenced_object = deepcopy(_retrieve_ref(ref_path, full_schema))
+ resolved_reference = _dereference_refs_helper(
+ referenced_object,
+ full_schema,
+ processed_refs,
+ skip_keys,
+ shallow_refs=shallow_refs,
+ )
+
+ # Clean up: remove from processing set before returning
+ processed_refs.remove(ref_path)
+
+ # Pure $ref case: no additional properties, return resolved reference directly
+ if not additional_properties:
+ return resolved_reference
+
+ # Mixed $ref case: merge resolved reference with additional properties
+ # Additional properties take precedence over resolved properties
+ merged_result = {}
+ if isinstance(resolved_reference, dict):
+ merged_result.update(resolved_reference)
+
+ # Process additional properties and merge them (they override resolved ones)
+ processed_additional = _process_dict_properties(
+ additional_properties,
+ full_schema,
+ processed_refs,
+ skip_keys,
+ shallow_refs=shallow_refs,
+ )
+ merged_result.update(processed_additional)
+
+ return merged_result
+
+ # Case 2: Regular dictionary without $ref - process all properties
+ if isinstance(obj, dict):
+ return _process_dict_properties(
+ obj, full_schema, processed_refs, skip_keys, shallow_refs=shallow_refs
+ )
+
+ # Case 3: List - recursively process each item
+ if isinstance(obj, list):
+ return [
+ _dereference_refs_helper(
+ item, full_schema, processed_refs, skip_keys, shallow_refs=shallow_refs
+ )
+ for item in obj
+ ]
+
+ # Case 4: Primitive value (string, number, boolean, null) - return unchanged
+ return obj
+
+
+def dereference_refs(
+ schema_obj: dict,
+ *,
+ full_schema: dict | None = None,
+ skip_keys: Sequence[str] | None = None,
+) -> dict:
+ """Resolve and inline JSON Schema `$ref` references in a schema object.
+
+ This function processes a JSON Schema and resolves all `$ref` references by
+ replacing them with the actual referenced content.
+
+ Handles both simple references and complex cases like circular references and mixed
+ `$ref` objects that contain additional properties alongside the `$ref`.
+
+ Args:
+ schema_obj: The JSON Schema object or fragment to process.
+
+ This can be a complete schema or just a portion of one.
+ full_schema: The complete schema containing all definitions that `$refs` might
+ point to.
+
+ If not provided, defaults to `schema_obj` (useful when the schema is
+ self-contained).
+ skip_keys: Controls recursion behavior and reference resolution depth.
+
+ - If `None` (Default): Only recurse under `'$defs'` and use shallow
+ reference resolution (break cycles but don't deep-inline nested refs)
+ - If provided (even as `[]`): Recurse under all keys and use deep reference
+ resolution (fully inline all nested references)
+
+ Returns:
+ A new dictionary with all $ref references resolved and inlined.
+
+ The original `schema_obj` is not modified.
+
+ Examples:
+ Basic reference resolution:
+ >>> schema = {
+ ... "type": "object",
+ ... "properties": {"name": {"$ref": "#/$defs/string_type"}},
+ ... "$defs": {"string_type": {"type": "string"}},
+ ... }
+ >>> result = dereference_refs(schema)
+ >>> result["properties"]["name"] # {"type": "string"}
+
+ Mixed `$ref` with additional properties:
+
+ >>> schema = {
+ ... "properties": {
+ ... "name": {"$ref": "#/$defs/base", "description": "User name"}
+ ... },
+ ... "$defs": {"base": {"type": "string", "minLength": 1}},
+ ... }
+ >>> result = dereference_refs(schema)
+ >>> result["properties"]["name"]
+ # {"type": "string", "minLength": 1, "description": "User name"}
+
+ Handling circular references:
+
+ >>> schema = {
+ ... "properties": {"user": {"$ref": "#/$defs/User"}},
+ ... "$defs": {
+ ... "User": {
+ ... "type": "object",
+ ... "properties": {"friend": {"$ref": "#/$defs/User"}},
+ ... }
+ ... },
+ ... }
+ >>> result = dereference_refs(schema) # Won't cause infinite recursion
+
+ !!! note
+
+ - Circular references are handled gracefully by breaking cycles
+ - Mixed `$ref` objects (with both `$ref` and other properties) are supported
+ - Additional properties in mixed `$refs` override resolved properties
+ - The `$defs` section is preserved in the output by default
+ """
+ full = full_schema or schema_obj
+ keys_to_skip = list(skip_keys) if skip_keys is not None else ["$defs"]
+ shallow = skip_keys is None
+ return cast(
+ "dict",
+ _dereference_refs_helper(
+ schema_obj, full, None, keys_to_skip, shallow_refs=shallow
+ ),
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/mustache.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/mustache.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8282b0f38454cff37bdc66bcc5b0e9138bf1077
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/mustache.py
@@ -0,0 +1,704 @@
+"""Adapted from https://github.com/noahmorrison/chevron.
+
+MIT License.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Iterator, Mapping, Sequence
+from types import MappingProxyType
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Literal,
+ cast,
+)
+
+if TYPE_CHECKING:
+ from typing import TypeAlias
+
+logger = logging.getLogger(__name__)
+
+
+Scopes: TypeAlias = list[Literal[False, 0] | Mapping[str, Any]]
+
+
+# Globals
+_CURRENT_LINE = 1
+_LAST_TAG_LINE = None
+
+
+class ChevronError(SyntaxError):
+ """Custom exception for Chevron errors."""
+
+
+#
+# Helper functions
+#
+
+
+def grab_literal(template: str, l_del: str) -> tuple[str, str]:
+ """Parse a literal from the template.
+
+ Args:
+ template: The template to parse.
+ l_del: The left delimiter.
+
+ Returns:
+ The literal and the template.
+ """
+ global _CURRENT_LINE
+
+ try:
+ # Look for the next tag and move the template to it
+ literal, template = template.split(l_del, 1)
+ _CURRENT_LINE += literal.count("\n")
+
+ # There are no more tags in the template?
+ except ValueError:
+ # Then the rest of the template is a literal
+ return (template, "")
+
+ return (literal, template)
+
+
+def l_sa_check(
+ template: str, # noqa: ARG001
+ literal: str,
+ is_standalone: bool, # noqa: FBT001
+) -> bool:
+ """Do a preliminary check to see if a tag could be a standalone.
+
+ Args:
+ template: The template. (Not used.)
+ literal: The literal.
+ is_standalone: Whether the tag is standalone.
+
+ Returns:
+ Whether the tag could be a standalone.
+ """
+ # If there is a newline, or the previous tag was a standalone
+ if literal.find("\n") != -1 or is_standalone:
+ padding = literal.rsplit("\n", maxsplit=1)[-1]
+
+ # If all the characters since the last newline are spaces
+ # Then the next tag could be a standalone
+ # Otherwise it can't be
+ return padding.isspace() or not padding
+ return False
+
+
+def r_sa_check(
+ template: str,
+ tag_type: str,
+ is_standalone: bool, # noqa: FBT001
+) -> bool:
+ """Do a final check to see if a tag could be a standalone.
+
+ Args:
+ template: The template.
+ tag_type: The type of the tag.
+ is_standalone: Whether the tag is standalone.
+
+ Returns:
+ Whether the tag could be a standalone.
+ """
+ # Check right side if we might be a standalone
+ if is_standalone and tag_type not in {"variable", "no escape"}:
+ on_newline = template.split("\n", 1)
+
+ # If the stuff to the right of us are spaces we're a standalone
+ return on_newline[0].isspace() or not on_newline[0]
+
+ # If we're a tag can't be a standalone
+ return False
+
+
+def parse_tag(template: str, l_del: str, r_del: str) -> tuple[tuple[str, str], str]:
+ """Parse a tag from a template.
+
+ Args:
+ template: The template.
+ l_del: The left delimiter.
+ r_del: The right delimiter.
+
+ Returns:
+ The tag and the template.
+
+ Raises:
+ ChevronError: If the tag is unclosed.
+ ChevronError: If the set delimiter tag is unclosed.
+ """
+ tag_types = {
+ "!": "comment",
+ "#": "section",
+ "^": "inverted section",
+ "/": "end",
+ ">": "partial",
+ "=": "set delimiter?",
+ "{": "no escape?",
+ "&": "no escape",
+ }
+
+ # Get the tag
+ try:
+ tag, template = template.split(r_del, 1)
+ except ValueError as e:
+ msg = f"unclosed tag at line {_CURRENT_LINE}"
+ raise ChevronError(msg) from e
+
+ # Check for empty tags
+ if not tag.strip():
+ msg = f"empty tag at line {_CURRENT_LINE}"
+ raise ChevronError(msg)
+
+ # Find the type meaning of the first character
+ tag_type = tag_types.get(tag[0], "variable")
+
+ # If the type is not a variable
+ if tag_type != "variable":
+ # Then that first character is not needed
+ tag = tag[1:]
+
+ # If we might be a set delimiter tag
+ if tag_type == "set delimiter?":
+ # Double check to make sure we are
+ if tag.endswith("="):
+ tag_type = "set delimiter"
+ # Remove the equal sign
+ tag = tag[:-1]
+
+ # Otherwise we should complain
+ else:
+ msg = f"unclosed set delimiter tag\nat line {_CURRENT_LINE}"
+ raise ChevronError(msg)
+
+ elif (
+ # If we might be a no html escape tag
+ tag_type == "no escape?"
+ # And we have a third curly brace
+ # (And are using curly braces as delimiters)
+ and l_del == "{{"
+ and r_del == "}}"
+ and template.startswith("}")
+ ):
+ # Then we are a no html escape tag
+ template = template[1:]
+ tag_type = "no escape"
+
+ # Strip the whitespace off the key and return
+ return ((tag_type, tag.strip()), template)
+
+
+#
+# The main tokenizing function
+#
+
+
+def tokenize(
+ template: str, def_ldel: str = "{{", def_rdel: str = "}}"
+) -> Iterator[tuple[str, str]]:
+ """Tokenize a mustache template.
+
+ Tokenizes a mustache template in a generator fashion, using file-like objects. It
+ also accepts a string containing the template.
+
+ Args:
+ template: a file-like object, or a string of a mustache template
+ def_ldel: The default left delimiter
+ (`'{{'` by default, as in spec compliant mustache)
+ def_rdel: The default right delimiter
+ (`'}}'` by default, as in spec compliant mustache)
+
+ Yields:
+ Mustache tags in the form of a tuple `(tag_type, tag_key)` where `tag_type` is
+ one of:
+
+ * literal
+ * section
+ * inverted section
+ * end
+ * partial
+ * no escape
+
+ ...and `tag_key` is either the key or in the case of a literal tag, the
+ literal itself.
+
+ Raises:
+ ChevronError: If there is a syntax error in the template.
+ """
+ global _CURRENT_LINE, _LAST_TAG_LINE
+ _CURRENT_LINE = 1
+ _LAST_TAG_LINE = None
+
+ is_standalone = True
+ open_sections = []
+ l_del = def_ldel
+ r_del = def_rdel
+
+ while template:
+ literal, template = grab_literal(template, l_del)
+
+ # If the template is completed
+ if not template:
+ # Then yield the literal and leave
+ yield ("literal", literal)
+ break
+
+ # Do the first check to see if we could be a standalone
+ is_standalone = l_sa_check(template, literal, is_standalone)
+
+ # Parse the tag
+ tag, template = parse_tag(template, l_del, r_del)
+ tag_type, tag_key = tag
+
+ # Special tag logic
+
+ # If we are a set delimiter tag
+ if tag_type == "set delimiter":
+ # Then get and set the delimiters
+ dels = tag_key.strip().split(" ")
+ l_del, r_del = dels[0], dels[-1]
+
+ # If we are a section tag
+ elif tag_type in {"section", "inverted section"}:
+ # Then open a new section
+ open_sections.append(tag_key)
+ _LAST_TAG_LINE = _CURRENT_LINE
+
+ # If we are an end tag
+ elif tag_type == "end":
+ # Then check to see if the last opened section
+ # is the same as us
+ try:
+ last_section = open_sections.pop()
+ except IndexError as e:
+ msg = (
+ f'Trying to close tag "{tag_key}"\n'
+ "Looks like it was not opened.\n"
+ f"line {_CURRENT_LINE + 1}"
+ )
+ raise ChevronError(msg) from e
+ if tag_key != last_section:
+ # Otherwise we need to complain
+ msg = (
+ f'Trying to close tag "{tag_key}"\n'
+ f'last open tag is "{last_section}"\n'
+ f"line {_CURRENT_LINE + 1}"
+ )
+ raise ChevronError(msg)
+
+ # Do the second check to see if we're a standalone
+ is_standalone = r_sa_check(template, tag_type, is_standalone)
+
+ # Which if we are
+ if is_standalone:
+ # Remove the stuff before the newline
+ template = template.split("\n", 1)[-1]
+
+ # Partials need to keep the spaces on their left
+ if tag_type != "partial":
+ # But other tags don't
+ literal = literal.rstrip(" ")
+
+ # Start yielding
+ # Ignore literals that are empty
+ if literal:
+ yield ("literal", literal)
+
+ # Ignore comments and set delimiters
+ if tag_type not in {"comment", "set delimiter?"}:
+ yield (tag_type, tag_key)
+
+ # If there are any open sections when we're done
+ if open_sections:
+ # Then we need to complain
+ msg = (
+ "Unexpected EOF\n"
+ f'the tag "{open_sections[-1]}" was never closed\n'
+ f"was opened at line {_LAST_TAG_LINE}"
+ )
+ raise ChevronError(msg)
+
+
+#
+# Helper functions
+#
+
+
+def _html_escape(string: str) -> str:
+ """Return the HTML-escaped string with these characters escaped: `" & < >`."""
+ html_codes = {
+ '"': """,
+ "<": "<",
+ ">": ">",
+ }
+
+ # & must be handled first
+ string = string.replace("&", "&")
+ for char, code in html_codes.items():
+ string = string.replace(char, code)
+ return string
+
+
+def _get_key(
+ key: str,
+ scopes: Scopes,
+ *,
+ warn: bool,
+ keep: bool,
+ def_ldel: str,
+ def_rdel: str,
+) -> Any:
+ """Retrieve a value from the current scope using a dot-separated key path.
+
+ Traverses through nested dictionaries and lists using dot notation.
+
+ Supports special key `'.'` to return the current scope.
+
+ Args:
+ key: Dot-separated key path (e.g., `'user.name'` or `'.'` for current scope).
+ scopes: List of scope dictionaries to search through.
+ warn: Whether to log a warning when a key is not found.
+ keep: Whether to return the original template tag when key is not found.
+ def_ldel: Left delimiter for template (used when keep is `True`).
+ def_rdel: Right delimiter for template (used when keep is `True`).
+
+ Returns:
+ The value found at the key path.
+
+ If not found, returns the original template tag when keep is `True`,
+ otherwise returns an empty string.
+ """
+ # If the key is a dot
+ if key == ".":
+ # Then just return the current scope
+ return scopes[0]
+
+ # Loop through the scopes
+ for scope in scopes:
+ try:
+ # Return an empty string if falsy, with two exceptions
+ # 0 should return 0, and False should return False
+ if scope in (0, False):
+ return scope
+
+ resolved_scope = scope
+ # For every dot separated key
+ for child in key.split("."):
+ # Return an empty string if falsy, with two exceptions
+ # 0 should return 0, and False should return False
+ if resolved_scope in (0, False):
+ return resolved_scope
+ # Move into the scope
+ if isinstance(resolved_scope, dict):
+ try:
+ resolved_scope = resolved_scope[child]
+ except (KeyError, TypeError):
+ # Key not found - will be caught by outer try-except
+ msg = f"Key {child!r} not found in dict"
+ raise KeyError(msg) from None
+ elif isinstance(resolved_scope, (list, tuple)):
+ try:
+ resolved_scope = resolved_scope[int(child)]
+ except (ValueError, IndexError, TypeError):
+ # Invalid index - will be caught by outer try-except
+ msg = f"Invalid index {child!r} for list/tuple"
+ raise IndexError(msg) from None
+ else:
+ # Reject everything else for security
+ # This prevents traversing into arbitrary Python objects
+ msg = (
+ f"Cannot traverse into {type(resolved_scope).__name__}. "
+ "Mustache templates only support dict, list, and tuple. "
+ f"Got: {type(resolved_scope)}"
+ )
+ raise TypeError(msg) # noqa: TRY301
+
+ try:
+ # This allows for custom falsy data types
+ # https://github.com/noahmorrison/chevron/issues/35
+ if resolved_scope._CHEVRON_return_scope_when_falsy: # type: ignore[union-attr] # noqa: SLF001
+ return resolved_scope
+ except AttributeError:
+ if resolved_scope in (0, False):
+ return resolved_scope
+ return resolved_scope or ""
+ except (AttributeError, KeyError, IndexError, ValueError, TypeError):
+ # We couldn't find the key in the current scope
+ # TypeError: Attempted to traverse into non-dict/list type
+ # We'll try again on the next pass
+ pass
+
+ # We couldn't find the key in any of the scopes
+
+ if warn:
+ logger.warning("Could not find key '%s'", key)
+
+ if keep:
+ return f"{def_ldel} {key} {def_rdel}"
+
+ return ""
+
+
+def _get_partial(name: str, partials_dict: Mapping[str, str]) -> str:
+ """Load a partial.
+
+ Returns:
+ The partial.
+ """
+ try:
+ # Maybe the partial is in the dictionary
+ return partials_dict[name]
+ except KeyError:
+ return ""
+
+
+#
+# The main rendering function
+#
+g_token_cache: dict[str, list[tuple[str, str]]] = {}
+
+EMPTY_DICT: MappingProxyType[str, str] = MappingProxyType({})
+
+
+def render(
+ template: str | list[tuple[str, str]] = "",
+ data: Mapping[str, Any] = EMPTY_DICT,
+ partials_dict: Mapping[str, str] = EMPTY_DICT,
+ padding: str = "",
+ def_ldel: str = "{{",
+ def_rdel: str = "}}",
+ scopes: Scopes | None = None,
+ warn: bool = False, # noqa: FBT001,FBT002
+ keep: bool = False, # noqa: FBT001,FBT002
+) -> str:
+ """Render a mustache template.
+
+ Renders a mustache template with a data scope and inline partial capability.
+
+ Args:
+ template: A file-like object or a string containing the template.
+ data: A python dictionary with your data scope.
+ partials_dict: A python dictionary which will be search for partials
+ before the filesystem is.
+
+ `{'include': 'foo'}` is the same as a file called include.mustache
+ (defaults to `{}`).
+ padding: This is for padding partials, and shouldn't be used
+ (but can be if you really want to).
+ def_ldel: The default left delimiter
+
+ (`'{{'` by default, as in spec compliant mustache).
+ def_rdel: The default right delimiter
+
+ (`'}}'` by default, as in spec compliant mustache).
+ scopes: The list of scopes that `get_key` will look through.
+ warn: Log a warning when a template substitution isn't found in the data
+ keep: Keep unreplaced tags when a substitution isn't found in the data.
+
+ Returns:
+ A string containing the rendered template.
+ """
+ # If the template is a sequence but not derived from a string
+ if isinstance(template, Sequence) and not isinstance(template, str):
+ # Then we don't need to tokenize it
+ # But it does need to be a generator
+ tokens: Iterator[tuple[str, str]] = (token for token in template)
+ elif template in g_token_cache:
+ tokens = (token for token in g_token_cache[template])
+ else:
+ # Otherwise make a generator
+ tokens = tokenize(template, def_ldel, def_rdel)
+
+ output = ""
+
+ if scopes is None:
+ scopes = [data]
+
+ # Run through the tokens
+ for tag, key in tokens:
+ # Set the current scope
+ current_scope = scopes[0]
+
+ # If we're an end tag
+ if tag == "end":
+ # Pop out of the latest scope
+ del scopes[0]
+
+ # If the current scope is falsy and not the only scope
+ elif not current_scope and len(scopes) != 1:
+ if tag in {"section", "inverted section"}:
+ # Set the most recent scope to a falsy value
+ scopes.insert(0, False)
+
+ # If we're a literal tag
+ elif tag == "literal":
+ # Add padding to the key and add it to the output
+ output += key.replace("\n", "\n" + padding)
+
+ # If we're a variable tag
+ elif tag == "variable":
+ # Add the html escaped key to the output
+ thing = _get_key(
+ key, scopes, warn=warn, keep=keep, def_ldel=def_ldel, def_rdel=def_rdel
+ )
+ if thing is True and key == ".":
+ # if we've coerced into a boolean by accident
+ # (inverted tags do this)
+ # then get the un-coerced object (next in the stack)
+ thing = scopes[1]
+ if not isinstance(thing, str):
+ thing = str(thing)
+ output += _html_escape(thing)
+
+ # If we're a no html escape tag
+ elif tag == "no escape":
+ # Just lookup the key and add it
+ thing = _get_key(
+ key, scopes, warn=warn, keep=keep, def_ldel=def_ldel, def_rdel=def_rdel
+ )
+ if not isinstance(thing, str):
+ thing = str(thing)
+ output += thing
+
+ # If we're a section tag
+ elif tag == "section":
+ # Get the sections scope
+ scope = _get_key(
+ key, scopes, warn=warn, keep=keep, def_ldel=def_ldel, def_rdel=def_rdel
+ )
+
+ # If the scope is a callable (as described in
+ # https://mustache.github.io/mustache.5.html)
+ if callable(scope):
+ # Generate template text from tags
+ text = ""
+ tags: list[tuple[str, str]] = []
+ for token in tokens:
+ if token == ("end", key):
+ break
+
+ tags.append(token)
+ tag_type, tag_key = token
+ if tag_type == "literal":
+ text += tag_key
+ elif tag_type == "no escape":
+ text += f"{def_ldel}& {tag_key} {def_rdel}"
+ else:
+ text += "{}{} {}{}".format(
+ def_ldel,
+ {
+ "comment": "!",
+ "section": "#",
+ "inverted section": "^",
+ "end": "/",
+ "partial": ">",
+ "set delimiter": "=",
+ "no escape": "&",
+ "variable": "",
+ }[tag_type],
+ tag_key,
+ def_rdel,
+ )
+
+ g_token_cache[text] = tags
+
+ rend = scope(
+ text,
+ lambda template, data=None: render(
+ template,
+ data={},
+ partials_dict=partials_dict,
+ padding=padding,
+ def_ldel=def_ldel,
+ def_rdel=def_rdel,
+ scopes=(data and [data, *scopes]) or scopes,
+ warn=warn,
+ keep=keep,
+ ),
+ )
+
+ output += rend
+
+ # If the scope is a sequence, an iterator or generator but not
+ # derived from a string
+ elif isinstance(scope, (Sequence, Iterator)) and not isinstance(scope, str):
+ # Then we need to do some looping
+
+ # Gather up all the tags inside the section
+ # (And don't be tricked by nested end tags with the same key)
+ # TODO: This feels like it still has edge cases, no?
+ tags = []
+ tags_with_same_key = 0
+ for token in tokens:
+ if token == ("section", key):
+ tags_with_same_key += 1
+ if token == ("end", key):
+ tags_with_same_key -= 1
+ if tags_with_same_key < 0:
+ break
+ tags.append(token)
+
+ # For every item in the scope
+ for thing in scope:
+ # Append it as the most recent scope and render
+ new_scope = [thing, *scopes]
+ rend = render(
+ template=tags,
+ scopes=new_scope,
+ padding=padding,
+ partials_dict=partials_dict,
+ def_ldel=def_ldel,
+ def_rdel=def_rdel,
+ warn=warn,
+ keep=keep,
+ )
+
+ output += rend
+
+ else:
+ # Otherwise we're just a scope section
+ scopes.insert(0, scope)
+
+ # If we're an inverted section
+ elif tag == "inverted section":
+ # Add the flipped scope to the scopes
+ scope = _get_key(
+ key, scopes, warn=warn, keep=keep, def_ldel=def_ldel, def_rdel=def_rdel
+ )
+ scopes.insert(0, cast("Literal[False]", not scope))
+
+ # If we're a partial
+ elif tag == "partial":
+ # Load the partial
+ partial = _get_partial(key, partials_dict)
+
+ # Find what to pad the partial with
+ left = output.rpartition("\n")[2]
+ part_padding = padding
+ if left.isspace():
+ part_padding += left
+
+ # Render the partial
+ part_out = render(
+ template=partial,
+ partials_dict=partials_dict,
+ def_ldel=def_ldel,
+ def_rdel=def_rdel,
+ padding=part_padding,
+ scopes=scopes,
+ warn=warn,
+ keep=keep,
+ )
+
+ # If the partial was indented
+ if left.isspace():
+ # then remove the spaces from the end
+ part_out = part_out.rstrip(" \t")
+
+ # Add the partials output to the output
+ output += part_out
+
+ return output
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/pydantic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/pydantic.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1c152d8d53b13d8ca1709b8b84558691a82f796
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/pydantic.py
@@ -0,0 +1,589 @@
+"""Utilities for pydantic."""
+
+from __future__ import annotations
+
+import inspect
+import textwrap
+import warnings
+from contextlib import nullcontext
+from functools import lru_cache, wraps
+from types import GenericAlias
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ TypeVar,
+ cast,
+ overload,
+)
+
+import pydantic
+from packaging import version
+
+# root_validator is deprecated but we need it for backward compatibility of @pre_init
+from pydantic import ( # type: ignore[deprecated]
+ BaseModel,
+ ConfigDict,
+ Field,
+ PydanticDeprecationWarning,
+ RootModel,
+ root_validator,
+)
+from pydantic import (
+ create_model as _create_model_base,
+)
+from pydantic.fields import FieldInfo as FieldInfoV2
+from pydantic.json_schema import (
+ DEFAULT_REF_TEMPLATE,
+ GenerateJsonSchema,
+ JsonSchemaMode,
+ JsonSchemaValue,
+)
+from pydantic.v1 import BaseModel as BaseModelV1
+from pydantic.v1 import create_model as create_model_v1
+from typing_extensions import deprecated, override
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ from pydantic.v1.fields import ModelField
+ from pydantic_core import core_schema
+
+PYDANTIC_VERSION = version.parse(pydantic.__version__)
+
+
+@deprecated("Use PYDANTIC_VERSION.major instead.")
+def get_pydantic_major_version() -> int:
+ """DEPRECATED - Get the major version of Pydantic.
+
+ Use `PYDANTIC_VERSION.major` instead.
+
+ Returns:
+ The major version of Pydantic.
+ """
+ return PYDANTIC_VERSION.major
+
+
+PYDANTIC_MAJOR_VERSION = PYDANTIC_VERSION.major
+PYDANTIC_MINOR_VERSION = PYDANTIC_VERSION.minor
+
+IS_PYDANTIC_V1 = False
+IS_PYDANTIC_V2 = True
+
+PydanticBaseModel = BaseModel
+TypeBaseModel = type[BaseModel]
+
+TBaseModel = TypeVar("TBaseModel", bound=PydanticBaseModel)
+
+
+def is_pydantic_v1_subclass(cls: type) -> bool:
+ """Check if the given class is Pydantic v1-like.
+
+ Returns:
+ `True` if the given class is a subclass of Pydantic `BaseModel` 1.x.
+ """
+ return issubclass(cls, BaseModelV1)
+
+
+def is_pydantic_v2_subclass(cls: type) -> bool:
+ """Check if the given class is Pydantic v2-like.
+
+ Returns:
+ `True` if the given class is a subclass of Pydantic `BaseModel` 2.x.
+ """
+ return issubclass(cls, BaseModel)
+
+
+def is_basemodel_subclass(cls: type) -> bool:
+ """Check if the given class is a subclass of Pydantic `BaseModel`.
+
+ Check if the given class is a subclass of any of the following:
+
+ * `pydantic.BaseModel` in Pydantic 2.x
+ * `pydantic.v1.BaseModel` in Pydantic 2.x
+
+ Returns:
+ `True` if the given class is a subclass of Pydantic `BaseModel`.
+ """
+ # Before we can use issubclass on the cls we need to check if it is a class
+ if not inspect.isclass(cls) or isinstance(cls, GenericAlias):
+ return False
+
+ return issubclass(cls, (BaseModel, BaseModelV1))
+
+
+def is_basemodel_instance(obj: Any) -> bool:
+ """Check if the given class is an instance of Pydantic `BaseModel`.
+
+ Check if the given class is an instance of any of the following:
+
+ * `pydantic.BaseModel` in Pydantic 2.x
+ * `pydantic.v1.BaseModel` in Pydantic 2.x
+
+ Returns:
+ `True` if the given class is an instance of Pydantic `BaseModel`.
+ """
+ return isinstance(obj, (BaseModel, BaseModelV1))
+
+
+# How to type hint this?
+def pre_init(func: Callable) -> Any:
+ """Decorator to run a function before model initialization.
+
+ Args:
+ func: The function to run before model initialization.
+
+ Returns:
+ The decorated function.
+ """
+ with warnings.catch_warnings():
+ warnings.filterwarnings(action="ignore", category=PydanticDeprecationWarning)
+
+ # Ideally we would use @model_validator(mode="before") but this would change the
+ # order of the validators. See https://github.com/pydantic/pydantic/discussions/7434.
+ # So we keep root_validator for backward compatibility.
+ @root_validator(pre=True) # type: ignore[deprecated]
+ @wraps(func)
+ def wrapper(cls: type[BaseModel], values: dict[str, Any]) -> Any:
+ """Decorator to run a function before model initialization.
+
+ Args:
+ cls: The model class.
+ values: The values to initialize the model with.
+
+ Returns:
+ The values to initialize the model with.
+ """
+ # Insert default values
+ fields = cls.model_fields
+ for name, field_info in fields.items():
+ # Check if allow_population_by_field_name is enabled
+ # If yes, then set the field name to the alias
+ if (
+ hasattr(cls, "Config")
+ and hasattr(cls.Config, "allow_population_by_field_name")
+ and cls.Config.allow_population_by_field_name
+ and field_info.alias in values
+ ):
+ values[name] = values.pop(field_info.alias)
+ if (
+ hasattr(cls, "model_config")
+ and cls.model_config.get("populate_by_name")
+ and field_info.alias in values
+ ):
+ values[name] = values.pop(field_info.alias)
+
+ if (
+ name not in values or values[name] is None
+ ) and not field_info.is_required():
+ if field_info.default_factory is not None:
+ values[name] = field_info.default_factory() # type: ignore[call-arg]
+ else:
+ values[name] = field_info.default
+
+ # Call the decorated function
+ return func(cls, values)
+
+ return wrapper
+
+
+class _IgnoreUnserializable(GenerateJsonSchema):
+ """A JSON schema generator that ignores unknown types.
+
+ https://docs.pydantic.dev/latest/concepts/json_schema/#customizing-the-json-schema-generation-process
+ """
+
+ @override
+ def handle_invalid_for_json_schema(
+ self, schema: core_schema.CoreSchema, error_info: str
+ ) -> JsonSchemaValue:
+ return {}
+
+
+def _create_subset_model_v1(
+ name: str,
+ model: type[BaseModelV1],
+ field_names: list,
+ *,
+ descriptions: dict | None = None,
+ fn_description: str | None = None,
+) -> type[BaseModelV1]:
+ """Create a Pydantic model with only a subset of model's fields."""
+ fields = {}
+
+ for field_name in field_names:
+ # Using pydantic v1 so can access __fields__ as a dict.
+ field = model.__fields__[field_name]
+ t = (
+ # this isn't perfect but should work for most functions
+ field.outer_type_
+ if field.required and not field.allow_none
+ else field.outer_type_ | None
+ )
+ if descriptions and field_name in descriptions:
+ field.field_info.description = descriptions[field_name]
+ fields[field_name] = (t, field.field_info)
+
+ rtn = cast("type[BaseModelV1]", create_model_v1(name, **fields)) # type: ignore[call-overload]
+ rtn.__doc__ = textwrap.dedent(fn_description or model.__doc__ or "")
+ return rtn
+
+
+def _create_subset_model_v2(
+ name: str,
+ model: type[BaseModel],
+ field_names: list[str],
+ *,
+ descriptions: dict | None = None,
+ fn_description: str | None = None,
+) -> type[BaseModel]:
+ """Create a Pydantic model with a subset of the model fields."""
+ descriptions_ = descriptions or {}
+ fields = {}
+ for field_name in field_names:
+ field = model.model_fields[field_name]
+ description = descriptions_.get(field_name, field.description)
+ field_kwargs: dict[str, Any] = {"description": description}
+ if field.default_factory is not None:
+ field_kwargs["default_factory"] = field.default_factory
+ else:
+ field_kwargs["default"] = field.default
+ field_info = FieldInfoV2(**field_kwargs)
+ if field.metadata:
+ field_info.metadata = field.metadata
+ fields[field_name] = (field.annotation, field_info)
+
+ rtn = cast(
+ "type[BaseModel]",
+ _create_model_base( # type: ignore[call-overload]
+ name, **fields, __config__=ConfigDict(arbitrary_types_allowed=True)
+ ),
+ )
+
+ # TODO(0.3): Determine if there is a more "pydantic" way to preserve annotations.
+ # This is done to preserve __annotations__ when working with pydantic 2.x
+ # and using the Annotated type with TypedDict.
+ # Comment out the following line, to trigger the relevant test case.
+ selected_annotations = [
+ (name, annotation)
+ for name, annotation in model.__annotations__.items()
+ if name in field_names
+ ]
+
+ rtn.__annotations__ = dict(selected_annotations)
+ rtn.__doc__ = textwrap.dedent(fn_description or model.__doc__ or "")
+ return rtn
+
+
+# Private functionality to create a subset model that's compatible across
+# different versions of pydantic.
+# Handles pydantic versions 2.x. including v1 of pydantic in 2.x.
+# However, can't find a way to type hint this.
+def _create_subset_model(
+ name: str,
+ model: TypeBaseModel,
+ field_names: list[str],
+ *,
+ descriptions: dict | None = None,
+ fn_description: str | None = None,
+) -> type[BaseModel]:
+ """Create subset model using the same pydantic version as the input model.
+
+ Returns:
+ The created subset model.
+ """
+ if issubclass(model, BaseModelV1):
+ return _create_subset_model_v1(
+ name,
+ model,
+ field_names,
+ descriptions=descriptions,
+ fn_description=fn_description,
+ )
+ return _create_subset_model_v2(
+ name,
+ model,
+ field_names,
+ descriptions=descriptions,
+ fn_description=fn_description,
+ )
+
+
+@overload
+def get_fields(model: type[BaseModel]) -> dict[str, FieldInfoV2]: ...
+
+
+@overload
+def get_fields(model: BaseModel) -> dict[str, FieldInfoV2]: ...
+
+
+@overload
+def get_fields(model: type[BaseModelV1]) -> dict[str, ModelField]: ...
+
+
+@overload
+def get_fields(model: BaseModelV1) -> dict[str, ModelField]: ...
+
+
+def get_fields(
+ model: type[BaseModel | BaseModelV1] | BaseModel | BaseModelV1,
+) -> dict[str, FieldInfoV2] | dict[str, ModelField]:
+ """Return the field names of a Pydantic model.
+
+ Args:
+ model: The Pydantic model or instance.
+
+ Raises:
+ TypeError: If the model is not a Pydantic model.
+ """
+ if not isinstance(model, type):
+ model = type(model)
+ if issubclass(model, BaseModel):
+ return model.model_fields
+ if issubclass(model, BaseModelV1):
+ return model.__fields__
+ msg = f"Expected a Pydantic model. Got {model}"
+ raise TypeError(msg)
+
+
+_SchemaConfig = ConfigDict(
+ arbitrary_types_allowed=True, frozen=True, protected_namespaces=()
+)
+
+NO_DEFAULT = object()
+
+
+def _create_root_model(
+ name: str,
+ type_: Any,
+ module_name: str | None = None,
+ default_: object = NO_DEFAULT,
+) -> type[BaseModel]:
+ """Create a base class."""
+
+ def schema(
+ cls: type[BaseModelV1],
+ by_alias: bool = True, # noqa: FBT001,FBT002
+ ref_template: str = DEFAULT_REF_TEMPLATE,
+ ) -> dict[str, Any]:
+ super_cls = cast("type[BaseModelV1]", super(cls, cls))
+ schema_ = super_cls.schema(by_alias=by_alias, ref_template=ref_template)
+ schema_["title"] = name
+ return schema_
+
+ def model_json_schema(
+ cls: type[BaseModel],
+ by_alias: bool = True, # noqa: FBT001,FBT002
+ ref_template: str = DEFAULT_REF_TEMPLATE,
+ schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
+ mode: JsonSchemaMode = "validation",
+ ) -> dict[str, Any]:
+ super_cls = cast("type[BaseModel]", super(cls, cls))
+ schema_ = super_cls.model_json_schema(
+ by_alias=by_alias,
+ ref_template=ref_template,
+ schema_generator=schema_generator,
+ mode=mode,
+ )
+ schema_["title"] = name
+ return schema_
+
+ base_class_attributes = {
+ "__annotations__": {"root": type_},
+ "model_config": ConfigDict(arbitrary_types_allowed=True),
+ "schema": classmethod(schema),
+ "model_json_schema": classmethod(model_json_schema),
+ "__module__": module_name or "langchain_core.runnables.utils",
+ }
+
+ if default_ is not NO_DEFAULT:
+ base_class_attributes["root"] = default_
+ with warnings.catch_warnings():
+ try:
+ if (
+ isinstance(type_, type)
+ and not isinstance(type_, GenericAlias)
+ and issubclass(type_, BaseModelV1)
+ ):
+ warnings.filterwarnings(
+ action="ignore", category=PydanticDeprecationWarning
+ )
+ except TypeError:
+ pass
+ custom_root_type = type(name, (RootModel,), base_class_attributes)
+ return cast("type[BaseModel]", custom_root_type)
+
+
+@lru_cache(maxsize=256)
+def _create_root_model_cached(
+ model_name: str,
+ type_: Any,
+ *,
+ module_name: str | None = None,
+ default_: object = NO_DEFAULT,
+) -> type[BaseModel]:
+ return _create_root_model(
+ model_name, type_, default_=default_, module_name=module_name
+ )
+
+
+@lru_cache(maxsize=256)
+def _create_model_cached(
+ model_name: str,
+ /,
+ **field_definitions: Any,
+) -> type[BaseModel]:
+ return _create_model_base(
+ model_name,
+ __config__=_SchemaConfig,
+ **_remap_field_definitions(field_definitions),
+ )
+
+
+def create_model(
+ model_name: str,
+ module_name: str | None = None,
+ /,
+ **field_definitions: Any,
+) -> type[BaseModel]:
+ """Create a Pydantic model with the given field definitions.
+
+ Please use `create_model_v2` instead of this function.
+
+ Args:
+ model_name: The name of the model.
+ module_name: The name of the module where the model is defined.
+
+ This is used by Pydantic to resolve any forward references.
+ **field_definitions: The field definitions for the model.
+
+ Returns:
+ The created model.
+ """
+ kwargs = {}
+ if "__root__" in field_definitions:
+ kwargs["root"] = field_definitions.pop("__root__")
+
+ return create_model_v2(
+ model_name,
+ module_name=module_name,
+ field_definitions=field_definitions,
+ **kwargs,
+ )
+
+
+# Reserved names should capture all the `public` names / methods that are
+# used by BaseModel internally. This will keep the reserved names up-to-date.
+# For reference, the reserved names are:
+# "construct", "copy", "dict", "from_orm", "json", "parse_file", "parse_obj",
+# "parse_raw", "schema", "schema_json", "update_forward_refs", "validate",
+# "model_computed_fields", "model_config", "model_construct", "model_copy",
+# "model_dump", "model_dump_json", "model_extra", "model_fields",
+# "model_fields_set", "model_json_schema", "model_parametrized_name",
+# "model_post_init", "model_rebuild", "model_validate", "model_validate_json",
+# "model_validate_strings"
+_RESERVED_NAMES = {key for key in dir(BaseModel) if not key.startswith("_")}
+
+
+def _remap_field_definitions(field_definitions: dict[str, Any]) -> dict[str, Any]:
+ """This remaps fields to avoid colliding with internal pydantic fields."""
+ remapped = {}
+ for key, value in field_definitions.items():
+ if key.startswith("_") or key in _RESERVED_NAMES:
+ # Let's add a prefix to avoid colliding with internal pydantic fields
+ if isinstance(value, FieldInfoV2):
+ msg = (
+ f"Remapping for fields starting with '_' or fields with a name "
+ f"matching a reserved name {_RESERVED_NAMES} is not supported if "
+ f" the field is a pydantic Field instance. Got {key}."
+ )
+ raise NotImplementedError(msg)
+ type_, default_ = value
+ remapped[f"private_{key}"] = (
+ type_,
+ Field(
+ default=default_,
+ alias=key,
+ serialization_alias=key,
+ title=key.lstrip("_").replace("_", " ").title(),
+ ),
+ )
+ else:
+ remapped[key] = value
+ return remapped
+
+
+def create_model_v2(
+ model_name: str,
+ *,
+ module_name: str | None = None,
+ field_definitions: dict[str, Any] | None = None,
+ root: Any | None = None,
+) -> type[BaseModel]:
+ """Create a Pydantic model with the given field definitions.
+
+ !!! warning
+
+ Do not use outside of langchain packages. This API is subject to change at any
+ time.
+
+ Args:
+ model_name: The name of the model.
+ module_name: The name of the module where the model is defined.
+
+ This is used by Pydantic to resolve any forward references.
+ field_definitions: The field definitions for the model.
+ root: Type for a root model (`RootModel`)
+
+ Returns:
+ The created model.
+ """
+ field_definitions = field_definitions or {}
+
+ if root:
+ if field_definitions:
+ msg = (
+ "When specifying __root__ no other "
+ f"fields should be provided. Got {field_definitions}"
+ )
+ raise NotImplementedError(msg)
+
+ if isinstance(root, tuple):
+ kwargs = {"type_": root[0], "default_": root[1]}
+ else:
+ kwargs = {"type_": root}
+
+ try:
+ named_root_model = _create_root_model_cached(
+ model_name, module_name=module_name, **kwargs
+ )
+ except TypeError:
+ # something in the arguments into _create_root_model_cached is not hashable
+ named_root_model = _create_root_model(
+ model_name,
+ module_name=module_name,
+ **kwargs,
+ )
+ return named_root_model
+
+ # No root, just field definitions
+ names = set(field_definitions.keys())
+
+ capture_warnings = False
+
+ for name in names:
+ # Also if any non-reserved name is used (e.g., model_id or model_name)
+ if name.startswith("model"):
+ capture_warnings = True
+
+ with warnings.catch_warnings() if capture_warnings else nullcontext():
+ if capture_warnings:
+ warnings.filterwarnings(action="ignore")
+ try:
+ return _create_model_cached(model_name, **field_definitions)
+ except TypeError:
+ # something in field definitions is not hashable
+ return _create_model_base(
+ model_name,
+ __config__=_SchemaConfig,
+ **_remap_field_definitions(field_definitions),
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/strings.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/strings.py
new file mode 100644
index 0000000000000000000000000000000000000000..357b16f8e164b0bd61b6488f3bade77024d29fd8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/strings.py
@@ -0,0 +1,69 @@
+"""String utilities."""
+
+from collections.abc import Iterable
+from typing import Any
+
+
+def stringify_value(val: Any) -> str:
+ """Stringify a value.
+
+ Args:
+ val: The value to stringify.
+
+ Returns:
+ The stringified value.
+ """
+ if isinstance(val, str):
+ return val
+ if isinstance(val, dict):
+ return "\n" + stringify_dict(val)
+ if isinstance(val, list):
+ return "\n".join(stringify_value(v) for v in val)
+ return str(val)
+
+
+def stringify_dict(data: dict) -> str:
+ """Stringify a dictionary.
+
+ Args:
+ data: The dictionary to stringify.
+
+ Returns:
+ The stringified dictionary.
+ """
+ return "".join(f"{key}: {stringify_value(value)}\n" for key, value in data.items())
+
+
+def comma_list(items: Iterable[Any]) -> str:
+ """Convert an iterable to a comma-separated string.
+
+ Args:
+ items: The iterable to convert.
+
+ Returns:
+ The comma-separated string.
+ """
+ return ", ".join(str(item) for item in items)
+
+
+def sanitize_for_postgres(text: str, replacement: str = "") -> str:
+ r"""Sanitize text by removing NUL bytes that are incompatible with PostgreSQL.
+
+ PostgreSQL text fields cannot contain `NUL (0x00)` bytes, which can cause
+ `psycopg.DataError` when inserting documents. This function removes or replaces
+ such characters to ensure compatibility.
+
+ Args:
+ text: The text to sanitize.
+ replacement: String to replace `NUL` bytes with.
+
+ Returns:
+ The sanitized text with `NUL` bytes removed or replaced.
+
+ Example:
+ >>> sanitize_for_postgres("Hello\\x00world")
+ 'Helloworld'
+ >>> sanitize_for_postgres("Hello\\x00world", " ")
+ 'Hello world'
+ """
+ return text.replace("\x00", replacement)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/usage.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/usage.py
new file mode 100644
index 0000000000000000000000000000000000000000..47e483a5555cd0cc64d0a21f9cca43ce4148ff31
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/usage.py
@@ -0,0 +1,60 @@
+"""Usage utilities."""
+
+from collections.abc import Callable
+
+
+def _dict_int_op(
+ left: dict,
+ right: dict,
+ op: Callable[[int, int], int],
+ *,
+ default: int = 0,
+ depth: int = 0,
+ max_depth: int = 100,
+) -> dict:
+ """Apply an integer operation to corresponding values in two dictionaries.
+
+ Recursively combines two dictionaries by applying the given operation to integer
+ values at matching keys.
+
+ Supports nested dictionaries.
+
+ Args:
+ left: First dictionary to combine.
+ right: Second dictionary to combine.
+ op: Binary operation function to apply to integer values.
+ default: Default value to use when a key is missing from a dictionary.
+ depth: Current recursion depth (used internally).
+ max_depth: Maximum recursion depth (to prevent infinite loops).
+
+ Returns:
+ A new dictionary with combined values.
+
+ Raises:
+ ValueError: If `max_depth` is exceeded or if value types are not supported.
+ """
+ if depth >= max_depth:
+ msg = f"{max_depth=} exceeded, unable to combine dicts."
+ raise ValueError(msg)
+ combined: dict = {}
+ for k in set(left).union(right):
+ if isinstance(left.get(k, default), int) and isinstance(
+ right.get(k, default), int
+ ):
+ combined[k] = op(left.get(k, default), right.get(k, default))
+ elif isinstance(left.get(k, {}), dict) and isinstance(right.get(k, {}), dict):
+ combined[k] = _dict_int_op(
+ left.get(k, {}),
+ right.get(k, {}),
+ op,
+ default=default,
+ depth=depth + 1,
+ max_depth=max_depth,
+ )
+ else:
+ types = [type(d[k]) for d in (left, right) if k in d]
+ msg = (
+ f"Unknown value types: {types}. Only dict and int values are supported."
+ )
+ raise ValueError(msg) # noqa: TRY004
+ return combined
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8a5ed999a28f8c9c56276d8aa60ecfd3f3f1d89
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/utils.py
@@ -0,0 +1,521 @@
+"""Generic utility functions."""
+
+import contextlib
+import datetime
+import functools
+import importlib
+import os
+import warnings
+from collections.abc import Callable, Iterator, Sequence
+from importlib.metadata import version
+from typing import Any, overload
+from uuid import uuid4
+
+from packaging.version import parse
+from pydantic import SecretStr
+from requests import HTTPError, Response
+from typing_extensions import override
+
+from langchain_core.utils.pydantic import (
+ is_pydantic_v1_subclass,
+)
+
+
+def xor_args(*arg_groups: tuple[str, ...]) -> Callable:
+ """Validate specified keyword args are mutually exclusive.
+
+ Args:
+ *arg_groups: Groups of mutually exclusive keyword args.
+
+ Returns:
+ Decorator that validates the specified keyword args are mutually exclusive.
+ """
+
+ def decorator(func: Callable) -> Callable:
+ @functools.wraps(func)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ """Validate exactly one arg in each group is not None."""
+ counts = [
+ sum(1 for arg in arg_group if kwargs.get(arg) is not None)
+ for arg_group in arg_groups
+ ]
+ invalid_groups = [i for i, count in enumerate(counts) if count != 1]
+ if invalid_groups:
+ invalid_group_names = [", ".join(arg_groups[i]) for i in invalid_groups]
+ msg = (
+ "Exactly one argument in each of the following"
+ " groups must be defined:"
+ f" {', '.join(invalid_group_names)}"
+ )
+ raise ValueError(msg)
+ return func(*args, **kwargs)
+
+ return wrapper
+
+ return decorator
+
+
+def raise_for_status_with_text(response: Response) -> None:
+ """Raise an error with the response text.
+
+ Args:
+ response: The response to check for errors.
+
+ Raises:
+ ValueError: If the response has an error status code.
+ """
+ try:
+ response.raise_for_status()
+ except HTTPError as e:
+ raise ValueError(response.text) from e
+
+
+@contextlib.contextmanager
+def mock_now(dt_value: datetime.datetime) -> Iterator[type]:
+ """Context manager for mocking out datetime.now() in unit tests.
+
+ Args:
+ dt_value: The datetime value to use for datetime.now().
+
+ Yields:
+ The mocked datetime class.
+
+ Example:
+ ```python
+ with mock_now(datetime.datetime(2011, 2, 3, 10, 11)):
+ assert datetime.datetime.now() == datetime.datetime(2011, 2, 3, 10, 11)
+ ```
+ """
+
+ class MockDateTime(datetime.datetime):
+ """Mock datetime.datetime.now() with a fixed datetime."""
+
+ @classmethod
+ @override
+ def now(cls, tz: datetime.tzinfo | None = None) -> "MockDateTime":
+ # Create a copy of dt_value.
+ return MockDateTime(
+ dt_value.year,
+ dt_value.month,
+ dt_value.day,
+ dt_value.hour,
+ dt_value.minute,
+ dt_value.second,
+ dt_value.microsecond,
+ dt_value.tzinfo,
+ )
+
+ real_datetime = datetime.datetime
+ datetime.datetime = MockDateTime # type: ignore[misc]
+ try:
+ yield datetime.datetime
+ finally:
+ datetime.datetime = real_datetime # type: ignore[misc]
+
+
+def guard_import(
+ module_name: str, *, pip_name: str | None = None, package: str | None = None
+) -> Any:
+ """Dynamically import a module.
+
+ Raise an exception if the module is not installed.
+
+ Args:
+ module_name: The name of the module to import.
+ pip_name: The name of the module to install with pip.
+ package: The package to import the module from.
+
+ Returns:
+ The imported module.
+
+ Raises:
+ ImportError: If the module is not installed.
+ """
+ try:
+ module = importlib.import_module(module_name, package)
+ except (ImportError, ModuleNotFoundError) as e:
+ pip_name = pip_name or module_name.split(".", maxsplit=1)[0].replace("_", "-")
+ msg = (
+ f"Could not import {module_name} python package. "
+ f"Please install it with `pip install {pip_name}`."
+ )
+ raise ImportError(msg) from e
+ return module
+
+
+def check_package_version(
+ package: str,
+ lt_version: str | None = None,
+ lte_version: str | None = None,
+ gt_version: str | None = None,
+ gte_version: str | None = None,
+) -> None:
+ """Check the version of a package.
+
+ Args:
+ package: The name of the package.
+ lt_version: The version must be less than this.
+ lte_version: The version must be less than or equal to this.
+ gt_version: The version must be greater than this.
+ gte_version: The version must be greater than or equal to this.
+
+
+ Raises:
+ ValueError: If the package version does not meet the requirements.
+ """
+ imported_version = parse(version(package))
+ if lt_version is not None and imported_version >= parse(lt_version):
+ msg = (
+ f"Expected {package} version to be < {lt_version}. Received "
+ f"{imported_version}."
+ )
+ raise ValueError(msg)
+ if lte_version is not None and imported_version > parse(lte_version):
+ msg = (
+ f"Expected {package} version to be <= {lte_version}. Received "
+ f"{imported_version}."
+ )
+ raise ValueError(msg)
+ if gt_version is not None and imported_version <= parse(gt_version):
+ msg = (
+ f"Expected {package} version to be > {gt_version}. Received "
+ f"{imported_version}."
+ )
+ raise ValueError(msg)
+ if gte_version is not None and imported_version < parse(gte_version):
+ msg = (
+ f"Expected {package} version to be >= {gte_version}. Received "
+ f"{imported_version}."
+ )
+ raise ValueError(msg)
+
+
+def get_pydantic_field_names(pydantic_cls: Any) -> set[str]:
+ """Get field names, including aliases, for a pydantic class.
+
+ Args:
+ pydantic_cls: Pydantic class.
+
+ Returns:
+ Field names.
+ """
+ all_required_field_names = set()
+ if is_pydantic_v1_subclass(pydantic_cls):
+ for field in pydantic_cls.__fields__.values():
+ all_required_field_names.add(field.name)
+ if field.has_alias:
+ all_required_field_names.add(field.alias)
+ else: # Assuming pydantic 2 for now
+ for name, field in pydantic_cls.model_fields.items():
+ all_required_field_names.add(name)
+ if field.alias:
+ all_required_field_names.add(field.alias)
+ return all_required_field_names
+
+
+def _build_model_kwargs(
+ values: dict[str, Any],
+ all_required_field_names: set[str],
+) -> dict[str, Any]:
+ """Build `model_kwargs` param from Pydantic constructor values.
+
+ Args:
+ values: All init args passed in by user.
+ all_required_field_names: All required field names for the pydantic class.
+
+ Returns:
+ Extra kwargs.
+
+ Raises:
+ ValueError: If a field is specified in both `values` and `extra_kwargs`.
+ ValueError: If a field is specified in `model_kwargs`.
+ """
+ extra_kwargs = values.get("model_kwargs", {})
+ for field_name in list(values):
+ if field_name in extra_kwargs:
+ msg = f"Found {field_name} supplied twice."
+ raise ValueError(msg)
+ if field_name not in all_required_field_names:
+ warnings.warn(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please confirm that {field_name} is what you intended.""",
+ stacklevel=7,
+ )
+ extra_kwargs[field_name] = values.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra_kwargs.keys())
+ if invalid_model_kwargs:
+ warnings.warn(
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter.",
+ stacklevel=7,
+ )
+ for k in invalid_model_kwargs:
+ values[k] = extra_kwargs.pop(k)
+
+ values["model_kwargs"] = extra_kwargs
+ return values
+
+
+# DON'T USE! Kept for backwards-compatibility but should never have been public.
+def build_extra_kwargs(
+ extra_kwargs: dict[str, Any],
+ values: dict[str, Any],
+ all_required_field_names: set[str],
+) -> dict[str, Any]:
+ """Build extra kwargs from values and extra_kwargs.
+
+ !!! danger "DON'T USE"
+
+ Kept for backwards-compatibility but should never have been public. Use the
+ internal `_build_model_kwargs` function instead.
+
+ Args:
+ extra_kwargs: Extra kwargs passed in by user.
+ values: Values passed in by user.
+ all_required_field_names: All required field names for the pydantic class.
+
+ Returns:
+ Extra kwargs.
+
+ Raises:
+ ValueError: If a field is specified in both `values` and `extra_kwargs`.
+ ValueError: If a field is specified in `model_kwargs`.
+ """
+ # DON'T USE! Kept for backwards-compatibility but should never have been public.
+ for field_name in list(values):
+ if field_name in extra_kwargs:
+ msg = f"Found {field_name} supplied twice."
+ raise ValueError(msg)
+ if field_name not in all_required_field_names:
+ warnings.warn(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please confirm that {field_name} is what you intended.""",
+ stacklevel=7,
+ )
+ extra_kwargs[field_name] = values.pop(field_name)
+
+ # DON'T USE! Kept for backwards-compatibility but should never have been public.
+ invalid_model_kwargs = all_required_field_names.intersection(extra_kwargs.keys())
+ if invalid_model_kwargs:
+ msg = (
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+ raise ValueError(msg)
+
+ # DON'T USE! Kept for backwards-compatibility but should never have been public.
+ return extra_kwargs
+
+
+def convert_to_secret_str(value: SecretStr | str) -> SecretStr:
+ """Convert a string to a `SecretStr` if needed.
+
+ Args:
+ value: The value to convert.
+
+ Returns:
+ The `SecretStr` value.
+ """
+ if isinstance(value, SecretStr):
+ return value
+ return SecretStr(value)
+
+
+class _NoDefaultType:
+ """Type to indicate no default value is provided."""
+
+
+_NoDefault = _NoDefaultType()
+
+
+@overload
+def from_env(key: str, /) -> Callable[[], str]: ...
+
+
+@overload
+def from_env(key: str, /, *, default: str) -> Callable[[], str]: ...
+
+
+@overload
+def from_env(key: Sequence[str], /, *, default: str) -> Callable[[], str]: ...
+
+
+@overload
+def from_env(key: str, /, *, error_message: str) -> Callable[[], str]: ...
+
+
+@overload
+def from_env(
+ key: str | Sequence[str], /, *, default: str, error_message: str | None
+) -> Callable[[], str]: ...
+
+
+@overload
+def from_env(
+ key: str, /, *, default: None, error_message: str | None
+) -> Callable[[], str | None]: ...
+
+
+@overload
+def from_env(
+ key: str | Sequence[str], /, *, default: None
+) -> Callable[[], str | None]: ...
+
+
+def from_env(
+ key: str | Sequence[str],
+ /,
+ *,
+ default: str | _NoDefaultType | None = _NoDefault,
+ error_message: str | None = None,
+) -> Callable[[], str] | Callable[[], str | None]:
+ """Create a factory method that gets a value from an environment variable.
+
+ Args:
+ key: The environment variable to look up.
+
+ If a list of keys is provided, the first key found in the environment will
+ be used. If no key is found, the default value will be used if set,
+ otherwise an error will be raised.
+ default: The default value to return if the environment variable is not set.
+ error_message: The error message which will be raised if the key is not found
+ and no default value is provided.
+
+ This will be raised as a ValueError.
+
+ Returns:
+ Factory method that will look up the value from the environment.
+ """
+
+ def get_from_env_fn() -> str | None:
+ """Get a value from an environment variable.
+
+ Raises:
+ ValueError: If the environment variable is not set and no default is
+ provided.
+
+ Returns:
+ The value from the environment.
+ """
+ if isinstance(key, (list, tuple)):
+ for k in key:
+ if k in os.environ:
+ return os.environ[k]
+ if isinstance(key, str) and key in os.environ:
+ return os.environ[key]
+
+ if isinstance(default, (str, type(None))):
+ return default
+ if error_message:
+ raise ValueError(error_message)
+ msg = (
+ f"Did not find {key}, please add an environment variable"
+ f" `{key}` which contains it, or pass"
+ f" `{key}` as a named parameter."
+ )
+ raise ValueError(msg)
+
+ return get_from_env_fn
+
+
+@overload
+def secret_from_env(key: str | Sequence[str], /) -> Callable[[], SecretStr]: ...
+
+
+@overload
+def secret_from_env(key: str, /, *, default: str) -> Callable[[], SecretStr]: ...
+
+
+@overload
+def secret_from_env(
+ key: str | Sequence[str], /, *, default: None
+) -> Callable[[], SecretStr | None]: ...
+
+
+@overload
+def secret_from_env(key: str, /, *, error_message: str) -> Callable[[], SecretStr]: ...
+
+
+def secret_from_env(
+ key: str | Sequence[str],
+ /,
+ *,
+ default: str | _NoDefaultType | None = _NoDefault,
+ error_message: str | None = None,
+) -> Callable[[], SecretStr | None] | Callable[[], SecretStr]:
+ """Secret from env.
+
+ Args:
+ key: The environment variable to look up.
+ default: The default value to return if the environment variable is not set.
+ error_message: The error message which will be raised if the key is not found
+ and no default value is provided.
+
+ This will be raised as a `ValueError`.
+
+ Returns:
+ Factory method that will look up the secret from the environment.
+ """
+
+ def get_secret_from_env() -> SecretStr | None:
+ """Get a value from an environment variable.
+
+ Raises:
+ ValueError: If the environment variable is not set and no default is
+ provided.
+
+ Returns:
+ The secret from the environment.
+ """
+ if isinstance(key, (list, tuple)):
+ for k in key:
+ if k in os.environ:
+ return SecretStr(os.environ[k])
+ if isinstance(key, str) and key in os.environ:
+ return SecretStr(os.environ[key])
+ if isinstance(default, str):
+ return SecretStr(default)
+ if default is None:
+ return None
+ if error_message:
+ raise ValueError(error_message)
+ msg = (
+ f"Did not find {key}, please add an environment variable"
+ f" `{key}` which contains it, or pass"
+ f" `{key}` as a named parameter."
+ )
+ raise ValueError(msg)
+
+ return get_secret_from_env
+
+
+LC_AUTO_PREFIX = "lc_"
+"""LangChain auto-generated ID prefix for messages and content blocks."""
+
+LC_ID_PREFIX = "lc_run-"
+"""Internal tracing/callback system identifier.
+
+Used for:
+
+- Tracing. Every LangChain operation (LLM call, chain execution, tool use, etc.)
+ gets a unique run_id (UUID)
+- Enables tracking parent-child relationships between operations
+"""
+
+
+def ensure_id(id_val: str | None) -> str:
+ """Ensure the ID is a valid string, generating a new UUID if not provided.
+
+ Auto-generated UUIDs are prefixed by `'lc_'` to indicate they are
+ LangChain-generated IDs.
+
+ Args:
+ id_val: Optional string ID value to validate.
+
+ Returns:
+ A string ID, either the validated provided value or a newly generated UUID4.
+ """
+ return id_val or f"{LC_AUTO_PREFIX}{uuid4()}"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/uuid.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/uuid.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d895edabaa22b839c6100af1813ba5f7ae63fb1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/utils/uuid.py
@@ -0,0 +1,57 @@
+"""UUID utility functions.
+
+This module exports a uuid7 function to generate monotonic, time-ordered UUIDs
+for tracing and similar operations.
+"""
+
+from __future__ import annotations
+
+import typing
+from uuid import UUID
+
+from uuid_utils.compat import uuid7 as _uuid_utils_uuid7
+
+if typing.TYPE_CHECKING:
+ from uuid import UUID
+
+_NANOS_PER_SECOND: typing.Final = 1_000_000_000
+
+
+def _to_timestamp_and_nanos(nanoseconds: int) -> tuple[int, int]:
+ """Split a nanosecond timestamp into seconds and remaining nanoseconds."""
+ seconds, nanos = divmod(nanoseconds, _NANOS_PER_SECOND)
+ return seconds, nanos
+
+
+def uuid7(nanoseconds: int | None = None) -> UUID:
+ """Generate a UUID from a Unix timestamp in nanoseconds and random bits.
+
+ UUIDv7 objects feature monotonicity within a millisecond.
+
+ Args:
+ nanoseconds: Optional ns timestamp. If not provided, uses current time.
+
+ Returns:
+ A UUIDv7 object.
+ """
+ # --- 48 --- -- 4 -- --- 12 --- -- 2 -- --- 30 --- - 32 -
+ # unix_ts_ms | version | counter_hi | variant | counter_lo | random
+ #
+ # 'counter = counter_hi | counter_lo' is a 42-bit counter constructed
+ # with Method 1 of RFC 9562, §6.2, and its MSB is set to 0.
+ #
+ # 'random' is a 32-bit random value regenerated for every new UUID.
+ #
+ # If multiple UUIDs are generated within the same millisecond, the LSB
+ # of 'counter' is incremented by 1. When overflowing, the timestamp is
+ # advanced and the counter is reset to a random 42-bit integer with MSB
+ # set to 0.
+
+ # For now, just delegate to the uuid_utils implementation
+ if nanoseconds is None:
+ return _uuid_utils_uuid7()
+ seconds, nanos = _to_timestamp_and_nanos(nanoseconds)
+ return _uuid_utils_uuid7(timestamp=seconds, nanos=nanos)
+
+
+__all__ = ["uuid7"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1da27459d6bb8a831c4109aac36ba1b971594245
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__init__.py
@@ -0,0 +1,53 @@
+"""Vector stores."""
+
+from typing import TYPE_CHECKING
+
+from langchain_core._import_utils import import_attr
+
+if TYPE_CHECKING:
+ from langchain_core.vectorstores.base import VST, VectorStore, VectorStoreRetriever
+ from langchain_core.vectorstores.in_memory import InMemoryVectorStore
+
+__all__ = (
+ "VST",
+ "InMemoryVectorStore",
+ "VectorStore",
+ "VectorStoreRetriever",
+)
+
+_dynamic_imports = {
+ "VectorStore": "base",
+ "VST": "base",
+ "VectorStoreRetriever": "base",
+ "InMemoryVectorStore": "in_memory",
+}
+
+
+def __getattr__(attr_name: str) -> object:
+ """Dynamically import and return an attribute from a submodule.
+
+ This function enables lazy loading of vectorstore classes from submodules, reducing
+ initial import time and circular dependency issues.
+
+ Args:
+ attr_name: Name of the attribute to import.
+
+ Returns:
+ The imported attribute object.
+
+ Raises:
+ AttributeError: If the attribute is not found in `_dynamic_imports`.
+ """
+ module_name = _dynamic_imports.get(attr_name)
+ result = import_attr(attr_name, module_name, __spec__.parent)
+ globals()[attr_name] = result
+ return result
+
+
+def __dir__() -> list[str]:
+ """Return a list of available attributes for this module.
+
+ Returns:
+ List of attribute names that can be imported from this module.
+ """
+ return list(__all__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40dd063400d79545de5ee6583e7f122d8ae0d67d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..971d97e972a75fa851f9d61475ada65d376b54d9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__pycache__/in_memory.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__pycache__/in_memory.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c73e46f2a9fef1f294396c4763474309e5c77d8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__pycache__/in_memory.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52985ddb40129472b00780d3c43ff354efdbbaae
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/__pycache__/utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..827a05cc90dbc3f50c7224d5ec7a1d340c70e380
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/base.py
@@ -0,0 +1,1111 @@
+"""A vector store stores embedded data and performs vector search.
+
+One of the most common ways to store and search over unstructured data is to
+embed it and store the resulting embedding vectors, and then query the store
+and retrieve the data that are 'most similar' to the embedded query.
+"""
+
+from __future__ import annotations
+
+import logging
+import math
+import warnings
+from abc import ABC, abstractmethod
+from itertools import cycle
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ ClassVar,
+ TypeVar,
+)
+
+from pydantic import ConfigDict, Field, model_validator
+from typing_extensions import Self, override
+
+from langchain_core.documents import Document
+from langchain_core.embeddings import Embeddings
+from langchain_core.retrievers import BaseRetriever, LangSmithRetrieverParams
+from langchain_core.runnables.config import run_in_executor
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Collection, Iterable, Iterator, Sequence
+
+ from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForRetrieverRun,
+ CallbackManagerForRetrieverRun,
+ )
+
+logger = logging.getLogger(__name__)
+
+VST = TypeVar("VST", bound="VectorStore")
+
+
+class VectorStore(ABC):
+ """Interface for vector store."""
+
+ def add_texts(
+ self,
+ texts: Iterable[str],
+ metadatas: list[dict] | None = None,
+ *,
+ ids: list[str] | None = None,
+ **kwargs: Any,
+ ) -> list[str]:
+ """Run more texts through the embeddings and add to the `VectorStore`.
+
+ Args:
+ texts: Iterable of strings to add to the `VectorStore`.
+ metadatas: Optional list of metadatas associated with the texts.
+ ids: Optional list of IDs associated with the texts.
+ **kwargs: `VectorStore` specific parameters.
+
+ One of the kwargs should be `ids` which is a list of ids
+ associated with the texts.
+
+ Returns:
+ List of IDs from adding the texts into the `VectorStore`.
+
+ Raises:
+ ValueError: If the number of metadatas does not match the number of texts.
+ ValueError: If the number of IDs does not match the number of texts.
+ """
+ if type(self).add_documents != VectorStore.add_documents:
+ # This condition is triggered if the subclass has provided
+ # an implementation of the upsert method.
+ # The existing add_texts
+ texts_: Sequence[str] = (
+ texts if isinstance(texts, (list, tuple)) else list(texts)
+ )
+ if metadatas and len(metadatas) != len(texts_):
+ msg = (
+ "The number of metadatas must match the number of texts."
+ f"Got {len(metadatas)} metadatas and {len(texts_)} texts."
+ )
+ raise ValueError(msg)
+ metadatas_ = iter(metadatas) if metadatas else cycle([{}])
+ ids_: Iterator[str | None] = iter(ids) if ids else cycle([None])
+ docs = [
+ Document(id=id_, page_content=text, metadata=metadata_)
+ for text, metadata_, id_ in zip(texts, metadatas_, ids_, strict=False)
+ ]
+ if ids is not None:
+ # For backward compatibility
+ kwargs["ids"] = ids
+
+ return self.add_documents(docs, **kwargs)
+ msg = f"`add_texts` has not been implemented for {self.__class__.__name__} "
+ raise NotImplementedError(msg)
+
+ @property
+ def embeddings(self) -> Embeddings | None:
+ """Access the query embedding object if available."""
+ logger.debug(
+ "The embeddings property has not been implemented for %s",
+ self.__class__.__name__,
+ )
+ return None
+
+ def delete(self, ids: list[str] | None = None, **kwargs: Any) -> bool | None:
+ """Delete by vector ID or other criteria.
+
+ Args:
+ ids: List of IDs to delete. If `None`, delete all.
+ **kwargs: Other keyword arguments that subclasses might use.
+
+ Returns:
+ `True` if deletion is successful, `False` otherwise, `None` if not
+ implemented.
+ """
+ msg = "delete method must be implemented by subclass."
+ raise NotImplementedError(msg)
+
+ def get_by_ids(self, ids: Sequence[str], /) -> list[Document]:
+ """Get documents by their IDs.
+
+ The returned documents are expected to have the ID field set to the ID of the
+ document in the vector store.
+
+ Fewer documents may be returned than requested if some IDs are not found or
+ if there are duplicated IDs.
+
+ Users should not assume that the order of the returned documents matches
+ the order of the input IDs. Instead, users should rely on the ID field of the
+ returned documents.
+
+ This method should **NOT** raise exceptions if no documents are found for
+ some IDs.
+
+ Args:
+ ids: List of IDs to retrieve.
+
+ Returns:
+ List of `Document` objects.
+ """
+ msg = f"{self.__class__.__name__} does not yet support get_by_ids."
+ raise NotImplementedError(msg)
+
+ # Implementations should override this method to provide an async native version.
+ async def aget_by_ids(self, ids: Sequence[str], /) -> list[Document]:
+ """Async get documents by their IDs.
+
+ The returned documents are expected to have the ID field set to the ID of the
+ document in the vector store.
+
+ Fewer documents may be returned than requested if some IDs are not found or
+ if there are duplicated IDs.
+
+ Users should not assume that the order of the returned documents matches
+ the order of the input IDs. Instead, users should rely on the ID field of the
+ returned documents.
+
+ This method should **NOT** raise exceptions if no documents are found for
+ some IDs.
+
+ Args:
+ ids: List of IDs to retrieve.
+
+ Returns:
+ List of `Document` objects.
+ """
+ return await run_in_executor(None, self.get_by_ids, ids)
+
+ async def adelete(self, ids: list[str] | None = None, **kwargs: Any) -> bool | None:
+ """Async delete by vector ID or other criteria.
+
+ Args:
+ ids: List of IDs to delete. If `None`, delete all.
+ **kwargs: Other keyword arguments that subclasses might use.
+
+ Returns:
+ `True` if deletion is successful, `False` otherwise, `None` if not
+ implemented.
+ """
+ return await run_in_executor(None, self.delete, ids, **kwargs)
+
+ async def aadd_texts(
+ self,
+ texts: Iterable[str],
+ metadatas: list[dict] | None = None,
+ *,
+ ids: list[str] | None = None,
+ **kwargs: Any,
+ ) -> list[str]:
+ """Async run more texts through the embeddings and add to the `VectorStore`.
+
+ Args:
+ texts: Iterable of strings to add to the `VectorStore`.
+ metadatas: Optional list of metadatas associated with the texts.
+ ids: Optional list
+ **kwargs: `VectorStore` specific parameters.
+
+ Returns:
+ List of IDs from adding the texts into the `VectorStore`.
+
+ Raises:
+ ValueError: If the number of metadatas does not match the number of texts.
+ ValueError: If the number of IDs does not match the number of texts.
+ """
+ if ids is not None:
+ # For backward compatibility
+ kwargs["ids"] = ids
+ if type(self).aadd_documents != VectorStore.aadd_documents:
+ # This condition is triggered if the subclass has provided
+ # an implementation of the upsert method.
+ # The existing add_texts
+ texts_: Sequence[str] = (
+ texts if isinstance(texts, (list, tuple)) else list(texts)
+ )
+ if metadatas and len(metadatas) != len(texts_):
+ msg = (
+ "The number of metadatas must match the number of texts."
+ f"Got {len(metadatas)} metadatas and {len(texts_)} texts."
+ )
+ raise ValueError(msg)
+ metadatas_ = iter(metadatas) if metadatas else cycle([{}])
+ ids_: Iterator[str | None] = iter(ids) if ids else cycle([None])
+
+ docs = [
+ Document(id=id_, page_content=text, metadata=metadata_)
+ for text, metadata_, id_ in zip(texts, metadatas_, ids_, strict=False)
+ ]
+ return await self.aadd_documents(docs, **kwargs)
+ return await run_in_executor(None, self.add_texts, texts, metadatas, **kwargs)
+
+ def add_documents(self, documents: list[Document], **kwargs: Any) -> list[str]:
+ """Add or update documents in the `VectorStore`.
+
+ Args:
+ documents: Documents to add to the `VectorStore`.
+ **kwargs: Additional keyword arguments.
+
+ If kwargs contains IDs and documents contain ids, the IDs in the kwargs
+ will receive precedence.
+
+ Returns:
+ List of IDs of the added texts.
+ """
+ if type(self).add_texts != VectorStore.add_texts:
+ if "ids" not in kwargs:
+ ids = [doc.id for doc in documents]
+
+ # If there's at least one valid ID, we'll assume that IDs
+ # should be used.
+ if any(ids):
+ kwargs["ids"] = ids
+
+ texts = [doc.page_content for doc in documents]
+ metadatas = [doc.metadata for doc in documents]
+ return self.add_texts(texts, metadatas, **kwargs)
+ msg = (
+ f"`add_documents` and `add_texts` has not been implemented "
+ f"for {self.__class__.__name__} "
+ )
+ raise NotImplementedError(msg)
+
+ async def aadd_documents(
+ self, documents: list[Document], **kwargs: Any
+ ) -> list[str]:
+ """Async run more documents through the embeddings and add to the `VectorStore`.
+
+ Args:
+ documents: Documents to add to the `VectorStore`.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ List of IDs of the added texts.
+ """
+ # If the async method has been overridden, we'll use that.
+ if type(self).aadd_texts != VectorStore.aadd_texts:
+ if "ids" not in kwargs:
+ ids = [doc.id for doc in documents]
+
+ # If there's at least one valid ID, we'll assume that IDs
+ # should be used.
+ if any(ids):
+ kwargs["ids"] = ids
+
+ texts = [doc.page_content for doc in documents]
+ metadatas = [doc.metadata for doc in documents]
+ return await self.aadd_texts(texts, metadatas, **kwargs)
+
+ return await run_in_executor(None, self.add_documents, documents, **kwargs)
+
+ def search(self, query: str, search_type: str, **kwargs: Any) -> list[Document]:
+ """Return docs most similar to query using a specified search type.
+
+ Args:
+ query: Input text.
+ search_type: Type of search to perform.
+
+ Can be `'similarity'`, `'mmr'`, or `'similarity_score_threshold'`.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects most similar to the query.
+
+ Raises:
+ ValueError: If `search_type` is not one of `'similarity'`,
+ `'mmr'`, or `'similarity_score_threshold'`.
+ """
+ if search_type == "similarity":
+ return self.similarity_search(query, **kwargs)
+ if search_type == "similarity_score_threshold":
+ docs_and_similarities = self.similarity_search_with_relevance_scores(
+ query, **kwargs
+ )
+ return [doc for doc, _ in docs_and_similarities]
+ if search_type == "mmr":
+ return self.max_marginal_relevance_search(query, **kwargs)
+ msg = (
+ f"search_type of {search_type} not allowed. Expected "
+ "search_type to be 'similarity', 'similarity_score_threshold'"
+ " or 'mmr'."
+ )
+ raise ValueError(msg)
+
+ async def asearch(
+ self, query: str, search_type: str, **kwargs: Any
+ ) -> list[Document]:
+ """Async return docs most similar to query using a specified search type.
+
+ Args:
+ query: Input text.
+ search_type: Type of search to perform.
+
+ Can be `'similarity'`, `'mmr'`, or `'similarity_score_threshold'`.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects most similar to the query.
+
+ Raises:
+ ValueError: If `search_type` is not one of `'similarity'`,
+ `'mmr'`, or `'similarity_score_threshold'`.
+ """
+ if search_type == "similarity":
+ return await self.asimilarity_search(query, **kwargs)
+ if search_type == "similarity_score_threshold":
+ docs_and_similarities = await self.asimilarity_search_with_relevance_scores(
+ query, **kwargs
+ )
+ return [doc for doc, _ in docs_and_similarities]
+ if search_type == "mmr":
+ return await self.amax_marginal_relevance_search(query, **kwargs)
+ msg = (
+ f"search_type of {search_type} not allowed. Expected "
+ "search_type to be 'similarity', 'similarity_score_threshold' or 'mmr'."
+ )
+ raise ValueError(msg)
+
+ @abstractmethod
+ def similarity_search(
+ self, query: str, k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ """Return docs most similar to query.
+
+ Args:
+ query: Input text.
+ k: Number of `Document` objects to return.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects most similar to the query.
+ """
+
+ @staticmethod
+ def _euclidean_relevance_score_fn(distance: float) -> float:
+ """Return a similarity score on a scale [0, 1]."""
+ # The 'correct' relevance function
+ # may differ depending on a few things, including:
+ # - the distance / similarity metric used by the VectorStore
+ # - the scale of your embeddings (OpenAI's are unit normed. Many
+ # others are not!)
+ # - embedding dimensionality
+ # - etc.
+ # This function converts the Euclidean norm of normalized embeddings
+ # (0 is most similar, sqrt(2) most dissimilar)
+ # to a similarity function (0 to 1)
+ return 1.0 - distance / math.sqrt(2)
+
+ @staticmethod
+ def _cosine_relevance_score_fn(distance: float) -> float:
+ """Normalize the distance to a score on a scale [0, 1]."""
+ return 1.0 - distance
+
+ @staticmethod
+ def _max_inner_product_relevance_score_fn(distance: float) -> float:
+ """Normalize the distance to a score on a scale [0, 1]."""
+ if distance > 0:
+ return 1.0 - distance
+
+ return -1.0 * distance
+
+ def _select_relevance_score_fn(self) -> Callable[[float], float]:
+ """The 'correct' relevance function.
+
+ May differ depending on a few things, including:
+
+ - The distance / similarity metric used by the VectorStore
+ - The scale of your embeddings (OpenAI's are unit normed. Many others are not!)
+ - Embedding dimensionality
+ - etc.
+
+ Vectorstores should define their own selection-based method of relevance.
+ """
+ raise NotImplementedError
+
+ def similarity_search_with_score(
+ self, *args: Any, **kwargs: Any
+ ) -> list[tuple[Document, float]]:
+ """Run similarity search with distance.
+
+ Args:
+ *args: Arguments to pass to the search method.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of tuples of `(doc, similarity_score)`.
+ """
+ raise NotImplementedError
+
+ async def asimilarity_search_with_score(
+ self, *args: Any, **kwargs: Any
+ ) -> list[tuple[Document, float]]:
+ """Async run similarity search with distance.
+
+ Args:
+ *args: Arguments to pass to the search method.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of tuples of `(doc, similarity_score)`.
+ """
+ # This is a temporary workaround to make the similarity search
+ # asynchronous. The proper solution is to make the similarity search
+ # asynchronous in the vector store implementations.
+ return await run_in_executor(
+ None, self.similarity_search_with_score, *args, **kwargs
+ )
+
+ def _similarity_search_with_relevance_scores(
+ self,
+ query: str,
+ k: int = 4,
+ **kwargs: Any,
+ ) -> list[tuple[Document, float]]:
+ """Default similarity search with relevance scores.
+
+ Modify if necessary in subclass.
+ Return docs and relevance scores in the range `[0, 1]`.
+
+ `0` is dissimilar, `1` is most similar.
+
+ Args:
+ query: Input text.
+ k: Number of `Document` objects to return.
+ **kwargs: Kwargs to be passed to similarity search.
+
+ Should include `score_threshold`, an optional floating point value
+ between `0` to `1` to filter the resulting set of retrieved docs.
+
+ Returns:
+ List of tuples of `(doc, similarity_score)`
+ """
+ relevance_score_fn = self._select_relevance_score_fn()
+ docs_and_scores = self.similarity_search_with_score(query, k, **kwargs)
+ return [(doc, relevance_score_fn(score)) for doc, score in docs_and_scores]
+
+ async def _asimilarity_search_with_relevance_scores(
+ self,
+ query: str,
+ k: int = 4,
+ **kwargs: Any,
+ ) -> list[tuple[Document, float]]:
+ """Default similarity search with relevance scores.
+
+ Modify if necessary in subclass.
+ Return docs and relevance scores in the range `[0, 1]`.
+
+ `0` is dissimilar, `1` is most similar.
+
+ Args:
+ query: Input text.
+ k: Number of `Document` objects to return.
+ **kwargs: Kwargs to be passed to similarity search.
+
+ Should include `score_threshold`, an optional floating point value
+ between `0` to `1` to filter the resulting set of retrieved docs.
+
+ Returns:
+ List of tuples of `(doc, similarity_score)`
+ """
+ relevance_score_fn = self._select_relevance_score_fn()
+ docs_and_scores = await self.asimilarity_search_with_score(query, k, **kwargs)
+ return [(doc, relevance_score_fn(score)) for doc, score in docs_and_scores]
+
+ def similarity_search_with_relevance_scores(
+ self,
+ query: str,
+ k: int = 4,
+ **kwargs: Any,
+ ) -> list[tuple[Document, float]]:
+ """Return docs and relevance scores in the range `[0, 1]`.
+
+ `0` is dissimilar, `1` is most similar.
+
+ Args:
+ query: Input text.
+ k: Number of `Document` objects to return.
+ **kwargs: Kwargs to be passed to similarity search.
+
+ Should include `score_threshold`, an optional floating point value
+ between `0` to `1` to filter the resulting set of retrieved docs.
+
+ Returns:
+ List of tuples of `(doc, similarity_score)`.
+ """
+ score_threshold = kwargs.pop("score_threshold", None)
+
+ docs_and_similarities = self._similarity_search_with_relevance_scores(
+ query, k=k, **kwargs
+ )
+ if any(
+ similarity < 0.0 or similarity > 1.0
+ for _, similarity in docs_and_similarities
+ ):
+ warnings.warn(
+ "Relevance scores must be between"
+ f" 0 and 1, got {docs_and_similarities}",
+ stacklevel=2,
+ )
+
+ if score_threshold is not None:
+ docs_and_similarities = [
+ (doc, similarity)
+ for doc, similarity in docs_and_similarities
+ if similarity >= score_threshold
+ ]
+ if len(docs_and_similarities) == 0:
+ logger.warning(
+ "No relevant docs were retrieved using the "
+ "relevance score threshold %s",
+ score_threshold,
+ )
+ return docs_and_similarities
+
+ async def asimilarity_search_with_relevance_scores(
+ self,
+ query: str,
+ k: int = 4,
+ **kwargs: Any,
+ ) -> list[tuple[Document, float]]:
+ """Async return docs and relevance scores in the range `[0, 1]`.
+
+ `0` is dissimilar, `1` is most similar.
+
+ Args:
+ query: Input text.
+ k: Number of `Document` objects to return.
+ **kwargs: Kwargs to be passed to similarity search.
+
+ Should include `score_threshold`, an optional floating point value
+ between `0` to `1` to filter the resulting set of retrieved docs.
+
+ Returns:
+ List of tuples of `(doc, similarity_score)`
+ """
+ score_threshold = kwargs.pop("score_threshold", None)
+
+ docs_and_similarities = await self._asimilarity_search_with_relevance_scores(
+ query, k=k, **kwargs
+ )
+ if any(
+ similarity < 0.0 or similarity > 1.0
+ for _, similarity in docs_and_similarities
+ ):
+ warnings.warn(
+ "Relevance scores must be between"
+ f" 0 and 1, got {docs_and_similarities}",
+ stacklevel=2,
+ )
+
+ if score_threshold is not None:
+ docs_and_similarities = [
+ (doc, similarity)
+ for doc, similarity in docs_and_similarities
+ if similarity >= score_threshold
+ ]
+ if len(docs_and_similarities) == 0:
+ logger.warning(
+ "No relevant docs were retrieved using the "
+ "relevance score threshold %s",
+ score_threshold,
+ )
+ return docs_and_similarities
+
+ async def asimilarity_search(
+ self, query: str, k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ """Async return docs most similar to query.
+
+ Args:
+ query: Input text.
+ k: Number of `Document` objects to return.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects most similar to the query.
+ """
+ # This is a temporary workaround to make the similarity search
+ # asynchronous. The proper solution is to make the similarity search
+ # asynchronous in the vector store implementations.
+ return await run_in_executor(None, self.similarity_search, query, k=k, **kwargs)
+
+ def similarity_search_by_vector(
+ self, embedding: list[float], k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ """Return docs most similar to embedding vector.
+
+ Args:
+ embedding: Embedding to look up documents similar to.
+ k: Number of `Document` objects to return.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects most similar to the query vector.
+ """
+ raise NotImplementedError
+
+ async def asimilarity_search_by_vector(
+ self, embedding: list[float], k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ """Async return docs most similar to embedding vector.
+
+ Args:
+ embedding: Embedding to look up documents similar to.
+ k: Number of `Document` objects to return.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects most similar to the query vector.
+ """
+ # This is a temporary workaround to make the similarity search
+ # asynchronous. The proper solution is to make the similarity search
+ # asynchronous in the vector store implementations.
+ return await run_in_executor(
+ None, self.similarity_search_by_vector, embedding, k=k, **kwargs
+ )
+
+ def max_marginal_relevance_search(
+ self,
+ query: str,
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ **kwargs: Any,
+ ) -> list[Document]:
+ """Return docs selected using the maximal marginal relevance.
+
+ Maximal marginal relevance optimizes for similarity to query AND diversity
+ among selected documents.
+
+ Args:
+ query: Text to look up documents similar to.
+ k: Number of `Document` objects to return.
+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
+ lambda_mult: Number between `0` and `1` that determines the degree of
+ diversity among the results with `0` corresponding to maximum diversity
+ and `1` to minimum diversity.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects selected by maximal marginal relevance.
+ """
+ raise NotImplementedError
+
+ async def amax_marginal_relevance_search(
+ self,
+ query: str,
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ **kwargs: Any,
+ ) -> list[Document]:
+ """Async return docs selected using the maximal marginal relevance.
+
+ Maximal marginal relevance optimizes for similarity to query AND diversity
+ among selected documents.
+
+ Args:
+ query: Text to look up documents similar to.
+ k: Number of `Document` objects to return.
+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
+ lambda_mult: Number between `0` and `1` that determines the degree of
+ diversity among the results with `0` corresponding to maximum diversity
+ and `1` to minimum diversity.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects selected by maximal marginal relevance.
+ """
+ # This is a temporary workaround to make the similarity search
+ # asynchronous. The proper solution is to make the similarity search
+ # asynchronous in the vector store implementations.
+ return await run_in_executor(
+ None,
+ self.max_marginal_relevance_search,
+ query,
+ k=k,
+ fetch_k=fetch_k,
+ lambda_mult=lambda_mult,
+ **kwargs,
+ )
+
+ def max_marginal_relevance_search_by_vector(
+ self,
+ embedding: list[float],
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ **kwargs: Any,
+ ) -> list[Document]:
+ """Return docs selected using the maximal marginal relevance.
+
+ Maximal marginal relevance optimizes for similarity to query AND diversity
+ among selected documents.
+
+ Args:
+ embedding: Embedding to look up documents similar to.
+ k: Number of `Document` objects to return.
+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
+ lambda_mult: Number between `0` and `1` that determines the degree of
+ diversity among the results with `0` corresponding to maximum diversity
+ and `1` to minimum diversity.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects selected by maximal marginal relevance.
+ """
+ raise NotImplementedError
+
+ async def amax_marginal_relevance_search_by_vector(
+ self,
+ embedding: list[float],
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ **kwargs: Any,
+ ) -> list[Document]:
+ """Async return docs selected using the maximal marginal relevance.
+
+ Maximal marginal relevance optimizes for similarity to query AND diversity
+ among selected documents.
+
+ Args:
+ embedding: Embedding to look up documents similar to.
+ k: Number of `Document` objects to return.
+ fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
+ lambda_mult: Number between `0` and `1` that determines the degree of
+ diversity among the results with `0` corresponding to maximum diversity
+ and `1` to minimum diversity.
+ **kwargs: Arguments to pass to the search method.
+
+ Returns:
+ List of `Document` objects selected by maximal marginal relevance.
+ """
+ return await run_in_executor(
+ None,
+ self.max_marginal_relevance_search_by_vector,
+ embedding,
+ k=k,
+ fetch_k=fetch_k,
+ lambda_mult=lambda_mult,
+ **kwargs,
+ )
+
+ @classmethod
+ def from_documents(
+ cls,
+ documents: list[Document],
+ embedding: Embeddings,
+ **kwargs: Any,
+ ) -> Self:
+ """Return `VectorStore` initialized from documents and embeddings.
+
+ Args:
+ documents: List of `Document` objects to add to the `VectorStore`.
+ embedding: Embedding function to use.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ `VectorStore` initialized from documents and embeddings.
+ """
+ texts = [d.page_content for d in documents]
+ metadatas = [d.metadata for d in documents]
+
+ if "ids" not in kwargs:
+ ids = [doc.id for doc in documents]
+
+ # If there's at least one valid ID, we'll assume that IDs
+ # should be used.
+ if any(ids):
+ kwargs["ids"] = ids
+
+ return cls.from_texts(texts, embedding, metadatas=metadatas, **kwargs)
+
+ @classmethod
+ async def afrom_documents(
+ cls,
+ documents: list[Document],
+ embedding: Embeddings,
+ **kwargs: Any,
+ ) -> Self:
+ """Async return `VectorStore` initialized from documents and embeddings.
+
+ Args:
+ documents: List of `Document` objects to add to the `VectorStore`.
+ embedding: Embedding function to use.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ `VectorStore` initialized from documents and embeddings.
+ """
+ texts = [d.page_content for d in documents]
+ metadatas = [d.metadata for d in documents]
+
+ if "ids" not in kwargs:
+ ids = [doc.id for doc in documents]
+
+ # If there's at least one valid ID, we'll assume that IDs
+ # should be used.
+ if any(ids):
+ kwargs["ids"] = ids
+
+ return await cls.afrom_texts(texts, embedding, metadatas=metadatas, **kwargs)
+
+ @classmethod
+ @abstractmethod
+ def from_texts(
+ cls: type[VST],
+ texts: list[str],
+ embedding: Embeddings,
+ metadatas: list[dict] | None = None,
+ *,
+ ids: list[str] | None = None,
+ **kwargs: Any,
+ ) -> VST:
+ """Return `VectorStore` initialized from texts and embeddings.
+
+ Args:
+ texts: Texts to add to the `VectorStore`.
+ embedding: Embedding function to use.
+ metadatas: Optional list of metadatas associated with the texts.
+ ids: Optional list of IDs associated with the texts.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ `VectorStore` initialized from texts and embeddings.
+ """
+
+ @classmethod
+ async def afrom_texts(
+ cls,
+ texts: list[str],
+ embedding: Embeddings,
+ metadatas: list[dict] | None = None,
+ *,
+ ids: list[str] | None = None,
+ **kwargs: Any,
+ ) -> Self:
+ """Async return `VectorStore` initialized from texts and embeddings.
+
+ Args:
+ texts: Texts to add to the `VectorStore`.
+ embedding: Embedding function to use.
+ metadatas: Optional list of metadatas associated with the texts.
+ ids: Optional list of IDs associated with the texts.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ `VectorStore` initialized from texts and embeddings.
+ """
+ if ids is not None:
+ kwargs["ids"] = ids
+ return await run_in_executor(
+ None, cls.from_texts, texts, embedding, metadatas, **kwargs
+ )
+
+ def _get_retriever_tags(self) -> list[str]:
+ """Get tags for retriever."""
+ tags = [self.__class__.__name__]
+ if self.embeddings:
+ tags.append(self.embeddings.__class__.__name__)
+ return tags
+
+ def as_retriever(self, **kwargs: Any) -> VectorStoreRetriever:
+ """Return `VectorStoreRetriever` initialized from this `VectorStore`.
+
+ Args:
+ **kwargs: Keyword arguments to pass to the search function.
+
+ Can include:
+
+ * `search_type`: Defines the type of search that the Retriever should
+ perform. Can be `'similarity'` (default), `'mmr'`, or
+ `'similarity_score_threshold'`.
+ * `search_kwargs`: Keyword arguments to pass to the search function.
+
+ Can include things like:
+
+ * `k`: Amount of documents to return (Default: `4`)
+ * `score_threshold`: Minimum relevance threshold
+ for `similarity_score_threshold`
+ * `fetch_k`: Amount of documents to pass to MMR algorithm
+ (Default: `20`)
+ * `lambda_mult`: Diversity of results returned by MMR;
+ `1` for minimum diversity and 0 for maximum. (Default: `0.5`)
+ * `filter`: Filter by document metadata
+
+ Returns:
+ Retriever class for `VectorStore`.
+
+ Examples:
+ ```python
+ # Retrieve more documents with higher diversity
+ # Useful if your dataset has many similar documents
+ docsearch.as_retriever(
+ search_type="mmr", search_kwargs={"k": 6, "lambda_mult": 0.25}
+ )
+
+ # Fetch more documents for the MMR algorithm to consider
+ # But only return the top 5
+ docsearch.as_retriever(search_type="mmr", search_kwargs={"k": 5, "fetch_k": 50})
+
+ # Only retrieve documents that have a relevance score
+ # Above a certain threshold
+ docsearch.as_retriever(
+ search_type="similarity_score_threshold",
+ search_kwargs={"score_threshold": 0.8},
+ )
+
+ # Only get the single most similar document from the dataset
+ docsearch.as_retriever(search_kwargs={"k": 1})
+
+ # Use a filter to only retrieve documents from a specific paper
+ docsearch.as_retriever(
+ search_kwargs={"filter": {"paper_title": "GPT-4 Technical Report"}}
+ )
+ ```
+ """
+ tags = kwargs.pop("tags", None) or [*self._get_retriever_tags()]
+ return VectorStoreRetriever(vectorstore=self, tags=tags, **kwargs)
+
+
+class VectorStoreRetriever(BaseRetriever):
+ """Base Retriever class for VectorStore."""
+
+ vectorstore: VectorStore
+ """VectorStore to use for retrieval."""
+
+ search_type: str = "similarity"
+ """Type of search to perform."""
+
+ search_kwargs: dict = Field(default_factory=dict)
+ """Keyword arguments to pass to the search function."""
+
+ allowed_search_types: ClassVar[Collection[str]] = (
+ "similarity",
+ "similarity_score_threshold",
+ "mmr",
+ )
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def validate_search_type(cls, values: dict) -> Any:
+ """Validate search type.
+
+ Args:
+ values: Values to validate.
+
+ Returns:
+ Validated values.
+
+ Raises:
+ ValueError: If `search_type` is not one of the allowed search types.
+ ValueError: If `score_threshold` is not specified with a float value(`0~1`)
+ """
+ search_type = values.get("search_type", "similarity")
+ if search_type not in cls.allowed_search_types:
+ msg = (
+ f"search_type of {search_type} not allowed. Valid values are: "
+ f"{cls.allowed_search_types}"
+ )
+ raise ValueError(msg)
+ if search_type == "similarity_score_threshold":
+ score_threshold = values.get("search_kwargs", {}).get("score_threshold")
+ if (score_threshold is None) or (not isinstance(score_threshold, float)):
+ msg = (
+ "`score_threshold` is not specified with a float value(0~1) "
+ "in `search_kwargs`."
+ )
+ raise ValueError(msg)
+ return values
+
+ def _get_ls_params(self, **kwargs: Any) -> LangSmithRetrieverParams:
+ """Get standard params for tracing."""
+ kwargs_ = self.search_kwargs | kwargs
+
+ ls_params = super()._get_ls_params(**kwargs_)
+
+ ls_params["ls_vector_store_provider"] = self.vectorstore.__class__.__name__
+
+ if self.vectorstore.embeddings:
+ ls_params["ls_embedding_provider"] = (
+ self.vectorstore.embeddings.__class__.__name__
+ )
+ elif hasattr(self.vectorstore, "embedding") and isinstance(
+ self.vectorstore.embedding, Embeddings
+ ):
+ ls_params["ls_embedding_provider"] = (
+ self.vectorstore.embedding.__class__.__name__
+ )
+
+ return ls_params
+
+ @override
+ def _get_relevant_documents(
+ self, query: str, *, run_manager: CallbackManagerForRetrieverRun, **kwargs: Any
+ ) -> list[Document]:
+ kwargs_ = self.search_kwargs | kwargs
+ if self.search_type == "similarity":
+ docs = self.vectorstore.similarity_search(query, **kwargs_)
+ elif self.search_type == "similarity_score_threshold":
+ docs_and_similarities = (
+ self.vectorstore.similarity_search_with_relevance_scores(
+ query, **kwargs_
+ )
+ )
+ docs = [doc for doc, _ in docs_and_similarities]
+ elif self.search_type == "mmr":
+ docs = self.vectorstore.max_marginal_relevance_search(query, **kwargs_)
+ else:
+ msg = f"search_type of {self.search_type} not allowed."
+ raise ValueError(msg)
+ return docs
+
+ @override
+ async def _aget_relevant_documents(
+ self,
+ query: str,
+ *,
+ run_manager: AsyncCallbackManagerForRetrieverRun,
+ **kwargs: Any,
+ ) -> list[Document]:
+ kwargs_ = self.search_kwargs | kwargs
+ if self.search_type == "similarity":
+ docs = await self.vectorstore.asimilarity_search(query, **kwargs_)
+ elif self.search_type == "similarity_score_threshold":
+ docs_and_similarities = (
+ await self.vectorstore.asimilarity_search_with_relevance_scores(
+ query, **kwargs_
+ )
+ )
+ docs = [doc for doc, _ in docs_and_similarities]
+ elif self.search_type == "mmr":
+ docs = await self.vectorstore.amax_marginal_relevance_search(
+ query, **kwargs_
+ )
+ else:
+ msg = f"search_type of {self.search_type} not allowed."
+ raise ValueError(msg)
+ return docs
+
+ def add_documents(self, documents: list[Document], **kwargs: Any) -> list[str]:
+ """Add documents to the `VectorStore`.
+
+ Args:
+ documents: Documents to add to the `VectorStore`.
+ **kwargs: Other keyword arguments that subclasses might use.
+
+ Returns:
+ List of IDs of the added texts.
+ """
+ return self.vectorstore.add_documents(documents, **kwargs)
+
+ async def aadd_documents(
+ self, documents: list[Document], **kwargs: Any
+ ) -> list[str]:
+ """Async add documents to the `VectorStore`.
+
+ Args:
+ documents: Documents to add to the `VectorStore`.
+ **kwargs: Other keyword arguments that subclasses might use.
+
+ Returns:
+ List of IDs of the added texts.
+ """
+ return await self.vectorstore.aadd_documents(documents, **kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/in_memory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/in_memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef3c78ab603f6c00c2a6107f89e55487a6f626c7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/in_memory.py
@@ -0,0 +1,546 @@
+"""In-memory vector store."""
+
+from __future__ import annotations
+
+import json
+import uuid
+from pathlib import Path
+from typing import (
+ TYPE_CHECKING,
+ Any,
+)
+
+from typing_extensions import override
+
+from langchain_core.documents import Document
+from langchain_core.load import dumpd, load
+from langchain_core.vectorstores import VectorStore
+from langchain_core.vectorstores.utils import _cosine_similarity as cosine_similarity
+from langchain_core.vectorstores.utils import maximal_marginal_relevance
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Iterator, Sequence
+
+ from langchain_core.embeddings import Embeddings
+
+try:
+ import numpy as np
+
+ _HAS_NUMPY = True
+except ImportError:
+ _HAS_NUMPY = False
+
+
+class InMemoryVectorStore(VectorStore):
+ """In-memory vector store implementation.
+
+ Uses a dictionary, and computes cosine similarity for search using numpy.
+
+ Setup:
+ Install `langchain-core`.
+
+ ```bash
+ pip install -U langchain-core
+ ```
+
+ Key init args — indexing params:
+
+ * embedding_function: Embeddings
+ Embedding function to use.
+
+ Instantiate:
+ ```python
+ from langchain_core.vectorstores import InMemoryVectorStore
+ from langchain_openai import OpenAIEmbeddings
+
+ vector_store = InMemoryVectorStore(OpenAIEmbeddings())
+ ```
+
+ Add Documents:
+ ```python
+ from langchain_core.documents import Document
+
+ document_1 = Document(id="1", page_content="foo", metadata={"baz": "bar"})
+ document_2 = Document(id="2", page_content="thud", metadata={"bar": "baz"})
+ document_3 = Document(id="3", page_content="i will be deleted :(")
+
+ documents = [document_1, document_2, document_3]
+ vector_store.add_documents(documents=documents)
+ ```
+
+ Inspect documents:
+ ```python
+ top_n = 10
+ for index, (id, doc) in enumerate(vector_store.store.items()):
+ if index < top_n:
+ # docs have keys 'id', 'vector', 'text', 'metadata'
+ print(f"{id}: {doc['text']}")
+ else:
+ break
+ ```
+
+ Delete Documents:
+ ```python
+ vector_store.delete(ids=["3"])
+ ```
+
+ Search:
+ ```python
+ results = vector_store.similarity_search(query="thud", k=1)
+ for doc in results:
+ print(f"* {doc.page_content} [{doc.metadata}]")
+ ```
+
+ ```txt
+ * thud [{'bar': 'baz'}]
+ ```
+
+ Search with filter:
+ ```python
+ def _filter_function(doc: Document) -> bool:
+ return doc.metadata.get("bar") == "baz"
+
+
+ results = vector_store.similarity_search(
+ query="thud", k=1, filter=_filter_function
+ )
+ for doc in results:
+ print(f"* {doc.page_content} [{doc.metadata}]")
+ ```
+
+ ```txt
+ * thud [{'bar': 'baz'}]
+ ```
+
+ Search with score:
+ ```python
+ results = vector_store.similarity_search_with_score(query="qux", k=1)
+ for doc, score in results:
+ print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")
+ ```
+
+ ```txt
+ * [SIM=0.832268] foo [{'baz': 'bar'}]
+ ```
+
+ Async:
+ ```python
+ # add documents
+ # await vector_store.aadd_documents(documents=documents)
+
+ # delete documents
+ # await vector_store.adelete(ids=["3"])
+
+ # search
+ # results = vector_store.asimilarity_search(query="thud", k=1)
+
+ # search with score
+ results = await vector_store.asimilarity_search_with_score(query="qux", k=1)
+ for doc, score in results:
+ print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")
+ ```
+
+ ```txt
+ * [SIM=0.832268] foo [{'baz': 'bar'}]
+ ```
+
+ Use as Retriever:
+ ```python
+ retriever = vector_store.as_retriever(
+ search_type="mmr",
+ search_kwargs={"k": 1, "fetch_k": 2, "lambda_mult": 0.5},
+ )
+ retriever.invoke("thud")
+ ```
+
+ ```txt
+ [Document(id='2', metadata={'bar': 'baz'}, page_content='thud')]
+ ```
+ """
+
+ def __init__(self, embedding: Embeddings) -> None:
+ """Initialize with the given embedding function.
+
+ Args:
+ embedding: embedding function to use.
+ """
+ # TODO: would be nice to change to
+ # dict[str, Document] at some point (will be a breaking change)
+ self.store: dict[str, dict[str, Any]] = {}
+ self.embedding = embedding
+
+ @property
+ @override
+ def embeddings(self) -> Embeddings:
+ return self.embedding
+
+ @override
+ def delete(self, ids: Sequence[str] | None = None, **kwargs: Any) -> None:
+ if ids:
+ for id_ in ids:
+ self.store.pop(id_, None)
+
+ @override
+ async def adelete(self, ids: Sequence[str] | None = None, **kwargs: Any) -> None:
+ self.delete(ids)
+
+ @override
+ def add_documents(
+ self,
+ documents: list[Document],
+ ids: list[str] | None = None,
+ **kwargs: Any,
+ ) -> list[str]:
+ texts = [doc.page_content for doc in documents]
+ vectors = self.embedding.embed_documents(texts)
+
+ if ids and len(ids) != len(texts):
+ msg = (
+ f"ids must be the same length as texts. "
+ f"Got {len(ids)} ids and {len(texts)} texts."
+ )
+ raise ValueError(msg)
+
+ id_iterator: Iterator[str | None] = (
+ iter(ids) if ids else iter(doc.id for doc in documents)
+ )
+
+ ids_ = []
+
+ for doc, vector in zip(documents, vectors, strict=False):
+ doc_id = next(id_iterator)
+ doc_id_ = doc_id or str(uuid.uuid4())
+ ids_.append(doc_id_)
+ self.store[doc_id_] = {
+ "id": doc_id_,
+ "vector": vector,
+ "text": doc.page_content,
+ "metadata": doc.metadata,
+ }
+
+ return ids_
+
+ @override
+ async def aadd_documents(
+ self, documents: list[Document], ids: list[str] | None = None, **kwargs: Any
+ ) -> list[str]:
+ texts = [doc.page_content for doc in documents]
+ vectors = await self.embedding.aembed_documents(texts)
+
+ if ids and len(ids) != len(texts):
+ msg = (
+ f"ids must be the same length as texts. "
+ f"Got {len(ids)} ids and {len(texts)} texts."
+ )
+ raise ValueError(msg)
+
+ id_iterator: Iterator[str | None] = (
+ iter(ids) if ids else iter(doc.id for doc in documents)
+ )
+ ids_: list[str] = []
+
+ for doc, vector in zip(documents, vectors, strict=False):
+ doc_id = next(id_iterator)
+ doc_id_ = doc_id or str(uuid.uuid4())
+ ids_.append(doc_id_)
+ self.store[doc_id_] = {
+ "id": doc_id_,
+ "vector": vector,
+ "text": doc.page_content,
+ "metadata": doc.metadata,
+ }
+
+ return ids_
+
+ @override
+ def get_by_ids(self, ids: Sequence[str], /) -> list[Document]:
+ """Get documents by their ids.
+
+ Args:
+ ids: The IDs of the documents to get.
+
+ Returns:
+ A list of `Document` objects.
+ """
+ documents = []
+
+ for doc_id in ids:
+ doc = self.store.get(doc_id)
+ if doc:
+ documents.append(
+ Document(
+ id=doc["id"],
+ page_content=doc["text"],
+ metadata=doc["metadata"],
+ )
+ )
+ return documents
+
+ @override
+ async def aget_by_ids(self, ids: Sequence[str], /) -> list[Document]:
+ """Async get documents by their ids.
+
+ Args:
+ ids: The IDs of the documents to get.
+
+ Returns:
+ A list of `Document` objects.
+ """
+ return self.get_by_ids(ids)
+
+ def _similarity_search_with_score_by_vector(
+ self,
+ embedding: list[float],
+ k: int = 4,
+ filter: Callable[[Document], bool] | None = None, # noqa: A002
+ ) -> list[tuple[Document, float, list[float]]]:
+ # Get all docs with fixed order in list
+ docs = list(self.store.values())
+
+ if filter is not None:
+ docs = [
+ doc
+ for doc in docs
+ if filter(
+ Document(
+ id=doc["id"], page_content=doc["text"], metadata=doc["metadata"]
+ )
+ )
+ ]
+
+ if not docs:
+ return []
+
+ similarity = cosine_similarity([embedding], [doc["vector"] for doc in docs])[0]
+
+ # Get the indices ordered by similarity score
+ top_k_idx = similarity.argsort()[::-1][:k]
+
+ return [
+ (
+ Document(
+ id=doc_dict["id"],
+ page_content=doc_dict["text"],
+ metadata=doc_dict["metadata"],
+ ),
+ float(similarity[idx].item()),
+ doc_dict["vector"],
+ )
+ for idx in top_k_idx
+ # Assign using walrus operator to avoid multiple lookups
+ if (doc_dict := docs[idx])
+ ]
+
+ def similarity_search_with_score_by_vector(
+ self,
+ embedding: list[float],
+ k: int = 4,
+ filter: Callable[[Document], bool] | None = None, # noqa: A002
+ **_kwargs: Any,
+ ) -> list[tuple[Document, float]]:
+ """Search for the most similar documents to the given embedding.
+
+ Args:
+ embedding: The embedding to search for.
+ k: The number of documents to return.
+ filter: A function to filter the documents.
+
+ Returns:
+ A list of tuples of `Document` objects and their similarity scores.
+ """
+ return [
+ (doc, similarity)
+ for doc, similarity, _ in self._similarity_search_with_score_by_vector(
+ embedding=embedding, k=k, filter=filter
+ )
+ ]
+
+ @override
+ def similarity_search_with_score(
+ self,
+ query: str,
+ k: int = 4,
+ **kwargs: Any,
+ ) -> list[tuple[Document, float]]:
+ embedding = self.embedding.embed_query(query)
+ return self.similarity_search_with_score_by_vector(
+ embedding,
+ k,
+ **kwargs,
+ )
+
+ @override
+ async def asimilarity_search_with_score(
+ self, query: str, k: int = 4, **kwargs: Any
+ ) -> list[tuple[Document, float]]:
+ embedding = await self.embedding.aembed_query(query)
+ return self.similarity_search_with_score_by_vector(
+ embedding,
+ k,
+ **kwargs,
+ )
+
+ @override
+ def similarity_search_by_vector(
+ self,
+ embedding: list[float],
+ k: int = 4,
+ **kwargs: Any,
+ ) -> list[Document]:
+ docs_and_scores = self.similarity_search_with_score_by_vector(
+ embedding,
+ k,
+ **kwargs,
+ )
+ return [doc for doc, _ in docs_and_scores]
+
+ @override
+ async def asimilarity_search_by_vector(
+ self, embedding: list[float], k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ return self.similarity_search_by_vector(embedding, k, **kwargs)
+
+ @override
+ def similarity_search(
+ self, query: str, k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ return [doc for doc, _ in self.similarity_search_with_score(query, k, **kwargs)]
+
+ @override
+ async def asimilarity_search(
+ self, query: str, k: int = 4, **kwargs: Any
+ ) -> list[Document]:
+ return [
+ doc
+ for doc, _ in await self.asimilarity_search_with_score(query, k, **kwargs)
+ ]
+
+ @override
+ def max_marginal_relevance_search_by_vector(
+ self,
+ embedding: list[float],
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ *,
+ filter: Callable[[Document], bool] | None = None,
+ **kwargs: Any,
+ ) -> list[Document]:
+ prefetch_hits = self._similarity_search_with_score_by_vector(
+ embedding=embedding,
+ k=fetch_k,
+ filter=filter,
+ )
+
+ if not _HAS_NUMPY:
+ msg = (
+ "numpy must be installed to use max_marginal_relevance_search "
+ "pip install numpy"
+ )
+ raise ImportError(msg)
+
+ mmr_chosen_indices = maximal_marginal_relevance(
+ np.array(embedding, dtype=np.float32),
+ [vector for _, _, vector in prefetch_hits],
+ k=k,
+ lambda_mult=lambda_mult,
+ )
+ return [prefetch_hits[idx][0] for idx in mmr_chosen_indices]
+
+ @override
+ def max_marginal_relevance_search(
+ self,
+ query: str,
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ **kwargs: Any,
+ ) -> list[Document]:
+ embedding_vector = self.embedding.embed_query(query)
+ return self.max_marginal_relevance_search_by_vector(
+ embedding_vector,
+ k,
+ fetch_k,
+ lambda_mult=lambda_mult,
+ **kwargs,
+ )
+
+ @override
+ async def amax_marginal_relevance_search(
+ self,
+ query: str,
+ k: int = 4,
+ fetch_k: int = 20,
+ lambda_mult: float = 0.5,
+ **kwargs: Any,
+ ) -> list[Document]:
+ embedding_vector = await self.embedding.aembed_query(query)
+ return self.max_marginal_relevance_search_by_vector(
+ embedding_vector,
+ k,
+ fetch_k,
+ lambda_mult=lambda_mult,
+ **kwargs,
+ )
+
+ @classmethod
+ @override
+ def from_texts(
+ cls,
+ texts: list[str],
+ embedding: Embeddings,
+ metadatas: list[dict] | None = None,
+ **kwargs: Any,
+ ) -> InMemoryVectorStore:
+ store = cls(
+ embedding=embedding,
+ )
+ store.add_texts(texts=texts, metadatas=metadatas, **kwargs)
+ return store
+
+ @classmethod
+ @override
+ async def afrom_texts(
+ cls,
+ texts: list[str],
+ embedding: Embeddings,
+ metadatas: list[dict] | None = None,
+ **kwargs: Any,
+ ) -> InMemoryVectorStore:
+ store = cls(
+ embedding=embedding,
+ )
+ await store.aadd_texts(texts=texts, metadatas=metadatas, **kwargs)
+ return store
+
+ @classmethod
+ def load(
+ cls, path: str, embedding: Embeddings, **kwargs: Any
+ ) -> InMemoryVectorStore:
+ """Load a vector store from a file.
+
+ Args:
+ path: The path to load the vector store from.
+ embedding: The embedding to use.
+ **kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ A `VectorStore` object.
+ """
+ path_: Path = Path(path)
+ with path_.open("r", encoding="utf-8") as f:
+ store = load(json.load(f), allowed_objects=[Document])
+ vectorstore = cls(embedding=embedding, **kwargs)
+ vectorstore.store = store
+ return vectorstore
+
+ def dump(self, path: str) -> None:
+ """Dump the vector store to a file.
+
+ Args:
+ path: The path to dump the vector store to.
+ """
+ path_: Path = Path(path)
+ path_.parent.mkdir(exist_ok=True, parents=True)
+ with path_.open("w", encoding="utf-8") as f:
+ json.dump(dumpd(self.store), f, indent=2)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..551524beb3bfbcfcf0cd7c7154100926d802ac29
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_core/vectorstores/utils.py
@@ -0,0 +1,157 @@
+"""Internal utilities for the in memory implementation of `VectorStore`.
+
+!!! warning
+
+ These are part of a private API, and users should not use them directly as they can
+ change without notice.
+"""
+
+from __future__ import annotations
+
+import logging
+import warnings
+from typing import TYPE_CHECKING, cast
+
+try:
+ import numpy as np
+
+ _HAS_NUMPY = True
+except ImportError:
+ _HAS_NUMPY = False
+
+try:
+ import simsimd as simd # type: ignore[import-not-found]
+
+ _HAS_SIMSIMD = True
+except ImportError:
+ _HAS_SIMSIMD = False
+
+if TYPE_CHECKING:
+ Matrix = list[list[float]] | list[np.ndarray] | np.ndarray
+
+logger = logging.getLogger(__name__)
+
+
+def _cosine_similarity(x: Matrix, y: Matrix) -> np.ndarray:
+ """Row-wise cosine similarity between two equal-width matrices.
+
+ Args:
+ x: A matrix of shape `(n, m)`.
+ y: A matrix of shape `(k, m)`.
+
+ Returns:
+ A matrix of shape `(n, k)` where each element `(i, j)` is the cosine similarity
+ between the `i`th row of `x` and the `j`th row of `y`.
+
+ Raises:
+ ValueError: If the number of columns in `x` and `y` are not the same.
+ ImportError: If numpy is not installed.
+ """
+ if not _HAS_NUMPY:
+ msg = (
+ "cosine_similarity requires numpy to be installed. "
+ "Please install numpy with `pip install numpy`."
+ )
+ raise ImportError(msg)
+
+ if len(x) == 0 or len(y) == 0:
+ return np.array([[]])
+
+ x = np.array(x)
+ y = np.array(y)
+
+ # Check for NaN
+ if np.any(np.isnan(x)) or np.any(np.isnan(y)):
+ warnings.warn(
+ "NaN found in input arrays, unexpected return might follow",
+ category=RuntimeWarning,
+ stacklevel=2,
+ )
+
+ # Check for Inf
+ if np.any(np.isinf(x)) or np.any(np.isinf(y)):
+ warnings.warn(
+ "Inf found in input arrays, unexpected return might follow",
+ category=RuntimeWarning,
+ stacklevel=2,
+ )
+
+ if x.shape[1] != y.shape[1]:
+ msg = (
+ f"Number of columns in X and Y must be the same. X has shape {x.shape} "
+ f"and Y has shape {y.shape}."
+ )
+ raise ValueError(msg)
+ if not _HAS_SIMSIMD:
+ logger.debug(
+ "Unable to import simsimd, defaulting to NumPy implementation. If you want "
+ "to use simsimd please install with `pip install simsimd`."
+ )
+ x_norm = np.linalg.norm(x, axis=1)
+ y_norm = np.linalg.norm(y, axis=1)
+ # Ignore divide by zero errors run time warnings as those are handled below.
+ with np.errstate(divide="ignore", invalid="ignore"):
+ similarity = np.dot(x, y.T) / np.outer(x_norm, y_norm)
+ if np.isnan(similarity).all():
+ msg = "NaN values found, please remove the NaN values and try again"
+ raise ValueError(msg) from None
+ similarity[np.isnan(similarity) | np.isinf(similarity)] = 0.0
+ return cast("np.ndarray", similarity)
+
+ x = np.array(x, dtype=np.float32)
+ y = np.array(y, dtype=np.float32)
+ return 1 - np.array(simd.cdist(x, y, metric="cosine"))
+
+
+def maximal_marginal_relevance(
+ query_embedding: np.ndarray,
+ embedding_list: list,
+ lambda_mult: float = 0.5,
+ k: int = 4,
+) -> list[int]:
+ """Calculate maximal marginal relevance.
+
+ Args:
+ query_embedding: The query embedding.
+ embedding_list: A list of embeddings.
+ lambda_mult: The lambda parameter for MMR.
+ k: The number of embeddings to return.
+
+ Returns:
+ A list of indices of the embeddings to return.
+
+ Raises:
+ ImportError: If numpy is not installed.
+ """
+ if not _HAS_NUMPY:
+ msg = (
+ "maximal_marginal_relevance requires numpy to be installed. "
+ "Please install numpy with `pip install numpy`."
+ )
+ raise ImportError(msg)
+
+ if min(k, len(embedding_list)) <= 0:
+ return []
+ if query_embedding.ndim == 1:
+ query_embedding = np.expand_dims(query_embedding, axis=0)
+ similarity_to_query = _cosine_similarity(query_embedding, embedding_list)[0]
+ most_similar = int(np.argmax(similarity_to_query))
+ idxs = [most_similar]
+ selected = np.array([embedding_list[most_similar]])
+ while len(idxs) < min(k, len(embedding_list)):
+ best_score = -np.inf
+ idx_to_add = -1
+ similarity_to_selected = _cosine_similarity(embedding_list, selected)
+ for i, query_score in enumerate(similarity_to_query):
+ if i in idxs:
+ continue
+ redundant_score = max(similarity_to_selected[i])
+ equation_score = (
+ lambda_mult * query_score - (1 - lambda_mult) * redundant_score
+ )
+ if equation_score > best_score:
+ best_score = equation_score
+ idx_to_add = i
+ idxs.append(idx_to_add)
+ selected = np.append(selected, [embedding_list[idx_to_add]], axis=0)
+ return idxs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface-1.2.2.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface-1.2.2.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..426b65090341f37bc64935cdc681cc8a8fb02a32
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface-1.2.2.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 LangChain, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d26e5400b62f2258e7be9b697c1dbea792f2e39
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/chat_models/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/chat_models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a01a77ac5cf6d9777be83fa7dcd7e86c439a4cdb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/chat_models/__init__.py
@@ -0,0 +1,8 @@
+from langchain_huggingface.chat_models.huggingface import ( # type: ignore[import-not-found]
+ TGI_MESSAGE,
+ TGI_RESPONSE,
+ ChatHuggingFace,
+ _convert_dict_to_message,
+)
+
+__all__ = ["TGI_MESSAGE", "TGI_RESPONSE", "ChatHuggingFace", "_convert_dict_to_message"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/chat_models/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/chat_models/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ad25fbd3fef4ceac888a2e499575b2a5f3c44b3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/chat_models/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/chat_models/__pycache__/huggingface.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/chat_models/__pycache__/huggingface.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..11c58c79523f2ec082b345404bdf222b0faa6bd4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/chat_models/__pycache__/huggingface.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/chat_models/huggingface.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/chat_models/huggingface.py
new file mode 100644
index 0000000000000000000000000000000000000000..52e9df5d34340da0d1bf7485cb1664992d9a4c5b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/chat_models/huggingface.py
@@ -0,0 +1,1245 @@
+"""Hugging Face Chat Wrapper."""
+
+from __future__ import annotations
+
+import contextlib
+import json
+from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
+from dataclasses import dataclass
+from operator import itemgetter
+from typing import TYPE_CHECKING, Any, Literal, cast
+
+if TYPE_CHECKING:
+ from langchain_huggingface.llms.huggingface_endpoint import HuggingFaceEndpoint
+ from langchain_huggingface.llms.huggingface_pipeline import HuggingFacePipeline
+
+from langchain_core.callbacks.manager import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models import (
+ LanguageModelInput,
+ ModelProfile,
+ ModelProfileRegistry,
+)
+from langchain_core.language_models.chat_models import (
+ BaseChatModel,
+ agenerate_from_stream,
+ generate_from_stream,
+)
+from langchain_core.messages import (
+ AIMessage,
+ AIMessageChunk,
+ BaseMessage,
+ BaseMessageChunk,
+ ChatMessage,
+ ChatMessageChunk,
+ FunctionMessage,
+ FunctionMessageChunk,
+ HumanMessage,
+ HumanMessageChunk,
+ InvalidToolCall,
+ SystemMessage,
+ SystemMessageChunk,
+ ToolCall,
+ ToolMessage,
+ ToolMessageChunk,
+)
+from langchain_core.messages.tool import ToolCallChunk
+from langchain_core.messages.tool import tool_call_chunk as create_tool_call_chunk
+from langchain_core.output_parsers import JsonOutputParser
+from langchain_core.output_parsers.openai_tools import (
+ JsonOutputKeyToolsParser,
+ make_invalid_tool_call,
+ parse_tool_call,
+)
+from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ ChatResult,
+ LLMResult,
+)
+from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
+from langchain_core.tools import BaseTool
+from langchain_core.utils.function_calling import (
+ convert_to_json_schema,
+ convert_to_openai_tool,
+)
+from langchain_core.utils.pydantic import is_basemodel_subclass
+from pydantic import BaseModel, Field, model_validator
+from typing_extensions import Self
+
+from langchain_huggingface.data._profiles import _PROFILES
+from langchain_huggingface.llms.huggingface_endpoint import HuggingFaceEndpoint
+from langchain_huggingface.llms.huggingface_pipeline import HuggingFacePipeline
+
+_MODEL_PROFILES = cast("ModelProfileRegistry", _PROFILES)
+
+
+def _get_default_model_profile(model_name: str) -> ModelProfile:
+ default = _MODEL_PROFILES.get(model_name) or {}
+ return default.copy()
+
+
+@dataclass
+class TGI_RESPONSE:
+ """Response from the TextGenInference API."""
+
+ choices: list[Any]
+ usage: dict
+
+
+@dataclass
+class TGI_MESSAGE:
+ """Message to send to the TextGenInference API."""
+
+ role: str
+ content: str
+ tool_calls: list[dict]
+
+
+def _lc_tool_call_to_hf_tool_call(tool_call: ToolCall) -> dict:
+ return {
+ "type": "function",
+ "id": tool_call["id"],
+ "function": {
+ "name": tool_call["name"],
+ "arguments": json.dumps(tool_call["args"], ensure_ascii=False),
+ },
+ }
+
+
+def _lc_invalid_tool_call_to_hf_tool_call(
+ invalid_tool_call: InvalidToolCall,
+) -> dict:
+ return {
+ "type": "function",
+ "id": invalid_tool_call["id"],
+ "function": {
+ "name": invalid_tool_call["name"],
+ "arguments": invalid_tool_call["args"],
+ },
+ }
+
+
+def _convert_message_to_dict(message: BaseMessage) -> dict:
+ """Convert a LangChain message to a dictionary.
+
+ Args:
+ message: The LangChain message.
+
+ Returns:
+ The dictionary.
+
+ """
+ message_dict: dict[str, Any]
+ if isinstance(message, ChatMessage):
+ message_dict = {"role": message.role, "content": message.content}
+ elif isinstance(message, HumanMessage):
+ message_dict = {"role": "user", "content": message.content}
+ elif isinstance(message, AIMessage):
+ message_dict = {"role": "assistant", "content": message.content}
+ if "function_call" in message.additional_kwargs:
+ message_dict["function_call"] = message.additional_kwargs["function_call"]
+ # If function call only, content is None not empty string
+ if message_dict["content"] == "":
+ message_dict["content"] = None
+ if message.tool_calls or message.invalid_tool_calls:
+ message_dict["tool_calls"] = [
+ _lc_tool_call_to_hf_tool_call(tc) for tc in message.tool_calls
+ ] + [
+ _lc_invalid_tool_call_to_hf_tool_call(tc)
+ for tc in message.invalid_tool_calls
+ ]
+ elif "tool_calls" in message.additional_kwargs:
+ message_dict["tool_calls"] = message.additional_kwargs["tool_calls"]
+ # If tool calls only, content is None not empty string
+ if "tool_calls" in message_dict and message_dict["content"] == "":
+ message_dict["content"] = None
+ else:
+ pass
+ elif isinstance(message, SystemMessage):
+ message_dict = {"role": "system", "content": message.content}
+ elif isinstance(message, FunctionMessage):
+ message_dict = {
+ "role": "function",
+ "content": message.content,
+ "name": message.name,
+ }
+ elif isinstance(message, ToolMessage):
+ message_dict = {
+ "role": "tool",
+ "content": message.content,
+ "tool_call_id": message.tool_call_id,
+ }
+ else:
+ msg = f"Got unknown type {message}"
+ raise TypeError(msg)
+ if "name" in message.additional_kwargs:
+ message_dict["name"] = message.additional_kwargs["name"]
+ return message_dict
+
+
+def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
+ """Convert a dictionary to a LangChain message.
+
+ Args:
+ _dict: The dictionary.
+
+ Returns:
+ The LangChain message.
+
+ """
+ role = _dict.get("role")
+ if role == "user":
+ return HumanMessage(content=_dict.get("content", ""))
+ if role == "assistant":
+ content = _dict.get("content", "") or ""
+ additional_kwargs: dict = {}
+ if function_call := _dict.get("function_call"):
+ additional_kwargs["function_call"] = dict(function_call)
+ tool_calls = []
+ invalid_tool_calls = []
+ if raw_tool_calls := _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ for raw_tool_call in raw_tool_calls:
+ try:
+ tool_calls.append(parse_tool_call(raw_tool_call, return_id=True))
+ except Exception as e:
+ invalid_tool_calls.append(
+ dict(make_invalid_tool_call(raw_tool_call, str(e)))
+ )
+ return AIMessage(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_calls=tool_calls,
+ invalid_tool_calls=invalid_tool_calls,
+ )
+ if role == "system":
+ return SystemMessage(content=_dict.get("content", ""))
+ if role == "function":
+ return FunctionMessage(
+ content=_dict.get("content", ""), name=_dict.get("name", "")
+ )
+ if role == "tool":
+ additional_kwargs = {}
+ if "name" in _dict:
+ additional_kwargs["name"] = _dict["name"]
+ return ToolMessage(
+ content=_dict.get("content", ""),
+ tool_call_id=_dict.get("tool_call_id", ""),
+ additional_kwargs=additional_kwargs,
+ )
+ return ChatMessage(content=_dict.get("content", ""), role=role or "")
+
+
+def _is_huggingface_hub(llm: Any) -> bool:
+ try:
+ from langchain_community.llms.huggingface_hub import (
+ HuggingFaceHub, # type: ignore[import-not-found]
+ )
+
+ return isinstance(llm, HuggingFaceHub)
+ except ImportError:
+ # if no langchain community, it is not a HuggingFaceHub
+ return False
+
+
+def _convert_chunk_to_message_chunk(
+ chunk: Mapping[str, Any], default_class: type[BaseMessageChunk]
+) -> BaseMessageChunk:
+ choice = chunk["choices"][0]
+ _dict = choice["delta"]
+ role = cast(str, _dict.get("role"))
+ content = cast(str, _dict.get("content") or "")
+ additional_kwargs: dict = {}
+ tool_call_chunks: list[ToolCallChunk] = []
+ if _dict.get("function_call"):
+ function_call = dict(_dict["function_call"])
+ if "name" in function_call and function_call["name"] is None:
+ function_call["name"] = ""
+ additional_kwargs["function_call"] = function_call
+ if raw_tool_calls := _dict.get("tool_calls"):
+ additional_kwargs["tool_calls"] = raw_tool_calls
+ for rtc in raw_tool_calls:
+ with contextlib.suppress(KeyError):
+ tool_call_chunks.append(
+ create_tool_call_chunk(
+ name=rtc["function"].get("name"),
+ args=rtc["function"].get("arguments"),
+ id=rtc.get("id"),
+ index=rtc.get("index"),
+ )
+ )
+ if role == "user" or default_class == HumanMessageChunk:
+ return HumanMessageChunk(content=content)
+ if role == "assistant" or default_class == AIMessageChunk:
+ if usage := chunk.get("usage"):
+ input_tokens = usage.get("prompt_tokens", 0)
+ output_tokens = usage.get("completion_tokens", 0)
+ usage_metadata = {
+ "input_tokens": input_tokens,
+ "output_tokens": output_tokens,
+ "total_tokens": usage.get("total_tokens", input_tokens + output_tokens),
+ }
+ else:
+ usage_metadata = None
+ return AIMessageChunk(
+ content=content,
+ additional_kwargs=additional_kwargs,
+ tool_call_chunks=tool_call_chunks,
+ usage_metadata=usage_metadata, # type: ignore[arg-type]
+ )
+ if role == "system" or default_class == SystemMessageChunk:
+ return SystemMessageChunk(content=content)
+ if role == "function" or default_class == FunctionMessageChunk:
+ return FunctionMessageChunk(content=content, name=_dict["name"])
+ if role == "tool" or default_class == ToolMessageChunk:
+ return ToolMessageChunk(content=content, tool_call_id=_dict["tool_call_id"])
+ if role or default_class == ChatMessageChunk:
+ return ChatMessageChunk(content=content, role=role)
+ return default_class(content=content) # type: ignore[call-arg]
+
+
+def _is_huggingface_textgen_inference(llm: Any) -> bool:
+ try:
+ from langchain_community.llms.huggingface_text_gen_inference import (
+ HuggingFaceTextGenInference, # type: ignore[import-not-found]
+ )
+
+ return isinstance(llm, HuggingFaceTextGenInference)
+ except ImportError:
+ # if no langchain community, it is not a HuggingFaceTextGenInference
+ return False
+
+
+def _is_huggingface_endpoint(llm: Any) -> bool:
+ return isinstance(llm, HuggingFaceEndpoint)
+
+
+def _is_huggingface_pipeline(llm: Any) -> bool:
+ return isinstance(llm, HuggingFacePipeline)
+
+
+class ChatHuggingFace(BaseChatModel):
+ r"""Hugging Face LLM's as ChatModels.
+
+ Works with `HuggingFaceTextGenInference`, `HuggingFaceEndpoint`,
+ `HuggingFaceHub`, and `HuggingFacePipeline` LLMs.
+
+ Upon instantiating this class, the model_id is resolved from the url
+ provided to the LLM, and the appropriate tokenizer is loaded from
+ the HuggingFace Hub.
+
+ Setup:
+ Install `langchain-huggingface` and ensure your Hugging Face token
+ is saved.
+
+ ```bash
+ pip install langchain-huggingface
+ ```
+
+ ```python
+ from huggingface_hub import login
+
+ login() # You will be prompted for your HF key, which will then be saved locally
+ ```
+
+ Key init args — completion params:
+ llm:
+ LLM to be used.
+
+ Key init args — client params:
+ custom_get_token_ids:
+ Optional encoder to use for counting tokens.
+ metadata:
+ Metadata to add to the run trace.
+ tags:
+ Tags to add to the run trace.
+ verbose:
+ Whether to print out response text.
+
+ See full list of supported init args and their descriptions in the params
+ section.
+
+ Instantiate:
+ ```python
+ from langchain_huggingface import HuggingFaceEndpoint,
+ ChatHuggingFace
+
+ model = HuggingFaceEndpoint(
+ repo_id="microsoft/Phi-3-mini-4k-instruct",
+ task="text-generation",
+ max_new_tokens=512,
+ do_sample=False,
+ repetition_penalty=1.03,
+ )
+
+ chat = ChatHuggingFace(llm=model, verbose=True)
+ ```
+
+ Invoke:
+ ```python
+ messages = [
+ ("system", "You are a helpful translator. Translate the user
+ sentence to French."),
+ ("human", "I love programming."),
+ ]
+
+ chat(...).invoke(messages)
+ ```
+
+ ```python
+ AIMessage(content='Je ai une passion pour le programme.\n\nIn
+ French, we use "ai" for masculine subjects and "a" for feminine
+ subjects. Since "programming" is gender-neutral in English, we
+ will go with the masculine "programme".\n\nConfirmation: "J\'aime
+ le programme." is more commonly used. The sentence above is
+ technically accurate, but less commonly used in spoken French as
+ "ai" is used less frequently in everyday speech.',
+ response_metadata={'token_usage': ChatCompletionOutputUsage
+ (completion_tokens=100, prompt_tokens=55, total_tokens=155),
+ 'model': '', 'finish_reason': 'length'},
+ id='run-874c24b7-0272-4c99-b259-5d6d7facbc56-0')
+ ```
+
+ Stream:
+ ```python
+ for chunk in chat.stream(messages):
+ print(chunk)
+ ```
+
+ ```python
+ content='Je ai une passion pour le programme.\n\nIn French, we use
+ "ai" for masculine subjects and "a" for feminine subjects.
+ Since "programming" is gender-neutral in English,
+ we will go with the masculine "programme".\n\nConfirmation:
+ "J\'aime le programme." is more commonly used. The sentence
+ above is technically accurate, but less commonly used in spoken
+ French as "ai" is used less frequently in everyday speech.'
+ response_metadata={'token_usage': ChatCompletionOutputUsage
+ (completion_tokens=100, prompt_tokens=55, total_tokens=155),
+ 'model': '', 'finish_reason': 'length'}
+ id='run-7d7b1967-9612-4f9a-911a-b2b5ca85046a-0'
+ ```
+
+ Async:
+ ```python
+ await chat.ainvoke(messages)
+ ```
+
+ ```python
+ AIMessage(content='Je déaime le programming.\n\nLittérale : Je
+ (j\'aime) déaime (le) programming.\n\nNote: "Programming" in
+ French is "programmation". But here, I used "programming" instead
+ of "programmation" because the user said "I love programming"
+ instead of "I love programming (in French)", which would be
+ "J\'aime la programmation". By translating the sentence
+ literally, I preserved the original meaning of the user\'s
+ sentence.', id='run-fd850318-e299-4735-b4c6-3496dc930b1d-0')
+ ```
+
+ Tool calling:
+ ```python
+ 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")
+
+ class GetPopulation(BaseModel):
+ '''Get the current population in a given location'''
+
+ location: str = Field(..., description="The city and state,
+ e.g. San Francisco, CA")
+
+ chat_with_tools = chat.bind_tools([GetWeather, GetPopulation])
+ ai_msg = chat_with_tools.invoke("Which city is hotter today and
+ which is bigger: LA or NY?")
+ ai_msg.tool_calls
+ ```
+
+ ```python
+ [
+ {
+ "name": "GetPopulation",
+ "args": {"location": "Los Angeles, CA"},
+ "id": "0",
+ }
+ ]
+ ```
+
+ Response metadata
+ ```python
+ ai_msg = chat.invoke(messages)
+ ai_msg.response_metadata
+ ```
+
+ ```python
+ {
+ "token_usage": ChatCompletionOutputUsage(
+ completion_tokens=100, prompt_tokens=8, total_tokens=108
+ ),
+ "model": "",
+ "finish_reason": "length",
+ }
+ ```
+ """ # noqa: E501
+
+ llm: Any
+ """LLM, must be of type HuggingFaceTextGenInference, HuggingFaceEndpoint,
+ HuggingFaceHub, or HuggingFacePipeline."""
+ tokenizer: Any = None
+ """Tokenizer for the model. Only used for HuggingFacePipeline."""
+ model_id: str | None = None
+ """Model ID for the model. Only used for HuggingFaceEndpoint."""
+ temperature: float | None = None
+ """What sampling temperature to use."""
+ stop: str | list[str] | None = Field(default=None, alias="stop_sequences")
+ """Default stop sequences."""
+ presence_penalty: float | None = None
+ """Penalizes repeated tokens."""
+ frequency_penalty: float | None = None
+ """Penalizes repeated tokens according to frequency."""
+ seed: int | None = None
+ """Seed for generation"""
+ logprobs: bool | None = None
+ """Whether to return logprobs."""
+ top_logprobs: int | None = None
+ """Number of most likely tokens to return at each token position, each with
+ an associated log probability. `logprobs` must be set to true
+ if this parameter is used."""
+ logit_bias: dict[int, int] | None = None
+ """Modify the likelihood of specified tokens appearing in the completion."""
+ streaming: bool = False
+ """Whether to stream the results or not."""
+ stream_usage: bool | None = None
+ """Whether to include usage metadata in streaming output. If True, an additional
+ message chunk will be generated during the stream including usage metadata."""
+ n: int | None = None
+ """Number of chat completions to generate for each prompt."""
+ top_p: float | None = None
+ """Total probability mass of tokens to consider at each step."""
+ max_tokens: int | None = None
+ """Maximum number of tokens to generate."""
+ model_kwargs: dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for `create` call not explicitly specified."""
+
+ def __init__(self, **kwargs: Any):
+ super().__init__(**kwargs)
+
+ # Inherit properties from the LLM if they weren't explicitly set
+ self._inherit_llm_properties()
+
+ self._resolve_model_id()
+
+ def _inherit_llm_properties(self) -> None:
+ """Inherit properties from the wrapped LLM instance if not explicitly set."""
+ if not hasattr(self, "llm") or self.llm is None:
+ return
+
+ # Map of ChatHuggingFace properties to LLM properties
+ property_mappings = {
+ "temperature": "temperature",
+ "max_tokens": "max_new_tokens", # Different naming convention
+ "top_p": "top_p",
+ "seed": "seed",
+ "streaming": "streaming",
+ "stop": "stop_sequences",
+ }
+
+ # Inherit properties from LLM and not explicitly set here
+ for chat_prop, llm_prop in property_mappings.items():
+ if hasattr(self.llm, llm_prop):
+ llm_value = getattr(self.llm, llm_prop)
+ chat_value = getattr(self, chat_prop, None)
+ if not chat_value and llm_value:
+ setattr(self, chat_prop, llm_value)
+
+ # Handle special cases for HuggingFaceEndpoint
+ if _is_huggingface_endpoint(self.llm):
+ # Inherit additional HuggingFaceEndpoint specific properties
+ endpoint_mappings = {
+ "frequency_penalty": "repetition_penalty",
+ }
+
+ for chat_prop, llm_prop in endpoint_mappings.items():
+ if hasattr(self.llm, llm_prop):
+ llm_value = getattr(self.llm, llm_prop)
+ chat_value = getattr(self, chat_prop, None)
+ if chat_value is None and llm_value is not None:
+ setattr(self, chat_prop, llm_value)
+
+ # Inherit model_kwargs if not explicitly set
+ if (
+ not self.model_kwargs
+ and hasattr(self.llm, "model_kwargs")
+ and isinstance(self.llm.model_kwargs, dict)
+ ):
+ self.model_kwargs = self.llm.model_kwargs.copy()
+
+ @model_validator(mode="after")
+ def validate_llm(self) -> Self:
+ if (
+ not _is_huggingface_hub(self.llm)
+ and not _is_huggingface_textgen_inference(self.llm)
+ and not _is_huggingface_endpoint(self.llm)
+ and not _is_huggingface_pipeline(self.llm)
+ ):
+ msg = (
+ "Expected llm to be one of HuggingFaceTextGenInference, "
+ "HuggingFaceEndpoint, HuggingFaceHub, HuggingFacePipeline "
+ f"received {type(self.llm)}"
+ )
+ raise TypeError(msg)
+ return self
+
+ def _resolve_model_profile(self) -> ModelProfile | None:
+ if self.model_id:
+ return _get_default_model_profile(self.model_id) or None
+ return None
+
+ @classmethod
+ def from_model_id(
+ cls,
+ model_id: str,
+ task: str | None = None,
+ backend: Literal["pipeline", "endpoint", "text-gen"] = "pipeline",
+ **kwargs: Any,
+ ) -> ChatHuggingFace:
+ """Construct a ChatHuggingFace model from a model_id.
+
+ Args:
+ model_id: The model ID of the Hugging Face model.
+ task: The task to perform (e.g., "text-generation").
+ backend: The backend to use. One of "pipeline", "endpoint", "text-gen".
+ **kwargs: Additional arguments to pass to the backend or ChatHuggingFace.
+ """
+ llm: (
+ Any # HuggingFacePipeline, HuggingFaceEndpoint, HuggingFaceTextGenInference
+ )
+ if backend == "pipeline":
+ from langchain_huggingface.llms.huggingface_pipeline import (
+ HuggingFacePipeline,
+ )
+
+ task = task if task is not None else "text-generation"
+
+ # Separate pipeline-specific kwargs from ChatHuggingFace kwargs
+ # Parameters that should go to HuggingFacePipeline.from_model_id
+ pipeline_specific_kwargs = {}
+
+ # Extract pipeline-specific parameters
+ pipeline_keys = [
+ "backend",
+ "device",
+ "device_map",
+ "model_kwargs",
+ "pipeline_kwargs",
+ "batch_size",
+ ]
+ for key in pipeline_keys:
+ if key in kwargs:
+ pipeline_specific_kwargs[key] = kwargs.pop(key)
+
+ # Remaining kwargs (temperature, max_tokens, etc.) should go to
+ # pipeline_kwargs for generation parameters, which ChatHuggingFace
+ # will inherit from the LLM
+ if "pipeline_kwargs" not in pipeline_specific_kwargs:
+ pipeline_specific_kwargs["pipeline_kwargs"] = {}
+
+ # Add generation parameters to pipeline_kwargs
+ # Map max_tokens to max_new_tokens for HuggingFace pipeline
+ generation_params = {}
+ for k, v in list(kwargs.items()):
+ if k == "max_tokens":
+ generation_params["max_new_tokens"] = v
+ kwargs.pop(k)
+ elif k in (
+ "temperature",
+ "max_new_tokens",
+ "top_p",
+ "top_k",
+ "repetition_penalty",
+ "do_sample",
+ ):
+ generation_params[k] = v
+ kwargs.pop(k)
+
+ pipeline_specific_kwargs["pipeline_kwargs"].update(generation_params)
+
+ # Create the HuggingFacePipeline
+ llm = HuggingFacePipeline.from_model_id(
+ model_id=model_id, task=task, **pipeline_specific_kwargs
+ )
+ elif backend == "endpoint":
+ from langchain_huggingface.llms.huggingface_endpoint import (
+ HuggingFaceEndpoint,
+ )
+
+ llm = HuggingFaceEndpoint(repo_id=model_id, task=task, **kwargs)
+ elif backend == "text-gen":
+ from langchain_community.llms.huggingface_text_gen_inference import ( # type: ignore[import-not-found]
+ HuggingFaceTextGenInference,
+ )
+
+ llm = HuggingFaceTextGenInference(inference_server_url=model_id, **kwargs)
+ else:
+ msg = f"Unknown backend: {backend}"
+ raise ValueError(msg)
+
+ return cls(llm=llm, **kwargs)
+
+ def _create_chat_result(self, response: dict) -> ChatResult:
+ generations = []
+ token_usage = response.get("usage", {})
+ for res in response["choices"]:
+ message = _convert_dict_to_message(res["message"])
+ if token_usage and isinstance(message, AIMessage):
+ message.usage_metadata = {
+ "input_tokens": token_usage.get("prompt_tokens", 0),
+ "output_tokens": token_usage.get("completion_tokens", 0),
+ "total_tokens": token_usage.get("total_tokens", 0),
+ }
+ generation_info = {"finish_reason": res.get("finish_reason")}
+ if "logprobs" in res:
+ generation_info["logprobs"] = res["logprobs"]
+ gen = ChatGeneration(
+ message=message,
+ generation_info=generation_info,
+ )
+ generations.append(gen)
+ llm_output = {
+ "token_usage": token_usage,
+ "model_name": self.model_id,
+ "system_fingerprint": response.get("system_fingerprint", ""),
+ }
+ return ChatResult(generations=generations, llm_output=llm_output)
+
+ def _generate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ stream: bool | None = None, # noqa: FBT001
+ **kwargs: Any,
+ ) -> ChatResult:
+ should_stream = stream if stream is not None else self.streaming
+
+ if _is_huggingface_textgen_inference(self.llm):
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ answer = self.llm.client.chat(messages=message_dicts, **kwargs)
+ return self._create_chat_result(answer)
+ if _is_huggingface_endpoint(self.llm):
+ if should_stream:
+ stream_iter = self._stream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {
+ "stop": stop,
+ **params,
+ **({"stream": stream} if stream is not None else {}),
+ **kwargs,
+ }
+ answer = self.llm.client.chat_completion(messages=message_dicts, **params)
+ return self._create_chat_result(answer)
+ llm_input = self._to_chat_prompt(messages)
+
+ if should_stream:
+ stream_iter = self.llm._stream(
+ llm_input, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return generate_from_stream(stream_iter)
+ llm_result = self.llm._generate(
+ prompts=[llm_input], stop=stop, run_manager=run_manager, **kwargs
+ )
+ return self._to_chat_result(llm_result)
+
+ async def _agenerate(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ stream: bool | None = None, # noqa: FBT001
+ **kwargs: Any,
+ ) -> ChatResult:
+ if _is_huggingface_textgen_inference(self.llm):
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ answer = await self.llm.async_client.chat(messages=message_dicts, **kwargs)
+ return self._create_chat_result(answer)
+ if _is_huggingface_endpoint(self.llm):
+ should_stream = stream if stream is not None else self.streaming
+ if should_stream:
+ stream_iter = self._astream(
+ messages, stop=stop, run_manager=run_manager, **kwargs
+ )
+ return await agenerate_from_stream(stream_iter)
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {
+ **params,
+ **({"stream": stream} if stream is not None else {}),
+ **kwargs,
+ }
+
+ answer = await self.llm.async_client.chat_completion(
+ messages=message_dicts, **params
+ )
+ return self._create_chat_result(answer)
+ if _is_huggingface_pipeline(self.llm):
+ msg = "async generation is not supported with HuggingFacePipeline"
+ raise NotImplementedError(msg)
+ llm_input = self._to_chat_prompt(messages)
+ llm_result = await self.llm._agenerate(
+ prompts=[llm_input], stop=stop, run_manager=run_manager, **kwargs
+ )
+ return self._to_chat_result(llm_result)
+
+ def _should_stream_usage(
+ self, *, stream_usage: bool | None = None, **kwargs: Any
+ ) -> bool | None:
+ """Determine whether to include usage metadata in streaming output.
+
+ For backwards compatibility, we check for `stream_options` passed
+ explicitly to kwargs or in the model_kwargs and override self.stream_usage.
+ """
+ stream_usage_sources = [ # order of precedence
+ stream_usage,
+ kwargs.get("stream_options", {}).get("include_usage"),
+ self.model_kwargs.get("stream_options", {}).get("include_usage"),
+ self.stream_usage,
+ ]
+ for source in stream_usage_sources:
+ if isinstance(source, bool):
+ return source
+ return self.stream_usage
+
+ def _stream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ *,
+ stream_usage: bool | None = None,
+ **kwargs: Any,
+ ) -> Iterator[ChatGenerationChunk]:
+ if _is_huggingface_endpoint(self.llm):
+ stream_usage = self._should_stream_usage(
+ stream_usage=stream_usage, **kwargs
+ )
+ if stream_usage:
+ kwargs["stream_options"] = {"include_usage": stream_usage}
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: type[BaseMessageChunk] = AIMessageChunk
+ for chunk in self.llm.client.chat_completion(
+ messages=message_dicts, **params
+ ):
+ if len(chunk["choices"]) == 0:
+ if usage := chunk.get("usage"):
+ usage_msg = AIMessageChunk(
+ content="",
+ additional_kwargs={},
+ response_metadata={},
+ usage_metadata={
+ "input_tokens": usage.get("prompt_tokens", 0),
+ "output_tokens": usage.get("completion_tokens", 0),
+ "total_tokens": usage.get("total_tokens", 0),
+ },
+ )
+ yield ChatGenerationChunk(message=usage_msg)
+ continue
+
+ choice = chunk["choices"][0]
+ message_chunk = _convert_chunk_to_message_chunk(
+ chunk, default_chunk_class
+ )
+ generation_info = {}
+ if finish_reason := choice.get("finish_reason"):
+ generation_info["finish_reason"] = finish_reason
+ generation_info["model_name"] = self.model_id
+ logprobs = choice.get("logprobs")
+ if logprobs:
+ generation_info["logprobs"] = logprobs
+ default_chunk_class = message_chunk.__class__
+ generation_chunk = ChatGenerationChunk(
+ message=message_chunk, generation_info=generation_info or None
+ )
+ if run_manager:
+ run_manager.on_llm_new_token(
+ generation_chunk.text, chunk=generation_chunk, logprobs=logprobs
+ )
+ yield generation_chunk
+ else:
+ llm_input = self._to_chat_prompt(messages)
+ stream_iter = self.llm._stream(
+ llm_input, stop=stop, run_manager=run_manager, **kwargs
+ )
+ for chunk in stream_iter: # chunk is a GenerationChunk
+ chat_chunk = ChatGenerationChunk(
+ message=AIMessageChunk(content=chunk.text),
+ generation_info=chunk.generation_info,
+ )
+ yield chat_chunk
+
+ async def _astream(
+ self,
+ messages: list[BaseMessage],
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ *,
+ stream_usage: bool | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[ChatGenerationChunk]:
+ stream_usage = self._should_stream_usage(stream_usage=stream_usage, **kwargs)
+ if stream_usage:
+ kwargs["stream_options"] = {"include_usage": stream_usage}
+ message_dicts, params = self._create_message_dicts(messages, stop)
+ params = {**params, **kwargs, "stream": True}
+
+ default_chunk_class: type[BaseMessageChunk] = AIMessageChunk
+
+ async for chunk in await self.llm.async_client.chat_completion(
+ messages=message_dicts, **params
+ ):
+ if len(chunk["choices"]) == 0:
+ if usage := chunk.get("usage"):
+ usage_msg = AIMessageChunk(
+ content="",
+ additional_kwargs={},
+ response_metadata={},
+ usage_metadata={
+ "input_tokens": usage.get("prompt_tokens", 0),
+ "output_tokens": usage.get("completion_tokens", 0),
+ "total_tokens": usage.get("total_tokens", 0),
+ },
+ )
+ yield ChatGenerationChunk(message=usage_msg)
+ continue
+
+ choice = chunk["choices"][0]
+ message_chunk = _convert_chunk_to_message_chunk(chunk, default_chunk_class)
+ generation_info = {}
+ if finish_reason := choice.get("finish_reason"):
+ generation_info["finish_reason"] = finish_reason
+ generation_info["model_name"] = self.model_id
+ logprobs = choice.get("logprobs")
+ if logprobs:
+ generation_info["logprobs"] = logprobs
+ default_chunk_class = message_chunk.__class__
+ generation_chunk = ChatGenerationChunk(
+ message=message_chunk, generation_info=generation_info or None
+ )
+ if run_manager:
+ await run_manager.on_llm_new_token(
+ token=generation_chunk.text,
+ chunk=generation_chunk,
+ logprobs=logprobs,
+ )
+ yield generation_chunk
+
+ def _to_chat_prompt(
+ self,
+ messages: list[BaseMessage],
+ ) -> str:
+ """Convert a list of messages into a prompt format expected by wrapped LLM."""
+ if not messages:
+ msg = "At least one HumanMessage must be provided!"
+ raise ValueError(msg)
+
+ if not isinstance(messages[-1], HumanMessage):
+ msg = "Last message must be a HumanMessage!"
+ raise ValueError(msg)
+
+ messages_dicts = [self._to_chatml_format(m) for m in messages]
+
+ return self.tokenizer.apply_chat_template(
+ messages_dicts, tokenize=False, add_generation_prompt=True
+ )
+
+ def _to_chatml_format(self, message: BaseMessage) -> dict:
+ """Convert LangChain message to ChatML format."""
+ if isinstance(message, SystemMessage):
+ role = "system"
+ elif isinstance(message, AIMessage):
+ role = "assistant"
+ elif isinstance(message, HumanMessage):
+ role = "user"
+ else:
+ msg = f"Unknown message type: {type(message)}"
+ raise ValueError(msg)
+
+ return {"role": role, "content": message.content}
+
+ @staticmethod
+ def _to_chat_result(llm_result: LLMResult) -> ChatResult:
+ chat_generations = []
+
+ for g in llm_result.generations[0]:
+ chat_generation = ChatGeneration(
+ message=AIMessage(content=g.text), generation_info=g.generation_info
+ )
+ chat_generations.append(chat_generation)
+
+ return ChatResult(
+ generations=chat_generations, llm_output=llm_result.llm_output
+ )
+
+ def _resolve_model_id(self) -> None:
+ """Resolve the model_id from the LLM's inference_server_url."""
+ from huggingface_hub import list_inference_endpoints # type: ignore[import]
+
+ if _is_huggingface_hub(self.llm) or (
+ hasattr(self.llm, "repo_id") and self.llm.repo_id
+ ):
+ self.model_id = self.llm.repo_id
+ return
+ if _is_huggingface_textgen_inference(self.llm):
+ endpoint_url: str | None = self.llm.inference_server_url
+ if _is_huggingface_pipeline(self.llm):
+ from transformers import AutoTokenizer # type: ignore[import]
+
+ self.model_id = self.model_id or self.llm.model_id
+ self.tokenizer = (
+ AutoTokenizer.from_pretrained(self.model_id)
+ if self.tokenizer is None
+ else self.tokenizer
+ )
+ return
+ if _is_huggingface_endpoint(self.llm):
+ self.model_id = self.llm.repo_id or self.llm.model
+ return
+ endpoint_url = self.llm.endpoint_url
+ available_endpoints = list_inference_endpoints("*")
+ for endpoint in available_endpoints:
+ if endpoint.url == endpoint_url:
+ self.model_id = endpoint.repository
+
+ if not self.model_id:
+ msg = (
+ "Failed to resolve model_id:"
+ f"Could not find model id for inference server: {endpoint_url}"
+ "Make sure that your Hugging Face token has access to the endpoint."
+ )
+ raise ValueError(msg)
+
+ def bind_tools(
+ self,
+ tools: Sequence[dict[str, Any] | type | Callable | BaseTool],
+ *,
+ tool_choice: dict | str | bool | None = None,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, AIMessage]:
+ """Bind tool-like objects to this chat model.
+
+ Assumes model is compatible with OpenAI tool-calling API.
+
+ Args:
+ tools: A list of tool definitions to bind to this chat model.
+
+ Supports any tool definition handled by [`convert_to_openai_tool`][langchain_core.utils.function_calling.convert_to_openai_tool].
+ tool_choice: Which tool to require the model to call.
+ Must be the name of the single provided function or
+ `'auto'` to automatically determine which function to call
+ (if any), or a dict of the form:
+ {"type": "function", "function": {"name": <>}}.
+ **kwargs: Any additional parameters to pass to the
+ `langchain.runnable.Runnable` constructor.
+ """ # noqa: E501
+ formatted_tools = [convert_to_openai_tool(tool) for tool in tools]
+ if tool_choice is not None and tool_choice:
+ if len(formatted_tools) != 1:
+ msg = (
+ "When specifying `tool_choice`, you must provide exactly one "
+ f"tool. Received {len(formatted_tools)} tools."
+ )
+ raise ValueError(msg)
+ if isinstance(tool_choice, str):
+ if tool_choice not in ("auto", "none", "required"):
+ tool_choice = {
+ "type": "function",
+ "function": {"name": tool_choice},
+ }
+ elif isinstance(tool_choice, bool):
+ tool_choice = formatted_tools[0]
+ elif isinstance(tool_choice, dict):
+ if (
+ formatted_tools[0]["function"]["name"]
+ != tool_choice["function"]["name"]
+ ):
+ msg = (
+ f"Tool choice {tool_choice} was specified, but the only "
+ f"provided tool was {formatted_tools[0]['function']['name']}."
+ )
+ raise ValueError(msg)
+ else:
+ msg = (
+ f"Unrecognized tool_choice type. Expected str, bool or dict. "
+ f"Received: {tool_choice}"
+ )
+ raise ValueError(msg)
+ kwargs["tool_choice"] = tool_choice
+ return super().bind(tools=formatted_tools, **kwargs)
+
+ def with_structured_output(
+ self,
+ schema: dict | type[BaseModel] | None = None,
+ *,
+ method: Literal[
+ "function_calling", "json_mode", "json_schema"
+ ] = "function_calling",
+ include_raw: bool = False,
+ **kwargs: Any,
+ ) -> Runnable[LanguageModelInput, dict | BaseModel]:
+ """Model wrapper that returns outputs formatted to match the given schema.
+
+ Args:
+ schema: The output schema. Can be passed in as:
+
+ - An OpenAI function/tool schema,
+ - A JSON Schema,
+ - A `TypedDict` class
+
+ Pydantic class is currently supported.
+
+ method: The method for steering model generation, one of:
+
+ - `'function_calling'`: uses tool-calling features.
+ - `'json_schema'`: uses dedicated structured output features.
+ - `'json_mode'`: uses JSON mode.
+
+ include_raw:
+ If `False` then only the parsed structured output is returned.
+
+ If an error occurs during model output parsing it will be raised.
+
+ If `True` then both the raw model response (a `BaseMessage`) and the
+ parsed model response will be returned.
+
+ If an error occurs during output parsing it will be caught and returned
+ as well.
+
+ The final output is always a `dict` with keys `'raw'`, `'parsed'`, and
+ `'parsing_error'`.
+
+ kwargs:
+ Additional parameters to pass to the underlying LLM's
+ `langchain_core.language_models.chat.BaseChatModel.bind`
+ method, such as `response_format` or `ls_structured_output_format`.
+
+ Returns:
+ A `Runnable` that takes same inputs as a
+ `langchain_core.language_models.chat.BaseChatModel`. If `include_raw` is
+ `False` and `schema` is a Pydantic class, `Runnable` outputs an instance
+ of `schema` (i.e., a Pydantic object). Otherwise, if `include_raw` is
+ `False` then `Runnable` outputs a `dict`.
+
+ If `include_raw` is `True`, then `Runnable` outputs a `dict` with keys:
+
+ - `'raw'`: `BaseMessage`
+ - `'parsed'`: `None` if there was a parsing error, otherwise the type
+ depends on the `schema` as described above.
+ - `'parsing_error'`: `BaseException | None`
+ """
+ _ = kwargs.pop("strict", None)
+ if kwargs:
+ msg = f"Received unsupported arguments {kwargs}"
+ raise ValueError(msg)
+ is_pydantic_schema = isinstance(schema, type) and is_basemodel_subclass(schema)
+ if method == "function_calling":
+ if schema is None:
+ msg = (
+ "schema must be specified when method is 'function_calling'. "
+ "Received None."
+ )
+ raise ValueError(msg)
+ formatted_tool = convert_to_openai_tool(schema)
+ tool_name = formatted_tool["function"]["name"]
+ llm = self.bind_tools(
+ [schema],
+ tool_choice=tool_name,
+ ls_structured_output_format={
+ "kwargs": {"method": "function_calling"},
+ "schema": formatted_tool,
+ },
+ )
+ if is_pydantic_schema:
+ msg = "Pydantic schema is not supported for function calling"
+ raise NotImplementedError(msg)
+ output_parser: JsonOutputKeyToolsParser | JsonOutputParser = (
+ JsonOutputKeyToolsParser(key_name=tool_name, first_tool_only=True)
+ )
+ elif method == "json_schema":
+ if schema is None:
+ msg = (
+ "schema must be specified when method is 'json_schema'. "
+ "Received None."
+ )
+ raise ValueError(msg)
+ formatted_schema = convert_to_json_schema(schema)
+ llm = self.bind(
+ response_format={"type": "json_object", "schema": formatted_schema},
+ ls_structured_output_format={
+ "kwargs": {"method": "json_schema"},
+ "schema": schema,
+ },
+ )
+ output_parser = JsonOutputParser() # type: ignore[arg-type]
+ elif method == "json_mode":
+ llm = self.bind(
+ response_format={"type": "json_object"},
+ ls_structured_output_format={
+ "kwargs": {"method": "json_mode"},
+ "schema": schema,
+ },
+ )
+ output_parser = JsonOutputParser() # type: ignore[arg-type]
+ else:
+ msg = (
+ f"Unrecognized method argument. Expected one of 'function_calling' or "
+ f"'json_mode'. Received: '{method}'"
+ )
+ raise ValueError(msg)
+
+ if include_raw:
+ parser_assign = RunnablePassthrough.assign(
+ parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
+ )
+ parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
+ parser_with_fallback = parser_assign.with_fallbacks(
+ [parser_none], exception_key="parsing_error"
+ )
+ return RunnableMap(raw=llm) | parser_with_fallback
+ return llm | output_parser
+
+ def _create_message_dicts(
+ self, messages: list[BaseMessage], stop: list[str] | None
+ ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
+ params = self._default_params
+ if stop is not None:
+ params["stop"] = stop
+ message_dicts = [_convert_message_to_dict(m) for m in messages]
+ return message_dicts, params
+
+ @property
+ def _default_params(self) -> dict[str, Any]:
+ """Get default parameters for calling Hugging Face Inference Providers API."""
+ params = {
+ "model": self.model_id,
+ "stream": self.streaming,
+ "n": self.n,
+ "temperature": self.temperature,
+ "stop": self.stop,
+ **(self.model_kwargs if self.model_kwargs else {}),
+ }
+ if self.max_tokens is not None:
+ params["max_tokens"] = self.max_tokens
+ return params
+
+ @property
+ def _llm_type(self) -> str:
+ return "huggingface-chat-wrapper"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/data/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..07c24b14111f538c866a6e7769b1933a3d5b9165
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/data/__init__.py
@@ -0,0 +1 @@
+"""Model profile data. All edits should be made in profile_augmentations.toml."""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/data/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/data/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a596006b1b4d50bf47fdba4f9f684f10fc4c3d5f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/data/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/data/__pycache__/_profiles.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/data/__pycache__/_profiles.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21b6549dfa28c2cf7b9711de7fa0ff9df6e3714d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/data/__pycache__/_profiles.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/data/_profiles.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/data/_profiles.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b78dc6ac610808f34c868a7b4213e943e4ede66
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/data/_profiles.py
@@ -0,0 +1,460 @@
+"""Auto-generated model profiles.
+
+DO NOT EDIT THIS FILE MANUALLY.
+This file is generated by the langchain-profiles CLI tool.
+
+It contains data derived from the models.dev project.
+
+Source: https://github.com/sst/models.dev
+License: MIT License
+
+To update these data, refer to the instructions here:
+
+https://docs.langchain.com/oss/python/langchain/models#updating-or-overwriting-profile-data
+"""
+
+from typing import Any
+
+_PROFILES: dict[str, dict[str, Any]] = {
+ "MiniMaxAI/MiniMax-M2.1": {
+ "name": "MiniMax-M2.1",
+ "release_date": "2025-12-23",
+ "last_updated": "2025-12-23",
+ "open_weights": True,
+ "max_input_tokens": 204800,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "MiniMaxAI/MiniMax-M2.5": {
+ "name": "MiniMax-M2.5",
+ "release_date": "2026-02-12",
+ "last_updated": "2026-02-12",
+ "open_weights": True,
+ "max_input_tokens": 204800,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "MiniMaxAI/MiniMax-M2.7": {
+ "name": "MiniMax-M2.7",
+ "release_date": "2026-03-18",
+ "last_updated": "2026-03-18",
+ "open_weights": True,
+ "max_input_tokens": 204800,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "structured_output": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "Qwen/Qwen3-235B-A22B-Thinking-2507": {
+ "name": "Qwen3-235B-A22B-Thinking-2507",
+ "release_date": "2025-07-25",
+ "last_updated": "2025-07-25",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "Qwen/Qwen3-Coder-480B-A35B-Instruct": {
+ "name": "Qwen3-Coder-480B-A35B-Instruct",
+ "release_date": "2025-07-23",
+ "last_updated": "2025-07-23",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 66536,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "Qwen/Qwen3-Coder-Next": {
+ "name": "Qwen3-Coder-Next",
+ "release_date": "2026-02-03",
+ "last_updated": "2026-02-03",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 65536,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "Qwen/Qwen3-Embedding-4B": {
+ "name": "Qwen 3 Embedding 4B",
+ "release_date": "2025-01-01",
+ "last_updated": "2025-01-01",
+ "open_weights": True,
+ "max_input_tokens": 32000,
+ "max_output_tokens": 2048,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": False,
+ "attachment": False,
+ "temperature": False,
+ },
+ "Qwen/Qwen3-Embedding-8B": {
+ "name": "Qwen 3 Embedding 8B",
+ "release_date": "2025-01-01",
+ "last_updated": "2025-01-01",
+ "open_weights": True,
+ "max_input_tokens": 32000,
+ "max_output_tokens": 4096,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": False,
+ "attachment": False,
+ "temperature": False,
+ },
+ "Qwen/Qwen3-Next-80B-A3B-Instruct": {
+ "name": "Qwen3-Next-80B-A3B-Instruct",
+ "release_date": "2025-09-11",
+ "last_updated": "2025-09-11",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 66536,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "Qwen/Qwen3-Next-80B-A3B-Thinking": {
+ "name": "Qwen3-Next-80B-A3B-Thinking",
+ "release_date": "2025-09-11",
+ "last_updated": "2025-09-11",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "Qwen/Qwen3.5-397B-A17B": {
+ "name": "Qwen3.5-397B-A17B",
+ "release_date": "2026-02-01",
+ "last_updated": "2026-02-01",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 32768,
+ "text_inputs": True,
+ "image_inputs": True,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": True,
+ "temperature": True,
+ },
+ "XiaomiMiMo/MiMo-V2-Flash": {
+ "name": "MiMo-V2-Flash",
+ "release_date": "2025-12-16",
+ "last_updated": "2025-12-16",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 4096,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "deepseek-ai/DeepSeek-R1-0528": {
+ "name": "DeepSeek-R1-0528",
+ "release_date": "2025-05-28",
+ "last_updated": "2025-05-28",
+ "open_weights": True,
+ "max_input_tokens": 163840,
+ "max_output_tokens": 163840,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "deepseek-ai/DeepSeek-V3.2": {
+ "name": "DeepSeek-V3.2",
+ "release_date": "2025-12-01",
+ "last_updated": "2025-12-01",
+ "open_weights": True,
+ "max_input_tokens": 163840,
+ "max_output_tokens": 65536,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "moonshotai/Kimi-K2-Instruct": {
+ "name": "Kimi-K2-Instruct",
+ "release_date": "2025-07-14",
+ "last_updated": "2025-07-14",
+ "open_weights": True,
+ "max_input_tokens": 131072,
+ "max_output_tokens": 16384,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "moonshotai/Kimi-K2-Instruct-0905": {
+ "name": "Kimi-K2-Instruct-0905",
+ "release_date": "2025-09-04",
+ "last_updated": "2025-09-04",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 16384,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": False,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "moonshotai/Kimi-K2-Thinking": {
+ "name": "Kimi-K2-Thinking",
+ "release_date": "2025-11-06",
+ "last_updated": "2025-11-06",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "moonshotai/Kimi-K2.5": {
+ "name": "Kimi-K2.5",
+ "release_date": "2026-01-01",
+ "last_updated": "2026-01-01",
+ "open_weights": True,
+ "max_input_tokens": 262144,
+ "max_output_tokens": 262144,
+ "text_inputs": True,
+ "image_inputs": True,
+ "audio_inputs": False,
+ "video_inputs": True,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": True,
+ "temperature": True,
+ },
+ "zai-org/GLM-4.7": {
+ "name": "GLM-4.7",
+ "release_date": "2025-12-22",
+ "last_updated": "2025-12-22",
+ "open_weights": True,
+ "max_input_tokens": 204800,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "zai-org/GLM-4.7-Flash": {
+ "name": "GLM-4.7-Flash",
+ "release_date": "2025-08-08",
+ "last_updated": "2025-08-08",
+ "open_weights": True,
+ "max_input_tokens": 200000,
+ "max_output_tokens": 128000,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "zai-org/GLM-5": {
+ "name": "GLM-5",
+ "release_date": "2026-02-11",
+ "last_updated": "2026-02-11",
+ "open_weights": True,
+ "max_input_tokens": 202752,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+ "zai-org/GLM-5.1": {
+ "name": "GLM-5.1",
+ "release_date": "2026-04-03",
+ "last_updated": "2026-04-03",
+ "open_weights": True,
+ "max_input_tokens": 202752,
+ "max_output_tokens": 131072,
+ "text_inputs": True,
+ "image_inputs": False,
+ "audio_inputs": False,
+ "video_inputs": False,
+ "text_outputs": True,
+ "image_outputs": False,
+ "audio_outputs": False,
+ "video_outputs": False,
+ "reasoning_output": True,
+ "tool_calling": True,
+ "attachment": False,
+ "temperature": True,
+ },
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..746d1c31ca7c75034ef7bf31e354fcf11ef6a26f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/__init__.py
@@ -0,0 +1,11 @@
+from langchain_huggingface.embeddings.huggingface import (
+ HuggingFaceEmbeddings, # type: ignore[import-not-found]
+)
+from langchain_huggingface.embeddings.huggingface_endpoint import (
+ HuggingFaceEndpointEmbeddings,
+)
+
+__all__ = [
+ "HuggingFaceEmbeddings",
+ "HuggingFaceEndpointEmbeddings",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b1b94c6664014b4fdc1b96d4044c1c50ed4c7cfe
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/__pycache__/huggingface.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/__pycache__/huggingface.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4026adc8edbeffcf498cfc0ba748a31005f2a160
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/__pycache__/huggingface.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/__pycache__/huggingface_endpoint.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/__pycache__/huggingface_endpoint.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e245820ec8773528938f0db13261a31d95a41fa
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/__pycache__/huggingface_endpoint.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/huggingface.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/huggingface.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c55348cee1aa56f4a2aa3f10377456bde5c466e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/huggingface.py
@@ -0,0 +1,172 @@
+from __future__ import annotations
+
+from typing import Any
+
+from langchain_core.embeddings import Embeddings
+from pydantic import BaseModel, ConfigDict, Field
+
+from langchain_huggingface.utils.import_utils import (
+ IMPORT_ERROR,
+ is_ipex_available,
+ is_optimum_intel_available,
+ is_optimum_intel_version,
+)
+
+_MIN_OPTIMUM_VERSION = "1.22"
+
+
+class HuggingFaceEmbeddings(BaseModel, Embeddings):
+ """HuggingFace sentence_transformers embedding models.
+
+ To use, you should have the `sentence_transformers` python package installed.
+
+ Example:
+ ```python
+ from langchain_huggingface import HuggingFaceEmbeddings
+
+ model_name = "sentence-transformers/all-mpnet-base-v2"
+ model_kwargs = {"device": "cpu"}
+ encode_kwargs = {"normalize_embeddings": False}
+ hf = HuggingFaceEmbeddings(
+ model_name=model_name,
+ model_kwargs=model_kwargs,
+ encode_kwargs=encode_kwargs,
+ )
+ ```
+ """
+
+ model_name: str = Field(
+ default="sentence-transformers/all-mpnet-base-v2", alias="model"
+ )
+ """Model name to use."""
+ cache_folder: str | None = None
+ """Path to store models.
+ Can be also set by SENTENCE_TRANSFORMERS_HOME environment variable."""
+ model_kwargs: dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass to the Sentence Transformer model, such as `device`,
+ `prompts`, `default_prompt_name`, `revision`, `trust_remote_code`, or `token`.
+ See also the Sentence Transformer documentation: https://sbert.net/docs/package_reference/SentenceTransformer.html#sentence_transformers.SentenceTransformer"""
+ encode_kwargs: dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass when calling the `encode` method for the documents of
+ the Sentence Transformer model, such as `prompt_name`, `prompt`, `batch_size`,
+ `precision`, `normalize_embeddings`, and more.
+ See also the Sentence Transformer documentation: https://sbert.net/docs/package_reference/SentenceTransformer.html#sentence_transformers.SentenceTransformer.encode"""
+ query_encode_kwargs: dict[str, Any] = Field(default_factory=dict)
+ """Keyword arguments to pass when calling the `encode` method for the query of
+ the Sentence Transformer model, such as `prompt_name`, `prompt`, `batch_size`,
+ `precision`, `normalize_embeddings`, and more.
+ See also the Sentence Transformer documentation: https://sbert.net/docs/package_reference/SentenceTransformer.html#sentence_transformers.SentenceTransformer.encode"""
+ multi_process: bool = False
+ """Run encode() on multiple GPUs."""
+ show_progress: bool = False
+ """Whether to show a progress bar."""
+
+ def __init__(self, **kwargs: Any):
+ """Initialize the sentence_transformer."""
+ super().__init__(**kwargs)
+ try:
+ import sentence_transformers # type: ignore[import]
+ except ImportError as exc:
+ msg = (
+ "Could not import sentence_transformers python package. "
+ "Please install it with `pip install sentence-transformers`."
+ )
+ raise ImportError(msg) from exc
+
+ if self.model_kwargs.get("backend", "torch") == "ipex":
+ if not is_optimum_intel_available() or not is_ipex_available():
+ msg = f"Backend: ipex {IMPORT_ERROR.format('optimum[ipex]')}"
+ raise ImportError(msg)
+
+ if is_optimum_intel_version("<", _MIN_OPTIMUM_VERSION):
+ msg = (
+ f"Backend: ipex requires optimum-intel>="
+ f"{_MIN_OPTIMUM_VERSION}. You can install it with pip: "
+ "`pip install --upgrade --upgrade-strategy eager "
+ "`optimum[ipex]`."
+ )
+ raise ImportError(msg)
+
+ from optimum.intel import IPEXSentenceTransformer # type: ignore[import]
+
+ model_cls = IPEXSentenceTransformer
+
+ else:
+ model_cls = sentence_transformers.SentenceTransformer
+
+ self._client = model_cls(
+ self.model_name, cache_folder=self.cache_folder, **self.model_kwargs
+ )
+
+ model_config = ConfigDict(
+ extra="forbid",
+ protected_namespaces=(),
+ populate_by_name=True,
+ )
+
+ def _embed(
+ self, texts: list[str], encode_kwargs: dict[str, Any]
+ ) -> list[list[float]]:
+ """Embed a text using the HuggingFace transformer model.
+
+ Args:
+ texts: The list of texts to embed.
+ encode_kwargs: Keyword arguments to pass when calling the
+ `encode` method for the documents of the SentenceTransformer
+ encode method.
+
+ Returns:
+ List of embeddings, one for each text.
+
+ """
+ import sentence_transformers # type: ignore[import]
+
+ texts = [x.replace("\n", " ") for x in texts]
+ if self.multi_process:
+ pool = self._client.start_multi_process_pool()
+ embeddings = self._client.encode_multi_process(texts, pool)
+ sentence_transformers.SentenceTransformer.stop_multi_process_pool(pool)
+ else:
+ embeddings = self._client.encode(
+ texts,
+ show_progress_bar=self.show_progress,
+ **encode_kwargs,
+ )
+
+ if isinstance(embeddings, list):
+ msg = (
+ "Expected embeddings to be a Tensor or a numpy array, "
+ "got a list instead."
+ )
+ raise TypeError(msg)
+
+ return embeddings.tolist() # type: ignore[return-type]
+
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
+ """Compute doc embeddings using a HuggingFace transformer model.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+
+ """
+ return self._embed(texts, self.encode_kwargs)
+
+ def embed_query(self, text: str) -> list[float]:
+ """Compute query embeddings using a HuggingFace transformer model.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+
+ """
+ embed_kwargs = (
+ self.query_encode_kwargs
+ if len(self.query_encode_kwargs) > 0
+ else self.encode_kwargs
+ )
+ return self._embed([text], embed_kwargs)[0]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/huggingface_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/huggingface_endpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..25dfd4fc753c25c0a85c75eb5eb4a106fd1174ab
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/embeddings/huggingface_endpoint.py
@@ -0,0 +1,178 @@
+from __future__ import annotations
+
+import os
+from typing import Any
+
+from langchain_core.embeddings import Embeddings
+from langchain_core.utils import from_env
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+from typing_extensions import Self
+
+DEFAULT_MODEL = "sentence-transformers/all-mpnet-base-v2"
+VALID_TASKS = ("feature-extraction",)
+
+
+class HuggingFaceEndpointEmbeddings(BaseModel, Embeddings):
+ """HuggingFaceHub embedding models.
+
+ To use, you should have the `huggingface_hub` python package installed, and the
+ environment variable `HUGGINGFACEHUB_API_TOKEN` set with your API token, or pass
+ it as a named parameter to the constructor.
+
+ Example:
+ ```python
+ from langchain_huggingface import HuggingFaceEndpointEmbeddings
+
+ model = "sentence-transformers/all-mpnet-base-v2"
+ hf = HuggingFaceEndpointEmbeddings(
+ model=model,
+ task="feature-extraction",
+ huggingfacehub_api_token="my-api-key",
+ )
+ ```
+ """
+
+ client: Any = None
+
+ async_client: Any = None
+
+ model: str | None = None
+ """Model name to use."""
+
+ provider: str | None = None
+ """Name of the provider to use for inference with the model specified in
+ `repo_id`. e.g. "sambanova". if not specified, defaults to HF Inference API.
+ available providers can be found in the [huggingface_hub documentation](https://huggingface.co/docs/huggingface_hub/guides/inference#supported-providers-and-tasks)."""
+
+ repo_id: str | None = None
+ """Huggingfacehub repository id, for backward compatibility."""
+
+ task: str | None = "feature-extraction"
+ """Task to call the model with."""
+
+ model_kwargs: dict | None = None
+ """Keyword arguments to pass to the model."""
+
+ huggingfacehub_api_token: str | None = Field(
+ default_factory=from_env("HUGGINGFACEHUB_API_TOKEN", default=None)
+ )
+
+ model_config = ConfigDict(
+ extra="forbid",
+ protected_namespaces=(),
+ )
+
+ @model_validator(mode="after")
+ def validate_environment(self) -> Self:
+ """Validate that api key and python package exists in environment."""
+ for field_name in ("model", "repo_id"):
+ value = getattr(self, field_name)
+ if value and value.startswith(("http://", "https://")):
+ msg = f"`{field_name}` must be a HuggingFace repo ID, not a URL."
+ raise ValueError(msg)
+
+ huggingfacehub_api_token = self.huggingfacehub_api_token or os.getenv(
+ "HF_TOKEN"
+ )
+
+ try:
+ from huggingface_hub import ( # type: ignore[import]
+ AsyncInferenceClient,
+ InferenceClient,
+ )
+
+ if self.model:
+ self.repo_id = self.model
+ elif self.repo_id:
+ self.model = self.repo_id
+ else:
+ self.model = DEFAULT_MODEL
+ self.repo_id = DEFAULT_MODEL
+
+ client = InferenceClient(
+ model=self.model,
+ token=huggingfacehub_api_token,
+ provider=self.provider, # type: ignore[arg-type]
+ )
+
+ async_client = AsyncInferenceClient(
+ model=self.model,
+ token=huggingfacehub_api_token,
+ provider=self.provider, # type: ignore[arg-type]
+ )
+
+ if self.task not in VALID_TASKS:
+ msg = (
+ f"Got invalid task {self.task}, "
+ f"currently only {VALID_TASKS} are supported"
+ )
+ raise ValueError(msg)
+ self.client = client
+ self.async_client = async_client
+
+ except ImportError as e:
+ msg = (
+ "Could not import huggingface_hub python package. "
+ "Please install it with `pip install huggingface_hub`."
+ )
+ raise ImportError(msg) from e
+ return self
+
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
+ """Call out to HuggingFaceHub's embedding endpoint for embedding search docs.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+
+ """
+ # replace newlines, which can negatively affect performance.
+ texts = [text.replace("\n", " ") for text in texts]
+ _model_kwargs = self.model_kwargs or {}
+ # api doc: https://huggingface.github.io/text-embeddings-inference/#/Text%20Embeddings%20Inference/embed
+ responses = self.client.feature_extraction(text=texts, **_model_kwargs)
+ return responses.tolist()
+
+ async def aembed_documents(self, texts: list[str]) -> list[list[float]]:
+ """Async Call to HuggingFaceHub's embedding endpoint for embedding search docs.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ List of embeddings, one for each text.
+
+ """
+ # replace newlines, which can negatively affect performance.
+ texts = [text.replace("\n", " ") for text in texts]
+ _model_kwargs = self.model_kwargs or {}
+ responses = await self.async_client.feature_extraction(
+ text=texts, **_model_kwargs
+ )
+ return responses.tolist()
+
+ def embed_query(self, text: str) -> list[float]:
+ """Call out to HuggingFaceHub's embedding endpoint for embedding query text.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+
+ """
+ return self.embed_documents([text])[0]
+
+ async def aembed_query(self, text: str) -> list[float]:
+ """Async Call to HuggingFaceHub's embedding endpoint for embedding query text.
+
+ Args:
+ text: The text to embed.
+
+ Returns:
+ Embeddings for the text.
+
+ """
+ return (await self.aembed_documents([text]))[0]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c5acce55177b4adbd42cc17f7ebdf4e490be572
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/__init__.py
@@ -0,0 +1,9 @@
+from langchain_huggingface.llms.huggingface_endpoint import (
+ HuggingFaceEndpoint, # type: ignore[import-not-found]
+)
+from langchain_huggingface.llms.huggingface_pipeline import HuggingFacePipeline
+
+__all__ = [
+ "HuggingFaceEndpoint",
+ "HuggingFacePipeline",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b058cf775a3214407f58b38d8f234f76698bf091
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/__pycache__/huggingface_endpoint.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/__pycache__/huggingface_endpoint.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1159aa76e868a42b2d3d88abc10f886b77673d1e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/__pycache__/huggingface_endpoint.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/__pycache__/huggingface_pipeline.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/__pycache__/huggingface_pipeline.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2eeb9197354d267ccc599c79653387aa3375fa93
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/__pycache__/huggingface_pipeline.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/huggingface_endpoint.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/huggingface_endpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3a15b1c675c8ef35b8ac8c36ce4b3aff1a4354a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/huggingface_endpoint.py
@@ -0,0 +1,481 @@
+from __future__ import annotations
+
+import inspect
+import logging
+import os
+from collections.abc import AsyncIterator, Iterator, Mapping
+from typing import Any
+from urllib.parse import urlparse
+
+from langchain_core.callbacks import (
+ AsyncCallbackManagerForLLMRun,
+ CallbackManagerForLLMRun,
+)
+from langchain_core.language_models.llms import LLM
+from langchain_core.outputs import GenerationChunk
+from langchain_core.utils import from_env, get_pydantic_field_names
+from pydantic import ConfigDict, Field, model_validator
+from typing_extensions import Self
+
+logger = logging.getLogger(__name__)
+
+
+def _is_huggingface_hosted_url(url: str | None) -> bool:
+ """True if url is HF-hosted (huggingface.co or hf.space)."""
+ if not url:
+ return False
+ hostname = (urlparse(url).hostname or "").lower()
+ return (
+ hostname == "huggingface.co"
+ or hostname == "hf.space"
+ or hostname.endswith((".huggingface.co", ".hf.space"))
+ )
+
+
+VALID_TASKS = (
+ "text2text-generation",
+ "text-generation",
+ "summarization",
+ "conversational",
+)
+
+
+class HuggingFaceEndpoint(LLM):
+ """Hugging Face Endpoint. This works with any model that supports text generation (i.e. text completion) task.
+
+ To use this class, you should have installed the `huggingface_hub` package, and
+ the environment variable `HUGGINGFACEHUB_API_TOKEN` set with your API token,
+ or given as a named parameter to the constructor.
+
+ Example:
+ ```python
+ # Basic Example (no streaming)
+ model = HuggingFaceEndpoint(
+ endpoint_url="http://localhost:8010/",
+ max_new_tokens=512,
+ top_k=10,
+ top_p=0.95,
+ typical_p=0.95,
+ temperature=0.01,
+ repetition_penalty=1.03,
+ huggingfacehub_api_token="my-api-key",
+ )
+ print(model.invoke("What is Deep Learning?"))
+
+ # Streaming response example
+ from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
+
+ callbacks = [StreamingStdOutCallbackHandler()]
+ model = HuggingFaceEndpoint(
+ endpoint_url="http://localhost:8010/",
+ max_new_tokens=512,
+ top_k=10,
+ top_p=0.95,
+ typical_p=0.95,
+ temperature=0.01,
+ repetition_penalty=1.03,
+ callbacks=callbacks,
+ streaming=True,
+ huggingfacehub_api_token="my-api-key",
+ )
+ print(model.invoke("What is Deep Learning?"))
+
+ # Basic Example (no streaming) with Mistral-Nemo-Base-2407 model using a third-party provider (Novita).
+ model = HuggingFaceEndpoint(
+ repo_id="mistralai/Mistral-Nemo-Base-2407",
+ provider="novita",
+ max_new_tokens=100,
+ do_sample=False,
+ huggingfacehub_api_token="my-api-key",
+ )
+ print(model.invoke("What is Deep Learning?"))
+ ```
+ """ # noqa: E501
+
+ endpoint_url: str | None = None
+ """Endpoint URL to use. If repo_id is not specified then this needs to given or
+ should be pass as env variable in `HF_INFERENCE_ENDPOINT`"""
+
+ repo_id: str | None = None
+ """Repo to use. If endpoint_url is not specified then this needs to given"""
+
+ provider: str | None = None
+ """Name of the provider to use for inference with the model specified in `repo_id`.
+ e.g. "cerebras". if not specified, Defaults to "auto" i.e. the first of the
+ providers available for the model, sorted by the user's order in https://hf.co/settings/inference-providers.
+ available providers can be found in the [huggingface_hub documentation](https://huggingface.co/docs/huggingface_hub/guides/inference#supported-providers-and-tasks)."""
+
+ huggingfacehub_api_token: str | None = Field(
+ default_factory=from_env("HUGGINGFACEHUB_API_TOKEN", default=None)
+ )
+
+ max_new_tokens: int = 512
+ """Maximum number of generated tokens"""
+
+ top_k: int | None = None
+ """The number of highest probability vocabulary tokens to keep for
+ top-k-filtering."""
+
+ top_p: float | None = 0.95
+ """If set to < 1, only the smallest set of most probable tokens with probabilities
+ that add up to `top_p` or higher are kept for generation."""
+
+ typical_p: float | None = 0.95
+ """Typical Decoding mass. See [Typical Decoding for Natural Language
+ Generation](https://arxiv.org/abs/2202.00666) for more information."""
+
+ temperature: float | None = 0.8
+ """The value used to module the logits distribution."""
+
+ repetition_penalty: float | None = None
+ """The parameter for repetition penalty. 1.0 means no penalty.
+ See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details."""
+
+ return_full_text: bool = False
+ """Whether to prepend the prompt to the generated text"""
+
+ truncate: int | None = None
+ """Truncate inputs tokens to the given size"""
+
+ stop_sequences: list[str] = Field(default_factory=list)
+ """Stop generating tokens if a member of `stop_sequences` is generated"""
+
+ seed: int | None = None
+ """Random sampling seed"""
+
+ inference_server_url: str = ""
+ """text-generation-inference instance base url"""
+
+ timeout: int = 120
+ """Timeout in seconds"""
+
+ streaming: bool = False
+ """Whether to generate a stream of tokens asynchronously"""
+
+ do_sample: bool = False
+ """Activate logits sampling"""
+
+ watermark: bool = False
+ """Watermarking with [A Watermark for Large Language Models]
+ (https://arxiv.org/abs/2301.10226)"""
+
+ server_kwargs: dict[str, Any] = Field(default_factory=dict)
+ """Holds any text-generation-inference server parameters not explicitly specified"""
+
+ model_kwargs: dict[str, Any] = Field(default_factory=dict)
+ """Holds any model parameters valid for `call` not explicitly specified"""
+
+ model: str
+
+ client: Any = None
+
+ async_client: Any = None
+
+ task: str | None = None
+ """Task to call the model with. Should be a task that returns `generated_text`."""
+
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def build_extra(cls, values: dict[str, Any]) -> Any:
+ """Build extra kwargs from additional params that were passed in."""
+ all_required_field_names = get_pydantic_field_names(cls)
+ extra = values.get("model_kwargs", {})
+ for field_name in list(values):
+ if field_name in extra:
+ msg = f"Found {field_name} supplied twice."
+ raise ValueError(msg)
+ if field_name not in all_required_field_names:
+ logger.warning(
+ f"""WARNING! {field_name} is not default parameter.
+ {field_name} was transferred to model_kwargs.
+ Please make sure that {field_name} is what you intended."""
+ )
+ extra[field_name] = values.pop(field_name)
+
+ invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
+ if invalid_model_kwargs:
+ msg = (
+ f"Parameters {invalid_model_kwargs} should be specified explicitly. "
+ f"Instead they were passed in as part of `model_kwargs` parameter."
+ )
+ raise ValueError(msg)
+
+ values["model_kwargs"] = extra
+
+ # to correctly create the InferenceClient and AsyncInferenceClient
+ # in validate_environment, we need to populate values["model"].
+ # from InferenceClient docstring:
+ # model (`str`, `optional`):
+ # The model to run inference with. Can be a model id hosted on the Hugging
+ # Face Hub, e.g. `bigcode/starcoder`
+ # or a URL to a deployed Inference Endpoint. Defaults to `None`, in which
+ # case a recommended model is
+ # automatically selected for the task.
+
+ # this string could be in 3 places of descending priority:
+ # 2. values["model"] or values["endpoint_url"] or values["repo_id"]
+ # (equal priority - don't allow both set)
+ # 3. values["HF_INFERENCE_ENDPOINT"] (if none above set)
+
+ model = values.get("model")
+ endpoint_url = values.get("endpoint_url")
+ repo_id = values.get("repo_id")
+
+ if repo_id and repo_id.startswith(("http://", "https://")):
+ msg = (
+ "`repo_id` must be a HuggingFace repo ID, not a URL. "
+ "Use `endpoint_url` for direct endpoints."
+ )
+ raise ValueError(msg)
+
+ if sum([bool(model), bool(endpoint_url), bool(repo_id)]) > 1:
+ msg = (
+ "Please specify either a `model` OR an `endpoint_url` OR a `repo_id`,"
+ "not more than one."
+ )
+ raise ValueError(msg)
+ values["model"] = (
+ model or endpoint_url or repo_id or os.environ.get("HF_INFERENCE_ENDPOINT")
+ )
+ if not values["model"]:
+ msg = (
+ "Please specify a `model` or an `endpoint_url` or a `repo_id` for the "
+ "model."
+ )
+ raise ValueError(msg)
+ return values
+
+ @model_validator(mode="after")
+ def validate_environment(self) -> Self:
+ """Validate that package is installed and that the API token is valid."""
+ huggingfacehub_api_token = self.huggingfacehub_api_token or os.getenv(
+ "HF_TOKEN"
+ )
+ # Local/custom endpoint URL -> don't pass HF token (avoids 401s and egress).
+ if self.endpoint_url and not _is_huggingface_hosted_url(self.endpoint_url):
+ client_api_key: str | None = None
+ else:
+ client_api_key = huggingfacehub_api_token
+
+ from huggingface_hub import ( # type: ignore[import]
+ AsyncInferenceClient, # type: ignore[import]
+ InferenceClient, # type: ignore[import]
+ )
+
+ # Instantiate clients with supported kwargs
+ sync_supported_kwargs = set(inspect.signature(InferenceClient).parameters)
+ self.client = InferenceClient(
+ model=self.model,
+ timeout=self.timeout,
+ api_key=client_api_key,
+ provider=self.provider, # type: ignore[arg-type]
+ **{
+ key: value
+ for key, value in self.server_kwargs.items()
+ if key in sync_supported_kwargs
+ },
+ )
+
+ async_supported_kwargs = set(inspect.signature(AsyncInferenceClient).parameters)
+ self.async_client = AsyncInferenceClient(
+ model=self.model,
+ timeout=self.timeout,
+ api_key=client_api_key,
+ provider=self.provider, # type: ignore[arg-type]
+ **{
+ key: value
+ for key, value in self.server_kwargs.items()
+ if key in async_supported_kwargs
+ },
+ )
+ ignored_kwargs = (
+ set(self.server_kwargs.keys())
+ - sync_supported_kwargs
+ - async_supported_kwargs
+ )
+ if len(ignored_kwargs) > 0:
+ logger.warning(
+ f"Ignoring following parameters as they are not supported by the "
+ f"InferenceClient or AsyncInferenceClient: {ignored_kwargs}."
+ )
+
+ return self
+
+ @property
+ def _default_params(self) -> dict[str, Any]:
+ """Get the default parameters for calling text generation inference API."""
+ return {
+ "max_new_tokens": self.max_new_tokens,
+ "top_k": self.top_k,
+ "top_p": self.top_p,
+ "typical_p": self.typical_p,
+ "temperature": self.temperature,
+ "repetition_penalty": self.repetition_penalty,
+ "return_full_text": self.return_full_text,
+ "truncate": self.truncate,
+ "stop": self.stop_sequences,
+ "seed": self.seed,
+ "do_sample": self.do_sample,
+ "watermark": self.watermark,
+ **self.model_kwargs,
+ }
+
+ @property
+ def _identifying_params(self) -> Mapping[str, Any]:
+ """Get the identifying parameters."""
+ _model_kwargs = self.model_kwargs or {}
+ return {
+ "endpoint_url": self.endpoint_url,
+ "task": self.task,
+ "provider": self.provider,
+ "model_kwargs": _model_kwargs,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ """Return type of llm."""
+ return "huggingface_endpoint"
+
+ def _invocation_params(
+ self, runtime_stop: list[str] | None, **kwargs: Any
+ ) -> dict[str, Any]:
+ params = {**self._default_params, **kwargs}
+ params["stop"] = params["stop"] + (runtime_stop or [])
+ return params
+
+ def _call(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ """Call out to HuggingFace Hub's inference endpoint."""
+ invocation_params = self._invocation_params(stop, **kwargs)
+ if self.streaming:
+ completion = ""
+ for chunk in self._stream(
+ prompt, run_manager=run_manager, **invocation_params
+ ):
+ completion += chunk.text
+ return completion
+
+ response_text = self.client.text_generation(
+ prompt=prompt,
+ model=self.model,
+ **invocation_params,
+ )
+
+ # Maybe the generation has stopped at one of the stop sequences:
+ # then we remove this stop sequence from the end of the generated text
+ for stop_seq in invocation_params["stop"]:
+ if response_text[-len(stop_seq) :] == stop_seq:
+ response_text = response_text[: -len(stop_seq)]
+ return response_text
+
+ async def _acall(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> str:
+ invocation_params = self._invocation_params(stop, **kwargs)
+ if self.streaming:
+ completion = ""
+ async for chunk in self._astream(
+ prompt, run_manager=run_manager, **invocation_params
+ ):
+ completion += chunk.text
+ return completion
+
+ response_text = await self.async_client.text_generation(
+ prompt=prompt,
+ **invocation_params,
+ model=self.model,
+ stream=False,
+ )
+
+ # Maybe the generation has stopped at one of the stop sequences:
+ # then remove this stop sequence from the end of the generated text
+ for stop_seq in invocation_params["stop"]:
+ if response_text[-len(stop_seq) :] == stop_seq:
+ response_text = response_text[: -len(stop_seq)]
+ return response_text
+
+ def _stream(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> Iterator[GenerationChunk]:
+ invocation_params = self._invocation_params(stop, **kwargs)
+
+ for response in self.client.text_generation(
+ prompt, **invocation_params, stream=True
+ ):
+ # identify stop sequence in generated text, if any
+ stop_seq_found: str | None = None
+ for stop_seq in invocation_params["stop"]:
+ if stop_seq in response:
+ stop_seq_found = stop_seq
+
+ # identify text to yield
+ text: str | None = None
+ if stop_seq_found:
+ text = response[: response.index(stop_seq_found)]
+ else:
+ text = response
+
+ # yield text, if any
+ if text:
+ chunk = GenerationChunk(text=text)
+
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text)
+ yield chunk
+
+ # break if stop sequence found
+ if stop_seq_found:
+ break
+
+ async def _astream(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: AsyncCallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> AsyncIterator[GenerationChunk]:
+ invocation_params = self._invocation_params(stop, **kwargs)
+ async for response in await self.async_client.text_generation(
+ prompt, **invocation_params, stream=True
+ ):
+ # identify stop sequence in generated text, if any
+ stop_seq_found: str | None = None
+ for stop_seq in invocation_params["stop"]:
+ if stop_seq in response:
+ stop_seq_found = stop_seq
+
+ # identify text to yield
+ text: str | None = None
+ if stop_seq_found:
+ text = response[: response.index(stop_seq_found)]
+ else:
+ text = response
+
+ # yield text, if any
+ if text:
+ chunk = GenerationChunk(text=text)
+
+ if run_manager:
+ await run_manager.on_llm_new_token(chunk.text)
+ yield chunk
+
+ # break if stop sequence found
+ if stop_seq_found:
+ break
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/huggingface_pipeline.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/huggingface_pipeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba646f1309f181b60f023f8500cd6a4e3d561dff
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/llms/huggingface_pipeline.py
@@ -0,0 +1,422 @@
+from __future__ import annotations # type: ignore[import-not-found]
+
+import importlib.util
+import logging
+from collections.abc import Iterator, Mapping
+from typing import Any
+
+from langchain_core.callbacks import CallbackManagerForLLMRun
+from langchain_core.language_models.llms import BaseLLM
+from langchain_core.outputs import Generation, GenerationChunk, LLMResult
+from pydantic import ConfigDict, model_validator
+
+from langchain_huggingface.utils.import_utils import (
+ IMPORT_ERROR,
+ is_ipex_available,
+ is_openvino_available,
+ is_optimum_intel_available,
+ is_optimum_intel_version,
+)
+
+DEFAULT_MODEL_ID = "gpt2"
+DEFAULT_TASK = "text-generation"
+VALID_TASKS = (
+ "text2text-generation",
+ "text-generation",
+ "image-text-to-text",
+ "summarization",
+ "translation",
+)
+DEFAULT_BATCH_SIZE = 4
+_MIN_OPTIMUM_VERSION = "1.21"
+
+
+logger = logging.getLogger(__name__)
+
+
+class HuggingFacePipeline(BaseLLM):
+ """HuggingFace Pipeline API.
+
+ To use, you should have the `transformers` python package installed.
+
+ Only supports `text-generation`, `text2text-generation`, `image-text-to-text`,
+ `summarization` and `translation` for now.
+
+ Example using from_model_id:
+ ```python
+ from langchain_huggingface import HuggingFacePipeline
+
+ hf = HuggingFacePipeline.from_model_id(
+ model_id="gpt2",
+ task="text-generation",
+ pipeline_kwargs={"max_new_tokens": 10},
+ )
+ ```
+
+ Example passing pipeline in directly:
+ ```python
+ from langchain_huggingface import HuggingFacePipeline
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
+
+ model_id = "gpt2"
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
+ model = AutoModelForCausalLM.from_pretrained(model_id)
+ pipe = pipeline(
+ "text-generation",
+ model=model,
+ tokenizer=tokenizer,
+ max_new_tokens=10,
+ )
+ hf = HuggingFacePipeline(pipeline=pipe)
+ ```
+ """
+
+ pipeline: Any = None
+
+ model_id: str | None = None
+ """The model name. If not set explicitly by the user,
+ it will be inferred from the provided pipeline (if available).
+ If neither is provided, the DEFAULT_MODEL_ID will be used."""
+
+ model_kwargs: dict | None = None
+ """Keyword arguments passed to the model."""
+
+ pipeline_kwargs: dict | None = None
+ """Keyword arguments passed to the pipeline."""
+
+ batch_size: int = DEFAULT_BATCH_SIZE
+ """Batch size to use when passing multiple documents to generate."""
+
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def pre_init_validator(cls, values: dict[str, Any]) -> dict[str, Any]:
+ """Ensure model_id is set either by pipeline or user input."""
+ if "model_id" not in values:
+ if values.get("pipeline"):
+ values["model_id"] = values["pipeline"].model.name_or_path
+ else:
+ values["model_id"] = DEFAULT_MODEL_ID
+ return values
+
+ @classmethod
+ def from_model_id(
+ cls,
+ model_id: str,
+ task: str,
+ backend: str = "default",
+ device: int | None = None,
+ device_map: str | None = None,
+ model_kwargs: dict | None = None,
+ pipeline_kwargs: dict | None = None,
+ batch_size: int = DEFAULT_BATCH_SIZE,
+ **kwargs: Any,
+ ) -> HuggingFacePipeline:
+ """Construct the pipeline object from model_id and task."""
+ try:
+ from transformers import ( # type: ignore[import]
+ AutoModelForCausalLM,
+ AutoModelForSeq2SeqLM,
+ AutoTokenizer,
+ )
+ from transformers import pipeline as hf_pipeline # type: ignore[import]
+
+ except ImportError as e:
+ msg = (
+ "Could not import transformers python package. "
+ "Please install it with `pip install transformers`."
+ )
+ raise ValueError(msg) from e
+
+ _model_kwargs = model_kwargs.copy() if model_kwargs else {}
+ if device_map is not None:
+ if device is not None:
+ msg = (
+ "Both `device` and `device_map` are specified. "
+ "`device` will override `device_map`. "
+ "You will most likely encounter unexpected behavior."
+ "Please remove `device` and keep "
+ "`device_map`."
+ )
+ raise ValueError(msg)
+
+ if "device_map" in _model_kwargs:
+ msg = "`device_map` is already specified in `model_kwargs`."
+ raise ValueError(msg)
+
+ _model_kwargs["device_map"] = device_map
+ tokenizer = AutoTokenizer.from_pretrained(model_id, **_model_kwargs)
+
+ if backend in {"openvino", "ipex"}:
+ if task not in VALID_TASKS:
+ msg = (
+ f"Got invalid task {task}, "
+ f"currently only {VALID_TASKS} are supported"
+ )
+ raise ValueError(msg)
+
+ err_msg = f"Backend: {backend} {IMPORT_ERROR.format(f'optimum[{backend}]')}"
+ if not is_optimum_intel_available():
+ raise ImportError(err_msg)
+
+ # TODO: upgrade _MIN_OPTIMUM_VERSION to 1.22 after release
+ min_optimum_version = (
+ "1.22"
+ if backend == "ipex" and task != "text-generation"
+ else _MIN_OPTIMUM_VERSION
+ )
+ if is_optimum_intel_version("<", min_optimum_version):
+ msg = (
+ f"Backend: {backend} requires optimum-intel>="
+ f"{min_optimum_version}. You can install it with pip: "
+ "`pip install --upgrade --upgrade-strategy eager "
+ f"`optimum[{backend}]`."
+ )
+ raise ImportError(msg)
+
+ if backend == "openvino":
+ if not is_openvino_available():
+ raise ImportError(err_msg)
+
+ from optimum.intel import ( # type: ignore[import]
+ OVModelForCausalLM,
+ OVModelForSeq2SeqLM,
+ )
+
+ model_cls = (
+ OVModelForCausalLM
+ if task == "text-generation"
+ else OVModelForSeq2SeqLM
+ )
+ else:
+ if not is_ipex_available():
+ raise ImportError(err_msg)
+
+ if task == "text-generation":
+ from optimum.intel import (
+ IPEXModelForCausalLM, # type: ignore[import]
+ )
+
+ model_cls = IPEXModelForCausalLM
+ else:
+ from optimum.intel import (
+ IPEXModelForSeq2SeqLM, # type: ignore[import]
+ )
+
+ model_cls = IPEXModelForSeq2SeqLM
+
+ else:
+ model_cls = (
+ AutoModelForCausalLM
+ if task == "text-generation"
+ else AutoModelForSeq2SeqLM
+ )
+
+ model = model_cls.from_pretrained(model_id, **_model_kwargs)
+
+ if tokenizer.pad_token is None:
+ if model.config.pad_token_id is not None:
+ tokenizer.pad_token_id = model.config.pad_token_id
+ elif model.config.eos_token_id is not None and isinstance(
+ model.config.eos_token_id, int
+ ):
+ tokenizer.pad_token_id = model.config.eos_token_id
+ elif tokenizer.eos_token_id is not None:
+ tokenizer.pad_token_id = tokenizer.eos_token_id
+ else:
+ tokenizer.add_special_tokens({"pad_token": "[PAD]"})
+
+ if (
+ (
+ getattr(model, "is_loaded_in_4bit", False)
+ or getattr(model, "is_loaded_in_8bit", False)
+ )
+ and device is not None
+ and backend == "default"
+ ):
+ logger.warning(
+ f"Setting the `device` argument to None from {device} to avoid "
+ "the error caused by attempting to move the model that was already "
+ "loaded on the GPU using the Accelerate module to the same or "
+ "another device."
+ )
+ device = None
+
+ if (
+ device is not None
+ and importlib.util.find_spec("torch") is not None
+ and backend == "default"
+ ):
+ import torch
+
+ cuda_device_count = torch.cuda.device_count()
+ if device < -1 or (device >= cuda_device_count):
+ msg = (
+ f"Got device=={device}, "
+ f"device is required to be within [-1, {cuda_device_count})"
+ )
+ raise ValueError(msg)
+ if device_map is not None and device < 0:
+ device = None
+ if device is not None and device < 0 and cuda_device_count > 0:
+ logger.warning(
+ "Device has %d GPUs available. "
+ "Provide device={deviceId} to `from_model_id` to use available"
+ "GPUs for execution. deviceId is -1 (default) for CPU and "
+ "can be a positive integer associated with CUDA device id.",
+ cuda_device_count,
+ )
+ if device is not None and device_map is not None and backend == "openvino":
+ logger.warning("Please set device for OpenVINO through: `model_kwargs`")
+ if "trust_remote_code" in _model_kwargs:
+ _model_kwargs = {
+ k: v for k, v in _model_kwargs.items() if k != "trust_remote_code"
+ }
+ _pipeline_kwargs = pipeline_kwargs or {}
+ pipeline = hf_pipeline( # type: ignore[call-overload]
+ task=task,
+ model=model,
+ tokenizer=tokenizer,
+ device=device,
+ batch_size=batch_size,
+ model_kwargs=_model_kwargs,
+ **_pipeline_kwargs,
+ )
+ if pipeline.task not in VALID_TASKS:
+ msg = (
+ f"Got invalid task {pipeline.task}, "
+ f"currently only {VALID_TASKS} are supported"
+ )
+ raise ValueError(msg)
+ return cls(
+ pipeline=pipeline,
+ model_id=model_id,
+ model_kwargs=_model_kwargs,
+ pipeline_kwargs=_pipeline_kwargs,
+ batch_size=batch_size,
+ **kwargs,
+ )
+
+ @property
+ def _identifying_params(self) -> Mapping[str, Any]:
+ """Get the identifying parameters."""
+ return {
+ "model_id": self.model_id,
+ "model_kwargs": self.model_kwargs,
+ "pipeline_kwargs": self.pipeline_kwargs,
+ }
+
+ @property
+ def _llm_type(self) -> str:
+ return "huggingface_pipeline"
+
+ def _generate(
+ self,
+ prompts: list[str],
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> LLMResult:
+ # List to hold all results
+ text_generations: list[str] = []
+ pipeline_kwargs = kwargs.get("pipeline_kwargs", {})
+ skip_prompt = kwargs.get("skip_prompt", False)
+
+ for i in range(0, len(prompts), self.batch_size):
+ batch_prompts = prompts[i : i + self.batch_size]
+
+ # Process batch of prompts
+ responses = self.pipeline(
+ batch_prompts,
+ **pipeline_kwargs,
+ )
+
+ # Process each response in the batch
+ for j, response in enumerate(responses):
+ if isinstance(response, list):
+ # if model returns multiple generations, pick the top one
+ response = response[0]
+
+ if (
+ self.pipeline.task == "text-generation"
+ or self.pipeline.task == "text2text-generation"
+ or self.pipeline.task == "image-text-to-text"
+ ):
+ text = response["generated_text"]
+ elif self.pipeline.task == "summarization":
+ text = response["summary_text"]
+ elif self.pipeline.task in "translation":
+ text = response["translation_text"]
+ else:
+ msg = (
+ f"Got invalid task {self.pipeline.task}, "
+ f"currently only {VALID_TASKS} are supported"
+ )
+ raise ValueError(msg)
+ if skip_prompt:
+ text = text[len(batch_prompts[j]) :]
+ # Append the processed text to results
+ text_generations.append(text)
+
+ return LLMResult(
+ generations=[[Generation(text=text)] for text in text_generations]
+ )
+
+ def _stream(
+ self,
+ prompt: str,
+ stop: list[str] | None = None,
+ run_manager: CallbackManagerForLLMRun | None = None,
+ **kwargs: Any,
+ ) -> Iterator[GenerationChunk]:
+ from threading import Thread
+
+ import torch
+ from transformers import (
+ StoppingCriteria,
+ StoppingCriteriaList,
+ TextIteratorStreamer,
+ )
+
+ pipeline_kwargs = kwargs.get("pipeline_kwargs", {})
+ skip_prompt = kwargs.get("skip_prompt", True)
+
+ if stop is not None:
+ stop = self.pipeline.tokenizer.convert_tokens_to_ids(stop)
+ stopping_ids_list = stop or []
+
+ class StopOnTokens(StoppingCriteria):
+ def __call__(
+ self,
+ input_ids: torch.LongTensor,
+ scores: torch.FloatTensor,
+ **kwargs: Any,
+ ) -> bool:
+ return any(input_ids[0][-1] == stop_id for stop_id in stopping_ids_list)
+
+ stopping_criteria = StoppingCriteriaList([StopOnTokens()])
+
+ streamer = TextIteratorStreamer(
+ self.pipeline.tokenizer,
+ timeout=60.0,
+ skip_prompt=skip_prompt,
+ skip_special_tokens=True,
+ )
+ generation_kwargs = dict(
+ text_inputs=prompt,
+ streamer=streamer,
+ stopping_criteria=stopping_criteria,
+ **pipeline_kwargs,
+ )
+ t1 = Thread(target=self.pipeline, kwargs=generation_kwargs)
+ t1.start()
+
+ for char in streamer:
+ chunk = GenerationChunk(text=char)
+ if run_manager:
+ run_manager.on_llm_new_token(chunk.text, chunk=chunk)
+
+ yield chunk
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/tests/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..698fc005776e96e415e93c952819db69f4459c00
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/tests/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/tests/integration_tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/tests/integration_tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/tests/integration_tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/tests/integration_tests/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c878da24c6b3e3ca5fc7dc82c556f8b5178ba851
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/tests/integration_tests/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/utils/__pycache__/import_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/utils/__pycache__/import_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d20775f6db390098a027b68297638c039659799
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/utils/__pycache__/import_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/utils/import_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/utils/import_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f217517a9804918467093d45edba19e0b110908a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_huggingface/utils/import_utils.py
@@ -0,0 +1,114 @@
+from __future__ import annotations
+
+import importlib.metadata
+import importlib.util
+import operator as op
+
+from packaging import version
+
+STR_OPERATION_TO_FUNC = {
+ ">": op.gt,
+ ">=": op.ge,
+ "==": op.eq,
+ "!=": op.ne,
+ "<=": op.le,
+ "<": op.lt,
+}
+
+
+_optimum_available = importlib.util.find_spec("optimum") is not None
+_optimum_version = "N/A"
+if _optimum_available:
+ try:
+ _optimum_version = importlib.metadata.version("optimum")
+ except importlib.metadata.PackageNotFoundError:
+ _optimum_available = False
+
+
+_optimum_intel_available = (
+ _optimum_available and importlib.util.find_spec("optimum.intel") is not None
+)
+_optimum_intel_version = "N/A"
+if _optimum_intel_available:
+ try:
+ _optimum_intel_version = importlib.metadata.version("optimum-intel")
+ except importlib.metadata.PackageNotFoundError:
+ _optimum_intel_available = False
+
+
+_ipex_available = importlib.util.find_spec("intel_extension_for_pytorch") is not None
+
+_openvino_available = importlib.util.find_spec("openvino") is not None
+
+
+# This function was copied from: https://github.com/huggingface/accelerate/blob/874c4967d94badd24f893064cc3bef45f57cadf7/src/accelerate/utils/versions.py#L319
+def compare_versions(
+ library_or_version: str | version.Version,
+ operation: str,
+ requirement_version: str,
+) -> bool:
+ """Compare a library version to some requirement using a given operation.
+
+ Args:
+ library_or_version:
+ A library name or a version to check.
+ operation:
+ A string representation of an operator, such as `">"` or `"<="`.
+ requirement_version:
+ The version to compare the library version against
+
+ """
+ if operation not in STR_OPERATION_TO_FUNC:
+ msg = (
+ f"`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys())}"
+ f", received {operation}"
+ )
+ raise ValueError(msg)
+ if isinstance(library_or_version, str):
+ library_or_version = version.parse(
+ importlib.metadata.version(library_or_version)
+ )
+ return STR_OPERATION_TO_FUNC[operation](
+ library_or_version, version.parse(requirement_version)
+ )
+
+
+def is_optimum_available() -> bool:
+ return _optimum_available
+
+
+def is_optimum_intel_available() -> bool:
+ return _optimum_intel_available
+
+
+def is_ipex_available() -> bool:
+ return _ipex_available
+
+
+def is_openvino_available() -> bool:
+ return _openvino_available
+
+
+def is_optimum_version(operation: str, reference_version: str) -> bool:
+ """Compare the current Optimum version to a given reference with an operation."""
+ if not _optimum_version:
+ return False
+ return compare_versions(
+ version.parse(_optimum_version), operation, reference_version
+ )
+
+
+def is_optimum_intel_version(operation: str, reference_version: str) -> bool:
+ """Compare current Optimum Intel version to a given reference with an operation."""
+ if not _optimum_intel_version:
+ return False
+ return compare_versions(
+ version.parse(_optimum_intel_version), operation, reference_version
+ )
+
+
+IMPORT_ERROR = """
+requires the {0} library but it was not found in your environment.
+You can install it with pip: `pip install {0}`.
+Please note that you may need to restart your runtime after installation.
+"""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_protocol-0.0.15.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_protocol-0.0.15.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..5600729a39188be2387b22ba3016de16c112bc25
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_protocol-0.0.15.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 LangChain, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_protocol/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_protocol/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3858b30b66ec4b6e14a006a9f9dda7c4edfbe3a1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_protocol/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_protocol/__pycache__/protocol.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_protocol/__pycache__/protocol.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea79046454c15f13e6efb4a6ca4f463de44e92b6
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_protocol/__pycache__/protocol.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ebb7da733367a001a515e44cc59c71df9855aae
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e984eb129139a484fde43e7c886692866049aaa6
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/character.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/character.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e771942707f0dfa00eda41a293a2bc2ce02b251
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/character.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/html.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/html.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a7df27db7101386d41394c2c59606b64ce62540
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/html.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/json.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/json.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e99a187a07db925414543928df6281d5eaa3b46a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/json.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/jsx.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/jsx.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c842acb62eeed15139d574d3a21f34594ef920ae
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/jsx.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/konlpy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/konlpy.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ac6d55b501e15dc327c3872dfd74102633d66e4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/konlpy.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/latex.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/latex.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b44dfafd9ad5efb52452a9580b90cc13c2f0c878
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/latex.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/markdown.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/markdown.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0229357d2264b500dc0c3ced5ab425083767ff9f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/markdown.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/nltk.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/nltk.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79fb0de1fa20ab45376a4cd7fefebefe59df3276
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/nltk.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/python.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/python.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6673c5895f86aa3af5c03f75e23acee52a752e97
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/python.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/sentence_transformers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/sentence_transformers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d6644b88d8e8201d04ac1f86c2913681be44162
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/sentence_transformers.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/spacy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/spacy.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0225e3ff033296905b0523c75107a6c85c95e9c6
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/__pycache__/spacy.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/xsl/converting_to_header.xslt b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/xsl/converting_to_header.xslt
new file mode 100644
index 0000000000000000000000000000000000000000..620e13f54b1bd4904472bb9fee2e919d30f4dab2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langchain_text_splitters/xsl/converting_to_header.xslt
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c81ce8f05e94a1e0bef671830ac5a7dc84f37b64
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/_expect.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/_expect.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e6e55fd78c17104bdcb2c847645ab9d94b8ac16
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/_expect.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/_runtime_overrides.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/_runtime_overrides.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dbca2d6f8138317946642dbebd0fd2b906d63247
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/_runtime_overrides.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/anonymizer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/anonymizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b3a5d1d32fda7f6e6904f91e4609d5dcd0dfc04c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/anonymizer.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/middleware.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/middleware.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..502578f3206efa670946c68c5322be7f75dc1989
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/middleware.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/prompt_cache.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/prompt_cache.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26195acecbeaf64f99cce275e8f2204ac09fd287
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/prompt_cache.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/pytest_plugin.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/pytest_plugin.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9640890081bc68423a95c4fc0eae45dc683e2b88
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/pytest_plugin.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/run_helpers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/run_helpers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c9e8739e40d420736f2ab927d6fa954b4d358be
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/run_helpers.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/run_trees.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/run_trees.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1225557d067f6a19cc69513fa37ad1a3e0d3640
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/run_trees.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/schemas.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/schemas.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44e17ac586503528f282b851dd6b43ac9293ec74
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/schemas.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1ce1840442bd678404afb1489be613e1ba228337
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/uuid.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/uuid.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..89636bccee4e486f1dc4cd45d83e3cfd173fe207
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/__pycache__/uuid.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe24992e425e50ebf6e8110c554d8d380caee73f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_aiter.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_aiter.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20f11a5ad37f7538e9fc67c76a159bcc05c02dfa
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_aiter.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_background_thread.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_background_thread.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..729aba67abad1c6ee3f7aa6ba65bddb633fab726
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_background_thread.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_beta_decorator.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_beta_decorator.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e168f9879a42cec7c42d090bfb779eec849745a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_beta_decorator.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_compressed_traces.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_compressed_traces.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..24e87759be4299da46343b793cffce2f30b5d546
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_compressed_traces.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_constants.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_constants.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7980a2ede5e3afd1be94548cbabc04dc65584b85
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_constants.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_context.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_context.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33951efe2a198898d3411a4e72e814f4159b441c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_context.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_edit_distance.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_edit_distance.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e46c582659d11b428680e66a937e8adba4c89e55
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_edit_distance.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_embedding_distance.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_embedding_distance.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cc90fca259957637bd72c662f5d9ce9cc9674442
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_embedding_distance.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_hub.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_hub.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff12c245e15b548181ccf9ee5af946025a5ea371
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_hub.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_multipart.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_multipart.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0016ca51f5d20ed0d658e02b956767fc662318d8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_multipart.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_operations.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_operations.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01e47f351b27292f67a21386e2d7afe8d58ac52e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_operations.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_orjson.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_orjson.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e082b8225283dcf6c503d85157b2c1db0009d5e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_orjson.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_otel_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_otel_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..49f9d361105eb019131947714dd3caf2a08e8600
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_otel_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_patch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_patch.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b9637495d187c4fe3f6dfb030468476d81c6674
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_patch.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_profiles.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_profiles.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0d6afb21b5c712ded8def0282ed10634b8c715bd
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_profiles.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_serde.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_serde.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3435800b9438b1a3b3080d26d8817692c29ee0c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_serde.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_uuid.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_uuid.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b346e70528b357e51afde5e3e0da61cddbe06c64
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/__pycache__/_uuid.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_aiter.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_aiter.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a984c7201f4a3e81ae3f623eb903e66ffccf999
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_aiter.py
@@ -0,0 +1,382 @@
+"""Adapted.
+
+Original source:
+https://github.com/maxfischer2781/asyncstdlib/blob/master/asyncstdlib/itertools.py
+MIT License
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextvars
+import functools
+import inspect
+from collections import deque
+from collections.abc import (
+ AsyncGenerator,
+ AsyncIterable,
+ AsyncIterator,
+ Awaitable,
+ Coroutine,
+ Iterable,
+ Iterator,
+)
+from contextlib import AbstractAsyncContextManager
+from typing import (
+ Any,
+ Callable,
+ Generic,
+ Optional,
+ TypeVar,
+ Union,
+ cast,
+ overload,
+)
+
+from langsmith._runtime_overrides import get_runtime_overrides
+
+T = TypeVar("T")
+
+_no_default = object()
+
+
+# https://github.com/python/cpython/blob/main/Lib/test/test_asyncgen.py#L54
+# before 3.10, the builtin anext() was not available
+def py_anext(
+ iterator: AsyncIterator[T], default: Union[T, Any] = _no_default
+) -> Awaitable[Union[T, None, Any]]:
+ """Pure-Python implementation of anext() for testing purposes.
+
+ Closely matches the builtin anext() C implementation.
+ Can be used to compare the built-in implementation of the inner
+ coroutines machinery to C-implementation of __anext__() and send()
+ or throw() on the returned generator.
+ """
+ try:
+ __anext__ = cast(
+ Callable[[AsyncIterator[T]], Awaitable[T]], type(iterator).__anext__
+ )
+ except AttributeError:
+ raise TypeError(f"{iterator!r} is not an async iterator")
+
+ if default is _no_default:
+ return __anext__(iterator)
+
+ async def anext_impl() -> Union[T, Any]:
+ try:
+ # The C code is way more low-level than this, as it implements
+ # all methods of the iterator protocol. In this implementation
+ # we're relying on higher-level coroutine concepts, but that's
+ # exactly what we want -- crosstest pure-Python high-level
+ # implementation and low-level C anext() iterators.
+ return await __anext__(iterator)
+ except StopAsyncIteration:
+ return default
+
+ return anext_impl()
+
+
+class NoLock:
+ """Dummy lock that provides the proper interface but no protection."""
+
+ async def __aenter__(self) -> None:
+ pass
+
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
+ return False
+
+
+async def tee_peer(
+ iterator: AsyncIterator[T],
+ # the buffer specific to this peer
+ buffer: deque[T],
+ # the buffers of all peers, including our own
+ peers: list[deque[T]],
+ lock: AbstractAsyncContextManager[Any],
+) -> AsyncGenerator[T, None]:
+ """Iterate over :py:func:`~.tee`."""
+ try:
+ while True:
+ if not buffer:
+ async with lock:
+ # Another peer produced an item while we were waiting for the lock.
+ # Proceed with the next loop iteration to yield the item.
+ if buffer:
+ continue
+ try:
+ item = await iterator.__anext__()
+ except StopAsyncIteration:
+ break
+ else:
+ # Append to all buffers, including our own. We'll fetch our
+ # item from the buffer again, instead of yielding it directly.
+ # This ensures the proper item ordering if any of our peers
+ # are fetching items concurrently. They may have buffered their
+ # item already.
+ for peer_buffer in peers:
+ peer_buffer.append(item)
+ yield buffer.popleft()
+ finally:
+ async with lock:
+ # this peer is done – remove its buffer
+ for idx, peer_buffer in enumerate(peers): # pragma: no branch
+ if peer_buffer is buffer:
+ peers.pop(idx)
+ break
+ # if we are the last peer, try and close the iterator
+ if not peers and hasattr(iterator, "aclose"):
+ await iterator.aclose()
+
+
+class Tee(Generic[T]):
+ """Create ``n`` separate asynchronous iterators over ``iterable``.
+
+ This splits a single ``iterable`` into multiple iterators, each providing
+ the same items in the same order.
+ All child iterators may advance separately but pare the same items
+ from ``iterable`` -- when the most advanced iterator retrieves an item,
+ it is buffered until the least advanced iterator has yielded it as well.
+ A ``tee`` works lazily and can handle an infinite ``iterable``, provided
+ that all iterators advance.
+
+ ```python
+ async def derivative(sensor_data):
+ previous, current = a.tee(sensor_data, n=2)
+ await a.anext(previous) # advance one iterator
+ return a.map(operator.sub, previous, current)
+ ```
+
+ Unlike :py:func:`itertools.tee`, :py:func:`~.tee` returns a custom type instead
+ of a :py:class:`tuple`. Like a tuple, it can be indexed, iterated and unpacked
+ to get the child iterators. In addition, its :py:meth:`~.tee.aclose` method
+ immediately closes all children, and it can be used in an ``async with`` context
+ for the same effect.
+
+ If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*
+ provide these items. Also, ``tee`` must internally buffer each item until the
+ last iterator has yielded it; if the most and least advanced iterator differ
+ by most data, using a :py:class:`list` is more efficient (but not lazy).
+
+ If the underlying iterable is concurrency safe (``anext`` may be awaited
+ concurrently) the resulting iterators are concurrency safe as well. Otherwise,
+ the iterators are safe if there is only ever one single "most advanced" iterator.
+ To enforce sequential use of ``anext``, provide a ``lock``
+ - e.g. an :py:class:`asyncio.Lock` instance in an :py:mod:`asyncio` application -
+ and access is automatically synchronised.
+ """
+
+ def __init__(
+ self,
+ iterable: AsyncIterator[T],
+ n: int = 2,
+ *,
+ lock: Optional[AbstractAsyncContextManager[Any]] = None,
+ ):
+ self._iterator = iterable.__aiter__() # before 3.10 aiter() doesn't exist
+ self._buffers: list[deque[T]] = [deque() for _ in range(n)]
+ self._children = tuple(
+ tee_peer(
+ iterator=self._iterator,
+ buffer=buffer,
+ peers=self._buffers,
+ lock=lock if lock is not None else NoLock(),
+ )
+ for buffer in self._buffers
+ )
+
+ def __len__(self) -> int:
+ return len(self._children)
+
+ @overload
+ def __getitem__(self, item: int) -> AsyncIterator[T]: ...
+
+ @overload
+ def __getitem__(self, item: slice) -> tuple[AsyncIterator[T], ...]: ...
+
+ def __getitem__(
+ self, item: Union[int, slice]
+ ) -> Union[AsyncIterator[T], tuple[AsyncIterator[T], ...]]:
+ return self._children[item]
+
+ def __iter__(self) -> Iterator[AsyncIterator[T]]:
+ yield from self._children
+
+ async def __aenter__(self) -> Tee[T]:
+ return self
+
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
+ await self.aclose()
+ return False
+
+ async def aclose(self) -> None:
+ for child in self._children:
+ await child.aclose()
+
+
+atee = Tee
+
+
+async def async_zip(*async_iterables):
+ """Async version of zip."""
+ # Before Python 3.10, aiter() was not available
+ iterators = [iterable.__aiter__() for iterable in async_iterables]
+ while True:
+ try:
+ items = await asyncio.gather(
+ *(py_anext(iterator) for iterator in iterators)
+ )
+ yield tuple(items)
+ except StopAsyncIteration:
+ break
+
+
+def ensure_async_iterator(
+ iterable: Union[Iterable, AsyncIterable],
+) -> AsyncIterator:
+ if hasattr(iterable, "__anext__"):
+ return cast(AsyncIterator, iterable)
+ elif hasattr(iterable, "__aiter__"):
+ return cast(AsyncIterator, iterable.__aiter__())
+ else:
+
+ class AsyncIteratorWrapper:
+ def __init__(self, iterable: Iterable):
+ self._iterator = iter(iterable)
+
+ async def __anext__(self):
+ try:
+ return next(self._iterator)
+ except StopIteration:
+ raise StopAsyncIteration
+
+ def __aiter__(self):
+ return self
+
+ return AsyncIteratorWrapper(iterable)
+
+
+def aiter_with_concurrency(
+ n: Optional[int],
+ generator: AsyncIterator[Coroutine[None, None, T]],
+ *,
+ _eager_consumption_timeout: float = 0,
+) -> AsyncGenerator[T, None]:
+ """Process async generator with max parallelism.
+
+ Args:
+ n: The number of tasks to run concurrently.
+ generator: The async generator to process.
+ _eager_consumption_timeout: If set, check for completed tasks after
+ each iteration and yield their results. This can be used to
+ consume the generator eagerly while still respecting the concurrency
+ limit.
+
+ Yields:
+ The processed items yielded by the async generator.
+ """
+ if n == 0:
+
+ async def consume():
+ async for item in generator:
+ yield await item
+
+ return consume()
+ semaphore = cast(
+ asyncio.Semaphore, asyncio.Semaphore(n) if n is not None else NoLock()
+ )
+
+ async def process_item(ix: int, item):
+ async with semaphore:
+ res = await item
+ return (ix, res)
+
+ async def process_generator():
+ tasks = {}
+ accepts_context = asyncio_accepts_context()
+ ix = 0
+ async for item in generator:
+ if accepts_context:
+ context = contextvars.copy_context()
+ task = asyncio.create_task(process_item(ix, item), context=context)
+ else:
+ task = asyncio.create_task(process_item(ix, item))
+ tasks[ix] = task
+ ix += 1
+ if _eager_consumption_timeout > 0:
+ try:
+ for _fut in asyncio.as_completed(
+ tasks.values(),
+ timeout=_eager_consumption_timeout,
+ ):
+ task_idx, res = await _fut
+ yield res
+ del tasks[task_idx]
+ except asyncio.TimeoutError:
+ pass
+ if n is not None and len(tasks) >= n:
+ done, _ = await asyncio.wait(
+ tasks.values(), return_when=asyncio.FIRST_COMPLETED
+ )
+ for task in done:
+ task_idx, res = task.result()
+ yield res
+ del tasks[task_idx]
+
+ for task in asyncio.as_completed(tasks.values()):
+ _, res = await task
+ yield res
+
+ return process_generator()
+
+
+def accepts_context(callable: Callable[..., Any]) -> bool:
+ """Check if a callable accepts a context argument."""
+ try:
+ return inspect.signature(callable).parameters.get("context") is not None
+ except ValueError:
+ return False
+
+
+# Ported from Python 3.9+ to support Python 3.8
+async def aio_to_thread(
+ ctx: contextvars.Context,
+ func,
+ /,
+ *args,
+ **kwargs,
+):
+ """Run ``func`` in a separate thread, inside ``ctx``.
+
+ ``ctx`` is the :class:`~contextvars.Context` in which ``func`` is invoked.
+ Callers that want default isolation should pass
+ ``contextvars.copy_context()``; callers with a specific Context
+ (e.g. :func:`trace`) pass it directly so subsequent reads from that
+ Context see the mutations.
+
+ Return a coroutine that can be awaited to get the eventual result of ``func``.
+ """
+ overrides = get_runtime_overrides()
+ if overrides.aio_to_thread is not None:
+ return await overrides.aio_to_thread(
+ _default_aio_to_thread, ctx, func, *args, **kwargs
+ )
+ return await _default_aio_to_thread(ctx, func, *args, **kwargs)
+
+
+async def _default_aio_to_thread(
+ ctx: contextvars.Context,
+ func,
+ /,
+ *args,
+ **kwargs,
+):
+ """Default implementation of aio_to_thread using run_in_executor."""
+ loop = asyncio.get_running_loop()
+ func_call = functools.partial(ctx.run, func, *args, **kwargs)
+ return await loop.run_in_executor(None, func_call)
+
+
+@functools.lru_cache(maxsize=1)
+def asyncio_accepts_context():
+ """Check if the current asyncio event loop accepts a context argument."""
+ return accepts_context(asyncio.create_task)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_background_thread.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_background_thread.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb17c813eb5ee5c651a6b50208c1eb60eff37a30
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_background_thread.py
@@ -0,0 +1,968 @@
+from __future__ import annotations
+
+import concurrent.futures as cf
+import copy
+import functools
+import io
+import logging
+import sys
+import threading
+import time
+import weakref
+from multiprocessing import cpu_count
+from queue import Empty, Queue
+from typing import TYPE_CHECKING, Any, Optional, Union, cast
+
+from langsmith import schemas as ls_schemas
+from langsmith import utils as ls_utils
+from langsmith._internal._compressed_traces import ZSTD_AVAILABLE, CompressedTraces
+from langsmith._internal._constants import (
+ _AUTO_SCALE_DOWN_NEMPTY_TRIGGER,
+ _AUTO_SCALE_UP_NTHREADS_LIMIT,
+ _AUTO_SCALE_UP_QSIZE_TRIGGER,
+ _BOUNDARY,
+)
+from langsmith._internal._operations import (
+ SerializedFeedbackOperation,
+ SerializedRunOperation,
+ combine_serialized_queue_operations,
+)
+
+if TYPE_CHECKING:
+ from opentelemetry.context.context import Context # type: ignore[import]
+
+ from langsmith.client import Client
+
+logger = logging.getLogger("langsmith.client")
+
+LANGSMITH_CLIENT_THREAD_POOL = cf.ThreadPoolExecutor(max_workers=cpu_count())
+
+
+def _group_batch_by_api_endpoint(
+ batch: list[TracingQueueItem],
+) -> dict[
+ tuple[
+ Optional[str],
+ Optional[str],
+ Optional[str],
+ Optional[str],
+ Optional[str],
+ Optional[str],
+ ],
+ list[TracingQueueItem],
+]:
+ """Group batch items by endpoint and auth combination."""
+ from collections import defaultdict
+
+ grouped = defaultdict(list)
+ for item in batch:
+ key = (
+ item.api_url,
+ item.api_key,
+ item.service_key,
+ item.tenant_id,
+ item.authorization,
+ item.cookie,
+ )
+ grouped[key].append(item)
+ return grouped
+
+
+@functools.total_ordering
+class TracingQueueItem:
+ """An item in the tracing queue.
+
+ Attributes:
+ priority (str): The priority of the item.
+ item (Any): The item itself.
+ otel_context (Optional[Context]): The OTEL context of the item.
+ """
+
+ priority: str
+ item: Union[SerializedRunOperation, SerializedFeedbackOperation]
+ api_url: Optional[str]
+ api_key: Optional[str]
+ service_key: Optional[str]
+ tenant_id: Optional[str]
+ authorization: Optional[str]
+ cookie: Optional[str]
+ otel_context: Optional[Context]
+
+ __slots__ = (
+ "priority",
+ "item",
+ "api_key",
+ "api_url",
+ "service_key",
+ "tenant_id",
+ "authorization",
+ "cookie",
+ "otel_context",
+ )
+
+ def __init__(
+ self,
+ priority: str,
+ item: Union[SerializedRunOperation, SerializedFeedbackOperation],
+ api_key: Optional[str] = None,
+ api_url: Optional[str] = None,
+ service_key: Optional[str] = None,
+ tenant_id: Optional[str] = None,
+ authorization: Optional[str] = None,
+ cookie: Optional[str] = None,
+ otel_context: Optional[Context] = None,
+ ) -> None:
+ self.priority = priority
+ self.item = item
+ self.api_key = api_key
+ self.api_url = api_url
+ self.service_key = service_key
+ self.tenant_id = tenant_id
+ self.authorization = authorization
+ self.cookie = cookie
+ self.otel_context = otel_context
+
+ def __lt__(self, other: TracingQueueItem) -> bool:
+ return (self.priority, self.item.__class__) < (
+ other.priority,
+ other.item.__class__,
+ )
+
+ def __eq__(self, other: object) -> bool:
+ return isinstance(other, TracingQueueItem) and (
+ self.priority,
+ self.item.__class__,
+ ) == (other.priority, other.item.__class__)
+
+
+def _tracing_thread_drain_queue(
+ tracing_queue: Queue, limit: int = 100, block: bool = True, max_size_bytes: int = 0
+) -> list[TracingQueueItem]:
+ next_batch: list[TracingQueueItem] = []
+ current_size = 0
+
+ try:
+ # wait 250ms for the first item, then
+ # - drain the queue with a 50ms block timeout
+ # - stop draining if we hit either count or size limit
+ # shorter drain timeout is used instead of non-blocking calls to
+ # avoid creating too many small batches
+ if item := tracing_queue.get(block=block, timeout=0.25):
+ next_batch.append(item)
+ if max_size_bytes > 0:
+ current_size += item.item.calculate_serialized_size()
+ # If first item already exceeds limit, return just this item
+ if current_size > max_size_bytes:
+ return next_batch
+
+ # Continue draining until we hit count limit OR size limit
+ while True:
+ try:
+ item = tracing_queue.get(block=block, timeout=0.05)
+ except Empty:
+ break
+
+ # Add the item first
+ next_batch.append(item)
+
+ # Then check size limit AFTER adding the item
+ if max_size_bytes > 0:
+ current_size += item.item.calculate_serialized_size()
+ # If we've exceeded size limit, stop here
+ # (item is included in this batch)
+ if current_size > max_size_bytes:
+ break
+
+ # Check count limit AFTER adding the item
+ if limit and len(next_batch) >= limit:
+ break
+ except Empty:
+ pass
+ return next_batch
+
+
+def _tracing_thread_drain_compressed_buffer(
+ client: Client, size_limit: int = 100, size_limit_bytes: int | None = 20_971_520
+) -> tuple[Optional[io.BytesIO], Optional[tuple[int, int]]]:
+ try:
+ if client.compressed_traces is None:
+ return None, None
+ with client.compressed_traces.lock:
+ pre_compressed_size = client.compressed_traces.uncompressed_size
+
+ size_limit_bytes = client._max_batch_size_bytes or size_limit_bytes
+
+ if size_limit is not None and size_limit <= 0:
+ raise ValueError(f"size_limit must be positive; got {size_limit}")
+ if size_limit_bytes is not None and size_limit_bytes < 0:
+ raise ValueError(
+ f"size_limit_bytes must be nonnegative; got {size_limit_bytes}"
+ )
+
+ if (
+ size_limit_bytes is None or pre_compressed_size < size_limit_bytes
+ ) and (
+ size_limit is None or client.compressed_traces.trace_count < size_limit
+ ):
+ return None, None
+
+ # Write final boundary and close compression stream
+ client.compressed_traces.compressor_writer.write(
+ f"--{_BOUNDARY}--\r\n".encode()
+ )
+ client.compressed_traces.compressor_writer.close()
+ current_size = client.compressed_traces.buffer.tell()
+
+ filled_buffer = client.compressed_traces.buffer
+ setattr(
+ cast(Any, filled_buffer),
+ "context",
+ client.compressed_traces._context,
+ )
+
+ compressed_traces_info = (pre_compressed_size, current_size)
+
+ client.compressed_traces.reset()
+
+ filled_buffer.seek(0)
+ return (filled_buffer, compressed_traces_info)
+ except Exception:
+ logger.error(
+ "LangSmith tracing error: Failed to submit trace data.\n"
+ "This does not affect your application's runtime.\n"
+ "Error details:",
+ exc_info=True,
+ )
+ # exceptions are logged elsewhere, but we need to make sure the
+ # background thread continues to run
+ return None, None
+
+
+def _process_buffered_run_ops_batch(
+ client: Client,
+ batch_to_process: list[tuple[str, dict, dict[str, Optional[str]]]],
+) -> None:
+ """Process a batch of run operations asynchronously."""
+ try:
+ # Extract just the run dictionaries for process_buffered_run_ops
+ run_dicts = [run_data for _, run_data, _ in batch_to_process]
+ original_ids = [run.get("id") for run in run_dicts]
+
+ # Apply process_buffered_run_ops transformation
+ if client._process_buffered_run_ops is None:
+ raise RuntimeError(
+ "process_buffered_run_ops should not be None when processing batch"
+ )
+ processed_runs = list(client._process_buffered_run_ops(run_dicts))
+
+ # Validate that the transformation preserves run count and IDs
+ if len(processed_runs) != len(run_dicts):
+ raise ValueError(
+ f"process_buffered_run_ops must return the same number of runs. "
+ f"Expected {len(run_dicts)}, got {len(processed_runs)}"
+ )
+
+ processed_ids = [run.get("id") for run in processed_runs]
+ if processed_ids != original_ids:
+ raise ValueError(
+ f"process_buffered_run_ops must preserve run IDs in the same order. "
+ f"Expected {original_ids}, got {processed_ids}"
+ )
+
+ # Process each run and add to compressed traces
+ for (operation, _, write_ctx), processed_run in zip(
+ batch_to_process, processed_runs
+ ):
+ if operation == "post":
+ client._create_run(processed_run, **write_ctx)
+ elif operation == "patch":
+ client._update_run(processed_run, **write_ctx)
+
+ # Trigger data available event
+ if client._data_available_event:
+ client._data_available_event.set()
+ except Exception:
+ # Log errors but don't crash the background thread
+ logger.error(
+ "LangSmith buffered run ops processing error: Failed to process batch.\n"
+ "This does not affect your application's runtime.\n"
+ "Error details:",
+ exc_info=True,
+ )
+
+
+def _tracing_thread_handle_batch(
+ client: Client,
+ tracing_queue: Queue,
+ batch: list[TracingQueueItem],
+ use_multipart: bool,
+ mark_task_done: bool = True,
+ ops: Optional[
+ list[Union[SerializedRunOperation, SerializedFeedbackOperation]]
+ ] = None,
+) -> None:
+ """Handle a batch of tracing queue items by sending them to LangSmith.
+
+ Args:
+ client: The LangSmith client to use for sending data.
+ tracing_queue: The queue containing tracing items (used for task_done calls).
+ batch: List of tracing queue items to process.
+ use_multipart: Whether to use multipart endpoint for sending data.
+ mark_task_done: Whether to mark queue tasks as done after processing.
+ Set to False when called from parallel execution to avoid double counting.
+ ops: Pre-combined serialized operations to use instead of combining from batch.
+ If None, operations will be combined from the batch items.
+ """
+ try:
+ # Group batch items by (api_url, auth) combination
+ grouped_batches = _group_batch_by_api_endpoint(batch)
+
+ for (
+ api_url,
+ api_key,
+ service_key,
+ tenant_id,
+ authorization,
+ cookie,
+ ), group_batch in grouped_batches.items():
+ if not ops:
+ group_ops = combine_serialized_queue_operations(
+ [item.item for item in group_batch]
+ )
+ else:
+ group_ids = {item.item.id for item in group_batch}
+ group_ops = [op for op in ops if op.id in group_ids]
+
+ if use_multipart:
+ client._multipart_ingest_ops(
+ group_ops,
+ api_url=api_url,
+ api_key=api_key,
+ service_key=service_key,
+ tenant_id=tenant_id,
+ authorization=authorization,
+ cookie=cookie,
+ )
+ else:
+ if any(isinstance(op, SerializedFeedbackOperation) for op in group_ops):
+ logger.warning(
+ "Feedback operations are not supported in non-multipart mode"
+ )
+ group_ops = [
+ op
+ for op in group_ops
+ if not isinstance(op, SerializedFeedbackOperation)
+ ]
+ client._batch_ingest_run_ops(
+ cast(list[SerializedRunOperation], group_ops),
+ api_url=api_url,
+ api_key=api_key,
+ service_key=service_key,
+ tenant_id=tenant_id,
+ authorization=authorization,
+ cookie=cookie,
+ )
+
+ except Exception as e:
+ logger.error(
+ "LangSmith tracing error: Failed to submit trace data.\n"
+ "This does not affect your application's runtime.\n"
+ "Error details:",
+ exc_info=True,
+ )
+ client._invoke_tracing_error_callback(e)
+ finally:
+ if mark_task_done and tracing_queue is not None:
+ for _ in batch:
+ try:
+ tracing_queue.task_done()
+ except ValueError as e:
+ if "task_done() called too many times" in str(e):
+ # This can happen during shutdown when multiple threads
+ # process the same queue items. It's harmless.
+ logger.debug(
+ f"Ignoring harmless task_done error during shutdown: {e}"
+ )
+ else:
+ raise
+
+
+def _otel_tracing_thread_handle_batch(
+ client: Client,
+ tracing_queue: Queue,
+ batch: list[TracingQueueItem],
+ mark_task_done: bool = True,
+ ops: Optional[
+ list[Union[SerializedRunOperation, SerializedFeedbackOperation]]
+ ] = None,
+) -> None:
+ """Handle a batch of tracing queue items by exporting them to OTEL.
+
+ Args:
+ client: The LangSmith client containing the OTEL exporter.
+ tracing_queue: The queue containing tracing items (used for task_done calls).
+ batch: List of tracing queue items to process.
+ mark_task_done: Whether to mark queue tasks as done after processing.
+ Set to False when called from parallel execution to avoid double counting.
+ ops: Pre-combined serialized operations to use instead of combining from batch.
+ If None, operations will be combined from the batch items.
+ """
+ try:
+ if ops is None:
+ ops = combine_serialized_queue_operations([item.item for item in batch])
+
+ run_ops = [op for op in ops if isinstance(op, SerializedRunOperation)]
+ otel_context_map = {
+ item.item.id: item.otel_context
+ for item in batch
+ if isinstance(item.item, SerializedRunOperation)
+ }
+ if run_ops:
+ if client.otel_exporter is not None:
+ client.otel_exporter.export_batch(run_ops, otel_context_map)
+ else:
+ logger.error(
+ "LangSmith tracing error: Failed to submit OTEL trace data.\n"
+ "This does not affect your application's runtime.\n"
+ "Error details: client.otel_exporter is None"
+ )
+
+ except Exception as e:
+ logger.error(
+ "OTEL tracing error: Failed to submit trace data.\n"
+ "This does not affect your application's runtime.\n"
+ "Error details:",
+ exc_info=True,
+ )
+ client._invoke_tracing_error_callback(e)
+ finally:
+ if mark_task_done and tracing_queue is not None:
+ for _ in batch:
+ try:
+ tracing_queue.task_done()
+ except ValueError as e:
+ if "task_done() called too many times" in str(e):
+ # This can happen during shutdown when multiple threads
+ # process the same queue items. It's harmless.
+ logger.debug(
+ f"Ignoring harmless task_done error during shutdown: {e}"
+ )
+ else:
+ raise
+
+
+def _hybrid_tracing_thread_handle_batch(
+ client: Client,
+ tracing_queue: Queue,
+ batch: list[TracingQueueItem],
+ use_multipart: bool,
+ mark_task_done: bool = True,
+) -> None:
+ """Handle a batch of tracing queue items by sending to both both LangSmith and OTEL.
+
+ Args:
+ client: The LangSmith client to use for sending data.
+ tracing_queue: The queue containing tracing items (used for task_done calls).
+ batch: List of tracing queue items to process.
+ use_multipart: Whether to use multipart endpoint for LangSmith.
+ mark_task_done: Whether to mark queue tasks as done after processing.
+ Set to False primarily for testing when items weren't actually queued.
+ """
+ # Combine operations once to avoid race conditions
+ ops = combine_serialized_queue_operations([item.item for item in batch])
+
+ # Create copies for each thread to avoid shared mutation
+ langsmith_ops = copy.deepcopy(ops)
+ otel_ops = copy.deepcopy(ops)
+
+ try:
+ # Use ThreadPoolExecutor for parallel execution
+ with cf.ThreadPoolExecutor(max_workers=2) as executor:
+ # Submit both tasks
+ future_langsmith = executor.submit(
+ _tracing_thread_handle_batch,
+ client,
+ tracing_queue,
+ batch,
+ use_multipart,
+ False, # Don't mark tasks done - we'll do it once at the end
+ langsmith_ops,
+ )
+ future_otel = executor.submit(
+ _otel_tracing_thread_handle_batch,
+ client,
+ tracing_queue,
+ batch,
+ False, # Don't mark tasks done - we'll do it once at the end
+ otel_ops,
+ )
+
+ # Wait for both to complete
+ future_langsmith.result()
+ future_otel.result()
+ except RuntimeError as e:
+ if "cannot schedule new futures after interpreter shutdown" in str(e):
+ # During interpreter shutdown, ThreadPoolExecutor is blocked,
+ # fall back to sequential processing
+ logger.debug(
+ "Interpreter shutting down, falling back to sequential processing"
+ )
+ _tracing_thread_handle_batch(
+ client, tracing_queue, batch, use_multipart, False, langsmith_ops
+ )
+ _otel_tracing_thread_handle_batch(
+ client, tracing_queue, batch, False, otel_ops
+ )
+ else:
+ raise
+
+ # Mark all tasks as done once, only if requested
+ if mark_task_done and tracing_queue is not None:
+ for _ in batch:
+ try:
+ tracing_queue.task_done()
+ except ValueError as e:
+ if "task_done() called too many times" in str(e):
+ # This can happen during shutdown when multiple threads
+ # process the same queue items. It's harmless.
+ logger.debug(
+ f"Ignoring harmless task_done error during shutdown: {e}"
+ )
+ else:
+ raise
+
+
+def get_size_limit_from_env() -> Optional[int]:
+ size_limit_str = ls_utils.get_env_var(
+ "BATCH_INGEST_SIZE_LIMIT",
+ )
+ if size_limit_str is not None:
+ try:
+ return int(size_limit_str)
+ except ValueError:
+ logger.warning(
+ f"Invalid value for BATCH_INGEST_SIZE_LIMIT: {size_limit_str}, "
+ "continuing with default"
+ )
+ return None
+
+
+def _ensure_ingest_config(
+ info: ls_schemas.LangSmithInfo,
+) -> ls_schemas.BatchIngestConfig:
+ default_config = ls_schemas.BatchIngestConfig(
+ use_multipart_endpoint=True,
+ size_limit_bytes=None, # Note this field is not used here
+ size_limit=100,
+ scale_up_nthreads_limit=_AUTO_SCALE_UP_NTHREADS_LIMIT,
+ scale_up_qsize_trigger=_AUTO_SCALE_UP_QSIZE_TRIGGER,
+ scale_down_nempty_trigger=_AUTO_SCALE_DOWN_NEMPTY_TRIGGER,
+ )
+ if not info:
+ return default_config
+ try:
+ if not info.batch_ingest_config:
+ return default_config
+ env_size_limit = get_size_limit_from_env()
+ if env_size_limit is not None:
+ info.batch_ingest_config["size_limit"] = env_size_limit
+ return info.batch_ingest_config
+ except BaseException:
+ return default_config
+
+
+def tracing_control_thread_func(client_ref: weakref.ref[Client]) -> None:
+ client = client_ref()
+ if client is None:
+ return
+ tracing_queue = client.tracing_queue
+ assert tracing_queue is not None
+ batch_ingest_config = _ensure_ingest_config(client.info)
+ size_limit: int = batch_ingest_config["size_limit"]
+ scale_up_nthreads_limit: int = batch_ingest_config["scale_up_nthreads_limit"]
+ scale_up_qsize_trigger: int = batch_ingest_config["scale_up_qsize_trigger"]
+ use_multipart = not client._multipart_disabled and batch_ingest_config.get(
+ "use_multipart_endpoint", True
+ )
+
+ sub_threads: list[threading.Thread] = []
+ # 1 for this func, 1 for getrefcount, 1 for _get_data_type_cached
+ num_known_refs = 3
+
+ # Disable compression if explicitly set, using OpenTelemetry, or zstd unavailable
+ if not ZSTD_AVAILABLE:
+ logger.debug(
+ "zstandard package is not installed. "
+ "Falling back to uncompressed multipart ingestion."
+ )
+ disable_compression = (
+ ls_utils.is_env_var_truish("DISABLE_RUN_COMPRESSION")
+ or client._tracing_mode in ("otel", "hybrid")
+ or not ZSTD_AVAILABLE
+ )
+ if not disable_compression and use_multipart:
+ if not (client.info.instance_flags or {}).get(
+ "zstd_compression_enabled", False
+ ):
+ logger.warning(
+ "Run compression is not enabled. Please update to the latest "
+ "version of LangSmith. Falling back to regular multipart ingestion."
+ )
+ else:
+ client._futures = weakref.WeakSet()
+ client.compressed_traces = CompressedTraces()
+ client._data_available_event = threading.Event()
+ threading.Thread(
+ target=tracing_control_thread_func_compress_parallel,
+ args=(weakref.ref(client),),
+ daemon=client._use_daemon_threads,
+ ).start()
+
+ num_known_refs += 1
+
+ def keep_thread_active() -> bool:
+ # if `client.cleanup()` was called, stop thread
+ if not client or (
+ hasattr(client, "_manual_cleanup") and client._manual_cleanup
+ ):
+ logger.debug("Client is being cleaned up, stopping tracing thread")
+ return False
+ if not threading.main_thread().is_alive():
+ # main thread is dead. should not be active
+ logger.debug("Main thread is dead, stopping tracing thread")
+ return False
+
+ if hasattr(sys, "getrefcount"):
+ # check if client refs count indicates we're the only remaining
+ # reference to the client
+ refcount = sys.getrefcount(client)
+ threshold = num_known_refs + len(sub_threads)
+ should_keep_thread = refcount > threshold
+ if not should_keep_thread:
+ logger.debug(
+ "Client refs count indicates we're the only remaining reference "
+ "to the client, stopping tracing thread "
+ "(refcount=%d, threshold=%d)",
+ refcount,
+ threshold,
+ )
+ return should_keep_thread
+ else:
+ # in PyPy, there is no sys.getrefcount attribute
+ # for now, keep thread alive
+ return True
+
+ # loop until
+ while keep_thread_active():
+ for thread in sub_threads:
+ if not thread.is_alive():
+ sub_threads.remove(thread)
+ if (
+ len(sub_threads) < scale_up_nthreads_limit
+ and tracing_queue.qsize() > scale_up_qsize_trigger
+ ):
+ new_thread = threading.Thread(
+ target=_tracing_sub_thread_func,
+ args=(weakref.ref(client), use_multipart),
+ daemon=client._use_daemon_threads,
+ )
+ sub_threads.append(new_thread)
+ new_thread.start()
+
+ mode = client._tracing_mode
+ max_batch_size = (
+ client._max_batch_size_bytes
+ or batch_ingest_config.get("size_limit_bytes")
+ or 0
+ )
+ if next_batch := _tracing_thread_drain_queue(
+ tracing_queue, limit=size_limit, max_size_bytes=max_batch_size
+ ):
+ if mode == "hybrid":
+ logger.debug("Handling batch in hybrid mode")
+ _hybrid_tracing_thread_handle_batch(
+ client, tracing_queue, next_batch, use_multipart
+ )
+ elif mode == "otel":
+ logger.debug("Handling batch in otel mode")
+ _otel_tracing_thread_handle_batch(client, tracing_queue, next_batch)
+ else:
+ logger.debug("Handling batch in langsmith mode")
+ _tracing_thread_handle_batch(
+ client, tracing_queue, next_batch, use_multipart
+ )
+
+ # drain the queue on exit
+ logger.debug(
+ "Tracing thread draining queue on exit: qsize=%d",
+ tracing_queue.qsize(),
+ )
+ mode = client._tracing_mode
+ max_batch_size = (
+ client._max_batch_size_bytes or batch_ingest_config.get("size_limit_bytes") or 0
+ )
+ while next_batch := _tracing_thread_drain_queue(
+ tracing_queue, limit=size_limit, block=False, max_size_bytes=max_batch_size
+ ):
+ if mode == "hybrid":
+ logger.debug("Draining batch in hybrid mode")
+ _hybrid_tracing_thread_handle_batch(
+ client, tracing_queue, next_batch, use_multipart
+ )
+ elif mode == "otel":
+ logger.debug("Draining batch in otel mode")
+ _otel_tracing_thread_handle_batch(client, tracing_queue, next_batch)
+ else:
+ logger.debug("Draining batch in langsmith mode")
+ _tracing_thread_handle_batch(
+ client, tracing_queue, next_batch, use_multipart
+ )
+ logger.debug("Tracing control thread is shutting down")
+
+
+def tracing_control_thread_func_compress_parallel(
+ client_ref: weakref.ref[Client], flush_interval: float = 0.5
+) -> None:
+ client = client_ref()
+ if client is None:
+ return
+ logger.debug("Tracing control thread func compress parallel called")
+ if (
+ client.compressed_traces is None
+ or client._data_available_event is None
+ or client._futures is None
+ ):
+ logger.error(
+ "LangSmith tracing error: Required compression attributes not "
+ "initialized.\nThis may affect trace submission but does not "
+ "impact your application's runtime."
+ )
+ return
+
+ batch_ingest_config = _ensure_ingest_config(client.info)
+ size_limit: int = batch_ingest_config["size_limit"]
+ size_limit_bytes = client._max_batch_size_bytes or batch_ingest_config.get(
+ "size_limit_bytes", 20_971_520
+ )
+ # One for this func, one for the parent thread, one for getrefcount,
+ # one for _get_data_type_cached
+ num_known_refs = 4
+
+ def keep_thread_active() -> bool:
+ # if `client.cleanup()` was called, stop thread
+ if not client or (
+ hasattr(client, "_manual_cleanup") and client._manual_cleanup
+ ):
+ logger.debug("Client is being cleaned up, stopping compression thread")
+ return False
+ if not threading.main_thread().is_alive():
+ # main thread is dead. should not be active
+ logger.debug("Main thread is dead, stopping compression thread")
+ return False
+ if hasattr(sys, "getrefcount"):
+ # check if client refs count indicates we're the only remaining
+ # reference to the client
+ refcount = sys.getrefcount(client)
+ should_keep_thread = refcount > num_known_refs
+ if not should_keep_thread:
+ logger.debug(
+ "Client refs count indicates we're the only remaining reference "
+ "to the client, stopping compression thread "
+ "(refcount=%d, threshold=%d)",
+ refcount,
+ num_known_refs,
+ )
+ return should_keep_thread
+ else:
+ # in PyPy, there is no sys.getrefcount attribute
+ # for now, keep thread alive
+ return True
+
+ last_flush_time = time.monotonic()
+
+ while True:
+ triggered = client._data_available_event.wait(timeout=0.05)
+ if not keep_thread_active():
+ break
+
+ # If data arrived, clear the event and attempt a drain
+ if triggered:
+ client._data_available_event.clear()
+
+ data_stream, compressed_traces_info = (
+ _tracing_thread_drain_compressed_buffer
+ )(client, size_limit, size_limit_bytes)
+ # If we have data, submit the send request
+ if data_stream is not None:
+ try:
+ future = LANGSMITH_CLIENT_THREAD_POOL.submit(
+ client._send_compressed_multipart_req,
+ data_stream,
+ compressed_traces_info,
+ )
+ client._futures.add(future)
+ except RuntimeError:
+ client._send_compressed_multipart_req(
+ data_stream,
+ compressed_traces_info,
+ )
+ last_flush_time = time.monotonic()
+
+ else:
+ if (time.monotonic() - last_flush_time) >= flush_interval:
+ (
+ data_stream,
+ compressed_traces_info,
+ ) = _tracing_thread_drain_compressed_buffer(
+ client, size_limit=1, size_limit_bytes=1
+ )
+ if data_stream is not None:
+ try:
+ cf.wait(
+ [
+ LANGSMITH_CLIENT_THREAD_POOL.submit(
+ client._send_compressed_multipart_req,
+ data_stream,
+ compressed_traces_info,
+ )
+ ]
+ )
+ except RuntimeError:
+ client._send_compressed_multipart_req(
+ data_stream,
+ compressed_traces_info,
+ )
+ last_flush_time = time.monotonic()
+
+ # Drain the buffer on exit (final flush)
+ try:
+ trace_count = (
+ client.compressed_traces.trace_count
+ if client.compressed_traces is not None
+ else 0
+ )
+ logger.debug(
+ "Compression thread final flush: trace_count=%d",
+ trace_count,
+ )
+ (
+ final_data_stream,
+ compressed_traces_info,
+ ) = _tracing_thread_drain_compressed_buffer(
+ client, size_limit=1, size_limit_bytes=1
+ )
+ if final_data_stream is not None:
+ logger.debug(
+ "Compression thread final flush: sending %d bytes",
+ final_data_stream.getbuffer().nbytes,
+ )
+ try:
+ cf.wait(
+ [
+ LANGSMITH_CLIENT_THREAD_POOL.submit(
+ client._send_compressed_multipart_req,
+ final_data_stream,
+ compressed_traces_info,
+ )
+ ]
+ )
+ logger.debug("Compression thread final flush: send completed")
+ except RuntimeError:
+ logger.debug(
+ "Compression thread final flush: thread pool shutdown, "
+ "sending synchronously"
+ )
+ client._send_compressed_multipart_req(
+ final_data_stream,
+ compressed_traces_info,
+ )
+ logger.debug("Compression thread final flush: sync send completed")
+ else:
+ logger.debug("Compression thread final flush: no data to send")
+
+ except Exception:
+ logger.error(
+ "LangSmith tracing error: Failed during final cleanup.\n"
+ "This does not affect your application's runtime.\n"
+ "Error details:",
+ exc_info=True,
+ )
+ logger.debug("Compressed traces control thread is shutting down")
+
+
+def _tracing_sub_thread_func(
+ client_ref: weakref.ref[Client],
+ use_multipart: bool,
+) -> None:
+ client = client_ref()
+ if client is None:
+ return
+ try:
+ if not client.info:
+ return
+ except BaseException as e:
+ logger.debug("Error in tracing control thread: %s", e)
+ return
+ tracing_queue = client.tracing_queue
+ assert tracing_queue is not None
+ batch_ingest_config = _ensure_ingest_config(client.info)
+ size_limit = batch_ingest_config.get("size_limit", 100)
+ seen_successive_empty_queues = 0
+
+ # loop until
+ while (
+ # the main thread dies
+ threading.main_thread().is_alive()
+ # or we've seen the queue empty 4 times in a row
+ and seen_successive_empty_queues
+ <= batch_ingest_config["scale_down_nempty_trigger"]
+ ):
+ max_batch_size = (
+ client._max_batch_size_bytes
+ or batch_ingest_config.get("size_limit_bytes")
+ or 0
+ )
+ if next_batch := _tracing_thread_drain_queue(
+ tracing_queue, limit=size_limit, max_size_bytes=max_batch_size
+ ):
+ seen_successive_empty_queues = 0
+
+ mode = client._tracing_mode
+ if mode == "hybrid":
+ logger.debug("Sub-thread handling batch in hybrid mode")
+ _hybrid_tracing_thread_handle_batch(
+ client, tracing_queue, next_batch, use_multipart
+ )
+ elif mode == "otel":
+ logger.debug("Sub-thread handling batch in otel mode")
+ _otel_tracing_thread_handle_batch(client, tracing_queue, next_batch)
+ else:
+ logger.debug("Sub-thread handling batch in langsmith mode")
+ _tracing_thread_handle_batch(
+ client, tracing_queue, next_batch, use_multipart
+ )
+ else:
+ seen_successive_empty_queues += 1
+
+ # drain the queue on exit
+ mode = client._tracing_mode
+ max_batch_size = (
+ client._max_batch_size_bytes or batch_ingest_config.get("size_limit_bytes") or 0
+ )
+ while next_batch := _tracing_thread_drain_queue(
+ tracing_queue, limit=size_limit, block=False, max_size_bytes=max_batch_size
+ ):
+ if mode == "hybrid":
+ logger.debug("Sub-thread draining batch in hybrid mode")
+ _hybrid_tracing_thread_handle_batch(
+ client, tracing_queue, next_batch, use_multipart
+ )
+ elif mode == "otel":
+ logger.debug("Sub-thread draining batch in otel mode")
+ _otel_tracing_thread_handle_batch(client, tracing_queue, next_batch)
+ else:
+ logger.debug("Sub-thread draining batch in langsmith mode")
+ _tracing_thread_handle_batch(
+ client, tracing_queue, next_batch, use_multipart
+ )
+ logger.debug("Tracing control sub-thread is shutting down")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_beta_decorator.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_beta_decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..edbcaee86d87faa122c1b635c24d3b743e57fa24
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_beta_decorator.py
@@ -0,0 +1,21 @@
+import functools
+import warnings
+from typing import Callable
+
+
+class LangSmithBetaWarning(UserWarning):
+ """This is a warning specific to the LangSmithBeta module."""
+
+
+@functools.lru_cache(maxsize=100)
+def _warn_once(message: str, stacklevel: int = 2) -> None:
+ warnings.warn(message, LangSmithBetaWarning, stacklevel=stacklevel)
+
+
+def warn_beta(func: Callable) -> Callable:
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ _warn_once(f"Function {func.__name__} is in beta.", stacklevel=3)
+ return func(*args, **kwargs)
+
+ return wrapper
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_compressed_traces.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_compressed_traces.py
new file mode 100644
index 0000000000000000000000000000000000000000..731e455cff2ed20296519f079e34f0e392e0ef02
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_compressed_traces.py
@@ -0,0 +1,56 @@
+import io
+import threading
+from typing import Optional
+
+from langsmith import utils as ls_utils
+
+try:
+ from zstandard import ZstdCompressor # type: ignore[import]
+
+ ZSTD_AVAILABLE = True
+except ImportError:
+ ZSTD_AVAILABLE = False
+
+compression_level = int(ls_utils.get_env_var("RUN_COMPRESSION_LEVEL") or 1)
+compression_threads = int(ls_utils.get_env_var("RUN_COMPRESSION_THREADS") or -1)
+
+DEFAULT_MAX_UNCOMPRESSED_QUEUE_BYTES = 1024 * 1024 * 1024 # 1GB
+
+
+class CompressedTraces:
+ def __init__(self, max_uncompressed_size_bytes: Optional[int] = None) -> None:
+ if not ZSTD_AVAILABLE:
+ raise ImportError(
+ "zstandard is required for compressed trace ingestion. "
+ "Install it with `pip install zstandard` or set the environment "
+ "variable LANGSMITH_DISABLE_RUN_COMPRESSION=true to disable "
+ "compression."
+ )
+ # Configure the maximum total uncompressed size for the in-memory queue.
+ if max_uncompressed_size_bytes is None:
+ max_bytes_str = ls_utils.get_env_var("MAX_INGEST_MEMORY_BYTES")
+ if max_bytes_str is not None:
+ max_uncompressed_size_bytes = int(max_bytes_str)
+ else:
+ max_uncompressed_size_bytes = DEFAULT_MAX_UNCOMPRESSED_QUEUE_BYTES
+
+ self.max_uncompressed_size_bytes = max_uncompressed_size_bytes
+
+ self.buffer: io.BytesIO = io.BytesIO()
+ self.trace_count: int = 0
+ self.lock = threading.Lock()
+ self.uncompressed_size: int = 0
+ self._context: list[str] = []
+
+ self.compressor_writer = ZstdCompressor(
+ level=compression_level, threads=compression_threads
+ ).stream_writer(self.buffer, closefd=False)
+
+ def reset(self) -> None:
+ self.buffer = io.BytesIO()
+ self.trace_count = 0
+ self.uncompressed_size = 0
+ self._context = []
+ self.compressor_writer = ZstdCompressor(
+ level=compression_level, threads=-1
+ ).stream_writer(self.buffer, closefd=False)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_constants.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..575e8dead4fd509d9e1e7cda74d5a28d9426d90d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_constants.py
@@ -0,0 +1,9 @@
+import uuid
+
+_SIZE_LIMIT_BYTES = 20_971_520 # 20MB by default
+_AUTO_SCALE_UP_QSIZE_TRIGGER = 200
+_AUTO_SCALE_UP_NTHREADS_LIMIT = 32
+_AUTO_SCALE_DOWN_NEMPTY_TRIGGER = 4
+_BLOCKSIZE_BYTES = 1024 * 1024 # 1MB
+_BOUNDARY = uuid.uuid4().hex
+_TRACING_QUEUE_MAX_SIZE = 10_000
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_context.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_context.py
new file mode 100644
index 0000000000000000000000000000000000000000..93ba5fe68ec7fddc9d85fc0d66c891a3b8d64ae4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_context.py
@@ -0,0 +1,46 @@
+"""Shared context (ContextVars and global defaults) that configure tracing."""
+
+import contextvars
+import weakref
+from typing import TYPE_CHECKING, Any, Literal, Optional, Union
+
+if TYPE_CHECKING:
+ from langsmith.client import Client
+ from langsmith.run_trees import RunTree
+else:
+ Client = Any # type: ignore[assignment]
+ RunTree = Any # type: ignore[assignment]
+
+_PROJECT_NAME = contextvars.ContextVar[Optional[str]]("_PROJECT_NAME", default=None)
+_TAGS = contextvars.ContextVar[Optional[list[str]]]("_TAGS", default=None)
+_METADATA = contextvars.ContextVar[Optional[dict[str, Any]]]("_METADATA", default=None)
+
+_TRACING_ENABLED = contextvars.ContextVar[Optional[Union[bool, Literal["local"]]]](
+ "_TRACING_ENABLED", default=None
+)
+_CLIENT = contextvars.ContextVar[Optional["Client"]]("_CLIENT", default=None)
+
+# Store a weak reference to the RunTree in the context.
+# This prevents memory leaks when contexts are captured by asyncio operations
+# (call_later, create_task, etc.) — the captured context holds only a weakref,
+# and the RunTree can be GC'd once no strong references remain.
+_PARENT_RUN_TREE_REF = contextvars.ContextVar[Optional[weakref.ref["RunTree"]]](
+ "_PARENT_RUN_TREE_REF", default=None
+)
+
+
+def get_current_run_tree() -> Optional["RunTree"]:
+ """Get the current RunTree from the context.
+
+ Returns the RunTree if it's still alive, otherwise None.
+ """
+ ref = _PARENT_RUN_TREE_REF.get()
+ return ref() if ref is not None else None
+
+
+# Not thread-local, so you can set this process-wide (before asyncio.run, etc.)
+_GLOBAL_PROJECT_NAME: Optional[str] = None
+_GLOBAL_TAGS: Optional[list[str]] = None
+_GLOBAL_METADATA: Optional[dict[str, Any]] = None
+_GLOBAL_TRACING_ENABLED: Optional[Union[bool, Literal["local"]]] = None
+_GLOBAL_CLIENT: Optional["Client"] = None
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_edit_distance.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_edit_distance.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef544cd281aeaa8231ee87417929dc7132ecaaff
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_edit_distance.py
@@ -0,0 +1,67 @@
+from typing import Any, Callable, Literal, Optional
+
+from typing_extensions import TypedDict
+
+METRICS = Literal[
+ "damerau_levenshtein",
+ "levenshtein",
+ "jaro",
+ "jaro_winkler",
+ "hamming",
+ "indel",
+]
+
+
+class EditDistanceConfig(TypedDict, total=False):
+ metric: METRICS
+ normalize_score: bool
+
+
+class EditDistance:
+ def __init__(
+ self,
+ config: Optional[EditDistanceConfig] = None,
+ ):
+ config = config or {}
+ metric = config.get("metric") or "damerau_levenshtein"
+ self.metric = self._get_metric(
+ metric, normalize_score=config.get("normalize_score", True)
+ )
+
+ def evaluate(
+ self,
+ prediction: str,
+ reference: Optional[str] = None,
+ ) -> float:
+ return self.metric(prediction, reference)
+
+ @staticmethod
+ def _get_metric(distance: str, normalize_score: bool = True) -> Callable:
+ try:
+ from rapidfuzz import ( # type: ignore[import-not-found]
+ distance as rf_distance,
+ )
+ except ImportError:
+ raise ImportError(
+ "This operation requires the rapidfuzz library to use."
+ "Please install it with `pip install -U rapidfuzz`."
+ )
+
+ module_map: dict[str, Any] = {
+ "damerau_levenshtein": rf_distance.DamerauLevenshtein,
+ "levenshtein": rf_distance.Levenshtein,
+ "jaro": rf_distance.Jaro,
+ "jaro_winkler": rf_distance.JaroWinkler,
+ "hamming": rf_distance.Hamming,
+ "indel": rf_distance.Indel,
+ }
+ if distance not in module_map:
+ raise ValueError(
+ f"Invalid distance metric: {distance}"
+ f"\nMust be one of: {list(module_map)}"
+ )
+ module = module_map[distance]
+ if normalize_score:
+ return module.normalized_distance
+ else:
+ return module.distance
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_embedding_distance.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_embedding_distance.py
new file mode 100644
index 0000000000000000000000000000000000000000..1daac60d8d84cc0d5038d280314d9895997f18c6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_embedding_distance.py
@@ -0,0 +1,190 @@
+from __future__ import annotations
+
+import logging
+from collections.abc import Sequence
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Literal,
+ Optional,
+ Union,
+)
+
+from typing_extensions import TypedDict
+
+if TYPE_CHECKING:
+ import numpy as np # type: ignore
+
+
+logger = logging.getLogger(__name__)
+
+Matrix = Union[list[list[float]], list[Any], Any]
+
+
+def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray:
+ """Row-wise cosine similarity between two equal-width matrices."""
+ import numpy as np
+
+ if len(X) == 0 or len(Y) == 0:
+ return np.array([])
+
+ X = np.array(X)
+ Y = np.array(Y)
+ if X.shape[1] != Y.shape[1]:
+ raise ValueError(
+ f"Number of columns in X and Y must be the same. X has shape {X.shape} "
+ f"and Y has shape {Y.shape}."
+ )
+ try:
+ import simsimd as simd # type: ignore
+
+ X = np.array(X, dtype=np.float32)
+ Y = np.array(Y, dtype=np.float32)
+ Z = 1 - simd.cdist(X, Y, metric="cosine")
+ if isinstance(Z, float):
+ return np.array([Z])
+ return np.array(Z)
+ except ImportError:
+ logger.debug(
+ "Unable to import simsimd, defaulting to NumPy implementation. If you want "
+ "to use simsimd please install with `pip install simsimd`."
+ )
+ X_norm = np.linalg.norm(X, axis=1)
+ Y_norm = np.linalg.norm(Y, axis=1)
+ # Ignore divide by zero errors run time warnings as those are handled below.
+ with np.errstate(divide="ignore", invalid="ignore"):
+ similarity = np.dot(X, Y.T) / np.outer(X_norm, Y_norm)
+ similarity[np.isnan(similarity) | np.isinf(similarity)] = 0.0
+ return similarity
+
+
+def _get_openai_encoder() -> Callable[[Sequence[str]], Sequence[Sequence[float]]]:
+ """Get the OpenAI GPT-3 encoder."""
+ try:
+ from openai import Client as OpenAIClient
+ except ImportError:
+ raise ImportError(
+ "THe default encoder for the EmbeddingDistance class uses the OpenAI API. "
+ "Please either install the openai library with `pip install openai` or "
+ "provide a custom encoder function (Callable[[str], Sequence[float]])."
+ )
+
+ def encode_text(texts: Sequence[str]) -> Sequence[Sequence[float]]:
+ client = OpenAIClient()
+ response = client.embeddings.create(
+ input=list(texts), model="text-embedding-3-small"
+ )
+ return [d.embedding for d in response.data]
+
+ return encode_text
+
+
+class EmbeddingConfig(TypedDict, total=False):
+ encoder: Callable[[list[str]], Sequence[Sequence[float]]]
+ metric: Literal["cosine", "euclidean", "manhattan", "chebyshev", "hamming"]
+
+
+class EmbeddingDistance:
+ def __init__(
+ self,
+ config: Optional[EmbeddingConfig] = None,
+ ):
+ config = config or {}
+ self.distance = config.get("metric") or "cosine"
+ self.encoder = config.get("encoder") or _get_openai_encoder()
+
+ def evaluate(
+ self,
+ prediction: str,
+ reference: str,
+ ) -> float:
+ try:
+ import numpy as np
+ except ImportError:
+ raise ImportError(
+ "The EmbeddingDistance class requires NumPy. Please install it with "
+ "`pip install numpy`."
+ )
+ embeddings = self.encoder([prediction, reference])
+ vector = np.array(embeddings)
+ return self._compute_distance(vector[0], vector[1]).item()
+
+ def _compute_distance(self, a: np.ndarray, b: np.ndarray) -> np.floating:
+ if self.distance == "cosine":
+ return self._cosine_distance(a, b) # type: ignore
+ elif self.distance == "euclidean":
+ return self._euclidean_distance(a, b)
+ elif self.distance == "manhattan":
+ return self._manhattan_distance(a, b)
+ elif self.distance == "chebyshev":
+ return self._chebyshev_distance(a, b)
+ elif self.distance == "hamming":
+ return self._hamming_distance(a, b)
+ else:
+ raise ValueError(f"Invalid distance metric: {self.distance}")
+
+ @staticmethod
+ def _cosine_distance(a: np.ndarray, b: np.ndarray) -> np.ndarray:
+ """Compute the cosine distance between two vectors.
+
+ Args:
+ a (np.ndarray): The first vector.
+ b (np.ndarray): The second vector.
+
+ Returns:
+ np.ndarray: The cosine distance.
+ """
+ return 1.0 - cosine_similarity([a], [b])
+
+ @staticmethod
+ def _euclidean_distance(a: np.ndarray, b: np.ndarray) -> np.floating:
+ """Compute the Euclidean distance between two vectors.
+
+ Args:
+ a (np.ndarray): The first vector.
+ b (np.ndarray): The second vector.
+
+ Returns:
+ np.floating: The Euclidean distance.
+ """
+ return np.linalg.norm(a - b)
+
+ @staticmethod
+ def _manhattan_distance(a: np.ndarray, b: np.ndarray) -> np.floating:
+ """Compute the Manhattan distance between two vectors.
+
+ Args:
+ a (np.ndarray): The first vector.
+ b (np.ndarray): The second vector.
+
+ Returns:
+ np.floating: The Manhattan distance.
+ """
+ return np.sum(np.abs(a - b))
+
+ @staticmethod
+ def _chebyshev_distance(a: np.ndarray, b: np.ndarray) -> np.floating:
+ """Compute the Chebyshev distance between two vectors.
+
+ Args:
+ a (np.ndarray): The first vector.
+ b (np.ndarray): The second vector.
+
+ Returns:
+ np.floating: The Chebyshev distance.
+ """
+ return np.max(np.abs(a - b))
+
+ @staticmethod
+ def _hamming_distance(a: np.ndarray, b: np.ndarray) -> np.floating:
+ """Compute the Hamming distance between two vectors.
+
+ Args:
+ a (np.ndarray): The first vector.
+ b (np.ndarray): The second vector.
+
+ Returns:
+ np.floating: The Hamming distance.
+ """
+ return np.mean(a != b)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_hub.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e0873322970160b3cfa1e54ff3c6a6253674b49
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_hub.py
@@ -0,0 +1,30 @@
+"""Shared constants and helpers for hub (agent/skill) methods."""
+
+from __future__ import annotations
+
+import re
+from typing import Optional
+
+from langsmith import utils as ls_utils
+
+REPO_HANDLE_PATTERN = re.compile(r"^[a-z][a-z0-9-_]*$")
+PLATFORM_HUB = "/v1/platform/hub/repos"
+HUB = "/repos"
+
+
+def build_commit_url(host: str, owner: str, name: str, commit_hash: str) -> str:
+ """Build the URL for a hub directory commit."""
+ return f"{host}/hub/{owner}/{name}:{commit_hash[:8]}"
+
+
+def resolve_owner_for_url(owner: str, tenant_handle: Optional[str]) -> str:
+ """Resolve internal owner sentinel to a user-visible owner in URLs."""
+ if owner == "-" and tenant_handle:
+ return tenant_handle
+ return owner
+
+
+def validate_parent_commit(parent_commit: Optional[str]) -> None:
+ """Raise ``LangSmithUserError`` if ``parent_commit`` is set but malformed."""
+ if parent_commit is not None and not (8 <= len(parent_commit) <= 64):
+ raise ls_utils.LangSmithUserError("parent_commit must be 8-64 characters.")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_multipart.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_multipart.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5ecf9caebd039ed7af89c476af17ff30aebbe78
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_multipart.py
@@ -0,0 +1,31 @@
+from __future__ import annotations
+
+from collections.abc import Iterable
+from io import BufferedReader
+from typing import Union
+
+MultipartPart = tuple[
+ str, tuple[None, Union[bytes, BufferedReader], str, dict[str, str]]
+]
+
+
+class MultipartPartsAndContext:
+ parts: list[MultipartPart]
+ context: str
+
+ __slots__ = ("parts", "context")
+
+ def __init__(self, parts: list[MultipartPart], context: str) -> None:
+ self.parts = parts
+ self.context = context
+
+
+def join_multipart_parts_and_context(
+ parts_and_contexts: Iterable[MultipartPartsAndContext],
+) -> MultipartPartsAndContext:
+ acc_parts: list[MultipartPart] = []
+ acc_context: list[str] = []
+ for parts_and_context in parts_and_contexts:
+ acc_parts.extend(parts_and_context.parts)
+ acc_context.append(parts_and_context.context)
+ return MultipartPartsAndContext(acc_parts, "; ".join(acc_context))
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_operations.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_operations.py
new file mode 100644
index 0000000000000000000000000000000000000000..0940b2d7484d753266a5822157e78c2a42d6cd77
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_operations.py
@@ -0,0 +1,446 @@
+from __future__ import annotations
+
+import itertools
+import logging
+import os
+import uuid
+from collections.abc import Iterable
+from io import BufferedReader
+from typing import Literal, Optional, Union, cast
+
+from langsmith import schemas as ls_schemas
+from langsmith._internal import _orjson
+from langsmith._internal._compressed_traces import CompressedTraces
+from langsmith._internal._multipart import MultipartPart, MultipartPartsAndContext
+from langsmith._internal._serde import dumps_json as _dumps_json
+
+logger = logging.getLogger(__name__)
+
+
+class SerializedRunOperation:
+ operation: Literal["post", "patch"]
+ id: uuid.UUID
+ trace_id: uuid.UUID
+
+ # this is the whole object, minus the other fields which
+ # are popped (inputs/outputs/events/attachments)
+ _none: bytes
+
+ inputs: Optional[bytes]
+ outputs: Optional[bytes]
+ events: Optional[bytes]
+ extra: Optional[bytes]
+ error: Optional[bytes]
+ serialized: Optional[bytes]
+ attachments: Optional[ls_schemas.Attachments]
+
+ __slots__ = (
+ "operation",
+ "id",
+ "trace_id",
+ "_none",
+ "inputs",
+ "outputs",
+ "events",
+ "extra",
+ "error",
+ "serialized",
+ "attachments",
+ )
+
+ def __init__(
+ self,
+ operation: Literal["post", "patch"],
+ id: uuid.UUID,
+ trace_id: uuid.UUID,
+ _none: bytes,
+ inputs: Optional[bytes] = None,
+ outputs: Optional[bytes] = None,
+ events: Optional[bytes] = None,
+ extra: Optional[bytes] = None,
+ error: Optional[bytes] = None,
+ serialized: Optional[bytes] = None,
+ attachments: Optional[ls_schemas.Attachments] = None,
+ ) -> None:
+ self.operation = operation
+ self.id = id
+ self.trace_id = trace_id
+ self._none = _none
+ self.inputs = inputs
+ self.outputs = outputs
+ self.events = events
+ self.extra = extra
+ self.error = error
+ self.serialized = serialized
+ self.attachments = attachments
+
+ def calculate_serialized_size(self) -> int:
+ """Calculate actual serialized size of this operation."""
+ size = 0
+ if self._none:
+ size += len(self._none)
+ if self.inputs:
+ size += len(self.inputs)
+ if self.outputs:
+ size += len(self.outputs)
+ if self.events:
+ size += len(self.events)
+ if self.extra:
+ size += len(self.extra)
+ if self.error:
+ size += len(self.error)
+ if self.serialized:
+ size += len(self.serialized)
+ if self.attachments:
+ for content_type, data_or_path in self.attachments.values():
+ if isinstance(data_or_path, bytes):
+ size += len(data_or_path)
+ return size
+
+ def deserialize_run_info(self) -> dict:
+ """Deserialize the main run info (_none and extra, error and serialized)."""
+ run_info = _orjson.loads(self._none)
+ if self.extra is not None:
+ run_info["extra"] = _orjson.loads(self.extra)
+
+ if self.error is not None:
+ run_info["error"] = _orjson.loads(self.error)
+
+ if self.serialized is not None:
+ run_info["serialized"] = _orjson.loads(self.serialized)
+
+ return run_info
+
+ def __eq__(self, other: object) -> bool:
+ return isinstance(other, SerializedRunOperation) and (
+ self.operation,
+ self.id,
+ self.trace_id,
+ self._none,
+ self.inputs,
+ self.outputs,
+ self.events,
+ self.extra,
+ self.error,
+ self.serialized,
+ self.attachments,
+ ) == (
+ other.operation,
+ other.id,
+ other.trace_id,
+ other._none,
+ other.inputs,
+ other.outputs,
+ other.events,
+ other.extra,
+ other.error,
+ other.serialized,
+ other.attachments,
+ )
+
+
+class SerializedFeedbackOperation:
+ id: uuid.UUID
+ trace_id: uuid.UUID
+ feedback: bytes
+
+ __slots__ = ("id", "trace_id", "feedback")
+
+ def __init__(self, id: uuid.UUID, trace_id: uuid.UUID, feedback: bytes) -> None:
+ self.id = id
+ self.trace_id = trace_id
+ self.feedback = feedback
+
+ def calculate_serialized_size(self) -> int:
+ """Calculate actual serialized size of this operation."""
+ return len(self.feedback)
+
+ def __eq__(self, other: object) -> bool:
+ return isinstance(other, SerializedFeedbackOperation) and (
+ self.id,
+ self.trace_id,
+ self.feedback,
+ ) == (other.id, other.trace_id, other.feedback)
+
+
+def serialize_feedback_dict(
+ feedback: Union[ls_schemas.FeedbackCreate, dict],
+) -> SerializedFeedbackOperation:
+ if hasattr(feedback, "model_dump") and callable(getattr(feedback, "model_dump")):
+ feedback_create: dict = feedback.model_dump() # type: ignore
+ else:
+ feedback_create = cast(dict, feedback)
+ if "id" not in feedback_create:
+ feedback_create["id"] = uuid.uuid4()
+ elif isinstance(feedback_create["id"], str):
+ feedback_create["id"] = uuid.UUID(feedback_create["id"])
+ if "trace_id" not in feedback_create:
+ feedback_create["trace_id"] = uuid.uuid4()
+ elif isinstance(feedback_create["trace_id"], str):
+ feedback_create["trace_id"] = uuid.UUID(feedback_create["trace_id"])
+
+ return SerializedFeedbackOperation(
+ id=feedback_create["id"],
+ trace_id=feedback_create["trace_id"],
+ feedback=_dumps_json(feedback_create),
+ )
+
+
+def serialize_run_dict(
+ operation: Literal["post", "patch"], payload: dict
+) -> SerializedRunOperation:
+ inputs = payload.pop("inputs", None)
+ outputs = payload.pop("outputs", None)
+ events = payload.pop("events", None)
+ extra = payload.pop("extra", None)
+ error = payload.pop("error", None)
+ serialized = payload.pop("serialized", None)
+ attachments = payload.pop("attachments", None)
+ return SerializedRunOperation(
+ operation=operation,
+ id=payload["id"],
+ trace_id=payload["trace_id"],
+ _none=_dumps_json(payload),
+ inputs=_dumps_json(inputs) if inputs is not None else None,
+ outputs=_dumps_json(outputs) if outputs is not None else None,
+ events=_dumps_json(events) if events is not None else None,
+ extra=_dumps_json(extra) if extra is not None else None,
+ error=_dumps_json(error) if error is not None else None,
+ serialized=_dumps_json(serialized) if serialized is not None else None,
+ attachments=attachments if attachments is not None else None,
+ )
+
+
+def combine_serialized_queue_operations(
+ ops: list[Union[SerializedRunOperation, SerializedFeedbackOperation]],
+) -> list[Union[SerializedRunOperation, SerializedFeedbackOperation]]:
+ create_ops_by_id = {
+ op.id: op
+ for op in ops
+ if isinstance(op, SerializedRunOperation) and op.operation == "post"
+ }
+ passthrough_ops: list[
+ Union[SerializedRunOperation, SerializedFeedbackOperation]
+ ] = []
+ for op in ops:
+ if isinstance(op, SerializedRunOperation):
+ if op.operation == "post":
+ continue
+
+ # must be patch
+
+ create_op = create_ops_by_id.get(op.id)
+ if create_op is None:
+ passthrough_ops.append(op)
+ continue
+
+ if op._none is not None and op._none != create_op._none:
+ # TODO optimize this more - this would currently be slowest
+ # for large payloads
+ create_op_dict = _orjson.loads(create_op._none)
+ op_dict = {
+ k: v for k, v in _orjson.loads(op._none).items() if v is not None
+ }
+ create_op_dict.update(op_dict)
+ create_op._none = _orjson.dumps(create_op_dict)
+
+ if op.inputs is not None:
+ create_op.inputs = op.inputs
+ if op.outputs is not None:
+ create_op.outputs = op.outputs
+ if op.events is not None:
+ create_op.events = op.events
+ if op.extra is not None:
+ create_op.extra = op.extra
+ if op.error is not None:
+ create_op.error = op.error
+ if op.serialized is not None:
+ create_op.serialized = op.serialized
+ if op.attachments is not None:
+ if create_op.attachments is None:
+ create_op.attachments = {}
+ create_op.attachments.update(op.attachments)
+ else:
+ passthrough_ops.append(op)
+ return list(itertools.chain(create_ops_by_id.values(), passthrough_ops))
+
+
+def serialized_feedback_operation_to_multipart_parts_and_context(
+ op: SerializedFeedbackOperation,
+) -> MultipartPartsAndContext:
+ return MultipartPartsAndContext(
+ [
+ (
+ f"feedback.{op.id}",
+ (
+ None,
+ op.feedback,
+ "application/json",
+ {"Content-Length": str(len(op.feedback))},
+ ),
+ )
+ ],
+ f"trace={op.trace_id},id={op.id}",
+ )
+
+
+def serialized_run_operation_to_multipart_parts_and_context(
+ op: SerializedRunOperation,
+) -> tuple[MultipartPartsAndContext, dict[str, BufferedReader]]:
+ acc_parts: list[MultipartPart] = []
+ opened_files_dict: dict[str, BufferedReader] = {}
+ # this is main object, minus inputs/outputs/events/attachments
+ acc_parts.append(
+ (
+ f"{op.operation}.{op.id}",
+ (
+ None,
+ op._none,
+ "application/json",
+ {"Content-Length": str(len(op._none))},
+ ),
+ )
+ )
+ for key, value in (
+ ("inputs", op.inputs),
+ ("outputs", op.outputs),
+ ("events", op.events),
+ ("extra", op.extra),
+ ("error", op.error),
+ ("serialized", op.serialized),
+ ):
+ if value is None:
+ continue
+ valb = value
+ acc_parts.append(
+ (
+ f"{op.operation}.{op.id}.{key}",
+ (
+ None,
+ valb,
+ "application/json",
+ {"Content-Length": str(len(valb))},
+ ),
+ ),
+ )
+ if op.attachments:
+ for n, (content_type, data_or_path) in op.attachments.items():
+ if "." in n:
+ logger.warning(
+ f"Skipping logging of attachment '{n}' "
+ f"for run {op.id}:"
+ " Invalid attachment name. Attachment names must not contain"
+ " periods ('.'). Please rename the attachment and try again."
+ )
+ continue
+
+ if isinstance(data_or_path, bytes):
+ acc_parts.append(
+ (
+ f"attachment.{op.id}.{n}",
+ (
+ None,
+ data_or_path,
+ content_type,
+ {"Content-Length": str(len(data_or_path))},
+ ),
+ )
+ )
+ else:
+ try:
+ file_size = os.path.getsize(data_or_path)
+ file = open(data_or_path, "rb")
+ except FileNotFoundError:
+ logger.warning(
+ "Attachment file not found for run %s: %s", op.id, data_or_path
+ )
+ continue
+ opened_files_dict[str(data_or_path) + str(uuid.uuid4())] = file
+ acc_parts.append(
+ (
+ f"attachment.{op.id}.{n}",
+ (
+ None,
+ file,
+ f"{content_type}; length={file_size}",
+ {},
+ ),
+ )
+ )
+ return (
+ MultipartPartsAndContext(acc_parts, f"trace={op.trace_id},id={op.id}"),
+ opened_files_dict,
+ )
+
+
+def encode_multipart_parts_and_context(
+ parts_and_context: MultipartPartsAndContext,
+ boundary: str,
+) -> Iterable[tuple[bytes, Union[bytes, BufferedReader]]]:
+ for part_name, (filename, data, content_type, headers) in parts_and_context.parts:
+ header_parts = [
+ f"--{boundary}\r\n",
+ f'Content-Disposition: form-data; name="{part_name}"',
+ ]
+
+ if filename:
+ header_parts.append(f'; filename="{filename}"')
+
+ header_parts.extend(
+ [
+ f"\r\nContent-Type: {content_type}\r\n",
+ *[f"{k}: {v}\r\n" for k, v in headers.items()],
+ "\r\n",
+ ]
+ )
+
+ yield ("".join(header_parts).encode(), data)
+
+
+def compress_multipart_parts_and_context(
+ parts_and_context: MultipartPartsAndContext,
+ compressed_traces: CompressedTraces,
+ boundary: str,
+) -> bool:
+ """Compress multipart parts into the shared compressed buffer.
+
+ Returns True if the parts were enqueued into the compressed buffer, or False
+ if they were rejected because the configured in-memory size limit would be
+ exceeded.
+ """
+ write = compressed_traces.compressor_writer.write
+
+ parts: list[tuple[bytes, bytes]] = []
+ op_uncompressed_size = 0
+
+ for headers, data in encode_multipart_parts_and_context(
+ parts_and_context, boundary
+ ):
+ # Normalise to bytes
+ if not isinstance(data, (bytes, bytearray)):
+ data = (
+ data.read() if isinstance(data, BufferedReader) else str(data).encode()
+ )
+
+ parts.append((headers, data))
+ op_uncompressed_size += len(data)
+
+ max_bytes = getattr(compressed_traces, "max_uncompressed_size_bytes", None)
+ if max_bytes is not None and max_bytes > 0:
+ current_size = compressed_traces.uncompressed_size
+ if current_size > 0 and current_size + op_uncompressed_size > max_bytes:
+ from langsmith.client import _log_tracing_drop
+
+ _log_tracing_drop(
+ f"compressed traces buffer full ({current_size}/{max_bytes} bytes)"
+ )
+ return False
+
+ for headers, data in parts:
+ write(headers)
+ compressed_traces.uncompressed_size += len(data)
+ write(data)
+ write(b"\r\n") # part terminator
+
+ compressed_traces._context.append(parts_and_context.context)
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_orjson.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_orjson.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d32fd1f2d34d8e40cfe655ebdf20ee23f01816b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_orjson.py
@@ -0,0 +1,88 @@
+"""Stubs for orjson operations, compatible with PyPy via a json fallback."""
+
+try:
+ from orjson import (
+ OPT_NON_STR_KEYS,
+ OPT_SERIALIZE_DATACLASS,
+ OPT_SERIALIZE_NUMPY,
+ OPT_SERIALIZE_UUID,
+ Fragment,
+ JSONDecodeError,
+ dumps,
+ loads,
+ )
+
+except ImportError:
+ import dataclasses
+ import json
+ import uuid
+ from typing import Any, Callable, Optional, Union
+
+ DefaultFunc = Optional[Callable[[Any], Any]]
+
+ OPT_NON_STR_KEYS = 1
+ OPT_SERIALIZE_DATACLASS = 2
+ OPT_SERIALIZE_NUMPY = 4
+ OPT_SERIALIZE_UUID = 8
+
+ class Fragment: # type: ignore
+ def __init__(self, payloadb: bytes):
+ self.payloadb = payloadb
+
+ from json import JSONDecodeError # type: ignore
+
+ def dumps(
+ obj: Any,
+ /,
+ default: DefaultFunc = None,
+ option: Optional[int] = None,
+ ) -> bytes:
+ # for now, don't do anything for this case because `json.dumps`
+ # automatically encodes non-str keys as str by default, unlike orjson
+ # enable_non_str_keys = bool(option & OPT_NON_STR_KEYS)
+ if option is None:
+ option = 0
+
+ enable_serialize_numpy = bool(option & OPT_SERIALIZE_NUMPY)
+ enable_serialize_dataclass = bool(option & OPT_SERIALIZE_DATACLASS)
+ enable_serialize_uuid = bool(option & OPT_SERIALIZE_UUID)
+
+ class CustomEncoder(json.JSONEncoder): # type: ignore
+ def encode(self, o: Any) -> str:
+ if isinstance(o, Fragment):
+ return o.payloadb.decode("utf-8") # type: ignore
+ return super().encode(o)
+
+ def default(self, o: Any) -> Any:
+ if enable_serialize_uuid and isinstance(o, uuid.UUID):
+ return str(o)
+ if enable_serialize_numpy and hasattr(o, "tolist"):
+ # even objects like np.uint16(15) have a .tolist() function
+ return o.tolist()
+ if (
+ enable_serialize_dataclass
+ and dataclasses.is_dataclass(o)
+ and not isinstance(o, type)
+ ):
+ return dataclasses.asdict(o)
+ if default is not None:
+ return default(o)
+
+ return super().default(o)
+
+ return json.dumps(obj, cls=CustomEncoder).encode("utf-8")
+
+ def loads(payload: Union[bytes, bytearray, memoryview, str], /) -> Any:
+ return json.loads(payload)
+
+
+__all__ = [
+ "loads",
+ "dumps",
+ "Fragment",
+ "JSONDecodeError",
+ "OPT_SERIALIZE_NUMPY",
+ "OPT_SERIALIZE_DATACLASS",
+ "OPT_SERIALIZE_UUID",
+ "OPT_NON_STR_KEYS",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_otel_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_otel_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c59b6aacbafc6c0daa52c89df353f47d1e9f9c62
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_otel_utils.py
@@ -0,0 +1,31 @@
+from __future__ import annotations
+
+from uuid import UUID
+
+
+def get_otel_trace_id_from_uuid(uuid_val: UUID) -> int:
+ """Get OpenTelemetry trace ID as integer from UUID.
+
+ Args:
+ uuid_val: The UUID to convert.
+
+ Returns:
+ Integer representation of the trace ID.
+ """
+ trace_id_hex = uuid_val.hex
+ return int(trace_id_hex, 16)
+
+
+def get_otel_span_id_from_uuid(uuid_val: UUID) -> int:
+ """Get OpenTelemetry span ID as integer from UUID.
+
+ Args:
+ uuid_val: The UUID to convert.
+
+ Returns:
+ Integer representation of the span ID.
+ """
+ uuid_bytes = uuid_val.bytes
+ span_id_bytes = uuid_bytes[:8]
+ span_id_hex = span_id_bytes.hex()
+ return int(span_id_hex, 16)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_patch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_patch.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7bf88bdf750572bc290ae1df931d567f225bbda
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_patch.py
@@ -0,0 +1,93 @@
+import functools
+
+from urllib3 import __version__ as urllib3version # type: ignore[import-untyped]
+from urllib3 import connection # type: ignore[import-untyped]
+
+
+def _ensure_str(s, encoding="utf-8", errors="strict") -> str:
+ if isinstance(s, str):
+ return s
+
+ if isinstance(s, bytes):
+ return s.decode(encoding, errors)
+ return str(s)
+
+
+# Copied from https://github.com/urllib3/urllib3/blob/1c994dfc8c5d5ecaee8ed3eb585d4785f5febf6e/src/urllib3/connection.py#L231
+def request(self, method, url, body=None, headers=None):
+ """Make the request.
+
+ This function is based on the urllib3 request method, with modifications
+ to handle potential issues when using vcrpy in concurrent workloads.
+
+ Args:
+ self: The HTTPConnection instance.
+ method (str): The HTTP method (e.g., 'GET', 'POST').
+ url (str): The URL for the request.
+ body (Optional[Any]): The body of the request.
+ headers (Optional[dict]): Headers to send with the request.
+
+ Returns:
+ The result of calling the parent request method.
+ """
+ # Update the inner socket's timeout value to send the request.
+ # This only triggers if the connection is re-used.
+ if getattr(self, "sock", None) is not None:
+ self.sock.settimeout(self.timeout)
+
+ if headers is None:
+ headers = {}
+ else:
+ # Avoid modifying the headers passed into .request()
+ headers = headers.copy()
+ if "user-agent" not in (_ensure_str(k.lower()) for k in headers):
+ headers["User-Agent"] = connection._get_default_user_agent()
+ # The above is all the same ^^^
+ # The following is different:
+ return self._parent_request(method, url, body=body, headers=headers)
+
+
+_PATCHED = False
+
+
+def patch_urllib3():
+ """Patch the request method of urllib3 to avoid type errors when using vcrpy.
+
+ In concurrent workloads (such as the tracing background queue), the
+ connection pool can get in a state where an HTTPConnection is created
+ before vcrpy patches the HTTPConnection class. In urllib3 >= 2.0 this isn't
+ a problem since they use the proper super().request(...) syntax, but in older
+ versions, super(HTTPConnection, self).request is used, resulting in a TypeError
+ since self is no longer a subclass of "HTTPConnection" (which at this point
+ is vcr.stubs.VCRConnection).
+
+ This method patches the class to fix the super() syntax to avoid mixed inheritance.
+ In the case of the LangSmith tracing logic, it doesn't really matter since we always
+ exclude cache checks for calls to LangSmith.
+
+ The patch is only applied for urllib3 versions older than 2.0.
+ """
+ global _PATCHED
+ if _PATCHED:
+ return
+ from packaging import version
+
+ if version.parse(urllib3version) >= version.parse("2.0"):
+ _PATCHED = True
+ return
+
+ # Lookup the parent class and its request method
+ parent_class = connection.HTTPConnection.__bases__[0]
+ parent_request = parent_class.request
+
+ def new_request(self, *args, **kwargs):
+ """Handle parent request.
+
+ This method binds the parent's request method to self and then
+ calls our modified request function.
+ """
+ self._parent_request = functools.partial(parent_request, self)
+ return request(self, *args, **kwargs)
+
+ connection.HTTPConnection.request = new_request
+ _PATCHED = True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_profiles.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_profiles.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ccc0e02142edc47a6d79670ecf5b3a6d96496e3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_profiles.py
@@ -0,0 +1,338 @@
+"""LangSmith profile configuration and auth helpers."""
+
+from __future__ import annotations
+
+import datetime
+import json
+import os
+import threading
+from collections.abc import Mapping
+from pathlib import Path
+from typing import Any, NamedTuple, Optional, TypedDict, cast
+
+import requests
+
+_OAUTH_CLIENT_ID = "langsmith-cli"
+_TOKEN_REFRESH_LEEWAY = datetime.timedelta(minutes=1)
+_TOKEN_REFRESH_TIMEOUT = 10
+
+
+class ProfileOAuth(TypedDict, total=False):
+ access_token: str
+ refresh_token: str
+ expires_at: str
+
+
+class ProfileConfig(TypedDict, total=False):
+ api_key: str
+ api_url: str
+ workspace_id: str
+ oauth: ProfileOAuth
+
+
+class ProfileConfigFile(TypedDict, total=False):
+ current_profile: str
+ profiles: dict[str, ProfileConfig]
+
+
+class ProfileState(NamedTuple):
+ path: Path
+ config: ProfileConfigFile
+ profile_name: str
+
+
+class ProfileClientConfig(NamedTuple):
+ api_url: Optional[str] = None
+ api_key: Optional[str] = None
+ workspace_id: Optional[str] = None
+ oauth_access_token: Optional[str] = None
+ oauth_refresh_token: Optional[str] = None
+ oauth_expires_at: Optional[str] = None
+ profile_state: Optional[ProfileState] = None
+
+ @property
+ def has_oauth(self) -> bool:
+ return bool(self.oauth_access_token or self.oauth_refresh_token)
+
+
+def trim_auth_value(value: Optional[str]) -> Optional[str]:
+ if not value:
+ return None
+ trimmed = value.strip().strip('"').strip("'")
+ return trimmed or None
+
+
+def _profile_config_path() -> Optional[Path]:
+ if config_file := os.environ.get("LANGSMITH_CONFIG_FILE"):
+ return Path(config_file)
+ try:
+ return Path.home() / ".langsmith" / "config.json"
+ except RuntimeError:
+ return None
+
+
+def _load_profile_state() -> Optional[ProfileState]:
+ path = _profile_config_path()
+ if path is None or not path.exists():
+ return None
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ if not isinstance(raw, dict):
+ return None
+ profiles = raw.get("profiles")
+ if not isinstance(profiles, dict):
+ return None
+ profile_name = os.environ.get("LANGSMITH_PROFILE")
+ if not profile_name:
+ current_profile = raw.get("current_profile")
+ if isinstance(current_profile, str) and current_profile:
+ profile_name = current_profile
+ elif "default" in profiles:
+ profile_name = "default"
+ if not profile_name or not isinstance(profiles.get(profile_name), dict):
+ return None
+ return ProfileState(path, cast(ProfileConfigFile, raw), profile_name)
+
+
+def _profile_from_state(state: ProfileState) -> Optional[ProfileConfig]:
+ profiles = state.config.get("profiles") or {}
+ profile = profiles.get(state.profile_name)
+ if not isinstance(profile, dict):
+ return None
+ return cast(ProfileConfig, profile)
+
+
+def load_profile_client_config() -> ProfileClientConfig:
+ state = _load_profile_state()
+ if state is None:
+ return ProfileClientConfig()
+ profile = _profile_from_state(state)
+ if profile is None:
+ return ProfileClientConfig()
+ oauth = profile.get("oauth") or {}
+ return ProfileClientConfig(
+ api_url=profile.get("api_url"),
+ api_key=trim_auth_value(profile.get("api_key")),
+ workspace_id=profile.get("workspace_id"),
+ oauth_access_token=trim_auth_value(oauth.get("access_token")),
+ oauth_refresh_token=trim_auth_value(oauth.get("refresh_token")),
+ oauth_expires_at=oauth.get("expires_at"),
+ profile_state=state,
+ )
+
+
+def _normalize_profile_api_url(api_url: str) -> str:
+ while api_url.endswith("/"):
+ api_url = api_url[:-1]
+ suffix = "/api/v1"
+ if api_url.endswith(suffix):
+ return api_url[: -len(suffix)]
+ return api_url
+
+
+def _parse_profile_expires_at(expires_at: str) -> Optional[datetime.datetime]:
+ try:
+ parsed = datetime.datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=datetime.timezone.utc)
+ return parsed
+
+
+def should_refresh_profile_token(profile: ProfileConfig) -> bool:
+ oauth = profile.get("oauth") or {}
+ if not oauth.get("refresh_token"):
+ return False
+ if not oauth.get("access_token"):
+ return True
+ expires_at = oauth.get("expires_at")
+ if not expires_at:
+ return False
+ parsed = _parse_profile_expires_at(expires_at)
+ if parsed is None:
+ return False
+ return (
+ parsed <= datetime.datetime.now(datetime.timezone.utc) + _TOKEN_REFRESH_LEEWAY
+ )
+
+
+def _refresh_profile_oauth_token(
+ api_url: Optional[str], refresh_token: str
+) -> Optional[dict[str, Any]]:
+ refresh_url = _normalize_profile_api_url(
+ api_url or "https://api.smith.langchain.com"
+ )
+ try:
+ response = requests.post(
+ f"{refresh_url}/oauth/token",
+ data={
+ "grant_type": "refresh_token",
+ "client_id": _OAUTH_CLIENT_ID,
+ "refresh_token": refresh_token,
+ },
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ timeout=_TOKEN_REFRESH_TIMEOUT,
+ )
+ except requests.RequestException:
+ return None
+ if response.status_code < 200 or response.status_code >= 300:
+ return None
+ try:
+ token = response.json()
+ except ValueError:
+ return None
+ if not isinstance(token, dict) or not token.get("access_token"):
+ return None
+ return token
+
+
+def _apply_profile_token_response(
+ profile: ProfileConfig, token: Mapping[str, Any]
+) -> None:
+ oauth = profile.setdefault("oauth", {})
+ access_token = token.get("access_token")
+ if isinstance(access_token, str) and access_token:
+ oauth["access_token"] = access_token
+ refresh_token = token.get("refresh_token")
+ if isinstance(refresh_token, str) and refresh_token:
+ oauth["refresh_token"] = refresh_token
+ expires_in = token.get("expires_in")
+ if isinstance(expires_in, (int, float)) and expires_in > 0:
+ expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
+ seconds=expires_in
+ )
+ oauth["expires_at"] = expires_at.isoformat().replace("+00:00", "Z")
+
+
+def _save_profile_config(path: Path, config: ProfileConfigFile) -> None:
+ try:
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ temp_path = path.with_name(f"{path.name}.tmp")
+ temp_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
+ os.chmod(temp_path, 0o600)
+ os.replace(temp_path, path)
+ os.chmod(path, 0o600)
+ except OSError:
+ return
+
+
+class ProfileAuth:
+ def __init__(
+ self,
+ config: ProfileClientConfig,
+ *,
+ api_key_header: str,
+ ) -> None:
+ self._state = config.profile_state
+ self._api_key_header = api_key_header
+ self._lock = threading.Lock()
+ self._managed_auth_headers: set[tuple[str, str]] = set()
+ self._remember_auth_headers(self._auth_headers(refresh=False))
+
+ @property
+ def has_auth(self) -> bool:
+ profile = self._profile()
+ if profile is None:
+ return False
+ oauth = profile.get("oauth") or {}
+ return bool(
+ trim_auth_value(oauth.get("access_token"))
+ or trim_auth_value(oauth.get("refresh_token"))
+ or trim_auth_value(profile.get("api_key"))
+ )
+
+ @property
+ def oauth_access_token(self) -> Optional[str]:
+ profile = self._profile()
+ if profile is None:
+ return None
+ return trim_auth_value((profile.get("oauth") or {}).get("access_token"))
+
+ def needs_refresh(self) -> bool:
+ profile = self._profile()
+ return profile is not None and should_refresh_profile_token(profile)
+
+ def current_auth_headers(self) -> dict[str, str]:
+ headers = self._auth_headers(refresh=False)
+ self._remember_auth_headers(headers)
+ return headers
+
+ def get_auth_headers(self) -> dict[str, str]:
+ headers = self._auth_headers(refresh=True)
+ self._remember_auth_headers(headers)
+ return headers
+
+ def prepare_request_headers(self, headers: Mapping[str, str]) -> dict[str, str]:
+ """Replace stale profile-managed auth while preserving explicit auth."""
+ request_headers = dict(headers)
+ for key, value in list(request_headers.items()):
+ if self._is_profile_auth_header(key, value):
+ del request_headers[key]
+ if not self._has_auth_header(request_headers):
+ request_headers.update(self.current_auth_headers())
+ return request_headers
+
+ def _profile(self) -> Optional[ProfileConfig]:
+ if self._state is None:
+ return None
+ return _profile_from_state(self._state)
+
+ def _auth_headers(self, *, refresh: bool) -> dict[str, str]:
+ profile = self._profile()
+ if profile is None:
+ return {}
+ if refresh and should_refresh_profile_token(profile):
+ with self._lock:
+ profile = self._profile()
+ if profile is not None and should_refresh_profile_token(profile):
+ self._refresh(profile)
+ return self._headers_from_profile(profile)
+
+ def _refresh(self, profile: ProfileConfig) -> None:
+ refresh_token = trim_auth_value(
+ (profile.get("oauth") or {}).get("refresh_token")
+ )
+ if refresh_token is None or self._state is None:
+ return
+ api_url = profile.get("api_url")
+ token = _refresh_profile_oauth_token(api_url, refresh_token)
+ if token is None:
+ return
+ _apply_profile_token_response(profile, token)
+ profiles = self._state.config.get("profiles") or {}
+ profiles[self._state.profile_name] = profile
+ self._state.config["profiles"] = profiles
+ _save_profile_config(self._state.path, self._state.config)
+
+ def _headers_from_profile(self, profile: Optional[ProfileConfig]) -> dict[str, str]:
+ if profile is None:
+ return {}
+ oauth_access_token = trim_auth_value(
+ (profile.get("oauth") or {}).get("access_token")
+ )
+ if oauth_access_token:
+ return {"Authorization": f"Bearer {oauth_access_token}"}
+ api_key = trim_auth_value(profile.get("api_key"))
+ if api_key:
+ return {self._api_key_header: api_key}
+ return {}
+
+ def _remember_auth_headers(self, headers: Mapping[str, str]) -> None:
+ for name, value in headers.items():
+ if self._is_auth_header_name(name) and value:
+ self._managed_auth_headers.add((name.lower(), value))
+
+ def _is_profile_auth_header(self, name: str, value: str) -> bool:
+ return (name.lower(), value) in self._managed_auth_headers
+
+ def _has_auth_header(self, headers: Mapping[str, str]) -> bool:
+ return any(
+ self._is_auth_header_name(name) and bool(value)
+ for name, value in headers.items()
+ )
+
+ def _is_auth_header_name(self, name: str) -> bool:
+ return name.lower() in {"authorization", self._api_key_header.lower()}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_serde.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_serde.py
new file mode 100644
index 0000000000000000000000000000000000000000..586822f2fe52514ee953eae40dc215cd3015d5d0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_serde.py
@@ -0,0 +1,164 @@
+from __future__ import annotations
+
+import base64
+import collections
+import datetime
+import decimal
+import ipaddress
+import json
+import logging
+import pathlib
+import re
+import uuid
+from typing import Any
+
+from langsmith._internal import _orjson
+
+try:
+ from zoneinfo import ZoneInfo # type: ignore[import-not-found]
+except ImportError:
+
+ class ZoneInfo: # type: ignore[no-redef]
+ """Introduced in python 3.9."""
+
+
+logger = logging.getLogger(__name__)
+
+
+def _simple_default(obj):
+ try:
+ # Only need to handle types that orjson doesn't serialize by default
+ # https://github.com/ijl/orjson#serialize
+ if isinstance(obj, datetime.datetime):
+ return obj.isoformat()
+ elif isinstance(obj, uuid.UUID):
+ return str(obj)
+ elif isinstance(obj, BaseException):
+ return {"error": type(obj).__name__, "message": str(obj)}
+ elif isinstance(obj, (set, frozenset, collections.deque)):
+ return list(obj)
+ elif isinstance(obj, (datetime.timezone, ZoneInfo)):
+ return obj.tzname(None)
+ elif isinstance(obj, datetime.timedelta):
+ return obj.total_seconds()
+ elif isinstance(obj, decimal.Decimal):
+ if obj.as_tuple().exponent >= 0:
+ return int(obj)
+ else:
+ return float(obj)
+ elif isinstance(
+ obj,
+ (
+ ipaddress.IPv4Address,
+ ipaddress.IPv4Interface,
+ ipaddress.IPv4Network,
+ ipaddress.IPv6Address,
+ ipaddress.IPv6Interface,
+ ipaddress.IPv6Network,
+ pathlib.Path,
+ ),
+ ):
+ return str(obj)
+ elif isinstance(obj, re.Pattern):
+ return obj.pattern
+ elif isinstance(obj, (bytes, bytearray)):
+ return base64.b64encode(obj).decode()
+ return str(obj)
+ except BaseException as e:
+ logger.debug(f"Failed to serialize {type(obj)} to JSON: {e}")
+ return str(obj)
+
+
+_serialization_methods: list[tuple[str, dict[str, Any]]] = [
+ (
+ "model_dump",
+ {"exclude_none": True, "mode": "json"},
+ ), # Pydantic V2 with non-serializable fields
+ ("model_dump", {"exclude_none": True}), # Pydantic V2 without json mode
+ ("dict", {}), # Pydantic V1 with non-serializable field
+ ("to_dict", {}), # dataclasses-json
+]
+
+
+# IMPORTANT: This function is used from Rust code in `langsmith-pyo3` serialization,
+# in order to handle serializing these tricky Python types *from Rust*.
+# Do not cause this function to become inaccessible (e.g. by deleting
+# or renaming it) without also fixing the corresponding Rust code found in:
+# rust/crates/langsmith-pyo3/src/serialization/mod.rs
+def _serialize_json(obj: Any) -> Any:
+ try:
+ if isinstance(obj, (set, tuple)):
+ if hasattr(obj, "_asdict") and callable(obj._asdict):
+ # NamedTuple
+ return obj._asdict()
+ return list(obj)
+
+ for attr, kwargs in _serialization_methods:
+ if (
+ hasattr(obj, attr)
+ and callable(getattr(obj, attr))
+ and not isinstance(obj, type)
+ ):
+ try:
+ method = getattr(obj, attr)
+ response = method(**kwargs)
+ if not isinstance(response, dict):
+ return str(response)
+ return response
+ except Exception as e:
+ logger.debug(
+ f"Failed to use {attr} to serialize {type(obj)} to"
+ f" JSON: {repr(e)}"
+ )
+ pass
+ return _simple_default(obj)
+ except BaseException as e:
+ logger.debug(f"Failed to serialize {type(obj)} to JSON: {e}")
+ return str(obj)
+
+
+def _elide_surrogates(s: bytes) -> bytes:
+ pattern = re.compile(rb"\\ud[89a-f][0-9a-f]{2}", re.IGNORECASE)
+ result = pattern.sub(b"", s)
+ return result
+
+
+def dumps_json(obj: Any) -> bytes:
+ """Serialize an object to a JSON formatted string.
+
+ Parameters
+ ----------
+ obj : Any
+ The object to serialize.
+ default : Callable[[Any], Any] or None, default=None
+ The default function to use for serialization.
+
+ Returns:
+ -------
+ str
+ The JSON formatted string.
+ """
+ try:
+ return _orjson.dumps(
+ obj,
+ default=_serialize_json,
+ option=_orjson.OPT_SERIALIZE_NUMPY
+ | _orjson.OPT_SERIALIZE_DATACLASS
+ | _orjson.OPT_SERIALIZE_UUID
+ | _orjson.OPT_NON_STR_KEYS,
+ )
+ except TypeError as e:
+ # Usually caused by UTF surrogate characters
+ logger.debug(f"Orjson serialization failed: {repr(e)}. Falling back to json.")
+ result = json.dumps(
+ obj,
+ default=_serialize_json,
+ ensure_ascii=True,
+ ).encode("utf-8")
+ try:
+ result = _orjson.dumps(
+ _orjson.loads(result.decode("utf-8", errors="surrogateescape"))
+ )
+ except _orjson.JSONDecodeError:
+ result = _elide_surrogates(result)
+ return result
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_uuid.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_uuid.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f5cc205764cb82ee692c5d8bf3bcbe15bc5b90f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/_uuid.py
@@ -0,0 +1,155 @@
+"""UUID helpers backed by uuid-utils."""
+
+from __future__ import annotations
+
+import time
+import uuid
+import warnings
+from typing import Final
+
+import xxhash
+from uuid_utils.compat import uuid7 as _uuid_utils_uuid7
+
+_NANOS_PER_SECOND: Final = 1_000_000_000
+
+
+def _to_timestamp_and_nanos(nanoseconds: int) -> tuple[int, int]:
+ """Split a nanosecond timestamp into seconds and remaining nanoseconds."""
+ seconds, nanos = divmod(nanoseconds, _NANOS_PER_SECOND)
+ return seconds, nanos
+
+
+def uuid7(nanoseconds: int | None = None) -> uuid.UUID:
+ """Generate a UUID from a Unix timestamp in nanoseconds and random bits.
+
+ UUIDv7 objects feature monotonicity within a millisecond.
+
+ Args:
+ nanoseconds: Optional ns timestamp. If not provided, uses current time.
+ """
+ # --- 48 --- -- 4 -- --- 12 --- -- 2 -- --- 30 --- - 32 -
+ # unix_ts_ms | version | counter_hi | variant | counter_lo | random
+ #
+ # 'counter = counter_hi | counter_lo' is a 42-bit counter constructed
+ # with Method 1 of RFC 9562, §6.2, and its MSB is set to 0.
+ #
+ # 'random' is a 32-bit random value regenerated for every new UUID.
+ #
+ # If multiple UUIDs are generated within the same millisecond, the LSB
+ # of 'counter' is incremented by 1. When overflowing, the timestamp is
+ # advanced and the counter is reset to a random 42-bit integer with MSB
+ # set to 0.
+
+ # For now, just delegate to the uuid_utils implementation
+ if nanoseconds is None:
+ return _uuid_utils_uuid7()
+ seconds, nanos = _to_timestamp_and_nanos(nanoseconds)
+ return _uuid_utils_uuid7(timestamp=seconds, nanos=nanos)
+
+
+def is_uuid_v7(uuid_obj: uuid.UUID) -> bool:
+ """Check if a UUID is version 7.
+
+ Args:
+ uuid_obj: The UUID to check.
+
+ Returns:
+ True if the UUID is version 7, False otherwise.
+ """
+ return uuid_obj.version == 7
+
+
+_UUID_V7_WARNING_EMITTED = False
+
+
+def warn_if_not_uuid_v7(uuid_obj: uuid.UUID, id_type: str) -> None:
+ """Warn if a UUID is not version 7.
+
+ Args:
+ uuid_obj: The UUID to check.
+ id_type: The type of ID (e.g., "run_id", "trace_id") for the warning message.
+ """
+ global _UUID_V7_WARNING_EMITTED
+ if not is_uuid_v7(uuid_obj) and not _UUID_V7_WARNING_EMITTED:
+ _UUID_V7_WARNING_EMITTED = True
+ warnings.warn(
+ (
+ "LangSmith now uses UUID v7 for run and trace identifiers. "
+ "This warning appears when passing custom IDs. "
+ "Please use: from langsmith import uuid7\n"
+ " id = uuid7()\n"
+ "Future versions will require UUID v7."
+ ),
+ UserWarning,
+ stacklevel=3,
+ )
+
+
+def uuid7_deterministic(original_id: uuid.UUID, key: str) -> uuid.UUID:
+ """Generate a deterministic UUID7 derived from an original UUID and a key.
+
+ This function creates a new UUID that:
+ - Preserves the timestamp from the original UUID if it's UUID v7
+ - Uses current time if the original is not UUID v7
+ - Uses deterministic bits derived from hashing the original + key with XXH3-128
+ - Is valid UUID v7 format
+
+ This is used for creating replica IDs that maintain time-ordering properties
+ while being deterministic across distributed systems.
+
+ Args:
+ original_id: The source UUID (ideally UUID v7 to preserve timestamp).
+ key: A string key used for deterministic derivation (e.g., project name).
+
+ Returns:
+ A new UUID v7 with preserved timestamp (if original is v7) and
+ deterministic random bits.
+
+ Example:
+ >>> original = uuid7()
+ >>> replica_id = uuid7_deterministic(original, "replica-project")
+ >>> # Same inputs always produce same output
+ >>> assert uuid7_deterministic(original, "replica-project") == replica_id
+ """
+ # Generate deterministic bytes from XXH3-128 hash of original + key
+ hash_input = f"{original_id}:{key}".encode()
+ h = xxhash.xxh3_128(hash_input).digest()
+
+ # Build new UUID7:
+ # UUID7 structure (RFC 9562):
+ # [0-5] 48 bits: unix_ts_ms (timestamp in milliseconds)
+ # [6] 4 bits: version (0111 = 7) + 4 bits rand_a
+ # [7] 8 bits: rand_a (continued)
+ # [8] 2 bits: variant (10) + 6 bits rand_b
+ # [9-15] 56 bits: rand_b (continued)
+
+ b = bytearray(16)
+
+ # Check if original is UUID v7 - if so, preserve its timestamp
+ # If not, use current time to ensure the derived UUID has a valid timestamp
+ if is_uuid_v7(original_id):
+ # Preserve timestamp from original UUID7 (bytes 0-5)
+ b[0:6] = original_id.bytes[0:6]
+ else:
+ # Generate fresh timestamp for non-UUID7 inputs
+ # This matches CPython 3.14's uuid7() implementation:
+ # timestamp_ms = time.time_ns() // 1_000_000
+ # Then convert to big-endian bytes
+ timestamp_ms = time.time_ns() // 1_000_000
+ # Mask to 48 bits and convert to big-endian bytes
+ unix_ts_ms = timestamp_ms & 0xFFFF_FFFF_FFFF
+ b[0:6] = unix_ts_ms.to_bytes(6, "big")
+
+ # Set version 7 (0111) in high nibble + 4 bits from hash
+ b[6] = 0x70 | (h[0] & 0x0F)
+
+ # rand_a continued (8 bits from hash)
+ b[7] = h[1]
+
+ # Set variant (10) in high 2 bits + 6 bits from hash
+ b[8] = 0x80 | (h[2] & 0x3F)
+
+ # rand_b (56 bits = 7 bytes from hash)
+ b[9:16] = h[3:10]
+
+ return uuid.UUID(bytes=bytes(b))
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/otel/__pycache__/_otel_client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/otel/__pycache__/_otel_client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..923926f69d43bcf89ca02873174ce47c7fbe8ced
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/otel/__pycache__/_otel_client.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/otel/__pycache__/_otel_exporter.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/otel/__pycache__/_otel_exporter.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a513eb38823b21cd8e73c1bd811324abed4be9f3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/otel/__pycache__/_otel_exporter.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/otel/_otel_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/otel/_otel_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ec67b1a8f45cae2000cb2d5f5825d4a3de742e0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/otel/_otel_client.py
@@ -0,0 +1,115 @@
+"""Client configuration for OpenTelemetry integration with LangSmith."""
+
+import os
+import warnings
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ try:
+ from opentelemetry.sdk.trace import TracerProvider # type: ignore[import]
+ except ImportError:
+ TracerProvider = object # type: ignore[assignment, misc]
+
+from langsmith import utils as ls_utils
+
+
+def _import_otel_client():
+ """Dynamically import OTEL client modules when needed."""
+ try:
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import ( # type: ignore[import]
+ OTLPSpanExporter,
+ )
+ from opentelemetry.sdk.resources import ( # type: ignore[import]
+ SERVICE_NAME,
+ Resource,
+ )
+ from opentelemetry.sdk.trace import TracerProvider # type: ignore[import]
+ from opentelemetry.sdk.trace.export import ( # type: ignore[import]
+ BatchSpanProcessor,
+ )
+
+ return (
+ OTLPSpanExporter,
+ SERVICE_NAME,
+ Resource,
+ TracerProvider,
+ BatchSpanProcessor,
+ )
+ except ImportError as e:
+ warnings.warn(
+ f"OTEL_ENABLED is set but OpenTelemetry packages are not installed: {e}"
+ )
+ return None
+
+
+def get_otlp_tracer_provider() -> "TracerProvider":
+ """Get the OTLP tracer provider for LangSmith.
+
+ This function creates a tracer provider that exports spans using the OTLP protocol
+ with LangSmith-specific defaults:
+
+ - OTEL_EXPORTER_OTLP_ENDPOINT: https://api.smith.langchain.com/otel
+ - OTEL_EXPORTER_OTLP_HEADERS: Contains x-api-key from LangSmith API key and
+ Langsmith-Project header if project is configured
+
+ These defaults can be overridden by setting the environment variables before
+ calling this function. Values are passed directly to the exporter constructor
+ rather than written to os.environ.
+
+ Returns:
+ TracerProvider: The OTLP tracer provider.
+ """
+ # Import OTEL modules dynamically
+ otel_imports = _import_otel_client()
+ if otel_imports is None:
+ raise ImportError(
+ "OpenTelemetry packages are required to use this function. "
+ "Please install with `pip install langsmith[otel]`"
+ )
+ (
+ OTLPSpanExporter,
+ SERVICE_NAME,
+ Resource,
+ TracerProvider,
+ BatchSpanProcessor,
+ ) = otel_imports
+
+ endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
+ if not endpoint:
+ ls_endpoint = ls_utils.get_api_url(None)
+ endpoint = f"{ls_endpoint}/otel"
+
+ # Configure headers with API key and project if available.
+ # Build a dict because OTLPSpanExporter expects a mapping, not a string.
+ headers_env = os.environ.get("OTEL_EXPORTER_OTLP_HEADERS")
+ if headers_env:
+ headers = {
+ k.strip(): v.strip()
+ for k, v in (
+ pair.split("=", 1) for pair in headers_env.split(",") if "=" in pair
+ )
+ }
+ else:
+ api_key = ls_utils.get_api_key(None) or ""
+ headers = {"x-api-key": api_key}
+
+ project = ls_utils.get_tracer_project()
+ if project:
+ headers["Langsmith-Project"] = project
+
+ service_name = os.environ.get("OTEL_SERVICE_NAME", "langsmith")
+ resource = Resource(
+ attributes={
+ SERVICE_NAME: service_name,
+ # Marker to identify LangSmith's internal provider
+ "langsmith.internal_provider": True,
+ }
+ )
+
+ tracer_provider = TracerProvider(resource=resource)
+
+ otlp_exporter = OTLPSpanExporter(endpoint=endpoint, headers=headers)
+ span_processor = BatchSpanProcessor(otlp_exporter)
+ tracer_provider.add_span_processor(span_processor)
+
+ return tracer_provider
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/otel/_otel_exporter.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/otel/_otel_exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac836c5270b9fdff4ca823aa4f9c2026e53231b4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/_internal/otel/_otel_exporter.py
@@ -0,0 +1,866 @@
+"""OpenTelemetry exporter for LangSmith runs."""
+
+from __future__ import annotations
+
+import datetime
+import logging
+import time
+import uuid
+import warnings
+from typing import TYPE_CHECKING, Any, Optional
+
+if TYPE_CHECKING:
+ try:
+ from opentelemetry.context.context import Context # type: ignore[import]
+ from opentelemetry.trace import Span # type: ignore[import]
+ except ImportError:
+ Context = Any # type: ignore[assignment, misc]
+ Span = Any # type: ignore[assignment, misc]
+
+from langsmith import utils as ls_utils
+from langsmith._internal import _orjson
+from langsmith._internal._operations import (
+ SerializedRunOperation,
+)
+from langsmith._internal._otel_utils import (
+ get_otel_span_id_from_uuid,
+ get_otel_trace_id_from_uuid,
+)
+
+
+def _import_otel_exporter():
+ """Dynamically import OTEL exporter modules when needed."""
+ try:
+ from opentelemetry import trace # type: ignore[import]
+ from opentelemetry.context.context import Context # type: ignore[import]
+ from opentelemetry.trace import ( # type: ignore[import]
+ NonRecordingSpan,
+ Span,
+ SpanContext,
+ TraceFlags,
+ TraceState,
+ set_span_in_context,
+ )
+
+ return (
+ trace,
+ Context,
+ NonRecordingSpan,
+ Span,
+ SpanContext,
+ TraceFlags,
+ TraceState,
+ set_span_in_context,
+ )
+ except ImportError as e:
+ warnings.warn(
+ f"OTEL_ENABLED is set but OpenTelemetry packages are not installed: {e}"
+ )
+ return None
+
+
+logger = logging.getLogger(__name__)
+
+# OpenTelemetry GenAI semconv attribute names
+GEN_AI_OPERATION_NAME = "gen_ai.operation.name"
+GEN_AI_SYSTEM = "gen_ai.system"
+GEN_AI_REQUEST_MODEL = "gen_ai.request.model"
+GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"
+GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"
+GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"
+GEN_AI_USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens"
+GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens"
+GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature"
+GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p"
+GEN_AI_REQUEST_FREQUENCY_PENALTY = "gen_ai.request.frequency_penalty"
+GEN_AI_REQUEST_PRESENCE_PENALTY = "gen_ai.request.presence_penalty"
+GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons"
+GENAI_PROMPT = "gen_ai.prompt"
+GENAI_COMPLETION = "gen_ai.completion"
+
+GEN_AI_REQUEST_EXTRA_QUERY = "gen_ai.request.extra_query"
+GEN_AI_REQUEST_EXTRA_BODY = "gen_ai.request.extra_body"
+GEN_AI_SERIALIZED_NAME = "gen_ai.serialized.name"
+GEN_AI_SERIALIZED_SIGNATURE = "gen_ai.serialized.signature"
+GEN_AI_SERIALIZED_DOC = "gen_ai.serialized.doc"
+GEN_AI_RESPONSE_ID = "gen_ai.response.id"
+GEN_AI_RESPONSE_SERVICE_TIER = "gen_ai.response.service_tier"
+GEN_AI_RESPONSE_SYSTEM_FINGERPRINT = "gen_ai.response.system_fingerprint"
+GEN_AI_USAGE_INPUT_TOKEN_DETAILS = "gen_ai.usage.input_token_details"
+GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS = "gen_ai.usage.output_token_details"
+
+
+def _otel_safe_attribute_value(value: Any) -> Optional[Any]:
+ """Convert a value to an OTel-valid attribute type.
+
+ OTel only accepts bool, str, bytes, int, float, or sequences of those.
+ Dicts and lists are JSON-serialized to a string.
+ """
+ if value is None:
+ return None
+ if isinstance(value, (bool, bytes, int, float, str)):
+ return value
+ if isinstance(value, (dict, list)):
+ try:
+ return _orjson.dumps(value).decode("utf-8")
+ except (TypeError, ValueError):
+ return str(value)
+ return str(value)
+
+
+# LangSmith custom attributes
+LANGSMITH_SESSION_ID = "langsmith.trace.session_id"
+LANGSMITH_SESSION_NAME = "langsmith.trace.session_name"
+LANGSMITH_RUN_TYPE = "langsmith.span.kind"
+LANGSMITH_NAME = "langsmith.trace.name"
+LANGSMITH_METADATA = "langsmith.metadata"
+LANGSMITH_TAGS = "langsmith.span.tags"
+LANGSMITH_RUNTIME = "langsmith.span.runtime"
+LANGSMITH_REQUEST_STREAMING = "langsmith.request.streaming"
+LANGSMITH_REQUEST_HEADERS = "langsmith.request.headers"
+
+# GenAI event names
+GEN_AI_SYSTEM_MESSAGE = "gen_ai.system.message"
+GEN_AI_USER_MESSAGE = "gen_ai.user.message"
+GEN_AI_ASSISTANT_MESSAGE = "gen_ai.assistant.message"
+GEN_AI_CHOICE = "gen_ai.choice"
+
+WELL_KNOWN_OPERATION_NAMES = {
+ "llm": "chat",
+ "tool": "execute_tool",
+ "retriever": "embeddings",
+ "embedding": "embeddings",
+ "prompt": "chat",
+}
+
+
+def _get_operation_name(run_type: str) -> str:
+ return WELL_KNOWN_OPERATION_NAMES.get(run_type, run_type)
+
+
+class OTELExporter:
+ __slots__ = [
+ "_tracer",
+ "_span_info",
+ "_otel_available",
+ "_trace",
+ "_span_ttl_seconds",
+ "_last_cleanup",
+ ]
+ """OpenTelemetry exporter for LangSmith runs."""
+
+ def __init__(self, tracer_provider=None, span_ttl_seconds=None):
+ """Initialize the OTEL exporter.
+
+ Args:
+ tracer_provider: Optional tracer provider to use. If not provided,
+ the global tracer provider will be used.
+ span_ttl_seconds: TTL for incomplete traces in seconds. If None,
+ uses LANGSMITH_OTEL_SPAN_TTL_SECONDS env var (default: 3600s)
+ """
+ # Set defaults from environment variables if not provided
+ if span_ttl_seconds is None:
+ span_ttl_seconds = int(
+ ls_utils.get_env_var("OTEL_SPAN_TTL_SECONDS", default="3600")
+ )
+ otel_imports = _import_otel_exporter()
+ if otel_imports is None:
+ self._tracer = None
+ self._span_info = {}
+ self._otel_available = False
+ self._trace = None
+ self._span_ttl_seconds = span_ttl_seconds
+ self._last_cleanup = 0.0
+ else:
+ (
+ trace,
+ Context,
+ NonRecordingSpan,
+ Span,
+ SpanContext,
+ TraceFlags,
+ TraceState,
+ set_span_in_context,
+ ) = otel_imports
+
+ self._tracer = trace.get_tracer(
+ "langsmith", tracer_provider=tracer_provider
+ )
+ self._span_info = {}
+ self._otel_available = True
+ self._trace = trace
+ self._span_ttl_seconds = span_ttl_seconds
+ self._last_cleanup = 0.0
+
+ def export_batch(
+ self,
+ operations: list[SerializedRunOperation],
+ otel_context_map: dict[uuid.UUID, Optional[Context]],
+ ) -> None:
+ """Export a batch of serialized run operations to OTEL.
+
+ Args:
+ operations: List of serialized run operations to export.
+ """
+ # Proactive cleanup of expired and excess spans before new operations
+ self._cleanup_stale_spans()
+
+ for op in operations:
+ try:
+ run_info = self._deserialize_run_info(op)
+ if not run_info:
+ continue
+ if op.operation == "post":
+ span = self._create_span_for_run(
+ op, run_info, otel_context_map.get(op.id)
+ )
+ if span:
+ self._span_info[op.id] = {
+ "span": span,
+ "created_at": time.time(),
+ }
+ else:
+ self._update_span_for_run(op, run_info)
+ except Exception as e:
+ logger.exception(f"Error processing operation {op.id}: {e}")
+
+ def _deserialize_run_info(self, op: SerializedRunOperation) -> Optional[dict]:
+ """Deserialize the run info from the operation.
+
+ Args:
+ op: The serialized run operation.
+
+ Returns:
+ The deserialized run info as a dictionary, or None if deserialization
+ failed.
+ """
+ try:
+ return op.deserialize_run_info()
+ except Exception as e:
+ logger.exception(f"Failed to deserialize run info for {op.id}: {e}")
+ return None
+
+ def _create_span_for_run(
+ self,
+ op: SerializedRunOperation,
+ run_info: dict,
+ otel_context: Optional[Context] = None,
+ ) -> Optional[Span]:
+ """Create an OpenTelemetry span for a run operation.
+
+ Args:
+ op: The serialized run operation.
+ run_info: The deserialized run info.
+ parent_span: Optional parent span.
+
+ Returns:
+ The created span, or None if creation failed.
+ """
+ try:
+ start_time = run_info.get("start_time")
+ start_time_utc_nano = self._as_utc_nano(start_time)
+
+ end_time = run_info.get("end_time")
+ end_time_utc_nano = self._as_utc_nano(end_time)
+
+ # Create deterministic trace and span IDs to match user OpenTelemetry spans
+ trace_id_int = get_otel_trace_id_from_uuid(op.trace_id)
+ span_id_int = get_otel_span_id_from_uuid(op.id)
+
+ # Get OTEL imports for this operation
+ otel_imports = _import_otel_exporter()
+ if otel_imports is None:
+ return None
+ (
+ trace,
+ Context,
+ NonRecordingSpan,
+ Span,
+ SpanContext,
+ TraceFlags,
+ TraceState,
+ set_span_in_context,
+ ) = otel_imports
+
+ # Create SpanContext with deterministic IDs
+ span_context = SpanContext(
+ trace_id=trace_id_int,
+ span_id=span_id_int,
+ is_remote=False,
+ trace_flags=TraceFlags(TraceFlags.SAMPLED),
+ trace_state=TraceState(),
+ )
+
+ # Create NonRecordingSpan for context setting
+ non_recording_span = NonRecordingSpan(span_context)
+ deterministic_context = set_span_in_context(non_recording_span)
+
+ # Start the span with appropriate context
+ parent_run_id = run_info.get("parent_run_id")
+ if (
+ parent_run_id is not None
+ and uuid.UUID(parent_run_id) in self._span_info
+ ):
+ # Use the parent span context
+ parent_span = self._span_info[uuid.UUID(parent_run_id)]["span"]
+ span = self._tracer.start_span(
+ run_info.get("name"),
+ context=set_span_in_context(parent_span),
+ start_time=start_time_utc_nano,
+ )
+ else:
+ # For root spans, check if there's an existing OpenTelemetry context
+ # If so, inherit from it; otherwise use our deterministic context
+ current_context = (
+ otel_context if otel_context else deterministic_context
+ )
+ span = self._tracer.start_span(
+ run_info.get("name"),
+ context=current_context,
+ start_time=start_time_utc_nano,
+ )
+
+ # Set all attributes
+ self._set_span_attributes(span, run_info, op)
+
+ # Set status based on error
+ if run_info.get("error"):
+ span.set_status(trace.StatusCode.ERROR)
+ span.record_exception(Exception(run_info.get("error")))
+ else:
+ span.set_status(trace.StatusCode.OK)
+
+ # End the span if end_time is present
+ end_time = run_info.get("end_time")
+ if end_time:
+ end_time_utc_nano = self._as_utc_nano(end_time)
+ if end_time_utc_nano:
+ span.end(end_time=end_time_utc_nano)
+ else:
+ span.end()
+
+ return span
+ except Exception as e:
+ logger.exception(f"Failed to create span for run {op.id}: {e}")
+ return None
+
+ def _update_span_for_run(self, op: SerializedRunOperation, run_info: dict) -> None:
+ """Update an OpenTelemetry span for a run operation.
+
+ Args:
+ op: The serialized run operation.
+ run_info: The deserialized run info.
+ """
+ try:
+ # Get the span for this run
+ if op.id not in self._span_info:
+ logger.debug(f"No span found for run {op.id} during update")
+ return
+
+ span = self._span_info[op.id]["span"]
+
+ # Update attributes
+ self._set_span_attributes(span, run_info, op)
+ # Update status based on error
+ if run_info.get("error"):
+ span.set_status(self._trace.StatusCode.ERROR)
+ span.record_exception(Exception(run_info.get("error")))
+ else:
+ span.set_status(self._trace.StatusCode.OK)
+
+ # End the span if end_time is present
+ end_time = run_info.get("end_time")
+ if end_time:
+ end_time_utc_nano = self._as_utc_nano(end_time)
+ if end_time_utc_nano:
+ span.end(end_time=end_time_utc_nano)
+ else:
+ span.end()
+ # Remove the span info from our dictionary
+ del self._span_info[op.id]
+ logger.debug(f"Completed span, remaining spans: {len(self._span_info)}")
+ else:
+ # Span exists but no end_time - this is normal for ongoing operations
+ logger.debug("Updated span (no end_time yet)")
+
+ except Exception as e:
+ logger.exception(f"Failed to update span for run {op.id}: {e}")
+
+ def _cleanup_stale_spans(self) -> None:
+ """Clean up spans older than TTL threshold."""
+ if not self._span_info:
+ return
+
+ current_time = time.time()
+
+ # Only run cleanup every 10 seconds to reduce overhead
+ if current_time - self._last_cleanup < 10.0:
+ return
+
+ self._last_cleanup = current_time
+ cutoff_time = current_time - self._span_ttl_seconds
+
+ # Remove spans older than TTL in one pass
+ stale_span_ids = [
+ span_id
+ for span_id, info in self._span_info.items()
+ if info["created_at"] < cutoff_time
+ ]
+
+ if stale_span_ids:
+ logger.info(
+ f" LangSmith OTEL Cleanup: Removing {len(stale_span_ids)} stale spans"
+ )
+
+ for span_id in stale_span_ids:
+ self._remove_span(span_id)
+
+ def _remove_span(self, span_id: uuid.UUID) -> None:
+ """Remove a single span and clean up resources.
+
+ Note:
+ We call `span.end()` here because spans in `_span_info` are orphaned -
+ they never received their patch operation and will never naturally complete.
+
+ Ending them gracefully is better than leaving them open indefinitely.
+ """
+ if span_id not in self._span_info:
+ return
+
+ try:
+ # End the orphaned span gracefully
+ span = self._span_info[span_id]["span"]
+
+ # Check if span is still active before ending it
+ if (
+ hasattr(span, "end")
+ and hasattr(span, "is_recording")
+ and span.is_recording()
+ ):
+ span.end()
+ logger.debug(f"Ended orphaned span {span_id}")
+ elif hasattr(span, "end"):
+ # Span already ended, just log it
+ logger.debug(f"Span {span_id} already ended, skipping end() call")
+
+ # Remove from tracking regardless
+ del self._span_info[span_id]
+
+ except Exception as e:
+ logger.debug(f"Error removing span {span_id}: {e}")
+ # Still try to remove from tracking even if ending failed
+ try:
+ del self._span_info[span_id]
+ except KeyError:
+ pass
+
+ def _extract_model_name(self, run_info: dict) -> Optional[str]:
+ """Extract model name from run info.
+
+ Args:
+ run_info: The run info.
+
+ Returns:
+ The model name, or None if not found.
+ """
+ # Try to get model name from metadata
+ if run_info.get("extra") and run_info["extra"].get("metadata"):
+ metadata = run_info["extra"]["metadata"]
+
+ # First check for ls_model_name in metadata
+ if metadata.get("ls_model_name"):
+ return metadata["ls_model_name"]
+
+ # Then check invocation_params for model info
+ if "invocation_params" in metadata:
+ invocation_params = metadata["invocation_params"]
+ # Check model first, then model_name
+ if invocation_params.get("model"):
+ return invocation_params["model"]
+ elif invocation_params.get("model_name"):
+ return invocation_params["model_name"]
+
+ return None
+
+ def _set_span_attributes(
+ self,
+ span: Span,
+ run_info: dict,
+ op: SerializedRunOperation,
+ ) -> None:
+ """Set attributes on the span.
+
+ Args:
+ span: The span to set attributes on.
+ run_info: The deserialized run info.
+ op: The serialized run operation.
+ """
+ # Set LangSmith-specific attributes
+ if run_info.get("run_type"):
+ span.set_attribute(LANGSMITH_RUN_TYPE, str(run_info.get("run_type")))
+
+ if run_info.get("name"):
+ span.set_attribute(LANGSMITH_NAME, str(run_info.get("name")))
+
+ if run_info.get("session_id"):
+ span.set_attribute(LANGSMITH_SESSION_ID, str(run_info.get("session_id")))
+ if run_info.get("session_name"):
+ span.set_attribute(
+ LANGSMITH_SESSION_NAME, str(run_info.get("session_name"))
+ )
+
+ # Set GenAI attributes according to OTEL semantic conventions
+ # Set gen_ai.operation.name
+ if op.operation == "post":
+ operation_name = _get_operation_name(run_info.get("run_type", "chain"))
+ span.set_attribute(GEN_AI_OPERATION_NAME, operation_name)
+
+ # Set gen_ai.system
+ self._set_gen_ai_system(span, run_info)
+
+ # Set model name if available
+ model_name = self._extract_model_name(run_info)
+ if model_name:
+ span.set_attribute(GEN_AI_REQUEST_MODEL, model_name)
+
+ # Set token usage information
+ if run_info.get("prompt_tokens") is not None:
+ prompt_tokens = run_info["prompt_tokens"]
+ span.set_attribute(GEN_AI_USAGE_INPUT_TOKENS, int(prompt_tokens))
+
+ if run_info.get("completion_tokens") is not None:
+ completion_tokens = run_info["completion_tokens"]
+ span.set_attribute(GEN_AI_USAGE_OUTPUT_TOKENS, int(completion_tokens))
+
+ if run_info.get("total_tokens") is not None:
+ total_tokens = run_info["total_tokens"]
+ span.set_attribute(GEN_AI_USAGE_TOTAL_TOKENS, int(total_tokens))
+
+ # Set other parameters from invocation_params
+ self._set_invocation_parameters(span, run_info)
+
+ # Set metadata and tags if available
+ extra = run_info.get("extra", {})
+ metadata = extra.get("metadata", {})
+ for key, value in metadata.items():
+ if value is not None:
+ safe = _otel_safe_attribute_value(value)
+ if safe is not None:
+ span.set_attribute(f"{LANGSMITH_METADATA}.{key}", safe)
+
+ tags = run_info.get("tags")
+ if tags:
+ if isinstance(tags, list):
+ span.set_attribute(LANGSMITH_TAGS, ", ".join(tags))
+ else:
+ span.set_attribute(LANGSMITH_TAGS, tags)
+
+ # Support additional serialized attributes, if present
+ if run_info.get("serialized") and isinstance(run_info["serialized"], dict):
+ serialized = run_info["serialized"]
+ if "name" in serialized and serialized["name"] is not None:
+ span.set_attribute(GEN_AI_SERIALIZED_NAME, serialized["name"])
+ if "signature" in serialized and serialized["signature"] is not None:
+ span.set_attribute(GEN_AI_SERIALIZED_SIGNATURE, serialized["signature"])
+ if "doc" in serialized and serialized["doc"] is not None:
+ span.set_attribute(GEN_AI_SERIALIZED_DOC, serialized["doc"])
+
+ # Set inputs/outputs if available
+ self._set_io_attributes(span, op)
+
+ def _set_gen_ai_system(self, span: Span, run_info: dict) -> None:
+ """Set the gen_ai.system attribute on the span based on the model provider.
+
+ Args:
+ span: The span to set attributes on.
+ run_info: The deserialized run info.
+ """
+ # Default to "langchain" if we can't determine the system
+ system = "langchain"
+
+ # Extract model name to determine the system
+ model_name = self._extract_model_name(run_info)
+ if model_name:
+ model_lower = model_name.lower()
+ if "anthropic" in model_lower or model_lower.startswith("claude"):
+ system = "anthropic"
+ elif "bedrock" in model_lower:
+ system = "aws.bedrock"
+ elif "azure" in model_lower and "openai" in model_lower:
+ system = "az.ai.openai"
+ elif "azure" in model_lower and "inference" in model_lower:
+ system = "az.ai.inference"
+ elif "cohere" in model_lower:
+ system = "cohere"
+ elif "deepseek" in model_lower:
+ system = "deepseek"
+ elif "gemini" in model_lower:
+ system = "gemini"
+ elif "groq" in model_lower:
+ system = "groq"
+ elif "watson" in model_lower or "ibm" in model_lower:
+ system = "ibm.watsonx.ai"
+ elif "mistral" in model_lower:
+ system = "mistral_ai"
+ elif "gpt" in model_lower or "openai" in model_lower:
+ system = "openai"
+ elif "perplexity" in model_lower or "sonar" in model_lower:
+ system = "perplexity"
+ elif "vertex" in model_lower:
+ system = "vertex_ai"
+ elif "xai" in model_lower or "grok" in model_lower:
+ system = "xai"
+ elif "qwen" in model_lower:
+ system = "qwen"
+
+ span.set_attribute(GEN_AI_SYSTEM, system)
+ setattr(span, "_gen_ai_system", system)
+
+ def _set_invocation_parameters(self, span: Span, run_info: dict) -> None:
+ """Set invocation parameters on the span.
+
+ Args:
+ span: The span to set attributes on.
+ run_info: The deserialized run info.
+ """
+ if not (run_info.get("extra") and run_info["extra"].get("metadata")):
+ return
+
+ metadata = run_info["extra"]["metadata"]
+ if "invocation_params" not in metadata:
+ return
+
+ invocation_params = metadata["invocation_params"]
+
+ # Set relevant invocation parameters
+ if "max_tokens" in invocation_params:
+ span.set_attribute(
+ GEN_AI_REQUEST_MAX_TOKENS, invocation_params["max_tokens"]
+ )
+
+ if "temperature" in invocation_params:
+ span.set_attribute(
+ GEN_AI_REQUEST_TEMPERATURE, invocation_params["temperature"]
+ )
+
+ if "top_p" in invocation_params:
+ span.set_attribute(GEN_AI_REQUEST_TOP_P, invocation_params["top_p"])
+
+ if "frequency_penalty" in invocation_params:
+ span.set_attribute(
+ GEN_AI_REQUEST_FREQUENCY_PENALTY, invocation_params["frequency_penalty"]
+ )
+
+ if "presence_penalty" in invocation_params:
+ span.set_attribute(
+ GEN_AI_REQUEST_PRESENCE_PENALTY, invocation_params["presence_penalty"]
+ )
+
+ def _set_io_attributes(self, span: Span, op: SerializedRunOperation) -> None:
+ """Set input/output attributes on the span.
+
+ Args:
+ span: The span to set attributes on.
+ op: The serialized run operation.
+ """
+ if op.inputs:
+ try:
+ inputs = _orjson.loads(op.inputs)
+
+ if isinstance(inputs, dict):
+ if (
+ "model" in inputs
+ and isinstance(inputs.get("messages"), list)
+ and inputs["model"] is not None
+ ):
+ span.set_attribute(GEN_AI_REQUEST_MODEL, inputs["model"])
+
+ # Set additional request attributes if available.
+ if "stream" in inputs and inputs["stream"] is not None:
+ span.set_attribute(
+ LANGSMITH_REQUEST_STREAMING, inputs["stream"]
+ )
+ if (
+ "extra_headers" in inputs
+ and inputs["extra_headers"] is not None
+ ):
+ span.set_attribute(
+ LANGSMITH_REQUEST_HEADERS, inputs["extra_headers"]
+ )
+ if "extra_query" in inputs and inputs["extra_query"] is not None:
+ span.set_attribute(
+ GEN_AI_REQUEST_EXTRA_QUERY, inputs["extra_query"]
+ )
+ if "extra_body" in inputs and inputs["extra_body"] is not None:
+ span.set_attribute(
+ GEN_AI_REQUEST_EXTRA_BODY, inputs["extra_body"]
+ )
+
+ span.set_attribute(GENAI_PROMPT, op.inputs)
+
+ except Exception:
+ logger.debug(
+ "Failed to process inputs for run %s", op.id, exc_info=True
+ )
+
+ if op.outputs:
+ try:
+ outputs = _orjson.loads(op.outputs)
+
+ # Extract token usage from outputs (for LLM runs)
+ token_usage = self.get_unified_run_tokens(outputs)
+ if token_usage:
+ span.set_attribute(GEN_AI_USAGE_INPUT_TOKENS, token_usage[0])
+ span.set_attribute(GEN_AI_USAGE_OUTPUT_TOKENS, token_usage[1])
+ span.set_attribute(
+ GEN_AI_USAGE_TOTAL_TOKENS, token_usage[0] + token_usage[1]
+ )
+
+ if "model" in outputs:
+ span.set_attribute(GEN_AI_RESPONSE_MODEL, str(outputs["model"]))
+ # Extract additional response attributes.
+ if isinstance(outputs, dict):
+ if "id" in outputs and outputs["id"] is not None:
+ span.set_attribute(GEN_AI_RESPONSE_ID, outputs["id"])
+ if "choices" in outputs and isinstance(outputs["choices"], list):
+ finish_reasons = []
+ for choice in outputs["choices"]:
+ if (
+ "finish_reason" in choice
+ and choice["finish_reason"] is not None
+ ):
+ finish_reasons.append(str(choice["finish_reason"]))
+ if finish_reasons:
+ span.set_attribute(
+ GEN_AI_RESPONSE_FINISH_REASONS,
+ ", ".join(finish_reasons),
+ )
+ if (
+ "service_tier" in outputs
+ and outputs["service_tier"] is not None
+ ):
+ span.set_attribute(
+ GEN_AI_RESPONSE_SERVICE_TIER, outputs["service_tier"]
+ )
+ if (
+ "system_fingerprint" in outputs
+ and outputs["system_fingerprint"] is not None
+ ):
+ span.set_attribute(
+ GEN_AI_RESPONSE_SYSTEM_FINGERPRINT,
+ outputs["system_fingerprint"],
+ )
+ if "usage_metadata" in outputs and isinstance(
+ outputs["usage_metadata"], dict
+ ):
+ usage_metadata = outputs["usage_metadata"]
+ if (
+ "input_token_details" in usage_metadata
+ and usage_metadata["input_token_details"] is not None
+ ):
+ input_token_details = str(
+ usage_metadata["input_token_details"]
+ )
+ span.set_attribute(
+ GEN_AI_USAGE_INPUT_TOKEN_DETAILS, input_token_details
+ )
+ if (
+ "output_token_details" in usage_metadata
+ and usage_metadata["output_token_details"] is not None
+ ):
+ output_token_details = str(
+ usage_metadata["output_token_details"]
+ )
+ span.set_attribute(
+ GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS, output_token_details
+ )
+
+ span.set_attribute(GENAI_COMPLETION, op.outputs)
+
+ except Exception:
+ logger.debug(
+ "Failed to process outputs for run %s", op.id, exc_info=True
+ )
+
+ def _as_utc_nano(self, timestamp: Optional[str]) -> Optional[int]:
+ if not timestamp:
+ return None
+ try:
+ dt = datetime.datetime.fromisoformat(timestamp)
+ return int(dt.astimezone(datetime.timezone.utc).timestamp() * 1_000_000_000)
+ except ValueError:
+ logger.exception(f"Failed to parse timestamp {timestamp}")
+ return None
+
+ def get_unified_run_tokens(
+ self, outputs: Optional[dict]
+ ) -> Optional[tuple[int, int]]:
+ if not outputs:
+ return None
+
+ # search in non-generations lists
+ if output := self._extract_unified_run_tokens(outputs.get("usage_metadata")):
+ return output
+
+ # find if direct kwarg in outputs
+ keys = outputs.keys()
+ for key in keys:
+ haystack = outputs[key]
+ if not haystack or not isinstance(haystack, dict):
+ continue
+
+ if output := self._extract_unified_run_tokens(
+ haystack.get("usage_metadata")
+ ):
+ return output
+
+ if (
+ haystack.get("lc") == 1
+ and "kwargs" in haystack
+ and isinstance(haystack["kwargs"], dict)
+ and (
+ output := self._extract_unified_run_tokens(
+ haystack["kwargs"].get("usage_metadata")
+ )
+ )
+ ):
+ return output
+
+ # find in generations
+ generations = outputs.get("generations") or []
+ if not isinstance(generations, list):
+ return None
+ if generations and not isinstance(generations[0], list):
+ generations = [generations]
+
+ for generation in [x for xs in generations for x in xs]:
+ if (
+ isinstance(generation, dict)
+ and "message" in generation
+ and isinstance(generation["message"], dict)
+ and "kwargs" in generation["message"]
+ and isinstance(generation["message"]["kwargs"], dict)
+ and (
+ output := self._extract_unified_run_tokens(
+ generation["message"]["kwargs"].get("usage_metadata")
+ )
+ )
+ ):
+ return output
+ return None
+
+ def _extract_unified_run_tokens(
+ self, outputs: Optional[Any]
+ ) -> Optional[tuple[int, int]]:
+ if not outputs or not isinstance(outputs, dict):
+ return None
+
+ if "input_tokens" not in outputs or "output_tokens" not in outputs:
+ return None
+
+ if not isinstance(outputs["input_tokens"], int) or not isinstance(
+ outputs["output_tokens"], int
+ ):
+ return None
+
+ return outputs["input_tokens"], outputs["output_tokens"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/beta/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/beta/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f712c1adb3a25d5d6b1e951e82d93d4c1381002e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/beta/__init__.py
@@ -0,0 +1,6 @@
+"""Beta functionality prone to change."""
+
+from langsmith._internal._beta_decorator import warn_beta
+from langsmith.beta._evals import compute_test_metrics, convert_runs_to_test
+
+__all__ = ["convert_runs_to_test", "compute_test_metrics", "warn_beta"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/beta/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/beta/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c820e3de20c66f2f4fe8b6f0fec4f4c7086e77dc
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/beta/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/beta/__pycache__/_evals.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/beta/__pycache__/_evals.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e63bd4deeed84b829222f62c118803d300553f97
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/beta/__pycache__/_evals.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/beta/_evals.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/beta/_evals.py
new file mode 100644
index 0000000000000000000000000000000000000000..e26348026de9498d48786a4bd387b84d99fcefb7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/beta/_evals.py
@@ -0,0 +1,243 @@
+"""Beta utility functions to assist in common eval workflows.
+
+These functions may change in the future.
+"""
+
+import collections
+import datetime
+import itertools
+import uuid
+from collections.abc import Sequence
+from typing import Optional, TypeVar
+
+import langsmith.run_trees as rt
+import langsmith.schemas as ls_schemas
+from langsmith import evaluation as ls_eval
+from langsmith._internal._beta_decorator import warn_beta
+from langsmith.client import Client
+
+
+def _convert_ids(run_dict: dict, id_map: dict) -> dict:
+ """Convert the IDs in the run dictionary using the provided ID map.
+
+ Parameters:
+ - run_dict: The dictionary representing a run.
+ - id_map: The dictionary mapping old IDs to new IDs.
+
+ Returns:
+ - dict: The updated run dictionary.
+ """
+ do = run_dict["dotted_order"]
+ for k, v in id_map.items():
+ do = do.replace(str(k), str(v))
+ run_dict["dotted_order"] = do
+
+ if run_dict.get("parent_run_id"):
+ run_dict["parent_run_id"] = id_map[run_dict["parent_run_id"]]
+ if not run_dict.get("extra"):
+ run_dict["extra"] = {}
+ return run_dict
+
+
+def _convert_root_run(root: ls_schemas.Run, run_to_example_map: dict) -> list[dict]:
+ """Convert the root run and its child runs to a list of dictionaries.
+
+ Parameters:
+ - root: The root run to convert.
+ - run_to_example_map: The dictionary mapping run IDs to example IDs.
+
+ Returns:
+ - The list of converted run dictionaries.
+ """
+ runs_ = [root]
+ trace_id = uuid.uuid4()
+ id_map = {root.trace_id: trace_id}
+ results = []
+ while runs_:
+ src = runs_.pop()
+ src_dict = src.dict(exclude={"parent_run_ids", "child_run_ids", "session_id"})
+ id_map[src_dict["id"]] = id_map.get(src_dict["id"], uuid.uuid4())
+ src_dict["id"] = id_map[src_dict["id"]]
+ src_dict["trace_id"] = id_map[src_dict["trace_id"]]
+ if src.child_runs:
+ runs_.extend(src.child_runs)
+ results.append(src_dict)
+ result = [_convert_ids(r, id_map) for r in results]
+ result[0]["reference_example_id"] = run_to_example_map[root.id]
+ return result
+
+
+@warn_beta
+def convert_runs_to_test(
+ runs: Sequence[ls_schemas.Run],
+ *,
+ dataset_name: str,
+ test_project_name: Optional[str] = None,
+ client: Optional[Client] = None,
+ load_child_runs: bool = False,
+ include_outputs: bool = False,
+) -> ls_schemas.TracerSession:
+ """Convert the following runs to a dataset + test.
+
+ This makes it easy to sample prod runs into a new regression testing
+ workflow and compare against a candidate system.
+
+ Internally, this function does the following:
+ 1. Create a dataset from the provided production run inputs.
+ 2. Create a new test project.
+ 3. Clone the production runs and re-upload against the dataset.
+
+ Parameters:
+ - runs: A sequence of runs to be executed as a test.
+ - dataset_name: The name of the dataset to associate with the test runs.
+ - client: An optional LangSmith client instance. If not provided, a new client will
+ be created.
+ - load_child_runs: Whether to load child runs when copying runs.
+
+ Returns:
+ - The project containing the cloned runs.
+
+ Example:
+ --------
+ ```python
+ import langsmith
+ import random
+
+ client = langsmith.Client()
+
+ # Randomly sample 100 runs from a prod project
+ runs = list(client.list_runs(project_name="My Project", execution_order=1))
+ sampled_runs = random.sample(runs, min(len(runs), 100))
+
+ runs_as_test(runs, dataset_name="Random Runs")
+
+ # Select runs named "extractor" whose root traces received good feedback
+ runs = client.list_runs(
+ project_name="",
+ filter='eq(name, "extractor")',
+ trace_filter='and(eq(feedback_key, "user_score"), eq(feedback_score, 1))',
+ )
+ runs_as_test(runs, dataset_name="Extraction Good")
+ ```
+ """
+ if not runs:
+ raise ValueError(f"""Expected a non-empty sequence of runs. Received: {runs}""")
+ client = client or rt.get_cached_client()
+ ds = client.create_dataset(dataset_name=dataset_name)
+ outputs = [r.outputs for r in runs] if include_outputs else None
+ client.create_examples(
+ inputs=[r.inputs for r in runs],
+ outputs=outputs,
+ source_run_ids=[r.id for r in runs],
+ dataset_id=ds.id,
+ )
+
+ if not load_child_runs:
+ runs_to_copy = runs
+ else:
+ runs_to_copy = [
+ client.read_run(r.id, load_child_runs=load_child_runs) for r in runs
+ ]
+
+ test_project_name = test_project_name or f"prod-baseline-{uuid.uuid4().hex[:6]}"
+
+ examples = list(client.list_examples(dataset_name=dataset_name))
+ run_to_example_map = {e.source_run_id: e.id for e in examples}
+ dataset_version = (
+ examples[0].modified_at if examples[0].modified_at else examples[0].created_at
+ )
+
+ to_create = [
+ run_dict
+ for root_run in runs_to_copy
+ for run_dict in _convert_root_run(root_run, run_to_example_map)
+ ]
+
+ project = client.create_project(
+ project_name=test_project_name,
+ reference_dataset_id=ds.id,
+ metadata={
+ "which": "prod-baseline",
+ "dataset_version": dataset_version.isoformat(),
+ },
+ )
+
+ for new_run in to_create:
+ latency = new_run["end_time"] - new_run["start_time"]
+ new_run["start_time"] = datetime.datetime.now(tz=datetime.timezone.utc)
+ new_run["end_time"] = new_run["start_time"] + latency
+ client.create_run(**new_run, project_name=test_project_name)
+
+ _ = client.update_project(
+ project.id,
+ )
+ return project
+
+
+def _load_nested_traces(project_name: str, client: Client) -> list[ls_schemas.Run]:
+ runs = client.list_runs(project_name=project_name)
+ treemap: collections.defaultdict[uuid.UUID, list[ls_schemas.Run]] = (
+ collections.defaultdict(list)
+ )
+ results = []
+ all_runs = {}
+ for run in runs:
+ if run.parent_run_id is not None:
+ treemap[run.parent_run_id].append(run)
+ else:
+ results.append(run)
+ all_runs[run.id] = run
+ for run_id, child_runs in treemap.items():
+ all_runs[run_id].child_runs = sorted(child_runs, key=lambda r: r.dotted_order)
+ return results
+
+
+T = TypeVar("T")
+U = TypeVar("U")
+
+
+def _outer_product(list1: list[T], list2: list[U]) -> list[tuple[T, U]]:
+ return list(itertools.product(list1, list2))
+
+
+@warn_beta
+def compute_test_metrics(
+ project_name: str,
+ *,
+ evaluators: list,
+ max_concurrency: Optional[int] = 10,
+ client: Optional[Client] = None,
+) -> None:
+ """Compute test metrics for a given test name using a list of evaluators.
+
+ Args:
+ project_name (str): The name of the test project to evaluate.
+ evaluators (list): A list of evaluators to compute metrics with.
+ max_concurrency (Optional[int], optional): The maximum number of concurrent
+ evaluations. Defaults to 10.
+ client (Optional[Client], optional): The client to use for evaluations.
+ Defaults to None.
+
+ Returns:
+ None: This function does not return any value.
+ """
+ from langsmith import ContextThreadPoolExecutor
+
+ evaluators_: list[ls_eval.RunEvaluator] = []
+ for func in evaluators:
+ if isinstance(func, ls_eval.RunEvaluator):
+ evaluators_.append(func)
+ elif callable(func):
+ evaluators_.append(ls_eval.run_evaluator(func))
+ else:
+ raise NotImplementedError(
+ f"Evaluation not yet implemented for evaluator of type {type(func)}"
+ )
+ client = client or rt.get_cached_client()
+ traces = _load_nested_traces(project_name, client)
+ with ContextThreadPoolExecutor(max_workers=max_concurrency) as executor:
+ results = executor.map(
+ client.evaluate_run, *zip(*_outer_product(traces, evaluators_))
+ )
+ for _ in results:
+ pass
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/cli/README.md b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/cli/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..8a0f9ad98e3327061ff35c8fc77d54cf000feb3c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/cli/README.md
@@ -0,0 +1,3 @@
+# DOCKER-COMPOSE MOVED
+
+All documentation for `docker-compose` has been moved to the [helm repository](https://github.com/langchain-ai/helm/tree/main/charts/langsmith).
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..542342ecbe867f7bea1e1d38ccbb06b96338d019
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/__init__.py
@@ -0,0 +1,30 @@
+"""Utilities to get information about the runtime environment."""
+from langsmith.env._git import get_git_info
+from langsmith.env._runtime_env import (
+ get_docker_compose_command,
+ get_docker_compose_version,
+ get_docker_environment,
+ get_docker_version,
+ get_langchain_env_var_metadata,
+ get_langchain_env_vars,
+ get_langchain_environment,
+ get_release_shas,
+ get_runtime_and_metrics,
+ get_runtime_environment,
+ get_system_metrics,
+)
+
+__all__ = [
+ "get_docker_compose_command",
+ "get_docker_compose_version",
+ "get_docker_environment",
+ "get_docker_version",
+ "get_langchain_env_var_metadata",
+ "get_langchain_env_vars",
+ "get_langchain_environment",
+ "get_release_shas",
+ "get_runtime_and_metrics",
+ "get_runtime_environment",
+ "get_system_metrics",
+ "get_git_info",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69ad2b0bd26e5be2623753e76c82d3f183230492
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/__pycache__/_git.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/__pycache__/_git.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..73fefc5f2df994bc10b76332580ce554e7a355e0
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/__pycache__/_git.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/__pycache__/_runtime_env.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/__pycache__/_runtime_env.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59e21767ed9f8776d273b5cb4cd0e46e27652586
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/__pycache__/_runtime_env.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/_git.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/_git.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce598285fae940870dbdf7389b17572ccef413b8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/_git.py
@@ -0,0 +1,64 @@
+"""Fetch information about any current git repo."""
+
+import functools
+import logging
+import subprocess
+from typing import List, Optional, TypeVar
+
+from typing_extensions import TypedDict
+
+logger = logging.getLogger(__name__)
+
+T = TypeVar("T")
+
+
+def exec_git(command: List[str]) -> Optional[str]:
+ try:
+ return subprocess.check_output(
+ ["git"] + command, encoding="utf-8", stderr=subprocess.DEVNULL
+ ).strip()
+ except BaseException:
+ return None
+
+
+class GitInfo(TypedDict, total=False):
+ repo_name: Optional[str]
+ remote_url: Optional[str]
+ commit: Optional[str]
+ branch: Optional[str]
+ author_name: Optional[str]
+ author_email: Optional[str]
+ commit_time: Optional[str]
+ dirty: Optional[bool]
+ tags: Optional[str]
+
+
+@functools.lru_cache(maxsize=1)
+def get_git_info(remote: str = "origin") -> GitInfo:
+ """Get information about the git repository."""
+ if not exec_git(["rev-parse", "--is-inside-work-tree"]):
+ return GitInfo(
+ remote_url=None,
+ commit=None,
+ branch=None,
+ author_name=None,
+ author_email=None,
+ commit_time=None,
+ dirty=None,
+ tags=None,
+ repo_name=None,
+ )
+
+ return {
+ "remote_url": exec_git(["remote", "get-url", remote]),
+ "commit": exec_git(["rev-parse", "HEAD"]),
+ "commit_time": exec_git(["log", "-1", "--format=%ct"]),
+ "branch": exec_git(["rev-parse", "--abbrev-ref", "HEAD"]),
+ "tags": exec_git(
+ ["describe", "--tags", "--exact-match", "--always", "--dirty"]
+ ),
+ "dirty": exec_git(["status", "--porcelain"]) != "",
+ "author_name": exec_git(["log", "-1", "--format=%an"]),
+ "author_email": exec_git(["log", "-1", "--format=%ae"]),
+ "repo_name": (exec_git(["rev-parse", "--show-toplevel"]) or "").split("/")[-1],
+ }
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/_runtime_env.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/_runtime_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..354f0eca1cbbc2b53bbfe61696fe46092a335ff5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/env/_runtime_env.py
@@ -0,0 +1,236 @@
+"""Environment information."""
+
+import functools
+import logging
+import os
+import platform
+import subprocess
+from typing import Dict, List, Optional, Union
+
+from langsmith.utils import get_docker_compose_command
+from langsmith.env._git import exec_git
+
+try:
+ # psutil is an optional dependency
+ import psutil
+
+ _PSUTIL_AVAILABLE = True
+except ImportError:
+ _PSUTIL_AVAILABLE = False
+logger = logging.getLogger(__name__)
+
+
+def get_runtime_and_metrics() -> dict:
+ """Get the runtime information as well as metrics."""
+ return {**get_runtime_environment(), **get_system_metrics()}
+
+
+def get_system_metrics() -> Dict[str, Union[float, dict]]:
+ """Get CPU and other performance metrics."""
+ global _PSUTIL_AVAILABLE
+ if not _PSUTIL_AVAILABLE:
+ return {}
+ try:
+ process = psutil.Process(os.getpid())
+ metrics: Dict[str, Union[float, dict]] = {}
+
+ with process.oneshot():
+ mem_info = process.memory_info()
+ metrics["thread_count"] = float(process.num_threads())
+ metrics["mem"] = {
+ "rss": float(mem_info.rss),
+ }
+ ctx_switches = process.num_ctx_switches()
+ cpu_times = process.cpu_times()
+ metrics["cpu"] = {
+ "time": {
+ "sys": cpu_times.system,
+ "user": cpu_times.user,
+ },
+ "ctx_switches": {
+ "voluntary": float(ctx_switches.voluntary),
+ "involuntary": float(ctx_switches.involuntary),
+ },
+ "percent": process.cpu_percent(),
+ }
+ return metrics
+ except Exception as e:
+ # If psutil is installed but not compatible with the build,
+ # we'll just cease further attempts to use it.
+ _PSUTIL_AVAILABLE = False
+ logger.debug("Failed to get system metrics: %s", e)
+ return {}
+
+
+@functools.lru_cache(maxsize=1)
+def get_runtime_environment() -> dict:
+ """Get information about the environment."""
+ # Lazy import to avoid circular imports
+ from langsmith import __version__
+
+ shas = get_release_shas()
+ return {
+ "sdk": "langsmith-py",
+ "sdk_version": __version__,
+ "library": "langsmith",
+ "platform": platform.platform(),
+ "runtime": "python",
+ "py_implementation": platform.python_implementation(),
+ "runtime_version": platform.python_version(),
+ "langchain_version": get_langchain_environment(),
+ "langchain_core_version": get_langchain_core_version(),
+ **shas,
+ }
+
+
+@functools.lru_cache(maxsize=1)
+def get_langchain_environment() -> Optional[str]:
+ try:
+ import langchain # type: ignore
+
+ return langchain.__version__
+ except: # noqa
+ return None
+
+
+@functools.lru_cache(maxsize=1)
+def get_langchain_core_version() -> Optional[str]:
+ try:
+ import langchain_core # type: ignore
+
+ return langchain_core.__version__
+ except ImportError:
+ return None
+
+
+@functools.lru_cache(maxsize=1)
+def get_docker_version() -> Optional[str]:
+ import subprocess
+
+ try:
+ docker_version = (
+ subprocess.check_output(["docker", "--version"]).decode("utf-8").strip()
+ )
+ except FileNotFoundError:
+ docker_version = "unknown"
+ except: # noqa
+ return None
+ return docker_version
+
+
+@functools.lru_cache(maxsize=1)
+def get_docker_compose_version() -> Optional[str]:
+ try:
+ docker_compose_version = (
+ subprocess.check_output(["docker-compose", "--version"])
+ .decode("utf-8")
+ .strip()
+ )
+ except FileNotFoundError:
+ docker_compose_version = "unknown"
+ except: # noqa
+ return None
+ return docker_compose_version
+
+
+@functools.lru_cache(maxsize=1)
+def _get_compose_command() -> Optional[List[str]]:
+ try:
+ compose_command = get_docker_compose_command()
+ except ValueError as e:
+ compose_command = [f"NOT INSTALLED: {e}"]
+ except: # noqa
+ return None
+ return compose_command
+
+
+@functools.lru_cache(maxsize=1)
+def get_docker_environment() -> dict:
+ """Get information about the environment."""
+ compose_command = _get_compose_command()
+ return {
+ "docker_version": get_docker_version(),
+ "docker_compose_command": (
+ " ".join(compose_command) if compose_command is not None else None
+ ),
+ "docker_compose_version": get_docker_compose_version(),
+ }
+
+
+def get_langchain_env_vars() -> dict:
+ """Retrieve the langchain environment variables."""
+ env_vars = {k: v for k, v in os.environ.items() if k.startswith("LANGCHAIN_")}
+ for key in list(env_vars):
+ if "key" in key.lower():
+ v = env_vars[key]
+ env_vars[key] = v[:2] + "*" * (len(v) - 4) + v[-2:]
+ return env_vars
+
+
+@functools.lru_cache(maxsize=1)
+def get_langchain_env_var_metadata() -> dict:
+ """Retrieve the langchain environment variables."""
+ excluded = {
+ "LANGCHAIN_API_KEY",
+ "LANGCHAIN_ENDPOINT",
+ "LANGCHAIN_TRACING_V2",
+ "LANGCHAIN_PROJECT",
+ "LANGCHAIN_SESSION",
+ "LANGSMITH_RUNS_ENDPOINTS",
+ }
+ langchain_metadata = {
+ k: v
+ for k, v in os.environ.items()
+ if (k.startswith("LANGCHAIN_") or k.startswith("LANGSMITH_"))
+ and k not in excluded
+ and "key" not in k.lower()
+ and "secret" not in k.lower()
+ and "token" not in k.lower()
+ }
+ env_revision_id = langchain_metadata.pop("LANGCHAIN_REVISION_ID", None)
+ if env_revision_id:
+ langchain_metadata["revision_id"] = env_revision_id
+ elif default_revision_id := _get_default_revision_id():
+ langchain_metadata["revision_id"] = default_revision_id
+
+ return langchain_metadata
+
+
+@functools.lru_cache(maxsize=1)
+def _get_default_revision_id() -> Optional[str]:
+ """Get the default revision ID based on `git describe`."""
+ try:
+ return exec_git(["describe", "--tags", "--always", "--dirty"])
+ except BaseException:
+ return None
+
+
+@functools.lru_cache(maxsize=1)
+def get_release_shas() -> Dict[str, str]:
+ common_release_envs = [
+ "VERCEL_GIT_COMMIT_SHA",
+ "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA",
+ "COMMIT_REF",
+ "RENDER_GIT_COMMIT",
+ "CI_COMMIT_SHA",
+ "CIRCLE_SHA1",
+ "CF_PAGES_COMMIT_SHA",
+ "REACT_APP_GIT_SHA",
+ "SOURCE_VERSION",
+ "GITHUB_SHA",
+ "TRAVIS_COMMIT",
+ "GIT_COMMIT",
+ "BUILD_VCS_NUMBER",
+ "bamboo_planRepository_revision",
+ "Build.SourceVersion",
+ "BITBUCKET_COMMIT",
+ "DRONE_COMMIT_SHA",
+ "SEMAPHORE_GIT_SHA",
+ "BUILDKITE_COMMIT",
+ ]
+ shas = {}
+ for env in common_release_envs:
+ env_var = os.environ.get(env)
+ if env_var is not None:
+ shas[env] = env_var
+ return shas
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..244697df282795e0ef9c1dcd6d50bfe5ebf9653e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__init__.py
@@ -0,0 +1,89 @@
+"""Evaluation Helpers."""
+
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from langsmith.evaluation._arunner import (
+ aevaluate,
+ aevaluate_existing,
+ )
+ from langsmith.evaluation._runner import (
+ evaluate,
+ evaluate_comparative,
+ evaluate_existing,
+ )
+ from langsmith.evaluation.evaluator import (
+ EvaluationResult,
+ EvaluationResults,
+ RunEvaluator,
+ run_evaluator,
+ )
+
+
+def __getattr__(
+ name: str,
+) -> Any:
+ """.. deprecated:: 0.5.0.
+
+ Importing from langsmith.evaluation is deprecated. Use client.evaluate() instead.
+ """
+ if name == "evaluate":
+ from langsmith.evaluation._runner import evaluate
+
+ return evaluate
+ elif name == "evaluate_existing":
+ from langsmith.evaluation._runner import evaluate_existing
+
+ return evaluate_existing
+ elif name == "aevaluate":
+ from langsmith.evaluation._arunner import aevaluate
+
+ return aevaluate
+ elif name == "aevaluate_existing":
+ from langsmith.evaluation._arunner import aevaluate_existing
+
+ return aevaluate_existing
+ elif name == "evaluate_comparative":
+ from langsmith.evaluation._runner import evaluate_comparative
+
+ return evaluate_comparative
+ elif name == "EvaluationResult":
+ from langsmith.evaluation.evaluator import EvaluationResult
+
+ return EvaluationResult
+ elif name == "EvaluationResults":
+ from langsmith.evaluation.evaluator import EvaluationResults
+
+ return EvaluationResults
+ elif name == "RunEvaluator":
+ from langsmith.evaluation.evaluator import RunEvaluator
+
+ return RunEvaluator
+ elif name == "run_evaluator":
+ from langsmith.evaluation.evaluator import run_evaluator
+
+ return run_evaluator
+ elif name == "StringEvaluator":
+ from langsmith.evaluation.string_evaluator import StringEvaluator
+
+ return StringEvaluator
+
+ raise AttributeError(f"module {__name__} has no attribute {name}")
+
+
+__all__ = [
+ "run_evaluator",
+ "EvaluationResult",
+ "EvaluationResults",
+ "RunEvaluator",
+ "StringEvaluator",
+ "aevaluate",
+ "aevaluate_existing",
+ "evaluate",
+ "evaluate_existing",
+ "evaluate_comparative",
+]
+
+
+def __dir__() -> list[str]:
+ return __all__
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..37279561f74082831bc146339bcd52f347ed03b2
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/_arunner.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/_arunner.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..66ffcdd0df8d529c1f06f2d218c5f911eecdf909
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/_arunner.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/_name_generation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/_name_generation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab3989ff4792d23ce34b40f234b3d92aaef35636
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/_name_generation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/evaluator.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/evaluator.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb7ace721043384a175a1d7356949f72ce53e006
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/evaluator.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/llm_evaluator.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/llm_evaluator.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5a278d1ae5ec3bb75f0a6eb0639e94969f87b02
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/llm_evaluator.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/string_evaluator.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/string_evaluator.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c93370b915db89e9d316bcdd5a38635a1e236984
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/__pycache__/string_evaluator.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/_arunner.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/_arunner.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaba3480549e00c00368abd0c63e002ed612e9a6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/_arunner.py
@@ -0,0 +1,1395 @@
+"""V2 Evaluation Interface."""
+
+from __future__ import annotations
+
+import asyncio
+import concurrent.futures as cf
+import contextvars
+import io
+import logging
+import pathlib
+import uuid
+from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Iterable, Sequence
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Literal,
+ Optional,
+ TypeVar,
+ Union,
+ cast,
+)
+
+import langsmith
+from langsmith import run_helpers as rh
+from langsmith import run_trees, schemas
+from langsmith import run_trees as rt
+from langsmith import utils as ls_utils
+from langsmith._internal import _aiter as aitertools
+from langsmith._internal._beta_decorator import _warn_once
+from langsmith.evaluation._runner import (
+ AEVALUATOR_T,
+ DATA_T,
+ EVALUATOR_T,
+ ExperimentResultRow,
+ _evaluators_include_attachments,
+ _ExperimentManagerMixin,
+ _extract_feedback_keys,
+ _ForwardResults,
+ _get_target_args,
+ _is_langchain_runnable,
+ _load_examples_map,
+ _load_experiment,
+ _load_tqdm,
+ _load_traces,
+ _resolve_data,
+ _resolve_evaluators,
+ _resolve_experiment,
+ _target_include_attachments,
+ _to_pandas,
+ _wrap_summary_evaluators,
+)
+from langsmith.evaluation.evaluator import (
+ SUMMARY_EVALUATOR_T,
+ EvaluationResult,
+ EvaluationResults,
+ RunEvaluator,
+)
+
+if TYPE_CHECKING:
+ import pandas as pd
+ from langchain_core.runnables import Runnable
+
+ DataFrame = pd.DataFrame
+else:
+ DataFrame = Any
+
+logger = logging.getLogger(__name__)
+
+ATARGET_T = Union[
+ Callable[[dict], Awaitable[dict]], Callable[[dict, dict], Awaitable[dict]]
+]
+
+
+async def aevaluate(
+ target: Union[
+ ATARGET_T, AsyncIterable[dict], Runnable, str, uuid.UUID, schemas.TracerSession
+ ],
+ /,
+ data: Union[
+ DATA_T, AsyncIterable[schemas.Example], Iterable[schemas.Example], None
+ ] = None,
+ evaluators: Optional[Sequence[Union[EVALUATOR_T, AEVALUATOR_T]]] = None,
+ summary_evaluators: Optional[Sequence[SUMMARY_EVALUATOR_T]] = None,
+ metadata: Optional[dict] = None,
+ experiment_prefix: Optional[str] = None,
+ description: Optional[str] = None,
+ max_concurrency: Optional[int] = 0,
+ num_repetitions: int = 1,
+ client: Optional[langsmith.Client] = None,
+ blocking: bool = True,
+ experiment: Optional[Union[schemas.TracerSession, str, uuid.UUID]] = None,
+ upload_results: bool = True,
+ error_handling: Literal["log", "ignore"] = "log",
+ **kwargs: Any,
+) -> AsyncExperimentResults:
+ r"""Evaluate an async target system on a given dataset.
+
+ Args:
+ target (AsyncCallable[[dict], dict] | AsyncIterable[dict] | Runnable | EXPERIMENT_T | Tuple[EXPERIMENT_T, EXPERIMENT_T]):
+ The target system or experiment(s) to evaluate.
+
+ Can be an async function that takes a `dict` and returns a `dict`, a
+ langchain `Runnable`, an existing experiment ID, or a two-tuple of experiment IDs.
+ data (Union[DATA_T, AsyncIterable[schemas.Example]]): The dataset to evaluate on.
+
+ Can be a dataset name, a list of examples, an async generator of examples, or an async iterable of examples.
+ evaluators (Optional[Sequence[EVALUATOR_T]]): A list of evaluators to run
+ on each example.
+ summary_evaluators (Optional[Sequence[SUMMARY_EVALUATOR_T]]): A list of summary
+ evaluators to run on the entire dataset.
+ metadata (Optional[dict]): Metadata to attach to the experiment.
+ experiment_prefix (Optional[str]): A prefix to provide for your experiment name.
+ description (Optional[str]): A description of the experiment.
+ max_concurrency (int | None): The maximum number of concurrent
+ evaluations to run.
+
+ If `None` then no limit is set. If `0` then no concurrency.
+ num_repetitions (int): The number of times to run the evaluation.
+ Each item in the dataset will be run and evaluated this many times.
+ client (Optional[langsmith.Client]): The LangSmith client to use.
+ blocking (bool): Whether to block until the evaluation is complete.
+ experiment (Optional[schemas.TracerSession]): An existing experiment to
+ extend.
+
+ If provided, `experiment_prefix` is ignored. For advanced usage only.
+ error_handling (str, default="log"): How to handle individual run errors.
+
+ `'log'` will trace the runs with the error message as part of the
+ experiment, `'ignore'` will not count the run as part of the experiment at
+ all.
+
+ Returns:
+ An async iterator over the experiment results.
+
+ Environment:
+ - `LANGSMITH_TEST_CACHE`: If set, API calls will be cached to disk to save time and
+ cost during testing.
+
+ Recommended to commit the cache files to your repository for faster CI/CD runs.
+
+ Requires the `'langsmith[vcr]'` package to be installed.
+
+ Examples:
+ >>> from typing import Sequence
+ >>> from langsmith import Client, aevaluate
+ >>> from langsmith.schemas import Example, Run
+ >>> client = Client()
+ >>> dataset = client.clone_public_dataset(
+ ... "https://smith.langchain.com/public/419dcab2-1d66-4b94-8901-0357ead390df/d"
+ ... )
+ >>> dataset_name = "Evaluate Examples"
+
+ Basic usage:
+
+ >>> def accuracy(run: Run, example: Example):
+ ... # Row-level evaluator for accuracy.
+ ... pred = run.outputs["output"]
+ ... expected = example.outputs["answer"]
+ ... return {"score": expected.lower() == pred.lower()}
+
+ >>> def precision(runs: Sequence[Run], examples: Sequence[Example]):
+ ... # Experiment-level evaluator for precision.
+ ... # TP / (TP + FP)
+ ... predictions = [run.outputs["output"].lower() for run in runs]
+ ... expected = [example.outputs["answer"].lower() for example in examples]
+ ... # yes and no are the only possible answers
+ ... tp = sum([p == e for p, e in zip(predictions, expected) if p == "yes"])
+ ... fp = sum([p == "yes" and e == "no" for p, e in zip(predictions, expected)])
+ ... return {"score": tp / (tp + fp)}
+
+ >>> import asyncio
+ >>> async def apredict(inputs: dict) -> dict:
+ ... # This can be any async function or just an API call to your app.
+ ... await asyncio.sleep(0.1)
+ ... return {"output": "Yes"}
+ >>> results = asyncio.run(
+ ... aevaluate(
+ ... apredict,
+ ... data=dataset_name,
+ ... evaluators=[accuracy],
+ ... summary_evaluators=[precision],
+ ... experiment_prefix="My Experiment",
+ ... description="Evaluate the accuracy of the model asynchronously.",
+ ... metadata={
+ ... "my-prompt-version": "abcd-1234",
+ ... },
+ ... )
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+
+ Evaluating over only a subset of the examples using an async generator:
+
+ >>> async def example_generator():
+ ... examples = client.list_examples(dataset_name=dataset_name, limit=5)
+ ... for example in examples:
+ ... yield example
+ >>> results = asyncio.run(
+ ... aevaluate(
+ ... apredict,
+ ... data=example_generator(),
+ ... evaluators=[accuracy],
+ ... summary_evaluators=[precision],
+ ... experiment_prefix="My Subset Experiment",
+ ... description="Evaluate a subset of examples asynchronously.",
+ ... )
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+
+ Streaming each prediction to more easily + eagerly debug.
+
+ >>> results = asyncio.run(
+ ... aevaluate(
+ ... apredict,
+ ... data=dataset_name,
+ ... evaluators=[accuracy],
+ ... summary_evaluators=[precision],
+ ... experiment_prefix="My Streaming Experiment",
+ ... description="Streaming predictions for debugging.",
+ ... blocking=False,
+ ... )
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+
+ >>> async def aenumerate(iterable):
+ ... async for elem in iterable:
+ ... print(elem)
+ >>> asyncio.run(aenumerate(results))
+
+ Running without concurrency:
+
+ >>> results = asyncio.run(
+ ... aevaluate(
+ ... apredict,
+ ... data=dataset_name,
+ ... evaluators=[accuracy],
+ ... summary_evaluators=[precision],
+ ... experiment_prefix="My Experiment Without Concurrency",
+ ... description="This was run without concurrency.",
+ ... max_concurrency=0,
+ ... )
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+
+ Using Async evaluators:
+
+ >>> async def helpfulness(run: Run, example: Example):
+ ... # Row-level evaluator for helpfulness.
+ ... await asyncio.sleep(5) # Replace with your LLM API call
+ ... return {"score": run.outputs["output"] == "Yes"}
+
+ >>> results = asyncio.run(
+ ... aevaluate(
+ ... apredict,
+ ... data=dataset_name,
+ ... evaluators=[helpfulness],
+ ... summary_evaluators=[precision],
+ ... experiment_prefix="My Helpful Experiment",
+ ... description="Applying async evaluators example.",
+ ... )
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+
+
+ !!! warning "Behavior changed in `langsmith` 0.2.0"
+
+ 'max_concurrency' default updated from None (no limit on concurrency)
+ to 0 (no concurrency at all).
+ """ # noqa: E501
+ if isinstance(target, (str, uuid.UUID, schemas.TracerSession)):
+ invalid_args = {
+ "num_repetitions": num_repetitions > 1,
+ "experiment": bool(experiment),
+ "upload_results": not upload_results,
+ "experiment_prefix": bool(experiment_prefix),
+ "data": bool(data),
+ }
+ if any(invalid_args.values()):
+ msg = (
+ f"Received invalid arguments. "
+ f"{tuple(k for k, v in invalid_args.items() if v)} should not be "
+ f"specified when target is an existing experiment."
+ )
+ raise ValueError(msg)
+ target_id = target if isinstance(target, (str, uuid.UUID)) else target.id
+ logger.debug(f"Running evaluation over existing experiment {target_id}...")
+ return await aevaluate_existing(
+ target,
+ evaluators=evaluators,
+ summary_evaluators=summary_evaluators,
+ metadata=metadata,
+ max_concurrency=max_concurrency,
+ client=client,
+ blocking=blocking,
+ **kwargs,
+ )
+ elif isinstance(target, (list, tuple)):
+ msg = (
+ "Running a comparison of two existing experiments asynchronously is not "
+ "currently supported. Please use the `evaluate()` method instead and make "
+ "sure that your evaluators are defined as synchronous functions."
+ )
+ raise ValueError(msg)
+ elif kwargs:
+ msg = (
+ f"Received unsupported arguments {kwargs}. These arguments are not "
+ f"supported when creating a new experiment."
+ )
+ raise ValueError(msg)
+ elif not data:
+ msg = "Must specify 'data' when running evaluations over a target function."
+ raise ValueError(msg)
+ elif experiment and experiment_prefix:
+ msg = (
+ "Expected at most one of 'experiment' or 'experiment_prefix',"
+ " but both were provided. "
+ f"Got: experiment={experiment}, experiment_prefix={experiment_prefix}"
+ )
+ raise ValueError(msg)
+ else:
+ if not upload_results:
+ _warn_once("'upload_results' parameter is in beta.")
+ logger.debug(f"Running evaluation over target system {target}...")
+ return await _aevaluate(
+ target,
+ data=data,
+ evaluators=evaluators,
+ summary_evaluators=summary_evaluators,
+ metadata=metadata,
+ experiment_prefix=experiment_prefix,
+ description=description,
+ max_concurrency=max_concurrency,
+ num_repetitions=num_repetitions,
+ client=client,
+ blocking=blocking,
+ experiment=experiment,
+ upload_results=upload_results,
+ error_handling=error_handling,
+ )
+
+
+async def aevaluate_existing(
+ experiment: Union[str, uuid.UUID, schemas.TracerSession],
+ /,
+ evaluators: Optional[Sequence[Union[EVALUATOR_T, AEVALUATOR_T]]] = None,
+ summary_evaluators: Optional[Sequence[SUMMARY_EVALUATOR_T]] = None,
+ metadata: Optional[dict] = None,
+ max_concurrency: Optional[int] = 0,
+ client: Optional[langsmith.Client] = None,
+ load_nested: bool = False,
+ blocking: bool = True,
+) -> AsyncExperimentResults:
+ r"""Evaluate existing experiment runs asynchronously.
+
+ Args:
+ experiment (Union[str, uuid.UUID]): The identifier of the experiment to evaluate.
+ evaluators (Optional[Sequence[EVALUATOR_T]]): Optional sequence of evaluators to use for individual run evaluation.
+ summary_evaluators (Optional[Sequence[SUMMARY_EVALUATOR_T]]): Optional sequence of evaluators
+ to apply over the entire dataset.
+ metadata (Optional[dict]): Optional metadata to include in the evaluation results.
+ max_concurrency (int | None): The maximum number of concurrent
+ evaluations to run.
+
+ If `None` then no limit is set. If `0` then no concurrency.
+ client (Optional[langsmith.Client]): Optional Langsmith client to use for evaluation.
+ load_nested: Whether to load all child runs for the experiment.
+
+ Default is to only load the top-level root runs.
+ blocking (bool): Whether to block until evaluation is complete.
+
+ Returns:
+ An async iterator over the experiment results.
+
+ Examples:
+ Define your evaluators
+
+ >>> from typing import Sequence
+ >>> from langsmith.schemas import Example, Run
+ >>> def accuracy(run: Run, example: Example):
+ ... # Row-level evaluator for accuracy.
+ ... pred = run.outputs["output"]
+ ... expected = example.outputs["answer"]
+ ... return {"score": expected.lower() == pred.lower()}
+ >>> def precision(runs: Sequence[Run], examples: Sequence[Example]):
+ ... # Experiment-level evaluator for precision.
+ ... # TP / (TP + FP)
+ ... predictions = [run.outputs["output"].lower() for run in runs]
+ ... expected = [example.outputs["answer"].lower() for example in examples]
+ ... # yes and no are the only possible answers
+ ... tp = sum([p == e for p, e in zip(predictions, expected) if p == "yes"])
+ ... fp = sum([p == "yes" and e == "no" for p, e in zip(predictions, expected)])
+ ... return {"score": tp / (tp + fp)}
+
+ Load the experiment and run the evaluation.
+
+ >>> import asyncio
+ >>> import uuid
+ >>> from langsmith import Client, aevaluate, aevaluate_existing
+ >>> client = Client()
+ >>> dataset_name = "__doctest_aevaluate_existing_" + uuid.uuid4().hex[:8]
+ >>> dataset = client.create_dataset(dataset_name)
+ >>> example = client.create_example(
+ ... inputs={"question": "What is 2+2?"},
+ ... outputs={"answer": "4"},
+ ... dataset_id=dataset.id,
+ ... )
+ >>> async def apredict(inputs: dict) -> dict:
+ ... await asyncio.sleep(0.001)
+ ... return {"output": "4"}
+ >>> results = asyncio.run(
+ ... aevaluate(
+ ... apredict, data=dataset_name, experiment_prefix="doctest_experiment"
+ ... )
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+ >>> experiment_id = results.experiment_name
+ >>> # Consume all results to ensure evaluation is complete
+ >>> async def consume_results():
+ ... result_list = [r async for r in results]
+ ... return len(result_list) > 0
+ >>> asyncio.run(consume_results())
+ True
+ >>> import time
+ >>> time.sleep(3)
+ >>> results = asyncio.run(
+ ... aevaluate_existing(
+ ... experiment_id,
+ ... evaluators=[accuracy],
+ ... summary_evaluators=[precision],
+ ... )
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+ >>> client.delete_dataset(dataset_id=dataset.id)
+
+
+ """ # noqa: E501
+ client = client or run_trees.get_cached_client()
+ project = (
+ experiment
+ if isinstance(experiment, schemas.TracerSession)
+ else (
+ await aitertools.aio_to_thread(
+ contextvars.copy_context(), _load_experiment, experiment, client
+ )
+ )
+ )
+ runs = await aitertools.aio_to_thread(
+ contextvars.copy_context(),
+ _load_traces,
+ experiment,
+ client,
+ load_nested=load_nested,
+ )
+ data_map = await aitertools.aio_to_thread(
+ contextvars.copy_context(), _load_examples_map, client, project
+ )
+ data = [data_map[run.reference_example_id] for run in runs]
+ return await _aevaluate(
+ runs,
+ data=data,
+ evaluators=evaluators,
+ summary_evaluators=summary_evaluators,
+ metadata=metadata,
+ max_concurrency=max_concurrency,
+ client=client,
+ blocking=blocking,
+ experiment=project,
+ )
+
+
+async def _aevaluate(
+ target: Union[ATARGET_T, AsyncIterable[dict], Iterable[schemas.Run], Runnable],
+ /,
+ data: Union[DATA_T, AsyncIterable[schemas.Example]],
+ evaluators: Optional[Sequence[Union[EVALUATOR_T, AEVALUATOR_T]]] = None,
+ summary_evaluators: Optional[Sequence[SUMMARY_EVALUATOR_T]] = None,
+ metadata: Optional[dict] = None,
+ experiment_prefix: Optional[str] = None,
+ description: Optional[str] = None,
+ max_concurrency: Optional[int] = None,
+ num_repetitions: int = 1,
+ client: Optional[langsmith.Client] = None,
+ blocking: bool = True,
+ experiment: Optional[Union[schemas.TracerSession, str, uuid.UUID]] = None,
+ upload_results: bool = True,
+ error_handling: Literal["log", "ignore"] = "log",
+) -> AsyncExperimentResults:
+ is_async_target = (
+ asyncio.iscoroutinefunction(target)
+ or (hasattr(target, "__aiter__") and asyncio.iscoroutine(target.__aiter__()))
+ or _is_langchain_runnable(target)
+ )
+ client = client or rt.get_cached_client()
+ runs = None if is_async_target else cast(Iterable[schemas.Run], target)
+ experiment_, runs = await aitertools.aio_to_thread(
+ contextvars.copy_context(),
+ _resolve_experiment,
+ experiment,
+ runs,
+ client,
+ )
+ num_include_attachments = int(
+ _target_include_attachments(target)
+ ) + _evaluators_include_attachments(evaluators)
+ manager = await _AsyncExperimentManager(
+ data,
+ client=client,
+ metadata=metadata,
+ experiment=experiment_ or experiment_prefix,
+ description=description,
+ num_repetitions=num_repetitions,
+ runs=runs,
+ include_attachments=num_include_attachments > 0,
+ reuse_attachments=num_repetitions * num_include_attachments > 1,
+ upload_results=upload_results,
+ error_handling=error_handling,
+ ).astart()
+ cache_dir = ls_utils.get_cache_dir(None)
+ if cache_dir is not None:
+ dsid = await manager.get_dataset_id()
+ cache_path = pathlib.Path(cache_dir) / f"{dsid}.yaml"
+ else:
+ cache_path = None
+ with ls_utils.with_optional_cache(cache_path, ignore_hosts=[client.api_url]):
+ if is_async_target:
+ if evaluators:
+ # Run predictions and evaluations in a single pipeline
+ manager = await manager.awith_predictions_and_evaluators(
+ cast(ATARGET_T, target), evaluators, max_concurrency=max_concurrency
+ )
+ else:
+ manager = await manager.awith_predictions(
+ cast(ATARGET_T, target), max_concurrency=max_concurrency
+ )
+ if summary_evaluators:
+ manager = await manager.awith_summary_evaluators(summary_evaluators)
+ else:
+ if evaluators:
+ manager = await manager.awith_evaluators(
+ evaluators, max_concurrency=max_concurrency
+ )
+ if summary_evaluators:
+ manager = await manager.awith_summary_evaluators(summary_evaluators)
+ results = AsyncExperimentResults(manager)
+ if blocking:
+ await results.wait()
+ return results
+
+
+class _AsyncExperimentManager(_ExperimentManagerMixin):
+ """Manage the execution of experiments asynchronously.
+
+ Supports lazily running predictions and evaluations in parallel to facilitate
+ result streaming and early debugging.
+
+ Args:
+ data (DATA_T): The data used for the experiment. Can be a dataset name or ID OR
+ a generator of examples.
+ runs (Optional[Iterable[schemas.Run]]): The runs associated with the experiment
+ predictions.
+ experiment (Optional[schemas.TracerSession]): The tracer session
+ associated with the experiment.
+ experiment_prefix (Optional[str]): The prefix for the experiment name.
+ description (Optional[str]): The description for the experiment.
+ metadata (Optional[dict]): Additional metadata for the experiment.
+ client (Optional[langsmith.Client]): The Langsmith client used for
+ the experiment.
+ evaluation_results (Optional[Iterable[EvaluationResults]]): The evaluation
+ sresults for the experiment.
+ summary_results (Optional[Iterable[EvaluationResults]]): The aggregate results
+ for the experiment.
+ num_repetitions (Optional[int], default=1): The number of repetitions for
+ the experiment.
+ include_attachments (Optional[bool], default=False): Whether to include
+ attachments. This is used for when we pull the examples for the experiment.
+ reuse_attachments (Optional[bool], default=False): Whether to reuse attachments
+ from examples. This is True if we need to reuse attachments across multiple
+ target/evaluator functions.
+ upload_results (Optional[bool], default=True): Whether to upload results
+ to Langsmith.
+ attachment_raw_data_dict (Optional[dict]): A dictionary to store raw data
+ for attachments. Only used if we reuse attachments across multiple
+ target/evaluator functions.
+ error_handling (str, default="log"): How to handle individual run errors.
+
+ `'log'` will trace the runs with the error message as part of the
+ experiment, `'ignore'` will not count the run as part of the experiment at
+ all.
+ """
+
+ def __init__(
+ self,
+ data: Union[DATA_T, AsyncIterable[schemas.Example]],
+ /,
+ experiment: Optional[Union[schemas.TracerSession, str]] = None,
+ metadata: Optional[dict] = None,
+ runs: Optional[Union[Iterable[schemas.Run], AsyncIterable[schemas.Run]]] = None,
+ client: Optional[langsmith.Client] = None,
+ evaluation_results: Optional[AsyncIterable[EvaluationResults]] = None,
+ summary_results: Optional[AsyncIterable[EvaluationResults]] = None,
+ description: Optional[str] = None,
+ num_repetitions: int = 1,
+ include_attachments: bool = False,
+ reuse_attachments: bool = False,
+ upload_results: bool = True,
+ attachment_raw_data_dict: Optional[dict] = None,
+ error_handling: Literal["log", "ignore"] = "log",
+ ):
+ super().__init__(
+ experiment=experiment,
+ metadata=metadata,
+ client=client,
+ description=description,
+ )
+ self._data = data
+ self._examples: Optional[AsyncIterable[schemas.Example]] = None
+ self._runs = (
+ aitertools.ensure_async_iterator(runs) if runs is not None else None
+ )
+ self._evaluation_results = evaluation_results
+ self._summary_results = summary_results
+ self._num_repetitions = num_repetitions
+ self._include_attachments = include_attachments
+ self._reuse_attachments = reuse_attachments
+ self._upload_results = upload_results
+ self._attachment_raw_data_dict = attachment_raw_data_dict
+ self._error_handling = error_handling
+
+ def _reset_example_attachments(self, example: schemas.Example) -> schemas.Example:
+ """Reset attachment readers for an example.
+
+ This is only in the case that an attachment is going to be used by more
+ than 1 callable (target + evaluators). In that case we keep a single copy
+ of the attachment data in self._attachment_raw_data_dict, and create
+ readers from that data. This makes it so that we don't have to keep
+ copies of the same data in memory, instead we can just create readers
+ from the same data.
+ """
+ if not hasattr(example, "attachments") or not example.attachments:
+ return example
+
+ new_attachments: dict[str, schemas.AttachmentInfo] = {}
+ for name, attachment in example.attachments.items():
+ if (
+ self._attachment_raw_data_dict is not None
+ and str(example.id) + name in self._attachment_raw_data_dict
+ ):
+ new_attachments[name] = {
+ "presigned_url": attachment["presigned_url"],
+ "reader": io.BytesIO(
+ self._attachment_raw_data_dict[str(example.id) + name]
+ ),
+ "mime_type": attachment["mime_type"],
+ }
+ else:
+ new_attachments[name] = attachment
+
+ # Create a new Example instance with the updated attachments
+ return schemas.Example(
+ id=example.id,
+ created_at=example.created_at,
+ dataset_id=example.dataset_id,
+ inputs=example.inputs,
+ outputs=example.outputs,
+ metadata=example.metadata,
+ modified_at=example.modified_at,
+ source_run_id=example.source_run_id,
+ attachments=new_attachments,
+ _host_url=example._host_url,
+ _tenant_id=example._tenant_id,
+ )
+
+ async def aget_examples(self) -> AsyncIterator[schemas.Example]:
+ if self._examples is None:
+ self._examples = _aresolve_data(
+ self._data,
+ client=self.client,
+ include_attachments=self._include_attachments,
+ )
+ if self._reuse_attachments and self._attachment_raw_data_dict is None:
+ examples_copy, self._examples = aitertools.atee(self._examples)
+ self._attachment_raw_data_dict = {
+ str(e.id) + name: value["reader"].read()
+ async for e in examples_copy
+ for name, value in (e.attachments or {}).items()
+ }
+ if self._num_repetitions > 1:
+ examples_list = [example async for example in self._examples]
+ self._examples = async_chain_from_iterable(
+ [
+ async_iter_from_list(
+ [
+ self._reset_example_attachments(example)
+ for example in examples_list
+ ]
+ )
+ for _ in range(self._num_repetitions)
+ ]
+ )
+
+ self._examples, examples_iter = aitertools.atee(
+ aitertools.ensure_async_iterator(self._examples), 2, lock=asyncio.Lock()
+ )
+ return examples_iter
+
+ async def get_dataset_id(self) -> str:
+ if self._experiment is None or not getattr(
+ self._experiment, "reference_dataset_id", None
+ ):
+ example = await aitertools.py_anext(await self.aget_examples())
+ if example is None:
+ raise ValueError("No examples found in the dataset.")
+ return str(example.dataset_id)
+ return str(self._experiment.reference_dataset_id)
+
+ async def aget_runs(self) -> AsyncIterator[schemas.Run]:
+ if self._runs is None:
+ raise ValueError("Runs not loaded yet.")
+ self._runs, runs = aitertools.atee(
+ aitertools.ensure_async_iterator(self._runs), 2, lock=asyncio.Lock()
+ )
+ async for run in runs:
+ yield run
+
+ async def aget_evaluation_results(self) -> AsyncIterator[EvaluationResults]:
+ if self._evaluation_results is None:
+ async for _ in await self.aget_examples():
+ yield {"results": []}
+ else:
+ self._evaluation_results, evaluation_results = aitertools.atee(
+ aitertools.ensure_async_iterator(self._evaluation_results),
+ 2,
+ lock=asyncio.Lock(),
+ )
+ async for result in evaluation_results:
+ yield result
+
+ async def astart(self) -> _AsyncExperimentManager:
+ try:
+ first_example = await aitertools.py_anext(await self.aget_examples())
+ except StopAsyncIteration:
+ raise ValueError(
+ "No examples found in the dataset. "
+ "Please ensure the data provided to aevaluate is not empty."
+ )
+ if not first_example:
+ raise ValueError(
+ "No examples found in the dataset."
+ "Please ensure the data provided to aevaluate is not empty."
+ )
+ project = self._get_project(first_example) if self._upload_results else None
+ self._print_experiment_start(project, first_example)
+ self._metadata["num_repetitions"] = self._num_repetitions
+ return self._copy(
+ await self.aget_examples(),
+ experiment=project,
+ )
+
+ def _get_example_with_readers(self, example: schemas.Example) -> schemas.Example:
+ new_attachments: dict[str, schemas.AttachmentInfo] = {}
+ for name, attachment in (example.attachments or {}).items():
+ if (
+ self._attachment_raw_data_dict is not None
+ and str(example.id) + name in self._attachment_raw_data_dict
+ ):
+ reader = io.BytesIO(
+ self._attachment_raw_data_dict[str(example.id) + name]
+ )
+ new_attachments[name] = {
+ "presigned_url": attachment["presigned_url"],
+ "reader": reader,
+ "mime_type": attachment["mime_type"],
+ }
+ else:
+ new_attachments[name] = attachment
+
+ return schemas.Example(
+ id=example.id,
+ created_at=example.created_at,
+ dataset_id=example.dataset_id,
+ inputs=example.inputs,
+ outputs=example.outputs,
+ metadata=example.metadata,
+ modified_at=example.modified_at,
+ source_run_id=example.source_run_id,
+ attachments=new_attachments,
+ _host_url=example._host_url,
+ _tenant_id=example._tenant_id,
+ )
+
+ async def awith_predictions_and_evaluators(
+ self,
+ target: ATARGET_T,
+ evaluators: Sequence[Union[EVALUATOR_T, AEVALUATOR_T]],
+ /,
+ max_concurrency: Optional[int] = None,
+ ) -> _AsyncExperimentManager:
+ """Run predictions and evaluations in a single pipeline.
+
+ This allows evaluators to process results as soon as they're available from
+ the target function, rather than waiting for all predictions to complete first.
+ """
+ evaluators = _resolve_evaluators(evaluators)
+
+ if not hasattr(self, "_evaluation_feedback_executor"):
+ self._evaluation_feedback_executor = cf.ThreadPoolExecutor(max_workers=4)
+
+ traceable_target = _ensure_async_traceable(target)
+
+ async def process_example(example: schemas.Example):
+ # Yield the coroutine to be awaited later
+ pred = await _aforward(
+ traceable_target,
+ self._get_example_with_readers(example),
+ self.experiment_name,
+ self._metadata,
+ self.client,
+ _target_include_attachments(target),
+ self._error_handling,
+ )
+ example, run = pred["example"], pred["run"]
+ result = await self._arun_evaluators(
+ evaluators,
+ {
+ "run": run,
+ "example": example,
+ "evaluation_results": {"results": []},
+ },
+ feedback_executor=self._evaluation_feedback_executor,
+ )
+ return result
+
+ async def process_examples():
+ """Create a single task per example.
+
+ That task is to run the target function and all the evaluators
+ sequentially.
+ """
+ async for example in await self.aget_examples():
+ yield process_example(example)
+
+ await self._aend()
+
+ # Run the per-example tasks with max-concurrency
+ # This guarantees that max_concurrency is the upper limit
+ # for the number of target/evaluators that can be run in parallel
+ experiment_results = aitertools.aiter_with_concurrency(
+ max_concurrency,
+ process_examples(),
+ _eager_consumption_timeout=0.001,
+ )
+
+ r1, r2, r3 = aitertools.atee(experiment_results, 3, lock=asyncio.Lock())
+
+ return self._copy(
+ (result["example"] async for result in r1),
+ runs=(result["run"] async for result in r2),
+ evaluation_results=(result["evaluation_results"] async for result in r3),
+ )
+
+ async def awith_predictions(
+ self,
+ target: ATARGET_T,
+ /,
+ max_concurrency: Optional[int] = None,
+ ) -> _AsyncExperimentManager:
+ _experiment_results = self._apredict(
+ target,
+ max_concurrency=max_concurrency,
+ include_attachments=_target_include_attachments(target),
+ )
+ r1, r2 = aitertools.atee(_experiment_results, 2, lock=asyncio.Lock())
+ return self._copy(
+ (pred["example"] async for pred in r1),
+ runs=(pred["run"] async for pred in r2),
+ )
+
+ async def awith_evaluators(
+ self,
+ evaluators: Sequence[Union[EVALUATOR_T, AEVALUATOR_T]],
+ *,
+ max_concurrency: Optional[int] = None,
+ ) -> _AsyncExperimentManager:
+ evaluators = _resolve_evaluators(evaluators)
+ experiment_results = self._ascore(evaluators, max_concurrency=max_concurrency)
+ r1, r2, r3 = aitertools.atee(experiment_results, 3, lock=asyncio.Lock())
+ return self._copy(
+ (result["example"] async for result in r1),
+ runs=(result["run"] async for result in r2),
+ evaluation_results=(result["evaluation_results"] async for result in r3),
+ )
+
+ async def awith_summary_evaluators(
+ self,
+ summary_evaluators: Sequence[SUMMARY_EVALUATOR_T],
+ ) -> _AsyncExperimentManager:
+ wrapped_evaluators = _wrap_summary_evaluators(summary_evaluators)
+ aggregate_feedback_gen = self._aapply_summary_evaluators(wrapped_evaluators)
+ return self._copy(
+ await self.aget_examples(),
+ runs=self.aget_runs(),
+ summary_results=aggregate_feedback_gen,
+ )
+
+ async def aget_results(self) -> AsyncIterator[ExperimentResultRow]:
+ async for run, example, evaluation_results in aitertools.async_zip(
+ self.aget_runs(), await self.aget_examples(), self.aget_evaluation_results()
+ ):
+ yield ExperimentResultRow(
+ run=run,
+ example=example,
+ evaluation_results=evaluation_results,
+ )
+
+ async def aget_summary_scores(self) -> dict[str, list[dict]]:
+ if self._summary_results is None:
+ return {"results": []}
+ return {
+ "results": [
+ res # type: ignore[misc]
+ async for results in self._summary_results
+ for res in results["results"]
+ ]
+ }
+
+ ## Private methods
+
+ async def _apredict(
+ self,
+ target: ATARGET_T,
+ /,
+ max_concurrency: Optional[int] = None,
+ include_attachments: bool = False,
+ ) -> AsyncIterator[_ForwardResults]:
+ fn = _ensure_async_traceable(target)
+
+ async def predict_all():
+ async for example in await self.aget_examples():
+ # Yield the coroutine to be awaited later
+ yield _aforward(
+ fn,
+ self._get_example_with_readers(example),
+ self.experiment_name,
+ self._metadata,
+ self.client,
+ include_attachments,
+ self._error_handling,
+ )
+
+ async for result in aitertools.aiter_with_concurrency(
+ max_concurrency, predict_all(), _eager_consumption_timeout=0.001
+ ):
+ yield result
+
+ await self._aend()
+
+ async def _ascore(
+ self,
+ evaluators: Sequence[RunEvaluator],
+ max_concurrency: Optional[int] = None,
+ ) -> AsyncIterator[ExperimentResultRow]:
+ with cf.ThreadPoolExecutor(max_workers=4) as feedback_executor:
+
+ async def score_all():
+ async for current_results in self.aget_results():
+ # Yield the coroutine to be awaited later in aiter_with_concurrency
+ yield self._arun_evaluators(
+ evaluators, current_results, feedback_executor=feedback_executor
+ )
+
+ async for result in aitertools.aiter_with_concurrency(
+ max_concurrency, score_all(), _eager_consumption_timeout=0.001
+ ):
+ yield result
+
+ async def _arun_evaluators(
+ self,
+ evaluators: Sequence[RunEvaluator],
+ current_results: ExperimentResultRow,
+ feedback_executor: cf.ThreadPoolExecutor,
+ ) -> ExperimentResultRow:
+ current_context = rh.get_tracing_context()
+ metadata = {
+ **(current_context["metadata"] or {}),
+ **{"experiment": self.experiment_name},
+ }
+ with rh.tracing_context(
+ **{
+ **current_context,
+ "project_name": "evaluators",
+ "metadata": metadata,
+ "enabled": "local" if not self._upload_results else True,
+ "client": self.client,
+ }
+ ):
+ run = current_results["run"]
+ example = current_results["example"]
+ eval_results = current_results["evaluation_results"]
+
+ async def _run_single_evaluator(evaluator: RunEvaluator):
+ evaluator_run_id = uuid.uuid4()
+ try:
+ evaluator_response = await evaluator.aevaluate_run( # type: ignore[call-arg]
+ run=run,
+ example=self._get_example_with_readers(example),
+ evaluator_run_id=evaluator_run_id,
+ )
+ selected_results = self.client._select_eval_results(
+ evaluator_response
+ )
+
+ if self._upload_results:
+ self.client._log_evaluation_feedback(
+ evaluator_response, run=run, _executor=feedback_executor
+ )
+ return selected_results
+ except Exception as e:
+ try:
+ feedback_keys = _extract_feedback_keys(evaluator)
+
+ error_response = EvaluationResults(
+ results=[
+ EvaluationResult(
+ key=key,
+ source_run_id=evaluator_run_id,
+ comment=repr(e),
+ extra={"error": True},
+ )
+ for key in feedback_keys
+ ]
+ )
+ selected_results = self.client._select_eval_results(
+ error_response
+ )
+ if self._upload_results:
+ self.client._log_evaluation_feedback(
+ error_response, run=run, _executor=feedback_executor
+ )
+ return selected_results
+ except Exception as e2:
+ logger.debug(f"Error parsing feedback keys: {e2}")
+ pass
+ logger.error(
+ f"Error running evaluator {repr(evaluator)} on"
+ f" run {run.id}: {repr(e)}",
+ exc_info=True,
+ )
+
+ all_results = []
+ for evaluator in evaluators:
+ all_results.append(await _run_single_evaluator(evaluator))
+
+ for result in all_results:
+ if result is not None:
+ eval_results["results"].extend(result)
+ return ExperimentResultRow(
+ run=run,
+ example=example,
+ evaluation_results=eval_results,
+ )
+
+ async def _aapply_summary_evaluators(
+ self, summary_evaluators: Sequence[SUMMARY_EVALUATOR_T]
+ ) -> AsyncIterator[EvaluationResults]:
+ runs, examples = [], []
+ async_examples = aitertools.ensure_async_iterator(await self.aget_examples())
+ async for run, example in aitertools.async_zip(
+ self.aget_runs(), async_examples
+ ):
+ runs.append(run)
+ examples.append(example)
+ aggregate_feedback = []
+ project_id = self._get_experiment().id if self._upload_results else None
+ current_context = rh.get_tracing_context()
+ metadata = {
+ **(current_context["metadata"] or {}),
+ **{
+ "experiment": self.experiment_name,
+ "experiment_id": project_id,
+ },
+ }
+ with rh.tracing_context(
+ **{
+ **current_context,
+ "project_name": "evaluators",
+ "metadata": metadata,
+ "enabled": "local" if not self._upload_results else True,
+ "client": self.client,
+ }
+ ):
+ for evaluator in summary_evaluators:
+ try:
+ summary_eval_result = evaluator(runs, examples)
+ flattened_results = self.client._select_eval_results(
+ summary_eval_result,
+ fn_name=evaluator.__name__,
+ )
+ aggregate_feedback.extend(flattened_results)
+ if self._upload_results:
+ for result in flattened_results:
+ feedback = result.model_dump(exclude={"target_run_id"})
+ evaluator_info = feedback.pop("evaluator_info", None)
+ await aitertools.aio_to_thread(
+ contextvars.copy_context(),
+ self.client.create_feedback,
+ **feedback,
+ run_id=None,
+ project_id=project_id,
+ source_info=evaluator_info,
+ )
+ except Exception as e:
+ logger.error(
+ f"Error running summary evaluator {repr(evaluator)}: {e}",
+ exc_info=True,
+ )
+ yield {"results": aggregate_feedback}
+
+ async def _get_dataset_version(self) -> Optional[str]:
+ modified_at = []
+ async for example in await self.aget_examples():
+ if example.modified_at:
+ # Should always be defined in practice when fetched,
+ # but the typing permits None
+ modified_at.append(example.modified_at)
+
+ max_modified_at = max(modified_at) if modified_at else None
+ return max_modified_at.isoformat() if max_modified_at else None
+
+ async def _get_dataset_splits(self) -> Optional[list[str]]:
+ splits = set()
+ async for example in await self.aget_examples():
+ if (
+ example.metadata
+ and example.metadata.get("dataset_split")
+ and isinstance(example.metadata["dataset_split"], list)
+ ):
+ for split in example.metadata["dataset_split"]:
+ if isinstance(split, str):
+ splits.add(split)
+ else:
+ splits.add("base")
+
+ return list(splits)
+
+ async def _aend(self) -> None:
+ if not self._upload_results:
+ return
+ experiment = self._experiment
+ if experiment is None:
+ raise ValueError("Experiment not started yet.")
+
+ project_metadata = self._get_experiment_metadata()
+ project_metadata["dataset_version"] = await self._get_dataset_version()
+ project_metadata["dataset_splits"] = await self._get_dataset_splits()
+ self.client.update_project(
+ experiment.id,
+ metadata={
+ **experiment.metadata,
+ **project_metadata,
+ },
+ )
+
+ def _copy(self, *args: Any, **kwargs: Any) -> _AsyncExperimentManager:
+ default_args = (self._data,)
+ default_kwargs = {
+ "experiment": self._experiment,
+ "metadata": self._metadata,
+ "runs": self._runs,
+ "client": self.client,
+ "evaluation_results": self._evaluation_results,
+ "summary_results": self._summary_results,
+ "include_attachments": self._include_attachments,
+ "reuse_attachments": self._reuse_attachments,
+ "upload_results": self._upload_results,
+ "attachment_raw_data_dict": self._attachment_raw_data_dict,
+ "error_handling": self._error_handling,
+ }
+ full_args = list(args) + list(default_args[len(args) :])
+ full_kwargs = {**default_kwargs, **kwargs}
+ return self.__class__(*full_args, **full_kwargs)
+
+
+class AsyncExperimentResults:
+ def __init__(
+ self,
+ experiment_manager: _AsyncExperimentManager,
+ ):
+ self._manager = experiment_manager
+ self._results: list[ExperimentResultRow] = []
+ self._condition = asyncio.Condition()
+ self._task = asyncio.create_task(self._process_data(self._manager))
+ self._processed_count = 0
+ self._comparison_url: Optional[str] = None
+
+ @property
+ def experiment_name(self) -> str:
+ return self._manager.experiment_name
+
+ @property
+ def experiment_id(self) -> uuid.UUID:
+ """The ID of the experiment."""
+ return self._manager._get_experiment().id
+
+ @property
+ def url(self) -> Optional[str]:
+ """The URL of the experiment in the LangSmith UI."""
+ return self._manager._get_experiment().url
+
+ async def get_dataset_id(self) -> str:
+ """Get the ID of the dataset associated with this experiment."""
+ return await self._manager.get_dataset_id()
+
+ async def get_comparison_url(self) -> Optional[str]:
+ """Get the URL to the comparison view for this experiment."""
+ experiment = self._manager._get_experiment()
+ if not self._comparison_url and experiment.url:
+ dataset_id = await self._manager.get_dataset_id()
+ project_url = experiment.url.split("?")[0]
+ base_url = project_url.split("/projects/p/")[0]
+ self._comparison_url = (
+ f"{base_url}/datasets/{dataset_id}/compare?"
+ f"selectedSessions={experiment.id}"
+ )
+ return self._comparison_url
+
+ def __aiter__(self) -> AsyncIterator[ExperimentResultRow]:
+ return self
+
+ async def __anext__(self) -> ExperimentResultRow:
+ async with self._condition:
+ while True:
+ if self._processed_count < len(self._results):
+ result = self._results[self._processed_count]
+ self._processed_count += 1
+ return result
+ elif self._task.done():
+ exc = self._task.exception()
+ if exc is not None:
+ raise exc
+ raise StopAsyncIteration
+ await self._condition.wait()
+
+ async def _process_data(self, manager: _AsyncExperimentManager) -> None:
+ tqdm = _load_tqdm()
+ async for item in tqdm(manager.aget_results()):
+ async with self._condition:
+ self._results.append(item)
+ self._condition.notify()
+ summary_scores = await manager.aget_summary_scores()
+ async with self._condition:
+ self._summary_results = summary_scores
+ self._condition.notify_all()
+
+ def to_pandas(
+ self, start: Optional[int] = 0, end: Optional[int] = None
+ ) -> DataFrame:
+ return _to_pandas(self._results, start=start, end=end)
+
+ def _repr_html_(self) -> str:
+ import importlib.util
+
+ if self._results and importlib.util.find_spec("pandas"):
+ df = self.to_pandas(0, 5)
+ return df._repr_html_() # type: ignore[operator]
+ else:
+ return self.__repr__()
+
+ def __len__(self) -> int:
+ return len(self._results)
+
+ def __repr__(self) -> str:
+ return f""
+
+ async def wait(self) -> None:
+ await self._task
+
+
+async def _aforward(
+ fn: rh.SupportsLangsmithExtra[[dict], Awaitable],
+ example: schemas.Example,
+ experiment_name: str,
+ metadata: dict,
+ client: langsmith.Client,
+ include_attachments: bool = False,
+ error_handling: Literal["log", "ignore"] = "log",
+) -> _ForwardResults:
+ run: Optional[schemas.RunBase] = None
+
+ def _get_run(r: run_trees.RunTree) -> None:
+ nonlocal run
+ run = r
+
+ def _set_reference_example_id(r: rt.RunTree) -> None:
+ r.reference_example_id = example.id
+
+ langsmith_extra = rh.LangSmithExtra(
+ on_end=_get_run,
+ project_name=experiment_name,
+ metadata={
+ **metadata,
+ "example_version": (example.modified_at or example.created_at).isoformat(),
+ },
+ client=client,
+ )
+ if error_handling == "log":
+ langsmith_extra["reference_example_id"] = example.id
+ elif error_handling == "ignore":
+ langsmith_extra["_on_success"] = _set_reference_example_id
+ else:
+ raise ValueError(f"Unrecognized error_handling value: {error_handling=}")
+
+ with rh.tracing_context(enabled=True):
+ try:
+ arg_names = _get_target_args(fn)
+ args = [getattr(example, argn) for argn in arg_names]
+ await fn(*args, langsmith_extra=langsmith_extra)
+ except Exception as e:
+ logger.error(
+ f"Error running target function: {e}", exc_info=True, stacklevel=1
+ )
+ return _ForwardResults(
+ run=cast(schemas.Run, run),
+ example=example,
+ )
+
+
+def _default_process_inputs(inputs: dict) -> dict:
+ return inputs["inputs"] if "inputs" in inputs else inputs
+
+
+def _ensure_async_traceable(
+ target: ATARGET_T,
+) -> rh.SupportsLangsmithExtra[[dict], Awaitable]:
+ if not asyncio.iscoroutinefunction(target) and not _is_langchain_runnable(target):
+ if callable(target):
+ raise ValueError(
+ "Target must be an async function. For sync functions, use evaluate."
+ " Example usage:\n\n"
+ "async def predict(inputs: dict) -> dict:\n"
+ " # do work, like chain.invoke(inputs)\n"
+ " return {...}\n"
+ "await aevaluate(predict, ...)"
+ )
+ else:
+ raise ValueError(
+ "Target must be a callable async function. "
+ "Received a non-callable object. Example usage:\n\n"
+ "async def predict(inputs: dict) -> dict:\n"
+ " # do work, like chain.invoke(inputs)\n"
+ " return {...}\n"
+ "await aevaluate(predict, ...)"
+ )
+ if rh.is_traceable_function(target):
+ return target # type: ignore
+ else:
+ if _is_langchain_runnable(target):
+ target = target.ainvoke # type: ignore[union-attr]
+ return rh.traceable(
+ name="AsyncTarget",
+ process_inputs=_default_process_inputs,
+ )(target) # type: ignore[arg-type]
+
+
+def _aresolve_data(
+ data: Union[DATA_T, AsyncIterable[schemas.Example]],
+ *,
+ client: langsmith.Client,
+ include_attachments: bool = False,
+) -> AsyncIterator[schemas.Example]:
+ """Return the examples for the given dataset."""
+ if isinstance(data, AsyncIterable):
+ return aitertools.ensure_async_iterator(data)
+ return aitertools.ensure_async_iterator(
+ _resolve_data(data, client=client, include_attachments=include_attachments)
+ )
+
+
+T = TypeVar("T")
+
+
+async def async_chain_from_iterable(
+ iterable: Iterable[AsyncIterable[T]],
+) -> AsyncIterator[T]:
+ """Chain multiple async iterables."""
+ for sub_iterable in iterable:
+ async for item in sub_iterable:
+ yield item
+
+
+async def async_iter_from_list(
+ examples: list[schemas.Example],
+) -> AsyncIterable[schemas.Example]:
+ """Convert a list of examples to an async iterable."""
+ for example in examples:
+ yield example
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/_name_generation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/_name_generation.py
new file mode 100644
index 0000000000000000000000000000000000000000..191c74632fef95b02c05acb639b13eabc39c6648
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/_name_generation.py
@@ -0,0 +1,727 @@
+import random
+
+adjectives = [
+ "abandoned",
+ "aching",
+ "advanced",
+ "ample",
+ "artistic",
+ "back",
+ "best",
+ "bold",
+ "brief",
+ "clear",
+ "cold",
+ "complicated",
+ "cooked",
+ "crazy",
+ "crushing",
+ "damp",
+ "dear",
+ "definite",
+ "dependable",
+ "diligent",
+ "drab",
+ "earnest",
+ "elderly",
+ "enchanted",
+ "essential",
+ "excellent",
+ "extraneous",
+ "fixed",
+ "flowery",
+ "formal",
+ "fresh",
+ "frosty",
+ "giving",
+ "glossy",
+ "healthy",
+ "helpful",
+ "impressionable",
+ "kind",
+ "large",
+ "left",
+ "long",
+ "loyal",
+ "mealy",
+ "memorable",
+ "monthly",
+ "new",
+ "notable",
+ "only",
+ "ordinary",
+ "passionate",
+ "perfect",
+ "pertinent",
+ "proper",
+ "puzzled",
+ "reflecting",
+ "respectful",
+ "roasted",
+ "scholarly",
+ "shiny",
+ "slight",
+ "sparkling",
+ "spotless",
+ "stupendous",
+ "sunny",
+ "tart",
+ "terrific",
+ "timely",
+ "unique",
+ "upbeat",
+ "vacant",
+ "virtual",
+ "warm",
+ "weary",
+ "whispered",
+ "worthwhile",
+ "yellow",
+]
+
+nouns = [
+ "account",
+ "acknowledgment",
+ "address",
+ "advertising",
+ "airplane",
+ "animal",
+ "appointment",
+ "arrival",
+ "artist",
+ "attachment",
+ "attitude",
+ "availability",
+ "backpack",
+ "bag",
+ "balance",
+ "bass",
+ "bean",
+ "beauty",
+ "bibliography",
+ "bill",
+ "bite",
+ "blossom",
+ "boat",
+ "book",
+ "box",
+ "boy",
+ "bread",
+ "bridge",
+ "broccoli",
+ "building",
+ "butter",
+ "button",
+ "cabbage",
+ "cake",
+ "camera",
+ "camp",
+ "candle",
+ "candy",
+ "canvas",
+ "car",
+ "card",
+ "carrot",
+ "cart",
+ "case",
+ "cat",
+ "chain",
+ "chair",
+ "chalk",
+ "chance",
+ "change",
+ "channel",
+ "character",
+ "charge",
+ "charm",
+ "chart",
+ "check",
+ "cheek",
+ "cheese",
+ "chef",
+ "cherry",
+ "chicken",
+ "child",
+ "church",
+ "circle",
+ "class",
+ "clay",
+ "click",
+ "clock",
+ "cloth",
+ "cloud",
+ "clove",
+ "club",
+ "coach",
+ "coal",
+ "coast",
+ "coat",
+ "cod",
+ "coffee",
+ "collar",
+ "color",
+ "comb",
+ "comfort",
+ "comic",
+ "committee",
+ "community",
+ "company",
+ "comparison",
+ "competition",
+ "condition",
+ "connection",
+ "control",
+ "cook",
+ "copper",
+ "copy",
+ "corn",
+ "cough",
+ "country",
+ "cover",
+ "crate",
+ "crayon",
+ "cream",
+ "creator",
+ "crew",
+ "crown",
+ "current",
+ "curtain",
+ "curve",
+ "cushion",
+ "dad",
+ "daughter",
+ "day",
+ "death",
+ "debt",
+ "decision",
+ "deer",
+ "degree",
+ "design",
+ "desire",
+ "desk",
+ "detail",
+ "development",
+ "digestion",
+ "dime",
+ "dinner",
+ "direction",
+ "dirt",
+ "discovery",
+ "discussion",
+ "disease",
+ "disgust",
+ "distance",
+ "distribution",
+ "division",
+ "doctor",
+ "dog",
+ "door",
+ "drain",
+ "drawer",
+ "dress",
+ "drink",
+ "driving",
+ "dust",
+ "ear",
+ "earth",
+ "edge",
+ "education",
+ "effect",
+ "egg",
+ "end",
+ "energy",
+ "engine",
+ "error",
+ "event",
+ "example",
+ "exchange",
+ "existence",
+ "expansion",
+ "experience",
+ "expert",
+ "eye",
+ "face",
+ "fact",
+ "fall",
+ "family",
+ "farm",
+ "father",
+ "fear",
+ "feeling",
+ "field",
+ "finger",
+ "fire",
+ "fish",
+ "flag",
+ "flight",
+ "floor",
+ "flower",
+ "fold",
+ "food",
+ "football",
+ "force",
+ "form",
+ "frame",
+ "friend",
+ "frog",
+ "fruit",
+ "fuel",
+ "furniture",
+ "game",
+ "garden",
+ "gate",
+ "girl",
+ "glass",
+ "glove",
+ "goat",
+ "gold",
+ "government",
+ "grade",
+ "grain",
+ "grass",
+ "green",
+ "grip",
+ "group",
+ "growth",
+ "guide",
+ "guitar",
+ "hair",
+ "hall",
+ "hand",
+ "harbor",
+ "harmony",
+ "hat",
+ "head",
+ "health",
+ "heart",
+ "heat",
+ "hill",
+ "history",
+ "hobbies",
+ "hole",
+ "hope",
+ "horn",
+ "horse",
+ "hospital",
+ "hour",
+ "house",
+ "humor",
+ "idea",
+ "impulse",
+ "income",
+ "increase",
+ "industry",
+ "ink",
+ "insect",
+ "instrument",
+ "insurance",
+ "interest",
+ "invention",
+ "iron",
+ "island",
+ "jelly",
+ "jet",
+ "jewel",
+ "join",
+ "judge",
+ "juice",
+ "jump",
+ "kettle",
+ "key",
+ "kick",
+ "kiss",
+ "kitten",
+ "knee",
+ "knife",
+ "knowledge",
+ "land",
+ "language",
+ "laugh",
+ "law",
+ "lead",
+ "learning",
+ "leather",
+ "leg",
+ "lettuce",
+ "level",
+ "library",
+ "lift",
+ "light",
+ "limit",
+ "line",
+ "linen",
+ "lip",
+ "liquid",
+ "list",
+ "look",
+ "loss",
+ "love",
+ "lunch",
+ "machine",
+ "man",
+ "manager",
+ "map",
+ "marble",
+ "mark",
+ "market",
+ "mass",
+ "match",
+ "meal",
+ "measure",
+ "meat",
+ "meeting",
+ "memory",
+ "metal",
+ "middle",
+ "milk",
+ "mind",
+ "mine",
+ "minute",
+ "mist",
+ "mitten",
+ "mom",
+ "money",
+ "monkey",
+ "month",
+ "moon",
+ "morning",
+ "mother",
+ "motion",
+ "mountain",
+ "mouth",
+ "muscle",
+ "music",
+ "nail",
+ "name",
+ "nation",
+ "neck",
+ "need",
+ "news",
+ "night",
+ "noise",
+ "note",
+ "number",
+ "nut",
+ "observation",
+ "offer",
+ "oil",
+ "operation",
+ "opinion",
+ "orange",
+ "order",
+ "organization",
+ "ornament",
+ "oven",
+ "page",
+ "pail",
+ "pain",
+ "paint",
+ "pan",
+ "pancake",
+ "paper",
+ "parcel",
+ "parent",
+ "part",
+ "passenger",
+ "paste",
+ "payment",
+ "peace",
+ "pear",
+ "pen",
+ "pencil",
+ "person",
+ "pest",
+ "pet",
+ "picture",
+ "pie",
+ "pin",
+ "pipe",
+ "pizza",
+ "place",
+ "plane",
+ "plant",
+ "plastic",
+ "plate",
+ "play",
+ "pleasure",
+ "plot",
+ "plough",
+ "pocket",
+ "point",
+ "poison",
+ "police",
+ "pollution",
+ "popcorn",
+ "porter",
+ "position",
+ "pot",
+ "potato",
+ "powder",
+ "power",
+ "price",
+ "print",
+ "process",
+ "produce",
+ "product",
+ "profit",
+ "property",
+ "prose",
+ "protest",
+ "pull",
+ "pump",
+ "punishment",
+ "purpose",
+ "push",
+ "quarter",
+ "question",
+ "quiet",
+ "quill",
+ "quilt",
+ "quince",
+ "rabbit",
+ "rail",
+ "rain",
+ "range",
+ "rat",
+ "rate",
+ "ray",
+ "reaction",
+ "reading",
+ "reason",
+ "record",
+ "regret",
+ "relation",
+ "religion",
+ "representative",
+ "request",
+ "respect",
+ "rest",
+ "reward",
+ "rhythm",
+ "rice",
+ "river",
+ "road",
+ "roll",
+ "room",
+ "root",
+ "rose",
+ "route",
+ "rub",
+ "rule",
+ "run",
+ "sack",
+ "sail",
+ "salt",
+ "sand",
+ "scale",
+ "scarecrow",
+ "scarf",
+ "scene",
+ "scent",
+ "school",
+ "science",
+ "scissors",
+ "screw",
+ "sea",
+ "seat",
+ "secretary",
+ "seed",
+ "selection",
+ "self",
+ "sense",
+ "servant",
+ "shade",
+ "shake",
+ "shame",
+ "shape",
+ "sheep",
+ "sheet",
+ "shelf",
+ "ship",
+ "shirt",
+ "shock",
+ "shoe",
+ "shop",
+ "show",
+ "side",
+ "sign",
+ "silk",
+ "sink",
+ "sister",
+ "size",
+ "sky",
+ "sleep",
+ "smash",
+ "smell",
+ "smile",
+ "smoke",
+ "snail",
+ "snake",
+ "sneeze",
+ "snow",
+ "soap",
+ "society",
+ "sock",
+ "soda",
+ "sofa",
+ "son",
+ "song",
+ "sort",
+ "sound",
+ "soup",
+ "space",
+ "spark",
+ "speed",
+ "sponge",
+ "spoon",
+ "spray",
+ "spring",
+ "spy",
+ "square",
+ "stamp",
+ "star",
+ "start",
+ "statement",
+ "station",
+ "steam",
+ "steel",
+ "stem",
+ "step",
+ "stew",
+ "stick",
+ "stitch",
+ "stocking",
+ "stomach",
+ "stone",
+ "stop",
+ "store",
+ "story",
+ "stove",
+ "stranger",
+ "straw",
+ "stream",
+ "street",
+ "stretch",
+ "string",
+ "structure",
+ "substance",
+ "sugar",
+ "suggestion",
+ "suit",
+ "summer",
+ "sun",
+ "support",
+ "surprise",
+ "sweater",
+ "swim",
+ "system",
+ "table",
+ "tail",
+ "talk",
+ "tank",
+ "taste",
+ "tax",
+ "tea",
+ "teaching",
+ "team",
+ "tendency",
+ "test",
+ "texture",
+ "theory",
+ "thing",
+ "thought",
+ "thread",
+ "throat",
+ "thumb",
+ "thunder",
+ "ticket",
+ "time",
+ "tin",
+ "title",
+ "toad",
+ "toe",
+ "tooth",
+ "toothpaste",
+ "touch",
+ "town",
+ "toy",
+ "trade",
+ "train",
+ "transport",
+ "tray",
+ "treatment",
+ "tree",
+ "trick",
+ "trip",
+ "trouble",
+ "trousers",
+ "truck",
+ "tub",
+ "turkey",
+ "turn",
+ "twist",
+ "umbrella",
+ "uncle",
+ "underwear",
+ "unit",
+ "use",
+ "vacation",
+ "value",
+ "van",
+ "vase",
+ "vegetable",
+ "veil",
+ "vein",
+ "verse",
+ "vessel",
+ "view",
+ "visitor",
+ "voice",
+ "volcano",
+ "walk",
+ "wall",
+ "war",
+ "wash",
+ "waste",
+ "watch",
+ "water",
+ "wave",
+ "wax",
+ "way",
+ "wealth",
+ "weather",
+ "week",
+ "weight",
+ "wheel",
+ "whip",
+ "whistle",
+ "window",
+ "wine",
+ "wing",
+ "winter",
+ "wire",
+ "wish",
+ "woman",
+ "wood",
+ "wool",
+ "word",
+ "work",
+ "worm",
+ "wound",
+ "wrist",
+ "writer",
+ "yard",
+ "yoke",
+ "zebra",
+ "zinc",
+ "zipper",
+ "zone",
+]
+
+
+def random_name() -> str:
+ """Generate a random name."""
+ adjective = random.choice(adjectives)
+ noun = random.choice(nouns)
+ number = random.randint(1, 100)
+ return f"{adjective}-{noun}-{number}"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/_runner.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/_runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5c6e8a5cf4f9d09c46e6b9c86a051d98de9b485
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/_runner.py
@@ -0,0 +1,2314 @@
+"""V2 Evaluation Interface."""
+
+from __future__ import annotations
+
+import ast
+import collections
+import concurrent.futures as cf
+import functools
+import inspect
+import io
+import itertools
+import logging
+import pathlib
+import queue
+import random
+import textwrap
+import threading
+import uuid
+from collections.abc import Awaitable, Generator, Iterable, Iterator, Sequence
+from contextvars import copy_context
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Literal,
+ Optional,
+ TypeVar,
+ Union,
+ cast,
+)
+
+from typing_extensions import TypedDict, overload
+
+import langsmith
+from langsmith import env as ls_env
+from langsmith import run_helpers as rh
+from langsmith import run_trees as rt
+from langsmith import schemas
+from langsmith import utils as ls_utils
+from langsmith._internal._beta_decorator import _warn_once
+from langsmith.evaluation.evaluator import (
+ SUMMARY_EVALUATOR_T,
+ ComparisonEvaluationResult,
+ DynamicComparisonRunEvaluator,
+ DynamicRunEvaluator,
+ EvaluationResult,
+ EvaluationResults,
+ RunEvaluator,
+ _normalize_summary_evaluator,
+ comparison_evaluator,
+ run_evaluator,
+)
+
+# Python 3.14+ removes ast.Str in favor of ast.Constant
+_AST_STR_TYPES: tuple = (
+ (ast.Str, ast.Constant) if hasattr(ast, "Str") else (ast.Constant,)
+)
+
+
+def _get_str_value(node: ast.expr) -> str:
+ """Get string value from ast.Str or ast.Constant."""
+ return node.value if isinstance(node, ast.Constant) else node.s # type: ignore[return-value,union-attr,attr-defined]
+
+
+if TYPE_CHECKING:
+ import pandas as pd
+ from langchain_core.runnables import Runnable
+
+ DataFrame = pd.DataFrame
+else:
+ DataFrame = Any
+logger = logging.getLogger(__name__)
+
+TARGET_T = Union[Callable[[dict], dict], Callable[[dict, dict], dict]]
+# Data format: dataset-name, dataset_id, or examples
+DATA_T = Union[str, uuid.UUID, Iterable[schemas.Example], schemas.Dataset]
+# Summary evaluator runs over the whole dataset
+# and reports aggregate metric(s)
+# Row-level evaluator
+EVALUATOR_T = Union[
+ RunEvaluator,
+ Callable[
+ [schemas.Run, Optional[schemas.Example]],
+ Union[EvaluationResult, EvaluationResults],
+ ],
+ Callable[..., Union[dict, EvaluationResults, EvaluationResult]],
+]
+AEVALUATOR_T = Union[
+ Callable[
+ [schemas.Run, Optional[schemas.Example]],
+ Awaitable[Union[EvaluationResult, EvaluationResults]],
+ ],
+]
+EXPERIMENT_T = Union[str, uuid.UUID, schemas.TracerSession]
+
+
+@overload
+def evaluate(
+ target: Union[TARGET_T, Runnable, EXPERIMENT_T],
+ /,
+ data: Optional[DATA_T] = None,
+ evaluators: Optional[Sequence[EVALUATOR_T]] = None,
+ summary_evaluators: Optional[Sequence[SUMMARY_EVALUATOR_T]] = None,
+ metadata: Optional[dict] = None,
+ experiment_prefix: Optional[str] = None,
+ description: Optional[str] = None,
+ max_concurrency: Optional[int] = 0,
+ num_repetitions: int = 1,
+ client: Optional[langsmith.Client] = None,
+ blocking: bool = True,
+ experiment: Optional[EXPERIMENT_T] = None,
+ upload_results: bool = True,
+ **kwargs: Any,
+) -> ExperimentResults: ...
+
+
+@overload
+def evaluate(
+ target: Union[tuple[EXPERIMENT_T, EXPERIMENT_T]],
+ /,
+ data: Optional[DATA_T] = None,
+ evaluators: Optional[Sequence[COMPARATIVE_EVALUATOR_T]] = None,
+ summary_evaluators: Optional[Sequence[SUMMARY_EVALUATOR_T]] = None,
+ metadata: Optional[dict] = None,
+ experiment_prefix: Optional[str] = None,
+ description: Optional[str] = None,
+ max_concurrency: Optional[int] = 0,
+ num_repetitions: int = 1,
+ client: Optional[langsmith.Client] = None,
+ blocking: bool = True,
+ experiment: Optional[EXPERIMENT_T] = None,
+ upload_results: bool = True,
+ **kwargs: Any,
+) -> ComparativeExperimentResults: ...
+
+
+def evaluate(
+ target: Union[TARGET_T, Runnable, EXPERIMENT_T, tuple[EXPERIMENT_T, EXPERIMENT_T]],
+ /,
+ data: Optional[DATA_T] = None,
+ evaluators: Optional[
+ Union[Sequence[EVALUATOR_T], Sequence[COMPARATIVE_EVALUATOR_T]]
+ ] = None,
+ summary_evaluators: Optional[Sequence[SUMMARY_EVALUATOR_T]] = None,
+ metadata: Optional[dict] = None,
+ experiment_prefix: Optional[str] = None,
+ description: Optional[str] = None,
+ max_concurrency: Optional[int] = 0,
+ num_repetitions: int = 1,
+ client: Optional[langsmith.Client] = None,
+ blocking: bool = True,
+ experiment: Optional[EXPERIMENT_T] = None,
+ upload_results: bool = True,
+ error_handling: Literal["log", "ignore"] = "log",
+ **kwargs: Any,
+) -> Union[ExperimentResults, ComparativeExperimentResults]:
+ r"""Evaluate a target system on a given dataset.
+
+ Args:
+ target (TARGET_T | Runnable | EXPERIMENT_T | Tuple[EXPERIMENT_T, EXPERIMENT_T]):
+ The target system or experiment(s) to evaluate.
+
+ Can be a function that takes a dict and returns a `dict`, a langchain `Runnable`, an
+ existing experiment ID, or a two-tuple of experiment IDs.
+ data (DATA_T): The dataset to evaluate on.
+
+ Can be a dataset name, a list of examples, or a generator of examples.
+ evaluators (Sequence[EVALUATOR_T] | Sequence[COMPARATIVE_EVALUATOR_T] | None):
+ A list of evaluators to run on each example. The evaluator signature
+ depends on the target type.
+ summary_evaluators (Sequence[SUMMARY_EVALUATOR_T] | None): A list of summary
+ evaluators to run on the entire dataset.
+
+ Should not be specified if comparing two existing experiments.
+ metadata (dict | None): Metadata to attach to the experiment.
+ experiment_prefix (str | None): A prefix to provide for your experiment name.
+ description (str | None): A free-form text description for the experiment.
+ max_concurrency (int | None): The maximum number of concurrent
+ evaluations to run.
+
+ If `None` then no limit is set. If `0` then no concurrency.
+ client (langsmith.Client | None): The LangSmith client to use.
+ blocking (bool): Whether to block until the evaluation is complete.
+ num_repetitions (int): The number of times to run the evaluation.
+ Each item in the dataset will be run and evaluated this many times.
+ experiment (schemas.TracerSession | None): An existing experiment to
+ extend.
+
+ If provided, `experiment_prefix` is ignored.
+
+ For advanced usage only. Should not be specified if target is an existing
+ experiment or two-tuple fo experiments.
+ error_handling (str, default="log"): How to handle individual run errors.
+
+ `'log'` will trace the runs with the error message as part of the
+ experiment, `'ignore'` will not count the run as part of the experiment at
+ all.
+
+ Returns:
+ ExperimentResults: If target is a function, `Runnable`, or existing experiment.
+ ComparativeExperimentResults: If target is a two-tuple of existing experiments.
+
+ Examples:
+ Prepare the dataset:
+
+ >>> from typing import Sequence
+ >>> from langsmith import Client
+ >>> from langsmith.evaluation import evaluate
+ >>> from langsmith.schemas import Example, Run
+ >>> client = Client()
+ >>> dataset = client.clone_public_dataset(
+ ... "https://smith.langchain.com/public/419dcab2-1d66-4b94-8901-0357ead390df/d"
+ ... )
+ >>> dataset_name = "Evaluate Examples"
+
+ Basic usage:
+
+ >>> def accuracy(run: Run, example: Example):
+ ... # Row-level evaluator for accuracy.
+ ... pred = run.outputs["output"]
+ ... expected = example.outputs["answer"]
+ ... return {"score": expected.lower() == pred.lower()}
+ >>> def precision(runs: Sequence[Run], examples: Sequence[Example]):
+ ... # Experiment-level evaluator for precision.
+ ... # TP / (TP + FP)
+ ... predictions = [run.outputs["output"].lower() for run in runs]
+ ... expected = [example.outputs["answer"].lower() for example in examples]
+ ... # yes and no are the only possible answers
+ ... tp = sum([p == e for p, e in zip(predictions, expected) if p == "yes"])
+ ... fp = sum([p == "yes" and e == "no" for p, e in zip(predictions, expected)])
+ ... return {"score": tp / (tp + fp)}
+ >>> def predict(inputs: dict) -> dict:
+ ... # This can be any function or just an API call to your app.
+ ... return {"output": "Yes"}
+ >>> results = evaluate(
+ ... predict,
+ ... data=dataset_name,
+ ... evaluators=[accuracy],
+ ... summary_evaluators=[precision],
+ ... experiment_prefix="My Experiment",
+ ... description="Evaluating the accuracy of a simple prediction model.",
+ ... metadata={
+ ... "my-prompt-version": "abcd-1234",
+ ... },
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+
+ Evaluating over only a subset of the examples
+
+ >>> experiment_name = results.experiment_name
+ >>> examples = client.list_examples(dataset_name=dataset_name, limit=5)
+ >>> results = evaluate(
+ ... predict,
+ ... data=examples,
+ ... evaluators=[accuracy],
+ ... summary_evaluators=[precision],
+ ... experiment_prefix="My Experiment",
+ ... description="Just testing a subset synchronously.",
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+
+ Streaming each prediction to more easily + eagerly debug.
+
+ >>> results = evaluate(
+ ... predict,
+ ... data=dataset_name,
+ ... evaluators=[accuracy],
+ ... summary_evaluators=[precision],
+ ... description="I don't even have to block!",
+ ... blocking=False,
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+ >>> for i, result in enumerate(results): # doctest: +ELLIPSIS
+ ... pass
+
+
+
+ Evaluating a LangChain object:
+
+ >>> from langchain_core.runnables import chain as as_runnable
+ >>> @as_runnable
+ ... def nested_predict(inputs):
+ ... return {"output": "Yes"}
+ >>> @as_runnable
+ ... def lc_predict(inputs):
+ ... return nested_predict.invoke(inputs)
+ >>> results = evaluate(
+ ... lc_predict.invoke,
+ ... data=dataset_name,
+ ... evaluators=[accuracy],
+ ... description="This time we're evaluating a LangChain object.",
+ ... summary_evaluators=[precision],
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+
+ !!! warning "Behavior changed in `langsmith` 0.2.0"
+
+ 'max_concurrency' default updated from None (no limit on concurrency)
+ to 0 (no concurrency at all).
+ """ # noqa: E501
+ if isinstance(target, (str, uuid.UUID, schemas.TracerSession)):
+ invalid_args = {
+ "num_repetitions": num_repetitions > 1,
+ "experiment": bool(experiment),
+ "upload_results": not upload_results,
+ "experiment_prefix": bool(experiment_prefix),
+ "data": bool(data),
+ }
+ if any(invalid_args.values()):
+ msg = (
+ f"Received invalid arguments. "
+ f"{tuple(k for k, v in invalid_args.items() if v)} should not be "
+ f"specified when target is an existing experiment."
+ )
+ raise ValueError(msg)
+ target_id = target if isinstance(target, (str, uuid.UUID)) else target.id
+ logger.debug(f"Running evaluation over existing experiment {target_id}...")
+ return evaluate_existing(
+ target,
+ evaluators=cast(Optional[Sequence[EVALUATOR_T]], evaluators),
+ summary_evaluators=summary_evaluators,
+ metadata=metadata,
+ max_concurrency=max_concurrency,
+ client=client,
+ blocking=blocking,
+ **kwargs,
+ )
+ elif isinstance(target, (list, tuple)):
+ invalid_args = {
+ "num_repetitions": num_repetitions > 1,
+ "experiment": bool(experiment),
+ "upload_results": not upload_results,
+ "summary_evaluators": bool(summary_evaluators),
+ "data": bool(data),
+ }
+ if len(target) != 2 or not all(
+ isinstance(t, (str, uuid.UUID, schemas.TracerSession)) for t in target
+ ):
+ msg = (
+ "Received invalid target. If a tuple is specified it must have length "
+ "2 and each element should by the ID or schemas.TracerSession of an "
+ f"existing experiment. Received {target=}"
+ )
+ raise ValueError(msg)
+ elif any(invalid_args.values()):
+ msg = (
+ f"Received invalid arguments. "
+ f"{tuple(k for k, v in invalid_args.items() if v)} should not be "
+ f"specified when target is two existing experiments."
+ )
+ raise ValueError(msg)
+ if max_concurrency is not None:
+ kwargs["max_concurrency"] = max_concurrency
+ target_ids = [t if isinstance(t, (str, uuid.UUID)) else t.id for t in target]
+ logger.debug(
+ f"Running pairwise evaluation over existing experiments {target_ids}..."
+ )
+ return evaluate_comparative(
+ target,
+ evaluators=cast(Sequence[COMPARATIVE_EVALUATOR_T], evaluators or ()),
+ experiment_prefix=experiment_prefix,
+ description=description,
+ client=client,
+ metadata=metadata,
+ **kwargs,
+ )
+ elif kwargs:
+ msg = (
+ f"Received unsupported arguments {kwargs}. These arguments are not "
+ f"supported when creating a new experiment."
+ )
+ raise ValueError(msg)
+ elif not data:
+ msg = "Must specify 'data' when running evaluations over a target function."
+ raise ValueError(msg)
+ elif callable(target) and rh.is_async(target):
+ msg = (
+ "Async functions are not supported by `evaluate`. "
+ "Please use `aevaluate` instead:\n\n"
+ "from langsmith import aevaluate\n\n"
+ "await aevaluate(\n"
+ " async_target_function,\n"
+ " data=data,\n"
+ " evaluators=evaluators,\n"
+ " # ... other parameters\n"
+ ")"
+ )
+ raise ValueError(msg)
+ elif experiment and experiment_prefix:
+ msg = (
+ "Expected at most one of 'experiment' or 'experiment_prefix',"
+ " but both were provided. "
+ f"Got: experiment={experiment}, experiment_prefix={experiment_prefix}"
+ )
+ raise ValueError(msg)
+ else:
+ if not upload_results:
+ _warn_once("'upload_results' parameter is in beta.")
+ logger.debug(f"Running evaluation over target system {target}...")
+ return _evaluate(
+ target,
+ data=data,
+ evaluators=cast(Optional[Sequence[EVALUATOR_T]], evaluators),
+ summary_evaluators=summary_evaluators,
+ metadata=metadata,
+ experiment_prefix=experiment_prefix,
+ description=description,
+ max_concurrency=max_concurrency,
+ num_repetitions=num_repetitions,
+ client=client,
+ blocking=blocking,
+ experiment=experiment,
+ upload_results=upload_results,
+ error_handling=error_handling,
+ )
+
+
+def evaluate_existing(
+ experiment: Union[str, uuid.UUID, schemas.TracerSession],
+ /,
+ evaluators: Optional[Sequence[EVALUATOR_T]] = None,
+ summary_evaluators: Optional[Sequence[SUMMARY_EVALUATOR_T]] = None,
+ metadata: Optional[dict] = None,
+ max_concurrency: Optional[int] = 0,
+ client: Optional[langsmith.Client] = None,
+ load_nested: bool = False,
+ blocking: bool = True,
+) -> ExperimentResults:
+ r"""Evaluate existing experiment runs.
+
+ Args:
+ experiment (Union[str, uuid.UUID]): The identifier of the experiment to evaluate.
+ evaluators (Optional[Sequence[EVALUATOR_T]]): Optional sequence of evaluators to use for individual run evaluation.
+ summary_evaluators (Optional[Sequence[SUMMARY_EVALUATOR_T]]): Optional sequence of evaluators
+ to apply over the entire dataset.
+ metadata (Optional[dict]): Optional metadata to include in the evaluation results.
+ max_concurrency (int | None): The maximum number of concurrent
+ evaluations to run.
+
+ If `None` then no limit is set. If `0` then no concurrency.
+ client (Optional[langsmith.Client]): Optional Langsmith client to use for evaluation.
+ load_nested: Whether to load all child runs for the experiment.
+
+ Default is to only load the top-level root runs.
+ blocking (bool): Whether to block until evaluation is complete.
+
+ Returns:
+ The evaluation results.
+
+ Environment:
+ - `LANGSMITH_TEST_CACHE`: If set, API calls will be cached to disk to save time and
+ cost during testing.
+
+ Recommended to commit the cache files to your repository for faster CI/CD runs.
+
+ Requires the `'langsmith[vcr]'` package to be installed.
+
+ Examples:
+ Define your evaluators
+
+ >>> from typing import Sequence
+ >>> from langsmith.schemas import Example, Run
+ >>> def accuracy(run: Run, example: Example):
+ ... # Row-level evaluator for accuracy.
+ ... pred = run.outputs["output"]
+ ... expected = example.outputs["answer"]
+ ... return {"score": expected.lower() == pred.lower()}
+ >>> def precision(runs: Sequence[Run], examples: Sequence[Example]):
+ ... # Experiment-level evaluator for precision.
+ ... # TP / (TP + FP)
+ ... predictions = [run.outputs["output"].lower() for run in runs]
+ ... expected = [example.outputs["answer"].lower() for example in examples]
+ ... # yes and no are the only possible answers
+ ... tp = sum([p == e for p, e in zip(predictions, expected) if p == "yes"])
+ ... fp = sum([p == "yes" and e == "no" for p, e in zip(predictions, expected)])
+ ... return {"score": tp / (tp + fp)}
+
+ Load the experiment and run the evaluation.
+
+ >>> import uuid
+ >>> from langsmith import Client
+ >>> from langsmith.evaluation import evaluate, evaluate_existing
+ >>> client = Client()
+ >>> dataset_name = "__doctest_evaluate_existing_" + uuid.uuid4().hex[:8]
+ >>> dataset = client.create_dataset(dataset_name)
+ >>> example = client.create_example(
+ ... inputs={"question": "What is 2+2?"},
+ ... outputs={"answer": "4"},
+ ... dataset_id=dataset.id,
+ ... )
+ >>> def predict(inputs: dict) -> dict:
+ ... return {"output": "4"}
+ >>> # First run inference on the dataset
+ ... results = evaluate(
+ ... predict, data=dataset_name, experiment_prefix="doctest_experiment"
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+ >>> experiment_id = results.experiment_name
+ >>> # Wait for the experiment to be fully processed and check if we have results
+ >>> len(results) > 0
+ True
+ >>> import time
+ >>> time.sleep(5) # Wait longer for runs to be indexed
+ >>> results = evaluate_existing(
+ ... experiment_id,
+ ... evaluators=[accuracy],
+ ... summary_evaluators=[precision],
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+ >>> client.delete_dataset(dataset_id=dataset.id)
+ """ # noqa: E501
+ client = client or rt.get_cached_client(timeout_ms=(20_000, 90_001))
+ project = _load_experiment(experiment, client)
+ runs = _load_traces(experiment, client, load_nested=load_nested)
+ data_map = _load_examples_map(client, project)
+ data = [data_map[cast(uuid.UUID, run.reference_example_id)] for run in runs]
+ return _evaluate(
+ runs,
+ data=data,
+ evaluators=evaluators,
+ summary_evaluators=summary_evaluators,
+ metadata=metadata,
+ max_concurrency=max_concurrency,
+ client=client,
+ blocking=blocking,
+ experiment=project,
+ )
+
+
+class ExperimentResultRow(TypedDict):
+ run: schemas.Run
+ example: schemas.Example
+ evaluation_results: EvaluationResults
+
+
+class ExperimentResults:
+ """Represents the results of an evaluate() call.
+
+ This class provides an iterator interface to iterate over the experiment results
+ as they become available. It also provides methods to access the experiment name,
+ the number of results, and to wait for the results to be processed.
+
+ Methods:
+ experiment_name() -> str: Returns the name of the experiment.
+ wait() -> None: Waits for the experiment data to be processed.
+ """
+
+ def __init__(self, experiment_manager: _ExperimentManager, blocking: bool = True):
+ self._manager = experiment_manager
+ self._results: list[ExperimentResultRow] = []
+ self._queue: queue.Queue[ExperimentResultRow] = queue.Queue()
+ self._processing_complete = threading.Event()
+ self._processing_error: Optional[BaseException] = None
+ if not blocking:
+ self._thread: Optional[threading.Thread] = threading.Thread(
+ target=self._process_data
+ )
+ self._thread.start()
+ else:
+ self._thread = None
+ self._process_data()
+
+ @property
+ def experiment_name(self) -> str:
+ return self._manager.experiment_name
+
+ @property
+ def experiment_id(self) -> uuid.UUID:
+ """The ID of the experiment."""
+ return self._manager._get_experiment().id
+
+ @property
+ def url(self) -> Optional[str]:
+ """The URL of the experiment in the LangSmith UI."""
+ experiment = self._manager._get_experiment()
+ if experiment.url:
+ project_url = experiment.url.split("?")[0]
+ base_url = project_url.split("/projects/p/")[0]
+ return (
+ f"{base_url}/datasets/{self._manager.dataset_id}/compare?"
+ f"selectedSessions={experiment.id}"
+ )
+ return None
+
+ def get_dataset_id(self) -> str:
+ """Get the ID of the dataset associated with this experiment."""
+ return self._manager.dataset_id
+
+ @property
+ def comparison_url(self) -> Optional[str]:
+ """The URL to the comparison view for this experiment."""
+ return self.url
+
+ def __iter__(self) -> Iterator[ExperimentResultRow]:
+ ix = 0
+ while (
+ not self._processing_complete.is_set()
+ or not self._queue.empty()
+ or ix < len(self._results)
+ ):
+ try:
+ if ix < len(self._results):
+ yield self._results[ix]
+ ix += 1
+ else:
+ self._queue.get(block=True, timeout=0.1)
+ except queue.Empty:
+ if self._processing_error is not None:
+ raise self._processing_error
+ continue
+ if self._processing_error is not None:
+ raise self._processing_error
+
+ def _process_data(self) -> None:
+ tqdm = _load_tqdm()
+ try:
+ results = self._manager.get_results()
+ for item in tqdm(results):
+ self._queue.put(item)
+ self._results.append(item)
+
+ summary_scores = self._manager.get_summary_scores()
+ self._summary_results = summary_scores
+ except BaseException as e:
+ self._processing_error = e
+ finally:
+ self._processing_complete.set()
+
+ def __len__(self) -> int:
+ return len(self._results)
+
+ def to_pandas(
+ self, start: Optional[int] = 0, end: Optional[int] = None
+ ) -> DataFrame:
+ return _to_pandas(self._results, start=start, end=end)
+
+ def _repr_html_(self) -> str:
+ import importlib.util
+
+ if self._results and importlib.util.find_spec("pandas"):
+ df = self.to_pandas()
+ return df._repr_html_() # type: ignore[operator]
+ else:
+ return self.__repr__()
+
+ def __repr__(self) -> str:
+ return f""
+
+ def wait(self) -> None:
+ """Wait for the evaluation runner to complete.
+
+ This method blocks the current thread until the evaluation runner has
+ finished its execution.
+ """
+ if self._thread:
+ self._thread.join()
+ if self._processing_error is not None:
+ raise self._processing_error
+
+
+## Public API for Comparison Experiments
+
+# Row-level evaluator
+COMPARATIVE_EVALUATOR_T = Callable[
+ [Sequence[schemas.Run], Optional[schemas.Example]],
+ Union[
+ Union[ComparisonEvaluationResult, dict],
+ Awaitable[Union[ComparisonEvaluationResult, dict]],
+ ],
+]
+
+
+def evaluate_comparative(
+ experiments: tuple[EXPERIMENT_T, EXPERIMENT_T],
+ /,
+ evaluators: Sequence[COMPARATIVE_EVALUATOR_T],
+ experiment_prefix: Optional[str] = None,
+ description: Optional[str] = None,
+ max_concurrency: int = 5,
+ client: Optional[langsmith.Client] = None,
+ metadata: Optional[dict] = None,
+ load_nested: bool = False,
+ randomize_order: bool = False,
+) -> ComparativeExperimentResults:
+ r"""Evaluate existing experiment runs against each other.
+
+ This lets you use pairwise preference scoring to generate more
+ reliable feedback in your experiments.
+
+ Args:
+ experiments (Tuple[Union[str, uuid.UUID], Union[str, uuid.UUID]]):
+ The identifiers of the experiments to compare.
+ evaluators (Sequence[COMPARATIVE_EVALUATOR_T]):
+ A list of evaluators to run on each example.
+ experiment_prefix (Optional[str]): A prefix to provide for your experiment name.
+ description (Optional[str]): A free-form text description for the experiment.
+ max_concurrency (int): The maximum number of concurrent evaluations to run.
+ client (Optional[langsmith.Client]): The LangSmith client to use.
+ metadata (Optional[dict]): Metadata to attach to the experiment.
+ load_nested (bool): Whether to load all child runs for the experiment.
+
+ Default is to only load the top-level root runs.
+ randomize_order (bool): Whether to randomize the order of the outputs for each evaluation.
+
+ Returns:
+ The results of the comparative evaluation.
+
+ Examples:
+ Suppose you want to compare two prompts to see which one is more effective.
+ You would first prepare your dataset:
+
+ >>> from typing import Sequence
+ >>> from langsmith import Client
+ >>> from langsmith.evaluation import evaluate
+ >>> from langsmith.schemas import Example, Run
+ >>> client = Client()
+ >>> dataset = client.clone_public_dataset(
+ ... "https://smith.langchain.com/public/419dcab2-1d66-4b94-8901-0357ead390df/d"
+ ... )
+ >>> dataset_name = "Evaluate Examples"
+
+ Then you would run your different prompts:
+ >>> import functools
+ >>> import openai
+ >>> from langsmith.evaluation import evaluate
+ >>> from langsmith.wrappers import wrap_openai
+ >>> oai_client = openai.Client()
+ >>> wrapped_client = wrap_openai(oai_client)
+ >>> prompt_1 = "You are a helpful assistant."
+ >>> prompt_2 = "You are an exceedingly helpful assistant."
+ >>> def predict(inputs: dict, prompt: str) -> dict:
+ ... completion = wrapped_client.chat.completions.create(
+ ... model="gpt-4o-mini",
+ ... messages=[
+ ... {"role": "system", "content": prompt},
+ ... {
+ ... "role": "user",
+ ... "content": f"Context: {inputs['context']}"
+ ... f"\n\ninputs['question']",
+ ... },
+ ... ],
+ ... )
+ ... return {"output": completion.choices[0].message.content}
+ >>> results_1 = evaluate(
+ ... functools.partial(predict, prompt=prompt_1),
+ ... data=dataset_name,
+ ... description="Evaluating our basic system prompt.",
+ ... blocking=False, # Run these experiments in parallel
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+ >>> results_2 = evaluate(
+ ... functools.partial(predict, prompt=prompt_2),
+ ... data=dataset_name,
+ ... description="Evaluating our advanced system prompt.",
+ ... blocking=False,
+ ... ) # doctest: +ELLIPSIS
+ View the evaluation results for experiment:...
+ >>> results_1.wait()
+ >>> results_2.wait()
+
+ Finally, you would compare the two prompts directly:
+ >>> import json
+ >>> from langsmith.evaluation import evaluate_comparative
+ >>> from langsmith import schemas
+ >>> def score_preferences(runs: list, example: schemas.Example):
+ ... assert len(runs) == 2 # Comparing 2 systems
+ ... assert isinstance(example, schemas.Example)
+ ... assert all(run.reference_example_id == example.id for run in runs)
+ ... pred_a = runs[0].outputs["output"] if runs[0].outputs else ""
+ ... pred_b = runs[1].outputs["output"] if runs[1].outputs else ""
+ ... ground_truth = example.outputs["answer"] if example.outputs else ""
+ ... tools = [
+ ... {
+ ... "type": "function",
+ ... "function": {
+ ... "name": "rank_preferences",
+ ... "description": "Saves the prefered response ('A' or 'B')",
+ ... "parameters": {
+ ... "type": "object",
+ ... "properties": {
+ ... "reasoning": {
+ ... "type": "string",
+ ... "description": "The reasoning behind the choice.",
+ ... },
+ ... "preferred_option": {
+ ... "type": "string",
+ ... "enum": ["A", "B"],
+ ... "description": "The preferred option, either 'A' or 'B'",
+ ... },
+ ... },
+ ... "required": ["preferred_option"],
+ ... },
+ ... },
+ ... }
+ ... ]
+ ... completion = openai.Client().chat.completions.create(
+ ... model="gpt-4o-mini",
+ ... messages=[
+ ... {"role": "system", "content": "Select the better response."},
+ ... {
+ ... "role": "user",
+ ... "content": f"Option A: {pred_a}"
+ ... f"\n\nOption B: {pred_b}"
+ ... f"\n\nGround Truth: {ground_truth}",
+ ... },
+ ... ],
+ ... tools=tools,
+ ... tool_choice={
+ ... "type": "function",
+ ... "function": {"name": "rank_preferences"},
+ ... },
+ ... )
+ ... tool_args = completion.choices[0].message.tool_calls[0].function.arguments
+ ... loaded_args = json.loads(tool_args)
+ ... preference = loaded_args["preferred_option"]
+ ... comment = loaded_args["reasoning"]
+ ... if preference == "A":
+ ... return {
+ ... "key": "ranked_preference",
+ ... "scores": {runs[0].id: 1, runs[1].id: 0},
+ ... "comment": comment,
+ ... }
+ ... else:
+ ... return {
+ ... "key": "ranked_preference",
+ ... "scores": {runs[0].id: 0, runs[1].id: 1},
+ ... "comment": comment,
+ ... }
+ >>> def score_length_difference(runs: list, example: schemas.Example):
+ ... # Just return whichever response is longer.
+ ... # Just an example, not actually useful in real life.
+ ... assert len(runs) == 2 # Comparing 2 systems
+ ... assert isinstance(example, schemas.Example)
+ ... assert all(run.reference_example_id == example.id for run in runs)
+ ... pred_a = runs[0].outputs["output"] if runs[0].outputs else ""
+ ... pred_b = runs[1].outputs["output"] if runs[1].outputs else ""
+ ... if len(pred_a) > len(pred_b):
+ ... return {
+ ... "key": "length_difference",
+ ... "scores": {runs[0].id: 1, runs[1].id: 0},
+ ... }
+ ... else:
+ ... return {
+ ... "key": "length_difference",
+ ... "scores": {runs[0].id: 0, runs[1].id: 1},
+ ... }
+ >>> results = evaluate_comparative(
+ ... [results_1.experiment_name, results_2.experiment_name],
+ ... evaluators=[score_preferences, score_length_difference],
+ ... client=client,
+ ... ) # doctest: +ELLIPSIS
+ View the pairwise evaluation results at:...
+ >>> eval_results = list(results)
+ >>> assert len(eval_results) >= 10 # doctest: +SKIP
+ >>> assert all(
+ ... "feedback.ranked_preference" in r["evaluation_results"]
+ ... for r in eval_results
+ ... ) # doctest: +SKIP
+ >>> assert all(
+ ... "feedback.length_difference" in r["evaluation_results"]
+ ... for r in eval_results
+ ... ) # doctest: +SKIP
+ """ # noqa: E501
+ if len(experiments) < 2:
+ raise ValueError("Comparative evaluation requires at least 2 experiments.")
+ if not evaluators:
+ raise ValueError(
+ "At least one evaluator is required for comparative evaluation."
+ )
+ if max_concurrency < 0:
+ raise ValueError("max_concurrency must be a positive integer.")
+ client = client or rt.get_cached_client()
+
+ # TODO: Add information about comparison experiments
+ projects = [_load_experiment(experiment, client) for experiment in experiments]
+ ref_datasets_ = [str(p.reference_dataset_id) for p in projects]
+ if not len(set(ref_datasets_)) == 1:
+ raise ValueError("All experiments must have the same reference dataset.")
+ experiment_ids = [p.id for p in projects]
+ if experiment_prefix is None:
+ experiment_names = [p.name for p in projects if p.name is not None]
+ experiment_name = (
+ " vs. ".join(experiment_names) + "-" + str(uuid.uuid4().hex[:4])
+ )
+ else:
+ experiment_name = experiment_prefix + "-" + str(uuid.uuid4().hex[:8])
+ comparative_experiment_id = uuid.uuid4()
+ comparative_experiment = client.create_comparative_experiment(
+ experiment_name,
+ experiments=experiment_ids,
+ description=description,
+ metadata=metadata,
+ id=comparative_experiment_id,
+ )
+ _print_comparative_experiment_start(
+ cast(
+ tuple[schemas.TracerSessionResult, schemas.TracerSessionResult],
+ tuple(projects),
+ ),
+ comparative_experiment,
+ )
+ runs = [
+ _load_traces(experiment, client, load_nested=load_nested)
+ for experiment in experiments
+ ]
+ # Only check intersections for the experiments
+ examples_intersection = None
+ for runs_list in runs:
+ example_ids_set = {run.reference_example_id for run in runs_list}
+ if examples_intersection is None:
+ examples_intersection = example_ids_set
+ else:
+ examples_intersection &= example_ids_set
+ example_ids_nullable = (
+ list(examples_intersection) if examples_intersection is not None else []
+ )
+ example_ids = [eid for eid in example_ids_nullable if eid is not None]
+ # TODO: Warn if different dataset versions, etc. are used in the different
+ # experiments. We aren't providing any training wheels here.
+ batch_size = 99
+ data = {}
+ for i in range(0, len(example_ids), batch_size):
+ example_ids_batch = example_ids[i : i + batch_size]
+ for e in client.list_examples(
+ dataset_id=projects[0].reference_dataset_id,
+ as_of=projects[0].metadata.get("dataset_version"),
+ example_ids=example_ids_batch,
+ ):
+ data[e.id] = e
+ runs_dict: dict[uuid.UUID, list[schemas.Run]] = collections.defaultdict(list)
+ for runs_list in runs:
+ for run in runs_list:
+ if run.reference_example_id in data:
+ runs_dict[cast(uuid.UUID, run.reference_example_id)].append(run)
+
+ comparators = [comparison_evaluator(evaluator) for evaluator in evaluators or []]
+ results: dict = {}
+
+ def evaluate_and_submit_feedback(
+ runs_list: list[schemas.Run],
+ example: schemas.Example,
+ comparator: DynamicComparisonRunEvaluator,
+ executor: cf.Executor,
+ ) -> tuple[uuid.UUID, ComparisonEvaluationResult]:
+ feedback_group_id = uuid.uuid4()
+ if randomize_order:
+ random.shuffle(runs_list)
+ with rh.tracing_context(project_name="evaluators", client=client):
+ result = comparator.compare_runs(runs_list, example)
+ if client is None:
+ raise ValueError("Client is required to submit feedback.")
+ comments = (
+ {str(rid): result.comment for rid in result.scores}
+ if isinstance(result.comment, str)
+ else (result.comment or {})
+ )
+ # Build a lookup for run metadata
+ runs_by_id = {str(run.id): run for run in runs_list}
+ for run_id, score in result.scores.items():
+ run = runs_by_id.get(str(run_id))
+ executor.submit(
+ client.create_feedback,
+ run_id=run_id,
+ key=result.key,
+ score=score,
+ comment=comments.get(str(run_id)),
+ comparative_experiment_id=comparative_experiment.id,
+ source_run_id=result.source_run_id,
+ feedback_group_id=feedback_group_id,
+ session_id=run.session_id if run else None,
+ start_time=run.start_time if run else None,
+ )
+ return example.id, result
+
+ tqdm = _load_tqdm()
+ with ls_utils.ContextThreadPoolExecutor(
+ max_workers=max_concurrency or 1
+ ) as executor:
+ futures = []
+ for example_id, runs_list in tqdm(runs_dict.items()):
+ results[example_id] = {"runs": runs_list}
+ for comparator in comparators:
+ if max_concurrency > 1:
+ future = executor.submit(
+ evaluate_and_submit_feedback,
+ runs_list,
+ data[example_id],
+ comparator,
+ executor,
+ )
+ futures.append(future)
+ else:
+ _, result = evaluate_and_submit_feedback(
+ runs_list, data[example_id], comparator, executor
+ )
+ results[example_id][f"feedback.{result.key}"] = result
+ if futures:
+ cf.wait(futures)
+ for future in futures:
+ example_id, result = future.result()
+ results[example_id][f"feedback.{result.key}"] = result
+
+ return ComparativeExperimentResults(results, data)
+
+
+class ComparativeExperimentResults:
+ """Represents the results of an evaluate_comparative() call.
+
+ This class provides an iterator interface to iterate over the experiment results
+ as they become available. It also provides methods to access the experiment name,
+ the number of results, and to wait for the results to be processed.
+
+ Methods:
+ experiment_name() -> str: Returns the name of the experiment.
+ wait() -> None: Waits for the experiment data to be processed.
+ """
+
+ def __init__(
+ self,
+ results: dict,
+ examples: Optional[dict[uuid.UUID, schemas.Example]] = None,
+ ):
+ self._results = results
+ self._examples = examples
+
+ def __getitem__(self, key):
+ """Return the result associated with the given key."""
+ return self._results[key]
+
+ def __iter__(self):
+ for key, value in self._results.items():
+ yield {
+ "example": self._examples[key] if self._examples else None,
+ "evaluation_results": value,
+ }
+
+
+## Private API
+
+
+def _print_comparative_experiment_start(
+ experiments: tuple[schemas.TracerSession, schemas.TracerSession],
+ comparative_experiment: schemas.ComparativeExperiment,
+) -> None:
+ url = experiments[0].url or experiments[1].url
+ if url:
+ project_url = url.split("?")[0]
+ dataset_id = comparative_experiment.reference_dataset_id
+ base_url = project_url.split("/projects/p/")[0]
+ comparison_url = (
+ f"{base_url}/datasets/{dataset_id}/compare?"
+ f"selectedSessions={'%2C'.join([str(e.id) for e in experiments])}"
+ f"&comparativeExperiment={comparative_experiment.id}"
+ )
+ print( # noqa: T201
+ f"View the pairwise evaluation results at:\n{comparison_url}\n\n"
+ )
+
+
+def _is_callable(target: Union[TARGET_T, Iterable[schemas.Run], Runnable]) -> bool:
+ return callable(target) or _is_langchain_runnable(target)
+
+
+def _evaluate(
+ target: Union[TARGET_T, Iterable[schemas.Run], Runnable],
+ /,
+ data: DATA_T,
+ evaluators: Optional[Sequence[EVALUATOR_T]] = None,
+ summary_evaluators: Optional[Sequence[SUMMARY_EVALUATOR_T]] = None,
+ metadata: Optional[dict] = None,
+ experiment_prefix: Optional[str] = None,
+ description: Optional[str] = None,
+ max_concurrency: Optional[int] = None,
+ num_repetitions: int = 1,
+ client: Optional[langsmith.Client] = None,
+ blocking: bool = True,
+ experiment: Optional[Union[schemas.TracerSession, str, uuid.UUID]] = None,
+ upload_results: bool = True,
+ error_handling: Literal["log", "ignore"] = "log",
+) -> ExperimentResults:
+ # Initialize the experiment manager.
+ client = client or rt.get_cached_client()
+ runs = None if _is_callable(target) else cast(Iterable[schemas.Run], target)
+ experiment_, runs = _resolve_experiment(experiment, runs, client)
+
+ manager = _ExperimentManager(
+ data,
+ client=client,
+ metadata=metadata,
+ experiment=experiment_ or experiment_prefix,
+ description=description,
+ num_repetitions=num_repetitions,
+ # If provided, we don't need to create a new experiment.
+ runs=runs,
+ # Create or resolve the experiment.
+ include_attachments=_include_attachments(target, evaluators),
+ upload_results=upload_results,
+ error_handling=error_handling,
+ ).start()
+ if cache_dir := ls_utils.get_cache_dir(None):
+ cache_path = pathlib.Path(cache_dir) / f"{manager.dataset_id}.yaml"
+ else:
+ cache_path = None
+ with ls_utils.with_optional_cache(cache_path, ignore_hosts=[client.api_url]):
+ if _is_callable(target):
+ # Add predictions to the experiment.
+ manager = manager.with_predictions(
+ cast(TARGET_T, target), max_concurrency=max_concurrency
+ )
+ if evaluators:
+ # Apply evaluators to the predictions.
+ manager = manager.with_evaluators(
+ evaluators, max_concurrency=max_concurrency
+ )
+ if summary_evaluators:
+ # Apply the experiment-level summary evaluators.
+ manager = manager.with_summary_evaluators(summary_evaluators)
+ # Start consuming the results.
+ results = ExperimentResults(manager, blocking=blocking)
+ return results
+
+
+def _is_uuid(value: str) -> bool:
+ try:
+ uuid.UUID(value)
+ return True
+ except ValueError:
+ return False
+
+
+def _load_experiment(
+ project: EXPERIMENT_T, client: langsmith.Client
+) -> schemas.TracerSession:
+ if isinstance(project, schemas.TracerSession):
+ return project
+ elif isinstance(project, uuid.UUID) or _is_uuid(project):
+ return client.read_project(project_id=project)
+ else:
+ return client.read_project(project_name=project)
+
+
+def _load_traces(
+ project: Union[str, uuid.UUID, schemas.TracerSession],
+ client: langsmith.Client,
+ load_nested: bool = False,
+) -> list[schemas.Run]:
+ """Load nested traces for a given project."""
+ is_root = None if load_nested else True
+ if isinstance(project, schemas.TracerSession):
+ runs = client.list_runs(project_id=project.id, is_root=is_root)
+ elif isinstance(project, uuid.UUID) or _is_uuid(project):
+ runs = client.list_runs(project_id=project, is_root=is_root)
+ else:
+ runs = client.list_runs(project_name=project, is_root=is_root)
+ if not load_nested:
+ return list(runs)
+
+ treemap: collections.defaultdict[uuid.UUID, list[schemas.Run]] = (
+ collections.defaultdict(list)
+ )
+ results = []
+ all_runs = {}
+ for run in runs:
+ if run.parent_run_id is not None:
+ treemap[run.parent_run_id].append(run)
+ else:
+ results.append(run)
+ all_runs[run.id] = run
+ for run_id, child_runs in treemap.items():
+ all_runs[run_id].child_runs = sorted(child_runs, key=lambda r: r.dotted_order)
+ return results
+
+
+def _load_examples_map(
+ client: langsmith.Client, project: schemas.TracerSession
+) -> dict[uuid.UUID, schemas.Example]:
+ return {
+ e.id: e
+ for e in client.list_examples(
+ dataset_id=project.reference_dataset_id,
+ as_of=project.metadata.get("dataset_version"),
+ )
+ }
+
+
+IT = TypeVar("IT")
+
+
+def _load_tqdm() -> Callable[[IT], IT]:
+ try:
+ from tqdm.auto import tqdm
+ except ImportError:
+ return lambda x: x
+ return tqdm # type: ignore[return-value]
+
+
+ET = TypeVar("ET", bound="_ExperimentManagerMixin")
+
+
+class _ExperimentManagerMixin:
+ def __init__(
+ self,
+ /,
+ experiment: Optional[Union[schemas.TracerSession, str]],
+ metadata: Optional[dict] = None,
+ client: Optional[langsmith.Client] = None,
+ description: Optional[str] = None,
+ ):
+ self.client = client or rt.get_cached_client()
+ self._experiment: Optional[schemas.TracerSession] = None
+ if experiment is None:
+ self._experiment_name = _get_random_name()
+ elif isinstance(experiment, str):
+ self._experiment_name = experiment + "-" + str(uuid.uuid4().hex[:8])
+ else:
+ self._experiment_name = cast(str, experiment.name)
+ self._experiment = experiment
+
+ metadata = metadata or {}
+ if not metadata.get("revision_id"):
+ metadata = {
+ "revision_id": ls_env.get_langchain_env_var_metadata().get(
+ "revision_id"
+ ),
+ **metadata,
+ }
+ self._metadata = metadata or {}
+ self._description = description
+
+ @property
+ def experiment_name(self) -> str:
+ if self._experiment_name is not None:
+ return self._experiment_name
+ raise ValueError(
+ "Experiment name not provided, and experiment not yet started."
+ )
+
+ def _get_experiment(self) -> schemas.TracerSession:
+ if self._experiment is None:
+ raise ValueError("Experiment not started yet.")
+ return self._experiment
+
+ def _get_experiment_metadata(self):
+ project_metadata = self._metadata or {}
+ project_metadata["__ls_runner"] = "py_sdk_evaluate"
+ git_info = ls_env.get_git_info()
+ if git_info:
+ project_metadata = {
+ **project_metadata,
+ "git": git_info,
+ }
+ if self._experiment:
+ project_metadata = {
+ **self._experiment.metadata,
+ **project_metadata,
+ }
+ return project_metadata
+
+ def _create_experiment(
+ self, dataset_id: uuid.UUID, metadata: dict
+ ) -> schemas.TracerSession:
+ # There is a chance of name collision, so we'll retry
+ starting_name = self._experiment_name
+ num_attempts = 10
+ for _ in range(num_attempts):
+ try:
+ return self.client.create_project(
+ self._experiment_name,
+ description=self._description,
+ reference_dataset_id=dataset_id,
+ metadata=metadata,
+ )
+ except ls_utils.LangSmithConflictError:
+ self._experiment_name = f"{starting_name}-{str(uuid.uuid4().hex[:6])}"
+ raise ValueError(
+ f"Could not find a unique experiment name in {num_attempts} attempts."
+ " Please try again with a different experiment name."
+ )
+
+ def _get_project(self, first_example: schemas.Example) -> schemas.TracerSession:
+ if self._experiment is None:
+ project_metadata = self._get_experiment_metadata()
+ project = self._create_experiment(
+ first_example.dataset_id, project_metadata
+ )
+ else:
+ project = self._experiment
+ return project
+
+ def _print_experiment_start(
+ self, project: Optional[schemas.TracerSession], first_example: schemas.Example
+ ) -> None:
+ if project and project.url:
+ project_url = project.url.split("?")[0]
+ dataset_id = first_example.dataset_id
+ base_url = project_url.split("/projects/p/")[0]
+ comparison_url = (
+ f"{base_url}/datasets/{dataset_id}/compare?"
+ f"selectedSessions={project.id}"
+ )
+ print( # noqa: T201
+ f"View the evaluation results for experiment: '{self.experiment_name}'"
+ f" at:\n{comparison_url}\n\n"
+ )
+ else:
+ # HACKHACK
+ print( # noqa: T201
+ "Starting evaluation of experiment: %s", self.experiment_name
+ )
+
+
+class _ExperimentManager(_ExperimentManagerMixin):
+ """Manage the execution of experiments.
+
+ Supports lazily running predictions and evaluations in parallel to facilitate
+ result streaming and early debugging.
+
+ Args:
+ data (DATA_T): The data used for the experiment. Can be a dataset name or ID OR
+ a generator of examples.
+ num_repetitions (int): The number of times to run over the data.
+ runs (Optional[Iterable[schemas.Run]]): The runs associated with the experiment
+ predictions.
+ experiment (Optional[schemas.TracerSession]): The tracer session
+ associated with the experiment.
+ experiment_prefix (Optional[str]): The prefix for the experiment name.
+ metadata (Optional[dict]): Additional metadata for the experiment.
+ client (Optional[langsmith.Client]): The Langsmith client used for
+ the experiment.
+ evaluation_results (Optional[Iterable[EvaluationResults]]): The evaluation
+ sresults for the experiment.
+ summary_results (Optional[Iterable[EvaluationResults]]): The aggregate results
+ for the experiment.
+ """
+
+ def __init__(
+ self,
+ data: DATA_T,
+ /,
+ experiment: Optional[Union[schemas.TracerSession, str]],
+ metadata: Optional[dict] = None,
+ client: Optional[langsmith.Client] = None,
+ runs: Optional[Iterable[schemas.Run]] = None,
+ evaluation_results: Optional[Iterable[EvaluationResults]] = None,
+ summary_results: Optional[Iterable[EvaluationResults]] = None,
+ description: Optional[str] = None,
+ num_repetitions: int = 1,
+ include_attachments: bool = False,
+ reuse_attachments: bool = False,
+ upload_results: bool = True,
+ attachment_raw_data_dict: Optional[dict] = None,
+ error_handling: Literal["log", "ignore"] = "log",
+ ):
+ super().__init__(
+ experiment=experiment,
+ metadata=metadata,
+ client=client,
+ description=description,
+ )
+ self._data = data
+ self._examples: Optional[Iterable[schemas.Example]] = None
+ self._runs = runs
+ self._evaluation_results = evaluation_results
+ self._summary_results = summary_results
+ self._num_repetitions = num_repetitions
+ self._include_attachments = include_attachments
+ self._reuse_attachments = reuse_attachments
+ self._upload_results = upload_results
+ self._attachment_raw_data_dict = attachment_raw_data_dict
+ self._error_handling = error_handling
+
+ def _reset_example_attachment_readers(
+ self, example: schemas.Example
+ ) -> schemas.Example:
+ """Reset attachment readers for an example.
+
+ This is only in the case that an attachment is going to be used by more
+ than 1 callable (target + evaluators). In that case we keep a single copy
+ of the attachment data in `self._attachment_raw_data_dict`, and create
+ readers from that data. This makes it so that we don't have to keep
+ copies of the same data in memory, instead we can just create readers
+ from the same data.
+ """
+ if not hasattr(example, "attachments") or not example.attachments:
+ return example
+
+ new_attachments: dict[str, schemas.AttachmentInfo] = {}
+ for name, attachment in example.attachments.items():
+ if (
+ self._attachment_raw_data_dict is not None
+ and str(example.id) + name in self._attachment_raw_data_dict
+ ):
+ new_attachments[name] = {
+ "presigned_url": attachment["presigned_url"],
+ "reader": io.BytesIO(
+ self._attachment_raw_data_dict[str(example.id) + name]
+ ),
+ "mime_type": attachment["mime_type"],
+ }
+ else:
+ new_attachments[name] = attachment
+
+ # Create a new Example instance with the updated attachments
+ return schemas.Example(
+ id=example.id,
+ created_at=example.created_at,
+ dataset_id=example.dataset_id,
+ inputs=example.inputs,
+ outputs=example.outputs,
+ metadata=example.metadata,
+ modified_at=example.modified_at,
+ source_run_id=example.source_run_id,
+ attachments=new_attachments,
+ _host_url=example._host_url,
+ _tenant_id=example._tenant_id,
+ )
+
+ @property
+ def examples(self) -> Iterable[schemas.Example]:
+ if self._examples is None:
+ self._examples = _resolve_data(
+ self._data,
+ client=self.client,
+ include_attachments=self._include_attachments,
+ )
+ if self._reuse_attachments and self._attachment_raw_data_dict is None:
+ examples_copy, self._examples = itertools.tee(self._examples)
+ self._attachment_raw_data_dict = {
+ str(e.id) + name: value["reader"].read()
+ for e in examples_copy
+ for name, value in (e.attachments or {}).items()
+ }
+ if self._num_repetitions > 1:
+ examples_list = list(self._examples)
+ self._examples = itertools.chain.from_iterable(
+ [
+ self._reset_example_attachment_readers(example)
+ for example in examples_list
+ ]
+ for _ in range(self._num_repetitions)
+ )
+ self._examples, examples_iter = itertools.tee(self._examples)
+ return examples_iter
+
+ @property
+ def dataset_id(self) -> str:
+ if self._experiment is None or not getattr(
+ self._experiment, "reference_dataset_id", None
+ ):
+ example = next(iter(self.examples))
+ return str(example.dataset_id)
+ return str(
+ cast(schemas.TracerSessionResult, self._experiment).reference_dataset_id
+ )
+
+ @property
+ def evaluation_results(self) -> Iterable[EvaluationResults]:
+ if self._evaluation_results is None:
+ return ({"results": []} for _ in self.examples)
+ return self._evaluation_results
+
+ @property
+ def runs(self) -> Iterable[schemas.Run]:
+ if self._runs is None:
+ raise ValueError(
+ "Runs not provided in this experiment. Please predict first."
+ )
+ self._runs, runs_iter = itertools.tee(self._runs)
+ return runs_iter
+
+ def start(self) -> _ExperimentManager:
+ first_example = next(itertools.islice(self.examples, 1))
+ project = self._get_project(first_example) if self._upload_results else None
+ self._print_experiment_start(project, first_example)
+ self._metadata["num_repetitions"] = self._num_repetitions
+ return self._copy(self.examples, experiment=project)
+
+ def with_predictions(
+ self,
+ target: TARGET_T,
+ /,
+ max_concurrency: Optional[int] = None,
+ ) -> _ExperimentManager:
+ """Lazily apply the target function to the experiment."""
+ context = copy_context()
+ _experiment_results = context.run(
+ self._predict,
+ target,
+ max_concurrency=max_concurrency,
+ include_attachments=_target_include_attachments(target),
+ )
+ r1, r2 = itertools.tee(_experiment_results, 2)
+ return self._copy(
+ (pred["example"] for pred in r1), runs=(pred["run"] for pred in r2)
+ )
+
+ def with_evaluators(
+ self,
+ evaluators: Sequence[
+ Union[
+ EVALUATOR_T,
+ RunEvaluator,
+ ]
+ ],
+ *,
+ max_concurrency: Optional[int] = None,
+ ) -> _ExperimentManager:
+ """Lazily apply the provided evaluators to the experiment."""
+ evaluators = _resolve_evaluators(evaluators)
+ context = copy_context()
+ experiment_results = context.run(
+ self._score, evaluators, max_concurrency=max_concurrency
+ )
+ # Split the generator into three so the manager
+ # can consume each value individually.
+ r1, r2, r3 = itertools.tee(experiment_results, 3)
+ return self._copy(
+ (result["example"] for result in r1),
+ runs=(result["run"] for result in r2),
+ evaluation_results=(result["evaluation_results"] for result in r3),
+ )
+
+ def with_summary_evaluators(
+ self,
+ summary_evaluators: Sequence[SUMMARY_EVALUATOR_T],
+ ) -> _ExperimentManager:
+ """Lazily apply the provided summary evaluators to the experiment."""
+ wrapped_evaluators = _wrap_summary_evaluators(summary_evaluators)
+ context = copy_context()
+ aggregate_feedback_gen = context.run(
+ self._apply_summary_evaluators, wrapped_evaluators
+ )
+ return self._copy(
+ self.examples, runs=self.runs, summary_results=aggregate_feedback_gen
+ )
+
+ def get_results(self) -> Iterable[ExperimentResultRow]:
+ """Return the traces, evaluation results, and associated examples."""
+ for run, example, evaluation_results in zip(
+ self.runs, self.examples, self.evaluation_results
+ ):
+ yield ExperimentResultRow(
+ run=run,
+ example=example,
+ evaluation_results=evaluation_results,
+ )
+
+ def get_summary_scores(self) -> dict[str, list[dict]]:
+ """If `summary_evaluators` were applied, consume and return the results."""
+ if self._summary_results is None:
+ return {"results": []}
+ # Consume the generator
+ return {
+ "results": [
+ res # type: ignore[misc]
+ for results in self._summary_results
+ for res in results["results"]
+ ]
+ }
+
+ # Private methods
+
+ def _predict(
+ self,
+ target: TARGET_T,
+ /,
+ max_concurrency: Optional[int] = None,
+ include_attachments: bool = False,
+ ) -> Generator[_ForwardResults, None, None]:
+ """Run the target function on the examples."""
+ fn = _ensure_traceable(target)
+
+ if max_concurrency == 0:
+ for example in self.examples:
+ yield _forward(
+ fn,
+ example,
+ self.experiment_name,
+ self._metadata,
+ self.client,
+ self._upload_results,
+ include_attachments,
+ self._error_handling,
+ )
+
+ else:
+ with ls_utils.ContextThreadPoolExecutor(max_concurrency) as executor:
+ futures = [
+ executor.submit(
+ _forward,
+ fn,
+ example,
+ self.experiment_name,
+ self._metadata,
+ self.client,
+ self._upload_results,
+ include_attachments,
+ self._error_handling,
+ )
+ for example in self.examples
+ ]
+ for future in cf.as_completed(futures):
+ yield future.result()
+ # Close out the project.
+ self._end()
+
+ def _run_evaluators(
+ self,
+ evaluators: Sequence[RunEvaluator],
+ current_results: ExperimentResultRow,
+ executor: cf.ThreadPoolExecutor,
+ ) -> ExperimentResultRow:
+ current_context = rh.get_tracing_context()
+ metadata = {
+ **(current_context["metadata"] or {}),
+ **{
+ "experiment": self.experiment_name,
+ "reference_example_id": current_results["example"].id,
+ "reference_run_id": current_results["run"].id,
+ },
+ }
+ with rh.tracing_context(
+ **{
+ **current_context,
+ "project_name": "evaluators",
+ "metadata": metadata,
+ "enabled": "local" if not self._upload_results else True,
+ "client": self.client,
+ }
+ ):
+ run = current_results["run"]
+ example = current_results["example"]
+ eval_results = current_results["evaluation_results"]
+ for evaluator in evaluators:
+ evaluator_run_id = uuid.uuid4()
+ try:
+ evaluator_response = evaluator.evaluate_run( # type: ignore[call-arg]
+ run=run,
+ example=example,
+ evaluator_run_id=evaluator_run_id,
+ )
+
+ eval_results["results"].extend(
+ self.client._select_eval_results(evaluator_response)
+ )
+ if self._upload_results:
+ # TODO: This is a hack
+ self.client._log_evaluation_feedback(
+ evaluator_response, run=run, _executor=executor
+ )
+ except Exception as e:
+ try:
+ feedback_keys = _extract_feedback_keys(evaluator)
+
+ error_response = EvaluationResults(
+ results=[
+ EvaluationResult(
+ key=key,
+ source_run_id=evaluator_run_id,
+ comment=repr(e),
+ extra={"error": True},
+ )
+ for key in feedback_keys
+ ]
+ )
+ eval_results["results"].extend(
+ self.client._select_eval_results(error_response)
+ )
+ if self._upload_results:
+ # TODO: This is a hack
+ self.client._log_evaluation_feedback(
+ error_response, run=run, _executor=executor
+ )
+ except Exception as e2:
+ logger.debug(f"Error parsing feedback keys: {e2}")
+ pass
+ logger.error(
+ f"Error running evaluator {repr(evaluator)} on"
+ f" run {run.id if run else ''}: {repr(e)}",
+ exc_info=True,
+ )
+ if example.attachments is not None:
+ for attachment in example.attachments:
+ reader = example.attachments[attachment]["reader"]
+ reader.seek(0)
+
+ return ExperimentResultRow(
+ run=run,
+ example=example,
+ evaluation_results=eval_results,
+ )
+
+ def _score(
+ self,
+ evaluators: Sequence[RunEvaluator],
+ max_concurrency: Optional[int] = None,
+ ) -> Iterable[ExperimentResultRow]:
+ """Run the evaluators on the prediction stream.
+
+ Expects runs to be available in the manager.
+ (e.g. from a previous prediction step)
+ """
+ with ls_utils.ContextThreadPoolExecutor(
+ max_workers=max_concurrency or 1
+ ) as executor:
+ if max_concurrency == 0:
+ context = copy_context()
+ for current_results in self.get_results():
+ yield context.run(
+ self._run_evaluators,
+ evaluators,
+ current_results,
+ executor,
+ )
+ else:
+ futures = set()
+ for current_results in self.get_results():
+ futures.add(
+ executor.submit(
+ self._run_evaluators,
+ evaluators,
+ current_results,
+ executor,
+ )
+ )
+ try:
+ # Since prediction may be slow, yield (with a timeout) to
+ # allow for early results to be emitted.
+ for future in cf.as_completed(futures, timeout=0.001):
+ yield future.result()
+ futures.remove(future)
+ except (cf.TimeoutError, TimeoutError):
+ pass
+ for future in cf.as_completed(futures):
+ result = future.result()
+ yield result
+
+ def _apply_summary_evaluators(
+ self, summary_evaluators: Sequence[SUMMARY_EVALUATOR_T]
+ ) -> Generator[EvaluationResults, None, None]:
+ runs, examples = [], []
+ for run, example in zip(self.runs, self.examples):
+ runs.append(run)
+ examples.append(example)
+ aggregate_feedback = []
+ with ls_utils.ContextThreadPoolExecutor() as executor:
+ project_id = self._get_experiment().id if self._upload_results else None
+ current_context = rh.get_tracing_context()
+ metadata = {
+ **(current_context["metadata"] or {}),
+ **{
+ "experiment": self.experiment_name,
+ "experiment_id": project_id,
+ },
+ }
+ with rh.tracing_context(
+ **{
+ **current_context,
+ "project_name": "evaluators",
+ "metadata": metadata,
+ "client": self.client,
+ "enabled": "local" if not self._upload_results else True,
+ }
+ ):
+ for evaluator in summary_evaluators:
+ try:
+ summary_eval_result = evaluator(runs, examples)
+ # TODO: Expose public API for this.
+ flattened_results = self.client._select_eval_results(
+ summary_eval_result,
+ fn_name=evaluator.__name__,
+ )
+ aggregate_feedback.extend(flattened_results)
+ if self._upload_results:
+ for result in flattened_results:
+ feedback = result.model_dump(exclude={"target_run_id"})
+ evaluator_info = feedback.pop("evaluator_info", None)
+ executor.submit(
+ self.client.create_feedback,
+ **feedback,
+ run_id=None,
+ project_id=project_id,
+ source_info=evaluator_info,
+ )
+ except Exception as e:
+ logger.error(
+ f"Error running summary evaluator {repr(evaluator)}: {e}",
+ exc_info=True,
+ )
+ yield {"results": aggregate_feedback}
+
+ def _get_dataset_version(self) -> Optional[str]:
+ examples = list(self.examples)
+ modified_at = [ex.modified_at for ex in examples if ex.modified_at]
+ # Should always be defined in practice when fetched,
+ # but the typing permits None
+ max_modified_at = max(modified_at) if modified_at else None
+ return max_modified_at.isoformat() if max_modified_at else None
+
+ def _get_dataset_splits(self) -> Optional[list[str]]:
+ examples = list(self.examples)
+ splits = set()
+ for example in examples:
+ if (
+ example.metadata
+ and example.metadata.get("dataset_split")
+ and isinstance(example.metadata["dataset_split"], list)
+ ):
+ for split in example.metadata["dataset_split"]:
+ if isinstance(split, str):
+ splits.add(split)
+ else:
+ splits.add("base")
+
+ return list(splits)
+
+ def _end(self) -> None:
+ if not self._upload_results:
+ return
+ experiment = self._experiment
+ if experiment is None:
+ raise ValueError("Experiment not started yet.")
+
+ project_metadata = self._get_experiment_metadata()
+ project_metadata["dataset_version"] = self._get_dataset_version()
+ project_metadata["dataset_splits"] = self._get_dataset_splits()
+ self.client.update_project(
+ experiment.id,
+ metadata={
+ **experiment.metadata,
+ **project_metadata,
+ },
+ )
+
+ def _copy(self, *args: Any, **kwargs: Any) -> _ExperimentManager:
+ default_args = (self._data,)
+ default_kwargs = {
+ "experiment": self._experiment,
+ "metadata": self._metadata,
+ "runs": self._runs,
+ "client": self.client,
+ "evaluation_results": self._evaluation_results,
+ "summary_results": self._summary_results,
+ "include_attachments": self._include_attachments,
+ "reuse_attachments": self._reuse_attachments,
+ "upload_results": self._upload_results,
+ "attachment_raw_data_dict": self._attachment_raw_data_dict,
+ "error_handling": self._error_handling,
+ }
+ full_args = list(args) + list(default_args[len(args) :])
+ full_kwargs = {**default_kwargs, **kwargs}
+ return self.__class__(*full_args, **full_kwargs)
+
+
+def _resolve_evaluators(
+ evaluators: Sequence[Union[EVALUATOR_T, RunEvaluator, AEVALUATOR_T]],
+) -> Sequence[RunEvaluator]:
+ results = []
+ for evaluator in evaluators:
+ if isinstance(evaluator, RunEvaluator):
+ results.append(evaluator)
+ else:
+ results.append(run_evaluator(evaluator))
+ return results
+
+
+def _wrap_summary_evaluators(
+ evaluators: Sequence[SUMMARY_EVALUATOR_T],
+) -> list[SUMMARY_EVALUATOR_T]:
+ def _wrap(evaluator: SUMMARY_EVALUATOR_T) -> SUMMARY_EVALUATOR_T:
+ eval_name = getattr(evaluator, "__name__", "BatchEvaluator")
+ evaluator = _normalize_summary_evaluator(evaluator)
+
+ @functools.wraps(evaluator)
+ def _wrapper_inner(
+ runs: Sequence[schemas.Run], examples: Sequence[schemas.Example]
+ ) -> Union[EvaluationResult, EvaluationResults]:
+ @rh.traceable(name=eval_name)
+ def _wrapper_super_inner(
+ runs_: str, examples_: str
+ ) -> Union[EvaluationResult, EvaluationResults]:
+ return evaluator(list(runs), list(examples))
+
+ return _wrapper_super_inner(
+ f"Runs[] (Length={len(runs)})", f"Examples[] (Length={len(examples)})"
+ )
+
+ return _wrapper_inner
+
+ results = []
+ for evaluator in evaluators:
+ results.append(_wrap(evaluator))
+ return results
+
+
+class _ForwardResults(TypedDict):
+ run: schemas.Run
+ example: schemas.Example
+
+
+def _forward(
+ fn: rh.SupportsLangsmithExtra,
+ example: schemas.Example,
+ experiment_name: str,
+ metadata: dict,
+ client: langsmith.Client,
+ upload_results: bool,
+ include_attachments: bool = False,
+ error_handling: Literal["log", "ignore"] = "log",
+) -> _ForwardResults:
+ run: Optional[schemas.RunBase] = None
+
+ def _get_run(r: rt.RunTree) -> None:
+ nonlocal run
+ run = r
+
+ def _set_reference_example_id(r: rt.RunTree) -> None:
+ r.reference_example_id = example.id
+
+ example_version = (example.modified_at or example.created_at).isoformat()
+ langsmith_extra = rh.LangSmithExtra(
+ on_end=_get_run,
+ project_name=experiment_name,
+ metadata={**metadata, "example_version": example_version},
+ client=client,
+ )
+ if error_handling == "log":
+ langsmith_extra["reference_example_id"] = example.id
+ elif error_handling == "ignore":
+ # Only set the reference_example_id if the run succeeds.
+ langsmith_extra["_on_success"] = _set_reference_example_id
+ else:
+ raise ValueError(f"Unrecognized error_handling value: {error_handling=}")
+
+ with rh.tracing_context(enabled="local" if not upload_results else True):
+ try:
+ arg_names = _get_target_args(fn)
+ args = [getattr(example, argn) for argn in arg_names]
+ fn(*args, langsmith_extra=langsmith_extra)
+ # Reset attachment readers if attachments were used.
+ if include_attachments and example.attachments is not None:
+ for attachment in example.attachments:
+ reader = example.attachments[attachment]["reader"]
+ reader.seek(0)
+ except Exception as e:
+ logger.error(
+ f"Error running target function: {e}", exc_info=True, stacklevel=1
+ )
+ return _ForwardResults(run=cast(schemas.Run, run), example=example)
+
+
+def _is_valid_uuid(value: str) -> bool:
+ try:
+ uuid.UUID(value)
+ return True
+ except ValueError:
+ return False
+
+
+def _resolve_data(
+ data: DATA_T,
+ *,
+ client: langsmith.Client,
+ include_attachments: bool = False,
+) -> Iterable[schemas.Example]:
+ """Return the examples for the given dataset."""
+ if isinstance(data, uuid.UUID):
+ return client.list_examples(
+ dataset_id=data, include_attachments=include_attachments
+ )
+ elif isinstance(data, str) and _is_valid_uuid(data):
+ return client.list_examples(
+ dataset_id=uuid.UUID(data), include_attachments=include_attachments
+ )
+ elif isinstance(data, str):
+ return client.list_examples(
+ dataset_name=data, include_attachments=include_attachments
+ )
+ elif isinstance(data, schemas.Dataset):
+ return client.list_examples(
+ dataset_id=data.id, include_attachments=include_attachments
+ )
+ return data
+
+
+def _default_process_inputs(inputs: dict) -> dict:
+ return inputs["inputs"] if "inputs" in inputs else inputs
+
+
+def _ensure_traceable(
+ target: TARGET_T | rh.SupportsLangsmithExtra[[dict], dict] | Runnable,
+) -> rh.SupportsLangsmithExtra[[dict], dict]:
+ """Ensure the target function is traceable."""
+ if not _is_callable(target):
+ raise ValueError(
+ "Target must be a callable function or a langchain/langgraph object. For "
+ "example:\n\n"
+ "def predict(inputs: dict) -> dict:\n"
+ " # do work, like chain.invoke(inputs)\n"
+ " return {...}\n\n"
+ "evaluate(\n"
+ " predict,\n"
+ " ...\n"
+ ")"
+ )
+
+ if rh.is_traceable_function(target):
+ fn: rh.SupportsLangsmithExtra[[dict], dict] = target
+ else:
+ if _is_langchain_runnable(target):
+ target = target.invoke # type: ignore[union-attr]
+ fn = rh.traceable(name="Target", process_inputs=_default_process_inputs)(
+ cast(Callable, target)
+ )
+ return fn
+
+
+def _include_attachments(target: Any, evaluators: Optional[Sequence]) -> bool:
+ return _target_include_attachments(target) or bool(
+ _evaluators_include_attachments(evaluators)
+ )
+
+
+def _evaluators_include_attachments(evaluators: Optional[Sequence]) -> int:
+ if evaluators is None:
+ return 0
+
+ return sum(_evaluator_uses_attachments(e) for e in evaluators)
+
+
+def _evaluator_uses_attachments(evaluator: Any) -> bool:
+ if not callable(evaluator):
+ return False
+ sig = inspect.signature(evaluator)
+ params = list(sig.parameters.values())
+ positional_params = [
+ p for p in params if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)
+ ]
+ return any(p.name == "attachments" for p in positional_params)
+
+
+def _target_include_attachments(target: Any) -> bool:
+ """Whether the target function accepts attachments."""
+ return "attachments" in _get_target_args(target)
+
+
+def _get_target_args(target: Any) -> list[str]:
+ """Whether the target function accepts attachments."""
+ if not callable(target):
+ return []
+ if _is_langchain_runnable(target):
+ return ["inputs"]
+ # Check function signature
+ sig = inspect.signature(target)
+ params = list(sig.parameters.values())
+ positional_params = [
+ p for p in params if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)
+ ]
+ positional_no_default = [p for p in positional_params if p.default is p.empty]
+
+ if len(positional_params) == 0:
+ raise ValueError(
+ "Target function must accept at least one positional argument (inputs)."
+ )
+ elif len(positional_no_default) > 3:
+ raise ValueError(
+ "Target function must accept at most three "
+ "arguments without default values: (inputs, attachments, metadata)."
+ )
+ elif len(positional_no_default) > 1 and {
+ p.name for p in positional_no_default
+ }.difference(["inputs", "attachments", "metadata"]):
+ raise ValueError(
+ "When passing multiple positional arguments without default values, they "
+ "must be named 'inputs', 'attachments', or 'metadata'. Received: "
+ f"{[p.name for p in positional_no_default]}"
+ )
+ else:
+ args = []
+ for p in positional_params[:3]:
+ if p.name in {"inputs", "attachments", "metadata"}:
+ args.append(p.name)
+ else:
+ break
+ return args or ["inputs"]
+
+
+def _resolve_experiment(
+ experiment: Optional[Union[schemas.TracerSession, str, uuid.UUID]],
+ runs: Optional[Iterable[schemas.Run]],
+ client: langsmith.Client,
+) -> tuple[
+ Optional[Union[schemas.TracerSession, str]], Optional[Iterable[schemas.Run]]
+]:
+ # TODO: Remove this, handle outside the manager
+ if experiment is not None:
+ if isinstance(experiment, schemas.TracerSession):
+ experiment_ = experiment
+ else:
+ experiment_ = _load_experiment(experiment, client)
+
+ if not experiment_.name:
+ raise ValueError("Experiment name must be defined if provided.")
+ if not experiment_.reference_dataset_id:
+ raise ValueError(
+ "Experiment must have an associated reference_dataset_id, "
+ "but none was provided."
+ )
+ return experiment_, runs
+ # If we have runs, that means the experiment was already started.
+ if runs is not None:
+ runs_, runs = itertools.tee(runs)
+ first_run = next(runs_)
+ experiment_ = client.read_project(project_id=first_run.session_id)
+ if not experiment_.name:
+ raise ValueError("Experiment name not found for provided runs.")
+ return experiment_, runs
+ return None, None
+
+
+def _get_random_name() -> str:
+ from langsmith.evaluation._name_generation import random_name # noqa: F401
+
+ return random_name()
+
+
+def _extract_feedback_keys(evaluator: RunEvaluator):
+ if isinstance(evaluator, DynamicRunEvaluator):
+ if getattr(evaluator, "func", None):
+ return _extract_code_evaluator_feedback_keys(evaluator.func)
+ elif getattr(evaluator, "afunc", None):
+ return _extract_code_evaluator_feedback_keys(evaluator.afunc)
+ # TODO: Support for DynamicComparisonRunEvaluator
+ if hasattr(evaluator, "evaluator"):
+ # LangChainStringEvaluator
+ if getattr(getattr(evaluator, "evaluator"), "evaluation_name", None):
+ return [evaluator.evaluator.evaluation_name]
+ return []
+
+
+def _extract_code_evaluator_feedback_keys(func: Callable) -> list[str]:
+ python_code = inspect.getsource(func)
+
+ def extract_dict_keys(node):
+ if isinstance(node, ast.Dict):
+ keys = []
+ key_value = None
+ for key, value in zip(node.keys, node.values):
+ if isinstance(key, _AST_STR_TYPES):
+ key_str = _get_str_value(key)
+ if key_str == "key" and isinstance(value, _AST_STR_TYPES):
+ key_value = _get_str_value(value)
+ return [key_value] if key_value else keys
+ elif (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "dict"
+ ):
+ for keyword in node.keywords:
+ if keyword.arg == "key" and isinstance(keyword.value, _AST_STR_TYPES):
+ return [_get_str_value(keyword.value)]
+ return []
+
+ def extract_evaluation_result_key(node):
+ if (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "EvaluationResult"
+ ):
+ for keyword in node.keywords:
+ if keyword.arg == "key" and isinstance(keyword.value, _AST_STR_TYPES):
+ return [_get_str_value(keyword.value)]
+ return []
+
+ def extract_evaluation_results_keys(node, variables):
+ if (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "EvaluationResults"
+ ):
+ for keyword in node.keywords:
+ if keyword.arg == "results":
+ if isinstance(keyword.value, ast.Name):
+ return variables.get(keyword.value.id, [])
+ elif isinstance(keyword.value, ast.List):
+ keys = []
+ for elt in keyword.value.elts:
+ keys.extend(extract_evaluation_result_key(elt))
+ return keys
+ elif isinstance(node, ast.Dict):
+ for key, value in zip(node.keys, node.values):
+ if isinstance(key, _AST_STR_TYPES) and _get_str_value(key) == "results":
+ if isinstance(value, ast.List):
+ keys = []
+ for elt in value.elts:
+ if isinstance(elt, ast.Dict):
+ for elt_key, elt_value in zip(elt.keys, elt.values):
+ if (
+ isinstance(elt_key, _AST_STR_TYPES)
+ and _get_str_value(elt_key) == "key"
+ ):
+ if isinstance(elt_value, _AST_STR_TYPES):
+ keys.append(_get_str_value(elt_value))
+ elif (
+ isinstance(elt, ast.Call)
+ and isinstance(elt.func, ast.Name)
+ and elt.func.id in ("EvaluationResult", "dict")
+ ):
+ for keyword in elt.keywords:
+ if keyword.arg == "key" and isinstance(
+ keyword.value, _AST_STR_TYPES
+ ):
+ keys.append(_get_str_value(keyword.value))
+
+ return keys
+ return []
+
+ python_code = textwrap.dedent(python_code)
+
+ try:
+ tree = ast.parse(python_code)
+ function_def = tree.body[0]
+ if not isinstance(function_def, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ return []
+
+ variables = {}
+ keys = []
+
+ for node in ast.walk(function_def):
+ if isinstance(node, ast.Assign):
+ if isinstance(node.value, ast.List):
+ list_keys = []
+ for elt in node.value.elts:
+ list_keys.extend(extract_evaluation_result_key(elt))
+ if isinstance(node.targets[0], ast.Name):
+ variables[node.targets[0].id] = list_keys
+ elif isinstance(node, ast.Return) and node.value is not None:
+ dict_keys = extract_dict_keys(node.value)
+ eval_result_key = extract_evaluation_result_key(node.value)
+ eval_results_keys = extract_evaluation_results_keys(
+ node.value, variables
+ )
+
+ keys.extend(dict_keys)
+ keys.extend(eval_result_key)
+ keys.extend(eval_results_keys)
+
+ # If no keys found, return the function name
+ return keys if keys else [function_def.name]
+
+ except SyntaxError:
+ return []
+
+
+def _to_pandas(
+ results: list[ExperimentResultRow],
+ start: Optional[int] = 0,
+ end: Optional[int] = None,
+):
+ try:
+ import pandas as pd
+ except ImportError as e:
+ raise ImportError(
+ "The 'pandas' library is required to use the 'to_pandas' function. "
+ "Please install it using 'pip install pandas' or "
+ "'conda install pandas' before calling this method."
+ ) from e
+
+ return pd.DataFrame(_flatten_experiment_results(results, start=start, end=end))
+
+
+def _flatten_experiment_results(
+ results: list[ExperimentResultRow],
+ start: Optional[int] = 0,
+ end: Optional[int] = None,
+):
+ return [
+ {
+ **{f"inputs.{k}": v for k, v in (x["example"].inputs or {}).items()},
+ **{f"outputs.{k}": v for k, v in (x["run"].outputs or {}).items()},
+ "error": x["run"].error,
+ **(
+ {f"reference.{k}": v for k, v in x["example"].outputs.items()}
+ if x["example"].outputs is not None
+ else {}
+ ),
+ **{
+ f"feedback.{r.key}": r.score if r.score is not None else r.value
+ for r in x["evaluation_results"]["results"]
+ },
+ "execution_time": (
+ (x["run"].end_time - x["run"].start_time).total_seconds()
+ if x["run"].end_time
+ else None
+ ),
+ "example_id": x["run"].reference_example_id,
+ "id": x["run"].id,
+ }
+ for x in results[start:end]
+ ]
+
+
+@functools.lru_cache(maxsize=1)
+def _import_langchain_runnable() -> Optional[type]:
+ try:
+ from langchain_core.runnables import Runnable
+
+ return Runnable
+ except ImportError:
+ return None
+
+
+def _is_langchain_runnable(o: Any) -> bool:
+ return bool((Runnable := _import_langchain_runnable()) and isinstance(o, Runnable))
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/evaluator.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/evaluator.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c2e75d2d217e2bbd5eb2579931fa3075be423c5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/evaluator.py
@@ -0,0 +1,1001 @@
+"""This module contains the evaluator classes for evaluating runs."""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import logging
+import uuid
+from abc import abstractmethod
+from collections.abc import Awaitable, Sequence
+from functools import wraps
+from typing import (
+ Any,
+ Callable,
+ Literal,
+ Optional,
+ Union,
+ cast,
+)
+
+from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
+from typing_extensions import TypedDict
+
+from langsmith import run_helpers as rh
+from langsmith import schemas
+from langsmith.schemas import SCORE_TYPE, VALUE_TYPE, Example, Run
+
+logger = logging.getLogger(__name__)
+
+
+class Category(TypedDict):
+ """A category for categorical feedback."""
+
+ value: Optional[Union[float, int]]
+ """The numeric score/ordinal corresponding to this category."""
+ label: str
+ """The label for this category."""
+
+
+class FeedbackConfig(TypedDict, total=False):
+ """Configuration to define a type of feedback.
+
+ Applied on on the first creation of a `feedback_key`.
+ """
+
+ type: Literal["continuous", "categorical", "freeform"]
+ """The type of feedback."""
+ min: Optional[Union[float, int]]
+ """The minimum permitted value (if continuous type)."""
+ max: Optional[Union[float, int]]
+ """The maximum value permitted value (if continuous type)."""
+ categories: Optional[list[Union[Category, dict]]]
+
+
+class EvaluationResult(BaseModel):
+ """Evaluation result."""
+
+ key: str
+ """The aspect, metric name, or label for this evaluation."""
+ score: SCORE_TYPE = None
+ """The numeric score for this evaluation."""
+ value: VALUE_TYPE = None
+ """The value for this evaluation, if not numeric."""
+ metadata: Optional[dict] = None
+ """Arbitrary metadata attached to the evaluation."""
+ comment: Optional[str] = None
+ """An explanation regarding the evaluation."""
+ correction: Optional[dict] = None
+ """What the correct value should be, if applicable."""
+ evaluator_info: dict = Field(default_factory=dict)
+ """Additional information about the evaluator."""
+ feedback_config: Optional[Union[FeedbackConfig, dict]] = None
+ """The configuration used to generate this feedback."""
+ source_run_id: Optional[Union[uuid.UUID, str]] = None
+ """The ID of the trace of the evaluator itself."""
+ target_run_id: Optional[Union[uuid.UUID, str]] = None
+ """The ID of the trace this evaluation is applied to.
+
+ If none provided, the evaluation feedback is applied to the
+ root trace being."""
+ extra: Optional[dict] = None
+ """Metadata for the evaluator run."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ @model_validator(mode="after")
+ def check_value_non_numeric(self) -> EvaluationResult:
+ """Warn when numeric values are passed via the `value` field."""
+ if self.score is None and isinstance(self.value, (int, float)):
+ logger.warning(
+ "Numeric values should be provided in the 'score' field, not 'value'."
+ f" Got: {self.value}"
+ )
+ return self
+
+
+class EvaluationResults(TypedDict, total=False):
+ """Batch evaluation results.
+
+ This makes it easy for your evaluator to return multiple
+ metrics at once.
+ """
+
+ results: list[EvaluationResult]
+ """The evaluation results."""
+
+
+class RunEvaluator:
+ """Evaluator interface class."""
+
+ @abstractmethod
+ def evaluate_run(
+ self,
+ run: Run,
+ example: Optional[Example] = None,
+ evaluator_run_id: Optional[uuid.UUID] = None,
+ ) -> Union[EvaluationResult, EvaluationResults]:
+ """Evaluate an example."""
+
+ async def aevaluate_run(
+ self,
+ run: Run,
+ example: Optional[Example] = None,
+ evaluator_run_id: Optional[uuid.UUID] = None,
+ ) -> Union[EvaluationResult, EvaluationResults]:
+ """Evaluate an example asynchronously."""
+ current_context = rh.get_tracing_context()
+
+ def _run_with_context():
+ with rh.tracing_context(**current_context):
+ return self.evaluate_run(run, example, evaluator_run_id)
+
+ return await asyncio.get_running_loop().run_in_executor(None, _run_with_context)
+
+
+_RUNNABLE_OUTPUT = Union[EvaluationResult, EvaluationResults, dict]
+
+
+class ComparisonEvaluationResult(BaseModel):
+ """Feedback scores for the results of comparative evaluations.
+
+ These are generated by functions that compare two or more runs,
+ returning a ranking or other feedback.
+ """
+
+ key: str
+ """The aspect, metric name, or label for this evaluation."""
+ scores: dict[Union[uuid.UUID, str], SCORE_TYPE]
+ """The scores for each run in the comparison."""
+ source_run_id: Optional[Union[uuid.UUID, str]] = None
+ """The ID of the trace of the evaluator itself."""
+ comment: Optional[Union[str, dict[Union[uuid.UUID, str], str]]] = None
+ """Comment for the scores. If a string, it's shared across all target runs.
+
+ If a `dict`, it maps run IDs to individual comments.
+ """
+
+
+_COMPARISON_OUTPUT = Union[ComparisonEvaluationResult, dict]
+
+
+class DynamicRunEvaluator(RunEvaluator):
+ """A dynamic evaluator that wraps a function and transforms it into a `RunEvaluator`.
+
+ This class is designed to be used with the `@run_evaluator` decorator, allowing
+ functions that take a `Run` and an optional `Example` as arguments, and return
+ an `EvaluationResult` or `EvaluationResults`, to be used as instances of `RunEvaluator`.
+
+ Attributes:
+ func (Callable): The function that is wrapped by this evaluator.
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ func: Callable[
+ [Run, Optional[Example]],
+ Union[_RUNNABLE_OUTPUT, Awaitable[_RUNNABLE_OUTPUT]],
+ ],
+ # Async function to be used for async evaluation. Optional
+ afunc: Optional[
+ Callable[
+ [Run, Optional[Example]],
+ Awaitable[_RUNNABLE_OUTPUT],
+ ]
+ ] = None,
+ ):
+ """Initialize the `DynamicRunEvaluator` with a given function.
+
+ Args:
+ func (Callable): A function that takes a `Run` and an optional `Example` as
+ arguments, and returns a dict or `ComparisonEvaluationResult`.
+ """
+ (func, prepare_inputs) = _normalize_evaluator_func(func)
+ if afunc:
+ (afunc, prepare_inputs) = _normalize_evaluator_func(afunc) # type: ignore[assignment]
+
+ def process_inputs(inputs: dict) -> dict:
+ if prepare_inputs is None:
+ return inputs
+ (_, _, traced_inputs) = prepare_inputs(
+ inputs.get("run"), inputs.get("example")
+ )
+ return traced_inputs
+
+ wraps(func)(self)
+ from langsmith import run_helpers # type: ignore
+
+ if afunc is not None:
+ self.afunc = run_helpers.ensure_traceable(
+ afunc, process_inputs=process_inputs
+ )
+ self._name = getattr(afunc, "__name__", "DynamicRunEvaluator")
+ if inspect.iscoroutinefunction(func):
+ if afunc is not None:
+ raise TypeError(
+ "Func was provided as a coroutine function, but afunc was "
+ "also provided. If providing both, func should be a regular "
+ "function to avoid ambiguity."
+ )
+ self.afunc = run_helpers.ensure_traceable(
+ func, process_inputs=process_inputs
+ )
+ self._name = getattr(func, "__name__", "DynamicRunEvaluator")
+ else:
+ self.func = run_helpers.ensure_traceable(
+ cast(Callable[[Run, Optional[Example]], _RUNNABLE_OUTPUT], func),
+ process_inputs=process_inputs,
+ )
+ self._name = getattr(func, "__name__", "DynamicRunEvaluator")
+
+ def _coerce_evaluation_result(
+ self,
+ result: Union[EvaluationResult, dict],
+ source_run_id: uuid.UUID,
+ allow_no_key: bool = False,
+ ) -> EvaluationResult:
+ if isinstance(result, EvaluationResult):
+ if not result.source_run_id:
+ result.source_run_id = source_run_id
+ return result
+ try:
+ if not result:
+ raise ValueError(
+ "Expected an EvaluationResult object, or dict with a metric"
+ f" 'key' and optional 'score'; got empty result: {result}"
+ )
+ if "key" not in result and allow_no_key:
+ result["key"] = self._name
+ if all(k not in result for k in ("score", "value", "comment")):
+ raise ValueError(
+ "Expected an EvaluationResult object, or dict with a metric"
+ f" 'key' and optional 'score' or categorical 'value'; got {result}"
+ )
+ return EvaluationResult(**{"source_run_id": source_run_id, **result})
+ except ValidationError as e:
+ raise ValueError(
+ "Expected an EvaluationResult object, or dict with a metric"
+ f" 'key' and optional 'score'; got {result}"
+ ) from e
+
+ def _coerce_evaluation_results(
+ self,
+ results: Union[dict, EvaluationResults],
+ source_run_id: uuid.UUID,
+ ) -> Union[EvaluationResult, EvaluationResults]:
+ if "results" in results:
+ cp = results.copy()
+ cp["results"] = [
+ self._coerce_evaluation_result(r, source_run_id=source_run_id)
+ for r in results["results"]
+ ]
+ return EvaluationResults(**cp)
+
+ return self._coerce_evaluation_result(
+ cast(dict, results), source_run_id=source_run_id, allow_no_key=True
+ )
+
+ def _format_result(
+ self,
+ result: Union[
+ EvaluationResult, EvaluationResults, dict, str, int, bool, float, list
+ ],
+ source_run_id: uuid.UUID,
+ ) -> Union[EvaluationResult, EvaluationResults]:
+ if isinstance(result, EvaluationResult):
+ if not result.source_run_id:
+ result.source_run_id = source_run_id
+ return result
+ result = _format_evaluator_result(result)
+ return self._coerce_evaluation_results(result, source_run_id)
+
+ @property
+ def is_async(self) -> bool:
+ """Check if the evaluator function is asynchronous.
+
+ Returns:
+ bool: `True` if the evaluator function is asynchronous, `False` otherwise.
+ """
+ return hasattr(self, "afunc")
+
+ def evaluate_run(
+ self,
+ run: Run,
+ example: Optional[Example] = None,
+ evaluator_run_id: Optional[uuid.UUID] = None,
+ ) -> Union[EvaluationResult, EvaluationResults]:
+ """Evaluate a run using the wrapped function.
+
+ This method directly invokes the wrapped function with the provided arguments.
+
+ Args:
+ run (Run): The run to be evaluated.
+ example (Optional[Example]): An optional example to be used in the evaluation.
+
+ Returns:
+ Union[EvaluationResult, EvaluationResults]: The result of the evaluation.
+ """ # noqa: E501
+ if not hasattr(self, "func"):
+ running_loop = asyncio.get_event_loop()
+ if running_loop.is_running():
+ raise RuntimeError(
+ "Cannot call `evaluate_run` on an async run evaluator from"
+ " within an running event loop. Use `aevaluate_run` instead."
+ )
+ else:
+ return running_loop.run_until_complete(self.aevaluate_run(run, example))
+ if evaluator_run_id is None:
+ evaluator_run_id = uuid.uuid4()
+ metadata: dict[str, Any] = {"target_run_id": run.id}
+ if getattr(run, "session_id", None):
+ metadata["experiment"] = str(run.session_id)
+ result = self.func(
+ run,
+ example,
+ langsmith_extra={"run_id": evaluator_run_id, "metadata": metadata},
+ )
+ return self._format_result(result, evaluator_run_id)
+
+ async def aevaluate_run(
+ self,
+ run: Run,
+ example: Optional[Example] = None,
+ evaluator_run_id: Optional[uuid.UUID] = None,
+ ):
+ """Evaluate a run asynchronously using the wrapped async function.
+
+ This method directly invokes the wrapped async function with the
+ provided arguments.
+
+ Args:
+ run (Run): The run to be evaluated.
+ example (Optional[Example]): An optional example to be used
+ in the evaluation.
+
+ Returns:
+ Union[EvaluationResult, EvaluationResults]: The result of the evaluation.
+ """
+ if not hasattr(self, "afunc"):
+ return await super().aevaluate_run(run, example)
+ if evaluator_run_id is None:
+ evaluator_run_id = uuid.uuid4()
+ metadata: dict[str, Any] = {"target_run_id": run.id}
+ if getattr(run, "session_id", None):
+ metadata["experiment"] = str(run.session_id)
+ result = await self.afunc(
+ run,
+ example,
+ langsmith_extra={"run_id": evaluator_run_id, "metadata": metadata},
+ )
+ return self._format_result(result, evaluator_run_id)
+
+ def __call__(
+ self, run: Run, example: Optional[Example] = None
+ ) -> Union[EvaluationResult, EvaluationResults]:
+ """Make the evaluator callable, allowing it to be used like a function.
+
+ This method enables the evaluator instance to be called directly, forwarding the
+ call to `evaluate_run`.
+
+ Args:
+ run (Run): The run to be evaluated.
+ example (Optional[Example]): An optional example to be used in the evaluation.
+
+ Returns:
+ Union[EvaluationResult, EvaluationResults]: The result of the evaluation.
+ """ # noqa: E501
+ return self.evaluate_run(run, example)
+
+ def __repr__(self) -> str:
+ """Represent the DynamicRunEvaluator object."""
+ return f""
+
+
+def run_evaluator(
+ func: Callable[
+ [Run, Optional[Example]], Union[_RUNNABLE_OUTPUT, Awaitable[_RUNNABLE_OUTPUT]]
+ ],
+):
+ """Create a run evaluator from a function.
+
+ Decorator that transforms a function into a `RunEvaluator`.
+ """
+ return DynamicRunEvaluator(func)
+
+
+_MAXSIZE = 10_000
+
+
+def _maxsize_repr(obj: Any):
+ s = repr(obj)
+ if len(s) > _MAXSIZE:
+ s = s[: _MAXSIZE - 4] + "...)"
+ return s
+
+
+class DynamicComparisonRunEvaluator:
+ """Compare predictions (as traces) from 2 or more runs."""
+
+ def __init__(
+ self,
+ func: Callable[
+ [Sequence[Run], Optional[Example]],
+ Union[_COMPARISON_OUTPUT, Awaitable[_COMPARISON_OUTPUT]],
+ ],
+ # Async function to be used for async evaluation. Optional
+ afunc: Optional[
+ Callable[
+ [Sequence[Run], Optional[Example]],
+ Awaitable[_COMPARISON_OUTPUT],
+ ]
+ ] = None,
+ ):
+ """Initialize the `DynamicRunEvaluator` with a given function.
+
+ Args:
+ func (Callable): A function that takes a `Run` and an optional `Example` as
+ arguments, and returns an `EvaluationResult` or `EvaluationResults`.
+ """
+ (func, prepare_inputs) = _normalize_comparison_evaluator_func(func)
+ if afunc:
+ (afunc, prepare_inputs) = _normalize_comparison_evaluator_func(afunc) # type: ignore[assignment]
+
+ def process_inputs(inputs: dict) -> dict:
+ if prepare_inputs is None:
+ return inputs
+ (_, _, traced_inputs) = prepare_inputs(
+ inputs.get("runs"), inputs.get("example")
+ )
+ return traced_inputs
+
+ wraps(func)(self)
+ from langsmith import run_helpers # type: ignore
+
+ if afunc is not None:
+ self.afunc = run_helpers.ensure_traceable(
+ afunc, process_inputs=process_inputs
+ )
+ self._name = getattr(afunc, "__name__", "DynamicRunEvaluator")
+ if inspect.iscoroutinefunction(func):
+ if afunc is not None:
+ raise TypeError(
+ "Func was provided as a coroutine function, but afunc was "
+ "also provided. If providing both, func should be a regular "
+ "function to avoid ambiguity."
+ )
+ self.afunc = run_helpers.ensure_traceable(
+ func, process_inputs=process_inputs
+ )
+ self._name = getattr(func, "__name__", "DynamicRunEvaluator")
+ else:
+ self.func = run_helpers.ensure_traceable(
+ cast(
+ Callable[
+ [Sequence[Run], Optional[Example]],
+ _COMPARISON_OUTPUT,
+ ],
+ func,
+ ),
+ process_inputs=process_inputs,
+ )
+ self._name = getattr(func, "__name__", "DynamicRunEvaluator")
+
+ @property
+ def is_async(self) -> bool:
+ """Check if the evaluator function is asynchronous.
+
+ Returns:
+ bool: `True` if the evaluator function is asynchronous, `False` otherwise.
+ """
+ return hasattr(self, "afunc")
+
+ def compare_runs(
+ self, runs: Sequence[Run], example: Optional[Example] = None
+ ) -> ComparisonEvaluationResult:
+ """Compare runs to score preferences.
+
+ Args:
+ runs: A list of runs to compare.
+ example: An optional example to be used in the evaluation.
+
+ """ # noqa: E501
+ if not hasattr(self, "func"):
+ running_loop = asyncio.get_event_loop()
+ if running_loop.is_running():
+ raise RuntimeError(
+ "Cannot call `evaluate_run` on an async run evaluator from"
+ " within an running event loop. Use `aevaluate_run` instead."
+ )
+ else:
+ return running_loop.run_until_complete(
+ self.acompare_runs(runs, example)
+ )
+ source_run_id = uuid.uuid4()
+ tags = self._get_tags(runs)
+ # TODO: Add metadata for the "comparison experiment" here
+ result = self.func(
+ runs,
+ example,
+ langsmith_extra={"run_id": source_run_id, "tags": tags},
+ )
+ return self._format_results(result, source_run_id, runs)
+
+ async def acompare_runs(
+ self, runs: Sequence[Run], example: Optional[Example] = None
+ ) -> ComparisonEvaluationResult:
+ """Evaluate a run asynchronously using the wrapped async function.
+
+ This method directly invokes the wrapped async function with the
+ provided arguments.
+
+ Args:
+ runs (Run): The runs to be evaluated.
+ example (Optional[Example]): An optional example to be used
+ in the evaluation.
+
+ Returns:
+ ComparisonEvaluationResult: The result of the evaluation.
+ """
+ if not hasattr(self, "afunc"):
+ return self.compare_runs(runs, example)
+ source_run_id = uuid.uuid4()
+ tags = self._get_tags(runs)
+ # TODO: Add metadata for the "comparison experiment" here
+ result = await self.afunc(
+ runs,
+ example,
+ langsmith_extra={"run_id": source_run_id, "tags": tags},
+ )
+ return self._format_results(result, source_run_id, runs)
+
+ def __call__(
+ self, runs: Sequence[Run], example: Optional[Example] = None
+ ) -> ComparisonEvaluationResult:
+ """Make the evaluator callable, allowing it to be used like a function.
+
+ This method enables the evaluator instance to be called directly, forwarding the
+ call to `evaluate_run`.
+
+ Args:
+ run (Run): The run to be evaluated.
+ example (Optional[Example]): An optional example to be used in the evaluation.
+
+ Returns:
+ ComparisonEvaluationResult: The result of the evaluation.
+ """ # noqa: E501
+ return self.compare_runs(runs, example)
+
+ def __repr__(self) -> str:
+ """Represent the DynamicRunEvaluator object."""
+ return f""
+
+ @staticmethod
+ def _get_tags(runs: Sequence[Run]) -> list[str]:
+ """Extract tags from runs."""
+ # Add tags to support filtering
+ tags = []
+ for run in runs:
+ tags.append("run:" + str(run.id))
+ if getattr(run, "session_id", None):
+ tags.append("experiment:" + str(run.session_id))
+ return tags
+
+ def _format_results(
+ self,
+ result: Union[dict, list, ComparisonEvaluationResult],
+ source_run_id: uuid.UUID,
+ runs: Sequence[Run],
+ ) -> ComparisonEvaluationResult:
+ if isinstance(result, ComparisonEvaluationResult):
+ if not result.source_run_id:
+ result.source_run_id = source_run_id
+ return result
+ elif isinstance(result, list):
+ result = {
+ "scores": {run.id: score for run, score in zip(runs, result)},
+ "key": self._name,
+ "source_run_id": source_run_id,
+ }
+ elif isinstance(result, dict):
+ if "key" not in result:
+ result["key"] = self._name
+ else:
+ msg = (
+ "Expected 'dict', 'list' or 'ComparisonEvaluationResult' result "
+ f"object. Received: {result=}"
+ )
+ raise ValueError(msg)
+ try:
+ return ComparisonEvaluationResult(
+ **{"source_run_id": source_run_id, **result}
+ )
+ except ValidationError as e:
+ raise ValueError(
+ f"Expected a dictionary with a 'key' and dictionary of scores mapping"
+ "run IDs to numeric scores, or ComparisonEvaluationResult object,"
+ f" got {result}"
+ ) from e
+
+
+def comparison_evaluator(
+ func: Callable[
+ [Sequence[Run], Optional[Example]],
+ Union[_COMPARISON_OUTPUT, Awaitable[_COMPARISON_OUTPUT]],
+ ],
+) -> DynamicComparisonRunEvaluator:
+ """Create a comaprison evaluator from a function."""
+ return DynamicComparisonRunEvaluator(func)
+
+
+def _normalize_evaluator_func(
+ func: Callable,
+) -> tuple[
+ Union[
+ Callable[[Run, Optional[Example]], _RUNNABLE_OUTPUT],
+ Callable[[Run, Optional[Example]], Awaitable[_RUNNABLE_OUTPUT]],
+ ],
+ Optional[Callable[..., dict]],
+]:
+ supported_args = (
+ "run",
+ "example",
+ "inputs",
+ "outputs",
+ "reference_outputs",
+ "attachments",
+ )
+ sig = inspect.signature(func)
+ all_args = [pname for pname, p in sig.parameters.items() if p.kind != p.VAR_KEYWORD]
+ args_with_defaults = [
+ pname
+ for pname, p in sig.parameters.items()
+ if p.default is not inspect.Parameter.empty
+ ]
+ if not all_args or (
+ not all(
+ pname in supported_args or pname in args_with_defaults for pname in all_args
+ )
+ and len([a for a in all_args if a not in args_with_defaults]) != 2
+ ):
+ msg = (
+ f"Invalid evaluator function. Must have at least one "
+ f"argument. Supported arguments are {supported_args}. Please "
+ f"see https://docs.smith.langchain.com/evaluation/how_to_guides/evaluation/evaluate_llm_application#use-custom-evaluators"
+ # noqa: E501
+ )
+ raise ValueError(msg)
+ # For backwards compatibility we assume custom arg names are Run and Example
+ # types, respectively.
+ elif not all(
+ pname in supported_args or pname in args_with_defaults for pname in all_args
+ ) or all_args == [
+ "run",
+ "example",
+ ]:
+ return func, None
+ else:
+ if inspect.iscoroutinefunction(func):
+
+ def _prepare_inputs(
+ run: Run, example: Optional[Example]
+ ) -> tuple[list, dict, dict]:
+ arg_map = {
+ "run": run,
+ "example": example,
+ "inputs": example.inputs if example else {},
+ "outputs": run.outputs or {},
+ "attachments": example.attachments or {} if example else {},
+ "reference_outputs": example.outputs or {} if example else {},
+ }
+ kwargs = {}
+ args = []
+ traced_inputs = {}
+ for param_name, param in sig.parameters.items():
+ # Could have params with defaults that are not in the arg map
+ if param_name in arg_map:
+ if param.kind in (
+ param.POSITIONAL_OR_KEYWORD,
+ param.POSITIONAL_ONLY,
+ ):
+ args.append(arg_map[param_name])
+ else:
+ kwargs[param_name] = arg_map[param_name]
+ traced_inputs[param_name] = (
+ _maxsize_repr(arg_map[param_name])
+ if param_name in ("run", "example")
+ else arg_map[param_name]
+ )
+ return args, kwargs, traced_inputs
+
+ async def awrapper(
+ run: Run, example: Optional[Example]
+ ) -> _RUNNABLE_OUTPUT:
+ (args, kwargs, _) = _prepare_inputs(run, example)
+ return await func(*args, **kwargs)
+
+ awrapper.__name__ = (
+ getattr(func, "__name__")
+ if hasattr(func, "__name__")
+ else awrapper.__name__
+ )
+ return (awrapper, _prepare_inputs) # type: ignore[return-value]
+
+ else:
+
+ def _prepare_inputs(
+ run: Run, example: Optional[Example]
+ ) -> tuple[list, dict, dict]:
+ arg_map = {
+ "run": run,
+ "example": example,
+ "inputs": example.inputs if example else {},
+ "outputs": run.outputs or {},
+ "attachments": example.attachments or {} if example else {},
+ "reference_outputs": example.outputs or {} if example else {},
+ }
+ kwargs = {}
+ args = []
+ traced_inputs = {}
+ for param_name, param in sig.parameters.items():
+ # Could have params with defaults that are not in the arg map
+ if param_name in arg_map:
+ if param.kind in (
+ param.POSITIONAL_OR_KEYWORD,
+ param.POSITIONAL_ONLY,
+ ):
+ args.append(arg_map[param_name])
+ else:
+ kwargs[param_name] = arg_map[param_name]
+ traced_inputs[param_name] = (
+ _maxsize_repr(arg_map[param_name])
+ if param_name in ("run", "example")
+ else arg_map[param_name]
+ )
+ return args, kwargs, traced_inputs
+
+ def wrapper(run: Run, example: Optional[Example]) -> _RUNNABLE_OUTPUT:
+ (args, kwargs, _) = _prepare_inputs(run, example)
+ return func(*args, **kwargs)
+
+ wrapper.__name__ = (
+ getattr(func, "__name__")
+ if hasattr(func, "__name__")
+ else wrapper.__name__
+ )
+ return (wrapper, _prepare_inputs) # type: ignore[return-value]
+
+
+def _normalize_comparison_evaluator_func(
+ func: Callable,
+) -> tuple[
+ Union[
+ Callable[[Sequence[Run], Optional[Example]], _COMPARISON_OUTPUT],
+ Callable[[Sequence[Run], Optional[Example]], Awaitable[_COMPARISON_OUTPUT]],
+ ],
+ Optional[Callable[..., dict]],
+]:
+ supported_args = ("runs", "example", "inputs", "outputs", "reference_outputs")
+ sig = inspect.signature(func)
+ all_args = [pname for pname, p in sig.parameters.items() if p.kind != p.VAR_KEYWORD]
+ args_with_defaults = [
+ pname
+ for pname, p in sig.parameters.items()
+ if p.default is not inspect.Parameter.empty
+ ]
+ if not all_args or (
+ not all(
+ pname in supported_args or pname in args_with_defaults for pname in all_args
+ )
+ and len([a for a in all_args if a not in args_with_defaults]) != 2
+ ):
+ msg = (
+ f"Invalid evaluator function. Must have at least one "
+ f"argument. Supported arguments are {supported_args}. Please "
+ f"see https://docs.smith.langchain.com/evaluation/how_to_guides/evaluation/evaluate_llm_application#use-custom-evaluators"
+ # noqa: E501
+ )
+ raise ValueError(msg)
+ # For backwards compatibility we assume custom arg names are List[Run] and
+ # List[Example] types, respectively.
+ elif not all(
+ pname in supported_args or pname in args_with_defaults for pname in all_args
+ ) or all_args == [
+ "runs",
+ "example",
+ ]:
+ return func, None
+ else:
+ if inspect.iscoroutinefunction(func):
+
+ def _prepare_inputs(
+ runs: Sequence[Run], example: Optional[Example]
+ ) -> tuple[list, dict, dict]:
+ arg_map = {
+ "runs": runs,
+ "example": example,
+ "inputs": example.inputs if example else {},
+ "outputs": [run.outputs or {} for run in runs],
+ "reference_outputs": example.outputs or {} if example else {},
+ }
+ kwargs = {}
+ args = []
+ traced_inputs = {}
+ for param_name, param in sig.parameters.items():
+ # Could have params with defaults that are not in the arg map
+ if param_name in arg_map:
+ if param.kind in (
+ param.POSITIONAL_OR_KEYWORD,
+ param.POSITIONAL_ONLY,
+ ):
+ args.append(arg_map[param_name])
+ else:
+ kwargs[param_name] = arg_map[param_name]
+ traced_inputs[param_name] = (
+ _maxsize_repr(arg_map[param_name])
+ if param_name in ("runs", "example")
+ else arg_map[param_name]
+ )
+ return args, kwargs, traced_inputs
+
+ async def awrapper(
+ runs: Sequence[Run], example: Optional[Example]
+ ) -> _COMPARISON_OUTPUT:
+ (args, kwargs, _) = _prepare_inputs(runs, example)
+ return await func(*args, **kwargs)
+
+ awrapper.__name__ = (
+ getattr(func, "__name__")
+ if hasattr(func, "__name__")
+ else awrapper.__name__
+ )
+ return awrapper, _prepare_inputs # type: ignore[return-value]
+
+ else:
+
+ def _prepare_inputs(
+ runs: Sequence[Run], example: Optional[Example]
+ ) -> tuple[list, dict, dict]:
+ arg_map = {
+ "runs": runs,
+ "example": example,
+ "inputs": example.inputs if example else {},
+ "outputs": [run.outputs or {} for run in runs],
+ "reference_outputs": example.outputs or {} if example else {},
+ }
+ kwargs = {}
+ args = []
+ traced_inputs = {}
+ for param_name, param in sig.parameters.items():
+ # Could have params with defaults that are not in the arg map
+ if param_name in arg_map:
+ if param.kind in (
+ param.POSITIONAL_OR_KEYWORD,
+ param.POSITIONAL_ONLY,
+ ):
+ args.append(arg_map[param_name])
+ else:
+ kwargs[param_name] = arg_map[param_name]
+ traced_inputs[param_name] = (
+ _maxsize_repr(arg_map[param_name])
+ if param_name in ("runs", "example")
+ else arg_map[param_name]
+ )
+ return args, kwargs, traced_inputs
+
+ def wrapper(
+ runs: Sequence[Run], example: Optional[Example]
+ ) -> _COMPARISON_OUTPUT:
+ (args, kwargs, _) = _prepare_inputs(runs, example)
+ return func(*args, **kwargs)
+
+ wrapper.__name__ = (
+ getattr(func, "__name__")
+ if hasattr(func, "__name__")
+ else wrapper.__name__
+ )
+ return wrapper, _prepare_inputs # type: ignore[return-value]
+
+
+def _format_evaluator_result(
+ result: Union[EvaluationResults, dict, str, int, bool, float, list],
+) -> Union[EvaluationResults, dict]:
+ if isinstance(result, (bool, float, int)):
+ result = {"score": result}
+ elif not result:
+ raise ValueError(
+ f"Expected a non-empty dict, str, bool, int, float, list, "
+ f"EvaluationResult, or EvaluationResults. Got {result}"
+ )
+ elif isinstance(result, list):
+ if not all(isinstance(x, dict) for x in result):
+ raise ValueError(
+ f"Expected a list of dicts or EvaluationResults. Received {result}."
+ )
+ result = {"results": result} # type: ignore[misc]
+ elif isinstance(result, str):
+ result = {"value": result}
+ elif isinstance(result, dict):
+ pass
+ else:
+ raise ValueError(
+ f"Expected a dict, str, bool, int, float, list, EvaluationResult, or "
+ f"EvaluationResults. Got {result}"
+ )
+ return result
+
+
+SUMMARY_EVALUATOR_T = Union[
+ Callable[
+ [Sequence[schemas.Run], Sequence[schemas.Example]],
+ Union[EvaluationResult, EvaluationResults],
+ ],
+ Callable[
+ [list[schemas.Run], list[schemas.Example]],
+ Union[EvaluationResult, EvaluationResults],
+ ],
+]
+
+
+def _normalize_summary_evaluator(func: Callable) -> SUMMARY_EVALUATOR_T:
+ supported_args = ("runs", "examples", "inputs", "outputs", "reference_outputs")
+ sig = inspect.signature(func)
+ all_args = [pname for pname, p in sig.parameters.items()]
+ args_with_defaults = [
+ pname
+ for pname, p in sig.parameters.items()
+ if p.default is not inspect.Parameter.empty
+ ]
+ if not all_args or (
+ not all(
+ pname in supported_args or pname in args_with_defaults for pname in all_args
+ )
+ and len([a for a in all_args if a not in args_with_defaults]) != 2
+ ):
+ msg = (
+ f"Invalid evaluator function. Must have at least one "
+ f"argument. Supported arguments are {supported_args}."
+ )
+ if all_args:
+ msg += f" Received arguments {all_args}."
+ raise ValueError(msg)
+ # For backwards compatibility we assume custom arg names are Sequence[Run] and
+ # Sequence[Example] types, respectively.
+ elif not all(pname in supported_args for pname in all_args) or all_args == [
+ "runs",
+ "examples",
+ ]:
+ return func
+ else:
+
+ def wrapper(
+ runs: Sequence[schemas.Run], examples: Sequence[schemas.Example]
+ ) -> Union[EvaluationResult, EvaluationResults]:
+ arg_map = {
+ "runs": runs,
+ "examples": examples,
+ "inputs": [example.inputs for example in examples],
+ "outputs": [run.outputs or {} for run in runs],
+ "reference_outputs": [example.outputs or {} for example in examples],
+ }
+ kwargs = {}
+ args = []
+ for param_name, param in sig.parameters.items():
+ # Could have params with defaults that are not in the arg map
+ if param_name in arg_map:
+ if param.kind in (
+ param.POSITIONAL_OR_KEYWORD,
+ param.POSITIONAL_ONLY,
+ ):
+ args.append(arg_map[param_name])
+ else:
+ kwargs[param_name] = arg_map[param_name]
+
+ result = func(*args, **kwargs)
+ if isinstance(result, EvaluationResult):
+ return result
+ return _format_evaluator_result(result) # type: ignore
+
+ wrapper.__name__ = (
+ getattr(func, "__name__") if hasattr(func, "__name__") else wrapper.__name__
+ )
+ return wrapper # type: ignore[return-value]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/llm_evaluator.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/llm_evaluator.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8e73fc14cefa801acf892a27512fcecd2798593
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/llm_evaluator.py
@@ -0,0 +1,302 @@
+"""Contains the `LLMEvaluator` class for building LLM-as-a-judge evaluators."""
+
+from typing import Any, Callable, Optional, Union, cast
+
+from pydantic import BaseModel
+
+from langsmith._internal._beta_decorator import warn_beta
+from langsmith.evaluation import EvaluationResult, EvaluationResults, RunEvaluator
+from langsmith.schemas import Example, Run
+
+
+class CategoricalScoreConfig(BaseModel):
+ """Configuration for a categorical score."""
+
+ key: str
+ choices: list[str]
+ description: str
+ include_explanation: bool = False
+ explanation_description: Optional[str] = None
+
+
+class ContinuousScoreConfig(BaseModel):
+ """Configuration for a continuous score."""
+
+ key: str
+ min: float = 0
+ max: float = 1
+ description: str
+ include_explanation: bool = False
+ explanation_description: Optional[str] = None
+
+
+def _create_score_json_schema(
+ score_config: Union[CategoricalScoreConfig, ContinuousScoreConfig],
+) -> dict:
+ properties: dict[str, Any] = {}
+ if isinstance(score_config, CategoricalScoreConfig):
+ properties["score"] = {
+ "type": "string",
+ "enum": score_config.choices,
+ "description": f"The score for the evaluation, one of "
+ f"{', '.join(score_config.choices)}.",
+ }
+ elif isinstance(score_config, ContinuousScoreConfig):
+ properties["score"] = {
+ "type": "number",
+ "minimum": score_config.min,
+ "maximum": score_config.max,
+ "description": f"The score for the evaluation, between "
+ f"{score_config.min} and {score_config.max}, inclusive.",
+ }
+ else:
+ raise ValueError("Invalid score type. Must be 'categorical' or 'continuous'")
+
+ if score_config.include_explanation:
+ properties["explanation"] = {
+ "type": "string",
+ "description": (
+ "The explanation for the score."
+ if score_config.explanation_description is None
+ else score_config.explanation_description
+ ),
+ }
+
+ return {
+ "title": score_config.key,
+ "description": score_config.description,
+ "type": "object",
+ "properties": properties,
+ "required": (
+ ["score", "explanation"] if score_config.include_explanation else ["score"]
+ ),
+ }
+
+
+class LLMEvaluator(RunEvaluator):
+ """A class for building LLM-as-a-judge evaluators.
+
+ .. deprecated:: 0.5.0
+
+ LLMEvaluator is deprecated. Use openevals instead: https://github.com/langchain-ai/openevals
+ """
+
+ def __init__(
+ self,
+ *,
+ prompt_template: Union[str, list[tuple[str, str]]],
+ score_config: Union[CategoricalScoreConfig, ContinuousScoreConfig],
+ map_variables: Optional[Callable[[Run, Optional[Example]], dict]] = None,
+ model_name: str = "gpt-4o",
+ model_provider: str = "openai",
+ **kwargs,
+ ):
+ """Initialize the `LLMEvaluator`.
+
+ Args:
+ prompt_template (Union[str, List[Tuple[str, str]]): The prompt
+ template to use for the evaluation. If a string is provided, it is
+ assumed to be a human / user message.
+ score_config (Union[CategoricalScoreConfig, ContinuousScoreConfig]):
+ The configuration for the score, either categorical or continuous.
+ map_variables (Optional[Callable[[Run, Example], dict]], optional):
+ A function that maps the run and example to the variables in the
+ prompt.
+
+ If `None`, it is assumed that the prompt only requires 'input',
+ 'output', and 'expected'.
+ model_name (Optional[str], optional): The model to use for the evaluation.
+ model_provider (Optional[str], optional): The model provider to use
+ for the evaluation.
+ """
+ try:
+ from langchain.chat_models import ( # type: ignore[import-not-found]
+ init_chat_model,
+ )
+ except ImportError as e:
+ raise ImportError(
+ "LLMEvaluator requires langchain to be installed. "
+ "Please install langchain by running `pip install langchain`."
+ ) from e
+
+ chat_model = init_chat_model(
+ model=model_name, model_provider=model_provider, **kwargs
+ )
+
+ self._initialize(prompt_template, score_config, map_variables, chat_model)
+
+ @classmethod
+ def from_model(
+ cls,
+ model: Any,
+ *,
+ prompt_template: Union[str, list[tuple[str, str]]],
+ score_config: Union[CategoricalScoreConfig, ContinuousScoreConfig],
+ map_variables: Optional[Callable[[Run, Optional[Example]], dict]] = None,
+ ):
+ """Create an `LLMEvaluator` instance from a `BaseChatModel` instance.
+
+ Args:
+ model (BaseChatModel): The chat model instance to use for the evaluation.
+ prompt_template (Union[str, List[Tuple[str, str]]): The prompt
+ template to use for the evaluation. If a string is provided, it is
+ assumed to be a system message.
+ score_config (Union[CategoricalScoreConfig, ContinuousScoreConfig]):
+ The configuration for the score, either categorical or continuous.
+ map_variables (Optional[Callable[[Run, Example]], dict]], optional):
+ A function that maps the run and example to the variables in the
+ prompt.
+
+ If `None`, it is assumed that the prompt only requires 'input',
+ 'output', and 'expected'.
+
+ Returns:
+ LLMEvaluator: An instance of `LLMEvaluator`.
+ """
+ instance = cls.__new__(cls)
+ instance._initialize(prompt_template, score_config, map_variables, model)
+ return instance
+
+ def _initialize(
+ self,
+ prompt_template: Union[str, list[tuple[str, str]]],
+ score_config: Union[CategoricalScoreConfig, ContinuousScoreConfig],
+ map_variables: Optional[Callable[[Run, Optional[Example]], dict]],
+ chat_model: Any,
+ ):
+ """Shared initialization code for `__init__` and `from_model`.
+
+ Args:
+ prompt_template (Union[str, List[Tuple[str, str]]): The prompt template.
+ score_config (Union[CategoricalScoreConfig, ContinuousScoreConfig]):
+ The score configuration.
+ map_variables (Optional[Callable[[Run, Example]], dict]]):
+ Function to map variables.
+ chat_model (BaseChatModel): The chat model instance.
+ """
+ try:
+ from langchain_core.language_models.chat_models import BaseChatModel
+ from langchain_core.prompts import ChatPromptTemplate
+ except ImportError as e:
+ raise ImportError(
+ "LLMEvaluator requires langchain-core to be installed. "
+ "Please install langchain-core by running `pip install langchain-core`."
+ ) from e
+
+ if not (
+ isinstance(chat_model, BaseChatModel)
+ and hasattr(chat_model, "with_structured_output")
+ ):
+ raise ValueError(
+ "chat_model must be an instance of "
+ "BaseLanguageModel and support structured output."
+ )
+
+ if isinstance(prompt_template, str):
+ self.prompt = ChatPromptTemplate.from_messages([("human", prompt_template)])
+ else:
+ self.prompt = ChatPromptTemplate.from_messages(prompt_template)
+
+ if set(self.prompt.input_variables) - {"input", "output", "expected"}:
+ if not map_variables:
+ raise ValueError(
+ "map_inputs must be provided if the prompt template contains "
+ "variables other than 'input', 'output', and 'expected'"
+ )
+ self.map_variables = map_variables
+
+ self.score_config = score_config
+ self.score_schema = _create_score_json_schema(self.score_config)
+
+ chat_model = chat_model.with_structured_output(self.score_schema)
+ self.runnable = self.prompt | chat_model
+
+ @warn_beta
+ def evaluate_run(
+ self, run: Run, example: Optional[Example] = None
+ ) -> Union[EvaluationResult, EvaluationResults]:
+ """Evaluate a run."""
+ variables = self._prepare_variables(run, example)
+ output: dict = cast(dict, self.runnable.invoke(variables))
+ return self._parse_output(output)
+
+ @warn_beta
+ async def aevaluate_run(
+ self, run: Run, example: Optional[Example] = None
+ ) -> Union[EvaluationResult, EvaluationResults]:
+ """Asynchronously evaluate a run."""
+ variables = self._prepare_variables(run, example)
+ output: dict = cast(dict, await self.runnable.ainvoke(variables))
+ return self._parse_output(output)
+
+ def _prepare_variables(self, run: Run, example: Optional[Example]) -> dict:
+ """Prepare variables for model invocation."""
+ if self.map_variables:
+ return self.map_variables(run, example)
+
+ variables = {}
+ if "input" in self.prompt.input_variables:
+ if len(run.inputs) == 0:
+ raise ValueError(
+ "No input keys are present in run.inputs but the prompt "
+ "requires 'input'."
+ )
+ if len(run.inputs) != 1:
+ raise ValueError(
+ "Multiple input keys are present in run.inputs. Please provide "
+ "a map_variables function."
+ )
+ variables["input"] = list(run.inputs.values())[0]
+
+ if "output" in self.prompt.input_variables:
+ if not run.outputs:
+ raise ValueError(
+ "No output keys are present in run.outputs but the prompt "
+ "requires 'output'."
+ )
+ if len(run.outputs) == 0:
+ raise ValueError(
+ "No output keys are present in run.outputs but the prompt "
+ "requires 'output'."
+ )
+ if len(run.outputs) != 1:
+ raise ValueError(
+ "Multiple output keys are present in run.outputs. Please "
+ "provide a map_variables function."
+ )
+ variables["output"] = list(run.outputs.values())[0]
+
+ if "expected" in self.prompt.input_variables:
+ if not example or not example.outputs:
+ raise ValueError(
+ "No example or example outputs is provided but the prompt "
+ "requires 'expected'."
+ )
+ if len(example.outputs) == 0:
+ raise ValueError(
+ "No output keys are present in example.outputs but the prompt "
+ "requires 'expected'."
+ )
+ if len(example.outputs) != 1:
+ raise ValueError(
+ "Multiple output keys are present in example.outputs. Please "
+ "provide a map_variables function."
+ )
+ variables["expected"] = list(example.outputs.values())[0]
+
+ return variables
+
+ def _parse_output(self, output: dict) -> Union[EvaluationResult, EvaluationResults]:
+ """Parse the model output into an evaluation result."""
+ if isinstance(self.score_config, CategoricalScoreConfig):
+ value = output["score"]
+ explanation = output.get("explanation", None)
+ return EvaluationResult(
+ key=self.score_config.key, value=value, comment=explanation
+ )
+ elif isinstance(self.score_config, ContinuousScoreConfig):
+ score = output["score"]
+ explanation = output.get("explanation", None)
+ return EvaluationResult(
+ key=self.score_config.key, score=score, comment=explanation
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/string_evaluator.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/string_evaluator.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfe5430ca2af30ae6b41b5c6be8e0272fdd0a0e8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/evaluation/string_evaluator.py
@@ -0,0 +1,47 @@
+"""This module contains the StringEvaluator class."""
+
+import uuid
+from typing import Callable, Optional
+
+from pydantic import BaseModel
+
+from langsmith.evaluation.evaluator import EvaluationResult, RunEvaluator
+from langsmith.schemas import Example, Run
+
+
+class StringEvaluator(RunEvaluator, BaseModel):
+ """Grades the run's string input, output, and optional answer.
+
+ .. deprecated:: 0.5.0
+
+ StringEvaluator is deprecated. Use openevals instead: https://github.com/langchain-ai/openevals
+ """
+
+ evaluation_name: Optional[str] = None
+ """The name evaluation, such as `'Accuracy'` or `'Salience'`."""
+ input_key: str = "input"
+ """The key in the run inputs to extract the input string."""
+ prediction_key: str = "output"
+ """The key in the run outputs to extra the prediction string."""
+ answer_key: Optional[str] = "output"
+ """The key in the example outputs the answer string."""
+ grading_function: Callable[[str, str, Optional[str]], dict]
+ """Function that grades the run output against the example output."""
+
+ def evaluate_run(
+ self,
+ run: Run,
+ example: Optional[Example] = None,
+ evaluator_run_id: Optional[uuid.UUID] = None,
+ ) -> EvaluationResult:
+ """Evaluate a single run."""
+ if run.outputs is None:
+ raise ValueError("Run outputs cannot be None.")
+ if not example or example.outputs is None or self.answer_key is None:
+ answer = None
+ else:
+ answer = example.outputs.get(self.answer_key)
+ run_input = run.inputs[self.input_key]
+ run_output = run.outputs[self.prediction_key]
+ grading_results = self.grading_function(run_input, run_output, answer)
+ return EvaluationResult(**{"key": self.evaluation_name, **grading_results})
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fa7eafc49cc5c15d7a093d4861e13032df28ca1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__init__.py
@@ -0,0 +1,84 @@
+"""LangSmith integration for Claude Agent SDK.
+
+This module provides automatic tracing for the Claude Agent SDK by instrumenting
+`ClaudeSDKClient` and injecting hooks to trace all tool calls.
+
+Instrumentation is applied **in place** on the original ``ClaudeSDKClient`` class
+so that callers who imported the class *before* ``configure_claude_agent_sdk()``
+was called still get traced.
+"""
+
+import logging
+from typing import Optional
+
+from ._client import instrument_claude_client, instrument_sdk_mcp_tool
+from ._config import set_tracing_config
+
+logger = logging.getLogger(__name__)
+
+__all__ = ["configure_claude_agent_sdk"]
+
+
+def configure_claude_agent_sdk(
+ name: Optional[str] = None,
+ project_name: Optional[str] = None,
+ metadata: Optional[dict] = None,
+ tags: Optional[list[str]] = None,
+) -> bool:
+ """Enable LangSmith tracing for the Claude Agent SDK by patching entry points.
+
+ This function instruments the Claude Agent SDK to automatically trace:
+ - Chain runs for each conversation stream (via `ClaudeSDKClient`)
+ - Model runs for each assistant turn
+ - All tool calls including built-in tools, external MCP tools, and SDK MCP tools
+
+ Tool tracing is implemented via `PreToolUse` and `PostToolUse` hooks.
+
+ The class is patched **in place**, so references obtained via
+ ``from claude_agent_sdk import ClaudeSDKClient`` before this call
+ will still be instrumented.
+
+ Args:
+ name: Name of the root trace.
+ project_name: LangSmith project to trace to.
+ metadata: Metadata to associate with all traces.
+ tags: Tags to associate with all traces.
+
+ Returns:
+ `True` if configuration was successful, `False` otherwise.
+
+ Example:
+ >>> from langsmith.integrations.claude_agent_sdk import (
+ ... configure_claude_agent_sdk,
+ ... )
+ >>> configure_claude_agent_sdk(
+ ... project_name="my-project", tags=["production"]
+ ... ) # doctest: +SKIP
+ >>> # Now use claude_agent_sdk as normal - tracing is automatic
+ """
+ try:
+ import claude_agent_sdk # type: ignore[import-not-found]
+ except ImportError:
+ logger.warning("Claude Agent SDK not installed.")
+ return False
+
+ if not hasattr(claude_agent_sdk, "ClaudeSDKClient"):
+ logger.warning("Claude Agent SDK missing ClaudeSDKClient.")
+ return False
+
+ set_tracing_config(
+ name=name,
+ project_name=project_name,
+ metadata=metadata,
+ tags=tags,
+ )
+
+ instrument_claude_client(claude_agent_sdk.ClaudeSDKClient)
+
+ # Patch SdkMcpTool so that tool handlers are lazily wrapped with
+ # run-context propagation, regardless of import order.
+ sdk_mcp_tool_cls = getattr(claude_agent_sdk, "SdkMcpTool", None)
+ if sdk_mcp_tool_cls:
+ instrument_sdk_mcp_tool(sdk_mcp_tool_cls)
+
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1eb8f2dc6a0c9d829e9673c51fa27a8ef806211a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac8ed35a448af1fbeb8f20c769ee5a477205794f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_client.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_config.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_config.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..11f3f9af3daf78e2bb77d58221213f9f2ff2d248
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_config.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_hooks.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_hooks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b89e68ece681e07d0cc3b4a1171313d65cb99fb9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_hooks.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_messages.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_messages.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..330e3de95c47298f577160e01f22792c5ad23f1d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_messages.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_tools.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_tools.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fb803e1efb0efc8f2bec6c716b70db1d01ae35f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_tools.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_transcripts.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_transcripts.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43210c5dbb7e58121457570541d4de8b8f9109e4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_transcripts.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_usage.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_usage.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc653a42b96c5e1b53c701812b10cbaa75108a5b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/__pycache__/_usage.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f9f28c02fb902294ff746695c58ef3ce227d6eb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_client.py
@@ -0,0 +1,709 @@
+"""Client instrumentation for Claude Agent SDK."""
+
+import logging
+import time
+import weakref
+from collections.abc import AsyncGenerator, AsyncIterable
+from datetime import datetime, timezone
+from functools import cache
+from typing import Any, Optional
+
+from langsmith._internal import _context
+from langsmith.run_helpers import get_current_run_tree, trace
+
+from ._config import get_tracing_config
+from ._hooks import (
+ SessionState,
+ _current_session,
+ _register_session,
+ _set_session_root,
+ _unregister_session,
+ clear_active_tool_runs,
+ get_subagent_run_by_tool_id,
+ post_tool_use_failure_hook,
+ post_tool_use_hook,
+ pre_tool_use_hook,
+ subagent_start_hook,
+ subagent_stop_hook,
+)
+from ._messages import (
+ build_llm_input,
+ flatten_content_blocks,
+ unwrap_message_dicts,
+)
+from ._tools import (
+ clear_parent_run_tree,
+ get_parent_run_tree,
+ set_parent_run_tree,
+)
+from ._transcripts import LLM_RUN_NAME, reconcile_from_transcripts
+from ._usage import extract_usage_metadata
+
+logger = logging.getLogger(__name__)
+
+TRACE_CHAIN_NAME = "claude.conversation"
+
+
+@cache
+def _get_package_version(package_name: str) -> str | None:
+ try:
+ from importlib.metadata import version
+
+ return version(package_name)
+ except Exception:
+ return None
+
+
+class TurnLifecycle:
+ """Track ongoing model runs so consecutive messages are recorded correctly.
+
+ The Claude Agent SDK may deliver a single assistant turn as multiple
+ ``AssistantMessage`` events (e.g. one with ``ThinkingBlock``, another
+ with ``TextBlock``/``ToolUseBlock``). Messages that share the same
+ ``message_id`` are accumulated into a single LLM run.
+ """
+
+ def __init__(self, query_start_time: Optional[float] = None):
+ self.current_run: Optional[Any] = None
+ self.current_message_id: Optional[str] = None
+ self.next_start_time: Optional[float] = query_start_time
+ # message_id → RunTree for all LLM runs created this conversation.
+ # Used to retroactively set usage from transcripts.
+ self.llm_runs_by_message_id: dict[str, Any] = {}
+ # Runs that have been end()ed but not yet patch()ed.
+ # Deferred so transcript usage can be set before the single patch().
+ self._pending_patch: list[Any] = []
+
+ def start_llm_run(
+ self,
+ message: Any,
+ prompt: Any,
+ history: list[dict[str, Any]],
+ parent: Optional[Any] = None,
+ ) -> Optional[dict[str, Any]]:
+ """Begin or continue a model run for *message*.
+
+ If *message* has the same ``message_id`` as the current run the
+ output is appended; otherwise a new run is started (ending any
+ previous one first).
+ """
+ message_id = getattr(message, "message_id", None)
+ start = self.next_start_time or time.time()
+
+ # Same turn – just accumulate the output blocks and update usage.
+ # Return None so the caller does NOT append a duplicate history
+ # entry; the original entry in ``history`` is updated in place.
+ if message_id and message_id == self.current_message_id and self.current_run:
+ content = flatten_content_blocks(getattr(message, "content", None))
+ if content and self.current_run.outputs:
+ prev = self.current_run.outputs.get("content", [])
+ if isinstance(prev, list) and isinstance(content, list):
+ merged = prev + content
+ self.current_run.outputs["content"] = merged
+ # Update the existing history entry in place so
+ # subsequent LLM runs see a single merged message.
+ for entry in reversed(history):
+ if entry.get("role") == "assistant":
+ entry["content"] = merged
+ break
+ elif isinstance(content, list):
+ self.current_run.outputs["content"] = content
+ self._set_usage_from_message(message, self.current_run)
+ return None
+
+ # Different turn – end previous but defer patch() until
+ # transcript usage is available.
+ if self.current_run:
+ self.current_run.end()
+ self._pending_patch.append(self.current_run)
+
+ final_output, run = begin_llm_run_from_assistant_messages(
+ [message], prompt, history, start_time=start, parent=parent
+ )
+ self.current_run = run
+ self.current_message_id = message_id
+ self.next_start_time = None
+
+ if run:
+ if message_id:
+ self.llm_runs_by_message_id[message_id] = run
+ self._set_usage_from_message(message, run)
+
+ return final_output
+
+ @staticmethod
+ def _set_usage_from_message(message: Any, run: Any) -> None:
+ """Set usage metadata on a run from a live AssistantMessage.
+
+ Always overwrites — later chunks in the same turn have more
+ accurate counts. Transcript-based usage will overwrite again
+ if available.
+ """
+ raw_usage = getattr(message, "usage", None)
+ if not raw_usage:
+ return
+ usage_meta = extract_usage_metadata(raw_usage)
+ if usage_meta:
+ meta = run.extra.setdefault("metadata", {})
+ meta["usage_metadata"] = usage_meta
+
+ def mark_next_start(self) -> None:
+ """Mark when the next assistant message will start."""
+ self.next_start_time = time.time()
+
+ def close(self) -> None:
+ """End any open run and add to pending patch list."""
+ if self.current_run:
+ self.current_run.end()
+ self._pending_patch.append(self.current_run)
+ self.current_run = None
+
+ def flush(self) -> None:
+ """Patch all deferred LLM runs. Call after usage has been set."""
+ for run in self._pending_patch:
+ try:
+ run.patch()
+ except Exception as e:
+ logger.warning(f"Failed to patch LLM run: {e}")
+ self._pending_patch.clear()
+
+
+def begin_llm_run_from_assistant_messages(
+ messages: list[Any],
+ prompt: Any,
+ history: list[dict[str, Any]],
+ start_time: Optional[float] = None,
+ parent: Optional[Any] = None,
+) -> tuple[Optional[dict[str, Any]], Optional[Any]]:
+ """Create a traced model run from assistant messages."""
+ if not messages or type(messages[-1]).__name__ != "AssistantMessage":
+ return None, None
+
+ last_msg = messages[-1]
+ model = getattr(last_msg, "model", None)
+ if parent is None:
+ parent = get_parent_run_tree() or get_current_run_tree()
+ if not parent:
+ return None, None
+
+ inputs = build_llm_input(prompt, history)
+ outputs = [
+ {"content": flatten_content_blocks(m.content), "role": "assistant"}
+ for m in messages
+ if hasattr(m, "content")
+ ]
+
+ llm_metadata: dict[str, Any] = {"ls_provider": "anthropic"}
+ if model:
+ llm_metadata["ls_model_name"] = model
+
+ llm_run = parent.create_child(
+ name=LLM_RUN_NAME,
+ run_type="llm",
+ inputs={"messages": inputs} if inputs else {},
+ extra={"metadata": llm_metadata},
+ start_time=datetime.fromtimestamp(start_time, tz=timezone.utc)
+ if start_time
+ else None,
+ )
+
+ try:
+ llm_run.post()
+ except Exception as e:
+ logger.warning(f"Failed to post LLM run: {e}")
+
+ # Set outputs after posting so they are sent with end_time on the patch.
+ llm_run.outputs = outputs[-1] if len(outputs) == 1 else {"content": outputs}
+
+ final_content = (
+ {"content": flatten_content_blocks(last_msg.content), "role": "assistant"}
+ if hasattr(last_msg, "content")
+ else None
+ )
+ return final_content, llm_run
+
+
+def _bind_hook_to_session(hook: Any, session: Optional[SessionState]) -> Any:
+ """Return a hook callable that runs with *session* bound, if provided."""
+ if session is None:
+ return hook
+
+ async def _bound(input_data: Any, tool_use_id: Any, context: Any) -> Any:
+ token = _current_session.set(session)
+ try:
+ return await hook(input_data, tool_use_id, context)
+ finally:
+ _current_session.reset(token)
+
+ return _bound
+
+
+def _inject_tracing_hooks(options: Any, session: Optional[SessionState] = None) -> None:
+ """Inject LangSmith tracing hooks into ClaudeAgentOptions.
+
+ If *session* is provided, injected hook callables bind that session around
+ each hook invocation. This is important because the Claude SDK may execute
+ hooks in async contexts that do not inherit the ``receive_response``
+ ContextVar; binding at hook injection time keeps each client isolated.
+ """
+ if not hasattr(options, "hooks"):
+ return
+
+ # Initialize hooks dict if not present
+ if options.hooks is None:
+ options.hooks = {}
+
+ for event in (
+ "PreToolUse",
+ "PostToolUse",
+ "PostToolUseFailure",
+ "SubagentStart",
+ "SubagentStop",
+ ):
+ if event not in options.hooks:
+ options.hooks[event] = []
+
+ try:
+ from claude_agent_sdk import HookMatcher # type: ignore[import-not-found]
+
+ langsmith_pre_matcher = HookMatcher(
+ matcher=None, hooks=[_bind_hook_to_session(pre_tool_use_hook, session)]
+ )
+ langsmith_post_matcher = HookMatcher(
+ matcher=None, hooks=[_bind_hook_to_session(post_tool_use_hook, session)]
+ )
+ langsmith_failure_matcher = HookMatcher(
+ matcher=None,
+ hooks=[_bind_hook_to_session(post_tool_use_failure_hook, session)],
+ )
+ langsmith_subagent_start_matcher = HookMatcher(
+ matcher=None, hooks=[_bind_hook_to_session(subagent_start_hook, session)]
+ )
+ langsmith_subagent_stop_matcher = HookMatcher(
+ matcher=None, hooks=[_bind_hook_to_session(subagent_stop_hook, session)]
+ )
+
+ options.hooks["PreToolUse"].insert(0, langsmith_pre_matcher)
+ options.hooks["PostToolUse"].insert(0, langsmith_post_matcher)
+ options.hooks["PostToolUseFailure"].insert(0, langsmith_failure_matcher)
+ options.hooks["SubagentStart"].insert(0, langsmith_subagent_start_matcher)
+ options.hooks["SubagentStop"].insert(0, langsmith_subagent_stop_matcher)
+
+ logger.debug("Injected LangSmith tracing hooks into ClaudeAgentOptions")
+ except ImportError:
+ logger.warning("Failed to import HookMatcher from claude_agent_sdk")
+ except Exception as e:
+ logger.warning(f"Failed to inject tracing hooks: {e}")
+
+
+def _wrap_tool_handler(
+ original_handler: Any,
+ session: Optional[SessionState] = None,
+ tool_name: Optional[str] = None,
+) -> Any:
+ """Wrap an MCP tool handler to propagate LangSmith run context.
+
+ The Claude SDK runs hooks and tool handlers in different async task
+ contexts, so contextvars set in ``PreToolUse`` are invisible to the
+ handler. This wrapper copies the active tool run into the contextvar before
+ calling the original handler, so ``@traceable`` calls inside the handler
+ nest correctly.
+ """
+
+ async def _wrapped(args: Any) -> Any:
+ # The most recently added active tool run is the one PreToolUse just
+ # created for this invocation. Prefer an explicitly bound client
+ # session because tool handlers may run in an async context that did
+ # not inherit _current_session.
+ tool_run = _get_last_active_tool_run(session, args=args, tool_name=tool_name)
+ if tool_run:
+ token = _context._PARENT_RUN_TREE_REF.set(weakref.ref(tool_run))
+ session_token = (
+ _current_session.set(session) if session is not None else None
+ )
+ try:
+ return await original_handler(args)
+ finally:
+ if session_token is not None:
+ _current_session.reset(session_token)
+ _context._PARENT_RUN_TREE_REF.reset(token)
+ return await original_handler(args)
+
+ _wrapped._langsmith_wrapped = True # type: ignore[attr-defined]
+ _wrapped._langsmith_original_handler = original_handler # type: ignore[attr-defined]
+ _wrapped._langsmith_session = session # type: ignore[attr-defined]
+ _wrapped._langsmith_tool_name = tool_name # type: ignore[attr-defined]
+ return _wrapped
+
+
+def _tool_run_matches(run: Any, args: Any, tool_name: Optional[str]) -> bool:
+ """Return whether *run* appears to be for this SDK MCP handler call.
+
+ Matching is intentionally strict: we require both the tool name and the
+ handler args to line up with what the ``PreToolUse`` hook recorded. This
+ avoids cross-attributing a handler invocation to the wrong client's active
+ tool run under concurrency.
+ """
+ if not tool_name:
+ return False
+ run_name = str(getattr(run, "name", ""))
+ # SDK MCP tools show up in hook data as e.g. ``mcp__weather__get_weather``
+ # while the handler only knows its short name ``get_weather``.
+ name_matches = (
+ tool_name == run_name or tool_name in run_name or run_name in tool_name
+ )
+ if not name_matches:
+ return False
+ inputs = getattr(run, "inputs", None)
+ if not isinstance(inputs, dict):
+ return False
+ # PreToolUse stores {} when the tool had no inputs, otherwise
+ # {"input": }. Normalise both sides before comparing.
+ recorded = inputs.get("input", {}) if inputs else {}
+ return recorded == (args or {})
+
+
+def _newest_matching_tool_run(
+ sessions: list[SessionState], args: Any, tool_name: Optional[str]
+) -> Any:
+ """Return the most recently created active tool run that matches."""
+ candidates: list[tuple[float, Any]] = []
+ for candidate_session in sessions:
+ for run, start_time in candidate_session.active_tool_runs.values():
+ if _tool_run_matches(run, args, tool_name):
+ candidates.append((start_time, run))
+ if not candidates:
+ return None
+ return max(candidates, key=lambda item: item[0])[1]
+
+
+def _get_last_active_tool_run(
+ session: Optional[SessionState] = None,
+ *,
+ args: Any = None,
+ tool_name: Optional[str] = None,
+) -> Any:
+ """Return the active tool run for an SDK MCP handler, or None.
+
+ Lookup order:
+
+ 1. The session explicitly bound to the handler (if any).
+ 2. The session bound to the current ContextVar.
+ 3. The module-level default session (unit tests / unbound callers).
+ 4. Any live client session — only used when the handler is unbound and the
+ SDK invoked it in a detached async context. Requires an exact tool
+ name + args match to avoid cross-attribution across clients.
+ """
+ from ._hooks import (
+ _current_session,
+ _current_session_or_default,
+ _registered_sessions,
+ )
+
+ # If we have a specific session (explicitly bound, current-context, or the
+ # test default), just return its newest active tool run. There is no
+ # cross-client ambiguity at that point.
+ def _newest_in(s: SessionState) -> Any:
+ if not s.active_tool_runs:
+ return None
+ latest_id = max(
+ s.active_tool_runs,
+ key=lambda tid: s.active_tool_runs[tid][1],
+ )
+ return s.active_tool_runs[latest_id][0]
+
+ if session is not None:
+ return _newest_in(session)
+
+ current_session = _current_session.get()
+ if current_session is not None:
+ run = _newest_in(current_session)
+ if run is not None:
+ return run
+
+ default_session = _current_session_or_default()
+ if default_session is not current_session:
+ run = _newest_in(default_session)
+ if run is not None:
+ return run
+
+ # Last resort: the SDK invoked this handler in a detached async context and
+ # the handler object wasn't bound to a session. Require strict tool-name +
+ # args match so concurrent clients can't steal each other's attribution.
+ return _newest_matching_tool_run(_registered_sessions(), args, tool_name)
+
+
+def instrument_claude_client(original_class: Any) -> None:
+ """Patch ``ClaudeSDKClient`` **in place** to trace calls.
+
+ In-place patching (rather than subclassing + reference replacement)
+ ensures that callers who imported ``ClaudeSDKClient`` *before*
+ ``configure_claude_agent_sdk()`` was called still get instrumented.
+ """
+ if getattr(original_class, "_langsmith_instrumented", False):
+ return # Already wrapped, avoid double-tracing
+
+ # ── stash originals ──────────────────────────────────────────────
+ _orig_init = original_class.__init__
+ _orig_query = original_class.query
+ _orig_receive_response = original_class.receive_response
+
+ # ── patched __init__ ─────────────────────────────────────────────
+ def _traced_init(self: Any, *args: Any, **kwargs: Any) -> None:
+ options = kwargs.get("options") or (args[0] if args else None)
+ self._ls_session = SessionState()
+ if options:
+ _inject_tracing_hooks(options, self._ls_session)
+ _orig_init(self, *args, **kwargs)
+ self._ls_prompt = None
+ self._ls_start_time = None
+ self._ls_streamed_input = None
+
+ # ── patched query ────────────────────────────────────────────────
+ async def _traced_query(self: Any, *args: Any, **kwargs: Any) -> Any:
+ self._ls_start_time = time.time()
+ self._ls_streamed_input = None
+ prompt = args[0] if args else kwargs.get("prompt")
+
+ if prompt is None:
+ pass
+ elif isinstance(prompt, str):
+ self._ls_prompt = prompt
+ elif isinstance(prompt, AsyncIterable):
+ collector: list[dict[str, Any]] = []
+ self._ls_streamed_input = collector
+ self._ls_prompt = None
+
+ async def _gen_wrapper() -> AsyncGenerator[dict[str, Any], None]:
+ async for msg in prompt:
+ collector.append(msg)
+ yield msg
+
+ if args:
+ args = (_gen_wrapper(),) + args[1:]
+ else:
+ kwargs["prompt"] = _gen_wrapper()
+ else:
+ self._ls_prompt = str(prompt)
+
+ return await _orig_query(self, *args, **kwargs)
+
+ # ── patched receive_response ─────────────────────────────────────
+ async def _traced_receive_response(self: Any) -> AsyncGenerator[Any, None]:
+ messages = _orig_receive_response(self)
+
+ trace_inputs: dict[str, Any] = {}
+ trace_metadata: dict[str, Any] = {
+ "ls_integration": "claude-agent-sdk",
+ "ls_integration_version": _get_package_version("claude_agent_sdk"),
+ }
+
+ awaiting_streamed_input = self._ls_streamed_input is not None
+
+ if self._ls_prompt:
+ trace_inputs["prompt"] = self._ls_prompt
+
+ if hasattr(self, "options") and self.options:
+ if hasattr(self.options, "system_prompt") and self.options.system_prompt:
+ system_prompt = self.options.system_prompt
+ if isinstance(system_prompt, str):
+ trace_inputs["system"] = system_prompt
+ elif isinstance(system_prompt, dict):
+ if system_prompt.get("type") == "preset":
+ preset_text = (
+ f"preset: {system_prompt.get('preset', 'claude_code')}"
+ )
+ if "append" in system_prompt:
+ preset_text += f"\nappend: {system_prompt['append']}"
+ trace_inputs["system"] = preset_text
+ else:
+ trace_inputs["system"] = system_prompt
+
+ for attr in ["model", "permission_mode", "max_turns"]:
+ if hasattr(self.options, attr):
+ val = getattr(self.options, attr)
+ if val is not None:
+ trace_metadata[attr] = val
+
+ config = get_tracing_config()
+ user_metadata = config.get("metadata") or {}
+
+ trace_kwargs: dict[str, Any] = {
+ "name": config.get("name") or TRACE_CHAIN_NAME,
+ "run_type": "chain",
+ "inputs": trace_inputs,
+ "metadata": {
+ **trace_metadata,
+ **user_metadata,
+ "ls_agent_type": "root",
+ },
+ }
+ if config.get("project_name"):
+ trace_kwargs["project_name"] = config["project_name"]
+ if config.get("tags"):
+ trace_kwargs["tags"] = config["tags"]
+
+ async with trace(**trace_kwargs) as run:
+ # Bind this client's state container to the ContextVar so stream
+ # helpers on this SDK event loop pick it up (see
+ # _hooks.SessionState). This keeps concurrent ClaudeSDKClient
+ # instances — eval runs, FastAPI handlers, Celery workers,
+ # asyncio.gather — from corrupting each other's correlation state.
+ session = getattr(self, "_ls_session", None)
+ if session is None:
+ session = self._ls_session = SessionState()
+ session_token = _register_session(session)
+ _set_session_root(session, run)
+ parent_token = set_parent_run_tree(run)
+ tracker = TurnLifecycle(self._ls_start_time)
+ collected_by_ctx: dict[Optional[str], list[dict[str, Any]]] = {None: []}
+
+ prompt_for_llm: Any = self._ls_prompt
+
+ try:
+ async for msg in messages:
+ if awaiting_streamed_input and self._ls_streamed_input:
+ unwrapped_messages = unwrap_message_dicts(
+ self._ls_streamed_input
+ )
+ if unwrapped_messages:
+ run.inputs["messages"] = unwrapped_messages
+ prompt_for_llm = self._ls_streamed_input
+ awaiting_streamed_input = False
+
+ msg_type = type(msg).__name__
+
+ if msg_type == "AssistantMessage":
+ parent_tool_use_id = getattr(msg, "parent_tool_use_id", None)
+ llm_parent = (
+ get_subagent_run_by_tool_id(parent_tool_use_id)
+ if parent_tool_use_id
+ else None
+ )
+
+ ctx_key = parent_tool_use_id
+ ctx_history = collected_by_ctx.setdefault(ctx_key, [])
+
+ content = tracker.start_llm_run(
+ msg,
+ prompt_for_llm if parent_tool_use_id is None else None,
+ ctx_history,
+ parent=llm_parent,
+ )
+ if content:
+ ctx_history.append(content)
+
+ elif msg_type == "UserMessage":
+ parent_tool_use_id = getattr(msg, "parent_tool_use_id", None)
+ ctx_key = parent_tool_use_id
+ ctx_history = collected_by_ctx.setdefault(ctx_key, [])
+
+ if hasattr(msg, "content"):
+ flattened = flatten_content_blocks(msg.content)
+ if (
+ isinstance(flattened, list)
+ and flattened
+ and isinstance(flattened[0], dict)
+ and flattened[0].get("type") == "tool_result"
+ ):
+ for block in flattened:
+ tool_use_id = block.get("tool_use_id")
+ ctx_history.append(
+ {
+ "role": "tool",
+ "content": block.get("content", ""),
+ "tool_call_id": tool_use_id,
+ }
+ )
+ if (
+ tool_use_id
+ and tool_use_id in session.active_tool_runs
+ ):
+ tool_run, _ = session.active_tool_runs.pop(
+ tool_use_id
+ )
+ result_content = block.get("content", "")
+ is_error = block.get("is_error", False)
+ tool_run.end(
+ outputs={"output": result_content},
+ error=str(result_content)
+ if is_error
+ else None,
+ )
+ try:
+ tool_run.patch()
+ except Exception as e:
+ logger.warning(
+ "Failed to patch"
+ f" orphaned tool run: {e}"
+ )
+ else:
+ ctx_history.append(
+ {
+ "content": flattened,
+ "role": "user",
+ }
+ )
+ tracker.mark_next_start()
+ elif msg_type == "ResultMessage":
+ meta = {
+ k: v
+ for k, v in {
+ "num_turns": getattr(msg, "num_turns", None),
+ "session_id": getattr(msg, "session_id", None),
+ "duration_ms": getattr(msg, "duration_ms", None),
+ "duration_api_ms": getattr(
+ msg, "duration_api_ms", None
+ ),
+ "is_error": getattr(msg, "is_error", None),
+ }.items()
+ if v is not None
+ }
+ if meta:
+ run.metadata.update(meta)
+
+ yield msg
+ main_collected = collected_by_ctx.get(None, [])
+ run.end(outputs=main_collected[-1] if main_collected else None)
+ except Exception:
+ logger.exception("Error while tracing Claude Agent stream")
+ finally:
+ tracker.close()
+ reconcile_from_transcripts(tracker, session=session)
+ tracker.flush()
+ clear_parent_run_tree(parent_token)
+ try:
+ clear_active_tool_runs(session)
+ finally:
+ _unregister_session(session, session_token)
+
+ # ── apply patches to the class itself ────────────────────────────
+ original_class.__init__ = _traced_init
+ original_class.query = _traced_query
+ original_class.receive_response = _traced_receive_response
+ original_class._langsmith_instrumented = True
+
+
+def instrument_sdk_mcp_tool(tool_class: Any) -> None:
+ """Patch ``SdkMcpTool.__init__`` to auto-wrap handlers.
+
+ Wrapping happens at construction time so that any tool created
+ *after* ``configure_claude_agent_sdk()`` automatically gets
+ run-context propagation, regardless of how ``tool`` or
+ ``create_sdk_mcp_server`` were imported.
+ """
+ if getattr(tool_class, "_langsmith_handler_patched", False):
+ return
+
+ _orig_init = tool_class.__init__
+
+ def _patched_init(self: Any, *args: Any, **kwargs: Any) -> None:
+ _orig_init(self, *args, **kwargs)
+ handler = self.handler
+ if callable(handler) and not getattr(handler, "_langsmith_wrapped", False):
+ self.handler = _wrap_tool_handler(
+ handler, tool_name=getattr(self, "name", None)
+ )
+
+ tool_class.__init__ = _patched_init
+ tool_class._langsmith_handler_patched = True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_config.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..125d3003072cc5c7a7a64456e5e2da102fb7ff23
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_config.py
@@ -0,0 +1,39 @@
+"""Configuration management for Claude Agent SDK tracing."""
+
+from typing import Any, Optional
+
+# Global configuration for tracing
+_tracing_config: dict[str, Any] = {
+ "name": None,
+ "project_name": None,
+ "metadata": None,
+ "tags": None,
+}
+
+
+def set_tracing_config(
+ name: Optional[str] = None,
+ project_name: Optional[str] = None,
+ metadata: Optional[dict] = None,
+ tags: Optional[list[str]] = None,
+) -> None:
+ """Set the global tracing configuration for Claude Agent SDK.
+
+ Args:
+ name: Name of the root trace.
+ project_name: LangSmith project to trace to.
+ metadata: Metadata to associate with all traces.
+ tags: Tags to associate with all traces.
+ """
+ global _tracing_config
+ _tracing_config = {
+ "name": name,
+ "project_name": project_name,
+ "metadata": metadata,
+ "tags": tags,
+ }
+
+
+def get_tracing_config() -> dict[str, Any]:
+ """Get the current tracing configuration."""
+ return _tracing_config.copy()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_hooks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a98d27b97437e8436a4f5085a0c2b8ed1b518de
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_hooks.py
@@ -0,0 +1,564 @@
+"""Hook-based tool tracing for Claude Agent SDK.
+
+Correlation state is scoped **per client session** via a
+:class:`contextvars.ContextVar`. Each instrumented ``ClaudeSDKClient`` owns a
+:class:`SessionState`; ``receive_response()`` binds it while processing the
+stream so helper functions can look up the right state regardless of how many
+clients are concurrently active in the process.
+
+Hooks injected by ``_client.py`` are also bound to their owning
+``SessionState`` so hook callbacks use the correct state even if the SDK runs
+them in an async context that did not inherit ``receive_response``'s
+ContextVar.
+
+When no ContextVar is active, hooks use a module-level default session. This is
+primarily for direct unit tests; real traffic under ``receive_response`` uses a
+client-bound session.
+"""
+
+import logging
+import threading
+import time
+import weakref
+from contextvars import ContextVar
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from typing import TYPE_CHECKING, Any, Optional
+
+from langsmith.run_helpers import get_current_run_tree
+from langsmith.run_trees import RunTree
+
+from ._tools import get_parent_run_tree
+
+if TYPE_CHECKING:
+ from claude_agent_sdk import (
+ HookContext,
+ HookInput,
+ HookJSONOutput,
+ )
+
+logger = logging.getLogger(__name__)
+
+
+# ── Per-session state ─────────────────────────────────────────────────────────
+
+
+@dataclass
+class SessionState:
+ """All mutable correlation state for a single conversation.
+
+ One instance is created per instrumented ``ClaudeSDKClient`` and bound to
+ the ``_current_session`` ContextVar while that client is active.
+ """
+
+ # Key: tool_use_id → (run_tree, start_time)
+ active_tool_runs: dict[str, tuple[Any, float]] = field(default_factory=dict)
+
+ # Key: agent_id → RunTree for the subagent chain.
+ # Populated by SubagentStart, consumed by SubagentStop.
+ subagent_runs: dict[str, RunTree] = field(default_factory=dict)
+
+ # Key: tool_use_id → tool_input dict.
+ # When PreToolUse fires for an "Agent" tool, it stashes here.
+ # SubagentStart pops it to find the matching Agent tool run.
+ pending_agent_tools: dict[str, dict[str, Any]] = field(default_factory=dict)
+
+ # Key: agent_id → Agent tool_use_id.
+ # Maps a subagent back to the Agent tool that spawned it.
+ agent_to_tool_mapping: dict[str, str] = field(default_factory=dict)
+
+ # Key: Agent tool_use_id → RunTree.
+ # SubagentStop moves the run here; PostToolUse sets outputs on it;
+ # clear_active_tool_runs() ends + patches it.
+ ended_subagent_runs: dict[str, RunTree] = field(default_factory=dict)
+
+ # (transcript_path, subagent_RunTree) captured from SubagentStop.
+ # Used for usage extraction and creating missing LLM runs.
+ subagent_transcript_paths: list[tuple[str, RunTree]] = field(default_factory=list)
+
+ # Main session transcript path, captured from BaseHookInput.transcript_path
+ # on the first hook that fires (every hook inherits this field).
+ main_transcript_path: Optional[str] = None
+
+ # Root LangSmith run used for parenting root-level hook spans.
+ root_run: Optional[RunTree] = None
+
+
+# Module-level *default* session. Used when no ContextVar is set (e.g. tests
+# that poke hooks directly, or hooks firing outside a traced conversation).
+_default_session: SessionState = SessionState()
+
+# ContextVar holding the active session for a conversation. Injected hook
+# callables bind this explicitly before calling the shared hook function.
+_current_session: ContextVar[Optional[SessionState]] = ContextVar(
+ "langsmith_claude_agent_session", default=None
+)
+
+# Live sessions are only used by SDK MCP tool handlers when the SDK invokes the
+# handler in a detached async context that did not inherit _current_session.
+# Store weak values so this fallback registry never owns session lifetime.
+_live_sessions_lock = threading.Lock()
+_live_sessions: weakref.WeakValueDictionary[int, SessionState] = (
+ weakref.WeakValueDictionary()
+)
+
+
+def _current_session_or_default() -> SessionState:
+ """Return the session bound to the current context, or the default."""
+ session = _current_session.get()
+ if session is not None:
+ return session
+ return _default_session
+
+
+def _session_for_hook() -> SessionState:
+ """Resolve the session that owns the current hook invocation.
+
+ Real Claude SDK hook invocations are wrapped by ``_bind_hook_to_session``
+ in ``_client.py``, so the ContextVar should be set. The default session is
+ only for tests or direct, unbound hook calls.
+ """
+ return _current_session_or_default()
+
+
+def _register_session(session: SessionState) -> object:
+ """Bind *session* to the ContextVar and return a reset token.
+
+ The caller must pass the returned token to ``_unregister_session`` when
+ the conversation ends.
+ """
+ with _live_sessions_lock:
+ _live_sessions[id(session)] = session
+ return _current_session.set(session)
+
+
+def _set_session_root(session: SessionState, run_tree: RunTree) -> None:
+ """Store the root LangSmith run for *session*."""
+ session.root_run = run_tree
+
+
+def _unregister_session(session: SessionState, token: Any) -> None:
+ """Reset the ContextVar for the current session and drop the live entry."""
+ try:
+ _current_session.reset(token)
+ except ValueError:
+ # Token was created in a different context. Don't clobber an unrelated
+ # current value — just log and continue. The live-sessions registry
+ # below is still cleaned up so matching won't find a stale session.
+ logger.debug("Could not reset _current_session with token from another context")
+ finally:
+ with _live_sessions_lock:
+ _live_sessions.pop(id(session), None)
+
+
+def _registered_sessions() -> list[SessionState]:
+ """Return currently active client sessions."""
+ with _live_sessions_lock:
+ return list(_live_sessions.values())
+
+
+# ── Public helpers (used by _client.py) ───────────────────────────────────────
+
+
+def get_subagent_run_by_tool_id(tool_use_id: str) -> Optional[RunTree]:
+ """Get a subagent run by the Agent tool's tool_use_id.
+
+ Checks both active subagent runs and ended-but-not-finalised runs,
+ because the SDK fires ``SubagentStop`` before the subagent's messages
+ reach the client.
+ """
+ session = _current_session_or_default()
+ # Check active subagents first
+ for aid, tid in session.agent_to_tool_mapping.items():
+ if tid == tool_use_id:
+ return session.subagent_runs.get(aid)
+ # Fall back to ended-but-not-finalised subagents
+ return session.ended_subagent_runs.get(tool_use_id)
+
+
+# ── Hook functions ────────────────────────────────────────────────────────────
+
+
+async def pre_tool_use_hook(
+ input_data: "HookInput",
+ tool_use_id: Optional[str],
+ context: "HookContext",
+) -> "HookJSONOutput":
+ """Trace tool execution before it starts.
+
+ Args:
+ input_data: Contains `tool_name`, `tool_input`, `session_id`, `agent_id`
+ tool_use_id: Unique identifier for this tool invocation
+ context: Hook context (currently contains only signal)
+
+ Returns:
+ Hook output (empty dict allows execution to proceed)
+ """
+ if not tool_use_id:
+ return {}
+
+ data: dict[str, Any] = dict(input_data) # flatten TypedDict union
+ tool_name: str = str(data.get("tool_name", "unknown_tool"))
+ tool_input: dict[str, Any] = dict(data.get("tool_input") or {})
+ agent_id: Optional[str] = str(data["agent_id"]) if data.get("agent_id") else None
+ session = _session_for_hook()
+
+ # Capture main session transcript path from BaseHookInput
+ if session.main_transcript_path is None and data.get("transcript_path"):
+ session.main_transcript_path = str(data["transcript_path"])
+
+ # If this is an Agent tool call, record it so SubagentStart can find it
+ if tool_name == "Agent":
+ session.pending_agent_tools[tool_use_id] = tool_input
+
+ try:
+ # Determine parent: subagent chain > root chain.
+ # Tool runs are siblings of LLM runs, not children.
+ parent: Optional[RunTree] = None
+ if agent_id and agent_id in session.subagent_runs:
+ parent = session.subagent_runs[agent_id]
+ else:
+ parent = (
+ session.root_run
+ if session is not _default_session
+ else get_parent_run_tree()
+ ) or get_current_run_tree()
+
+ if not parent:
+ return {}
+
+ start_time = time.time()
+ tool_run = parent.create_child(
+ name=tool_name,
+ run_type="tool",
+ inputs={"input": tool_input} if tool_input else {},
+ start_time=datetime.fromtimestamp(start_time, tz=timezone.utc),
+ )
+
+ try:
+ tool_run.post()
+ except Exception as e:
+ logger.warning(f"Failed to post tool run for {tool_name}: {e}")
+
+ session.active_tool_runs[tool_use_id] = (tool_run, start_time)
+
+ except Exception as e:
+ logger.warning(f"Error in PreToolUse hook for {tool_name}: {e}", exc_info=True)
+
+ return {}
+
+
+async def post_tool_use_hook(
+ input_data: "HookInput",
+ tool_use_id: Optional[str],
+ context: "HookContext",
+) -> "HookJSONOutput":
+ """Trace tool execution after it completes.
+
+ Args:
+ input_data: Contains `tool_name`, `tool_input`, `tool_response`,
+ `session_id`, etc.
+ tool_use_id: Unique identifier for this tool invocation
+ context: Hook context (currently contains only signal)
+
+ Returns:
+ Hook output (empty `dict` by default)
+ """
+ if not tool_use_id:
+ return {}
+
+ tool_name: str = str(input_data.get("tool_name", "unknown_tool"))
+ tool_response = input_data.get("tool_response")
+ session = _session_for_hook()
+
+ try:
+ run_info = session.active_tool_runs.pop(tool_use_id, None)
+ if not run_info:
+ return {}
+
+ tool_run, _ = run_info
+
+ if isinstance(tool_response, dict):
+ outputs = tool_response
+ elif isinstance(tool_response, list):
+ outputs = {"content": tool_response}
+ else:
+ outputs = {"output": str(tool_response)} if tool_response else {}
+
+ # Check if the tool execution was an error
+ is_error = False
+ if isinstance(tool_response, dict):
+ is_error = tool_response.get("is_error", False)
+
+ tool_run.end(
+ outputs=outputs,
+ error=outputs.get("output") if is_error else None,
+ )
+
+ try:
+ tool_run.patch()
+ except Exception as e:
+ logger.warning(f"Failed to patch tool run for {tool_name}: {e}")
+
+ # If this is an Agent tool, also set outputs on the stashed
+ # subagent run. We don't end/patch the subagent here because
+ # its AssistantMessages may not have been yielded to
+ # receive_response() yet. clear_active_tool_runs() will
+ # finalise it at the end of the conversation.
+ subagent_run = session.ended_subagent_runs.get(tool_use_id)
+ if subagent_run:
+ try:
+ subagent_run.outputs = outputs
+ except Exception as e:
+ logger.warning(f"Failed to set subagent run outputs: {e}")
+
+ except Exception as e:
+ logger.warning(
+ f"Error in PostToolUse hook for {tool_name}: {e}",
+ exc_info=True,
+ )
+
+ return {}
+
+
+async def post_tool_use_failure_hook(
+ input_data: "HookInput",
+ tool_use_id: Optional[str],
+ context: "HookContext",
+) -> "HookJSONOutput":
+ """Trace tool execution when it fails.
+
+ This hook fires for built-in tool failures (Bash, Read, Write, etc.)
+ and is mutually exclusive with :func:`post_tool_use_hook` — when a
+ built-in tool fails, only ``PostToolUseFailure`` fires.
+
+ Args:
+ input_data: Contains ``tool_name``, ``tool_input``, ``error``,
+ and optionally ``is_interrupt``.
+ tool_use_id: Unique identifier for this tool invocation
+ context: Hook context (currently contains only signal)
+
+ Returns:
+ Hook output (empty dict)
+ """
+ if not tool_use_id:
+ return {}
+
+ tool_name: str = str(input_data.get("tool_name", "unknown_tool"))
+ error: str = str(input_data.get("error", "Unknown error"))
+ session = _session_for_hook()
+
+ try:
+ run_info = session.active_tool_runs.pop(tool_use_id, None)
+ if not run_info:
+ return {}
+
+ tool_run, _ = run_info
+
+ tool_run.end(
+ outputs={"error": error},
+ error=error,
+ )
+
+ try:
+ tool_run.patch()
+ except Exception as e:
+ logger.warning(f"Failed to patch failed tool run for {tool_name}: {e}")
+
+ except Exception as e:
+ logger.warning(
+ f"Error in PostToolUseFailure hook for {tool_name}: {e}",
+ exc_info=True,
+ )
+
+ return {}
+
+
+async def subagent_start_hook(
+ input_data: "HookInput",
+ tool_use_id: Optional[str],
+ context: "HookContext",
+) -> "HookJSONOutput":
+ """Create a chain run when a subagent starts.
+
+ The subagent chain is nested under the Agent tool run that spawned it.
+ Since the SDK passes a different ``tool_use_id`` to this hook than the
+ one from ``PreToolUse`` for the Agent tool, we match them via the
+ ``_pending_agent_tools`` queue.
+
+ Args:
+ input_data: Contains ``agent_id``, ``agent_type``, ``session_id``
+ tool_use_id: SDK-internal session id (not the Agent tool's
+ tool_use_id)
+ context: Hook context
+
+ Returns:
+ Hook output (empty dict)
+ """
+ data: dict[str, Any] = dict(input_data)
+ agent_id: Optional[str] = str(data["agent_id"]) if data.get("agent_id") else None
+ agent_type: str = str(data.get("agent_type") or "subagent")
+ session = _session_for_hook()
+
+ if not agent_id:
+ return {}
+
+ try:
+ # Find the Agent tool run that triggered this subagent.
+ # pending_agent_tools is populated by pre_tool_use_hook when
+ # tool_name == "Agent". Pop the most recent one.
+ agent_tool_use_id: Optional[str] = None
+ agent_tool_input: dict[str, Any] = {}
+ parent: Optional[RunTree] = None
+
+ if session.pending_agent_tools:
+ agent_tool_use_id, agent_tool_input = session.pending_agent_tools.popitem()
+
+ if agent_tool_use_id in session.active_tool_runs:
+ agent_tool_run, _ = session.active_tool_runs[agent_tool_use_id]
+ parent = agent_tool_run
+
+ if parent is None:
+ parent = (
+ session.root_run
+ if session is not _default_session
+ else get_parent_run_tree()
+ ) or get_current_run_tree()
+
+ if not parent:
+ return {}
+
+ start_time = time.time()
+ subagent_run = parent.create_child(
+ name=agent_type,
+ run_type="chain",
+ inputs=agent_tool_input if agent_tool_input else {},
+ start_time=datetime.fromtimestamp(start_time, tz=timezone.utc),
+ )
+ subagent_run.extra["metadata"] = {
+ **subagent_run.extra.get("metadata", {}),
+ "ls_agent_type": "subagent",
+ }
+
+ try:
+ subagent_run.post()
+ except Exception as e:
+ logger.warning(f"Failed to post subagent run: {e}")
+
+ # Store by agent_id so tool hooks and LLM run lookup can find it
+ session.subagent_runs[agent_id] = subagent_run
+
+ # Remember which Agent tool_use_id spawned this agent_id
+ if agent_tool_use_id:
+ session.agent_to_tool_mapping[agent_id] = agent_tool_use_id
+
+ except Exception as e:
+ logger.warning(f"Error in SubagentStart hook: {e}", exc_info=True)
+
+ return {}
+
+
+async def subagent_stop_hook(
+ input_data: "HookInput",
+ tool_use_id: Optional[str],
+ context: "HookContext",
+) -> "HookJSONOutput":
+ """Move the subagent run to ended state when it finishes.
+
+ Does NOT end/patch the run — ``PostToolUse`` for the Agent tool will
+ set outputs, and ``clear_active_tool_runs()`` will finalise it at the
+ end of the conversation.
+
+ Args:
+ input_data: Contains ``agent_id``, ``agent_type``, ``session_id``,
+ ``agent_transcript_path``
+ tool_use_id: SDK-internal session id
+ context: Hook context
+
+ Returns:
+ Hook output (empty dict)
+ """
+ data: dict[str, Any] = dict(input_data)
+ agent_id: Optional[str] = str(data["agent_id"]) if data.get("agent_id") else None
+ transcript_path: Optional[str] = (
+ str(data["agent_transcript_path"])
+ if data.get("agent_transcript_path")
+ else None
+ )
+ session = _session_for_hook()
+
+ if not agent_id:
+ return {}
+
+ try:
+ subagent_run = session.subagent_runs.pop(agent_id, None)
+ if not subagent_run:
+ return {}
+
+ if transcript_path:
+ session.subagent_transcript_paths.append((transcript_path, subagent_run))
+
+ # Move to ended state so PostToolUse can set outputs.
+ agent_tool_id = session.agent_to_tool_mapping.pop(agent_id, None)
+ if agent_tool_id:
+ session.ended_subagent_runs[agent_tool_id] = subagent_run
+ else:
+ # No matching Agent tool — just end it now
+ subagent_run.end()
+ try:
+ subagent_run.patch()
+ except Exception as e:
+ logger.warning(f"Failed to patch subagent run: {e}")
+
+ except Exception as e:
+ logger.warning(f"Error in SubagentStop hook: {e}", exc_info=True)
+
+ return {}
+
+
+# ── Cleanup ───────────────────────────────────────────────────────────────────
+
+
+def clear_active_tool_runs(session: Optional[SessionState] = None) -> None:
+ """Finalise all runs and clear state for *session*.
+
+ If *session* is omitted the current ContextVar-bound session is used
+ (falling back to the module-level default session). ``receive_response``
+ passes the per-call session explicitly.
+ """
+ if session is None:
+ session = _current_session_or_default()
+
+ # 1. End orphaned subagent runs (SubagentStop never fired)
+ for agent_id, subagent_run in session.subagent_runs.items():
+ try:
+ subagent_run.end(error="Subagent run not completed (conversation ended)")
+ subagent_run.patch()
+ except Exception as e:
+ logger.debug(f"Failed to clean up orphaned subagent run {agent_id}: {e}")
+
+ # 2. Finalise ended subagent runs (outputs already set by PostToolUse)
+ for tool_use_id, subagent_run in session.ended_subagent_runs.items():
+ try:
+ subagent_run.end()
+ subagent_run.patch()
+ except Exception as e:
+ logger.debug(f"Failed to finalise ended subagent run {tool_use_id}: {e}")
+
+ # 3. End orphaned tool runs
+ for tool_use_id, (tool_run, _) in session.active_tool_runs.items():
+ try:
+ tool_run.end(error="Tool run not completed (conversation ended)")
+ tool_run.patch()
+ except Exception as e:
+ logger.debug(f"Failed to clean up orphaned tool run {tool_use_id}: {e}")
+
+ # 4. Reset session state
+ session.active_tool_runs.clear()
+ session.subagent_runs.clear()
+ session.pending_agent_tools.clear()
+ session.agent_to_tool_mapping.clear()
+ session.ended_subagent_runs.clear()
+ session.subagent_transcript_paths.clear()
+ session.main_transcript_path = None
+ session.root_run = None
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_messages.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_messages.py
new file mode 100644
index 0000000000000000000000000000000000000000..102c5640b710b6530b6a69f09239946299c9228d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_messages.py
@@ -0,0 +1,112 @@
+"""Message processing and content serialization for Claude Agent SDK."""
+
+from typing import Any
+
+
+def _extract_tool_result_text(content: Any) -> str:
+ """Extract text content from tool result content blocks."""
+ if content is None:
+ return ""
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ texts = []
+ for item in content:
+ if isinstance(item, dict):
+ if item.get("type") == "text":
+ texts.append(item.get("text", ""))
+ elif hasattr(item, "text"):
+ texts.append(getattr(item, "text", ""))
+ return "\n".join(texts) if texts else str(content)
+ return str(content)
+
+
+def flatten_content_blocks(content: Any) -> Any:
+ """Convert SDK content blocks into serializable dicts using explicit type checks."""
+ if not isinstance(content, list):
+ return content
+
+ result = []
+ for block in content:
+ block_type = type(block).__name__
+
+ # Handle known Claude SDK block types
+ if block_type == "TextBlock":
+ result.append(
+ {
+ "type": "text",
+ "text": getattr(block, "text", ""),
+ }
+ )
+ elif block_type == "ThinkingBlock":
+ result.append(
+ {
+ "type": "thinking",
+ "thinking": getattr(block, "thinking", ""),
+ "signature": getattr(block, "signature", ""),
+ }
+ )
+ elif block_type == "ToolUseBlock":
+ result.append(
+ {
+ "type": "tool_use",
+ "id": getattr(block, "id", None),
+ "name": getattr(block, "name", None),
+ "input": getattr(block, "input", None),
+ }
+ )
+ elif block_type == "ToolResultBlock":
+ # Extract text from nested content for tool results
+ tool_content = getattr(block, "content", None)
+ content_text = _extract_tool_result_text(tool_content)
+ result.append(
+ {
+ "type": "tool_result",
+ "tool_use_id": getattr(block, "tool_use_id", None),
+ "content": content_text,
+ "is_error": getattr(block, "is_error", False),
+ }
+ )
+ else:
+ result.append(block)
+ return result
+
+
+def unwrap_message_dicts(messages: list[Any]) -> list[dict[str, Any]]:
+ """Normalize SDK message dicts into ``{role, content}`` form.
+
+ The Claude SDK wraps messages in ``{"message": {"role": ..., "content": ...}}``
+ envelopes. This function unwraps them into a flat list.
+ """
+ result: list[dict[str, Any]] = []
+ for msg in messages:
+ if not isinstance(msg, dict):
+ result.append(msg)
+ continue
+ if "message" in msg:
+ inner = msg["message"]
+ if isinstance(inner, dict):
+ result.append(
+ {
+ "role": inner.get("role", "user"),
+ "content": inner.get("content", ""),
+ }
+ )
+ else:
+ result.append(msg)
+ else:
+ result.append(msg)
+ return result
+
+
+def build_llm_input(prompt: Any, history: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Construct a combined prompt + history message list."""
+ if isinstance(prompt, str):
+ entry = {"content": prompt, "role": "user"}
+ return [entry, *history] if history else [entry]
+
+ if isinstance(prompt, list):
+ formatted = unwrap_message_dicts(prompt)
+ return [*formatted, *history] if history else formatted
+
+ return list(history) if history else []
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_tools.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b15ef7ff9628c865e98cb3e7f0e2c87483ad8e2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_tools.py
@@ -0,0 +1,43 @@
+"""Context-var storage utilities for Claude Agent SDK tracing.
+
+This module stores the *parent run tree* — the root chain span opened by
+``_traced_receive_response`` — for direct/default-session hook calls. Real
+instrumented client sessions primarily parent hook spans via
+``SessionState.root_run``.
+
+A :class:`contextvars.ContextVar` is used so concurrent conversations on the
+same thread (e.g. multiple ``ClaudeSDKClient`` instances driven by
+``asyncio.gather``) each see their own parent run tree.
+"""
+
+from contextvars import ContextVar
+from typing import Any, Optional
+
+_parent_run_tree: ContextVar[Optional[Any]] = ContextVar(
+ "langsmith_claude_agent_parent_run_tree", default=None
+)
+
+
+def set_parent_run_tree(run_tree: Any) -> Any:
+ """Bind *run_tree* to the current context and return a reset token."""
+ return _parent_run_tree.set(run_tree)
+
+
+def clear_parent_run_tree(token: Any = None) -> None:
+ """Reset the parent run tree in the current context.
+
+ If a *token* from :func:`set_parent_run_tree` is provided, it is used
+ to restore the previous value; otherwise the context is cleared.
+ """
+ if token is not None:
+ try:
+ _parent_run_tree.reset(token)
+ except ValueError:
+ _parent_run_tree.set(None)
+ else:
+ _parent_run_tree.set(None)
+
+
+def get_parent_run_tree() -> Any:
+ """Return the parent run tree bound to the current context."""
+ return _parent_run_tree.get()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_transcripts.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_transcripts.py
new file mode 100644
index 0000000000000000000000000000000000000000..533089ab31076b294f7a7ffbf0de6b05bee8a85b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_transcripts.py
@@ -0,0 +1,172 @@
+"""Post-conversation transcript reconciliation.
+
+After a conversation ends this module:
+
+1. Creates LLM runs for subagent turns that were not relayed through
+ the parent stream (the SDK only streams the first assistant message
+ per subagent; subsequent turns are folded into the Agent tool result).
+
+2. Patches accurate token usage onto all LLM runs from the JSONL
+ transcripts (the live stream only has partial streaming counts).
+
+.. note::
+
+ The transcript JSONL format is **not a contracted API** of the Claude
+ Agent SDK. Changes to the format could silently degrade trace
+ fidelity. If the SDK begins relaying all subagent messages through
+ the stream, step 1 becomes a no-op (the dedup guard skips already-
+ seen ``message_id`` values).
+"""
+
+import logging
+from datetime import datetime
+from typing import TYPE_CHECKING, Any, Optional
+
+from ._hooks import SessionState, _current_session_or_default
+from ._usage import (
+ extract_usage_metadata,
+ read_llm_turns_from_transcript,
+ read_usage_from_transcript,
+)
+
+if TYPE_CHECKING:
+ from ._client import TurnLifecycle
+
+logger = logging.getLogger(__name__)
+
+LLM_RUN_NAME = "claude.assistant.turn"
+
+
+def reconcile_from_transcripts(
+ tracker: "TurnLifecycle",
+ session: Optional[SessionState] = None,
+) -> None:
+ """Read transcripts and reconcile LLM runs.
+
+ This function does two things after the conversation ends:
+
+ 1. **Missing subagent LLM runs** — creates LLM runs for subagent
+ turns whose ``message_id`` is not already in
+ ``tracker.llm_runs_by_message_id``.
+
+ 2. **Usage correction** — patches accurate usage from the JSONL
+ transcripts onto all LLM runs (both streamed and synthetic).
+
+ If *session* is omitted the current ContextVar-bound session (or the
+ module-level default) is used. The caller in ``receive_response``
+ passes the per-conversation session explicitly to stay safe under
+ concurrent tracing.
+ """
+ if session is None:
+ session = _current_session_or_default()
+ _create_missing_subagent_llm_runs(tracker, session)
+ _patch_usage_on_llm_runs(tracker, session)
+
+
+# ── Step 1: synthetic subagent LLM runs ─────────────────────────────
+
+
+def _create_missing_subagent_llm_runs(
+ tracker: "TurnLifecycle",
+ session: SessionState,
+) -> None:
+ # Guard against the same message_id being processed twice (e.g. if
+ # the same transcript path appears multiple times in the list).
+ created: set[str] = set()
+ for path, subagent_run in session.subagent_transcript_paths:
+ try:
+ turns = read_llm_turns_from_transcript(path)
+ for turn in turns:
+ mid = turn["message_id"]
+ if mid in tracker.llm_runs_by_message_id:
+ continue
+ if mid in created:
+ continue
+
+ ts = _parse_timestamp(turn.get("timestamp"))
+
+ input_messages = turn.get("input_messages", [])
+ llm_metadata: dict[str, Any] = {
+ "ls_provider": "anthropic",
+ }
+ if turn.get("model"):
+ llm_metadata["ls_model_name"] = turn["model"]
+
+ llm_run = subagent_run.create_child(
+ name=LLM_RUN_NAME,
+ run_type="llm",
+ inputs={"messages": input_messages} if input_messages else {},
+ extra={"metadata": llm_metadata},
+ start_time=ts,
+ )
+
+ llm_run.outputs = {
+ "content": turn.get("content", []),
+ "role": "assistant",
+ }
+
+ raw_usage = turn.get("usage")
+ if raw_usage:
+ usage_meta = extract_usage_metadata(raw_usage)
+ if usage_meta:
+ meta = llm_run.extra.setdefault("metadata", {})
+ meta["usage_metadata"] = usage_meta
+
+ llm_run.end(end_time=ts)
+ try:
+ llm_run.post()
+ llm_run.patch()
+ except Exception as e:
+ logger.warning(f"Failed to post/patch subagent LLM run: {e}")
+
+ tracker.llm_runs_by_message_id[mid] = llm_run
+ created.add(mid)
+ logger.debug(f"Created missing subagent LLM run for message {mid}")
+ except Exception as e:
+ logger.warning(
+ f"Failed to create subagent LLM runs from {path}: {e}",
+ exc_info=True,
+ )
+
+
+# ── Step 2: usage patching ──────────────────────────────────────────
+
+
+def _patch_usage_on_llm_runs(
+ tracker: "TurnLifecycle",
+ session: SessionState,
+) -> None:
+ if not tracker.llm_runs_by_message_id:
+ return
+
+ all_usage: dict[str, dict[str, Any]] = {}
+
+ main_path = session.main_transcript_path
+ if main_path:
+ all_usage.update(read_usage_from_transcript(main_path))
+
+ for path, _run in session.subagent_transcript_paths:
+ all_usage.update(read_usage_from_transcript(path))
+
+ patched = 0
+ for message_id, run in tracker.llm_runs_by_message_id.items():
+ usage = all_usage.get(message_id)
+ if usage:
+ meta = run.extra.setdefault("metadata", {})
+ meta["usage_metadata"] = usage
+ patched += 1
+
+ if patched:
+ logger.debug(f"Set usage on {patched} LLM run(s) from transcripts")
+
+
+# ── Helpers ─────────────────────────────────────────────────────────
+
+
+def _parse_timestamp(value: Optional[str]) -> Optional[datetime]:
+ if not value:
+ return None
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except (ValueError, TypeError):
+ return None
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_usage.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_usage.py
new file mode 100644
index 0000000000000000000000000000000000000000..46a6e679b37ebc61a5ce689b43839d112bed239f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/claude_agent_sdk/_usage.py
@@ -0,0 +1,248 @@
+"""Token usage utilities for Claude Agent SDK.
+
+Normalizes raw Anthropic usage dicts into the canonical ``usage_metadata``
+format expected by LangSmith. The key Anthropic-specific behavior is that
+cache tokens (``cache_read_input_tokens`` and ``cache_creation_input_tokens``)
+are **additive** — they are *not* included in the raw ``input_tokens`` value,
+so they must be summed in.
+
+The canonical shape matches the JS LangSmith SDK's ``createUsageMetadata``:
+
+.. code-block:: json
+
+ {
+ "input_tokens": 21400,
+ "output_tokens": 7,
+ "total_tokens": 21407,
+ "input_token_details": {
+ "cache_read": 21375,
+ "ephemeral_5m_input_tokens": 0,
+ "ephemeral_1hr_input_tokens": 0
+ }
+ }
+"""
+
+import json
+import logging
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+
+def _to_int(value: Any) -> int:
+ try:
+ return int(value)
+ except (ValueError, TypeError):
+ return 0
+
+
+def extract_usage_metadata(usage: Any) -> dict[str, Any]:
+ """Normalize a raw Anthropic usage dict into canonical ``usage_metadata``.
+
+ Anthropic cache tokens are **additive**: ``cache_read_input_tokens`` and
+ ``cache_creation_input_tokens`` are not included in the raw
+ ``input_tokens``, so we sum them in to get the true input total.
+ """
+ if not usage:
+ return {}
+
+ get = (
+ usage.get if isinstance(usage, dict) else lambda k, d=None: getattr(usage, k, d)
+ )
+
+ raw_input = _to_int(get("input_tokens"))
+ output_tokens = _to_int(get("output_tokens"))
+
+ # Build input_token_details from cache fields
+ input_token_details: dict[str, int] = {}
+
+ cache_read = _to_int(get("cache_read_input_tokens"))
+ if cache_read:
+ input_token_details["cache_read"] = cache_read
+
+ # Structured cache_creation (with ephemeral breakdown) takes precedence
+ # over the flat cache_creation_input_tokens field.
+ cache_creation = get("cache_creation")
+ if isinstance(cache_creation, dict):
+ eph_5m = _to_int(cache_creation.get("ephemeral_5m_input_tokens"))
+ eph_1h = _to_int(cache_creation.get("ephemeral_1h_input_tokens"))
+ if eph_5m:
+ input_token_details["ephemeral_5m_input_tokens"] = eph_5m
+ if eph_1h:
+ input_token_details["ephemeral_1hr_input_tokens"] = eph_1h
+ else:
+ # Flat/legacy field — assume 5-minute cache
+ flat_cache_create = _to_int(get("cache_creation_input_tokens"))
+ if flat_cache_create:
+ input_token_details["ephemeral_5m_input_tokens"] = flat_cache_create
+
+ # Sum cache tokens into input_tokens (Anthropic cache tokens are additive)
+ cache_token_sum = sum(input_token_details.values())
+ adjusted_input = raw_input + cache_token_sum
+ total_tokens = adjusted_input + output_tokens
+
+ meta: dict[str, Any] = {
+ "input_tokens": adjusted_input,
+ "output_tokens": output_tokens,
+ "total_tokens": total_tokens,
+ }
+ if input_token_details:
+ meta["input_token_details"] = input_token_details
+
+ return meta
+
+
+def read_usage_from_transcript(
+ file_path: str,
+) -> dict[str, dict[str, Any]]:
+ """Read a JSONL transcript and return final usage per message_id.
+
+ The Claude SDK streams assistant messages as multiple JSONL chunks
+ with the same ``message.id``. Only the final chunk (where
+ ``stop_reason`` is set) has accurate ``output_tokens``.
+
+ Returns:
+ ``{message_id: usage_metadata}`` with canonical usage dicts.
+ """
+ try:
+ path = Path(file_path)
+ if not path.exists():
+ return {}
+
+ # Collect the last usage seen per message_id — the final chunk
+ # (with stop_reason set) overwrites earlier partials.
+ raw_usage: dict[str, dict[str, Any]] = {}
+ with open(path) as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ data = json.loads(line)
+ except (json.JSONDecodeError, ValueError):
+ continue
+ if data.get("type") != "assistant":
+ continue
+ msg = data.get("message", {})
+ msg_id = msg.get("id")
+ usage = msg.get("usage")
+ if not msg_id or not usage:
+ continue
+ # Always overwrite — later chunks have better counts.
+ # The final chunk (with stop_reason) is last.
+ raw_usage[msg_id] = usage
+
+ return {mid: extract_usage_metadata(u) for mid, u in raw_usage.items() if u}
+ except OSError as e:
+ logger.debug(f"Could not read transcript {file_path}: {e}")
+ return {}
+
+
+def read_llm_turns_from_transcript(
+ file_path: str,
+) -> list[dict[str, Any]]:
+ """Read final LLM turns from a JSONL transcript.
+
+ Each API request produces two assistant entries in the transcript
+ (a streaming partial and a final completion) sharing the same
+ ``message.id``. Only the **final** entry (with ``stop_reason`` set)
+ is returned.
+
+ Returns a list of dicts ordered by appearance, each containing::
+
+ {
+ "message_id": str,
+ "model": str,
+ "content": list[dict], # Anthropic content blocks
+ "stop_reason": str, # "end_turn" or "tool_use"
+ "usage": dict, # raw Anthropic usage dict
+ "timestamp": str | None, # ISO 8601 timestamp
+ "input_messages": list[dict], # preceding conversation messages
+ }
+ """
+ try:
+ path = Path(file_path)
+ if not path.exists():
+ return []
+
+ # Single pass: build a running conversation history so each
+ # assistant turn gets the full message context the API saw.
+ # Tool result blocks are formatted as role:"tool" messages.
+ entries_by_id: dict[str, dict[str, Any]] = {}
+ conversation: list[dict[str, Any]] = []
+ with open(path) as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ data = json.loads(line)
+ except (json.JSONDecodeError, ValueError):
+ continue
+
+ entry_type = data.get("type")
+
+ if entry_type == "user":
+ msg = data.get("message", {})
+ content = msg.get("content")
+ if content is None:
+ continue
+ # Detect tool_result blocks and format as tool
+ # messages, matching the live stream formatting.
+ if isinstance(content, list) and content:
+ is_tool_result = any(
+ isinstance(b, dict) and b.get("type") == "tool_result"
+ for b in content
+ )
+ if is_tool_result:
+ for block in content:
+ if (
+ isinstance(block, dict)
+ and block.get("type") == "tool_result"
+ ):
+ conversation.append(
+ {
+ "role": "tool",
+ "content": block.get("content", ""),
+ "tool_call_id": block.get("tool_use_id"),
+ }
+ )
+ continue
+ conversation.append({"role": "user", "content": content})
+ continue
+
+ if entry_type != "assistant":
+ continue
+
+ msg = data.get("message", {})
+ msg_id = msg.get("id")
+ if not msg_id:
+ continue
+ # Always overwrite — the final entry (with stop_reason)
+ # comes last for each message_id.
+ entries_by_id[msg_id] = {
+ "message_id": msg_id,
+ "model": msg.get("model"),
+ "content": msg.get("content", []),
+ "stop_reason": msg.get("stop_reason"),
+ "usage": msg.get("usage"),
+ "timestamp": data.get("timestamp"),
+ # Full conversation history up to this turn.
+ "input_messages": list(conversation),
+ }
+ # Add completed assistant content to conversation
+ # so subsequent turns see it.
+ if msg.get("stop_reason"):
+ conversation.append(
+ {
+ "role": "assistant",
+ "content": msg.get("content", []),
+ }
+ )
+
+ # Only return final entries (stop_reason is set).
+ return [e for e in entries_by_id.values() if e.get("stop_reason")]
+ except OSError as e:
+ logger.debug(f"Could not read transcript {file_path}: {e}")
+ return []
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..63fa7c23ec79b2f4461d244016bf87dd95b5a2ef
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__init__.py
@@ -0,0 +1,127 @@
+"""LangSmith integration for Google ADK (Agent Development Kit)."""
+
+from __future__ import annotations
+
+import logging
+from typing import Optional
+
+from ._config import set_tracing_config
+
+logger = logging.getLogger(__name__)
+
+__all__ = ["configure_google_adk", "create_traced_session_context"]
+
+_patched = False
+
+
+def configure_google_adk(
+ name: Optional[str] = None,
+ project_name: Optional[str] = None,
+ metadata: Optional[dict] = None,
+ tags: Optional[list[str]] = None,
+) -> bool:
+ """Enable LangSmith tracing for Google ADK.
+
+ Can be called before or after importing Runner (import-order agnostic).
+
+ Args:
+ name: Name of the root trace. Defaults to "google_adk.session".
+ project_name: LangSmith project to trace to.
+ metadata: Metadata to associate with all traces.
+ tags: Tags to associate with all traces.
+
+ Returns:
+ True if configuration was successful, False otherwise.
+ """
+ global _patched
+
+ if _patched:
+ set_tracing_config(
+ name=name, project_name=project_name, metadata=metadata, tags=tags
+ )
+ return True
+
+ try:
+ import google.adk # noqa: F401
+ from wrapt import wrap_function_wrapper # type: ignore[import-untyped]
+ except ImportError as e:
+ logger.warning(f"Missing dependency: {e}")
+ return False
+
+ set_tracing_config(
+ name=name, project_name=project_name, metadata=metadata, tags=tags
+ )
+
+ from ._client import (
+ wrap_agent_run_async,
+ wrap_flow_call_llm_async,
+ wrap_runner_run,
+ wrap_runner_run_async,
+ wrap_tool_run_async,
+ )
+
+ _wraps = [
+ (
+ "google.adk.runners",
+ "Runner.run",
+ wrap_runner_run,
+ ),
+ (
+ "google.adk.runners",
+ "Runner.run_async",
+ wrap_runner_run_async,
+ ),
+ (
+ "google.adk.agents.base_agent",
+ "BaseAgent.run_async",
+ wrap_agent_run_async,
+ ),
+ (
+ "google.adk.flows.llm_flows.base_llm_flow",
+ "BaseLlmFlow._call_llm_async",
+ wrap_flow_call_llm_async,
+ ),
+ (
+ "google.adk.tools.base_tool",
+ "BaseTool.run_async",
+ wrap_tool_run_async,
+ ),
+ (
+ "google.adk.tools.function_tool",
+ "FunctionTool.run_async",
+ wrap_tool_run_async,
+ ),
+ (
+ "google.adk.tools.mcp_tool.mcp_tool",
+ "McpTool.run_async",
+ wrap_tool_run_async,
+ ),
+ ]
+
+ for module, name, wrapper in _wraps:
+ try:
+ wrap_function_wrapper(module, name, wrapper)
+ except Exception as e:
+ logger.warning(f"Failed to wrap {name}: {e}")
+
+ _patched = True
+ return True
+
+
+def create_traced_session_context(
+ name: Optional[str] = None,
+ project_name: Optional[str] = None,
+ metadata: Optional[dict] = None,
+ tags: Optional[list[str]] = None,
+ inputs: Optional[dict] = None,
+):
+ """Create a trace context for manual session tracing."""
+ from ._client import create_traced_session_context as _create_context
+
+ return _create_context(
+ name=name,
+ project_name=project_name,
+ metadata=metadata,
+ tags=tags,
+ inputs=inputs,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0bb95fa7bca1978083bd360384b9379181486bb
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/_client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/_client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea67b471095b2de0d6f69441d7232cd7a4ba9438
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/_client.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/_config.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/_config.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8cf3d4f78851ddc07f288435947e378a3100ac5d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/_config.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/_messages.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/_messages.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..728c229f74ad13b5aae25d0eefc93cbf1dbdeb12
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/_messages.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/_usage.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/_usage.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e3f296e1294a1537e0590206e14e915a922ef400
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/__pycache__/_usage.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe521eb9c4b923606c7afded9921679c928b508b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/_client.py
@@ -0,0 +1,489 @@
+"""Client instrumentation for Google ADK using wrapt."""
+
+from __future__ import annotations
+
+import json
+import logging
+import time
+from collections.abc import AsyncGenerator
+from contextlib import aclosing
+from datetime import datetime, timezone
+from functools import cache
+from typing import Any, Optional
+
+from langsmith.run_helpers import get_current_run_tree, set_tracing_parent, trace
+
+from ._config import get_tracing_config
+from ._messages import convert_llm_request_to_messages, has_function_calls
+from ._usage import extract_model_name, extract_usage_from_response
+
+_LS_PROVIDER_VERTEXAI = "google_vertexai"
+_LS_PROVIDER_GOOGLE_AI = "google_ai"
+
+
+def extract_tools_from_llm_request(llm_request: Any) -> list[dict[str, Any]]:
+ """Extract tool definitions from LlmRequest and convert to OpenAI format."""
+ config = getattr(llm_request, "config", None)
+ if not config:
+ return []
+
+ tools_list = getattr(config, "tools", None)
+ if not tools_list:
+ return []
+
+ result = []
+ for tool in tools_list:
+ for func_decl in getattr(tool, "function_declarations", None) or []:
+ try:
+ dumped = func_decl.model_dump(exclude_none=True)
+ result.append(
+ {
+ "type": "function",
+ "function": dumped,
+ }
+ )
+ except Exception:
+ pass
+
+ return result
+
+
+def _get_ls_provider() -> str:
+ """Detect provider based on GOOGLE_GENAI_USE_VERTEXAI env var."""
+ import os
+
+ use_vertexai = os.environ.get("GOOGLE_GENAI_USE_VERTEXAI", "0").lower() in (
+ "1",
+ "true",
+ "yes",
+ )
+ return _LS_PROVIDER_VERTEXAI if use_vertexai else _LS_PROVIDER_GOOGLE_AI
+
+
+logger = logging.getLogger(__name__)
+
+TRACE_CHAIN_NAME = "google_adk.session"
+
+
+@cache
+def _get_package_version(package_name: str) -> str | None:
+ try:
+ from importlib.metadata import version
+
+ return version(package_name)
+ except Exception:
+ return None
+
+
+# Attribute name used to bridge the root run from Runner.run (sync) into the
+# background thread where Runner.run_async executes. Runner.run spins up a
+# new thread for its internal asyncio event loop, so context vars don't
+# propagate automatically. Storing the run on the instance (a plain object
+# attribute) crosses the thread boundary, and wrap_runner_run_async picks it
+# up and re-establishes it as a context var.
+_SYNC_ROOT_RUN_ATTR = "_langsmith_root_run"
+
+
+def _extract_text_from_content(content: Any) -> Optional[str]:
+ if content is None:
+ return None
+ parts = getattr(content, "parts", None)
+ if not parts:
+ return None
+ text_parts = [str(p.text) for p in parts if getattr(p, "text", None)]
+ return " ".join(text_parts) if text_parts else None
+
+
+def _iter_invocation_events(ctx: Any) -> list[Any]:
+ """Get session events for the current invocation."""
+ session = getattr(ctx, "session", None)
+ if session is None:
+ return []
+ invocation_id = getattr(ctx, "invocation_id", None)
+ events = getattr(session, "events", None) or []
+ if invocation_id is None:
+ return list(events)
+ return [e for e in events if getattr(e, "invocation_id", None) == invocation_id]
+
+
+def _extract_latest_invocation_text(ctx: Any) -> Optional[str]:
+ """Get the latest text from session events for the current invocation."""
+ for event in reversed(_iter_invocation_events(ctx)):
+ text = _extract_text_from_content(getattr(event, "content", None))
+ if text:
+ return text
+ return None
+
+
+def wrap_runner_run(wrapped: Any, instance: Any, args: Any, kwargs: Any) -> Any:
+ """Wrap Runner.run to create a root trace for synchronous execution.
+
+ Runner.run internally starts a new thread to run its async event loop, so
+ context vars set here would not be visible to code running in that thread.
+ We bridge the gap by storing the root run on the instance (a plain object
+ attribute that IS visible across threads) so that wrap_runner_run_async can
+ re-establish it as a context var inside the async event loop.
+ """
+ config = get_tracing_config()
+ trace_name = config.get("name") or TRACE_CHAIN_NAME
+
+ trace_inputs: dict[str, Any] = {}
+ if new_message := kwargs.get("new_message"):
+ if text := _extract_text_from_content(new_message):
+ trace_inputs["input"] = text
+
+ trace_metadata: dict[str, Any] = {
+ "ls_provider": _get_ls_provider(),
+ "ls_integration": "google-adk",
+ "ls_integration_version": _get_package_version("google-adk"),
+ **(config.get("metadata") or {}),
+ }
+ if app_name := getattr(instance, "app_name", None):
+ trace_metadata["app_name"] = app_name
+ if user_id := kwargs.get("user_id"):
+ trace_metadata["user_id"] = user_id
+ if session_id := kwargs.get("session_id"):
+ trace_metadata["session_id"] = session_id
+
+ def _trace_run():
+ with trace(
+ name=trace_name,
+ run_type="chain",
+ inputs=trace_inputs,
+ project_name=config.get("project_name"),
+ tags=config.get("tags"),
+ metadata=trace_metadata,
+ ) as root_run:
+ setattr(instance, _SYNC_ROOT_RUN_ATTR, root_run)
+ try:
+ events = list(wrapped(*args, **kwargs))
+ final_output = None
+ for event in reversed(events):
+ if content := getattr(event, "content", None):
+ if text := _extract_text_from_content(content):
+ final_output = text
+ break
+ root_run.end(outputs={"output": final_output} if final_output else None)
+ yield from events
+ except Exception as e:
+ root_run.end(error=str(e))
+ raise
+ finally:
+ setattr(instance, _SYNC_ROOT_RUN_ATTR, None)
+
+ return _trace_run()
+
+
+async def wrap_runner_run_async(
+ wrapped: Any, instance: Any, args: Any, kwargs: Any
+) -> Any:
+ """Wrap Runner.run_async to create a root trace for asynchronous execution.
+
+ When called from the background thread spawned by Runner.run, the root run
+ stored on the instance is re-established as a context var so that
+ wrap_agent_run_async and wrap_flow_call_llm_async can find the parent via
+ get_current_run_tree().
+ """
+ root_run = getattr(instance, _SYNC_ROOT_RUN_ATTR, None)
+ if root_run is not None:
+ # sync bridge: re-establish root run as context var in this thread
+ with set_tracing_parent(root_run):
+ async with aclosing(wrapped(*args, **kwargs)) as agen:
+ async for event in agen:
+ yield event
+ return
+
+ config = get_tracing_config()
+ trace_name = config.get("name") or TRACE_CHAIN_NAME
+
+ trace_inputs: dict[str, Any] = {}
+ if new_message := kwargs.get("new_message"):
+ if text := _extract_text_from_content(new_message):
+ trace_inputs["input"] = text
+
+ trace_metadata: dict[str, Any] = {
+ "ls_provider": _get_ls_provider(),
+ "ls_integration": "google-adk",
+ "ls_integration_version": _get_package_version("google-adk"),
+ **(config.get("metadata") or {}),
+ }
+ if app_name := getattr(instance, "app_name", None):
+ trace_metadata["app_name"] = app_name
+ if user_id := kwargs.get("user_id"):
+ trace_metadata["user_id"] = user_id
+ if session_id := kwargs.get("session_id"):
+ trace_metadata["session_id"] = session_id
+
+ async def _trace_run_async() -> AsyncGenerator[Any, None]:
+ async with trace(
+ name=trace_name,
+ run_type="chain",
+ inputs=trace_inputs,
+ project_name=config.get("project_name"),
+ tags=config.get("tags"),
+ metadata=trace_metadata,
+ ) as run:
+ try:
+ final_output: Optional[str] = None
+ async with aclosing(wrapped(*args, **kwargs)) as agen:
+ async for event in agen:
+ if content := getattr(event, "content", None):
+ if text := _extract_text_from_content(content):
+ final_output = text
+ yield event
+ run.end(outputs={"output": final_output} if final_output else None)
+ except Exception as e:
+ run.end(error=str(e))
+ raise
+
+ async for event in _trace_run_async():
+ yield event
+
+
+async def wrap_agent_run_async(
+ wrapped: Any, instance: Any, args: Any, kwargs: Any
+) -> Any:
+ """Wrap BaseAgent.run_async to create a chain span for each agent invocation."""
+ parent = get_current_run_tree()
+ if not parent:
+ async with aclosing(wrapped(*args, **kwargs)) as agen:
+ async for event in agen:
+ yield event
+ return
+
+ ctx = args[0] if args else kwargs.get("parent_context")
+ agent_name = getattr(instance, "name", None) or type(instance).__name__
+
+ inputs: dict[str, Any] = {}
+ if ctx is not None:
+ if latest := _extract_latest_invocation_text(ctx):
+ inputs["input"] = latest
+
+ async with trace(name=agent_name, run_type="chain", inputs=inputs) as agent_run:
+ try:
+ final_output: Optional[str] = None
+ async with aclosing(wrapped(*args, **kwargs)) as agen:
+ async for event in agen:
+ if content := getattr(event, "content", None):
+ if text := _extract_text_from_content(content):
+ final_output = text
+ yield event
+ agent_run.end(outputs={"output": final_output} if final_output else None)
+ except Exception as e:
+ agent_run.end(error=str(e))
+ raise
+
+
+async def wrap_tool_run_async(
+ wrapped: Any, instance: Any, args: Any, kwargs: Any
+) -> Any:
+ """Wrap BaseTool.run_async (all tool subclasses) to trace tool invocations."""
+ parent = get_current_run_tree()
+ if not parent:
+ return await wrapped(*args, **kwargs)
+
+ tool_name = getattr(instance, "name", None) or type(instance).__name__
+ tool_args = kwargs.get("args") or (args[0] if args else {})
+ inputs = tool_args if isinstance(tool_args, dict) else {"args": tool_args}
+
+ start_time = time.time()
+ tool_run = parent.create_child(
+ name=tool_name,
+ run_type="tool",
+ inputs=inputs,
+ extra={"metadata": {"ls_provider": _get_ls_provider()}},
+ start_time=datetime.fromtimestamp(start_time, tz=timezone.utc),
+ )
+
+ try:
+ tool_run.post()
+ except Exception as e:
+ logger.debug(f"Failed to post tool run: {e}")
+
+ try:
+ result = await wrapped(*args, **kwargs)
+ if isinstance(result, dict):
+ outputs = result
+ elif isinstance(result, list):
+ outputs = {"content": result}
+ elif result is not None:
+ outputs = {"output": str(result)}
+ else:
+ outputs = {}
+ tool_run.end(outputs=outputs)
+ try:
+ tool_run.patch()
+ except Exception as e:
+ logger.debug(f"Failed to patch tool run: {e}")
+ return result
+ except Exception as e:
+ tool_run.end(error=str(e))
+ try:
+ tool_run.patch()
+ except Exception as patch_e:
+ logger.debug(f"Failed to patch tool run on error: {patch_e}")
+ raise
+
+
+def _determine_llm_call_type(llm_request: Any, llm_response: Any) -> str:
+ try:
+ for content in getattr(llm_request, "contents", None) or []:
+ for part in getattr(content, "parts", None) or []:
+ if hasattr(part, "function_response") and part.function_response:
+ return "response_generation"
+ if has_function_calls(llm_response):
+ return "tool_selection"
+ return "direct_response"
+ except Exception:
+ return "unknown"
+
+
+async def wrap_flow_call_llm_async(
+ wrapped: Any, instance: Any, args: Any, kwargs: Any
+) -> Any:
+ """Wrap BaseLlmFlow._call_llm_async to capture LLM calls with TTFT tracking."""
+ parent = get_current_run_tree()
+ if not parent:
+ async for event in wrapped(*args, **kwargs):
+ yield event
+ return
+
+ llm_request = args[1] if len(args) > 1 else kwargs.get("llm_request")
+ model_name = extract_model_name(llm_request) if llm_request else None
+ messages = convert_llm_request_to_messages(llm_request) if llm_request else None
+ tools = extract_tools_from_llm_request(llm_request) if llm_request else []
+
+ inputs: dict[str, Any] = {}
+ if messages:
+ inputs["messages"] = messages
+
+ metadata: dict[str, Any] = {"ls_provider": _get_ls_provider()}
+ if model_name:
+ metadata["ls_model_name"] = model_name
+
+ # Build extra dict with invocation_params if tools exist
+ extra: dict[str, Any] = {"metadata": metadata}
+ if tools:
+ extra["invocation_params"] = {"tools": tools}
+
+ start_time = time.time()
+ llm_run = parent.create_child(
+ name=model_name or "google_adk_llm",
+ run_type="llm",
+ inputs=inputs,
+ extra=extra,
+ start_time=datetime.fromtimestamp(start_time, tz=timezone.utc),
+ )
+
+ try:
+ llm_run.post()
+ except Exception as e:
+ logger.debug(f"Failed to post LLM run: {e}")
+
+ first_token_time: Optional[float] = None
+ last_event = None
+ event_with_content = None
+
+ try:
+ async with aclosing(wrapped(*args, **kwargs)) as agen:
+ async for event in agen:
+ is_partial = getattr(event, "partial", False)
+
+ if first_token_time is None and is_partial:
+ first_token_time = time.time()
+ try:
+ llm_run.add_event(
+ {
+ "name": "new_token",
+ "time": datetime.fromtimestamp(
+ first_token_time, tz=timezone.utc
+ ).isoformat(),
+ }
+ )
+ except Exception as e:
+ logger.debug(f"Failed to add new_token event: {e}")
+
+ last_event = event
+ if hasattr(event, "content") and event.content is not None:
+ event_with_content = event
+ yield event
+
+ outputs: dict[str, Any] = {"role": "assistant"}
+ content_source = event_with_content or last_event
+
+ if (
+ content_source
+ and hasattr(content_source, "content")
+ and content_source.content
+ ):
+ parts = getattr(content_source.content, "parts", None) or []
+ text_parts, tool_calls = [], []
+
+ for i, part in enumerate(parts):
+ if hasattr(part, "text") and part.text:
+ text_parts.append(str(part.text))
+ elif hasattr(part, "function_call") and part.function_call:
+ fc = part.function_call
+ tool_calls.append(
+ {
+ "id": f"call_{i}",
+ "type": "function",
+ "function": {
+ "name": getattr(fc, "name", ""),
+ "arguments": json.dumps(
+ dict(fc.args) if getattr(fc, "args", None) else {}
+ ),
+ },
+ }
+ )
+
+ outputs["content"] = " ".join(text_parts) if text_parts else None
+ if tool_calls:
+ outputs["tool_calls"] = tool_calls
+
+ if last_event:
+ if usage := extract_usage_from_response(last_event):
+ llm_run.extra.setdefault("metadata", {})["usage_metadata"] = usage
+
+ if first_token_time is not None:
+ llm_run.extra.setdefault("metadata", {})["time_to_first_token"] = (
+ first_token_time - start_time
+ )
+
+ if last_event and llm_request:
+ llm_run.extra.setdefault("metadata", {})["llm_call_type"] = (
+ _determine_llm_call_type(llm_request, last_event)
+ )
+
+ llm_run.end(outputs=outputs)
+ try:
+ llm_run.patch()
+ except Exception as e:
+ logger.debug(f"Failed to patch LLM run: {e}")
+
+ except Exception as e:
+ llm_run.end(error=str(e))
+ try:
+ llm_run.patch()
+ except Exception as patch_e:
+ logger.debug(f"Failed to patch LLM run on error: {patch_e}")
+ raise
+
+
+def create_traced_session_context(
+ name: Optional[str] = None,
+ project_name: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
+ tags: Optional[list[str]] = None,
+ inputs: Optional[dict[str, Any]] = None,
+):
+ """Create a trace context for manual session tracing."""
+ config = get_tracing_config()
+ return trace(
+ name=name or config.get("name") or TRACE_CHAIN_NAME,
+ run_type="chain",
+ inputs=inputs or {},
+ project_name=project_name or config.get("project_name"),
+ tags=tags or config.get("tags"),
+ metadata={**(config.get("metadata") or {}), **(metadata or {})},
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/_config.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..b32340bf46f7a08741585e9b0d25da25681dae6a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/_config.py
@@ -0,0 +1,31 @@
+"""Configuration for Google ADK tracing."""
+
+from __future__ import annotations
+
+from typing import Any, Optional
+
+_tracing_config: dict[str, Any] = {
+ "name": None,
+ "project_name": None,
+ "metadata": None,
+ "tags": None,
+}
+
+
+def set_tracing_config(
+ name: Optional[str] = None,
+ project_name: Optional[str] = None,
+ metadata: Optional[dict] = None,
+ tags: Optional[list[str]] = None,
+) -> None:
+ global _tracing_config
+ _tracing_config = {
+ "name": name,
+ "project_name": project_name,
+ "metadata": metadata,
+ "tags": tags,
+ }
+
+
+def get_tracing_config() -> dict[str, Any]:
+ return _tracing_config.copy()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/_messages.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/_messages.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2b4b8352dc842b8798921222c9ea7d6401bfba8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/_messages.py
@@ -0,0 +1,200 @@
+"""Message serialization for Google ADK."""
+
+from __future__ import annotations
+
+import base64
+import json
+from typing import Any
+
+
+def convert_adk_content_to_langsmith(content: Any) -> list[dict[str, Any]]:
+ """Convert ADK Content/Part objects to serializable format."""
+ if content is None:
+ return []
+ if hasattr(content, "parts"):
+ parts = content.parts
+ elif isinstance(content, list):
+ parts = content
+ else:
+ return [_serialize_part(content)]
+ return [_serialize_part(part) for part in parts if part is not None]
+
+
+def _serialize_part(part: Any) -> dict[str, Any]:
+ """Serialize a single Part."""
+ if isinstance(part, dict):
+ return part
+
+ if hasattr(part, "inline_data") and part.inline_data:
+ data = getattr(part.inline_data, "data", None)
+ mime_type = getattr(part.inline_data, "mime_type", "application/octet-stream")
+ if data is not None:
+ encoded = (
+ base64.b64encode(data).decode("utf-8")
+ if isinstance(data, bytes)
+ else str(data)
+ )
+ return {"type": "image", "data": encoded, "mime_type": mime_type}
+
+ if hasattr(part, "file_data") and part.file_data:
+ return {
+ "type": "file",
+ "file_uri": getattr(part.file_data, "file_uri", None),
+ "mime_type": getattr(part.file_data, "mime_type", None),
+ }
+
+ if hasattr(part, "function_call") and part.function_call:
+ fc = part.function_call
+ return {
+ "type": "tool_use",
+ "name": getattr(fc, "name", "unknown"),
+ "input": dict(getattr(fc, "args", None) or {}),
+ }
+
+ if hasattr(part, "function_response") and part.function_response:
+ fr = part.function_response
+ return {
+ "type": "tool_result",
+ "name": getattr(fr, "name", "unknown"),
+ "content": _safe_serialize(getattr(fr, "response", None)),
+ }
+
+ if hasattr(part, "text") and part.text is not None:
+ return {"type": "text", "text": str(part.text)}
+
+ if hasattr(part, "executable_code") and part.executable_code:
+ code = part.executable_code
+ return {
+ "type": "executable_code",
+ "language": getattr(code, "language", "python"),
+ "code": getattr(code, "code", ""),
+ }
+
+ if hasattr(part, "code_execution_result") and part.code_execution_result:
+ result = part.code_execution_result
+ return {
+ "type": "code_execution_result",
+ "outcome": getattr(result, "outcome", "unknown"),
+ "output": getattr(result, "output", ""),
+ }
+
+ if hasattr(part, "thought") and part.thought is not None:
+ return {"type": "thinking", "thinking": str(part.thought)}
+
+ return _safe_serialize(part)
+
+
+def _safe_serialize(obj: Any) -> Any:
+ """Safely serialize an object to JSON-compatible format."""
+ if obj is None or isinstance(obj, (str, int, float, bool)):
+ return obj
+ if isinstance(obj, bytes):
+ return base64.b64encode(obj).decode("utf-8")
+ if isinstance(obj, dict):
+ return {k: _safe_serialize(v) for k, v in obj.items()}
+ if isinstance(obj, (list, tuple)):
+ return [_safe_serialize(item) for item in obj]
+ if hasattr(obj, "model_dump"):
+ try:
+ return obj.model_dump()
+ except Exception:
+ pass
+ if hasattr(obj, "__dict__"):
+ try:
+ return {k: _safe_serialize(v) for k, v in obj.__dict__.items()}
+ except Exception:
+ pass
+ return str(obj)
+
+
+def convert_llm_request_to_messages(llm_request: Any) -> list[dict[str, Any]]:
+ """Convert LlmRequest to OpenAI-compatible message format."""
+ messages: list[dict[str, Any]] = []
+
+ # Extract system instruction from config
+ config = getattr(llm_request, "config", None)
+ if config:
+ sys_inst = getattr(config, "system_instruction", None)
+ if sys_inst:
+ messages.append({"role": "system", "content": str(sys_inst)})
+
+ contents = getattr(llm_request, "contents", None)
+ if not contents:
+ return messages
+
+ for content in contents:
+ role = getattr(content, "role", "user")
+ if role == "model":
+ role = "assistant"
+
+ parts = convert_adk_content_to_langsmith(content)
+ text_parts, tool_calls, tool_results = [], [], []
+
+ for part in parts:
+ t = part.get("type")
+ if t == "text":
+ text_parts.append(part.get("text", ""))
+ elif t == "tool_use":
+ tool_calls.append(part)
+ elif t == "tool_result":
+ tool_results.append(part)
+ else:
+ text_parts.append(str(part))
+
+ if tool_calls and role == "assistant":
+ messages.append(
+ {
+ "role": "assistant",
+ "content": " ".join(text_parts) if text_parts else None,
+ "tool_calls": [
+ {
+ "id": f"call_{i}",
+ "type": "function",
+ "function": {
+ "name": tc.get("name", ""),
+ "arguments": json.dumps(tc.get("input", {})),
+ },
+ }
+ for i, tc in enumerate(tool_calls)
+ ],
+ }
+ )
+ elif tool_results:
+ for tr in tool_results:
+ c = tr.get("content")
+ messages.append(
+ {
+ "role": "tool",
+ "name": tr.get("name", ""),
+ "content": (
+ json.dumps(c) if isinstance(c, dict) else str(c or "")
+ ),
+ }
+ )
+ else:
+ messages.append(
+ {
+ "role": role,
+ "content": " ".join(text_parts) if text_parts else "",
+ }
+ )
+
+ return messages
+
+
+def has_function_calls(llm_response: Any) -> bool:
+ """Check if LlmResponse contains function calls."""
+ content = getattr(llm_response, "content", None)
+ if not content:
+ return False
+ parts = convert_adk_content_to_langsmith(content)
+ return any(p.get("type") == "tool_use" for p in parts)
+
+
+def has_function_response_in_request(llm_request: Any) -> bool:
+ """Check if LlmRequest contains function responses (tool results)."""
+ for content in getattr(llm_request, "contents", None) or []:
+ parts = convert_adk_content_to_langsmith(content)
+ if any(p.get("type") == "tool_result" for p in parts):
+ return True
+ return False
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/_usage.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/_usage.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7afb56e1f20aef1be37be826dabd17ce585e782
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/google_adk/_usage.py
@@ -0,0 +1,36 @@
+"""Token usage extraction for Google ADK."""
+
+from __future__ import annotations
+
+from typing import Any, Optional
+
+
+def extract_usage_from_response(llm_response: Any) -> dict[str, Any]:
+ """Extract token usage from LlmResponse."""
+ usage: dict[str, Any] = {}
+ usage_metadata = getattr(llm_response, "usage_metadata", None)
+ if not usage_metadata:
+ return usage
+
+ if (v := getattr(usage_metadata, "prompt_token_count", None)) is not None:
+ usage["input_tokens"] = int(v)
+ if (v := getattr(usage_metadata, "candidates_token_count", None)) is not None:
+ usage["output_tokens"] = int(v)
+ if (v := getattr(usage_metadata, "total_token_count", None)) is not None:
+ usage["total_tokens"] = int(v)
+ if (v := getattr(usage_metadata, "cached_content_token_count", None)) is not None:
+ usage.setdefault("input_token_details", {})["cache_read"] = int(v)
+ if (v := getattr(usage_metadata, "thoughts_token_count", None)) is not None:
+ usage.setdefault("output_token_details", {})["reasoning"] = int(v)
+
+ return usage
+
+
+def extract_model_name(llm_request: Any) -> Optional[str]:
+ """Extract the model name from an LlmRequest."""
+ if config := getattr(llm_request, "config", None):
+ if model := getattr(config, "model", None):
+ return str(model)
+ if model := getattr(llm_request, "model", None):
+ return str(model)
+ return None
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..649cb4208ce8cb30f56f0fa7313cea4fa12c61d7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/__init__.py
@@ -0,0 +1,8 @@
+"""LangSmith integration for OpenAI Agents SDK.
+
+This module provides tracing support for the OpenAI Agents SDK.
+"""
+
+from ._openai_agents import OpenAIAgentsTracingProcessor
+
+__all__ = ["OpenAIAgentsTracingProcessor"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..89cc7c61b3fab2d777a413c5694fa32a52fc256a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/__pycache__/_openai_agent_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/__pycache__/_openai_agent_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9996bba3185aafdd13463cbb42d4ee848c709adc
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/__pycache__/_openai_agent_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/__pycache__/_openai_agents.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/__pycache__/_openai_agents.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b384b026595bbdec9d40d0807867720e0d9da3f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/__pycache__/_openai_agents.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/_openai_agent_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/_openai_agent_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f80db8d8f2dbadf7ee436013643cd9147449c9ed
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/_openai_agent_utils.py
@@ -0,0 +1,228 @@
+import json
+import logging
+from typing import Any, Literal
+
+try:
+ from agents import tracing # type: ignore[import]
+
+ HAVE_AGENTS = True
+except ImportError:
+ HAVE_AGENTS = False
+
+logger = logging.getLogger(__name__)
+
+RunTypeT = Literal["tool", "chain", "llm", "retriever", "embedding", "prompt", "parser"]
+
+if HAVE_AGENTS:
+
+ def parse_io(data: Any, default_key: str = "output") -> dict:
+ """Parse inputs or outputs into a dictionary format.
+
+ Args:
+ data: The data to parse (can be inputs or outputs)
+ default_key: The default key to use if data is not a dict
+ (`'input'` or `'output'`)
+
+ Returns:
+ Dict: The parsed data as a dictionary
+ """
+ if isinstance(data, list):
+ if len(data) == 0:
+ return {}
+ # Check if this is a list of output blocks (reasoning, message, etc.)
+ if len(data) > 0 and isinstance(data[0], dict):
+ if "type" in data[0]:
+ return {default_key: data}
+ elif len(data) == 1:
+ return data[0]
+ return {default_key: data}
+ elif isinstance(data, dict):
+ data_ = data
+ elif isinstance(data, str):
+ try:
+ parsed_json = json.loads(data)
+ if isinstance(parsed_json, dict):
+ data_ = parsed_json
+ else:
+ data_ = {default_key: data}
+ except json.JSONDecodeError:
+ data_ = {default_key: data}
+ elif (
+ data is not None
+ and hasattr(data, "model_dump")
+ and callable(data.model_dump)
+ and not isinstance(data, type)
+ ):
+ try:
+ data_ = data.model_dump(exclude_none=True, mode="json")
+ except Exception as e:
+ logger.debug(
+ f"Failed to use model_dump to serialize {type(data)} to JSON: {e}"
+ )
+ data_ = {default_key: data}
+ else:
+ data_ = {default_key: data}
+
+ return data_
+
+ def get_run_type(span: tracing.Span) -> RunTypeT:
+ span_type = getattr(span.span_data, "type", None)
+ if span_type in ["agent", "handoff", "custom"]:
+ return "chain"
+ elif span_type in ["function", "guardrail"]:
+ return "tool"
+ elif span_type in ["generation", "response"]:
+ return "llm"
+ else:
+ return "chain"
+
+ def get_run_name(span: tracing.Span) -> str:
+ if hasattr(span.span_data, "name") and span.span_data.name:
+ return span.span_data.name
+ span_type = getattr(span.span_data, "type", None)
+ if span_type == "generation":
+ return "Generation"
+ elif span_type == "response":
+ return "Response"
+ elif span_type == "handoff":
+ return "Handoff"
+ else:
+ return "Span"
+
+ def _extract_function_span_data(
+ span_data: tracing.FunctionSpanData,
+ ) -> dict[str, Any]:
+ return {
+ "inputs": parse_io(span_data.input, "input"),
+ "outputs": parse_io(span_data.output, "output"),
+ }
+
+ def _extract_generation_span_data(
+ span_data: tracing.GenerationSpanData,
+ ) -> dict[str, Any]:
+ data = {
+ "inputs": parse_io(span_data.input, "input"),
+ "outputs": parse_io(span_data.output, "output"),
+ "invocation_params": {
+ "model": span_data.model,
+ "model_config": span_data.model_config,
+ },
+ }
+ if span_data.usage:
+ from langsmith.wrappers._openai import _create_usage_metadata
+
+ if "metadata" not in data:
+ data["metadata"] = {}
+ data["metadata"]["usage_metadata"] = _create_usage_metadata(span_data.usage)
+ return data
+
+ def _extract_response_span_data(
+ span_data: tracing.ResponseSpanData,
+ ) -> dict[str, Any]:
+ data: dict[str, Any] = {}
+ if span_data.input is not None:
+ data["inputs"] = {
+ "input": span_data.input,
+ "instructions": (
+ span_data.response.instructions
+ if span_data.response is not None
+ and span_data.response.instructions
+ else ""
+ ),
+ }
+ if span_data.response is not None:
+ response = span_data.response.model_dump(exclude_none=True, mode="json")
+ output_data = response.pop("output", [])
+ data["outputs"] = parse_io(output_data, "output")
+ data["invocation_params"] = {
+ k: v
+ for k, v in response.items()
+ if k
+ in (
+ "max_output_tokens",
+ "model",
+ "parallel_tool_calls",
+ "reasoning",
+ "temperature",
+ "text",
+ "tool_choice",
+ "tools",
+ "top_p",
+ "truncation",
+ )
+ }
+ metadata = {
+ k: v
+ for k, v in response.items()
+ if k
+ not in (
+ {"output", "usage", "instructions"}.union(data["invocation_params"])
+ )
+ }
+ metadata.update(
+ {
+ "ls_model_name": data["invocation_params"].get("model"),
+ "ls_max_tokens": data["invocation_params"].get("max_output_tokens"),
+ "ls_temperature": data["invocation_params"].get("temperature"),
+ "ls_model_type": "chat",
+ "ls_provider": "openai",
+ }
+ )
+ if usage := response.pop("usage", None):
+ from langsmith.wrappers._openai import _create_usage_metadata
+
+ metadata["usage_metadata"] = _create_usage_metadata(usage)
+ data["metadata"] = metadata
+
+ return data
+
+ def _extract_agent_span_data(span_data: tracing.AgentSpanData) -> dict[str, Any]:
+ return {
+ "invocation_params": {
+ "tools": span_data.tools,
+ "handoffs": span_data.handoffs,
+ },
+ "metadata": {
+ "output_type": span_data.output_type,
+ },
+ }
+
+ def _extract_handoff_span_data(
+ span_data: tracing.HandoffSpanData,
+ ) -> dict[str, Any]:
+ return {
+ "inputs": {
+ "from_agent": span_data.from_agent,
+ "to_agent": span_data.to_agent,
+ }
+ }
+
+ def _extract_guardrail_span_data(
+ span_data: tracing.GuardrailSpanData,
+ ) -> dict[str, Any]:
+ return {"metadata": {"triggered": span_data.triggered}}
+
+ def _extract_custom_span_data(span_data: tracing.CustomSpanData) -> dict[str, Any]:
+ return {"metadata": span_data.data}
+
+ def extract_span_data(span: tracing.Span) -> dict[str, Any]:
+ data: dict[str, Any] = {}
+
+ if isinstance(span.span_data, tracing.FunctionSpanData):
+ data.update(_extract_function_span_data(span.span_data))
+ elif isinstance(span.span_data, tracing.GenerationSpanData):
+ data.update(_extract_generation_span_data(span.span_data))
+ elif isinstance(span.span_data, tracing.ResponseSpanData):
+ data.update(_extract_response_span_data(span.span_data))
+ elif isinstance(span.span_data, tracing.AgentSpanData):
+ data.update(_extract_agent_span_data(span.span_data))
+ elif isinstance(span.span_data, tracing.HandoffSpanData):
+ data.update(_extract_handoff_span_data(span.span_data))
+ elif isinstance(span.span_data, tracing.GuardrailSpanData):
+ data.update(_extract_guardrail_span_data(span.span_data))
+ elif isinstance(span.span_data, tracing.CustomSpanData):
+ data.update(_extract_custom_span_data(span.span_data))
+ else:
+ return {}
+
+ return data
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/_openai_agents.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/_openai_agents.py
new file mode 100644
index 0000000000000000000000000000000000000000..d95364bd89876892f1dc2df1665f526046317c09
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/openai_agents_sdk/_openai_agents.py
@@ -0,0 +1,436 @@
+import logging
+import weakref
+from datetime import datetime
+from functools import cache
+from typing import Optional
+
+from langsmith import run_trees as rt
+from langsmith._internal import _context
+from langsmith.run_helpers import get_current_run_tree
+
+try:
+ from agents import tracing # type: ignore[import]
+
+ required = (
+ "TracingProcessor",
+ "Trace",
+ "Span",
+ "ResponseSpanData",
+ )
+ if not all(hasattr(tracing, name) for name in required):
+ raise ImportError("The `agents` package is not installed.")
+
+ from langsmith.integrations.openai_agents_sdk import (
+ _openai_agent_utils as agent_utils,
+ )
+
+ HAVE_AGENTS = True
+except ImportError:
+ HAVE_AGENTS = False
+
+ class OpenAIAgentsTracingProcessor:
+ """Tracing processor for the [OpenAI Agents SDK](https://openai.github.io/openai-agents-python/).
+
+ Traces all intermediate steps of your OpenAI Agent to LangSmith.
+
+ Requirements: Make sure to install `pip install -U langsmith[openai-agents]`.
+
+ Args:
+ client: An instance of `langsmith.client.Client`. If not provided, a default
+ client is created.
+
+ Example:
+ ```python
+ from agents import (
+ Agent,
+ FileSearchTool,
+ Runner,
+ WebSearchTool,
+ function_tool,
+ set_trace_processors,
+ )
+
+ from langsmith.wrappers import OpenAIAgentsTracingProcessor
+
+ set_trace_processors([OpenAIAgentsTracingProcessor()])
+
+
+ @function_tool
+ def get_weather(city: str) -> str:
+ return f"The weather in {city} is sunny"
+
+
+ haiku_agent = Agent(
+ name="Haiku agent",
+ instructions="Always respond in haiku form",
+ model="o3-mini",
+ tools=[get_weather],
+ )
+ agent = Agent(
+ name="Assistant",
+ tools=[WebSearchTool()],
+ instructions="speak in spanish. use Haiku agent if they ask for a haiku or for the weather",
+ handoffs=[haiku_agent],
+ )
+
+ result = await Runner.run(
+ agent,
+ "write a haiku about the weather today and tell me a recent news story about new york",
+ )
+ print(result.final_output)
+ ```
+ """ # noqa: E501
+
+ def __init__(self, *args, **kwargs):
+ raise ImportError(
+ "The `agents` package is not installed. "
+ "Please install it with `pip install langsmith[openai-agents]`."
+ )
+
+
+from langsmith import client as ls_client
+
+logger = logging.getLogger(__name__)
+
+
+@cache
+def _get_package_version(package_name: str) -> str | None:
+ try:
+ from importlib.metadata import version
+
+ return version(package_name)
+ except Exception:
+ return None
+
+
+if HAVE_AGENTS:
+
+ class OpenAIAgentsTracingProcessor(tracing.TracingProcessor): # type: ignore[no-redef]
+ """Tracing processor for the [OpenAI Agents SDK](https://openai.github.io/openai-agents-python/).
+
+ Traces all intermediate steps of your OpenAI Agent to LangSmith.
+
+ Requirements: Make sure to install `pip install -U langsmith[openai-agents]`.
+
+ Args:
+ client: An instance of `langsmith.client.Client`. If not provided,
+ a default client is created.
+ metadata: Metadata to associate with all traces.
+ tags: Tags to associate with all traces.
+ project_name: LangSmith project to trace to.
+ name: Name of the root trace.
+
+ Example:
+ ```python
+ from agents import (
+ Agent,
+ FileSearchTool,
+ Runner,
+ WebSearchTool,
+ function_tool,
+ set_trace_processors,
+ )
+
+ from langsmith.wrappers import OpenAIAgentsTracingProcessor
+
+ set_trace_processors([OpenAIAgentsTracingProcessor()])
+
+
+ @function_tool
+ def get_weather(city: str) -> str:
+ return f"The weather in {city} is sunny"
+
+
+ haiku_agent = Agent(
+ name="Haiku agent",
+ instructions="Always respond in haiku form",
+ model="o3-mini",
+ tools=[get_weather],
+ )
+ agent = Agent(
+ name="Assistant",
+ tools=[WebSearchTool()],
+ instructions="speak in spanish. use Haiku agent if they ask for a haiku or for the weather",
+ handoffs=[haiku_agent],
+ )
+
+ result = await Runner.run(
+ agent,
+ "write a haiku about the weather today and tell me a recent news story about new york",
+ )
+ print(result.final_output)
+ ```
+ """ # noqa: E501
+
+ def __init__(
+ self,
+ client: Optional[ls_client.Client] = None,
+ *,
+ metadata: Optional[dict] = None,
+ tags: Optional[list[str]] = None,
+ project_name: Optional[str] = None,
+ name: Optional[str] = None,
+ ):
+ self.client = client or rt.get_cached_client()
+ self._metadata = metadata
+ self._tags = tags
+ self._project_name = project_name
+ self._name = name
+ self._first_response_inputs: dict = {}
+ self._last_response_outputs: dict = {}
+
+ self._runs: dict[str, rt.RunTree] = {}
+ self._span_data_types: dict[
+ str, type
+ ] = {} # Track span data types by span_id
+ self._unposted_traces: set[str] = set()
+ self._unposted_spans: set[str] = set()
+
+ def on_trace_start(self, trace: tracing.Trace) -> None:
+ current_run_tree = get_current_run_tree()
+
+ # Determine run name
+ if self._name:
+ run_name = self._name
+ elif trace.name:
+ run_name = trace.name
+ else:
+ run_name = "Agent workflow"
+
+ # Build metadata
+ run_extra = {
+ "metadata": {
+ **(self._metadata or {}),
+ "ls_integration": "openai-agents-sdk",
+ "ls_integration_version": _get_package_version("openai-agents"),
+ "ls_agent_type": "root",
+ }
+ }
+ trace_dict = trace.export() or {}
+ if trace_dict.get("group_id") is not None:
+ run_extra["metadata"]["thread_id"] = trace_dict["group_id"]
+
+ try:
+ if current_run_tree is not None:
+ # Nest under existing trace
+ new_run = current_run_tree.create_child(
+ name=run_name,
+ run_type="chain",
+ inputs={},
+ extra=run_extra,
+ tags=self._tags,
+ )
+ else:
+ # Create new root trace
+ run_kwargs = {
+ "name": run_name,
+ "run_type": "chain",
+ "inputs": {},
+ "extra": run_extra,
+ "tags": self._tags,
+ "client": self.client,
+ }
+ if self._project_name is not None:
+ run_kwargs["project_name"] = self._project_name
+ new_run = rt.RunTree(**run_kwargs) # type: ignore[arg-type]
+
+ # Delay posting until first response/generation span ends
+ # so inputs can be included in the POST.
+ self._unposted_traces.add(trace.trace_id)
+ if new_run is not None:
+ _context._PARENT_RUN_TREE_REF.set(weakref.ref(new_run))
+ self._runs[trace.trace_id] = new_run
+ except Exception as e:
+ logger.exception(f"Error creating trace run: {e}")
+
+ def on_trace_end(self, trace: tracing.Trace) -> None:
+ run = self._runs.pop(trace.trace_id, None)
+ if not run:
+ return
+
+ trace_dict = trace.export() or {}
+ metadata = {**(trace_dict.get("metadata") or {}), **(self._metadata or {})}
+
+ try:
+ # Update run with final inputs/outputs
+ run.outputs = self._last_response_outputs.pop(trace.trace_id, {})
+
+ # Update metadata
+ if "metadata" not in run.extra:
+ run.extra["metadata"] = {}
+ run.extra["metadata"].update(metadata)
+
+ # End and patch
+ run.end()
+
+ if trace.trace_id in self._unposted_traces:
+ # No response/generation spans ended, post now
+ run.inputs = self._first_response_inputs.pop(trace.trace_id, {})
+ self._unposted_traces.discard(trace.trace_id)
+ run.post()
+ else:
+ self._first_response_inputs.pop(trace.trace_id, None)
+ run.patch(exclude_inputs=True)
+
+ # Restore parent context
+ if run.parent_run is not None:
+ _context._PARENT_RUN_TREE_REF.set(weakref.ref(run.parent_run))
+ else:
+ _context._PARENT_RUN_TREE_REF.set(None)
+ except Exception as e:
+ logger.exception(f"Error updating trace run: {e}")
+
+ def on_span_start(self, span: tracing.Span) -> None:
+ # Find parent run
+ parent_run = (
+ self._runs.get(span.parent_id)
+ if span.parent_id
+ else self._runs.get(span.trace_id)
+ )
+
+ if parent_run is None:
+ logger.warning(
+ f"No trace info found for span, skipping: {span.span_id}"
+ )
+ return
+
+ # Extract span data
+ run_name = agent_utils.get_run_name(span)
+ if isinstance(span.span_data, tracing.ResponseSpanData):
+ parent_name = parent_run.name
+ raw_span_name = getattr(span, "name", None) or getattr(
+ span.span_data, "name", None
+ )
+ span_name = str(raw_span_name) if raw_span_name else run_name
+ if parent_name:
+ run_name = f"{parent_name} {span_name}".strip()
+ else:
+ run_name = span_name
+
+ run_type = agent_utils.get_run_type(span)
+ extracted = agent_utils.extract_span_data(span)
+
+ try:
+ # Create child run
+ child_run = parent_run.create_child(
+ name=run_name,
+ run_type=run_type,
+ inputs=extracted.get("inputs", {}),
+ extra=extracted,
+ start_time=datetime.fromisoformat(span.started_at)
+ if span.started_at
+ else None,
+ )
+
+ # Add ls_agent_type metadata for agent spans that are children of
+ # function spans (i.e., agents used as tools via as_tool()).
+ # Note: Handoff agents are considered root agents, not subagents,
+ # since they take over the conversation rather than being called
+ # as tools.
+ if isinstance(span.span_data, tracing.AgentSpanData):
+ # Check if parent span is a function span (agent used as tool)
+ parent_span_data_type = (
+ self._span_data_types.get(span.parent_id)
+ if span.parent_id
+ else None
+ )
+ if parent_span_data_type is tracing.FunctionSpanData:
+ if "metadata" not in child_run.extra:
+ child_run.extra["metadata"] = {}
+ child_run.extra["metadata"]["ls_agent_type"] = "subagent"
+
+ # Track span data type for parent lookups
+ self._span_data_types[span.span_id] = type(span.span_data)
+
+ # Delay posting for spans whose inputs aren't available at start
+ if isinstance(
+ span.span_data,
+ (
+ tracing.GenerationSpanData,
+ tracing.ResponseSpanData,
+ tracing.FunctionSpanData,
+ ),
+ ):
+ self._unposted_spans.add(span.span_id)
+ else:
+ child_run.post()
+ self._runs[span.span_id] = child_run
+ except Exception as e:
+ logger.exception(f"Error creating span run: {e}")
+
+ def on_span_end(self, span: tracing.Span) -> None:
+ run = self._runs.pop(span.span_id, None)
+ self._span_data_types.pop(
+ span.span_id, None
+ ) # Clean up span data type tracking
+ if not run:
+ return
+
+ try:
+ # Extract outputs and metadata
+ extracted = agent_utils.extract_span_data(span)
+ outputs = extracted.pop("outputs", {})
+ inputs = extracted.pop("inputs", {})
+
+ # Update run
+ run.outputs = outputs
+ if inputs:
+ run.inputs = inputs
+ if error := span.error:
+ run.error = str(error)
+
+ # Add OpenAI metadata
+ if "metadata" not in run.extra:
+ run.extra["metadata"] = {}
+ run.extra["metadata"].update(
+ {
+ "openai_parent_id": span.parent_id,
+ "openai_trace_id": span.trace_id,
+ "openai_span_id": span.span_id,
+ }
+ )
+ if metadata := extracted.get("metadata"):
+ run.extra["metadata"].update(metadata)
+ if invocation_params := extracted.get("invocation_params"):
+ run.extra["invocation_params"] = invocation_params
+
+ if isinstance(span.span_data, tracing.ResponseSpanData):
+ self._first_response_inputs[span.trace_id] = (
+ self._first_response_inputs.get(span.trace_id) or inputs
+ )
+ self._last_response_outputs[span.trace_id] = outputs
+ self._maybe_post_trace(span.trace_id, inputs)
+ elif isinstance(span.span_data, tracing.GenerationSpanData):
+ self._first_response_inputs[span.trace_id] = (
+ self._first_response_inputs.get(span.trace_id) or inputs
+ )
+ self._last_response_outputs[span.trace_id] = outputs
+ self._maybe_post_trace(span.trace_id, inputs)
+
+ if span.ended_at:
+ run.end_time = datetime.fromisoformat(span.ended_at)
+ else:
+ run.end()
+
+ if span.span_id in self._unposted_spans:
+ self._unposted_spans.discard(span.span_id)
+ run.post()
+ else:
+ run.patch(exclude_inputs=True)
+ except Exception as e:
+ logger.exception(f"Error updating span run: {e}")
+
+ def _maybe_post_trace(self, trace_id: str, inputs: dict) -> None:
+ """Post the trace if it hasn't been posted yet."""
+ if trace_id in self._unposted_traces:
+ trace_run = self._runs.get(trace_id)
+ if trace_run:
+ trace_run.inputs = inputs
+ trace_run.post()
+ self._unposted_traces.discard(trace_id)
+
+ def shutdown(self) -> None:
+ self.client.flush()
+
+ def force_flush(self) -> None:
+ self.client.flush()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/otel/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/otel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d610248dcd6f7fa665a39e2b0b6198f3f52e0a79
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/otel/__init__.py
@@ -0,0 +1,114 @@
+"""OpenTelemetry integration for LangSmith."""
+
+import logging
+from typing import Optional, cast
+
+from langsmith import utils as ls_utils
+
+from .processor import OtelExporter, OtelSpanProcessor
+
+logger = logging.getLogger(__name__)
+
+__all__ = ["configure", "OtelSpanProcessor", "OtelExporter"]
+
+
+def configure(
+ api_key: Optional[str] = None,
+ project_name: Optional[str] = None,
+ SpanProcessor: Optional[type] = None,
+) -> bool:
+ """Configure OpenTelemetry with LangSmith as the `TracerProvider`.
+
+ Initializes OpenTelemetry with LangSmith as the primary and only `TracerProvider`.
+
+ Usage:
+ >>> from langsmith.integrations.otel import configure
+ >>> configure( # doctest: +SKIP
+ ... api_key="your-api-key", project_name="your-project"
+ ... )
+
+ Using environment variables:
+ >>> # Set LANGSMITH_API_KEY and LANGSMITH_PROJECT
+ >>> configure() # Will use env vars # doctest: +SKIP
+
+ !!! warning
+
+ This function is only for when LangSmith is your ONLY OpenTelemetry source.
+
+ It sets the global TracerProvider, which can only be done once per application.
+
+ This function will fail if OpenTelemetry is already initialized with another
+ `TracerProvider` (you cannot override an existing `TracerProvider`).
+
+ If you already have OpenTelemetry set up with other tools, use `OtelSpanProcessor`
+ directly to add LangSmith to your existing setup:
+
+ !!! example "Adding LangSmith to existing OTEL setup"
+ ```python
+ from opentelemetry import trace
+ from langsmith.integrations.otel.processor import OtelSpanProcessor
+
+ # Use your existing provider (already initialized)
+ provider = trace.get_tracer_provider()
+
+ # Add LangSmith processor to existing provider
+ langsmith_processor = OtelSpanProcessor(
+ api_key="your-api-key", project="your-project"
+ )
+ provider.add_span_processor(langsmith_processor)
+ ```
+
+ Args:
+ api_key: LangSmith API key. Defaults to `LANGSMITH_API_KEY` env var.
+ project_name: Project name. Defaults to `LANGSMITH_PROJECT` env var.
+ SpanProcessor: Span processor class to use. Defaults to `BatchSpanProcessor`.
+
+ Returns:
+ `True` if configuration succeeded, `False` if `TracerProvider` already exists.
+ """
+ try:
+ from opentelemetry import trace
+ from opentelemetry.sdk.trace import TracerProvider
+ from opentelemetry.trace import NoOpTracer, ProxyTracer, ProxyTracerProvider
+
+ existing_provider = cast(TracerProvider, trace.get_tracer_provider())
+ tracer = existing_provider.get_tracer(__name__)
+
+ # Check if OpenTelemetry is in its default uninitialized state
+ # (ProxyTracerProvider with NoOpTracer means no real TracerProvider was set)
+ if (
+ isinstance(existing_provider, ProxyTracerProvider)
+ and hasattr(tracer, "_tracer")
+ and isinstance(
+ cast(
+ ProxyTracer, # type: ignore[attr-defined, name-defined]
+ tracer,
+ )._tracer,
+ NoOpTracer,
+ )
+ ):
+ # Safe to set TracerProvider since none exists yet
+ provider = TracerProvider()
+ trace.set_tracer_provider(provider)
+ else:
+ logger.warning(
+ "OpenTelemetry TracerProvider is already set. "
+ "Cannot override existing TracerProvider. Use OtelSpanProcessor "
+ "directly to add LangSmith to your existing provider instead."
+ )
+ return False
+
+ api_key = api_key or ls_utils.get_api_key(None)
+ if not api_key:
+ return False
+
+ project_name = project_name or ls_utils.get_tracer_project()
+
+ processor = OtelSpanProcessor(
+ api_key=api_key, project=project_name, SpanProcessor=SpanProcessor
+ )
+ provider.add_span_processor(processor) # type: ignore
+ return True
+ except Exception as e:
+ logger.warning("Failed to initialize Otel for LangSmith:", e)
+ return False
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/otel/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/otel/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32d93155c9d55c9cd15fe7e40324d2492851ca4e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/otel/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/otel/__pycache__/processor.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/otel/__pycache__/processor.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5272cecf35664264ab401f983b2919365628b321
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/otel/__pycache__/processor.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/otel/processor.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/otel/processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..b177a4c45e0fb7b7f174ae0e1f2bc9d4125c65d2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/otel/processor.py
@@ -0,0 +1,243 @@
+"""OpenTelemetry span processor and exporter for LangSmith."""
+
+import logging
+import warnings
+from typing import Any, Optional
+from urllib.parse import urljoin
+
+from langsmith import utils as ls_utils
+
+try:
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
+
+ OTEL_AVAILABLE = True
+except ImportError:
+ warnings.warn(
+ "OpenTelemetry packages are not installed. "
+ "Install optional OpenTelemetry dependencies with: "
+ "pip install langsmith[otel]",
+ UserWarning,
+ stacklevel=2,
+ )
+
+ class OTLPSpanExporter: # type: ignore[no-redef]
+ """Mock otlp span exporter class."""
+
+ def __init__(self, *args, **kwargs):
+ """Mock init method."""
+ raise ImportError(
+ "OpenTelemetry packages are not installed. "
+ "Install optional OpenTelemetry dependencies with: "
+ "pip install langsmith[otel]"
+ )
+
+ class BatchSpanProcessor: # type: ignore[no-redef]
+ """Mock batch span processor class."""
+
+ def __init__(self, *args, **kwargs):
+ """Mock init method."""
+ raise ImportError(
+ "OpenTelemetry packages are not installed. "
+ "Install optional OpenTelemetry dependencies with: "
+ "pip install langsmith[otel]"
+ )
+
+ class trace:
+ """Mock trace class."""
+
+ @staticmethod
+ def get_tracer_provider():
+ """Mock get tracer provider method."""
+ raise ImportError(
+ "OpenTelemetry packages are not installed. "
+ "Install optional OpenTelemetry dependencies with: "
+ "pip install langsmith[otel]"
+ )
+
+ OTEL_AVAILABLE = False
+
+LANGSMITH_METADATA_PREFIX = "langsmith.metadata"
+
+
+class OtelExporter(OTLPSpanExporter):
+ """A subclass of `OTLPSpanExporter` configured for LangSmith.
+
+ Environment Variables:
+
+ - `LANGSMITH_API_KEY`: Your LangSmith API key.
+ - `LANGSMITH_ENDPOINT`: Base URL for LangSmith API (defaults to `https://api.smith.langchain.com`).
+ - `LANGSMITH_PROJECT`: Project identifier.
+ """
+
+ def __init__(
+ self,
+ url: Optional[str] = None,
+ api_key: Optional[str] = None,
+ project: Optional[str] = None,
+ headers: Optional[dict[str, str]] = None,
+ **kwargs,
+ ):
+ """Initialize the `OtelExporter`.
+
+ Args:
+ url: OTLP endpoint URL. Defaults to `{LANGSMITH_ENDPOINT}/otel/v1/traces`.
+ api_key: LangSmith API key. Defaults to `LANGSMITH_API_KEY` env var.
+ parent: Parent identifier (e.g., `'project_name:test'`).
+
+ Defaults to `LANGSMITH_PARENT` env var.
+ headers: Additional headers to include in requests.
+ **kwargs: Additional arguments passed to `OTLPSpanExporter`.
+ """
+ base_url = ls_utils.get_api_url(None)
+ # Ensure base_url ends with / for proper joining
+ if not base_url.endswith("/"):
+ base_url += "/"
+ endpoint = url or urljoin(base_url, "otel/v1/traces")
+ api_key = api_key or ls_utils.get_api_key(None)
+ project = project or ls_utils.get_tracer_project()
+ headers = headers or {}
+
+ if not api_key:
+ raise ValueError(
+ "API key is required. Provide it via api_key parameter or "
+ "LANGSMITH_API_KEY environment variable."
+ )
+
+ if not project:
+ project = "default"
+ logging.info(
+ "No project specified, using default. "
+ "Configure with LANGSMITH_PROJECT environment variable or "
+ "project parameter."
+ )
+
+ exporter_headers = {
+ "x-api-key": api_key,
+ **headers,
+ }
+
+ if project:
+ exporter_headers["Langsmith-Project"] = project
+
+ self.project = project
+
+ super().__init__(endpoint=endpoint, headers=exporter_headers, **kwargs)
+
+
+class OtelSpanProcessor:
+ """A span processor for adding LangSmith to OpenTelemetry setups.
+
+ This class combines the `OtelExporter` and `BatchSpanProcessor`
+ into a single processor that can be added to any `TracerProvider`.
+
+ Use this when:
+
+ 1. You already have OpenTelemetry initialized with other tools
+ 2. You want to add LangSmith alongside existing OTEL exporters
+
+ Examples:
+ # Fresh OpenTelemetry setup (LangSmith only):
+ from langsmith.integrations.otel import configure
+ configure(api_key="your-key", project="your-project")
+
+ # Add LangSmith to existing OpenTelemetry setup:
+ from opentelemetry import trace
+ from langsmith.integrations.otel.processor import OtelSpanProcessor
+
+ # Get your existing TracerProvider (already set by other tools)
+ provider = trace.get_tracer_provider()
+
+ # Add LangSmith processor alongside existing processors
+ langsmith_processor = OtelSpanProcessor(
+ project="your-project",
+ )
+ provider.add_span_processor(langsmith_processor)
+ """
+
+ def __init__(
+ self,
+ api_key: Optional[str] = None,
+ project: Optional[str] = None,
+ url: Optional[str] = None,
+ headers: Optional[dict[str, str]] = None,
+ SpanProcessor: Optional[type] = None,
+ ):
+ """Initialize the `OtelSpanProcessor`.
+
+ Args:
+ api_key: LangSmith API key. Defaults to `LANGSMITH_API_KEY` env var.
+ project: Project identifier. Defaults to `LANGSMITH_PROJECT` env var.
+ url: Base URL for LangSmith API. Defaults to `LANGSMITH_ENDPOINT` env var
+ or `https://api.smith.langchain.com`.
+ headers: Additional headers to include in requests.
+ SpanProcessor: Optional span processor class. Defaults to
+ `BatchSpanProcessor`.
+ """
+ # Create the exporter
+ # Convert url to the full endpoint URL that OtelExporter expects
+ exporter_url = None
+ if url:
+ exporter_url = f"{url.rstrip('/')}/otel/v1/traces"
+
+ self._exporter = OtelExporter(
+ url=exporter_url, api_key=api_key, project=project, headers=headers
+ )
+
+ # Create the processor chain
+ if not OTEL_AVAILABLE:
+ raise ImportError(
+ "OpenTelemetry packages are not installed. "
+ "Install optional OpenTelemetry dependencies with: "
+ "pip install langsmith[otel]"
+ )
+
+ if SpanProcessor is None:
+ SpanProcessor = BatchSpanProcessor
+
+ self._processor = SpanProcessor(self._exporter)
+ self._metadata: dict[str, Any] = {}
+
+ def set_metadata(self, metadata: dict[str, Any]) -> None:
+ """Set metadata attributes to propagate to all spans.
+
+ Use this to ensure metadata like ``thread_id`` appears on every span
+ in a trace, not just the root span. This is required for LangSmith
+ features (e.g. the threads view) that query runs by metadata fields.
+ """
+ self._metadata = metadata.copy()
+
+ def on_start(self, span, parent_context=None):
+ """Forward span start events to the inner processor."""
+ if self._metadata:
+ for key, value in self._metadata.items():
+ if value is not None:
+ span.set_attribute(f"{LANGSMITH_METADATA_PREFIX}.{key}", value)
+ self._processor.on_start(span, parent_context)
+
+ def on_end(self, span):
+ """Forward span end events to the inner processor."""
+ self._processor.on_end(span)
+
+ def _on_ending(self, span):
+ """Forward span ending events to the inner processor."""
+ if hasattr(self._processor, "_on_ending"):
+ self._processor._on_ending(span)
+
+ def shutdown(self):
+ """Shutdown processor."""
+ self._processor.shutdown()
+
+ def force_flush(self, timeout_millis=30000):
+ """Force flush the inner processor."""
+ return self._processor.force_flush(timeout_millis)
+
+ @property
+ def exporter(self):
+ """The underlying OtelExporter."""
+ return self._exporter
+
+ @property
+ def processor(self):
+ """The underlying span processor."""
+ return self._processor
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/strands_agents/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/strands_agents/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a77f9b6a1b7fd54039986a42126dd3c520d44956
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/strands_agents/__init__.py
@@ -0,0 +1,13 @@
+"""LangSmith integration for Strands Agents."""
+
+from .exporter import (
+ LangSmithSpanExporter,
+ create_langsmith_exporter,
+ setup_langsmith_telemetry,
+)
+
+__all__ = [
+ "LangSmithSpanExporter",
+ "create_langsmith_exporter",
+ "setup_langsmith_telemetry",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/strands_agents/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/strands_agents/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b21af9efd34b7805c60d2f7a5bbd07806f213883
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/strands_agents/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/strands_agents/__pycache__/exporter.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/strands_agents/__pycache__/exporter.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5c3b0824e7852ae3005868b11777d03977cdeb5
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/strands_agents/__pycache__/exporter.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/strands_agents/exporter.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/strands_agents/exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c66c64e4cbc7fbacce3dd30f9ffbc2a8dc820a6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/integrations/strands_agents/exporter.py
@@ -0,0 +1,497 @@
+"""Transform Strands OTEL spans into LangSmith-compatible formats.
+
+This module wraps the standard OTLPSpanExporter and intercepts spans before export,
+remapping attributes, span names, and structure to align with LangSmith's expected
+OTEL ingest schema.
+
+Strands emits GenAI message data as span events (gen_ai.user.message,
+gen_ai.assistant.message, gen_ai.choice, etc.), which is non-standard — the OTEL
+GenAI semantic conventions define these as Log Events, not span events. This
+exporter flattens those span events into span attributes (gen_ai.prompt,
+gen_ai.completion) that LangSmith's server-side OTEL ingest can consume directly.
+"""
+
+import json
+import logging
+from collections.abc import Sequence
+from typing import Any
+
+from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
+from opentelemetry.sdk.trace import ReadableSpan
+from opentelemetry.sdk.trace.export import (
+ BatchSpanProcessor,
+ ConsoleSpanExporter,
+ SimpleSpanProcessor,
+ SpanExporter,
+ SpanExportResult,
+)
+from strands.telemetry import StrandsTelemetry
+
+logger = logging.getLogger(__name__)
+
+__all__ = [
+ "LangSmithSpanExporter",
+ "create_langsmith_exporter",
+ "setup_langsmith_telemetry",
+]
+
+
+class LangSmithSpanExporter(SpanExporter):
+ """Span exporter that reformats Strands OTEL spans for LangSmith compatibility.
+
+ Wraps a delegate exporter (typically OTLPSpanExporter pointed at LangSmith's
+ OTEL endpoint) and transforms each span before forwarding it.
+
+ Args:
+ delegate: The underlying SpanExporter to forward transformed spans to.
+ """
+
+ def __init__(self, delegate: SpanExporter) -> None:
+ """Initialize the exporter.
+
+ Args:
+ delegate: The underlying SpanExporter to forward transformed spans to.
+ """
+ self._delegate = delegate
+
+ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
+ """Transform spans and forward them to the delegate exporter.
+
+ Args:
+ spans: The batch of spans to export.
+
+ Returns:
+ The result from the delegate exporter.
+ """
+ transformed = []
+ for span in spans:
+ try:
+ transformed.append(self._transform_span(span))
+ except Exception:
+ logger.warning(
+ "Failed to transform span %r, exporting original",
+ span.name,
+ exc_info=True,
+ )
+ transformed.append(span)
+ return self._delegate.export(transformed)
+
+ def shutdown(self) -> None:
+ """Shut down the delegate exporter."""
+ self._delegate.shutdown()
+
+ def force_flush(self, timeout_millis: int = 30000) -> bool:
+ """Force flush the delegate exporter.
+
+ Args:
+ timeout_millis: Maximum time to wait for flush to complete.
+
+ Returns:
+ True if flush succeeded.
+ """
+ return self._delegate.force_flush(timeout_millis)
+
+ # -- gen_ai.operation.name → langsmith.span.kind mapping ---------------
+
+ _OPERATION_TO_RUN_TYPE: dict[str, str] = {
+ "chat": "llm",
+ "invoke_agent": "chain",
+ "execute_tool": "tool",
+ "execute_event_loop_cycle": "chain",
+ }
+
+ # -- Span name fallback → langsmith.span.kind mapping ------------------
+ # Some Strands spans (e.g. execute_event_loop_cycle) don't always carry
+ # gen_ai.operation.name. Fall back to the span *name* in that case.
+ _SPAN_NAME_TO_RUN_TYPE: dict[str, str] = {
+ "execute_event_loop_cycle": "chain",
+ }
+
+ # -- Event name → role mapping ----------------------------------------
+
+ _EVENT_ROLE_MAP: dict[str, str] = {
+ "gen_ai.user.message": "user",
+ "gen_ai.assistant.message": "assistant",
+ "gen_ai.system.message": "system",
+ "gen_ai.tool.message": "tool",
+ "gen_ai.choice": "assistant",
+ }
+
+ _MESSAGE_EVENTS: set[str] = {
+ "gen_ai.user.message",
+ "gen_ai.system.message",
+ "gen_ai.tool.message",
+ "gen_ai.assistant.message",
+ "gen_ai.choice",
+ }
+
+ # ----------------------------------------------------------------------
+
+ def _transform_span(self, span: ReadableSpan) -> ReadableSpan:
+ """Flatten span events into prompt/completion attributes.
+
+ Strands attaches GenAI message data as span events. LangSmith expects
+ them as JSON-serialized span attributes instead. Each message object
+ gets a ``role`` field injected when one can be inferred from the event
+ name and isn't already present in the payload.
+
+ All conversation history (user, system, tool, and intermediate assistant
+ messages) is placed into ``gen_ai.prompt``. Only the final
+ ``gen_ai.choice`` event — the model's actual response — goes into
+ ``gen_ai.completion``.
+
+ Args:
+ span: The original Strands span.
+
+ Returns:
+ A new ReadableSpan with the message attributes added.
+ """
+ span_attrs = dict(span.attributes) if span.attributes else {}
+ operation_raw = span_attrs.get("gen_ai.operation.name", "")
+ operation = operation_raw if isinstance(operation_raw, str) else ""
+ # Strands puts tool metadata in span attributes (only on tool spans)
+ tool_call_id_raw = span_attrs.get("gen_ai.tool.call.id", "")
+ tool_call_id = tool_call_id_raw if isinstance(tool_call_id_raw, str) else ""
+ tool_name_raw = span_attrs.get("gen_ai.tool.name", "")
+ tool_name = tool_name_raw if isinstance(tool_name_raw, str) else ""
+
+ # Maps toolUseId → tool name so tool-result messages can be labelled.
+ # Seeded from span attrs on tool spans; extended inline as we encounter
+ # assistant/choice events that contain toolUse blocks.
+ tool_id_to_name: dict[str, str] = {}
+ if tool_name and tool_call_id:
+ tool_id_to_name[tool_call_id] = tool_name
+
+ input_messages: list[dict[str, Any]] = []
+ output_messages: list[dict[str, Any]] = []
+ remaining_events: list[Any] = []
+
+ for event in span.events:
+ name = event.name
+ attrs = dict(event.attributes) if event.attributes else {}
+
+ if name == "gen_ai.choice":
+ # The final model response is the only true output
+ msg = self._event_to_message(
+ name, attrs, tool_id_to_name=tool_id_to_name
+ )
+ if tool_call_id:
+ msg["tool_call_id"] = tool_call_id
+ output_messages.append(msg)
+ elif name in self._MESSAGE_EVENTS:
+ msg = self._event_to_message(
+ name, attrs, tool_id_to_name=tool_id_to_name
+ )
+ if tool_call_id:
+ msg["tool_call_id"] = tool_call_id
+ input_messages.append(msg)
+ else:
+ # Preserve non-message events as-is
+ remaining_events.append(event)
+
+ # Merge new attributes with the originals.
+ # LangSmith's server-side OTEL ingest expects inputs under "gen_ai.prompt"
+ # and outputs under "gen_ai.completion" (matching the attribute names used
+ # by LangSmith's own OTELExporter).
+ new_attrs: dict[str, Any] = dict(span_attrs)
+ if input_messages:
+ new_attrs["gen_ai.prompt"] = json.dumps({"messages": input_messages})
+ if output_messages:
+ new_attrs["gen_ai.completion"] = json.dumps(output_messages[-1])
+
+ # Map gen_ai.operation.name to langsmith.span.kind (run type).
+ # Some Strands spans (e.g. execute_event_loop_cycle) don't carry
+ # gen_ai.operation.name — fall back to the span name.
+ run_type = self._OPERATION_TO_RUN_TYPE.get(operation)
+ if not run_type:
+ run_type = self._SPAN_NAME_TO_RUN_TYPE.get(span.name)
+ if run_type:
+ new_attrs["langsmith.span.kind"] = run_type
+
+ # For LLM spans, set the provider metadata and display name.
+ # Strands hardcodes gen_ai.system to "strands-agents" regardless of
+ # backend, so we use langsmith.metadata.ls_provider to surface the
+ # actual provider.
+ # TODO: Detect non-Bedrock providers
+ if run_type == "llm" and new_attrs.get("gen_ai.system"):
+ new_attrs["langsmith.metadata.ls_provider"] = "amazon_bedrock"
+ new_attrs["langsmith.metadata.ls_model_type"] = "chat"
+
+ return ReadableSpan(
+ name=span.name,
+ context=span.context,
+ parent=span.parent,
+ resource=span.resource,
+ attributes=new_attrs,
+ events=remaining_events,
+ links=span.links,
+ kind=span.kind,
+ status=span.status,
+ start_time=span.start_time,
+ end_time=span.end_time,
+ instrumentation_scope=span.instrumentation_scope,
+ )
+
+ def _event_to_message(
+ self,
+ event_name: str,
+ attrs: dict[str, Any],
+ *,
+ tool_id_to_name: dict[str, str] | None = None,
+ ) -> dict[str, Any]:
+ """Convert a span event into a message dict, injecting ``role`` if missing.
+
+ For ``gen_ai.choice`` events the content lives under the ``message``
+ key; for all other events it lives under ``content``. In both cases
+ the value may be a JSON-encoded string that we parse back so the final
+ attribute is cleanly nested.
+
+ Args:
+ event_name: The OTEL event name (e.g. ``gen_ai.user.message``).
+ attrs: The event's attribute dict.
+ tool_id_to_name: Optional mapping of tool-call IDs to tool names.
+
+ Returns:
+ A message dict with at least ``role`` and ``content`` keys.
+ """
+ role = self._EVENT_ROLE_MAP.get(event_name, "unknown")
+
+ # gen_ai.choice stores content in "message", others in "content"
+ if event_name == "gen_ai.choice":
+ raw = attrs.get("message", "[]")
+ else:
+ raw = attrs.get("content", "[]")
+
+ # Parse the JSON string back into a list so the final serialized
+ # attribute isn't double-encoded.
+ try:
+ content = json.loads(raw) if isinstance(raw, str) else raw
+ except (json.JSONDecodeError, TypeError):
+ content = raw
+
+ # Tool messages in chat history contain Bedrock toolResult blocks.
+ # Flatten them into the format LangSmith expects: a top-level
+ # tool_call_id and plain-text content.
+ if event_name == "gen_ai.tool.message" and isinstance(content, list):
+ return self._flatten_tool_result_message(
+ content,
+ tool_id_to_name=tool_id_to_name or {},
+ )
+
+ # Convert Bedrock-shaped content blocks to LangSmith-shaped blocks.
+ # While iterating, harvest toolUse names so later tool-result messages
+ # can be labelled (assistant messages precede their tool results).
+ if isinstance(content, list):
+ converted = []
+ for block in content:
+ if (
+ tool_id_to_name is not None
+ and isinstance(block, dict)
+ and "toolUse" in block
+ ):
+ tu = block["toolUse"]
+ tid, tname = tu.get("toolUseId", ""), tu.get("name", "")
+ if tid and tname:
+ tool_id_to_name[tid] = tname
+ converted.append(self._convert_content_block(block))
+ content = converted
+
+ if event_name == "gen_ai.tool.message":
+ content = self._stringify_tool_content(content)
+
+ msg: dict[str, Any] = {"role": role, "content": content}
+
+ # Carry over tool_call_id from event attributes (Strands stores it as "id")
+ if "id" in attrs:
+ msg["tool_call_id"] = attrs["id"]
+
+ # Carry over finish_reason for choice events
+ if "finish_reason" in attrs:
+ msg["finish_reason"] = attrs["finish_reason"]
+
+ return msg
+
+ @staticmethod
+ def _flatten_tool_result_message(
+ content_blocks: list[Any],
+ *,
+ tool_id_to_name: dict[str, str] | None = None,
+ ) -> dict[str, Any]:
+ """Flatten Bedrock ``toolResult`` content blocks into a LangSmith tool message.
+
+ Bedrock tool results arrive as::
+
+ [
+ {
+ "toolResult": {
+ "toolUseId": "x",
+ "status": "success",
+ "content": [{"text": "..."}],
+ }
+ }
+ ]
+
+ LangSmith expects tool messages as::
+
+ {"role": "tool", "name": "my_tool", "tool_call_id": "x", "content": "..."}
+
+ If there are multiple toolResult blocks they are joined with newlines.
+ Non-toolResult blocks are converted normally and appended.
+
+ Args:
+ content_blocks: The parsed content block list from the event.
+ tool_id_to_name: Optional mapping of tool-call IDs to tool names.
+
+ Returns:
+ A flat tool message dict.
+ """
+ tool_call_id = ""
+ text_parts: list[str] = []
+ other_blocks: list[Any] = []
+
+ for block in content_blocks:
+ if isinstance(block, dict) and "toolResult" in block:
+ tr = block["toolResult"]
+ if not tool_call_id:
+ tool_call_id = tr.get("toolUseId", "")
+ # Extract text from nested content blocks
+ for nested in tr.get("content", []):
+ if isinstance(nested, dict) and "text" in nested:
+ text_parts.append(nested["text"])
+ else:
+ other_blocks.append(nested)
+ else:
+ other_blocks.append(block)
+
+ if text_parts:
+ flat_content: Any = "\n".join(text_parts)
+ else:
+ flat_content = other_blocks
+
+ msg: dict[str, Any] = {
+ "role": "tool",
+ "content": LangSmithSpanExporter._stringify_tool_content(flat_content),
+ }
+ # Look up the tool name from the toolUseId → name mapping
+ tool_name = (tool_id_to_name or {}).get(tool_call_id, "")
+ if tool_name:
+ msg["name"] = tool_name
+ if tool_call_id:
+ msg["tool_call_id"] = tool_call_id
+ return msg
+
+ @staticmethod
+ def _stringify_tool_content(content: Any) -> str:
+ """Ensure tool message content is a string.
+
+ Strands emits tool-call inputs as JSON-serialized objects in
+ ``gen_ai.tool.message`` events. After parsing event payloads for the
+ rest of the exporter, convert those tool inputs back to strings so
+ LangSmith receives tool message content as either a plain string or a
+ stringified object.
+ """
+ if isinstance(content, str):
+ return content
+ try:
+ return json.dumps(content, ensure_ascii=False)
+ except (TypeError, ValueError):
+ return str(content)
+
+ @staticmethod
+ def _convert_content_block(block: Any) -> Any:
+ """Convert a single Bedrock/Converse content block to LangSmith format.
+
+ Bedrock uses implicit typing (the key name *is* the type)::
+
+ {"text": "hello"}
+ {"toolUse": {"toolUseId": "x", "name": "f", "input": {...}}}
+ {"toolResult": {"toolUseId": "x", "status": "success", "content": [...]}}
+
+ LangSmith expects explicit ``type`` fields::
+
+ {"type": "text", "text": "hello"}
+ {"type": "tool_use", "id": "x", "name": "f", "input": {...}}
+ {
+ "type": "tool_result",
+ "tool_use_id": "x",
+ "status": "success",
+ "content": [...],
+ }
+
+ Unrecognised blocks are returned as-is.
+ """
+ if not isinstance(block, dict):
+ return block
+
+ if "text" in block and len(block) == 1:
+ return {"type": "text", "text": block["text"]}
+
+ if "toolUse" in block:
+ tu = block["toolUse"]
+ return {
+ "type": "tool_use",
+ "id": tu.get("toolUseId", ""),
+ "name": tu.get("name", ""),
+ "input": tu.get("input", {}),
+ }
+
+ if "toolResult" in block:
+ tr = block["toolResult"]
+ converted: dict[str, Any] = {
+ "type": "tool_result",
+ "tool_use_id": tr.get("toolUseId", ""),
+ }
+ if "status" in tr:
+ converted["status"] = tr["status"]
+ if "content" in tr:
+ # Recursively convert nested content blocks
+ nested = tr["content"]
+ if isinstance(nested, list):
+ nested = [
+ LangSmithSpanExporter._convert_content_block(b) for b in nested
+ ]
+ converted["content"] = nested
+ return converted
+
+ # Unknown block shape — pass through unchanged
+ return block
+
+
+# ---------------------------------------------------------------------------
+# Convenience wiring
+# ---------------------------------------------------------------------------
+
+
+def create_langsmith_exporter(**otlp_kwargs: Any) -> LangSmithSpanExporter:
+ """Create a LangSmithSpanExporter wrapping a standard OTLPSpanExporter.
+
+ Keyword arguments are forwarded to OTLPSpanExporter (endpoint, headers, etc.).
+ If not provided, the exporter will fall back to the standard OTEL_EXPORTER_OTLP_*
+ environment variables.
+
+ Returns:
+ A ready-to-use LangSmithSpanExporter instance.
+ """
+ delegate = OTLPSpanExporter(**otlp_kwargs)
+ return LangSmithSpanExporter(delegate=delegate)
+
+
+def setup_langsmith_telemetry(*, console: bool = False) -> None:
+ """Wire up Strands telemetry with the LangSmith-compatible exporter.
+
+ Call this instead of (or in addition to) the standard
+ ``StrandsTelemetry().setup_otlp_exporter()`` flow.
+
+ Args:
+ console: If True, also add a ConsoleSpanExporter that prints transformed
+ spans to stdout (useful for debugging).
+ """
+ telemetry = StrandsTelemetry()
+ exporter = create_langsmith_exporter()
+ telemetry.tracer_provider.add_span_processor(BatchSpanProcessor(exporter))
+
+ if console:
+ console_exporter = LangSmithSpanExporter(delegate=ConsoleSpanExporter())
+ telemetry.tracer_provider.add_span_processor(
+ SimpleSpanProcessor(console_exporter)
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/README.md b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..b3571dcea3da9c10dfc010838ac67c552f2e5a05
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/README.md
@@ -0,0 +1,1023 @@
+# LangSmith Sandbox
+
+Sandboxed code execution for LangSmith. Run untrusted code safely in isolated containers.
+
+> ⚠️ **Warning**: This module is experimental. Features and APIs may change, and breaking changes are expected as we iterate.
+
+## Quick Start
+
+```python
+from langsmith.sandbox import SandboxClient
+
+# Client uses LANGSMITH_ENDPOINT and LANGSMITH_API_KEY from environment
+client = SandboxClient()
+
+# First, build a snapshot (defines the container image and root filesystem)
+snapshot = client.create_snapshot(
+ "python-snapshot",
+ docker_image="python:3.12-slim",
+ fs_capacity_bytes=4 * 1024**3, # 4 GB
+)
+
+# Now create a sandbox from the snapshot and run code
+with client.sandbox(snapshot_id=snapshot.id) as sb:
+ result = sb.run("python -c 'print(2 + 2)'")
+ print(result.stdout) # "4\n"
+ print(result.success) # True
+
+# Or create a sandbox to keep
+sb = client.create_sandbox(snapshot_id=snapshot.id)
+result = sb.run("python -c 'print(2 + 2)'")
+client.delete_sandbox(sb.name) # Don't forget to clean up when done
+
+# Or use an existing sandbox by name
+sb = client.get_sandbox(name="your-sandbox")
+result = sb.run("python -c 'print(2 + 2)'")
+```
+
+The examples below assume `snapshot_id` is bound to a snapshot UUID obtained
+from `client.create_snapshot(...)` (or `client.list_snapshots()` /
+`client.get_snapshot(...)`). You only need to build a snapshot once; many
+sandboxes can be created from the same `snapshot_id`.
+
+## Installation
+
+The sandbox module works out of the box for basic command execution (HTTP). For
+**real-time output** (streaming, callbacks, and `timeout=0`), install the
+optional dependency:
+
+```bash
+pip install 'langsmith[sandbox]'
+```
+
+This pulls in the `websockets` package. Without it, `sb.run()` falls back to
+HTTP automatically.
+
+## Configuration
+
+The client automatically uses LangSmith environment variables:
+
+```python
+from langsmith.sandbox import SandboxClient
+
+# Uses LANGSMITH_ENDPOINT and LANGSMITH_API_KEY
+client = SandboxClient()
+
+# Or configure explicitly
+client = SandboxClient(
+ api_endpoint="https://api.smith.langchain.com/v2/sandboxes",
+ api_key="your-api-key",
+ timeout=30.0,
+)
+```
+
+## Running Commands
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ # Run a command
+ result = sb.run("echo 'Hello, World!'")
+
+ print(result.stdout) # "Hello, World!\n"
+ print(result.stderr) # ""
+ print(result.exit_code) # 0
+ print(result.success) # True
+
+ # Commands that fail return non-zero exit codes
+ result = sb.run("exit 1")
+ print(result.success) # False
+ print(result.exit_code) # 1
+```
+
+## Streaming Output
+
+For long-running commands, you can stream output in real time. This requires
+the `websockets` package (`pip install 'langsmith[sandbox]'`).
+
+### Callbacks
+
+The simplest way to get real-time output. Blocks until the command completes.
+
+```python
+import sys
+
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ result = sb.run(
+ "make build",
+ timeout=600,
+ on_stdout=lambda s: print(s, end=""),
+ on_stderr=lambda s: print(s, end="", file=sys.stderr),
+ )
+ print(f"\nBuild {'succeeded' if result.success else 'failed'}")
+```
+
+### Streaming with CommandHandle
+
+For full control — access to the process handle, stream identity, kill, and
+reconnection.
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ handle = sb.run("make build", timeout=600, wait=False)
+
+ print(f"Command ID: {handle.command_id}")
+
+ for chunk in handle:
+ prefix = "OUT" if chunk.stream == "stdout" else "ERR"
+ print(f"[{prefix}] {chunk.data}", end="")
+
+ result = handle.result
+ print(f"\nExit code: {result.exit_code}")
+```
+
+### Killing a Running Command
+
+```python
+import threading
+import time
+
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ handle = sb.run("sleep 3600", timeout=7200, wait=False)
+
+ # Kill after 10 seconds from another thread
+ def kill_after(h, seconds):
+ time.sleep(seconds)
+ h.kill()
+
+ threading.Thread(target=kill_after, args=(handle, 10)).start()
+
+ for chunk in handle:
+ print(chunk.data, end="")
+
+ result = handle.result
+ print(f"Exit code: {result.exit_code}") # non-zero (killed)
+```
+
+### Sending Stdin Input
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ handle = sb.run(
+ "python -c 'name = input(\"Name: \"); print(f\"Hello {name}\")'",
+ timeout=30,
+ wait=False,
+ )
+
+ for chunk in handle:
+ if "Name:" in chunk.data:
+ handle.send_input("World\n")
+ print(chunk.data, end="")
+
+ result = handle.result
+```
+
+### Auto-Reconnect
+
+`CommandHandle` (returned by `sb.run(wait=False)`) automatically
+reconnects on transient disconnects — hot-reloads, network blips, etc. No user
+code needed:
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ handle = sb.run("make build", timeout=600, wait=False)
+
+ # Auto-reconnects on transient errors (hot-reload, network blips)
+ for chunk in handle:
+ print(chunk.data, end="")
+
+ result = handle.result
+```
+
+For manual reconnection across process restarts:
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ handle = sb.run("make build", timeout=600, wait=False)
+ command_id = handle.command_id
+
+ # ... later, possibly in a different process ...
+
+ handle = sb.reconnect(command_id)
+ for chunk in handle:
+ print(chunk.data, end="")
+ result = handle.result
+```
+
+### No Timeout (`timeout=0`)
+
+With WebSocket enabled, you can set `timeout=0` to let a command run
+indefinitely with no server-side deadline. This works with both `wait=False`
+and callbacks. Useful for long-lived processes like dev servers, file watchers,
+or background tasks that you control via `kill()`.
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ handle = sb.run("python server.py", timeout=0, wait=False)
+
+ for chunk in handle:
+ print(chunk.data, end="")
+ if "Ready" in chunk.data:
+ break # server is up, do other work
+
+ handle.kill() # stop when done
+```
+
+> **Note:** `timeout=0` requires WebSocket support
+> (`pip install 'langsmith[sandbox]'`). Without WebSocket, `run()` falls
+> back to HTTP which has its own request-level timeout.
+
+## Command Lifecycle & TTL
+
+The sandbox daemon automatically manages command session lifecycles with two
+timeout mechanisms:
+
+### Session TTL (finished commands)
+
+After a command finishes (exits), its session remains in memory for a TTL
+period. During this window you can still reconnect to retrieve output. After the
+TTL expires, the session is cleaned up and `reconnect()` will raise an error.
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ handle = sb.run("make build", wait=False)
+ command_id = handle.command_id
+
+ # Even after the command finishes, you can reconnect within the TTL window
+ handle = sb.reconnect(command_id)
+ result = handle.result
+ print(result.stdout)
+
+ # After TTL expires, reconnect raises SandboxOperationError
+```
+
+### Idle Timeout (running commands)
+
+Running commands with no connected clients are killed after an idle timeout
+(default: 5 minutes). The idle timer resets each time a client connects. This
+prevents orphaned long-running processes from consuming resources indefinitely.
+
+You can set a per-command idle timeout via the `idle_timeout` parameter.
+Set to `-1` for no idle timeout (the command runs indefinitely until explicitly
+killed or it exits on its own).
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ # Start a long-running command with a 30-minute idle timeout
+ handle = sb.run(
+ "python server.py",
+ timeout=0,
+ idle_timeout=1800,
+ wait=False,
+ )
+
+ # As long as a client is connected (iterating), the idle timer is paused
+ for chunk in handle:
+ print(chunk.data, end="")
+ if "Ready" in chunk.data:
+ break
+
+ # After disconnecting, the idle timer starts
+ # If no client reconnects within idle_timeout seconds, the process is killed
+```
+
+### Kill on Disconnect
+
+By default, commands continue running after a client disconnects and can be
+reconnected to later. Set `kill_on_disconnect=True` to kill the command
+immediately when the last client disconnects:
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ # Command is killed as soon as the client disconnects
+ handle = sb.run(
+ "python server.py",
+ kill_on_disconnect=True,
+ wait=False,
+ )
+
+ for chunk in handle:
+ print(chunk.data, end="")
+ if "Ready" in chunk.data:
+ break
+ # Command is killed here when iteration stops and the WS disconnects
+```
+
+### Combining Lifecycle Options
+
+All lifecycle parameters can be combined:
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ # Long-running task: 30-min idle timeout, 1-hour session TTL
+ handle = sb.run(
+ "python train.py",
+ timeout=0, # No command timeout
+ idle_timeout=1800, # Kill after 30min with no clients
+ ttl_seconds=3600, # Keep session for 1 hour after exit
+ wait=False,
+ )
+
+ # Fire-and-forget: no idle timeout, infinite TTL
+ handle = sb.run(
+ "python background_job.py",
+ timeout=0,
+ idle_timeout=-1, # Never kill due to idle
+ ttl_seconds=-1, # Keep session forever
+ wait=False,
+ )
+```
+
+## PTY (Pseudo-Terminal)
+
+Set `pty=True` to allocate a pseudo-terminal for the command. This is useful
+for interactive programs and commands that detect terminal capabilities:
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ # Run an interactive Python REPL with PTY
+ handle = sb.run("python", pty=True, wait=False)
+
+ for chunk in handle:
+ if ">>>" in chunk.data:
+ handle.send_input("print('hello')\n")
+ break
+
+ for chunk in handle:
+ if ">>>" in chunk.data:
+ handle.send_input("exit()\n")
+ break
+
+ result = handle.result
+
+ # Commands that require a TTY
+ result = sb.run("top -b -n 1", pty=True)
+```
+
+> **Note:** PTY mode merges stdout and stderr into a single stream (stdout).
+> Only use PTY when the command requires it — most commands work fine without it.
+
+## File Operations
+
+Read and write files in the sandbox:
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ # Write a file
+ sb.write("/app/script.py", "print('Hello from file!')")
+
+ # Run the script
+ result = sb.run("python /app/script.py")
+ print(result.stdout) # "Hello from file!\n"
+
+ # Read a file (returns bytes)
+ content = sb.read("/app/script.py")
+ print(content.decode()) # "print('Hello from file!')"
+
+ # Write binary files
+ sb.write("/app/data.bin", b"\x00\x01\x02\x03")
+```
+
+## TCP Tunnel
+
+Access any TCP service running inside a sandbox (databases, Redis, HTTP servers,
+etc.) as if it were running on your local machine. The tunnel opens a local TCP
+port and forwards connections through a multiplexed WebSocket to the target port
+inside the sandbox.
+
+Requires the `websockets` package (`pip install 'langsmith[sandbox]'`).
+
+### Basic Usage — PostgreSQL
+
+Build a snapshot from the `postgres:16` image. The entrypoint initializes and
+starts Postgres automatically:
+
+```python
+import psycopg2
+
+postgres_snapshot = client.create_snapshot(
+ "postgres-snapshot",
+ docker_image="postgres:16",
+ fs_capacity_bytes=4 * 1024**3,
+)
+
+sb = client.create_sandbox(snapshot_id=postgres_snapshot.id)
+pg_handle = sb.run(
+ "POSTGRES_HOST_AUTH_METHOD=trust docker-entrypoint.sh postgres",
+ timeout=0,
+ wait=False,
+)
+import time; time.sleep(6) # wait for Postgres to initialize and start
+
+try:
+ with sb.tunnel(remote_port=5432, local_port=25432) as t:
+ conn = psycopg2.connect(
+ host="127.0.0.1",
+ port=t.local_port,
+ user="postgres",
+ )
+ cursor = conn.cursor()
+ cursor.execute("SELECT version()")
+ print(cursor.fetchone())
+ conn.close()
+finally:
+ pg_handle.kill()
+ client.delete_sandbox(sb.name)
+```
+
+### Basic Usage — Redis
+
+Build a snapshot from the `redis:7` image. Redis self-daemonizes:
+
+```python
+import redis
+
+redis_snapshot = client.create_snapshot(
+ "redis-snapshot",
+ docker_image="redis:7",
+ fs_capacity_bytes=2 * 1024**3,
+)
+
+with client.sandbox(snapshot_id=redis_snapshot.id) as sb:
+ sb.run("redis-server --daemonize yes", timeout=10)
+
+ with sb.tunnel(remote_port=6379, local_port=26379) as t:
+ r = redis.Redis(host="127.0.0.1", port=t.local_port)
+ r.set("key", "value")
+ print(r.get("key")) # b"value"
+```
+
+### HTTP Services
+
+Works with any TCP service. Start long-running services with `wait=False` and
+`timeout=0` so they stay alive across commands:
+
+```python
+sb = client.create_sandbox(snapshot_id=snapshot_id)
+http_handle = sb.run("python3 -m http.server 3000", timeout=0, wait=False)
+import time; time.sleep(2)
+
+try:
+ with sb.tunnel(remote_port=3000, local_port=13000) as t:
+ import urllib.request
+ resp = urllib.request.urlopen(f"http://127.0.0.1:{t.local_port}/")
+ print(resp.status) # 200
+finally:
+ http_handle.kill()
+ client.delete_sandbox(sb.name)
+```
+
+### Multiple Tunnels
+
+Open several tunnels simultaneously to different services:
+
+```python
+http_handle2 = sb.run("python3 -m http.server 3001", timeout=0, wait=False)
+import time; time.sleep(1)
+
+with sb.tunnel(remote_port=3000, local_port=23000) as t1, \
+ sb.tunnel(remote_port=3001, local_port=23001) as t2:
+ resp1 = urllib.request.urlopen(f"http://127.0.0.1:{t1.local_port}/")
+ resp2 = urllib.request.urlopen(f"http://127.0.0.1:{t2.local_port}/")
+
+http_handle2.kill()
+```
+
+### Explicit Lifecycle
+
+For notebooks or long-lived sessions where a context manager isn't convenient:
+
+```python
+t = sb.tunnel(remote_port=3000, local_port=23002)
+
+print(t.local_port)
+# ... use the tunnel as long as needed ...
+
+t.close()
+```
+
+### Async Usage
+
+```python
+async with await client.sandbox(snapshot_id=snapshot_id) as sb:
+ async with await sb.tunnel(remote_port=5432) as t:
+ conn = await asyncpg.connect(host="127.0.0.1", port=t.local_port)
+```
+
+## Service URLs
+
+Access HTTP services running inside a sandbox without opening a TCP tunnel.
+`service()` returns a `ServiceURL` object with a short-lived JWT that
+auto-refreshes transparently. Built-in HTTP helpers inject the auth header
+for you.
+
+### Basic Usage
+
+```python
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ # Start a web server inside the sandbox
+ handle = sb.run("python -m http.server 3000", timeout=0, wait=False)
+ import time; time.sleep(2)
+
+ # Get a service URL for port 3000
+ svc = sb.service(port=3000)
+
+ # Make requests — token is injected automatically
+ resp = svc.get("/")
+ print(resp.status_code) # 200
+
+ # POST with JSON body
+ resp = svc.post("/api/data", json={"key": "value"})
+
+ # Access the raw token or URLs directly
+ print(svc.token) # JWT (auto-refreshes near expiry)
+ print(svc.service_url) # base URL for programmatic access
+ print(svc.browser_url) # URL that sets a cookie in a browser
+
+ handle.kill()
+```
+
+### Custom Token TTL
+
+Tokens default to 10 minutes. Set `expires_in_seconds` for longer or shorter
+lifetimes (1 second to 24 hours):
+
+```python
+# Token valid for 1 hour
+svc = sb.service(port=3000, expires_in_seconds=3600)
+```
+
+### Auto-Refresh
+
+The `ServiceURL` object automatically refreshes its token before it expires.
+You never need to worry about token rotation — just keep using the object:
+
+```python
+svc = sb.service(port=3000, expires_in_seconds=60)
+
+# Even after 60 seconds, this still works — token refreshes transparently
+resp = svc.get("/api/status")
+```
+
+### Async Usage
+
+```python
+async with await client.sandbox(snapshot_id=snapshot_id) as sb:
+ svc = await sb.service(port=3000)
+
+ # Async HTTP helpers
+ resp = await svc.get("/api/data")
+
+ # Async accessors for auto-refreshing properties
+ token = await svc.get_token()
+ url = await svc.get_service_url()
+```
+
+## Snapshots
+
+Snapshots are the starting point for every sandbox. They're built from Docker
+images or captured from running sandboxes, and many sandboxes can share the
+same snapshot.
+
+### Build a Snapshot from a Docker Image
+
+```python
+from langsmith.sandbox import SandboxClient
+
+client = SandboxClient()
+
+# Build a snapshot — blocks until ready (default timeout=60s)
+snapshot = client.create_snapshot(
+ "my-python-env",
+ docker_image="python:3.12-slim",
+ fs_capacity_bytes=4 * 1024**3, # 4 GB
+)
+
+# Create a sandbox from the snapshot (by ID)
+with client.sandbox(snapshot_id=snapshot.id) as sb:
+ result = sb.run("python --version")
+ print(result.stdout)
+
+# Or resolve by snapshot name — the server looks up the snapshot owned by
+# your tenant and boots from it. Exactly one of snapshot_id or snapshot_name
+# must be provided.
+with client.sandbox(snapshot_name="my-python-env") as sb:
+ result = sb.run("python --version")
+ print(result.stdout)
+```
+
+### Capture a Running Sandbox
+
+Install packages or prepare files on a running sandbox, then capture the
+result as a reusable snapshot. The returned snapshot has `source_sandbox_id`
+set to the sandbox it was captured from, and can be used as the
+`snapshot_id` for any later `create_sandbox` / `sandbox(...)` call.
+
+```python
+sb = client.create_sandbox(snapshot_id=base_snapshot_id, name="setup-box")
+sb.run("pip install numpy pandas scikit-learn", timeout=180)
+sb.write("/opt/config.yaml", "model: gpt-5\n")
+
+# Either form works; the instance method just forwards to the client.
+snapshot = sb.capture_snapshot("ml-ready", timeout=300)
+# snapshot = client.capture_snapshot(sb.name, "ml-ready", timeout=300)
+print(snapshot.id, snapshot.source_sandbox_id)
+
+sb.delete()
+
+# Later: spin up sandboxes from the captured snapshot
+with client.sandbox(snapshot_id=snapshot.id) as sb:
+ sb.run("python -c 'import numpy; print(numpy.__version__)'")
+ assert sb.read("/opt/config.yaml") == b"model: gpt-5\n"
+```
+
+> **Note:** `capture_snapshot` preserves only the **persistent filesystem**.
+> Installed packages (under `/usr/local`, `/root`, `/opt`, the home
+> directory, etc.) and files you wrote to those paths are kept. Running
+> processes, open sockets, in-memory state, and anything under `/tmp`
+> (which is a tmpfs) are **not** carried over — restart the processes you
+> need in the new sandbox.
+
+### Snapshot CRUD
+
+```python
+# List snapshots (server paginates with a default page size of 50)
+snapshots = client.list_snapshots()
+
+# Filter and paginate — all three kwargs are optional and independent.
+# `limit` must be between 1 and 500 (inclusive); `offset` must be >= 0.
+snapshots = client.list_snapshots(
+ name_contains="python", # case-insensitive substring match on name
+ limit=100,
+ offset=0,
+)
+
+# Get a snapshot by ID
+snapshot = client.get_snapshot("550e8400-...")
+
+# Delete a snapshot
+client.delete_snapshot("550e8400-...")
+
+# Build with longer timeout for large images
+snapshot = client.create_snapshot(
+ "heavy-image",
+ docker_image="nvidia/cuda:12.0-devel-ubuntu22.04",
+ fs_capacity_bytes=16 * 1024**3,
+ timeout=600,
+)
+```
+
+## Start / Stop
+
+Snapshot-based sandboxes can be stopped and restarted. The sandbox files are
+preserved across stop/start cycles.
+
+```python
+sb = client.create_sandbox(snapshot_id=snapshot.id, name="my-vm")
+sb.run("echo 'hello' > /tmp/state.txt")
+
+# Stop the sandbox (preserves sandbox files)
+sb.stop()
+
+# Later: restart it
+sb.start() # blocks until ready (default timeout=120s)
+
+result = sb.run("cat /tmp/state.txt")
+assert result.stdout.strip() == "hello"
+```
+
+You can also use the client methods directly:
+
+```python
+client.stop_sandbox("my-vm")
+sandbox = client.start_sandbox("my-vm")
+```
+
+## Sandbox Lifetime & TTL
+
+Sandboxes follow a two-stage retention model anchored to **idle activity**
+and the **`stopped`** state — there is no wall-clock "max lifetime" TTL:
+
+- **`idle_ttl_seconds`** — Idle timeout. The launcher stops the sandbox
+ after this many seconds of inactivity (any command execution or file I/O
+ resets the timer). When omitted at creation, the server applies a default
+ of `600` seconds (10 minutes); pass `0` explicitly to disable the idle
+ stop and keep the sandbox running indefinitely.
+- **`delete_after_stop_seconds`** — Stop-anchored deletion. Once a sandbox
+ enters the `stopped` state (either via the idle timer above or an explicit
+ `stop_sandbox` call), this timer starts. After the deadline passes, the
+ sandbox row and its filesystem clone are permanently deleted by a
+ server-side sweep. Pass `0` to disable stop-anchored deletion (manual
+ cleanup required); when omitted, the server applies its configured default
+ (typically 14 days).
+
+Both values must be multiples of 60 (minute-resolution). The lifecycle is:
+
+```
+running ──(idle for idle_ttl_seconds)──▶ stopped ──(delete_after_stop_seconds)──▶ deleted
+```
+
+```python
+# Default retention (server defaults: 10 min idle stop, 14 day delete)
+with client.sandbox(snapshot_id=snapshot_id) as sb:
+ result = sb.run("echo hello")
+
+# Aggressive: stop after 5 min idle, delete 1 hour after stop
+sb = client.create_sandbox(
+ snapshot_id=snapshot_id,
+ idle_ttl_seconds=300,
+ delete_after_stop_seconds=3600,
+)
+
+# Long-running: never auto-stop, delete 7 days after manual stop
+sb = client.create_sandbox(
+ snapshot_id=snapshot_id,
+ idle_ttl_seconds=0,
+ delete_after_stop_seconds=604800,
+)
+
+# Inspect retention settings
+print(sb.idle_ttl_seconds) # e.g. 300
+print(sb.delete_after_stop_seconds) # e.g. 3600
+print(sb.stopped_at) # None while running, ISO timestamp once stopped
+```
+
+### Updating retention on existing sandboxes
+
+You can update either retention setting on a running or stopped sandbox.
+Updating `delete_after_stop_seconds` on an already-stopped sandbox shifts
+its deletion deadline (`stopped_at + delete_after_stop_seconds`):
+
+```python
+# Extend the idle stop to 30 minutes
+sb = client.update_sandbox("my-sandbox", idle_ttl_seconds=1800)
+
+# Push the deletion deadline out to 30 days after stop
+sb = client.update_sandbox("my-sandbox", delete_after_stop_seconds=2592000)
+
+# Disable both — sandbox keeps running and never auto-deletes
+sb = client.update_sandbox(
+ "my-sandbox",
+ idle_ttl_seconds=0,
+ delete_after_stop_seconds=0,
+)
+```
+
+> **Migration note (alpha):** the previous `ttl_seconds` (hard wall-clock
+> TTL) and `expires_at` fields were removed. The hard TTL never reliably
+> deleted stopped sandboxes; replace any usage with `idle_ttl_seconds` for
+> stopping and `delete_after_stop_seconds` for deletion.
+
+## Reusing Existing Sandboxes
+
+Get a sandbox that's already running:
+
+```python
+# Create a sandbox (requires explicit cleanup)
+sb = client.create_sandbox(snapshot_id=snapshot_id)
+print(sb.name) # e.g., "sandbox-abc123"
+
+# Later, get the same sandbox
+sb = client.get_sandbox("sandbox-abc123")
+result = sb.run("echo 'Still running!'")
+
+# Clean up when done
+client.delete_sandbox("sandbox-abc123")
+```
+
+## Async Sandbox Creation
+
+By default, `create_sandbox()` blocks until the sandbox is ready. For
+non-blocking creation, pass `wait_for_ready=False`:
+
+```python
+# Returns immediately with status="provisioning"
+sb = client.create_sandbox(snapshot_id=snapshot_id, wait_for_ready=False)
+print(sb.status) # "provisioning"
+
+# Poll until ready using the lightweight status endpoint
+sb = client.wait_for_sandbox(sb.name, timeout=120, poll_interval=1.0)
+print(sb.status) # "ready"
+
+# Now the sandbox is usable
+result = sb.run("echo hello")
+```
+
+You can also poll manually for more control:
+
+```python
+sb = client.create_sandbox(snapshot_id=snapshot_id, wait_for_ready=False)
+
+while True:
+ status = client.get_sandbox_status(sb.name)
+ if status.status == "ready":
+ sb = client.get_sandbox(sb.name)
+ break
+ if status.status == "failed":
+ print(f"Failed: {status.status_message}")
+ break
+ time.sleep(1)
+```
+
+> **Note:** Operations like `run()`, `write()`, and `read()` will raise
+> `SandboxNotReadyError` if called on a sandbox that isn't ready yet.
+
+## Async Support
+
+Full async support for all operations:
+
+```python
+from langsmith.sandbox import AsyncSandboxClient
+
+async def main():
+ async with AsyncSandboxClient() as client:
+ # Build a snapshot first
+ snapshot = await client.create_snapshot(
+ "async-python",
+ docker_image="python:3.12-slim",
+ fs_capacity_bytes=4 * 1024**3,
+ )
+
+ # Use the snapshot
+ async with await client.sandbox(snapshot_id=snapshot.id) as sb:
+ result = await sb.run("python -c 'print(1 + 1)'")
+ print(result.stdout) # "2\n"
+
+ await sb.write("/app/test.txt", "async content")
+ content = await sb.read("/app/test.txt")
+ print(content.decode())
+```
+
+### Async Streaming
+
+```python
+async with await client.sandbox(snapshot_id=snapshot_id) as sb:
+ handle = await sb.run("make build", timeout=600, wait=False)
+
+ async for chunk in handle:
+ print(chunk.data, end="")
+
+ result = await handle.result
+```
+
+## Error Handling
+
+The module provides type-based exceptions with a `resource_type` attribute for specific handling:
+
+```python
+from langsmith.sandbox import (
+ SandboxClientError, # Base exception for all sandbox errors
+ ResourceCreationError, # Resource provisioning failed (check resource_type, error_type)
+ ResourceNotFoundError, # Resource doesn't exist (check resource_type)
+ ResourceTimeoutError, # Operation timed out (check resource_type)
+ SandboxNotReadyError, # Sandbox not ready for operations yet
+ SandboxConnectionError, # Network/WebSocket error
+ CommandTimeoutError, # Command exceeded its timeout (extends SandboxOperationError)
+ QuotaExceededError, # Quota limit reached
+ TunnelError, # Base for tunnel errors
+ TunnelPortNotAllowedError, # Port blocked by daemon allowlist
+ TunnelConnectionRefusedError, # Nothing listening on remote port
+ TunnelUnsupportedVersionError, # Client/daemon protocol mismatch
+)
+
+try:
+ with client.sandbox(snapshot_id=snapshot_id) as sb:
+ result = sb.run("sleep 999", timeout=10)
+except CommandTimeoutError as e:
+ print(f"Command timed out: {e}")
+except ResourceCreationError as e:
+ print(f"{e.resource_type} creation failed: {e}")
+except ResourceNotFoundError as e:
+ print(f"{e.resource_type} not found: {e}")
+except ResourceTimeoutError as e:
+ print(f"Timeout waiting for {e.resource_type}: {e}")
+except SandboxConnectionError as e:
+ print(f"Connection error: {e}")
+except SandboxClientError as e:
+ print(f"Error: {e}")
+```
+
+## API Reference
+
+### SandboxClient
+
+| Method | Description |
+|--------|-------------|
+| `sandbox(snapshot_id=None, *, snapshot_name=None, idle_ttl_seconds=None, delete_after_stop_seconds=None, ...)` | Create a sandbox (auto-deleted on context exit). Exactly one of `snapshot_id` / `snapshot_name` must be set. |
+| `create_sandbox(snapshot_id=None, *, snapshot_name=None, wait_for_ready=True, ...)` | Create a sandbox (requires explicit delete). Exactly one of `snapshot_id` / `snapshot_name` must be set. |
+| `get_sandbox(name)` | Get an existing sandbox by name |
+| `get_sandbox_status(name)` | Get lightweight provisioning status (`ResourceStatus`) |
+| `wait_for_sandbox(name, *, timeout=120, poll_interval=1.0)` | Poll until sandbox is ready or failed |
+| `service(name, port, *, expires_in_seconds=600)` | Get a `ServiceURL` for an HTTP service on the given port |
+| `list_sandboxes()` | List all sandboxes |
+| `update_sandbox(name, *, new_name=None, idle_ttl_seconds=None, delete_after_stop_seconds=None)` | Update a sandbox's name or retention settings |
+| `delete_sandbox(name)` | Delete a sandbox |
+| `start_sandbox(name, *, timeout=120)` | Start a stopped sandbox, poll until ready |
+| `stop_sandbox(name)` | Stop a running sandbox (preserves sandbox files) |
+| `create_snapshot(name, docker_image, fs_capacity_bytes, *, timeout=60)` | Build a snapshot from a Docker image |
+| `capture_snapshot(sandbox_name, name, *, timeout=60)` | Capture a snapshot from a running sandbox |
+| `get_snapshot(snapshot_id)` | Get a snapshot by ID |
+| `list_snapshots(*, name_contains=None, limit=None, offset=None)` | List a page of snapshots (server paginates, default limit 50, max 500; `name_contains` is a case-insensitive substring match) |
+| `delete_snapshot(snapshot_id)` | Delete a snapshot |
+| `wait_for_snapshot(snapshot_id, *, timeout=300)` | Poll until snapshot is ready or failed |
+
+### Sandbox
+
+| Property | Description |
+|----------|-------------|
+| `name` | Display name |
+| `snapshot_id` | Snapshot ID used to create this sandbox |
+| `status` | Lifecycle status: `"provisioning"`, `"ready"`, `"failed"`, or `"stopped"` |
+| `status_message` | Human-readable details when status is `"failed"`, `None` otherwise |
+| `dataplane_url` | URL for runtime operations (only functional when status is `"ready"`) |
+| `id` | Unique identifier (UUID) |
+| `idle_ttl_seconds` | Idle timeout in seconds before the launcher stops the sandbox (`0` means disabled, `None` means not set). New sandboxes get a server-side default of `600` (10 minutes) when not explicitly provided. |
+| `delete_after_stop_seconds` | Seconds after entering `stopped` before the sandbox and its filesystem clone are permanently deleted (`0` means disabled, `None` means server default). |
+| `stopped_at` | ISO 8601 timestamp when the sandbox transitioned to `stopped`, or `None` while running. |
+
+| Method | Description |
+|--------|-------------|
+| `run(command, *, timeout=60, on_stdout=None, on_stderr=None, idle_timeout=300, kill_on_disconnect=False, ttl_seconds=600, pty=False, wait=True)` | Execute a shell command. Returns `ExecutionResult` or `CommandHandle` (when `wait=False`). |
+| `reconnect(command_id, *, stdout_offset=0, stderr_offset=0)` | Reconnect to a running command. Returns `CommandHandle`. |
+| `write(path, content)` | Write file (str or bytes) |
+| `read(path)` | Read file (returns bytes) |
+| `tunnel(remote_port, *, local_port=0)` | Open a TCP tunnel. Returns `Tunnel` (context manager). |
+| `service(port, *, expires_in_seconds=600)` | Get a `ServiceURL` for an HTTP service. Auto-refreshes token. |
+| `start(*, timeout=120)` | Start a stopped sandbox and wait until ready. |
+| `stop()` | Stop a running sandbox (preserves sandbox files for later restart). |
+| `delete()` | Delete this sandbox. |
+| `capture_snapshot(name, *, timeout=60)` | Capture a snapshot from this sandbox. |
+
+### ExecutionResult
+
+| Property | Description |
+|----------|-------------|
+| `stdout` | Standard output (str) |
+| `stderr` | Standard error (str) |
+| `exit_code` | Exit code (int) |
+| `success` | True if exit_code == 0 |
+
+### ResourceStatus
+
+Returned by `client.get_sandbox_status()`.
+
+| Property | Description |
+|----------|-------------|
+| `status` | Lifecycle status: `"provisioning"`, `"ready"`, or `"failed"` |
+| `status_message` | Human-readable details when `"failed"`, `None` otherwise |
+
+### CommandHandle
+
+Returned by `sb.run(wait=False)`. Iterable, yielding `OutputChunk` objects.
+
+| Property / Method | Description |
+|-------------------|-------------|
+| `command_id` | Server-assigned command ID |
+| `pid` | Process ID on the sandbox |
+| `result` | Final `ExecutionResult` (blocks until complete) |
+| `kill()` | Send SIGKILL to the running command |
+| `send_input(data)` | Write string data to the command's stdin |
+| `reconnect()` | Reconnect from last known offsets |
+
+### OutputChunk
+
+| Property | Description |
+|----------|-------------|
+| `stream` | `"stdout"` or `"stderr"` |
+| `data` | Text content of this chunk (str) |
+| `offset` | Byte offset within the stream (int) |
+
+### Tunnel
+
+Returned by `sb.tunnel(remote_port)`. Context manager that opens a local TCP
+listener forwarding to a port inside the sandbox.
+
+| Property / Method | Description |
+|-------------------|-------------|
+| `local_port` | Local port the tunnel is listening on (int) |
+| `remote_port` | Target port inside the sandbox (int) |
+| `close()` | Shut down the tunnel and all connections |
+
+### ServiceURL
+
+Returned by `sb.service(port)`. Holds a short-lived JWT for accessing an HTTP
+service in the sandbox. Properties auto-refresh the token near expiry.
+
+| Property | Description |
+|----------|-------------|
+| `token` | Raw JWT for programmatic use (auto-refreshes) |
+| `service_url` | Base URL for programmatic HTTP access (auto-refreshes) |
+| `browser_url` | URL that exchanges the JWT for a cookie in a browser (auto-refreshes) |
+| `expires_at` | ISO 8601 expiration timestamp (auto-refreshes) |
+
+| Method | Description |
+|--------|-------------|
+| `request(method, path="/", **kwargs)` | Make an HTTP request with auth header injected. Returns `httpx.Response`. |
+| `get(path="/", **kwargs)` | HTTP GET |
+| `post(path="/", **kwargs)` | HTTP POST |
+| `put(path="/", **kwargs)` | HTTP PUT |
+| `patch(path="/", **kwargs)` | HTTP PATCH |
+| `delete(path="/", **kwargs)` | HTTP DELETE |
+
+`AsyncServiceURL` is the async variant. Use `await svc.get_token()`,
+`await svc.get_service_url()`, etc. for auto-refreshing access, and
+`await svc.get(path)` for async HTTP helpers.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..809aa2f57cacd179907b05491585678031accc6e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__init__.py
@@ -0,0 +1,124 @@
+"""LangSmith Sandbox Module.
+
+This module provides sandboxed code execution capabilities through the
+LangSmith Sandbox API.
+
+Example:
+ from langsmith.sandbox import SandboxClient
+
+ # Uses LANGSMITH_ENDPOINT and LANGSMITH_API_KEY from environment
+ client = SandboxClient()
+
+ snapshot = client.create_snapshot(
+ docker_image="python:3.12-slim", name="python-snapshot"
+ )
+ with client.sandbox(snapshot_id=snapshot.id) as sb:
+ result = sb.run("python --version")
+ print(result.stdout)
+
+ # Or async:
+ from langsmith.sandbox import AsyncSandboxClient
+
+ async with AsyncSandboxClient() as client:
+ snapshot = await client.create_snapshot(
+ docker_image="python:3.12-slim", name="python-snapshot"
+ )
+ async with await client.sandbox(snapshot_id=snapshot.id) as sb:
+ result = await sb.run("python --version")
+ print(result.stdout)
+"""
+
+from langsmith.sandbox._async_client import AsyncSandboxClient
+from langsmith.sandbox._async_sandbox import AsyncSandbox
+from langsmith.sandbox._client import SandboxClient
+from langsmith.sandbox._exceptions import (
+ CommandTimeoutError,
+ DataplaneNotConfiguredError,
+ QuotaExceededError,
+ ResourceAlreadyExistsError,
+ ResourceCreationError,
+ ResourceInUseError,
+ ResourceNameConflictError,
+ ResourceNotFoundError,
+ ResourceTimeoutError,
+ SandboxAPIError,
+ SandboxAuthenticationError,
+ SandboxClientError,
+ SandboxConnectionError,
+ SandboxNotReadyError,
+ SandboxOperationError,
+ SandboxServerReloadError,
+ TunnelConnectionRefusedError,
+ TunnelError,
+ TunnelPortNotAllowedError,
+ TunnelUnsupportedVersionError,
+ ValidationError,
+)
+from langsmith.sandbox._models import (
+ AsyncCommandHandle,
+ AsyncServiceURL,
+ CommandHandle,
+ ExecutionResult,
+ OutputChunk,
+ ResourceStatus,
+ ServiceURL,
+ Snapshot,
+)
+from langsmith.sandbox._sandbox import Sandbox
+from langsmith.sandbox._tunnel import AsyncTunnel, Tunnel
+
+__all__ = [
+ # Main classes
+ "SandboxClient",
+ "AsyncSandboxClient",
+ "Sandbox",
+ "AsyncSandbox",
+ # Models
+ "ResourceStatus",
+ "ExecutionResult",
+ "Snapshot",
+ "ServiceURL",
+ "AsyncServiceURL",
+ # WebSocket streaming models
+ "CommandHandle",
+ "AsyncCommandHandle",
+ "OutputChunk",
+ # Base and connection errors
+ "SandboxClientError",
+ "SandboxAPIError",
+ "SandboxAuthenticationError",
+ "SandboxConnectionError",
+ "SandboxServerReloadError",
+ # Resource errors (type-based with resource_type attribute)
+ "ResourceCreationError",
+ "ResourceNotFoundError",
+ "ResourceTimeoutError",
+ "ResourceInUseError",
+ "ResourceAlreadyExistsError",
+ "ResourceNameConflictError",
+ # Validation and quota errors
+ "ValidationError",
+ "QuotaExceededError",
+ # Sandbox-specific errors
+ "SandboxNotReadyError",
+ "SandboxOperationError",
+ "CommandTimeoutError",
+ "DataplaneNotConfiguredError",
+ # Tunnel
+ "Tunnel",
+ "AsyncTunnel",
+ "TunnelError",
+ "TunnelPortNotAllowedError",
+ "TunnelConnectionRefusedError",
+ "TunnelUnsupportedVersionError",
+]
+
+# Emit warning on import
+import warnings
+
+warnings.warn(
+ "langsmith.sandbox is in alpha. "
+ "This feature is experimental, and breaking changes are expected.",
+ FutureWarning,
+ stacklevel=2,
+)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..958cdcc5539851e75dfc4350cf48452a16db7448
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_async_client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_async_client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6dd14307749f06231a3589c1753e6ecd8c13be5c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_async_client.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_async_sandbox.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_async_sandbox.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..75c066ad313f62f3f9bc24811f18ded7325983a3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_async_sandbox.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_client.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a747a0e56bd731ff47555fc4a441619b702717a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_client.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_exceptions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8b03abd3e84d78d0b3810bcf5f427b7903c4ef4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_exceptions.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_helpers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_helpers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1fef33fc5799cf020bb1ac2b58476658edbdd361
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_helpers.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_models.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_models.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6bae20b5d7dbc20dd0c3e4673b15117819021827
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_models.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_sandbox.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_sandbox.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..027bcdaa7fdf66fc497244c230f5ffdfe989d951
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_sandbox.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_transport.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_transport.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44fe63eebf3b9764ac49006b9db6fd7b0b2dea66
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_transport.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_tunnel.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_tunnel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85f08d58b3144026d8549febbe7d2ef38cd1300f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_tunnel.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_ws_execute.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_ws_execute.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..016db622f8388024dd31395541e0f4406ba5b2e7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_ws_execute.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_yamux.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_yamux.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de0191469a1087f85ae87bf72c6fb9ee65202b22
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/__pycache__/_yamux.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_async_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_async_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..d342be160e54e13390279f9f0717ca9a90859033
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_async_client.py
@@ -0,0 +1,975 @@
+"""Async SandboxClient class for interacting with the sandbox server API."""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Mapping
+from typing import Any, Optional
+
+import httpx
+
+from langsmith import utils as ls_utils
+from langsmith.sandbox._async_sandbox import AsyncSandbox
+from langsmith.sandbox._exceptions import (
+ ResourceCreationError,
+ ResourceNameConflictError,
+ ResourceNotFoundError,
+ ResourceTimeoutError,
+ SandboxAPIError,
+)
+from langsmith.sandbox._helpers import (
+ handle_client_http_error,
+ handle_sandbox_creation_error,
+ merge_headers,
+ validate_service_params,
+ validate_ttl,
+)
+from langsmith.sandbox._models import (
+ AsyncServiceURL,
+ ResourceStatus,
+ Snapshot,
+)
+from langsmith.sandbox._transport import AsyncRetryTransport
+
+
+def _get_default_api_endpoint() -> str:
+ """Get the default sandbox API endpoint from environment.
+
+ Derives the endpoint from LANGSMITH_ENDPOINT (or LANGCHAIN_ENDPOINT).
+ """
+ base = ls_utils.get_env_var("ENDPOINT", default="https://api.smith.langchain.com")
+ return f"{base.rstrip('/')}/v2/sandboxes"
+
+
+def _get_default_api_key() -> Optional[str]:
+ """Get the default API key from environment."""
+ return ls_utils.get_env_var("API_KEY")
+
+
+RequestHeaders = Optional[Mapping[str, str]]
+
+
+class AsyncSandboxClient:
+ """Async client for interacting with the Sandbox Server API.
+
+ This client provides an async interface for managing sandboxes and snapshots.
+
+ Example:
+ # Uses LANGSMITH_ENDPOINT and LANGSMITH_API_KEY from environment
+ async with AsyncSandboxClient() as client:
+ # Create a sandbox from a snapshot and run commands
+ async with await client.sandbox(
+ snapshot_id=""
+ ) as sandbox:
+ result = await sandbox.run("python --version")
+ print(result.stdout)
+ """
+
+ def __init__(
+ self,
+ *,
+ api_endpoint: Optional[str] = None,
+ timeout: float = 10.0,
+ api_key: Optional[str] = None,
+ max_retries: int = 3,
+ ):
+ """Initialize the AsyncSandboxClient.
+
+ Args:
+ api_endpoint: Full URL of the sandbox API endpoint. If not provided,
+ derived from LANGSMITH_ENDPOINT environment variable.
+ timeout: Default HTTP timeout in seconds.
+ api_key: API key for authentication. If not provided, uses
+ LANGSMITH_API_KEY environment variable.
+ max_retries: Maximum number of retries for transient errors (502, 503,
+ 504), rate limits (429), and connection failures. Set to 0
+ to disable retries. Default: 3.
+ """
+ self._base_url = (api_endpoint or _get_default_api_endpoint()).rstrip("/")
+ resolved_api_key = api_key or _get_default_api_key()
+ self._api_key = resolved_api_key
+ headers: dict[str, str] = {}
+ if resolved_api_key:
+ headers["X-Api-Key"] = resolved_api_key
+ transport = AsyncRetryTransport(max_retries=max_retries)
+ self._http = httpx.AsyncClient(
+ transport=transport, timeout=timeout, headers=headers
+ )
+
+ def _request_headers(self, headers: RequestHeaders) -> Optional[dict[str, str]]:
+ """Merge default client headers with per-request overrides."""
+ if headers is None:
+ return None
+ return merge_headers(self._http.headers, headers)
+
+ async def aclose(self) -> None:
+ """Close the async HTTP client."""
+ await self._http.aclose()
+
+ def __del__(self) -> None:
+ """Best-effort cleanup of the async HTTP client on garbage collection.
+
+ If an event loop is running, schedules ``aclose()`` as a task.
+ Otherwise the underlying sockets will be closed by the GC.
+ For deterministic cleanup, use ``async with`` or ``await aclose()``.
+ """
+ try:
+ if not self._http.is_closed:
+ try:
+ loop = asyncio.get_running_loop()
+ if not loop.is_closed():
+ loop.create_task(self.aclose())
+ except RuntimeError:
+ pass
+ except Exception:
+ pass
+
+ async def __aenter__(self) -> AsyncSandboxClient:
+ """Enter async context manager."""
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: Optional[type],
+ exc_val: Optional[BaseException],
+ exc_tb: Optional[Any],
+ ) -> None:
+ """Exit async context manager."""
+ await self.aclose()
+
+ def __repr__(self) -> str:
+ """Return a string representation of the instance.
+
+ Returns:
+ The string representation of the instance.
+ """
+ return f"AsyncSandboxClient (API URL: {self._base_url})"
+
+ # ========================================================================
+ # Sandbox Operations
+ # ========================================================================
+
+ async def sandbox(
+ self,
+ snapshot_id: Optional[str] = None,
+ *,
+ snapshot_name: Optional[str] = None,
+ name: Optional[str] = None,
+ timeout: int = 30,
+ idle_ttl_seconds: Optional[int] = None,
+ delete_after_stop_seconds: Optional[int] = None,
+ vcpus: Optional[int] = None,
+ mem_bytes: Optional[int] = None,
+ fs_capacity_bytes: Optional[int] = None,
+ proxy_config: Optional[dict[str, Any]] = None,
+ headers: RequestHeaders = None,
+ ) -> AsyncSandbox:
+ """Create a sandbox and return an AsyncSandbox instance.
+
+ This is the primary method for creating sandboxes. Use it as an
+ async context manager for automatic cleanup:
+
+ async with await client.sandbox(snapshot_id="") as sandbox:
+ result = await sandbox.run("echo hello")
+
+ # Resolve by snapshot name instead of ID:
+ async with await client.sandbox(snapshot_name="my-snap") as sandbox:
+ result = await sandbox.run("echo hello")
+
+ The sandbox is automatically deleted when exiting the context manager.
+ For sandboxes with manual lifecycle management, use create_sandbox().
+
+ Args:
+ snapshot_id: Snapshot ID to boot from. Mutually exclusive with
+ ``snapshot_name``; exactly one must be provided.
+ snapshot_name: Snapshot name to boot from. Resolved server-side to a
+ snapshot owned by the caller's tenant. Mutually exclusive with
+ ``snapshot_id``; exactly one must be provided.
+ name: Optional sandbox name (auto-generated if not provided).
+ timeout: Timeout in seconds when waiting for ready.
+ idle_ttl_seconds: Idle timeout in seconds. The launcher
+ automatically stops the sandbox after this duration of
+ inactivity. Must be a multiple of 60. ``0`` explicitly
+ disables the idle stop. When omitted (``None``), the server
+ applies a default of ``600`` seconds (10 minutes).
+ delete_after_stop_seconds: Seconds after the sandbox enters the
+ ``stopped`` state before it (and its filesystem clone) are
+ permanently deleted. Must be a multiple of 60. ``0`` disables
+ stop-anchored deletion (manual cleanup required). When
+ omitted (``None``), the server applies its configured default.
+ vcpus: Number of vCPUs.
+ mem_bytes: Memory in bytes.
+ fs_capacity_bytes: Root filesystem capacity in bytes.
+ proxy_config: Per-sandbox proxy configuration forwarded to the
+ server as-is. Shape matches the backend `proxy_config` field:
+ ``{"rules": [...], "no_proxy": [...], "access_control":
+ {"allow_list": [...]}}`` or ``{"access_control":
+ {"deny_list": [...]}}``. Use ``access_control.allow_list`` to
+ restrict outbound HTTPS to a set of host patterns (exact
+ domains, globs like ``*.example.com``, IPs, CIDRs, or
+ ``~regex``).
+
+ Returns:
+ AsyncSandbox instance.
+
+ Raises:
+ ResourceTimeoutError: If timeout waiting for sandbox to be ready.
+ ResourceCreationError: If sandbox creation fails.
+ SandboxClientError: For other errors.
+ ValueError: If TTL values are invalid, or if neither/both of
+ ``snapshot_id`` and ``snapshot_name`` are provided.
+ """
+ sb = await self.create_sandbox(
+ snapshot_id,
+ snapshot_name=snapshot_name,
+ name=name,
+ timeout=timeout,
+ idle_ttl_seconds=idle_ttl_seconds,
+ delete_after_stop_seconds=delete_after_stop_seconds,
+ vcpus=vcpus,
+ mem_bytes=mem_bytes,
+ fs_capacity_bytes=fs_capacity_bytes,
+ proxy_config=proxy_config,
+ headers=headers,
+ )
+ sb._auto_delete = True
+ return sb
+
+ async def create_sandbox(
+ self,
+ snapshot_id: Optional[str] = None,
+ *,
+ snapshot_name: Optional[str] = None,
+ name: Optional[str] = None,
+ timeout: int = 30,
+ wait_for_ready: bool = True,
+ idle_ttl_seconds: Optional[int] = None,
+ delete_after_stop_seconds: Optional[int] = None,
+ vcpus: Optional[int] = None,
+ mem_bytes: Optional[int] = None,
+ fs_capacity_bytes: Optional[int] = None,
+ proxy_config: Optional[dict[str, Any]] = None,
+ headers: RequestHeaders = None,
+ ) -> AsyncSandbox:
+ """Create a new Sandbox.
+
+ The sandbox is NOT automatically deleted. Use delete_sandbox() for cleanup,
+ or use sandbox() for automatic cleanup with a context manager.
+
+ Args:
+ snapshot_id: Snapshot ID to boot from. Mutually exclusive with
+ ``snapshot_name``; exactly one must be provided.
+ snapshot_name: Snapshot name to boot from. Resolved server-side to a
+ snapshot owned by the caller's tenant. Mutually exclusive with
+ ``snapshot_id``; exactly one must be provided.
+ name: Optional sandbox name (auto-generated if not provided).
+ timeout: Timeout in seconds when waiting for ready (only used when
+ wait_for_ready=True).
+ wait_for_ready: If True (default), block until sandbox is ready.
+ If False, return immediately with status "provisioning". Use
+ get_sandbox_status() or wait_for_sandbox() to poll for readiness.
+ idle_ttl_seconds: Idle timeout in seconds. The launcher
+ automatically stops the sandbox after this duration of
+ inactivity. Must be a multiple of 60. ``0`` explicitly
+ disables the idle stop. When omitted (``None``), the server
+ applies a default of ``600`` seconds (10 minutes).
+ delete_after_stop_seconds: Seconds after the sandbox enters the
+ ``stopped`` state before it (and its filesystem clone) are
+ permanently deleted. Must be a multiple of 60. ``0`` disables
+ stop-anchored deletion (manual cleanup required). When
+ omitted (``None``), the server applies its configured default.
+ vcpus: Number of vCPUs.
+ mem_bytes: Memory in bytes.
+ fs_capacity_bytes: Root filesystem capacity in bytes.
+ proxy_config: Per-sandbox proxy configuration forwarded to the
+ server as-is. Shape matches the backend `proxy_config` field:
+ ``{"rules": [...], "no_proxy": [...], "access_control":
+ {"allow_list": [...]}}`` or ``{"access_control":
+ {"deny_list": [...]}}``. Use ``access_control.allow_list`` to
+ restrict outbound HTTPS to a set of host patterns (exact
+ domains, globs like ``*.example.com``, IPs, CIDRs, or
+ ``~regex``).
+
+ Returns:
+ Created AsyncSandbox. When wait_for_ready=False, the sandbox will have
+ status="provisioning" and cannot be used for operations until ready.
+
+ Raises:
+ ResourceTimeoutError: If timeout waiting for sandbox to be ready.
+ ResourceCreationError: If sandbox creation fails.
+ SandboxClientError: For other errors.
+ ValueError: If TTL values are invalid, or if neither/both of
+ ``snapshot_id`` and ``snapshot_name`` are provided.
+ """
+ if bool(snapshot_id) == bool(snapshot_name):
+ raise ValueError("Exactly one of snapshot_id or snapshot_name must be set")
+
+ validate_ttl(idle_ttl_seconds, "idle_ttl_seconds")
+ validate_ttl(delete_after_stop_seconds, "delete_after_stop_seconds")
+
+ url = f"{self._base_url}/boxes"
+
+ payload: dict[str, Any] = {
+ "wait_for_ready": wait_for_ready,
+ }
+ if snapshot_id:
+ payload["snapshot_id"] = snapshot_id
+ if snapshot_name:
+ payload["snapshot_name"] = snapshot_name
+ if wait_for_ready:
+ payload["timeout"] = timeout
+ if name:
+ payload["name"] = name
+ if idle_ttl_seconds is not None:
+ payload["idle_ttl_seconds"] = idle_ttl_seconds
+ if delete_after_stop_seconds is not None:
+ payload["delete_after_stop_seconds"] = delete_after_stop_seconds
+ if vcpus is not None:
+ payload["vcpus"] = vcpus
+ if mem_bytes is not None:
+ payload["mem_bytes"] = mem_bytes
+ if fs_capacity_bytes is not None:
+ payload["fs_capacity_bytes"] = fs_capacity_bytes
+ if proxy_config is not None:
+ payload["proxy_config"] = proxy_config
+
+ http_timeout = (timeout + 30) if wait_for_ready else 30
+
+ try:
+ response = await self._http.post(
+ url,
+ json=payload,
+ timeout=http_timeout,
+ headers=self._request_headers(headers),
+ )
+ response.raise_for_status()
+ return AsyncSandbox.from_dict(
+ response.json(), client=self, auto_delete=False
+ )
+ except httpx.HTTPStatusError as e:
+ handle_sandbox_creation_error(e)
+ raise # pragma: no cover
+
+ async def get_sandbox(
+ self, name: str, *, headers: RequestHeaders = None
+ ) -> AsyncSandbox:
+ """Get a Sandbox by name.
+
+ The sandbox is NOT automatically deleted. Use delete_sandbox() for cleanup.
+
+ Args:
+ name: Sandbox name.
+
+ Returns:
+ AsyncSandbox.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/boxes/{name}"
+
+ try:
+ response = await self._http.get(url, headers=self._request_headers(headers))
+ response.raise_for_status()
+ return AsyncSandbox.from_dict(
+ response.json(), client=self, auto_delete=False
+ )
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ async def list_sandboxes(
+ self, *, headers: RequestHeaders = None
+ ) -> list[AsyncSandbox]:
+ """List all Sandboxes.
+
+ Returns:
+ List of AsyncSandboxes.
+ """
+ url = f"{self._base_url}/boxes"
+
+ try:
+ response = await self._http.get(url, headers=self._request_headers(headers))
+ response.raise_for_status()
+ data = response.json()
+ return [
+ AsyncSandbox.from_dict(c, client=self, auto_delete=False)
+ for c in data.get("sandboxes", [])
+ ]
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise SandboxAPIError(
+ f"API endpoint not found: {url}. "
+ f"Check that api_endpoint is correct."
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ async def update_sandbox(
+ self,
+ name: str,
+ *,
+ new_name: Optional[str] = None,
+ idle_ttl_seconds: Optional[int] = None,
+ delete_after_stop_seconds: Optional[int] = None,
+ headers: RequestHeaders = None,
+ ) -> AsyncSandbox:
+ """Update a sandbox's properties.
+
+ Args:
+ name: Current sandbox name.
+ new_name: New display name.
+ idle_ttl_seconds: Idle timeout in seconds. Must be a multiple of
+ 60. ``0`` disables idle-stop. ``None`` leaves the existing
+ value unchanged.
+ delete_after_stop_seconds: Seconds after entering ``stopped``
+ before deletion. Must be a multiple of 60. ``0`` disables
+ stop-anchored deletion. ``None`` leaves the existing value
+ unchanged.
+
+ Returns:
+ Updated AsyncSandbox.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ResourceNameConflictError: If new_name is already in use.
+ SandboxClientError: For other errors.
+ ValueError: If TTL values are invalid.
+ """
+ validate_ttl(idle_ttl_seconds, "idle_ttl_seconds")
+ validate_ttl(delete_after_stop_seconds, "delete_after_stop_seconds")
+
+ url = f"{self._base_url}/boxes/{name}"
+ payload: dict[str, Any] = {}
+ if new_name is not None:
+ payload["name"] = new_name
+ if idle_ttl_seconds is not None:
+ payload["idle_ttl_seconds"] = idle_ttl_seconds
+ if delete_after_stop_seconds is not None:
+ payload["delete_after_stop_seconds"] = delete_after_stop_seconds
+
+ try:
+ response = await self._http.patch(
+ url, json=payload, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ return AsyncSandbox.from_dict(
+ response.json(), client=self, auto_delete=False
+ )
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ if e.response.status_code == 409:
+ raise ResourceNameConflictError(
+ f"Sandbox name '{new_name}' already in use",
+ resource_type="sandbox",
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ async def delete_sandbox(
+ self, name: str, *, headers: RequestHeaders = None
+ ) -> None:
+ """Delete a Sandbox.
+
+ Args:
+ name: Sandbox name.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/boxes/{name}"
+
+ try:
+ response = await self._http.delete(
+ url, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+
+ async def get_sandbox_status(
+ self, name: str, *, headers: RequestHeaders = None
+ ) -> ResourceStatus:
+ """Get the provisioning status of a sandbox.
+
+ This is a lightweight endpoint designed for high-frequency polling
+ during sandbox provisioning. It returns only the status fields
+ without full sandbox data.
+
+ Args:
+ name: Sandbox name.
+
+ Returns:
+ ResourceStatus with status and status_message.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/boxes/{name}/status"
+
+ try:
+ response = await self._http.get(url, headers=self._request_headers(headers))
+ response.raise_for_status()
+ return ResourceStatus.from_dict(response.json())
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ async def service(
+ self,
+ name: str,
+ port: int,
+ *,
+ expires_in_seconds: int = 600,
+ headers: RequestHeaders = None,
+ ) -> AsyncServiceURL:
+ """Get an authenticated URL for a service running inside a sandbox.
+
+ Returns an :class:`AsyncServiceURL` whose async accessors
+ auto-refresh the token transparently before it expires. The
+ object also provides async HTTP helper methods (``.get``,
+ ``.post``, etc.) that inject the authentication header
+ automatically.
+
+ Args:
+ name: Sandbox name.
+ port: Port the service is listening on inside the sandbox.
+ expires_in_seconds: Token TTL in seconds (1--86400, default 600).
+ headers: Optional per-request header overrides.
+
+ Returns:
+ AsyncServiceURL with auto-refreshing token and HTTP helpers.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ValueError: If port or expires_in_seconds is out of range.
+ SandboxClientError: For other errors.
+ """
+ validate_service_params(port, expires_in_seconds)
+ url = f"{self._base_url}/boxes/{name}/service-url"
+ payload = {"port": port, "expires_in_seconds": expires_in_seconds}
+
+ async def _refresher() -> AsyncServiceURL:
+ return await self.service(
+ name,
+ port,
+ expires_in_seconds=expires_in_seconds,
+ headers=headers,
+ )
+
+ try:
+ response = await self._http.post(
+ url, json=payload, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ return AsyncServiceURL.from_dict(response.json(), _refresher=_refresher)
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ async def wait_for_sandbox(
+ self,
+ name: str,
+ *,
+ timeout: int = 120,
+ poll_interval: float = 1.0,
+ headers: RequestHeaders = None,
+ ) -> AsyncSandbox:
+ """Poll until a sandbox reaches "ready" or "failed" status.
+
+ Uses the lightweight status endpoint for polling, then fetches the
+ full sandbox data once ready.
+
+ Args:
+ name: Sandbox name.
+ timeout: Maximum time to wait in seconds.
+ poll_interval: Time between status checks in seconds.
+
+ Returns:
+ AsyncSandbox in "ready" status.
+
+ Raises:
+ ResourceCreationError: If sandbox status becomes "failed".
+ ResourceTimeoutError: If timeout expires while still "provisioning".
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ import time
+
+ deadline = time.monotonic() + timeout
+ while True:
+ status = await self.get_sandbox_status(name, headers=headers)
+ if status.status == "ready":
+ return await self.get_sandbox(name, headers=headers)
+ if status.status == "failed":
+ raise ResourceCreationError(
+ status.status_message or "Sandbox provisioning failed",
+ resource_type="sandbox",
+ )
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise ResourceTimeoutError(
+ f"Sandbox '{name}' not ready after {timeout}s",
+ resource_type="sandbox",
+ last_status=status.status,
+ )
+ await asyncio.sleep(min(poll_interval, remaining))
+
+ async def start_sandbox(
+ self,
+ name: str,
+ *,
+ timeout: int = 120,
+ headers: RequestHeaders = None,
+ ) -> AsyncSandbox:
+ """Start a stopped sandbox and wait until ready.
+
+ Args:
+ name: Sandbox name.
+ timeout: Timeout in seconds when waiting for ready.
+
+ Returns:
+ AsyncSandbox in "ready" status.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ResourceCreationError: If sandbox fails during startup.
+ ResourceTimeoutError: If sandbox doesn't become ready within timeout.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/boxes/{name}/start"
+
+ try:
+ response = await self._http.post(
+ url, json={}, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+
+ return await self.wait_for_sandbox(name, timeout=timeout, headers=headers)
+
+ async def stop_sandbox(self, name: str, *, headers: RequestHeaders = None) -> None:
+ """Stop a running sandbox (preserves sandbox files for later restart).
+
+ Args:
+ name: Sandbox name.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/boxes/{name}/stop"
+
+ try:
+ response = await self._http.post(
+ url, json={}, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+
+ # ========================================================================
+ # Snapshot Operations
+ # ========================================================================
+
+ async def create_snapshot(
+ self,
+ name: str,
+ docker_image: str,
+ fs_capacity_bytes: int,
+ *,
+ registry_id: Optional[str] = None,
+ registry_url: Optional[str] = None,
+ registry_username: Optional[str] = None,
+ registry_password: Optional[str] = None,
+ timeout: int = 60,
+ headers: RequestHeaders = None,
+ ) -> Snapshot:
+ """Build a snapshot from a Docker image.
+
+ Blocks until the snapshot is ready (polls with 2s interval).
+
+ Args:
+ name: Snapshot name.
+ docker_image: Docker image to build from (e.g., "python:3.12-slim").
+ fs_capacity_bytes: Filesystem capacity in bytes.
+ registry_id: Private registry ID (alternative to URL/credentials).
+ registry_url: Registry URL for private images.
+ registry_username: Registry username.
+ registry_password: Registry password.
+ timeout: Timeout in seconds when waiting for ready.
+
+ Returns:
+ Snapshot in "ready" status.
+
+ Raises:
+ ResourceTimeoutError: If snapshot doesn't become ready within timeout.
+ ResourceCreationError: If snapshot build fails.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/snapshots"
+
+ payload: dict[str, Any] = {
+ "name": name,
+ "docker_image": docker_image,
+ "fs_capacity_bytes": fs_capacity_bytes,
+ }
+ if registry_id is not None:
+ payload["registry_id"] = registry_id
+ if registry_url is not None:
+ payload["registry_url"] = registry_url
+ if registry_username is not None:
+ payload["registry_username"] = registry_username
+ if registry_password is not None:
+ payload["registry_password"] = registry_password
+
+ try:
+ response = await self._http.post(
+ url, json=payload, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ snapshot = Snapshot.from_dict(response.json())
+ except httpx.HTTPStatusError as e:
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ return await self.wait_for_snapshot(
+ snapshot.id, timeout=timeout, headers=headers
+ )
+
+ async def capture_snapshot(
+ self,
+ sandbox_name: str,
+ name: str,
+ *,
+ timeout: int = 60,
+ headers: RequestHeaders = None,
+ ) -> Snapshot:
+ """Capture a snapshot from a running sandbox.
+
+ Blocks until the snapshot is ready (polls with 2s interval).
+
+ Args:
+ sandbox_name: Name of the sandbox to capture from.
+ name: Snapshot name.
+ timeout: Timeout in seconds when waiting for ready.
+
+ Returns:
+ Snapshot in "ready" status.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ResourceTimeoutError: If snapshot doesn't become ready within timeout.
+ ResourceCreationError: If snapshot capture fails.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/boxes/{sandbox_name}/snapshot"
+
+ payload: dict[str, Any] = {"name": name}
+
+ try:
+ response = await self._http.post(
+ url, json=payload, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ snapshot = Snapshot.from_dict(response.json())
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{sandbox_name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ return await self.wait_for_snapshot(
+ snapshot.id, timeout=timeout, headers=headers
+ )
+
+ async def get_snapshot(
+ self, snapshot_id: str, *, headers: RequestHeaders = None
+ ) -> Snapshot:
+ """Get a snapshot by ID.
+
+ Args:
+ snapshot_id: Snapshot UUID.
+
+ Returns:
+ Snapshot.
+
+ Raises:
+ ResourceNotFoundError: If snapshot not found.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/snapshots/{snapshot_id}"
+
+ try:
+ response = await self._http.get(url, headers=self._request_headers(headers))
+ response.raise_for_status()
+ return Snapshot.from_dict(response.json())
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Snapshot '{snapshot_id}' not found", resource_type="snapshot"
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ async def list_snapshots(
+ self,
+ *,
+ name_contains: Optional[str] = None,
+ limit: Optional[int] = None,
+ offset: Optional[int] = None,
+ headers: RequestHeaders = None,
+ ) -> list[Snapshot]:
+ """List snapshots.
+
+ The backend always paginates this endpoint. When ``limit`` is omitted
+ the server applies a default page size (currently 50), so a single
+ call is not guaranteed to return every snapshot. To iterate through
+ all results, repeat the call with increasing ``offset`` values (or an
+ explicit ``limit``) until fewer than ``limit`` snapshots come back.
+
+ Args:
+ name_contains: Optional case-insensitive substring filter applied
+ to snapshot names server-side.
+ limit: Optional maximum number of snapshots to return for a single
+ request. Must be between 1 and 500 (inclusive); the server
+ rejects values outside that range. Defaults to 50 server-side
+ when omitted.
+ offset: Optional number of snapshots to skip before returning
+ results. Must be ``>= 0``. Useful for paginating through
+ large result sets in combination with ``limit``.
+
+ Returns:
+ A single page of Snapshots matching the provided filters.
+ """
+ url = f"{self._base_url}/snapshots"
+
+ params: dict[str, Any] = {}
+ if name_contains is not None:
+ params["name_contains"] = name_contains
+ if limit is not None:
+ params["limit"] = limit
+ if offset is not None:
+ params["offset"] = offset
+
+ try:
+ response = await self._http.get(
+ url,
+ params=params or None,
+ headers=self._request_headers(headers),
+ )
+ response.raise_for_status()
+ data = response.json()
+ return [Snapshot.from_dict(s) for s in data.get("snapshots", [])]
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise SandboxAPIError(
+ f"API endpoint not found: {url}. "
+ f"Check that api_endpoint is correct."
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ async def delete_snapshot(
+ self, snapshot_id: str, *, headers: RequestHeaders = None
+ ) -> None:
+ """Delete a snapshot.
+
+ Args:
+ snapshot_id: Snapshot UUID.
+
+ Raises:
+ ResourceNotFoundError: If snapshot not found.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/snapshots/{snapshot_id}"
+
+ try:
+ response = await self._http.delete(
+ url, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Snapshot '{snapshot_id}' not found", resource_type="snapshot"
+ ) from e
+ handle_client_http_error(e)
+
+ async def wait_for_snapshot(
+ self,
+ snapshot_id: str,
+ *,
+ timeout: int = 300,
+ poll_interval: float = 2.0,
+ headers: RequestHeaders = None,
+ ) -> Snapshot:
+ """Poll until a snapshot reaches "ready" or "failed" status.
+
+ Args:
+ snapshot_id: Snapshot UUID.
+ timeout: Maximum time to wait in seconds.
+ poll_interval: Time between status checks in seconds.
+
+ Returns:
+ Snapshot in "ready" status.
+
+ Raises:
+ ResourceCreationError: If snapshot status becomes "failed".
+ ResourceTimeoutError: If timeout expires.
+ ResourceNotFoundError: If snapshot not found.
+ SandboxClientError: For other errors.
+ """
+ import time
+
+ deadline = time.monotonic() + timeout
+ while True:
+ snapshot = await self.get_snapshot(snapshot_id, headers=headers)
+ if snapshot.status == "ready":
+ return snapshot
+ if snapshot.status == "failed":
+ raise ResourceCreationError(
+ snapshot.status_message or "Snapshot build failed",
+ resource_type="snapshot",
+ )
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise ResourceTimeoutError(
+ f"Snapshot '{snapshot_id}' not ready after {timeout}s",
+ resource_type="snapshot",
+ last_status=snapshot.status,
+ )
+ await asyncio.sleep(min(poll_interval, remaining))
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_async_sandbox.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_async_sandbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc76451e993932dc2898a39d85107b5a2747faab
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_async_sandbox.py
@@ -0,0 +1,732 @@
+"""AsyncSandbox class for async sandbox operations."""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Union, overload
+
+import httpx
+
+from langsmith.sandbox._exceptions import (
+ DataplaneNotConfiguredError,
+ ResourceNotFoundError,
+ SandboxConnectionError,
+ SandboxNotReadyError,
+)
+from langsmith.sandbox._helpers import handle_sandbox_http_error
+from langsmith.sandbox._models import (
+ AsyncCommandHandle,
+ AsyncServiceURL,
+ ExecutionResult,
+ Snapshot,
+)
+from langsmith.sandbox._tunnel import AsyncTunnel
+
+if TYPE_CHECKING:
+ from langsmith.sandbox._async_client import AsyncSandboxClient
+
+
+RequestHeaders = Optional[Mapping[str, str]]
+
+
+@dataclass
+class AsyncSandbox:
+ """Represents an active sandbox for running commands and file operations async.
+
+ This class is typically obtained from AsyncSandboxClient.sandbox() and supports
+ the async context manager protocol for automatic cleanup.
+
+ Attributes:
+ name: Display name (can be updated).
+ dataplane_url: URL for data plane operations (file I/O, command execution).
+ Only functional when status is "ready".
+ id: Unique identifier (UUID). Remains constant even if name changes.
+ May be None for resources created before ID support was added.
+ status: Sandbox lifecycle status. One of "provisioning", "ready",
+ "failed", "stopped".
+ status_message: Human-readable details when status is "failed", None otherwise.
+ created_at: Timestamp when the sandbox was created.
+ updated_at: Timestamp when the sandbox was last updated.
+ idle_ttl_seconds: Idle timeout TTL in seconds (``0`` means disabled).
+ Newly-created sandboxes receive a server-side default of ``600``
+ seconds (10 minutes) when the caller did not set ``idle_ttl_seconds``
+ explicitly. The launcher stops the sandbox after this many idle
+ seconds; deletion is anchored to ``stopped_at`` and controlled by
+ ``delete_after_stop_seconds`` (see below).
+ delete_after_stop_seconds: Seconds after a sandbox enters the
+ ``stopped`` state before it (and its filesystem clone) are
+ permanently deleted. ``0`` disables stop-anchored deletion;
+ ``None`` falls back to the server default.
+ stopped_at: Timestamp when the sandbox transitioned to ``stopped``,
+ or ``None`` while running. The deletion deadline is
+ ``stopped_at + delete_after_stop_seconds``.
+ snapshot_id: Snapshot ID used to create this sandbox.
+ vcpus: Number of vCPUs allocated.
+ mem_bytes: Memory allocation in bytes.
+ fs_capacity_bytes: Root filesystem capacity in bytes.
+
+ Example:
+ async with await client.sandbox(
+ snapshot_id=""
+ ) as sandbox:
+ result = await sandbox.run("python --version")
+ print(result.stdout)
+ """
+
+ # Data fields (from API response)
+ name: str
+ dataplane_url: Optional[str] = None
+ id: Optional[str] = None
+ status: str = "ready"
+ status_message: Optional[str] = None
+ created_at: Optional[str] = None
+ updated_at: Optional[str] = None
+ idle_ttl_seconds: Optional[int] = None
+ delete_after_stop_seconds: Optional[int] = None
+ stopped_at: Optional[str] = None
+ snapshot_id: Optional[str] = None
+ vcpus: Optional[int] = None
+ mem_bytes: Optional[int] = None
+ fs_capacity_bytes: Optional[int] = None
+
+ # Internal fields (not from API)
+ _client: AsyncSandboxClient = field(repr=False, default=None) # type: ignore
+ _auto_delete: bool = field(repr=False, default=True)
+
+ @classmethod
+ def from_dict(
+ cls,
+ data: dict[str, Any],
+ client: AsyncSandboxClient,
+ auto_delete: bool = True,
+ ) -> AsyncSandbox:
+ """Create an AsyncSandbox from API response dict.
+
+ Args:
+ data: API response dictionary containing sandbox data.
+ client: Parent AsyncSandboxClient for operations.
+ auto_delete: Whether to delete the sandbox on context exit.
+
+ Returns:
+ AsyncSandbox instance.
+ """
+ return cls(
+ name=data.get("name", ""),
+ dataplane_url=data.get("dataplane_url"),
+ id=data.get("id"),
+ status=data.get("status", "ready"),
+ status_message=data.get("status_message"),
+ created_at=data.get("created_at"),
+ updated_at=data.get("updated_at"),
+ idle_ttl_seconds=data.get("idle_ttl_seconds"),
+ delete_after_stop_seconds=data.get("delete_after_stop_seconds"),
+ stopped_at=data.get("stopped_at"),
+ snapshot_id=data.get("snapshot_id"),
+ vcpus=data.get("vcpus"),
+ mem_bytes=data.get("mem_bytes"),
+ fs_capacity_bytes=data.get("fs_capacity_bytes"),
+ _client=client,
+ _auto_delete=auto_delete,
+ )
+
+ async def __aenter__(self) -> AsyncSandbox:
+ """Enter async context manager."""
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: Optional[type],
+ exc_val: Optional[BaseException],
+ exc_tb: Optional[Any],
+ ) -> None:
+ """Exit async context manager, optionally deleting the sandbox."""
+ if self._auto_delete:
+ try:
+ await self._client.delete_sandbox(self.name)
+ except Exception:
+ # Don't raise on cleanup errors
+ pass
+
+ def _require_dataplane_url(self) -> str:
+ """Validate and return the dataplane URL.
+
+ Returns:
+ The dataplane URL.
+
+ Raises:
+ SandboxNotReadyError: If sandbox status is not "ready".
+ DataplaneNotConfiguredError: If dataplane_url is not configured.
+ """
+ if self.status != "ready":
+ raise SandboxNotReadyError(
+ f"Sandbox '{self.name}' is not ready (status: {self.status}). "
+ "Wait for status 'ready' before running operations."
+ )
+ if not self.dataplane_url:
+ raise DataplaneNotConfiguredError(
+ f"Sandbox '{self.name}' does not have a dataplane_url configured. "
+ "Runtime operations require a dataplane URL."
+ )
+ return self.dataplane_url
+
+ @overload
+ async def run(
+ self,
+ command: str,
+ *,
+ timeout: int = ...,
+ env: Optional[dict[str, str]] = ...,
+ cwd: Optional[str] = ...,
+ shell: str = ...,
+ on_stdout: Optional[Callable[[str], Any]] = ...,
+ on_stderr: Optional[Callable[[str], Any]] = ...,
+ idle_timeout: int = ...,
+ kill_on_disconnect: bool = ...,
+ ttl_seconds: int = ...,
+ pty: bool = ...,
+ headers: RequestHeaders = ...,
+ wait: Literal[True] = ...,
+ ) -> ExecutionResult: ...
+
+ @overload
+ async def run(
+ self,
+ command: str,
+ *,
+ timeout: int = ...,
+ env: Optional[dict[str, str]] = ...,
+ cwd: Optional[str] = ...,
+ shell: str = ...,
+ on_stdout: Optional[Callable[[str], Any]] = ...,
+ on_stderr: Optional[Callable[[str], Any]] = ...,
+ idle_timeout: int = ...,
+ kill_on_disconnect: bool = ...,
+ ttl_seconds: int = ...,
+ pty: bool = ...,
+ headers: RequestHeaders = ...,
+ wait: Literal[False],
+ ) -> AsyncCommandHandle: ...
+
+ async def run(
+ self,
+ command: str,
+ *,
+ timeout: int = 60,
+ env: Optional[dict[str, str]] = None,
+ cwd: Optional[str] = None,
+ shell: str = "/bin/bash",
+ on_stdout: Optional[Callable[[str], Any]] = None,
+ on_stderr: Optional[Callable[[str], Any]] = None,
+ idle_timeout: int = 300,
+ kill_on_disconnect: bool = False,
+ ttl_seconds: int = 600,
+ pty: bool = False,
+ headers: RequestHeaders = None,
+ wait: bool = True,
+ ) -> Union[ExecutionResult, AsyncCommandHandle]:
+ """Execute a command in the sandbox asynchronously.
+
+ Args:
+ command: Shell command to execute.
+ timeout: Command timeout in seconds.
+ env: Environment variables to set for the command.
+ cwd: Working directory for command execution. If None, uses sandbox default.
+ shell: Shell to use for command execution. Defaults to "/bin/bash".
+ on_stdout: Callback invoked with each stdout chunk as it arrives.
+ Blocks until the command completes and returns ExecutionResult.
+ Cannot be combined with wait=False.
+ on_stderr: Callback invoked with each stderr chunk as it arrives.
+ Blocks until the command completes and returns ExecutionResult.
+ Cannot be combined with wait=False.
+ idle_timeout: Idle timeout in seconds. If the command has no
+ connected clients for this duration, it is killed. Defaults
+ to 300 (5 minutes). Set to -1 for no idle timeout.
+ Only applies to WebSocket execution.
+ kill_on_disconnect: If True, kill the command immediately when
+ the last client disconnects. Defaults to False (command
+ continues running and can be reconnected to).
+ ttl_seconds: How long (in seconds) a finished command's session
+ is kept for reconnection. Defaults to 600 (10 minutes).
+ Set to -1 to keep indefinitely.
+ pty: If True, allocate a pseudo-terminal for the command.
+ Useful for commands that require a TTY (e.g., interactive
+ programs, commands that use terminal control codes).
+ Defaults to False.
+ wait: If True (default), block until the command completes and
+ return ExecutionResult. If False, return an
+ AsyncCommandHandle immediately for streaming output,
+ kill, stdin input, and reconnection. Cannot be combined
+ with on_stdout/on_stderr callbacks.
+
+ Returns:
+ ExecutionResult when wait=True (default).
+ AsyncCommandHandle when wait=False.
+
+ Raises:
+ ValueError: If wait=False is combined with callbacks.
+ DataplaneNotConfiguredError: If dataplane_url is not configured.
+ SandboxOperationError: If command execution fails.
+ CommandTimeoutError: If command exceeds its timeout.
+ SandboxConnectionError: If connection to sandbox fails after retries.
+ SandboxNotReadyError: If sandbox is not ready.
+ SandboxClientError: For other errors.
+ """
+ if not wait and (on_stdout or on_stderr):
+ raise ValueError(
+ "Cannot combine wait=False with on_stdout/on_stderr callbacks. "
+ "Use wait=False and iterate the CommandHandle, or use callbacks."
+ )
+
+ self._require_dataplane_url()
+
+ use_ws = not wait or on_stdout or on_stderr
+ if use_ws:
+ return await self._run_ws(
+ command,
+ timeout=timeout,
+ env=env,
+ cwd=cwd,
+ shell=shell,
+ wait=wait,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ idle_timeout=idle_timeout,
+ kill_on_disconnect=kill_on_disconnect,
+ ttl_seconds=ttl_seconds,
+ pty=pty,
+ headers=headers,
+ )
+
+ # Catch broad exceptions so that unexpected WS failures (e.g. version
+ # incompatibilities) don't break users who don't need WS features.
+ try:
+ return await self._run_ws(
+ command,
+ timeout=timeout,
+ env=env,
+ cwd=cwd,
+ shell=shell,
+ wait=True,
+ on_stdout=None,
+ on_stderr=None,
+ idle_timeout=idle_timeout,
+ kill_on_disconnect=kill_on_disconnect,
+ ttl_seconds=ttl_seconds,
+ pty=pty,
+ headers=headers,
+ )
+ except (SandboxConnectionError, ImportError, OSError, TypeError):
+ return await self._run_http(
+ command,
+ timeout=timeout,
+ env=env,
+ cwd=cwd,
+ shell=shell,
+ headers=headers,
+ )
+
+ async def _run_ws(
+ self,
+ command: str,
+ *,
+ timeout: int,
+ env: Optional[dict[str, str]],
+ cwd: Optional[str],
+ shell: str,
+ wait: bool,
+ on_stdout: Optional[Callable[[str], Any]],
+ on_stderr: Optional[Callable[[str], Any]],
+ idle_timeout: int = 300,
+ kill_on_disconnect: bool = False,
+ ttl_seconds: int = 600,
+ pty: bool = False,
+ headers: RequestHeaders = None,
+ ) -> Union[ExecutionResult, AsyncCommandHandle]:
+ """Execute via WebSocket /execute/ws."""
+ from langsmith.sandbox._ws_execute import run_ws_stream_async
+
+ dataplane_url = self._require_dataplane_url()
+ api_key = self._client._api_key
+
+ ws_kwargs: dict[str, Any] = {
+ "timeout": timeout,
+ "env": env,
+ "cwd": cwd,
+ "shell": shell,
+ "on_stdout": on_stdout,
+ "on_stderr": on_stderr,
+ "idle_timeout": idle_timeout,
+ "kill_on_disconnect": kill_on_disconnect,
+ "ttl_seconds": ttl_seconds,
+ "pty": pty,
+ }
+ if headers is not None:
+ ws_kwargs["headers"] = headers
+
+ msg_stream, control = await run_ws_stream_async(
+ dataplane_url,
+ api_key,
+ command,
+ **ws_kwargs,
+ )
+
+ handle = AsyncCommandHandle(msg_stream, control, self)
+ await handle._ensure_started()
+
+ if not wait:
+ return handle
+
+ return await handle.result
+
+ async def _run_http(
+ self,
+ command: str,
+ *,
+ timeout: int,
+ env: Optional[dict[str, str]],
+ cwd: Optional[str],
+ shell: str,
+ headers: RequestHeaders,
+ ) -> ExecutionResult:
+ """Execute via HTTP POST /execute (existing implementation)."""
+ dataplane_url = self._require_dataplane_url()
+ url = f"{dataplane_url}/execute"
+ payload: dict[str, Any] = {
+ "command": command,
+ "timeout": timeout,
+ "shell": shell,
+ }
+ if env is not None:
+ payload["env"] = env
+ if cwd is not None:
+ payload["cwd"] = cwd
+
+ try:
+ response = await self._client._http.post(
+ url,
+ json=payload,
+ timeout=timeout + 10,
+ headers=self._client._request_headers(headers),
+ )
+ response.raise_for_status()
+ data = response.json()
+ return ExecutionResult(
+ stdout=data.get("stdout", ""),
+ stderr=data.get("stderr", ""),
+ exit_code=data.get("exit_code", -1),
+ )
+ except httpx.HTTPStatusError as e:
+ handle_sandbox_http_error(e)
+ raise # pragma: no cover
+
+ async def reconnect(
+ self,
+ command_id: str,
+ *,
+ stdout_offset: int = 0,
+ stderr_offset: int = 0,
+ headers: RequestHeaders = None,
+ ) -> AsyncCommandHandle:
+ """Reconnect to a running or recently-finished command.
+
+ Resumes output from the given byte offsets. Any output produced while
+ the client was disconnected is replayed from the server's ring buffer.
+
+ Args:
+ command_id: The command ID from handle.command_id.
+ stdout_offset: Byte offset to resume stdout from (default: 0).
+ stderr_offset: Byte offset to resume stderr from (default: 0).
+
+ Returns:
+ An AsyncCommandHandle for the command.
+
+ Raises:
+ SandboxOperationError: If command_id is not found or session expired.
+ SandboxConnectionError: If connection to sandbox fails after retries.
+ """
+ from langsmith.sandbox._ws_execute import reconnect_ws_stream_async
+
+ dataplane_url = self._require_dataplane_url()
+ api_key = self._client._api_key
+
+ reconnect_kwargs: dict[str, Any] = {
+ "stdout_offset": stdout_offset,
+ "stderr_offset": stderr_offset,
+ }
+ if headers is not None:
+ reconnect_kwargs["headers"] = headers
+
+ msg_stream, control = await reconnect_ws_stream_async(
+ dataplane_url,
+ api_key,
+ command_id,
+ **reconnect_kwargs,
+ )
+
+ return AsyncCommandHandle(
+ msg_stream,
+ control,
+ self,
+ command_id=command_id,
+ stdout_offset=stdout_offset,
+ stderr_offset=stderr_offset,
+ )
+
+ async def write(
+ self,
+ path: str,
+ content: Union[str, bytes],
+ *,
+ timeout: int = 60,
+ headers: RequestHeaders = None,
+ ) -> None:
+ """Write content to a file in the sandbox asynchronously.
+
+ Args:
+ path: Target file path in the sandbox.
+ content: File content (str or bytes).
+ timeout: Request timeout in seconds.
+
+ Raises:
+ DataplaneNotConfiguredError: If dataplane_url is not configured.
+ SandboxOperationError: If file write fails.
+ SandboxConnectionError: If connection to sandbox fails after retries.
+ SandboxNotReadyError: If sandbox is not ready.
+ SandboxClientError: For other errors.
+ """
+ dataplane_url = self._require_dataplane_url()
+ url = f"{dataplane_url}/upload"
+
+ # Ensure content is bytes for multipart upload
+ if isinstance(content, str):
+ content = content.encode("utf-8")
+
+ files = {"file": ("file", content)}
+
+ try:
+ response = await self._client._http.post(
+ url,
+ params={"path": path},
+ files=files,
+ timeout=timeout,
+ headers=self._client._request_headers(headers),
+ )
+ response.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ handle_sandbox_http_error(e)
+
+ async def read(
+ self, path: str, *, timeout: int = 60, headers: RequestHeaders = None
+ ) -> bytes:
+ """Read a file from the sandbox asynchronously.
+
+ Args:
+ path: File path to read. Supports both absolute paths (e.g., /tmp/file.txt)
+ and relative paths (resolved from /home/user/).
+ timeout: Request timeout in seconds.
+
+ Returns:
+ File contents as bytes.
+
+ Raises:
+ DataplaneNotConfiguredError: If dataplane_url is not configured.
+ ResourceNotFoundError: If the file doesn't exist.
+ SandboxOperationError: If file read fails.
+ SandboxConnectionError: If connection to sandbox fails after retries.
+ SandboxNotReadyError: If sandbox is not ready.
+ SandboxClientError: For other errors.
+ """
+ dataplane_url = self._require_dataplane_url()
+ url = f"{dataplane_url}/download"
+
+ try:
+ response = await self._client._http.get(
+ url,
+ params={"path": path},
+ timeout=timeout,
+ headers=self._client._request_headers(headers),
+ )
+ response.raise_for_status()
+ return response.content
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"File '{path}' not found in sandbox '{self.name}'",
+ resource_type="file",
+ ) from e
+ handle_sandbox_http_error(e)
+ # This line should never be reached but satisfies type checker
+ raise # pragma: no cover
+
+ async def tunnel(
+ self,
+ remote_port: int,
+ *,
+ local_port: int = 0,
+ max_reconnects: int = 3,
+ headers: RequestHeaders = None,
+ ) -> AsyncTunnel:
+ """Open a TCP tunnel to a port inside the sandbox.
+
+ Creates a local TCP listener that forwards connections through a
+ yamux-multiplexed WebSocket to the specified port inside the sandbox.
+ Works with any TCP protocol (databases, Redis, HTTP, etc.).
+
+ Usage::
+
+ async with await sandbox.tunnel(remote_port=5432) as t:
+ conn = await asyncpg.connect(host="127.0.0.1", port=t.local_port)
+
+ Args:
+ remote_port: TCP port inside the sandbox to tunnel to (1-65535).
+ local_port: Local port to listen on. Defaults to mirroring
+ remote_port. Use 0 to let the OS pick an available port.
+ max_reconnects: Maximum number of automatic reconnect attempts
+ when the WebSocket session drops. Set to 0 to disable.
+
+ Returns:
+ An AsyncTunnel instance (async context manager).
+
+ Raises:
+ ValueError: If port values are out of range.
+ DataplaneNotConfiguredError: If dataplane_url is not configured.
+ SandboxNotReadyError: If sandbox is not ready.
+ """
+ if not 1 <= remote_port <= 65535:
+ raise ValueError(
+ f"remote_port must be between 1 and 65535 (got {remote_port})"
+ )
+ if local_port and not 1 <= local_port <= 65535:
+ raise ValueError(
+ f"local_port must be between 1 and 65535 (got {local_port})"
+ )
+ dataplane_url = self._require_dataplane_url()
+ api_key = self._client._api_key
+ t = AsyncTunnel(
+ dataplane_url,
+ api_key,
+ remote_port,
+ local_port=local_port,
+ max_reconnects=max_reconnects,
+ headers=headers,
+ )
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(None, t._tunnel._start)
+ return t
+
+ async def service(
+ self,
+ port: int,
+ *,
+ expires_in_seconds: int = 600,
+ headers: RequestHeaders = None,
+ ) -> AsyncServiceURL:
+ """Get an authenticated URL for a service running in this sandbox.
+
+ Returns an :class:`AsyncServiceURL` whose async accessors
+ auto-refresh the token transparently before it expires.
+
+ Args:
+ port: Port the service is listening on inside the sandbox.
+ expires_in_seconds: Token TTL in seconds (1--86400, default 600).
+ headers: Optional per-request header overrides.
+
+ Returns:
+ AsyncServiceURL with auto-refreshing token and HTTP helpers.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ValueError: If port or expires_in_seconds is out of range.
+ SandboxClientError: For other errors.
+ """
+ return await self._client.service(
+ self.name,
+ port,
+ expires_in_seconds=expires_in_seconds,
+ headers=headers,
+ )
+
+ async def start(
+ self,
+ *,
+ timeout: int = 120,
+ headers: RequestHeaders = None,
+ ) -> None:
+ """Start a stopped sandbox and wait until ready.
+
+ After starting, the sandbox's status and dataplane_url are updated
+ in place.
+
+ Args:
+ timeout: Timeout in seconds when waiting for ready.
+ headers: Optional per-request header overrides.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ResourceCreationError: If sandbox fails during startup.
+ ResourceTimeoutError: If sandbox doesn't become ready within timeout.
+ SandboxClientError: For other errors.
+ """
+ refreshed = await self._client.start_sandbox(
+ self.name, timeout=timeout, headers=headers
+ )
+ self.status = refreshed.status
+ self.dataplane_url = refreshed.dataplane_url
+
+ async def stop(self, *, headers: RequestHeaders = None) -> None:
+ """Stop a running sandbox (preserves sandbox files for later restart).
+
+ Args:
+ headers: Optional per-request header overrides.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ await self._client.stop_sandbox(self.name, headers=headers)
+ self.status = "stopped"
+ self.dataplane_url = None
+
+ async def delete(self, *, headers: RequestHeaders = None) -> None:
+ """Delete this sandbox.
+
+ Args:
+ headers: Optional per-request header overrides.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ await self._client.delete_sandbox(self.name, headers=headers)
+
+ async def capture_snapshot(
+ self,
+ name: str,
+ *,
+ timeout: int = 60,
+ headers: RequestHeaders = None,
+ ) -> Snapshot:
+ """Capture a snapshot from this sandbox.
+
+ Args:
+ name: Snapshot name.
+ timeout: Timeout in seconds when waiting for ready.
+ headers: Optional per-request header overrides.
+
+ Returns:
+ Snapshot in "ready" status.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ResourceTimeoutError: If snapshot doesn't become ready within timeout.
+ ResourceCreationError: If snapshot capture fails.
+ SandboxClientError: For other errors.
+ """
+ return await self._client.capture_snapshot(
+ self.name,
+ name,
+ timeout=timeout,
+ headers=headers,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..1034b5bb102d3567dc2b4b2d34af4d7fbe240ed6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_client.py
@@ -0,0 +1,951 @@
+"""Main SandboxClient class for interacting with the sandbox server API."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, Optional
+
+import httpx
+
+from langsmith import utils as ls_utils
+from langsmith.sandbox._exceptions import (
+ ResourceCreationError,
+ ResourceNameConflictError,
+ ResourceNotFoundError,
+ ResourceTimeoutError,
+ SandboxAPIError,
+)
+from langsmith.sandbox._helpers import (
+ handle_client_http_error,
+ handle_sandbox_creation_error,
+ merge_headers,
+ validate_service_params,
+ validate_ttl,
+)
+from langsmith.sandbox._models import (
+ ResourceStatus,
+ ServiceURL,
+ Snapshot,
+)
+from langsmith.sandbox._sandbox import Sandbox
+from langsmith.sandbox._transport import RetryTransport
+
+
+def _get_default_api_endpoint() -> str:
+ """Get the default sandbox API endpoint from environment.
+
+ Derives the endpoint from LANGSMITH_ENDPOINT (or LANGCHAIN_ENDPOINT).
+ """
+ base = ls_utils.get_env_var("ENDPOINT", default="https://api.smith.langchain.com")
+ return f"{base.rstrip('/')}/v2/sandboxes"
+
+
+def _get_default_api_key() -> Optional[str]:
+ """Get the default API key from environment."""
+ return ls_utils.get_env_var("API_KEY")
+
+
+RequestHeaders = Optional[Mapping[str, str]]
+
+
+class SandboxClient:
+ """Client for interacting with the Sandbox Server API.
+
+ This client provides a simple interface for managing sandboxes and snapshots.
+
+ Example:
+ # Uses LANGSMITH_ENDPOINT and LANGSMITH_API_KEY from environment
+ client = SandboxClient()
+
+ # Or with explicit configuration
+ client = SandboxClient(
+ api_endpoint="https://api.smith.langchain.com/v2/sandboxes",
+ api_key="your-api-key",
+ )
+
+ # Create a sandbox from a snapshot and run commands
+ with client.sandbox(snapshot_id="") as sandbox:
+ result = sandbox.run("python --version")
+ print(result.stdout)
+ """
+
+ def __init__(
+ self,
+ *,
+ api_endpoint: Optional[str] = None,
+ timeout: float = 10.0,
+ api_key: Optional[str] = None,
+ max_retries: int = 3,
+ headers: Optional[RequestHeaders] = None,
+ ):
+ """Initialize the SandboxClient.
+
+ Args:
+ api_endpoint: Full URL of the sandbox API endpoint. If not provided,
+ derived from LANGSMITH_ENDPOINT environment variable.
+ timeout: Default HTTP timeout in seconds.
+ api_key: API key for authentication. If not provided, uses
+ LANGSMITH_API_KEY environment variable.
+ max_retries: Maximum number of retries for transient errors (502, 503,
+ 504), rate limits (429), and connection failures. Set to 0
+ to disable retries. Default: 3.
+ """
+ self._base_url = (api_endpoint or _get_default_api_endpoint()).rstrip("/")
+ resolved_api_key = api_key or _get_default_api_key()
+ self._api_key = resolved_api_key
+ client_headers: dict[str, str] = {}
+ if resolved_api_key:
+ client_headers["X-Api-Key"] = resolved_api_key
+ if headers:
+ client_headers = merge_headers(client_headers, headers)
+ transport = RetryTransport(max_retries=max_retries)
+ self._http = httpx.Client(
+ transport=transport, timeout=timeout, headers=client_headers
+ )
+
+ def _request_headers(self, headers: RequestHeaders) -> Optional[dict[str, str]]:
+ """Merge default client headers with per-request overrides."""
+ if headers is None:
+ return None
+ return merge_headers(self._http.headers, headers)
+
+ def close(self) -> None:
+ """Close the HTTP client."""
+ self._http.close()
+
+ def __del__(self) -> None:
+ """Close the HTTP client on garbage collection."""
+ try:
+ if not self._http.is_closed:
+ self._http.close()
+ except Exception:
+ pass
+
+ def __enter__(self) -> SandboxClient:
+ """Enter context manager."""
+ return self
+
+ def __exit__(
+ self,
+ exc_type: Optional[type],
+ exc_val: Optional[BaseException],
+ exc_tb: Optional[Any],
+ ) -> None:
+ """Exit context manager."""
+ self.close()
+
+ def __repr__(self) -> str:
+ """Return a string representation of the instance.
+
+ Returns:
+ The string representation of the instance.
+ """
+ return f"SandboxClient (API URL: {self._base_url})"
+
+ # ========================================================================
+ # Sandbox Operations
+ # ========================================================================
+
+ def sandbox(
+ self,
+ snapshot_id: Optional[str] = None,
+ *,
+ snapshot_name: Optional[str] = None,
+ name: Optional[str] = None,
+ timeout: int = 30,
+ idle_ttl_seconds: Optional[int] = None,
+ delete_after_stop_seconds: Optional[int] = None,
+ vcpus: Optional[int] = None,
+ mem_bytes: Optional[int] = None,
+ fs_capacity_bytes: Optional[int] = None,
+ proxy_config: Optional[dict[str, Any]] = None,
+ headers: RequestHeaders = None,
+ ) -> Sandbox:
+ """Create a sandbox and return a Sandbox instance.
+
+ This is the primary method for creating sandboxes. Use it as a
+ context manager for automatic cleanup:
+
+ with client.sandbox(snapshot_id="") as sandbox:
+ result = sandbox.run("echo hello")
+
+ # Resolve by snapshot name instead of ID:
+ with client.sandbox(snapshot_name="my-snap") as sandbox:
+ result = sandbox.run("echo hello")
+
+ The sandbox is automatically deleted when exiting the context manager.
+ For sandboxes with manual lifecycle management, use create_sandbox().
+
+ Args:
+ snapshot_id: Snapshot ID to boot from. Mutually exclusive with
+ ``snapshot_name``; exactly one must be provided.
+ snapshot_name: Snapshot name to boot from. Resolved server-side to a
+ snapshot owned by the caller's tenant. Mutually exclusive with
+ ``snapshot_id``; exactly one must be provided.
+ name: Optional sandbox name (auto-generated if not provided).
+ timeout: Timeout in seconds when waiting for ready.
+ idle_ttl_seconds: Idle timeout in seconds. The launcher
+ automatically stops the sandbox after this duration of
+ inactivity. Must be a multiple of 60. ``0`` explicitly
+ disables the idle stop. When omitted (``None``), the server
+ applies a default of ``600`` seconds (10 minutes).
+ delete_after_stop_seconds: Seconds after the sandbox enters the
+ ``stopped`` state before it (and its filesystem clone) are
+ permanently deleted. Must be a multiple of 60. ``0`` disables
+ stop-anchored deletion (manual cleanup required). When
+ omitted (``None``), the server applies its configured default.
+ vcpus: Number of vCPUs.
+ mem_bytes: Memory in bytes.
+ fs_capacity_bytes: Root filesystem capacity in bytes.
+ proxy_config: Per-sandbox proxy configuration forwarded to the
+ server as-is. Shape matches the backend `proxy_config` field:
+ ``{"rules": [...], "no_proxy": [...], "access_control":
+ {"allow_list": [...]}}`` or ``{"access_control":
+ {"deny_list": [...]}}``. Use ``access_control.allow_list`` to
+ restrict outbound HTTPS to a set of host patterns (exact
+ domains, globs like ``*.example.com``, IPs, CIDRs, or
+ ``~regex``).
+
+ Returns:
+ Sandbox instance.
+
+ Raises:
+ ResourceTimeoutError: If timeout waiting for sandbox to be ready.
+ ResourceCreationError: If sandbox creation fails.
+ SandboxClientError: For other errors.
+ ValueError: If TTL values are invalid, or if neither/both of
+ ``snapshot_id`` and ``snapshot_name`` are provided.
+ """
+ sb = self.create_sandbox(
+ snapshot_id,
+ snapshot_name=snapshot_name,
+ name=name,
+ timeout=timeout,
+ idle_ttl_seconds=idle_ttl_seconds,
+ delete_after_stop_seconds=delete_after_stop_seconds,
+ vcpus=vcpus,
+ mem_bytes=mem_bytes,
+ fs_capacity_bytes=fs_capacity_bytes,
+ proxy_config=proxy_config,
+ headers=headers,
+ )
+ sb._auto_delete = True
+ return sb
+
+ def create_sandbox(
+ self,
+ snapshot_id: Optional[str] = None,
+ *,
+ snapshot_name: Optional[str] = None,
+ name: Optional[str] = None,
+ timeout: int = 30,
+ wait_for_ready: bool = True,
+ idle_ttl_seconds: Optional[int] = None,
+ delete_after_stop_seconds: Optional[int] = None,
+ vcpus: Optional[int] = None,
+ mem_bytes: Optional[int] = None,
+ fs_capacity_bytes: Optional[int] = None,
+ proxy_config: Optional[dict[str, Any]] = None,
+ headers: RequestHeaders = None,
+ ) -> Sandbox:
+ """Create a new Sandbox.
+
+ The sandbox is NOT automatically deleted. Use delete_sandbox() for cleanup,
+ or use sandbox() for automatic cleanup with a context manager.
+
+ Args:
+ snapshot_id: Snapshot ID to boot from. Mutually exclusive with
+ ``snapshot_name``; exactly one must be provided.
+ snapshot_name: Snapshot name to boot from. Resolved server-side to a
+ snapshot owned by the caller's tenant. Mutually exclusive with
+ ``snapshot_id``; exactly one must be provided.
+ name: Optional sandbox name (auto-generated if not provided).
+ timeout: Timeout in seconds when waiting for ready (only used when
+ wait_for_ready=True).
+ wait_for_ready: If True (default), block until sandbox is ready.
+ If False, return immediately with status "provisioning". Use
+ get_sandbox_status() or wait_for_sandbox() to poll for readiness.
+ idle_ttl_seconds: Idle timeout in seconds. The launcher
+ automatically stops the sandbox after this duration of
+ inactivity. Must be a multiple of 60. ``0`` explicitly
+ disables the idle stop. When omitted (``None``), the server
+ applies a default of ``600`` seconds (10 minutes).
+ delete_after_stop_seconds: Seconds after the sandbox enters the
+ ``stopped`` state before it (and its filesystem clone) are
+ permanently deleted. Must be a multiple of 60. ``0`` disables
+ stop-anchored deletion (manual cleanup required). When
+ omitted (``None``), the server applies its configured default.
+ vcpus: Number of vCPUs.
+ mem_bytes: Memory in bytes.
+ fs_capacity_bytes: Root filesystem capacity in bytes.
+ proxy_config: Per-sandbox proxy configuration forwarded to the
+ server as-is. Shape matches the backend `proxy_config` field:
+ ``{"rules": [...], "no_proxy": [...], "access_control":
+ {"allow_list": [...]}}`` or ``{"access_control":
+ {"deny_list": [...]}}``. Use ``access_control.allow_list`` to
+ restrict outbound HTTPS to a set of host patterns (exact
+ domains, globs like ``*.example.com``, IPs, CIDRs, or
+ ``~regex``).
+
+ Returns:
+ Created Sandbox. When wait_for_ready=False, the sandbox will have
+ status="provisioning" and cannot be used for operations until ready.
+
+ Raises:
+ ResourceTimeoutError: If timeout waiting for sandbox to be ready.
+ ResourceCreationError: If sandbox creation fails.
+ SandboxClientError: For other errors.
+ ValueError: If TTL values are invalid, or if neither/both of
+ ``snapshot_id`` and ``snapshot_name`` are provided.
+ """
+ if bool(snapshot_id) == bool(snapshot_name):
+ raise ValueError("Exactly one of snapshot_id or snapshot_name must be set")
+
+ validate_ttl(idle_ttl_seconds, "idle_ttl_seconds")
+ validate_ttl(delete_after_stop_seconds, "delete_after_stop_seconds")
+
+ url = f"{self._base_url}/boxes"
+
+ payload: dict[str, Any] = {
+ "wait_for_ready": wait_for_ready,
+ }
+ if snapshot_id:
+ payload["snapshot_id"] = snapshot_id
+ if snapshot_name:
+ payload["snapshot_name"] = snapshot_name
+ if wait_for_ready:
+ payload["timeout"] = timeout
+ if name:
+ payload["name"] = name
+ if idle_ttl_seconds is not None:
+ payload["idle_ttl_seconds"] = idle_ttl_seconds
+ if delete_after_stop_seconds is not None:
+ payload["delete_after_stop_seconds"] = delete_after_stop_seconds
+ if vcpus is not None:
+ payload["vcpus"] = vcpus
+ if mem_bytes is not None:
+ payload["mem_bytes"] = mem_bytes
+ if fs_capacity_bytes is not None:
+ payload["fs_capacity_bytes"] = fs_capacity_bytes
+ if proxy_config is not None:
+ payload["proxy_config"] = proxy_config
+
+ http_timeout = (timeout + 30) if wait_for_ready else 30
+
+ try:
+ response = self._http.post(
+ url,
+ json=payload,
+ timeout=http_timeout,
+ headers=self._request_headers(headers),
+ )
+ response.raise_for_status()
+ return Sandbox.from_dict(response.json(), client=self, auto_delete=False)
+ except httpx.HTTPStatusError as e:
+ handle_sandbox_creation_error(e)
+ raise # pragma: no cover
+
+ def get_sandbox(self, name: str, *, headers: RequestHeaders = None) -> Sandbox:
+ """Get a Sandbox by name.
+
+ The sandbox is NOT automatically deleted. Use delete_sandbox() for cleanup.
+
+ Args:
+ name: Sandbox name.
+
+ Returns:
+ Sandbox.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/boxes/{name}"
+
+ try:
+ response = self._http.get(url, headers=self._request_headers(headers))
+ response.raise_for_status()
+ return Sandbox.from_dict(response.json(), client=self, auto_delete=False)
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ def list_sandboxes(self, *, headers: RequestHeaders = None) -> list[Sandbox]:
+ """List all Sandboxes.
+
+ Returns:
+ List of Sandboxes.
+ """
+ url = f"{self._base_url}/boxes"
+
+ try:
+ response = self._http.get(url, headers=self._request_headers(headers))
+ response.raise_for_status()
+ data = response.json()
+ return [
+ Sandbox.from_dict(c, client=self, auto_delete=False)
+ for c in data.get("sandboxes", [])
+ ]
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise SandboxAPIError(
+ f"API endpoint not found: {url}. "
+ f"Check that api_endpoint is correct."
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ def update_sandbox(
+ self,
+ name: str,
+ *,
+ new_name: Optional[str] = None,
+ idle_ttl_seconds: Optional[int] = None,
+ delete_after_stop_seconds: Optional[int] = None,
+ headers: RequestHeaders = None,
+ ) -> Sandbox:
+ """Update a sandbox's properties.
+
+ Args:
+ name: Current sandbox name.
+ new_name: New display name.
+ idle_ttl_seconds: Idle timeout in seconds. Must be a multiple of
+ 60. ``0`` disables idle-stop. ``None`` leaves the existing
+ value unchanged.
+ delete_after_stop_seconds: Seconds after entering ``stopped``
+ before deletion. Must be a multiple of 60. ``0`` disables
+ stop-anchored deletion. ``None`` leaves the existing value
+ unchanged.
+
+ Returns:
+ Updated Sandbox.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ResourceNameConflictError: If new_name is already in use.
+ SandboxClientError: For other errors.
+ ValueError: If TTL values are invalid.
+ """
+ validate_ttl(idle_ttl_seconds, "idle_ttl_seconds")
+ validate_ttl(delete_after_stop_seconds, "delete_after_stop_seconds")
+
+ url = f"{self._base_url}/boxes/{name}"
+ payload: dict[str, Any] = {}
+ if new_name is not None:
+ payload["name"] = new_name
+ if idle_ttl_seconds is not None:
+ payload["idle_ttl_seconds"] = idle_ttl_seconds
+ if delete_after_stop_seconds is not None:
+ payload["delete_after_stop_seconds"] = delete_after_stop_seconds
+
+ try:
+ response = self._http.patch(
+ url, json=payload, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ return Sandbox.from_dict(response.json(), client=self, auto_delete=False)
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ if e.response.status_code == 409:
+ raise ResourceNameConflictError(
+ f"Sandbox name '{new_name}' already in use",
+ resource_type="sandbox",
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ def delete_sandbox(self, name: str, *, headers: RequestHeaders = None) -> None:
+ """Delete a Sandbox.
+
+ Args:
+ name: Sandbox name.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/boxes/{name}"
+
+ try:
+ response = self._http.delete(url, headers=self._request_headers(headers))
+ response.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+
+ def get_sandbox_status(
+ self, name: str, *, headers: RequestHeaders = None
+ ) -> ResourceStatus:
+ """Get the provisioning status of a sandbox.
+
+ This is a lightweight endpoint designed for high-frequency polling
+ during sandbox provisioning. It returns only the status fields
+ without full sandbox data.
+
+ Args:
+ name: Sandbox name.
+
+ Returns:
+ ResourceStatus with status and status_message.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/boxes/{name}/status"
+
+ try:
+ response = self._http.get(url, headers=self._request_headers(headers))
+ response.raise_for_status()
+ return ResourceStatus.from_dict(response.json())
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ def service(
+ self,
+ name: str,
+ port: int,
+ *,
+ expires_in_seconds: int = 600,
+ headers: RequestHeaders = None,
+ ) -> ServiceURL:
+ """Get an authenticated URL for a service running inside a sandbox.
+
+ Returns a :class:`ServiceURL` whose properties auto-refresh the
+ token transparently before it expires. The object also provides
+ HTTP helper methods (``.get``, ``.post``, etc.) that inject the
+ authentication header automatically.
+
+ Args:
+ name: Sandbox name.
+ port: Port the service is listening on inside the sandbox.
+ expires_in_seconds: Token TTL in seconds (1--86400, default 600).
+ headers: Optional per-request header overrides.
+
+ Returns:
+ ServiceURL with auto-refreshing token and HTTP helpers.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ValueError: If port or expires_in_seconds is out of range.
+ SandboxClientError: For other errors.
+ """
+ validate_service_params(port, expires_in_seconds)
+ url = f"{self._base_url}/boxes/{name}/service-url"
+ payload = {"port": port, "expires_in_seconds": expires_in_seconds}
+
+ def _refresher() -> ServiceURL:
+ return self.service(
+ name,
+ port,
+ expires_in_seconds=expires_in_seconds,
+ headers=headers,
+ )
+
+ try:
+ response = self._http.post(
+ url, json=payload, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ return ServiceURL.from_dict(response.json(), _refresher=_refresher)
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ def wait_for_sandbox(
+ self,
+ name: str,
+ *,
+ timeout: int = 120,
+ poll_interval: float = 1.0,
+ headers: RequestHeaders = None,
+ ) -> Sandbox:
+ """Poll until a sandbox reaches "ready" or "failed" status.
+
+ Uses the lightweight status endpoint for polling, then fetches the
+ full sandbox data once ready.
+
+ Args:
+ name: Sandbox name.
+ timeout: Maximum time to wait in seconds.
+ poll_interval: Time between status checks in seconds.
+
+ Returns:
+ Sandbox in "ready" status.
+
+ Raises:
+ ResourceCreationError: If sandbox status becomes "failed".
+ ResourceTimeoutError: If timeout expires while still "provisioning".
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ import time
+
+ deadline = time.monotonic() + timeout
+ while True:
+ status = self.get_sandbox_status(name, headers=headers)
+ if status.status == "ready":
+ return self.get_sandbox(name, headers=headers)
+ if status.status == "failed":
+ raise ResourceCreationError(
+ status.status_message or "Sandbox provisioning failed",
+ resource_type="sandbox",
+ )
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise ResourceTimeoutError(
+ f"Sandbox '{name}' not ready after {timeout}s",
+ resource_type="sandbox",
+ last_status=status.status,
+ )
+ time.sleep(min(poll_interval, remaining))
+
+ def start_sandbox(
+ self,
+ name: str,
+ *,
+ timeout: int = 120,
+ headers: RequestHeaders = None,
+ ) -> Sandbox:
+ """Start a stopped sandbox and wait until ready.
+
+ Args:
+ name: Sandbox name.
+ timeout: Timeout in seconds when waiting for ready.
+
+ Returns:
+ Sandbox in "ready" status.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ResourceCreationError: If sandbox fails during startup.
+ ResourceTimeoutError: If sandbox doesn't become ready within timeout.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/boxes/{name}/start"
+
+ try:
+ response = self._http.post(
+ url, json={}, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+
+ return self.wait_for_sandbox(name, timeout=timeout, headers=headers)
+
+ def stop_sandbox(self, name: str, *, headers: RequestHeaders = None) -> None:
+ """Stop a running sandbox (preserves sandbox files for later restart).
+
+ Args:
+ name: Sandbox name.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/boxes/{name}/stop"
+
+ try:
+ response = self._http.post(
+ url, json={}, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+
+ # ========================================================================
+ # Snapshot Operations
+ # ========================================================================
+
+ def create_snapshot(
+ self,
+ name: str,
+ docker_image: str,
+ fs_capacity_bytes: int,
+ *,
+ registry_id: Optional[str] = None,
+ registry_url: Optional[str] = None,
+ registry_username: Optional[str] = None,
+ registry_password: Optional[str] = None,
+ timeout: int = 60,
+ headers: RequestHeaders = None,
+ ) -> Snapshot:
+ """Build a snapshot from a Docker image.
+
+ Blocks until the snapshot is ready (polls with 2s interval).
+
+ Args:
+ name: Snapshot name.
+ docker_image: Docker image to build from (e.g., "python:3.12-slim").
+ fs_capacity_bytes: Filesystem capacity in bytes.
+ registry_id: Private registry ID (alternative to URL/credentials).
+ registry_url: Registry URL for private images.
+ registry_username: Registry username.
+ registry_password: Registry password.
+ timeout: Timeout in seconds when waiting for ready.
+
+ Returns:
+ Snapshot in "ready" status.
+
+ Raises:
+ ResourceTimeoutError: If snapshot doesn't become ready within timeout.
+ ResourceCreationError: If snapshot build fails.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/snapshots"
+
+ payload: dict[str, Any] = {
+ "name": name,
+ "docker_image": docker_image,
+ "fs_capacity_bytes": fs_capacity_bytes,
+ }
+ if registry_id is not None:
+ payload["registry_id"] = registry_id
+ if registry_url is not None:
+ payload["registry_url"] = registry_url
+ if registry_username is not None:
+ payload["registry_username"] = registry_username
+ if registry_password is not None:
+ payload["registry_password"] = registry_password
+
+ try:
+ response = self._http.post(
+ url, json=payload, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ snapshot = Snapshot.from_dict(response.json())
+ except httpx.HTTPStatusError as e:
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ return self.wait_for_snapshot(snapshot.id, timeout=timeout, headers=headers)
+
+ def capture_snapshot(
+ self,
+ sandbox_name: str,
+ name: str,
+ *,
+ timeout: int = 60,
+ headers: RequestHeaders = None,
+ ) -> Snapshot:
+ """Capture a snapshot from a running sandbox.
+
+ Blocks until the snapshot is ready (polls with 2s interval).
+
+ Args:
+ sandbox_name: Name of the sandbox to capture from.
+ name: Snapshot name.
+ timeout: Timeout in seconds when waiting for ready.
+
+ Returns:
+ Snapshot in "ready" status.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ResourceTimeoutError: If snapshot doesn't become ready within timeout.
+ ResourceCreationError: If snapshot capture fails.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/boxes/{sandbox_name}/snapshot"
+
+ payload: dict[str, Any] = {"name": name}
+
+ try:
+ response = self._http.post(
+ url, json=payload, headers=self._request_headers(headers)
+ )
+ response.raise_for_status()
+ snapshot = Snapshot.from_dict(response.json())
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Sandbox '{sandbox_name}' not found", resource_type="sandbox"
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ return self.wait_for_snapshot(snapshot.id, timeout=timeout, headers=headers)
+
+ def get_snapshot(
+ self, snapshot_id: str, *, headers: RequestHeaders = None
+ ) -> Snapshot:
+ """Get a snapshot by ID.
+
+ Args:
+ snapshot_id: Snapshot UUID.
+
+ Returns:
+ Snapshot.
+
+ Raises:
+ ResourceNotFoundError: If snapshot not found.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/snapshots/{snapshot_id}"
+
+ try:
+ response = self._http.get(url, headers=self._request_headers(headers))
+ response.raise_for_status()
+ return Snapshot.from_dict(response.json())
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Snapshot '{snapshot_id}' not found", resource_type="snapshot"
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ def list_snapshots(
+ self,
+ *,
+ name_contains: Optional[str] = None,
+ limit: Optional[int] = None,
+ offset: Optional[int] = None,
+ headers: RequestHeaders = None,
+ ) -> list[Snapshot]:
+ """List snapshots.
+
+ The backend always paginates this endpoint. When ``limit`` is omitted
+ the server applies a default page size (currently 50), so a single
+ call is not guaranteed to return every snapshot. To iterate through
+ all results, repeat the call with increasing ``offset`` values (or an
+ explicit ``limit``) until fewer than ``limit`` snapshots come back.
+
+ Args:
+ name_contains: Optional case-insensitive substring filter applied
+ to snapshot names server-side.
+ limit: Optional maximum number of snapshots to return for a single
+ request. Must be between 1 and 500 (inclusive); the server
+ rejects values outside that range. Defaults to 50 server-side
+ when omitted.
+ offset: Optional number of snapshots to skip before returning
+ results. Must be ``>= 0``. Useful for paginating through
+ large result sets in combination with ``limit``.
+
+ Returns:
+ A single page of Snapshots matching the provided filters.
+ """
+ url = f"{self._base_url}/snapshots"
+
+ params: dict[str, Any] = {}
+ if name_contains is not None:
+ params["name_contains"] = name_contains
+ if limit is not None:
+ params["limit"] = limit
+ if offset is not None:
+ params["offset"] = offset
+
+ try:
+ response = self._http.get(
+ url,
+ params=params or None,
+ headers=self._request_headers(headers),
+ )
+ response.raise_for_status()
+ data = response.json()
+ return [Snapshot.from_dict(s) for s in data.get("snapshots", [])]
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise SandboxAPIError(
+ f"API endpoint not found: {url}. "
+ f"Check that api_endpoint is correct."
+ ) from e
+ handle_client_http_error(e)
+ raise # pragma: no cover
+
+ def delete_snapshot(
+ self, snapshot_id: str, *, headers: RequestHeaders = None
+ ) -> None:
+ """Delete a snapshot.
+
+ Args:
+ snapshot_id: Snapshot UUID.
+
+ Raises:
+ ResourceNotFoundError: If snapshot not found.
+ SandboxClientError: For other errors.
+ """
+ url = f"{self._base_url}/snapshots/{snapshot_id}"
+
+ try:
+ response = self._http.delete(url, headers=self._request_headers(headers))
+ response.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"Snapshot '{snapshot_id}' not found", resource_type="snapshot"
+ ) from e
+ handle_client_http_error(e)
+
+ def wait_for_snapshot(
+ self,
+ snapshot_id: str,
+ *,
+ timeout: int = 300,
+ poll_interval: float = 2.0,
+ headers: RequestHeaders = None,
+ ) -> Snapshot:
+ """Poll until a snapshot reaches "ready" or "failed" status.
+
+ Args:
+ snapshot_id: Snapshot UUID.
+ timeout: Maximum time to wait in seconds.
+ poll_interval: Time between status checks in seconds.
+
+ Returns:
+ Snapshot in "ready" status.
+
+ Raises:
+ ResourceCreationError: If snapshot status becomes "failed".
+ ResourceTimeoutError: If timeout expires.
+ ResourceNotFoundError: If snapshot not found.
+ SandboxClientError: For other errors.
+ """
+ import time
+
+ deadline = time.monotonic() + timeout
+ while True:
+ snapshot = self.get_snapshot(snapshot_id, headers=headers)
+ if snapshot.status == "ready":
+ return snapshot
+ if snapshot.status == "failed":
+ raise ResourceCreationError(
+ snapshot.status_message or "Snapshot build failed",
+ resource_type="snapshot",
+ )
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise ResourceTimeoutError(
+ f"Snapshot '{snapshot_id}' not ready after {timeout}s",
+ resource_type="snapshot",
+ last_status=snapshot.status,
+ )
+ time.sleep(min(poll_interval, remaining))
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_exceptions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..3848e1540240fcc3340e0d6446c3bb8184755636
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_exceptions.py
@@ -0,0 +1,328 @@
+"""Custom exceptions for the sandbox client.
+
+All sandbox exceptions extend LangSmithError for unified error handling.
+The exceptions are organized by error type rather than resource type,
+with a resource_type attribute for specific handling when needed.
+"""
+
+from __future__ import annotations
+
+from typing import Optional
+
+from langsmith.utils import LangSmithError
+
+
+class SandboxClientError(LangSmithError):
+ """Base exception for sandbox client errors."""
+
+ pass
+
+
+# =============================================================================
+# Connection and Authentication Errors
+# =============================================================================
+
+
+class SandboxAPIError(SandboxClientError):
+ """Raised when the API endpoint returns an unexpected error.
+
+ For example, this is raised for wrong URL or path.
+ """
+
+ pass
+
+
+class SandboxAuthenticationError(SandboxClientError):
+ """Raised when authentication fails (invalid or missing API key)."""
+
+ pass
+
+
+class SandboxConnectionError(SandboxClientError):
+ """Raised when connection to the sandbox server fails."""
+
+ pass
+
+
+class SandboxServerReloadError(SandboxConnectionError):
+ """Raised when the server sends a 1001 Going Away close frame.
+
+ This indicates a server hot-reload, not a true connection failure.
+ The command is still running on the server.
+
+ This is a subclass of SandboxConnectionError, so the auto-reconnect
+ logic in CommandHandle catches it along with all other
+ connection errors. The distinction matters for retry strategy:
+ SandboxServerReloadError triggers immediate reconnect (no backoff),
+ while other SandboxConnectionError triggers exponential backoff.
+
+ Users typically never see this exception — it's handled internally.
+ """
+
+ pass
+
+
+# =============================================================================
+# Resource Errors (type-based, with resource_type attribute)
+# =============================================================================
+
+
+class ResourceNotFoundError(SandboxClientError):
+ """Raised when a resource is not found.
+
+ Attributes:
+ resource_type: Type of resource (sandbox, snapshot, file).
+ """
+
+ def __init__(self, message: str, resource_type: Optional[str] = None):
+ """Initialize the error."""
+ super().__init__(message)
+ self.resource_type = resource_type
+
+
+class ResourceTimeoutError(SandboxClientError):
+ """Raised when an operation times out.
+
+ Attributes:
+ resource_type: Type of resource (sandbox, snapshot).
+ last_status: The last known status before timeout (for sandboxes).
+ """
+
+ def __init__(
+ self,
+ message: str,
+ resource_type: Optional[str] = None,
+ last_status: Optional[str] = None,
+ ):
+ """Initialize the error."""
+ super().__init__(message)
+ self.resource_type = resource_type
+ self.last_status = last_status
+
+ def __str__(self) -> str:
+ """Return string representation."""
+ base = super().__str__()
+ if self.last_status:
+ return f"{base} (last_status: {self.last_status})"
+ return base
+
+
+class ResourceInUseError(SandboxClientError):
+ """Raised when deleting a resource that is still in use.
+
+ Attributes:
+ resource_type: Type of resource (snapshot).
+ """
+
+ def __init__(self, message: str, resource_type: Optional[str] = None):
+ """Initialize the error."""
+ super().__init__(message)
+ self.resource_type = resource_type
+
+
+class ResourceAlreadyExistsError(SandboxClientError):
+ """Raised when creating a resource that already exists.
+
+ Attributes:
+ resource_type: Type of resource (e.g., snapshot).
+ """
+
+ def __init__(self, message: str, resource_type: Optional[str] = None):
+ """Initialize the error."""
+ super().__init__(message)
+ self.resource_type = resource_type
+
+
+class ResourceNameConflictError(SandboxClientError):
+ """Raised when updating a resource name to one that already exists.
+
+ Attributes:
+ resource_type: Type of resource (sandbox, snapshot).
+ """
+
+ def __init__(self, message: str, resource_type: Optional[str] = None):
+ """Initialize the error."""
+ super().__init__(message)
+ self.resource_type = resource_type
+
+
+# =============================================================================
+# Validation and Quota Errors
+# =============================================================================
+
+
+class ValidationError(SandboxClientError):
+ """Raised when request validation fails.
+
+ This includes:
+ - Resource values exceeding server-defined limits (CPU, memory, storage)
+ - Invalid resource units
+ - Invalid name formats
+
+ Attributes:
+ field: The field that failed validation (e.g., "cpu", "memory").
+ details: List of validation error details from the API.
+ error_type: Machine-readable error type from the API.
+ """
+
+ def __init__(
+ self,
+ message: str,
+ field: Optional[str] = None,
+ details: Optional[list[dict]] = None,
+ error_type: Optional[str] = None,
+ ):
+ """Initialize the error."""
+ super().__init__(message)
+ self.field = field
+ self.details = details or []
+ self.error_type = error_type
+
+
+class QuotaExceededError(SandboxClientError):
+ """Raised when organization quota limits are exceeded.
+
+ Users should contact support@langchain.dev to increase quotas.
+
+ Attributes:
+ quota_type: Type of quota exceeded (e.g., "sandbox_count", "cpu").
+ """
+
+ def __init__(self, message: str, quota_type: Optional[str] = None):
+ """Initialize the error."""
+ super().__init__(message)
+ self.quota_type = quota_type
+
+
+# =============================================================================
+# Resource Creation Errors
+# =============================================================================
+
+
+class ResourceCreationError(SandboxClientError):
+ """Raised when resource provisioning fails.
+
+ Attributes:
+ resource_type: Type of resource (sandbox, snapshot).
+ error_type: Machine-readable error type (ImagePull, CrashLoop,
+ SandboxConfig, Unschedulable).
+ """
+
+ def __init__(
+ self,
+ message: str,
+ resource_type: Optional[str] = None,
+ error_type: Optional[str] = None,
+ ):
+ """Initialize the error."""
+ super().__init__(message)
+ self.resource_type = resource_type
+ self.error_type = error_type
+
+ def __str__(self) -> str:
+ """Return string representation."""
+ if self.error_type:
+ return f"{super().__str__()} [{self.error_type}]"
+ return super().__str__()
+
+
+# =============================================================================
+# Sandbox Operation Errors (runtime errors during sandbox interaction)
+# =============================================================================
+
+
+class DataplaneNotConfiguredError(SandboxClientError):
+ """Raised when dataplane_url is not available for the sandbox.
+
+ This occurs when the sandbox-router URL is not configured for the cluster.
+ """
+
+ pass
+
+
+class SandboxNotReadyError(SandboxClientError):
+ """Raised when attempting to interact with a sandbox that is not ready."""
+
+ pass
+
+
+class SandboxOperationError(SandboxClientError):
+ """Raised when a sandbox operation fails (run, read, write).
+
+ Attributes:
+ operation: The operation that failed (command, read, write).
+ error_type: Machine-readable error type from the API.
+ """
+
+ def __init__(
+ self,
+ message: str,
+ operation: Optional[str] = None,
+ error_type: Optional[str] = None,
+ ):
+ """Initialize the error."""
+ super().__init__(message)
+ self.operation = operation
+ self.error_type = error_type
+
+ def __str__(self) -> str:
+ """Return string representation."""
+ if self.error_type:
+ return f"{super().__str__()} [{self.error_type}]"
+ return super().__str__()
+
+
+class CommandTimeoutError(SandboxOperationError):
+ """Raised when a command exceeds its timeout.
+
+ Attributes:
+ timeout: The timeout value in seconds that was exceeded.
+ """
+
+ def __init__(self, message: str, timeout: Optional[int] = None):
+ """Initialize the error."""
+ super().__init__(message, operation="command", error_type="CommandTimeout")
+ self.timeout = timeout
+
+
+# ========================================================================
+# Tunnel Errors
+# ========================================================================
+
+
+class TunnelError(SandboxClientError):
+ """Base exception for TCP tunnel errors."""
+
+ pass
+
+
+class TunnelPortNotAllowedError(TunnelError):
+ """The daemon rejected the port as not allowed.
+
+ Attributes:
+ port: The port that was rejected.
+ """
+
+ def __init__(self, message: str, *, port: int):
+ """Initialize the error."""
+ super().__init__(message)
+ self.port = port
+
+
+class TunnelConnectionRefusedError(TunnelError):
+ """Nothing is listening on the target port inside the sandbox.
+
+ Attributes:
+ port: The port that could not be reached.
+ """
+
+ def __init__(self, message: str, *, port: int):
+ """Initialize the error."""
+ super().__init__(message)
+ self.port = port
+
+
+class TunnelUnsupportedVersionError(TunnelError):
+ """Protocol version mismatch between the tunnel client and the daemon."""
+
+ pass
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_helpers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7b2af173cf1c7ab1b2ed1ee620584187031bea1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_helpers.py
@@ -0,0 +1,350 @@
+"""Shared helper functions for error handling.
+
+These functions are used by both sync and async clients to parse error responses
+and raise appropriate exceptions. They contain no I/O operations.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, Optional
+
+import httpx
+
+from langsmith.sandbox._exceptions import (
+ QuotaExceededError,
+ ResourceCreationError,
+ ResourceNotFoundError,
+ ResourceTimeoutError,
+ SandboxAPIError,
+ SandboxAuthenticationError,
+ SandboxClientError,
+ SandboxConnectionError,
+ SandboxNotReadyError,
+ SandboxOperationError,
+ ValidationError,
+)
+
+# =============================================================================
+# Header Utilities
+# =============================================================================
+
+
+def merge_headers(
+ base_headers: Optional[Mapping[str, str]] = None,
+ override_headers: Optional[Mapping[str, str]] = None,
+) -> dict[str, str]:
+ """Merge request headers, giving precedence to overrides."""
+ merged: dict[str, str] = dict(base_headers or {})
+ if override_headers:
+ merged.update(override_headers)
+ return merged
+
+
+# =============================================================================
+# Input Validation
+# =============================================================================
+
+
+def validate_service_params(port: int, expires_in_seconds: int) -> None:
+ """Validate parameters for service URL generation.
+
+ Args:
+ port: Target port inside the sandbox.
+ expires_in_seconds: Token TTL.
+
+ Raises:
+ ValueError: If port or TTL is out of range.
+ """
+ if not isinstance(port, int) or port <= 0:
+ raise ValueError(f"port must be a positive integer, got {port!r}")
+ if not isinstance(expires_in_seconds, int) or not (
+ 1 <= expires_in_seconds <= 86400
+ ):
+ raise ValueError(
+ f"expires_in_seconds must be between 1 and 86400, "
+ f"got {expires_in_seconds!r}"
+ )
+
+
+def validate_ttl(value: Optional[int], name: str) -> None:
+ """Validate a TTL value for sandbox create/update.
+
+ Args:
+ value: TTL in seconds (None means unset, 0 disables).
+ name: Parameter name for error messages.
+
+ Raises:
+ ValueError: If value is negative or not a multiple of 60.
+ """
+ if value is None:
+ return
+ if value < 0:
+ raise ValueError(f"{name} must be >= 0, got {value}")
+ if value != 0 and value % 60 != 0:
+ raise ValueError(f"{name} must be a multiple of 60 seconds, got {value}")
+
+
+# =============================================================================
+# Error Response Parsing
+# =============================================================================
+
+
+def parse_error_response(error: httpx.HTTPStatusError) -> dict[str, Any]:
+ """Parse standardized error response.
+
+ Expected format: {"detail": {"error": "...", "message": "..."}}
+
+ Returns a dict with:
+ - error_type: The error type (e.g., "ImagePull", "CrashLoop")
+ - message: Human-readable error message
+ """
+ try:
+ data = error.response.json()
+ detail = data.get("detail")
+
+ # Standardized format: {"detail": {"error": "...", "message": "..."}}
+ if isinstance(detail, dict):
+ return {
+ "error_type": detail.get("error"),
+ "message": detail.get("message", str(error)),
+ }
+
+ # Pydantic validation error format: {"detail": [{"loc": [...], "msg": "..."}]}
+ if isinstance(detail, list) and detail:
+ messages = [d.get("msg", str(d)) for d in detail if isinstance(d, dict)]
+ return {
+ "error_type": None,
+ "message": "; ".join(messages) if messages else str(error),
+ }
+
+ # Fallback for plain string detail
+ return {"error_type": None, "message": detail or str(error)}
+ except Exception:
+ return {"error_type": None, "message": str(error)}
+
+
+def parse_error_response_simple(error: httpx.HTTPStatusError) -> dict[str, Any]:
+ """Parse error response (simplified version for sandbox operations).
+
+ Returns a dict with:
+ - error_type: The error type
+ - message: Human-readable error message
+ """
+ try:
+ data = error.response.json()
+ detail = data.get("detail")
+
+ if isinstance(detail, dict):
+ return {
+ "error_type": detail.get("error"),
+ "message": detail.get("message", str(error)),
+ }
+
+ return {"error_type": None, "message": detail or str(error)}
+ except Exception:
+ return {"error_type": None, "message": str(error)}
+
+
+def parse_validation_error(error: httpx.HTTPStatusError) -> list[dict]:
+ """Parse Pydantic validation error response.
+
+ Returns a list of validation error details, each containing:
+ - loc: Location of the error (e.g., ["body", "resources", "cpu"])
+ - msg: Human-readable error message
+ - type: Error type (e.g., "value_error")
+ """
+ try:
+ data = error.response.json()
+ detail = data.get("detail", [])
+ if isinstance(detail, list):
+ return detail
+ return []
+ except Exception:
+ return []
+
+
+def extract_quota_type(message: str) -> Optional[str]:
+ """Extract quota type from error message.
+
+ Returns one of: "sandbox_count", "cpu", "memory", "storage", or None.
+ """
+ message_lower = message.lower()
+ # Check for sandbox count quota
+ if "sandbox" in message_lower and (
+ "count" in message_lower or "limit" in message_lower
+ ):
+ return "sandbox_count"
+ elif "cpu" in message_lower:
+ return "cpu"
+ elif "memory" in message_lower:
+ return "memory"
+ elif "storage" in message_lower:
+ return "storage"
+ return None
+
+
+# =============================================================================
+# Client Error Handlers
+# =============================================================================
+
+
+def raise_creation_error(
+ data: dict[str, Any],
+ error: httpx.HTTPStatusError,
+ resource_type: str = "sandbox",
+) -> None:
+ """Raise ResourceCreationError with the error_type from the API response.
+
+ The error_type indicates the specific failure reason:
+ - ImagePull: Image pull failed
+ - CrashLoop: Container crashed during startup
+ - SandboxConfig: Configuration error
+ - Unschedulable: Cannot be scheduled
+ """
+ raise ResourceCreationError(
+ data.get("message", f"{resource_type.title()} creation failed"),
+ resource_type=resource_type,
+ error_type=data.get("error_type"),
+ ) from error
+
+
+def handle_sandbox_creation_error(error: httpx.HTTPStatusError) -> None:
+ """Handle HTTP errors specific to sandbox creation.
+
+ Maps API error responses to specific exception types:
+ - 408: ResourceTimeoutError (sandbox didn't become ready in time)
+ - 422: ValidationError (bad input) or ResourceCreationError (runtime)
+ - 429: QuotaExceededError (org limits exceeded)
+ - 503: ResourceCreationError (no resources available)
+ - Other: Falls through to generic error handling
+ """
+ status = error.response.status_code
+ data = parse_error_response(error)
+
+ if status == 408:
+ # Timeout - include the message which contains last known status
+ raise ResourceTimeoutError(data["message"], resource_type="sandbox") from error
+ elif status == 422:
+ # Check if this is a Pydantic validation error (bad input) vs creation error
+ details = parse_validation_error(error)
+ if details and any(d.get("type") == "value_error" for d in details):
+ # Pydantic validation error (bad input - exceeds server limits)
+ field = details[0].get("loc", [None])[-1] if details else None
+ raise ValidationError(
+ message=data["message"],
+ field=field,
+ details=details,
+ ) from error
+ else:
+ # Sandbox creation failed (runtime error like image pull failure)
+ raise_creation_error(data, error)
+ elif status == 429:
+ # Organization quota exceeded
+ quota_type = extract_quota_type(data["message"])
+ raise QuotaExceededError(
+ message=data["message"],
+ quota_type=quota_type,
+ ) from error
+ elif status == 503:
+ # Service Unavailable - scheduling failed
+ raise ResourceCreationError(
+ data["message"],
+ resource_type="sandbox",
+ error_type=data.get("error_type") or "Unschedulable",
+ ) from error
+ else:
+ # Fall through to generic handling
+ handle_client_http_error(error)
+
+
+def handle_client_http_error(error: httpx.HTTPStatusError) -> None:
+ """Handle HTTP errors and raise appropriate exceptions (for client operations)."""
+ data = parse_error_response(error)
+ message = data["message"]
+ error_type = data.get("error_type")
+ status = error.response.status_code
+
+ if status in (401, 403):
+ raise SandboxAuthenticationError(message) from error
+ if status == 404:
+ raise ResourceNotFoundError(message) from error
+
+ # Handle validation errors (invalid resource values, formats, etc.)
+ if status == 422:
+ details = parse_validation_error(error)
+ field = details[0].get("loc", [None])[-1] if details else None
+ raise ValidationError(
+ message=message,
+ field=field,
+ details=details,
+ ) from error
+
+ # Handle quota exceeded errors (org limits)
+ if status == 429:
+ quota_type = extract_quota_type(message)
+ raise QuotaExceededError(
+ message=message,
+ quota_type=quota_type,
+ ) from error
+
+ if status == 502 and error_type == "ConnectionError":
+ raise SandboxConnectionError(message) from error
+ if status == 500:
+ raise SandboxAPIError(message) from error
+ raise SandboxClientError(message) from error
+
+
+# =============================================================================
+# Sandbox Operation Error Handlers
+# =============================================================================
+
+
+def handle_sandbox_http_error(error: httpx.HTTPStatusError) -> None:
+ """Handle HTTP errors for sandbox operations (run, read, write).
+
+ Maps API error types to specific exceptions:
+ - WriteError -> SandboxOperationError (operation="write")
+ - ReadError -> SandboxOperationError (operation="read")
+ - CommandError -> SandboxOperationError (operation="command")
+ - ConnectionError (502) -> SandboxConnectionError
+ - FileNotFound / 404 -> ResourceNotFoundError (resource_type="file")
+ - NotReady (400) -> SandboxNotReadyError
+ - 403 -> SandboxOperationError (permission denied)
+ """
+ data = parse_error_response_simple(error)
+ message = data["message"]
+ error_type = data.get("error_type")
+ status = error.response.status_code
+
+ # Operation-specific errors (from sandbox runtime)
+ if error_type == "WriteError":
+ raise SandboxOperationError(
+ message, operation="write", error_type=error_type
+ ) from error
+ if error_type == "ReadError":
+ raise SandboxOperationError(
+ message, operation="read", error_type=error_type
+ ) from error
+ if error_type == "CommandError":
+ raise SandboxOperationError(
+ message, operation="command", error_type=error_type
+ ) from error
+
+ # Permission denied
+ if status == 403:
+ raise SandboxOperationError(
+ message, operation=None, error_type="PermissionDenied"
+ ) from error
+
+ # Connection to sandbox failed
+ if status == 502 and error_type == "ConnectionError":
+ raise SandboxConnectionError(message) from error
+
+ # Not ready / not found
+ if status == 400 and error_type == "NotReady":
+ raise SandboxNotReadyError(message) from error
+ if status == 404 or error_type == "FileNotFound":
+ raise ResourceNotFoundError(message, resource_type="file") from error
+
+ raise SandboxClientError(message) from error
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_models.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..be06fa3c2f072f962a5e7dee4c0cc3ceccad591e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_models.py
@@ -0,0 +1,918 @@
+"""Data models for the sandbox client."""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import TYPE_CHECKING, Any, Optional
+
+import httpx
+
+from langsmith.sandbox._exceptions import (
+ SandboxConnectionError,
+ SandboxOperationError,
+ SandboxServerReloadError,
+)
+
+if TYPE_CHECKING:
+ from langsmith.sandbox._async_sandbox import AsyncSandbox
+ from langsmith.sandbox._sandbox import Sandbox
+ from langsmith.sandbox._ws_execute import (
+ _AsyncWSStreamControl,
+ _WSStreamControl,
+ )
+
+
+@dataclass
+class ExecutionResult:
+ """Result of executing a command in a sandbox."""
+
+ stdout: str
+ stderr: str
+ exit_code: int
+
+ @property
+ def success(self) -> bool:
+ """Return True if the command exited with code 0."""
+ return self.exit_code == 0
+
+
+@dataclass
+class ResourceStatus:
+ """Lightweight provisioning status for any async-created resource.
+
+ Attributes:
+ status: Resource lifecycle status. One of "provisioning", "ready", "failed".
+ status_message: Human-readable details when status is "failed", None otherwise.
+ """
+
+ status: str
+ status_message: Optional[str] = None
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> ResourceStatus:
+ """Create a ResourceStatus from API response dict."""
+ return cls(
+ status=data.get("status", "provisioning"),
+ status_message=data.get("status_message"),
+ )
+
+
+@dataclass
+class Snapshot:
+ """Represents a sandbox snapshot.
+
+ Snapshots are built from Docker images or captured from running sandboxes.
+ They are used to create new sandboxes.
+
+ Attributes:
+ id: Unique identifier (UUID).
+ name: Display name.
+ status: Build status. One of "building", "ready", "failed".
+ fs_capacity_bytes: Filesystem capacity in bytes.
+ docker_image: Source Docker image (for build snapshots).
+ image_digest: Docker image digest after pull.
+ source_sandbox_id: Source sandbox (for capture snapshots).
+ status_message: Human-readable details when status is "failed".
+ fs_used_bytes: Actual bytes used on the filesystem.
+ created_by: User or service that created the snapshot.
+ registry_id: Private registry ID, if applicable.
+ created_at: Timestamp when the snapshot was created.
+ updated_at: Timestamp when the snapshot was last updated.
+ """
+
+ id: str
+ name: str
+ status: str
+ fs_capacity_bytes: int
+ docker_image: Optional[str] = None
+ image_digest: Optional[str] = None
+ source_sandbox_id: Optional[str] = None
+ status_message: Optional[str] = None
+ fs_used_bytes: Optional[int] = None
+ created_by: Optional[str] = None
+ registry_id: Optional[str] = None
+ created_at: Optional[str] = None
+ updated_at: Optional[str] = None
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> Snapshot:
+ """Create a Snapshot from API response dict."""
+ return cls(
+ id=data.get("id", ""),
+ name=data.get("name", ""),
+ status=data.get("status", "building"),
+ fs_capacity_bytes=data.get("fs_capacity_bytes", 0),
+ docker_image=data.get("docker_image"),
+ image_digest=data.get("image_digest"),
+ source_sandbox_id=data.get("source_sandbox_id"),
+ status_message=data.get("status_message"),
+ fs_used_bytes=data.get("fs_used_bytes"),
+ created_by=data.get("created_by"),
+ registry_id=data.get("registry_id"),
+ created_at=data.get("created_at"),
+ updated_at=data.get("updated_at"),
+ )
+
+
+# =============================================================================
+# Service URL Models
+# =============================================================================
+
+_AUTH_HEADER = "X-Langsmith-Sandbox-Service-Token"
+_REFRESH_MARGIN_SECONDS = 30
+
+
+class ServiceURL:
+ """Authenticated URL for accessing an HTTP service running in a sandbox.
+
+ Properties auto-refresh the token transparently when it nears expiry.
+ HTTP helper methods (``.get``, ``.post``, etc.) inject the auth header
+ automatically.
+
+ When constructed by :meth:`SandboxClient.service` or
+ :meth:`Sandbox.service`, the object holds an internal refresher that
+ re-calls the API to obtain a fresh token before the current one expires.
+
+ Example::
+
+ svc = sb.service(port=3000)
+
+ resp = svc.get("/api/data") # token injected + auto-refreshed
+ print(svc.browser_url) # always-fresh URL
+ """
+
+ def __init__(
+ self,
+ browser_url: str,
+ service_url: str,
+ token: str,
+ expires_at: str,
+ *,
+ _refresher: Optional[Callable[[], ServiceURL]] = None,
+ ) -> None:
+ self._browser_url = browser_url
+ self._service_url = service_url
+ self._token = token
+ self._expires_at = expires_at
+ self._refresher = _refresher
+
+ # -- Auto-refresh logic -------------------------------------------------
+
+ def _should_refresh(self) -> bool:
+ if self._refresher is None:
+ return False
+ raw = self._expires_at.replace("Z", "+00:00")
+ expires = datetime.fromisoformat(raw)
+ if expires.tzinfo is None:
+ expires = expires.replace(tzinfo=timezone.utc)
+ remaining = (expires - datetime.now(timezone.utc)).total_seconds()
+ return remaining <= _REFRESH_MARGIN_SECONDS
+
+ def _maybe_refresh(self) -> None:
+ if self._should_refresh():
+ fresh = self._refresher() # type: ignore[misc]
+ self._browser_url = fresh._browser_url
+ self._service_url = fresh._service_url
+ self._token = fresh._token
+ self._expires_at = fresh._expires_at
+
+ # -- Properties (auto-refresh on access) --------------------------------
+
+ @property
+ def token(self) -> str:
+ """Return the raw JWT, refreshing if near expiry."""
+ self._maybe_refresh()
+ return self._token
+
+ @property
+ def service_url(self) -> str:
+ """Return the base URL, refreshing if near expiry."""
+ self._maybe_refresh()
+ return self._service_url
+
+ @property
+ def browser_url(self) -> str:
+ """Return the browser auth URL, refreshing if near expiry."""
+ self._maybe_refresh()
+ return self._browser_url
+
+ @property
+ def expires_at(self) -> str:
+ """Return the ISO 8601 expiration, refreshing if near expiry."""
+ self._maybe_refresh()
+ return self._expires_at
+
+ # -- HTTP helpers (stateless, one httpx call per request) ----------------
+
+ def request(self, method: str, path: str = "/", **kwargs: Any) -> httpx.Response:
+ """Make an HTTP request to the service, injecting the auth header.
+
+ Args:
+ method: HTTP method (GET, POST, etc.).
+ path: Path relative to the service URL.
+ **kwargs: Forwarded to ``httpx.request``.
+
+ Returns:
+ httpx.Response.
+ """
+ url = self.service_url.rstrip("/") + "/" + path.lstrip("/")
+ headers = dict(kwargs.pop("headers", None) or {})
+ headers[_AUTH_HEADER] = self.token
+ return httpx.request(method, url, headers=headers, **kwargs)
+
+ def get(self, path: str = "/", **kwargs: Any) -> httpx.Response:
+ """HTTP GET to the service."""
+ return self.request("GET", path, **kwargs)
+
+ def post(self, path: str = "/", **kwargs: Any) -> httpx.Response:
+ """HTTP POST to the service."""
+ return self.request("POST", path, **kwargs)
+
+ def put(self, path: str = "/", **kwargs: Any) -> httpx.Response:
+ """HTTP PUT to the service."""
+ return self.request("PUT", path, **kwargs)
+
+ def patch(self, path: str = "/", **kwargs: Any) -> httpx.Response:
+ """HTTP PATCH to the service."""
+ return self.request("PATCH", path, **kwargs)
+
+ def delete(self, path: str = "/", **kwargs: Any) -> httpx.Response:
+ """HTTP DELETE to the service."""
+ return self.request("DELETE", path, **kwargs)
+
+ # -- Construction -------------------------------------------------------
+
+ @classmethod
+ def from_dict(
+ cls,
+ data: dict[str, Any],
+ *,
+ _refresher: Optional[Callable[[], ServiceURL]] = None,
+ ) -> ServiceURL:
+ """Create a ServiceURL from API response dict."""
+ return cls(
+ browser_url=data["browser_url"],
+ service_url=data["service_url"],
+ token=data["token"],
+ expires_at=data["expires_at"],
+ _refresher=_refresher,
+ )
+
+ def __repr__(self) -> str:
+ return (
+ f"ServiceURL(service_url={self._service_url!r}, "
+ f"expires_at={self._expires_at!r})"
+ )
+
+
+class AsyncServiceURL:
+ """Async variant of :class:`ServiceURL` with auto-refreshing token.
+
+ Properties and HTTP helpers are async. Use with
+ :meth:`AsyncSandboxClient.service` or :meth:`AsyncSandbox.service`.
+
+ Example::
+
+ svc = await sb.service(port=3000)
+
+ resp = await svc.get("/api/data")
+ print(await svc.get_browser_url())
+ """
+
+ def __init__(
+ self,
+ browser_url: str,
+ service_url: str,
+ token: str,
+ expires_at: str,
+ *,
+ _refresher: Optional[Callable[[], Awaitable[AsyncServiceURL]]] = None,
+ ) -> None:
+ self._browser_url = browser_url
+ self._service_url = service_url
+ self._token = token
+ self._expires_at = expires_at
+ self._refresher = _refresher
+
+ # -- Auto-refresh logic -------------------------------------------------
+
+ def _should_refresh(self) -> bool:
+ if self._refresher is None:
+ return False
+ raw = self._expires_at.replace("Z", "+00:00")
+ expires = datetime.fromisoformat(raw)
+ if expires.tzinfo is None:
+ expires = expires.replace(tzinfo=timezone.utc)
+ remaining = (expires - datetime.now(timezone.utc)).total_seconds()
+ return remaining <= _REFRESH_MARGIN_SECONDS
+
+ async def _maybe_refresh(self) -> None:
+ if self._should_refresh():
+ fresh = await self._refresher() # type: ignore[misc]
+ self._browser_url = fresh._browser_url
+ self._service_url = fresh._service_url
+ self._token = fresh._token
+ self._expires_at = fresh._expires_at
+
+ # -- Async accessors (auto-refresh on access) ---------------------------
+
+ async def get_token(self) -> str:
+ """Return the raw JWT, refreshing if near expiry."""
+ await self._maybe_refresh()
+ return self._token
+
+ async def get_service_url(self) -> str:
+ """Return the base URL, refreshing if near expiry."""
+ await self._maybe_refresh()
+ return self._service_url
+
+ async def get_browser_url(self) -> str:
+ """Return the browser auth URL, refreshing if near expiry."""
+ await self._maybe_refresh()
+ return self._browser_url
+
+ async def get_expires_at(self) -> str:
+ """Return the ISO 8601 expiration, refreshing if near expiry."""
+ await self._maybe_refresh()
+ return self._expires_at
+
+ # -- Sync property access (no refresh, use when token is known-fresh) ---
+
+ @property
+ def token(self) -> str:
+ """Return the raw JWT without refreshing."""
+ return self._token
+
+ @property
+ def service_url(self) -> str:
+ """Return the base URL without refreshing."""
+ return self._service_url
+
+ @property
+ def browser_url(self) -> str:
+ """Return the browser auth URL without refreshing."""
+ return self._browser_url
+
+ @property
+ def expires_at(self) -> str:
+ """Return the expiration timestamp without refreshing."""
+ return self._expires_at
+
+ # -- HTTP helpers (one request per call) --------------------------------
+
+ async def request(
+ self, method: str, path: str = "/", **kwargs: Any
+ ) -> httpx.Response:
+ """Make an async HTTP request to the service, injecting the auth header.
+
+ Args:
+ method: HTTP method (GET, POST, etc.).
+ path: Path relative to the service URL.
+ **kwargs: Forwarded to ``httpx.AsyncClient.request``.
+
+ Returns:
+ httpx.Response.
+ """
+ url = (await self.get_service_url()).rstrip("/") + "/" + path.lstrip("/")
+ headers = dict(kwargs.pop("headers", None) or {})
+ headers[_AUTH_HEADER] = await self.get_token()
+ async with httpx.AsyncClient() as client:
+ return await client.request(method, url, headers=headers, **kwargs)
+
+ async def get(self, path: str = "/", **kwargs: Any) -> httpx.Response:
+ """Async HTTP GET to the service."""
+ return await self.request("GET", path, **kwargs)
+
+ async def post(self, path: str = "/", **kwargs: Any) -> httpx.Response:
+ """Async HTTP POST to the service."""
+ return await self.request("POST", path, **kwargs)
+
+ async def put(self, path: str = "/", **kwargs: Any) -> httpx.Response:
+ """Async HTTP PUT to the service."""
+ return await self.request("PUT", path, **kwargs)
+
+ async def patch(self, path: str = "/", **kwargs: Any) -> httpx.Response:
+ """Async HTTP PATCH to the service."""
+ return await self.request("PATCH", path, **kwargs)
+
+ async def delete(self, path: str = "/", **kwargs: Any) -> httpx.Response:
+ """Async HTTP DELETE to the service."""
+ return await self.request("DELETE", path, **kwargs)
+
+ # -- Construction -------------------------------------------------------
+
+ @classmethod
+ def from_dict(
+ cls,
+ data: dict[str, Any],
+ *,
+ _refresher: Optional[Callable[[], Awaitable[AsyncServiceURL]]] = None,
+ ) -> AsyncServiceURL:
+ """Create an AsyncServiceURL from API response dict."""
+ return cls(
+ browser_url=data["browser_url"],
+ service_url=data["service_url"],
+ token=data["token"],
+ expires_at=data["expires_at"],
+ _refresher=_refresher,
+ )
+
+ def __repr__(self) -> str:
+ return (
+ f"AsyncServiceURL(service_url={self._service_url!r}, "
+ f"expires_at={self._expires_at!r})"
+ )
+
+
+# =============================================================================
+# WebSocket Command Execution Models
+# =============================================================================
+
+
+@dataclass
+class OutputChunk:
+ """A single chunk of streaming output from command execution.
+
+ Attributes:
+ stream: Either "stdout" or "stderr".
+ data: The text content of this chunk (valid UTF-8, server handles
+ boundary splitting).
+ offset: Byte offset within the stream. Used internally for
+ reconnection; users typically don't need this.
+ """
+
+ stream: str
+ data: str
+ offset: int
+
+
+class CommandHandle:
+ """Handle to a running command with streaming output and auto-reconnect.
+
+ Iterable, yielding OutputChunk objects (stdout and stderr interleaved
+ in arrival order). Access .result after iteration to get the full
+ ExecutionResult.
+
+ Auto-reconnect behavior:
+ - Server hot-reload (1001 Going Away): reconnect immediately
+ - Network error / unexpected close: reconnect with exponential backoff
+ - User called kill(): do NOT reconnect (propagate error)
+
+ The auto-reconnect is transparent -- the iterator reconnects and
+ continues yielding chunks without any user intervention. If all
+ reconnect attempts are exhausted, SandboxConnectionError is raised.
+
+ Construction modes (controlled by ``command_id``):
+ - **New execution** (``command_id=""``, the default): the constructor
+ eagerly reads the server's ``"started"`` message to populate
+ ``command_id`` and ``pid`` before returning.
+ - **Reconnection** (``command_id`` set): skips the started-message
+ read, since reconnect streams don't emit one.
+
+ Example:
+ handle = sandbox.run("make build", timeout=600, wait=False)
+
+ for chunk in handle: # auto-reconnects on transient errors
+ print(chunk.data, end="")
+
+ result = handle.result
+ print(f"Exit code: {result.exit_code}")
+ """
+
+ MAX_AUTO_RECONNECTS = 5
+ _BACKOFF_BASE = 0.5 # seconds
+ _BACKOFF_MAX = 8.0 # seconds
+
+ def __init__(
+ self,
+ message_stream: Iterator[dict],
+ control: Optional[_WSStreamControl],
+ sandbox: Sandbox,
+ *,
+ command_id: str = "",
+ stdout_offset: int = 0,
+ stderr_offset: int = 0,
+ ) -> None:
+ self._stream = message_stream
+ self._control = control
+ self._sandbox = sandbox
+ self._command_id: Optional[str] = None
+ self._pid: Optional[int] = None
+ self._result: Optional[ExecutionResult] = None
+ self._stdout_parts: list[str] = []
+ self._stderr_parts: list[str] = []
+ self._exhausted = False
+ self._last_stdout_offset = stdout_offset
+ self._last_stderr_offset = stderr_offset
+
+ # New executions (command_id=""): eager_start reads "started" message.
+ # Reconnections (command_id set): skip eager_start since reconnect
+ # streams don't send a "started" message.
+ if command_id:
+ self._command_id = command_id
+ else:
+ self._consume_started()
+
+ def _consume_started(self) -> None:
+ """Eagerly read the 'started' message to populate command_id and pid.
+
+ Blocks briefly until the server sends the started message (arrives
+ near-instantly after connection). After this call, command_id and
+ pid are available, and the WebSocket is bound to the control object
+ (so kill() works).
+ """
+ try:
+ first_msg = next(self._stream)
+ except StopIteration:
+ raise SandboxOperationError(
+ "Command stream ended before 'started' message",
+ operation="command",
+ )
+ if first_msg.get("type") != "started":
+ raise SandboxOperationError(
+ f"Expected 'started' message, got '{first_msg.get('type')}'",
+ operation="command",
+ )
+ self._command_id = first_msg.get("command_id")
+ self._pid = first_msg.get("pid")
+
+ @property
+ def command_id(self) -> Optional[str]:
+ """The server-assigned command ID. Available after construction."""
+ return self._command_id
+
+ @property
+ def pid(self) -> Optional[int]:
+ """The process ID on the sandbox. Available after construction."""
+ return self._pid
+
+ @property
+ def result(self) -> ExecutionResult:
+ """The final execution result. Blocks until the command completes.
+
+ Drains the remaining stream if not already exhausted, then returns
+ the ExecutionResult with aggregated stdout, stderr, and exit_code.
+ """
+ if self._result is None:
+ for _ in self:
+ pass
+ if self._result is None:
+ raise SandboxOperationError(
+ "Command stream ended without exit message",
+ operation="command",
+ )
+ return self._result
+
+ def _iter_stream(self) -> Iterator[OutputChunk]:
+ """Iterate over output chunks from the current stream (no reconnect)."""
+ if self._exhausted:
+ return
+ for msg in self._stream:
+ msg_type = msg.get("type")
+ if msg_type in ("stdout", "stderr"):
+ chunk = OutputChunk(
+ stream=msg_type,
+ data=msg["data"],
+ offset=msg.get("offset", 0),
+ )
+ if msg_type == "stdout":
+ self._stdout_parts.append(msg["data"])
+ else:
+ self._stderr_parts.append(msg["data"])
+ yield chunk
+ elif msg_type == "exit":
+ self._result = ExecutionResult(
+ stdout="".join(self._stdout_parts),
+ stderr="".join(self._stderr_parts),
+ exit_code=msg["exit_code"],
+ )
+ self._exhausted = True
+ return
+ self._exhausted = True
+
+ def __iter__(self) -> Iterator[OutputChunk]:
+ """Iterate over output chunks, auto-reconnecting on transient errors.
+
+ Reconnect strategy:
+ - 1001 Going Away (hot-reload): immediate reconnect, no delay
+ - Other SandboxConnectionError: exponential backoff (0.5s, 1s, 2s...)
+ - After kill(): no reconnect, error propagates
+ """
+ import time
+
+ reconnect_attempts = 0
+ while True:
+ try:
+ for chunk in self._iter_stream():
+ reconnect_attempts = 0 # Reset on successful data
+ if chunk.stream == "stdout":
+ self._last_stdout_offset = chunk.offset + len(
+ chunk.data.encode("utf-8")
+ )
+ else:
+ self._last_stderr_offset = chunk.offset + len(
+ chunk.data.encode("utf-8")
+ )
+ yield chunk
+ return # Stream ended normally (exit message received)
+
+ except SandboxConnectionError as e:
+ if self._control and self._control.killed:
+ raise
+
+ reconnect_attempts += 1
+ if reconnect_attempts > self.MAX_AUTO_RECONNECTS:
+ raise SandboxConnectionError(
+ f"Lost connection {reconnect_attempts} times in "
+ f"succession, giving up"
+ ) from e
+
+ is_hot_reload = isinstance(e, SandboxServerReloadError)
+ if not is_hot_reload:
+ delay = min(
+ self._BACKOFF_BASE * (2 ** (reconnect_attempts - 1)),
+ self._BACKOFF_MAX,
+ )
+ time.sleep(delay)
+
+ assert self._command_id is not None
+ new_handle = self._sandbox.reconnect(
+ self._command_id,
+ stdout_offset=self._last_stdout_offset,
+ stderr_offset=self._last_stderr_offset,
+ )
+ self._stream = new_handle._stream
+ self._control = new_handle._control
+ self._exhausted = False
+
+ def kill(self) -> None:
+ """Send a kill signal to the running command (SIGKILL).
+
+ The server kills the entire process group. The stream will
+ subsequently yield an exit message with a non-zero exit code.
+
+ Has no effect if the command has already exited or the
+ WebSocket connection is closed.
+ """
+ if self._control:
+ self._control.send_kill()
+
+ def send_input(self, data: str) -> None:
+ """Write data to the command's stdin.
+
+ Args:
+ data: String data to write to stdin.
+
+ Has no effect if the command has already exited or the
+ WebSocket connection is closed.
+ """
+ if self._control:
+ self._control.send_input(data)
+
+ @property
+ def last_stdout_offset(self) -> int:
+ """Last known stdout byte offset (for manual reconnection)."""
+ return self._last_stdout_offset
+
+ @property
+ def last_stderr_offset(self) -> int:
+ """Last known stderr byte offset (for manual reconnection)."""
+ return self._last_stderr_offset
+
+ def reconnect(self) -> CommandHandle:
+ """Reconnect to this command from the last known offsets.
+
+ Returns a new handle that resumes output from where this one
+ left off. Any output produced while disconnected is replayed
+ from the server's ring buffer.
+
+ Returns:
+ A new CommandHandle.
+
+ Raises:
+ SandboxOperationError: If command_id is not found or
+ session expired.
+ SandboxConnectionError: If connection to sandbox fails.
+ """
+ assert self._command_id is not None
+ return self._sandbox.reconnect(
+ self._command_id,
+ stdout_offset=self._last_stdout_offset,
+ stderr_offset=self._last_stderr_offset,
+ )
+
+
+class AsyncCommandHandle:
+ """Async handle to a running command with streaming output and auto-reconnect.
+
+ Async iterable, yielding OutputChunk objects (stdout and stderr interleaved
+ in arrival order). Access .result after iteration to get the full
+ ExecutionResult.
+
+ Auto-reconnect behavior:
+ - Server hot-reload (1001 Going Away): reconnect immediately
+ - Network error / unexpected close: reconnect with exponential backoff
+ - User called kill(): do NOT reconnect (propagate error)
+
+ Construction modes (controlled by ``command_id``):
+ - **New execution** (``command_id=""``, the default): call
+ ``await handle._ensure_started()`` after construction to read the
+ server's ``"started"`` message and populate ``command_id`` / ``pid``.
+ - **Reconnection** (``command_id`` set): skips the started-message
+ read, since reconnect streams don't emit one.
+
+ Example:
+ handle = await sandbox.run("make build", timeout=600, wait=False)
+
+ async for chunk in handle: # auto-reconnects on transient errors
+ print(chunk.data, end="")
+
+ result = await handle.result
+ print(f"Exit code: {result.exit_code}")
+ """
+
+ MAX_AUTO_RECONNECTS = 5
+ _BACKOFF_BASE = 0.5 # seconds
+ _BACKOFF_MAX = 8.0 # seconds
+
+ def __init__(
+ self,
+ message_stream: AsyncIterator[dict],
+ control: Optional[_AsyncWSStreamControl],
+ sandbox: AsyncSandbox,
+ *,
+ command_id: str = "",
+ stdout_offset: int = 0,
+ stderr_offset: int = 0,
+ ) -> None:
+ self._stream = message_stream
+ self._control = control
+ self._sandbox = sandbox
+ self._command_id: Optional[str] = None
+ self._pid: Optional[int] = None
+ self._result: Optional[ExecutionResult] = None
+ self._stdout_parts: list[str] = []
+ self._stderr_parts: list[str] = []
+ self._exhausted = False
+ self._last_stdout_offset = stdout_offset
+ self._last_stderr_offset = stderr_offset
+
+ # New executions (command_id=""): _ensure_started reads "started".
+ # Reconnections (command_id set): skip since reconnect streams
+ # don't send a "started" message.
+ if command_id:
+ self._command_id = command_id
+ self._started = True
+ else:
+ self._started = False
+
+ async def _ensure_started(self) -> None:
+ """Read the 'started' message to populate command_id and pid."""
+ if self._started:
+ return
+ try:
+ first_msg = await self._stream.__anext__()
+ except StopAsyncIteration:
+ raise SandboxOperationError(
+ "Command stream ended before 'started' message",
+ operation="command",
+ )
+ if first_msg.get("type") != "started":
+ raise SandboxOperationError(
+ f"Expected 'started' message, got '{first_msg.get('type')}'",
+ operation="command",
+ )
+ self._command_id = first_msg.get("command_id")
+ self._pid = first_msg.get("pid")
+ self._started = True
+
+ @property
+ def command_id(self) -> Optional[str]:
+ """The server-assigned command ID. Available after _ensure_started."""
+ return self._command_id
+
+ @property
+ def pid(self) -> Optional[int]:
+ """The process ID on the sandbox. Available after _ensure_started."""
+ return self._pid
+
+ @property
+ async def result(self) -> ExecutionResult:
+ """The final execution result. Awaitable."""
+ if self._result is None:
+ async for _ in self:
+ pass
+ if self._result is None:
+ raise SandboxOperationError(
+ "Command stream ended without exit message",
+ operation="command",
+ )
+ return self._result
+
+ async def _aiter_stream(self) -> AsyncIterator[OutputChunk]:
+ """Iterate over output chunks from the current stream (no reconnect)."""
+ await self._ensure_started()
+ if self._exhausted:
+ return
+ async for msg in self._stream:
+ msg_type = msg.get("type")
+ if msg_type in ("stdout", "stderr"):
+ chunk = OutputChunk(
+ stream=msg_type,
+ data=msg["data"],
+ offset=msg.get("offset", 0),
+ )
+ if msg_type == "stdout":
+ self._stdout_parts.append(msg["data"])
+ else:
+ self._stderr_parts.append(msg["data"])
+ yield chunk
+ elif msg_type == "exit":
+ self._result = ExecutionResult(
+ stdout="".join(self._stdout_parts),
+ stderr="".join(self._stderr_parts),
+ exit_code=msg["exit_code"],
+ )
+ self._exhausted = True
+ return
+ self._exhausted = True
+
+ async def __aiter__(self) -> AsyncIterator[OutputChunk]:
+ """Async iterate with auto-reconnect on transient errors."""
+ import asyncio
+
+ reconnect_attempts = 0
+ while True:
+ try:
+ async for chunk in self._aiter_stream():
+ reconnect_attempts = 0
+ if chunk.stream == "stdout":
+ self._last_stdout_offset = chunk.offset + len(
+ chunk.data.encode("utf-8")
+ )
+ else:
+ self._last_stderr_offset = chunk.offset + len(
+ chunk.data.encode("utf-8")
+ )
+ yield chunk
+ return # Stream ended normally
+
+ except SandboxConnectionError as e:
+ if self._control and self._control.killed:
+ raise
+
+ reconnect_attempts += 1
+ if reconnect_attempts > self.MAX_AUTO_RECONNECTS:
+ raise SandboxConnectionError(
+ f"Lost connection {reconnect_attempts} times "
+ f"in succession, giving up"
+ ) from e
+
+ is_hot_reload = isinstance(e, SandboxServerReloadError)
+ if not is_hot_reload:
+ delay = min(
+ self._BACKOFF_BASE * (2 ** (reconnect_attempts - 1)),
+ self._BACKOFF_MAX,
+ )
+ await asyncio.sleep(delay)
+
+ assert self._command_id is not None
+ new_handle = await self._sandbox.reconnect(
+ self._command_id,
+ stdout_offset=self._last_stdout_offset,
+ stderr_offset=self._last_stderr_offset,
+ )
+ self._stream = new_handle._stream
+ self._control = new_handle._control
+ self._exhausted = False
+
+ async def kill(self) -> None:
+ """Send a kill signal to the running command."""
+ if self._control:
+ await self._control.send_kill()
+
+ async def send_input(self, data: str) -> None:
+ """Write data to the command's stdin."""
+ if self._control:
+ await self._control.send_input(data)
+
+ @property
+ def last_stdout_offset(self) -> int:
+ """Last known stdout byte offset (for manual reconnection)."""
+ return self._last_stdout_offset
+
+ @property
+ def last_stderr_offset(self) -> int:
+ """Last known stderr byte offset (for manual reconnection)."""
+ return self._last_stderr_offset
+
+ async def reconnect(self) -> AsyncCommandHandle:
+ """Reconnect to this command from the last known offsets."""
+ assert self._command_id is not None
+ return await self._sandbox.reconnect(
+ self._command_id,
+ stdout_offset=self._last_stdout_offset,
+ stderr_offset=self._last_stderr_offset,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_sandbox.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_sandbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..7507f9109a2206ae4b8f89f851f18e30d96a04b3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_sandbox.py
@@ -0,0 +1,735 @@
+"""Sandbox class for interacting with a specific sandbox instance."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Union, overload
+
+import httpx
+
+from langsmith.sandbox._exceptions import (
+ DataplaneNotConfiguredError,
+ ResourceNotFoundError,
+ SandboxConnectionError,
+ SandboxNotReadyError,
+)
+from langsmith.sandbox._helpers import handle_sandbox_http_error
+from langsmith.sandbox._models import (
+ CommandHandle,
+ ExecutionResult,
+ ServiceURL,
+ Snapshot,
+)
+from langsmith.sandbox._tunnel import Tunnel
+
+if TYPE_CHECKING:
+ from langsmith.sandbox._client import SandboxClient
+
+
+RequestHeaders = Optional[Mapping[str, str]]
+
+
+@dataclass
+class Sandbox:
+ """Represents an active sandbox for running commands and file operations.
+
+ This class is typically obtained from SandboxClient.sandbox() and supports
+ the context manager protocol for automatic cleanup.
+
+ Attributes:
+ name: Display name (can be updated).
+ dataplane_url: URL for data plane operations (file I/O, command execution).
+ Only functional when status is "ready".
+ id: Unique identifier (UUID). Remains constant even if name changes.
+ May be None for resources created before ID support was added.
+ status: Sandbox lifecycle status. One of "provisioning", "ready",
+ "failed", "stopped".
+ status_message: Human-readable details when status is "failed", None otherwise.
+ created_at: Timestamp when the sandbox was created.
+ updated_at: Timestamp when the sandbox was last updated.
+ idle_ttl_seconds: Idle timeout TTL in seconds (``0`` means disabled).
+ Newly-created sandboxes receive a server-side default of ``600``
+ seconds (10 minutes) when the caller did not set ``idle_ttl_seconds``
+ explicitly. The launcher stops the sandbox after this many idle
+ seconds; deletion is anchored to ``stopped_at`` and controlled by
+ ``delete_after_stop_seconds`` (see below).
+ delete_after_stop_seconds: Seconds after a sandbox enters the
+ ``stopped`` state before it (and its filesystem clone) are
+ permanently deleted. ``0`` disables stop-anchored deletion;
+ ``None`` falls back to the server default.
+ stopped_at: Timestamp when the sandbox transitioned to ``stopped``,
+ or ``None`` while running. The deletion deadline is
+ ``stopped_at + delete_after_stop_seconds``.
+ snapshot_id: Snapshot ID used to create this sandbox.
+ vcpus: Number of vCPUs allocated.
+ mem_bytes: Memory allocation in bytes.
+ fs_capacity_bytes: Root filesystem capacity in bytes.
+
+ Example:
+ with client.sandbox(snapshot_id="") as sandbox:
+ result = sandbox.run("python --version")
+ print(result.stdout)
+ """
+
+ # Data fields (from API response)
+ name: str
+ dataplane_url: Optional[str] = None
+ id: Optional[str] = None
+ status: str = "ready"
+ status_message: Optional[str] = None
+ created_at: Optional[str] = None
+ updated_at: Optional[str] = None
+ idle_ttl_seconds: Optional[int] = None
+ delete_after_stop_seconds: Optional[int] = None
+ stopped_at: Optional[str] = None
+ snapshot_id: Optional[str] = None
+ vcpus: Optional[int] = None
+ mem_bytes: Optional[int] = None
+ fs_capacity_bytes: Optional[int] = None
+
+ # Internal fields (not from API)
+ _client: SandboxClient = field(repr=False, default=None) # type: ignore
+ _auto_delete: bool = field(repr=False, default=True)
+
+ @classmethod
+ def from_dict(
+ cls,
+ data: dict[str, Any],
+ client: SandboxClient,
+ auto_delete: bool = True,
+ ) -> Sandbox:
+ """Create a Sandbox from API response dict.
+
+ Args:
+ data: API response dictionary containing sandbox data.
+ client: Parent SandboxClient for operations.
+ auto_delete: Whether to delete the sandbox on context exit.
+
+ Returns:
+ Sandbox instance.
+ """
+ return cls(
+ name=data.get("name", ""),
+ dataplane_url=data.get("dataplane_url"),
+ id=data.get("id"),
+ status=data.get("status", "ready"),
+ status_message=data.get("status_message"),
+ created_at=data.get("created_at"),
+ updated_at=data.get("updated_at"),
+ idle_ttl_seconds=data.get("idle_ttl_seconds"),
+ delete_after_stop_seconds=data.get("delete_after_stop_seconds"),
+ stopped_at=data.get("stopped_at"),
+ snapshot_id=data.get("snapshot_id"),
+ vcpus=data.get("vcpus"),
+ mem_bytes=data.get("mem_bytes"),
+ fs_capacity_bytes=data.get("fs_capacity_bytes"),
+ _client=client,
+ _auto_delete=auto_delete,
+ )
+
+ def __enter__(self) -> Sandbox:
+ """Enter context manager."""
+ return self
+
+ def __exit__(
+ self,
+ exc_type: Optional[type],
+ exc_val: Optional[BaseException],
+ exc_tb: Optional[Any],
+ ) -> None:
+ """Exit context manager, optionally deleting the sandbox."""
+ if self._auto_delete:
+ try:
+ self._client.delete_sandbox(self.name)
+ except Exception:
+ # Don't raise on cleanup errors
+ pass
+
+ def _require_dataplane_url(self) -> str:
+ """Validate and return the dataplane URL.
+
+ Returns:
+ The dataplane URL.
+
+ Raises:
+ SandboxNotReadyError: If sandbox status is not "ready".
+ DataplaneNotConfiguredError: If dataplane_url is not configured.
+ """
+ if self.status != "ready":
+ raise SandboxNotReadyError(
+ f"Sandbox '{self.name}' is not ready (status: {self.status}). "
+ "Wait for status 'ready' before running operations."
+ )
+ if not self.dataplane_url:
+ raise DataplaneNotConfiguredError(
+ f"Sandbox '{self.name}' does not have a dataplane_url configured. "
+ "Runtime operations require a dataplane URL."
+ )
+ return self.dataplane_url
+
+ @overload
+ def run(
+ self,
+ command: str,
+ *,
+ timeout: int = ...,
+ env: Optional[dict[str, str]] = ...,
+ cwd: Optional[str] = ...,
+ shell: str = ...,
+ on_stdout: Optional[Callable[[str], Any]] = ...,
+ on_stderr: Optional[Callable[[str], Any]] = ...,
+ idle_timeout: int = ...,
+ kill_on_disconnect: bool = ...,
+ ttl_seconds: int = ...,
+ pty: bool = ...,
+ headers: RequestHeaders = ...,
+ wait: Literal[True] = ...,
+ ) -> ExecutionResult: ...
+
+ @overload
+ def run(
+ self,
+ command: str,
+ *,
+ timeout: int = ...,
+ env: Optional[dict[str, str]] = ...,
+ cwd: Optional[str] = ...,
+ shell: str = ...,
+ on_stdout: Optional[Callable[[str], Any]] = ...,
+ on_stderr: Optional[Callable[[str], Any]] = ...,
+ idle_timeout: int = ...,
+ kill_on_disconnect: bool = ...,
+ ttl_seconds: int = ...,
+ pty: bool = ...,
+ headers: RequestHeaders = ...,
+ wait: Literal[False],
+ ) -> CommandHandle: ...
+
+ def run(
+ self,
+ command: str,
+ *,
+ timeout: int = 60,
+ env: Optional[dict[str, str]] = None,
+ cwd: Optional[str] = None,
+ shell: str = "/bin/bash",
+ on_stdout: Optional[Callable[[str], Any]] = None,
+ on_stderr: Optional[Callable[[str], Any]] = None,
+ idle_timeout: int = 300,
+ kill_on_disconnect: bool = False,
+ ttl_seconds: int = 600,
+ pty: bool = False,
+ headers: RequestHeaders = None,
+ wait: bool = True,
+ ) -> Union[ExecutionResult, CommandHandle]:
+ """Execute a command in the sandbox.
+
+ Args:
+ command: Shell command to execute.
+ timeout: Command timeout in seconds.
+ env: Environment variables to set for the command.
+ cwd: Working directory for command execution. If None, uses sandbox default.
+ shell: Shell to use for command execution. Defaults to "/bin/bash".
+ on_stdout: Callback invoked with each stdout chunk as it arrives.
+ Blocks until the command completes and returns ExecutionResult.
+ Cannot be combined with wait=False.
+ on_stderr: Callback invoked with each stderr chunk as it arrives.
+ Blocks until the command completes and returns ExecutionResult.
+ Cannot be combined with wait=False.
+ idle_timeout: Idle timeout in seconds. If the command has no
+ connected clients for this duration, it is killed. Defaults
+ to 300 (5 minutes). Set to -1 for no idle timeout.
+ Only applies to WebSocket execution.
+ kill_on_disconnect: If True, kill the command immediately when
+ the last client disconnects. Defaults to False (command
+ continues running and can be reconnected to).
+ ttl_seconds: How long (in seconds) a finished command's session
+ is kept for reconnection. Defaults to 600 (10 minutes).
+ Set to -1 to keep indefinitely.
+ pty: If True, allocate a pseudo-terminal for the command.
+ Useful for commands that require a TTY (e.g., interactive
+ programs, commands that use terminal control codes).
+ Defaults to False.
+ wait: If True (default), block until the command completes and
+ return ExecutionResult. If False, return a
+ CommandHandle immediately for streaming output,
+ kill, stdin input, and reconnection. Cannot be combined with
+ on_stdout/on_stderr callbacks.
+
+ Returns:
+ ExecutionResult when wait=True (default).
+ CommandHandle when wait=False.
+
+ Raises:
+ ValueError: If wait=False is combined with callbacks.
+ DataplaneNotConfiguredError: If dataplane_url is not configured.
+ SandboxOperationError: If command execution fails.
+ CommandTimeoutError: If command exceeds its timeout.
+ SandboxConnectionError: If connection to sandbox fails after retries.
+ SandboxNotReadyError: If sandbox is not ready.
+ SandboxClientError: For other errors.
+ """
+ if not wait and (on_stdout or on_stderr):
+ raise ValueError(
+ "Cannot combine wait=False with on_stdout/on_stderr callbacks. "
+ "Use wait=False and iterate the CommandHandle, or use callbacks."
+ )
+
+ self._require_dataplane_url()
+
+ # When not waiting or callbacks are requested, WS is required
+ use_ws = not wait or on_stdout or on_stderr
+ if use_ws:
+ return self._run_ws(
+ command,
+ timeout=timeout,
+ env=env,
+ cwd=cwd,
+ shell=shell,
+ wait=wait,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ idle_timeout=idle_timeout,
+ kill_on_disconnect=kill_on_disconnect,
+ ttl_seconds=ttl_seconds,
+ pty=pty,
+ headers=headers,
+ )
+
+ # Default (wait=True, no callbacks): try WS, fall back to HTTP.
+ # Catch broad exceptions so that unexpected WS failures (e.g. version
+ # incompatibilities) don't break users who don't need WS features.
+ try:
+ return self._run_ws(
+ command,
+ timeout=timeout,
+ env=env,
+ cwd=cwd,
+ shell=shell,
+ wait=True,
+ on_stdout=None,
+ on_stderr=None,
+ idle_timeout=idle_timeout,
+ kill_on_disconnect=kill_on_disconnect,
+ ttl_seconds=ttl_seconds,
+ pty=pty,
+ headers=headers,
+ )
+ except (SandboxConnectionError, ImportError, OSError, TypeError):
+ return self._run_http(
+ command,
+ timeout=timeout,
+ env=env,
+ cwd=cwd,
+ shell=shell,
+ headers=headers,
+ )
+
+ def _run_ws(
+ self,
+ command: str,
+ *,
+ timeout: int,
+ env: Optional[dict[str, str]],
+ cwd: Optional[str],
+ shell: str,
+ wait: bool,
+ on_stdout: Optional[Callable[[str], Any]],
+ on_stderr: Optional[Callable[[str], Any]],
+ idle_timeout: int = 300,
+ kill_on_disconnect: bool = False,
+ ttl_seconds: int = 600,
+ pty: bool = False,
+ headers: RequestHeaders = None,
+ ) -> Union[ExecutionResult, CommandHandle]:
+ """Execute via WebSocket /execute/ws."""
+ from langsmith.sandbox._ws_execute import run_ws_stream
+
+ dataplane_url = self._require_dataplane_url()
+ api_key = self._client._api_key
+
+ ws_kwargs: dict[str, Any] = {
+ "timeout": timeout,
+ "env": env,
+ "cwd": cwd,
+ "shell": shell,
+ "on_stdout": on_stdout,
+ "on_stderr": on_stderr,
+ "idle_timeout": idle_timeout,
+ "kill_on_disconnect": kill_on_disconnect,
+ "ttl_seconds": ttl_seconds,
+ "pty": pty,
+ }
+ if headers is not None:
+ ws_kwargs["headers"] = headers
+
+ msg_stream, control = run_ws_stream(
+ dataplane_url,
+ api_key,
+ command,
+ **ws_kwargs,
+ )
+
+ handle = CommandHandle(msg_stream, control, self)
+
+ if not wait:
+ return handle
+
+ return handle.result # blocks until command completes
+
+ def _run_http(
+ self,
+ command: str,
+ *,
+ timeout: int,
+ env: Optional[dict[str, str]],
+ cwd: Optional[str],
+ shell: str,
+ headers: RequestHeaders,
+ ) -> ExecutionResult:
+ """Execute via HTTP POST /execute (existing implementation)."""
+ dataplane_url = self._require_dataplane_url()
+ url = f"{dataplane_url}/execute"
+ payload: dict[str, Any] = {
+ "command": command,
+ "timeout": timeout,
+ "shell": shell,
+ }
+ if env is not None:
+ payload["env"] = env
+ if cwd is not None:
+ payload["cwd"] = cwd
+
+ try:
+ response = self._client._http.post(
+ url,
+ json=payload,
+ timeout=timeout + 10,
+ headers=self._client._request_headers(headers),
+ )
+ response.raise_for_status()
+ data = response.json()
+ return ExecutionResult(
+ stdout=data.get("stdout", ""),
+ stderr=data.get("stderr", ""),
+ exit_code=data.get("exit_code", -1),
+ )
+ except httpx.HTTPStatusError as e:
+ handle_sandbox_http_error(e)
+ raise # pragma: no cover
+
+ def reconnect(
+ self,
+ command_id: str,
+ *,
+ stdout_offset: int = 0,
+ stderr_offset: int = 0,
+ headers: RequestHeaders = None,
+ ) -> CommandHandle:
+ """Reconnect to a running or recently-finished command.
+
+ Resumes output from the given byte offsets. Any output produced while
+ the client was disconnected is replayed from the server's ring buffer.
+
+ Args:
+ command_id: The command ID from handle.command_id.
+ stdout_offset: Byte offset to resume stdout from (default: 0).
+ stderr_offset: Byte offset to resume stderr from (default: 0).
+
+ Returns:
+ A CommandHandle for the command.
+
+ Raises:
+ SandboxOperationError: If command_id is not found or session expired.
+ SandboxConnectionError: If connection to sandbox fails after retries.
+ """
+ from langsmith.sandbox._ws_execute import reconnect_ws_stream
+
+ dataplane_url = self._require_dataplane_url()
+ api_key = self._client._api_key
+
+ reconnect_kwargs: dict[str, Any] = {
+ "stdout_offset": stdout_offset,
+ "stderr_offset": stderr_offset,
+ }
+ if headers is not None:
+ reconnect_kwargs["headers"] = headers
+
+ msg_stream, control = reconnect_ws_stream(
+ dataplane_url,
+ api_key,
+ command_id,
+ **reconnect_kwargs,
+ )
+
+ return CommandHandle(
+ msg_stream,
+ control,
+ self,
+ command_id=command_id,
+ stdout_offset=stdout_offset,
+ stderr_offset=stderr_offset,
+ )
+
+ def write(
+ self,
+ path: str,
+ content: Union[str, bytes],
+ *,
+ timeout: int = 60,
+ headers: RequestHeaders = None,
+ ) -> None:
+ """Write content to a file in the sandbox.
+
+ Args:
+ path: Target file path in the sandbox.
+ content: File content (str or bytes).
+ timeout: Request timeout in seconds.
+
+ Raises:
+ DataplaneNotConfiguredError: If dataplane_url is not configured.
+ SandboxOperationError: If file write fails.
+ SandboxConnectionError: If connection to sandbox fails after retries.
+ SandboxNotReadyError: If sandbox is not ready.
+ SandboxClientError: For other errors.
+ """
+ dataplane_url = self._require_dataplane_url()
+ url = f"{dataplane_url}/upload"
+
+ # Ensure content is bytes for multipart upload
+ if isinstance(content, str):
+ content = content.encode("utf-8")
+
+ files = {"file": ("file", content)}
+
+ try:
+ response = self._client._http.post(
+ url,
+ params={"path": path},
+ files=files,
+ timeout=timeout,
+ headers=self._client._request_headers(headers),
+ )
+ response.raise_for_status()
+ except httpx.HTTPStatusError as e:
+ handle_sandbox_http_error(e)
+
+ def read(
+ self, path: str, *, timeout: int = 60, headers: RequestHeaders = None
+ ) -> bytes:
+ """Read a file from the sandbox.
+
+ Args:
+ path: File path to read. Supports both absolute paths (e.g., /tmp/file.txt)
+ and relative paths (resolved from /home/user/).
+ timeout: Request timeout in seconds.
+
+ Returns:
+ File contents as bytes.
+
+ Raises:
+ DataplaneNotConfiguredError: If dataplane_url is not configured.
+ ResourceNotFoundError: If the file doesn't exist.
+ SandboxOperationError: If file read fails.
+ SandboxConnectionError: If connection to sandbox fails after retries.
+ SandboxNotReadyError: If sandbox is not ready.
+ SandboxClientError: For other errors.
+ """
+ dataplane_url = self._require_dataplane_url()
+ url = f"{dataplane_url}/download"
+
+ try:
+ response = self._client._http.get(
+ url,
+ params={"path": path},
+ timeout=timeout,
+ headers=self._client._request_headers(headers),
+ )
+ response.raise_for_status()
+ return response.content
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 404:
+ raise ResourceNotFoundError(
+ f"File '{path}' not found in sandbox '{self.name}'",
+ resource_type="file",
+ ) from e
+ handle_sandbox_http_error(e)
+ # This line should never be reached but satisfies type checker
+ raise # pragma: no cover
+
+ def tunnel(
+ self,
+ remote_port: int,
+ *,
+ local_port: int = 0,
+ max_reconnects: int = 3,
+ headers: RequestHeaders = None,
+ ) -> Tunnel:
+ """Open a TCP tunnel to a port inside the sandbox.
+
+ Creates a local TCP listener that forwards connections through a
+ yamux-multiplexed WebSocket to the specified port inside the sandbox.
+ Works with any TCP protocol (databases, Redis, HTTP, etc.).
+
+ Use as a context manager for automatic cleanup::
+
+ with sandbox.tunnel(remote_port=5432) as t:
+ conn = psycopg2.connect(host="127.0.0.1", port=t.local_port)
+
+ Or manage the lifecycle explicitly::
+
+ t = sandbox.tunnel(remote_port=5432)
+ # ... use tunnel ...
+ t.close()
+
+ Args:
+ remote_port: TCP port inside the sandbox to tunnel to (1-65535).
+ local_port: Local port to listen on. Defaults to mirroring
+ remote_port. Use 0 to let the OS pick an available port.
+ max_reconnects: Maximum number of automatic reconnect attempts
+ when the WebSocket session drops. Set to 0 to disable.
+
+ Returns:
+ A Tunnel instance (context manager).
+
+ Raises:
+ ValueError: If port values are out of range.
+ DataplaneNotConfiguredError: If dataplane_url is not configured.
+ SandboxNotReadyError: If sandbox is not ready.
+ """
+ if not 1 <= remote_port <= 65535:
+ raise ValueError(
+ f"remote_port must be between 1 and 65535 (got {remote_port})"
+ )
+ if local_port and not 1 <= local_port <= 65535:
+ raise ValueError(
+ f"local_port must be between 1 and 65535 (got {local_port})"
+ )
+ dataplane_url = self._require_dataplane_url()
+ api_key = self._client._api_key
+ t = Tunnel(
+ dataplane_url,
+ api_key,
+ remote_port,
+ local_port=local_port,
+ max_reconnects=max_reconnects,
+ headers=headers,
+ )
+ t._start()
+ return t
+
+ def service(
+ self,
+ port: int,
+ *,
+ expires_in_seconds: int = 600,
+ headers: RequestHeaders = None,
+ ) -> ServiceURL:
+ """Get an authenticated URL for a service running in this sandbox.
+
+ Returns a :class:`ServiceURL` whose properties auto-refresh the
+ token transparently before it expires.
+
+ Args:
+ port: Port the service is listening on inside the sandbox.
+ expires_in_seconds: Token TTL in seconds (1--86400, default 600).
+ headers: Optional per-request header overrides.
+
+ Returns:
+ ServiceURL with auto-refreshing token and HTTP helpers.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ValueError: If port or expires_in_seconds is out of range.
+ SandboxClientError: For other errors.
+ """
+ return self._client.service(
+ self.name,
+ port,
+ expires_in_seconds=expires_in_seconds,
+ headers=headers,
+ )
+
+ def start(
+ self,
+ *,
+ timeout: int = 120,
+ headers: RequestHeaders = None,
+ ) -> None:
+ """Start a stopped sandbox and wait until ready.
+
+ After starting, the sandbox's status and dataplane_url are updated
+ in place.
+
+ Args:
+ timeout: Timeout in seconds when waiting for ready.
+ headers: Optional per-request header overrides.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ResourceCreationError: If sandbox fails during startup.
+ ResourceTimeoutError: If sandbox doesn't become ready within timeout.
+ SandboxClientError: For other errors.
+ """
+ refreshed = self._client.start_sandbox(
+ self.name, timeout=timeout, headers=headers
+ )
+ self.status = refreshed.status
+ self.dataplane_url = refreshed.dataplane_url
+
+ def stop(self, *, headers: RequestHeaders = None) -> None:
+ """Stop a running sandbox (preserves sandbox files for later restart).
+
+ Args:
+ headers: Optional per-request header overrides.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ self._client.stop_sandbox(self.name, headers=headers)
+ self.status = "stopped"
+ self.dataplane_url = None
+
+ def delete(self, *, headers: RequestHeaders = None) -> None:
+ """Delete this sandbox.
+
+ Args:
+ headers: Optional per-request header overrides.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ SandboxClientError: For other errors.
+ """
+ self._client.delete_sandbox(self.name, headers=headers)
+
+ def capture_snapshot(
+ self,
+ name: str,
+ *,
+ timeout: int = 60,
+ headers: RequestHeaders = None,
+ ) -> Snapshot:
+ """Capture a snapshot from this sandbox.
+
+ Args:
+ name: Snapshot name.
+ timeout: Timeout in seconds when waiting for ready.
+ headers: Optional per-request header overrides.
+
+ Returns:
+ Snapshot in "ready" status.
+
+ Raises:
+ ResourceNotFoundError: If sandbox not found.
+ ResourceTimeoutError: If snapshot doesn't become ready within timeout.
+ ResourceCreationError: If snapshot capture fails.
+ SandboxClientError: For other errors.
+ """
+ return self._client.capture_snapshot(
+ self.name,
+ name,
+ timeout=timeout,
+ headers=headers,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_transport.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_transport.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2901abe268d51375cbb3b48eca03ac082bdb80f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_transport.py
@@ -0,0 +1,216 @@
+"""Custom httpx transports with retry logic for the sandbox client.
+
+Provides RetryTransport (sync) and AsyncRetryTransport (async) that wrap
+the default httpx transports with automatic retry on transient errors.
+This mirrors the main LangSmith client's _LangSmithHttpAdapter + urllib3.Retry
+architecture at the transport level, making retries transparent to all call sites.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import random
+import time
+
+import httpx
+
+from langsmith.sandbox._exceptions import SandboxConnectionError
+
+logger = logging.getLogger(__name__)
+
+RETRYABLE_STATUS_CODES = frozenset({502, 503, 504})
+
+_MAX_BACKOFF = 10.0
+
+
+def _compute_backoff(attempt: int) -> float:
+ """Compute exponential backoff with jitter, capped at _MAX_BACKOFF."""
+ return min(2**attempt + random.random(), _MAX_BACKOFF)
+
+
+class RetryTransport(httpx.BaseTransport):
+ """Sync httpx transport that retries on transient errors.
+
+ Retries on:
+ - 502/503/504 with exponential backoff
+ - 429 with Retry-After header support
+ - Connection errors with exponential backoff
+
+ After exhausting retries, the last response is returned (for status errors)
+ or SandboxConnectionError is raised (for connection errors).
+ """
+
+ def __init__(
+ self,
+ *,
+ max_retries: int = 3,
+ transport: httpx.BaseTransport | None = None,
+ ) -> None:
+ self._transport = transport or httpx.HTTPTransport()
+ self._max_retries = max_retries
+
+ def handle_request(self, request: httpx.Request) -> httpx.Response:
+ last_response: httpx.Response | None = None
+
+ for attempt in range(self._max_retries + 1):
+ is_last_attempt = attempt == self._max_retries
+
+ try:
+ response = self._transport.handle_request(request)
+ last_response = response
+
+ if not is_last_attempt:
+ if response.status_code in RETRYABLE_STATUS_CODES:
+ response.close()
+ sleep_time = _compute_backoff(attempt)
+ logger.debug(
+ "Retrying %s %s (status %d, attempt %d/%d, sleeping %.1fs)",
+ request.method,
+ request.url,
+ response.status_code,
+ attempt + 1,
+ self._max_retries,
+ sleep_time,
+ )
+ time.sleep(sleep_time)
+ continue
+
+ if response.status_code == 429:
+ retry_after = _parse_retry_after(response)
+ sleep_time = retry_after * 2**attempt + random.random()
+ response.close()
+ logger.debug(
+ "Rate limited on %s %s, retrying after %.1fs "
+ "(attempt %d/%d)",
+ request.method,
+ request.url,
+ sleep_time,
+ attempt + 1,
+ self._max_retries,
+ )
+ time.sleep(sleep_time)
+ continue
+
+ return response
+
+ except httpx.ConnectError as exc:
+ if not is_last_attempt:
+ sleep_time = _compute_backoff(attempt)
+ logger.debug(
+ "Connection error on %s %s, retrying "
+ "(attempt %d/%d, sleeping %.1fs): %s",
+ request.method,
+ request.url,
+ attempt + 1,
+ self._max_retries,
+ sleep_time,
+ exc,
+ )
+ time.sleep(sleep_time)
+ continue
+ raise SandboxConnectionError(
+ f"Failed to connect to server after "
+ f"{self._max_retries + 1} attempts: {exc}"
+ ) from exc
+
+ assert last_response is not None
+ return last_response
+
+ def close(self) -> None:
+ self._transport.close()
+
+
+class AsyncRetryTransport(httpx.AsyncBaseTransport):
+ """Async httpx transport that retries on transient errors.
+
+ Async equivalent of RetryTransport. See RetryTransport for details.
+ """
+
+ def __init__(
+ self,
+ *,
+ max_retries: int = 3,
+ transport: httpx.AsyncBaseTransport | None = None,
+ ) -> None:
+ self._transport = transport or httpx.AsyncHTTPTransport()
+ self._max_retries = max_retries
+
+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
+ last_response: httpx.Response | None = None
+
+ for attempt in range(self._max_retries + 1):
+ is_last_attempt = attempt == self._max_retries
+
+ try:
+ response = await self._transport.handle_async_request(request)
+ last_response = response
+
+ if not is_last_attempt:
+ if response.status_code in RETRYABLE_STATUS_CODES:
+ await response.aclose()
+ sleep_time = _compute_backoff(attempt)
+ logger.debug(
+ "Retrying %s %s (status %d, attempt %d/%d, sleeping %.1fs)",
+ request.method,
+ request.url,
+ response.status_code,
+ attempt + 1,
+ self._max_retries,
+ sleep_time,
+ )
+ await asyncio.sleep(sleep_time)
+ continue
+
+ if response.status_code == 429:
+ retry_after = _parse_retry_after(response)
+ sleep_time = retry_after * 2**attempt + random.random()
+ await response.aclose()
+ logger.debug(
+ "Rate limited on %s %s, retrying after %.1fs "
+ "(attempt %d/%d)",
+ request.method,
+ request.url,
+ sleep_time,
+ attempt + 1,
+ self._max_retries,
+ )
+ await asyncio.sleep(sleep_time)
+ continue
+
+ return response
+
+ except httpx.ConnectError as exc:
+ if not is_last_attempt:
+ sleep_time = _compute_backoff(attempt)
+ logger.debug(
+ "Connection error on %s %s, retrying "
+ "(attempt %d/%d, sleeping %.1fs): %s",
+ request.method,
+ request.url,
+ attempt + 1,
+ self._max_retries,
+ sleep_time,
+ exc,
+ )
+ await asyncio.sleep(sleep_time)
+ continue
+ raise SandboxConnectionError(
+ f"Failed to connect to server after "
+ f"{self._max_retries + 1} attempts: {exc}"
+ ) from exc
+
+ assert last_response is not None
+ return last_response
+
+ async def aclose(self) -> None:
+ await self._transport.aclose()
+
+
+def _parse_retry_after(response: httpx.Response) -> float:
+ """Parse Retry-After header value, defaulting to 1.0 second."""
+ raw = response.headers.get("retry-after", "1")
+ try:
+ return max(float(raw), 0.0)
+ except (ValueError, TypeError):
+ return 1.0
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_tunnel.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_tunnel.py
new file mode 100644
index 0000000000000000000000000000000000000000..80efdce55adf3a42e9f407bad50cbaf6db697e5d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_tunnel.py
@@ -0,0 +1,484 @@
+"""TCP tunnel for accessing services running inside sandboxes.
+
+Establishes a WebSocket connection to the daemon's ``/tunnel`` endpoint,
+runs a yamux multiplexing session on top, and forwards local TCP connections
+through yamux streams to the target port inside the sandbox.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import socket
+import struct
+import threading
+import time
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, Optional
+
+from langsmith.sandbox._helpers import merge_headers
+
+if TYPE_CHECKING:
+ from langsmith.sandbox._yamux import YamuxSession, YamuxStream
+
+logger = logging.getLogger(__name__)
+
+# ---------------------------------------------------------------------------
+# Tunnel connect-header protocol (layered on top of yamux streams)
+# ---------------------------------------------------------------------------
+
+PROTOCOL_VERSION = 0x01
+
+STATUS_OK = 0x00
+STATUS_PORT_NOT_ALLOWED = 0x01
+STATUS_DIAL_FAILED = 0x02
+STATUS_UNSUPPORTED_VERSION = 0x03
+
+_CONNECT_HEADER_FMT = ">BH" # version(1) + port(2, big-endian)
+
+
+def _write_connect_header(stream: YamuxStream, port: int) -> None:
+ """Write the 3-byte connect header on a freshly opened yamux stream."""
+ stream.write(struct.pack(_CONNECT_HEADER_FMT, PROTOCOL_VERSION, port))
+
+
+def _read_status(stream: YamuxStream) -> int:
+ """Read the 1-byte status response from the daemon."""
+ data = stream.read(1)
+ if not data:
+ raise ConnectionError("tunnel: connection closed before status")
+ return data[0]
+
+
+# ---------------------------------------------------------------------------
+# WebSocket adapter
+# ---------------------------------------------------------------------------
+
+
+class _WSAdapter:
+ """Adapts the ``websockets`` message API to a byte-stream interface.
+
+ yamux requires a plain read/write/close byte stream. WebSocket is
+ message-based, so this adapter buffers partially consumed messages on
+ reads and sends one binary message per write.
+ """
+
+ def __init__(self, ws: Any) -> None:
+ self._ws = ws
+ self._buf = bytearray()
+ self._write_lock = threading.Lock()
+
+ def read(self, n: int) -> bytes:
+ while len(self._buf) < n:
+ msg = self._ws.recv()
+ if isinstance(msg, str):
+ msg = msg.encode()
+ self._buf.extend(msg)
+
+ result = bytes(self._buf[:n])
+ del self._buf[:n]
+ return result
+
+ def write(self, data: bytes) -> int:
+ with self._write_lock:
+ self._ws.send(data)
+ return len(data)
+
+ def close(self) -> None:
+ try:
+ self._ws.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------------
+# Bridge: bidirectional copy between yamux stream and TCP socket
+# ---------------------------------------------------------------------------
+
+_BRIDGE_BUF_SIZE = 16384
+
+
+def _bridge(stream: YamuxStream, tcp_conn: socket.socket) -> None:
+ """Copy data bidirectionally until one side closes or errors."""
+ done = threading.Event()
+
+ def _stream_to_tcp() -> None:
+ try:
+ while True:
+ data = stream.read(_BRIDGE_BUF_SIZE)
+ if not data:
+ break
+ tcp_conn.sendall(data)
+ except Exception:
+ pass
+ finally:
+ done.set()
+
+ def _tcp_to_stream() -> None:
+ try:
+ while True:
+ data = tcp_conn.recv(_BRIDGE_BUF_SIZE)
+ if not data:
+ break
+ stream.write(data)
+ except Exception:
+ pass
+ finally:
+ done.set()
+
+ t1 = threading.Thread(target=_stream_to_tcp, daemon=True)
+ t2 = threading.Thread(target=_tcp_to_stream, daemon=True)
+ t1.start()
+ t2.start()
+
+ done.wait()
+
+ try:
+ stream.close()
+ except Exception:
+ pass
+ try:
+ tcp_conn.shutdown(socket.SHUT_RDWR)
+ except OSError:
+ pass
+ try:
+ tcp_conn.close()
+ except OSError:
+ pass
+
+ t1.join(timeout=5)
+ t2.join(timeout=5)
+
+
+# ---------------------------------------------------------------------------
+# Tunnel
+# ---------------------------------------------------------------------------
+
+
+def _ensure_websockets():
+ """Import websockets sync client or raise a clear error."""
+ try:
+ from websockets.sync.client import connect as ws_connect
+
+ return ws_connect
+ except ImportError:
+ raise ImportError(
+ "TCP tunnel requires the 'websockets' package. "
+ "Install it with: pip install 'langsmith[sandbox]'"
+ ) from None
+
+
+class Tunnel:
+ """TCP tunnel to a port inside a sandbox.
+
+ Opens a local TCP listener and forwards each accepted connection through
+ a yamux-multiplexed WebSocket to the daemon, which dials the target port
+ inside the sandbox.
+
+ Typically used as a context manager::
+
+ with sandbox.tunnel(remote_port=5432) as t:
+ conn = psycopg2.connect(host="127.0.0.1", port=t.local_port)
+
+ Or with explicit lifecycle::
+
+ t = sandbox.tunnel(remote_port=5432)
+ # ... use tunnel ...
+ t.close()
+ """
+
+ _BACKOFF_BASE = 0.5
+ _BACKOFF_MAX = 8.0
+
+ def __init__(
+ self,
+ dataplane_url: str,
+ api_key: Optional[str],
+ remote_port: int,
+ *,
+ local_port: int = 0,
+ max_reconnects: int = 3,
+ headers: Optional[Mapping[str, str]] = None,
+ ) -> None:
+ self._dataplane_url = dataplane_url
+ self._api_key = api_key
+ self._headers = headers
+ self._remote_port = remote_port
+ self._requested_local_port = local_port or remote_port
+ self._local_port = self._requested_local_port
+ self._max_reconnects = max_reconnects
+
+ self._ws: object = None
+ self._yamux: Optional[YamuxSession] = None
+ self._server_socket: Optional[socket.socket] = None
+ self._accept_thread: Optional[threading.Thread] = None
+ self._reconnect_lock = threading.Lock()
+ self._closed = False
+ self._started = False
+
+ @property
+ def local_port(self) -> int:
+ """Local port the tunnel is listening on."""
+ return self._local_port
+
+ @property
+ def remote_port(self) -> int:
+ """Port inside the sandbox that the tunnel connects to."""
+ return self._remote_port
+
+ # -- Context manager ----------------------------------------------------
+
+ def __enter__(self) -> Tunnel:
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ self.close()
+
+ # -- Lifecycle ----------------------------------------------------------
+
+ def _start(self) -> None:
+ if self._started:
+ return
+ self._started = True
+
+ try:
+ self._do_start()
+ except Exception:
+ self.close()
+ raise
+
+ def _do_start(self) -> None:
+ self._connect()
+
+ self._server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self._server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+
+ # Check if another process is actively listening on this port.
+ # SO_REUSEADDR lets us rebind over TIME_WAIT, but we don't want to
+ # silently steal a port from a running service.
+ port = self._requested_local_port
+ if port != 0:
+ probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ probe.settimeout(0.5)
+ probe.connect(("127.0.0.1", port))
+ probe.close()
+ raise OSError(
+ f"Port {port} is already in use by another service. "
+ f"Choose a different local_port."
+ )
+ except ConnectionRefusedError:
+ pass # nothing listening — safe to bind
+ except OSError as e:
+ if "Connection refused" in str(e):
+ pass # same as above, different OS error message
+ elif "already in use" in str(e).lower():
+ raise
+ else:
+ pass # TIME_WAIT or other transient state — safe to bind
+ finally:
+ try:
+ probe.close()
+ except OSError:
+ pass
+
+ self._server_socket.bind(("127.0.0.1", self._requested_local_port))
+ self._server_socket.listen(128)
+ self._local_port = self._server_socket.getsockname()[1]
+
+ self._accept_thread = threading.Thread(
+ target=self._accept_loop, daemon=True, name="tunnel-accept"
+ )
+ self._accept_thread.start()
+
+ def _connect(self) -> None:
+ """Establish (or re-establish) the WebSocket + yamux session."""
+ from langsmith.sandbox._yamux import YamuxSession
+
+ old_yamux = self._yamux
+ if old_yamux:
+ try:
+ old_yamux.close()
+ except Exception:
+ pass
+
+ ws_connect = _ensure_websockets()
+ ws_url = self._build_ws_url()
+ headers = merge_headers(
+ {"X-Api-Key": self._api_key} if self._api_key else None,
+ self._headers,
+ )
+
+ self._ws = ws_connect(
+ ws_url,
+ additional_headers=headers,
+ open_timeout=15,
+ close_timeout=5,
+ ping_interval=None, # yamux handles keepalive
+ )
+
+ adapter = _WSAdapter(self._ws)
+ self._yamux = YamuxSession(adapter)
+
+ def _ensure_session(self) -> YamuxSession:
+ """Return a live yamux session, reconnecting if needed."""
+ from langsmith.sandbox._exceptions import TunnelError
+
+ if self._yamux and not self._yamux.is_closed:
+ return self._yamux
+
+ with self._reconnect_lock:
+ if self._yamux and not self._yamux.is_closed:
+ return self._yamux
+
+ last_err: Optional[Exception] = None
+ for attempt in range(self._max_reconnects):
+ try:
+ self._connect()
+ logger.debug("tunnel: reconnected (attempt %d)", attempt + 1)
+ return self._yamux # type: ignore[return-value]
+ except Exception as exc:
+ last_err = exc
+ if attempt < self._max_reconnects - 1:
+ delay = min(
+ self._BACKOFF_BASE * (2**attempt),
+ self._BACKOFF_MAX,
+ )
+ time.sleep(delay)
+
+ raise TunnelError(
+ f"tunnel: reconnect failed after {self._max_reconnects} attempts"
+ ) from last_err
+
+ def close(self) -> None:
+ """Shut down the tunnel, closing all connections."""
+ if self._closed:
+ return
+ self._closed = True
+
+ if self._server_socket:
+ try:
+ self._server_socket.close()
+ except OSError:
+ pass
+
+ if self._yamux:
+ self._yamux.close()
+
+ # -- Internal -----------------------------------------------------------
+
+ def _accept_loop(self) -> None:
+ while not self._closed:
+ try:
+ conn, _ = self._server_socket.accept() # type: ignore[union-attr]
+ except OSError:
+ break
+ threading.Thread(
+ target=self._handle_conn,
+ args=(conn,),
+ daemon=True,
+ name="tunnel-bridge",
+ ).start()
+
+ def _handle_conn(self, tcp_conn: socket.socket) -> None:
+ try:
+ session = self._ensure_session()
+ stream = session.open_stream()
+ _write_connect_header(stream, self._remote_port)
+ status = _read_status(stream)
+
+ if status == STATUS_OK:
+ _bridge(stream, tcp_conn)
+ return
+
+ stream.close()
+ tcp_conn.close()
+
+ if status == STATUS_PORT_NOT_ALLOWED:
+ logger.warning(
+ "tunnel: port %d not allowed by daemon",
+ self._remote_port,
+ )
+ elif status == STATUS_DIAL_FAILED:
+ logger.warning(
+ "tunnel: nothing listening on port %d inside sandbox",
+ self._remote_port,
+ )
+ elif status == STATUS_UNSUPPORTED_VERSION:
+ logger.warning(
+ "tunnel: protocol version mismatch (client v%d)",
+ PROTOCOL_VERSION,
+ )
+ else:
+ logger.warning("tunnel: unknown status %d", status)
+
+ except Exception as exc:
+ logger.debug("tunnel: connection handler error: %s", exc)
+ try:
+ tcp_conn.close()
+ except OSError:
+ pass
+
+ def _build_ws_url(self) -> str:
+ url = self._dataplane_url.rstrip("/")
+ url = url.replace("https://", "wss://").replace("http://", "ws://")
+ return f"{url}/tunnel"
+
+
+# ---------------------------------------------------------------------------
+# AsyncTunnel
+# ---------------------------------------------------------------------------
+
+
+class AsyncTunnel:
+ """Async wrapper around :class:`Tunnel`.
+
+ The underlying tunnel runs in background threads (TCP listener + bridges);
+ async context-manager methods delegate to the sync tunnel via the event
+ loop's executor.
+
+ Usage::
+
+ async with await sandbox.tunnel(remote_port=5432) as t:
+ conn = await asyncpg.connect(host="127.0.0.1", port=t.local_port)
+ """
+
+ def __init__(
+ self,
+ dataplane_url: str,
+ api_key: Optional[str],
+ remote_port: int,
+ *,
+ local_port: int = 0,
+ max_reconnects: int = 3,
+ headers: Optional[Mapping[str, str]] = None,
+ ) -> None:
+ self._tunnel = Tunnel(
+ dataplane_url,
+ api_key,
+ remote_port,
+ local_port=local_port,
+ max_reconnects=max_reconnects,
+ headers=headers,
+ )
+
+ @property
+ def local_port(self) -> int:
+ return self._tunnel.local_port
+
+ @property
+ def remote_port(self) -> int:
+ return self._tunnel.remote_port
+
+ async def __aenter__(self) -> AsyncTunnel:
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(None, self._tunnel._start)
+ return self
+
+ async def __aexit__(self, *args: object) -> None:
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(None, self._tunnel.close)
+
+ def close(self) -> None:
+ """Shut down the tunnel (sync, safe to call from any context)."""
+ self._tunnel.close()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_ws_execute.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_ws_execute.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a2ba98629d49aaaae2d585f6608492372ac8782
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_ws_execute.py
@@ -0,0 +1,565 @@
+"""WebSocket-based command execution for long-running commands."""
+
+from __future__ import annotations
+
+import json
+from collections.abc import AsyncIterator, Iterator, Mapping
+from typing import Any, Callable, Optional
+
+from langsmith.sandbox._exceptions import (
+ CommandTimeoutError,
+ SandboxConnectionError,
+ SandboxOperationError,
+ SandboxServerReloadError,
+)
+from langsmith.sandbox._helpers import merge_headers
+
+
+def _ensure_websockets():
+ """Import websockets or raise a clear error."""
+ try:
+ from websockets.exceptions import ConnectionClosed, InvalidStatus
+ from websockets.sync.client import connect as ws_connect
+
+ return ws_connect, ConnectionClosed, InvalidStatus
+ except ImportError:
+ raise ImportError(
+ "WebSocket-based execution requires the 'websockets' package. "
+ "Install it with: pip install 'langsmith[sandbox]'"
+ ) from None
+
+
+def _ensure_websockets_async():
+ """Import async websockets or raise a clear error."""
+ try:
+ from websockets.asyncio.client import connect as ws_connect_async
+ from websockets.exceptions import ConnectionClosed, InvalidStatus
+
+ return ws_connect_async, ConnectionClosed, InvalidStatus
+ except ImportError:
+ raise ImportError(
+ "WebSocket-based execution requires the 'websockets' package. "
+ "Install it with: pip install 'langsmith[sandbox]'"
+ ) from None
+
+
+def _build_ws_url(dataplane_url: str) -> str:
+ """Convert dataplane HTTP URL to WebSocket URL for /execute/ws."""
+ ws_url = dataplane_url.replace("https://", "wss://").replace("http://", "ws://")
+ return f"{ws_url}/execute/ws"
+
+
+def _build_auth_headers(
+ api_key: Optional[str], headers: Optional[Mapping[str, str]] = None
+) -> dict[str, str]:
+ """Build auth headers for the WebSocket upgrade request."""
+ auth_headers = {"X-Api-Key": api_key} if api_key else None
+ return merge_headers(auth_headers, headers)
+
+
+# =============================================================================
+# Stream Control
+# =============================================================================
+
+
+class _WSStreamControl:
+ """Control interface for an active WebSocket stream.
+
+ Created before the generator starts, bound to the WebSocket once
+ the connection opens. The CommandHandle holds a reference to this
+ object to send kill/input messages.
+
+ Thread safety: websockets' sync client supports send() from one
+ thread while recv() runs on another. So kill() from user code
+ and iteration on a different thread are safe.
+ """
+
+ def __init__(self) -> None:
+ self._ws: Any = None
+ self._closed = False
+ self._killed = False
+
+ def _bind(self, ws: Any) -> None:
+ """Bind to the active WebSocket. Called inside the generator."""
+ self._ws = ws
+
+ def _unbind(self) -> None:
+ """Mark as closed. Called when the generator exits."""
+ self._closed = True
+ self._ws = None
+
+ @property
+ def killed(self) -> bool:
+ """True if kill() has been called on this stream."""
+ return self._killed
+
+ def send_kill(self) -> None:
+ """Send a kill message and immediately close the WebSocket."""
+ self._killed = True
+ if self._ws and not self._closed:
+ try:
+ self._ws.send(json.dumps({"type": "kill"}))
+ except Exception:
+ pass
+ try:
+ self._ws.close_timeout = 0
+ self._ws.close()
+ except Exception:
+ pass
+
+ def send_input(self, data: str) -> None:
+ """Send stdin data to the running command."""
+ if self._ws and not self._closed:
+ self._ws.send(json.dumps({"type": "input", "data": data}))
+
+
+class _AsyncWSStreamControl:
+ """Async equivalent of _WSStreamControl."""
+
+ def __init__(self) -> None:
+ self._ws: Any = None
+ self._closed = False
+ self._killed = False
+
+ def _bind(self, ws: Any) -> None:
+ self._ws = ws
+
+ def _unbind(self) -> None:
+ self._closed = True
+ self._ws = None
+
+ @property
+ def killed(self) -> bool:
+ return self._killed
+
+ async def send_kill(self) -> None:
+ self._killed = True
+ if self._ws and not self._closed:
+ try:
+ await self._ws.send(json.dumps({"type": "kill"}))
+ except Exception:
+ pass
+ try:
+ self._ws.close_timeout = 0
+ await self._ws.close()
+ except Exception:
+ pass
+
+ async def send_input(self, data: str) -> None:
+ if self._ws and not self._closed:
+ await self._ws.send(json.dumps({"type": "input", "data": data}))
+
+
+# =============================================================================
+# Error Handling
+# =============================================================================
+
+
+def _raise_for_invalid_status(exc: Exception, ws_url: str) -> None:
+ """Raise a clear error when the server rejects the WebSocket upgrade.
+
+ The most common case is HTTP 404 — the server doesn't have the
+ /execute/ws endpoint, meaning it doesn't support WebSocket streaming.
+ """
+ status = getattr(getattr(exc, "response", None), "status_code", None)
+ if status == 404:
+ raise SandboxConnectionError(
+ f"The sandbox server does not support WebSocket command execution "
+ f"(endpoint {ws_url} returned 404). Ensure the server is updated "
+ f"to a version that supports the /execute/ws endpoint, or use "
+ f"run() without wait=False or callbacks."
+ ) from exc
+ # For other HTTP status codes, include the status in the message
+ raise SandboxConnectionError(
+ f"WebSocket upgrade rejected by server (HTTP {status}): {exc}"
+ ) from exc
+
+
+def _raise_from_error_msg(msg: dict, *, command_id: str = "") -> None:
+ """Raise the appropriate exception from a server error message."""
+ error_type = msg.get("error_type", "CommandError")
+ error_msg = msg.get("error", "Unknown error")
+
+ if error_type == "CommandTimeout":
+ raise CommandTimeoutError(error_msg)
+ if error_type == "CommandNotFound":
+ raise SandboxOperationError(
+ f"Command not found: {command_id}" if command_id else error_msg,
+ operation="reconnect" if command_id else "command",
+ error_type=error_type,
+ )
+ if error_type == "SessionExpired":
+ raise SandboxOperationError(
+ f"Session expired: {command_id}" if command_id else error_msg,
+ operation="reconnect" if command_id else "command",
+ error_type=error_type,
+ )
+
+ raise SandboxOperationError(
+ error_msg,
+ operation="reconnect" if command_id else "command",
+ error_type=error_type,
+ )
+
+
+# =============================================================================
+# Sync Stream Functions
+# =============================================================================
+
+
+def run_ws_stream(
+ dataplane_url: str,
+ api_key: Optional[str],
+ command: str,
+ *,
+ timeout: int = 60,
+ env: Optional[dict[str, str]] = None,
+ cwd: Optional[str] = None,
+ shell: str = "/bin/bash",
+ on_stdout: Optional[Callable[[str], Any]] = None,
+ on_stderr: Optional[Callable[[str], Any]] = None,
+ idle_timeout: int = 300,
+ kill_on_disconnect: bool = False,
+ ttl_seconds: int = 600,
+ pty: bool = False,
+ headers: Optional[Mapping[str, str]] = None,
+) -> tuple[Iterator[dict], _WSStreamControl]:
+ """Execute a command over WebSocket, yielding raw message dicts.
+
+ Returns a tuple of (message_iterator, control). The control object
+ provides send_kill() and send_input() methods for the CommandHandle.
+
+ The iterator yields dicts with a "type" field:
+ - {"type": "started", "command_id": "...", "pid": N}
+ - {"type": "stdout", "data": "...", "offset": N}
+ - {"type": "stderr", "data": "...", "offset": N}
+ - {"type": "exit", "exit_code": N}
+
+ If on_stdout/on_stderr callbacks are provided, they are invoked as
+ data arrives in addition to yielding the messages.
+ """
+ ws_connect, ConnectionClosed, InvalidStatus = _ensure_websockets()
+ ws_url = _build_ws_url(dataplane_url)
+ request_headers = _build_auth_headers(api_key, headers)
+ control = _WSStreamControl()
+
+ def _stream() -> Iterator[dict]:
+ try:
+ with ws_connect(
+ ws_url,
+ additional_headers=request_headers,
+ open_timeout=30,
+ close_timeout=10,
+ ping_interval=30,
+ ping_timeout=60,
+ ) as ws:
+ control._bind(ws)
+
+ # Send execute request
+ payload: dict[str, Any] = {
+ "type": "execute",
+ "command": command,
+ "timeout_seconds": timeout,
+ "shell": shell,
+ "idle_timeout_seconds": idle_timeout,
+ "kill_on_disconnect": kill_on_disconnect,
+ "ttl_seconds": ttl_seconds,
+ }
+ if env:
+ payload["env"] = env
+ if cwd:
+ payload["cwd"] = cwd
+ if pty:
+ payload["pty"] = True
+ ws.send(json.dumps(payload))
+
+ # Read messages until exit or error
+ for raw_msg in ws:
+ msg = json.loads(raw_msg)
+ msg_type = msg.get("type")
+
+ if msg_type == "started":
+ yield msg
+
+ elif msg_type == "stdout":
+ if on_stdout:
+ on_stdout(msg["data"])
+ yield msg
+
+ elif msg_type == "stderr":
+ if on_stderr:
+ on_stderr(msg["data"])
+ yield msg
+
+ elif msg_type == "exit":
+ yield msg
+ return
+
+ elif msg_type == "error":
+ _raise_from_error_msg(msg)
+
+ except InvalidStatus as e:
+ _raise_for_invalid_status(e, ws_url)
+ except ConnectionClosed as e:
+ if e.rcvd and e.rcvd.code == 1001:
+ raise SandboxServerReloadError(
+ "Server is reloading, reconnect to resume"
+ ) from e
+ raise SandboxConnectionError(
+ f"WebSocket connection closed unexpectedly: {e}"
+ ) from e
+ except OSError as e:
+ raise SandboxConnectionError(f"Failed to connect to sandbox: {e}") from e
+ finally:
+ control._unbind()
+
+ return _stream(), control
+
+
+def reconnect_ws_stream(
+ dataplane_url: str,
+ api_key: Optional[str],
+ command_id: str,
+ *,
+ stdout_offset: int = 0,
+ stderr_offset: int = 0,
+ headers: Optional[Mapping[str, str]] = None,
+) -> tuple[Iterator[dict], _WSStreamControl]:
+ """Reconnect to an existing command over WebSocket.
+
+ Returns a tuple of (message_iterator, control), same as run_ws_stream.
+ The iterator yields stdout, stderr, exit, and error messages.
+ No 'started' message is sent on reconnection.
+
+ With the ring buffer reader server model, there is no replay/live
+ phase distinction and no deduplication needed. The server reads from
+ its ring buffer starting at the requested offsets and streams output
+ from there. If the requested offset is older than the buffer's
+ earliest data, the server sends from the earliest available offset.
+ """
+ ws_connect, ConnectionClosed, InvalidStatus = _ensure_websockets()
+ ws_url = _build_ws_url(dataplane_url)
+ request_headers = _build_auth_headers(api_key, headers)
+ control = _WSStreamControl()
+
+ def _stream() -> Iterator[dict]:
+ try:
+ with ws_connect(
+ ws_url,
+ additional_headers=request_headers,
+ open_timeout=30,
+ close_timeout=10,
+ ping_interval=30,
+ ping_timeout=60,
+ ) as ws:
+ control._bind(ws)
+
+ # Send reconnect request
+ ws.send(
+ json.dumps(
+ {
+ "type": "reconnect",
+ "command_id": command_id,
+ "stdout_offset": stdout_offset,
+ "stderr_offset": stderr_offset,
+ }
+ )
+ )
+
+ # Read messages until exit or error
+ for raw_msg in ws:
+ msg = json.loads(raw_msg)
+ msg_type = msg.get("type")
+
+ if msg_type in ("stdout", "stderr"):
+ yield msg
+
+ elif msg_type == "exit":
+ yield msg
+ return
+
+ elif msg_type == "error":
+ _raise_from_error_msg(msg, command_id=command_id)
+
+ except InvalidStatus as e:
+ _raise_for_invalid_status(e, ws_url)
+ except ConnectionClosed as e:
+ if e.rcvd and e.rcvd.code == 1001:
+ raise SandboxServerReloadError(
+ "Server is reloading, reconnect to resume"
+ ) from e
+ raise SandboxConnectionError(
+ f"WebSocket connection closed unexpectedly: {e}"
+ ) from e
+ except OSError as e:
+ raise SandboxConnectionError(f"Failed to connect to sandbox: {e}") from e
+ finally:
+ control._unbind()
+
+ return _stream(), control
+
+
+# =============================================================================
+# Async Stream Functions
+# =============================================================================
+
+
+async def run_ws_stream_async(
+ dataplane_url: str,
+ api_key: Optional[str],
+ command: str,
+ *,
+ timeout: int = 60,
+ env: Optional[dict[str, str]] = None,
+ cwd: Optional[str] = None,
+ shell: str = "/bin/bash",
+ on_stdout: Optional[Callable[[str], Any]] = None,
+ on_stderr: Optional[Callable[[str], Any]] = None,
+ idle_timeout: int = 300,
+ kill_on_disconnect: bool = False,
+ ttl_seconds: int = 600,
+ pty: bool = False,
+ headers: Optional[Mapping[str, str]] = None,
+) -> tuple[AsyncIterator[dict], _AsyncWSStreamControl]:
+ """Async equivalent of run_ws_stream.
+
+ Returns (async_message_iterator, async_control).
+ """
+ ws_connect_async, ConnectionClosed, InvalidStatus = _ensure_websockets_async()
+ ws_url = _build_ws_url(dataplane_url)
+ request_headers = _build_auth_headers(api_key, headers)
+ control = _AsyncWSStreamControl()
+
+ async def _stream() -> AsyncIterator[dict]:
+ try:
+ async with ws_connect_async(
+ ws_url,
+ additional_headers=request_headers,
+ open_timeout=30,
+ close_timeout=10,
+ ping_interval=30,
+ ping_timeout=60,
+ ) as ws:
+ control._bind(ws)
+
+ payload: dict[str, Any] = {
+ "type": "execute",
+ "command": command,
+ "timeout_seconds": timeout,
+ "shell": shell,
+ "idle_timeout_seconds": idle_timeout,
+ "kill_on_disconnect": kill_on_disconnect,
+ "ttl_seconds": ttl_seconds,
+ }
+ if env:
+ payload["env"] = env
+ if cwd:
+ payload["cwd"] = cwd
+ if pty:
+ payload["pty"] = True
+ await ws.send(json.dumps(payload))
+
+ async for raw_msg in ws:
+ msg = json.loads(raw_msg)
+ msg_type = msg.get("type")
+
+ if msg_type == "started":
+ yield msg
+ elif msg_type == "stdout":
+ if on_stdout:
+ on_stdout(msg["data"])
+ yield msg
+ elif msg_type == "stderr":
+ if on_stderr:
+ on_stderr(msg["data"])
+ yield msg
+ elif msg_type == "exit":
+ yield msg
+ return
+ elif msg_type == "error":
+ _raise_from_error_msg(msg)
+
+ except InvalidStatus as e:
+ _raise_for_invalid_status(e, ws_url)
+ except ConnectionClosed as e:
+ if e.rcvd and e.rcvd.code == 1001:
+ raise SandboxServerReloadError(
+ "Server is reloading, reconnect to resume"
+ ) from e
+ raise SandboxConnectionError(
+ f"WebSocket connection closed unexpectedly: {e}"
+ ) from e
+ except OSError as e:
+ raise SandboxConnectionError(f"Failed to connect to sandbox: {e}") from e
+ finally:
+ control._unbind()
+
+ return _stream(), control
+
+
+async def reconnect_ws_stream_async(
+ dataplane_url: str,
+ api_key: Optional[str],
+ command_id: str,
+ *,
+ stdout_offset: int = 0,
+ stderr_offset: int = 0,
+ headers: Optional[Mapping[str, str]] = None,
+) -> tuple[AsyncIterator[dict], _AsyncWSStreamControl]:
+ """Async equivalent of reconnect_ws_stream."""
+ ws_connect_async, ConnectionClosed, InvalidStatus = _ensure_websockets_async()
+ ws_url = _build_ws_url(dataplane_url)
+ request_headers = _build_auth_headers(api_key, headers)
+ control = _AsyncWSStreamControl()
+
+ async def _stream() -> AsyncIterator[dict]:
+ try:
+ async with ws_connect_async(
+ ws_url,
+ additional_headers=request_headers,
+ open_timeout=30,
+ close_timeout=10,
+ ping_interval=30,
+ ping_timeout=60,
+ ) as ws:
+ control._bind(ws)
+
+ await ws.send(
+ json.dumps(
+ {
+ "type": "reconnect",
+ "command_id": command_id,
+ "stdout_offset": stdout_offset,
+ "stderr_offset": stderr_offset,
+ }
+ )
+ )
+
+ async for raw_msg in ws:
+ msg = json.loads(raw_msg)
+ msg_type = msg.get("type")
+
+ if msg_type in ("stdout", "stderr"):
+ yield msg
+ elif msg_type == "exit":
+ yield msg
+ return
+ elif msg_type == "error":
+ _raise_from_error_msg(msg, command_id=command_id)
+
+ except InvalidStatus as e:
+ _raise_for_invalid_status(e, ws_url)
+ except ConnectionClosed as e:
+ if e.rcvd and e.rcvd.code == 1001:
+ raise SandboxServerReloadError(
+ "Server is reloading, reconnect to resume"
+ ) from e
+ raise SandboxConnectionError(
+ f"WebSocket connection closed unexpectedly: {e}"
+ ) from e
+ except OSError as e:
+ raise SandboxConnectionError(f"Failed to connect to sandbox: {e}") from e
+ finally:
+ control._unbind()
+
+ return _stream(), control
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_yamux.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_yamux.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ccfd0add8b3d7f9e84aa10f1a6ef28a96d14100
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/sandbox/_yamux.py
@@ -0,0 +1,354 @@
+"""Minimal yamux (Yet Another Multiplexer) client for TCP tunneling.
+
+Implements the client side of the yamux protocol as specified at
+https://github.com/hashicorp/yamux/blob/master/spec.md
+
+Only the subset needed for tunnel client operation is implemented:
+opening streams, sending/receiving data, flow control, and keepalive.
+"""
+
+from __future__ import annotations
+
+import struct
+import threading
+from typing import Protocol
+
+# ---------------------------------------------------------------------------
+# Protocol constants
+# ---------------------------------------------------------------------------
+
+_VERSION = 0
+
+_TYPE_DATA = 0
+_TYPE_WINDOW_UPDATE = 1
+_TYPE_PING = 2
+_TYPE_GO_AWAY = 3
+
+_FLAG_SYN = 0x0001
+_FLAG_ACK = 0x0002
+_FLAG_FIN = 0x0004
+_FLAG_RST = 0x0008
+
+_HEADER_SIZE = 12
+_HEADER_FMT = ">BBHII" # version(1), type(1), flags(2), streamID(4), length(4)
+
+_INITIAL_WINDOW_SIZE = 256 * 1024 # 256 KB
+
+
+# ---------------------------------------------------------------------------
+# Byte-stream interface required by the session
+# ---------------------------------------------------------------------------
+
+
+class _ReadWriteCloser(Protocol):
+ def read(self, n: int) -> bytes: ...
+
+ def write(self, data: bytes) -> int: ...
+
+ def close(self) -> None: ...
+
+
+# ---------------------------------------------------------------------------
+# YamuxStream
+# ---------------------------------------------------------------------------
+
+
+class YamuxStream:
+ """A single multiplexed stream within a yamux session.
+
+ Streams are created via :meth:`YamuxSession.open_stream` and provide
+ blocking read/write/close with per-stream flow control.
+ """
+
+ def __init__(self, stream_id: int, session: YamuxSession) -> None:
+ self._id = stream_id
+ self._session = session
+
+ self._recv_buf = bytearray()
+ self._recv_cond = threading.Condition()
+ self._recv_closed = False
+ self._recv_error = False
+ self._recv_window = _INITIAL_WINDOW_SIZE
+
+ self._send_window = _INITIAL_WINDOW_SIZE
+ self._send_cond = threading.Condition()
+ self._send_closed = False
+
+ @property
+ def stream_id(self) -> int:
+ return self._id
+
+ def read(self, n: int) -> bytes:
+ """Read up to *n* bytes, blocking until data is available.
+
+ Returns ``b""`` on EOF (FIN received).
+ Raises :class:`ConnectionResetError` on RST.
+ """
+ delta_to_send = 0
+
+ with self._recv_cond:
+ while not self._recv_buf and not self._recv_closed and not self._recv_error:
+ self._recv_cond.wait()
+
+ if self._recv_error and not self._recv_buf:
+ raise ConnectionResetError("yamux stream reset by peer")
+
+ if not self._recv_buf:
+ return b""
+
+ size = min(n, len(self._recv_buf))
+ data = bytes(self._recv_buf[:size])
+ del self._recv_buf[:size]
+
+ consumed = _INITIAL_WINDOW_SIZE - self._recv_window
+ if consumed >= _INITIAL_WINDOW_SIZE // 2:
+ delta_to_send = consumed
+ self._recv_window += consumed
+
+ if delta_to_send > 0:
+ try:
+ self._session._send_window_update(self._id, delta_to_send)
+ except Exception:
+ pass
+
+ return data
+
+ def write(self, data: bytes) -> int:
+ """Write *data*, blocking if the send window is exhausted."""
+ if self._send_closed:
+ raise BrokenPipeError("yamux stream closed for writing")
+
+ offset = 0
+ mv = memoryview(data)
+
+ while offset < len(data):
+ with self._send_cond:
+ while self._send_window == 0 and not self._send_closed:
+ self._send_cond.wait()
+ if self._send_closed:
+ raise BrokenPipeError("yamux stream closed for writing")
+ chunk = min(len(data) - offset, self._send_window)
+ self._send_window -= chunk
+
+ self._session._send_data(self._id, bytes(mv[offset : offset + chunk]))
+ offset += chunk
+
+ return len(data)
+
+ def close(self) -> None:
+ """Close the stream (sends FIN to the remote end)."""
+ if not self._send_closed:
+ self._send_closed = True
+ try:
+ self._session._send_frame(_TYPE_DATA, _FLAG_FIN, self._id, 0)
+ except Exception:
+ pass
+
+ with self._recv_cond:
+ self._recv_closed = True
+ self._recv_cond.notify_all()
+ with self._send_cond:
+ self._send_cond.notify_all()
+
+ # -- Internal: called by YamuxSession._read_loop ------------------------
+
+ def _receive_data(self, data: bytes) -> None:
+ with self._recv_cond:
+ self._recv_buf.extend(data)
+ self._recv_window -= len(data)
+ self._recv_cond.notify_all()
+
+ def _receive_fin(self) -> None:
+ with self._recv_cond:
+ self._recv_closed = True
+ self._recv_cond.notify_all()
+
+ def _receive_rst(self) -> None:
+ with self._recv_cond:
+ self._recv_error = True
+ self._recv_cond.notify_all()
+ with self._send_cond:
+ self._send_closed = True
+ self._send_cond.notify_all()
+
+ def _update_send_window(self, delta: int) -> None:
+ with self._send_cond:
+ self._send_window += delta
+ self._send_cond.notify_all()
+
+
+# ---------------------------------------------------------------------------
+# YamuxSession
+# ---------------------------------------------------------------------------
+
+
+class YamuxSession:
+ """Client-side yamux session over a byte-stream connection.
+
+ The connection must implement ``read(n) -> bytes``, ``write(data) -> int``,
+ and ``close() -> None``. Typically this is a :class:`_WSAdapter` wrapping
+ a WebSocket.
+
+ Usage::
+
+ session = YamuxSession(conn)
+ stream = session.open_stream()
+ stream.write(b"hello")
+ data = stream.read(1024)
+ stream.close()
+ session.close()
+ """
+
+ def __init__(self, conn: _ReadWriteCloser) -> None:
+ self._conn = conn
+ self._streams: dict[int, YamuxStream] = {}
+ self._next_stream_id = 1 # client uses odd IDs
+ self._lock = threading.Lock()
+ self._write_lock = threading.Lock()
+ self._closed = False
+ self._shutdown_event = threading.Event()
+
+ self._reader_thread = threading.Thread(
+ target=self._read_loop, daemon=True, name="yamux-reader"
+ )
+ self._reader_thread.start()
+
+ self._keepalive_thread = threading.Thread(
+ target=self._keepalive_loop, daemon=True, name="yamux-keepalive"
+ )
+ self._keepalive_thread.start()
+
+ @property
+ def is_closed(self) -> bool:
+ return self._closed
+
+ def open_stream(self) -> YamuxStream:
+ """Open a new multiplexed stream.
+
+ Raises :class:`RuntimeError` if the session is closed.
+ """
+ with self._lock:
+ if self._closed:
+ raise RuntimeError("yamux session is closed")
+ stream_id = self._next_stream_id
+ self._next_stream_id += 2
+ stream = YamuxStream(stream_id, self)
+ self._streams[stream_id] = stream
+
+ self._send_frame(_TYPE_WINDOW_UPDATE, _FLAG_SYN, stream_id, 0)
+ return stream
+
+ def close(self) -> None:
+ """Close the session and all streams."""
+ if self._closed:
+ return
+ self._closed = True
+ self._shutdown_event.set()
+
+ try:
+ self._send_frame(_TYPE_GO_AWAY, 0, 0, 0)
+ except Exception:
+ pass
+
+ with self._lock:
+ for stream in self._streams.values():
+ stream._receive_rst()
+
+ try:
+ self._conn.close()
+ except Exception:
+ pass
+
+ # -- Frame I/O ----------------------------------------------------------
+
+ def _send_frame(
+ self, msg_type: int, flags: int, stream_id: int, length: int
+ ) -> None:
+ hdr = struct.pack(_HEADER_FMT, _VERSION, msg_type, flags, stream_id, length)
+ with self._write_lock:
+ self._conn.write(hdr)
+
+ def _send_data(self, stream_id: int, data: bytes) -> None:
+ hdr = struct.pack(_HEADER_FMT, _VERSION, _TYPE_DATA, 0, stream_id, len(data))
+ with self._write_lock:
+ self._conn.write(hdr + data)
+
+ def _send_window_update(self, stream_id: int, delta: int) -> None:
+ self._send_frame(_TYPE_WINDOW_UPDATE, 0, stream_id, delta)
+
+ # -- Read loop ----------------------------------------------------------
+
+ def _read_loop(self) -> None:
+ try:
+ while not self._closed:
+ hdr_bytes = self._conn.read(_HEADER_SIZE)
+ if len(hdr_bytes) < _HEADER_SIZE:
+ break
+
+ _ver, msg_type, flags, stream_id, length = struct.unpack(
+ _HEADER_FMT, hdr_bytes
+ )
+
+ if msg_type == _TYPE_DATA:
+ self._handle_data(flags, stream_id, length)
+ elif msg_type == _TYPE_WINDOW_UPDATE:
+ self._handle_window_update(flags, stream_id, length)
+ elif msg_type == _TYPE_PING:
+ self._handle_ping(flags, length)
+ elif msg_type == _TYPE_GO_AWAY:
+ break
+ except Exception:
+ pass
+ finally:
+ if not self._closed:
+ self._closed = True
+ self._shutdown_event.set()
+ with self._lock:
+ for stream in self._streams.values():
+ stream._receive_rst()
+
+ def _handle_data(self, flags: int, stream_id: int, length: int) -> None:
+ payload = self._conn.read(length) if length > 0 else b""
+
+ with self._lock:
+ stream = self._streams.get(stream_id)
+ if stream is None:
+ return
+
+ if payload:
+ stream._receive_data(payload)
+ if flags & _FLAG_FIN:
+ stream._receive_fin()
+ if flags & _FLAG_RST:
+ stream._receive_rst()
+
+ def _handle_window_update(self, flags: int, stream_id: int, length: int) -> None:
+ with self._lock:
+ stream = self._streams.get(stream_id)
+ if stream is None:
+ return
+
+ if length > 0:
+ stream._update_send_window(length)
+ if flags & _FLAG_FIN:
+ stream._receive_fin()
+ if flags & _FLAG_RST:
+ stream._receive_rst()
+
+ def _handle_ping(self, flags: int, opaque: int) -> None:
+ if flags & _FLAG_SYN:
+ try:
+ self._send_frame(_TYPE_PING, _FLAG_ACK, 0, opaque)
+ except Exception:
+ pass
+
+ # -- Keepalive ----------------------------------------------------------
+
+ def _keepalive_loop(self) -> None:
+ ping_id = 0
+ while not self._shutdown_event.wait(30):
+ ping_id += 1
+ try:
+ self._send_frame(_TYPE_PING, _FLAG_SYN, 0, ping_id)
+ except Exception:
+ break
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/testing/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/testing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f64c1f687dc27941526d12b1f0e304bac9b75677
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/testing/__init__.py
@@ -0,0 +1,17 @@
+"""LangSmith pytest testing module."""
+
+from langsmith.testing._internal import (
+ log_feedback,
+ log_inputs,
+ log_outputs,
+ log_reference_outputs,
+ trace_feedback,
+)
+
+__all__ = [
+ "log_inputs",
+ "log_outputs",
+ "log_reference_outputs",
+ "log_feedback",
+ "trace_feedback",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/testing/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/testing/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c2200d74aa04010ffdcf8ba82a57a3d7275269d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/testing/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/testing/__pycache__/_internal.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/testing/__pycache__/_internal.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..971bfc56b57b6f076ef7a2053f905d00a407ece1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/testing/__pycache__/_internal.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/testing/_internal.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/testing/_internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..22ee38742be75e2ec2149952a235bb43ed37d39e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/testing/_internal.py
@@ -0,0 +1,1470 @@
+from __future__ import annotations
+
+import atexit
+import contextlib
+import contextvars
+import datetime
+import functools
+import hashlib
+import importlib
+import inspect
+import logging
+import os
+import threading
+import time
+import uuid
+import warnings
+from collections.abc import Generator, Sequence
+from concurrent.futures import Future
+from pathlib import Path
+from typing import (
+ Any,
+ Callable,
+ Optional,
+ TypeVar,
+ Union,
+ cast,
+ overload,
+)
+
+from typing_extensions import TypedDict
+
+from langsmith import client as ls_client
+from langsmith import env as ls_env
+from langsmith import run_helpers as rh
+from langsmith import run_trees
+from langsmith import run_trees as rt
+from langsmith import schemas as ls_schemas
+from langsmith import utils as ls_utils
+from langsmith._internal import _orjson
+from langsmith._internal._serde import dumps_json
+from langsmith.client import ID_TYPE
+
+try:
+ import pytest # type: ignore
+
+ SkipException = pytest.skip.Exception
+except ImportError:
+
+ class SkipException(Exception): # type: ignore[no-redef]
+ pass
+
+
+logger = logging.getLogger(__name__)
+
+# UUID5 namespace used for generating consistent example IDs
+UUID5_NAMESPACE = uuid.UUID("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
+
+T = TypeVar("T")
+U = TypeVar("U")
+
+
+def _object_hash(obj: Any) -> str:
+ """Hash an object to generate a consistent hash string."""
+ # Use the existing serialization infrastructure with consistent ordering
+ serialized = _stringify(obj)
+ return hashlib.sha256(serialized.encode()).hexdigest()
+
+
+@overload
+def test(
+ func: Callable,
+) -> Callable: ...
+
+
+@overload
+def test(
+ *,
+ id: Optional[uuid.UUID] = None,
+ output_keys: Optional[Sequence[str]] = None,
+ client: Optional[ls_client.Client] = None,
+ test_suite_name: Optional[str] = None,
+ metadata: Optional[dict] = None,
+ experiment_metadata: Optional[dict] = None,
+ repetitions: Optional[int] = None,
+ split: Optional[Union[str | list[str]]] = None,
+ cached_hosts: Optional[Sequence[str]] = None,
+) -> Callable[[Callable], Callable]: ...
+
+
+def test(*args: Any, **kwargs: Any) -> Callable:
+ """Trace a pytest test case in LangSmith.
+
+ This decorator is used to trace a pytest test to LangSmith. It ensures
+ that the necessary example data is created and associated with the test function.
+ The decorated function will be executed as a test case, and the results will be
+ recorded and reported by LangSmith.
+
+ Args:
+ - id (Optional[uuid.UUID]): A unique identifier for the test case. If not
+ provided, an ID will be generated based on the test function's module
+ and name.
+ - output_keys (Optional[Sequence[str]]): A list of keys to be considered as
+ the output keys for the test case. These keys will be extracted from the
+ test function's inputs and stored as the expected outputs.
+ - client (Optional[ls_client.Client]): An instance of the LangSmith client
+ to be used for communication with the LangSmith service. If not provided,
+ a default client will be used.
+ - test_suite_name (Optional[str]): The name of the test suite to which the
+ test case belongs. If not provided, the test suite name will be determined
+ based on the environment or the package name.
+ - cached_hosts (Optional[Sequence[str]]): A list of hosts or URL prefixes to
+ cache requests to during testing. If not provided, all requests will be
+ cached (default behavior). This is useful for caching only specific
+ API calls (e.g., ["api.openai.com"] or ["https://api.openai.com"]).
+
+ Returns:
+ Callable: The decorated test function.
+
+ Environment:
+ - `LANGSMITH_TEST_CACHE`: If set, API calls will be cached to disk to
+ save time and costs during testing. Recommended to commit the
+ cache files to your repository for faster CI/CD runs.
+ Requires the 'langsmith[vcr]' package to be installed.
+ - `LANGSMITH_TEST_TRACKING`: Set this variable to the path of a directory
+ to enable caching of test results. This is useful for re-running tests
+ without re-executing the code. Requires the 'langsmith[vcr]' package.
+
+ Example:
+ For basic usage, simply decorate a test function with `@pytest.mark.langsmith`.
+ Under the hood this will call the `test` method:
+
+ ```python
+ import pytest
+
+
+ # Equivalently can decorate with `test` directly:
+ # from langsmith import test
+ # @test
+ @pytest.mark.langsmith
+ def test_addition():
+ assert 3 + 4 == 7
+ ```
+
+
+ Any code that is traced (such as those traced using `@traceable`
+ or `wrap_*` functions) will be traced within the test case for
+ improved visibility and debugging.
+
+ ```python
+ import pytest
+ from langsmith import traceable
+
+
+ @traceable
+ def generate_numbers():
+ return 3, 4
+
+
+ @pytest.mark.langsmith
+ def test_nested():
+ # Traced code will be included in the test case
+ a, b = generate_numbers()
+ assert a + b == 7
+ ```
+
+ LLM calls are expensive! Cache requests by setting
+ `LANGSMITH_TEST_CACHE=path/to/cache`. Check in these files to speed up
+ CI/CD pipelines, so your results only change when your prompt or requested
+ model changes.
+
+ Note that this will require that you install langsmith with the `vcr` extra:
+
+ `pip install -U "langsmith[vcr]"`
+
+ Caching is faster if you install libyaml. See
+ https://vcrpy.readthedocs.io/en/latest/installation.html#speed for more details.
+
+ ```python
+ # os.environ["LANGSMITH_TEST_CACHE"] = "tests/cassettes"
+ import openai
+ import pytest
+ from langsmith import wrappers
+
+ oai_client = wrappers.wrap_openai(openai.Client())
+
+
+ @pytest.mark.langsmith
+ def test_openai_says_hello():
+ # Traced code will be included in the test case
+ response = oai_client.chat.completions.create(
+ model="gpt-3.5-turbo",
+ messages=[
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": "Say hello!"},
+ ],
+ )
+ assert "hello" in response.choices[0].message.content.lower()
+ ```
+
+ You can also specify which hosts to cache by using the `cached_hosts` parameter.
+ This is useful when you only want to cache specific API calls:
+
+ ```python
+ @pytest.mark.langsmith(cached_hosts=["https://api.openai.com"])
+ def test_openai_with_selective_caching():
+ # Only OpenAI API calls will be cached, other API calls will not
+ # be cached
+ response = oai_client.chat.completions.create(
+ model="gpt-3.5-turbo",
+ messages=[
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": "Say hello!"},
+ ],
+ )
+ assert "hello" in response.choices[0].message.content.lower()
+ ```
+
+ LLMs are stochastic. Naive assertions are flakey. You can use langsmith's
+ `expect` to score and make approximate assertions on your results.
+
+ ```python
+ import pytest
+ from langsmith import expect
+
+
+ @pytest.mark.langsmith
+ def test_output_semantically_close():
+ response = oai_client.chat.completions.create(
+ model="gpt-3.5-turbo",
+ messages=[
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": "Say hello!"},
+ ],
+ )
+ # The embedding_distance call logs the embedding distance to LangSmith
+ expect.embedding_distance(
+ prediction=response.choices[0].message.content,
+ reference="Hello!",
+ # The following optional assertion logs a
+ # pass/fail score to LangSmith
+ # and raises an AssertionError if the assertion fails.
+ ).to_be_less_than(1.0)
+ # Compute damerau_levenshtein distance
+ expect.edit_distance(
+ prediction=response.choices[0].message.content,
+ reference="Hello!",
+ # And then log a pass/fail score to LangSmith
+ ).to_be_less_than(1.0)
+ ```
+
+ The `@test` decorator works natively with pytest fixtures.
+ The values will populate the "inputs" of the corresponding example in LangSmith.
+
+ ```python
+ import pytest
+
+
+ @pytest.fixture
+ def some_input():
+ return "Some input"
+
+
+ @pytest.mark.langsmith
+ def test_with_fixture(some_input: str):
+ assert "input" in some_input
+ ```
+
+ You can still use `pytest.parametrize()` as usual to run multiple test cases
+ using the same test function.
+
+ ```python
+ import pytest
+
+
+ @pytest.mark.langsmith(output_keys=["expected"])
+ @pytest.mark.parametrize(
+ "a, b, expected",
+ [
+ (1, 2, 3),
+ (3, 4, 7),
+ ],
+ )
+ def test_addition_with_multiple_inputs(a: int, b: int, expected: int):
+ assert a + b == expected
+ ```
+
+ By default, each test case will be assigned a consistent, unique identifier
+ based on the function name and module. You can also provide a custom identifier
+ using the `id` argument:
+
+ ```python
+ import pytest
+ import uuid
+
+ example_id = uuid.uuid4()
+
+
+ @pytest.mark.langsmith(id=str(example_id))
+ def test_multiplication():
+ assert 3 * 4 == 12
+ ```
+
+ By default, all test inputs are saved as "inputs" to a dataset.
+ You can specify the `output_keys` argument to persist those keys
+ within the dataset's "outputs" fields.
+
+ ```python
+ import pytest
+
+
+ @pytest.fixture
+ def expected_output():
+ return "input"
+
+
+ @pytest.mark.langsmith(output_keys=["expected_output"])
+ def test_with_expected_output(some_input: str, expected_output: str):
+ assert expected_output in some_input
+ ```
+
+
+ To run these tests, use the pytest CLI. Or directly run the test functions.
+
+ ```python
+ test_output_semantically_close()
+ test_addition()
+ test_nested()
+ test_with_fixture("Some input")
+ test_with_expected_output("Some input", "Some")
+ test_multiplication()
+ test_openai_says_hello()
+ test_addition_with_multiple_inputs(1, 2, 3)
+ ```
+ """
+ cached_hosts = kwargs.pop("cached_hosts", None)
+ cache_dir = ls_utils.get_cache_dir(kwargs.pop("cache", None))
+
+ # Validate cached_hosts usage
+ if cached_hosts and not cache_dir:
+ raise ValueError(
+ "cached_hosts parameter requires caching to be enabled. "
+ "Please set the LANGSMITH_TEST_CACHE environment variable "
+ "to a cache directory path, "
+ "or pass a cache parameter to the test decorator. "
+ "Example: LANGSMITH_TEST_CACHE='tests/cassettes' "
+ "or @pytest.mark.langsmith(cache='tests/cassettes', cached_hosts=[...])"
+ )
+
+ langtest_extra = _UTExtra(
+ id=kwargs.pop("id", None),
+ output_keys=kwargs.pop("output_keys", None),
+ client=kwargs.pop("client", None),
+ test_suite_name=kwargs.pop("test_suite_name", None),
+ cache=cache_dir,
+ metadata=kwargs.pop("metadata", None),
+ experiment_metadata=kwargs.pop("experiment_metadata", None),
+ repetitions=kwargs.pop("repetitions", None),
+ split=kwargs.pop("split", None),
+ cached_hosts=cached_hosts,
+ )
+ if kwargs:
+ warnings.warn(f"Unexpected keyword arguments: {kwargs.keys()}")
+ disable_tracking = ls_utils.test_tracking_is_disabled()
+ if disable_tracking:
+ logger.info(
+ "LANGSMITH_TEST_TRACKING is set to 'false'."
+ " Skipping LangSmith test tracking."
+ )
+
+ def decorator(func: Callable) -> Callable:
+ # Handle repetitions
+ repetitions = langtest_extra.get("repetitions", 1) or 1
+
+ if inspect.iscoroutinefunction(func):
+
+ @functools.wraps(func)
+ async def async_wrapper(
+ *test_args: Any, request: Any = None, **test_kwargs: Any
+ ):
+ if disable_tracking:
+ return await func(*test_args, **test_kwargs)
+
+ # Run test multiple times for repetitions
+ for i in range(repetitions):
+ repetition_extra = langtest_extra.copy()
+ await _arun_test(
+ func,
+ *test_args,
+ pytest_request=request,
+ **test_kwargs,
+ langtest_extra=repetition_extra,
+ )
+
+ return async_wrapper
+
+ @functools.wraps(func)
+ def wrapper(*test_args: Any, request: Any = None, **test_kwargs: Any):
+ if disable_tracking:
+ return func(*test_args, **test_kwargs)
+
+ # Run test multiple times for repetitions
+ for i in range(repetitions):
+ repetition_extra = langtest_extra.copy()
+ _run_test(
+ func,
+ *test_args,
+ pytest_request=request,
+ **test_kwargs,
+ langtest_extra=repetition_extra,
+ )
+
+ return wrapper
+
+ if args and callable(args[0]):
+ return decorator(args[0])
+
+ return decorator
+
+
+## Private functions
+
+
+def _get_experiment_name(test_suite_name: str) -> str:
+ # If this is a pytest-xdist multi-process run then we need to create the same
+ # experiment name across processes. We can do this by accessing the
+ # PYTEST_XDIST_TESTRUNID env var.
+ if os.environ.get("PYTEST_XDIST_TESTRUNUID") and importlib.util.find_spec("xdist"):
+ id_name = test_suite_name + os.environ["PYTEST_XDIST_TESTRUNUID"]
+ id_ = str(uuid.uuid5(uuid.NAMESPACE_DNS, id_name).hex[:8])
+ else:
+ id_ = str(uuid.uuid4().hex[:8])
+
+ if os.environ.get("LANGSMITH_EXPERIMENT"):
+ prefix = os.environ["LANGSMITH_EXPERIMENT"]
+ else:
+ prefix = ls_utils.get_tracer_project(False) or "TestSuiteResult"
+ name = f"{prefix}:{id_}"
+ return name
+
+
+def _get_test_suite_name(func: Callable) -> str:
+ test_suite_name = ls_utils.get_env_var("TEST_SUITE")
+ if test_suite_name:
+ return test_suite_name
+ repo_name = ls_env.get_git_info()["repo_name"]
+ try:
+ mod = inspect.getmodule(func)
+ if mod:
+ return f"{repo_name}.{mod.__name__}"
+ except BaseException:
+ logger.debug("Could not determine test suite name from file path.")
+
+ raise ValueError("Please set the LANGSMITH_TEST_SUITE environment variable.")
+
+
+def _get_test_suite(
+ client: ls_client.Client, test_suite_name: str
+) -> ls_schemas.Dataset:
+ if client.has_dataset(dataset_name=test_suite_name):
+ return client.read_dataset(dataset_name=test_suite_name)
+ else:
+ repo = ls_env.get_git_info().get("remote_url") or ""
+ description = "Test suite"
+ if repo:
+ description += f" for {repo}"
+ try:
+ return client.create_dataset(
+ dataset_name=test_suite_name,
+ description=description,
+ metadata={"__ls_runner": "pytest"},
+ )
+ except ls_utils.LangSmithConflictError:
+ return client.read_dataset(dataset_name=test_suite_name)
+
+
+def _start_experiment(
+ client: ls_client.Client,
+ test_suite: ls_schemas.Dataset,
+ experiment_metadata: Optional[dict] = None,
+) -> ls_schemas.TracerSession:
+ experiment_name = _get_experiment_name(test_suite.name)
+ # User-provided experiment_metadata is merged first so that system keys
+ # (revision_id, __ls_runner) always take precedence.
+ metadata = {
+ **(experiment_metadata or {}),
+ "revision_id": ls_env.get_langchain_env_var_metadata().get("revision_id"),
+ "__ls_runner": "pytest",
+ }
+ try:
+ return client.create_project(
+ experiment_name,
+ reference_dataset_id=test_suite.id,
+ description="Test Suite Results.",
+ metadata=metadata,
+ )
+ except ls_utils.LangSmithConflictError:
+ return client.read_project(project_name=experiment_name)
+
+
+def _get_example_id(
+ dataset_id: str,
+ inputs: dict,
+ outputs: Optional[dict] = None,
+) -> uuid.UUID:
+ """Generate example ID based on inputs, outputs, and dataset ID."""
+ identifier_obj = (dataset_id, _object_hash(inputs), _object_hash(outputs or {}))
+ identifier = _stringify(identifier_obj)
+ return uuid.uuid5(UUID5_NAMESPACE, identifier)
+
+
+def _get_example_id_legacy(
+ func: Callable, inputs: Optional[dict], suite_id: uuid.UUID
+) -> tuple[uuid.UUID, str]:
+ try:
+ file_path = str(Path(inspect.getfile(func)).relative_to(Path.cwd()))
+ except ValueError:
+ # Fall back to module name if file path is not available
+ file_path = func.__module__
+ identifier = f"{suite_id}{file_path}::{func.__name__}"
+ # If parametrized test, need to add inputs to identifier:
+ if hasattr(func, "pytestmark") and any(
+ m.name == "parametrize" for m in func.pytestmark
+ ):
+ identifier += _stringify(inputs)
+ return uuid.uuid5(uuid.NAMESPACE_DNS, identifier), identifier[len(str(suite_id)) :]
+
+
+def _end_tests(test_suite: _LangSmithTestSuite):
+ git_info = ls_env.get_git_info() or {}
+ test_suite.shutdown()
+ dataset_version = test_suite.get_dataset_version()
+ dataset_id = test_suite._dataset.id
+ # User-provided experiment_metadata is merged first so that system keys
+ # always take precedence.
+ test_suite.client.update_project(
+ test_suite.experiment_id,
+ metadata={
+ **(test_suite.experiment_metadata or {}),
+ **git_info,
+ "dataset_version": dataset_version,
+ "revision_id": ls_env.get_langchain_env_var_metadata().get("revision_id"),
+ "__ls_runner": "pytest",
+ },
+ )
+ if dataset_version and git_info["commit"] is not None:
+ test_suite.client.update_dataset_tag(
+ dataset_id=dataset_id,
+ as_of=dataset_version,
+ tag=f"git:commit:{git_info['commit']}",
+ )
+ if dataset_version and git_info["branch"] is not None:
+ test_suite.client.update_dataset_tag(
+ dataset_id=dataset_id,
+ as_of=dataset_version,
+ tag=f"git:branch:{git_info['branch']}",
+ )
+
+
+VT = TypeVar("VT", bound=Optional[dict])
+
+
+def _serde_example_values(values: VT) -> VT:
+ if values is None:
+ return cast(VT, values)
+ bts = ls_client._dumps_json(values)
+ return _orjson.loads(bts)
+
+
+class _LangSmithTestSuite:
+ _instances: Optional[dict] = None
+ _lock = threading.RLock()
+
+ def __init__(
+ self,
+ client: Optional[ls_client.Client],
+ experiment: ls_schemas.TracerSession,
+ dataset: ls_schemas.Dataset,
+ experiment_metadata: Optional[dict] = None,
+ ):
+ self.client = client or rt.get_cached_client()
+ self._experiment = experiment
+ self._dataset = dataset
+ self._dataset_version: Optional[datetime.datetime] = dataset.modified_at
+ self._executor = ls_utils.ContextThreadPoolExecutor()
+ self.experiment_metadata = experiment_metadata
+ atexit.register(_end_tests, self)
+
+ @property
+ def id(self):
+ return self._dataset.id
+
+ @property
+ def experiment_id(self):
+ return self._experiment.id
+
+ @property
+ def experiment(self):
+ return self._experiment
+
+ @classmethod
+ def from_test(
+ cls,
+ client: Optional[ls_client.Client],
+ func: Callable,
+ test_suite_name: Optional[str] = None,
+ experiment_metadata: Optional[dict] = None,
+ ) -> _LangSmithTestSuite:
+ client = client or rt.get_cached_client()
+ test_suite_name = test_suite_name or _get_test_suite_name(func)
+ with cls._lock:
+ if not cls._instances:
+ cls._instances = {}
+ if test_suite_name not in cls._instances:
+ test_suite = _get_test_suite(client, test_suite_name)
+ experiment = _start_experiment(client, test_suite, experiment_metadata)
+ cls._instances[test_suite_name] = cls(
+ client, experiment, test_suite, experiment_metadata
+ )
+ return cls._instances[test_suite_name]
+
+ @property
+ def name(self):
+ return self._experiment.name
+
+ def get_dataset_version(self):
+ return self._dataset_version
+
+ def submit_result(
+ self,
+ run_id: uuid.UUID,
+ error: Optional[str] = None,
+ skipped: bool = False,
+ pytest_plugin: Any = None,
+ pytest_nodeid: Any = None,
+ ) -> None:
+ if skipped:
+ score = None
+ status = "skipped"
+ elif error:
+ score = 0
+ status = "failed"
+ else:
+ score = 1
+ status = "passed"
+ if pytest_plugin and pytest_nodeid:
+ pytest_plugin.update_process_status(pytest_nodeid, {"status": status})
+ self._executor.submit(self._submit_result, run_id, score)
+
+ def _submit_result(self, run_id: uuid.UUID, score: Optional[int]) -> None:
+ # trace_id will always be run_id here because the feedback is on the root
+ # test run
+ self.client.create_feedback(run_id, key="pass", score=score, trace_id=run_id)
+
+ def sync_example(
+ self,
+ example_id: uuid.UUID,
+ *,
+ inputs: Optional[dict] = None,
+ outputs: Optional[dict] = None,
+ metadata: Optional[dict] = None,
+ split: Optional[Union[str, list[str]]] = None,
+ pytest_plugin=None,
+ pytest_nodeid=None,
+ ) -> None:
+ inputs = inputs or {}
+ if pytest_plugin and pytest_nodeid:
+ update = {"inputs": inputs, "reference_outputs": outputs}
+ update = {k: v for k, v in update.items() if v is not None}
+ pytest_plugin.update_process_status(pytest_nodeid, update)
+ metadata = metadata.copy() if metadata else metadata
+ inputs = _serde_example_values(inputs)
+ outputs = _serde_example_values(outputs)
+ try:
+ example = self.client.read_example(example_id=example_id)
+ except ls_utils.LangSmithNotFoundError:
+ try:
+ example = self.client.create_example(
+ example_id=example_id,
+ inputs=inputs,
+ outputs=outputs,
+ dataset_id=self.id,
+ metadata=metadata,
+ split=split,
+ created_at=self._experiment.start_time,
+ )
+ except ls_utils.LangSmithConflictError:
+ # Another worker (e.g. pytest-xdist) created this example
+ # concurrently between our read and create. Read the existing one.
+ example = self.client.read_example(example_id=example_id)
+ else:
+ normalized_split = split
+ if isinstance(normalized_split, str):
+ normalized_split = [normalized_split]
+ if normalized_split and metadata:
+ metadata["dataset_split"] = normalized_split
+ existing_dataset_split = (example.metadata or {}).pop("dataset_split")
+ if (
+ (inputs != example.inputs)
+ or (outputs is not None and outputs != example.outputs)
+ or (metadata is not None and metadata != example.metadata)
+ or str(example.dataset_id) != str(self.id)
+ or (
+ normalized_split is not None
+ and existing_dataset_split != normalized_split
+ )
+ ):
+ self.client.update_example(
+ example_id=example.id,
+ inputs=inputs,
+ outputs=outputs,
+ metadata=metadata,
+ split=split,
+ dataset_id=self.id,
+ )
+ example = self.client.read_example(example_id=example.id)
+ if self._dataset_version is None:
+ self._dataset_version = example.modified_at
+ elif (
+ example.modified_at
+ and self._dataset_version
+ and example.modified_at > self._dataset_version
+ ):
+ self._dataset_version = example.modified_at
+
+ def _submit_feedback(
+ self,
+ run_id: ID_TYPE,
+ feedback: Union[dict, list],
+ pytest_plugin: Any = None,
+ pytest_nodeid: Any = None,
+ **kwargs: Any,
+ ):
+ feedback = feedback if isinstance(feedback, list) else [feedback]
+ for fb in feedback:
+ if pytest_plugin and pytest_nodeid:
+ val = fb["score"] if "score" in fb else fb["value"]
+ pytest_plugin.update_process_status(
+ pytest_nodeid, {"feedback": {fb["key"]: val}}
+ )
+ self._executor.submit(
+ self._create_feedback, run_id=run_id, feedback=fb, **kwargs
+ )
+
+ def _create_feedback(self, run_id: ID_TYPE, feedback: dict, **kwargs: Any) -> None:
+ # trace_id will always be run_id here because the feedback is on the root
+ # test run
+ self.client.create_feedback(run_id, **feedback, **kwargs, trace_id=run_id)
+
+ def shutdown(self):
+ self._executor.shutdown()
+
+ def end_run(
+ self,
+ run_tree,
+ example_id,
+ outputs,
+ reference_outputs,
+ metadata,
+ split,
+ pytest_plugin=None,
+ pytest_nodeid=None,
+ ) -> Future:
+ return self._executor.submit(
+ self._end_run,
+ run_tree=run_tree,
+ example_id=example_id,
+ outputs=outputs,
+ reference_outputs=reference_outputs,
+ metadata=metadata,
+ split=split,
+ pytest_plugin=pytest_plugin,
+ pytest_nodeid=pytest_nodeid,
+ )
+
+ def _end_run(
+ self,
+ run_tree,
+ example_id,
+ outputs,
+ reference_outputs,
+ metadata,
+ split,
+ pytest_plugin,
+ pytest_nodeid,
+ ) -> None:
+ # TODO: remove this hack so that run durations are correct
+ # Ensure example is fully updated
+ self.sync_example(
+ example_id,
+ inputs=run_tree.inputs,
+ outputs=reference_outputs,
+ split=split,
+ metadata=metadata,
+ )
+ run_tree.reference_example_id = example_id
+ run_tree.end(outputs=outputs, metadata={"reference_example_id": example_id})
+ run_tree.patch()
+
+
+class _TestCase:
+ def __init__(
+ self,
+ test_suite: _LangSmithTestSuite,
+ run_id: uuid.UUID,
+ example_id: Optional[uuid.UUID] = None,
+ metadata: Optional[dict] = None,
+ split: Optional[Union[str, list[str]]] = None,
+ pytest_plugin: Any = None,
+ pytest_nodeid: Any = None,
+ inputs: Optional[dict] = None,
+ reference_outputs: Optional[dict] = None,
+ ) -> None:
+ self.test_suite = test_suite
+ self.example_id = example_id
+ self.run_id = run_id
+ self.metadata = metadata
+ self.split = split
+ self.pytest_plugin = pytest_plugin
+ self.pytest_nodeid = pytest_nodeid
+ self.inputs = inputs
+ self.reference_outputs = reference_outputs
+ self._logged_reference_outputs: Optional[dict] = None
+ self._logged_outputs: Optional[dict] = None
+
+ if pytest_plugin and pytest_nodeid:
+ pytest_plugin.add_process_to_test_suite(
+ test_suite._dataset.name, pytest_nodeid
+ )
+ if inputs:
+ self.log_inputs(inputs)
+ if reference_outputs:
+ self.log_reference_outputs(reference_outputs)
+
+ def submit_feedback(self, *args, **kwargs: Any):
+ self.test_suite._submit_feedback(
+ *args,
+ **{
+ **kwargs,
+ **dict(
+ pytest_plugin=self.pytest_plugin,
+ pytest_nodeid=self.pytest_nodeid,
+ ),
+ },
+ )
+
+ def log_inputs(self, inputs: dict) -> None:
+ self.inputs = inputs
+ if self.pytest_plugin and self.pytest_nodeid:
+ self.pytest_plugin.update_process_status(
+ self.pytest_nodeid, {"inputs": inputs}
+ )
+
+ def log_outputs(self, outputs: dict) -> None:
+ self._logged_outputs = outputs
+ if self.pytest_plugin and self.pytest_nodeid:
+ self.pytest_plugin.update_process_status(
+ self.pytest_nodeid, {"outputs": outputs}
+ )
+
+ def log_reference_outputs(self, reference_outputs: dict) -> None:
+ self._logged_reference_outputs = reference_outputs
+ if self.pytest_plugin and self.pytest_nodeid:
+ self.pytest_plugin.update_process_status(
+ self.pytest_nodeid, {"reference_outputs": reference_outputs}
+ )
+
+ def submit_test_result(
+ self,
+ error: Optional[str] = None,
+ skipped: bool = False,
+ ) -> None:
+ return self.test_suite.submit_result(
+ self.run_id,
+ error=error,
+ skipped=skipped,
+ pytest_plugin=self.pytest_plugin,
+ pytest_nodeid=self.pytest_nodeid,
+ )
+
+ def start_time(self) -> None:
+ if self.pytest_plugin and self.pytest_nodeid:
+ self.pytest_plugin.update_process_status(
+ self.pytest_nodeid, {"start_time": time.time()}
+ )
+
+ def end_time(self) -> None:
+ if self.pytest_plugin and self.pytest_nodeid:
+ self.pytest_plugin.update_process_status(
+ self.pytest_nodeid, {"end_time": time.time()}
+ )
+
+ def end_run(self, run_tree, outputs: Any) -> None:
+ if not (outputs is None or isinstance(outputs, dict)):
+ outputs = {"output": outputs}
+ example_id = self.example_id or _get_example_id(
+ dataset_id=str(self.test_suite.id),
+ inputs=self.inputs or {},
+ outputs=outputs,
+ )
+ self.test_suite.end_run(
+ run_tree,
+ example_id,
+ outputs,
+ reference_outputs=self._logged_reference_outputs,
+ metadata=self.metadata,
+ split=self.split,
+ pytest_plugin=self.pytest_plugin,
+ pytest_nodeid=self.pytest_nodeid,
+ )
+
+
+_TEST_CASE = contextvars.ContextVar[Optional[_TestCase]]("_TEST_CASE", default=None)
+
+
+class _UTExtra(TypedDict, total=False):
+ client: Optional[ls_client.Client]
+ id: Optional[uuid.UUID]
+ output_keys: Optional[Sequence[str]]
+ test_suite_name: Optional[str]
+ cache: Optional[str]
+ metadata: Optional[dict]
+ experiment_metadata: Optional[dict]
+ repetitions: Optional[int]
+ split: Optional[Union[str, list[str]]]
+ cached_hosts: Optional[Sequence[str]]
+
+
+def _create_test_case(
+ func: Callable,
+ *args: Any,
+ pytest_request: Any,
+ langtest_extra: _UTExtra,
+ **kwargs: Any,
+) -> _TestCase:
+ client = langtest_extra["client"] or rt.get_cached_client()
+ output_keys = langtest_extra["output_keys"]
+ metadata = langtest_extra["metadata"]
+ split = langtest_extra["split"]
+ # Resolve experiment_metadata: explicit kwarg > env var
+ experiment_metadata = langtest_extra.get("experiment_metadata")
+ if experiment_metadata is None:
+ env_val = os.environ.get("LANGSMITH_EXPERIMENT_METADATA")
+ if env_val:
+ try:
+ experiment_metadata = _orjson.loads(env_val)
+ except Exception as e:
+ msg = f"LANGSMITH_EXPERIMENT_METADATA env var is not valid JSON: {e}"
+ raise ValueError(msg) from e
+ signature = inspect.signature(func)
+ inputs = rh._get_inputs_safe(signature, *args, **kwargs) or None
+ outputs = None
+ if output_keys:
+ outputs = {}
+ if not inputs:
+ msg = (
+ "'output_keys' should only be specified when marked test function has "
+ "input arguments."
+ )
+ raise ValueError(msg)
+ for k in output_keys:
+ outputs[k] = inputs.pop(k, None)
+ test_suite = _LangSmithTestSuite.from_test(
+ client, func, langtest_extra.get("test_suite_name"), experiment_metadata
+ )
+ example_id = langtest_extra["id"]
+ dataset_sdk_version = (
+ test_suite._dataset.metadata
+ and test_suite._dataset.metadata.get("runtime")
+ and test_suite._dataset.metadata.get("runtime", {}).get("sdk_version")
+ )
+ if not dataset_sdk_version or not ls_utils.is_version_greater_or_equal(
+ dataset_sdk_version, "0.4.33"
+ ):
+ legacy_example_id, example_name = _get_example_id_legacy(
+ func, inputs, test_suite.id
+ )
+ example_id = example_id or legacy_example_id
+ pytest_plugin = (
+ pytest_request.config.pluginmanager.get_plugin("langsmith_output_plugin")
+ if pytest_request
+ else None
+ )
+ pytest_nodeid = pytest_request.node.nodeid if pytest_request else None
+ if pytest_plugin:
+ pytest_plugin.test_suite_urls[test_suite._dataset.name] = (
+ cast(str, test_suite._dataset.url)
+ + "/compare?selectedSessions="
+ + str(test_suite.experiment_id)
+ )
+ test_case = _TestCase(
+ test_suite,
+ run_id=uuid.uuid4(),
+ example_id=example_id,
+ metadata=metadata,
+ split=split,
+ inputs=inputs,
+ reference_outputs=outputs,
+ pytest_plugin=pytest_plugin,
+ pytest_nodeid=pytest_nodeid,
+ )
+ return test_case
+
+
+def _run_test(
+ func: Callable,
+ *test_args: Any,
+ pytest_request: Any,
+ langtest_extra: _UTExtra,
+ **test_kwargs: Any,
+) -> None:
+ test_case = _create_test_case(
+ func,
+ *test_args,
+ **test_kwargs,
+ pytest_request=pytest_request,
+ langtest_extra=langtest_extra,
+ )
+ _TEST_CASE.set(test_case)
+
+ def _test():
+ test_case.start_time()
+ with rh.trace(
+ name=getattr(func, "__name__", "Test"),
+ run_id=test_case.run_id,
+ inputs=test_case.inputs,
+ metadata={
+ # Experiment run metadata is prefixed with "ls_example_" in
+ # the ingest backend, but we must reproduce this behavior here
+ # because the example may not have been created before the trace
+ # starts.
+ f"ls_example_{k}": v
+ for k, v in (test_case.metadata or {}).items()
+ },
+ project_name=test_case.test_suite.name,
+ exceptions_to_handle=(SkipException,),
+ _end_on_exit=False,
+ ) as run_tree:
+ try:
+ result = func(*test_args, **test_kwargs)
+ except SkipException as e:
+ test_case.submit_test_result(error=repr(e), skipped=True)
+ test_case.end_run(run_tree, {"skipped_reason": repr(e)})
+ raise e
+ except BaseException as e:
+ test_case.submit_test_result(error=repr(e))
+ test_case.end_run(run_tree, None)
+ raise e
+ else:
+ test_case.end_run(run_tree, result)
+ finally:
+ test_case.end_time()
+ try:
+ test_case.submit_test_result()
+ except BaseException as e:
+ logger.warning(
+ f"Failed to create feedback for run_id {test_case.run_id}:\n{e}"
+ )
+
+ if langtest_extra["cache"]:
+ cache_path = Path(langtest_extra["cache"]) / f"{test_case.test_suite.id}.yaml"
+ else:
+ cache_path = None
+ current_context = rh.get_tracing_context()
+ metadata = {
+ **(current_context["metadata"] or {}),
+ **{
+ "experiment": test_case.test_suite.experiment.name,
+ },
+ }
+ # Handle cached_hosts parameter
+ ignore_hosts = [test_case.test_suite.client.api_url]
+ allow_hosts = langtest_extra.get("cached_hosts") or None
+
+ with (
+ rh.tracing_context(**{**current_context, "metadata": metadata}),
+ ls_utils.with_optional_cache(
+ cache_path, ignore_hosts=ignore_hosts, allow_hosts=allow_hosts
+ ),
+ ):
+ _test()
+
+
+async def _arun_test(
+ func: Callable,
+ *test_args: Any,
+ pytest_request: Any,
+ langtest_extra: _UTExtra,
+ **test_kwargs: Any,
+) -> None:
+ test_case = _create_test_case(
+ func,
+ *test_args,
+ **test_kwargs,
+ pytest_request=pytest_request,
+ langtest_extra=langtest_extra,
+ )
+ _TEST_CASE.set(test_case)
+
+ async def _test():
+ test_case.start_time()
+ with rh.trace(
+ name=getattr(func, "__name__", "Test"),
+ run_id=test_case.run_id,
+ reference_example_id=test_case.example_id,
+ inputs=test_case.inputs,
+ metadata={
+ # Experiment run metadata is prefixed with "ls_example_" in
+ # the ingest backend, but we must reproduce this behavior here
+ # because the example may not have been created before the trace
+ # starts.
+ f"ls_example_{k}": v
+ for k, v in (test_case.metadata or {}).items()
+ },
+ project_name=test_case.test_suite.name,
+ exceptions_to_handle=(SkipException,),
+ _end_on_exit=False,
+ ) as run_tree:
+ try:
+ result = await func(*test_args, **test_kwargs)
+ except SkipException as e:
+ test_case.submit_test_result(error=repr(e), skipped=True)
+ test_case.end_run(run_tree, {"skipped_reason": repr(e)})
+ raise e
+ except BaseException as e:
+ test_case.submit_test_result(error=repr(e))
+ test_case.end_run(run_tree, None)
+ raise e
+ else:
+ test_case.end_run(run_tree, result)
+ finally:
+ test_case.end_time()
+ try:
+ test_case.submit_test_result()
+ except BaseException as e:
+ logger.warning(
+ f"Failed to create feedback for run_id {test_case.run_id}:\n{e}"
+ )
+
+ if langtest_extra["cache"]:
+ cache_path = Path(langtest_extra["cache"]) / f"{test_case.test_suite.id}.yaml"
+ else:
+ cache_path = None
+ current_context = rh.get_tracing_context()
+ metadata = {
+ **(current_context["metadata"] or {}),
+ **{
+ "experiment": test_case.test_suite.experiment.name,
+ "reference_example_id": str(test_case.example_id),
+ },
+ }
+ # Handle cached_hosts parameter
+ ignore_hosts = [test_case.test_suite.client.api_url]
+ cached_hosts = langtest_extra.get("cached_hosts")
+ allow_hosts = cached_hosts if cached_hosts else None
+
+ with (
+ rh.tracing_context(**{**current_context, "metadata": metadata}),
+ ls_utils.with_optional_cache(
+ cache_path, ignore_hosts=ignore_hosts, allow_hosts=allow_hosts
+ ),
+ ):
+ await _test()
+
+
+# For backwards compatibility
+unit = test
+
+
+def log_inputs(inputs: dict, /) -> None:
+ """Log run inputs from within a pytest test run.
+
+ Should only be used in pytest tests decorated with @pytest.mark.langsmith.
+
+ Args:
+ inputs: Inputs to log.
+
+ Example:
+ ```python
+ from langsmith import testing as t
+
+
+ @pytest.mark.langsmith
+ def test_foo() -> None:
+ x = 0
+ y = 1
+ t.log_inputs({"x": x, "y": y})
+ assert foo(x, y) == 2
+ ```
+ """
+ if ls_utils.test_tracking_is_disabled():
+ logger.info("LANGSMITH_TEST_TRACKING is set to 'false'. Skipping log_inputs.")
+ return
+ run_tree = rh.get_current_run_tree()
+ test_case = _TEST_CASE.get()
+ if not run_tree or not test_case:
+ msg = (
+ "log_inputs should only be called within a pytest test decorated with "
+ "@pytest.mark.langsmith, and with tracing enabled (by setting the "
+ "LANGSMITH_TRACING environment variable to 'true')."
+ )
+ raise ValueError(msg)
+ run_tree.add_inputs(inputs)
+ test_case.log_inputs(run_tree.inputs)
+
+
+def log_outputs(outputs: dict, /) -> None:
+ """Log run outputs from within a pytest test run.
+
+ Should only be used in pytest tests decorated with @pytest.mark.langsmith.
+
+ Args:
+ outputs: Outputs to log.
+
+ Example:
+ ```python
+ from langsmith import testing as t
+
+
+ @pytest.mark.langsmith
+ def test_foo() -> None:
+ x = 0
+ y = 1
+ result = foo(x, y)
+ t.log_outputs({"foo": result})
+ assert result == 2
+ ```
+ """
+ if ls_utils.test_tracking_is_disabled():
+ logger.info("LANGSMITH_TEST_TRACKING is set to 'false'. Skipping log_outputs.")
+ return
+ run_tree = rh.get_current_run_tree()
+ test_case = _TEST_CASE.get()
+ if not run_tree or not test_case:
+ msg = (
+ "log_outputs should only be called within a pytest test decorated with "
+ "@pytest.mark.langsmith, and with tracing enabled (by setting the "
+ "LANGSMITH_TRACING environment variable to 'true')."
+ )
+ raise ValueError(msg)
+ outputs = _dumpd(outputs)
+ run_tree.add_outputs(outputs)
+ test_case.log_outputs(outputs)
+
+
+def log_reference_outputs(reference_outputs: dict, /) -> None:
+ """Log example reference outputs from within a pytest test run.
+
+ Should only be used in pytest tests decorated with @pytest.mark.langsmith.
+
+ Args:
+ reference_outputs: Reference outputs to log.
+
+ Example:
+ ```python
+ from langsmith import testing
+
+
+ @pytest.mark.langsmith
+ def test_foo() -> None:
+ x = 0
+ y = 1
+ expected = 2
+ testing.log_reference_outputs({"foo": expected})
+ assert foo(x, y) == expected
+ ```
+ """
+ if ls_utils.test_tracking_is_disabled():
+ logger.info(
+ "LANGSMITH_TEST_TRACKING is set to 'false'. Skipping log_reference_outputs."
+ )
+ return
+ test_case = _TEST_CASE.get()
+ if not test_case:
+ msg = (
+ "log_reference_outputs should only be called within a pytest test "
+ "decorated with @pytest.mark.langsmith."
+ )
+ raise ValueError(msg)
+ test_case.log_reference_outputs(reference_outputs)
+
+
+def log_feedback(
+ feedback: Optional[Union[dict, list[dict]]] = None,
+ /,
+ *,
+ key: str,
+ score: Optional[Union[int, bool, float]] = None,
+ value: Optional[Union[str, int, float, bool]] = None,
+ **kwargs: Any,
+) -> None:
+ """Log run feedback from within a pytest test run.
+
+ Should only be used in pytest tests decorated with @pytest.mark.langsmith.
+
+ Args:
+ key: Feedback name.
+ score: Numerical feedback value.
+ value: Categorical feedback value
+ kwargs: Any other Client.create_feedback args.
+
+ Example:
+ ```python
+ import pytest
+ from langsmith import testing as t
+
+
+ @pytest.mark.langsmith
+ def test_foo() -> None:
+ x = 0
+ y = 1
+ expected = 2
+ result = foo(x, y)
+ t.log_feedback(key="right_type", score=isinstance(result, int))
+ assert result == expected
+ ```
+ """
+ if ls_utils.test_tracking_is_disabled():
+ logger.info("LANGSMITH_TEST_TRACKING is set to 'false'. Skipping log_feedback.")
+ return
+ if feedback and any((key, score, value)):
+ msg = "Must specify one of 'feedback' and ('key', 'score', 'value'), not both."
+ raise ValueError(msg)
+ elif not (feedback or key):
+ msg = "Must specify at least one of 'feedback' or ('key', 'score', value')."
+ raise ValueError(msg)
+ elif key:
+ feedback = {"key": key}
+ if score is not None:
+ feedback["score"] = score
+ if value is not None:
+ feedback["value"] = value
+ else:
+ pass
+
+ run_tree = rh.get_current_run_tree()
+ test_case = _TEST_CASE.get()
+ if not run_tree or not test_case:
+ msg = (
+ "log_feedback should only be called within a pytest test decorated with "
+ "@pytest.mark.langsmith, and with tracing enabled (by setting the "
+ "LANGSMITH_TRACING environment variable to 'true')."
+ )
+ raise ValueError(msg)
+ if run_tree.session_name == "evaluators" and run_tree.metadata.get(
+ "reference_run_id"
+ ):
+ run_id = run_tree.metadata["reference_run_id"]
+ run_tree.add_outputs(
+ feedback if isinstance(feedback, dict) else {"feedback": feedback}
+ )
+ kwargs["source_run_id"] = run_tree.id
+ else:
+ run_id = run_tree.trace_id
+ test_case.submit_feedback(run_id, cast(Union[list, dict], feedback), **kwargs)
+
+
+@contextlib.contextmanager
+def trace_feedback(
+ *, name: str = "Feedback"
+) -> Generator[Optional[run_trees.RunTree], None, None]:
+ """Trace the computation of a pytest run feedback as its own run.
+
+ Args:
+ name: Feedback run name. Defaults to "Feedback".
+
+ Example:
+ ```python
+ import openai
+ import pytest
+
+ from langsmith import testing as t
+ from langsmith import wrappers
+
+ oai_client = wrappers.wrap_openai(openai.Client())
+
+
+ @pytest.mark.langsmith
+ def test_openai_says_hello():
+ # Traced code will be included in the test case
+ text = "Say hello!"
+ response = oai_client.chat.completions.create(
+ model="gpt-4o-mini",
+ messages=[
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": text},
+ ],
+ )
+ t.log_inputs({"text": text})
+ t.log_outputs({"response": response.choices[0].message.content})
+ t.log_reference_outputs({"response": "hello!"})
+
+ # Use this context manager to trace any steps used for generating evaluation
+ # feedback separately from the main application logic
+ with t.trace_feedback():
+ grade = oai_client.chat.completions.create(
+ model="gpt-4o-mini",
+ messages=[
+ {
+ "role": "system",
+ "content": "Return 1 if 'hello' is in the user message and 0 otherwise.",
+ },
+ {
+ "role": "user",
+ "content": response.choices[0].message.content,
+ },
+ ],
+ )
+ # Make sure to log relevant feedback within the context for the
+ # trace to be associated with this feedback.
+ t.log_feedback(
+ key="llm_judge", score=float(grade.choices[0].message.content)
+ )
+
+ assert "hello" in response.choices[0].message.content.lower()
+ ```
+ """ # noqa: E501
+ if ls_utils.test_tracking_is_disabled():
+ logger.info("LANGSMITH_TEST_TRACKING is set to 'false'. Skipping log_feedback.")
+ yield None
+ return
+ test_case = _TEST_CASE.get()
+ if not test_case:
+ msg = (
+ "trace_feedback should only be called within a pytest test decorated with "
+ "@pytest.mark.langsmith, and with tracing enabled (by setting the "
+ "LANGSMITH_TRACING environment variable to 'true')."
+ )
+ raise ValueError(msg)
+ metadata = {
+ "experiment": test_case.test_suite.experiment.name,
+ "reference_example_id": test_case.example_id,
+ "reference_run_id": test_case.run_id,
+ }
+ with rh.trace(
+ name=name,
+ inputs=test_case._logged_outputs,
+ parent="ignore",
+ project_name="evaluators",
+ metadata=metadata,
+ ) as run_tree:
+ yield run_tree
+
+
+def _stringify(x: Any) -> str:
+ try:
+ return dumps_json(x).decode("utf-8", errors="surrogateescape")
+ except Exception:
+ return str(x)
+
+
+def _dumpd(x: Any) -> Any:
+ """Serialize LangChain Serializable objects."""
+ dumpd = _get_langchain_dumpd()
+ if not dumpd:
+ return x
+ try:
+ serialized = dumpd(x)
+ return serialized
+ except Exception:
+ return x
+
+
+@functools.lru_cache
+def _get_langchain_dumpd() -> Optional[Callable]:
+ try:
+ from langchain_core.load import dumpd
+
+ return dumpd
+ except ImportError:
+ return None
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..da062025e0b8c326b15f03d15f113ca865193fd0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__init__.py
@@ -0,0 +1,13 @@
+"""This module provides convenient tracing wrappers for popular libraries."""
+
+from langsmith.wrappers._anthropic import wrap_anthropic
+from langsmith.wrappers._gemini import wrap_gemini # BETA
+from langsmith.wrappers._openai import wrap_openai
+from langsmith.wrappers._openai_agents import OpenAIAgentsTracingProcessor
+
+__all__ = [
+ "wrap_anthropic",
+ "wrap_gemini", # BETA
+ "wrap_openai",
+ "OpenAIAgentsTracingProcessor",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8cb2c36090e548e59969c7f9aa3abcdd5ba4d94
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/_anthropic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/_anthropic.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3a81e8f660748edb31ec9e30174f8a810af2a07
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/_anthropic.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/_gemini.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/_gemini.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ded595c3ab113aa0cf597eede9ec5f1a5838935
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/_gemini.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/_openai.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/_openai.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..62e775020eaeb0b0856451851cef2db77ec45a7b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/_openai.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/_openai_agents.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/_openai_agents.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8359ef86d5f0996234356ef62985836787a67011
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/__pycache__/_openai_agents.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/_anthropic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/_anthropic.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed17394c992678d9a0d58cc7f919bea17640451e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/_anthropic.py
@@ -0,0 +1,608 @@
+from __future__ import annotations
+
+import functools
+import logging
+import warnings
+from collections.abc import AsyncIterator, Mapping, Sequence
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Optional,
+ TypeVar,
+ Union,
+)
+
+from typing_extensions import Self, TypedDict
+
+from langsmith import client as ls_client
+from langsmith import run_helpers
+from langsmith._internal._orjson import dumps as _dumps
+from langsmith.schemas import InputTokenDetails, UsageMetadata
+
+if TYPE_CHECKING:
+ import httpx
+ from anthropic import Anthropic, AsyncAnthropic
+ from anthropic.lib.streaming import AsyncMessageStream, MessageStream
+ from anthropic.types import Completion, Message, MessageStreamEvent
+
+C = TypeVar("C", bound=Union["Anthropic", "AsyncAnthropic", Any])
+logger = logging.getLogger(__name__)
+
+
+@functools.lru_cache
+def _get_not_given() -> Optional[tuple[type, ...]]:
+ try:
+ from anthropic._types import NotGiven, Omit
+
+ return (NotGiven, Omit)
+ except ImportError:
+ return None
+
+
+def _strip_not_given(d: dict) -> dict:
+ try:
+ if not_given := _get_not_given():
+ d = {
+ k: v
+ for k, v in d.items()
+ if not any(isinstance(v, t) for t in not_given)
+ }
+ except Exception as e:
+ logger.error(f"Error stripping NotGiven: {e}")
+
+ if "system" in d:
+ d["messages"] = [{"role": "system", "content": d["system"]}] + d.get(
+ "messages", []
+ )
+ d.pop("system")
+ return {k: v for k, v in d.items() if v is not None}
+
+
+def _infer_ls_params(prepopulated_invocation_params: dict, kwargs: dict):
+ stripped = _strip_not_given(kwargs)
+
+ stop = stripped.get("stop")
+ if stop and isinstance(stop, str):
+ stop = [stop]
+
+ # Allowlist of safe invocation parameters to include
+ # Only include known, non-sensitive parameters
+ allowed_invocation_keys = {
+ "mcp_servers",
+ "service_tier",
+ "tool_choice",
+ "top_k",
+ "top_p",
+ "stream",
+ "thinking",
+ }
+
+ # Only include allowlisted parameters
+ invocation_params = {
+ k: v for k, v in stripped.items() if k in allowed_invocation_keys
+ }
+
+ return {
+ "ls_provider": "anthropic",
+ "ls_model_type": "chat",
+ "ls_model_name": stripped.get("model", None),
+ "ls_temperature": stripped.get("temperature", None),
+ "ls_max_tokens": stripped.get("max_tokens", None),
+ "ls_stop": stop,
+ "ls_invocation_params": {
+ **prepopulated_invocation_params,
+ **invocation_params,
+ },
+ }
+
+
+@functools.lru_cache
+def _get_sdk_accumulate_event() -> Optional[Callable]:
+ try:
+ from anthropic.lib.streaming._messages import accumulate_event
+
+ return accumulate_event
+ except ImportError:
+ return None
+
+
+def _create_usage_metadata(anthropic_token_usage: dict) -> UsageMetadata:
+ input_tokens = anthropic_token_usage.get("input_tokens") or 0
+ output_tokens = anthropic_token_usage.get("output_tokens") or 0
+
+ input_token_details: dict = {}
+ cache_read = anthropic_token_usage.get("cache_read_input_tokens") or 0
+ if cache_read:
+ input_token_details["cache_read"] = cache_read
+
+ cache_creation_obj = anthropic_token_usage.get("cache_creation") or {}
+ if cache_creation_obj:
+ ephemeral_5m = cache_creation_obj.get("ephemeral_5m_input_tokens") or 0
+ ephemeral_1h = cache_creation_obj.get("ephemeral_1h_input_tokens") or 0
+ if ephemeral_5m:
+ input_token_details["ephemeral_5m_input_tokens"] = ephemeral_5m
+ if ephemeral_1h:
+ input_token_details["ephemeral_1h_input_tokens"] = ephemeral_1h
+ else:
+ cache_creation = anthropic_token_usage.get("cache_creation_input_tokens") or 0
+ if cache_creation:
+ input_token_details["cache_creation"] = cache_creation
+
+ # Anthropic cache tokens are ADDITIVE (not subsets of input_tokens like OpenAI).
+ # Sum them into input_tokens so the backend cost calculation is correct.
+ cache_token_sum = sum(input_token_details.values())
+ adjusted_input = input_tokens + cache_token_sum
+ adjusted_total = adjusted_input + output_tokens
+
+ result = UsageMetadata(
+ input_tokens=adjusted_input,
+ output_tokens=output_tokens,
+ total_tokens=adjusted_total,
+ )
+ if input_token_details:
+ result["input_token_details"] = InputTokenDetails(**input_token_details)
+ return result
+
+
+def _message_to_outputs(message: Any) -> dict:
+ """Convert an Anthropic Message to a flat outputs dict with usage_metadata."""
+ # ParsedBetaMessage/ParsedMessage (from beta.messages.parse()) carry user-defined
+ # Pydantic models in parsed_output and ParsedBetaTextBlock in content. These trigger
+ # PydanticSerializationUnexpectedValue warnings because the values do not match the
+ # declared union types in the base BetaMessage schema. Suppress for parsed types.
+ if hasattr(message, "parsed_output"):
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ outputs = message.model_dump()
+ else:
+ outputs = message.model_dump()
+ anthropic_token_usage = outputs.pop("usage", None)
+ if anthropic_token_usage:
+ outputs["usage_metadata"] = _create_usage_metadata(anthropic_token_usage)
+ outputs.pop("type", None)
+
+ content = outputs.get("content") or []
+ tool_use_blocks = [
+ b for b in content if isinstance(b, dict) and b.get("type") == "tool_use"
+ ]
+ if tool_use_blocks:
+ text_parts = [
+ b.get("text", "")
+ for b in content
+ if isinstance(b, dict) and b.get("type") == "text"
+ ]
+ outputs["content"] = "".join(text_parts) or None
+ outputs["tool_calls"] = [
+ {
+ "id": block.get("id", f"call_{i}"),
+ "type": "function",
+ "index": i,
+ "function": {
+ "name": block.get("name", ""),
+ "arguments": _dumps(block.get("input", {})).decode(),
+ },
+ }
+ for i, block in enumerate(tool_use_blocks)
+ ]
+ return outputs
+
+
+def _reduce_chat_chunks(all_chunks: Sequence) -> dict:
+ accumulate = _get_sdk_accumulate_event()
+ if accumulate is None:
+ return {"output": all_chunks}
+ full_message = None
+ for chunk in all_chunks:
+ try:
+ full_message = accumulate(
+ event=chunk,
+ current_snapshot=full_message,
+ )
+ except RuntimeError as e:
+ logger.debug(f"Error accumulating event in Anthropic Wrapper: {e}")
+ return {"output": all_chunks}
+ if full_message is None:
+ return {"output": all_chunks}
+ return _message_to_outputs(full_message)
+
+
+def _reduce_completions(all_chunks: list[Completion]) -> dict:
+ all_content = []
+ for chunk in all_chunks:
+ content = chunk.completion
+ if content is not None:
+ all_content.append(content)
+ content = "".join(all_content)
+ if all_chunks:
+ d = all_chunks[-1].model_dump()
+ d["choices"] = [{"text": content}]
+ else:
+ d = {"choices": [{"text": content}]}
+
+ return d
+
+
+def _process_chat_completion(outputs: Any):
+ try:
+ # Check if outputs is a LegacyAPIResponse wrapper (from with_raw_response).
+ # The Anthropic SDK's LegacyAPIResponse wraps the actual response object.
+ # Call .parse() to extract the Message for tracing.
+ # See: anthropics/anthropic-sdk-python _legacy_response.py#L102
+ if hasattr(outputs, "parse") and callable(outputs.parse):
+ try:
+ outputs = outputs.parse()
+ except Exception:
+ pass
+ return _message_to_outputs(outputs)
+ except BaseException as e:
+ logger.debug(f"Error processing chat completion: {e}")
+ return {"output": outputs}
+
+
+def _get_wrapper(
+ original_create: Callable,
+ name: str,
+ reduce_fn: Callable,
+ prepopulated_invocation_params: dict,
+ tracing_extra: TracingExtra,
+) -> Callable:
+ @functools.wraps(original_create)
+ def create(*args, **kwargs):
+ stream = kwargs.get("stream")
+ decorator = run_helpers.traceable(
+ name=name,
+ run_type="llm",
+ reduce_fn=reduce_fn if stream else None,
+ process_inputs=_strip_not_given,
+ process_outputs=_process_chat_completion,
+ _invocation_params_fn=functools.partial(
+ _infer_ls_params, prepopulated_invocation_params
+ ),
+ **tracing_extra,
+ )
+
+ result = decorator(original_create)(*args, **kwargs)
+ return result
+
+ @functools.wraps(original_create)
+ async def acreate(*args, **kwargs):
+ stream = kwargs.get("stream")
+ decorator = run_helpers.traceable(
+ name=name,
+ run_type="llm",
+ reduce_fn=reduce_fn if stream else None,
+ process_inputs=_strip_not_given,
+ process_outputs=_process_chat_completion,
+ _invocation_params_fn=functools.partial(
+ _infer_ls_params, prepopulated_invocation_params
+ ),
+ **tracing_extra,
+ )
+ result = await decorator(original_create)(*args, **kwargs)
+ return result
+
+ return acreate if run_helpers.is_async(original_create) else create
+
+
+def _get_stream_wrapper(
+ original_stream: Callable,
+ name: str,
+ prepopulated_invocation_params: dict,
+ tracing_extra: TracingExtra,
+) -> Callable:
+ """Create a wrapper for Anthropic's streaming context manager."""
+ is_async = "async" in str(original_stream).lower()
+ configured_traceable = run_helpers.traceable(
+ name=name,
+ reduce_fn=_reduce_chat_chunks,
+ run_type="llm",
+ process_inputs=_strip_not_given,
+ _invocation_params_fn=functools.partial(
+ _infer_ls_params, prepopulated_invocation_params
+ ),
+ **tracing_extra,
+ )
+ configured_traceable_text = run_helpers.traceable(
+ name=name,
+ run_type="llm",
+ process_inputs=_strip_not_given,
+ process_outputs=_process_chat_completion,
+ _invocation_params_fn=functools.partial(
+ _infer_ls_params, prepopulated_invocation_params
+ ),
+ **tracing_extra,
+ )
+
+ if is_async:
+
+ class AsyncMessageStreamWrapper:
+ def __init__(
+ self,
+ wrapped: AsyncMessageStream,
+ **kwargs,
+ ) -> None:
+ self._wrapped = wrapped
+ self._kwargs = kwargs
+
+ @property
+ def text_stream(self):
+ @configured_traceable_text
+ async def _text_stream(**_):
+ async for chunk in self._wrapped.text_stream:
+ yield chunk
+ run_tree = run_helpers.get_current_run_tree()
+ final_message = await self._wrapped.get_final_message()
+ outputs = _message_to_outputs(final_message)
+ run_tree.outputs = outputs
+ if usage := outputs.get("usage_metadata"):
+ run_tree.metadata["usage_metadata"] = usage
+
+ return _text_stream(**self._kwargs)
+
+ @property
+ def response(self) -> httpx.Response:
+ return self._wrapped.response
+
+ @property
+ def request_id(self) -> str | None:
+ return self._wrapped.request_id
+
+ async def __anext__(self) -> MessageStreamEvent:
+ aiter = self.__aiter__()
+ return await aiter.__anext__()
+
+ async def __aiter__(self) -> AsyncIterator[MessageStreamEvent]:
+ @configured_traceable
+ def traced_iter(**_):
+ return self._wrapped.__aiter__()
+
+ async for chunk in traced_iter(**self._kwargs):
+ yield chunk
+
+ async def __aenter__(self) -> Self:
+ await self._wrapped.__aenter__()
+ return self
+
+ async def __aexit__(self, *exc) -> None:
+ await self._wrapped.__aexit__(*exc)
+
+ async def close(self) -> None:
+ await self._wrapped.close()
+
+ async def get_final_message(self) -> Message:
+ return await self._wrapped.get_final_message()
+
+ async def get_final_text(self) -> str:
+ return await self._wrapped.get_final_text()
+
+ async def until_done(self) -> None:
+ await self._wrapped.until_done()
+
+ @property
+ def current_message_snapshot(self) -> Message:
+ return self._wrapped.current_message_snapshot
+
+ class AsyncMessagesStreamManagerWrapper:
+ def __init__(self, **kwargs):
+ self._kwargs = kwargs
+
+ async def __aenter__(self):
+ self._manager = original_stream(**self._kwargs)
+ stream = await self._manager.__aenter__()
+ return AsyncMessageStreamWrapper(stream, **self._kwargs)
+
+ async def __aexit__(self, *exc):
+ await self._manager.__aexit__(*exc)
+
+ return AsyncMessagesStreamManagerWrapper
+ else:
+
+ class MessageStreamWrapper:
+ def __init__(
+ self,
+ wrapped: MessageStream,
+ **kwargs,
+ ) -> None:
+ self._wrapped = wrapped
+ self._kwargs = kwargs
+
+ @property
+ def response(self) -> Any:
+ return self._wrapped.response
+
+ @property
+ def request_id(self) -> str | None:
+ return self._wrapped.request_id # type: ignore[no-any-return]
+
+ @property
+ def text_stream(self):
+ @configured_traceable_text
+ def _text_stream(**_):
+ yield from self._wrapped.text_stream
+ run_tree = run_helpers.get_current_run_tree()
+ final_message = self._wrapped.get_final_message()
+ outputs = _message_to_outputs(final_message)
+ run_tree.outputs = outputs
+ if usage := outputs.get("usage_metadata"):
+ run_tree.metadata["usage_metadata"] = usage
+
+ return _text_stream(**self._kwargs)
+
+ def __next__(self) -> MessageStreamEvent:
+ return self.__iter__().__next__()
+
+ def __iter__(self):
+ @configured_traceable
+ def traced_iter(**_):
+ return self._wrapped.__iter__()
+
+ return traced_iter(**self._kwargs)
+
+ def __enter__(self) -> Self:
+ self._wrapped.__enter__()
+ return self
+
+ def __exit__(self, *exc) -> None:
+ self._wrapped.__exit__(*exc)
+
+ def close(self) -> None:
+ self._wrapped.close()
+
+ def get_final_message(self) -> Message:
+ return self._wrapped.get_final_message()
+
+ def get_final_text(self) -> str:
+ return self._wrapped.get_final_text()
+
+ def until_done(self) -> None:
+ return self._wrapped.until_done()
+
+ @property
+ def current_message_snapshot(self) -> Message:
+ return self._wrapped.current_message_snapshot
+
+ class MessagesStreamManagerWrapper:
+ def __init__(self, **kwargs):
+ self._kwargs = kwargs
+
+ def __enter__(self):
+ self._manager = original_stream(**self._kwargs)
+ return MessageStreamWrapper(self._manager.__enter__(), **self._kwargs)
+
+ def __exit__(self, *exc):
+ self._manager.__exit__(*exc)
+
+ return MessagesStreamManagerWrapper
+
+
+class TracingExtra(TypedDict, total=False):
+ metadata: Optional[Mapping[str, Any]]
+ tags: Optional[list[str]]
+ client: Optional[ls_client.Client]
+
+
+def wrap_anthropic(
+ client: C,
+ *,
+ tracing_extra: Optional[TracingExtra] = None,
+ chat_name: str = "ChatAnthropic",
+ completions_name: str = "Anthropic",
+) -> C:
+ """Patch the Anthropic client to make it traceable.
+
+ Args:
+ client: The client to patch.
+ tracing_extra: Extra tracing information.
+ chat_name: The run name for the messages endpoint.
+ completions_name: The run name for the completions endpoint.
+
+ Returns:
+ The patched client.
+
+ Example:
+ ```python
+ import anthropic
+ from langsmith import wrappers
+
+ client = wrappers.wrap_anthropic(anthropic.Anthropic())
+
+ # Use Anthropic client same as you normally would:
+ system = "You are a helpful assistant."
+ messages = [
+ {
+ "role": "user",
+ "content": "What physics breakthroughs do you predict will happen by 2300?",
+ }
+ ]
+ completion = client.messages.create(
+ model="claude-3-5-sonnet-latest",
+ messages=messages,
+ max_tokens=1000,
+ system=system,
+ )
+ print(completion.content)
+
+ # With raw response to access headers:
+ raw_response = client.messages.with_raw_response.create(
+ model="claude-3-5-sonnet-latest",
+ messages=messages,
+ max_tokens=1000,
+ system=system,
+ )
+ print(raw_response.headers) # Access HTTP headers
+ message = raw_response.parse() # Get parsed response
+
+ # You can also use the streaming context manager:
+ with client.messages.stream(
+ model="claude-3-5-sonnet-latest",
+ messages=messages,
+ max_tokens=1000,
+ system=system,
+ ) as stream:
+ for text in stream.text_stream:
+ print(text, end="", flush=True)
+ message = stream.get_final_message()
+ ```
+ """ # noqa: E501
+ tracing_extra = tracing_extra or {}
+
+ # Extract ls_invocation_params from metadata
+ metadata = dict(tracing_extra.get("metadata") or {})
+ prepopulated_invocation_params = metadata.pop("ls_invocation_params", {})
+
+ # Create new tracing_extra without ls_invocation_params in metadata
+ tracing_extra_rest: TracingExtra = { # type: ignore[assignment]
+ k: v for k, v in tracing_extra.items() if k != "metadata"
+ }
+ if metadata:
+ tracing_extra_rest["metadata"] = metadata # type: ignore[typeddict-item]
+
+ client.messages.create = _get_wrapper( # type: ignore[method-assign]
+ client.messages.create,
+ chat_name,
+ _reduce_chat_chunks,
+ prepopulated_invocation_params,
+ tracing_extra_rest,
+ )
+
+ client.messages.stream = _get_stream_wrapper( # type: ignore[method-assign]
+ client.messages.stream,
+ chat_name,
+ prepopulated_invocation_params,
+ tracing_extra_rest,
+ )
+ client.completions.create = _get_wrapper( # type: ignore[method-assign]
+ client.completions.create,
+ completions_name,
+ _reduce_completions,
+ prepopulated_invocation_params,
+ tracing_extra_rest,
+ )
+
+ if (
+ hasattr(client, "beta")
+ and hasattr(client.beta, "messages")
+ and hasattr(client.beta.messages, "create")
+ ):
+ client.beta.messages.create = _get_wrapper( # type: ignore[method-assign]
+ client.beta.messages.create, # type: ignore
+ chat_name,
+ _reduce_chat_chunks,
+ prepopulated_invocation_params,
+ tracing_extra_rest,
+ )
+
+ if (
+ hasattr(client, "beta")
+ and hasattr(client.beta, "messages")
+ and hasattr(client.beta.messages, "parse")
+ ):
+ client.beta.messages.parse = _get_wrapper( # type: ignore[method-assign]
+ client.beta.messages.parse, # type: ignore
+ chat_name,
+ _reduce_chat_chunks,
+ prepopulated_invocation_params,
+ tracing_extra_rest,
+ )
+ return client
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/_gemini.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/_gemini.py
new file mode 100644
index 0000000000000000000000000000000000000000..f65c40c1ed3356603068046855fde0e8b035457a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/_gemini.py
@@ -0,0 +1,686 @@
+from __future__ import annotations
+
+import base64
+import functools
+import logging
+from collections.abc import Mapping
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Optional,
+ TypeVar,
+ Union,
+)
+
+from typing_extensions import TypedDict
+
+from langsmith import client as ls_client
+from langsmith import run_helpers
+from langsmith._internal._beta_decorator import warn_beta
+from langsmith._internal._orjson import dumps as _dumps
+from langsmith.schemas import InputTokenDetails, OutputTokenDetails, UsageMetadata
+
+if TYPE_CHECKING:
+ from google import genai # type: ignore[import-untyped, attr-defined]
+
+C = TypeVar("C", bound=Union["genai.Client", Any])
+logger = logging.getLogger(__name__)
+
+
+def _strip_none(d: dict) -> dict:
+ """Remove `None` values from dictionary."""
+ return {k: v for k, v in d.items() if v is not None}
+
+
+def _convert_config_for_tracing(kwargs: dict) -> None:
+ """Convert `GenerateContentConfig` to `dict` for LangSmith compatibility."""
+ if "config" in kwargs and not isinstance(kwargs["config"], dict):
+ kwargs["config"] = vars(kwargs["config"])
+
+
+def _to_dict(obj: Any) -> Any:
+ """Serialize a Pydantic/model object to dict (or return as-is for dict/str)."""
+ if isinstance(obj, (dict, str)):
+ return obj
+ if hasattr(obj, "model_dump"):
+ return obj.model_dump()
+ if hasattr(obj, "to_dict"):
+ return obj.to_dict()
+ return obj
+
+
+def _process_gemini_inputs(inputs: dict) -> dict:
+ r"""Process Gemini inputs to normalize them for LangSmith tracing.
+
+ Example:
+ ```txt
+ {"contents": "Hello", "model": "gemini-pro"}
+ → {"messages": [{"role": "user", "content": "Hello"}], "model": "gemini-pro"}
+ {"contents": [{"role": "user", "parts": [{"text": "What is AI?"}]}], "model": "gemini-pro"}
+ → {"messages": [{"role": "user", "content": "What is AI?"}], "model": "gemini-pro"}
+ ```
+ """ # noqa: E501
+ # If contents is not present or not in list format, return as-is
+ contents = inputs.get("contents")
+ if not contents:
+ return inputs
+
+ # Handle string input (simple case)
+ if isinstance(contents, str):
+ return {
+ "messages": [{"role": "user", "content": contents}],
+ "model": inputs.get("model"),
+ **({k: v for k, v in inputs.items() if k not in ("contents", "model")}),
+ }
+
+ # Handle list of content objects (multimodal case)
+ if isinstance(contents, list):
+ # Check if it's a simple list of strings
+ if all(isinstance(item, str) for item in contents):
+ # Each string becomes a separate user message (matches Gemini's behavior)
+ return {
+ "messages": [{"role": "user", "content": item} for item in contents],
+ "model": inputs.get("model"),
+ **({k: v for k, v in inputs.items() if k not in ("contents", "model")}),
+ }
+ # Handle complex multimodal case (dict or types.Content / types.Part objects)
+ messages = []
+ for content in contents:
+ content = _to_dict(content)
+ if not isinstance(content, dict):
+ continue
+ role = content.get("role", "user")
+ raw_parts = content.get("parts", [])
+
+ text_parts: list[str] = []
+ content_parts: list[dict[str, Any]] = []
+
+ for part in raw_parts:
+ part = _to_dict(part)
+ if isinstance(part, str):
+ text_parts.append(part)
+ content_parts.append({"type": "text", "text": part})
+ continue
+ if not isinstance(part, dict):
+ continue
+ if "text" in part and part["text"]:
+ text_parts.append(part["text"])
+ content_parts.append({"type": "text", "text": part["text"]})
+ elif "inline_data" in part:
+ inline_data = _to_dict(part["inline_data"])
+ if not isinstance(inline_data, dict):
+ continue
+ mime_type = inline_data.get("mime_type", "image/jpeg")
+ data = inline_data.get("data", b"")
+
+ if isinstance(data, bytes):
+ data_b64 = base64.b64encode(data).decode("utf-8")
+ else:
+ data_b64 = data
+
+ content_parts.append(
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": f"data:{mime_type};base64,{data_b64}",
+ "detail": "high",
+ },
+ }
+ )
+ elif "functionResponse" in part:
+ function_response = part["functionResponse"]
+ content_parts.append(
+ {
+ "type": "function_response",
+ "function_response": {
+ "name": function_response.get("name"),
+ "response": function_response.get("response", {}),
+ },
+ }
+ )
+ elif "function_call" in part or "functionCall" in part:
+ fc = _to_dict(part.get("function_call") or part.get("functionCall"))
+ if isinstance(fc, dict):
+ content_parts.append(
+ {
+ "type": "function_call",
+ "function_call": {
+ "id": fc.get("id"),
+ "name": fc.get("name"),
+ "arguments": fc.get("args", {}),
+ },
+ }
+ )
+
+ # If only text parts, use simple string format
+ if content_parts and all(p.get("type") == "text" for p in content_parts):
+ message_content: Union[str, list[dict[str, Any]]] = "\n".join(
+ text_parts
+ )
+ else:
+ message_content = content_parts if content_parts else ""
+
+ messages.append({"role": role, "content": message_content})
+
+ return {
+ "messages": messages,
+ "model": inputs.get("model"),
+ **({k: v for k, v in inputs.items() if k not in ("contents", "model")}),
+ }
+
+ # Fallback: return original inputs
+ return inputs
+
+
+def _infer_invocation_params(
+ prepopulated_invocation_params: dict, kwargs: dict
+) -> dict:
+ """Extract invocation parameters for tracing."""
+ stripped = _strip_none(kwargs)
+ config = stripped.get("config", {})
+
+ # Handle both dict config and GenerateContentConfig object
+ if hasattr(config, "temperature"):
+ temperature = config.temperature
+ max_tokens = getattr(config, "max_output_tokens", None)
+ stop = getattr(config, "stop_sequences", None)
+ else:
+ temperature = config.get("temperature")
+ max_tokens = config.get("max_output_tokens")
+ stop = config.get("stop_sequences")
+
+ return {
+ "ls_provider": "google",
+ "ls_model_type": "chat",
+ "ls_model_name": stripped.get("model"),
+ "ls_temperature": temperature,
+ "ls_max_tokens": max_tokens,
+ "ls_stop": stop,
+ "ls_invocation_params": prepopulated_invocation_params,
+ }
+
+
+def _create_usage_metadata(gemini_usage_metadata: dict) -> UsageMetadata:
+ """Convert Gemini usage metadata to LangSmith format."""
+ prompt_token_count = gemini_usage_metadata.get("prompt_token_count") or 0
+ candidates_token_count = gemini_usage_metadata.get("candidates_token_count") or 0
+ cached_content_token_count = (
+ gemini_usage_metadata.get("cached_content_token_count") or 0
+ )
+ thoughts_token_count = gemini_usage_metadata.get("thoughts_token_count") or 0
+ total_token_count = (
+ gemini_usage_metadata.get("total_token_count")
+ or prompt_token_count + candidates_token_count
+ )
+
+ input_token_details: dict = {}
+ if cached_content_token_count:
+ input_token_details["cache_read"] = cached_content_token_count
+ input_token_details["cache_read_over_200k"] = max(
+ 0, cached_content_token_count - 200000
+ )
+ input_token_details["over_200k"] = max(0, prompt_token_count - 200000)
+
+ output_token_details: dict = {}
+ if thoughts_token_count:
+ output_token_details["reasoning"] = thoughts_token_count
+
+ if candidates_token_count:
+ output_token_details["over_200k"] = max(0, candidates_token_count - 200000)
+
+ return UsageMetadata(
+ input_tokens=prompt_token_count,
+ output_tokens=candidates_token_count,
+ total_tokens=total_token_count,
+ input_token_details=InputTokenDetails(
+ **{k: v for k, v in input_token_details.items() if v is not None}
+ ),
+ output_token_details=OutputTokenDetails(
+ **{k: v for k, v in output_token_details.items() if v is not None}
+ ),
+ )
+
+
+def _process_generate_content_response(response: Any) -> dict:
+ """Process Gemini response for tracing."""
+ try:
+ # Convert response to dictionary
+ if hasattr(response, "to_dict"):
+ rdict = response.to_dict()
+ elif hasattr(response, "model_dump"):
+ rdict = response.model_dump()
+ else:
+ rdict = {"text": getattr(response, "text", str(response))}
+
+ # Extract content from candidates if available
+ content_result = ""
+ content_parts = []
+ finish_reason: Optional[str] = None
+ if "candidates" in rdict and rdict["candidates"]:
+ candidate = rdict["candidates"][0]
+ if "content" in candidate:
+ content = candidate["content"]
+ if "parts" in content and content["parts"]:
+ for part in content["parts"]:
+ # Handle text parts
+ if "text" in part and part["text"]:
+ content_result += part["text"]
+ content_parts.append({"type": "text", "text": part["text"]})
+ # Handle inline data (images) in response
+ elif "inline_data" in part and part["inline_data"] is not None:
+ inline_data = part["inline_data"]
+ mime_type = inline_data.get("mime_type", "image/jpeg")
+ data = inline_data.get("data", b"")
+
+ # Convert bytes to base64 string if needed
+ if isinstance(data, bytes):
+ data_b64 = base64.b64encode(data).decode("utf-8")
+ else:
+ data_b64 = data # Already a string
+
+ content_parts.append(
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": f"data:{mime_type};base64,{data_b64}",
+ "detail": "high",
+ },
+ }
+ )
+ elif "function_call" in part or "functionCall" in part:
+ fc = _to_dict(
+ part.get("function_call") or part.get("functionCall")
+ )
+ if isinstance(fc, dict):
+ content_parts.append(
+ {
+ "type": "function_call",
+ "function_call": {
+ "id": fc.get("id"),
+ "name": fc.get("name"),
+ "arguments": fc.get("args", {}),
+ },
+ }
+ )
+ if "finish_reason" in candidate and candidate["finish_reason"]:
+ finish_reason = candidate["finish_reason"]
+ elif "text" in rdict:
+ content_result = rdict["text"]
+ content_parts.append({"type": "text", "text": content_result})
+
+ # Build chat-like response format - use OpenAI-compatible format for tool calls
+ tool_calls = [p for p in content_parts if p.get("type") == "function_call"]
+ if tool_calls:
+ # OpenAI-compatible format for LangSmith UI
+ result = {
+ "content": content_result or None,
+ "role": "assistant",
+ "finish_reason": finish_reason,
+ "tool_calls": [
+ {
+ "id": tc["function_call"].get("id") or f"call_{i}",
+ "type": "function",
+ "index": i,
+ "function": {
+ "name": tc["function_call"]["name"],
+ "arguments": _dumps(
+ tc["function_call"]["arguments"]
+ ).decode(),
+ },
+ }
+ for i, tc in enumerate(tool_calls)
+ ],
+ }
+ elif len(content_parts) > 1 or (
+ content_parts and content_parts[0]["type"] != "text"
+ ):
+ # Use structured format for mixed non-tool content
+ result = {
+ "content": content_parts,
+ "role": "assistant",
+ "finish_reason": finish_reason,
+ }
+ else:
+ # Use simple string format for text-only responses
+ result = {
+ "content": content_result,
+ "role": "assistant",
+ "finish_reason": finish_reason,
+ }
+
+ # Extract and convert usage metadata
+ usage_metadata = rdict.get("usage_metadata")
+ usage_dict: UsageMetadata = UsageMetadata(
+ input_tokens=0, output_tokens=0, total_tokens=0
+ )
+ if usage_metadata:
+ usage_dict = _create_usage_metadata(usage_metadata)
+
+ # Return in a format that avoids stringification by LangSmith
+ if result.get("tool_calls"):
+ # For responses with tool calls, return structured format
+ return {
+ "content": result["content"],
+ "role": "assistant",
+ "finish_reason": finish_reason,
+ "tool_calls": result["tool_calls"],
+ "usage_metadata": usage_dict,
+ }
+ else:
+ # For simple text responses, return minimal structure with usage metadata
+ if isinstance(result["content"], str):
+ return {
+ "content": result["content"],
+ "role": "assistant",
+ "finish_reason": finish_reason,
+ "usage_metadata": usage_dict,
+ }
+ else:
+ # For multimodal content, return structured format with usage metadata
+ return {
+ "content": result["content"],
+ "role": "assistant",
+ "finish_reason": finish_reason,
+ "usage_metadata": usage_dict,
+ }
+ except Exception as e:
+ logger.debug(f"Error processing Gemini response: {e}")
+ return {"output": response}
+
+
+def _reduce_generate_content_chunks(all_chunks: list) -> dict:
+ """Reduce streaming chunks into a single response."""
+ if not all_chunks:
+ return {
+ "content": "",
+ "usage_metadata": UsageMetadata(
+ input_tokens=0, output_tokens=0, total_tokens=0
+ ),
+ }
+
+ # Accumulate text from all chunks
+ full_text = ""
+ last_chunk = None
+
+ for chunk in all_chunks:
+ try:
+ if hasattr(chunk, "text") and chunk.text:
+ full_text += chunk.text
+ last_chunk = chunk
+ except Exception as e:
+ logger.debug(f"Error processing chunk: {e}")
+
+ # Extract usage metadata from the last chunk
+ usage_metadata: UsageMetadata = UsageMetadata(
+ input_tokens=0, output_tokens=0, total_tokens=0
+ )
+ if last_chunk:
+ try:
+ if hasattr(last_chunk, "usage_metadata") and last_chunk.usage_metadata:
+ if hasattr(last_chunk.usage_metadata, "to_dict"):
+ usage_dict = last_chunk.usage_metadata.to_dict()
+ elif hasattr(last_chunk.usage_metadata, "model_dump"):
+ usage_dict = last_chunk.usage_metadata.model_dump()
+ else:
+ usage_dict = {
+ "prompt_token_count": getattr(
+ last_chunk.usage_metadata, "prompt_token_count", 0
+ ),
+ "candidates_token_count": getattr(
+ last_chunk.usage_metadata, "candidates_token_count", 0
+ ),
+ "cached_content_token_count": getattr(
+ last_chunk.usage_metadata, "cached_content_token_count", 0
+ ),
+ "thoughts_token_count": getattr(
+ last_chunk.usage_metadata, "thoughts_token_count", 0
+ ),
+ "total_token_count": getattr(
+ last_chunk.usage_metadata, "total_token_count", 0
+ ),
+ }
+ # Add usage_metadata to both run.extra AND outputs
+ usage_metadata = _create_usage_metadata(usage_dict)
+
+ except Exception as e:
+ logger.debug(f"Error extracting metadata from last chunk: {e}")
+
+ # Return minimal structure with usage_metadata in outputs
+ return {
+ "content": full_text,
+ "usage_metadata": usage_metadata,
+ }
+
+
+def _get_wrapper(
+ original_generate: Callable,
+ name: str,
+ prepopulated_invocation_params: dict,
+ tracing_extra: Optional[TracingExtra] = None,
+ is_streaming: bool = False,
+) -> Callable:
+ """Create a wrapper for Gemini's `generate_content` methods."""
+ textra = tracing_extra or {}
+
+ @functools.wraps(original_generate)
+ def generate(*args, **kwargs):
+ # Handle config object before tracing setup
+ _convert_config_for_tracing(kwargs)
+
+ decorator = run_helpers.traceable(
+ name=name,
+ run_type="llm",
+ reduce_fn=_reduce_generate_content_chunks if is_streaming else None,
+ process_inputs=_process_gemini_inputs,
+ process_outputs=(
+ _process_generate_content_response if not is_streaming else None
+ ),
+ _invocation_params_fn=functools.partial(
+ _infer_invocation_params, prepopulated_invocation_params
+ ),
+ **textra,
+ )
+
+ return decorator(original_generate)(*args, **kwargs)
+
+ @functools.wraps(original_generate)
+ async def agenerate(*args, **kwargs):
+ # Handle config object before tracing setup
+ _convert_config_for_tracing(kwargs)
+
+ decorator = run_helpers.traceable(
+ name=name,
+ run_type="llm",
+ reduce_fn=_reduce_generate_content_chunks if is_streaming else None,
+ process_inputs=_process_gemini_inputs,
+ process_outputs=(
+ _process_generate_content_response if not is_streaming else None
+ ),
+ _invocation_params_fn=functools.partial(
+ _infer_invocation_params, prepopulated_invocation_params
+ ),
+ **textra,
+ )
+
+ return await decorator(original_generate)(*args, **kwargs)
+
+ return agenerate if run_helpers.is_async(original_generate) else generate
+
+
+class TracingExtra(TypedDict, total=False):
+ metadata: Optional[Mapping[str, Any]]
+ tags: Optional[list[str]]
+ client: Optional[ls_client.Client]
+
+
+@warn_beta
+def wrap_gemini(
+ client: C,
+ *,
+ tracing_extra: Optional[TracingExtra] = None,
+ chat_name: str = "ChatGoogleGenerativeAI",
+) -> C:
+ """Patch the Google Gen AI client to make it traceable.
+
+ !!! warning
+
+ **BETA**: This wrapper is in beta.
+
+ Supports:
+ - `generate_content` and `generate_content_stream` methods
+ - Sync and async clients
+ - Streaming and non-streaming responses
+ - Tool/function calling with proper UI rendering
+ - Multimodal inputs (text + images)
+ - Image generation with `inline_data` support
+ - Token usage tracking including reasoning tokens
+
+ Args:
+ client: The Google Gen AI client to patch.
+ tracing_extra: Extra tracing information.
+ chat_name: The run name for the chat endpoint.
+
+ Returns:
+ The patched client.
+
+ Example:
+ ```python
+ from google import genai
+ from google.genai import types
+ from langsmith import wrappers
+
+ # Use Google Gen AI client same as you normally would.
+ client = wrappers.wrap_gemini(genai.Client(api_key="your-api-key"))
+
+ # Basic text generation:
+ response = client.models.generate_content(
+ model="gemini-2.5-flash",
+ contents="Why is the sky blue?",
+ )
+ print(response.text)
+
+ # Streaming:
+ for chunk in client.models.generate_content_stream(
+ model="gemini-2.5-flash",
+ contents="Tell me a story",
+ ):
+ print(chunk.text, end="")
+
+ # Tool/Function calling:
+ schedule_meeting_function = {
+ "name": "schedule_meeting",
+ "description": "Schedules a meeting with specified attendees.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "attendees": {"type": "array", "items": {"type": "string"}},
+ "date": {"type": "string"},
+ "time": {"type": "string"},
+ "topic": {"type": "string"},
+ },
+ "required": ["attendees", "date", "time", "topic"],
+ },
+ }
+
+ tools = types.Tool(function_declarations=[schedule_meeting_function])
+ config = types.GenerateContentConfig(tools=[tools])
+
+ response = client.models.generate_content(
+ model="gemini-2.5-flash",
+ contents="Schedule a meeting with Bob and Alice tomorrow at 2 PM.",
+ config=config,
+ )
+
+ # Image generation:
+ response = client.models.generate_content(
+ model="gemini-2.5-flash-image",
+ contents=["Create a picture of a futuristic city"],
+ )
+
+ # Save generated image
+ from io import BytesIO
+ from PIL import Image
+
+ for part in response.candidates[0].content.parts:
+ if part.inline_data is not None:
+ image = Image.open(BytesIO(part.inline_data.data))
+ image.save("generated_image.png")
+ ```
+
+ !!! version-added "Added in `langsmith` 0.4.33"
+
+ Initial beta release of Google Gemini wrapper.
+
+ """
+ tracing_extra = tracing_extra or {}
+
+ # Extract ls_invocation_params from metadata
+ metadata = dict(tracing_extra.get("metadata") or {})
+ prepopulated_invocation_params = metadata.pop("ls_invocation_params", {})
+
+ # Create new tracing_extra without ls_invocation_params in metadata
+ tracing_extra_rest: TracingExtra = { # type: ignore[assignment]
+ k: v for k, v in tracing_extra.items() if k != "metadata"
+ }
+ if metadata:
+ tracing_extra_rest["metadata"] = metadata # type: ignore[typeddict-item]
+
+ # Check if already wrapped to prevent double-wrapping
+ if (
+ hasattr(client, "models")
+ and hasattr(client.models, "generate_content")
+ and hasattr(client.models.generate_content, "__wrapped__")
+ ):
+ raise ValueError(
+ "This Google Gen AI client has already been wrapped. "
+ "Wrapping a client multiple times is not supported."
+ )
+
+ # Wrap synchronous methods
+ if hasattr(client, "models") and hasattr(client.models, "generate_content"):
+ client.models.generate_content = _get_wrapper( # type: ignore[method-assign]
+ client.models.generate_content,
+ chat_name,
+ prepopulated_invocation_params,
+ tracing_extra=tracing_extra_rest,
+ is_streaming=False,
+ )
+
+ if hasattr(client, "models") and hasattr(client.models, "generate_content_stream"):
+ client.models.generate_content_stream = _get_wrapper( # type: ignore[method-assign]
+ client.models.generate_content_stream,
+ chat_name,
+ prepopulated_invocation_params,
+ tracing_extra=tracing_extra_rest,
+ is_streaming=True,
+ )
+
+ # Wrap async methods (aio namespace)
+ if (
+ hasattr(client, "aio")
+ and hasattr(client.aio, "models")
+ and hasattr(client.aio.models, "generate_content")
+ ):
+ client.aio.models.generate_content = _get_wrapper( # type: ignore[method-assign]
+ client.aio.models.generate_content,
+ chat_name,
+ prepopulated_invocation_params,
+ tracing_extra=tracing_extra_rest,
+ is_streaming=False,
+ )
+
+ if (
+ hasattr(client, "aio")
+ and hasattr(client.aio, "models")
+ and hasattr(client.aio.models, "generate_content_stream")
+ ):
+ client.aio.models.generate_content_stream = _get_wrapper( # type: ignore[method-assign]
+ client.aio.models.generate_content_stream,
+ chat_name,
+ prepopulated_invocation_params,
+ tracing_extra=tracing_extra_rest,
+ is_streaming=True,
+ )
+
+ return client
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/_openai.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/_openai.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffaa1eec487fc666ffb5898f0cd05bbbef827693
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/_openai.py
@@ -0,0 +1,648 @@
+from __future__ import annotations
+
+import functools
+import logging
+from collections import defaultdict
+from collections.abc import Mapping
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Optional,
+ TypeVar,
+ Union,
+)
+
+from typing_extensions import TypedDict
+
+from langsmith import client as ls_client
+from langsmith import run_helpers
+from langsmith.schemas import InputTokenDetails, OutputTokenDetails, UsageMetadata
+
+if TYPE_CHECKING:
+ from openai import AsyncOpenAI, OpenAI
+ from openai.types.chat.chat_completion_chunk import (
+ ChatCompletionChunk,
+ Choice,
+ ChoiceDeltaToolCall,
+ )
+ from openai.types.completion import Completion
+ from openai.types.responses import ResponseStreamEvent # type: ignore
+
+# Any is used since it may work with Azure or other providers
+C = TypeVar("C", bound=Union["OpenAI", "AsyncOpenAI", Any])
+logger = logging.getLogger(__name__)
+
+
+@functools.lru_cache
+def _get_omit_types() -> tuple[type, ...]:
+ """Get NotGiven/Omit sentinel types used by OpenAI SDK."""
+ types: list[type[Any]] = []
+ try:
+ from openai._types import NotGiven, Omit
+
+ types.append(NotGiven)
+ types.append(Omit)
+ except ImportError:
+ pass
+
+ return tuple(types)
+
+
+def _strip_not_given(d: dict) -> dict:
+ try:
+ omit_types = _get_omit_types()
+ if not omit_types:
+ return d
+ return {
+ k: v
+ for k, v in d.items()
+ if not (isinstance(v, omit_types) or (k.startswith("extra_") and v is None))
+ }
+ except Exception as e:
+ logger.error(f"Error stripping NotGiven: {e}")
+ return d
+
+
+def _process_inputs(d: dict) -> dict:
+ """Strip `NotGiven` values and serialize `text_format` to JSON schema."""
+ d = _strip_not_given(d)
+
+ # Convert text_format (Pydantic model) to JSON schema if present
+ if "text_format" in d:
+ text_format = d["text_format"]
+ if hasattr(text_format, "model_json_schema"):
+ try:
+ return {
+ **d,
+ "text_format": text_format.model_json_schema(),
+ }
+ except Exception:
+ pass
+ return d
+
+
+def _infer_invocation_params(
+ model_type: str,
+ provider: str,
+ prepopulated_invocation_params: dict,
+ use_responses_api: bool,
+ kwargs: dict,
+):
+ stripped = _strip_not_given(kwargs)
+
+ stop = stripped.get("stop")
+ if stop and isinstance(stop, str):
+ stop = [stop]
+
+ # Allowlist of safe invocation parameters to include
+ # Only include known, non-sensitive parameters
+ allowed_invocation_keys = {
+ "frequency_penalty",
+ "n",
+ "logit_bias",
+ "logprobs",
+ "modalities",
+ "parallel_tool_calls",
+ "prediction",
+ "presence_penalty",
+ "prompt_cache_key",
+ "reasoning",
+ "reasoning_effort",
+ "response_format",
+ "seed",
+ "service_tier",
+ "stream_options",
+ "top_logprobs",
+ "top_p",
+ "truncation",
+ "user",
+ "verbosity",
+ "web_search_options",
+ }
+
+ # Only include allowlisted parameters
+ invocation_params = {
+ k: v for k, v in stripped.items() if k in allowed_invocation_keys
+ }
+
+ if use_responses_api:
+ invocation_params["use_responses_api"] = True
+
+ return {
+ "ls_provider": provider,
+ "ls_model_type": model_type,
+ "ls_model_name": stripped.get("model"),
+ "ls_temperature": stripped.get("temperature"),
+ "ls_max_tokens": stripped.get("max_tokens")
+ or stripped.get("max_completion_tokens")
+ or stripped.get("max_output_tokens"),
+ "ls_stop": stop,
+ "ls_invocation_params": {
+ **prepopulated_invocation_params,
+ **invocation_params,
+ },
+ }
+
+
+def _reduce_choices(choices: list[Choice]) -> dict:
+ reversed_choices = list(reversed(choices))
+ message: dict[str, Any] = {
+ "role": "assistant",
+ "content": "",
+ }
+ for c in reversed_choices:
+ if hasattr(c, "delta") and getattr(c.delta, "role", None):
+ message["role"] = c.delta.role
+ break
+ tool_calls: defaultdict[int, list[ChoiceDeltaToolCall]] = defaultdict(list)
+ for c in choices:
+ if hasattr(c, "delta"):
+ if getattr(c.delta, "content", None):
+ message["content"] += c.delta.content
+ if getattr(c.delta, "function_call", None):
+ if not message.get("function_call"):
+ message["function_call"] = {"name": "", "arguments": ""}
+ name_ = getattr(c.delta.function_call, "name", None)
+ if name_:
+ message["function_call"]["name"] += name_
+ arguments_ = getattr(c.delta.function_call, "arguments", None)
+ if arguments_:
+ message["function_call"]["arguments"] += arguments_
+ if getattr(c.delta, "tool_calls", None):
+ tool_calls_list = c.delta.tool_calls
+ if tool_calls_list is not None:
+ for tool_call in tool_calls_list:
+ tool_calls[tool_call.index].append(tool_call)
+ if tool_calls:
+ message["tool_calls"] = [None for _ in range(max(tool_calls.keys()) + 1)]
+ for index, tool_call_chunks in tool_calls.items():
+ message["tool_calls"][index] = {
+ "index": index,
+ "id": next((c.id for c in tool_call_chunks if c.id), None),
+ "type": next((c.type for c in tool_call_chunks if c.type), None),
+ "function": {"name": "", "arguments": ""},
+ }
+ for chunk in tool_call_chunks:
+ if getattr(chunk, "function", None):
+ name_ = getattr(chunk.function, "name", None)
+ if name_:
+ message["tool_calls"][index]["function"]["name"] += name_
+ arguments_ = getattr(chunk.function, "arguments", None)
+ if arguments_:
+ message["tool_calls"][index]["function"]["arguments"] += (
+ arguments_
+ )
+ return {
+ "index": getattr(choices[0], "index", 0) if choices else 0,
+ "finish_reason": next(
+ (
+ c.finish_reason
+ for c in reversed_choices
+ if getattr(c, "finish_reason", None)
+ ),
+ None,
+ ),
+ "message": message,
+ }
+
+
+def _reduce_chat(all_chunks: list[ChatCompletionChunk]) -> dict:
+ choices_by_index: defaultdict[int, list[Choice]] = defaultdict(list)
+ for chunk in all_chunks:
+ for choice in chunk.choices:
+ choices_by_index[choice.index].append(choice)
+ if all_chunks:
+ d = all_chunks[-1].model_dump()
+ d["choices"] = [
+ _reduce_choices(choices) for choices in choices_by_index.values()
+ ]
+ else:
+ d = {"choices": [{"message": {"role": "assistant", "content": ""}}]}
+ # streamed outputs don't go through `process_outputs`
+ # so we need to flatten metadata here
+ oai_token_usage = d.pop("usage", None)
+ d["usage_metadata"] = (
+ _create_usage_metadata(oai_token_usage) if oai_token_usage else None
+ )
+ return d
+
+
+def _reduce_completions(all_chunks: list[Completion]) -> dict:
+ all_content = []
+ for chunk in all_chunks:
+ content = chunk.choices[0].text
+ if content is not None:
+ all_content.append(content)
+ content = "".join(all_content)
+ if all_chunks:
+ d = all_chunks[-1].model_dump()
+ d["choices"] = [{"text": content}]
+ else:
+ d = {"choices": [{"text": content}]}
+
+ return d
+
+
+def _create_usage_metadata(
+ oai_token_usage: dict, service_tier: Optional[str] = None
+) -> UsageMetadata:
+ recognized_service_tier = (
+ service_tier if service_tier in ["priority", "flex"] else None
+ )
+ service_tier_prefix = (
+ f"{recognized_service_tier}_" if recognized_service_tier else ""
+ )
+
+ input_tokens = (
+ oai_token_usage.get("prompt_tokens") or oai_token_usage.get("input_tokens") or 0
+ )
+ output_tokens = (
+ oai_token_usage.get("completion_tokens")
+ or oai_token_usage.get("output_tokens")
+ or 0
+ )
+ total_tokens = oai_token_usage.get("total_tokens") or input_tokens + output_tokens
+ input_token_details: dict = {
+ "audio": (
+ oai_token_usage.get("prompt_tokens_details")
+ or oai_token_usage.get("input_tokens_details")
+ or {}
+ ).get("audio_tokens"),
+ f"{service_tier_prefix}cache_read": (
+ oai_token_usage.get("prompt_tokens_details")
+ or oai_token_usage.get("input_tokens_details")
+ or {}
+ ).get("cached_tokens"),
+ }
+ output_token_details: dict = {
+ "audio": (
+ oai_token_usage.get("completion_tokens_details")
+ or oai_token_usage.get("output_tokens_details")
+ or {}
+ ).get("audio_tokens"),
+ f"{service_tier_prefix}reasoning": (
+ oai_token_usage.get("completion_tokens_details")
+ or oai_token_usage.get("output_tokens_details")
+ or {}
+ ).get("reasoning_tokens"),
+ }
+
+ if recognized_service_tier:
+ # Avoid counting cache read and reasoning tokens towards the
+ # service tier token count since service tier tokens are already
+ # priced differently
+ input_token_details[recognized_service_tier] = input_tokens - (
+ input_token_details.get(f"{service_tier_prefix}cache_read") or 0
+ )
+ output_token_details[recognized_service_tier] = output_tokens - (
+ output_token_details.get(f"{service_tier_prefix}reasoning") or 0
+ )
+
+ return UsageMetadata(
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ total_tokens=total_tokens,
+ input_token_details=InputTokenDetails(
+ **{k: v for k, v in input_token_details.items() if v is not None}
+ ),
+ output_token_details=OutputTokenDetails(
+ **{k: v for k, v in output_token_details.items() if v is not None}
+ ),
+ )
+
+
+def _process_chat_completion(outputs: Any):
+ try:
+ # Check if outputs is an APIResponse wrapper (from with_raw_response).
+ # The OpenAI SDK's APIResponse wraps the actual response object.
+ # Call .parse() to extract the ChatCompletion/Completion for tracing.
+ # See: github.com/openai/openai-python/blob/main/src/openai/_response.py#L285
+ if hasattr(outputs, "parse") and callable(outputs.parse):
+ try:
+ outputs = outputs.parse()
+ except Exception:
+ pass
+
+ rdict = outputs.model_dump()
+ oai_token_usage = rdict.pop("usage", None)
+ rdict["usage_metadata"] = (
+ _create_usage_metadata(oai_token_usage, rdict.get("service_tier"))
+ if oai_token_usage
+ else None
+ )
+ return rdict
+ except BaseException as e:
+ logger.debug(f"Error processing chat completion: {e}")
+ return {"output": outputs}
+
+
+def _get_wrapper(
+ original_create: Callable,
+ name: str,
+ reduce_fn: Callable,
+ tracing_extra: Optional[TracingExtra] = None,
+ invocation_params_fn: Optional[Callable] = None,
+ process_outputs: Optional[Callable] = None,
+) -> Callable:
+ textra = tracing_extra or {}
+
+ @functools.wraps(original_create)
+ def create(*args, **kwargs):
+ decorator = run_helpers.traceable(
+ name=name,
+ run_type="llm",
+ reduce_fn=reduce_fn if kwargs.get("stream") is True else None,
+ process_inputs=_process_inputs,
+ _invocation_params_fn=invocation_params_fn,
+ process_outputs=process_outputs,
+ **textra,
+ )
+
+ return decorator(original_create)(*args, **kwargs)
+
+ @functools.wraps(original_create)
+ async def acreate(*args, **kwargs):
+ decorator = run_helpers.traceable(
+ name=name,
+ run_type="llm",
+ reduce_fn=reduce_fn if kwargs.get("stream") is True else None,
+ process_inputs=_process_inputs,
+ _invocation_params_fn=invocation_params_fn,
+ process_outputs=process_outputs,
+ **textra,
+ )
+ return await decorator(original_create)(*args, **kwargs)
+
+ return acreate if run_helpers.is_async(original_create) else create
+
+
+def _get_parse_wrapper(
+ original_parse: Callable,
+ name: str,
+ process_outputs: Callable,
+ tracing_extra: Optional[TracingExtra] = None,
+ invocation_params_fn: Optional[Callable] = None,
+) -> Callable:
+ textra = tracing_extra or {}
+
+ @functools.wraps(original_parse)
+ def parse(*args, **kwargs):
+ decorator = run_helpers.traceable(
+ name=name,
+ run_type="llm",
+ reduce_fn=None,
+ process_inputs=_process_inputs,
+ _invocation_params_fn=invocation_params_fn,
+ process_outputs=process_outputs,
+ **textra,
+ )
+ return decorator(original_parse)(*args, **kwargs)
+
+ @functools.wraps(original_parse)
+ async def aparse(*args, **kwargs):
+ decorator = run_helpers.traceable(
+ name=name,
+ run_type="llm",
+ reduce_fn=None,
+ process_inputs=_process_inputs,
+ _invocation_params_fn=invocation_params_fn,
+ process_outputs=process_outputs,
+ **textra,
+ )
+ return await decorator(original_parse)(*args, **kwargs)
+
+ return aparse if run_helpers.is_async(original_parse) else parse
+
+
+def _reduce_response_events(events: list[ResponseStreamEvent]) -> dict:
+ for event in events:
+ if event.type == "response.completed":
+ return _process_responses_api_output(event.response)
+ return {}
+
+
+class TracingExtra(TypedDict, total=False):
+ metadata: Optional[Mapping[str, Any]]
+ tags: Optional[list[str]]
+ client: Optional[ls_client.Client]
+
+
+def wrap_openai(
+ client: C,
+ *,
+ tracing_extra: Optional[TracingExtra] = None,
+ chat_name: str = "ChatOpenAI",
+ completions_name: str = "OpenAI",
+) -> C:
+ """Patch the OpenAI client to make it traceable.
+
+ Supports:
+ - Chat and Responses API's
+ - Sync and async OpenAI clients
+ - `create` and `parse` methods
+ - With and without streaming
+ - `with_raw_response` API for accessing HTTP headers
+
+ Args:
+ client: The client to patch.
+ tracing_extra: Extra tracing information.
+ chat_name: The run name for the chat completions endpoint.
+ completions_name: The run name for the completions endpoint.
+
+ Returns:
+ The patched client.
+
+ Example:
+ ```python
+ import openai
+ from langsmith import wrappers
+
+ # Use OpenAI client same as you normally would.
+ client = wrappers.wrap_openai(openai.OpenAI())
+
+ # Chat API:
+ messages = [
+ {"role": "system", "content": "You are a helpful assistant."},
+ {
+ "role": "user",
+ "content": "What physics breakthroughs do you predict will happen by 2300?",
+ },
+ ]
+ completion = client.chat.completions.create(
+ model="gpt-4o-mini", messages=messages
+ )
+ print(completion.choices[0].message.content)
+
+ # Responses API:
+ response = client.responses.create(
+ model="gpt-4o-mini",
+ messages=messages,
+ )
+ print(response.output_text)
+
+ # With raw response to access headers:
+ raw_response = client.chat.completions.with_raw_response.create(
+ model="gpt-4o-mini", messages=messages
+ )
+ print(raw_response.headers) # Access HTTP headers
+ completion = raw_response.parse() # Get parsed response
+ ```
+
+ !!! warning "Behavior changed in `langsmith` 0.3.16"
+
+ Support for Responses API added.
+
+ !!! warning "Behavior changed in `langsmith` 0.3.x"
+
+ Support for `with_raw_response` API added.
+ """ # noqa: E501
+ tracing_extra = tracing_extra or {}
+
+ # Extract ls_invocation_params from metadata
+ metadata = dict(tracing_extra.get("metadata") or {})
+ prepopulated_invocation_params = metadata.pop("ls_invocation_params", {})
+
+ # Create new tracing_extra without ls_invocation_params in metadata
+ tracing_extra_rest: TracingExtra = { # type: ignore[assignment]
+ k: v for k, v in tracing_extra.items() if k != "metadata"
+ }
+ if metadata:
+ tracing_extra_rest["metadata"] = metadata # type: ignore[typeddict-item]
+
+ ls_provider = "openai"
+ try:
+ from openai import AsyncAzureOpenAI, AzureOpenAI
+
+ if isinstance(client, AzureOpenAI) or isinstance(client, AsyncAzureOpenAI):
+ ls_provider = "azure"
+ chat_name = "AzureChatOpenAI"
+ completions_name = "AzureOpenAI"
+ except ImportError:
+ pass
+
+ # First wrap the create methods - these handle non-streaming cases
+ client.chat.completions.create = _get_wrapper( # type: ignore[method-assign]
+ client.chat.completions.create,
+ chat_name,
+ _reduce_chat,
+ tracing_extra=tracing_extra_rest,
+ invocation_params_fn=functools.partial(
+ _infer_invocation_params,
+ "chat",
+ ls_provider,
+ prepopulated_invocation_params,
+ False,
+ ),
+ process_outputs=_process_chat_completion,
+ )
+
+ client.completions.create = _get_wrapper( # type: ignore[method-assign]
+ client.completions.create,
+ completions_name,
+ _reduce_completions,
+ tracing_extra=tracing_extra_rest,
+ invocation_params_fn=functools.partial(
+ _infer_invocation_params,
+ "llm",
+ ls_provider,
+ prepopulated_invocation_params,
+ False,
+ ),
+ )
+
+ # Wrap beta.chat.completions.parse if it exists
+ if (
+ hasattr(client, "beta")
+ and hasattr(client.beta, "chat")
+ and hasattr(client.beta.chat, "completions")
+ and hasattr(client.beta.chat.completions, "parse")
+ ):
+ client.beta.chat.completions.parse = _get_parse_wrapper( # type: ignore[method-assign]
+ client.beta.chat.completions.parse, # type: ignore
+ chat_name,
+ _process_chat_completion,
+ tracing_extra=tracing_extra_rest,
+ invocation_params_fn=functools.partial(
+ _infer_invocation_params,
+ "chat",
+ ls_provider,
+ prepopulated_invocation_params,
+ False,
+ ),
+ )
+
+ # Wrap chat.completions.parse if it exists
+ if (
+ hasattr(client, "chat")
+ and hasattr(client.chat, "completions")
+ and hasattr(client.chat.completions, "parse")
+ ):
+ client.chat.completions.parse = _get_parse_wrapper( # type: ignore[method-assign]
+ client.chat.completions.parse, # type: ignore
+ chat_name,
+ _process_chat_completion,
+ tracing_extra=tracing_extra_rest,
+ invocation_params_fn=functools.partial(
+ _infer_invocation_params,
+ "chat",
+ ls_provider,
+ prepopulated_invocation_params,
+ False,
+ ),
+ )
+
+ # For the responses API: "client.responses.create(**kwargs)"
+ if hasattr(client, "responses"):
+ if hasattr(client.responses, "create"):
+ client.responses.create = _get_wrapper( # type: ignore[method-assign]
+ client.responses.create,
+ chat_name,
+ _reduce_response_events,
+ process_outputs=_process_responses_api_output,
+ tracing_extra=tracing_extra_rest,
+ invocation_params_fn=functools.partial(
+ _infer_invocation_params,
+ "chat",
+ ls_provider,
+ prepopulated_invocation_params,
+ True,
+ ),
+ )
+ if hasattr(client.responses, "parse"):
+ client.responses.parse = _get_parse_wrapper( # type: ignore[method-assign]
+ client.responses.parse,
+ chat_name,
+ _process_responses_api_output,
+ tracing_extra=tracing_extra_rest,
+ invocation_params_fn=functools.partial(
+ _infer_invocation_params,
+ "chat",
+ ls_provider,
+ prepopulated_invocation_params,
+ True,
+ ),
+ )
+
+ return client
+
+
+def _process_responses_api_output(response: Any) -> dict:
+ if response:
+ try:
+ # Unwrap APIResponse from with_raw_response for tracing
+ if hasattr(response, "parse") and callable(response.parse):
+ try:
+ response = response.parse()
+ except Exception:
+ pass
+
+ output = response.model_dump(exclude_none=True, mode="json")
+ if usage := output.pop("usage", None):
+ output["usage_metadata"] = _create_usage_metadata(
+ usage, output.get("service_tier")
+ )
+ return output
+ except Exception:
+ return {"output": response}
+ return {}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/_openai_agents.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/_openai_agents.py
new file mode 100644
index 0000000000000000000000000000000000000000..804b9bd5893b42bc0b9029ad84cb06b7812b667f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/langsmith/wrappers/_openai_agents.py
@@ -0,0 +1,19 @@
+"""Tombstone module for backward compatibility.
+
+This module has been moved to `langsmith.integrations.openai_agents`.
+
+Imports from this location are deprecated but will continue to work.
+"""
+
+import warnings
+
+from langsmith.integrations.openai_agents_sdk import OpenAIAgentsTracingProcessor
+
+warnings.warn(
+ "langsmith.wrappers._openai_agents is deprecated and has been moved to "
+ "langsmith.integrations.openai_agents_sdk. Please update your imports.",
+ DeprecationWarning,
+ stacklevel=2,
+)
+
+__all__ = ["OpenAIAgentsTracingProcessor"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f2c9684cbc4ab6c9e36f442d0974efcb60284c8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/_compat.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/_compat.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0152c3706af2ce425837ee88cbd3917cd2ac86b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/_compat.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/_punycode.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/_punycode.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a729435f8e9e192ee69484a0a9f6c3c5f834564
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/_punycode.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/main.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/main.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93f1fbefb4b25ca4a69bbfd12a0206d3bb9ca96a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/main.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/parser_block.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/parser_block.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1242cf1dcb7a7695821da5167e1331f2bf3d2ef9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/parser_block.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/parser_core.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/parser_core.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d0ae75480be87b03dedf853d2e7ea140fa62f326
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/parser_core.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/parser_inline.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/parser_inline.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..70de87bd3daa6c608de3e12120342b3f6514d0b0
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/parser_inline.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/renderer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/renderer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f08f38d3168919df63e9a76c7a64e9dcc00262e1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/renderer.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/ruler.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/ruler.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13fe927ba39d3388081aae614e8d89fbeded51eb
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/ruler.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/token.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/token.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54723a08c7be7b7e5726f8a8e21627aaefbab13c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/token.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/tree.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/tree.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a78b52024b6d186537ce35f7b244ceff474c6e4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/tree.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0d8053388581a40761caa3682d3ff159c820f1f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/__pycache__/utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/cli/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/cli/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/cli/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/cli/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d806b05995df7bd053535fc4aec56a71c0e7362
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/cli/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/cli/__pycache__/parse.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/cli/__pycache__/parse.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a868784bdc4eca4b3a6ccbbc8d1ba63a83674554
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/cli/__pycache__/parse.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/cli/parse.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/cli/parse.py
new file mode 100644
index 0000000000000000000000000000000000000000..5de738b2da7e528e974e9c6be6de44ac74b3d66f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/cli/parse.py
@@ -0,0 +1,127 @@
+#!/usr/bin/env python
+"""
+CLI interface to markdown-it-py
+
+Parse one or more markdown files, convert each to HTML, and print to stdout.
+"""
+
+from __future__ import annotations
+
+import argparse
+from collections.abc import Iterable, Sequence
+import sys
+
+from markdown_it import __version__
+from markdown_it.main import MarkdownIt
+
+version_str = f"markdown-it-py [version {__version__}]"
+
+
+def main(args: Sequence[str] | None = None) -> int:
+ namespace = parse_args(args)
+ if namespace.filenames:
+ convert(namespace.filenames)
+ elif namespace.stdin:
+ convert_stdin()
+ else:
+ interactive()
+ return 0
+
+
+def convert(filenames: Iterable[str]) -> None:
+ for filename in filenames:
+ convert_file(filename)
+
+
+def convert_stdin() -> None:
+ """
+ Parse a Markdown file and dump the output to stdout.
+ """
+ try:
+ rendered = MarkdownIt().render(sys.stdin.read())
+ print(rendered, end="")
+ except OSError:
+ sys.stderr.write("Cannot parse Markdown from the standard input.\n")
+ sys.exit(1)
+
+
+def convert_file(filename: str) -> None:
+ """
+ Parse a Markdown file and dump the output to stdout.
+ """
+ try:
+ with open(filename, encoding="utf8", errors="ignore") as fin:
+ rendered = MarkdownIt().render(fin.read())
+ print(rendered, end="")
+ except OSError:
+ sys.stderr.write(f'Cannot open file "{filename}".\n')
+ sys.exit(1)
+
+
+def interactive() -> None:
+ """
+ Parse user input, dump to stdout, rinse and repeat.
+ Python REPL style.
+ """
+ print_heading()
+ contents = []
+ more = False
+ while True:
+ try:
+ prompt, more = ("... ", True) if more else (">>> ", True)
+ contents.append(input(prompt) + "\n")
+ except EOFError:
+ print("\n" + MarkdownIt().render("\n".join(contents)), end="")
+ more = False
+ contents = []
+ except KeyboardInterrupt:
+ print("\nExiting.")
+ break
+
+
+def parse_args(args: Sequence[str] | None) -> argparse.Namespace:
+ """Parse input CLI arguments."""
+ parser = argparse.ArgumentParser(
+ description="Parse one or more markdown files, "
+ "convert each to HTML, and print to stdout",
+ # NOTE: Remember to update README.md w/ the output of `markdown-it -h`
+ epilog=(
+ f"""
+Interactive:
+
+ $ markdown-it
+ markdown-it-py [version {__version__}] (interactive)
+ Type Ctrl-D to complete input, or Ctrl-C to exit.
+ >>> # Example
+ ... > markdown *input*
+ ...
+ Example
+
+ markdown input
+
+
+Batch:
+
+ $ markdown-it README.md README.footer.md > index.html
+"""
+ ),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ parser.add_argument("-v", "--version", action="version", version=version_str)
+ parser.add_argument(
+ "--stdin", action="store_true", help="read Markdown from standard input"
+ )
+ parser.add_argument(
+ "filenames", nargs="*", help="specify an optional list of files to convert"
+ )
+ return parser.parse_args(args)
+
+
+def print_heading() -> None:
+ print(f"{version_str} (interactive)")
+ print("Type Ctrl-D to complete input, or Ctrl-C to exit.")
+
+
+if __name__ == "__main__":
+ exit_code = main(sys.argv[1:])
+ sys.exit(exit_code)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..65c4f9096ea42dbc0e106453dafb6dfa1ad5673f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/entities.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/entities.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5448717148d60315ac2191a3dce3dea60bf75a16
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/entities.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/html_blocks.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/html_blocks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..342ca422a1c29567764dfdcf7661bfde2935325a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/html_blocks.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/html_re.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/html_re.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b3df8c11439ab4846c7a40c01538544a2d367321
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/html_re.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/normalize_url.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/normalize_url.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..765ecdc4a7f4ecbe41c612641645d41809e0ef9e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/normalize_url.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a5c134e195b74b9b7ae3d82389d3fa33b55ef630
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/__pycache__/utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/entities.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/entities.py
new file mode 100644
index 0000000000000000000000000000000000000000..14d08ec9546995f8eea3e9b83ea896f29ef020cb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/entities.py
@@ -0,0 +1,5 @@
+"""HTML5 entities map: { name -> characters }."""
+
+import html.entities
+
+entities = {name.rstrip(";"): chars for name, chars in html.entities.html5.items()}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/html_blocks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/html_blocks.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a3b0b7d5ab7bc174a3c96cbc8976816278a6c21
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/html_blocks.py
@@ -0,0 +1,69 @@
+"""List of valid html blocks names, according to commonmark spec
+http://jgm.github.io/CommonMark/spec.html#html-blocks
+"""
+
+# see https://spec.commonmark.org/0.31.2/#html-blocks
+block_names = [
+ "address",
+ "article",
+ "aside",
+ "base",
+ "basefont",
+ "blockquote",
+ "body",
+ "caption",
+ "center",
+ "col",
+ "colgroup",
+ "dd",
+ "details",
+ "dialog",
+ "dir",
+ "div",
+ "dl",
+ "dt",
+ "fieldset",
+ "figcaption",
+ "figure",
+ "footer",
+ "form",
+ "frame",
+ "frameset",
+ "h1",
+ "h2",
+ "h3",
+ "h4",
+ "h5",
+ "h6",
+ "head",
+ "header",
+ "hr",
+ "html",
+ "iframe",
+ "legend",
+ "li",
+ "link",
+ "main",
+ "menu",
+ "menuitem",
+ "nav",
+ "noframes",
+ "ol",
+ "optgroup",
+ "option",
+ "p",
+ "param",
+ "search",
+ "section",
+ "summary",
+ "table",
+ "tbody",
+ "td",
+ "tfoot",
+ "th",
+ "thead",
+ "title",
+ "tr",
+ "track",
+ "ul",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/html_re.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/html_re.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab822c5fc487c5a494966604a1e89b57a06e0564
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/html_re.py
@@ -0,0 +1,39 @@
+"""Regexps to match html elements"""
+
+import re
+
+attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*"
+
+unquoted = "[^\"'=<>`\\x00-\\x20]+"
+single_quoted = "'[^']*'"
+double_quoted = '"[^"]*"'
+
+attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")"
+
+attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)"
+
+open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>"
+
+close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>"
+comment = ""
+processing = "<[?][\\s\\S]*?[?]>"
+declaration = "]*>"
+cdata = ""
+
+HTML_TAG_RE = re.compile(
+ "^(?:"
+ + open_tag
+ + "|"
+ + close_tag
+ + "|"
+ + comment
+ + "|"
+ + processing
+ + "|"
+ + declaration
+ + "|"
+ + cdata
+ + ")"
+)
+HTML_OPEN_CLOSE_TAG_STR = "^(?:" + open_tag + "|" + close_tag + ")"
+HTML_OPEN_CLOSE_TAG_RE = re.compile(HTML_OPEN_CLOSE_TAG_STR)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/normalize_url.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/normalize_url.py
new file mode 100644
index 0000000000000000000000000000000000000000..92720b31621b0f6b4ac853179d886cb58e4e2f36
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/normalize_url.py
@@ -0,0 +1,81 @@
+from __future__ import annotations
+
+from collections.abc import Callable
+from contextlib import suppress
+import re
+from urllib.parse import quote, unquote, urlparse, urlunparse # noqa: F401
+
+import mdurl
+
+from .. import _punycode
+
+RECODE_HOSTNAME_FOR = ("http:", "https:", "mailto:")
+
+
+def normalizeLink(url: str) -> str:
+ """Normalize destination URLs in links
+
+ ::
+
+ [label]: destination 'title'
+ ^^^^^^^^^^^
+ """
+ parsed = mdurl.parse(url, slashes_denote_host=True)
+
+ # Encode hostnames in urls like:
+ # `http://host/`, `https://host/`, `mailto:user@host`, `//host/`
+ #
+ # We don't encode unknown schemas, because it's likely that we encode
+ # something we shouldn't (e.g. `skype:name` treated as `skype:host`)
+ #
+ if parsed.hostname and (
+ not parsed.protocol or parsed.protocol in RECODE_HOSTNAME_FOR
+ ):
+ with suppress(Exception):
+ parsed = parsed._replace(hostname=_punycode.to_ascii(parsed.hostname))
+
+ return mdurl.encode(mdurl.format(parsed))
+
+
+def normalizeLinkText(url: str) -> str:
+ """Normalize autolink content
+
+ ::
+
+
+ ~~~~~~~~~~~
+ """
+ parsed = mdurl.parse(url, slashes_denote_host=True)
+
+ # Encode hostnames in urls like:
+ # `http://host/`, `https://host/`, `mailto:user@host`, `//host/`
+ #
+ # We don't encode unknown schemas, because it's likely that we encode
+ # something we shouldn't (e.g. `skype:name` treated as `skype:host`)
+ #
+ if parsed.hostname and (
+ not parsed.protocol or parsed.protocol in RECODE_HOSTNAME_FOR
+ ):
+ with suppress(Exception):
+ parsed = parsed._replace(hostname=_punycode.to_unicode(parsed.hostname))
+
+ # add '%' to exclude list because of https://github.com/markdown-it/markdown-it/issues/720
+ return mdurl.decode(mdurl.format(parsed), mdurl.DECODE_DEFAULT_CHARS + "%")
+
+
+BAD_PROTO_RE = re.compile(r"^(vbscript|javascript|file|data):")
+GOOD_DATA_RE = re.compile(r"^data:image\/(gif|png|jpeg|webp);")
+
+
+def validateLink(url: str, validator: Callable[[str], bool] | None = None) -> bool:
+ """Validate URL link is allowed in output.
+
+ This validator can prohibit more than really needed to prevent XSS.
+ It's a tradeoff to keep code simple and to be secure by default.
+
+ Note: url should be normalized at this point, and existing entities decoded.
+ """
+ if validator is not None:
+ return validator(url)
+ url = url.strip().lower()
+ return bool(GOOD_DATA_RE.search(url)) if BAD_PROTO_RE.search(url) else True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..11bda644c260b714cf010ed44d2ed345de80314e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/common/utils.py
@@ -0,0 +1,313 @@
+"""Utilities for parsing source text"""
+
+from __future__ import annotations
+
+import re
+from re import Match
+from typing import TypeVar
+import unicodedata
+
+from .entities import entities
+
+
+def charCodeAt(src: str, pos: int) -> int | None:
+ """
+ Returns the Unicode value of the character at the specified location.
+
+ @param - index The zero-based index of the desired character.
+ If there is no character at the specified index, NaN is returned.
+
+ This was added for compatibility with python
+ """
+ try:
+ return ord(src[pos])
+ except IndexError:
+ return None
+
+
+def charStrAt(src: str, pos: int) -> str | None:
+ """
+ Returns the Unicode value of the character at the specified location.
+
+ @param - index The zero-based index of the desired character.
+ If there is no character at the specified index, NaN is returned.
+
+ This was added for compatibility with python
+ """
+ try:
+ return src[pos]
+ except IndexError:
+ return None
+
+
+_ItemTV = TypeVar("_ItemTV")
+
+
+def arrayReplaceAt(
+ src: list[_ItemTV], pos: int, newElements: list[_ItemTV]
+) -> list[_ItemTV]:
+ """
+ Remove element from array and put another array at those position.
+ Useful for some operations with tokens
+ """
+ return src[:pos] + newElements + src[pos + 1 :]
+
+
+def isValidEntityCode(c: int) -> bool:
+ # broken sequence
+ if c >= 0xD800 and c <= 0xDFFF:
+ return False
+ # never used
+ if c >= 0xFDD0 and c <= 0xFDEF:
+ return False
+ if ((c & 0xFFFF) == 0xFFFF) or ((c & 0xFFFF) == 0xFFFE):
+ return False
+ # control codes
+ if c >= 0x00 and c <= 0x08:
+ return False
+ if c == 0x0B:
+ return False
+ if c >= 0x0E and c <= 0x1F:
+ return False
+ if c >= 0x7F and c <= 0x9F:
+ return False
+ # out of range
+ return not (c > 0x10FFFF)
+
+
+def fromCodePoint(c: int) -> str:
+ """Convert ordinal to unicode.
+
+ Note, in the original Javascript two string characters were required,
+ for codepoints larger than `0xFFFF`.
+ But Python 3 can represent any unicode codepoint in one character.
+ """
+ return chr(c)
+
+
+# UNESCAPE_MD_RE = re.compile(r'\\([!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])')
+# ENTITY_RE_g = re.compile(r'&([a-z#][a-z0-9]{1,31})', re.IGNORECASE)
+UNESCAPE_ALL_RE = re.compile(
+ r'\\([!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])' + "|" + r"&([a-z#][a-z0-9]{1,31});",
+ re.IGNORECASE,
+)
+DIGITAL_ENTITY_BASE10_RE = re.compile(r"#([0-9]{1,8})")
+DIGITAL_ENTITY_BASE16_RE = re.compile(r"#x([a-f0-9]{1,8})", re.IGNORECASE)
+
+
+def replaceEntityPattern(match: str, name: str) -> str:
+ """Convert HTML entity patterns,
+ see https://spec.commonmark.org/0.30/#entity-references
+ """
+ if name in entities:
+ return entities[name]
+
+ code: None | int = None
+ if pat := DIGITAL_ENTITY_BASE10_RE.fullmatch(name):
+ code = int(pat.group(1), 10)
+ elif pat := DIGITAL_ENTITY_BASE16_RE.fullmatch(name):
+ code = int(pat.group(1), 16)
+
+ if code is not None and isValidEntityCode(code):
+ return fromCodePoint(code)
+
+ return match
+
+
+def unescapeAll(string: str) -> str:
+ def replacer_func(match: Match[str]) -> str:
+ escaped = match.group(1)
+ if escaped:
+ return escaped
+ entity = match.group(2)
+ return replaceEntityPattern(match.group(), entity)
+
+ if "\\" not in string and "&" not in string:
+ return string
+ return UNESCAPE_ALL_RE.sub(replacer_func, string)
+
+
+ESCAPABLE = r"""\\!"#$%&'()*+,./:;<=>?@\[\]^`{}|_~-"""
+ESCAPE_CHAR = re.compile(r"\\([" + ESCAPABLE + r"])")
+
+
+def stripEscape(string: str) -> str:
+ """Strip escape \\ characters"""
+ return ESCAPE_CHAR.sub(r"\1", string)
+
+
+def escapeHtml(raw: str) -> str:
+ """Replace special characters "&", "<", ">" and '"' to HTML-safe sequences."""
+ # like html.escape, but without escaping single quotes
+ raw = raw.replace("&", "&") # Must be done first!
+ raw = raw.replace("<", "<")
+ raw = raw.replace(">", ">")
+ raw = raw.replace('"', """)
+ return raw
+
+
+# //////////////////////////////////////////////////////////////////////////////
+
+REGEXP_ESCAPE_RE = re.compile(r"[.?*+^$[\]\\(){}|-]")
+
+
+def escapeRE(string: str) -> str:
+ string = REGEXP_ESCAPE_RE.sub("\\$&", string)
+ return string
+
+
+# //////////////////////////////////////////////////////////////////////////////
+
+
+def isSpace(code: int | None) -> bool:
+ """Check if character code is a whitespace."""
+ return code in (0x09, 0x20)
+
+
+def isStrSpace(ch: str | None) -> bool:
+ """Check if character is a whitespace."""
+ return ch in ("\t", " ")
+
+
+MD_WHITESPACE = {
+ 0x09, # \t
+ 0x0A, # \n
+ 0x0B, # \v
+ 0x0C, # \f
+ 0x0D, # \r
+ 0x20, # space
+ 0xA0,
+ 0x1680,
+ 0x202F,
+ 0x205F,
+ 0x3000,
+}
+
+
+def isWhiteSpace(code: int) -> bool:
+ r"""Zs (unicode class) || [\t\f\v\r\n]"""
+ if code >= 0x2000 and code <= 0x200A:
+ return True
+ return code in MD_WHITESPACE
+
+
+# //////////////////////////////////////////////////////////////////////////////
+
+
+def isPunctChar(ch: str) -> bool:
+ """Check if character is a punctuation character."""
+ return unicodedata.category(ch).startswith(("P", "S"))
+
+
+MD_ASCII_PUNCT = {
+ 0x21, # /* ! */
+ 0x22, # /* " */
+ 0x23, # /* # */
+ 0x24, # /* $ */
+ 0x25, # /* % */
+ 0x26, # /* & */
+ 0x27, # /* ' */
+ 0x28, # /* ( */
+ 0x29, # /* ) */
+ 0x2A, # /* * */
+ 0x2B, # /* + */
+ 0x2C, # /* , */
+ 0x2D, # /* - */
+ 0x2E, # /* . */
+ 0x2F, # /* / */
+ 0x3A, # /* : */
+ 0x3B, # /* ; */
+ 0x3C, # /* < */
+ 0x3D, # /* = */
+ 0x3E, # /* > */
+ 0x3F, # /* ? */
+ 0x40, # /* @ */
+ 0x5B, # /* [ */
+ 0x5C, # /* \ */
+ 0x5D, # /* ] */
+ 0x5E, # /* ^ */
+ 0x5F, # /* _ */
+ 0x60, # /* ` */
+ 0x7B, # /* { */
+ 0x7C, # /* | */
+ 0x7D, # /* } */
+ 0x7E, # /* ~ */
+}
+
+
+def isMdAsciiPunct(ch: int) -> bool:
+ """Markdown ASCII punctuation characters.
+
+ ::
+
+ !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \\, ], ^, _, `, {, |, }, or ~
+
+ See http://spec.commonmark.org/0.15/#ascii-punctuation-character
+
+ Don't confuse with unicode punctuation !!! It lacks some chars in ascii range.
+
+ """
+ return ch in MD_ASCII_PUNCT
+
+
+def normalizeReference(string: str) -> str:
+ """Helper to unify [reference labels]."""
+ # Trim and collapse whitespace
+ #
+ string = re.sub(r"\s+", " ", string.strip())
+
+ # In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug
+ # fixed in v12 (couldn't find any details).
+ #
+ # So treat this one as a special case
+ # (remove this when node v10 is no longer supported).
+ #
+ # if ('ẞ'.toLowerCase() === 'Ṿ') {
+ # str = str.replace(/ẞ/g, 'ß')
+ # }
+
+ # .toLowerCase().toUpperCase() should get rid of all differences
+ # between letter variants.
+ #
+ # Simple .toLowerCase() doesn't normalize 125 code points correctly,
+ # and .toUpperCase doesn't normalize 6 of them (list of exceptions:
+ # İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently
+ # uppercased versions).
+ #
+ # Here's an example showing how it happens. Lets take greek letter omega:
+ # uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ)
+ #
+ # Unicode entries:
+ # 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8
+ # 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398
+ # 03D1;GREEK THETA SYMBOL;Ll;0;L; 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398
+ # 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L; 0398;;;;N;;;;03B8
+ #
+ # Case-insensitive comparison should treat all of them as equivalent.
+ #
+ # But .toLowerCase() doesn't change ϑ (it's already lowercase),
+ # and .toUpperCase() doesn't change ϴ (already uppercase).
+ #
+ # Applying first lower then upper case normalizes any character:
+ # '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398'
+ #
+ # Note: this is equivalent to unicode case folding; unicode normalization
+ # is a different step that is not required here.
+ #
+ # Final result should be uppercased, because it's later stored in an object
+ # (this avoid a conflict with Object.prototype members,
+ # most notably, `__proto__`)
+ #
+ return string.lower().upper()
+
+
+LINK_OPEN_RE = re.compile(r"^\s]", flags=re.IGNORECASE)
+LINK_CLOSE_RE = re.compile(r"^", flags=re.IGNORECASE)
+
+
+def isLinkOpen(string: str) -> bool:
+ return bool(LINK_OPEN_RE.search(string))
+
+
+def isLinkClose(string: str) -> bool:
+ return bool(LINK_CLOSE_RE.search(string))
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4e2cd21b94b9ee9ecb0cac21da619233a5258b9
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__init__.py
@@ -0,0 +1,6 @@
+"""Functions for parsing Links"""
+
+__all__ = ("parseLinkDestination", "parseLinkLabel", "parseLinkTitle")
+from .parse_link_destination import parseLinkDestination
+from .parse_link_label import parseLinkLabel
+from .parse_link_title import parseLinkTitle
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..826da078429f8d8b4dbf47a1bccf606c5e34e90d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__pycache__/parse_link_destination.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__pycache__/parse_link_destination.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..251da79d6959e9b7e4f3430174c9c19550561218
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__pycache__/parse_link_destination.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__pycache__/parse_link_label.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__pycache__/parse_link_label.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4095682c59e29f43fa0567d1a84db03b72769883
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__pycache__/parse_link_label.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__pycache__/parse_link_title.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__pycache__/parse_link_title.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96c33d2e6aa7aef15affc3f16064e40507e89c0a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/__pycache__/parse_link_title.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/parse_link_destination.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/parse_link_destination.py
new file mode 100644
index 0000000000000000000000000000000000000000..c98323c056e0103a12849671fbbac58dc76de4b4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/parse_link_destination.py
@@ -0,0 +1,83 @@
+"""
+Parse link destination
+"""
+
+from ..common.utils import charCodeAt, unescapeAll
+
+
+class _Result:
+ __slots__ = ("ok", "pos", "str")
+
+ def __init__(self) -> None:
+ self.ok = False
+ self.pos = 0
+ self.str = ""
+
+
+def parseLinkDestination(string: str, pos: int, maximum: int) -> _Result:
+ start = pos
+ result = _Result()
+
+ if charCodeAt(string, pos) == 0x3C: # /* < */
+ pos += 1
+ while pos < maximum:
+ code = charCodeAt(string, pos)
+ if code == 0x0A: # /* \n */)
+ return result
+ if code == 0x3C: # / * < * /
+ return result
+ if code == 0x3E: # /* > */) {
+ result.pos = pos + 1
+ result.str = unescapeAll(string[start + 1 : pos])
+ result.ok = True
+ return result
+
+ if code == 0x5C and pos + 1 < maximum: # \
+ pos += 2
+ continue
+
+ pos += 1
+
+ # no closing '>'
+ return result
+
+ # this should be ... } else { ... branch
+
+ level = 0
+ while pos < maximum:
+ code = charCodeAt(string, pos)
+
+ if code is None or code == 0x20:
+ break
+
+ # ascii control characters
+ if code < 0x20 or code == 0x7F:
+ break
+
+ if code == 0x5C and pos + 1 < maximum:
+ if charCodeAt(string, pos + 1) == 0x20:
+ break
+ pos += 2
+ continue
+
+ if code == 0x28: # /* ( */)
+ level += 1
+ if level > 32:
+ return result
+
+ if code == 0x29: # /* ) */)
+ if level == 0:
+ break
+ level -= 1
+
+ pos += 1
+
+ if start == pos:
+ return result
+ if level != 0:
+ return result
+
+ result.str = unescapeAll(string[start:pos])
+ result.pos = pos
+ result.ok = True
+ return result
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/parse_link_label.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/parse_link_label.py
new file mode 100644
index 0000000000000000000000000000000000000000..c80da5a7ec54521281dac45b66977404f5384491
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/parse_link_label.py
@@ -0,0 +1,44 @@
+"""
+Parse link label
+
+this function assumes that first character ("[") already matches
+returns the end of the label
+
+"""
+
+from markdown_it.rules_inline import StateInline
+
+
+def parseLinkLabel(state: StateInline, start: int, disableNested: bool = False) -> int:
+ labelEnd = -1
+ oldPos = state.pos
+ found = False
+
+ state.pos = start + 1
+ level = 1
+
+ while state.pos < state.posMax:
+ marker = state.src[state.pos]
+ if marker == "]":
+ level -= 1
+ if level == 0:
+ found = True
+ break
+
+ prevPos = state.pos
+ state.md.inline.skipToken(state)
+ if marker == "[":
+ if prevPos == state.pos - 1:
+ # increase level if we find text `[`,
+ # which is not a part of any token
+ level += 1
+ elif disableNested:
+ state.pos = oldPos
+ return -1
+ if found:
+ labelEnd = state.pos
+
+ # restore old state
+ state.pos = oldPos
+
+ return labelEnd
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/parse_link_title.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/parse_link_title.py
new file mode 100644
index 0000000000000000000000000000000000000000..a38ff0d98ac7feaba80fd67f3c8f0d0454dde47f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/helpers/parse_link_title.py
@@ -0,0 +1,75 @@
+"""Parse link title"""
+
+from ..common.utils import charCodeAt, unescapeAll
+
+
+class _State:
+ __slots__ = ("can_continue", "marker", "ok", "pos", "str")
+
+ def __init__(self) -> None:
+ self.ok = False
+ """if `true`, this is a valid link title"""
+ self.can_continue = False
+ """if `true`, this link can be continued on the next line"""
+ self.pos = 0
+ """if `ok`, it's the position of the first character after the closing marker"""
+ self.str = ""
+ """if `ok`, it's the unescaped title"""
+ self.marker = 0
+ """expected closing marker character code"""
+
+ def __str__(self) -> str:
+ return self.str
+
+
+def parseLinkTitle(
+ string: str, start: int, maximum: int, prev_state: _State | None = None
+) -> _State:
+ """Parse link title within `str` in [start, max] range,
+ or continue previous parsing if `prev_state` is defined (equal to result of last execution).
+ """
+ pos = start
+ state = _State()
+
+ if prev_state is not None:
+ # this is a continuation of a previous parseLinkTitle call on the next line,
+ # used in reference links only
+ state.str = prev_state.str
+ state.marker = prev_state.marker
+ else:
+ if pos >= maximum:
+ return state
+
+ marker = charCodeAt(string, pos)
+
+ # /* " */ /* ' */ /* ( */
+ if marker != 0x22 and marker != 0x27 and marker != 0x28:
+ return state
+
+ start += 1
+ pos += 1
+
+ # if opening marker is "(", switch it to closing marker ")"
+ if marker == 0x28:
+ marker = 0x29
+
+ state.marker = marker
+
+ while pos < maximum:
+ code = charCodeAt(string, pos)
+ if code == state.marker:
+ state.pos = pos + 1
+ state.str += unescapeAll(string[start:pos])
+ state.ok = True
+ return state
+ elif code == 0x28 and state.marker == 0x29: # /* ( */ /* ) */
+ return state
+ elif code == 0x5C and pos + 1 < maximum: # /* \ */
+ pos += 1
+
+ pos += 1
+
+ # no closing marker found, but this link title may continue on the next line (for references)
+ state.can_continue = True
+ state.str += unescapeAll(string[start:pos])
+ return state
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..43578148cee4dc544721e74c4bd5fed042f3e7fe
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__init__.py
@@ -0,0 +1,48 @@
+__all__ = ("commonmark", "default", "gfm_like", "gfm_like2", "js_default", "zero")
+
+from ..utils import PresetType
+from . import commonmark, default, zero
+
+js_default = default
+
+
+class gfm_like: # noqa: N801
+ """GitHub Flavoured Markdown (GFM) like.
+
+ This adds the linkify, table and strikethrough components to CommmonMark.
+
+ Note, it lacks task-list items and raw HTML filtering,
+ to meet the the full GFM specification
+ (see https://github.github.com/gfm/#autolinks-extension-).
+ """
+
+ @staticmethod
+ def make() -> PresetType:
+ config = commonmark.make()
+ config["components"]["core"]["rules"].append("linkify")
+ config["components"]["block"]["rules"].append("table")
+ config["components"]["inline"]["rules"].extend(["strikethrough", "linkify"])
+ config["components"]["inline"]["rules2"].append("strikethrough")
+ config["options"]["linkify"] = True
+ config["options"]["html"] = True
+ return config
+
+
+class gfm_like2: # noqa: N801
+ """GitHub Flavoured Markdown (GFM) like, extended.
+
+ Builds on ``gfm-like`` and additionally enables:
+
+ - Task lists (``- [x] done``)
+ - Alerts (``> [!NOTE]``)
+ - Single-tilde strikethrough (``~text~`` in addition to ``~~text~~``)
+ """
+
+ @staticmethod
+ def make() -> PresetType:
+ config = gfm_like.make()
+ config["options"]["tasklists"] = True
+ config["options"]["tasklists_editable"] = False
+ config["options"]["alerts"] = True
+ config["options"]["strikethrough_single_tilde"] = True
+ return config
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fdf9a3ec5a6a7b6ee77330e3fa92c5806e3932ea
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__pycache__/commonmark.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__pycache__/commonmark.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb24c85a97b9bf7d8ec8d55e3d300c4ab18a4ccb
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__pycache__/commonmark.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__pycache__/default.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__pycache__/default.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a1b8013ae91184313b518c957a2bb4c6e6ae713
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__pycache__/default.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__pycache__/zero.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__pycache__/zero.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1535f31f62b562783323e54c066cef0b46ccc04
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/__pycache__/zero.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/commonmark.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/commonmark.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed0de0fe4dfbad9e3ab82477433805ea0b6650c6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/presets/commonmark.py
@@ -0,0 +1,75 @@
+"""Commonmark default options.
+
+This differs to presets.default,
+primarily in that it allows HTML and does not enable components:
+
+- block: table
+- inline: strikethrough
+"""
+
+from ..utils import PresetType
+
+
+def make() -> PresetType:
+ return {
+ "options": {
+ "maxNesting": 20, # Internal protection, recursion limit
+ "html": True, # Enable HTML tags in source,
+ # this is just a shorthand for .enable(["html_inline", "html_block"])
+ # used by the linkify rule:
+ "linkify": False, # autoconvert URL-like texts to links
+ # used by the replacements and smartquotes rules
+ # Enable some language-neutral replacements + quotes beautification
+ "typographer": False,
+ # used by the smartquotes rule:
+ # Double + single quotes replacement pairs, when typographer enabled,
+ # and smartquotes on. Could be either a String or an Array.
+ #
+ # For example, you can use '«»„“' for Russian, '„“‚‘' for German,
+ # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
+ "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */
+ # Renderer specific; these options are used directly in the HTML renderer
+ "xhtmlOut": True, # Use '/' to close single tags (
)
+ "breaks": False, # Convert '\n' in paragraphs into
+ "langPrefix": "language-", # CSS language prefix for fenced blocks
+ # Highlighter function. Should return escaped HTML,
+ # or '' if the source string is not changed and should be escaped externally.
+ # If result starts with PresetType:
+ return {
+ "options": {
+ "maxNesting": 100, # Internal protection, recursion limit
+ "html": False, # Enable HTML tags in source
+ # this is just a shorthand for .disable(["html_inline", "html_block"])
+ # used by the linkify rule:
+ "linkify": False, # autoconvert URL-like texts to links
+ # used by the replacements and smartquotes rules:
+ # Enable some language-neutral replacements + quotes beautification
+ "typographer": False,
+ # used by the smartquotes rule:
+ # Double + single quotes replacement pairs, when typographer enabled,
+ # and smartquotes on. Could be either a String or an Array.
+ # For example, you can use '«»„“' for Russian, '„“‚‘' for German,
+ # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
+ "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */
+ # Renderer specific; these options are used directly in the HTML renderer
+ "xhtmlOut": False, # Use '/' to close single tags (
)
+ "breaks": False, # Convert '\n' in paragraphs into
+ "langPrefix": "language-", # CSS language prefix for fenced blocks
+ # Highlighter function. Should return escaped HTML,
+ # or '' if the source string is not changed and should be escaped externally.
+ # If result starts with PresetType:
+ return {
+ "options": {
+ "maxNesting": 20, # Internal protection, recursion limit
+ "html": False, # Enable HTML tags in source
+ # this is just a shorthand for .disable(["html_inline", "html_block"])
+ # used by the linkify rule:
+ "linkify": False, # autoconvert URL-like texts to links
+ # used by the replacements and smartquotes rules:
+ # Enable some language-neutral replacements + quotes beautification
+ "typographer": False,
+ # used by the smartquotes rule:
+ # Double + single quotes replacement pairs, when typographer enabled,
+ # and smartquotes on. Could be either a String or an Array.
+ # For example, you can use '«»„“' for Russian, '„“‚‘' for German,
+ # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
+ "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */
+ # Renderer specific; these options are used directly in the HTML renderer
+ "xhtmlOut": False, # Use '/' to close single tags (
)
+ "breaks": False, # Convert '\n' in paragraphs into
+ "langPrefix": "language-", # CSS language prefix for fenced blocks
+ # Highlighter function. Should return escaped HTML,
+ # or '' if the source string is not changed and should be escaped externally.
+ # If result starts with bool:
+ LOGGER.debug(
+ "entering blockquote: %s, %s, %s, %s", state, startLine, endLine, silent
+ )
+
+ oldLineMax = state.lineMax
+ pos = state.bMarks[startLine] + state.tShift[startLine]
+ max = state.eMarks[startLine]
+
+ if state.is_code_block(startLine):
+ return False
+
+ # check the block quote marker
+ try:
+ if state.src[pos] != ">":
+ return False
+ except IndexError:
+ return False
+ pos += 1
+
+ # we know that it's going to be a valid blockquote,
+ # so no point trying to find the end of it in silent mode
+ if silent:
+ return True
+
+ # set offset past spaces and ">"
+ initial = offset = state.sCount[startLine] + 1
+
+ try:
+ second_char: str | None = state.src[pos]
+ except IndexError:
+ second_char = None
+
+ # skip one optional space after '>'
+ if second_char == " ":
+ # ' > test '
+ # ^ -- position start of line here:
+ pos += 1
+ initial += 1
+ offset += 1
+ adjustTab = False
+ spaceAfterMarker = True
+ elif second_char == "\t":
+ spaceAfterMarker = True
+
+ if (state.bsCount[startLine] + offset) % 4 == 3:
+ # ' >\t test '
+ # ^ -- position start of line here (tab has width==1)
+ pos += 1
+ initial += 1
+ offset += 1
+ adjustTab = False
+ else:
+ # ' >\t test '
+ # ^ -- position start of line here + shift bsCount slightly
+ # to make extra space appear
+ adjustTab = True
+
+ else:
+ spaceAfterMarker = False
+
+ oldBMarks = [state.bMarks[startLine]]
+ state.bMarks[startLine] = pos
+
+ while pos < max:
+ ch = state.src[pos]
+
+ if isStrSpace(ch):
+ if ch == "\t":
+ offset += (
+ 4
+ - (offset + state.bsCount[startLine] + (1 if adjustTab else 0)) % 4
+ )
+ else:
+ offset += 1
+
+ else:
+ break
+
+ pos += 1
+
+ oldBSCount = [state.bsCount[startLine]]
+ state.bsCount[startLine] = (
+ state.sCount[startLine] + 1 + (1 if spaceAfterMarker else 0)
+ )
+
+ lastLineEmpty = pos >= max
+
+ oldSCount = [state.sCount[startLine]]
+ state.sCount[startLine] = offset - initial
+
+ oldTShift = [state.tShift[startLine]]
+ state.tShift[startLine] = pos - state.bMarks[startLine]
+
+ terminatorRules = state.md.block.ruler.getRules("blockquote")
+
+ oldParentType = state.parentType
+ state.parentType = "blockquote"
+
+ # Search the end of the block
+ #
+ # Block ends with either:
+ # 1. an empty line outside:
+ # ```
+ # > test
+ #
+ # ```
+ # 2. an empty line inside:
+ # ```
+ # >
+ # test
+ # ```
+ # 3. another tag:
+ # ```
+ # > test
+ # - - -
+ # ```
+
+ # for (nextLine = startLine + 1; nextLine < endLine; nextLine++) {
+ nextLine = startLine + 1
+ while nextLine < endLine:
+ # check if it's outdented, i.e. it's inside list item and indented
+ # less than said list item:
+ #
+ # ```
+ # 1. anything
+ # > current blockquote
+ # 2. checking this line
+ # ```
+ isOutdented = state.sCount[nextLine] < state.blkIndent
+
+ pos = state.bMarks[nextLine] + state.tShift[nextLine]
+ max = state.eMarks[nextLine]
+
+ if pos >= max:
+ # Case 1: line is not inside the blockquote, and this line is empty.
+ break
+
+ evaluatesTrue = state.src[pos] == ">" and not isOutdented
+ pos += 1
+ if evaluatesTrue:
+ # This line is inside the blockquote.
+
+ # set offset past spaces and ">"
+ initial = offset = state.sCount[nextLine] + 1
+
+ try:
+ next_char: str | None = state.src[pos]
+ except IndexError:
+ next_char = None
+
+ # skip one optional space after '>'
+ if next_char == " ":
+ # ' > test '
+ # ^ -- position start of line here:
+ pos += 1
+ initial += 1
+ offset += 1
+ adjustTab = False
+ spaceAfterMarker = True
+ elif next_char == "\t":
+ spaceAfterMarker = True
+
+ if (state.bsCount[nextLine] + offset) % 4 == 3:
+ # ' >\t test '
+ # ^ -- position start of line here (tab has width==1)
+ pos += 1
+ initial += 1
+ offset += 1
+ adjustTab = False
+ else:
+ # ' >\t test '
+ # ^ -- position start of line here + shift bsCount slightly
+ # to make extra space appear
+ adjustTab = True
+
+ else:
+ spaceAfterMarker = False
+
+ oldBMarks.append(state.bMarks[nextLine])
+ state.bMarks[nextLine] = pos
+
+ while pos < max:
+ ch = state.src[pos]
+
+ if isStrSpace(ch):
+ if ch == "\t":
+ offset += (
+ 4
+ - (
+ offset
+ + state.bsCount[nextLine]
+ + (1 if adjustTab else 0)
+ )
+ % 4
+ )
+ else:
+ offset += 1
+ else:
+ break
+
+ pos += 1
+
+ lastLineEmpty = pos >= max
+
+ oldBSCount.append(state.bsCount[nextLine])
+ state.bsCount[nextLine] = (
+ state.sCount[nextLine] + 1 + (1 if spaceAfterMarker else 0)
+ )
+
+ oldSCount.append(state.sCount[nextLine])
+ state.sCount[nextLine] = offset - initial
+
+ oldTShift.append(state.tShift[nextLine])
+ state.tShift[nextLine] = pos - state.bMarks[nextLine]
+
+ nextLine += 1
+ continue
+
+ # Case 2: line is not inside the blockquote, and the last line was empty.
+ if lastLineEmpty:
+ break
+
+ # Case 3: another tag found.
+ terminate = False
+
+ for terminatorRule in terminatorRules:
+ if terminatorRule(state, nextLine, endLine, True):
+ terminate = True
+ break
+
+ if terminate:
+ # Quirk to enforce "hard termination mode" for paragraphs;
+ # normally if you call `tokenize(state, startLine, nextLine)`,
+ # paragraphs will look below nextLine for paragraph continuation,
+ # but if blockquote is terminated by another tag, they shouldn't
+ state.lineMax = nextLine
+
+ if state.blkIndent != 0:
+ # state.blkIndent was non-zero, we now set it to zero,
+ # so we need to re-calculate all offsets to appear as
+ # if indent wasn't changed
+ oldBMarks.append(state.bMarks[nextLine])
+ oldBSCount.append(state.bsCount[nextLine])
+ oldTShift.append(state.tShift[nextLine])
+ oldSCount.append(state.sCount[nextLine])
+ state.sCount[nextLine] -= state.blkIndent
+
+ break
+
+ oldBMarks.append(state.bMarks[nextLine])
+ oldBSCount.append(state.bsCount[nextLine])
+ oldTShift.append(state.tShift[nextLine])
+ oldSCount.append(state.sCount[nextLine])
+
+ # A negative indentation means that this is a paragraph continuation
+ #
+ state.sCount[nextLine] = -1
+
+ nextLine += 1
+
+ oldIndent = state.blkIndent
+ state.blkIndent = 0
+
+ # Detect GitHub-style alert marker on the first content line.
+ # Note: `startLine` here refers to the first content line of the
+ # blockquote, after the `>` prefix has already been stripped by the
+ # blockquote parser above (bMarks/tShift adjusted to skip `> `).
+ alert_kind = None
+ if state.md.options.get("alerts", False) and nextLine > startLine:
+ alert_kind = _detect_alert(state, startLine)
+
+ lines = [startLine, 0]
+
+ if alert_kind is not None:
+ # Emit alert tokens instead of blockquote tokens
+ alert_lower = alert_kind.lower()
+ token = state.push("alert_open", "div", 1)
+ token.markup = ">"
+ token.attrSet("class", f"markdown-alert markdown-alert-{alert_lower}")
+ token.map = lines
+ token.info = alert_kind
+ token.meta = {"kind": alert_kind}
+
+ # Emit a title paragraph: Kind
+ token = state.push("alert_title_open", "p", 1)
+ token.attrSet("class", "markdown-alert-title")
+ title_token = state.push("inline", "", 0)
+ title_token.content = alert_kind.capitalize()
+ title_token.children = []
+ token = state.push("alert_title_close", "p", -1)
+
+ # Skip the marker line (startLine) and tokenize from startLine + 1.
+ contentStart = startLine + 1
+ if contentStart < nextLine:
+ # tokenize() updates state.line to nextLine as part of its
+ # contract, consistent with the blockquote code path below.
+ state.md.block.tokenize(state, contentStart, nextLine)
+ else:
+ state.line = nextLine
+
+ token = state.push("alert_close", "div", -1)
+ token.markup = ">"
+ else:
+ token = state.push("blockquote_open", "blockquote", 1)
+ token.markup = ">"
+ token.map = lines
+
+ state.md.block.tokenize(state, startLine, nextLine)
+
+ token = state.push("blockquote_close", "blockquote", -1)
+ token.markup = ">"
+
+ state.lineMax = oldLineMax
+ state.parentType = oldParentType
+ # Update the opening token map for both alert and blockquote containers.
+ lines[1] = state.line
+
+ # Restore original tShift; this might not be necessary since the parser
+ # has already been here, but just to make sure we can do that.
+ for i, item in enumerate(oldTShift):
+ state.bMarks[i + startLine] = oldBMarks[i]
+ state.tShift[i + startLine] = item
+ state.sCount[i + startLine] = oldSCount[i]
+ state.bsCount[i + startLine] = oldBSCount[i]
+
+ state.blkIndent = oldIndent
+
+ return True
+
+
+_ALERT_TYPES = {"NOTE", "TIP", "IMPORTANT", "WARNING", "CAUTION"}
+
+
+def _detect_alert(state: StateBlock, startLine: int) -> str | None:
+ """Detect ``[!TYPE]`` on *startLine* (after ``>`` prefix has been stripped).
+
+ Returns the alert type string (e.g. ``"NOTE"``) or ``None``.
+ """
+ pos = state.bMarks[startLine] + state.tShift[startLine]
+ maximum = state.eMarks[startLine]
+ src = state.src
+
+ # Trim trailing whitespace
+ while maximum > pos and src[maximum - 1] in (" ", "\t"):
+ maximum -= 1
+
+ if maximum - pos < 4:
+ return None
+ if src[pos] != "[" or src[pos + 1] != "!":
+ return None
+ if src[maximum - 1] != "]":
+ return None
+ type_str = src[pos + 2 : maximum - 1].upper()
+ if type_str not in _ALERT_TYPES:
+ return None
+ return type_str
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/code.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/code.py
new file mode 100644
index 0000000000000000000000000000000000000000..af8a41c8058b1a4887252469bdc6f20f085ad7d5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/code.py
@@ -0,0 +1,36 @@
+"""Code block (4 spaces padded)."""
+
+import logging
+
+from .state_block import StateBlock
+
+LOGGER = logging.getLogger(__name__)
+
+
+def code(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
+ LOGGER.debug("entering code: %s, %s, %s, %s", state, startLine, endLine, silent)
+
+ if not state.is_code_block(startLine):
+ return False
+
+ last = nextLine = startLine + 1
+
+ while nextLine < endLine:
+ if state.isEmpty(nextLine):
+ nextLine += 1
+ continue
+
+ if state.is_code_block(nextLine):
+ nextLine += 1
+ last = nextLine
+ continue
+
+ break
+
+ state.line = last
+
+ token = state.push("code_block", "code", 0)
+ token.content = state.getLines(startLine, last, 4 + state.blkIndent, False) + "\n"
+ token.map = [startLine, state.line]
+
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/fence.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/fence.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d7e651eb06b73386ef447f2d19e2aa0042f97e5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/fence.py
@@ -0,0 +1,146 @@
+# fences (``` lang, ~~~ lang)
+from __future__ import annotations
+
+from collections.abc import Callable
+import logging
+
+from .state_block import StateBlock
+
+LOGGER = logging.getLogger(__name__)
+
+
+def make_fence_rule(
+ *,
+ markers: tuple[str, ...] = ("~", "`"),
+ token_type: str = "fence",
+ exact_match: bool = False,
+ disallow_marker_in_info: tuple[str, ...] = ("`",),
+ min_markers: int = 3,
+) -> Callable[[StateBlock, int, int, bool], bool]:
+ """Create a fence parsing rule with configurable options.
+
+ :param markers: Tuple of single characters that can be used as fence markers.
+ :param token_type: The token type name to emit (e.g. "fence", "colon_fence").
+ :param exact_match: If True, the closing fence must have exactly the same
+ number of marker characters as the opening fence (not "at least as many").
+ This enables nesting of fences with different marker counts.
+ :param disallow_marker_in_info: Tuple of marker characters that are not allowed
+ to appear in the info string. The check only applies when the actual opening
+ marker is in this tuple (e.g. a tilde fence is unaffected by ``"`"`` being
+ listed). Per CommonMark, backtick fences cannot have backticks in the info
+ string. Use ``()`` to disable this restriction.
+ :param min_markers: Minimum number of marker characters to form a fence.
+ :return: A block rule function with signature
+ ``(state, startLine, endLine, silent) -> bool``.
+ """
+
+ closing_matcher: Callable[[int, int], bool]
+ if exact_match:
+ # closing code fence must have exactly the same number of markers as the opening one
+ closing_matcher = lambda opening_len, closing_len: closing_len == opening_len # noqa: E731
+ else:
+ # closing code fence must be at least as long as the opening one
+ closing_matcher = lambda opening_len, closing_len: closing_len >= opening_len # noqa: E731
+
+ def _fence_rule(
+ state: StateBlock, startLine: int, endLine: int, silent: bool
+ ) -> bool:
+ LOGGER.debug(
+ "entering fence: %s, %s, %s, %s", state, startLine, endLine, silent
+ )
+
+ haveEndMarker = False
+ pos = state.bMarks[startLine] + state.tShift[startLine]
+ maximum = state.eMarks[startLine]
+
+ if state.is_code_block(startLine):
+ return False
+
+ if pos + min_markers > maximum:
+ return False
+
+ marker = state.src[pos]
+
+ if marker not in markers:
+ return False
+
+ # scan marker length
+ mem = pos
+ pos = state.skipCharsStr(pos, marker)
+
+ length = pos - mem
+
+ if length < min_markers:
+ return False
+
+ markup = state.src[mem:pos]
+ params = state.src[pos:maximum]
+
+ if marker in disallow_marker_in_info and marker in params:
+ return False
+
+ # Since start is found, we can report success here in validation mode
+ if silent:
+ return True
+
+ # search end of block
+ nextLine = startLine
+
+ while True:
+ nextLine += 1
+ if nextLine >= endLine:
+ # unclosed block should be autoclosed by end of document.
+ # also block seems to be autoclosed by end of parent
+ break
+
+ pos = mem = state.bMarks[nextLine] + state.tShift[nextLine]
+ maximum = state.eMarks[nextLine]
+
+ if pos < maximum and state.sCount[nextLine] < state.blkIndent:
+ # non-empty line with negative indent should stop the list:
+ # - ```
+ # test
+ break
+
+ try:
+ if state.src[pos] != marker:
+ continue
+ except IndexError:
+ break
+
+ if state.is_code_block(nextLine):
+ continue
+
+ pos = state.skipCharsStr(pos, marker)
+
+ if not closing_matcher(length, pos - mem):
+ continue
+
+ # make sure tail has spaces only
+ pos = state.skipSpaces(pos)
+
+ if pos < maximum:
+ continue
+
+ haveEndMarker = True
+ # found!
+ break
+
+ # If a fence has heading spaces, they should be removed from its inner block
+ length = state.sCount[startLine]
+
+ state.line = nextLine + (1 if haveEndMarker else 0)
+
+ token = state.push(token_type, "code", 0)
+ token.info = params
+ token.content = state.getLines(startLine + 1, nextLine, length, True)
+ token.markup = markup
+ token.map = [startLine, state.line]
+
+ return True
+
+ return _fence_rule
+
+
+#: The default fence rule (backtick and tilde markers, CommonMark compliant).
+fence = make_fence_rule()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/heading.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/heading.py
new file mode 100644
index 0000000000000000000000000000000000000000..afcf9ed458124e52b9b365a6c17440872ffa0975
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/heading.py
@@ -0,0 +1,69 @@
+"""Atex heading (#, ##, ...)"""
+
+from __future__ import annotations
+
+import logging
+
+from ..common.utils import isStrSpace
+from .state_block import StateBlock
+
+LOGGER = logging.getLogger(__name__)
+
+
+def heading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
+ LOGGER.debug("entering heading: %s, %s, %s, %s", state, startLine, endLine, silent)
+
+ pos = state.bMarks[startLine] + state.tShift[startLine]
+ maximum = state.eMarks[startLine]
+
+ if state.is_code_block(startLine):
+ return False
+
+ ch: str | None = state.src[pos]
+
+ if ch != "#" or pos >= maximum:
+ return False
+
+ # count heading level
+ level = 1
+ pos += 1
+ try:
+ ch = state.src[pos]
+ except IndexError:
+ ch = None
+ while ch == "#" and pos < maximum and level <= 6:
+ level += 1
+ pos += 1
+ try:
+ ch = state.src[pos]
+ except IndexError:
+ ch = None
+
+ if level > 6 or (pos < maximum and not isStrSpace(ch)):
+ return False
+
+ if silent:
+ return True
+
+ # Let's cut tails like ' ### ' from the end of string
+
+ maximum = state.skipSpacesBack(maximum, pos)
+ tmp = state.skipCharsStrBack(maximum, "#", pos)
+ if tmp > pos and isStrSpace(state.src[tmp - 1]):
+ maximum = tmp
+
+ state.line = startLine + 1
+
+ token = state.push("heading_open", "h" + str(level), 1)
+ token.markup = "########"[:level]
+ token.map = [startLine, state.line]
+
+ token = state.push("inline", "", 0)
+ token.content = state.src[pos:maximum].strip()
+ token.map = [startLine, state.line]
+ token.children = []
+
+ token = state.push("heading_close", "h" + str(level), -1)
+ token.markup = "########"[:level]
+
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/hr.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/hr.py
new file mode 100644
index 0000000000000000000000000000000000000000..fca7d79d2780a5e656e689ac4843b8464b4ab5bd
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/hr.py
@@ -0,0 +1,56 @@
+"""Horizontal rule
+
+At least 3 of these characters on a line * - _
+"""
+
+import logging
+
+from ..common.utils import isStrSpace
+from .state_block import StateBlock
+
+LOGGER = logging.getLogger(__name__)
+
+
+def hr(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
+ LOGGER.debug("entering hr: %s, %s, %s, %s", state, startLine, endLine, silent)
+
+ pos = state.bMarks[startLine] + state.tShift[startLine]
+ maximum = state.eMarks[startLine]
+
+ if state.is_code_block(startLine):
+ return False
+
+ try:
+ marker = state.src[pos]
+ except IndexError:
+ return False
+ pos += 1
+
+ # Check hr marker
+ if marker not in ("*", "-", "_"):
+ return False
+
+ # markers can be mixed with spaces, but there should be at least 3 of them
+
+ cnt = 1
+ while pos < maximum:
+ ch = state.src[pos]
+ pos += 1
+ if ch != marker and not isStrSpace(ch):
+ return False
+ if ch == marker:
+ cnt += 1
+
+ if cnt < 3:
+ return False
+
+ if silent:
+ return True
+
+ state.line = startLine + 1
+
+ token = state.push("hr", "hr", 0)
+ token.map = [startLine, state.line]
+ token.markup = marker * (cnt + 1)
+
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/html_block.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/html_block.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d43f6ee1deb527a42f4d99da40bd052d9b02886
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/html_block.py
@@ -0,0 +1,90 @@
+# HTML block
+from __future__ import annotations
+
+import logging
+import re
+
+from ..common.html_blocks import block_names
+from ..common.html_re import HTML_OPEN_CLOSE_TAG_STR
+from .state_block import StateBlock
+
+LOGGER = logging.getLogger(__name__)
+
+# An array of opening and corresponding closing sequences for html tags,
+# last argument defines whether it can terminate a paragraph or not
+HTML_SEQUENCES: list[tuple[re.Pattern[str], re.Pattern[str], bool]] = [
+ (
+ re.compile(r"^<(script|pre|style|textarea)(?=(\s|>|$))", re.IGNORECASE),
+ re.compile(r"<\/(script|pre|style|textarea)>", re.IGNORECASE),
+ True,
+ ),
+ (re.compile(r"^"), True),
+ (re.compile(r"^<\?"), re.compile(r"\?>"), True),
+ (re.compile(r"^"), True),
+ (re.compile(r"^"), True),
+ (
+ re.compile("^?(" + "|".join(block_names) + ")(?=(\\s|/?>|$))", re.IGNORECASE),
+ re.compile(r"^$"),
+ True,
+ ),
+ (re.compile(HTML_OPEN_CLOSE_TAG_STR + "\\s*$"), re.compile(r"^$"), False),
+]
+
+
+def html_block(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
+ LOGGER.debug(
+ "entering html_block: %s, %s, %s, %s", state, startLine, endLine, silent
+ )
+ pos = state.bMarks[startLine] + state.tShift[startLine]
+ maximum = state.eMarks[startLine]
+
+ if state.is_code_block(startLine):
+ return False
+
+ if not state.md.options.get("html", None):
+ return False
+
+ if state.src[pos] != "<":
+ return False
+
+ lineText = state.src[pos:maximum]
+
+ html_seq = None
+ for HTML_SEQUENCE in HTML_SEQUENCES:
+ if HTML_SEQUENCE[0].search(lineText):
+ html_seq = HTML_SEQUENCE
+ break
+
+ if not html_seq:
+ return False
+
+ if silent:
+ # true if this sequence can be a terminator, false otherwise
+ return html_seq[2]
+
+ nextLine = startLine + 1
+
+ # If we are here - we detected HTML block.
+ # Let's roll down till block end.
+ if not html_seq[1].search(lineText):
+ while nextLine < endLine:
+ if state.sCount[nextLine] < state.blkIndent:
+ break
+
+ pos = state.bMarks[nextLine] + state.tShift[nextLine]
+ maximum = state.eMarks[nextLine]
+ lineText = state.src[pos:maximum]
+
+ if html_seq[1].search(lineText):
+ if len(lineText) != 0:
+ nextLine += 1
+ break
+ nextLine += 1
+
+ state.line = nextLine
+
+ token = state.push("html_block", "", 0)
+ token.map = [startLine, nextLine]
+ token.content = state.getLines(startLine, nextLine, state.blkIndent, True)
+
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/lheading.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/lheading.py
new file mode 100644
index 0000000000000000000000000000000000000000..3522207abb680510decdd6c54d0be81401128ad7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/lheading.py
@@ -0,0 +1,86 @@
+# lheading (---, ==)
+import logging
+
+from .state_block import StateBlock
+
+LOGGER = logging.getLogger(__name__)
+
+
+def lheading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
+ LOGGER.debug("entering lheading: %s, %s, %s, %s", state, startLine, endLine, silent)
+
+ level = None
+ nextLine = startLine + 1
+ ruler = state.md.block.ruler
+ terminatorRules = ruler.getRules("paragraph")
+
+ if state.is_code_block(startLine):
+ return False
+
+ oldParentType = state.parentType
+ state.parentType = "paragraph" # use paragraph to match terminatorRules
+
+ # jump line-by-line until empty one or EOF
+ while nextLine < endLine and not state.isEmpty(nextLine):
+ # this would be a code block normally, but after paragraph
+ # it's considered a lazy continuation regardless of what's there
+ if state.sCount[nextLine] - state.blkIndent > 3:
+ nextLine += 1
+ continue
+
+ # Check for underline in setext header
+ if state.sCount[nextLine] >= state.blkIndent:
+ pos = state.bMarks[nextLine] + state.tShift[nextLine]
+ maximum = state.eMarks[nextLine]
+
+ if pos < maximum:
+ marker = state.src[pos]
+
+ if marker in ("-", "="):
+ pos = state.skipCharsStr(pos, marker)
+ pos = state.skipSpaces(pos)
+
+ # /* = */
+ if pos >= maximum:
+ level = 1 if marker == "=" else 2
+ break
+
+ # quirk for blockquotes, this line should already be checked by that rule
+ if state.sCount[nextLine] < 0:
+ nextLine += 1
+ continue
+
+ # Some tags can terminate paragraph without empty line.
+ terminate = False
+ for terminatorRule in terminatorRules:
+ if terminatorRule(state, nextLine, endLine, True):
+ terminate = True
+ break
+ if terminate:
+ break
+
+ nextLine += 1
+
+ if not level:
+ # Didn't find valid underline
+ return False
+
+ content = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
+
+ state.line = nextLine + 1
+
+ token = state.push("heading_open", "h" + str(level), 1)
+ token.markup = marker
+ token.map = [startLine, state.line]
+
+ token = state.push("inline", "", 0)
+ token.content = content
+ token.map = [startLine, state.line - 1]
+ token.children = []
+
+ token = state.push("heading_close", "h" + str(level), -1)
+ token.markup = marker
+
+ state.parentType = oldParentType
+
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/list.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/list.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8fe7af5d5d0a2a1aedb59c09c01a2f8d49b1eea
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/list.py
@@ -0,0 +1,408 @@
+# Lists
+import logging
+
+from ..common.utils import isStrSpace
+from .state_block import StateBlock
+
+LOGGER = logging.getLogger(__name__)
+
+
+# Search `[-+*][\n ]`, returns next pos after marker on success
+# or -1 on fail.
+def skipBulletListMarker(state: StateBlock, startLine: int) -> int:
+ pos = state.bMarks[startLine] + state.tShift[startLine]
+ maximum = state.eMarks[startLine]
+
+ try:
+ marker = state.src[pos]
+ except IndexError:
+ return -1
+ pos += 1
+
+ if marker not in ("*", "-", "+"):
+ return -1
+
+ if pos < maximum:
+ ch = state.src[pos]
+
+ if not isStrSpace(ch):
+ # " -test " - is not a list item
+ return -1
+
+ return pos
+
+
+# Search `\d+[.)][\n ]`, returns next pos after marker on success
+# or -1 on fail.
+def skipOrderedListMarker(state: StateBlock, startLine: int) -> int:
+ start = state.bMarks[startLine] + state.tShift[startLine]
+ pos = start
+ maximum = state.eMarks[startLine]
+
+ # List marker should have at least 2 chars (digit + dot)
+ if pos + 1 >= maximum:
+ return -1
+
+ ch = state.src[pos]
+ pos += 1
+
+ ch_ord = ord(ch)
+ # /* 0 */ /* 9 */
+ if ch_ord < 0x30 or ch_ord > 0x39:
+ return -1
+
+ while True:
+ # EOL -> fail
+ if pos >= maximum:
+ return -1
+
+ ch = state.src[pos]
+ pos += 1
+
+ # /* 0 */ /* 9 */
+ ch_ord = ord(ch)
+ if ch_ord >= 0x30 and ch_ord <= 0x39:
+ # List marker should have no more than 9 digits
+ # (prevents integer overflow in browsers)
+ if pos - start >= 10:
+ return -1
+
+ continue
+
+ # found valid marker
+ if ch in (")", "."):
+ break
+
+ return -1
+
+ if pos < maximum:
+ ch = state.src[pos]
+
+ if not isStrSpace(ch):
+ # " 1.test " - is not a list item
+ return -1
+
+ return pos
+
+
+def markTightParagraphs(state: StateBlock, idx: int) -> None:
+ level = state.level + 2
+
+ i = idx + 2
+ length = len(state.tokens) - 2
+ while i < length:
+ if state.tokens[i].level == level and state.tokens[i].type == "paragraph_open":
+ state.tokens[i + 2].hidden = True
+ state.tokens[i].hidden = True
+ i += 2
+ i += 1
+
+
+def list_block(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
+ LOGGER.debug("entering list: %s, %s, %s, %s", state, startLine, endLine, silent)
+
+ isTerminatingParagraph = False
+ tight = True
+
+ if state.is_code_block(startLine):
+ return False
+
+ # Special case:
+ # - item 1
+ # - item 2
+ # - item 3
+ # - item 4
+ # - this one is a paragraph continuation
+ if (
+ state.listIndent >= 0
+ and state.sCount[startLine] - state.listIndent >= 4
+ and state.sCount[startLine] < state.blkIndent
+ ):
+ return False
+
+ # limit conditions when list can interrupt
+ # a paragraph (validation mode only)
+ # Next list item should still terminate previous list item
+ #
+ # This code can fail if plugins use blkIndent as well as lists,
+ # but I hope the spec gets fixed long before that happens.
+ #
+ if (
+ silent
+ and state.parentType == "paragraph"
+ and state.sCount[startLine] >= state.blkIndent
+ ):
+ isTerminatingParagraph = True
+
+ # Detect list type and position after marker
+ posAfterMarker = skipOrderedListMarker(state, startLine)
+ if posAfterMarker >= 0:
+ isOrdered = True
+ start = state.bMarks[startLine] + state.tShift[startLine]
+ markerValue = int(state.src[start : posAfterMarker - 1])
+
+ # If we're starting a new ordered list right after
+ # a paragraph, it should start with 1.
+ if isTerminatingParagraph and markerValue != 1:
+ return False
+ else:
+ posAfterMarker = skipBulletListMarker(state, startLine)
+ if posAfterMarker >= 0:
+ isOrdered = False
+ else:
+ return False
+
+ # If we're starting a new unordered list right after
+ # a paragraph, first line should not be empty.
+ if (
+ isTerminatingParagraph
+ and state.skipSpaces(posAfterMarker) >= state.eMarks[startLine]
+ ):
+ return False
+
+ # We should terminate list on style change. Remember first one to compare.
+ markerChar = state.src[posAfterMarker - 1]
+
+ # For validation mode we can terminate immediately
+ if silent:
+ return True
+
+ # Start list
+ listTokIdx = len(state.tokens)
+
+ if isOrdered:
+ token = state.push("ordered_list_open", "ol", 1)
+ if markerValue != 1:
+ token.attrs = {"start": markerValue}
+
+ else:
+ token = state.push("bullet_list_open", "ul", 1)
+
+ token.map = listLines = [startLine, 0]
+ token.markup = markerChar
+
+ #
+ # Iterate list items
+ #
+
+ nextLine = startLine
+ prevEmptyEnd = False
+ terminatorRules = state.md.block.ruler.getRules("list")
+
+ oldParentType = state.parentType
+ state.parentType = "list"
+
+ while nextLine < endLine:
+ pos = posAfterMarker
+ maximum = state.eMarks[nextLine]
+
+ initial = offset = (
+ state.sCount[nextLine]
+ + posAfterMarker
+ - (state.bMarks[startLine] + state.tShift[startLine])
+ )
+
+ while pos < maximum:
+ ch = state.src[pos]
+
+ if ch == "\t":
+ offset += 4 - (offset + state.bsCount[nextLine]) % 4
+ elif ch == " ":
+ offset += 1
+ else:
+ break
+
+ pos += 1
+
+ contentStart = pos
+
+ # trimming space in "- \n 3" case, indent is 1 here
+ indentAfterMarker = 1 if contentStart >= maximum else offset - initial
+
+ # If we have more than 4 spaces, the indent is 1
+ # (the rest is just indented code block)
+ if indentAfterMarker > 4:
+ indentAfterMarker = 1
+
+ # " - test"
+ # ^^^^^ - calculating total length of this thing
+ indent = initial + indentAfterMarker
+
+ # Run subparser & write tokens
+ token = state.push("list_item_open", "li", 1)
+ token.markup = markerChar
+ token.map = itemLines = [startLine, 0]
+ if isOrdered:
+ token.info = state.src[start : posAfterMarker - 1]
+
+ # Detect GFM task checkbox: `[ ] ` or `[x] `/`[X] ` at content start
+ checkboxLen = 0
+ if state.md.options.get("tasklists", False) and contentStart < maximum:
+ checked = _detect_task_checkbox(state.src, contentStart, maximum)
+ if checked is not None:
+ token.meta = {"checked": checked}
+ # Advance content past the checkbox: `[x]` (3 chars) + whitespace.
+ # `_detect_task_checkbox` already guarantees a whitespace char at
+ # pos+3, so we always consume 4 characters.
+ checkboxLen = 4
+
+ # change current state, then restore it after parser subcall
+ oldTight = state.tight
+ oldBMark = state.bMarks[startLine]
+ oldTShift = state.tShift[startLine]
+ oldSCount = state.sCount[startLine]
+
+ # - example list
+ # ^ listIndent position will be here
+ # ^ blkIndent position will be here
+ #
+ oldListIndent = state.listIndent
+ state.listIndent = state.blkIndent
+ state.blkIndent = indent
+
+ state.tight = True
+ state.tShift[startLine] = contentStart - state.bMarks[startLine]
+ state.sCount[startLine] = offset
+
+ # If we detected a checkbox, advance bMarks past it so that
+ # getLines() doesn't include the checkbox text in the content.
+ if checkboxLen:
+ state.bMarks[startLine] = contentStart + checkboxLen
+ state.tShift[startLine] = 0
+
+ if contentStart >= maximum and state.isEmpty(startLine + 1):
+ # workaround for this case
+ # (list item is empty, list terminates before "foo"):
+ # ~~~~~~~~
+ # -
+ #
+ # foo
+ # ~~~~~~~~
+ state.line = min(state.line + 2, endLine)
+ else:
+ # NOTE in list.js this was:
+ # state.md.block.tokenize(state, startLine, endLine, True)
+ # but tokeniz does not take the final parameter
+ state.md.block.tokenize(state, startLine, endLine)
+
+ # If any of list item is tight, mark list as tight
+ if (not state.tight) or prevEmptyEnd:
+ tight = False
+
+ # Item become loose if finish with empty line,
+ # but we should filter last element, because it means list finish
+ prevEmptyEnd = (state.line - startLine) > 1 and state.isEmpty(state.line - 1)
+
+ state.blkIndent = state.listIndent
+ state.listIndent = oldListIndent
+ if checkboxLen:
+ state.bMarks[startLine] = oldBMark
+ state.tShift[startLine] = oldTShift
+ state.sCount[startLine] = oldSCount
+ state.tight = oldTight
+
+ token = state.push("list_item_close", "li", -1)
+ token.markup = markerChar
+
+ nextLine = startLine = state.line
+ itemLines[1] = nextLine
+
+ if nextLine >= endLine:
+ break
+
+ contentStart = state.bMarks[startLine]
+
+ #
+ # Try to check if list is terminated or continued.
+ #
+ if state.sCount[nextLine] < state.blkIndent:
+ break
+
+ if state.is_code_block(startLine):
+ break
+
+ # fail if terminating block found
+ terminate = False
+ for terminatorRule in terminatorRules:
+ if terminatorRule(state, nextLine, endLine, True):
+ terminate = True
+ break
+
+ if terminate:
+ break
+
+ # fail if list has another type
+ if isOrdered:
+ posAfterMarker = skipOrderedListMarker(state, nextLine)
+ if posAfterMarker < 0:
+ break
+ start = state.bMarks[nextLine] + state.tShift[nextLine]
+ else:
+ posAfterMarker = skipBulletListMarker(state, nextLine)
+ if posAfterMarker < 0:
+ break
+
+ if markerChar != state.src[posAfterMarker - 1]:
+ break
+
+ # Finalize list
+
+ # If any direct list item has a task checkbox, add class to the list
+ if state.md.options.get("tasklists", False):
+ containsTask = False
+ level = state.tokens[listTokIdx].level
+ for j in range(listTokIdx + 1, len(state.tokens)):
+ tok = state.tokens[j]
+ if (
+ tok.level == level + 1
+ and tok.type == "list_item_open"
+ and tok.meta
+ and "checked" in tok.meta
+ ):
+ tok.attrJoin("class", "task-list-item")
+ containsTask = True
+ if containsTask:
+ state.tokens[listTokIdx].attrJoin("class", "contains-task-list")
+
+ if isOrdered:
+ token = state.push("ordered_list_close", "ol", -1)
+ else:
+ token = state.push("bullet_list_close", "ul", -1)
+
+ token.markup = markerChar
+
+ listLines[1] = nextLine
+ state.line = nextLine
+
+ state.parentType = oldParentType
+
+ # mark paragraphs tight if needed
+ if tight:
+ markTightParagraphs(state, listTokIdx)
+
+ return True
+
+
+def _detect_task_checkbox(src: str, pos: int, maximum: int) -> bool | None:
+ """Detect ``[ ]``, ``[x]``, or ``[X]`` at *pos*, followed by whitespace.
+
+ Returns ``True`` (checked), ``False`` (unchecked), or ``None`` (no match).
+ """
+ # Need at least 4 chars: `[`, char, `]`, whitespace
+ if pos + 4 > maximum:
+ return None
+ if src[pos] != "[":
+ return None
+ inner = src[pos + 1]
+ if src[pos + 2] != "]":
+ return None
+ if inner == " ":
+ checked = False
+ elif inner in ("x", "X"):
+ checked = True
+ else:
+ return None
+ # After `]`, must have whitespace
+ if src[pos + 3] not in (" ", "\t"):
+ return None
+ return checked
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/paragraph.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/paragraph.py
new file mode 100644
index 0000000000000000000000000000000000000000..30ba877799beb764dc0a603caa21fe6e6b641375
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/paragraph.py
@@ -0,0 +1,66 @@
+"""Paragraph."""
+
+import logging
+
+from .state_block import StateBlock
+
+LOGGER = logging.getLogger(__name__)
+
+
+def paragraph(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
+ LOGGER.debug(
+ "entering paragraph: %s, %s, %s, %s", state, startLine, endLine, silent
+ )
+
+ nextLine = startLine + 1
+ ruler = state.md.block.ruler
+ terminatorRules = ruler.getRules("paragraph")
+ endLine = state.lineMax
+
+ oldParentType = state.parentType
+ state.parentType = "paragraph"
+
+ # jump line-by-line until empty one or EOF
+ while nextLine < endLine:
+ if state.isEmpty(nextLine):
+ break
+ # this would be a code block normally, but after paragraph
+ # it's considered a lazy continuation regardless of what's there
+ if state.sCount[nextLine] - state.blkIndent > 3:
+ nextLine += 1
+ continue
+
+ # quirk for blockquotes, this line should already be checked by that rule
+ if state.sCount[nextLine] < 0:
+ nextLine += 1
+ continue
+
+ # Some tags can terminate paragraph without empty line.
+ terminate = False
+ for terminatorRule in terminatorRules:
+ if terminatorRule(state, nextLine, endLine, True):
+ terminate = True
+ break
+
+ if terminate:
+ break
+
+ nextLine += 1
+
+ content = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
+
+ state.line = nextLine
+
+ token = state.push("paragraph_open", "p", 1)
+ token.map = [startLine, state.line]
+
+ token = state.push("inline", "", 0)
+ token.content = content
+ token.map = [startLine, state.line]
+ token.children = []
+
+ token = state.push("paragraph_close", "p", -1)
+
+ state.parentType = oldParentType
+
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/reference.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/reference.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad94d40941ee7cd43c7d3873ac64276a47c15d8b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/reference.py
@@ -0,0 +1,235 @@
+import logging
+
+from ..common.utils import charCodeAt, isSpace, normalizeReference
+from .state_block import StateBlock
+
+LOGGER = logging.getLogger(__name__)
+
+
+def reference(state: StateBlock, startLine: int, _endLine: int, silent: bool) -> bool:
+ LOGGER.debug(
+ "entering reference: %s, %s, %s, %s", state, startLine, _endLine, silent
+ )
+
+ pos = state.bMarks[startLine] + state.tShift[startLine]
+ maximum = state.eMarks[startLine]
+ nextLine = startLine + 1
+
+ if state.is_code_block(startLine):
+ return False
+
+ if state.src[pos] != "[":
+ return False
+
+ string = state.src[pos : maximum + 1]
+
+ # string = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
+ maximum = len(string)
+
+ labelEnd = None
+ pos = 1
+ while pos < maximum:
+ ch = charCodeAt(string, pos)
+ if ch == 0x5B: # /* [ */
+ return False
+ elif ch == 0x5D: # /* ] */
+ labelEnd = pos
+ break
+ elif ch == 0x0A: # /* \n */
+ if (lineContent := getNextLine(state, nextLine)) is not None:
+ string += lineContent
+ maximum = len(string)
+ nextLine += 1
+ elif ch == 0x5C: # /* \ */
+ pos += 1
+ if (
+ pos < maximum
+ and charCodeAt(string, pos) == 0x0A
+ and (lineContent := getNextLine(state, nextLine)) is not None
+ ):
+ string += lineContent
+ maximum = len(string)
+ nextLine += 1
+ pos += 1
+
+ if (
+ labelEnd is None or labelEnd < 0 or charCodeAt(string, labelEnd + 1) != 0x3A
+ ): # /* : */
+ return False
+
+ # [label]: destination 'title'
+ # ^^^ skip optional whitespace here
+ pos = labelEnd + 2
+ while pos < maximum:
+ ch = charCodeAt(string, pos)
+ if ch == 0x0A:
+ if (lineContent := getNextLine(state, nextLine)) is not None:
+ string += lineContent
+ maximum = len(string)
+ nextLine += 1
+ elif isSpace(ch):
+ pass
+ else:
+ break
+ pos += 1
+
+ # [label]: destination 'title'
+ # ^^^^^^^^^^^ parse this
+ destRes = state.md.helpers.parseLinkDestination(string, pos, maximum)
+ if not destRes.ok:
+ return False
+
+ href = state.md.normalizeLink(destRes.str)
+ if not state.md.validateLink(href):
+ return False
+
+ pos = destRes.pos
+
+ # save cursor state, we could require to rollback later
+ destEndPos = pos
+ destEndLineNo = nextLine
+
+ # [label]: destination 'title'
+ # ^^^ skipping those spaces
+ start = pos
+ while pos < maximum:
+ ch = charCodeAt(string, pos)
+ if ch == 0x0A:
+ if (lineContent := getNextLine(state, nextLine)) is not None:
+ string += lineContent
+ maximum = len(string)
+ nextLine += 1
+ elif isSpace(ch):
+ pass
+ else:
+ break
+ pos += 1
+
+ # [label]: destination 'title'
+ # ^^^^^^^ parse this
+ titleRes = state.md.helpers.parseLinkTitle(string, pos, maximum, None)
+ while titleRes.can_continue:
+ if (lineContent := getNextLine(state, nextLine)) is None:
+ break
+ string += lineContent
+ pos = maximum
+ maximum = len(string)
+ nextLine += 1
+ titleRes = state.md.helpers.parseLinkTitle(string, pos, maximum, titleRes)
+
+ if pos < maximum and start != pos and titleRes.ok:
+ title = titleRes.str
+ pos = titleRes.pos
+ else:
+ title = ""
+ pos = destEndPos
+ nextLine = destEndLineNo
+
+ # skip trailing spaces until the rest of the line
+ while pos < maximum:
+ ch = charCodeAt(string, pos)
+ if not isSpace(ch):
+ break
+ pos += 1
+
+ if pos < maximum and charCodeAt(string, pos) != 0x0A and title:
+ # garbage at the end of the line after title,
+ # but it could still be a valid reference if we roll back
+ title = ""
+ pos = destEndPos
+ nextLine = destEndLineNo
+ while pos < maximum:
+ ch = charCodeAt(string, pos)
+ if not isSpace(ch):
+ break
+ pos += 1
+
+ if pos < maximum and charCodeAt(string, pos) != 0x0A:
+ # garbage at the end of the line
+ return False
+
+ label = normalizeReference(string[1:labelEnd])
+ if not label:
+ # CommonMark 0.20 disallows empty labels
+ return False
+
+ # Reference can not terminate anything. This check is for safety only.
+ if silent:
+ return True
+
+ if "references" not in state.env:
+ state.env["references"] = {}
+
+ state.line = nextLine
+
+ # note, this is not part of markdown-it JS, but is useful for renderers
+ if state.md.options.get("inline_definitions", False):
+ token = state.push("definition", "", 0)
+ token.meta = {
+ "id": label,
+ "title": title,
+ "url": href,
+ "label": string[1:labelEnd],
+ }
+ token.map = [startLine, state.line]
+
+ if label not in state.env["references"]:
+ state.env["references"][label] = {
+ "title": title,
+ "href": href,
+ "map": [startLine, state.line],
+ }
+ else:
+ state.env.setdefault("duplicate_refs", []).append(
+ {
+ "title": title,
+ "href": href,
+ "label": label,
+ "map": [startLine, state.line],
+ }
+ )
+
+ return True
+
+
+def getNextLine(state: StateBlock, nextLine: int) -> None | str:
+ endLine = state.lineMax
+
+ if nextLine >= endLine or state.isEmpty(nextLine):
+ # empty line or end of input
+ return None
+
+ isContinuation = False
+
+ # this would be a code block normally, but after paragraph
+ # it's considered a lazy continuation regardless of what's there
+ if state.is_code_block(nextLine):
+ isContinuation = True
+
+ # quirk for blockquotes, this line should already be checked by that rule
+ if state.sCount[nextLine] < 0:
+ isContinuation = True
+
+ if not isContinuation:
+ terminatorRules = state.md.block.ruler.getRules("reference")
+ oldParentType = state.parentType
+ state.parentType = "reference"
+
+ # Some tags can terminate paragraph without empty line.
+ terminate = False
+ for terminatorRule in terminatorRules:
+ if terminatorRule(state, nextLine, endLine, True):
+ terminate = True
+ break
+
+ state.parentType = oldParentType
+
+ if terminate:
+ # terminated by another block
+ return None
+
+ pos = state.bMarks[nextLine] + state.tShift[nextLine]
+ maximum = state.eMarks[nextLine]
+
+ # max + 1 explicitly includes the newline
+ return state.src[pos : maximum + 1]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/state_block.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/state_block.py
new file mode 100644
index 0000000000000000000000000000000000000000..445ad265a01e3f1dededf9f72848686a2b5ee901
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/state_block.py
@@ -0,0 +1,261 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Literal
+
+from ..common.utils import isStrSpace
+from ..ruler import StateBase
+from ..token import Token
+from ..utils import EnvType
+
+if TYPE_CHECKING:
+ from markdown_it.main import MarkdownIt
+
+
+class StateBlock(StateBase):
+ def __init__(
+ self, src: str, md: MarkdownIt, env: EnvType, tokens: list[Token]
+ ) -> None:
+ self.src = src
+
+ # link to parser instance
+ self.md = md
+
+ self.env = env
+
+ #
+ # Internal state variables
+ #
+
+ self.tokens = tokens
+
+ self.bMarks: list[int] = [] # line begin offsets for fast jumps
+ self.eMarks: list[int] = [] # line end offsets for fast jumps
+ # offsets of the first non-space characters (tabs not expanded)
+ self.tShift: list[int] = []
+ self.sCount: list[int] = [] # indents for each line (tabs expanded)
+
+ # An amount of virtual spaces (tabs expanded) between beginning
+ # of each line (bMarks) and real beginning of that line.
+ #
+ # It exists only as a hack because blockquotes override bMarks
+ # losing information in the process.
+ #
+ # It's used only when expanding tabs, you can think about it as
+ # an initial tab length, e.g. bsCount=21 applied to string `\t123`
+ # means first tab should be expanded to 4-21%4 === 3 spaces.
+ #
+ self.bsCount: list[int] = []
+
+ # block parser variables
+ self.blkIndent = 0 # required block content indent (for example, if we are
+ # inside a list, it would be positioned after list marker)
+ self.line = 0 # line index in src
+ self.lineMax = 0 # lines count
+ self.tight = False # loose/tight mode for lists
+ self.ddIndent = -1 # indent of the current dd block (-1 if there isn't any)
+ self.listIndent = -1 # indent of the current list block (-1 if there isn't any)
+
+ # can be 'blockquote', 'list', 'root', 'paragraph' or 'reference'
+ # used in lists to determine if they interrupt a paragraph
+ self.parentType = "root"
+
+ self.level = 0
+
+ # renderer
+ self.result = ""
+
+ # Create caches
+ # Generate markers.
+ indent_found = False
+
+ start = pos = indent = offset = 0
+ length = len(self.src)
+
+ for pos, character in enumerate(self.src):
+ if not indent_found:
+ if isStrSpace(character):
+ indent += 1
+
+ if character == "\t":
+ offset += 4 - offset % 4
+ else:
+ offset += 1
+ continue
+ else:
+ indent_found = True
+
+ if character == "\n" or pos == length - 1:
+ if character != "\n":
+ pos += 1
+ self.bMarks.append(start)
+ self.eMarks.append(pos)
+ self.tShift.append(indent)
+ self.sCount.append(offset)
+ self.bsCount.append(0)
+
+ indent_found = False
+ indent = 0
+ offset = 0
+ start = pos + 1
+
+ # Push fake entry to simplify cache bounds checks
+ self.bMarks.append(length)
+ self.eMarks.append(length)
+ self.tShift.append(0)
+ self.sCount.append(0)
+ self.bsCount.append(0)
+
+ self.lineMax = len(self.bMarks) - 1 # don't count last fake line
+
+ # pre-check if code blocks are enabled, to speed up is_code_block method
+ self._code_enabled = "code" in self.md["block"].ruler.get_active_rules()
+
+ def __repr__(self) -> str:
+ return (
+ f"{self.__class__.__name__}"
+ f"(line={self.line},level={self.level},tokens={len(self.tokens)})"
+ )
+
+ def push(self, ttype: str, tag: str, nesting: Literal[-1, 0, 1]) -> Token:
+ """Push new token to "stream"."""
+ token = Token(ttype, tag, nesting)
+ token.block = True
+ if nesting < 0:
+ self.level -= 1 # closing tag
+ token.level = self.level
+ if nesting > 0:
+ self.level += 1 # opening tag
+ self.tokens.append(token)
+ return token
+
+ def isEmpty(self, line: int) -> bool:
+ """."""
+ return (self.bMarks[line] + self.tShift[line]) >= self.eMarks[line]
+
+ def skipEmptyLines(self, from_pos: int) -> int:
+ """."""
+ while from_pos < self.lineMax:
+ try:
+ if (self.bMarks[from_pos] + self.tShift[from_pos]) < self.eMarks[
+ from_pos
+ ]:
+ break
+ except IndexError:
+ pass
+ from_pos += 1
+ return from_pos
+
+ def skipSpaces(self, pos: int) -> int:
+ """Skip spaces from given position."""
+ while True:
+ try:
+ current = self.src[pos]
+ except IndexError:
+ break
+ if not isStrSpace(current):
+ break
+ pos += 1
+ return pos
+
+ def skipSpacesBack(self, pos: int, minimum: int) -> int:
+ """Skip spaces from given position in reverse."""
+ if pos <= minimum:
+ return pos
+ while pos > minimum:
+ pos -= 1
+ if not isStrSpace(self.src[pos]):
+ return pos + 1
+ return pos
+
+ def skipChars(self, pos: int, code: int) -> int:
+ """Skip character code from given position."""
+ while True:
+ try:
+ current = self.srcCharCode[pos]
+ except IndexError:
+ break
+ if current != code:
+ break
+ pos += 1
+ return pos
+
+ def skipCharsStr(self, pos: int, ch: str) -> int:
+ """Skip character string from given position."""
+ while True:
+ try:
+ current = self.src[pos]
+ except IndexError:
+ break
+ if current != ch:
+ break
+ pos += 1
+ return pos
+
+ def skipCharsBack(self, pos: int, code: int, minimum: int) -> int:
+ """Skip character code reverse from given position - 1."""
+ if pos <= minimum:
+ return pos
+ while pos > minimum:
+ pos -= 1
+ if code != self.srcCharCode[pos]:
+ return pos + 1
+ return pos
+
+ def skipCharsStrBack(self, pos: int, ch: str, minimum: int) -> int:
+ """Skip character string reverse from given position - 1."""
+ if pos <= minimum:
+ return pos
+ while pos > minimum:
+ pos -= 1
+ if ch != self.src[pos]:
+ return pos + 1
+ return pos
+
+ def getLines(self, begin: int, end: int, indent: int, keepLastLF: bool) -> str:
+ """Cut lines range from source."""
+ line = begin
+ if begin >= end:
+ return ""
+
+ queue = [""] * (end - begin)
+
+ i = 1
+ while line < end:
+ lineIndent = 0
+ lineStart = first = self.bMarks[line]
+ last = (
+ self.eMarks[line] + 1
+ if line + 1 < end or keepLastLF
+ else self.eMarks[line]
+ )
+
+ while (first < last) and (lineIndent < indent):
+ ch = self.src[first]
+ if isStrSpace(ch):
+ if ch == "\t":
+ lineIndent += 4 - (lineIndent + self.bsCount[line]) % 4
+ else:
+ lineIndent += 1
+ elif first - lineStart < self.tShift[line]:
+ lineIndent += 1
+ else:
+ break
+ first += 1
+
+ if lineIndent > indent:
+ # partially expanding tabs in code blocks, e.g '\t\tfoobar'
+ # with indent=2 becomes ' \tfoobar'
+ queue[i - 1] = (" " * (lineIndent - indent)) + self.src[first:last]
+ else:
+ queue[i - 1] = self.src[first:last]
+
+ line += 1
+ i += 1
+
+ return "".join(queue)
+
+ def is_code_block(self, line: int) -> bool:
+ """Check if line is a code block,
+ i.e. the code block rule is enabled and text is indented by more than 3 spaces.
+ """
+ return self._code_enabled and (self.sCount[line] - self.blkIndent) >= 4
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/table.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/table.py
new file mode 100644
index 0000000000000000000000000000000000000000..c52553d8c21265df65e23be253686ef00b3297eb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_block/table.py
@@ -0,0 +1,250 @@
+# GFM table, https://github.github.com/gfm/#tables-extension-
+from __future__ import annotations
+
+import re
+
+from ..common.utils import charStrAt, isStrSpace
+from .state_block import StateBlock
+
+headerLineRe = re.compile(r"^:?-+:?$")
+enclosingPipesRe = re.compile(r"^\||\|$")
+
+# Limit the amount of empty autocompleted cells in a table,
+# see https://github.com/markdown-it/markdown-it/issues/1000,
+# Both pulldown-cmark and commonmark-hs limit the number of cells this way to ~200k.
+# We set it to 65k, which can expand user input by a factor of x370
+# (256x256 square is 1.8kB expanded into 650kB).
+MAX_AUTOCOMPLETED_CELLS = 0x10000
+
+
+def getLine(state: StateBlock, line: int) -> str:
+ pos = state.bMarks[line] + state.tShift[line]
+ maximum = state.eMarks[line]
+
+ # return state.src.substr(pos, max - pos)
+ return state.src[pos:maximum]
+
+
+def escapedSplit(string: str) -> list[str]:
+ result: list[str] = []
+ pos = 0
+ max = len(string)
+ isEscaped = False
+ lastPos = 0
+ current = ""
+ ch = charStrAt(string, pos)
+
+ while pos < max:
+ if ch == "|":
+ if not isEscaped:
+ # pipe separating cells, '|'
+ result.append(current + string[lastPos:pos])
+ current = ""
+ lastPos = pos + 1
+ else:
+ # escaped pipe, '\|'
+ current += string[lastPos : pos - 1]
+ lastPos = pos
+
+ isEscaped = ch == "\\"
+ pos += 1
+
+ ch = charStrAt(string, pos)
+
+ result.append(current + string[lastPos:])
+
+ return result
+
+
+def table(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
+ tbodyLines = None
+
+ # should have at least two lines
+ if startLine + 2 > endLine:
+ return False
+
+ nextLine = startLine + 1
+
+ if state.sCount[nextLine] < state.blkIndent:
+ return False
+
+ if state.is_code_block(nextLine):
+ return False
+
+ # first character of the second line should be '|', '-', ':',
+ # and no other characters are allowed but spaces;
+ # basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp
+
+ pos = state.bMarks[nextLine] + state.tShift[nextLine]
+ if pos >= state.eMarks[nextLine]:
+ return False
+ first_ch = state.src[pos]
+ pos += 1
+ if first_ch not in ("|", "-", ":"):
+ return False
+
+ if pos >= state.eMarks[nextLine]:
+ return False
+ second_ch = state.src[pos]
+ pos += 1
+ if second_ch not in ("|", "-", ":") and not isStrSpace(second_ch):
+ return False
+
+ # if first character is '-', then second character must not be a space
+ # (due to parsing ambiguity with list)
+ if first_ch == "-" and isStrSpace(second_ch):
+ return False
+
+ while pos < state.eMarks[nextLine]:
+ ch = state.src[pos]
+
+ if ch not in ("|", "-", ":") and not isStrSpace(ch):
+ return False
+
+ pos += 1
+
+ lineText = getLine(state, startLine + 1)
+
+ columns = lineText.split("|")
+ aligns = []
+ for i in range(len(columns)):
+ t = columns[i].strip()
+ if not t:
+ # allow empty columns before and after table, but not in between columns;
+ # e.g. allow ` |---| `, disallow ` ---||--- `
+ if i == 0 or i == len(columns) - 1:
+ continue
+ else:
+ return False
+
+ if not headerLineRe.search(t):
+ return False
+ if charStrAt(t, len(t) - 1) == ":":
+ aligns.append("center" if charStrAt(t, 0) == ":" else "right")
+ elif charStrAt(t, 0) == ":":
+ aligns.append("left")
+ else:
+ aligns.append("")
+
+ lineText = getLine(state, startLine).strip()
+ if "|" not in lineText:
+ return False
+ if state.is_code_block(startLine):
+ return False
+ columns = escapedSplit(lineText)
+ if columns and columns[0] == "":
+ columns.pop(0)
+ if columns and columns[-1] == "":
+ columns.pop()
+
+ # header row will define an amount of columns in the entire table,
+ # and align row should be exactly the same (the rest of the rows can differ)
+ columnCount = len(columns)
+ if columnCount == 0 or columnCount != len(aligns):
+ return False
+
+ if silent:
+ return True
+
+ oldParentType = state.parentType
+ state.parentType = "table"
+
+ # use 'blockquote' lists for termination because it's
+ # the most similar to tables
+ terminatorRules = state.md.block.ruler.getRules("blockquote")
+
+ token = state.push("table_open", "table", 1)
+ token.map = tableLines = [startLine, 0]
+
+ token = state.push("thead_open", "thead", 1)
+ token.map = [startLine, startLine + 1]
+
+ token = state.push("tr_open", "tr", 1)
+ token.map = [startLine, startLine + 1]
+
+ for i in range(len(columns)):
+ token = state.push("th_open", "th", 1)
+ if aligns[i]:
+ token.attrs = {"style": "text-align:" + aligns[i]}
+
+ token = state.push("inline", "", 0)
+ # note in markdown-it this map was removed in v12.0.0 however, we keep it,
+ # since it is helpful to propagate to children tokens
+ token.map = [startLine, startLine + 1]
+ token.content = columns[i].strip()
+ token.children = []
+
+ token = state.push("th_close", "th", -1)
+
+ token = state.push("tr_close", "tr", -1)
+ token = state.push("thead_close", "thead", -1)
+
+ autocompleted_cells = 0
+ nextLine = startLine + 2
+ while nextLine < endLine:
+ if state.sCount[nextLine] < state.blkIndent:
+ break
+
+ terminate = False
+ for i in range(len(terminatorRules)):
+ if terminatorRules[i](state, nextLine, endLine, True):
+ terminate = True
+ break
+
+ if terminate:
+ break
+ lineText = getLine(state, nextLine).strip()
+ if not lineText:
+ break
+ if state.is_code_block(nextLine):
+ break
+ columns = escapedSplit(lineText)
+ if columns and columns[0] == "":
+ columns.pop(0)
+ if columns and columns[-1] == "":
+ columns.pop()
+
+ # note: autocomplete count can be negative if user specifies more columns than header,
+ # but that does not affect intended use (which is limiting expansion)
+ autocompleted_cells += columnCount - len(columns)
+ if autocompleted_cells > MAX_AUTOCOMPLETED_CELLS:
+ break
+
+ if nextLine == startLine + 2:
+ token = state.push("tbody_open", "tbody", 1)
+ token.map = tbodyLines = [startLine + 2, 0]
+
+ token = state.push("tr_open", "tr", 1)
+ token.map = [nextLine, nextLine + 1]
+
+ for i in range(columnCount):
+ token = state.push("td_open", "td", 1)
+ if aligns[i]:
+ token.attrs = {"style": "text-align:" + aligns[i]}
+
+ token = state.push("inline", "", 0)
+ # note in markdown-it this map was removed in v12.0.0 however, we keep it,
+ # since it is helpful to propagate to children tokens
+ token.map = [nextLine, nextLine + 1]
+ try:
+ token.content = columns[i].strip() if columns[i] else ""
+ except IndexError:
+ token.content = ""
+ token.children = []
+
+ token = state.push("td_close", "td", -1)
+
+ token = state.push("tr_close", "tr", -1)
+
+ nextLine += 1
+
+ if tbodyLines:
+ token = state.push("tbody_close", "tbody", -1)
+ tbodyLines[1] = nextLine
+
+ token = state.push("table_close", "table", -1)
+
+ tableLines[1] = nextLine
+ state.parentType = oldParentType
+ state.line = nextLine
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7d775363c6e1d454e73a7e3fff9af3115be4339
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__init__.py
@@ -0,0 +1,19 @@
+__all__ = (
+ "StateCore",
+ "block",
+ "inline",
+ "linkify",
+ "normalize",
+ "replace",
+ "smartquotes",
+ "text_join",
+)
+
+from .block import block
+from .inline import inline
+from .linkify import linkify
+from .normalize import normalize
+from .replacements import replace
+from .smartquotes import smartquotes
+from .state_core import StateCore
+from .text_join import text_join
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b5a3287a407d012bccce1f215f4364c79f63d9a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/block.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/block.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..50af98e5d145613c2c73750a0f069910944c1db6
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/block.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/inline.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/inline.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..435f707b7b29dfc1b0ca143f65f3e53c40759a48
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/inline.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/linkify.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/linkify.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3fb42d2e04c7a62635e49a60aa7d8d07945a2827
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/linkify.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/normalize.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/normalize.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..379c1eae4219a4d8e41bb2a28b04e2fa8d3c6a02
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/normalize.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/replacements.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/replacements.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d86344108f5e30607b6c2dce48d0c707b3dd4c01
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/replacements.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/smartquotes.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/smartquotes.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67f9db5a36feff078a667cea874a46e1479d2437
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/smartquotes.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/state_core.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/state_core.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71d909fea155a231805bbbff067881a7f1bd136e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/state_core.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/text_join.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/text_join.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c3ef0fcee301b25af2ac2b45dcdeb169fd2d8a2
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/__pycache__/text_join.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/block.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/block.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6c3bb8d7ae18880fd638690fb5b09beb78b103c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/block.py
@@ -0,0 +1,13 @@
+from ..token import Token
+from .state_core import StateCore
+
+
+def block(state: StateCore) -> None:
+ if state.inlineMode:
+ token = Token("inline", "", 0)
+ token.content = state.src
+ token.map = [0, 1]
+ token.children = []
+ state.tokens.append(token)
+ else:
+ state.md.block.parse(state.src, state.md, state.env, state.tokens)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/inline.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/inline.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3fd0b5e25dda5d8a5a644cc9e460d0f92ae2d1d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/inline.py
@@ -0,0 +1,10 @@
+from .state_core import StateCore
+
+
+def inline(state: StateCore) -> None:
+ """Parse inlines"""
+ for token in state.tokens:
+ if token.type == "inline":
+ if token.children is None:
+ token.children = []
+ state.md.inline.parse(token.content, state.md, state.env, token.children)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/linkify.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/linkify.py
new file mode 100644
index 0000000000000000000000000000000000000000..efbc9d4c9b1cbada1c936401b3421d73fbff5b64
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/linkify.py
@@ -0,0 +1,149 @@
+from __future__ import annotations
+
+import re
+from typing import Protocol
+
+from ..common.utils import arrayReplaceAt, isLinkClose, isLinkOpen
+from ..token import Token
+from .state_core import StateCore
+
+HTTP_RE = re.compile(r"^http://")
+MAILTO_RE = re.compile(r"^mailto:")
+TEST_MAILTO_RE = re.compile(r"^mailto:", flags=re.IGNORECASE)
+
+
+def linkify(state: StateCore) -> None:
+ """Rule for identifying plain-text links."""
+ if not state.md.options.linkify:
+ return
+
+ if not state.md.linkify:
+ raise ModuleNotFoundError("Linkify enabled but not installed.")
+
+ for inline_token in state.tokens:
+ if inline_token.type != "inline" or not state.md.linkify.pretest(
+ inline_token.content
+ ):
+ continue
+
+ tokens = inline_token.children
+
+ htmlLinkLevel = 0
+
+ # We scan from the end, to keep position when new tags added.
+ # Use reversed logic in links start/end match
+ assert tokens is not None
+ i = len(tokens)
+ while i >= 1:
+ i -= 1
+ assert isinstance(tokens, list)
+ currentToken = tokens[i]
+
+ # Skip content of markdown links
+ if currentToken.type == "link_close":
+ i -= 1
+ while (
+ tokens[i].level != currentToken.level
+ and tokens[i].type != "link_open"
+ ):
+ i -= 1
+ continue
+
+ # Skip content of html tag links
+ if currentToken.type == "html_inline":
+ if isLinkOpen(currentToken.content) and htmlLinkLevel > 0:
+ htmlLinkLevel -= 1
+ if isLinkClose(currentToken.content):
+ htmlLinkLevel += 1
+ if htmlLinkLevel > 0:
+ continue
+
+ if currentToken.type == "text" and state.md.linkify.test(
+ currentToken.content
+ ):
+ text = currentToken.content
+ links: list[_LinkType] = state.md.linkify.match(text) or []
+
+ # Now split string to nodes
+ nodes = []
+ level = currentToken.level
+ lastPos = 0
+
+ # forbid escape sequence at the start of the string,
+ # this avoids http\://example.com/ from being linkified as
+ # http://example.com/
+ if (
+ links
+ and links[0].index == 0
+ and i > 0
+ and tokens[i - 1].type == "text_special"
+ ):
+ links = links[1:]
+
+ for link in links:
+ url = link.url
+ fullUrl = state.md.normalizeLink(url)
+ if not state.md.validateLink(fullUrl):
+ continue
+
+ urlText = link.text
+
+ # Linkifier might send raw hostnames like "example.com", where url
+ # starts with domain name. So we prepend http:// in those cases,
+ # and remove it afterwards.
+ if not link.schema:
+ urlText = HTTP_RE.sub(
+ "", state.md.normalizeLinkText("http://" + urlText)
+ )
+ elif link.schema == "mailto:" and TEST_MAILTO_RE.search(urlText):
+ urlText = MAILTO_RE.sub(
+ "", state.md.normalizeLinkText("mailto:" + urlText)
+ )
+ else:
+ urlText = state.md.normalizeLinkText(urlText)
+
+ pos = link.index
+
+ if pos > lastPos:
+ token = Token("text", "", 0)
+ token.content = text[lastPos:pos]
+ token.level = level
+ nodes.append(token)
+
+ token = Token("link_open", "a", 1)
+ token.attrs = {"href": fullUrl}
+ token.level = level
+ level += 1
+ token.markup = "linkify"
+ token.info = "auto"
+ nodes.append(token)
+
+ token = Token("text", "", 0)
+ token.content = urlText
+ token.level = level
+ nodes.append(token)
+
+ token = Token("link_close", "a", -1)
+ level -= 1
+ token.level = level
+ token.markup = "linkify"
+ token.info = "auto"
+ nodes.append(token)
+
+ lastPos = link.last_index
+
+ if lastPos < len(text):
+ token = Token("text", "", 0)
+ token.content = text[lastPos:]
+ token.level = level
+ nodes.append(token)
+
+ inline_token.children = tokens = arrayReplaceAt(tokens, i, nodes)
+
+
+class _LinkType(Protocol):
+ url: str
+ text: str
+ index: int
+ last_index: int
+ schema: str | None
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/normalize.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/normalize.py
new file mode 100644
index 0000000000000000000000000000000000000000..32439243ef6ebfa424d202ed63635983d4c9ea82
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/normalize.py
@@ -0,0 +1,19 @@
+"""Normalize input string."""
+
+import re
+
+from .state_core import StateCore
+
+# https://spec.commonmark.org/0.29/#line-ending
+NEWLINES_RE = re.compile(r"\r\n?|\n")
+NULL_RE = re.compile(r"\0")
+
+
+def normalize(state: StateCore) -> None:
+ # Normalize newlines
+ string = NEWLINES_RE.sub("\n", state.src)
+
+ # Replace NULL characters
+ string = NULL_RE.sub("\ufffd", string)
+
+ state.src = string
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/replacements.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/replacements.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcc9980046bf76723245b1ca2543af132efe5541
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/replacements.py
@@ -0,0 +1,127 @@
+"""Simple typographic replacements
+
+* ``(c)``, ``(C)`` → ©
+* ``(tm)``, ``(TM)`` → ™
+* ``(r)``, ``(R)`` → ®
+* ``+-`` → ±
+* ``...`` → …
+* ``?....`` → ?..
+* ``!....`` → !..
+* ``????????`` → ???
+* ``!!!!!`` → !!!
+* ``,,,`` → ,
+* ``--`` → &ndash
+* ``---`` → &mdash
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+
+from ..token import Token
+from .state_core import StateCore
+
+LOGGER = logging.getLogger(__name__)
+
+# TODO:
+# - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾
+# - multiplication 2 x 4 -> 2 × 4
+
+RARE_RE = re.compile(r"\+-|\.\.|\?\?\?\?|!!!!|,,|--")
+
+# Workaround for phantomjs - need regex without /g flag,
+# or root check will fail every second time
+# SCOPED_ABBR_TEST_RE = r"\((c|tm|r)\)"
+
+SCOPED_ABBR_RE = re.compile(r"\((c|tm|r)\)", flags=re.IGNORECASE)
+
+PLUS_MINUS_RE = re.compile(r"\+-")
+
+ELLIPSIS_RE = re.compile(r"\.{2,}")
+
+ELLIPSIS_QUESTION_EXCLAMATION_RE = re.compile(r"([?!])…")
+
+QUESTION_EXCLAMATION_RE = re.compile(r"([?!]){4,}")
+
+COMMA_RE = re.compile(r",{2,}")
+
+EM_DASH_RE = re.compile(r"(^|[^-])---(?=[^-]|$)", flags=re.MULTILINE)
+
+EN_DASH_RE = re.compile(r"(^|\s)--(?=\s|$)", flags=re.MULTILINE)
+
+EN_DASH_INDENT_RE = re.compile(r"(^|[^-\s])--(?=[^-\s]|$)", flags=re.MULTILINE)
+
+
+SCOPED_ABBR = {"c": "©", "r": "®", "tm": "™"}
+
+
+def replaceFn(match: re.Match[str]) -> str:
+ return SCOPED_ABBR[match.group(1).lower()]
+
+
+def replace_scoped(inlineTokens: list[Token]) -> None:
+ inside_autolink = 0
+
+ for token in inlineTokens:
+ if token.type == "text" and not inside_autolink:
+ token.content = SCOPED_ABBR_RE.sub(replaceFn, token.content)
+
+ if token.type == "link_open" and token.info == "auto":
+ inside_autolink -= 1
+
+ if token.type == "link_close" and token.info == "auto":
+ inside_autolink += 1
+
+
+def replace_rare(inlineTokens: list[Token]) -> None:
+ inside_autolink = 0
+
+ for token in inlineTokens:
+ if (
+ token.type == "text"
+ and (not inside_autolink)
+ and RARE_RE.search(token.content)
+ ):
+ # +- -> ±
+ token.content = PLUS_MINUS_RE.sub("±", token.content)
+
+ # .., ..., ....... -> …
+ token.content = ELLIPSIS_RE.sub("…", token.content)
+
+ # but ?..... & !..... -> ?.. & !..
+ token.content = ELLIPSIS_QUESTION_EXCLAMATION_RE.sub("\\1..", token.content)
+ token.content = QUESTION_EXCLAMATION_RE.sub("\\1\\1\\1", token.content)
+
+ # ,, ,,, ,,,, -> ,
+ token.content = COMMA_RE.sub(",", token.content)
+
+ # em-dash
+ token.content = EM_DASH_RE.sub("\\1\u2014", token.content)
+
+ # en-dash
+ token.content = EN_DASH_RE.sub("\\1\u2013", token.content)
+ token.content = EN_DASH_INDENT_RE.sub("\\1\u2013", token.content)
+
+ if token.type == "link_open" and token.info == "auto":
+ inside_autolink -= 1
+
+ if token.type == "link_close" and token.info == "auto":
+ inside_autolink += 1
+
+
+def replace(state: StateCore) -> None:
+ if not state.md.options.typographer:
+ return
+
+ for token in state.tokens:
+ if token.type != "inline":
+ continue
+ if token.children is None:
+ continue
+
+ if SCOPED_ABBR_RE.search(token.content):
+ replace_scoped(token.children)
+
+ if RARE_RE.search(token.content):
+ replace_rare(token.children)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/smartquotes.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/smartquotes.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9b8b457b6c134f5736fabd3b14dc746e75ab86b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/smartquotes.py
@@ -0,0 +1,202 @@
+"""Convert straight quotation marks to typographic ones"""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+from ..common.utils import charCodeAt, isMdAsciiPunct, isPunctChar, isWhiteSpace
+from ..token import Token
+from .state_core import StateCore
+
+QUOTE_TEST_RE = re.compile(r"['\"]")
+QUOTE_RE = re.compile(r"['\"]")
+APOSTROPHE = "\u2019" # ’
+
+
+def replaceAt(string: str, index: int, ch: str) -> str:
+ # When the index is negative, the behavior is different from the js version.
+ # But basically, the index will not be negative.
+ assert index >= 0
+ return string[:index] + ch + string[index + 1 :]
+
+
+def process_inlines(tokens: list[Token], state: StateCore) -> None:
+ stack: list[dict[str, Any]] = []
+
+ for i, token in enumerate(tokens):
+ thisLevel = token.level
+
+ j = 0
+ for j in range(len(stack))[::-1]:
+ if stack[j]["level"] <= thisLevel:
+ break
+ else:
+ # When the loop is terminated without a "break".
+ # Subtract 1 to get the same index as the js version.
+ j -= 1
+
+ stack = stack[: j + 1]
+
+ if token.type != "text":
+ continue
+
+ text = token.content
+ pos = 0
+ maximum = len(text)
+
+ while pos < maximum:
+ goto_outer = False
+ lastIndex = pos
+ t = QUOTE_RE.search(text[lastIndex:])
+ if not t:
+ break
+
+ canOpen = canClose = True
+ pos = t.start(0) + lastIndex + 1
+ isSingle = t.group(0) == "'"
+
+ # Find previous character,
+ # default to space if it's the beginning of the line
+ lastChar: None | int = 0x20
+
+ if t.start(0) + lastIndex - 1 >= 0:
+ lastChar = charCodeAt(text, t.start(0) + lastIndex - 1)
+ else:
+ for j in range(i)[::-1]:
+ if tokens[j].type == "softbreak" or tokens[j].type == "hardbreak":
+ break
+ # should skip all tokens except 'text', 'html_inline' or 'code_inline'
+ if not tokens[j].content:
+ continue
+
+ lastChar = charCodeAt(tokens[j].content, len(tokens[j].content) - 1)
+ break
+
+ # Find next character,
+ # default to space if it's the end of the line
+ nextChar: None | int = 0x20
+
+ if pos < maximum:
+ nextChar = charCodeAt(text, pos)
+ else:
+ for j in range(i + 1, len(tokens)):
+ # nextChar defaults to 0x20
+ if tokens[j].type == "softbreak" or tokens[j].type == "hardbreak":
+ break
+ # should skip all tokens except 'text', 'html_inline' or 'code_inline'
+ if not tokens[j].content:
+ continue
+
+ nextChar = charCodeAt(tokens[j].content, 0)
+ break
+
+ isLastPunctChar = lastChar is not None and (
+ isMdAsciiPunct(lastChar) or isPunctChar(chr(lastChar))
+ )
+ isNextPunctChar = nextChar is not None and (
+ isMdAsciiPunct(nextChar) or isPunctChar(chr(nextChar))
+ )
+
+ isLastWhiteSpace = lastChar is not None and isWhiteSpace(lastChar)
+ isNextWhiteSpace = nextChar is not None and isWhiteSpace(nextChar)
+
+ if isNextWhiteSpace: # noqa: SIM114
+ canOpen = False
+ elif isNextPunctChar and not (isLastWhiteSpace or isLastPunctChar):
+ canOpen = False
+
+ if isLastWhiteSpace: # noqa: SIM114
+ canClose = False
+ elif isLastPunctChar and not (isNextWhiteSpace or isNextPunctChar):
+ canClose = False
+
+ if nextChar == 0x22 and t.group(0) == '"': # 0x22: " # noqa: SIM102
+ if (
+ lastChar is not None and lastChar >= 0x30 and lastChar <= 0x39
+ ): # 0x30: 0, 0x39: 9
+ # special case: 1"" - count first quote as an inch
+ canClose = canOpen = False
+
+ if canOpen and canClose:
+ # Replace quotes in the middle of punctuation sequence, but not
+ # in the middle of the words, i.e.:
+ #
+ # 1. foo " bar " baz - not replaced
+ # 2. foo-"-bar-"-baz - replaced
+ # 3. foo"bar"baz - not replaced
+ canOpen = isLastPunctChar
+ canClose = isNextPunctChar
+
+ if not canOpen and not canClose:
+ # middle of word
+ if isSingle:
+ token.content = replaceAt(
+ token.content, t.start(0) + lastIndex, APOSTROPHE
+ )
+ continue
+
+ if canClose:
+ # this could be a closing quote, rewind the stack to get a match
+ for j in range(len(stack))[::-1]:
+ item = stack[j]
+ if stack[j]["level"] < thisLevel:
+ break
+ if item["single"] == isSingle and stack[j]["level"] == thisLevel:
+ item = stack[j]
+
+ if isSingle:
+ openQuote = state.md.options.quotes[2]
+ closeQuote = state.md.options.quotes[3]
+ else:
+ openQuote = state.md.options.quotes[0]
+ closeQuote = state.md.options.quotes[1]
+
+ # replace token.content *before* tokens[item.token].content,
+ # because, if they are pointing at the same token, replaceAt
+ # could mess up indices when quote length != 1
+ token.content = replaceAt(
+ token.content, t.start(0) + lastIndex, closeQuote
+ )
+ tokens[item["token"]].content = replaceAt(
+ tokens[item["token"]].content, item["pos"], openQuote
+ )
+
+ pos += len(closeQuote) - 1
+ if item["token"] == i:
+ pos += len(openQuote) - 1
+
+ text = token.content
+ maximum = len(text)
+
+ stack = stack[:j]
+ goto_outer = True
+ break
+ if goto_outer:
+ goto_outer = False
+ continue
+
+ if canOpen:
+ stack.append(
+ {
+ "token": i,
+ "pos": t.start(0) + lastIndex,
+ "single": isSingle,
+ "level": thisLevel,
+ }
+ )
+ elif canClose and isSingle:
+ token.content = replaceAt(
+ token.content, t.start(0) + lastIndex, APOSTROPHE
+ )
+
+
+def smartquotes(state: StateCore) -> None:
+ if not state.md.options.typographer:
+ return
+
+ for token in state.tokens:
+ if token.type != "inline" or not QUOTE_RE.search(token.content):
+ continue
+ if token.children is not None:
+ process_inlines(token.children, state)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/state_core.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/state_core.py
new file mode 100644
index 0000000000000000000000000000000000000000..a938041d992fdf7ae3f2843a2e0f9ef298c45790
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/state_core.py
@@ -0,0 +1,25 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from ..ruler import StateBase
+from ..token import Token
+from ..utils import EnvType
+
+if TYPE_CHECKING:
+ from markdown_it import MarkdownIt
+
+
+class StateCore(StateBase):
+ def __init__(
+ self,
+ src: str,
+ md: MarkdownIt,
+ env: EnvType,
+ tokens: list[Token] | None = None,
+ ) -> None:
+ self.src = src
+ self.md = md # link to parser instance
+ self.env = env
+ self.tokens: list[Token] = tokens or []
+ self.inlineMode = False
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/text_join.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/text_join.py
new file mode 100644
index 0000000000000000000000000000000000000000..939b83b29f75fa697a9b0f57ca86302744d639d1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_core/text_join.py
@@ -0,0 +1,53 @@
+"""Join raw text tokens with the rest of the text
+
+This is set as a separate rule to provide an opportunity for plugins
+to run text replacements after text join, but before escape join.
+
+For example, `\\:)` shouldn't be replaced with an emoji.
+"""
+
+from __future__ import annotations
+
+from ..token import Token
+from .state_core import StateCore
+
+
+def text_join(state: StateCore) -> None:
+ """Join raw text for escape sequences (`text_special`) tokens with the rest of the text"""
+
+ for inline_token in state.tokens[:]:
+ if inline_token.type != "inline":
+ continue
+
+ # convert text_special to text and join all adjacent text nodes
+ new_tokens: list[Token] = []
+ children = inline_token.children or []
+ i = 0
+ while i < len(children):
+ child_token = children[i]
+ if child_token.type == "text_special":
+ child_token.type = "text"
+ if (
+ child_token.type == "text"
+ and new_tokens
+ and new_tokens[-1].type == "text"
+ ):
+ # Collapse a run of adjacent text nodes in a single join, instead
+ # of pairwise `a + b` concatenation. The pairwise form is O(L*k)
+ # in the size of the run because each step rebuilds the growing
+ # prefix; "".join is O(L).
+ parts = [new_tokens[-1].content, child_token.content]
+ i += 1
+ while i < len(children):
+ next_token = children[i]
+ if next_token.type == "text_special":
+ next_token.type = "text"
+ if next_token.type != "text":
+ break
+ parts.append(next_token.content)
+ i += 1
+ new_tokens[-1].content = "".join(parts)
+ else:
+ new_tokens.append(child_token)
+ i += 1
+ inline_token.children = new_tokens
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d82ef8fbcca54eab4bbb40e8410104eef7a27f57
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__init__.py
@@ -0,0 +1,31 @@
+__all__ = (
+ "StateInline",
+ "autolink",
+ "backtick",
+ "emphasis",
+ "entity",
+ "escape",
+ "fragments_join",
+ "html_inline",
+ "image",
+ "link",
+ "link_pairs",
+ "linkify",
+ "newline",
+ "strikethrough",
+ "text",
+)
+from . import emphasis, strikethrough
+from .autolink import autolink
+from .backticks import backtick
+from .balance_pairs import link_pairs
+from .entity import entity
+from .escape import escape
+from .fragments_join import fragments_join
+from .html_inline import html_inline
+from .image import image
+from .link import link
+from .linkify import linkify
+from .newline import newline
+from .state_inline import StateInline
+from .text import text
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..877c5a1752ef33003a0b9ad102fac181ccb6efd1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/autolink.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/autolink.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..910c2f6fa1c605f853e91e64a3af12f5a10be213
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/autolink.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/backticks.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/backticks.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd223db19a59b4077de3a280665f3bdbf17c4c19
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/backticks.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/balance_pairs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/balance_pairs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e58323300cb6dcede7682cccfd97b8dd368b7b81
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/balance_pairs.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/emphasis.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/emphasis.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3255a85cf0c89023da33eb00c80d9c051ab02748
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/emphasis.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/entity.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/entity.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79548a816f163bfc7c7f900d43ae99ce88827da2
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/entity.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/escape.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/escape.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2904007ebee646e9ed125a783ab44136e839cb34
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/escape.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/fragments_join.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/fragments_join.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..585edacefee84c03ea69b1e18e3d6ce56d575337
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/fragments_join.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/html_inline.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/html_inline.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..98b86b7509130a3dd0ed203a448c39a4eedf5310
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/html_inline.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/image.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/image.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ad8681efdfc401092faae2cdf326cd441434452
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/image.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/link.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/link.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b61f2e12bc786471e8146a6825c5b8c550c64b90
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/link.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/linkify.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/linkify.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e34e96e1e9c56a4776c4ed47a9398cd369d64480
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/linkify.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/newline.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/newline.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b4d5679034e5db6ed032865b98eef93997886d14
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/newline.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/state_inline.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/state_inline.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e972f5a398e669fefc114d110b4713d657c650f5
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/state_inline.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/strikethrough.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/strikethrough.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f2d07248ce349fdbd7924b7141e2811fb2543a2
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/strikethrough.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/text.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/text.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7aa3d736464cf73c712d88ae978f74dd19892a71
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/__pycache__/text.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/autolink.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/autolink.py
new file mode 100644
index 0000000000000000000000000000000000000000..6546e2502f93a1b38a49c3fd728963a156cf0243
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/autolink.py
@@ -0,0 +1,77 @@
+# Process autolinks ''
+import re
+
+from .state_inline import StateInline
+
+EMAIL_RE = re.compile(
+ r"^([a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$"
+)
+AUTOLINK_RE = re.compile(r"^([a-zA-Z][a-zA-Z0-9+.\-]{1,31}):([^<>\x00-\x20]*)$")
+
+
+def autolink(state: StateInline, silent: bool) -> bool:
+ pos = state.pos
+
+ if state.src[pos] != "<":
+ return False
+
+ start = state.pos
+ maximum = state.posMax
+
+ while True:
+ pos += 1
+ if pos >= maximum:
+ return False
+
+ ch = state.src[pos]
+
+ if ch == "<":
+ return False
+ if ch == ">":
+ break
+
+ url = state.src[start + 1 : pos]
+
+ if AUTOLINK_RE.search(url) is not None:
+ fullUrl = state.md.normalizeLink(url)
+ if not state.md.validateLink(fullUrl):
+ return False
+
+ if not silent:
+ token = state.push("link_open", "a", 1)
+ token.attrs = {"href": fullUrl}
+ token.markup = "autolink"
+ token.info = "auto"
+
+ token = state.push("text", "", 0)
+ token.content = state.md.normalizeLinkText(url)
+
+ token = state.push("link_close", "a", -1)
+ token.markup = "autolink"
+ token.info = "auto"
+
+ state.pos += len(url) + 2
+ return True
+
+ if EMAIL_RE.search(url) is not None:
+ fullUrl = state.md.normalizeLink("mailto:" + url)
+ if not state.md.validateLink(fullUrl):
+ return False
+
+ if not silent:
+ token = state.push("link_open", "a", 1)
+ token.attrs = {"href": fullUrl}
+ token.markup = "autolink"
+ token.info = "auto"
+
+ token = state.push("text", "", 0)
+ token.content = state.md.normalizeLinkText(url)
+
+ token = state.push("link_close", "a", -1)
+ token.markup = "autolink"
+ token.info = "auto"
+
+ state.pos += len(url) + 2
+ return True
+
+ return False
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/backticks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/backticks.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc60d6b15cdfa7012a05bcf1ccbb06f44d870dfd
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/backticks.py
@@ -0,0 +1,72 @@
+# Parse backticks
+import re
+
+from .state_inline import StateInline
+
+regex = re.compile("^ (.+) $")
+
+
+def backtick(state: StateInline, silent: bool) -> bool:
+ pos = state.pos
+
+ if state.src[pos] != "`":
+ return False
+
+ start = pos
+ pos += 1
+ maximum = state.posMax
+
+ # scan marker length
+ while pos < maximum and (state.src[pos] == "`"):
+ pos += 1
+
+ marker = state.src[start:pos]
+ openerLength = len(marker)
+
+ if state.backticksScanned and state.backticks.get(openerLength, 0) <= start:
+ if not silent:
+ state.pending += marker
+ state.pos += openerLength
+ return True
+
+ matchStart = matchEnd = pos
+
+ # Nothing found in the cache, scan until the end of the line (or until marker is found)
+ while True:
+ try:
+ matchStart = state.src.index("`", matchEnd)
+ except ValueError:
+ break
+ matchEnd = matchStart + 1
+
+ # scan marker length
+ while matchEnd < maximum and (state.src[matchEnd] == "`"):
+ matchEnd += 1
+
+ closerLength = matchEnd - matchStart
+
+ if closerLength == openerLength:
+ # Found matching closer length.
+ if not silent:
+ token = state.push("code_inline", "code", 0)
+ token.markup = marker
+ token.content = state.src[pos:matchStart].replace("\n", " ")
+ if (
+ token.content.startswith(" ")
+ and token.content.endswith(" ")
+ and len(token.content.strip()) > 0
+ ):
+ token.content = token.content[1:-1]
+ state.pos = matchEnd
+ return True
+
+ # Some different length found, put it in cache as upper limit of where closer can be found
+ state.backticks[closerLength] = matchStart
+
+ # Scanned through the end, didn't find anything
+ state.backticksScanned = True
+
+ if not silent:
+ state.pending += marker
+ state.pos += openerLength
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/balance_pairs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/balance_pairs.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c63b27f7186eb99c61938d27309fda7e900b88d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/balance_pairs.py
@@ -0,0 +1,138 @@
+"""Balance paired characters (*, _, etc) in inline tokens."""
+
+from __future__ import annotations
+
+from .state_inline import Delimiter, StateInline
+
+
+def processDelimiters(state: StateInline, delimiters: list[Delimiter]) -> None:
+ """For each opening emphasis-like marker find a matching closing one."""
+ if not delimiters:
+ return
+
+ openersBottom = {}
+ maximum = len(delimiters)
+
+ # headerIdx is the first delimiter of the current (where closer is) delimiter run
+ headerIdx = 0
+ lastTokenIdx = -2 # needs any value lower than -1
+ jumps: list[int] = []
+ closerIdx = 0
+ while closerIdx < maximum:
+ closer = delimiters[closerIdx]
+
+ jumps.append(0)
+
+ # markers belong to same delimiter run if:
+ # - they have adjacent tokens
+ # - AND markers are the same
+ #
+ if (
+ delimiters[headerIdx].marker != closer.marker
+ or lastTokenIdx != closer.token - 1
+ ):
+ headerIdx = closerIdx
+ lastTokenIdx = closer.token
+
+ # Length is only used for emphasis-specific "rule of 3",
+ # if it's not defined (in strikethrough or 3rd party plugins),
+ # we can default it to 0 to disable those checks.
+ #
+ closer.length = closer.length or 0
+
+ if not closer.close:
+ closerIdx += 1
+ continue
+
+ # Previously calculated lower bounds (previous fails)
+ # for each marker, each delimiter length modulo 3,
+ # and for whether this closer can be an opener;
+ # https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460
+ if closer.marker not in openersBottom:
+ openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1]
+
+ minOpenerIdx = openersBottom[closer.marker][
+ (3 if closer.open else 0) + (closer.length % 3)
+ ]
+
+ openerIdx = headerIdx - jumps[headerIdx] - 1
+
+ newMinOpenerIdx = openerIdx
+
+ while openerIdx > minOpenerIdx:
+ opener = delimiters[openerIdx]
+
+ if opener.marker != closer.marker:
+ openerIdx -= jumps[openerIdx] + 1
+ continue
+
+ if opener.open and opener.end < 0:
+ isOddMatch = False
+
+ # from spec:
+ #
+ # If one of the delimiters can both open and close emphasis, then the
+ # sum of the lengths of the delimiter runs containing the opening and
+ # closing delimiters must not be a multiple of 3 unless both lengths
+ # are multiples of 3.
+ #
+ if (
+ (opener.close or closer.open)
+ and ((opener.length + closer.length) % 3 == 0)
+ and (opener.length % 3 != 0 or closer.length % 3 != 0)
+ ):
+ isOddMatch = True
+
+ if not isOddMatch:
+ # If previous delimiter cannot be an opener, we can safely skip
+ # the entire sequence in future checks. This is required to make
+ # sure algorithm has linear complexity (see *_*_*_*_*_... case).
+ #
+ if openerIdx > 0 and not delimiters[openerIdx - 1].open:
+ lastJump = jumps[openerIdx - 1] + 1
+ else:
+ lastJump = 0
+
+ jumps[closerIdx] = closerIdx - openerIdx + lastJump
+ jumps[openerIdx] = lastJump
+
+ closer.open = False
+ opener.end = closerIdx
+ opener.close = False
+ newMinOpenerIdx = -1
+
+ # treat next token as start of run,
+ # it optimizes skips in **<...>**a**<...>** pathological case
+ lastTokenIdx = -2
+
+ break
+
+ openerIdx -= jumps[openerIdx] + 1
+
+ if newMinOpenerIdx != -1:
+ # If match for this delimiter run failed, we want to set lower bound for
+ # future lookups. This is required to make sure algorithm has linear
+ # complexity.
+ #
+ # See details here:
+ # https:#github.com/commonmark/cmark/issues/178#issuecomment-270417442
+ #
+ openersBottom[closer.marker][
+ (3 if closer.open else 0) + ((closer.length or 0) % 3)
+ ] = newMinOpenerIdx
+
+ closerIdx += 1
+
+
+def link_pairs(state: StateInline) -> None:
+ tokens_meta = state.tokens_meta
+ maximum = len(state.tokens_meta)
+
+ processDelimiters(state, state.delimiters)
+
+ curr = 0
+ while curr < maximum:
+ curr_meta = tokens_meta[curr]
+ if curr_meta and "delimiters" in curr_meta:
+ processDelimiters(state, curr_meta["delimiters"])
+ curr += 1
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/emphasis.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/emphasis.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a98f9e216c94db0217e986270aaaa72fcc99f7f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/emphasis.py
@@ -0,0 +1,102 @@
+# Process *this* and _that_
+#
+from __future__ import annotations
+
+from .state_inline import Delimiter, StateInline
+
+
+def tokenize(state: StateInline, silent: bool) -> bool:
+ """Insert each marker as a separate text token, and add it to delimiter list"""
+ start = state.pos
+ marker = state.src[start]
+
+ if silent:
+ return False
+
+ if marker not in ("_", "*"):
+ return False
+
+ scanned = state.scanDelims(state.pos, marker == "*")
+
+ for _ in range(scanned.length):
+ token = state.push("text", "", 0)
+ token.content = marker
+ state.delimiters.append(
+ Delimiter(
+ marker=ord(marker),
+ length=scanned.length,
+ token=len(state.tokens) - 1,
+ end=-1,
+ open=scanned.can_open,
+ close=scanned.can_close,
+ )
+ )
+
+ state.pos += scanned.length
+
+ return True
+
+
+def _postProcess(state: StateInline, delimiters: list[Delimiter]) -> None:
+ i = len(delimiters) - 1
+ while i >= 0:
+ startDelim = delimiters[i]
+
+ # /* _ */ /* * */
+ if startDelim.marker != 0x5F and startDelim.marker != 0x2A:
+ i -= 1
+ continue
+
+ # Process only opening markers
+ if startDelim.end == -1:
+ i -= 1
+ continue
+
+ endDelim = delimiters[startDelim.end]
+
+ # If the previous delimiter has the same marker and is adjacent to this one,
+ # merge those into one strong delimiter.
+ #
+ # `whatever` -> `whatever`
+ #
+ isStrong = (
+ i > 0
+ and delimiters[i - 1].end == startDelim.end + 1
+ # check that first two markers match and adjacent
+ and delimiters[i - 1].marker == startDelim.marker
+ and delimiters[i - 1].token == startDelim.token - 1
+ # check that last two markers are adjacent (we can safely assume they match)
+ and delimiters[startDelim.end + 1].token == endDelim.token + 1
+ )
+
+ ch = chr(startDelim.marker)
+
+ token = state.tokens[startDelim.token]
+ token.type = "strong_open" if isStrong else "em_open"
+ token.tag = "strong" if isStrong else "em"
+ token.nesting = 1
+ token.markup = ch + ch if isStrong else ch
+ token.content = ""
+
+ token = state.tokens[endDelim.token]
+ token.type = "strong_close" if isStrong else "em_close"
+ token.tag = "strong" if isStrong else "em"
+ token.nesting = -1
+ token.markup = ch + ch if isStrong else ch
+ token.content = ""
+
+ if isStrong:
+ state.tokens[delimiters[i - 1].token].content = ""
+ state.tokens[delimiters[startDelim.end + 1].token].content = ""
+ i -= 1
+
+ i -= 1
+
+
+def postProcess(state: StateInline) -> None:
+ """Walk through delimiter list and replace text tokens with tags."""
+ _postProcess(state, state.delimiters)
+
+ for token in state.tokens_meta:
+ if token and "delimiters" in token:
+ _postProcess(state, token["delimiters"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/entity.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/entity.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec9d39650e5bc533e694d3d6699677068d22c69f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/entity.py
@@ -0,0 +1,53 @@
+# Process html entity - {, ¯, ", ...
+import re
+
+from ..common.entities import entities
+from ..common.utils import fromCodePoint, isValidEntityCode
+from .state_inline import StateInline
+
+DIGITAL_RE = re.compile(r"^((?:x[a-f0-9]{1,6}|[0-9]{1,7}));", re.IGNORECASE)
+NAMED_RE = re.compile(r"^&([a-z][a-z0-9]{1,31});", re.IGNORECASE)
+
+
+def entity(state: StateInline, silent: bool) -> bool:
+ pos = state.pos
+ maximum = state.posMax
+
+ if state.src[pos] != "&":
+ return False
+
+ if pos + 1 >= maximum:
+ return False
+
+ if state.src[pos + 1] == "#":
+ if match := DIGITAL_RE.search(state.src[pos:]):
+ if not silent:
+ match1 = match.group(1)
+ code = (
+ int(match1[1:], 16) if match1[0].lower() == "x" else int(match1, 10)
+ )
+
+ token = state.push("text_special", "", 0)
+ token.content = (
+ fromCodePoint(code)
+ if isValidEntityCode(code)
+ else fromCodePoint(0xFFFD)
+ )
+ token.markup = match.group(0)
+ token.info = "entity"
+
+ state.pos += len(match.group(0))
+ return True
+
+ else:
+ if (match := NAMED_RE.search(state.src[pos:])) and match.group(1) in entities:
+ if not silent:
+ token = state.push("text_special", "", 0)
+ token.content = entities[match.group(1)]
+ token.markup = match.group(0)
+ token.info = "entity"
+
+ state.pos += len(match.group(0))
+ return True
+
+ return False
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/escape.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/escape.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fca6c84e035b83b21d5224be92fd4973f25b80b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/escape.py
@@ -0,0 +1,93 @@
+"""
+Process escaped chars and hardbreaks
+"""
+
+from ..common.utils import isStrSpace
+from .state_inline import StateInline
+
+
+def escape(state: StateInline, silent: bool) -> bool:
+ """Process escaped chars and hardbreaks."""
+ pos = state.pos
+ maximum = state.posMax
+
+ if state.src[pos] != "\\":
+ return False
+
+ pos += 1
+
+ # '\' at the end of the inline block
+ if pos >= maximum:
+ return False
+
+ ch1 = state.src[pos]
+ ch1_ord = ord(ch1)
+ if ch1 == "\n":
+ if not silent:
+ state.push("hardbreak", "br", 0)
+ pos += 1
+ # skip leading whitespaces from next line
+ while pos < maximum:
+ ch = state.src[pos]
+ if not isStrSpace(ch):
+ break
+ pos += 1
+
+ state.pos = pos
+ return True
+
+ escapedStr = state.src[pos]
+
+ if ch1_ord >= 0xD800 and ch1_ord <= 0xDBFF and pos + 1 < maximum:
+ ch2 = state.src[pos + 1]
+ ch2_ord = ord(ch2)
+ if ch2_ord >= 0xDC00 and ch2_ord <= 0xDFFF:
+ escapedStr += ch2
+ pos += 1
+
+ origStr = "\\" + escapedStr
+
+ if not silent:
+ token = state.push("text_special", "", 0)
+ token.content = escapedStr if ch1 in _ESCAPED else origStr
+ token.markup = origStr
+ token.info = "escape"
+
+ state.pos = pos + 1
+ return True
+
+
+_ESCAPED = {
+ "!",
+ '"',
+ "#",
+ "$",
+ "%",
+ "&",
+ "'",
+ "(",
+ ")",
+ "*",
+ "+",
+ ",",
+ "-",
+ ".",
+ "/",
+ ":",
+ ";",
+ "<",
+ "=",
+ ">",
+ "?",
+ "@",
+ "[",
+ "\\",
+ "]",
+ "^",
+ "_",
+ "`",
+ "{",
+ "|",
+ "}",
+ "~",
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/fragments_join.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/fragments_join.py
new file mode 100644
index 0000000000000000000000000000000000000000..5eb88a14025793d02188392244c1099042cf3727
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/fragments_join.py
@@ -0,0 +1,54 @@
+from .state_inline import StateInline
+
+
+def fragments_join(state: StateInline) -> None:
+ """
+ Clean up tokens after emphasis and strikethrough postprocessing:
+ merge adjacent text nodes into one and re-calculate all token levels
+
+ This is necessary because initially emphasis delimiter markers (``*, _, ~``)
+ are treated as their own separate text tokens. Then emphasis rule either
+ leaves them as text (needed to merge with adjacent text) or turns them
+ into opening/closing tags (which messes up levels inside).
+ """
+ level = 0
+ maximum = len(state.tokens)
+
+ curr = last = 0
+ while curr < maximum:
+ # re-calculate levels after emphasis/strikethrough turns some text nodes
+ # into opening/closing tags
+ if state.tokens[curr].nesting < 0:
+ level -= 1 # closing tag
+ state.tokens[curr].level = level
+ if state.tokens[curr].nesting > 0:
+ level += 1 # opening tag
+
+ if (
+ state.tokens[curr].type == "text"
+ and curr + 1 < maximum
+ and state.tokens[curr + 1].type == "text"
+ ):
+ # Collapse a run of adjacent text nodes in a single join, instead
+ # of pairwise `a + b` concatenation. The pairwise form is O(L*k)
+ # in the size of the run because each step rebuilds the growing
+ # prefix; "".join is O(L).
+ parts = [state.tokens[curr].content]
+ curr += 1
+ while curr < maximum and state.tokens[curr].type == "text":
+ parts.append(state.tokens[curr].content)
+ curr += 1
+ merged = state.tokens[curr - 1]
+ merged.content = "".join(parts)
+ merged.level = level
+ state.tokens[last] = merged
+ last += 1
+ continue
+
+ if curr != last:
+ state.tokens[last] = state.tokens[curr]
+ last += 1
+ curr += 1
+
+ if curr != last:
+ del state.tokens[last:]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/html_inline.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/html_inline.py
new file mode 100644
index 0000000000000000000000000000000000000000..9065e1d034da76270f7d3f1ba528132c8d57d341
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/html_inline.py
@@ -0,0 +1,43 @@
+# Process html tags
+from ..common.html_re import HTML_TAG_RE
+from ..common.utils import isLinkClose, isLinkOpen
+from .state_inline import StateInline
+
+
+def isLetter(ch: int) -> bool:
+ lc = ch | 0x20 # to lower case
+ # /* a */ and /* z */
+ return (lc >= 0x61) and (lc <= 0x7A)
+
+
+def html_inline(state: StateInline, silent: bool) -> bool:
+ pos = state.pos
+
+ if not state.md.options.get("html", None):
+ return False
+
+ # Check start
+ maximum = state.posMax
+ if state.src[pos] != "<" or pos + 2 >= maximum:
+ return False
+
+ # Quick fail on second char
+ ch = state.src[pos + 1]
+ if ch not in ("!", "?", "/") and not isLetter(ord(ch)): # /* / */
+ return False
+
+ match = HTML_TAG_RE.search(state.src[pos:])
+ if not match:
+ return False
+
+ if not silent:
+ token = state.push("html_inline", "", 0)
+ token.content = state.src[pos : pos + len(match.group(0))]
+
+ if isLinkOpen(token.content):
+ state.linkLevel += 1
+ if isLinkClose(token.content):
+ state.linkLevel -= 1
+
+ state.pos += len(match.group(0))
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/image.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/image.py
new file mode 100644
index 0000000000000000000000000000000000000000..005105b1c7ed1a93772c62af8bd5ef54d97dfebe
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/image.py
@@ -0,0 +1,148 @@
+# Process 
+from __future__ import annotations
+
+from ..common.utils import isStrSpace, normalizeReference
+from ..token import Token
+from .state_inline import StateInline
+
+
+def image(state: StateInline, silent: bool) -> bool:
+ label = None
+ href = ""
+ oldPos = state.pos
+ max = state.posMax
+
+ if state.src[state.pos] != "!":
+ return False
+
+ if state.pos + 1 < state.posMax and state.src[state.pos + 1] != "[":
+ return False
+
+ labelStart = state.pos + 2
+ labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, False)
+
+ # parser failed to find ']', so it's not a valid link
+ if labelEnd < 0:
+ return False
+
+ pos = labelEnd + 1
+
+ if pos < max and state.src[pos] == "(":
+ #
+ # Inline link
+ #
+
+ # [link]( "title" )
+ # ^^ skipping these spaces
+ pos += 1
+ while pos < max:
+ ch = state.src[pos]
+ if not isStrSpace(ch) and ch != "\n":
+ break
+ pos += 1
+
+ if pos >= max:
+ return False
+
+ # [link]( "title" )
+ # ^^^^^^ parsing link destination
+ start = pos
+ res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax)
+ if res.ok:
+ href = state.md.normalizeLink(res.str)
+ if state.md.validateLink(href):
+ pos = res.pos
+ else:
+ href = ""
+
+ # [link]( "title" )
+ # ^^ skipping these spaces
+ start = pos
+ while pos < max:
+ ch = state.src[pos]
+ if not isStrSpace(ch) and ch != "\n":
+ break
+ pos += 1
+
+ # [link]( "title" )
+ # ^^^^^^^ parsing link title
+ res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax, None)
+ if pos < max and start != pos and res.ok:
+ title = res.str
+ pos = res.pos
+
+ # [link]( "title" )
+ # ^^ skipping these spaces
+ while pos < max:
+ ch = state.src[pos]
+ if not isStrSpace(ch) and ch != "\n":
+ break
+ pos += 1
+ else:
+ title = ""
+
+ if pos >= max or state.src[pos] != ")":
+ state.pos = oldPos
+ return False
+
+ pos += 1
+
+ else:
+ #
+ # Link reference
+ #
+ if "references" not in state.env:
+ return False
+
+ # /* [ */
+ if pos < max and state.src[pos] == "[":
+ start = pos + 1
+ pos = state.md.helpers.parseLinkLabel(state, pos)
+ if pos >= 0:
+ label = state.src[start:pos]
+ pos += 1
+ else:
+ pos = labelEnd + 1
+ else:
+ pos = labelEnd + 1
+
+ # covers label == '' and label == undefined
+ # (collapsed reference link and shortcut reference link respectively)
+ if not label:
+ label = state.src[labelStart:labelEnd]
+
+ label = normalizeReference(label)
+
+ ref = state.env["references"].get(label, None)
+ if not ref:
+ state.pos = oldPos
+ return False
+
+ href = ref["href"]
+ title = ref["title"]
+
+ #
+ # We found the end of the link, and know for a fact it's a valid link
+ # so all that's left to do is to call tokenizer.
+ #
+ if not silent:
+ content = state.src[labelStart:labelEnd]
+
+ tokens: list[Token] = []
+ state.md.inline.parse(content, state.md, state.env, tokens)
+
+ token = state.push("image", "img", 0)
+ token.attrs = {"src": href, "alt": ""}
+ token.children = tokens or None
+ token.content = content
+
+ if title:
+ token.attrSet("title", title)
+
+ # note, this is not part of markdown-it JS, but is useful for renderers
+ if label and state.md.options.get("store_labels", False):
+ token.meta["label"] = label
+
+ state.pos = pos
+ state.posMax = max
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/link.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/link.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e92c7d83629f00283b5ed885637c8c4a851ffc7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/link.py
@@ -0,0 +1,149 @@
+# Process [link]( "stuff")
+
+from ..common.utils import isStrSpace, normalizeReference
+from .state_inline import StateInline
+
+
+def link(state: StateInline, silent: bool) -> bool:
+ href = ""
+ title = ""
+ label = None
+ oldPos = state.pos
+ maximum = state.posMax
+ start = state.pos
+ parseReference = True
+
+ if state.src[state.pos] != "[":
+ return False
+
+ labelStart = state.pos + 1
+ labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, True)
+
+ # parser failed to find ']', so it's not a valid link
+ if labelEnd < 0:
+ return False
+
+ pos = labelEnd + 1
+
+ if pos < maximum and state.src[pos] == "(":
+ #
+ # Inline link
+ #
+
+ # might have found a valid shortcut link, disable reference parsing
+ parseReference = False
+
+ # [link]( "title" )
+ # ^^ skipping these spaces
+ pos += 1
+ while pos < maximum:
+ ch = state.src[pos]
+ if not isStrSpace(ch) and ch != "\n":
+ break
+ pos += 1
+
+ if pos >= maximum:
+ return False
+
+ # [link]( "title" )
+ # ^^^^^^ parsing link destination
+ start = pos
+ res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax)
+ if res.ok:
+ href = state.md.normalizeLink(res.str)
+ if state.md.validateLink(href):
+ pos = res.pos
+ else:
+ href = ""
+
+ # [link]( "title" )
+ # ^^ skipping these spaces
+ start = pos
+ while pos < maximum:
+ ch = state.src[pos]
+ if not isStrSpace(ch) and ch != "\n":
+ break
+ pos += 1
+
+ # [link]( "title" )
+ # ^^^^^^^ parsing link title
+ res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax)
+ if pos < maximum and start != pos and res.ok:
+ title = res.str
+ pos = res.pos
+
+ # [link]( "title" )
+ # ^^ skipping these spaces
+ while pos < maximum:
+ ch = state.src[pos]
+ if not isStrSpace(ch) and ch != "\n":
+ break
+ pos += 1
+
+ if pos >= maximum or state.src[pos] != ")":
+ # parsing a valid shortcut link failed, fallback to reference
+ parseReference = True
+
+ pos += 1
+
+ if parseReference:
+ #
+ # Link reference
+ #
+ if "references" not in state.env:
+ return False
+
+ if pos < maximum and state.src[pos] == "[":
+ start = pos + 1
+ pos = state.md.helpers.parseLinkLabel(state, pos)
+ if pos >= 0:
+ label = state.src[start:pos]
+ pos += 1
+ else:
+ pos = labelEnd + 1
+
+ else:
+ pos = labelEnd + 1
+
+ # covers label == '' and label == undefined
+ # (collapsed reference link and shortcut reference link respectively)
+ if not label:
+ label = state.src[labelStart:labelEnd]
+
+ label = normalizeReference(label)
+
+ ref = state.env["references"].get(label, None)
+ if not ref:
+ state.pos = oldPos
+ return False
+
+ href = ref["href"]
+ title = ref["title"]
+
+ #
+ # We found the end of the link, and know for a fact it's a valid link
+ # so all that's left to do is to call tokenizer.
+ #
+ if not silent:
+ state.pos = labelStart
+ state.posMax = labelEnd
+
+ token = state.push("link_open", "a", 1)
+ token.attrs = {"href": href}
+
+ if title:
+ token.attrSet("title", title)
+
+ # note, this is not part of markdown-it JS, but is useful for renderers
+ if label and state.md.options.get("store_labels", False):
+ token.meta["label"] = label
+
+ state.linkLevel += 1
+ state.md.inline.tokenize(state)
+ state.linkLevel -= 1
+
+ token = state.push("link_close", "a", -1)
+
+ state.pos = pos
+ state.posMax = maximum
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/linkify.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/linkify.py
new file mode 100644
index 0000000000000000000000000000000000000000..3669396e3e7d51c125678f45a862139fe3b3fd9d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/linkify.py
@@ -0,0 +1,62 @@
+"""Process links like https://example.org/"""
+
+import re
+
+from .state_inline import StateInline
+
+# RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
+SCHEME_RE = re.compile(r"(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$", re.IGNORECASE)
+
+
+def linkify(state: StateInline, silent: bool) -> bool:
+ """Rule for identifying plain-text links."""
+ if not state.md.options.linkify:
+ return False
+ if state.linkLevel > 0:
+ return False
+ if not state.md.linkify:
+ raise ModuleNotFoundError("Linkify enabled but not installed.")
+
+ pos = state.pos
+ maximum = state.posMax
+
+ if (
+ (pos + 3) > maximum
+ or state.src[pos] != ":"
+ or state.src[pos + 1] != "/"
+ or state.src[pos + 2] != "/"
+ ):
+ return False
+
+ if not (match := SCHEME_RE.search(state.pending)):
+ return False
+
+ proto = match.group(1)
+ if not (link := state.md.linkify.match_at_start(state.src[pos - len(proto) :])):
+ return False
+ url: str = link.url
+
+ # disallow '*' at the end of the link (conflicts with emphasis)
+ url = url.rstrip("*")
+
+ full_url = state.md.normalizeLink(url)
+ if not state.md.validateLink(full_url):
+ return False
+
+ if not silent:
+ state.pending = state.pending[: -len(proto)]
+
+ token = state.push("link_open", "a", 1)
+ token.attrs = {"href": full_url}
+ token.markup = "linkify"
+ token.info = "auto"
+
+ token = state.push("text", "", 0)
+ token.content = state.md.normalizeLinkText(url)
+
+ token = state.push("link_close", "a", -1)
+ token.markup = "linkify"
+ token.info = "auto"
+
+ state.pos += len(url) - len(proto)
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/newline.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/newline.py
new file mode 100644
index 0000000000000000000000000000000000000000..d05ee6dac712a2211ab24f90dbea64a99e4d80b0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/newline.py
@@ -0,0 +1,44 @@
+"""Proceess '\n'."""
+
+from ..common.utils import charStrAt, isStrSpace
+from .state_inline import StateInline
+
+
+def newline(state: StateInline, silent: bool) -> bool:
+ pos = state.pos
+
+ if state.src[pos] != "\n":
+ return False
+
+ pmax = len(state.pending) - 1
+ maximum = state.posMax
+
+ # ' \n' -> hardbreak
+ # Lookup in pending chars is bad practice! Don't copy to other rules!
+ # Pending string is stored in concat mode, indexed lookups will cause
+ # conversion to flat mode.
+ if not silent:
+ if pmax >= 0 and charStrAt(state.pending, pmax) == " ":
+ if pmax >= 1 and charStrAt(state.pending, pmax - 1) == " ":
+ # Find whitespaces tail of pending chars.
+ ws = pmax - 1
+ while ws >= 1 and charStrAt(state.pending, ws - 1) == " ":
+ ws -= 1
+ state.pending = state.pending[:ws]
+
+ state.push("hardbreak", "br", 0)
+ else:
+ state.pending = state.pending[:-1]
+ state.push("softbreak", "br", 0)
+
+ else:
+ state.push("softbreak", "br", 0)
+
+ pos += 1
+
+ # skip heading spaces for next line
+ while pos < maximum and isStrSpace(state.src[pos]):
+ pos += 1
+
+ state.pos = pos
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/state_inline.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/state_inline.py
new file mode 100644
index 0000000000000000000000000000000000000000..de35287d427969eb9354dd13a74e5372c85cbfab
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/state_inline.py
@@ -0,0 +1,167 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Literal, NamedTuple
+
+from ..common.utils import isMdAsciiPunct, isPunctChar, isWhiteSpace
+from ..ruler import StateBase
+from ..token import Token
+from ..utils import EnvType
+
+if TYPE_CHECKING:
+ from markdown_it import MarkdownIt
+
+
+@dataclass(slots=True)
+class Delimiter:
+ # Char code of the starting marker (number).
+ marker: int
+
+ # Total length of these series of delimiters.
+ length: int
+
+ # A position of the token this delimiter corresponds to.
+ token: int
+
+ # If this delimiter is matched as a valid opener, `end` will be
+ # equal to its position, otherwise it's `-1`.
+ end: int
+
+ # Boolean flags that determine if this delimiter could open or close
+ # an emphasis.
+ open: bool
+ close: bool
+
+ level: bool | None = None
+
+
+class Scanned(NamedTuple):
+ can_open: bool
+ can_close: bool
+ length: int
+
+
+class StateInline(StateBase):
+ def __init__(
+ self, src: str, md: MarkdownIt, env: EnvType, outTokens: list[Token]
+ ) -> None:
+ self.src = src
+ self.env = env
+ self.md = md
+ self.tokens = outTokens
+ self.tokens_meta: list[dict[str, Any] | None] = [None] * len(outTokens)
+
+ self.pos = 0
+ self.posMax = len(self.src)
+ self.level = 0
+ self.pending = ""
+ self.pendingLevel = 0
+
+ # Stores { start: end } pairs. Useful for backtrack
+ # optimization of pairs parse (emphasis, strikes).
+ self.cache: dict[int, int] = {}
+
+ # List of emphasis-like delimiters for current tag
+ self.delimiters: list[Delimiter] = []
+
+ # Stack of delimiter lists for upper level tags
+ self._prev_delimiters: list[list[Delimiter]] = []
+
+ # backticklength => last seen position
+ self.backticks: dict[int, int] = {}
+ self.backticksScanned = False
+
+ # Counter used to disable inline linkify-it execution
+ # inside and markdown links
+ self.linkLevel = 0
+
+ def __repr__(self) -> str:
+ return (
+ f"{self.__class__.__name__}"
+ f"(pos=[{self.pos} of {self.posMax}], token={len(self.tokens)})"
+ )
+
+ def pushPending(self) -> Token:
+ token = Token("text", "", 0)
+ token.content = self.pending
+ token.level = self.pendingLevel
+ self.tokens.append(token)
+ self.pending = ""
+ return token
+
+ def push(self, ttype: str, tag: str, nesting: Literal[-1, 0, 1]) -> Token:
+ """Push new token to "stream".
+ If pending text exists - flush it as text token
+ """
+ if self.pending:
+ self.pushPending()
+
+ token = Token(ttype, tag, nesting)
+ token_meta = None
+
+ if nesting < 0:
+ # closing tag
+ self.level -= 1
+ self.delimiters = self._prev_delimiters.pop()
+
+ token.level = self.level
+
+ if nesting > 0:
+ # opening tag
+ self.level += 1
+ self._prev_delimiters.append(self.delimiters)
+ self.delimiters = []
+ token_meta = {"delimiters": self.delimiters}
+
+ self.pendingLevel = self.level
+ self.tokens.append(token)
+ self.tokens_meta.append(token_meta)
+ return token
+
+ def scanDelims(self, start: int, canSplitWord: bool) -> Scanned:
+ """
+ Scan a sequence of emphasis-like markers, and determine whether
+ it can start an emphasis sequence or end an emphasis sequence.
+
+ - start - position to scan from (it should point at a valid marker);
+ - canSplitWord - determine if these markers can be found inside a word
+
+ """
+ pos = start
+ maximum = self.posMax
+ marker = self.src[start]
+
+ # treat beginning of the line as a whitespace
+ lastChar = self.src[start - 1] if start > 0 else " "
+
+ while pos < maximum and self.src[pos] == marker:
+ pos += 1
+
+ count = pos - start
+
+ # treat end of the line as a whitespace
+ nextChar = self.src[pos] if pos < maximum else " "
+
+ isLastPunctChar = isMdAsciiPunct(ord(lastChar)) or isPunctChar(lastChar)
+ isNextPunctChar = isMdAsciiPunct(ord(nextChar)) or isPunctChar(nextChar)
+
+ isLastWhiteSpace = isWhiteSpace(ord(lastChar))
+ isNextWhiteSpace = isWhiteSpace(ord(nextChar))
+
+ left_flanking = not (
+ isNextWhiteSpace
+ or (isNextPunctChar and not (isLastWhiteSpace or isLastPunctChar))
+ )
+ right_flanking = not (
+ isLastWhiteSpace
+ or (isLastPunctChar and not (isNextWhiteSpace or isNextPunctChar))
+ )
+
+ can_open = left_flanking and (
+ canSplitWord or (not right_flanking) or isLastPunctChar
+ )
+ can_close = right_flanking and (
+ canSplitWord or (not left_flanking) or isNextPunctChar
+ )
+
+ return Scanned(can_open, can_close, count)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/strikethrough.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/strikethrough.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9875e043abbacd6ce627964be7d7c70028a8199
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/strikethrough.py
@@ -0,0 +1,173 @@
+# ~~strike through~~ (and optionally ~single tilde~)
+from __future__ import annotations
+
+from .state_inline import Delimiter, StateInline
+
+
+def tokenize(state: StateInline, silent: bool) -> bool:
+ """Insert each marker as a separate text token, and add it to delimiter list.
+
+ When the ``strikethrough_single_tilde`` option is enabled on the
+ ``MarkdownIt`` instance, single ``~`` delimiters are also accepted and
+ runs of three or more tildes are rejected (matching GitHub's rendering behaviour).
+ """
+ start = state.pos
+ ch = state.src[start]
+
+ if silent:
+ return False
+
+ if ch != "~":
+ return False
+
+ scanned = state.scanDelims(state.pos, True)
+ length = scanned.length
+
+ single_tilde = state.md.options.get("strikethrough_single_tilde", False)
+
+ if single_tilde:
+ # GitHub mode: only accept exactly 1 or 2 tildes.
+ if length < 1:
+ return False
+ if length > 2:
+ # Consume 3+ tildes as plain text so the parser doesn't
+ # re-enter and match a subset of them. This intentionally
+ # matches GitHub's rendering, where ≥3 tildes are literal text.
+ token = state.push("text", "", 0)
+ token.content = ch * length
+ state.pos += scanned.length
+ return True
+
+ token = state.push("text", "", 0)
+ token.content = ch * length
+ state.delimiters.append(
+ Delimiter(
+ marker=ord(ch),
+ length=0, # disable "rule of 3" length checks
+ token=len(state.tokens) - 1,
+ end=-1,
+ open=scanned.can_open,
+ close=scanned.can_close,
+ )
+ )
+ else:
+ # Original markdown-it behaviour: minimum 2, split odd runs.
+ if length < 2:
+ return False
+
+ if length % 2:
+ token = state.push("text", "", 0)
+ token.content = ch
+ length -= 1
+
+ i = 0
+ while i < length:
+ token = state.push("text", "", 0)
+ token.content = ch + ch
+ state.delimiters.append(
+ Delimiter(
+ marker=ord(ch),
+ length=0, # disable "rule of 3" length checks
+ token=len(state.tokens) - 1,
+ end=-1,
+ open=scanned.can_open,
+ close=scanned.can_close,
+ )
+ )
+
+ i += 2
+
+ state.pos += scanned.length
+
+ return True
+
+
+def _postProcess(state: StateInline, delimiters: list[Delimiter]) -> None:
+ loneMarkers = []
+ maximum = len(delimiters)
+ single_tilde = state.md.options.get("strikethrough_single_tilde", False)
+
+ i = 0
+ while i < maximum:
+ startDelim = delimiters[i]
+
+ if startDelim.marker != 0x7E: # /* ~ */
+ i += 1
+ continue
+
+ if startDelim.end == -1:
+ i += 1
+ continue
+
+ endDelim = delimiters[startDelim.end]
+
+ # In single-tilde mode, opener and closer must have the same width
+ # (both `~` or both `~~`). The width is stored in the text token.
+ if single_tilde:
+ opener_content = state.tokens[startDelim.token].content
+ closer_content = state.tokens[endDelim.token].content
+ if opener_content != closer_content:
+ i += 1
+ continue
+
+ markup = state.tokens[startDelim.token].content
+
+ token = state.tokens[startDelim.token]
+ token.type = "s_open"
+ token.tag = "s"
+ token.nesting = 1
+ token.markup = markup
+ token.content = ""
+
+ token = state.tokens[endDelim.token]
+ token.type = "s_close"
+ token.tag = "s"
+ token.nesting = -1
+ token.markup = markup
+ token.content = ""
+
+ if (
+ state.tokens[endDelim.token - 1].type == "text"
+ and state.tokens[endDelim.token - 1].content == "~"
+ ):
+ loneMarkers.append(endDelim.token - 1)
+
+ i += 1
+
+ # If a marker sequence has an odd number of characters, it's split
+ # like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the
+ # start of the sequence.
+ #
+ # So, we have to move all those markers after subsequent s_close tags.
+ #
+ while loneMarkers:
+ i = loneMarkers.pop()
+ j = i + 1
+
+ while (j < len(state.tokens)) and (state.tokens[j].type == "s_close"):
+ j += 1
+
+ j -= 1
+
+ if i != j:
+ token = state.tokens[j]
+ state.tokens[j] = state.tokens[i]
+ state.tokens[i] = token
+
+
+def postProcess(state: StateInline) -> None:
+ """Walk through delimiter list and replace text tokens with tags."""
+ tokens_meta = state.tokens_meta
+ maximum = len(state.tokens_meta)
+ _postProcess(state, state.delimiters)
+
+ curr = 0
+ while curr < maximum:
+ try:
+ curr_meta = tokens_meta[curr]
+ except IndexError:
+ pass
+ else:
+ if curr_meta and "delimiters" in curr_meta:
+ _postProcess(state, curr_meta["delimiters"])
+ curr += 1
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/text.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/text.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef0cc9cec55e253a8eb17b37d593b1c320374cf5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it/rules_inline/text.py
@@ -0,0 +1,23 @@
+# Skip text characters for text token, place those to pending buffer
+# and increment current pos
+from .state_inline import StateInline
+
+# Rule to skip pure text
+
+
+def text(state: StateInline, silent: bool) -> bool:
+ pos = state.pos
+ posMax = state.posMax
+
+ terminator_char = state.md.inline.terminator_re.search(state.src, pos)
+ pos = terminator_char.start() if terminator_char else posMax
+
+ if pos == state.pos:
+ return False
+
+ if not silent:
+ state.pending += state.src[state.pos : pos]
+
+ state.pos = pos
+
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it_py-4.2.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it_py-4.2.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..582ddf59e08277fe6e78cee924d2c84805fe36fe
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it_py-4.2.0.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2020 ExecutableBookProject
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it_py-4.2.0.dist-info/licenses/LICENSE.markdown-it b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it_py-4.2.0.dist-info/licenses/LICENSE.markdown-it
new file mode 100644
index 0000000000000000000000000000000000000000..7ffa058cb78f8fb9beb974d9fd429004d2d2e585
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markdown_it_py-4.2.0.dist-info/licenses/LICENSE.markdown-it
@@ -0,0 +1,22 @@
+Copyright (c) 2014 Vitaly Puzrin, Alex Kocharin.
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markupsafe-3.0.3.dist-info/licenses/LICENSE.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/markupsafe-3.0.3.dist-info/licenses/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c4700f975c9f76ccf9dec953157a92c549f450cc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/markupsafe-3.0.3.dist-info/licenses/LICENSE.txt
@@ -0,0 +1,28 @@
+Copyright 2010 Pallets
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markupsafe/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markupsafe/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db16106c7039b7ed2bb18929bc13e7167c34ada7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markupsafe/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/markupsafe/__pycache__/_native.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/markupsafe/__pycache__/_native.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8121d412a89d5bac926eaf494a601f6703a3d812
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/markupsafe/__pycache__/_native.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow-3.26.2.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow-3.26.2.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow-3.26.2.dist-info/licenses/LICENSE
@@ -0,0 +1,19 @@
+Copyright Steven Loria and contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61aab35287a1c08bd59573ef5a3e0927c94cec4c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2d5b7bc5d8a67e0d62a024f1c0a98783683f022
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/class_registry.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/class_registry.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d4d1f420dc6533431225dca979bdc9c7c9019f73
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/class_registry.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/decorators.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/decorators.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0c411db48e1bdd45c84a7d2be3b78c3908a6ce0
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/decorators.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/error_store.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/error_store.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3477971498f615720e4dd8234661d637f83faf9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/error_store.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/exceptions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a820c037841fbb6215afe4b3d898c90f8f5a850d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/exceptions.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/fields.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/fields.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf11430a616ee167cecb2dade44d87e18cb94ea6
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/fields.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/orderedset.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/orderedset.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85e2798b1980c20268bbefbc25e99e1c0d2a24a3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/orderedset.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/schema.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/schema.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9dcd262e1eb3c98351cd9e200b9074ad17225a4a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/schema.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/types.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b164bb3f67f7a3926f3dd50deebe6d4ada2c4687
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/types.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1bafec2ad88170891345f8ae11672f20fc8c72f7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/validate.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/validate.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..690bcd1c45f7a3b47d230ea0f7e137bdb0009162
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/validate.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/warnings.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/warnings.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f2bccea19c76528366ffa685954398ef19029fc
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/marshmallow/__pycache__/warnings.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93e4c61f79f3a3f66937ebe16ce13bc2a857838a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_decode.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_decode.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..07e4ccd02bf438a18479edae00819724d1e6401e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_decode.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_encode.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_encode.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5cf21f84ba53d2576799f4d23b625cfa9c5d6705
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_encode.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_format.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_format.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d475af4f8a1b01c69291bf48b98416740e90aa9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_format.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_parse.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_parse.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9a217ffb99f8e7601d856c57f2b6cbbdd1daec1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_parse.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_url.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_url.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4924cfaa6296bcd648022a68c3ff2fedbc97d4d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mdurl/__pycache__/_url.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mmh3-5.2.1.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/mmh3-5.2.1.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..11d319d65fa53ed5528690645a7dc2e84f0d5923
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/mmh3-5.2.1.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2011-2026 Hajime Senuma
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d67af354ec28ababe9a0e14561e9da73f435a2b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/approximation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/approximation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15f8201d8a7ed634f000367500d5d1107b1bc7d0
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/approximation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/calculus.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/calculus.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9635ed2d23d8ca7c4a5d42c7ddc9368af628fcc4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/calculus.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/differentiation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/differentiation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36f4f03d468242f64be7857eae1fd3603d5f4f99
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/differentiation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/extrapolation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/extrapolation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3251293044b06c533bb092df1df898bd659cc88d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/extrapolation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/inverselaplace.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/inverselaplace.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4317d05c3f3e3fa62440c6952c5a307da0d70082
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/inverselaplace.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/odes.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/odes.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e45e801fa1ae0f8d0641d1a1f456a6fdcac65b41
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/odes.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/optimization.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/optimization.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8dca7c462b67d0de19b762a2126f06a28451bf14
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/optimization.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/polynomials.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/polynomials.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..957cf5f621872fb615ecd0bca09ed2d20e219549
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/polynomials.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/quadrature.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/quadrature.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35a95c636992607dc979b470672e4ad8757e9373
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/calculus/__pycache__/quadrature.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..353ad6f988097f953a6505e98a7328757c9d1c0a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/bessel.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/bessel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af0dd0afaf69af74830fc01d23eab84fa76e745a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/bessel.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/elliptic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/elliptic.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6ca4979166690dd7159b4aad1f8e643f9fe369a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/elliptic.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/expintegrals.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/expintegrals.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67b7b94f6f0b688f22607418e35ccbb9fdcc06a8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/expintegrals.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/factorials.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/factorials.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d348d2a5ca0c074054e0eca49d393e588621421
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/factorials.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/functions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/functions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b8a2bc1c25b4b2c9281ba8b3d233f44f9686fddc
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/functions.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/hypergeometric.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/hypergeometric.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d5da66f9908d24cde607f4b755fbd7cfd917c88
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/hypergeometric.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/orthogonal.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/orthogonal.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f877a0960d1b32b0dbbc8b44fc24d416a9fc929
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/orthogonal.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/qfunctions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/qfunctions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2191a2cc01a19ce3c0d1d6b783dbfc121b4f184
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/qfunctions.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/rszeta.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/rszeta.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1dcda4620e9c4b3e68a04b44adaed70e7ab46d71
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/rszeta.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/signals.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/signals.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01ea690a4d85cfb162b832a96b867e86ebf72881
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/signals.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/theta.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/theta.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bfdb5128cbd0377e906da0086b713edb2dd69053
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/theta.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/zeta.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/zeta.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c11e9b81a2273fe6ac001ea75dbbca009679df5
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/zeta.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/zetazeros.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/zetazeros.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3751e798fbff35fcc5159ec98a1f6b987039cd2f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/functions/__pycache__/zetazeros.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30142c597863a70c50dde39ba56f5906a23a7b8b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/backend.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/backend.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..986b2e19b98ebb48ca14c053c69e4333ccefd732
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/backend.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/gammazeta.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/gammazeta.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb75d7311ec1afe15de62a06acfc2448d76ed3e5
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/gammazeta.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libelefun.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libelefun.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..349f6b5a63903cb71cc5f4d66939380a61ef9e9c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libelefun.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libhyper.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libhyper.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c7639b22bf90334f2cb4ec12b9629601883b392
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libhyper.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libintmath.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libintmath.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c80604f77213fa89d6567b46bcdbc2058d16019
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libintmath.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libmpc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libmpc.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..82389d5930490f7cb344a7c33e9b6476709beba7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libmpc.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libmpf.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libmpf.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25e5e0ab3e7c87ad5045fbf9bd30cb46b107a577
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libmpf.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libmpi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libmpi.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7493d708f10c2df4526eec2280b5d77b52e2525d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/libmp/__pycache__/libmpi.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/matrices/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/matrices/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d18fb8c4b40f18e481bdf38c14c996eab8b51d23
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/matrices/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/matrices/__pycache__/eigen_symmetric.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/matrices/__pycache__/eigen_symmetric.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3c8840e4245b1a12e3b4818c03cb291328df61b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/matrices/__pycache__/eigen_symmetric.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/matrices/__pycache__/linalg.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/matrices/__pycache__/linalg.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d87f3e4ab79fbc7ba6ede9dd6e9b3172faaaf25b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/matrices/__pycache__/linalg.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/matrices/__pycache__/matrices.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/matrices/__pycache__/matrices.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35c2643aba923fcecc1b8f17aad90d114deffe72
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/mpmath/matrices/__pycache__/matrices.cpython-311.pyc differ