classModelClient(Protocol): """ A client class must implement the following methods: - create must return a response object that implements the ModelClientResponseProtocol - cost must return the cost of the response - get_usage must return a dict with the following keys: - prompt_tokens - completion_tokens - total_tokens - cost - model This class is used to create a client that can be used by OpenAIWrapper. The response returned from create must adhere to the ModelClientResponseProtocol but can be extended however needed. The message_retrieval method must be implemented to return a list of str or a list of messages from the response. """
defmessage_retrieval( self, response: ModelClientResponseProtocol ) -> Union[List[str], List[ModelClient.ModelClientResponseProtocol.Choice.Message]]: """ Retrieve and return a list of strings or a list of Choice.Message from the response. NOTE: if a list of Choice.Message is returned, it currently needs to contain the fields of OpenAI's ChatCompletion Message object, since that is expected for function or tool calling in the rest of the codebase at the moment, unless a custom agent is being used. """ ... # pragma: no cover
defcost(self, response: ModelClientResponseProtocol) -> float: ... # pragma: no cover
@staticmethod defget_usage(response: ModelClientResponseProtocol) -> Dict: """Return usage summary of the response using RESPONSE_USAGE_KEYS.""" ... # pragma: no cover
from autogen.agentchat import AssistantAgent, UserProxyAgent from autogen.oai.openai_utils import config_list_from_json from types import SimpleNamespace import requests import os
response = requests.post(self.api_url, headers=headers, json=data) response.raise_for_status() # Raise an exception for HTTP errors
api_response = response.json()
# Convert API response to SimpleNamespace for compatibility client_response = SimpleNamespace() client_response.choices = [] client_response.model = self.model
for choice in api_response.get("choices", []): client_choice = SimpleNamespace() client_choice.message = SimpleNamespace() client_choice.message.content = choice.get("message", {}).get("content") client_choice.message.function_call = None client_response.choices.append(client_choice)
return client_response
defmessage_retrieval(self, response): """Retrieve the messages from the response.""" choices = response.choices return [choice.message.content for choice in choices]
defcost(self, response) -> float: """Calculate the cost of the response.""" # Implement cost calculation if available from your API response.cost = 0 return0
@staticmethod defget_usage(response): # Implement usage tracking if available from your API return {}