Tony20100/langchain_full huggingface dataset:
Parameters
by_alias (bool) – 
ref_template (unicode) – 
dumps_kwargs (Any) – 
Return type
unicode
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
Return type
Union[SerializedConstructor, SerializedNotImplemented]
to_json_not_implemented() → SerializedNotImplemented¶
Return type
SerializedNotImplemented
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
property lc_attributes: Dict¶
Attrs to be serialized even if they are derived from other init args.
property lc_secrets: Dict[str, str]¶
A map of constructor argument names to secret ids.
For example,{“openai_api_key”: “OPENAI_API_KEY”}
Examples using AIMessage¶
Build a Chatbot
Build an Agent
Chat Bot Feedback Template
ChatAnthropic
ChatGLM
Conversational RAG
Google Cloud Vertex AI
Google Imagen
How to add a human-in-the-loop for tools
How to add a semantic layer over graph database
How to add chat history
How to add examples to the prompt for query analysis
How to add memory to chatbots
How to add retrieval to chatbots
How to add tools to chatbots
How to compose prompts together
How to create a custom Output Parser
How to create a custom chat model class
How to do tool/function calling
How to handle tool errors
How to return structured data from a model
How to use a model to call tools
How to use prompting alone (no tool calling) to do extraction
How to use reference examples when doing extraction
SQL Database
langchain_core.messages.tool.ToolMessageChunk¶
class langchain_core.messages.tool.ToolMessageChunk[source]¶
Bases: ToolMessage, BaseMessageChunk
Tool Message chunk.
Pass in content as positional arg.
param additional_kwargs: dict [Optional]¶
Reserved for additional payload data associated with the message.
For example, for a message from an AI, this could include tool calls.
param content: Union[str, List[Union[str, Dict]]] [Required]¶
The string contents of the message.
param id: Optional[str] = None¶
An optional unique identifier for the message. This should ideally be
provided by the provider/model which created the message.
param name: Optional[str] = None¶
param response_metadata: dict [Optional]¶
Response metadata. For example: response headers, logprobs, token counts.
param tool_call_id: str [Required]¶
Tool call that this message is responding to.
param type: Literal['ToolMessageChunk'] = 'ToolMessageChunk'¶
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
localns (Any) – 
Return type
None
classmethod validate(value: Any) → Model¶
Parameters
value (Any) – 
Return type
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”}
Examples using ToolMessageChunk¶
How to create a custom chat model class
langchain_core.messages.utils.get_buffer_string¶
langchain_core.messages.utils.get_buffer_string(messages: Sequence[BaseMessage], human_prefix: str = 'Human', ai_prefix: str = 'AI') → str[source]¶
Convert a sequence of Messages to strings and concatenate them into one string.
Args:messages: Messages to be converted to strings.
human_prefix: The prefix to prepend to contents of HumanMessages.
ai_prefix: THe prefix to prepend to contents of AIMessages.
Returns:A single string concatenation of all input messages.
Example:from langchain_core import AIMessage, HumanMessage
messages = [
    HumanMessage(content="Hi, how are you?"),
    AIMessage(content="Good, how are you?"),
]
get_buffer_string(messages)
# -> "Human: Hi, how are you?
AI: Good, how are you?”
Parameters
messages (Sequence[BaseMessage]) – 
human_prefix (str) – 
ai_prefix (str) – 
Return type
str
langchain_core.messages.system.SystemMessageChunk¶
class langchain_core.messages.system.SystemMessageChunk[source]¶
Bases: SystemMessage, BaseMessageChunk
System Message chunk.
Pass in content as positional arg.
param additional_kwargs: dict [Optional]¶
Reserved for additional payload data associated with the message.
For example, for a message from an AI, this could include tool calls.
param content: Union[str, List[Union[str, Dict]]] [Required]¶
The string contents of the message.
param id: Optional[str] = None¶
An optional unique identifier for the message. This should ideally be
provided by the provider/model which created the message.
param name: Optional[str] = None¶
param response_metadata: dict [Optional]¶
Response metadata. For example: response headers, logprobs, token counts.
param type: Literal['SystemMessageChunk'] = 'SystemMessageChunk'¶
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
Parameters
localns (Any) – 
Return type
None
classmethod validate(value: Any) → Model¶
Parameters
value (Any) – 
Return type
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”}
Examples using SystemMessageChunk¶
How to create a custom chat model class
langchain_core.messages.base.BaseMessageChunk¶
class langchain_core.messages.base.BaseMessageChunk[source]¶
Bases: BaseMessage
Message chunk, which can be concatenated with other Message chunks.
Pass in content as positional arg.
param additional_kwargs: dict [Optional]¶
Reserved for additional payload data associated with the message.
For example, for a message from an AI, this could include tool calls.
param content: Union[str, List[Union[str, Dict]]] [Required]¶
The string contents of the message.
param id: Optional[str] = None¶
An optional unique identifier for the message. This should ideally be
provided by the provider/model which created the message.
param name: Optional[str] = None¶
param response_metadata: dict [Optional]¶
Response metadata. For example: response headers, logprobs, token counts.
param type: str [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
content_type (unicode) – 
encoding (unicode) – 
proto (Protocol) – 
allow_pickle (bool) – 
Return type
Model
classmethod parse_obj(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
Parameters
b (Union[str, bytes]) – 
content_type (unicode) – 
encoding (unicode) – 
proto (Protocol) – 
allow_pickle (bool) – 
Return type
Model
pretty_print() → None¶
Return type
None
pretty_repr(html: bool = False) → str¶
Parameters
html (bool) – 
Return type
str
classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶
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
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
Return type
Union[SerializedConstructor, SerializedNotImplemented]
to_json_not_implemented() → SerializedNotImplemented¶
Return type
SerializedNotImplemented
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
langchain_core.messages.chat.ChatMessage¶
class langchain_core.messages.chat.ChatMessage[source]¶
Bases: BaseMessage
Message that can be assigned an arbitrary speaker (i.e. role).
Pass in content as positional arg.
param additional_kwargs: dict [Optional]¶
Reserved for additional payload data associated with the message.
For example, for a message from an AI, this could include tool calls.
param content: Union[str, List[Union[str, Dict]]] [Required]¶
The string contents of the message.
param id: Optional[str] = None¶
An optional unique identifier for the message. This should ideally be
provided by the provider/model which created the message.
param name: Optional[str] = None¶
param response_metadata: dict [Optional]¶
Response metadata. For example: response headers, logprobs, token counts.
param role: str [Required]¶
The speaker / role of the Message.
param type: Literal['chat'] = 'chat'¶
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
langchain_core.messages.ai.AIMessageChunk¶
class langchain_core.messages.ai.AIMessageChunk[source]¶
Bases: AIMessage, BaseMessageChunk
Message chunk from an AI.
Pass in content as positional arg.
param additional_kwargs: dict [Optional]¶
Reserved for additional payload data associated with the message.
For example, for a message from an AI, this could include tool calls.
param content: Union[str, List[Union[str, Dict]]] [Required]¶
The string contents of the message.
param example: bool = False¶
Whether this Message is being passed in to the model as part of an example
conversation.
param id: Optional[str] = None¶
An optional unique identifier for the message. This should ideally be
provided by the provider/model which created the message.
param invalid_tool_calls: List[InvalidToolCall] = []¶
If provided, tool calls with parsing errors associated with the message.
param name: Optional[str] = None¶
param response_metadata: dict [Optional]¶
Response metadata. For example: response headers, logprobs, token counts.
param tool_call_chunks: List[ToolCallChunk] = []¶
If provided, tool call chunks associated with the message.
param tool_calls: List[ToolCall] = []¶
If provided, tool calls associated with the message.
param type: Literal['AIMessageChunk'] = 'AIMessageChunk'¶
param usage_metadata: Optional[UsageMetadata] = None¶
If provided, usage metadata for a message, such as token counts.
This is a standard representation of token usage that is consistent across models.
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.
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) – 
Return type
DictStrAny
classmethod from_orm(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
classmethod get_lc_namespace() → List[str][source]¶
Get the namespace of the langchain object.
Return type
List[str]
classmethod is_lc_serializable() → bool¶
Return whether this class is serializable.
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¶
Generate a JSON representation of the model, include and exclude arguments as per dict().
encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) –
exclude_defaults (bool) – 
exclude_none (bool) – 
encoder (Optional[Callable[[Any], Any]]) – 
models_as_dict (bool) – 
dumps_kwargs (Any) – 
Return type
unicode
classmethod lc_id() → List[str]¶
A unique identifier for this class for serialization purposes.
The unique identifier is a list of strings that describes the path
to the object.
Return type
List[str]
classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
Parameters
path (Union[str, Path]) – 
content_type (unicode) – 
encoding (unicode) – 
proto (Protocol) – 
allow_pickle (bool) – 
Return type
Model
classmethod parse_obj(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
Parameters
b (Union[str, bytes]) – 
content_type (unicode) – 
encoding (unicode) – 
proto (Protocol) – 
allow_pickle (bool) – 
Return type
Model
pretty_print() → None¶
Return type
None
pretty_repr(html: bool = False) → str¶
Return a pretty representation of the message.
Parameters
html (bool) – 
Return type
str
classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶
Parameters
by_alias (bool) – 
ref_template (unicode) – 
Return type
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
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
Return type
Union[SerializedConstructor, SerializedNotImplemented]
to_json_not_implemented() → SerializedNotImplemented¶
Return type
SerializedNotImplemented
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
property lc_attributes: Dict¶
Attrs to be serialized even if they are derived from other init args.
property lc_secrets: Dict[str, str]¶
A map of constructor argument names to secret ids.
For example,{“openai_api_key”: “OPENAI_API_KEY”}
Examples using AIMessageChunk¶
Google Cloud Vertex AI
How to create a custom Output Parser
How to create a custom chat model class
langchain_core.messages.tool.ToolCallChunk¶
class langchain_core.messages.tool.ToolCallChunk[source]¶
A chunk of a tool call (e.g., as part of a stream).
When merging ToolCallChunks (e.g., via AIMessageChunk.__add__),
all string attributes are concatenated. Chunks are only merged if their
values of index are equal and not None.
Example:
left_chunks = [ToolCallChunk(name="foo", args='{"a":', index=0)]
right_chunks = [ToolCallChunk(name=None, args='1}', index=0)]
(
    AIMessageChunk(content="", tool_call_chunks=left_chunks)
    + AIMessageChunk(content="", tool_call_chunks=right_chunks)
).tool_call_chunks == [ToolCallChunk(name='foo', args='{"a":1}', index=0)]
name¶
(str) if provided, a substring of the name of the tool to be called
Type
Optional[str]
args¶
(str) if provided, a JSON substring of the arguments to the tool call
Type
Optional[str]
id¶
(str) if provided, a substring of an identifier for the tool call
Type
Optional[str]
index¶
(int) if provided, the index of the tool call in a sequence
Type
Optional[int]
Attributes
name
args
id
index
Methods
__init__(*args, **kwargs)
clear()
copy()
fromkeys([value])
Create a new dictionary with keys from iterable and values set to value.
get(key[, default])
Return the value for key if key is in the dictionary, else default.
items()
keys()
pop(k[,d])
If the key is not found, return the default if given; otherwise, raise a KeyError.
popitem()
popitem()
Remove and return a (key, value) pair as a 2-tuple.
setdefault(key[, default])
Insert key with a value of default if key is not in the dictionary.
update([E, ]**F)
If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v In either case, this is followed by: for k in F:  D[k] = F[k]
values()
__init__(*args, **kwargs)¶
clear() → None.  Remove all items from D.¶
copy() → a shallow copy of D¶
fromkeys(value=None, /)¶
Create a new dictionary with keys from iterable and values set to value.
get(key, default=None, /)¶
Return the value for key if key is in the dictionary, else default.
items() → a set-like object providing a view on D's items¶
keys() → a set-like object providing a view on D's keys¶
pop(k[, d]) → v, remove specified key and return the corresponding value.¶
If the key is not found, return the default if given; otherwise,
raise a KeyError.
popitem()¶
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order.
Raises KeyError if the dict is empty.
setdefault(key, default=None, /)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
Return the value for key if key is in the dictionary, else default.
update([E, ]**F) → None.  Update D from dict/iterable E and F.¶
If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
In either case, this is followed by: for k in F:  D[k] = F[k]
values() → an object providing a view on D's values¶
langchain_google_genai.genai_aqa.GenAIAqa¶
class langchain_google_genai.genai_aqa.GenAIAqa[source]¶
Bases: RunnableSerializable[AqaInput, AqaOutput]
Google’s Attributed Question and Answering service.
Given a user’s query and a list of passages, Google’s server will return
a response that is grounded to the provided list of passages. It will not
base the response on parametric memory.
answer_style¶
keyword-only argument. See
google.ai.generativelanguage.AnswerStyle for details.
Construct a Google Generative AI AQA model.
All arguments are optional.
Parameters
answer_style – See
google.ai.generativelanguage.GenerateAnswerRequest.AnswerStyle.
safety_settings – See google.ai.generativelanguage.SafetySetting.
temperature – 0.0 to 1.0.
param answer_style: int = 1¶
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]
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 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 = (