すべてのプロダクト
Search
ドキュメントセンター

Cloud Monitor:loongsuite-otel-util-genai と OpenTelemetry SDK を使用したカスタム計装の追加

最終更新日:Oct 29, 2026

アプリケーションを Application Real-Time Monitoring Service (ARMS) と連携させると、エージェントは一般的な AI フレームワークを自動的に計装し、コードを変更することなくトレースデータを収集します。ビジネスメソッドをトレースに含める必要がある場合は、loongsuite-otel-util-genai と OpenTelemetry SDK を使用してカスタム計装を実装できます。このトピックでは、loongsuite-otel-util-genai と OpenTelemetry Python SDK を使用してカスタム計装を実装し、カスタム属性を追加する方法について説明します。

ARMS エージェントがサポートする AI コンポーネントとフレームワークについては、以下をご参照ください。

前提条件

依存関係の追加

pip install -U "loongsuite-otel-util-genai>=0.6.1"

インストール後、opentelemetry.util.genai パッケージと ExtendedTelemetryHandler などの拡張インターフェイスが利用可能になります。バージョン 0.6.1 以降では、エージェントスパンのライフサイクル中に、エージェント名がダウンストリームの GenAI 子スパンに自動的に伝播されます。詳細については、loongsuite-otel-util-genai ドキュメントをご参照ください。

警告

Langfuse を使用しており、「Langfuse SDK と Alibaba Cloud Python エージェントの同時連携」で説明されているように OpenTelemetry API の計装を無効にしている場合は、このトピックのすべての from opentelemetry.xxx import 文 (付録の例を含む) のモジュールパスに aliyun. プレフィックスを追加してください。例えば、from opentelemetry.trace import get_tracer を from aliyun.opentelemetry.trace import get_tracer に変更します。

loongsuite-otel-util-genai と OpenTelemetry SDK の使用

loongsuite-otel-util-genai と OpenTelemetry SDK を使用すると、以下のことが可能になります。

  • Entry、Agent、Tool、ReAct Step などの GenAI セマンティックスパンの作成

  • OpenTelemetry SDK を使用した計装の追加とカスタムスパンの生成

  • スパンへのカスタム属性の追加

  • 現在のトレースコンテキストの取得と traceId の出力

用語

  • スパン:リクエスト内の特定の操作 (LLM 呼び出しやツール実行など) です。

  • SpanContext:traceId や spanId などの情報を含むトレースのコンテキストです。

  • 属性:モデル名やトークン使用量などのキー情報を記録するために使用されるスパン上の追加フィールドです。

  • ハンドラ:loongsuite-otel-util-genai が提供する ExtendedTelemetryHandler で、GenAI セマンティック規則に準拠したスパンを作成するために使用されます。

次の表は、loongsuite-otel-util-genai がサポートするすべてのスパンタイプの一覧です。このトピックでは、Entry、Agent、Tool、ReAct Step、LLM スパンの使用法に焦点を当てます。Embedding、Retrieval、Rerank、Memory などの他のタイプの詳細な使用法については、loongsuite-otel-util-genai の完全なドキュメントをご参照ください。

タイプ

オペレーション名

説明

Entry

enter

アプリケーションのエントリポイントです。session_id、user_id、および完全なインタラクション詳細を保持します。

Agent

invoke_agent {name}

トークン使用量を集計するエージェント呼び出しです。

Tool

execute_tool {name}

ツールまたは関数の実行です。

ReAct Step

react

ReAct ループの 1 回の反復です。

LLM

chat {model}

LLM チャットで、通常はプローブによって自動的に収集されます。

Embedding

embeddings {model}

ベクトル埋め込み操作です。

Retrieval

retrieval {data_source}

Retrieval-Augmented Generation (RAG) における取得操作です。

Rerank

rerank {model}

リランク操作です。

Memory

memory {operation}

メモリの読み書き操作です。

以下のセクションでは、各スパンタイプを計装するためのステップバイステップの手順と独立したコードスニペットを提供します。実行可能な完全なコード例については、このトピックの最後にある付録をご参照ください。

重要

ハンドラインスタンスは、必ず get_extended_telemetry_handler() を使用して取得してください。TelemetryHandler を直接インスタンス化しないでください。ARMS プローブは get_extended_telemetry_handler() とのみ互換性があります。TelemetryHandler を直接インスタンス化すると、環境変数の互換性の問題が発生する可能性があります。

重要

カスタム計装を追加する際は、「LLM トレースフィールド定義」のセマンティック規則に従う必要があります。トークン統計やセッション分析などの AI アプリケーション可観測性機能は、データ処理とレンダリングのためにこれらの規則に依存しています。スパン属性が仕様に準拠していない場合、関連データがコンソールで正しく表示されない可能性があります。リソース属性 acs.arms.service.feature=genai_app と gen_ai.instrumentation.sdk.name=loongsuite-genai-utils には特に注意してください。これらの属性は LLM トレースフィールド定義に由来し、アプリケーションが AI アプリケーション可観測性に対して有効であり、データソースが loongsuite-genai-utils であることを示します。これらの属性は、OTEL_RESOURCE_ATTRIBUTES 環境変数または OpenTelemetry Resource オブジェクトを使用して設定してください。通常のスパン属性として設定しないでください。

export OTEL_RESOURCE_ATTRIBUTES="acs.arms.service.feature=genai_app,gen_ai.instrumentation.sdk.name=loongsuite-genai-utils"

アプリケーションに既に OTEL_RESOURCE_ATTRIBUTES 環境変数が設定されている場合は、service.name などの既存のリソース情報を上書きしないように、カンマを使用して前述のキーと値のペアを追加してください。

1. ハンドラとトレーサーの取得

get_extended_telemetry_handler() を使用して loongsuite-otel-util-genai からシングルトンハンドラを取得し、get_tracer(__name__) を使用して OpenTelemetry SDK からトレーサーを取得します。ハンドラは GenAI セマンティックスパンの作成に、トレーサーはカスタムビジネススパンの作成に使用します。

from opentelemetry.util.genai.extended_handler import get_extended_telemetry_handler
from opentelemetry.util.genai.extended_types import (
    EntryInvocation,
    ExecuteToolInvocation,
    InvokeAgentInvocation,
    ReactStepInvocation,
)
from opentelemetry.util.genai.types import Error, InputMessage, OutputMessage, Text
from opentelemetry.trace import get_tracer
handler = get_extended_telemetry_handler()
tracer = get_tracer(__name__)

ハンドラは 2 つの方法で使用できます。

  • コンテキストマネージャー (例:with handler.entry(inv)):スパンのライフサイクルを自動的に管理するため、このアプローチを推奨します。

  • start/stop/fail API (例:handler.start_entry(inv)、handler.stop_entry(inv)、または handler.fail_entry(inv, error)):with 文を使用できない非同期、コールバックベース、またはストリーミングシナリオでこのアプローチを使用します。

2. Entry スパンの作成

リクエストのエントリポイントで Entry スパンを作成します。このスパンは session_id と user_id を保持し、input_messages を通じてユーザー入力を記録します。ストリーミング応答が完了したら、出力コンテンツを連結して output_messages に設定し、stop_entry を呼び出してスパンを終了します。これにより、コンソールでリクエストの完全な入力と最終出力を直接表示できます。

entry_inv = EntryInvocation(
    session_id=req.session_id or str(uuid.uuid4()),
    user_id=req.user_id or "anonymous",
    input_messages=[
        InputMessage(role="user", parts=[Text(content=req.topic)]),
    ],
)
def event_generator():
    handler.start_entry(entry_inv)
    output_chunks: list[str] = [ ]
    try:
        for chunk in run_agent_stream(topic=req.topic):
            output_chunks.append(chunk)
            yield f"data: {json.dumps({'content': chunk}, ensure_ascii=False)}\n\n"
        yield "data: [DONE]\n\n"
    except Exception as exc:
        handler.fail_entry(entry_inv, Error(message=str(exc), type=type(exc)))
        yield f"data: {json.dumps({'error': str(exc)}, ensure_ascii=False)}\n\n"
        return
    entry_inv.output_messages = [
        OutputMessage(
            role="assistant",
            parts=[Text(content="".join(output_chunks))],
            finish_reason="stop",
        ),
    ]
    handler.stop_entry(entry_inv)

3. Agent スパンの作成

start_invoke_agent を使用して Agent スパンを作成し、エージェント名、モデル、および説明を記録します。Agent スパンは、トレース全体のルート GenAI スパンとして機能します。後続の ReAct Step、LLM、および Tool の呼び出しは、その子スパンになります。

loongsuite-otel-util-genai 0.6.1 以降、start_invoke_agent を呼び出す際に InvokeAgentInvocation.agent_name が設定されていると、ユーティリティは自動的に gen_ai.agent.name を OpenTelemetry Baggage に書き込みます。この Agent スパンのライフサイクル内で、LoongSuite GenAI プローブまたはこのユーティリティによって作成される LLM、Tool、Embedding、Retrieval、Rerank、Memory、ReAct Step などの他の GenAI 子スパンは、この属性を自動的に継承します。各子スパンでエージェント名を手動で設定する必要はありません。OpenTelemetry SDK を使用して作成された通常のカスタムビジネススパンは、この GenAI 属性を自動的に継承しません。ビジネス属性を記録するには、引き続き span.set_attribute() を使用してください。

invocation = InvokeAgentInvocation(
    provider="dashscope",
    agent_name="TechContentAgent",
    agent_description="Technical content generation assistant",
    request_model="qwen-plus",
)
total_input_tokens = 0
total_output_tokens = 0
handler.start_invoke_agent(invocation)
try:
    # ... コアエージェントロジック (ReAct ループ) ...
    invocation.input_tokens = total_input_tokens
    invocation.output_tokens = total_output_tokens
    handler.stop_invoke_agent(invocation)
except Exception:
    handler.fail_invoke_agent(invocation, Error(message="agent failed", type=RuntimeError))
    raise

エージェントの実行が完了したら、蓄積された total_input_tokens と total_output_tokens を Agent スパンに書き込み、集計されたトークンメトリック統計を有効にします。

4. ReAct Step スパンの作成

ReAct 推論ループの各反復に対して ReAct Step スパンを作成し、現在の反復 round を渡します。反復が終了したら、さらに反復が必要な場合は finish_reason を continue に設定し、最終的な回答の場合は stop に設定します。この例では、各反復の LLM 呼び出しは ARMS プローブによって自動的に計装されるため、手動での作成は不要です。

step_inv = ReactStepInvocation(round=iteration + 1)
handler.start_react_step(step_inv)
try:
    response = client.chat.completions.create(
        model="qwen-plus",
        messages=messages,
        tools=TOOL_DEFINITIONS,
    )
    # ... 応答を処理 ...
    step_inv.finish_reason = "stop"  # または "continue"
    handler.stop_react_step(step_inv)
except Exception:
    handler.fail_react_step(step_inv, Error(message="step failed", type=RuntimeError))
    raise

5. Tool スパンの作成

モデルがツール呼び出しを返した場合、各 tool_call に対して Tool スパンを作成し、ツール名、呼び出し ID、入力引数、および結果を記録します。

tool_inv = ExecuteToolInvocation(
    tool_name=tool_call.function.name,
    tool_call_id=tool_call.id,
    tool_call_arguments=tool_call.function.arguments,
    tool_type="function",
)
handler.start_execute_tool(tool_inv)
try:
    result = dispatch_tool(tool_name, tool_call.function.arguments)
    tool_inv.tool_call_result = result
except Exception as exc:
    handler.fail_execute_tool(tool_inv, error=Error(message=str(exc), type=type(exc)))
    raise
else:
    handler.stop_execute_tool(tool_inv)

6. ASR または TTS 用の LLM スパンの作成

ASR や TTS などの音声モデル呼び出しで、音声の持続時間、認識レイテンシ、初回チャンクレイテンシなどのビジネス属性を追加する必要がある場合は、モデル呼び出し専用の LLM スパンを作成できます。ASR の場合は operation_name="transcribe" を設定します。TTS の場合は operation_name="synthesize_speech" を設定します。標準のトークンフィールドは、モデル API が実際にトークン使用量を返す場合にのみ設定してください。API がトークン使用量を返さない場合は、音声の持続時間、文字数、またはバイトサイズから gen_ai.usage.* 属性を推定しないでください。

def set_llm_attributes(invocation: LLMInvocation, attributes: dict) -> None:
    attributes = {key: value for key, value in attributes.items() if value is not None}
    invocation.attributes.update(attributes)
    if invocation.span is not None:
        invocation.span.set_attributes(attributes)


# ASR: 音声認識はテキストを出力します。LLM スパンを使用してモデル推論呼び出しを表します。
asr_invocation = LLMInvocation(
    provider="dashscope",
    request_model="paraformer-v2",
    operation_name="transcribe",
    output_type="text",
    input_messages=[
        InputMessage(
            role="user",
            parts=[Uri(mime_type="audio/wav", modality="audio", uri=audio_url)],
        )
    ],
    attributes={
        "gen_ai.asr.channel": "dashscope_transcription_async",
        "gen_ai.asr.input.source": "url",
    },
)

with handler.llm(asr_invocation) as llm:
    # ここで実際の ASR SDK を呼び出し、応答からタスク ID、文字起こしされたテキスト、使用量、タイムスタンプを取得します。
    llm.response_id = asr_task_id
    llm.output_messages = [
        OutputMessage(role="assistant", parts=[Text(content=transcript_text)], finish_reason="stop")
    ]
    llm.input_tokens = asr_usage.get("input_tokens")
    llm.output_tokens = asr_usage.get("output_tokens")
    set_llm_attributes(
        llm,
        {
            "gen_ai.asr.success": True,
            "gen_ai.asr.status": "SUCCEEDED",
            "gen_ai.asr.audio.duration": asr_usage.get("duration"),
            "gen_ai.asr.call.wall_time": asr_call_wall_time,
            "gen_ai.asr.provider.processing.duration": asr_provider_processing_time,
            "gen_ai.asr.audio_tokens": asr_usage.get("audio_tokens"),
        },
    )


# TTS: テキストが音声に合成されます。LLM スパンを使用してモデル推論呼び出しを表すことができます。
tts_invocation = LLMInvocation(
    provider="dashscope",
    request_model="qwen-tts",
    operation_name="synthesize_speech",
    output_type="audio",
    input_messages=[InputMessage(role="user", parts=[Text(content=tts_text)])],
    attributes={
        "gen_ai.tts.channel": "qwen_tts_http",
        "gen_ai.tts.voice": "Cherry",
        "gen_ai.tts.input.text_length": len(tts_text),
    },
)

with handler.llm(tts_invocation) as llm:
    # ここで実際の TTS SDK を呼び出し、応答からリクエスト ID、音声 ID/URL、および使用量を取得します。
    llm.response_id = tts_request_id
    llm.input_tokens = tts_usage.get("input_tokens")
    llm.output_tokens = tts_usage.get("output_tokens")
    llm.output_messages = [
        OutputMessage(role="assistant", parts=[Text(content=f"audio generated: {audio_id}")], finish_reason="stop")
    ]
    set_llm_attributes(
        llm,
        {
            "gen_ai.tts.success": True,
            "gen_ai.tts.status": "SUCCEEDED",
            "gen_ai.tts.audio.duration": generated_audio_duration,
            "gen_ai.tts.call.wall_time": tts_call_wall_time,
            "gen_ai.tts.first_audio.duration": first_audio_delay,
            "gen_ai.tts.audio_tokens": (tts_usage.get("output_tokens_details") or {}).get("audio_tokens"),
            "gen_ai.tts.usage.characters": tts_usage.get("characters"),
        },
    )

一般的な ASR/TTS フィールドは、その目的に基づいて区別します。gen_ai.asr.audio.duration は入力音声の持続時間を表し、gen_ai.asr.provider.processing.duration はサーバー側の認識時間を表します。gen_ai.tts.audio.duration は合成された音声の持続時間を表し、gen_ai.tts.first_audio.duration はストリーミング合成における最初の音声パケットまでの時間を表します。エンドツーエンドの呼び出し時間にはスパンの持続時間を使用するか、追加で gen_ai.asr.call.wall_time または gen_ai.tts.call.wall_time に書き込むことができます。実行可能な完全な例については、付録の asr_llm_span.py と tts_llm_span.py をご参照ください。

7. OpenTelemetry SDK を使用したカスタムスパンの作成

loongsuite-otel-util-genai が提供する GenAI セマンティックスパンに加えて、OpenTelemetry SDK の tracer.start_as_current_span() メソッドを使用してカスタムビジネススパンを作成し、GenAI スパンと組み合わせて使用することもできます。

以下の例は、カスタムスパンの 2 つの典型的なユースケースを示しています。

重複ツール検出

このプロセスは各 ReAct 反復の前に実行され、Counter を使用して各ツールが呼び出された回数をカウントし、検出結果を gen_ai.loop_detection.* 属性に書き込みます。重複が検出された場合、メッセージリストにシステムプロンプトが追加され、モデルが重複を避けるように誘導します。

def _check_duplicate_tools(
    tool_usage_counter: Counter,
    messages: list[dict[str, Any]],
) -> None:
    duplicates = [name for name, count in tool_usage_counter.items() if count > 1]
    has_duplicates = len(duplicates) > 0
    with tracer.start_as_current_span("duplicate_tool_detection") as span:
        span.set_attributes({
            "gen_ai.loop_detection.detected": has_duplicates,
            "gen_ai.loop_detection.duplicate_tools": str(duplicates) if has_duplicates else "[ ]",
            "gen_ai.loop_detection.total_calls": sum(tool_usage_counter.values()),
            "gen_ai.loop_detection.unique_tools": len(tool_usage_counter),
        })
    if has_duplicates:
        details = ", ".join(f"{n}({tool_usage_counter[n]} times)" for n in duplicates)
        messages.append({
            "role": "system",
            "content": f"[System Prompt] Duplicate tool calls detected: {details}. Please avoid calling them again.",
        })

LLM 応答ループ検出

このプロセスは、各 LLM 応答の後に実行されます。現在の応答と前の応答のテキスト類似度を比較し、is_loop や overlap_ratio などのメトリックをスパン属性に書き込みます。ループが検出された場合 (テキストが同一であるか、重複率が 80% を超える場合)、finish_reason は loop_detected に設定され、エージェントは早期終了します。

def _check_response_loop(
    current_content: str | None,
    previous_content: str | None,
) -> bool:
    cur = (current_content or "").strip()
    prev = (previous_content or "").strip()
    with tracer.start_as_current_span("response_loop_detection") as span:
        if not prev or not cur:
            span.set_attributes({
                "gen_ai.loop_detection.is_loop": False,
                "gen_ai.loop_detection.reason": "no_text_content",
            })
            return False
        is_identical = cur == prev
        longer = max(len(cur), len(prev))
        common_prefix_len = sum(1 for a, b in zip(cur, prev) if a == b)
        overlap_ratio = common_prefix_len / longer if longer > 0 else 0.0
        is_loop = is_identical or overlap_ratio > 0.8
        span.set_attributes({
            "gen_ai.loop_detection.is_loop": is_loop,
            "gen_ai.loop_detection.is_identical": is_identical,
            "gen_ai.loop_detection.overlap_ratio": round(overlap_ratio, 2),
            "gen_ai.loop_detection.current_length": len(cur),
            "gen_ai.loop_detection.previous_length": len(prev),
        })
        return is_loop
説明

カスタムスパンは LLM セマンティック規則に準拠していないため、コンソールのトレースビューで フルビュー に切り替えて表示する必要があります。

モニタリング詳細

  1. Cloud Monitor 2.0 コンソールにログインし、ターゲットワークスペースを選択し、ナビゲーションウィンドウで[すべての機能] > [AI アプリケーションの可観測性]を選択します。

  2. [AI アプリケーション一覧] ページには、統合されたアプリケーションが一覧表示されます。[アプリケーション名] をクリックすると、その詳細なモニタリングデータを表示できます。

計装結果

1. Entry スパンの詳細

Entry スパンには、gen_ai.session.id (一意のセッション ID) や gen_ai.user.id (ユーザー ID) などの主要な属性が表示されます。これらの属性を関数のエントリポイントで設定すると、LLM やツールスパンなどのダウンストリームスパンに自動的に伝播され、セッションおよびユーザー分析のためのデータ相関に役立ちます。Entry スパンには、gen_ai.input.messages (ユーザー入力) と gen_ai.output.messages (最終出力) も含まれており、コンソールでリクエストの完全なインタラクションを直接表示できます。

Entry スパンの詳細パネルには、gen_ai.session.id (一意のセッション ID) や gen_ai.user.id (ユーザー ID) などの主要な属性が含まれており、これらは関数のエントリポイントで設定された後、ダウンストリームの子スパンに自動的に伝播されます。パネルには、gen_ai.input.messages (ユーザーの入力メッセージの完全な内容) と gen_ai.output.messages (最終的なモデル出力メッセージの完全な内容) も表示されます。

2. Agent スパンの詳細

Agent スパンの詳細パネルでは、主要な属性として gen_ai.agent.name (TechContentAgent)、gen_ai.provider.name (dashscope)、gen_ai.request.model (qwen-plus)、およびエージェントレベルのトークン使用量の概要 (gen_ai.usage.input_tokens (3982)、gen_ai.usage.output_tokens (884)、gen_ai.usage.total_tokens (4866)) が含まれます。

3. Tool スパンの詳細

Tool スパンには、ツール名、その入力パラメーター、およびツール呼び出し結果が表示されます。これにより、ツール呼び出しの詳細が提供されます。execute_tool generate_seo_keywords を選択すると、右側の詳細パネルにツール名 (Tool: $generate_seo_keywords)、ツールタイプ (Tool Type: function)、ツール呼び出し引数 (Tool Call Arguments、例:{"topic": "CMS 2.0 AI alert noise reduction"})、およびツール結果 (Tool Result) が表示されます。これにより、ツール呼び出しの入出力が期待通りであるかを簡単にトラブルシューティングできます。

4. LLM スパンの詳細

LLM スパンは、OpenAI や DashScope などのサポートされているコンポーネントに対して ARMS エージェントによって自動的に収集されるか、このドキュメントの例で示されているように LLMInvocation を使用して手動で作成できます。自動収集は、一般的なテキストベースの対話モデルへの呼び出しに使用されます。ASR や TTS など、エージェントによってまだ自動的にカバーされていないモデル呼び出しや、ビジネス属性を追加する必要がある場合は、手動で LLM スパンを作成し、gen_ai.asr.* や gen_ai.tts.* などのカスタム属性を追加できます。

LLM スパンの詳細パネルには、アプリケーション名、API エンドポイント、IP アドレス、開始時刻と終了時刻、spanId、parentSpanId、ステータスコードなどの基本情報が表示されます。[追加情報] タブでは、応答内容、カスタム属性、および呼び出しのトークン使用量を確認できます。

5. カスタムスパンの詳細

サンプルコードでは、OpenTelemetry SDK を使用して 2 つのカスタムビジネススパンを作成し、カスタム計装と GenAI セマンティックスパンを組み合わせる方法を示しています。これらのカスタムスパンは GenAI セマンティクスの一部ではないため、表示するにはフルビューを開く必要があります。

  • duplicate_tool_detection:このスパンは、各 ReAct 反復の前に実行され、エージェントが繰り返しツールを呼び出すループに陥っていないかを検出します。スパンの属性には、重複が検出されたかどうか、重複したツールのリスト、呼び出しの総数、およびユニークなツールの数が記録されます。これにより、ARMS でエージェントのツール呼び出しループを迅速に特定できます。

    ARMS トレース詳細ページで、duplicate_tool_detection スパンをクリックすると、右側の詳細パネルにループ検出属性が表示されます。属性キーは gen_ai.loop_detection.detected、gen_ai.loop_detection.duplicate_tools、gen_ai.loop_detection.total_calls、gen_ai.loop_detection.unique_tools、および gen_ai.loop_detection.details です。4 つのツール呼び出しがすべてユニークな場合、detected は false で、duplicate_tools は空の配列 [] になります。

  • response_loop_detection:このスパンは、各 LLM 応答の後に実行され、モデルが非常に類似したコンテンツを繰り返し返していないかを検出します。スパンの属性には、ループが特定されたかどうか、テキストが同一であるかどうか、重複率、および現在と前の応答のテキスト長が記録されます。これにより、モデルが反復的な出力ループに陥っている例外的なシナリオをトラブルシューティングするのに役立ちます。

    トレース詳細ページのウォーターフォールビューで、response_loop_detection スパンを選択します。右側の属性パネルに特定の属性が表示されます。例えば、gen_ai.loop_detection.is_loop=false はループが検出されていないことを示し、gen_ai.loop_detection.reason=no_text_content は理由がテキストコンテンツなしであることを示します。

参考資料

他の言語のカスタム計装

付録

完全なサンプルコード

app.py

import json
import uuid
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from opentelemetry.util.genai.extended_handler import get_extended_telemetry_handler
from opentelemetry.util.genai.extended_types import EntryInvocation
from opentelemetry.util.genai.types import Error, InputMessage, OutputMessage, Text
from agent import run_marketing_agent_stream
app = FastAPI(title="Cloud Product Technical Content Generation Assistant")
class GenerateRequest(BaseModel):
    content_type: str = "blog"
    product: str = "CMS"
    target_audience: str = "Operations Engineer / SRE"
    topic: str = ""
    session_id: str = ""
    user_id: str = ""
@app.post("/api/v1/generate/stream")
async def generate_stream(req: GenerateRequest) -> StreamingResponse:
    handler = get_extended_telemetry_handler()
    user_prompt = (
        f"Content Type: {req.content_type}, Product: {req.product}, "
        f"Target Audience: {req.target_audience}, Topic: {req.topic}"
    )
    entry_inv = EntryInvocation(
        session_id=req.session_id or str(uuid.uuid4()),
        user_id=req.user_id or "anonymous",
        input_messages=[
            InputMessage(role="user", parts=[Text(content=user_prompt)]),
        ],
    )
    def event_generator():
        handler.start_entry(entry_inv)
        output_chunks: list[str] = []
        try:
            for chunk in run_marketing_agent_stream(
                content_type=req.content_type,
                product=req.product,
                target_audience=req.target_audience,
                topic=req.topic,
            ):
                output_chunks.append(chunk)
                yield f"data: {json.dumps({'content': chunk}, ensure_ascii=False)}\n\n"
            yield "data: [DONE]\n\n"
        except Exception as exc:
            handler.fail_entry(
                entry_inv,
                Error(message=str(exc), type=type(exc)),
            )
            yield f"data: {json.dumps({'error': str(exc)}, ensure_ascii=False)}\n\n"
            return
        entry_inv.output_messages = [
            OutputMessage(
                role="assistant",
                parts=[Text(content="".join(output_chunks))],
                finish_reason="stop",
            ),
        ]
        handler.stop_entry(entry_inv)
    return StreamingResponse(event_generator(), media_type="text/event-stream")
@app.get("/health")
async def health():
    return {"status": "ok"}
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

agent.py

import os
from collections import Counter
from collections.abc import Generator
from typing import Any
from openai import OpenAI
from opentelemetry.trace import get_tracer
from opentelemetry.util.genai.extended_handler import get_extended_telemetry_handler
from opentelemetry.util.genai.extended_types import (
    ExecuteToolInvocation,
    InvokeAgentInvocation,
    ReactStepInvocation,
)
from opentelemetry.util.genai.types import Error
from tools import TOOL_DEFINITIONS, dispatch_tool
tracer = get_tracer(__name__)
MODEL_NAME = os.environ.get("MODEL_NAME", "qwen-plus")
BASE_URL = os.environ.get(
    "OPENAI_BASE_URL",
    "https://dashscope.aliyuncs.com/compatible-mode/v1",
)
API_KEY = os.environ.get("DASHSCOPE_API_KEY", "")
MAX_ITERATIONS = 10
SYSTEM_PROMPT = """\
You are a technical content generation assistant for Alibaba Cloud CloudMonitor 2.0 (CMS 2.0).
You create high-value technical content for Operations Engineers/SREs and Architects in their professional language.
Key principle: Adapt the content's perspective and tone to the target audience.
- Operations Engineer / SRE: Focus on practical steps, troubleshooting efficiency, and tool integration, using everyday operational terminology.
- Architect: Focus on architectural design, standardization, and scalability, using technically in-depth, professional language.
You must strictly follow these steps, using the corresponding tool for each one:
Step 1: Use the `search_product_knowledge` tool to search for CMS product information (features or comparison).
Step 2: Use the `get_audience_profile` tool to get the target audience profile and pain points.
Step 3: Use the `get_industry_cases` tool to find relevant industry cases.
Step 4: If writing a blog post, use the `generate_seo_keywords` tool to get SEO keywords.
Step 5: Generate content based on the collected information.
Step 6: Use the `check_content_compliance` tool to check for compliance.
Content requirements: Focus on product strengths and audience pain points, cite data from case studies, write in Chinese, and stay within 800 words."""
def _build_client() -> OpenAI:
    return OpenAI(base_url=BASE_URL, api_key=API_KEY)
def _build_user_message(
    content_type: str,
    product: str,
    target_audience: str,
    topic: str,
) -> str:
    type_labels = {
        "blog": "a hands-on technical blog for frontline engineers",
        "email": "a technical recommendation email tailored to the target role",
        "case_study": "a customer case study with actionable takeaways",
        "comparison": "a product comparison analysis to aid technology selection",
    }
    label = type_labels.get(content_type, content_type)
    return (
        f"Please generate {label} for the {product} product.\n"
        f"Target Audience: {target_audience}\n"
        f"Topic/Direction: {topic}\n\n"
        f"Use the language and perspective of the target audience. "
        f"Call the tools in sequence to gather information before generating content."
    )
def _check_duplicate_tools(
    tool_usage_counter: Counter,
    messages: list[dict[str, Any]],
) -> list[str]:
    duplicates = [name for name, count in tool_usage_counter.items() if count > 1]
    total_calls = sum(tool_usage_counter.values())
    has_duplicates = len(duplicates) > 0
    duplicate_details = ", ".join(
        f"{name}({tool_usage_counter[name]} times)" for name in duplicates
    ) if has_duplicates else "none"
    with tracer.start_as_current_span("duplicate_tool_detection") as detect_span:
        detect_span.set_attributes({
            "gen_ai.loop_detection.detected": has_duplicates,
            "gen_ai.loop_detection.duplicate_tools": str(duplicates) if has_duplicates else "[]",
            "gen_ai.loop_detection.details": duplicate_details,
            "gen_ai.loop_detection.total_calls": total_calls,
            "gen_ai.loop_detection.unique_tools": len(tool_usage_counter),
        })
    if not has_duplicates:
        return []
    hint_message = (
        f"[System Prompt] Duplicate tool calls detected: {duplicate_details}. "
        f"Avoid calling the same tools repeatedly. Use the gathered information to proceed."
    )
    messages.append({"role": "system", "content": hint_message})
    return duplicates
def _check_response_loop(
    current_content: str | None,
    previous_content: str | None,
) -> bool:
    """Compare consecutive LLM text responses to detect stuck loops."""
    cur = (current_content or "").strip()
    prev = (previous_content or "").strip()
    with tracer.start_as_current_span("response_loop_detection") as span:
        if not prev or not cur:
            span.set_attributes({
                "gen_ai.loop_detection.is_loop": False,
                "gen_ai.loop_detection.reason": "no_text_content",
            })
            return False
        is_identical = cur == prev
        common_prefix_len = 0
        for a, b in zip(cur, prev):
            if a == b:
                common_prefix_len += 1
            else:
                break
        longer = max(len(cur), len(prev))
        overlap_ratio = common_prefix_len / longer if longer > 0 else 0.0
        is_loop = is_identical or overlap_ratio > 0.8
        span.set_attributes({
            "gen_ai.loop_detection.is_loop": is_loop,
            "gen_ai.loop_detection.is_identical": is_identical,
            "gen_ai.loop_detection.overlap_ratio": round(overlap_ratio, 2),
            "gen_ai.loop_detection.current_length": len(cur),
            "gen_ai.loop_detection.previous_length": len(prev),
        })
        return is_loop
def run_marketing_agent_stream(
    content_type: str,
    product: str,
    target_audience: str,
    topic: str,
) -> Generator[str, None, None]:
    client = _build_client()
    handler = get_extended_telemetry_handler()
    user_message = _build_user_message(content_type, product, target_audience, topic)
    invocation = InvokeAgentInvocation(
        provider="dashscope",
        agent_name="TechContentAgent",
        agent_description="A cloud product content generation assistant for different technical roles",
        request_model=MODEL_NAME,
    )
    total_input_tokens = 0
    total_output_tokens = 0
    tool_usage_counter: Counter = Counter()
    previous_content: str | None = None
    handler.start_invoke_agent(invocation)
    try:
        messages: list[dict[str, Any]] = [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": user_message},
        ]
        for iteration in range(MAX_ITERATIONS):
            _check_duplicate_tools(tool_usage_counter, messages)
            step_inv = ReactStepInvocation(round=iteration + 1)
            handler.start_react_step(step_inv)
            try:
                response = client.chat.completions.create(
                    model=MODEL_NAME,
                    messages=messages,
                    tools=TOOL_DEFINITIONS,
                    temperature=0.7,
                )
                choice = response.choices[0]
                message = choice.message
                if response.usage:
                    total_input_tokens += response.usage.prompt_tokens
                    total_output_tokens += response.usage.completion_tokens
                current_content = message.content
                if _check_response_loop(current_content, previous_content):
                    step_inv.finish_reason = "loop_detected"
                    handler.stop_react_step(step_inv)
                    if current_content:
                        yield current_content
                    break
                if (current_content or "").strip():
                    previous_content = current_content
                if message.tool_calls:
                    messages.append(message.model_dump())
                    for tool_call in message.tool_calls:
                        tool_name = tool_call.function.name
                        tool_args = tool_call.function.arguments
                        tool_usage_counter[tool_name] += 1
                        tool_inv = ExecuteToolInvocation(
                            tool_name=tool_name,
                            tool_call_id=tool_call.id,
                            tool_call_arguments=tool_args,
                            tool_type="function",
                        )
                        handler.start_execute_tool(tool_inv)
                        try:
                            result = dispatch_tool(tool_name, tool_args)
                            tool_inv.tool_call_result = result
                        except Exception as exc:
                            handler.fail_execute_tool(
                                tool_inv,
                                error=Error(message=str(exc), type=type(exc)),
                            )
                            raise
                        else:
                            handler.stop_execute_tool(tool_inv)
                        messages.append({
                            "role": "tool",
                            "tool_call_id": tool_call.id,
                            "content": result,
                        })
                    step_inv.finish_reason = "continue"
                    handler.stop_react_step(step_inv)
                    continue
                if choice.finish_reason == "stop" or message.content:
                    if message.content:
                        yield message.content
                    step_inv.finish_reason = "stop"
                    handler.stop_react_step(step_inv)
                    break
            except Exception:
                handler.fail_react_step(
                    step_inv, Error(message="step failed", type=RuntimeError)
                )
                raise
        invocation.input_tokens = total_input_tokens
        invocation.output_tokens = total_output_tokens
        handler.stop_invoke_agent(invocation)
    except Exception:
        handler.fail_invoke_agent(
            invocation, Error(message="agent failed", type=RuntimeError)
        )
        raise

tools.py

import json
from typing import Any
PRODUCT_KNOWLEDGE: dict[str, dict[str, str]] = {
    "CMS": {
        "features": (
            "CloudMonitor 2.0 (CMS 2.0) is the one-stop observability platform from Alibaba Cloud, integrating the capabilities of three products: Simple Log Service (SLS), CloudMonitor (CMS), and Application Real-Time Monitoring Service (ARMS):\n"
            "1. Full-stack unified monitoring: A unified view of metrics, traces, logs, and events.\n"
            "2. UModel unified modeling: Automatic resource association and observability graph construction.\n"
            "3. AI-powered analysis: Anomaly detection, alert noise reduction, and a conversational Ops Copilot.\n"
            "4. Open and compatible: Supports the Prometheus, Grafana, and OpenTelemetry ecosystems.\n"
            "5. AI application observability: LLM call chain tracing, token statistics, and model performance analysis."
        ),
        "comparison": (
            "CloudMonitor 2.0 vs. traditional monitoring solutions:\n"
            "1. Data fusion: Traditional solutions require switching between 3-5 consoles; CMS 2.0 offers a unified, one-stop experience.\n"
            "2. AI capabilities: Traditional static threshold alerts have a false positive rate of 30%+; CMS 2.0 reduces noise by 80% with its AI capabilities.\n"
            "3. Observability graph: CMS 2.0 automatically builds a dependency graph using UModel.\n"
            "4. AI application observability: Not supported by traditional solutions; CMS 2.0 provides native support for end-to-end LLM/Agent tracing."
        ),
    },
}
AUDIENCE_PROFILES: dict[str, dict[str, str]] = {
    "Operations Engineer / SRE": {
        "role": "Operations Engineer / SRE",
        "pain_points": (
            "1. Long troubleshooting times: Locating the root cause in a microservice architecture takes 30-60 minutes on average.\n"
            "2. Alert storms: A surge in alerts during promotional events makes it difficult to prioritize.\n"
            "3. Tool fragmentation: The need to switch between 5-6 different monitoring tools.\n"
            "4. AIOps blind spots: Lack of transparency in LLM call chains."
        ),
        "interests": "end-to-end tracing, root cause analysis, alert noise reduction, Prometheus/Grafana integration",
        "decision_factors": "Technical maturity, community activity, learning curve, integration difficulty",
    },
    "Architect": {
        "role": "Architect / Technical Expert",
        "pain_points": (
            "1. Observability challenges in hybrid microservice and AI Agent architectures.\n"
            "2. Lack of objective comparisons for selecting between open-source self-managed and commercial solutions.\n"
            "3. Inconsistent monitoring solutions and fragmented data formats across teams.\n"
            "4. Uncertainty about whether the current solution can support 10x business growth."
        ),
        "interests": "Architectural design, OpenTelemetry standardization, unified data models, scalability",
        "decision_factors": "Architectural maturity, standardization, scalability, openness, and ecosystem",
    },
}
INDUSTRY_CASES: dict[str, list[dict[str, str]]] = {
    "Finance": [
        {
            "company": "A leading joint-stock commercial bank",
            "scenario": (
                "Observability upgrade for a core trading system: Covering 200+ microservices "
                "with end-to-end tracing for 50 million daily transactions."
            ),
            "results": (
                "Reduced MTTR from 45 to 8 minutes (an 82% decrease); "
                "increased alert accuracy from 60% to 95%; "
                "improved operational efficiency by 3x, and passed Level 3 compliance checks on the first attempt."
            ),
        },
    ],
    "Internet": [
        {
            "company": "A social media platform",
            "scenario": (
                "Full-stack observability for an application with tens of millions of DAUs: Covering client-side experience monitoring → "
                "CDN → API gateway → 2000+ microservices → databases/caches."
            ),
            "results": (
                "Reduced user-side crash rate from 0.5% to 0.08%; "
                "optimized API P99 latency by 40%; "
                "saved over $14,000 per month in monitoring costs (compared to a self-built solution)."
            ),
        },
    ],
}
COMPLIANCE_RULES: dict[str, dict[str, Any]] = {
    "product_names": {
        "incorrect": {
            "Aliyun": "Alibaba Cloud",
            "CMS2.0": "CMS 2.0",
            "CMS2.0": "Cloud Monitor 2.0",
        },
    },
    "claim_rules": [
        "Data references must cite their sources.",
        "Avoid absolute terms (e.g., 'the best', 'the only', 'the first').",
        "Use objective data when making product comparisons.",
    ],
}
SEO_KEYWORDS_DB: dict[str, dict[str, Any]] = {
    "observability": {
        "primary": "observability",
        "long_tail": ["cloud-native observability solution", "microservice observability platform selection"],
        "search_volume": "High",
    },
    "ai observability": {
        "primary": "AI application observability",
        "long_tail": ["LLM call chain tracing", "AI Agent observability"],
        "search_volume": "Medium (fast-growing)",
    },
}
def search_product_knowledge(product: str, aspect: str) -> str:
    product_key = "CMS"
    product_data = PRODUCT_KNOWLEDGE.get(product_key)
    if not product_data:
        available = ", ".join(PRODUCT_KNOWLEDGE.keys())
        return f"Knowledge base for product '{product}' not found. Available products: {available}"
    aspect_lower = aspect.lower()
    aspect_data = product_data.get(aspect_lower)
    if not aspect_data:
        available = ", ".join(product_data.keys())
        return f"Information for aspect '{aspect}' of '{product}' not found. Queryable aspects: {available}"
    return f"[{product} - {aspect}]\n{aspect_data}"
def get_audience_profile(audience_type: str) -> str:
    profile = AUDIENCE_PROFILES.get(audience_type)
    if not profile:
        available = ", ".join(AUDIENCE_PROFILES.keys())
        return f"Audience type '{audience_type}' not found. Available types: {available}"
    return (
        f"Audience Profile — {profile['role']}\n\n"
        f"Core Pain Points:\n{profile['pain_points']}\n\n"
        f"Areas of Interest: {profile['interests']}\n\n"
        f"Decision Factors: {profile['decision_factors']}"
    )
def get_industry_cases(industry: str) -> str:
    cases = INDUSTRY_CASES.get(industry)
    if not cases:
        available = ", ".join(INDUSTRY_CASES.keys())
        return f"No cases found for the '{industry}' industry. Available industries: {available}"
    parts: list[str] = [f"[{industry} Industry Case Studies]\n"]
    for i, case in enumerate(cases, 1):
        parts.append(
            f"Case {i}: {case['company']}\n"
            f"  Scenario: {case['scenario']}\n"
            f"  Results: {case['results']}"
        )
    return "\n\n".join(parts)
def check_content_compliance(content_type: str, key_claims: str) -> str:
    issues: list[str] = []
    for wrong, correct in COMPLIANCE_RULES["product_names"]["incorrect"].items():
        if wrong in key_claims and correct not in key_claims:
            issues.append(f"Product name '{wrong}' should be corrected to '{correct}'")
    for word in ("best", "only", "first", "strongest"):
        if word in key_claims:
            issues.append(f"Contains the absolute term '{word}'. Replace it with an objective statement.")
    rules_text = "\n".join(
        f"  {i+1}. {rule}"
        for i, rule in enumerate(COMPLIANCE_RULES["claim_rules"])
    )
    result = "Compliance Check Results:\n\n"
    if issues:
        result += "Issues Found:\n" + "\n".join(f"  - {i}" for i in issues) + "\n\n"
    else:
        result += "No obvious compliance issues found.\n\n"
    result += f"Compliance Rules:\n{rules_text}"
    return result
def generate_seo_keywords(topic: str) -> str:
    topic_lower = topic.lower()
    matched: list[dict[str, Any]] = []
    for key, data in SEO_KEYWORDS_DB.items():
        if key.lower() in topic_lower or topic_lower in key.lower() or any(
            w in topic_lower for w in key.lower().split() if len(w) > 1
        ):
            matched.append({"keyword": key, **data})
    if not matched:
        all_keywords = list(SEO_KEYWORDS_DB.keys())
        return (
            f"No keyword data directly matching '{topic}' was found.\n"
            f"Suggested keyword directions: {', '.join(all_keywords)}\n"
            f"General SEO advice: Include core keywords in the title, "
            f"use long-tail keywords in H2/H3 tags, and write 2000+ words."
        )
    parts: list[str] = [f"SEO Keyword Analysis — '{topic}':\n"]
    for item in matched:
        long_tail = "\n".join(f"    - {kw}" for kw in item["long_tail"])
        parts.append(
            f"Primary Keyword: {item['primary']}\n"
            f"  Search Volume: {item['search_volume']}\n"
            f"  Long-tail Keywords:\n{long_tail}"
        )
    return "\n\n".join(parts)
TOOL_REGISTRY: dict[str, Any] = {
    "search_product_knowledge": search_product_knowledge,
    "get_audience_profile": get_audience_profile,
    "get_industry_cases": get_industry_cases,
    "check_content_compliance": check_content_compliance,
    "generate_seo_keywords": generate_seo_keywords,
}
def dispatch_tool(name: str, arguments: str) -> str:
    func = TOOL_REGISTRY.get(name)
    if not func:
        return f"Unknown tool: {name}"
    try:
        kwargs = json.loads(arguments)
    except json.JSONDecodeError:
        return f"Failed to parse tool arguments: {arguments}"
    return func(**kwargs)
TOOL_DEFINITIONS: list[dict[str, Any]] = [
    {
        "type": "function",
        "function": {
            "name": "search_product_knowledge",
            "description": "Searches the CMS product knowledge base for features or competitive comparisons.",
            "parameters": {
                "type": "object",
                "properties": {
                    "product": {
                        "type": "string",
                        "description": "Product Name",
                        "enum": ["CMS"],
                    },
                    "aspect": {
                        "type": "string",
                        "description": "Aspect to query",
                        "enum": ["features", "comparison"],
                    },
                },
                "required": ["product", "aspect"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_audience_profile",
            "description": "Retrieves the target audience profile, including pain points, interests, and decision factors.",
            "parameters": {
                "type": "object",
                "properties": {
                    "audience_type": {
                        "type": "string",
                        "description": "Target Audience Type",
                        "enum": ["Operations Engineer / SRE", "Architect"],
                    },
                },
                "required": ["audience_type"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_industry_cases",
            "description": "Retrieves customer success cases for an industry, including scenarios and results data.",
            "parameters": {
                "type": "object",
                "properties": {
                    "industry": {
                        "type": "string",
                        "description": "Target Industry",
                        "enum": ["Finance", "Internet"],
                    },
                },
                "required": ["industry"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "check_content_compliance",
            "description": "Checks content for compliance, including product naming and marketing claims.",
            "parameters": {
                "type": "object",
                "properties": {
                    "content_type": {
                        "type": "string",
                        "description": "Content Type",
                        "enum": ["blog", "case_study", "comparison"],
                    },
                    "key_claims": {
                        "type": "string",
                        "description": "Key claims and data references",
                    },
                },
                "required": ["content_type", "key_claims"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "generate_seo_keywords",
            "description": "Generates SEO keywords based on a topic. Call this when creating a blog post.",
            "parameters": {
                "type": "object",
                "properties": {
                    "topic": {
                        "type": "string",
                        "description": "Article topic or core keywords",
                    },
                },
                "required": ["topic"],
            },
        },
    },
]

asr_llm_span.py

from datetime import datetime
import time

import requests
from dashscope.audio.asr import Transcription
from opentelemetry.util.genai.extended_handler import get_extended_telemetry_handler
from opentelemetry.util.genai.types import InputMessage, LLMInvocation, OutputMessage, Text, Uri


ASR_AUDIO_URLS = [
    # DashScope 公式 / Object Storage Service (OSS) サンプル音声ファイル。
    # 本番環境では、これらを独自の OSS オブジェクトまたは一般公開されている音声 URL に置き換えてください。
    "https://dashscope.oss-cn-beijing.aliyuncs.com/samples/audio/paraformer/hello_world_female2.wav",
    "https://dashscope.oss-cn-beijing.aliyuncs.com/samples/audio/paraformer/hello_world_female.wav",
    "https://dashscope.oss-cn-beijing.aliyuncs.com/samples/audio/paraformer/hello_world_male.wav",
    "https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3",
]


def parse_time(value: str | None) -> datetime | None:
    if not value:
        return None
    for fmt in ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S"):
        try:
            return datetime.strptime(value, fmt)
        except ValueError:
            continue
    return None


def set_attr(invocation: LLMInvocation, attrs: dict) -> None:
    attrs = {key: value for key, value in attrs.items() if value is not None}
    invocation.attributes.update(attrs)
    if invocation.span is not None:
        invocation.span.set_attributes(attrs)


def transcribe(audio_url: str, model: str = "paraformer-v2") -> None:
    handler = get_extended_telemetry_handler()
    invocation = LLMInvocation(
        provider="dashscope",
        request_model=model,
        operation_name="transcribe",
        output_type="text",
        input_messages=[
            InputMessage(
                role="user",
                parts=[Uri(mime_type="audio/wav", modality="audio", uri=audio_url)],
            )
        ],
        attributes={
            "gen_ai.asr.api": "dashscope_transcription_async",
            "gen_ai.asr.input.source": "url",
        },
    )

    with handler.llm(invocation) as llm:
        start = time.perf_counter()
        submit = Transcription.async_call(model=model, file_urls=[audio_url])
        result = Transcription.wait(task=submit.output.task_id, wait_timeout=120)
        call_wall_time = time.perf_counter() - start

        output = result["output"]
        usage = result.get("usage") or {}
        task_metrics = output.get("task_metrics") or {}
        submit_time = parse_time(output.get("submit_time"))
        scheduled_time = parse_time(output.get("scheduled_time"))
        end_time = parse_time(output.get("end_time"))

        transcription_url = output["results"][0]["transcription_url"]
        transcription_json = requests.get(transcription_url, timeout=20).json()
        transcript = (transcription_json.get("transcripts") or [{}])[0]
        properties = transcription_json.get("properties") or {}

        queue_duration = None
        provider_duration = None
        task_duration = None
        if submit_time and scheduled_time:
            queue_duration = (scheduled_time - submit_time).total_seconds()
        if scheduled_time and end_time:
            provider_duration = (end_time - scheduled_time).total_seconds()
        if submit_time and end_time:
            task_duration = (end_time - submit_time).total_seconds()

        llm.response_id = output.get("task_id")
        llm.output_messages = [
            OutputMessage(
                role="assistant",
                parts=[Text(content=transcript.get("text", ""))],
                finish_reason=output.get("task_status", "SUCCEEDED").lower(),
            )
        ]
        set_attr(
            llm,
            {
                "gen_ai.asr.success": output.get("task_status") == "SUCCEEDED",
                "gen_ai.asr.status": output.get("task_status"),
                "gen_ai.asr.task.status": output.get("task_status"),
                "gen_ai.asr.task.total": task_metrics.get("TOTAL"),
                "gen_ai.asr.task.succeeded": task_metrics.get("SUCCEEDED"),
                "gen_ai.asr.task.failed": task_metrics.get("FAILED"),
                "gen_ai.asr.audio.duration": usage.get("duration"),
                "gen_ai.asr.call.wall_time": call_wall_time,
                "gen_ai.asr.audio.original_duration": properties.get("original_duration_in_milliseconds"),
                "gen_ai.asr.audio.content_duration": transcript.get("content_duration_in_milliseconds"),
                "gen_ai.asr.audio.format": properties.get("audio_format"),
                "gen_ai.asr.audio.sample_rate": properties.get("original_sampling_rate"),
                "gen_ai.asr.queue.duration": queue_duration,
                "gen_ai.asr.provider.processing.duration": provider_duration,
                "gen_ai.asr.task.duration": task_duration,
            },
        )


for url in ASR_AUDIO_URLS:
    transcribe(url)

tts_llm_span.py

import io
import time
import wave

import requests
from dashscope.audio.qwen_tts import SpeechSynthesizer as QwenTTSSynthesizer
from dashscope.audio.tts_v2 import AudioFormat
from dashscope.audio.tts_v2 import SpeechSynthesizer as TTSV2Synthesizer
from opentelemetry.util.genai.extended_handler import get_extended_telemetry_handler
from opentelemetry.util.genai.types import InputMessage, LLMInvocation, OutputMessage, Text


def to_dict(obj):
    if obj is None:
        return {}
    if isinstance(obj, dict):
        return obj
    if hasattr(obj, "to_dict"):
        return obj.to_dict()
    if hasattr(obj, "__dict__"):
        return vars(obj)
    return {}


def wav_duration(data: bytes) -> tuple[float | None, int | None]:
    try:
        with wave.open(io.BytesIO(data), "rb") as wf:
            frames = wf.getnframes()
            rate = wf.getframerate()
            channels = wf.getnchannels()
            width = wf.getsampwidth()
            max_frames = max((len(data) - 44) // max(channels * width, 1), 0)
            if frames > max_frames * 2:
                frames = max_frames
            return frames / float(rate), rate
    except Exception:
        return None, None


def set_attr(invocation: LLMInvocation, attrs: dict) -> None:
    attrs = {key: value for key, value in attrs.items() if value is not None}
    invocation.attributes.update(attrs)
    if invocation.span is not None:
        invocation.span.set_attributes(attrs)


def synthesize_qwen_tts() -> None:
    handler = get_extended_telemetry_handler()
    text = "Image, audio, and video traces are reported separately, which makes it easier to verify manual instrumentation against automatically aggregated metrics."
    invocation = LLMInvocation(
        provider="dashscope",
        request_model="qwen-tts",
        operation_name="synthesize_speech",
        output_type="audio",
        input_messages=[InputMessage(role="user", parts=[Text(content=text)])],
        attributes={
            "gen_ai.tts.channel": "qwen_tts_http",
            "gen_ai.tts.voice": "Cherry",
            "gen_ai.tts.input.text_length": len(text),
        },
    )

    with handler.llm(invocation) as llm:
        start = time.perf_counter()
        response = QwenTTSSynthesizer.call(model="qwen-tts", text=text, voice="Cherry")
        call_wall_time = time.perf_counter() - start
        payload = to_dict(response)
        output = payload.get("output") or {}
        usage = payload.get("usage") or {}
        audio = output.get("audio") or {}
        audio_bytes = b""
        if audio.get("url"):
            audio_bytes = requests.get(audio["url"], timeout=30).content
        audio_duration, sample_rate = wav_duration(audio_bytes)

        llm.response_id = payload.get("request_id")
        llm.input_tokens = usage.get("input_tokens")
        llm.output_tokens = usage.get("output_tokens")
        llm.output_messages = [
            OutputMessage(
                role="assistant",
                parts=[Text(content=f"audio generated: {audio.get('id')}")],
                finish_reason="stop",
            )
        ]
        set_attr(
            llm,
            {
                "gen_ai.tts.success": payload.get("status_code") == 200,
                "gen_ai.tts.status": "SUCCEEDED" if payload.get("status_code") == 200 else payload.get("code"),
                "gen_ai.tts.channel": "qwen_tts_http",
                "gen_ai.tts.voice": "Cherry",
                "gen_ai.tts.call.wall_time": call_wall_time,
                "gen_ai.tts.audio.duration": audio_duration,
                "gen_ai.tts.audio.bytes": len(audio_bytes) if audio_bytes else None,
                "gen_ai.tts.audio.format": "wav" if audio_bytes else None,
                "gen_ai.tts.audio.sample_rate": sample_rate,
                "gen_ai.tts.audio_tokens": (usage.get("output_tokens_details") or {}).get("audio_tokens"),
                "gen_ai.tts.usage.characters": usage.get("characters"),
                "gen_ai.usage.total_tokens": usage.get("total_tokens"),
            },
        )


def synthesize_cosyvoice() -> None:
    handler = get_extended_telemetry_handler()
    text = "DashScope speech synthesis verification is running."
    synth = TTSV2Synthesizer(
        model="cosyvoice-v1",
        voice="longxiaochun",
        format=AudioFormat.WAV_24000HZ_MONO_16BIT,
    )
    invocation = LLMInvocation(
        provider="dashscope",
        request_model="cosyvoice-v1",
        operation_name="synthesize_speech",
        output_type="audio",
        input_messages=[InputMessage(role="user", parts=[Text(content=text)])],
        attributes={
            "gen_ai.tts.channel": "dashscope_tts_v2_websocket",
            "gen_ai.tts.voice": "longxiaochun",
            "gen_ai.tts.input.text_length": len(text),
        },
    )

    try:
        with handler.llm(invocation) as llm:
            start = time.perf_counter()
            audio = synth.call(text, timeout_millis=30000) or b""
            call_wall_time = time.perf_counter() - start
            response = to_dict(synth.get_response())
            usage = (response.get("payload") or {}).get("usage") or {}
            audio_duration, sample_rate = wav_duration(audio)
            first_audio_ms = synth.get_first_package_delay()

            llm.response_id = synth.get_last_request_id()
            llm.output_messages = [
                OutputMessage(
                    role="assistant",
                    parts=[Text(content="audio generated by cosyvoice-v1")],
                    finish_reason="stop",
                )
            ]
            set_attr(
                llm,
                {
                    "gen_ai.tts.success": bool(audio),
                    "gen_ai.tts.status": "SUCCEEDED" if audio else "FAILED",
                    "gen_ai.tts.channel": "dashscope_tts_v2_websocket",
                    "gen_ai.tts.voice": "longxiaochun",
                    "gen_ai.tts.call.wall_time": call_wall_time,
                    "gen_ai.tts.first_audio.duration": first_audio_ms / 1000.0 if first_audio_ms else None,
                    "gen_ai.tts.audio.duration": audio_duration,
                    "gen_ai.tts.audio.bytes": len(audio) if audio else None,
                    "gen_ai.tts.audio.format": "wav" if audio else None,
                    "gen_ai.tts.audio.sample_rate": sample_rate,
                    "gen_ai.tts.usage.characters": usage.get("characters"),
                },
            )
    finally:
        synth.close()


synthesize_qwen_tts()
synthesize_cosyvoice()

requirements.txt

openai
fastapi
uvicorn[standard]
dashscope
requests
loongsuite-otel-util-genai>=0.6.1