Tony20100/langchain_full huggingface dataset:
langchain_community.adapters.openai.ChatCompletionChunk¶
class langchain_community.adapters.openai.ChatCompletionChunk[source]¶
Bases: IndexableBaseModel
Chat completion chunk.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param choices: List[ChoiceChunk] [Required]¶
classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) – 
values (Any) – 
Return type
Model
copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep (bool) – set to True to make a deep copy of the model
self (Model) – 
Returns
new model instance
Return type
Model
langchain_community.adapters.openai.convert_openai_messages¶
langchain_community.adapters.openai.convert_openai_messages(messages: Sequence[Dict[str, Any]]) → List[BaseMessage][source]¶
Convert dictionaries representing OpenAI messages to LangChain format.
Parameters
messages (Sequence[Dict[str, Any]]) – List of dictionaries representing OpenAI messages
Returns
List of LangChain BaseMessage objects.
Return type
List[BaseMessage]
langchain_community.adapters.openai.convert_messages_for_finetuning¶
langchain_community.adapters.openai.convert_messages_for_finetuning(sessions: Iterable[ChatSession]) → List[List[dict]][source]¶
Convert messages to a list of lists of dictionaries for fine-tuning.
Parameters
sessions (Iterable[ChatSession]) – The chat sessions.
Returns
The list of lists of dictionaries.
Return type
List[List[dict]]
Examples using convert_messages_for_finetuning¶
Facebook Messenger
LangSmith Chat Datasets
LangSmith LLM Runs
iMessage
langchain_community.adapters.openai.Choice¶
class langchain_community.adapters.openai.Choice[source]¶
Bases: IndexableBaseModel
Choice.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param message: dict [Required]¶
classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) – 
values (Any) – 
Return type
Model
copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep (bool) – set to True to make a deep copy of the model
self (Model) – 
Returns
new model instance
Return type
Model
langchain_community.adapters.openai.Completions¶
class langchain_community.adapters.openai.Completions[source]¶
Completions.
Methods
__init__()
acreate()
create()
__init__()¶
async static acreate(messages: Sequence[Dict[str, Any]], *, provider: str = 'ChatOpenAI', stream: Literal[False] = False, **kwargs: Any) → ChatCompletions[source]¶
async static acreate(messages: Sequence[Dict[str, Any]], *, provider: str = 'ChatOpenAI', stream: Literal[True], **kwargs: Any) → AsyncIterator
static create(messages: Sequence[Dict[str, Any]], *, provider: str = 'ChatOpenAI', stream: Literal[False] = False, **kwargs: Any) → ChatCompletions[source]¶
static create(messages: Sequence[Dict[str, Any]], *, provider: str = 'ChatOpenAI', stream: Literal[True], **kwargs: Any) → Iterable
langchain_community.adapters.openai.IndexableBaseModel¶
class langchain_community.adapters.openai.IndexableBaseModel[source]¶
Bases: BaseModel
Allows a BaseModel to return its fields by string variable indexing.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) – 
values (Any) – 
Return type
Model
copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep (bool) – set to True to make a deep copy of the model
self (Model) – 
Returns
new model instance
Return type
Model
langchain_community.adapters.openai.ChatCompletion¶
class langchain_community.adapters.openai.ChatCompletion[source]¶
Chat completion.
Methods
__init__()
acreate()
create()
__init__()¶
async static acreate(messages: Sequence[Dict[str, Any]], *, provider: str = 'ChatOpenAI', stream: Literal[False] = False, **kwargs: Any) → dict[source]¶
async static acreate(messages: Sequence[Dict[str, Any]], *, provider: str = 'ChatOpenAI', stream: Literal[True], **kwargs: Any) → AsyncIterator
static create(messages: Sequence[Dict[str, Any]], *, provider: str = 'ChatOpenAI', stream: Literal[False] = False, **kwargs: Any) → dict[source]¶
static create(messages: Sequence[Dict[str, Any]], *, provider: str = 'ChatOpenAI', stream: Literal[True], **kwargs: Any) → Iterable
langchain_community.adapters.openai.convert_dict_to_message¶
langchain_community.adapters.openai.convert_dict_to_message(_dict: Mapping[str, Any]) → BaseMessage[source]¶
Convert a dictionary to a LangChain message.
Parameters
_dict (Mapping[str, Any]) – The dictionary.
Returns
The LangChain message.
Return type
BaseMessage
langchain_community.adapters.openai.ChoiceChunk¶
class langchain_community.adapters.openai.ChoiceChunk[source]¶
Bases: IndexableBaseModel
Choice chunk.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param delta: dict [Required]¶
classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) – 
values (Any) – 
Return type
Model
copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep (bool) – set to True to make a deep copy of the model
self (Model) – 
Returns
new model instance
Return type
Model
langchain_community.adapters.openai.convert_message_to_dict¶
langchain_community.adapters.openai.convert_message_to_dict(message: BaseMessage) → dict[source]¶
Convert a LangChain message to a dictionary.
Parameters
message (BaseMessage) – The LangChain message.
Returns
The dictionary.
Return type
dict
Examples using convert_message_to_dict¶
Twitter (via Apify)
langchain_google_community.vertex_check_grounding.VertexAICheckGroundingWrapper¶
class langchain_google_community.vertex_check_grounding.VertexAICheckGroundingWrapper[source]¶
Bases: RunnableSerializable[str, VertexAICheckGroundingWrapper.CheckGroundingResponse]
Initializes the Vertex AI CheckGroundingOutputParser with configurable parameters.
Calls the Check Grounding API to validate the response against a given set of
documents and returns back citations that support the claims along with the cited
chunks. Output is of the type CheckGroundingResponse.
project_id¶
Google Cloud project ID
Type
str
location_id¶
Location ID for the ranking service.
Type
str
grounding_config¶
Required. The resource name of the grounding config, such as
default_grounding_config.
It is set to default_grounding_config by default if unspecified
Type
str
citation_threshold¶
The threshold (in [0,1]) used for determining whether a fact
must be cited for a claim in the answer candidate. Choosing
a higher threshold will lead to fewer but very strong
citations, while choosing a lower threshold may lead to more
but somewhat weaker citations. If unset, the threshold will
default to 0.6.
Type
float
credentials¶
Google Cloud credentials object.
Type
Optional[Credentials]
credentials_path¶
Path to the Google Cloud service
Type
Optional[str]
account credentials file.
Constructor for CheckGroundingOutputParser.
Initializes the grounding check service client with necessary credentials
and configurations.
param citation_threshold: Optional[float] = 0.6¶
param client: Any = None¶
param credentials: Optional[Credentials] = None¶
param credentials_path: Optional[str] = None¶
param grounding_config: str = 'default_grounding_config'¶
param location_id: str = 'global'¶
param location_id: str = 'global'¶
param project_id: str = None¶
class CheckGroundingResponse[source]¶
Bases: BaseModel
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param answer_with_citations: str = ''¶
param cited_chunks: List[Dict[str, Any]] = []¶
param claims: List[Dict[str, Any]] = []¶
param support_score: float = 0.0¶
classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
Parameters
_fields_set (Optional[SetStr]) – 
values (Any) – 
Return type
Model
copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
update (Optional[DictStrAny]) – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
Parameters
by_alias (bool) – 
ref_template (unicode) – 
Return type
DictStrAny
classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶
Parameters
by_alias (bool) – 
ref_template (unicode) – 
dumps_kwargs (Any) – 
Return type
unicode
classmethod update_forward_refs(**localns: Any) → None¶
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) – 
Return type
None
classmethod validate(value: Any) → Model¶
Parameters
value (Any) – 
Return type
Model
async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶
Default implementation runs ainvoke in parallel using asyncio.gather.
The default implementation of batch works well for IO bound runnables.
Subclasses should override this method if they can batch more efficiently;
e.g., if the underlying runnable uses an API which supports a batch mode.
Parameters
inputs (List[Input]) – 
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
List[Output]
async abatch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → AsyncIterator[Tuple[int, Union[Output, Exception]]]¶
Run ainvoke in parallel on a list of inputs,
Run ainvoke in parallel on a list of inputs,
yielding results as they complete.
Parameters
inputs (Sequence[Input]) – 
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
AsyncIterator[Tuple[int, Union[Output, Exception]]]
async ainvoke(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) → Output¶
Default implementation of ainvoke, calls invoke from a thread.
The default implementation allows usage of async code even if
the runnable did not implement a native async version of invoke.
Subclasses should override this method if they can run asynchronously.
Parameters
input (Input) – 
config (Optional[RunnableConfig]) – 
kwargs (Any) – 
Return type
Output
assign(**kwargs: Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any], Mapping[str, Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any]]]]) → RunnableSerializable[Any, Any]¶
Assigns new fields to the dict output of this runnable.
Returns a new runnable.
from langchain_community.llms.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}"
)
llm = FakeStreamingListLLM(responses=["foo-lish"])
chain: Runnable = prompt | llm | {"str": StrOutputParser()}
chain_with_assign = chain.assign(hello=itemgetter("str") | llm)
chain_with_assign = chain.assign(hello=itemgetter("str") | llm)
print(chain_with_assign.input_schema.schema())
# {'title': 'PromptInput', 'type': 'object', 'properties':
{'question': {'title': 'Question', 'type': 'string'}}}
print(chain_with_assign.output_schema.schema()) #
{'title': 'RunnableSequenceOutput', 'type': 'object', 'properties':
{'str': {'title': 'Str',
'type': 'string'}, 'hello': {'title': 'Hello', 'type': 'string'}}}
Parameters
kwargs (Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any], Mapping[str, Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any]]]]) – 
Return type
RunnableSerializable[Any, Any]
async astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output]¶
Default implementation of astream, which calls ainvoke.
Subclasses should override this method if they support streaming output.
Parameters
input (Input) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
AsyncIterator[Output]
astream_events(input: Any, config: Optional[RunnableConfig] = None, *, version: Literal['v1', 'v2'], include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Any) → AsyncIterator[StreamEvent]¶
[Beta] Generate a stream of events.
# Output is 'One two'
Parameters
kwargs (Any) – 
Return type
Runnable[Input, Output]
combine_claims_with_citations(claims: List[Dict[str, Any]]) → str[source]¶
Parameters
claims (List[Dict[str, Any]]) – 
Return type
str
config_schema(*, include: Optional[Sequence[str]] = 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.
Parameters
include (Optional[Sequence[str]]) – A list of fields to include in the config schema.
Returns
A pydantic model that can be used to validate config.
Return type
Type[BaseModel]
configurable_alternatives(which: ConfigurableField, *, default_key: str = 'default', prefix_keys: bool = False, **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) → RunnableSerializable[Input, Output]¶
Configure alternatives for runnables that can be set at runtime.
from langchain_anthropic import ChatAnthropic
from langchain_core.runnables.utils import ConfigurableField
from langchain_openai import ChatOpenAI
model = ChatAnthropic(
    model_name="claude-3-sonnet-20240229"
).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
)
).invoke("which organization created you?").content
)
Parameters
which (ConfigurableField) – 
default_key (str) – 
prefix_keys (bool) – 
kwargs (Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) – 
Return type
RunnableSerializable[Input, Output]
configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) → RunnableSerializable[Input, Output]¶
Configure particular runnable fields at runtime.
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
)
Parameters
kwargs (Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) – 
Return type
RunnableSerializable[Input, Output]
classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
Parameters
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) – 
Return type
DictStrAny
extract_documents(config: Optional[RunnableConfig]) → List[Document][source]¶
Parameters
config (Optional[RunnableConfig]) – 
Return type
List[Document]
classmethod from_orm(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
get_graph(config: Optional[RunnableConfig] = None) → Graph¶
Return a graph representation of this runnable.
Parameters
config (Optional[RunnableConfig]) – 
Return type
Graph
get_input_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶
Get a pydantic model that can be used to validate input to the runnable.
Runnables 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.
Parameters
config (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate input.
Return type
Type[BaseModel]
classmethod get_lc_namespace() → List[str][source]¶
Get the namespace of the langchain object.
For example, if the class is langchain.llms.openai.OpenAI, then the
namespace is [“langchain”, “llms”, “openai”]
Return type
List[str]
get_name(suffix: Optional[str] = None, *, name: Optional[str] = None) → str¶
Get the name of the runnable.
Parameters
suffix (Optional[str]) –
Get the name of the runnable.
Parameters
suffix (Optional[str]) – 
name (Optional[str]) – 
Return type
str
get_output_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶
Get a pydantic model that can be used to validate output to the runnable.
Runnables 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.
Parameters
config (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate output.
Return type
Type[BaseModel]
get_prompts(config: Optional[RunnableConfig] = None) → List[BasePromptTemplate]¶
Parameters
config (Optional[RunnableConfig]) – 
Return type
List[BasePromptTemplate]
invoke(input: str, config: Optional[RunnableConfig] = None) → CheckGroundingResponse[source]¶
Calls the Vertex Check Grounding API for a given answer candidate and a list
of documents (claims) to validate whether the set of claims support the
answer candidate.
Parameters
answer_candidate (str) – The candidate answer to be evaluated for grounding.
documents (List[Document]) – The documents against which grounding is
facts (checked. This will be converted to) – facts (MutableSequence[google.cloud.discoveryengine_v1alpha.types.                    GroundingFact]):
List of facts for the grounding check.
We support up to 200 facts.
input (str) – 
config (Optional[RunnableConfig]) – 
Returns
Response of the type CheckGroundingResponse
Attributes:
support_score (float):
The support score for the input answer