> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-feature-automate-reference-docs-generation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Weave via service api

<Note>
  これはインタラクティブなノートブックです。ローカルで実行するか、以下のリンクを使用してください：

  * [Google Colabで開く](https://colab.research.google.com/github/wandb/weave/blob/master/docs/notebooks/weave_via_service_api.ipynb)
  * [GitHubでソースを表示](https://github.com/wandb/weave/blob/master/docs/notebooks/weave_via_service_api.ipynb)
</Note>

# Service APIを使用してトレースをログに記録しクエリする

以下のガイドでは、Weave Service APIを使用してトレースをログに記録する方法を学びます。具体的には、Service APIを使用して以下を行います：

1. [シンプルなLLMの呼び出しと応答のモックを作成し、Weaveにログを記録します。](#simple-trace)
2. [より複雑なLLMの呼び出しと応答のモックを作成し、Weaveにログを記録します。](#complex-trace)
3. [ログに記録されたトレースに対してサンプル検索クエリを実行します。](#run-a-lookup-query)

> **ログに記録されたトレースを表示する**
>
> このガイドのコードを実行して作成されたすべてのWeaveトレースは、**Traces** タブのWeaveプロジェクト（`team_id\project_id`で指定）で、トレース名を選択することで表示できます。

始める前に、[前提条件](#prerequisites-set-variables-and-endpoints)

## Prerequisites: Set variables and endpoints

以下のコードは、Service APIにアクセスするために使用されるURLエンドポイントを設定します：

* [`https://trace.wandb.ai/call/start`](https://weave-docs.wandb.ai/reference/service-api/call-start-call-start-post)
* [`https://trace.wandb.ai/call/end`](https://weave-docs.wandb.ai/reference/service-api/call-end-call-end-post)
* [`https://trace.wandb.ai/calls/stream_query`](https://weave-docs.wandb.ai/reference/service-api/calls-query-stream-calls-stream-query-post)

さらに、以下の変数を設定する必要があります：

* `project_id`：トレースをログに記録したいW\&Bプロジェクトの名前。
* `team_id`：あなたのW\&Bチーム名。
* `wandb_token`：あなたの[W\&B認証トークン](https://wandb.ai/authorize)。

```python
import datetime
import json

import requests

# Headers and URLs
headers = {"Content-Type": "application/json"}
url_start = "https://trace.wandb.ai/call/start"
url_end = "https://trace.wandb.ai/call/end"
url_stream_query = "https://trace.wandb.ai/calls/stream_query"

# W&B variables
team_id = ""
project_id = ""
wandb_token = ""
```

## シンプルなトレース

以下のセクションでは、シンプルなトレースの作成手順を説明します。

1. [シンプルなトレースを開始する](#start-a-simple-trace)
2. [シンプルなトレースを終了する](#end-a-simple-trace)

### シンプルなトレースを開始する

以下のコードはサンプルのLLM呼び出しを作成し`payload_start`、`url_start`エンドポイントを使用してWeaveにログを記録します。`payload_start`オブジェクトはOpenAIの`gpt-4o`への呼び出しを模倣し、クエリは`Why is the sky blue?`です。

成功すると、このコードはトレースが開始されたことを示すメッセージを出力します：

```
Call started. ID: 01939cdc-38d2-7d61-940d-dcca0a56c575, Trace ID: 01939cdc-38d2-7d61-940d-dcd0e76c5f34
python
## ------------
## Start trace
## ------------
payload_start = {
    "start": {
        "project_id": f"{team_id}/{project_id}",
        "op_name": "simple_trace",
        "started_at": datetime.datetime.now().isoformat(),
        "inputs": {
            # Use this "messages" style to generate the chat UI in the expanded trace.
            "messages": [{"role": "user", "content": "Why is the sky blue?"}],
            "model": "gpt-4o",
        },
        "attributes": {},
    }
}
response = requests.post(
    url_start, headers=headers, json=payload_start, auth=("api", wandb_token)
)
if response.status_code == 200:
    data = response.json()
    call_id = data.get("id")
    trace_id = data.get("trace_id")
    print(f"Call started. ID: {call_id}, Trace ID: {trace_id}")
else:
    print("Start request failed with status:", response.status_code)
    print(response.text)
    exit()
```

### シンプルなトレースを終了する

シンプルなトレースを完了するために、以下のコードはサンプルのLLM呼び出し`payload_end`を作成し、`url_end`エンドポイントを使用してWeaveにログを記録します。`payload_end`オブジェクトはOpenAIの`gpt-4o`からのレスポンスを模倣し、クエリは`Why is the sky blue?`です。このオブジェクトは、価格概要情報とチャット完了がWeaveダッシュボードのトレースビューで生成されるようにフォーマットされています。

成功すると、このコードはトレースが完了したことを示すメッセージを出力します：

```
Call ended.
python
## ------------
## End trace
## ------------
payload_end = {
    "end": {
        "project_id": f"{team_id}/{project_id}",
        "id": call_id,
        "ended_at": datetime.datetime.now().isoformat(),
        "output": {
            # Use this "choices" style to add the completion to the chat UI in the expanded trace.
            "choices": [
                {
                    "message": {
                        "content": "It’s due to Rayleigh scattering, where shorter blue wavelengths of sunlight scatter in all directions."
                    }
                },
            ]
        },
        # Format the summary like this to generate the pricing summary information in the traces table.
        "summary": {
            "usage": {
                "gpt-4o": {
                    "prompt_tokens": 10,
                    "completion_tokens": 20,
                    "total_tokens": 30,
                    "requests": 1,
                }
            }
        },
    }
}
response = requests.post(
    url_end, headers=headers, json=payload_end, auth=("api", wandb_token)
)
if response.status_code == 200:
    print("Call ended.")
else:
    print("End request failed with status:", response.status_code)
    print(response.text)
```

## 複雑なトレース

以下のセクションでは、マルチオペレーションRAG検索に似た子スパンを持つより複雑なトレースの作成手順を説明します。

1. [複雑なトレースを開始する](#complex-trace)
2. [子スパンを追加する：RAGドキュメント検索](#add-a-child-span-to-a-complex-trace-rag-document-lookup)
3. [子スパンを追加する：LLM完了呼び出し](#add-a-child-span-to-a-complex-trace-llm-completion-call)
4. [複雑なトレースを終了する](#end-a-complex-trace)

### 複雑なトレースを開始する

以下のコードは、複数のスパンを持つより複雑なトレースを作成する方法を示しています。これの例としては、検索拡張生成（RAG）検索の後にLLM呼び出しを行うことが挙げられます。最初の部分では、全体的な操作を表す親トレース（`payload_parent_start`）を初期化します。この場合、操作はユーザークエリ`Can you summarize the key points of this document?`を処理することです。

`payload_parent_start`オブジェクトは、マルチステップワークフローの初期ステップを模倣し、`url_start`エンドポイントを使用して操作をWeaveにログ記録します。

成功すると、このコードは親呼び出しがログに記録されたことを示すメッセージを出力します：

```
Parent call started. ID: 01939d26-0844-7c43-94bb-cdc471b6d65f, Trace ID: 01939d26-0844-7c43-94bb-cdd97dc296c8
python
## ------------
## Start trace (parent)
## ------------

# Parent call: Start
payload_parent_start = {
    "start": {
        "project_id": f"{team_id}/{project_id}",
        "op_name": "complex_trace",
        "started_at": datetime.datetime.now().isoformat(),
        "inputs": {"question": "Can you summarize the key points of this document?"},
        "attributes": {},
    }
}
response = requests.post(
    url_start, headers=headers, json=payload_parent_start, auth=("api", wandb_token)
)
if response.status_code == 200:
    data = response.json()
    parent_call_id = data.get("id")
    trace_id = data.get("trace_id")
    print(f"Parent call started. ID: {parent_call_id}, Trace ID: {trace_id}")
else:
    print("Parent start request failed with status:", response.status_code)
    print(response.text)
    exit()
```

### 複雑なトレースに子スパンを追加する：RAGドキュメント検索

以下のコードは、前のステップで開始した親トレースに子スパンを追加する方法を示しています。このステップは、全体的なワークフローにおけるRAGドキュメント検索のサブ操作をモデル化しています。

子トレースは`payload_child_start`オブジェクトで開始され、以下を含みます：

* `trace_id`：この子スパンを親トレースにリンクします。
* `parent_id`：子スパンを親操作に関連付けます。
* `inputs`：検索クエリをログに記録します。例えば、
  `"This is a search query of the documents I'm looking for."`

`url_start`エンドポイントへの呼び出しが成功すると、コードは子呼び出しが開始され完了したことを示すメッセージを出力します：

```
Child call started. ID: 01939d32-23d6-75f2-9128-36a4a806f179
Child call ended.
python
## ------------
## Child span:
## Ex. RAG Document lookup
## ------------

# Child call: Start
payload_child_start = {
    "start": {
        "project_id": f"{team_id}/{project_id}",
        "op_name": "rag_document_lookup",
        "trace_id": trace_id,
        "parent_id": parent_call_id,
        "started_at": datetime.datetime.now().isoformat(),
        "inputs": {
            "document_search": "This is a search query of the documents I'm looking for."
        },
        "attributes": {},
    }
}
response = requests.post(
    url_start, headers=headers, json=payload_child_start, auth=("api", wandb_token)
)
if response.status_code == 200:
    data = response.json()
    child_call_id = data.get("id")
    print(f"Child call started. ID: {child_call_id}")
else:
    print("Child start request failed with status:", response.status_code)
    print(response.text)
    exit()

# Child call: End
payload_child_end = {
    "end": {
        "project_id": f"{team_id}/{project_id}",
        "id": child_call_id,
        "ended_at": datetime.datetime.now().isoformat(),
        "output": {
            "document_results": "This will be the RAG'd document text which will be returned from the search query."
        },
        "summary": {},
    }
}
response = requests.post(
    url_end, headers=headers, json=payload_child_end, auth=("api", wandb_token)
)
if response.status_code == 200:
    print("Child call ended.")
else:
    print("Child end request failed with status:", response.status_code)
    print(response.text)
```

### 複雑なトレースに子スパンを追加する：LLM完了呼び出し

以下のコードは、親トレースに別の子スパンを追加する方法を示しており、LLM完了呼び出しを表しています。このステップは、前のRAG操作で取得されたドキュメントコンテキストに基づくAIの応答生成をモデル化しています。

LLM完了トレースは`payload_child_start`オブジェクトで開始され、以下を含みます：

* `trace_id`：この子スパンを親トレースにリンクします。
* `parent_id`：子スパンを全体的なワークフローに関連付けます。
* `inputs`：LLMの入力メッセージをログに記録し、ユーザークエリと追加されたドキュメントコンテキストを含みます。
* `model`：操作に使用されるモデルを指定します（`gpt-4o`）。

成功すると、コードはLLM子スパントレースが開始され終了したことを示すメッセージを出力します：

```
Child call started. ID: 0245acdf-83a9-4c90-90df-dcb2b89f234a
```

操作が完了すると、`payload_child_end`オブジェクトは`output`フィールドにLLMが生成した応答をログに記録することでトレースを終了します。使用状況の概要情報もログに記録されます。

成功すると、コードはLLM子スパントレースが開始され終了したことを示すメッセージを出力します：

```
Child call started. ID: 0245acdf-83a9-4c90-90df-dcb2b89f234a
Child call ended.
python
## ------------
## Child span:
## Create an LLM completion call
## ------------

# Child call: Start
payload_child_start = {
    "start": {
        "project_id": f"{team_id}/{project_id}",
        "op_name": "llm_completion",
        "trace_id": trace_id,
        "parent_id": parent_call_id,
        "started_at": datetime.datetime.now().isoformat(),
        "inputs": {
            "messages": [
                {
                    "role": "user",
                    "content": "With the following document context, could you help me answer:\n Can you summarize the key points of this document?\n [+ appended document context]",
                }
            ],
            "model": "gpt-4o",
        },
        "attributes": {},
    }
}
response = requests.post(
    url_start, headers=headers, json=payload_child_start, auth=("api", wandb_token)
)
if response.status_code == 200:
    data = response.json()
    child_call_id = data.get("id")
    print(f"Child call started. ID: {child_call_id}")
else:
    print("Child start request failed with status:", response.status_code)
    print(response.text)
    exit()

# Child call: End
payload_child_end = {
    "end": {
        "project_id": f"{team_id}/{project_id}",
        "id": child_call_id,
        "ended_at": datetime.datetime.now().isoformat(),
        "output": {
            "choices": [
                {"message": {"content": "This is the response generated by the LLM."}},
            ]
        },
        "summary": {
            "usage": {
                "gpt-4o": {
                    "prompt_tokens": 10,
                    "completion_tokens": 20,
                    "total_tokens": 30,
                    "requests": 1,
                }
            }
        },
    }
}
response = requests.post(
    url_end, headers=headers, json=payload_child_end, auth=("api", wandb_token)
)
if response.status_code == 200:
    print("Child call ended.")
else:
    print("Child end request failed with status:", response.status_code)
    print(response.text)
```

### 複雑なトレースを終了する

以下のコードは、親トレースを完了させ、ワークフロー全体の完了をマークする方法を示しています。このステップでは、すべての子スパン（RAG検索やLLM完了など）の結果を集約し、最終的な出力とメタデータをログに記録します。

トレースは`payload_parent_end`オブジェクトを使用して完了し、以下を含みます：

* `id`：初期親トレース開始からの`parent_call_id`。
* `output`：ワークフロー全体の最終出力を表します。
* `summary`：ワークフロー全体の使用データを統合します。
* `prompt_tokens`：すべてのプロンプトに使用されたトークンの合計。
* `completion_tokens`：すべての応答で生成されたトークンの合計。
* `total_tokens`：ワークフローの合計トークン数。
* `requests`：行われたリクエストの総数（この場合、`1`）。

成功すると、コードは以下を出力します：

```
Parent call ended.
python
## ------------
## End trace
## ------------

# Parent call: End
payload_parent_end = {
    "end": {
        "project_id": f"{team_id}/{project_id}",
        "id": parent_call_id,
        "ended_at": datetime.datetime.now().isoformat(),
        "output": {
            "choices": [
                {"message": {"content": "This is the response generated by the LLM."}},
            ]
        },
        "summary": {
            "usage": {
                "gpt-4o": {
                    "prompt_tokens": 10,
                    "completion_tokens": 20,
                    "total_tokens": 30,
                    "requests": 1,
                }
            }
        },
    }
}
response = requests.post(
    url_end, headers=headers, json=payload_parent_end, auth=("api", wandb_token)
)
if response.status_code == 200:
    print("Parent call ended.")
else:
    print("Parent end request failed with status:", response.status_code)
    print(response.text)
```

## 検索クエリを実行する

以下のコードは、前の例で作成されたトレースをクエリする方法を示しており、`inputs.model`フィールドが`gpt-4o`に等しいトレースのみをフィルタリングします。

`query_payload`オブジェクトには以下が含まれます：

* `project_id`：クエリするチームとプロジェクトを識別します。
* `filter`：クエリが**trace roots**（トップレベルのトレース）のみを返すようにします。
* `query`：`$expr` operator:
  * `$getField`：`inputs.model`フィールドを取得します。
  * `$literal`：`inputs.model`が`"gpt-4o"`に等しいトレースを一致させます。
* `limit`：クエリを10,000件の結果に制限します。
* `offset`: クエリを最初の結果から開始します。
* `sort_by`: 結果を`started_at` タイムスタンプの降順で並べ替えます。
* `include_feedback`: 結果からフィードバックデータを除外します。

クエリが成功すると、レスポンスにはクエリパラメータに一致するトレースデータが含まれます：

```
{'id': '01939cf3-541f-76d3-ade3-50cfae068b39', 'project_id': 'cool-new-team/uncategorized', 'op_name': 'simple_trace', 'display_name': None, 'trace_id': '01939cf3-541f-76d3-ade3-50d5cfabe2db', 'parent_id': None, 'started_at': '2024-12-06T17:10:12.590000Z', 'attributes': {}, 'inputs': {'messages': [{'role': 'user', 'content': 'Why is the sky blue?'}], 'model': 'gpt-4o'}, 'ended_at': '2024-12-06T17:47:08.553000Z', 'exception': None, 'output': {'choices': [{'message': {'content': 'It’s due to Rayleigh scattering, where shorter blue wavelengths of sunlight scatter in all directions.'}}]}, 'summary': {'usage': {'gpt-4o': {'prompt_tokens': 10, 'completion_tokens': 20, 'requests': 1, 'total_tokens': 30}}, 'weave': {'status': 'success', 'trace_name': 'simple_trace', 'latency_ms': 2215963}}, 'wb_user_id': 'VXNlcjoyMDk5Njc0', 'wb_run_id': None, 'deleted_at': None}
python
query_payload = {
    "project_id": f"{team_id}/{project_id}",
    "filter": {"trace_roots_only": True},
    "query": {
        "$expr": {"$eq": [{"$getField": "inputs.model"}, {"$literal": "gpt-4o"}]}
    },
    "limit": 10000,
    "offset": 0,
    "sort_by": [{"field": "started_at", "direction": "desc"}],
    "include_feedback": False,
}
response = requests.post(
    url_stream_query, headers=headers, json=query_payload, auth=("api", wandb_token)
)
if response.status_code == 200:
    print("Query successful!")
    try:
        data = response.json()
        print(data)
    except json.JSONDecodeError as e:
        # Alternate decode
        json_objects = response.text.strip().split("\n")
        parsed_data = [json.loads(obj) for obj in json_objects]
        print(parsed_data)
else:
    print(f"Query failed with status code: {response.status_code}")
    print(response.text)
```
