Invoke Agent using .net

101 Views Asked by At

I need to completions same in .NET

completion = ""
traces =[]

try:
        bedrock_client = self.return_runtime_client(run_time=True)
        response = bedrock_client.invoke_agent(
            agentId=agent_id,
            agentAliasId=agent_alias_id,
            sessionId=session_id,
            inputText=prompt,
        )
        #print(response.get("completion"))
        #print(response)
        for event in response.get("completion"):
            #print(event)
            try:
                trace = event["trace"]
                traces.append(trace['trace'])
            except KeyError:
                chunk = event["chunk"]
                completion = completion + chunk["bytes"].decode()
            except Exception as e:
                print(e)

    except ClientError as e:
        print(e)

    return completion, traces

C#

public static async Task<string> InvokeBedrockAgentAsync(string prompt)
{
    AmazonBedrockAgentRuntimeClient client = new(RegionEndpoint.USEast1);

    // list agents
    InvokeAgentResponse response = await client.InvokeAgentAsync(new InvokeAgentRequest()
        {
            AgentId = "******",
            AgentAliasId = "****",
            SessionId = Guid.NewGuid().ToString(),
            InputText = prompt
        });

    if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
    {
        // Here I need completion and traces, same as above in Python 

    }
    else
    {
        Console.WriteLine("InvokeModelAsync failed with status code " + response.HttpStatusCode);
    }
}

https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/BedrockAgentRuntime/TInvokeAgentResponse.html

1

There are 1 best solutions below

0
On

Iam using this code to get get the complete agent result as string.

InvokeAgentResponse response = await client.InvokeAgentAsync(request);
if(response.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
    MemoryStream output = new MemoryStream();
    foreach(PayloadPart item in response.Completion)
    {
        item.Bytes.CopyTo(output);
    }
    var result = Encoding.UTF8.GetString(output.ToArray());
}