跳转至

Python API

当你的代码与 OpenSRE 运行在同一台机器上,且希望在不调用 CLI 的情况下获得智能体响应时,请使用 Python API。如需网络访问,请使用 HTTP API。如需提供自己的输出接收器、工具、提示词或错误报告,并让一个智能体跨多轮运行,请参阅 托管智能体。

OpenSRE 作为日常循环中的队友

OpenSRE 作为自主工程队友,直接嵌入你的日常运维工作流中。与其将智能体视为孤立的聊天界面,你可以将 Python API 嵌入定时 cron 任务、CI/CD 流水线和自动化事件分诊循环中,以执行重复性任务——审计仓库健康状况、分诊生产告警,并向 Slack、webhook 或工单系统等团队渠道发送摘要。

先决条件

独立 CLI 安装程序不提供可导入的包。请从源代码检出安装:

git clone https://github.com/Tracer-Cloud/opensre.git
cd opensre && make install

一次性配置一个提供商(opensre onboard)——会话 API 会复用与 CLI 相同的配置和凭据。使用 uv run python your_script.py 在检出的环境中运行你的脚本。

在首次轮次之前注册适配器:

from infrastructure.process.boot import EMBEDDED_PROFILE
from surfaces.shared.process_boot import configure_process

configure_process(EMBEDDED_PROFILE)

日常工程配方

配方 1:查询仓库与工作流指标

使用 session.chat() 查询已配置的开发者工具和可观测性数据源(例如 GitHub Star 增长速度、PR 积压、部署状态):

from core.agent_harness import AgentSession
from infrastructure.process.boot import EMBEDDED_PROFILE
from surfaces.shared.process_boot import configure_process

# 1. 每个进程仅注册一次工具和适配器插件
configure_process(EMBEDDED_PROFILE)

# 2. 启动一个连接到已配置集成的进程内会话
session = AgentSession.start()

# 3. 查询仓库趋势或指标(需要已配置 GitHub 集成)
result = session.chat("what's our GitHub star velocity over the last 7 days?")
action = result.action_result
if (
    result.cancelled
    or action.hit_iteration_cap
    or action.accounting_status != "completed"
    or not result.primary_response_text
):
    raise RuntimeError(f"Turn failed: {result.primary_response_text or 'no response produced'}")

print(result.primary_response_text)

配方 2:自动化告警分诊

将来自 alertmanager、webhook 或监控系统的原始告警负载作为一次聊天轮次交给智能体——它会调用你已连接的集成来收集上下文,并根据其发现作答:

import json

from core.agent_harness import AgentSession
from infrastructure.process.boot import EMBEDDED_PROFILE
from surfaces.shared.process_boot import configure_process

configure_process(EMBEDDED_PROFILE)
session = AgentSession.start()

alert_payload = {
    "alert_name": "HighLatency",
    "service": "checkout-api",
    "severity": "warning",
    "description": "p99 latency exceeded 1200ms in us-east-1",
}

result = session.chat(f"Triage this alert:\n{json.dumps(alert_payload)}")
action = result.action_result
if (
    result.cancelled
    or action.hit_iteration_cap
    or action.accounting_status != "completed"
    or not result.primary_response_text
):
    raise RuntimeError(f"Triage failed: {result.primary_response_text or 'no response produced'}")
print(result.primary_response_text)

一个 API——chat

嵌入模式和一次性 opensre ask 均使用 chat。网关和交互式 shell 则不是:它们在 SessionAgentPool 中为每个会话保留一个智能体,并调用 handle。请参阅 托管智能体。

from core.agent_harness import AgentSession
from infrastructure.process.boot import EMBEDDED_PROFILE
from surfaces.shared.process_boot import configure_process

configure_process(EMBEDDED_PROFILE)

session = AgentSession.start()
result = session.chat("why is checkout-api slow?")
action = result.action_result
if (
    not result.cancelled
    and not action.hit_iteration_cap
    and action.accounting_status == "completed"
    and result.primary_response_text
):
    print(result.primary_response_text)

或者使用下面这行代码,它会为你接好相同的启动步骤:

from surfaces.embedded import start_embedded_session

session = start_embedded_session()

AgentSession.start() 会解析环境、打开会话,并按标准接口附加一个智能体——即交互式 shell 使用的相同工具和提示词。它不会注册适配器(core 可能无法导入其上层宿主);请先调用 configure_process,或使用 start_embedded_session。

answered 表示 primary_response_text 非空。一次失败的模型调用仍会填充该文本:action_result.accounting_status 为 "not_run",stop_reason 为 "error"。当 accounting 已完成、该轮次未被取消且未达到迭代上限时,可信任该文本。

内部接缝(不适用于宿主)

聊天宿主终止于 dispatch_chat_turn → run_turn。不要创造并行的公共入口点。

无人值守的每日交付与后台循环

对于重复性的日常工作流(例如定时晨间摘要或 CI 健康检查),启动一个进程内会话,并将发现转发到团队渠道:

from core.agent_harness import AgentSession
from infrastructure.process.boot import EMBEDDED_PROFILE
from surfaces.shared.process_boot import configure_process

configure_process(EMBEDDED_PROFILE)

session = AgentSession.start()

result = session.chat("summarize critical alerts and deployment changes from the last 24h")
action = result.action_result
if (
    result.cancelled
    or action.hit_iteration_cap
    or action.accounting_status != "completed"
    or not result.primary_response_text
):
    raise RuntimeError(f"Scheduled digest failed: {result.primary_response_text or 'no response produced'}")

summary = result.primary_response_text
# 将摘要转发到团队通知 webhook(Slack、电子邮件或工单系统)
print("Delivering daily digest:\n", summary)

在交互式 shell 中,周期性无人值守运行由 /loops 管理——每个循环会将其结果发送到 OpenSRE 可触达的句柄 (Telegram、Slack 和本地 shell 收件箱)。

对话

每次 chat 调用都是同一会话中的一个回合,因此后续追问能看到更早的 上下文:

session.chat("list unresolved Sentry issues from the last 24 hours")
result = session.chat("which of those affect checkout?")

要恢复现有会话,请传入其 ID:

from core.agent_harness import SessionConfig
from surfaces.embedded import start_embedded_session

session = start_embedded_session(SessionConfig(session_id="abc123"))

运行直到目标完成

当单个请求可能需要多个智能体回合时,请使用 chat_until_goal。传入一个 显式的 SessionGoal,使完成条件、检查清单和回合上限 不依赖于第一个回合去推断它们:

from core.agent_harness import AgentSession
from core.agent_harness.session_goal import SessionGoal
from infrastructure.process.boot import EMBEDDED_PROFILE
from surfaces.shared.process_boot import configure_process

configure_process(EMBEDDED_PROFILE)
session = AgentSession.start()

outcome = session.chat_until_goal(
    "Audit active production alert rules and summarize risky thresholds.",
    goal=SessionGoal(
        condition=(
            "Every active production alert rule has been checked and risky "
            "thresholds have been summarized."
        ),
        checklist=(
            "List active production alert rules",
            "Check each threshold and evaluation window",
            "Summarize risky thresholds",
        ),
        max_outer_turns=5,
    ),
)

print(outcome.goal.status)
print(outcome.turn_count)
last = outcome.last_result
if (
    not last.cancelled
    and not last.action_result.hit_iteration_cap
    and last.action_result.accounting_status == "completed"
    and last.primary_response_text
):
    print(last.primary_response_text)

当目标达成、暂停、取消、清除,或其回合预算耗尽时,循环会停止。结果包含最终的 goal、来自 chat 的 last_result 以及 turn_count。如果不传 goal=,第一个 action 回合必须附加一个目标;否则 chat_until_goal 会在那一个 回合后返回。使用 cancel_requested 在回合之间停止,并使用 on_progress 接收 检查清单更新。

Prompt 界面

智能体会从会话中组装其 Prompt——系统 Prompt、已连接的 集成、记忆、任务计划以及更早的回合——因此无需传入 Prompt 文本。你所选择的是回合运行所在的界面: interactive_shell(默认)、headless_cli 或 gateway。界面 决定 Prompt 中与界面相关的部分,例如设置信息以及 智能体是否可以打开菜单。

from core.agent_harness import AgentSession, SessionConfig
from infrastructure.process.boot import EMBEDDED_PROFILE
from surfaces.shared.process_boot import configure_process

configure_process(EMBEDDED_PROFILE)
session = AgentSession.start(SessionConfig(), surface="headless_cli")

一个 prompts= provider——SessionConfig(prompts=…),或下面自定义端口路径中的 DefaultHeadlessBuild.agent(prompts=…)——会改为指定界面。它实现 core.agent_harness.ports.PromptContextProvider, 其唯一方法是 surface()。如果省略, 则使用 core.agent_harness.spi.defaults.DefaultPromptContextProvider。

自定义输出与端口

start() 会缓冲所有输出。若要自行捕获工具进度(例如 流式传输到 websocket),请先启动进程(见上面的代码片段),然后 构建智能体并传入你自己的 sink:

from core.agent_harness import AgentSession, SessionConfig
from core.agent_harness.runtime import DefaultHeadlessBuild
from core.agent_harness.turns.headless_adapters import BufferOutputSink

session = AgentSession(SessionConfig())
startup = session.startup()
sink = BufferOutputSink()
agent = DefaultHeadlessBuild(session=startup.session, output=sink).agent(
    prompts=my_provider,  # optional — same port as SessionConfig.prompts
)
session.attach_agent(agent)

session.chat("summarize open incidents")
print(sink.lines)      # rendered output lines
print(sink.streamed)   # streamed answer chunks

任何实现 OutputSink 协议的对象 (core.agent_harness.ports.OutputSink:print、render_response_header、 render_error、stream)都可以替换 BufferOutputSink。 DefaultHeadlessBuild 还接受自定义 logger、console 和 Prompt 界面;其 agent() 接受你自己的工具 provider(tools=,通常是已配置的 DefaultToolProvider)以及 gather 端口——参见其 docstring。

外部工具

在首次查找工具之前注册一个包:

from tools.registry import register_external_tool_package
import my_agent_tools

register_external_tool_package(my_agent_tools)

要求:

  1. 当 action 循环应能调用这些工具时,使用 surfaces=("action",) 声明工具。 @tool 的默认值是 ("chat",)。
  2. 工具可以定义在包的 __init__.py 中,也可以定义在子模块中;两者都会在 注册后被发现。

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 op/opensre