Skip to content

Base

base

Base classes used across the different LLM endpoint types offered by LLMeter

You can also use these classes to implement your own custom Endpoint types.

Endpoint

Endpoint(endpoint_name, model_id, provider)

Bases: ABC

An abstract base class for endpoint implementations.

This class defines the basic structure and interface for all endpoint classes. It provides abstract methods that must be implemented by subclasses.

Parameters:

Name Type Description Default
endpoint_name str

The name of the endpoint.

required
model_id str

The identifier of the model associated with this endpoint.

required
provider str

The provider of the endpoint.

required
Source code in llmeter/endpoints/base.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
@abstractmethod
def __init__(
    self,
    endpoint_name: str,
    model_id: str,
    provider: str,
):
    """
    Initialize the BaseEndpoint.

    Args:
        endpoint_name (str): The name of the endpoint.
        model_id (str): The identifier of the model associated with this endpoint.
        provider (str): The provider of the endpoint.
    """
    self.endpoint_name = endpoint_name
    self.model_id = model_id
    self.provider = provider

__subclasshook__ classmethod

__subclasshook__(C)

Determine if a class is considered a subclass of BaseEndpoint.

This method is used to implement a custom subclass check. A class is considered a subclass of BaseEndpoint if it has an 'invoke' method.

Parameters:

Name Type Description Default
C type

The class to check.

required

Returns:

Type Description
bool

bool or NotImplemented: True if the class is a subclass, False if it isn't, or NotImplemented if the check is inconclusive.

Source code in llmeter/endpoints/base.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
@classmethod
def __subclasshook__(cls, C: type) -> bool:
    """
    Determine if a class is considered a subclass of BaseEndpoint.

    This method is used to implement a custom subclass check. A class
    is considered a subclass of BaseEndpoint if it has an 'invoke' method.

    Args:
        C: The class to check.

    Returns:
        bool or NotImplemented: True if the class is a subclass, False if it isn't,
                                or NotImplemented if the check is inconclusive.
    """
    if cls is Endpoint:
        if any("invoke" in B.__dict__ for B in C.__mro__):
            return True
    return NotImplemented

create_payload staticmethod

create_payload(*args, **kwargs)

Create a payload for the endpoint invocation.

This static method should be implemented by subclasses to define how the payload is created based on the given arguments.

Parameters:

Name Type Description Default
*args Any

Variable length argument list.

()
**kwargs Any

Arbitrary keyword arguments.

{}

Returns:

Name Type Description
NotImplemented Any

This method returns NotImplemented in the base class.

Source code in llmeter/endpoints/base.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
@staticmethod
def create_payload(*args: Any, **kwargs: Any) -> Any:
    """
    Create a payload for the endpoint invocation.

    This static method should be implemented by subclasses to define
    how the payload is created based on the given arguments.

    Args:
        *args: Variable length argument list.
        **kwargs: Arbitrary keyword arguments.

    Returns:
        NotImplemented: This method returns NotImplemented in the base class.
    """
    return NotImplemented

invoke abstractmethod

invoke(payload)

Invoke the endpoint with the given payload.

This method must be implemented by subclasses to define how the endpoint is invoked and how the response is processed.

Parameters:

Name Type Description Default
payload Dict

The input payload for the model.

required

Returns:

Name Type Description
InvocationResponse InvocationResponse

An object containing the model's response and associated metrics.

Raises:

Type Description
NotImplementedError

If the method is not implemented by a subclass.

Source code in llmeter/endpoints/base.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
@abstractmethod
def invoke(self, payload: dict) -> InvocationResponse:
    """
    Invoke the endpoint with the given payload.

    This method must be implemented by subclasses to define how the endpoint
    is invoked and how the response is processed.

    Args:
        payload (Dict): The input payload for the model.

    Returns:
        InvocationResponse: An object containing the model's response and associated metrics.

    Raises:
        NotImplementedError: If the method is not implemented by a subclass.
    """
    raise NotImplementedError

load classmethod

load(endpoint_config)

Load an endpoint configuration from a dictionary.

This class method reads a dictionary containing an endpoint configuration, determines the appropriate endpoint class, and instantiates it with the loaded configuration.

Parameters:

Name Type Description Default
endpoint_config Dict

A dictionary containing the endpoint configuration.

required

Returns:

Name Type Description
Endpoint Endpoint

An instance of the appropriate endpoint class, initialized with the configuration from the dictionary.

Source code in llmeter/endpoints/base.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
@classmethod
def load(cls, endpoint_config: dict) -> "Endpoint":  # type: ignore
    """
    Load an endpoint configuration from a dictionary.

    This class method reads a dictionary containing an endpoint configuration,
    determines the appropriate endpoint class, and instantiates it with the
    loaded configuration.

    Args:
        endpoint_config (Dict): A dictionary containing the endpoint configuration.

    Returns:
        Endpoint: An instance of the appropriate endpoint class, initialized
                  with the configuration from the dictionary.
    """
    endpoint_type = endpoint_config.pop("endpoint_type")
    endpoint_module = importlib.import_module("llmeter.endpoints")
    endpoint_class = getattr(endpoint_module, endpoint_type)
    return endpoint_class(**endpoint_config)

load_from_file classmethod

load_from_file(input_path)

Load an endpoint configuration from a JSON file.

This class method reads a JSON file containing an endpoint configuration, determines the appropriate endpoint class, and instantiates it with the loaded configuration.

Parameters:

Name Type Description Default
input_path str | UPath

The path to the JSON configuration file.

required

Returns:

Name Type Description
Endpoint Endpoint

An instance of the appropriate endpoint class, initialized with the configuration from the file.

Source code in llmeter/endpoints/base.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
@classmethod
def load_from_file(cls, input_path: os.PathLike) -> "Endpoint":
    """
    Load an endpoint configuration from a JSON file.

    This class method reads a JSON file containing an endpoint configuration,
    determines the appropriate endpoint class, and instantiates it with the
    loaded configuration.

    Args:
        input_path (str|UPath): The path to the JSON configuration file.

    Returns:
        Endpoint: An instance of the appropriate endpoint class, initialized
                  with the configuration from the file.
    """

    input_path = Path(input_path)
    with input_path.open("r") as f:
        data = json.load(f)
    endpoint_type = data.pop("endpoint_type")
    endpoint_module = importlib.import_module("llmeter.endpoints")
    endpoint_class = getattr(endpoint_module, endpoint_type)
    return endpoint_class(**data)

save

save(output_path)

Save the endpoint configuration to a JSON file.

This method serializes the endpoint's configuration (excluding private attributes) to a JSON file at the specified path.

Parameters:

Name Type Description Default
output_path str | UPath

The path where the configuration file will be saved.

required

Returns:

Type Description
PathLike

None

Source code in llmeter/endpoints/base.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def save(self, output_path: os.PathLike) -> os.PathLike:
    """
    Save the endpoint configuration to a JSON file.

    This method serializes the endpoint's configuration (excluding private attributes)
    to a JSON file at the specified path.

    Args:
        output_path (str | UPath): The path where the configuration file will be saved.

    Returns:
        None
    """
    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    with output_path.open("w") as f:
        endpoint_conf = self.to_dict()
        json.dump(endpoint_conf, f, indent=4, default=str)
    return output_path

to_dict

to_dict()

Convert the endpoint configuration to a dictionary.

Returns:

Name Type Description
Dict dict

A dictionary representation of the endpoint configuration.

Source code in llmeter/endpoints/base.py
188
189
190
191
192
193
194
195
196
197
def to_dict(self) -> dict:
    """
    Convert the endpoint configuration to a dictionary.

    Returns:
        Dict: A dictionary representation of the endpoint configuration.
    """
    endpoint_conf = {k: v for k, v in vars(self).items() if not k.startswith("_")}
    endpoint_conf["endpoint_type"] = self.__class__.__name__
    return endpoint_conf

InvocationResponse dataclass

InvocationResponse(response_text, input_payload=None, id=None, input_prompt=None, time_to_first_token=None, time_to_last_token=None, num_tokens_input=None, num_tokens_output=None, time_per_output_token=None, error=None, retries=None)

A class representing a invocation result.

Attributes:

Name Type Description
response_text str

The invocation output.

id str

A unique identifier for the invocation.

time_to_last_token float

The time taken to generate the response in seconds.

time_to_first_token float

The time taken to receive the first token of the response in seconds.

num_tokens_output Optional[int]

The number of tokens in the response.

num_tokens_input Optional[int]

The number of tokens in the invocation payload.

input_prompt str

The input prompt used in the invocation.

time_per_output_token float

The average time taken to generate each token in the response.

error str

Any error that occurred during invocation.