LLM 基础类文档¶
LLM Base Class Documentation¶
本模块定义了大型语言模型 (LLM) 封装的基础类。 This module defines the base class for Large Language Model (LLM) wrappers.
BaseLLM 类¶
BaseLLM Class¶
BaseLLM 是所有具体 LLM 实现的抽象基类。它负责处理对 LLM 的调用、返回结果的封装,并进行基础的调用计费统计。
BaseLLM is an abstract base class for all concrete LLM implementations. It is responsible for handling calls to the LLM, encapsulating the returned results, and performing basic call cost statistics.
Bases: TFNeuralModel, ABC
基础大语言模型封装 | Base Large Language Model Wrapper
基础大语言模型负责处理对LLM的调用与返回封装,同时处理基础的调用计费统计 目前的费用统计无法做到与各大模型厂商严格对齐,仅供参考
Base Large Language Model is responsible for processing the call to LLM and returning the encapsulation, and processing the basic call billing statistics. The current cost statistics cannot be strictly aligned with the LLM manufacturers, for reference only.
Attributes:
| Name | Type | Description |
|---|---|---|
input_price(float) |
价格 | Price |
|
output_price(float) |
价格 | Price |
|
name(str) |
LLM-Model名称 | LLM-Model name |
|
context_window(int) |
单次请求上下文大小 | Single request context size |
all_prompts
abstractmethod
property
¶
all_prompts: list[BasePrompt]
获取当前LLM正在使用的所有Prompt | Get all prompts that the current LLM is using
Returns:
| Type | Description |
|---|---|
list[BasePrompt]
|
list[BasePrompt]: Prompt列表 | Prompt list |
used_tool_prompt
property
¶
used_tool_prompt: bool
是否使用了工具Prompt
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
是否使用了工具Prompt | Whether the tool prompt is used |
enable_dsl_mode
property
¶
enable_dsl_mode: bool
是否启用DSL模式。使用工具Prompt不一定启用DSL模式,而启用DSL模式一定使用了工具Prompt
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
是否启用DSL模式 | Whether DSL mode is enabled |
enable_tfl_mode
property
¶
enable_tfl_mode: bool
是否启用了TFL模式,TFL模式是对DSL模式的增加,主要是简化了配置复杂度,让整个调用过程更自然一些。详情请参考:
docs/brain/chain/prompt/tfl_prompt.md
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
additional_kwargs_schema
property
¶
additional_kwargs_schema: Optional[JsonSchemaValue]
通过此属性获取可以供此LLM正常运行的CurrentInput.AdditionalKwargs的JsonSchema要求。必须满足此要求,才可以正常渲染相关Prompt, 否则会触发异常。但需要注意,异常不一定会被抛出,为了最大化保证用户体验,Prompt渲染异常会被跳过。但仍然需要通过此字段的能力,来提醒用户 或者前置系统,按此要求来准备相关元数据。
Returns:
| Type | Description |
|---|---|
Optional[JsonSchemaValue]
|
Optional[JsonSchemaValue]: 所有Prompt的additional_kwargs的JsonSchema | The JsonSchema of all prompts' additional_kwargs |
construct_prompt_context ¶
construct_prompt_context(current_input: BaseMessage, conversation: Optional[list[BaseMessage]] = None, elements: Optional[list[DocElement]] = None, knowledge: Optional[str] = None, tools: Optional[list[BaseTool]] = None, intermediate_msgs: Optional[list[BaseMessage]] = None, response_format: Optional[LLMResponseFormat] = None) -> PromptContext
构建出提示词渲染所使用的上下文环境。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_input
|
BaseMessage
|
Current input | 当前输入 |
required |
conversation
|
Optional[list[BaseMessage]]
|
Conversation history | 会话历史 |
None
|
elements
|
Optional[list[DocElement]]
|
Document elements | 文档元素 |
None
|
knowledge
|
Optional[str]
|
Related knowledge | 相关知识 |
None
|
tools
|
Optional[list[BaseTool]]
|
Available tool list | 可用的工具列表 |
None
|
intermediate_msgs
|
Optional[list[BaseMessage]]
|
Intermediate messages, it will be generated during llm work in chain, list tool's response or other system message, those messages will not save into memory, but usefully during chain work | 中间消息,它将在链式工作中生成,列表工具的响应或其他系统消息,这些消息不会保存到记忆体中, 但在链式工作中非常有用 |
None
|
response_format
|
Optional[LLMResponseFormat]
|
Response format | 响应格式 如果指定了此参数,将会覆盖模型的默认响应格式 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
PromptContext |
PromptContext
|
提示词上下文信息 |
Source code in tfrobot/brain/chain/llms/base.py
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |
construct_request_params
abstractmethod
¶
construct_request_params(current_input: BaseMessage, conversation: Optional[list[BaseMessage]] = None, elements: Optional[list[DocElement]] = None, knowledge: Optional[str] = None, tools: Optional[list[BaseTool]] = None, intermediate_msgs: Optional[list[BaseMessage]] = None, response_format: Optional[LLMResponseFormat] = None) -> dict
Construct chat request parameters | 构造聊天请求参数
最终的会话排序如下: 1. 首条System Message 2. 用户历史会话内容 3. 当前输入前的提示 4. 当前输入 5. 当前输入后的提示 6. 中间消息
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_input
|
BaseMessage
|
Current input | 当前输入 |
required |
conversation
|
Optional[list[BaseMessage]]
|
Conversation history | 会话历史 |
None
|
elements
|
Optional[list[DocElement]]
|
Document elements | 文档元素 |
None
|
knowledge
|
Optional[str]
|
Related knowledge | 相关知识 |
None
|
tools
|
Optional[list[BaseTool]]
|
Available tool list | 可用的工具列表 |
None
|
intermediate_msgs
|
Optional[list[BaseMessage]]
|
Intermediate messages, it will be generated during llm work in chain, list tool's response or other system message, those messages will not save into memory, but usefully during chain work | 中间消息,它将在链式工作中生成,列表工具的响应或其他系统消息,这些消息不会保存到记忆体中, 但在链式工作中非常有用 |
None
|
response_format
|
Optional[LLMResponseFormat]
|
Response format | 响应格式。 如果在此指定响应格式,会覆盖LLM的默认响应格式。 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Request parameters | 请求参数 |
Source code in tfrobot/brain/chain/llms/base.py
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | |
complete
abstractmethod
¶
complete(current_input: BaseMessage, conversation: Optional[list[BaseMessage]] = None, elements: Optional[list[DocElement]] = None, knowledge: Optional[str] = None, tools: Optional[list[BaseTool]] = None, intermediate_msgs: Optional[list[BaseMessage]] = None, response_format: Optional[LLMResponseFormat] = None) -> LLMResult
Complete chat | 生成聊天结果
最终的会话排序如下: 1. 首条System Message 2. 用户历史会话内容 3. 当前输入前的提示 4. 当前输入 5. 当前输入后的提示 6. 中间消息
注意:子类在实现此方法时,应该在调用模型 API 时捕获上下文超长异常(如特定模型的错误码或异常消息), 并将其转换为 ContextTooLargeError 异常抛出。
注意:不在 LLM 生命周期内进行折叠重试,仅抛出异常,由 Chain 层捕获并触发 compact 流程。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_input
|
BaseMessage
|
current input | 当前输入 |
required |
conversation
|
Optional[list[BaseMessage]]
|
Conversation history | 会话历史 |
None
|
elements
|
Optional[list[DocElement]]
|
Document elements | 文档元素 |
None
|
knowledge
|
Optional[str]
|
Related knowledge | 相关知识 |
None
|
tools
|
Optional[list[BaseTool]]
|
Available tool list | 可用的工具列表 |
None
|
intermediate_msgs
|
Optional[list[BaseMessage]]
|
Intermediate messages, it will be generated during llm work in chain, list tool's response or other system message, those messages will not save into memory, but usefully during chain work | 中间消息,它将在链式工作中生成,列表工具的响应或其他系统消息,这些消息不会保存到记忆体中, 但在链式工作中非常有用 |
None
|
response_format
|
Optional[LLMResponseFormat]
|
Response format | 响应格式。 如果在此指定响应格式,会覆盖LLM的默认响应格式。 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
LLMResult |
LLMResult
|
The result of completion | 完成的结果 |
Raises:
| Type | Description |
|---|---|
ContextTooLargeError
|
当模型 API 返回上下文超长错误时,子类应捕获并转换为此异常抛出 |
Source code in tfrobot/brain/chain/llms/base.py
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 | |
async_complete
abstractmethod
async
¶
async_complete(current_input: BaseMessage, conversation: Optional[list[BaseMessage]] = None, elements: Optional[list[DocElement]] = None, knowledge: Optional[str] = None, tools: Optional[list[BaseTool]] = None, intermediate_msgs: Optional[list[BaseMessage]] = None, response_format: Optional[LLMResponseFormat] = None) -> LLMResult
Complete chat async | 异步生成聊天结果
最终的会话排序如下: 1. 首条System Message 2. 用户历史会话内容 3. 当前输入前的提示 4. 当前输入 5. 当前输入后的提示 6. 中间消息
注意:子类在实现此方法时,应该在调用模型 API 时捕获上下文超长异常(如特定模型的错误码或异常消息), 并将其转换为 ContextTooLargeError 异常抛出。
注意:不在 LLM 生命周期内进行折叠重试,仅抛出异常,由 Chain 层捕获并触发 compact 流程。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_input
|
BaseMessage
|
current input | 当前输入 |
required |
conversation
|
Optional[list[BaseMessage]]
|
Conversation history | 会话历史 |
None
|
elements
|
Optional[list[DocElement]]
|
Document elements | 文档元素 |
None
|
knowledge
|
Optional[str]
|
Related knowledge | 相关知识 |
None
|
tools
|
Optional[list[BaseTool]]
|
Available tool list | 可用的工具列表 |
None
|
intermediate_msgs
|
Optional[list[BaseMessage]]
|
Intermediate messages, it will be generated during llm work in chain, list tool's response or other system message, those messages will not save into memory, but usefully during chain work | 中间消息,它将在链式工作中生成,列表工具的响应或其他系统消息,这些消息不会保存到记忆体中, 但在链式工作中非常有用 |
None
|
response_format
|
Optional[LLMResponseFormat]
|
Response format | 响应格式。 如果在此指定响应格式,会覆盖LLM的默认响应格式。 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
LLMResult |
LLMResult
|
The result of completion | 完成的结果 |
Raises:
| Type | Description |
|---|---|
ContextTooLargeError
|
当模型 API 返回上下文超长错误时,子类应捕获并转换为此异常抛出 |
Source code in tfrobot/brain/chain/llms/base.py
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 | |
get_save_config
classmethod
¶
get_save_config() -> tuple[BaseSaverConfig, set]
生成用于save_to_dir使用的配置信息. Generate configuration information for use with save_to_dir.
LLM定义中属性默认值会使用inspect.Parameter.empty。这个值在pydantic中会被序列化,所以需要将其排除掉。 | The default value of the attribute in LLM definition will use inspect.Parameter.empty. This value will be serialized in pydantic, so it needs to be excluded.
Returns:
| Type | Description |
|---|---|
tuple[BaseSaverConfig, set]
|
Tuple[BaseSaverConfig, set] |
Source code in tfrobot/brain/chain/llms/base.py
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 | |
optimize_map_reduce_messages
staticmethod
¶
optimize_map_reduce_messages(intermediate_msgs: list[BaseMessage]) -> tuple[list[BaseMessage], bool, bool]
针对工具返回的调用,有可能存在Map-Reduce的情况,如果存在Map-Reduce,需要对中间消息进行优化,将其合并为一个消息,合并原则:
- 在出现Reduce消息之前,仅将最后一个Map消息作为Assistant ToolCall的返回,折叠中间的Map消息,仅给LLM生成针对此Map的答案。
- 在Reduce消息之前,处理Map消息的过程中,禁止工具调用。直到所有的map消息处理完毕(有可能存在多个工具调用,产生多个Map,需要等待所有Map执行完)。
- 遇到Reduce消息后,将之前所有Map消息的返回结果融入到Reduce消息模板中,利用Reduce消息生成Prompt,引导LLM生成汇总答案。
工具调用有可能成树型嵌套,所谓嵌套调用的判断标准:
- 当前Assistant消息包括ToolCalls调用。
- 当前Assistant消息紧跟着一个ToolReturn的消息,则当前的ToolCalls视为上一个ToolReturn调用ID的子调用
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
intermediate_msgs
|
list[BaseMessage]
|
Intermediate messages before optimize | 优化前的中间消息 |
required |
Returns:
| Type | Description |
|---|---|
tuple[list[BaseMessage], bool, bool]
|
tuple[list[BaseMessage], bool, bool]: (优化后的消息列表, 是否正在处理Map消息, Map消息是否设置了禁用工具) |
Source code in tfrobot/brain/chain/llms/base.py
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 | |
extract_tool_call_tree
staticmethod
¶
extract_tool_call_tree(intermediate_msgs: list[BaseMessage]) -> tuple[list[ToolCallTree], list[int]]
从intermediate_msgs中抽取所有的ToolCall树,同时返回被抽取的消息索引
第二个返回值是被抽取的消息索引位置,之所以有这个返回,是因为目前的消息树总是以带有TooCalls的AssistantMsg开始,因此会存在一些情况,比如部分无ToolCalls的 AssMsg(之所以是部分,是因为很多无ToolCalls的AssMsg作为ToolReturn的Response记录在树中),或者一些系统消息,在极端情况下,还可能存在一些ToolReturn在当前消息列表中没有归属, 这些消息都不会被记录在树中,也就不被追踪。因此需要返回这个索引,以便在后续的处理中,能够将这些消息记录下来,或者排除出去。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
intermediate_msgs
|
list[BaseMessage]
|
Intermediate messages | 中间消息 |
required |
Returns:
| Type | Description |
|---|---|
tuple[list[ToolCallTree], list[int]]
|
tuple[list[ToolCallTree], list[int]]: (ToolCall树列表, 被抽取的消息索引) | (ToolCall tree list, extracted message index) |
Source code in tfrobot/brain/chain/llms/base.py
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 | |
collapse_context ¶
collapse_context(current_input: BaseMessage, conversation: Optional[list[BaseMessage]] = None, elements: Optional[list[DocElement]] = None, knowledge: Optional[str] = None, tools: Optional[list[BaseTool]] = None, intermediate_msgs: Optional[list[BaseMessage]] = None, to_size: Optional[int] = None, current_size: Optional[int] = None, recursion_depth: int = 0) -> tuple[Optional[list[BaseMessage]], Optional[list[DocElement]], Optional[str], Optional[list[BaseMessage]], list[LLMResult]]
Collapse context | 折叠上下文 - 智能压缩版本
使用 LLM 智能压缩上下文,结合传统 Splitter 工具和 LLM 总结能力。 Uses LLM for smart context compression, combining traditional Splitter tools with LLM summarization.
压缩流程 | Compression flow: 1. 如果 current_size > to_size: - 先用 Splitter 预压缩到 to_size * 0.8,为 LLM 压缩留余量 - 再调用 LLM 进行智能压缩 2. 否则:直接调用 LLM 进行智能压缩 3. 如果 LLM 调用抛出 ContextTooLargeError: - 递归调用,目标大小衰减为 to_size * 0.9 - 最大递归深度 5 次
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_input
|
BaseMessage
|
用户最后输入 | User's last input |
required |
conversation
|
Optional[list[BaseMessage]]
|
会话历史 | Conversation history |
None
|
elements
|
Optional[list[DocElement]]
|
文档元素 | Document elements |
None
|
knowledge
|
Optional[str]
|
相关知识 | Related knowledge |
None
|
tools
|
Optional[list[BaseTool]]
|
可用的工具列表 | Available tools list |
None
|
intermediate_msgs
|
Optional[list[BaseMessage]]
|
中间消息 | Intermediate messages |
None
|
to_size
|
Optional[int]
|
折叠到的大小 | Target size to collapse to |
None
|
current_size
|
Optional[int]
|
当前上下文大小 | Current context size (auto-calculated if None) |
None
|
recursion_depth
|
int
|
递归深度计数器(内部使用)| Recursion depth counter (internal use) |
0
|
Returns:
| Type | Description |
|---|---|
tuple[Optional[list[BaseMessage]], Optional[list[DocElement]], Optional[str], Optional[list[BaseMessage]], list[LLMResult]]
|
tuple containing: - collapsed_conversation: Compressed conversation history - collapsed_elements: Compressed document elements - collapsed_knowledge: Compressed knowledge base - collapsed_intermediate_msgs: Compression summary message - llm_results: List of LLMResult objects from all successful LLM calls during compression |
Raises:
| Type | Description |
|---|---|
ValueError
|
无法确定目标大小或达到最大递归深度 | Cannot determine target size or max recursion depth reached |
Source code in tfrobot/brain/chain/llms/base.py
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 | |
async_collapse_context
async
¶
async_collapse_context(current_input: BaseMessage, conversation: Optional[list[BaseMessage]] = None, elements: Optional[list[DocElement]] = None, knowledge: Optional[str] = None, tools: Optional[list[BaseTool]] = None, intermediate_msgs: Optional[list[BaseMessage]] = None, to_size: Optional[int] = None, current_size: Optional[int] = None, recursion_depth: int = 0) -> tuple[Optional[list[BaseMessage]], Optional[list[DocElement]], Optional[str], Optional[list[BaseMessage]], list[LLMResult]]
Collapse context | 折叠上下文 - 智能压缩版本(异步) Async version of collapse_context.
使用 LLM 智能压缩上下文,结合传统 Splitter 工具和 LLM 总结能力。 详细的文档请参考 collapse_context 方法(同步版本)。 Uses LLM for smart context compression. See collapse_context for detailed documentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_input
|
BaseMessage
|
用户最后输入 | User's last input |
required |
conversation
|
Optional[list[BaseMessage]]
|
会话历史 | Conversation history |
None
|
elements
|
Optional[list[DocElement]]
|
文档元素 | Document elements |
None
|
knowledge
|
Optional[str]
|
相关知识 | Related knowledge |
None
|
tools
|
Optional[list[BaseTool]]
|
可用的工具列表 | Available tools list |
None
|
intermediate_msgs
|
Optional[list[BaseMessage]]
|
中间消息 | Intermediate messages |
None
|
to_size
|
Optional[int]
|
折叠到的大小 | Target size to collapse to |
None
|
current_size
|
Optional[int]
|
当前上下文大小 | Current context size (auto-calculated if None) |
None
|
recursion_depth
|
int
|
递归深度计数器(内部使用)| Recursion depth counter (internal use) |
0
|
Returns:
| Type | Description |
|---|---|
tuple[Optional[list[BaseMessage]], Optional[list[DocElement]], Optional[str], Optional[list[BaseMessage]], list[LLMResult]]
|
tuple containing: - collapsed_conversation: Compressed conversation history - collapsed_elements: Compressed document elements - collapsed_knowledge: Compressed knowledge base - collapsed_intermediate_msgs: Compression summary message - llm_results: List of LLMResult objects from all successful LLM calls during compression |
Raises:
| Type | Description |
|---|---|
ValueError
|
无法确定目标大小或达到最大递归深度 | Cannot determine target size or max recursion depth reached |
Source code in tfrobot/brain/chain/llms/base.py
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 | |
tokenize_str ¶
tokenize_str(text: str) -> list
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
|
required |
Returns:
Source code in tfrobot/brain/chain/llms/base.py
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 | |
calculate_token_count ¶
calculate_token_count(content: str | BaseMessage | DocElement) -> int
计算任意内容的 token 数量(支持多模态)
统一入口,自动分发到不同的计算逻辑: - str -> tokenize_str - BaseMessage -> _count_message_tokens - DocElement -> _count_element_tokens
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
str | BaseMessage | DocElement
|
可以是 str, BaseMessage, DocElement |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
token 数量 |
Source code in tfrobot/brain/chain/llms/base.py
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 | |
tile_image ¶
tile_image(uri: str, tile_size: int = 512, scale_shortest_side: Optional[int] = None) -> tuple[Optional[int], Optional[int], Optional[int]]
计算图片的瓦片数量(通用辅助方法,带缓存)
此方法提供类似 tokenize_str 的功能,用于图片瓦片计算。 子类可以调用此方法来获取瓦片信息,然后根据自己的计费规则计算 tokens。
处理流程: 1. 检查缓存(key 包含 uri, tile_size, scale_shortest_side) 2. 如果缓存未命中,获取图片尺寸 3. 如果指定了 scale_shortest_side,缩放图片使最短边等于该值 4. 计算需要多少个 tile_size × tile_size 的瓦片 5. 缓存并返回结果
典型用法: # OpenAI: 缩放到最短边 768px,然后分割为 512×512 瓦片 tiles_w, tiles_h, n = self.tile_image(uri, 512, 768) tokens = 85 + 170 * n
# Gemini: 直接分割为 512×512 瓦片
tiles_w, tiles_h, n = self.tile_image(uri, 512)
tokens = 258 * n
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
图片 URI |
required |
tile_size
|
int
|
瓦片大小(默认 512×512) |
512
|
scale_shortest_side
|
Optional[int]
|
缩放最短边到该值(None 表示不缩放) |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Optional[int], Optional[int], Optional[int]]
|
tuple[Optional[int], Optional[int], Optional[int]]: (tiles_w, tiles_h, total_tiles) 或 (None, None, None) |
示例: >>> # 1024×768 图片,缩放到最短边 768px >>> # 缩放后:1024×768 -> 1024×768(最短边已经是 768) >>> # 瓦片:(1024+511)//512 = 3, (768+511)//512 = 2 >>> tiles_w, tiles_h, n = self.tile_image(uri, 512, 768) >>> # 返回 (3, 2, 6)
Source code in tfrobot/brain/chain/llms/base.py
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 | |
get_current_tools_form_neural ¶
get_current_tools_form_neural() -> list[BaseTool]
从神经系统获取当前的工具列表 | Get current tools list from neural system
Returns:
| Type | Description |
|---|---|
list[BaseTool]
|
list[BaseTool]: Tools list | 工具列表. 如果没有连接到Neural,会返回空数组 |
Source code in tfrobot/brain/chain/llms/base.py
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 | |
connect_to_neural ¶
connect_to_neural(neural: Neural) -> None
连接到神经系统 | Connect to neural system
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
neural
|
Neural
|
Neural system | 神经系统 |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Source code in tfrobot/brain/chain/llms/base.py
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 | |
disconnect_from_neural ¶
disconnect_from_neural(neural: Neural) -> None
从神经系统断开连接 | Disconnect from neural system
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
neural
|
Neural
|
Neural system | 神经系统 |
required |
Returns:
| Type | Description |
|---|---|
None
|
None |
Source code in tfrobot/brain/chain/llms/base.py
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 | |
load_image_from_uri ¶
load_image_from_uri(uri: str, use_base64: bool = True) -> Optional[tuple[bytes, str]]
从URI加载图片并返回字节和MIME类型 | Load image from URI and return bytes and MIME type
此方法首先检查缓存,如果缓存未命中则尝试使用smart_open打开URI,如果失败则通过neural信号向外界求援。 子类可以覆盖此方法以提供自定义实现。
This method first checks the cache. If cache misses, it tries to open the URI using smart_open. If it fails, it sends a signal through neural to request external help. Subclasses can override this method to provide custom implementations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
图片的URI(可以是本地路径、URL等) | Image URI (can be local path, URL, etc.) |
required |
use_base64
|
bool
|
是否使用base64编码,默认为True | Whether to use base64 encoding, default is True |
True
|
Returns:
| Type | Description |
|---|---|
Optional[tuple[bytes, str]]
|
Optional[Tuple[bytes, str]]: 返回(字节数据, MIME类型)的元组,如果use_base64为True则返回base64编码的字节, 否则返回原始字节。如果加载失败返回None | Returns a tuple of (bytes data, MIME type). If use_base64 is True, returns base64 encoded bytes, otherwise returns raw bytes. Returns None if loading fails |
Source code in tfrobot/brain/chain/llms/base.py
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 | |
load_video_from_uri ¶
load_video_from_uri(uri: str, use_base64: bool = True) -> Optional[tuple[bytes, str]]
从URI加载视频并返回字节和MIME类型 | Load video from URI and return bytes and MIME type
此方法首先检查缓存,如果缓存未命中则尝试使用smart_open打开URI,如果失败则通过neural信号向外界求援。 子类可以覆盖此方法以提供自定义实现。
This method first checks the cache. If cache misses, it tries to open the URI using smart_open. If it fails, it sends a signal through neural to request external help. Subclasses can override this method to provide custom implementations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
视频的URI(可以是本地路径、URL等) | Video URI (can be local path, URL, etc.) |
required |
use_base64
|
bool
|
是否使用base64编码,默认为True | Whether to use base64 encoding, default is True |
True
|
Returns:
| Type | Description |
|---|---|
Optional[tuple[bytes, str]]
|
Optional[Tuple[bytes, str]]: 返回(字节数据, MIME类型)的元组,如果use_base64为True则返回base64编码的字节, 否则返回原始字节。如果加载失败返回None | Returns a tuple of (bytes data, MIME type). If use_base64 is True, returns base64 encoded bytes, otherwise returns raw bytes. Returns None if loading fails |
Source code in tfrobot/brain/chain/llms/base.py
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 | |
load_audio_from_uri ¶
load_audio_from_uri(uri: str, use_base64: bool = True) -> Optional[tuple[bytes, str]]
从URI加载音频并返回字节和MIME类型 | Load audio from URI and return bytes and MIME type
此方法首先检查缓存,如果缓存未命中则尝试使用smart_open打开URI,如果失败则通过neural信号向外界求援。 子类可以覆盖此方法以提供自定义实现。
This method first checks the cache. If cache misses, it tries to open the URI using smart_open. If it fails, it sends a signal through neural to request external help. Subclasses can override this method to provide custom implementations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
音频的URI(可以是本地路径、URL等) | Audio URI (can be local path, URL, etc.) |
required |
use_base64
|
bool
|
是否使用base64编码,默认为True | Whether to use base64 encoding, default is True |
True
|
Returns:
| Type | Description |
|---|---|
Optional[tuple[bytes, str]]
|
Optional[Tuple[bytes, str]]: 返回(字节数据, MIME类型)的元组,如果use_base64为True则返回base64编码的字节, 否则返回原始字节。如果加载失败返回None | Returns a tuple of (bytes data, MIME type). If use_base64 is True, returns base64 encoded bytes, otherwise returns raw bytes. Returns None if loading fails |
Source code in tfrobot/brain/chain/llms/base.py
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 | |
load_file_from_uri ¶
load_file_from_uri(uri: str, use_base64: bool = True) -> Optional[tuple[bytes, str]]
从URI加载文件并返回字节和MIME类型 | Load file from URI and return bytes and MIME type
此方法首先检查缓存,如果缓存未命中则尝试使用smart_open打开URI,如果失败则通过neural信号向外界求援。 子类可以覆盖此方法以提供自定义实现。
This method first checks the cache. If cache misses, it tries to open the URI using smart_open. If it fails, it sends a signal through neural to request external help. Subclasses can override this method to provide custom implementations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
文件的URI(可以是本地路径、URL等) | File URI (can be local path, URL, etc.) |
required |
use_base64
|
bool
|
是否使用base64编码,默认为True | Whether to use base64 encoding, default is True |
True
|
Returns:
| Type | Description |
|---|---|
Optional[tuple[bytes, str]]
|
Optional[Tuple[bytes, str]]: 返回(字节数据, MIME类型)的元组,如果use_base64为True则返回base64编码的字节, 否则返回原始字节。如果加载失败返回None | Returns a tuple of (bytes data, MIME type). If use_base64 is True, returns base64 encoded bytes, otherwise returns raw bytes. Returns None if loading fails |
Source code in tfrobot/brain/chain/llms/base.py
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 | |
validate_tool_by_tag_name ¶
validate_tool_by_tag_name(tool: BaseTool) -> bool
通过当前配置的 self.tool_filter 对工具进行校验,如果通过返回True,否则返回False
注意: 如果遇到非常tool_filter字符串等异常,会返回True,此举是为了尽可能保证工具的完整性,避免因为配置问题导致工具大面积丢失
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool
|
BaseTool
|
被校验的工具 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
是否校验成功 |
Source code in tfrobot/brain/chain/llms/base.py
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 | |
extract_context_size_from_error ¶
extract_context_size_from_error(exception: Exception) -> tuple[Optional[int], Optional[int]]
从 LLM API 异常中提取上下文大小信息(公开方法,带异常保护)| Extract context size from LLM API exception (public, with exception protection)
此方法是对 _extract_context_size_from_error 的包裹,确保无论子类如何实现都不会抛出异常。 所有异常都会被捕获并记录警告,然后返回 (None, None)。
This method wraps _extract_context_size_from_error to ensure that no exception is raised regardless of how subclasses implement it. All exceptions are caught and logged as warnings, then returns (None, None).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exception
|
Exception
|
LLM API 抛出的异常 | Exception raised by LLM API |
required |
Returns:
| Type | Description |
|---|---|
tuple[Optional[int], Optional[int]]
|
tuple[Optional[int], Optional[int]]: (current_size, target_size) | 当前大小和目标大小 |
Source code in tfrobot/brain/chain/llms/base.py
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 | |