Tony20100/langchain_full huggingface dataset:
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]¶
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]) – 
name (Optional[str]) – 
Return type
str
get_num_tokens(text: str) → int[source]¶
Calculate number of tokens.
Parameters
text (str) – 
Return type
int
get_num_tokens_from_messages(messages: List[BaseMessage]) → int¶
Get the number of tokens in the messages.
Useful for checking if an input will fit in a model’s context window.
Parameters
messages (List[BaseMessage]) – The message inputs to tokenize.
Returns
The sum of the number of tokens across the messages.
Return type
int
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
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]
get_token_ids(text: str) → List[int]¶
Return the ordered ids of the tokens in a text.
Parameters
text (str) – The string input to tokenize.
Returns
A list of ids corresponding to the tokens in the text, in order they occurin the text.
Return type
List[int]
invoke(input: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) → BaseMessage¶
Transform a single input into an output. Override to implement.
Parameters
input (LanguageModelInput) – The input to the runnable.
config (Optional[RunnableConfig]) – 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 the RunnableConfig
for more details.
stop (Optional[List[str]]) – 
kwargs (Any) – 
Returns
The output of the runnable.
Return type
BaseMessage
classmethod is_lc_serializable() → bool¶
Is this class serializable?
Return type
bool
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)
Parameters
retry_if_exception_type (Tuple[Type[BaseException], ...]) – A tuple of exception types to retry on
wait_exponential_jitter (bool) – Whether to add jitter to the wait time
between retries
stop_after_attempt (int) – The maximum number of attempts to make before giving up
Returns
A new Runnable that retries the original runnable on exceptions.
Return type
Runnable[Input, Output]
with_structured_output(schema: Union[Dict, Type[BaseModel]], **kwargs: Any) → Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], Union[Dict, BaseModel]][source]¶
Model wrapper that returns outputs formatted to match the given schema.
Parameters
schema (Union[Dict, Type[BaseModel]]) – 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.
kwargs (Any) – 
Returns
A Runnable that takes any ChatModel input and returns either a dict or
Pydantic class as output.
Return type
Pydantic class as output.
Return type
Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], Union[Dict, BaseModel]]
with_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) → Runnable[Input, Output]¶
Bind input and output types to a Runnable, returning a new Runnable.
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”}
property model_name: str¶
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.
langchain_community.chat_models.fireworks.completion_with_retry¶
langchain_community.chat_models.fireworks.completion_with_retry(llm: ChatFireworks, use_retry: bool, *, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) → Any[source]¶
Use tenacity to retry the completion call.
Parameters
llm (ChatFireworks) – 
use_retry (bool) – 
run_manager (Optional[CallbackManagerForLLMRun]) – 
kwargs (Any) – 
Return type
Any
langchain_mistralai.chat_models.ChatMistralAI¶
class langchain_mistralai.chat_models.ChatMistralAI[source]¶
Bases: BaseChatModel
A chat model that uses the MistralAI 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 custom_get_token_ids: Optional[Callable[[str], List[int]]] = None¶
Optional encoder to use for counting tokens.
param endpoint: str = 'https://api.mistral.ai/v1'¶
param max_concurrent_requests: int = 64¶
param max_retries: int = 5¶
param max_tokens: Optional[int] = None¶
param metadata: Optional[Dict[str, Any]] = None¶
Metadata to add to the run trace.
param mistral_api_key: Optional[SecretStr] = None (alias 'api_key')¶
Constraints
type = string
writeOnly = True
format = password
param model: str = 'mistral-small' (alias 'model_name')¶
param random_seed: Optional[int] = None¶
param safe_mode: bool = False¶
param streaming: bool = False¶
param safe_mode: bool = False¶
param streaming: bool = False¶
param tags: Optional[List[str]] = None¶
Tags to add to the run trace.
param temperature: float = 0.7¶
param timeout: int = 120¶
param top_p: float = 1¶
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].
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
Run invoke 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
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]], **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.
Assumes model is compatible with OpenAI tool-calling API.
Parameters
Assumes model is compatible with OpenAI 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 – 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
completion_with_retry(run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) → Any[source]¶
Use tenacity to retry the completion call.
Parameters
run_manager (Optional[CallbackManagerForLLMRun]) – 
kwargs (Any) – 
Return type
Any
config_schema(*, include: Optional[Sequence[str]] = None) → Type[BaseModel]¶
Return type
Type[BaseModel]
classmethod get_lc_namespace() → List[str][source]¶
Get the namespace of the langchain object.
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]) – 
name (Optional[str]) – 
Return type
str
get_num_tokens(text: str) → int¶
Get the number of tokens present in the text.
Useful for checking if an input will fit in a model’s context window.
Parameters
text (str) – The string input to tokenize.
Returns
The integer number of tokens in the text.
Return type
int
get_num_tokens_from_messages(messages: List[BaseMessage]) → int¶
Get the number of tokens in the messages.
Useful for checking if an input will fit in a model’s context window.
Parameters
messages (List[BaseMessage]) – The message inputs to tokenize.
Returns
The sum of the number of tokens across the messages.
Return type
int
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
Parameters
config (Optional[RunnableConfig]) – 
Return type
List[BasePromptTemplate]
get_token_ids(text: str) → List[int]¶
Return the ordered ids of the tokens in a text.
Parameters
text (str) – The string input to tokenize.
Returns
A list of ids corresponding to the tokens in the text, in order they occurin the text.
Return type
List[int]
invoke(input: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) → BaseMessage¶
Transform a single input into an output. Override to implement.
Parameters
input (LanguageModelInput) – The input to the runnable.
config (Optional[RunnableConfig]) – 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 the RunnableConfig
for more details.
stop (Optional[List[str]]) – 
kwargs (Any) – 
Returns
The output of the runnable.
Return type
BaseMessage
classmethod is_lc_serializable() → bool[source]¶
Return whether this model can be serialized by Langchain.
Return type
bool
json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶
stop_after_attempt (int) – The maximum number of attempts to make before giving up
Returns
A new Runnable that retries the original runnable on exceptions.
Return type
Runnable[Input, Output]
with_structured_output(schema: Optional[Union[Dict, Type[BaseModel]]] = None, *, method: Literal['function_calling', 'json_mode'] = 'function_calling', include_raw: bool = False, **kwargs: Any) → Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], Union[Dict, BaseModel]][source]¶
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 classthen 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”. 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” then OpenAI’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. Ifan error occurs during model output parsing it will be raised. If True
then both the raw model response (a BaseMessage) and the parsed model
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 Pydanticclass.
If schema is a dict then _DictOrPydantic is a dict.
Example: Function-calling, Pydantic schema (method=”function_calling”, include_raw=False):from langchain_mistralai import ChatMistralAI
from langchain_core.pydantic_v1 import BaseModel
class AnswerWithJustification(BaseModel):
    '''An answer to the user question along with justification for the answer.'''
    answer: str
    justification: str
llm = ChatMistralAI(model="mistral-large-latest", 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='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):from langchain_mistralai import ChatMistralAI
from langchain_core.pydantic_v1 import BaseModel
class AnswerWithJustification(BaseModel):
    '''An answer to the user question along with justification for the answer.'''
    answer: str
    justification: str
llm = ChatMistralAI(model="mistral-large-latest", 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_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):from langchain_mistralai import ChatMistralAI
from langchain_core.pydantic_v1 import BaseModel
from langchain_core.utils.function_calling import convert_to_openai_tool
class AnswerWithJustification(BaseModel):
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 = ChatMistralAI(model="mistral-large-latest", 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': '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.'
# }
Example: JSON mode, Pydantic schema (method=”json_mode”, include_raw=True):from langchain_mistralai import ChatMistralAI
from langchain_core.pydantic_v1 import BaseModel
class AnswerWithJustification(BaseModel):
    answer: str
    justification: str
llm = ChatMistralAI(model="mistral-large-latest", 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'.
“
“What’s heavier a pound of bricks or a pound of feathers?”
)
# -> {
#     ‘raw’: AIMessage(content=’{
“answer”: “They are both the same weight.”,
“justification”: “Both a pound of bricks and a pound of feathers weigh one pound. The difference lies in the volume and density of the materials, not the weight.”
}’),
#     ‘parsed’: AnswerWithJustification(answer=’They are both the same weight.’, justification=’Both a pound of bricks and a pound of feathers weigh one pound. The difference lies in the volume and density of the materials, not the weight.’),
#     ‘parsing_error’: None
# }
Example: JSON mode, no schema (schema=None, method=”json_mode”, include_raw=True):from langchain_mistralai import ChatMistralAI
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'.
“
“What’s heavier a pound of bricks or a pound of feathers?”
)
# -> {
#     ‘raw’: AIMessage(content=’{
“answer”: “They are both the same weight.”,
“justification”: “Both a pound of bricks and a pound of feathers weigh one pound. The difference lies in the volume and density of the materials, not the weight.”
}’),#     ‘parsed’: {
#         ‘answer’: ‘They are both the same weight.’,
#         ‘justification’: ‘Both a pound of bricks and a pound of feathers weigh one pound. The difference lies in the volume and density of the materials, not the weight.’
#     },
#     ‘parsing_error’: None
# }
Parameters
schema (Optional[Union[Dict, Type[BaseModel]]]) – 
method (Literal['function_calling', 'json_mode']) – 
include_raw (bool) – 
kwargs (Any) – 
Return type