SuperAPI AI 工具集

opik

智能体与模型

查看项目

更新于 10-15 17:15

技能介绍

用途

Opik 是一个开源 LLM 可观测性平台。本技能是 Opik SDK 的参考文档,用于查询 SDK 的用法与概念。若需逐步为代码库添加埋点(检测框架、添加配置、发出并验证追踪),应使用面向任务的 opik-instrument 技能;若要构建并运行评估,应使用 opik-evaluate 技能。

核心概念

  • 追踪(trace):一次执行路径(一次请求 → 一次响应)。
  • 跨度(span):追踪内部的操作,构成层级结构。

跨度类型(span types)——仅以下取值有效:

类型 用途
general 编排、智能体入口点
llm 模型调用
tool 工具、检索、API / 数据库调用
guardrail 安全 / 校验检查

不要使用 retrieval 或任何其他值。

主要能力

Python 追踪

import opik

@opik.track(name="agent", type="general")
def agent(query: str) -> str:
    return generate(retrieve(query))

@opik.track(type="tool")
def retrieve(query): ...

@opik.track(type="llm")
def generate(ctx): ...

opik.flush_tracker()   # required in scripts

TypeScript 追踪

import { Opik } from "opik";
const client = new Opik({ projectName: "my-project" });

const trace = client.trace({ name: "agent", input: { query } });
const span = trace.span({ name: "llm-call", type: "llm" });
span.end({ output });
trace.end({ output });
await client.flush();

框架集成

优先使用集成而非手动 @opik.track——集成会自动捕获 token、模型和成本。模式包括(完整列表见 references/integrations.md):

  • wrap-the-client:track_openai(OpenAI())、track_anthropic(...)
  • global-enable:track_crewai(crew=crew)
  • callback:dspy.configure(callbacks=[OpikCallback()])
  • tracer:OpikTracer() 用于 LangChain / LangGraph / LlamaIndex
  • agent-specific:track_adk_agent_recursive(agent, OpikTracer())

LiteLLM 在 @opik.track 内(常见陷阱)

如果代码使用 litellm 且添加了 @opik.track,需在每次 completion 调用时通过 metadata 传入 current_span_data——否则 OpikLogger 会发出孤立的顶层追踪,而不是嵌套在你的跨度下。

from opik.opik_context import get_current_span_data

@opik.track
def call_llm(messages):
    return litellm.completion(
        model="gpt-4o", messages=messages,
        metadata={"opik": {"current_span_data": get_current_span_data()}},
    )

线程(对话)

用 thread_id 对轮次分组——一轮 = 一个追踪,共享 thread_id = 一个线程。用于聊天 / 多轮;单次调用可跳过。

@opik.track(entrypoint=True)
def handle(session_id: str, message: str) -> str:
    opik.update_current_trace(thread_id=session_id)
    return reply(message)

提示词库

用 client.get_prompt / create_prompt 对提示词进行版本化(聊天变体:get_chat_prompt / create_chat_prompt)。将模型 + 温度存入提示词 metadata,使其随文本一起版本化。在 @opik.track 函数内调用 get_prompt,使版本与追踪关联。

@opik.track(entrypoint=True)
def run(question: str) -> str:
    p = client.get_prompt(name="system") or client.create_prompt(
        name="system",
        prompt="You help with {{product}}.",
        metadata={"model": "gpt-4o", "temperature": 0.7},
    )
    return llm(p.format(product="Opik"), model=p.metadata["model"])

项目运行状况

连接 MCP 后,从项目而非其追踪开始:

read("project", "<project name or id>")

一次调用返回最近 7 天对比前 7 天的数据——追踪数、错误率、平均时长、总成本(仅 SDK 流量,即 Logs 页面四张卡片所示内容)——以及项目实际记录的评分名称和用量键,还有其中最新的实验、数据集、提示词版本和优化运行。since/until 可选择其他窗口;since="30d" 是 UI 默认打开的窗口。无追踪窗口的比率或平均值返回 null 而非 0,因为无样本的比率未定义,而“0% 错误”可能被当作可行动的建议。

然后归因变化而非复述:

list("project_metric", project_name="<project>", metric_type="trace_cost")
list("project_metric", project_name="<project>", metric_type="span_count",
     breakdown="model", since="30d")

行是时间桶而非记录——interval 为 hourly/daily/weekly/total,page/size/sort 不适用。schema("list.project_metric") 是指标列表、各指标含义及各自接受的分组;其中七个不接受任何分组。概览返回的评分名称是值得过滤的,list("score_name", project_name=…) 有其余部分。

搜索追踪

一种过滤语法 OQL 同时服务于托管 MCP 的 list 工具和 SDK 的 search_traces / search_spans / search_threads:

<field>[.<key>] <op> <value> [AND ...]
ops: = != > >= < <= contains not_contains starts_with ends_with is_empty is_not_empty in not_in

字符串用双引号,数字裸写,时长以毫秒计,日期为带时区的 ISO-8601 时刻("2026-09-08T10:00:00Z")。评分和字典接受键:feedback_scores.accuracy < 0.5、metadata.environment = "prod"。AND 是唯一连接符。

error_info is_not_empty AND duration > 5000
type = "llm" AND usage.total_tokens > 10000            # spans
feedback_scores.hallucination > 0.5 AND start_time >= "2026-09-08T00:00:00Z"

连接 MCP 后,优先使用 list——它还支持排序(sort="duration desc")、窗口(since="1h", "7d")和自由文本搜索(search="order-42"):

list(entity_type="trace", project_name="<project>", since="1h",
     filters="error_info is_not_empty", sort="duration desc")

追踪、跨度和线程列表默认添加 source = "sdk",除非你指定 source,因此评估器、playground 和实验追踪会被排除在外。被拒绝的过滤会返回修复方法;schema("list.trace")(或 list.span、list.thread、list.experiment)是完整的字段和操作符参考。

不使用 MCP 时,同一字符串传给 SDK:

client.search_traces(project_name="<project>", filter_string="error_info is_not_empty")

反模式

反模式 修复
跨度类型 retrieval / 自定义 使用 tool(或 general)
get_prompt 在 @opik.track 之外 在内部获取——否则无追踪关联
已弃用的 opik.Prompt / opik.Config 使用 client.get_prompt / 配置文件
litellm 未传 current_span_data 传入——否则产生孤立追踪
脚本中无 flush opik.flush_tracker() / await client.flush()

参考文件

主题 文件
Python SDK(异步、分布式、上下文) references/tracing-python.md
TypeScript SDK references/tracing-typescript.md
REST API references/tracing-rest-api.md
所有集成 references/integrations.md
核心概念(追踪、跨度、线程) references/observability.md
最佳实践(生命周期、监控、反模式) references/best-practices.md
智能体架构、可靠性、安全 references/agent-patterns.md
生产监控、告警、护栏 references/production.md
评估数据集与测试套件(参考) references/evaluation-datasets.md、references/evaluation-test-suites.md

适用场景与限制

适用于:查询 Opik SDK 的跨度类型、追踪用法、框架集成、线程与提示词库;为代码添加追踪;通过 MCP 或 SDK 搜索追踪与项目指标。

限制:本技能仅为 SDK 参考;逐步埋点应使用 opik-instrument 技能,构建评估应使用 opik-evaluate 技能。跨度类型仅限 general、llm、tool、guardrail 四种。脚本中必须调用 flush。关于收费、价格、平台支持范围等具体信息,资料中暂未提供。