1SKILL_REGISTRY: dict[str, dict] = {}
str
dict
isinstance()
1isinstance(block, dict)
block
True
False
in
"key" in block
适用数据类型(classinfo 参数):
int
float
bool
complex
list
tuple
set
bytes
bytearray
isinstance(block, (list, tuple, dict))
123# 多类型检查isinstance(42, (int, float)) # Trueisinstance("hello", Iterable) # True(可迭代对象)
.get()
1meta.get("name", d.name)
meta
"name"
d.name
与直接索引meta["name"]的区别:
meta["name"]
meta.get("name", default)
KeyError
getattr()
1getattr(block, "type", None)
"type"
None
AttributeError
block.type
适用对象类型:
12345678# 获取类的静态属性getattr(MyClass, "class_var", None)# 获取模块的函数getattr(math, "sin", None)# 获取字符串的方法getattr("hello", "upper", None)()
核心特点:
enumerate()
123for mi, msg in enumerate(messages): # mi 是索引(0, 1, 2...) # msg 是列表中的每个元素值
(index, element)
enumerate(iterable, start=0)
适用数据类型(所有可迭代对象):
123# 从1开始(常用于行号)for num, day in enumerate(weekdays, start=1): print(f"{num}: {day}")
推荐使用enumerate()而不是range(len()),因为代码更清晰、性能更优、适用于生成器。
range(len())
sorted()
1sorted(blocks, key=lambda p: len(str(p[1].get("content", ""))), reverse=True)
blocks
content
any()
1any(_block_type(block) == "tool_use" for block in content)
"tool_use"
1messages[:] = compact_history(messages)
messages
与messages = compact_history(messages)的区别:
messages = compact_history(messages)
messages = new_list
messages[:] = new_list
核心应用场景:AI Agent 的上下文压缩(Context Compaction),确保主循环中的 history 变量同步更新为压缩后的内容。
history
1234# 变量作用域:messages 只在 agent_loop 函数内部# 使用 messages[:] = ... 才能将改变作用到函数外部def agent_loop(messages): messages[:] = compact_history(messages) # 外部 history 同步更新
1lambda p: len(str(p[1].get("content", "")))
lambda 参数: 表达式
filter()
map()
key
与def定义函数对比:
def
lambda
return
pathlib.Path.mkdir()
1TOOL_RESULTS_DIR.mkdir(parents=True, exist_ok=True)
mkdir -p
四种参数组合:
parents
exist_ok
12def _block_type(block): return block.get("type") if isinstance(block, dict) else getattr(block, "type", None)
1has_tool_call = any(_block_type(block) == "tool_use" for block in content)
_block_type()