Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Core refac #13627

Merged
merged 15 commits into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
3 changes: 3 additions & 0 deletions libs/core/langchain_core/_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@
surface_langchain_deprecation_warnings,
warn_deprecated,
)
from .path import as_import_path, get_relative_path
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any reason for the relative instead of absolute?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

was copying above, guessing linter complains about importing from private module?


__all__ = [
"as_import_path",
"deprecated",
"get_relative_path",
"LangChainDeprecationWarning",
"suppress_langchain_deprecation_warning",
"surface_langchain_deprecation_warnings",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Any, Literal, Sequence, Union

from langchain_core.load.serializable import Serializable
from langchain_core.schema.messages import BaseMessage
from langchain_core.messages import BaseMessage


class AgentAction(Serializable):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from abc import ABC, abstractmethod
from typing import Any, Optional, Sequence

from langchain_core.schema.output import Generation
from langchain_core.outputs import Generation

RETURN_VAL_TYPE = Sequence[Generation]

Expand Down
69 changes: 69 additions & 0 deletions libs/core/langchain_core/callbacks/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
from langchain_core.callbacks.base import (
AsyncCallbackHandler,
BaseCallbackHandler,
BaseCallbackManager,
CallbackManagerMixin,
Callbacks,
ChainManagerMixin,
LLMManagerMixin,
RetrieverManagerMixin,
RunManagerMixin,
ToolManagerMixin,
)
from langchain_core.callbacks.manager import (
AsyncCallbackManager,
AsyncCallbackManagerForChainGroup,
AsyncCallbackManagerForChainRun,
AsyncCallbackManagerForLLMRun,
AsyncCallbackManagerForRetrieverRun,
AsyncCallbackManagerForToolRun,
AsyncParentRunManager,
AsyncRunManager,
BaseRunManager,
CallbackManager,
CallbackManagerForChainGroup,
CallbackManagerForChainRun,
CallbackManagerForLLMRun,
CallbackManagerForRetrieverRun,
CallbackManagerForToolRun,
ParentRunManager,
RunManager,
env_var_is_set,
register_configure_hook,
)
from langchain_core.callbacks.stdout import StdOutCallbackHandler
from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler

__all__ = [
"RetrieverManagerMixin",
"LLMManagerMixin",
"ChainManagerMixin",
"ToolManagerMixin",
"Callbacks",
"CallbackManagerMixin",
"RunManagerMixin",
"BaseCallbackHandler",
"AsyncCallbackHandler",
"BaseCallbackManager",
"BaseRunManager",
"RunManager",
"ParentRunManager",
"AsyncRunManager",
"AsyncParentRunManager",
"CallbackManagerForLLMRun",
"AsyncCallbackManagerForLLMRun",
"CallbackManagerForChainRun",
"AsyncCallbackManagerForChainRun",
"CallbackManagerForToolRun",
"AsyncCallbackManagerForToolRun",
"CallbackManagerForRetrieverRun",
"AsyncCallbackManagerForRetrieverRun",
"CallbackManager",
"CallbackManagerForChainGroup",
"AsyncCallbackManager",
"AsyncCallbackManagerForChainGroup",
"StdOutCallbackHandler",
"StreamingStdOutCallbackHandler",
"env_var_is_set",
"register_configure_hook",
]
8 changes: 4 additions & 4 deletions libs/core/langchain_core/callbacks/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@

from tenacity import RetryCallState

from langchain_core.schema.agent import AgentAction, AgentFinish
from langchain_core.schema.document import Document
from langchain_core.schema.messages import BaseMessage
from langchain_core.schema.output import ChatGenerationChunk, GenerationChunk, LLMResult
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


class RetrieverManagerMixin:
Expand Down
27 changes: 12 additions & 15 deletions libs/core/langchain_core/callbacks/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@
from langsmith.run_helpers import get_run_tree_context
from tenacity import RetryCallState

from langchain_core.agents import (
AgentAction,
AgentFinish,
)
from langchain_core.callbacks.base import (
BaseCallbackHandler,
BaseCallbackManager,
Expand All @@ -41,23 +45,16 @@
ToolManagerMixin,
)
from langchain_core.callbacks.stdout import StdOutCallbackHandler
from langchain_core.callbacks.tracers import run_collector
from langchain_core.callbacks.tracers.langchain import (
from langchain_core.documents import Document
from langchain_core.messages import BaseMessage, get_buffer_string
from langchain_core.outputs import ChatGenerationChunk, GenerationChunk, LLMResult
from langchain_core.tracers import run_collector
from langchain_core.tracers.langchain import (
LangChainTracer,
)
from langchain_core.callbacks.tracers.langchain_v1 import (
LangChainTracerV1,
TracerSessionV1,
)
from langchain_core.callbacks.tracers.stdout import ConsoleCallbackHandler
from langchain_core.schema import (
AgentAction,
AgentFinish,
Document,
LLMResult,
)
from langchain_core.schema.messages import BaseMessage, get_buffer_string
from langchain_core.schema.output import ChatGenerationChunk, GenerationChunk
from langchain_core.tracers.langchain_v1 import LangChainTracerV1
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

leave some of the old tracer stuff in langchain?

from langchain_core.tracers.schemas import TracerSessionV1
from langchain_core.tracers.stdout import ConsoleCallbackHandler

if TYPE_CHECKING:
from langsmith import Client as LangSmithClient
Expand Down
5 changes: 3 additions & 2 deletions libs/core/langchain_core/callbacks/stdout.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"""Callback Handler that prints to std out."""
from typing import Any, Dict, List, Optional

from langchain_core.agents import AgentAction, AgentFinish
from langchain_core.callbacks.base import BaseCallbackHandler
from langchain_core.schema import AgentAction, AgentFinish, LLMResult
from langchain_core.utils.input import print_text
from langchain_core.outputs import LLMResult
from langchain_core.utils import print_text


class StdOutCallbackHandler(BaseCallbackHandler):
Expand Down
5 changes: 3 additions & 2 deletions libs/core/langchain_core/callbacks/streaming_stdout.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
import sys
from typing import Any, Dict, List

from langchain_core.agents import AgentAction, AgentFinish
from langchain_core.callbacks.base import BaseCallbackHandler
from langchain_core.schema import AgentAction, AgentFinish, LLMResult
from langchain_core.schema.messages import BaseMessage
from langchain_core.messages import BaseMessage
from langchain_core.outputs import LLMResult


class StreamingStdOutCallbackHandler(BaseCallbackHandler):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from abc import ABC, abstractmethod
from typing import List

from langchain_core.schema.messages import AIMessage, BaseMessage, HumanMessage
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage


class BaseChatMessageHistory(ABC):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Sequence, TypedDict

from langchain_core.schema import BaseMessage
from langchain_core.messages import BaseMessage


class ChatSession(TypedDict, total=False):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,9 @@
import asyncio
from abc import ABC, abstractmethod
from functools import partial
from typing import Any, Literal, Sequence
from typing import Any, Sequence

from langchain_core.load.serializable import Serializable
from langchain_core.pydantic_v1 import Field


class Document(Serializable):
"""Class for storing a piece of text and associated metadata."""

page_content: str
"""String text."""
metadata: dict = Field(default_factory=dict)
"""Arbitrary metadata about the page content (e.g., source, relationships to other
documents, etc.).
"""
type: Literal["Document"] = "Document"

@classmethod
def is_lc_serializable(cls) -> bool:
"""Return whether this class is serializable."""
return True
from langchain_core.documents import Document


class BaseDocumentTransformer(ABC):
Expand Down
23 changes: 23 additions & 0 deletions libs/core/langchain_core/documents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from __future__ import annotations

from typing import Literal

from langchain_core.load.serializable import Serializable
from langchain_core.pydantic_v1 import Field


class Document(Serializable):
"""Class for storing a piece of text and associated metadata."""

page_content: str
"""String text."""
metadata: dict = Field(default_factory=dict)
"""Arbitrary metadata about the page content (e.g., source, relationships to other
documents, etc.).
"""
type: Literal["Document"] = "Document"

@classmethod
def is_lc_serializable(cls) -> bool:
"""Return whether this class is serializable."""
return True
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
"""Logic for selecting examples to include in prompts."""
from langchain_core.prompts.example_selector.length_based import (
from langchain_core.example_selectors.base import BaseExampleSelector
from langchain_core.example_selectors.length_based import (
LengthBasedExampleSelector,
)
from langchain_core.prompts.example_selector.semantic_similarity import (
from langchain_core.example_selectors.semantic_similarity import (
MaxMarginalRelevanceExampleSelector,
SemanticSimilarityExampleSelector,
sorted_values,
)

__all__ = [
"BaseExampleSelector",
"LengthBasedExampleSelector",
"MaxMarginalRelevanceExampleSelector",
"SemanticSimilarityExampleSelector",
"sorted_values",
]
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import re
from typing import Callable, Dict, List

from langchain_core.prompts.example_selector.base import BaseExampleSelector
from langchain_core.example_selectors.base import BaseExampleSelector
from langchain_core.prompts.prompt import PromptTemplate
from langchain_core.pydantic_v1 import BaseModel, validator

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@

from typing import Any, Dict, List, Optional, Type

from langchain_core.prompts.example_selector.base import BaseExampleSelector
from langchain_core.embeddings import Embeddings
from langchain_core.example_selectors.base import BaseExampleSelector
from langchain_core.pydantic_v1 import BaseModel, Extra
from langchain_core.schema.embeddings import Embeddings
from langchain_core.schema.vectorstore import VectorStore
from langchain_core.vectorstores import VectorStore


def sorted_values(values: Dict[str, str]) -> List[Any]:
Expand Down
48 changes: 48 additions & 0 deletions libs/core/langchain_core/exceptions.py
efriis marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from typing import Any, Optional


class LangChainException(Exception):
"""General LangChain exception."""


class TracerException(LangChainException):
"""Base class for exceptions in tracers module."""


class OutputParserException(ValueError, LangChainException):
"""Exception that output parsers should raise to signify a parsing error.

This exists to differentiate parsing errors from other code or execution errors
that also may arise inside the output parser. OutputParserExceptions will be
available to catch and handle in ways to fix the parsing error, while other
errors will be raised.

Args:
error: The error that's being re-raised or an error message.
observation: String explanation of error which can be passed to a
model to try and remediate the issue.
llm_output: String model output which is error-ing.
send_to_llm: Whether to send the observation and llm_output back to an Agent
after an OutputParserException has been raised. This gives the underlying
model driving the agent the context that the previous output was improperly
structured, in the hopes that it will update the output to the correct
format.
"""

def __init__(
self,
error: Any,
observation: Optional[str] = None,
llm_output: Optional[str] = None,
send_to_llm: bool = False,
):
super(OutputParserException, self).__init__(error)
if send_to_llm:
if observation is None or llm_output is None:
raise ValueError(
"Arguments 'observation' & 'llm_output'"
" are required if 'send_to_llm' is True"
)
self.observation = observation
self.llm_output = llm_output
self.send_to_llm = send_to_llm
2 changes: 1 addition & 1 deletion libs/core/langchain_core/globals/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from typing import TYPE_CHECKING, Optional

if TYPE_CHECKING:
from langchain_core.schema import BaseCache
from langchain_core.caches import BaseCache


# DO NOT USE THESE VALUES DIRECTLY!
Expand Down
12 changes: 12 additions & 0 deletions libs/core/langchain_core/language_models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from langchain_core.language_models.base import BaseLanguageModel, LanguageModelInput
from langchain_core.language_models.chat_models import BaseChatModel, SimpleChatModel
from langchain_core.language_models.llms import LLM, BaseLLM

__all__ = [
"BaseLanguageModel",
"BaseChatModel",
"SimpleChatModel",
"BaseLLM",
"LLM",
"LanguageModelInput",
]
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@

from typing_extensions import TypeAlias

from langchain_core.messages import AnyMessage, BaseMessage, get_buffer_string
from langchain_core.outputs import LLMResult
from langchain_core.prompts import PromptValue
from langchain_core.runnables import RunnableSerializable
from langchain_core.schema.messages import AnyMessage, BaseMessage, get_buffer_string
from langchain_core.schema.output import LLMResult
from langchain_core.schema.prompt import PromptValue
from langchain_core.utils import get_pydantic_field_names

if TYPE_CHECKING:
from langchain_core.callbacks.manager import Callbacks
from langchain_core.callbacks import Callbacks


@lru_cache(maxsize=None) # Cache the tokenizer
Expand Down Expand Up @@ -74,8 +74,8 @@ class BaseLanguageModel(
@property
def InputType(self) -> TypeAlias:
"""Get the input type for this runnable."""
from langchain_core.prompts.base import StringPromptValue
from langchain_core.prompts.chat import ChatPromptValueConcrete
from langchain_core.prompts.str import StringPromptValue
baskaryan marked this conversation as resolved.
Show resolved Hide resolved

# This is a version of LanguageModelInput which replaces the abstract
# base class BaseMessage with a union of its subclasses, which makes
Expand Down
Loading
Loading