

# 叫用 AgentCore 執行期代理程式
<a name="runtime-invoke-agent"></a>

[InvokeAgentRuntime](https://docs.aws.amazon.com/bedrock-agentcore/latest/APIReference/API_InvokeAgentRuntime.html) 操作可讓您將請求傳送至由其 Amazon Resource Name (ARN) 識別的特定 AgentCore 執行期端點，並接收包含代理程式輸出的串流回應。API 透過工作階段識別符支援工作階段管理，讓您能夠在多個互動之間維持對話內容。您可以使用選用的限定詞來鎖定特定代理程式端點。

若要呼叫 `InvokeAgentRuntime` ，您需要 `bedrock-agentcore:InvokeAgentRuntime` 許可。在通話中，您也可以傳遞承載字符，讓代理程式用於使用者身分驗證。

`InvokeAgentRuntime` 操作接受您的請求承載為大小高達 100 MB 的二進位資料，並在代理程式處理您的請求時，傳回即時交付資料區塊的串流回應。此串流方法可讓您立即接收部分結果，而不是等待完整回應，因此非常適合互動式應用程式。

若要在相同工作階段中執行 shell 命令 （例如執行測試、git 操作或環境設定），請在 [ AgentCore 執行期工作階段操作中使用 Execute shell 命令](runtime-execute-command.md)。這兩個操作都適用於相同的代理程式執行時間和工作階段。

如果您打算將代理程式與 OAuth 整合，則無法使用 AWS SDK 呼叫 `InvokeAgentRuntime` 。請改為向 InvokeAgentRuntime 提出 HTTPS 請求。如需詳細資訊，請參閱[使用傳入身分驗證和傳出身分驗證進行身分驗證和授權](runtime-oauth.md)。

## 叫用串流代理程式
<a name="runtime-invoke-streaming-example"></a>

下列範例示範如何使用 boto3 叫用代理程式執行時間：

```
import boto3
import json

# Initialize the Bedrock AgentCore client
agent_core_client = boto3.client('bedrock-agentcore')

# Prepare the payload
payload = json.dumps({"prompt": prompt}).encode()

# Invoke the agent
response = agent_core_client.invoke_agent_runtime(
    agentRuntimeArn=agent_arn,
    runtimeSessionId=session_id,
    payload=payload
)


# Process and print the response
if "text/event-stream" in response.get("contentType", ""):

    # Handle streaming response
    content = []
    for line in response["response"].iter_lines(chunk_size=10):
        if line:
            line = line.decode("utf-8")
            if line.startswith("data: "):
                line = line[6:]
                print(line)
                content.append(line)
    print("\nComplete response:", "\n".join(content))

elif response.get("contentType") == "application/json":
    # Handle standard JSON response
    content = []
    for chunk in response.get("response", []):
        content.append(chunk.decode('utf-8'))
    print(json.loads(''.join(content)))

else:
    # Print raw response for other content types
    print(response)
```

## 叫用多模式代理程式
<a name="runtime-invoke-multimodal"></a>

您可以使用 `InvokeAgentRuntime`操作來傳送包含文字和影像的多模式請求。下列範例示範如何叫用多模式代理程式：

```
import boto3
import json
import base64

# Read and encode image
with open("image.jpg", "rb") as image_file:
    image_data = base64.b64encode(image_file.read()).decode('utf-8')

# Prepare multi-modal payload
payload = json.dumps({
    "prompt": "Describe what you see in this image",
    "media": {
        "type": "image",
        "format": "jpeg",
        "data": image_data
 }
}).encode()

# Invoke the agent
response = agent_core_client.invoke_agent_runtime(
    agentRuntimeArn=agent_arn,
    runtimeSessionId=session_id,
    payload=payload
)
```

## 工作階段管理
<a name="runtime-invoke-session-management"></a>

`InvokeAgentRuntime` 操作支援透過 `runtimeSessionId` 參數進行工作階段管理。透過跨多個請求提供相同的工作階段識別符，您可以維持對話內容，讓客服人員參考先前的互動。

若要開始新的對話，請產生唯一的工作階段識別符。若要繼續現有的對話，請使用先前請求的相同工作階段識別符。此方法可讓您建置互動式應用程式，以隨著時間維持內容。

**提示**  
為了獲得最佳結果，請為您的工作階段 IDs 使用 UUID 或其他唯一識別符，以避免不同使用者或對話之間發生衝突。

## 錯誤處理
<a name="runtime-invoke-error-handling"></a>

使用 `InvokeAgentRuntime`操作時，您可能會遇到各種錯誤。以下是一些常見的錯誤，以及如何處理這些錯誤：

 **ValidationException**   
當請求參數無效時發生。檢查您的客服人員 ARN、工作階段 ID 和承載格式是否正確。

 **ResourceNotFoundException**   
當找不到指定的代理程式執行時間時發生。確認代理程式 ARN 正確，且代理程式存在於您的帳戶中 AWS 。

 **AccessDeniedException**   
當您沒有必要的許可時發生。確保您的 IAM 政策包含 `bedrock-agentcore:InvokeAgentRuntime`許可。

 **ThrottlingException**   
當您超過請求率限制時發生。在應用程式中實作指數退避和重試邏輯。

在應用程式中實作適當的錯誤處理，以提供更好的使用者體驗，並有效疑難排解問題。

## 最佳實務
<a name="runtime-invoke-best-practices"></a>

使用 `InvokeAgentRuntime`操作時，請遵循下列最佳實務：
+ 使用工作階段管理來維護對話內容，以獲得更好的使用者體驗。
+ 逐步處理串流回應，以提供即時意見回饋給使用者。
+ 針對強大的應用程式實作適當的錯誤處理和重試邏輯。
+ 傳送請求時，請考慮承載大小限制 (100 MB)，尤其是多模態內容。
+ 使用適當的限定詞以特定代理程式版本或端點為目標。
+ 視需要使用承載字符實作身分驗證機制。
+ 將 `InvokeAgentRuntimeCommand`用於確定性操作 （測試、git、組建），而不是透過客服人員的 LLM 路由它們。請參閱在 [ AgentCore 執行期工作階段中執行 shell 命令](runtime-execute-command.md)。