Tony20100/langchain_full huggingface dataset:
langchain_community.chat_models.friendli.get_chat_request¶
langchain_community.chat_models.friendli.get_chat_request(messages: List[BaseMessage]) → Dict[str, Any][source]¶
Get a request of the Friendli chat API.
Parameters
messages (List[BaseMessage]) – Messages comprising the conversation so far.
Returns
The request for the Friendli chat API.
Return type
Dict[str, Any]
langchain_community.chat_models.azureml_endpoint.LlamaChatContentFormatter¶
class langchain_community.chat_models.azureml_endpoint.LlamaChatContentFormatter[source]¶
Deprecated: Kept for backwards compatibility
Chat Content formatter for Llama.
Attributes
SUPPORTED_ROLES
accepts
The MIME type of the response data returned from the endpoint
content_type
The MIME type of the input data passed to the endpoint
format_error_msg
supported_api_types
Supported APIs for the given formatter.
Methods
__init__()
escape_special_characters(prompt)
Escapes any special characters in prompt
format_messages_request_payload(messages, ...)
Formats the request according to the chosen api
format_request_payload(prompt, model_kwargs)
Formats the request body according to the input schema of the model.
format_response_payload(output[, api_type])
Formats response
__init__() → None[source]¶
Return type
None
static escape_special_characters(prompt: str) → str¶
Escapes any special characters in prompt
Parameters
prompt (str) – 
Return type
str
format_messages_request_payload(messages: List[BaseMessage], model_kwargs: Dict, api_type: AzureMLEndpointApiType) → bytes¶
Formats the request according to the chosen api
Parameters
messages (List[BaseMessage]) – 
model_kwargs (Dict) – 
api_type (AzureMLEndpointApiType) – 
Return type
bytes
format_request_payload(prompt: str, model_kwargs: Dict, api_type: AzureMLEndpointApiType = AzureMLEndpointApiType.dedicated) → Any¶
Formats the request body according to the input schema of
the model. Returns bytes or seekable file like object in the
format specified in the content_type request header.
Parameters
prompt (str) – 
model_kwargs (Dict) –
Parameters
prompt (str) – 
model_kwargs (Dict) – 
api_type (AzureMLEndpointApiType) – 
Return type
Any
format_response_payload(output: bytes, api_type: AzureMLEndpointApiType = AzureMLEndpointApiType.dedicated) → ChatGeneration¶
Formats response
Parameters
output (bytes) – 
api_type (AzureMLEndpointApiType) – 
Return type
ChatGeneration
langchain_aws.chat_models.bedrock.convert_messages_to_prompt_anthropic¶
langchain_aws.chat_models.bedrock.convert_messages_to_prompt_anthropic(messages: List[BaseMessage], *, human_prompt: str = '\n\nHuman:', ai_prompt: str = '\n\nAssistant:') → str[source]¶
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 “
Human:”.ai_prompt (str, optional): AI prompt tag. Defaults to “
Assistant:”.
Returns:str: Combined string with necessary human_prompt and ai_prompt tags.
Parameters
messages (List[BaseMessage]) – 
human_prompt (str) – 
ai_prompt (str) – 
Return type
str
langchain_community.chat_models.fireworks.acompletion_with_retry_streaming¶
async langchain_community.chat_models.fireworks.acompletion_with_retry_streaming(llm: ChatFireworks, use_retry: bool, *, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any) → Any[source]¶
Use tenacity to retry the completion call for streaming.
Parameters
llm (ChatFireworks) – 
use_retry (bool) – 
run_manager (Optional[AsyncCallbackManagerForLLMRun]) – 
kwargs (Any) – 
Return type
Any
langchain_community.chat_models.huggingface.ChatHuggingFace¶
class langchain_community.chat_models.huggingface.ChatHuggingFace[source]¶
Bases: BaseChatModel
[Deprecated] 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
Notes
Deprecated since version 0.0.37.
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 cache: Union[BaseCache, bool, None] = None¶
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.
param callback_manager: Optional[BaseCallbackManager] = None¶
[DEPRECATED] Callback manager to add to the run trace.
param callbacks: Callbacks = None¶
Callbacks to add to the run trace.
param custom_get_token_ids: Optional[Callable[[str], List[int]]] = None¶
Optional encoder to use for counting tokens.
param llm: Any = None¶
LLM, must be of type HuggingFaceTextGenInference, HuggingFaceEndpoint, or
HuggingFaceHub.
param metadata: Optional[Dict[str, Any]] = None¶
HuggingFaceHub.
param metadata: Optional[Dict[str, Any]] = None¶
Metadata to add to the run trace.
param model_id: Optional[str] = None¶
param streaming: bool = False¶
param system_message: SystemMessage = SystemMessage(content='You are a helpful, respectful, and honest assistant.')¶
param tags: Optional[List[str]] = None¶
Tags to add to the run trace.
param tokenizer: Any = None¶
param verbose: bool [Optional]¶
Whether to print out response text.
__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → BaseMessage¶
[Deprecated]
Notes
Deprecated since version langchain-core==0.1.7: Use invoke instead.
Parameters
messages (List[BaseMessage]) – 
stop (Optional[List[str]]) – 
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 
kwargs (Any) – 
Return type
BaseMessage
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]
Parameters
input_type (Optional[Type[Input]]) – 
output_type (Optional[Type[Output]]) – 
Return type
Runnable[Input, Output]
property InputType: TypeAlias¶
Get the input type for this runnable.
property OutputType: Any¶
Get the output type for this runnable.
property config_specs: List[ConfigurableFieldSpec]¶
List configurable fields for this runnable.
property input_schema: Type[BaseModel]¶
The type of input this runnable accepts specified as a pydantic model.
property lc_attributes: Dict¶
List of attribute names that should be included in the serialized kwargs.
These attributes must be accepted by the constructor.
property lc_secrets: Dict[str, str]¶
A map of constructor argument names to secret ids.
For example,{“openai_api_key”: “OPENAI_API_KEY”}
name: Optional[str] = None¶
The name of the runnable. Used for debugging and tracing.
property output_schema: Type[BaseModel]¶
The type of output this runnable produces specified as a pydantic model.
Examples using ChatHuggingFace¶
Hugging Face
langchain_huggingface.chat_models.huggingface.TGI_RESPONSE¶
class langchain_huggingface.chat_models.huggingface.TGI_RESPONSE(choices: List[Any], usage: Dict)[source]¶
Attributes
choices
usage
Methods
__init__(choices, usage)
Parameters
choices (List[Any]) – 
usage (Dict) – 
__init__(choices: List[Any], usage: Dict) → None¶
Parameters
choices (List[Any]) – 
usage (Dict) – 
Return type
None
langchain_experimental.chat_models.llm_wrapper.Mixtral¶
class langchain_experimental.chat_models.llm_wrapper.Mixtral[source]¶
Bases: ChatWrapper
See https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1#instruction-format
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 ai_n_beg: str = ' '¶
param ai_n_end: str = ' 
'¶
param cache: Union[BaseCache, bool, None] = None¶
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.
param callback_manager: Optional[BaseCallbackManager] = None¶
[DEPRECATED] Callback manager to add to the run trace.
param callbacks: Callbacks = None¶
Callbacks to add to the run trace.
param custom_get_token_ids: Optional[Callable[[str], List[int]]] = None¶
Optional encoder to use for counting tokens.
param llm: LLM [Required]¶
param metadata: Optional[Dict[str, Any]] = None¶
Metadata to add to the run trace.
param sys_beg: str = '

 '¶
param sys_end: str = '\n'¶
param sys_end: str = '\n'¶
param system_message: SystemMessage = SystemMessage(content="You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.")¶
param tags: Optional[List[str]] = None¶
Tags to add to the run trace.
param usr_0_beg: str = ''¶
param usr_0_end: str = ' 
'¶
param usr_n_beg: str = ' 
 '¶
param usr_n_end: str = ' 
'¶
param verbose: bool [Optional]¶
Whether to print out response text.
__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → BaseMessage¶
[Deprecated]
Notes
Deprecated since version langchain-core==0.1.7: Use invoke instead.
Parameters
messages (List[BaseMessage]) – 
stop (Optional[List[str]]) – 
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 
kwargs (Any) – 
Return type
BaseMessage
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.
langchain_aws.chat_models.bedrock.ChatBedrock¶
class langchain_aws.chat_models.bedrock.ChatBedrock[source]¶
Bases: BaseChatModel, BedrockBase
A chat model that uses the Bedrock API.
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 cache: Union[BaseCache, bool, None] = None¶
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.
param callback_manager: Optional[BaseCallbackManager] = None¶
[DEPRECATED] Callback manager to add to the run trace.
param callbacks: Callbacks = None¶
Callbacks to add to the run trace.
param config: Any = None¶
An optional botocore.config.Config instance to pass to the client.
param 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
param custom_get_token_ids: Optional[Callable[[str], List[int]]] = None¶
Optional encoder to use for counting tokens.
param endpoint_url: Optional[str] = None¶
Needed if you don’t want to default to us-east-1 endpoint
param metadata: Optional[Dict[str, Any]] = None¶
Metadata to add to the run trace.
param model_id: str [Required]¶
Id of the model to call, e.g., amazon.titan-text-express-v1, this is
equivalent to the modelId property in the list-foundation-models api. For custom and
provisioned models, an ARN value is expected.
param model_kwargs: Optional[Dict[str, Any]] = None¶
Keyword arguments to pass to the model.
param provider: Optional[str] = None¶
The model provider, e.g., amazon, cohere, ai21, etc. When not supplied, provider
is extracted from the first part of the model_id e.g. ‘amazon’ in
‘amazon.titan-text-express-v1’. This value should be provided for model ids that do
not have the provider in them, e.g., custom and provisioned models that have an ARN
associated with them.
param provider_stop_reason_key_map: Mapping[str, str] = {'ai21': 'finishReason', 'amazon': 'completionReason', 'anthropic': 'stop_reason', 'cohere': 'finish_reason', 'mistral': 'stop_reason'}¶
param provider_stop_sequence_key_name_map: Mapping[str, str] = {'ai21': 'stop_sequences', 'amazon': 'stopSequences', 'anthropic': 'stop_sequences', 'cohere': 'stop_sequences', 'mistral': 'stop_sequences'}¶
param region_name: Optional[str] = None¶
The aws region e.g., us-west-2. Fallsback to AWS_DEFAULT_REGION env variable
or region specified in ~/.aws/config in case it is not provided here.
param streaming: bool = False¶
Whether to stream the results.
param system_prompt_with_tools: str = ''¶
Whether to stream the results.
param system_prompt_with_tools: str = ''¶
param tags: Optional[List[str]] = None¶
Tags to add to the run trace.
param verbose: bool [Optional]¶
Whether to print out response text.
__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → BaseMessage¶
[Deprecated]
Notes
Deprecated since version langchain-core==0.1.7: Use invoke instead.
Parameters
messages (List[BaseMessage]) – 
stop (Optional[List[str]]) – 
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 
kwargs (Any) – 
Return type
BaseMessage
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,
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 agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, run_id: Optional[UUID] = 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:
take advantage of batched calls,
need more output from the model than just the top generated value,
are building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).
Parameters
messages (List[List[BaseMessage]]) – List of list of messages.
stop (Optional[List[str]]) – Stop words to use when generating. Model output is cut off at the
first occurrence of any of these substrings.
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – Callbacks to pass through. Used for executing additional
functionality, such as logging or streaming, throughout generation.
**kwargs (Any) – Arbitrary additional keyword arguments. These are usually passed
to the model provider API call.
tags (Optional[List[str]]) – 
metadata (Optional[Dict[str, Any]]) –
metadata (Optional[Dict[str, Any]]) – 
run_name (Optional[str]) – 
run_id (Optional[UUID]) – 
**kwargs – 
Returns
An LLMResult, which contains a list of candidate Generations for each inputprompt and additional model provider-specific output.
Return type
LLMResult
async agenerate_prompt(prompts: List[PromptValue], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = 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:
take advantage of batched calls,
need more output from the model than just the top generated value,
are building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).
Parameters
prompts (List[PromptValue]) – List of PromptValues. A PromptValue is an object that can be
converted to match the format of any language model (string for pure
text generation models and BaseMessages for chat models).
stop (Optional[List[str]]) – Stop words to use when generating. Model output is cut off at the
first occurrence of any of these substrings.
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – Callbacks to pass through. Used for executing additional
functionality, such as logging or streaming, throughout generation.
**kwargs (Any) – 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 inputprompt and additional model provider-specific output.
Return type
LLMResult
yielding results as they complete.
Parameters
inputs (Sequence[Input]) – 
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
Iterator[Tuple[int, Union[Output, Exception]]]
bind(**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.
Example:
from langchain_community.chat_models import ChatOllama
from langchain_core.output_parsers import StrOutputParser
llm = ChatOllama(model='llama2')
# Without bind.
chain = (
    llm
    | StrOutputParser()
)
chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
# Output is 'One two three four five.'
# With bind.
chain = (
    llm.bind(stop=["three"])
    | StrOutputParser()
)
chain.invoke("Repeat quoted words exactly: 'One two three four five.'")
# Output is 'One two'
Parameters
kwargs (Any) – 
Return type
Runnable[Input, Output]
bind_tools(tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]], *, tool_choice: Optional[Union[dict, str, Literal['auto', 'none'], bool]] = None, **kwargs: Any) → Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], BaseMessage][source]¶
Bind tool-like objects to this chat model.
Bind tool-like objects to this chat model.
Assumes model has a tool calling API.
Parameters
tools (Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]]) – 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 (Optional[Union[dict, str, Literal['auto', 'none'], bool]]) – 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”: <<tool_name>>}}.
**kwargs (Any) – Any additional parameters to pass to the
Runnable constructor.
Return type
Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], BaseMessage]
call_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) → str¶
[Deprecated]
Notes
Deprecated since version langchain-core==0.1.7: Use invoke instead.
Parameters
message (str) – 
stop (Optional[List[str]]) – 
kwargs (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.
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
)
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