使用.net调用代理

问题描述 投票:0回答:1

我需要在 .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

c# asp.net-mvc amazon-bedrock
1个回答
0
投票

我使用此代码来获取完整的代理结果作为字符串。

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());
}
© www.soinside.com 2019 - 2024. All rights reserved.