

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 從您的應用程式調用代理程式
<a name="agents-invoke-agent"></a>

透過使用 [Amazon Bedrock 代理程式執行時期端點](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-rt)提出 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 請求，在應用程式中使用代理程式。

根據預設，`InvokeAgent` 的回應包含一個區塊，其中包含來自代理程式的完整回應，這可能需要一些時間才能完成。或者，您也可以將 `InvokeAgent` 設定為在多個較小的區塊中串流回應。這可減少代理程式初始回應的延遲。

**串流回應**

您可以選擇在串流組態 ([StreamingConfigurations](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_StreamingConfigurations.html)) 中將 `streamFinalResponse` 設定為 `true`，以啟用回應的串流。回應串流包含多個事件，每個回應部分的區塊會依序排列。

若要串流回應，請確定代理程式執行角色包含已設定代理程式模型的 `bedrock:InvokeModelWithResponseStream` 許可。如需詳細資訊，請參閱 [代理程式服務角色的身分型許可](agents-permissions.md#agents-permissions-identity)。

如果您的代理程式已設定了防護機制，您也可以在 `StreamingConfigurations` 中指定 `applyGuardrailInterval`，以控制對傳出回應字元發出 `ApplyGuardrail` 呼叫的頻率 (例如，每 50 個字元)。

根據預設，防護機制間隔設定為 50 個字元。如果指定較大的間隔，則會在 `ApplyGuardrail` 呼叫較少的較大區塊中產生回應。下列範例顯示針對*您好，我是代理程式*輸入字串產生的回應。

**區塊回應範例：間隔設定為 3 個字元**

```
'Hel', 'lo, ', 'I am', ' an', ' Age', 'nt'
```

每個區塊至少有 3 個字元，最後一個區塊除外。

**區塊回應範例：間隔設定為 20 個或更多字元**

```
'Hello, I am an Agent'
```

## 調用代理程式
<a name="invoke-agent-example"></a>

下列 Python 範例顯示如何呼叫 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 操作並顯示代理程式的輸出，以及呼叫產生的任何[追蹤](trace-events.md)資訊。

**調用代理程式**

1. 遵循[手動建立和設定代理程式](agents-create.md)中的指示建立代理程式。記下代理程式的 ID。如有必要，您可以稍後取得 ID。如需詳細資訊，請參閱 [檢視代理程式的資訊](agents-view.md)。

1. 遵循[建立代理程式別名](deploy-agent-proc.md)中的指示，為代理程式建立別名。記下別名的 ID。如有必要，您可以稍後取得 ID。如需詳細資訊，請參閱 [檢視 Amazon Bedrock 中代理程式別名的相關資訊](agents-alias-view.md)。

1. 執行下列程式碼。將 `agent_id` 的值更新為代理程式的 ID，並將 `alias_id` 的值更新為代理程式的別名 ID。若要從代理程式串流回應，請將 `streamFinalResponse` 的值變更為 `True`。您也可以透過變更 `applyGuardrailInterval` 的值來變更防護機制間隔。

   ```
   import boto3
   import logging
   
   from botocore.exceptions import ClientError
   
   
   logging.basicConfig(level=logging.INFO)
   logger = logging.getLogger(__name__)
   
   def invoke_agent(client, agent_id, alias_id, prompt, session_id):
           response = client.invoke_agent(
               agentId=agent_id,
               agentAliasId=alias_id,
               enableTrace=True,
               sessionId = session_id,
               inputText=prompt,
               streamingConfigurations = { 
       "applyGuardrailInterval" : 20,
         "streamFinalResponse" : False
               }
           )
           completion = ""
           for event in response.get("completion"):
               #Collect agent output.
               if 'chunk' in event:
                   chunk = event["chunk"]
                   completion += chunk["bytes"].decode()
               
               # Log trace output.
               if 'trace' in event:
                   trace_event = event.get("trace")
                   trace = trace_event['trace']
                   for key, value in trace.items():
                       logging.info("%s: %s",key,value)
   
           print(f"Agent response: {completion}")
   
   
   if __name__ == "__main__":
   
       client=boto3.client(
               service_name="bedrock-agent-runtime"
           )
       
       agent_id = "AGENT_ID"
       alias_id = "ALIAS_ID"
       session_id = "MY_SESSION_ID"
       prompt = "Prompt to send to agent"
   
       try:
   
           invoke_agent(client, agent_id, alias_id, prompt, session_id)
   
       except ClientError as e:
           print(f"Client error: {str(e)}")
           logger.error("Client error: %s", {str(e)})
   ```