# リクエストヘッダーへのアクセス

> リクエストヘッダーへのアクセス - 認証、追跡、およびカスタムメタデータのために、デプロイされたエージェントのHTTPリクエストヘッダーにアクセスする方法について説明します。

This Markdown file sits beside the HTML page at the same path (with a `.md` suffix). It summarizes the topic and lists links for tools and LLM context.

Companion generated at `2026-07-15T05:55:44.566197+00:00` (UTC).

## Primary page

- [リクエストヘッダーへのアクセス](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-request-headers.html.md): Full documentation for this topic (Markdown sidecar).

## Sections on this page

- [X-Untrusted-*ヘッダーの抽出](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-request-headers.html.md#extracting-x-untrusted-headers): In-page section heading.
- [一般的なユースケース](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-request-headers.html.md#common-use-cases-for-headers): In-page section heading.
- [外部サービスに認証を渡す](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-request-headers.html.md#_1): In-page section heading.
- [リクエストメタデータの追跡](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-request-headers.html.md#_2): In-page section heading.
- [条件付きのエージェントの動作](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-request-headers.html.md#_3): In-page section heading.
- [重要な注意事項](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-request-headers.html.md#header-considerations): In-page section heading.
- [デバッグのためリクエストヘッダーのログを取る](https://docs.datarobot.com/ja/docs/agentic-ai/agentic-develop/agentic-request-headers.html.md#_4): In-page section heading.

## Documentation content

エージェントがデプロイされると、認証、追跡、またはカスタムメタデータのために、HTTPリクエストヘッダーにアクセスする必要があるかもしれません。 DataRobot は `chat()` 関数の `**kwargs` パラメーターを通して、エージェントコードからヘッダーを利用できるようにします。

## X-Untrusted-*ヘッダーの抽出

`X-Untrusted-*` プレフィックスを持つヘッダーは、元のリクエストから渡されます。 これらは、 `agent/agent/custom.py` にある `kwargs` ディクショナリに含まれています。

```
# agent/agent/custom.py
import asyncio
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Iterator, Union
from openai.types.chat import CompletionCreateParams
from openai.types.chat.completion_create_params import (
    CompletionCreateParamsNonStreaming,
    CompletionCreateParamsStreaming,
)

def chat(
    completion_create_params: CompletionCreateParams
    | CompletionCreateParamsNonStreaming
    | CompletionCreateParamsStreaming,
    load_model_result: tuple[ThreadPoolExecutor, asyncio.AbstractEventLoop],
    **kwargs: Any,
) -> Union[CustomModelChatResponse, Iterator[CustomModelStreamingResponse]]:
    # Extract all headers from kwargs
    headers = kwargs.get("headers", {})

    # Access specific X-Untrusted-* headers
    authorization_header = headers.get("X-Untrusted-Authorization")
    custom_header = headers.get("X-Untrusted-Custom-Metadata")

    # Use headers in your agent logic
    if authorization_header:
        # Pass to downstream services, tools, etc.
        # Do not log raw authorization tokens; log only non-sensitive metadata.
        request_id = headers.get("X-Untrusted-Request-ID")
        if request_id:
            print(f"Processing request {request_id} with authorization header present")
        else:
            print("Processing request with authorization header present")

    # Continue with agent logic... 
```

## 一般的なユースケース

リクエストヘッダーは、エージェントのワークフローでさまざまな目的に使用できます。 以下の例は、ヘッダー情報を抽出して使用するための一般的なパターンを示します。

### 外部サービスに認証を渡す

リクエストヘッダーから認証トークンを抽出し、外部サービスに渡します。 これにより、受信リクエストから下流のツールおよびサービスに資格情報を転送できます。

```
# agent/agent/custom.py
headers = kwargs.get("headers", {})
auth_token = headers.get("X-Untrusted-Authorization")

# Use the token to authenticate with external APIs
tool_client = MyTool(auth_token=auth_token) 
```

### リクエストメタデータの追跡

ヘッダーを使用して、デバッグや分析のためにリクエストID、ユーザーID、その他のメタデータを追跡します。 これにより、エージェントワークフローを通じてリクエストを追跡できます。

```
# agent/agent/custom.py
headers = kwargs.get("headers", {})
request_id = headers.get("X-Untrusted-Request-ID")
user_id = headers.get("X-Untrusted-User-ID")

# Log metadata for debugging or analytics
logging.info(f"Processing request {request_id} for user {user_id}") 
```

### 条件付きのエージェントの動作

ヘッダーからのリクエストコンテキストに基づいて、エージェントの動作を調整します。 これにより、さまざまなリージョン、ユーザー、またはデプロイコンテキストに対してエージェントの動作をカスタマイズできます。

```
# agent/agent/custom.py
headers = kwargs.get("headers", {})
region = headers.get("X-Untrusted-Region")

# Adjust agent behavior based on request context
if region == "EU":
    agent = MyAgent(enable_gdpr_mode=True) 
```

## 重要な注意事項

エージェントコードでリクエストヘッダーを扱う際には、以下の点に注意してください。

- X-Untrusted-* プレフィックスを持つヘッダーのみが、エージェントコードに渡されます。
- ディクショナリからヘッダーにアクセスする場合、英大文字と英小文字は区別されます。
- 存在しない可能性のあるヘッダーにアクセスする場合、常にデフォルト値を指定するか、「なし」をチェックします。
- ヘッダーは、ストリーミングと非ストリーミングの両方のチャット回答で使用できます。

## デバッグのためリクエストヘッダーのログを取る

使用可能なすべてのヘッダーをログに記録して、エージェントに渡される内容を調べます。

```
# agent/agent/custom.py
import asyncio
import logging
from concurrent.futures import ThreadPoolExecutor
from typing import Any

def chat(completion_create_params, load_model_result: tuple[ThreadPoolExecutor, asyncio.AbstractEventLoop], **kwargs: Any):
    headers = kwargs.get("headers", {})

    # Log all headers to inspect what's available
    if headers:
        logging.warning(f"All headers: {dict(headers)}")

    # Continue with agent logic... 
```
