Skip to content

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, Generic[CompletionType, ChunkType]

基础大语言模型封装 | 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

TFL | Whether TFL mode is enabled

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
513
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
def construct_prompt_context(
    self,
    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:
    """
    构建出提示词渲染所使用的上下文环境。

    Args:
        current_input(BaseMessage): Current input | 当前输入
        conversation(Optional[list[BaseMessage]]): Conversation history | 会话历史
        elements(Optional[list[DocElement]]): Document elements | 文档元素
        knowledge(Optional[str]): Related knowledge | 相关知识
        tools(Optional[list[BaseTool]]): Available tool list | 可用的工具列表
        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 | 中间消息,它将在链式工作中生成,列表工具的响应或其他系统消息,这些消息不会保存到记忆体中,
            但在链式工作中非常有用
        response_format(Optional[LLMResponseFormat]): Response format | 响应格式
            如果指定了此参数,将会覆盖模型的默认响应格式

    Returns:
        PromptContext: 提示词上下文信息
    """
    # 构建 intermediate_trace 只读快照
    trace_snapshot = IntermediateTraceSnapshot()
    if isinstance(current_input, UserMessage) and current_input.intermediate_trace.records:
        trace_snapshot = IntermediateTraceSnapshot(
            records=tuple(current_input.intermediate_trace.records), view=current_input.intermediate_trace.view
        )
    # 依据模板配置进行格式化
    prompt_ctx: PromptContext = PromptContext(
        user_input=UserInput(
            input=str(current_input.content),
            msg_id=current_input.msg_id,
            conversation_id=current_input.conversation_id,
            additional_info=current_input.additional_kwargs,
            attachments=collect_attachments_from_msg(current_input),
            intermediate_trace=trace_snapshot,
        ),
        neural=self._neural,
    )
    response_format = response_format or self.response_format

    if response_format and response_format != inspect.Parameter.empty and response_format.get("examples"):
        # 如果当前类配置中有response_format,且有examples字段,注入到 runtime_vars 供 ResponseExamplesPrompt 渲染
        examples = response_format["examples"]
        prompt_ctx.runtime_vars["response_examples"] = (
            json.dumps(examples, indent=4, ensure_ascii=False)
            if not isinstance(examples, list)
            else "\n---\n".join([json.dumps(e, indent=4, ensure_ascii=False) for e in examples])
        )
    if response_format and response_format != inspect.Parameter.empty and response_format.get("on_schema_failure"):
        # 如果配置了 on_schema_failure,注入到 runtime_vars 供 SchemaFailurePrompt 渲染
        failure = response_format["on_schema_failure"]
        parts: list[str] = []
        if failure.get("prompt"):
            parts.append(failure["prompt"])
        if failure.get("schema"):
            parts.append(_schema_to_instruction(failure["schema"]))
        if parts:
            prompt_ctx.runtime_vars["schema_failure_instruction"] = "\n".join(parts)
    intermediate_msgs, is_mapping, forbidden_tools = (
        self.optimize_map_reduce_messages(intermediate_msgs)
        if intermediate_msgs
        else (intermediate_msgs, False, False)
    )
    # 尝试从当前神经网络中获取是否有连接的Drive。如果有Drive,可以尝试获取其当前可用的工具
    llm_tools = []
    if tools is not None and not forbidden_tools:
        llm_tools.extend(tools)
    if self._neural and not forbidden_tools and not llm_tools:
        llm_tools.extend(self.get_current_tools_form_neural())
    if self.enable_dsl_mode:
        # 如果当前是DSL模式,则需要保证当前工具中有至少有一个合法的DSL工具
        if not any(isinstance(t, DSLTool) for t in llm_tools):
            raise ValueError("DSL模式下,当前工具列表中至少需要有一个DSL工具")
        all_dsl_tools = set([t for t in llm_tools if isinstance(t, DSLTool)])
        # 将DSLTools管理的工具集合并到当前工具列表中,进而保证在DSLToolPrompt中正常渲染提示大模型。
        for dsl_t in all_dsl_tools:
            llm_tools.extend(dsl_t.all_tools)
    else:
        # 如果非DSL工具模式,则移除当前工具中DSLTool
        llm_tools = [t for t in llm_tools if not isinstance(t, DSLTool)]
    if llm_tools:
        llm_tools = [t for t in set(llm_tools) if self.validate_tool_by_tag_name(t)]
        prompt_ctx.tools = llm_tools  # type: ignore
    # Trace 注入:仅对 conversation 中最后 N 条"非空 trace"的 UserMessage 展开
    # N 由环境变量 TFROBOT_INJECT_TRACE_LAST_N 控制,默认 1
    # 注:若 current_input 恰好也在 conversation 中(同对象),跳过之——
    # 它会由下方 current_input 分支单独展开,避免 pre/post 被注入两次
    if self.inject_trace and conversation:
        last_n = _get_inject_trace_last_n()
        selected_ids: set[int] = set()
        remaining = last_n
        for m in reversed(conversation):
            if remaining <= 0:
                break
            if m is current_input:
                continue
            if isinstance(m, UserMessage) and m.intermediate_trace.records:
                selected_ids.add(id(m))
                remaining -= 1
        enriched: list[BaseMessage] = []
        for msg in conversation:
            if isinstance(msg, UserMessage) and id(msg) in selected_ids:
                pre, post = self._expand_trace_for_msg(msg)
                enriched.extend(pre)
                enriched.append(msg)
                enriched.extend(post)
            else:
                enriched.append(msg)
        conversation = enriched
    if conversation:
        prompt_ctx.conversation = Conversation(msgs=conversation)
    if elements:
        prompt_ctx.doc_elements = DocElements(elements=elements)
    if knowledge:
        prompt_ctx.knowledge = Knowledge(knowledge=knowledge)
    # current_input 的 trace 按时序分组:pre 追加到 conversation,post 插入 intermediate_msgs 前面
    if self.inject_trace and isinstance(current_input, UserMessage):
        pre, post = self._expand_trace_for_msg(current_input)
        if pre:
            conv_msgs = list(prompt_ctx.conversation.msgs) if prompt_ctx.conversation else []
            conv_msgs.extend(pre)
            prompt_ctx.conversation = Conversation(msgs=conv_msgs)
        if post:
            intermediate_msgs = post + list(intermediate_msgs or [])
    if intermediate_msgs:
        prompt_ctx.intermediate_msgs = intermediate_msgs
    return prompt_ctx

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
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
@abstractmethod
def construct_request_params(
    self,
    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. 中间消息

    Args:
        current_input(BaseMessage): Current input | 当前输入
        conversation(Optional[list[BaseMessage]]): Conversation history | 会话历史
        elements(Optional[list[DocElement]]): Document elements | 文档元素
        knowledge(Optional[str]): Related knowledge | 相关知识
        tools(Optional[list[BaseTool]]): Available tool list | 可用的工具列表
        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 | 中间消息,它将在链式工作中生成,列表工具的响应或其他系统消息,这些消息不会保存到记忆体中,
            但在链式工作中非常有用
        response_format(Optional[LLMResponseFormat]): Response format | 响应格式。
            如果在此指定响应格式,会覆盖LLM的默认响应格式。

    Returns:
        dict: Request parameters | 请求参数
    """
    ...

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

LLM 同步调用。ChatLLM 以模板方法形式提供具体实现,GenerationLLM 分支由子类自行实现。

Source code in tfrobot/brain/chain/llms/base.py
812
813
814
815
816
817
818
819
820
821
822
823
824
@abstractmethod
def complete(
    self,
    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:
    """LLM 同步调用。ChatLLM 以模板方法形式提供具体实现,GenerationLLM 分支由子类自行实现。"""
    ...

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

LLM 异步调用。ChatLLM 以模板方法形式提供具体实现,GenerationLLM 分支由子类自行实现。

Source code in tfrobot/brain/chain/llms/base.py
826
827
828
829
830
831
832
833
834
835
836
837
838
@abstractmethod
async def async_complete(
    self,
    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:
    """LLM 异步调用。ChatLLM 以模板方法形式提供具体实现,GenerationLLM 分支由子类自行实现。"""
    ...

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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
@classmethod
def get_save_config(cls) -> 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:
        Tuple[BaseSaverConfig, set]
    """
    save_config, exclude_fields = super().get_save_config()
    save_config.exclude_defaults = True
    return save_config, exclude_fields

optimize_map_reduce_messages staticmethod

optimize_map_reduce_messages(
    intermediate_msgs: list[BaseMessage],
) -> tuple[list[BaseMessage], bool, bool]

针对工具返回的调用,有可能存在Map-Reduce的情况,如果存在Map-Reduce,需要对中间消息进行优化,将其合并为一个消息,合并原则:

  1. 在出现Reduce消息之前,仅将最后一个Map消息作为Assistant ToolCall的返回,折叠中间的Map消息,仅给LLM生成针对此Map的答案。
  2. 在Reduce消息之前,处理Map消息的过程中,禁止工具调用。直到所有的map消息处理完毕(有可能存在多个工具调用,产生多个Map,需要等待所有Map执行完)。
  3. 遇到Reduce消息后,将之前所有Map消息的返回结果融入到Reduce消息模板中,利用Reduce消息生成Prompt,引导LLM生成汇总答案。

工具调用有可能成树型嵌套,所谓嵌套调用的判断标准:

  1. 当前Assistant消息包括ToolCalls调用。
  2. 当前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
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 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
@staticmethod
def optimize_map_reduce_messages(intermediate_msgs: list[BaseMessage]) -> tuple[list[BaseMessage], bool, bool]:
    """
    针对工具返回的调用,有可能存在Map-Reduce的情况,如果存在Map-Reduce,需要对中间消息进行优化,将其合并为一个消息,合并原则:

    1. 在出现Reduce消息之前,仅将最后一个Map消息作为Assistant ToolCall的返回,折叠中间的Map消息,仅给LLM生成针对此Map的答案。
    2. 在Reduce消息之前,处理Map消息的过程中,禁止工具调用。直到所有的map消息处理完毕(有可能存在多个工具调用,产生多个Map,需要等待所有Map执行完)。
    3. 遇到Reduce消息后,将之前所有Map消息的返回结果融入到Reduce消息模板中,利用Reduce消息生成Prompt,引导LLM生成汇总答案。

    工具调用有可能成树型嵌套,所谓嵌套调用的判断标准:

    1. 当前Assistant消息包括ToolCalls调用。
    2. 当前Assistant消息紧跟着一个ToolReturn的消息,则当前的ToolCalls视为上一个ToolReturn调用ID的子调用

    Args:
        intermediate_msgs (list[BaseMessage]): Intermediate messages before optimize | 优化前的中间消息

    Returns:
        tuple[list[BaseMessage], bool, bool]: (优化后的消息列表, 是否正在处理Map消息, Map消息是否设置了禁用工具)
    """
    # tool_call_trees tree使用dict表示,dict的结果是
    # [{
    #   'tool_call_id': str,
    #   'assistant_msg': BaseMessage,
    #   'tool_return_msgs': [(BaseMessage, Optional[BaseMessage])]
    # }]
    #  注意这个tool_return_msgs的pair,第一个元素是ToolReturn的消息,第二个元素是Assistant对这个ToolReturn做的反馈,可能为空。
    #  判断标准是第一个ToolReturn后的第一个Assistant消息作为反馈
    tool_call_trees, tracked_indexes = BaseLLM.extract_tool_call_tree(intermediate_msgs)
    # 整理完成tool_call_trees,开始重新Format intermediate_msgs
    is_mapping: bool = False
    forbidden_tool_call: bool = False
    new_intermediate_msgs = []
    poped_tree: list[str] = []  # 已经处理完的tree会pop至此

    def msg_tree_formatter(ass_msg: BaseMessage) -> list[BaseMessage]:
        """
        将一个 tool_call_tree结构重新格式化(展开)成一个预期的消息列表。这个展开有以下两个难点:

        1. Yield模式的工具调用,会产生多个ToolReturn消息,这些消息需要按照顺序展开,同时在ToolReturn中间可能掺杂着新的工具调用。
        2. AssMsg存在多工具调用的情况。

        多工具调用与Yield工具又可能存在混合,因此需要对这两种情况进行处理。解决方案主要思路是:

        1. 允许Tool返回消息进行拆分,因为一个Tool返回消息中存在多个ToolRes,每个ToolRes中的不同工具返回有的是最近的工具调用,有的可能是之前的Yield残留。
            因此,允许将Tool返回消息拆分成多个封装,进而展开。
        2. 不允许AssMsg拆分,虽然AssMsg存在多个工具调用,但不可以拆分AssMsg,这是为了保证大模型上下文顺序与语义的完整性与连贯性。

        Args:
            ass_msg (BaseMessage): 要展开的消息

        Returns:
            list[BaseMessage]: 重新格式化的消息列表
        """
        nonlocal poped_tree
        msgs: list[BaseMessage] = [ass_msg]  # 使用msgs存储展开结果
        # 如果某个AssMsg有多工具调用,则一次展开全部解决,因此需要将AssMsg中的所有tool_call_id全部追加到POP中去
        if ass_msg.tool_calls is None:
            raise ValueError("工具调用树提取异常。当前AssMsg无工具调用。")
        for tc_in_ass_msg in ass_msg.tool_calls:
            # 因为tool_call_trees是一个list,因此使用next配合条件,过滤到tool_call_trees中与tc_in_ass_msg.call_id相同的元素
            tc_tree: Optional[ToolCallTree] = next(
                (t for t in tool_call_trees if tc_in_ass_msg.call_id == t["tool_call_id"]), None
            )
            if tc_tree is None:
                raise ValueError(f"AssMsg对应的工具调用:{tc_in_ass_msg.call_id}未被工具调用树抽取函数正常抽取")
            if tc_in_ass_msg.call_id in poped_tree:
                return []
            poped_tree.append(tc_in_ass_msg.call_id)
            for ind, tool_return_pair in enumerate(tc_tree.get("tool_return_msgs", [])):
                tr_msg_in_tree: BaseMessage = tool_return_pair[0]
                tc_ids_in_tr_msg: list[str] = [
                    cast(str, cast(MessageMeta, t.msg_meta).call_id if isinstance(t, ToolReturn) else t)
                    for t in cast(list, tr_msg_in_tree.tool_reses)
                ]
                tc_ids_in_ass_msg: list[str] = [t.call_id for t in ass_msg.tool_calls]
                # 比较一下如果tool_return_msg中存在其它AssMsg要求的工具返回,则进行提取,将ToolReturnMsg中与当前AssMsg有关的消息提取出来形成一个新的BaseMessage
                # 使用Set进行集合运算,如果tc_ids_in_tr_msg全部归属于当前AssMsg,则直接使用tool_return_msg,如果只有部分归属于当前AssMsg,则提取这部分出来形成一个新的Msg
                if set(tc_ids_in_tr_msg).issubset(tc_ids_in_ass_msg):
                    # 如果tool_return_msg中的所有工具调用ID均属于当前AssMsg,则直接使用tool_return_msg
                    tool_return_msg = tr_msg_in_tree
                else:
                    # 如果只有部分工具调用ID属于当前AssMsg,则提取这些部分形成一个新的BaseMessage
                    partial_tool_reses = [
                        trm
                        for trm in cast(list[ToolReturn], tr_msg_in_tree.tool_reses)
                        if cast(MessageMeta, trm.msg_meta).call_id in tc_ids_in_ass_msg
                    ]
                    if partial_tool_reses:
                        # 创建一个新的BaseMessage用于封装部分工具返回
                        tool_return_msg = BaseMessage(
                            role=tr_msg_in_tree.role, content=tr_msg_in_tree.content, tool_reses=partial_tool_reses
                        )
                    else:
                        raise ValueError(
                            f"工具调用数结构异常,在同一个树中,Return消息与AssMsg消息的工具调用ID不一致: AssMsg: {tc_ids_in_ass_msg} "
                            f"VS ReturnMsg: {tc_ids_in_tr_msg}"
                        )
                ass_response_msg: Optional[BaseMessage] = tool_return_pair[1]
                last_tr_msg_in_tree: BaseMessage = tc_tree["tool_return_msgs"][-1][0]
                tc_ids_in_last_tr_msg_in_tree: list[str] = [
                    cast(str, cast(MessageMeta, t.msg_meta).call_id if isinstance(t, ToolReturn) else t)
                    for t in cast(list, last_tr_msg_in_tree.tool_reses)
                ]
                # 与处理第一条消息一样的逻辑,对最后一条消息也进行类似的处理
                if set(tc_ids_in_last_tr_msg_in_tree).issubset(tc_ids_in_ass_msg):
                    last_tool_return_msg = last_tr_msg_in_tree
                else:
                    # 如果只有部分工具调用ID属于当前AssMsg,则提取这些部分形成一个新的BaseMessage
                    last_partial_tool_reses = [
                        trm
                        for trm in cast(list, last_tr_msg_in_tree.tool_reses)
                        if cast(MessageMeta, trm.msg_meta).call_id in tc_ids_in_ass_msg
                    ]
                    if last_partial_tool_reses:
                        # 创建一个新的BaseMessage用于封装部分工具返回
                        last_tool_return_msg = BaseMessage(
                            role=tr_msg_in_tree.role,
                            content=tr_msg_in_tree.content,
                            tool_reses=last_partial_tool_reses,
                        )
                    else:
                        raise ValueError(
                            f"工具调用数结构异常,在同一个树中,Return消息与AssMsg消息的工具调用ID不一致: AssMsg: {tc_ids_in_ass_msg} "
                            f"VS ReturnMsg: {tc_ids_in_last_tr_msg_in_tree}"
                        )
                if (
                    ind < len(tc_tree.get("tool_return_msgs", [])) - 1
                    and all(
                        cast(MessageMeta, cast(ToolReturn, trm).msg_meta).category == MessageCategory.Map
                        for trm in cast(list, tool_return_msg.tool_reses)
                    )
                    and (not ass_response_msg or not ass_response_msg.tool_calls)
                    and not any(
                        (
                            cast(MessageMeta, cast(ToolReturn, ltr).msg_meta).category == MessageCategory.Reduce
                            and cast(MessageMeta, cast(ToolReturn, ltr).msg_meta).flat_map_history_during_reduce
                            is True
                        )
                        for ltr in cast(list, last_tool_return_msg.tool_reses)
                    )
                ):
                    # 只有当所有的返回数据均为Map消息并且LLM返回没有再次调用工具时才会直接折叠。
                    nonlocal is_mapping
                    is_mapping = True
                    continue
                if any(
                    cast(MessageMeta, cast(ToolReturn, trm).msg_meta).forbidden_tools_during_map
                    for trm in cast(list, tool_return_msg.tool_reses)
                ) and any(
                    cast(MessageMeta, cast(ToolReturn, ltrm).msg_meta).category == MessageCategory.Map
                    for ltrm in cast(list, last_tool_return_msg.tool_reses)
                ):
                    # 只要有任意一个Map过程要求禁用函数调用同时当前的map-reduce过程尚未完成,则会全局禁用
                    nonlocal forbidden_tool_call
                    forbidden_tool_call = True
                if tool_return_msg not in msgs:
                    msgs.append(tool_return_msg)
                if ass_response_msg and ass_response_msg not in msgs:
                    if ass_response_msg.tool_calls:
                        msgs.extend([m for m in msg_tree_formatter(ass_response_msg) if m not in msgs])
                    else:
                        msgs.append(ass_response_msg)
        return msgs

    for index, msg in enumerate(intermediate_msgs):
        # 本次遍历主要处理的是带有ToolCall的Assistant消息与ToolReturn消息,其它消息不做处理
        if index not in tracked_indexes:
            new_intermediate_msgs.append(msg)
        else:
            if msg.role == "assistant" and msg.tool_calls:
                for tc in msg.tool_calls:
                    tc_dict = next((t for t in tool_call_trees if t["tool_call_id"] == tc.call_id), None)
                    if tc_dict:
                        new_intermediate_msgs.extend(msg_tree_formatter(msg))
    return new_intermediate_msgs, is_mapping, forbidden_tool_call

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
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
@staticmethod
def 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在当前消息列表中没有归属,
        这些消息都不会被记录在树中,也就不被追踪。因此需要返回这个索引,以便在后续的处理中,能够将这些消息记录下来,或者排除出去。

    Args:
        intermediate_msgs (list[BaseMessage]): Intermediate messages | 中间消息

    Returns:
        tuple[list[ToolCallTree], list[int]]: (ToolCall树列表, 被抽取的消息索引) | (ToolCall tree list, extracted message
            index)
    """
    tool_call_trees: list[ToolCallTree] = []
    tracked_indexes: list[int] = []  # 记录ToolCallTrees追踪的索引
    for index, msg in enumerate(intermediate_msgs):
        if msg.role == "assistant" and msg.tool_calls:
            # 代表当前的消息是Assistant消息,且包含了ToolCall
            for tc in msg.tool_calls:
                if not any([tc.call_id == t["tool_call_id"] for t in tool_call_trees]):
                    # 如果当前的ToolCall不在树中,说明是新的树
                    tool_call_trees.append(
                        {
                            "tool_call_id": tc.call_id,
                            "assistant_msg": msg,
                            "tool_return_msgs": [],
                            "tool_name": tc.function.name,
                            "tool_call_parameter": tc.function.parameters,
                        }
                    )
                    tracked_indexes.append(index)
        elif msg.role == "tool":
            # 代表当前的消息是ToolReturn消息
            if msg.tool_reses:
                for tr in msg.tool_reses:
                    if isinstance(tr, ToolReturn):
                        for tree in tool_call_trees:
                            if tree["tool_call_id"] == cast(MessageMeta, tr.msg_meta).call_id:
                                ar_index, assistant_response = next(
                                    (
                                        (ai_index, x)
                                        for ai_index, x in enumerate(intermediate_msgs[index + 1 :])
                                        if x.role == "assistant"
                                    ),
                                    (None, None),
                                )
                                tree["tool_return_msgs"].append((msg, assistant_response))
                                tracked_indexes.append(index)
                                if ar_index is not None:
                                    tracked_indexes.append(ar_index + index + 1)
        elif msg.role == "function":
            if msg.function_res and isinstance(msg.function_res, ToolReturn):
                for tree in tool_call_trees:
                    if tree["tool_call_id"] == cast(MessageMeta, msg.function_res.msg_meta).call_id:
                        ar_index, assistant_response = next(
                            (
                                (ai_index, x)
                                for ai_index, x in enumerate(intermediate_msgs[index + 1 :])
                                if x.role == "assistant"
                            ),
                            (None, None),
                        )
                        tree["tool_return_msgs"].append((msg, assistant_response))
                        tracked_indexes.append(index)
                        if ar_index is not None:
                            tracked_indexes.append(ar_index + index + 1)
    return tool_call_trees, tracked_indexes

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
1263
1264
1265
1266
1267
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
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
def collapse_context(
    self,
    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 次

    Args:
        current_input: 用户最后输入 | User's last input
        conversation: 会话历史 | Conversation history
        elements: 文档元素 | Document elements
        knowledge: 相关知识 | Related knowledge
        tools: 可用的工具列表 | Available tools list
        intermediate_msgs: 中间消息 | Intermediate messages
        to_size: 折叠到的大小 | Target size to collapse to
        current_size: 当前上下文大小 | Current context size (auto-calculated if None)
        recursion_depth: 递归深度计数器(内部使用)| Recursion depth counter (internal use)

    Returns:
        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:
        ValueError: 无法确定目标大小或达到最大递归深度 | Cannot determine target size or max recursion depth reached
    """
    # ===== 获取目标大小 =====
    to_size = self._validate_and_get_to_size(to_size)

    # ===== 设置当前大小 =====
    if current_size is None:
        current_size = int(to_size * 1.2)  # 估算为目标的 1.2 倍,递归会自动调整

    # ===== 预压缩(当超过目标大小时)| Pre-compress when exceeding target size =====
    # TODO: 单元测试重点 - 验证 intermediate_msgs 在压缩中的处理逻辑
    if current_size > to_size:
        n_conversation, n_elements, n_knowledge, n_intermediate_msgs = self._pre_compress_context(
            current_size=current_size,
            to_size=to_size,
            conversation=conversation,
            elements=elements,
            knowledge=knowledge,
            intermediate_msgs=intermediate_msgs,
        )
    else:
        # 不需要预压缩,直接使用原始上下文 | No pre-compression needed, use original context
        n_conversation = copy.deepcopy(conversation)
        n_elements = copy.deepcopy(elements)
        n_knowledge = copy.deepcopy(knowledge)
        n_intermediate_msgs = copy.deepcopy(intermediate_msgs)

    # ===== 调用 LLM 智能压缩 | Call LLM for smart compression =====
    try:
        compact_prompt = self._build_compact_prompt(current_size=current_size, target_size=to_size)
        # 将压缩提示添加到预压缩后的 intermediate_msgs 中
        compact_intermediate_msgs: list[BaseMessage] = [compact_prompt]
        if n_intermediate_msgs:
            compact_intermediate_msgs = n_intermediate_msgs + compact_intermediate_msgs

        llm_result = self.complete(
            current_input=current_input,
            conversation=n_conversation,
            elements=n_elements,
            knowledge=n_knowledge,
            tools=None,
            intermediate_msgs=compact_intermediate_msgs,
            response_format={"type": "text"},
        )

        compressed_generation = llm_result.generations[0]

        # 清空所有上下文,只保留压缩结果
        n_conversation = None
        n_elements = None
        n_knowledge = None
        n_intermediate_msgs = [
            compressed_generation.to_message(),
            TextMessage(
                content=get_continue_work_prompt(self.locale), creator=cast(BaseUser, current_input.creator)
            ),
        ]

        return n_conversation, n_elements, n_knowledge, n_intermediate_msgs, [llm_result]

    except ContextTooLargeError as e:
        # ===== 递归处理 | Recursive handling =====
        if recursion_depth >= _MAX_COMPACT_RECURSION_DEPTH:
            raise ValueError(
                f"上下文压缩失败:已达到最大递归深度 {_MAX_COMPACT_RECURSION_DEPTH},"
                f"仍无法将上下文压缩到 {to_size} tokens 以内"
            ) from e

        # 目标大小衰减,简化递归逻辑 | Decay target size, simplify recursion logic
        new_to_size = int(to_size * _COMPACT_RATE_DECAY)

        return self.collapse_context(
            current_input=current_input,
            conversation=n_conversation,
            elements=n_elements,
            knowledge=n_knowledge,
            tools=tools,
            intermediate_msgs=n_intermediate_msgs,
            to_size=new_to_size,
            current_size=e.current_size,
            recursion_depth=recursion_depth + 1,
        )

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
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
async def async_collapse_context(
    self,
    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.

    Args:
        current_input: 用户最后输入 | User's last input
        conversation: 会话历史 | Conversation history
        elements: 文档元素 | Document elements
        knowledge: 相关知识 | Related knowledge
        tools: 可用的工具列表 | Available tools list
        intermediate_msgs: 中间消息 | Intermediate messages
        to_size: 折叠到的大小 | Target size to collapse to
        current_size: 当前上下文大小 | Current context size (auto-calculated if None)
        recursion_depth: 递归深度计数器(内部使用)| Recursion depth counter (internal use)

    Returns:
        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:
        ValueError: 无法确定目标大小或达到最大递归深度 | Cannot determine target size or max recursion depth reached
    """
    # ===== 获取目标大小 =====
    to_size = self._validate_and_get_to_size(to_size)

    # ===== 设置当前大小 =====
    if current_size is None:
        current_size = int(to_size * 1.2)  # 估算为目标的 1.2 倍,递归会自动调整

    # ===== 预压缩(当超过目标大小时)| Pre-compress when exceeding target size =====
    # TODO: 单元测试重点 - 验证 intermediate_msgs 在压缩中的处理逻辑
    if current_size > to_size:
        n_conversation, n_elements, n_knowledge, n_intermediate_msgs = self._pre_compress_context(
            current_size=current_size,
            to_size=to_size,
            conversation=conversation,
            elements=elements,
            knowledge=knowledge,
            intermediate_msgs=intermediate_msgs,
        )
    else:
        # 不需要预压缩,直接使用原始上下文 | No pre-compression needed, use original context
        n_conversation = copy.deepcopy(conversation)
        n_elements = copy.deepcopy(elements)
        n_knowledge = copy.deepcopy(knowledge)
        n_intermediate_msgs = copy.deepcopy(intermediate_msgs)

    # ===== 调用 LLM 智能压缩(异步版本)| Call LLM for smart compression (async) =====
    try:
        compact_prompt = self._build_compact_prompt(current_size=current_size, target_size=to_size)
        # 将压缩提示添加到预压缩后的 intermediate_msgs 中
        compact_intermediate_msgs: list[BaseMessage] = [compact_prompt]
        if n_intermediate_msgs:
            compact_intermediate_msgs = n_intermediate_msgs + compact_intermediate_msgs

        llm_result = await self.async_complete(
            current_input=current_input,
            conversation=n_conversation,
            elements=n_elements,
            knowledge=n_knowledge,
            tools=None,
            intermediate_msgs=compact_intermediate_msgs,
            response_format={"type": "text"},
        )

        compressed_generation = llm_result.generations[0]

        # 清空所有上下文,只保留压缩结果
        n_conversation = None
        n_elements = None
        n_knowledge = None
        n_intermediate_msgs = [
            compressed_generation.to_message(),
            TextMessage(
                content=get_continue_work_prompt(self.locale), creator=cast(BaseUser, current_input.creator)
            ),
        ]

        return n_conversation, n_elements, n_knowledge, n_intermediate_msgs, [llm_result]

    except ContextTooLargeError as e:
        # ===== 递归处理 | Recursive handling =====
        if recursion_depth >= _MAX_COMPACT_RECURSION_DEPTH:
            raise ValueError(
                f"上下文压缩失败:已达到最大递归深度 {_MAX_COMPACT_RECURSION_DEPTH},"
                f"仍无法将上下文压缩到 {to_size} tokens 以内"
            ) from e

        # 目标大小衰减,简化递归逻辑 | Decay target size, simplify recursion logic
        new_to_size = int(to_size * _COMPACT_RATE_DECAY)

        return await self.async_collapse_context(
            current_input=current_input,
            conversation=n_conversation,
            elements=n_elements,
            knowledge=n_knowledge,
            tools=tools,
            intermediate_msgs=n_intermediate_msgs,
            to_size=new_to_size,
            current_size=e.current_size,
            recursion_depth=recursion_depth + 1,
        )

tokenize_str

tokenize_str(text: str) -> list

对文本进行 tokenize,返回 token id 列表。

默认策略:先通过 tokenizer_registry 按模型名路由到专用本地 tokenizer, 无匹配时回退到 tiktoken。子类可 override 以使用更精确的 provider-specific tokenizer。

Parameters:

Name Type Description Default
text str

要分词的字符串

required

Returns:

Name Type Description
list list

token ids 列表

Source code in tfrobot/brain/chain/llms/base.py
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
def tokenize_str(self, text: str) -> list:
    """
    对文本进行 tokenize,返回 token id 列表。

    默认策略:先通过 tokenizer_registry 按模型名路由到专用本地 tokenizer,
    无匹配时回退到 tiktoken。子类可 override 以使用更精确的 provider-specific tokenizer。

    Args:
        text: 要分词的字符串

    Returns:
        list: token ids 列表
    """
    from tfrobot.brain.chain.llms.tokenizer_registry import resolve_tokenizer

    encoder = resolve_tokenizer(self.name)
    if encoder is not None:
        return encoder(text)

    import tiktoken

    try:
        enc = tiktoken.encoding_for_model(self.name)
    except KeyError:
        enc = tiktoken.get_encoding("cl100k_base")
    return enc.encode(text)

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
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
def calculate_token_count(self, content: str | BaseMessage | DocElement) -> int:
    """
    计算任意内容的 token 数量(支持多模态)

    统一入口,自动分发到不同的计算逻辑:
    - str -> tokenize_str
    - BaseMessage -> _count_message_tokens
    - DocElement -> _count_element_tokens

    Args:
        content: 可以是 str, BaseMessage, DocElement

    Returns:
        int: token 数量
    """
    match content:
        case str():
            # 纯文本内容
            return len(self.tokenize_str(content))

        case BaseMessage():
            # BaseMessage 对象 - 委托给内部方法处理
            return self._count_message_tokens(content)

        case DocElement():
            # DocElement 对象 - 委托给内部方法处理
            return self._count_element_tokens(content)

        case _:
            # 其他类型转为字符串计算(兜底逻辑)
            return len(self.tokenize_str(str(content)))

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
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
def tile_image(
    self, 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

    Args:
        uri: 图片 URI
        tile_size: 瓦片大小(默认 512×512)
        scale_shortest_side: 缩放最短边到该值(None 表示不缩放)

    Returns:
        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)
    """
    # 生成包含参数的缓存 key
    params = {"tile_size": tile_size, "scale_shortest_side": scale_shortest_side}
    cache_key = self._get_media_cache_key("image", uri, params)

    # 检查缓存中的 tiles
    entry = self._get_or_create_media_cache_entry("image", cache_key)
    tiles = entry.get("tiles")
    if tiles:
        return tiles  # type: ignore[return-value]

    # 获取图片尺寸
    width, height = self._get_image_dimensions(uri)

    if not width or not height:
        return None, None, None

    # 如果需要缩放
    if scale_shortest_side:
        scale_factor = scale_shortest_side / min(width, height)
        width = int(width * scale_factor)
        height = int(height * scale_factor)

    # 计算瓦片数量(向上取整)
    tiles_w = (width + tile_size - 1) // tile_size
    tiles_h = (height + tile_size - 1) // tile_size
    total_tiles = tiles_w * tiles_h

    # 更新缓存中的 tiles 字段
    self._update_media_cache_metadata(cache_key, tiles=(tiles_w, tiles_h, total_tiles))

    return tiles_w, tiles_h, total_tiles

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
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
def get_current_tools_form_neural(self) -> list[BaseTool]:
    """
    从神经系统获取当前的工具列表 | Get current tools list from neural system

    Returns:
        list[BaseTool]: Tools list | 工具列表. 如果没有连接到Neural,会返回空数组
    """
    if not self._neural:
        return []
    current_tools_in_drive: set[BaseTool] = set({})
    try:
        neural_res = self._neural.signal.send("get_current_tools_in_drive")
    except Exception as e:
        warnings.warn(f"Get current tools from neural failed: {e}")
        neural_res = []
    if neural_res:
        for _, tools_res in neural_res:
            if isinstance(tools_res, set):
                # 在此通过判断类型来排除某个Drive召回的时候可能出现错误
                current_tools_in_drive.update(tools_res)
    return list(current_tools_in_drive)

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
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
def connect_to_neural(self, neural: Neural) -> None:
    """
    连接到神经系统 | Connect to neural system

    Args:
        neural (Neural): Neural system | 神经系统

    Returns:
        None
    """
    self._neural = neural

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
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
def disconnect_from_neural(self, neural: Neural) -> None:
    """
    从神经系统断开连接 | Disconnect from neural system

    Args:
        neural (Neural): Neural system | 神经系统

    Returns:
        None
    """
    if self._neural is not neural:
        raise ValueError("The neural model is not the same as the connected neural model.")
    self._neural = None

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
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
2240
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
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
@tracer.start_as_current_span("load_image_from_uri")
def load_image_from_uri(self, 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.

    Args:
        uri (str): 图片的URI(可以是本地路径、URL等) | Image URI (can be local path, URL, etc.)
        use_base64 (bool): 是否使用base64编码,默认为True | Whether to use base64 encoding, default is True

    Returns:
        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
    """
    get_current_span().set_attributes({"uri": uri, "use_base64": use_base64})
    # 第零步:检查缓存 | Step 0: Check cache
    params = {"use_base64": use_base64}
    cache_key = self._get_media_cache_key("image", uri, params)

    # 检查缓存中的 bytes_data
    entry = self._get_or_create_media_cache_entry("image", cache_key)
    if entry.get("bytes_data"):
        return entry["bytes_data"]

    result = None

    # 第一步:尝试使用smart_open打开 | Step 1: Try to open using smart_open
    try:
        from urllib.parse import unquote

        import magic
        from smart_open import open as sopen

        uri = unquote(uri)
        with sopen(uri, "rb", transport_params=_SMART_OPEN_TRANSPORT_PARAMS) as f:
            img = f.read()
            mime_type = magic.from_buffer(img, True)
            # 根据use_base64参数决定是否编码 | Encode based on use_base64 parameter
            if use_base64:
                import base64

                img = base64.b64encode(img)
        result = (img, mime_type)
    except Exception as e:
        warnings.warn(f"Failed to load image using smart_open: {e}")

    # 第二步:如果smart_open失败,尝试通过neural信号求援 | Step 2: If smart_open fails, try neural signal
    if not result and self._neural:
        from tfrobot.neural.tf_apis import TF_LLM_LOAD_IMAGE_FROM_URI

        try:
            neural_res = self._neural.signal.send(
                TF_LLM_LOAD_IMAGE_FROM_URI.sync_api, uri=uri, use_base64=use_base64
            )
            if neural_res:
                for _, neural_result in neural_res:
                    if neural_result and isinstance(neural_result, tuple) and len(neural_result) == 2:
                        # 验证返回的结果格式是否正确 | Validate the result format
                        img_data, mime_type = neural_result
                        if isinstance(img_data, bytes) and isinstance(mime_type, str):
                            result = neural_result
                            break
        except Exception as e:
            warnings.warn(f"Failed to load image through neural signal: {e}")

    # 缓存结果 | Cache the result
    if result:
        entry["bytes_data"] = result
        entry["cached_at"] = time.time()

    # 第三步:如果都失败了,返回None | Step 3: If all attempts fail, return None
    return result

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
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
@tracer.start_as_current_span("load_video_from_uri")
def load_video_from_uri(self, 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.

    Args:
        uri (str): 视频的URI(可以是本地路径、URL等) | Video URI (can be local path, URL, etc.)
        use_base64 (bool): 是否使用base64编码,默认为True | Whether to use base64 encoding, default is True

    Returns:
        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
    """
    get_current_span().set_attributes({"uri": uri, "use_base64": use_base64})
    # 第零步:检查缓存 | Step 0: Check cache
    params = {"use_base64": use_base64}
    cache_key = self._get_media_cache_key("video", uri, params)

    # 检查缓存中的 bytes_data
    entry = self._get_or_create_media_cache_entry("video", cache_key)
    if entry.get("bytes_data"):
        return entry["bytes_data"]

    result = None

    # 第一步:尝试使用smart_open打开 | Step 1: Try to open using smart_open
    try:
        from urllib.parse import unquote

        import magic
        from smart_open import open as sopen

        uri = unquote(uri)
        with sopen(uri, "rb", transport_params=_SMART_OPEN_TRANSPORT_PARAMS) as f:
            video = f.read()
            mime_type = magic.from_buffer(video, True)
            # 根据use_base64参数决定是否编码 | Encode based on use_base64 parameter
            if use_base64:
                import base64

                video = base64.b64encode(video)
        result = (video, mime_type)
    except Exception as e:
        warnings.warn(f"Failed to load video using smart_open: {e}")

    # 第二步:如果smart_open失败,尝试通过neural信号求援 | Step 2: If smart_open fails, try neural signal
    if not result and self._neural:
        from tfrobot.neural.tf_apis import TF_LLM_LOAD_VIDEO_FROM_URI

        try:
            neural_res = self._neural.signal.send(
                TF_LLM_LOAD_VIDEO_FROM_URI.sync_api, uri=uri, use_base64=use_base64
            )
            if neural_res:
                for _, neural_result in neural_res:
                    if neural_result and isinstance(neural_result, tuple) and len(neural_result) == 2:
                        # 验证返回的结果格式是否正确 | Validate the result format
                        video_data, mime_type = neural_result
                        if isinstance(video_data, bytes) and isinstance(mime_type, str):
                            result = neural_result
                            break
        except Exception as e:
            warnings.warn(f"Failed to load video through neural signal: {e}")

    # 缓存结果 | Cache the result
    if result:
        entry["bytes_data"] = result
        entry["cached_at"] = time.time()

    # 第三步:如果都失败了,返回None | Step 3: If all attempts fail, return None
    return result

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
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
@tracer.start_as_current_span("load_audio_from_uri")
def load_audio_from_uri(self, 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.

    Args:
        uri (str): 音频的URI(可以是本地路径、URL等) | Audio URI (can be local path, URL, etc.)
        use_base64 (bool): 是否使用base64编码,默认为True | Whether to use base64 encoding, default is True

    Returns:
        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
    """
    get_current_span().set_attributes({"uri": uri, "use_base64": use_base64})
    # 第零步:检查缓存 | Step 0: Check cache
    params = {"use_base64": use_base64}
    cache_key = self._get_media_cache_key("audio", uri, params)

    # 检查缓存中的 bytes_data
    entry = self._get_or_create_media_cache_entry("audio", cache_key)
    if entry.get("bytes_data"):
        return entry["bytes_data"]

    result = None

    # 第一步:尝试使用smart_open打开 | Step 1: Try to open using smart_open
    try:
        from urllib.parse import unquote

        import magic
        from smart_open import open as sopen

        uri = unquote(uri)
        with sopen(uri, "rb", transport_params=_SMART_OPEN_TRANSPORT_PARAMS) as f:
            audio = f.read()
            mime_type = magic.from_buffer(audio, True)
            # 根据use_base64参数决定是否编码 | Encode based on use_base64 parameter
            if use_base64:
                import base64

                audio = base64.b64encode(audio)
        result = (audio, mime_type)
    except Exception as e:
        warnings.warn(f"Failed to load audio using smart_open: {e}")

    # 第二步:如果smart_open失败,尝试通过neural信号求援 | Step 2: If smart_open fails, try neural signal
    if not result and self._neural:
        from tfrobot.neural.tf_apis import TF_LLM_LOAD_AUDIO_FROM_URI

        try:
            neural_res = self._neural.signal.send(
                TF_LLM_LOAD_AUDIO_FROM_URI.sync_api, uri=uri, use_base64=use_base64
            )
            if neural_res:
                for _, neural_result in neural_res:
                    if neural_result and isinstance(neural_result, tuple) and len(neural_result) == 2:
                        # 验证返回的结果格式是否正确 | Validate the result format
                        audio_data, mime_type = neural_result
                        if isinstance(audio_data, bytes) and isinstance(mime_type, str):
                            result = neural_result
                            break
        except Exception as e:
            warnings.warn(f"Failed to load audio through neural signal: {e}")

    # 缓存结果 | Cache the result
    if result:
        entry["bytes_data"] = result
        entry["cached_at"] = time.time()

    # 第三步:如果都失败了,返回None | Step 3: If all attempts fail, return None
    return result

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
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
@tracer.start_as_current_span("load_file_from_uri")
def load_file_from_uri(self, 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.

    Args:
        uri (str): 文件的URI(可以是本地路径、URL等) | File URI (can be local path, URL, etc.)
        use_base64 (bool): 是否使用base64编码,默认为True | Whether to use base64 encoding, default is True

    Returns:
        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
    """
    get_current_span().set_attributes({"uri": uri, "use_base64": use_base64})
    # 第零步:检查缓存 | Step 0: Check cache
    params = {"use_base64": use_base64}
    cache_key = self._get_media_cache_key("file", uri, params)

    # 检查缓存中的 bytes_data
    entry = self._get_or_create_media_cache_entry("file", cache_key)
    if entry.get("bytes_data"):
        return entry["bytes_data"]

    result = None

    # 第一步:尝试使用smart_open打开 | Step 1: Try to open using smart_open
    try:
        from urllib.parse import unquote

        import magic
        from smart_open import open as sopen

        uri = unquote(uri)
        with sopen(uri, "rb", transport_params=_SMART_OPEN_TRANSPORT_PARAMS) as f:
            file_data = f.read()
            mime_type = magic.from_buffer(file_data, True)
            # 根据use_base64参数决定是否编码 | Encode based on use_base64 parameter
            if use_base64:
                import base64

                file_data = base64.b64encode(file_data)
        result = (file_data, mime_type)
    except Exception as e:
        warnings.warn(f"Failed to load file using smart_open: {e}")

    # 第二步:如果smart_open失败,尝试通过neural信号求援 | Step 2: If smart_open fails, try neural signal
    if not result and self._neural:
        from tfrobot.neural.tf_apis import TF_LLM_LOAD_FILE_FROM_URI

        try:
            neural_res = self._neural.signal.send(
                TF_LLM_LOAD_FILE_FROM_URI.sync_api, uri=uri, use_base64=use_base64
            )
            if neural_res:
                for _, neural_result in neural_res:
                    if neural_result and isinstance(neural_result, tuple) and len(neural_result) == 2:
                        # 验证返回的结果格式是否正确 | Validate the result format
                        file_data, mime_type = neural_result
                        if isinstance(file_data, bytes) and isinstance(mime_type, str):
                            result = neural_result
                            break
        except Exception as e:
            warnings.warn(f"Failed to load file through neural signal: {e}")

    # 缓存结果 | Cache the result
    if result:
        entry["bytes_data"] = result
        entry["cached_at"] = time.time()

    # 第三步:如果都失败了,返回None | Step 3: If all attempts fail, return None
    return result

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
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
def validate_tool_by_tag_name(self, tool: BaseTool) -> bool:
    """
    通过当前配置的 self.tool_filter 对工具进行校验,如果通过返回True,否则返回False

    注意:
        如果遇到非常tool_filter字符串等异常,会返回True,此举是为了尽可能保证工具的完整性,避免因为配置问题导致工具大面积丢失

    Args:
        tool (BaseTool): 被校验的工具

    Returns:
        bool: 是否校验成功
    """
    if self.tool_filter is None:
        return True

    from tfrobot.utils.logic_str_expression import LogicStrExpression

    try:
        logic_expr = LogicStrExpression(self.tool_filter)
    except ValueError as e:
        warnings.warn(f"构建逻辑表达字符串失败,详情: {e}")
        return True

    try:
        tags = tool.tags
        # 构建新的标签集合,确保不会因为 set.add 返回 None 而影响逻辑 | Build a new tag set to avoid None from set.add
        tag_set = set(tags) if tags else set()
        tag_set.add(tool.tool_name)
        return logic_expr.match(tag_set)
    except Exception as e:
        warnings.warn(f"逻辑表达字符串构建失败,详情: {e}")
        return True

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
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
def extract_context_size_from_error(self, 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).

    Args:
        exception(Exception): LLM API 抛出的异常 | Exception raised by LLM API

    Returns:
        tuple[Optional[int], Optional[int]]: (current_size, target_size) | 当前大小和目标大小
    """
    try:
        return self._extract_context_size_from_error(exception)
    except Exception as e:
        # 确保子类实现不会影响异常抛出 | Ensure subclass implementation does not affect exception raising
        warnings.warn(f"Error extracting context size from {type(exception).__name__}: {e}")
        return None, None