|
21 | 21 | )
|
22 | 22 |
|
23 | 23 | import anthropic
|
24 |
| -from langchain_core._api import deprecated |
| 24 | +from langchain_core._api import beta, deprecated |
25 | 25 | from langchain_core.callbacks import (
|
26 | 26 | AsyncCallbackManagerForLLMRun,
|
27 | 27 | CallbackManagerForLLMRun,
|
@@ -1113,6 +1113,41 @@ class AnswerWithJustification(BaseModel):
|
1113 | 1113 | else:
|
1114 | 1114 | return llm | output_parser
|
1115 | 1115 |
|
| 1116 | + @beta() |
| 1117 | + def get_num_tokens_from_messages( |
| 1118 | + self, |
| 1119 | + messages: List[BaseMessage], |
| 1120 | + tools: Optional[ |
| 1121 | + Sequence[Union[Dict[str, Any], Type, Callable, BaseTool]] |
| 1122 | + ] = None, |
| 1123 | + ) -> int: |
| 1124 | + """Count tokens in a sequence of input messages. |
| 1125 | +
|
| 1126 | + Args: |
| 1127 | + messages: The message inputs to tokenize. |
| 1128 | + tools: If provided, sequence of dict, BaseModel, function, or BaseTools |
| 1129 | + to be converted to tool schemas. |
| 1130 | +
|
| 1131 | + .. versionchanged:: 0.3.0 |
| 1132 | +
|
| 1133 | + Uses Anthropic's token counting API to count tokens in messages. See: |
| 1134 | + https://docs.anthropic.com/en/docs/build-with-claude/token-counting |
| 1135 | + """ |
| 1136 | + formatted_system, formatted_messages = _format_messages(messages) |
| 1137 | + kwargs: Dict[str, Any] = {} |
| 1138 | + if isinstance(formatted_system, str): |
| 1139 | + kwargs["system"] = formatted_system |
| 1140 | + if tools: |
| 1141 | + kwargs["tools"] = [convert_to_anthropic_tool(tool) for tool in tools] |
| 1142 | + |
| 1143 | + response = self._client.beta.messages.count_tokens( |
| 1144 | + betas=["token-counting-2024-11-01"], |
| 1145 | + model=self.model, |
| 1146 | + messages=formatted_messages, # type: ignore[arg-type] |
| 1147 | + **kwargs, |
| 1148 | + ) |
| 1149 | + return response.input_tokens |
| 1150 | + |
1116 | 1151 |
|
1117 | 1152 | class AnthropicTool(TypedDict):
|
1118 | 1153 | """Anthropic tool definition."""
|
|
0 commit comments