一、前言
上一篇我们成功升级了 Azure Agent,实现了「多工具支持」和「多轮记忆」两大核心功能,摆脱了'单一文本总结、无上下文记忆'的局限,让 Agent 从基础工具升级为实用型智能助手。同时掌握了 Agent 的模块化扩展逻辑——通过工具映射字典,可灵活新增功能,无需重构核心代码。
这一篇我们进入「实战落地」阶段——结合职场高频需求,基于上一篇的模块化架构,打造一个能直接用的办公助手型 Agent,核心实现 3 个实用功能,全程复用你已有的 Azure GPT-4 模型和 azure_config.json 配置文件。
本篇核心目标:让 Agent 能'读文件、做总结、存结果',适配 Word、PDF、TXT 三种常见办公文件格式,解决职场中'手动读取文件、总结内容、保存结果'的重复工作,真正实现'一键操作、全程自动化'。同时,我们会优化 Agent 的稳定性和容错性,避免因文件格式错误、内容为空导致的程序崩溃,让实操更顺畅。
新增的「文件读取模块」和「结果保存模块」是本次实战的重点。
二、实操
安装依赖
# 补充文件读取依赖(支持 Word/PDF/TXT)
pip install python-docx # 读取 Word 文件(.docx 格式)
pip install PyPDF2 # 读取 PDF 文件(.pdf 格式)
# 结果保存依赖(复用之前的,若已安装可跳过)
pip install openpyxl # 保存为 Excel(可选,本次默认保存为 TXT,更简单)
完整代码
from openai import AzureOpenAI
import json
import os
from docx import Document # 读取 Word 文件
from PyPDF2 import PdfReader # 读取 PDF 文件
# ===================== 1. Azure 配置加载(完全复用 上一篇,无需修改) =====================
CONFIG_FILE = "azure_config.json"
def load_azure_config():
"""加载 Azure OpenAI 配置,沿用 上一篇的容错处理,避免配置错误导致程序崩溃"""
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
config = json.load(f)
# 验证核心配置是否完整(适配 GPT-4 部署,与 上一篇一致)
required_keys = ["azure_endpoint", "api_key", ]
(key config key required_keys):
config
:
()
Exception e:
()
config = {
: (),
: (),
: ()
}
(CONFIG_FILE, , encoding=) f:
json.dump(config, f, ensure_ascii=, indent=)
config
config = load_azure_config()
client = AzureOpenAI(
azure_endpoint=config[],
api_key=config[],
api_version=
)
() -> :
os.path.exists(file_path):
file_ext = os.path.splitext(file_path)[].lower()
:
file_ext == :
doc = Document(file_path)
content = .join([para.text para doc.paragraphs para.text.strip()])
file_ext == :
reader = PdfReader(file_path)
content = .join([page.extract_text() page reader.pages page.extract_text().strip()])
file_ext == :
(file_path, , encoding=) f:
content = f.read()
:
content.strip():
content
Exception e:
() -> :
:
response = client.chat.completions.create(
model=config[],
messages=[
{: , : },
{: , : }
],
temperature=
)
response.choices[].message.content.strip()
Exception e:
() -> :
datetime
file_name:
now = datetime.datetime.now().strftime()
file_name =
file_name.endswith():
file_name +=
:
(file_name, , encoding=) f:
f.write()
f.write( * + )
f.write(result)
Exception e:
:
():
.history = []
.last_file_path =
.tools = {: read_file, : summary_tool, : save_result}
() -> :
instruction_lower = instruction.lower()
file_path =
(ext instruction ext [, , ]):
re
pattern =
= re.search(pattern, instruction)
:
file_path = .group()
.last_file_path = file_path
:
file_path = .last_file_path
(keyword instruction_lower keyword [, ]):
, file_path, instruction
(keyword instruction_lower keyword [, , ]):
, file_path, instruction
(keyword instruction_lower keyword [, ]):
, , instruction
:
, file_path, instruction
() -> :
()
intent, file_path, raw_instruction = .parse_intent(instruction)
intent == :
file_path:
result =
:
result = .tools[](file_path)
result.startswith():
.last_file_path = file_path
.history.append((, file_path, result[:] + ))
intent == :
file_path:
result =
:
file_content = .tools[](file_path)
file_content.startswith():
result = file_content
:
result = .tools[](file_content)
.history.append((, file_path, result))
intent == :
.history:
result =
:
last_task, last_file, last_result = .history[-]
save_msg = .tools[](last_result)
result =
:
result =
.history.append((, raw_instruction, result))
(.history) > :
.history.pop()
result
__name__ == :
office_agent = OfficeAgent()
()
()
()
()
()
()
()
:
user_input = ()
user_input [, , ]:
()
result = office_agent.run(user_input)
()

