Tony20100/langchain_full huggingface dataset:
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_openai import ChatOpenAI
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 = ChatOpenAI(model="gpt-3.5-turbo-0125", 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_openai import ChatOpenAI
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 = ChatOpenAI(model="gpt-3.5-turbo-0125", 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_openai import ChatOpenAI
from langchain_core.pydantic_v1 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 = ChatOpenAI(model="gpt-3.5-turbo-0125", 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',
# -> {
#     '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_openai import ChatOpenAI
from langchain_core.pydantic_v1 import BaseModel
class AnswerWithJustification(BaseModel):
    answer: str
    justification: str
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", 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_openai import ChatOpenAI
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
# }
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¶
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.
langchain_community.chat_models.ollama.ChatOllama¶
class langchain_community.chat_models.ollama.ChatOllama[source]¶
Bases: BaseChatModel, _OllamaCommon
Ollama locally runs large language models.
To use, follow the instructions at https://ollama.ai/.
Example
from langchain_community.chat_models import ChatOllama
ollama = ChatOllama(model="llama2")
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 base_url: str = 'http://localhost:11434'¶
Base url the model is hosted under.
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 format: Optional[str] = None¶
Specify the format of the output (e.g., json)
param headers: Optional[dict] = None¶
Additional headers to pass to endpoint (e.g. Authorization, Referer).
This is useful when Ollama is hosted on cloud services that require
tokens for authentication.
param keep_alive: Optional[Union[int, str]] = None¶
tokens for authentication.
param keep_alive: Optional[Union[int, str]] = None¶
How long the model will stay loaded into memory.
The parameter (Default: 5 minutes) can be set to:
1. a duration string in Golang (such as “10m” or “24h”);
2. a number in seconds (such as 3600);
3. any negative number which will keep the model loaded         in memory (e.g. -1 or “-1m”);
4. 0 which will unload the model immediately after generating a response;
See the [Ollama documents](https://github.com/ollama/ollama/blob/main/docs/faq.md#how-do-i-keep-a-model-loaded-in-memory-or-make-it-unload-immediately)
param metadata: Optional[Dict[str, Any]] = None¶
Metadata to add to the run trace.
param mirostat: Optional[int] = None¶
Enable Mirostat sampling for controlling perplexity.
(default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)
param mirostat_eta: Optional[float] = None¶
Influences how quickly the algorithm responds to feedback
from the generated text. A lower learning rate will result in
slower adjustments, while a higher learning rate will make
the algorithm more responsive. (Default: 0.1)
param mirostat_tau: Optional[float] = None¶
Controls the balance between coherence and diversity
of the output. A lower value will result in more focused and
coherent text. (Default: 5.0)
param model: str = 'llama2'¶
Model name to use.
param num_ctx: Optional[int] = None¶
Sets the size of the context window used to generate the
Sets the size of the context window used to generate the
next token. (Default: 2048)
param num_gpu: Optional[int] = None¶
The number of GPUs to use. On macOS it defaults to 1 to
enable metal support, 0 to disable.
param num_predict: Optional[int] = None¶
Maximum number of tokens to predict when generating text.
(Default: 128, -1 = infinite generation, -2 = fill context)
param num_thread: Optional[int] = None¶
Sets the number of threads to use during computation.
By default, Ollama will detect this for optimal performance.
It is recommended to set this value to the number of physical
CPU cores your system has (as opposed to the logical number of cores).
param repeat_last_n: Optional[int] = None¶
Sets how far back for the model to look back to prevent
repetition. (Default: 64, 0 = disabled, -1 = num_ctx)
param repeat_penalty: Optional[float] = None¶
Sets how strongly to penalize repetitions. A higher value (e.g., 1.5)
will penalize repetitions more strongly, while a lower value (e.g., 0.9)
will be more lenient. (Default: 1.1)
param stop: Optional[List[str]] = None¶
Sets the stop tokens to use.
param system: Optional[str] = None¶
system prompt (overrides what is defined in the Modelfile)
param tags: Optional[List[str]] = None¶
Tags to add to the run trace.
param temperature: Optional[float] = None¶
The temperature of the model. Increasing the temperature will
make the model answer more creatively. (Default: 0.8)
param template: Optional[str] = None¶
param template: Optional[str] = None¶
full prompt or prompt template (overrides what is defined in the Modelfile)
param tfs_z: Optional[float] = None¶
Tail free sampling is used to reduce the impact of less probable
tokens from the output. A higher value (e.g., 2.0) will reduce the
impact more, while a value of 1.0 disables this setting. (default: 1)
param timeout: Optional[int] = None¶
Timeout for the request stream
param top_k: Optional[int] = None¶
Reduces the probability of generating nonsense. A higher value (e.g. 100)
will give more diverse answers, while a lower value (e.g. 10)
will be more conservative. (Default: 40)
param top_p: Optional[float] = None¶
Works together with top-k. A higher value (e.g., 0.95) will lead
to more diverse text, while a lower value (e.g., 0.5) will
generate more focused and conservative text. (Default: 0.9)
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
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 ChatOllama¶
ChatOllama
Ollama
langchain_community.chat_models.azureml_endpoint.CustomOpenAIChatContentFormatter¶
class langchain_community.chat_models.azureml_endpoint.CustomOpenAIChatContentFormatter[source]¶
Chat Content formatter for models with OpenAI like API scheme.
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__()¶
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[source]¶
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) – 
api_type (AzureMLEndpointApiType) – 
Return type
Any
api_type (AzureMLEndpointApiType) – 
Return type
Any
format_response_payload(output: bytes, api_type: AzureMLEndpointApiType = AzureMLEndpointApiType.dedicated) → ChatGeneration[source]¶
Formats response
Parameters
output (bytes) – 
api_type (AzureMLEndpointApiType) – 
Return type
ChatGeneration
Examples using CustomOpenAIChatContentFormatter¶
AzureMLChatOnlineEndpoint
langchain_community.chat_models.fake.FakeListChatModel¶
class langchain_community.chat_models.fake.FakeListChatModel[source]¶
Bases: SimpleChatModel
Fake ChatModel for testing purposes.
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 i: int = 0¶
param metadata: Optional[Dict[str, Any]] = None¶
Metadata to add to the run trace.
param responses: List [Required]¶
param sleep: Optional[float] = None¶
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
langchain_community.chat_models.openai.ChatOpenAI¶
class langchain_community.chat_models.openai.ChatOpenAI[source]¶
Bases: BaseChatModel
[Deprecated] 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
from langchain_community.chat_models import ChatOpenAI
openai = ChatOpenAI(model="gpt-3.5-turbo")
Notes
Deprecated since version 0.0.10.
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 default_headers: Union[Mapping[str, str], None] = None¶
param default_query: Union[Mapping[str, object], None] = None¶
param http_client: Union[Any, None] = None¶
Optional httpx.Client.
param http_client: Union[Any, None] = None¶
Optional httpx.Client.
param max_retries: int = 2¶
Maximum number of retries to make when generating.
param max_tokens: Optional[int] = None¶
Maximum number of tokens to generate.
param metadata: Optional[Dict[str, Any]] = None¶
Metadata to add to the run trace.
param model_kwargs: Dict[str, Any] [Optional]¶
Holds any model parameters valid for create call not explicitly specified.
param model_name: str = 'gpt-3.5-turbo' (alias 'model')¶
Model name to use.
param n: int = 1¶
Number of chat completions to generate for each prompt.
param openai_api_base: Optional[str] = None (alias 'base_url')¶
Base URL path for API requests, leave blank if not using a proxy or service
emulator.
param openai_api_key: Optional[str] = None (alias 'api_key')¶
Automatically inferred from env var OPENAI_API_KEY if not provided.
param openai_organization: Optional[str] = None (alias 'organization')¶
Automatically inferred from env var OPENAI_ORG_ID if not provided.
param openai_proxy: Optional[str] = None¶
param request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')¶
Timeout for requests to OpenAI completion API. Can be float, httpx.Timeout or
None.
param streaming: bool = False¶
Whether to stream the results or not.
param tags: Optional[List[str]] = None¶
Tags to add to the run trace.
param temperature: float = 0.7¶
What sampling temperature to use.
param tiktoken_model_name: Optional[str] = None¶
What sampling temperature to use.
param 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.
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;
Parameters
kwargs (Any) – 
Return type
Runnable[Input, Output]
bind_functions(functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]], function_call: Optional[str] = None, **kwargs: Any) → Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], BaseMessage][source]¶
Bind functions (and other objects) to this chat model.
Parameters
functions (Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]]) – 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 (Optional[str]) – 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) – 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]
bind_tools(tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]], **kwargs: Any) → Runnable[LanguageModelInput, BaseMessage]¶
Parameters
tools (Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]]) – 
kwargs (Any) – 
Return type
Runnable[LanguageModelInput, BaseMessage]
call_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) → str¶
[Deprecated]
Notes