リクエストヘッダーへのアクセス¶
When your agent is deployed, you may need to access HTTP request headers for authentication, tracking, or custom metadata. DataRobot makes headers available to your agent code through the chat() function's **kwargs parameter.
X-Untrusted-*ヘッダーの抽出¶
X-Untrusted-*プレフィックスを持つヘッダーは、元のリクエストから渡され、kwargsディクショナリで使用できます。 agent_generic_base/custom_model/custom.pyにあります。
from typing import 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,
model: str,
**kwargs,
) -> 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.
print(f"Authorization header: {authorization_header}")
# Continue with agent logic...
一般的なユースケース¶
リクエストヘッダーは、エージェントのワークフローでさまざまな目的に使用できます。 以下の例は、ヘッダー情報を抽出して使用するための一般的なパターンを示します。
外部サービスに認証を渡す¶
リクエストヘッダーから認証トークンを抽出し、外部サービスに渡します。 これにより、受信リクエストから下流のツールおよびサービスに資格情報を転送できます。
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、その他のメタデータを追跡します。 これにより、エージェントワークフローを通じてリクエストを追跡できます。
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}")
条件付きのエージェントの動作¶
ヘッダーからのリクエストコンテキストに基づいて、エージェントの動作を調整します。 これにより、さまざまなリージョン、ユーザー、またはデプロイコンテキストに対してエージェントの動作をカスタマイズできます。
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)
重要な注意事項¶
エージェントコードでリクエストヘッダーを扱う際には、以下の点に注意してください。
- Only headers with the
X-Untrusted-*prefix are passed through to your agent code. - Headers are case-sensitive when accessing them from the dictionary.
- Always provide default values or check for
Nonewhen accessing headers that may not be present. - Headers are available in both streaming and non-streaming chat responses.
Log request headers for debugging¶
使用可能なすべてのヘッダーをログに記録して、エージェントに渡される内容を調べます。
import logging
def chat(completion_create_params, model, **kwargs):
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...