OpenAIWrapper - AG2

OpenAIWrapper

autogen.OpenAIWrapper

OpenAIWrapper(*, config_list=None, **base_config)

A wrapper class for openai client. Initialize the OpenAIWrapper.

PARAMETER DESCRIPTION
config_list a list of config dicts to override the base_config. They can contain additional kwargs as allowed in the create method. E.g.,
<br> config_list = [<br> {<br> "model": "gpt-4",<br> "api_key": os.environ.get("AZURE_OPENAI_API_KEY"),<br> "api_type": "azure",<br> "base_url": os.environ.get("AZURE_OPENAI_API_BASE"),<br> "api_version": "2024-02-01",<br> },<br> {<br> "model": "gpt-3.5-turbo",<br> "api_key": os.environ.get("OPENAI_API_KEY"),<br> "base_url": "https://api.openai.com/v1",<br> },<br> {<br> "model": "llama-7B",<br> "base_url": "http://127.0.0.1:8080",<br> },<br> ]<br>
TYPE: `list[dict[str, Any]]
base_config base config. It can contain both keyword arguments for openai client and additional kwargs. When using OpenAI or Azure OpenAI endpoints, please specify a non-empty 'model' either in base_config or in each config of config_list.
TYPE: Any DEFAULT: {}

Source code in autogen/oai/client.py

801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
def __init__(self, *, config_list: list[dict[str, Any]] | None = None, **base_config: Any):
    """Initialize the OpenAIWrapper.

Args:
        config_list: a list of config dicts to override the base_config.
            They can contain additional kwargs as allowed in the [create](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create) method. E.g.,
            ```python
                config_list = [
                    {
                        "model": "gpt-4",
                        "api_key": os.environ.get("AZURE_OPENAI_API_KEY"),
                        "api_type": "azure",
                        "base_url": os.environ.get("AZURE_OPENAI_API_BASE"),
                        "api_version": "2024-02-01",
                    },
                    {
                        "model": "gpt-3.5-turbo",
                        "api_key": os.environ.get("OPENAI_API_KEY"),
                        "base_url": "https://api.openai.com/v1",
                    },
                    {
                        "model": "llama-7B",
                        "base_url": "http://127.0.0.1:8080",
                    },
                ]
            ```
        base_config: base config. It can contain both keyword arguments for openai client
            and additional kwargs.
            When using OpenAI or Azure OpenAI endpoints, please specify a non-empty 'model' either in `base_config` or in each config of `config_list`.
    """
    if logging_enabled():
        log_new_wrapper(self, locals())
    openai_config, extra_kwargs = self._separate_openai_config(base_config)
    self._clients: list[ModelClient] = []
    self._config_list: list[dict[str, Any]] = []
    self.routing_method = base_config.get("routing_method") or "fixed_order"
    self._round_robin_index = 0
    self._response_metadata: dict[str, dict[str, Any]] = {}  # response_id → metadata
    self._response_buffer: deque[str] = deque(maxlen=100)  # Circular buffer of response IDs
    self._response_buffer_size = base_config.get("response_buffer_size", 100)
    if self._response_buffer_size != 100:
        self._response_buffer = deque(maxlen=self._response_buffer_size)
    extra_kwargs.pop("routing_method", None)
    if config_list:
        config_list = [
            config.model_dump() if hasattr(config, "model_dump") else config.copy() for config in config_list
        ]  # make a copy before modifying
        for config_item in config_list:
            self._register_default_client(config_item, openai_config)
            config_item_specific_extras = {k: v for k, v in config_item.items() if k not in self.openai_kwargs}
            self._config_list.append({**extra_kwargs, **config_item_specific_extras})
    else:
        self._register_default_client(extra_kwargs, openai_config)
        self._config_list = [extra_kwargs]
    self.wrapper_id = id(self)

extra_kwargs

extra_kwargs = {'agent', 'cache', 'cache_seed', 'filter_func', 'allow_format_str_template', 'context', 'api_version', 'api_type', 'tags', 'price'}

openai_kwargs

openai_kwargs

total_usage_summary

total_usage_summary = None

actual_usage_summary

actual_usage_summary = None

routing_method

routing_method = get('routing_method') or 'fixed_order'

wrapper_id

wrapper_id = id(self)

register_model_client

register_model_client(model_client_cls, **kwargs)

Register a model client.

PARAMETER DESCRIPTION
model_client_cls A custom client class that follows the ModelClient interface
TYPE: ModelClient
kwargs The kwargs for the custom client class to be initialized with
TYPE: Any DEFAULT: {}

Source code in autogen/oai/client.py

1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
def register_model_client(self, model_client_cls: ModelClient, **kwargs: Any):
    """Register a model client.

Args:
        model_client_cls: A custom client class that follows the ModelClient interface
        kwargs: The kwargs for the custom client class to be initialized with
    """
    existing_client_class = False
    for i, client in enumerate(self._clients):
        if isinstance(client, PlaceHolderClient):
            placeholder_config = client.config
            if placeholder_config.get("model_client_cls") == model_client_cls.__name__:
                self._clients[i] = model_client_cls(placeholder_config, **kwargs)
                return
        elif isinstance(client, model_client_cls):
            existing_client_class = True
    if existing_client_class:
        logger.warning(<br>            f"Model client {model_client_cls.__name__} is already registered. Add more entries in the config_list to use multiple model clients."
        )
    else:
        raise ValueError(<br>            f'Model client "{model_client_cls.__name__}" is being registered but was not found in the config_list. '<br>            f'Please make sure to include an entry in the config_list with "model_client_cls": "{model_client_cls.__name__}"'<br>        )

instantiate

instantiate(template, context=None, allow_format_str_template=False)

Source code in autogen/oai/client.py

1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
@classmethod
def instantiate(cls, template: str | Callable[[dict[str, Any]], str] | None, context: dict[str, Any] | None = None, allow_format_str_template: bool | None = False) -> str | None:
    if not context or template is None:
        return template  # type: ignore [return-value]
    if isinstance(template, str):
        return template.format(**context) if allow_format_str_template else template
    return template(context)

create

create(**config)

Make a completion for a given config using available clients. Besides the kwargs allowed in openai's [or other] client, we allow the following additional kwargs. The config in each client will be overridden by the config.

PARAMETER DESCRIPTION
**config The config for the completion.
TYPE: Any DEFAULT: {}
RAISES DESCRIPTION
RuntimeError If all declared custom model clients are not registered
APIError If any model client create call raises an APIError

Source code in autogen/oai/client.py

1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
def create(self, **config: Any) -> ModelClient.ModelClientResponseProtocol:
    """Make a completion for a given config using available clients.
    Besides the kwargs allowed in openai's [or other] client, we allow the following additional kwargs.
    The config in each client will be overridden by the config.
    Args:
        **config: The config for the completion.
    Raises:
        RuntimeError: If all declared custom model clients are not registered
        APIError: If any model client create call raises an APIError
    """
    invocation_id = str(uuid.uuid4())
    last = len(self._clients) - 1
    non_activated = [
        client.config["model_client_cls"] for client in self._clients if isinstance(client, PlaceHolderClient)
    ]
    if non_activated:
        raise RuntimeError(
            f"Model client(s) {non_activated} are not activated. Please register the custom model clients using `register_model_client` or filter them out form the config list."
        )
    ordered_clients_indices = list(range(len(self._clients)))
    if self.routing_method == "round_robin" and len(self._clients) > 0:
        ordered_clients_indices = (
            ordered_clients_indices[self._round_robin_index :] + ordered_clients_indices[: self._round_robin_index]
        )
        self._round_robin_index = (self._round_robin_index + 1) % len(self._clients)
    for i in ordered_clients_indices:
        client_config = self._config_list[i]
        full_config = merge_config_with_tools(config, client_config)
        create_config, extra_kwargs = self._separate_create_config(full_config)
        params = self._construct_create_params(create_config, extra_kwargs)
        cache_seed = extra_kwargs.get("cache_seed")
        cache = extra_kwargs.get("cache")
        filter_func = extra_kwargs.get("filter_func")
        context = extra_kwargs.get("context")
        agent = extra_kwargs.get("agent")
        price = extra_kwargs.get("price", None)
        if isinstance(price, list):
            price = tuple(price)
        elif isinstance(price, (float, int)):
            logger.warning(
                "Input price is a float/int. Using the same price for prompt and completion tokens. Use a list/tuple if prompt and completion token prices are different."
            )
            price = (price, price)
        total_usage = None
        actual_usage = None
        cache_client = None
        if cache is not None:
            cache_client = cache
        elif cache_seed is not None:
            cache_client = Cache.disk(cache_seed, LEGACY_CACHE_DIR)
        client = self._clients[i]
        log_cache_seed_value(cache if cache is not None else cache_seed, client=client)
        if cache_client is not None:
            with cache_client as cache:
                key = get_key(
                    {
                        **params,
                        **{"response_format": json.dumps(TypeAdapter(params["response_format"]).json_schema())},
                    }
                    if "response_format" in params and not isinstance(params["response_format"], dict)
                    else params
                )
                request_ts = get_current_ts()
                response: ChatCompletionExtended | None = cache.get(key, None)
                if response is not None:
                    if hasattr(response, "message_retrieval_function"):
                        response.message_retrieval_function = client.message_retrieval
                    try:
                        response.cost
                    except AttributeError:
                        response.cost = client.cost(response)
                        cache.set(key, response)
                    total_usage = client.get_usage(response)
                    if logging_enabled():
                        log_chat_completion(
                            invocation_id=invocation_id,
                            client_id=id(client),
                            wrapper_id=id(self),
                            agent=agent,
                            request=params,
                            response=response,
                            is_cached=1,
                            cost=response.cost if response.cost is not None else 0.0,
                            start_time=request_ts,
                        )
                    pass_filter = filter_func is None or filter_func(context=context, response=response)
                    if pass_filter or i == last:
                        if hasattr(response, "id"):
                            self._store_response_metadata(response.id, client, i, pass_filter)
                        if hasattr(response, "config_id"):
                            response.config_id = i
                        if hasattr(response, "pass_filter"):
                            response.pass_filter = pass_filter
                        self._update_usage(actual_usage=actual_usage, total_usage=total_usage)
                        return response
                    continue
        try:
            request_ts = get_current_ts()
            response = client.create(params)
        except Exception as e:
            if openai_result.is_successful:
                if APITimeoutError is not None and isinstance(e, APITimeoutError):
                    if i == last:
                        raise TimeoutError(
                            "OpenAI API call timed out. This could be due to congestion or too small a timeout value. The timeout can be specified by setting the 'timeout' value (in seconds) in the llm_config (if you are using agents) or the OpenAIWrapper constructor (if you are using the OpenAIWrapper directly)."
                        ) from e
                elif APIError is not None and isinstance(e, APIError):
                    error_code = getattr(e, "code", None)
                    if logging_enabled():
                        log_chat_completion(
                            invocation_id=invocation_id,
                            client_id=id(client),
                            wrapper_id=id(self),
                            agent=agent,
                            request=params,
                            response=f"error_code:{error_code}, config {i} failed",
                            is_cached=0,
                            cost=0,
                            start_time=request_ts,
                        )
                    if error_code == "content_filter":
                        raise
                    if i == last:
                        raise
                else:
                    raise
            else:
                raise
        except (<br>            gemini_InternalServerError,<br>            gemini_ResourceExhausted,<br>            anthorpic_InternalServerError,<br>            anthorpic_RateLimitError,<br>            mistral_SDKError,<br>            mistral_HTTPValidationError,<br>            together_TogetherException,<br>            groq_InternalServerError,<br>            groq_RateLimitError,<br>            groq_APIConnectionError,<br>            cohere_InternalServerError,<br>            cohere_TooManyRequestsError,<br>            cohere_ServiceUnavailableError,<br>            ollama_RequestError,<br>            ollama_ResponseError,<br>            bedrock_BotoCoreError,<br>            bedrock_ClientError,<br>            cerebras_AuthenticationError,<br>            cerebras_InternalServerError,<br>            cerebras_RateLimitError,<br>        ):
            if i == last:
                raise
        else:
            if price is not None:
                response.cost = self._cost_with_customized_price(response, price)
            else:
                response.cost = client.cost(response)
            actual_usage = client.get_usage(response)
            total_usage = actual_usage.copy() if actual_usage is not None else total_usage
            self._update_usage(actual_usage=actual_usage, total_usage=total_usage)
            if cache_client is not None:
                with cache_client as cache:
                    cache.set(key, response)
            if logging_enabled():
                log_chat_completion(
                    invocation_id=invocation_id,
                    client_id=id(client),
                    wrapper_id=id(self),
                    agent=agent,
                    request=params,
                    response=response,
                    is_cached=0,
                    cost=response.cost,
                    start_time=request_ts,
                )
            if hasattr(response, "message_retrieval_function"):
                response.message_retrieval_function = client.message_retrieval
            pass_filter = filter_func is None or filter_func(context=context, response=response)
            if pass_filter or i == last:
                if hasattr(response, "id"):
                    self._store_response_metadata(response.id, client, i, pass_filter)
                if hasattr(response, "config_id"):
                    response.config_id = i
                if hasattr(response, "pass_filter"):
                    response.pass_filter = pass_filter
                return response
            continue
    raise RuntimeError("Should not reach here.")

print_usage_summary

print_usage_summary(mode=['actual', 'total'])

Print the usage summary.

Source code in autogen/oai/client.py

1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
def print_usage_summary(self, mode: str | list[str] = ["actual", "total"]) -> None:
    """Print the usage summary."""
    iostream = IOStream.get_default()
    if isinstance(mode, list):
        if len(mode) == 0 or len(mode) > 2:
            raise ValueError(f'Invalid mode: {mode}, choose from "actual", "total", ["actual", "total"]')
        if "actual" in mode and "total" in mode:
            mode = "both"
        elif "actual" in mode:
            mode = "actual"
        elif "total" in mode:
            mode = "total"
    iostream.send(
        UsageSummaryEvent(
            actual_usage_summary=self.actual_usage_summary, total_usage_summary=self.total_usage_summary, mode=mode
        )
    )

clear_usage_summary

clear_usage_summary()

Clear the usage summary.

Source code in autogen/oai/client.py

1566
1567
1568
1569
def clear_usage_summary(self) -> None:
    """Clear the usage summary."""
    self.total_usage_summary = None
    self.actual_usage_summary = None

extract_text_or_completion_object

extract_text_or_completion_object(response)

Extract the text or ChatCompletion objects from a completion or chat response. Supports both legacy responses (with message_retrieval_function) and new serializable responses.

PARAMETER DESCRIPTION
response The response from any client (ChatCompletion, UnifiedResponse, etc.)
TYPE: Any
RETURNS DESCRIPTION
`list[str] list[dict[str, Any]]`

Source code in autogen/oai/client.py

1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
def extract_text_or_completion_object(self, response: Any) -> list[str] | list[dict[str, Any]]:
    """Extract the text or ChatCompletion objects from a completion or chat response.
    Supports both legacy responses (with message_retrieval_function) and new serializable responses.
    Args:
        response: The response from any client (ChatCompletion, UnifiedResponse, etc.)
    Returns:
        A list of text, or a list of message dicts if function_call/tool_calls are present.
    """
    if hasattr(response, "message_retrieval_function") and callable(response.message_retrieval_function):
        return response.message_retrieval_function(response)  # type: ignore [misc]
    if hasattr(response, "id") and response.id in self._response_metadata:
        metadata = self._response_metadata[response.id]
        client = metadata["client"]
        return client.message_retrieval(response)
    if hasattr(response, "choices"):
        return [
            choice.message
            if hasattr(choice.message, "tool_calls") and choice.message.tool_calls
            else getattr(choice.message, "content", "")
            for choice in response.choices
        ]
    warnings.warn(
        f"Could not extract messages from response type {type(response).__name__}. "
        "Response may not be in metadata buffer or may not support extraction.",
        UserWarning,
    )
    return []