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

基础大语言模型封装 | 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
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
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: 提示词上下文信息
    """
    # 依据模板配置进行格式化
    prompt_ctx: PromptContext = PromptContext(
        user_input=UserInput(
            input=str(current_input.content),
            additional_info=current_input.additional_kwargs,
            attachments=collect_attachments_from_msg(current_input),
        ),
        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,且要求返回JsonSchema或JsonObject,且有examples字段,则在上下文中注入examples。
        # 其值为全局定义:LLM_JSON_RESULT_EXAMPLES_KEY
        if prompt_ctx.user_input.additional_info is None:
            prompt_ctx.user_input.additional_info = {}
        cast(dict, prompt_ctx.user_input.additional_info)[LLM_JSON_RESULT_EXAMPLES_KEY] = (
            json.dumps(response_format["examples"], indent=4, ensure_ascii=False)
            if not isinstance(response_format["examples"], list)
            else "\n---\n".join([json.dumps(e, indent=4, ensure_ascii=False) for e in response_format["examples"]])
        )
    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
    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)
    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
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
@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

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
@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:
    """
    Complete chat | 生成聊天结果

    最终的会话排序如下:
    1. 首条System Message
    2. 用户历史会话内容
    3. 当前输入前的提示
    4. 当前输入
    5. 当前输入后的提示
    6. 中间消息

    注意:子类在实现此方法时,应该在调用模型 API 时捕获上下文超长异常(如特定模型的错误码或异常消息),
    并将其转换为 ContextTooLargeError 异常抛出。

    注意:**不在 LLM 生命周期内进行折叠重试**,仅抛出异常,由 Chain 层捕获并触发 compact 流程。

    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:
        LLMResult: The result of completion | 完成的结果

    Raises:
        ContextTooLargeError: 当模型 API 返回上下文超长错误时,子类应捕获并转换为此异常抛出
    """
    ...

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
@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:
    """
    Complete chat async | 异步生成聊天结果

    最终的会话排序如下:
    1. 首条System Message
    2. 用户历史会话内容
    3. 当前输入前的提示
    4. 当前输入
    5. 当前输入后的提示
    6. 中间消息

    注意:子类在实现此方法时,应该在调用模型 API 时捕获上下文超长异常(如特定模型的错误码或异常消息),
    并将其转换为 ContextTooLargeError 异常抛出。

    注意:**不在 LLM 生命周期内进行折叠重试**,仅抛出异常,由 Chain 层捕获并触发 compact 流程。

    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:
        LLMResult: The result of completion | 完成的结果

    Raises:
        ContextTooLargeError: 当模型 API 返回上下文超长错误时,子类应捕获并转换为此异常抛出
    """
    ...

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
@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
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
@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
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
@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
 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
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
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
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

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
def tokenize_str(self, text: str) -> list:
    """

    Args:
        text:

    Returns:

    """
    import tiktoken

    try:
        enc = tiktoken.encoding_for_model(self.name)
    except KeyError:
        # 默认使用cl100k_base进行分词
        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
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
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
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
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
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
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
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
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
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
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
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
@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") 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
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
@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") 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
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
@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") 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
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
@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") 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
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
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
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
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