Skip to content

0.2 变量、数据类型与 AI 数据处理

引言:数据是 AI Agent 的血液

想象一个 AI Agent 正在工作:它接收用户的文本输入(字符串),检查用户是否已授权(布尔值),计算需要调用 API 的次数(整数),追踪对话轮次(整数),并维护整个对话历史(列表)。

每一个这样的数据,都需要存储在变量中,并且必须使用正确的数据类型。这就是本节要学习的核心内容。

🎯 小白理解:什么是"数据"和"变量"?

想象你在玩一个游戏:

  • 数据 = 游戏中的各种信息(你的名字、金币数、血量、是否通关)
  • 变量 = 存放这些信息的"格子"(每个格子有个名字,方便找到)
游戏存档:
┌────────────────┬───────────────┐
│ 格子名(变量)   │ 存的东西(数据)│
├────────────────┼───────────────┤
│ player_name    │ "小明"         │
│ gold_coins     │ 1500          │
│ health         │ 85.5          │
│ is_vip         │ True          │
└────────────────┴───────────────┘

数据类型就是告诉计算机这个格子里放的是什么类型的东西:

  • 文字(字符串)还是数字?
  • 整数还是小数?
  • 是/否(布尔值)?

搞清楚类型很重要,因为计算机是"死板"的,"100"100 在它看来是完全不同的东西!

学习目标

  • ✅ 理解变量的本质:内存中的命名存储位置
  • ✅ 掌握 Python 的基本数据类型:int, float, str, bool
  • ✅ 学会使用类型注解编写专业代码
  • ✅ 理解动态类型与静态类型的区别
  • ✅ 将数据类型与 AI Agent 的实际应用场景关联

第一部分:变量——数据的容器

什么是变量?

变量是程序中用来存储数据的命名容器。你可以把它想象成一个带标签的盒子

python
# 创建一个名为 agent_name 的变量,存储字符串 "ResearchBot"
agent_name = "ResearchBot"

# 创建一个名为 max_iterations 的变量,存储整数 10
max_iterations = 10

# 创建一个名为 is_active 的变量,存储布尔值 True
is_active = True

💡 关键概念:在 Python 中,= 不是"等于",而是赋值运算符,意思是"把右边的值赋给左边的变量"。

🎯 小白理解:变量赋值就像贴标签

python
agent_name = "ResearchBot"

这行代码做了两件事:

  1. 在计算机内存里开辟一块空间,放入 "ResearchBot" 这个文字
  2. 给这块空间贴上 agent_name 的标签

之后,你只要说 agent_name,计算机就知道你指的是 "ResearchBot"

等号 = 的含义

  • 数学里的 =:表示"相等"(5 = 5,说明两边一样)
  • 编程里的 =:表示"赋值"(把右边的东西放到左边的盒子里)

所以 x = x + 1 在数学里是错的,但在编程里很正常——意思是"把 x 加 1 后的结果,重新放回 x 这个盒子"。

变量命名规则

必须遵守的规则(语法要求)

python
# ✅ 合法的变量名
agent_name = "Bot"
max_tokens = 1000
user_id_123 = "abc"
_private_var = "hidden"

# ❌ 非法的变量名
2agent = "Bot"        # 不能以数字开头
max-tokens = 1000     # 不能包含连字符
user id = "abc"       # 不能包含空格
class = "MyClass"     # 不能使用 Python 关键字

应该遵守的约定(PEP 8 风格指南)

python
# ✅ 推荐:使用 snake_case(小写+下划线)
user_message = "Hello"
api_key = "sk-xxx"
max_retry_count = 3

# ❌ 不推荐(虽然合法)
userMessage = "Hello"    # camelCase(留给 JavaScript)
UserMessage = "Hello"    # PascalCase(留给类名)
USERMESSAGE = "Hello"    # 全大写(留给常量)

🔗 与 Agent 的联系:LangChain 的源码严格遵循 snake_case 命名,例如 ChatOpenAI, create_react_agent, invoke_chain 等。

变量的动态类型特性

Python 是动态类型语言,变量的类型可以改变:

python
# 变量 x 初始是整数
x = 42
print(type(x))  # <class 'int'>

# 现在 x 变成了字符串
x = "Hello"
print(type(x))  # <class 'str'>

# 现在 x 又变成了列表
x = [1, 2, 3]
print(type(x))  # <class 'list'>

⚠️ 常见陷阱:虽然 Python 允许这样做,但在实际开发中强烈不推荐。一个变量应该始终保持同一种类型,否则代码难以维护。


第二部分:数字类型——Agent 的计算基础

整数(int)

整数用于表示没有小数部分的数字,在 AI Agent 中的典型用途:

python
# Token 数量
max_tokens: int = 2000
current_tokens: int = 1523

# 重试次数
max_retries: int = 3
retry_count: int = 0

# 对话轮次
conversation_turn: int = 5

# Python 3 的整数可以任意大
huge_number: int = 123456789012345678901234567890
print(huge_number)  # 没有溢出问题

浮点数(float)

浮点数用于表示带小数的数字:

python
# Agent 的置信度分数
confidence_score: float = 0.87

# API 调用延迟(秒)
response_time: float = 1.23

# 温度参数(控制 LLM 的随机性)
temperature: float = 0.7

# 科学计数法
large_float: float = 1.5e10  # 1.5 × 10^10
small_float: float = 3.2e-5  # 3.2 × 10^-5

数字运算

python
# 基本运算
a: int = 10
b: int = 3

print(a + b)   # 13 加法
print(a - b)   # 7  减法
print(a * b)   # 30 乘法
print(a / b)   # 3.333... 除法(结果总是 float)
print(a // b)  # 3  整除(向下取整)
print(a % b)   # 1  取余
print(a ** b)  # 1000 幂运算

# AI 开发中的实际应用
tokens_used: int = 1523
max_tokens: int = 2000
remaining_tokens: int = max_tokens - tokens_used  # 477

# 计算 token 使用率
usage_ratio: float = tokens_used / max_tokens  # 0.7615
print(f"Token 使用率: {usage_ratio:.2%}")  # Token 使用率: 76.15%

💡 关键概念/ 总是返回 float,即使两个操作数都是整数。如果需要整数结果,使用 //

类型转换

python
# int → float
x: int = 42
y: float = float(x)  # 42.0

# float → int(截断小数部分)
a: float = 3.14
b: int = int(a)  # 3(不是四舍五入!)

# str → int
user_input: str = "123"
number: int = int(user_input)  # 123

# str → float
score_str: str = "95.5"
score: float = float(score_str)  # 95.5

⚠️ 常见陷阱:如果字符串无法转换,会抛出 ValueError

python
try:
    num = int("hello")  # ❌ ValueError: invalid literal
except ValueError as e:
    print(f"转换失败: {e}")

第三部分:字符串——AI 的输入输出

🎯 小白理解:什么是字符串?

字符串 = 一串字符 = 文字内容

计算机只认识数字(0和1),为了让它能处理文字,我们发明了"字符串"这个概念。

简单说:用引号包起来的内容就是字符串

python
"Hello"      # 这是字符串
'World'      # 这也是字符串(单引号双引号都行)
"123"        # 这是字符串!不是数字!
123          # 这才是数字

为什么 AI 开发中字符串超级重要?

因为你和 AI 的所有交流都是通过文字进行的:

  • 你输入的问题 → 字符串
  • AI 返回的回答 → 字符串
  • 提示词模板 → 字符串
  • 几乎所有 API 的输入输出 → 字符串

字符串的本质

字符串(str)是 Python 中最重要的数据类型之一,特别是在 AI 开发中:

python
# 单引号和双引号等价
message1: str = 'Hello, AI!'
message2: str = "Hello, AI!"

# 三引号用于多行字符串
prompt: str = """
You are a helpful AI assistant.
Please answer the following question:
What is the meaning of life?
"""

# 包含引号的字符串
response: str = "The AI said: 'Hello, human!'"
response2: str = 'The AI said: "Hello, human!"'

🔗 与 Agent 的联系:LangChain 的提示词模板大量使用多行字符串。

字符串操作

python
# 字符串拼接
first_name: str = "Claude"
last_name: str = "AI"
full_name: str = first_name + " " + last_name  # "Claude AI"

# 字符串重复
separator: str = "-" * 20  # "--------------------"

# 字符串长度
message: str = "Hello, Agent!"
length: int = len(message)  # 13

# 字符串索引(从 0 开始)
text: str = "Python"
first_char: str = text[0]   # "P"
last_char: str = text[-1]   # "n"

# 字符串切片
text: str = "AI Agent Development"
substring: str = text[0:8]   # "AI Agent"
substring2: str = text[3:]   # "Agent Development"
substring3: str = text[:8]   # "AI Agent"
substring4: str = text[::2]  # "A gnDvlpet"(步长为 2)

F-String:现代字符串格式化

python
# 传统方式(不推荐)
name = "ResearchBot"
version = 2
message = "Agent name: " + name + ", version: " + str(version)

# f-string(推荐)
name: str = "ResearchBot"
version: int = 2
message: str = f"Agent name: {name}, version: {version}"
print(message)  # Agent name: ResearchBot, version: 2

# 在 f-string 中使用表达式
tokens: int = 1523
max_tokens: int = 2000
print(f"Token 使用: {tokens}/{max_tokens} ({tokens/max_tokens:.1%})")
# 输出:Token 使用: 1523/2000 (76.2%)

# 格式化数字
price: float = 0.002
print(f"API 价格: ${price:.4f}/1K tokens")
# 输出:API 价格: $0.0020/1K tokens

常用字符串方法

python
text: str = "  Hello, AI Agent!  "

# 转换大小写
print(text.upper())      # "  HELLO, AI AGENT!  "
print(text.lower())      # "  hello, ai agent!  "
print(text.title())      # "  Hello, Ai Agent!  "

# 去除空白
print(text.strip())      # "Hello, AI Agent!"
print(text.lstrip())     # "Hello, AI Agent!  "
print(text.rstrip())     # "  Hello, AI Agent!"

# 替换
new_text = text.replace("AI", "ML")  # "  Hello, ML Agent!  "

# 分割字符串
message: str = "apple,banana,cherry"
fruits: list[str] = message.split(",")  # ['apple', 'banana', 'cherry']

# 拼接字符串列表
words: list[str] = ["AI", "is", "awesome"]
sentence: str = " ".join(words)  # "AI is awesome"

# 检查子字符串
text: str = "LangChain and LangGraph"
print("LangChain" in text)    # True
print("AutoGPT" in text)       # False
print(text.startswith("Lang")) # True
print(text.endswith("Graph"))  # True

🔗 与 Agent 的联系:在处理 LLM 的输出时,你经常需要 .strip() 去除多余空格,.split() 分割结构化数据。


第四部分:布尔值——Agent 的决策依据

🎯 小白理解:什么是布尔值?

布尔值就是是非题的答案——只有两个选项:

在 Python 里写作:True(真/是)和 False(假/否)

生活中的布尔值

  • 今天下雨了吗? → True(是)或 False(否)
  • 用户登录了吗? → TrueFalse
  • 余额够用吗? → TrueFalse

为什么布尔值重要?

因为计算机做决策靠的就是布尔值!

如果(用户已登录)那么 显示主页
如果(余额不足)那么 提示充值
如果(AI 回答正确)那么 继续下一步

这些"如果...那么..."判断,全都依赖布尔值来做出决策。

布尔类型(bool)

布尔值只有两个可能的值:TrueFalse(注意首字母大写)。

python
# Agent 状态标志
is_authenticated: bool = True
has_permission: bool = False
task_completed: bool = True

# 检查 API 密钥是否存在
api_key: str | None = "sk-xxx"
has_api_key: bool = api_key is not None  # True

比较运算符

python
# 数字比较
x: int = 10
y: int = 20

print(x == y)   # False  等于
print(x != y)   # True   不等于
print(x < y)    # True   小于
print(x > y)    # False  大于
print(x <= y)   # True   小于等于
print(x >= y)   # False  大于等于

# 字符串比较
agent1: str = "Alpha"
agent2: str = "Beta"
print(agent1 == agent2)  # False
print(agent1 < agent2)   # True(按字母顺序)

逻辑运算符

python
# and:两个条件都为 True 时结果才为 True
has_key: bool = True
has_permission: bool = True
can_access: bool = has_key and has_permission  # True

# or:任一条件为 True 时结果就为 True
is_admin: bool = False
is_owner: bool = True
can_modify: bool = is_admin or is_owner  # True

# not:取反
is_active: bool = True
is_inactive: bool = not is_active  # False

# 复杂条件
tokens_used: int = 1800
max_tokens: int = 2000
has_budget: bool = True

can_continue: bool = (tokens_used < max_tokens) and has_budget
print(can_continue)  # True

真值测试

在 Python 中,许多值在布尔上下文中会被视为 TrueFalse

python
# 被视为 False 的值
print(bool(0))          # False
print(bool(0.0))        # False
print(bool(""))         # False(空字符串)
print(bool([]))         # False(空列表)
print(bool({}))         # False(空字典)
print(bool(None))       # False

# 被视为 True 的值
print(bool(42))         # True
print(bool(-1))         # True
print(bool("Hello"))    # True
print(bool([1, 2]))     # True
print(bool({"a": 1}))   # True

# AI 开发中的实际应用
user_input: str = input("请输入内容: ")
if user_input:  # 等价于 if user_input != ""
    print("用户输入了内容")
else:
    print("用户没有输入")

第五部分:类型注解——现代 Python 的标准

🎯 小白理解:什么是类型注解?

类型注解就是给变量"贴上类型标签",告诉别人(和编辑器)这个变量应该存什么类型的数据。

没有类型注解

python
name = "小明"
age = 25

有类型注解

python
name: str = "小明"      # 明确告诉你:name 应该是字符串
age: int = 25           # 明确告诉你:age 应该是整数

类比:就像快递盒子上的"易碎品"、"此面朝上"标签,类型注解不会改变盒子里的东西,但能帮助处理的人(和程序)避免犯错。

为什么要写这些看起来"多余"的东西?

  1. 给未来的自己看:三个月后你可能忘了 x 应该是什么类型
  2. 给队友看:别人一眼就知道怎么用你的代码
  3. 让编辑器帮你检查错误:VS Code 会在你写错类型时提醒你
  4. 专业代码的标配:LangChain、LangGraph 的源码全都有类型注解

为什么需要类型注解?

Python 是动态类型语言,但这不意味着我们不应该关心类型。类型注解提供:

  1. 代码可读性:一眼看出变量的预期类型
  2. IDE 支持:更好的代码补全和错误检查
  3. 早期错误检测:在运行前发现类型错误
  4. 文档作用:类型就是最好的文档

🔗 与 Agent 的联系:LangChain 和 LangGraph 的源码 100% 使用类型注解。

基本类型注解

python
# 变量注解
name: str = "ResearchBot"
age: int = 2
temperature: float = 0.7
is_active: bool = True

# 函数注解
def calculate_tokens(text: str, model: str) -> int:
    """计算文本的 token 数量"""
    # 简化示例
    return len(text.split())

# 使用函数
message: str = "Hello, how are you?"
token_count: int = calculate_tokens(message, "gpt-4")

复合类型注解

python
from typing import List, Dict, Optional, Union, Tuple

# 列表类型
messages: list[str] = ["Hello", "Hi", "Hey"]
scores: list[float] = [0.9, 0.85, 0.92]

# 字典类型
config: dict[str, int] = {
    "max_tokens": 2000,
    "temperature": 1,
}

# Optional 类型(可能是 None)
api_key: Optional[str] = None  # 等价于 str | None
api_key = "sk-xxx"

# Union 类型(多种可能类型)
result: Union[str, int] = "success"  # 等价于 str | int
result = 200

# 元组类型
coordinates: tuple[float, float] = (40.7128, -74.0060)
rgb_color: tuple[int, int, int] = (255, 128, 0)

在 AI Agent 中的应用

python
from typing import Optional

def create_agent_config(
    model_name: str,
    temperature: float = 0.7,
    max_tokens: int = 2000,
    system_prompt: Optional[str] = None
) -> dict[str, Union[str, float, int]]:
    """
    创建 Agent 配置字典
    
    Args:
        model_name: 模型名称(如 "gpt-4")
        temperature: 温度参数,控制随机性(0-2)
        max_tokens: 最大 token 数
        system_prompt: 系统提示词(可选)
        
    Returns:
        配置字典
    """
    config: dict[str, Union[str, float, int]] = {
        "model": model_name,
        "temperature": temperature,
        "max_tokens": max_tokens,
    }
    
    if system_prompt:
        config["system_prompt"] = system_prompt
    
    return config

# 使用
agent_config = create_agent_config(
    model_name="gpt-4",
    temperature=0.5,
    system_prompt="You are a helpful assistant."
)
print(agent_config)

实战案例:构建 Agent 配置管理器

让我们综合运用所学知识,构建一个真实的 Agent 配置管理器:

python
"""
Agent 配置管理器
用于管理 AI Agent 的配置参数
"""

from typing import Optional


class AgentConfig:
    """Agent 配置类"""
    
    def __init__(
        self,
        name: str,
        model: str = "gpt-4",
        temperature: float = 0.7,
        max_tokens: int = 2000,
        max_retries: int = 3,
    ) -> None:
        """
        初始化 Agent 配置
        
        Args:
            name: Agent 名称
            model: 使用的模型
            temperature: 温度参数
            max_tokens: 最大 token 数
            max_retries: 最大重试次数
        """
        self.name: str = name
        self.model: str = model
        self.temperature: float = temperature
        self.max_tokens: int = max_tokens
        self.max_retries: int = max_retries
        self.is_active: bool = True
        self.total_requests: int = 0
        
    def get_summary(self) -> str:
        """获取配置摘要"""
        return f"""
Agent 配置摘要:
- 名称: {self.name}
- 模型: {self.model}
- 温度: {self.temperature}
- 最大Tokens: {self.max_tokens}
- 最大重试: {self.max_retries}
- 状态: {'激活' if self.is_active else '停用'}
- 总请求数: {self.total_requests}
        """.strip()
    
    def increment_requests(self) -> None:
        """增加请求计数"""
        self.total_requests += 1
    
    def calculate_cost(self, tokens_used: int) -> float:
        """
        计算 API 调用成本(简化示例)
        
        Args:
            tokens_used: 使用的 token 数量
            
        Returns:
            成本(美元)
        """
        # GPT-4 定价示例: $0.03/1K tokens(输入)
        cost_per_1k: float = 0.03
        cost: float = (tokens_used / 1000) * cost_per_1k
        return cost


def main() -> None:
    """主函数"""
    # 创建 Agent 配置
    config = AgentConfig(
        name="ResearchBot",
        model="gpt-4",
        temperature=0.5,
        max_tokens=4000,
    )
    
    # 打印配置摘要
    print(config.get_summary())
    
    # 模拟几次 API 调用
    for i in range(3):
        config.increment_requests()
        tokens: int = 1500 + i * 200
        cost: float = config.calculate_cost(tokens)
        print(f"\n请求 #{i+1}: 使用 {tokens} tokens, 成本 ${cost:.4f}")
    
    # 最终统计
    print(f"\n总请求数: {config.total_requests}")


if __name__ == "__main__":
    main()

运行结果

Agent 配置摘要:
- 名称: ResearchBot
- 模型: gpt-4
- 温度: 0.5
- 最大Tokens: 4000
- 最大重试: 3
- 状态: 激活
- 总请求数: 0

请求 #1: 使用 1500 tokens, 成本 $0.0450

请求 #2: 使用 1700 tokens, 成本 $0.0510

请求 #3: 使用 1900 tokens, 成本 $0.0570

总请求数: 3

本节总结

核心要点

  1. 变量:数据的命名容器,使用 snake_case 命名
  2. int: 整数,用于计数、索引等
  3. float: 浮点数,用于分数、百分比等
  4. str: 字符串,AI 的输入输出,使用 f-string 格式化
  5. bool: 布尔值,用于条件判断和状态标志
  6. 类型注解:现代 Python 的标准,提升代码质量

与 AI Agent 的联系

数据类型AI Agent 应用场景
inttoken 计数、重试次数、对话轮次
float置信度分数、温度参数、成本计算
str用户输入、LLM 输出、提示词模板
bool权限检查、状态标志、条件路由
list[str]消息历史、工具列表
dict配置参数、API 响应

下一节:0.3 控制流与决策逻辑

基于 MIT 许可证发布。内容版权归作者所有。