oai.bedrock
为Amazon Bedrock Converse API创建一个兼容的客户端。
使用示例:
通过运行pip install --upgrade boto3
安装boto3
包。
导入 autogen
config_list = [ { "api_type": "bedrock", "model": "meta.llama3-1-8b-instruct-v1:0", "aws_region": "us-west-2", "aws_access_key": "", "aws_secret_key": "", "price" : [0.003, 0.015] } ]
assistant = autogen.AssistantAgent("assistant", llm_config={"config_list": config_list})
BedrockClient
class BedrockClient()
适用于Amazon的Bedrock Converse API的客户端。
__init__
def __init__(**kwargs: Any)
初始化用于Amazon的Bedrock Converse API的BedrockClient
消息检索
def message_retrieval(response)
从响应中检索消息。
parse_custom_params
def parse_custom_params(params: Dict[str, Any])
解析此客户端类中用于逻辑的自定义参数
parse_params
def parse_params(
params: Dict[str, Any]) -> tuple[Dict[str, Any], Dict[str, Any]]
加载调用Bedrock Converse所需的有效参数 返回一个元组,包含 (base_params, additional_params)
创建
def create(params)
运行Amazon Bedrock推理并返回AutoGen响应
成本
def cost(response: ChatCompletion) -> float
计算响应的成本。
get_usage
@staticmethod
def get_usage(response) -> Dict
获取tokens的使用情况及其成本信息。
extract_system_messages
def extract_system_messages(messages: List[dict]) -> List
从消息列表中提取系统消息。
参数:
messages
list[dict] - 消息列表。
返回:
List[SystemMessage]
- 系统消息列表。
oai_messages_to_bedrock_messages
def oai_messages_to_bedrock_messages(
messages: List[Dict[str, Any]], has_tools: bool,
supports_system_prompts: bool) -> List[Dict]
将消息从OAI格式转换为Bedrock格式。 我们修正任何特定的角色顺序和类型等。 AWS Bedrock要求消息在用户和助手角色之间交替。此函数通过根据需要插入“请继续”消息,确保消息以正确的顺序和格式适用于Bedrock。 这与Autogen Anthropic客户端中的方法相同。
parse_image
def parse_image(image_url: str) -> Tuple[bytes, str]
尝试从图像URL获取原始数据。
参考:https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ImageSource.html 返回一个(Image Data, Content Type)的元组
format_tool_calls
def format_tool_calls(content)
将Converse API响应工具调用转换为AutoGen格式
convert_stop_reason_to_finish_reason
def convert_stop_reason_to_finish_reason(
stop_reason: str
) -> Literal["stop", "length", "tool_calls", "content_filter"]
根据OpenAI,将Bedrock的完成原因转换为我们的完成原因:
- stop: 如果模型遇到自然停止点或提供的停止序列,
- length: 如果达到了请求中指定的最大令牌数,
- content_filter: 如果内容因内容过滤器的标记而被省略,
- tool_calls: 如果模型调用了一个工具
calculate_cost
def calculate_cost(input_tokens: int, output_tokens: int,
model_id: str) -> float
使用Bedrock定价计算完成成本。