Message from an AI. AIMessage is returned from a chat model as a response to a prompt. This message represents the output of the model and consists of both the raw output as returned by the model together standardized fields (e.g., tool calls, usage metadata) added by the LangChain
| 47 | |
| 48 | |
| 49 | class AIMessage(BaseMessage): |
| 50 | """Message from an AI. |
| 51 | |
| 52 | AIMessage is returned from a chat model as a response to a prompt. |
| 53 | |
| 54 | This message represents the output of the model and consists of both |
| 55 | the raw output as returned by the model together standardized fields |
| 56 | (e.g., tool calls, usage metadata) added by the LangChain framework. |
| 57 | """ |
| 58 | |
| 59 | example: bool = False |
| 60 | """Use to denote that a message is part of an example conversation. |
| 61 | |
| 62 | At the moment, this is ignored by most models. Usage is discouraged. |
| 63 | """ |
| 64 | |
| 65 | tool_calls: List[ToolCall] = [] |
| 66 | """If provided, tool calls associated with the message.""" |
| 67 | invalid_tool_calls: List[InvalidToolCall] = [] |
| 68 | """If provided, tool calls with parsing errors associated with the message.""" |
| 69 | usage_metadata: Optional[UsageMetadata] = None |
| 70 | """If provided, usage metadata for a message, such as token counts. |
| 71 | |
| 72 | This is a standard representation of token usage that is consistent across models. |
| 73 | """ |
| 74 | |
| 75 | type: Literal["ai"] = "ai" |
| 76 | """The type of the message (used for deserialization).""" |
| 77 | |
| 78 | def __init__( |
| 79 | self, content: Union[str, List[Union[str, Dict]]], **kwargs: Any |
| 80 | ) -> None: |
| 81 | """Pass in content as positional arg.""" |
| 82 | super().__init__(content=content, **kwargs) |
| 83 | |
| 84 | @classmethod |
| 85 | def get_lc_namespace(cls) -> List[str]: |
| 86 | """Get the namespace of the langchain object.""" |
| 87 | return ["langchain", "schema", "messages"] |
| 88 | |
| 89 | @property |
| 90 | def lc_attributes(self) -> Dict: |
| 91 | """Attrs to be serialized even if they are derived from other init args.""" |
| 92 | return { |
| 93 | "tool_calls": self.tool_calls, |
| 94 | "invalid_tool_calls": self.invalid_tool_calls, |
| 95 | } |
| 96 | |
| 97 | @root_validator(pre=True) |
| 98 | def _backwards_compat_tool_calls(cls, values: dict) -> dict: |
| 99 | raw_tool_calls = values.get("additional_kwargs", {}).get("tool_calls") |
| 100 | tool_calls = ( |
| 101 | values.get("tool_calls") |
| 102 | or values.get("invalid_tool_calls") |
| 103 | or values.get("tool_call_chunks") |
| 104 | ) |
| 105 | if raw_tool_calls and not tool_calls: |
| 106 | try: |
no outgoing calls