工具调用示例
演示 Agent 如何使用内置工具完成文件操作任务。
read_file + write_file 示例
import asyncio
from txcode_sdk import TxCodeClient
from txcode_sdk.types import StepInfo
def on_step(step: StepInfo):
if step.printMsg: print(step.printMsg)
async def main():
client = TxCodeClient(
api_key="sk-xxx",
base_url="https://api.deepseek.com/v1",
model="deepseek-chat",
agent_type="code",
work_dir=".",
)
result = await client.chat(
"请读取 README.md 的内容,然后创建一个 summary.txt 文件,用3句话总结。",
on_step=on_step,
)
print(f"\n结果: {result.success}")
print(f"回答: {result.answer}")
asyncio.run(main())
预期调用:read_file("README.md") → write_file("summary.txt", "...")
glob + read_file 示例
import asyncio
from txcode_sdk import TxCodeClient
from txcode_sdk.types import StepInfo
def on_step(step: StepInfo):
for i, tc in enumerate(step.tool_calls):
res = step.results[i] if i < len(step.results) else None
status = "✓" if res and res.success else "✗"
print(f" [{status}] {tc.name}: {str(tc.arguments)[:80]}")
async def main():
client = TxCodeClient(
api_key="sk-xxx", base_url="https://api.deepseek.com/v1",
model="deepseek-chat", agent_type="code", work_dir=".",
)
result = await client.chat(
"找到 src/ 下所有的 .py 文件,读取其中最小的一个文件,告诉我它做了什么。",
on_step=on_step,
)
print(f"\n{result.answer}")
asyncio.run(main())
错误处理示例
import asyncio
from txcode_sdk import TxCodeClient
from txcode_sdk.types import StepInfo
def on_step(step: StepInfo):
for i, tc in enumerate(step.tool_calls):
res = step.results[i] if i < len(step.results) else None
if res and res.success:
print(f" ✓ {tc.name}: {(res.output or '')[:100]}")
else:
print(f" ✗ {tc.name}: {(res.error if res else 'unknown')[:100]}")
async def main():
client = TxCodeClient(
api_key="sk-xxx", base_url="https://api.deepseek.com/v1",
model="deepseek-chat", agent_type="code", work_dir=".",
max_iterations=5,
)
result = await client.chat(
"读取不存在的文件 nonexistent.txt,然后告诉我结果",
on_step=on_step,
)
print(f"\n成功: {result.success}")
print(f"回答: {result.answer[:200]}")
asyncio.run(main())
完整项目示例
import asyncio
from txcode_sdk import TxCodeClient
from txcode_sdk.types import StepInfo
def on_step(step: StepInfo):
if step.reasoning:
print(f"\n[推理] {step.reasoning[:120]}")
for i, tc in enumerate(step.tool_calls):
res = step.results[i] if i < len(step.results) else None
status = "✓" if res and res.success else "✗"
params = {k: v for k, v in tc.arguments.items() if k in ("file_path", "pattern", "command")}
print(f" [{status}] {tc.name}: {params}")
async def main():
client = TxCodeClient(
api_key="sk-xxx", base_url="https://api.deepseek.com/v1",
model="deepseek-chat", agent_type="code", work_dir=".",
)
result = await client.chat(
"分析这个 Python 项目的结构:1. 用 glob 找到所有 .py 文件 2. 用 bash 运行 pytest 3. 总结项目状况",
on_step=on_step,
)
print(f"\n{'='*50}")
print(result.answer)
asyncio.run(main())