gllm-inference-binary 0.5.9b1__cp312-cp312-macosx_11_0_universal2.macosx_13_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of gllm-inference-binary might be problematic. Click here for more details.

Files changed (105) hide show
  1. gllm_inference/__init__.pyi +0 -0
  2. gllm_inference/builder/__init__.pyi +6 -0
  3. gllm_inference/builder/build_em_invoker.pyi +137 -0
  4. gllm_inference/builder/build_lm_invoker.pyi +161 -0
  5. gllm_inference/builder/build_lm_request_processor.pyi +93 -0
  6. gllm_inference/builder/build_output_parser.pyi +29 -0
  7. gllm_inference/catalog/__init__.pyi +4 -0
  8. gllm_inference/catalog/catalog.pyi +121 -0
  9. gllm_inference/catalog/lm_request_processor_catalog.pyi +112 -0
  10. gllm_inference/catalog/prompt_builder_catalog.pyi +82 -0
  11. gllm_inference/constants.pyi +10 -0
  12. gllm_inference/em_invoker/__init__.pyi +10 -0
  13. gllm_inference/em_invoker/azure_openai_em_invoker.pyi +88 -0
  14. gllm_inference/em_invoker/bedrock_em_invoker.pyi +106 -0
  15. gllm_inference/em_invoker/em_invoker.pyi +90 -0
  16. gllm_inference/em_invoker/google_em_invoker.pyi +129 -0
  17. gllm_inference/em_invoker/langchain/__init__.pyi +3 -0
  18. gllm_inference/em_invoker/langchain/em_invoker_embeddings.pyi +84 -0
  19. gllm_inference/em_invoker/langchain_em_invoker.pyi +46 -0
  20. gllm_inference/em_invoker/openai_compatible_em_invoker.pyi +96 -0
  21. gllm_inference/em_invoker/openai_em_invoker.pyi +90 -0
  22. gllm_inference/em_invoker/schema/__init__.pyi +0 -0
  23. gllm_inference/em_invoker/schema/bedrock.pyi +22 -0
  24. gllm_inference/em_invoker/schema/google.pyi +9 -0
  25. gllm_inference/em_invoker/schema/langchain.pyi +5 -0
  26. gllm_inference/em_invoker/schema/openai.pyi +7 -0
  27. gllm_inference/em_invoker/schema/openai_compatible.pyi +7 -0
  28. gllm_inference/em_invoker/schema/twelvelabs.pyi +17 -0
  29. gllm_inference/em_invoker/schema/voyage.pyi +15 -0
  30. gllm_inference/em_invoker/twelevelabs_em_invoker.pyi +101 -0
  31. gllm_inference/em_invoker/voyage_em_invoker.pyi +104 -0
  32. gllm_inference/exceptions/__init__.pyi +4 -0
  33. gllm_inference/exceptions/error_parser.pyi +41 -0
  34. gllm_inference/exceptions/exceptions.pyi +132 -0
  35. gllm_inference/exceptions/provider_error_map.pyi +23 -0
  36. gllm_inference/lm_invoker/__init__.pyi +12 -0
  37. gllm_inference/lm_invoker/anthropic_lm_invoker.pyi +275 -0
  38. gllm_inference/lm_invoker/azure_openai_lm_invoker.pyi +252 -0
  39. gllm_inference/lm_invoker/bedrock_lm_invoker.pyi +234 -0
  40. gllm_inference/lm_invoker/datasaur_lm_invoker.pyi +166 -0
  41. gllm_inference/lm_invoker/google_lm_invoker.pyi +317 -0
  42. gllm_inference/lm_invoker/langchain_lm_invoker.pyi +260 -0
  43. gllm_inference/lm_invoker/litellm_lm_invoker.pyi +248 -0
  44. gllm_inference/lm_invoker/lm_invoker.pyi +152 -0
  45. gllm_inference/lm_invoker/openai_compatible_lm_invoker.pyi +265 -0
  46. gllm_inference/lm_invoker/openai_lm_invoker.pyi +362 -0
  47. gllm_inference/lm_invoker/schema/__init__.pyi +0 -0
  48. gllm_inference/lm_invoker/schema/anthropic.pyi +50 -0
  49. gllm_inference/lm_invoker/schema/bedrock.pyi +53 -0
  50. gllm_inference/lm_invoker/schema/datasaur.pyi +12 -0
  51. gllm_inference/lm_invoker/schema/google.pyi +24 -0
  52. gllm_inference/lm_invoker/schema/langchain.pyi +23 -0
  53. gllm_inference/lm_invoker/schema/openai.pyi +91 -0
  54. gllm_inference/lm_invoker/schema/openai_compatible.pyi +60 -0
  55. gllm_inference/lm_invoker/schema/xai.pyi +31 -0
  56. gllm_inference/lm_invoker/xai_lm_invoker.pyi +305 -0
  57. gllm_inference/model/__init__.pyi +9 -0
  58. gllm_inference/model/em/__init__.pyi +0 -0
  59. gllm_inference/model/em/google_em.pyi +16 -0
  60. gllm_inference/model/em/openai_em.pyi +15 -0
  61. gllm_inference/model/em/twelvelabs_em.pyi +13 -0
  62. gllm_inference/model/em/voyage_em.pyi +20 -0
  63. gllm_inference/model/lm/__init__.pyi +0 -0
  64. gllm_inference/model/lm/anthropic_lm.pyi +20 -0
  65. gllm_inference/model/lm/google_lm.pyi +17 -0
  66. gllm_inference/model/lm/openai_lm.pyi +27 -0
  67. gllm_inference/output_parser/__init__.pyi +3 -0
  68. gllm_inference/output_parser/json_output_parser.pyi +60 -0
  69. gllm_inference/output_parser/output_parser.pyi +27 -0
  70. gllm_inference/prompt_builder/__init__.pyi +3 -0
  71. gllm_inference/prompt_builder/prompt_builder.pyi +56 -0
  72. gllm_inference/prompt_formatter/__init__.pyi +7 -0
  73. gllm_inference/prompt_formatter/agnostic_prompt_formatter.pyi +49 -0
  74. gllm_inference/prompt_formatter/huggingface_prompt_formatter.pyi +55 -0
  75. gllm_inference/prompt_formatter/llama_prompt_formatter.pyi +59 -0
  76. gllm_inference/prompt_formatter/mistral_prompt_formatter.pyi +53 -0
  77. gllm_inference/prompt_formatter/openai_prompt_formatter.pyi +35 -0
  78. gllm_inference/prompt_formatter/prompt_formatter.pyi +30 -0
  79. gllm_inference/request_processor/__init__.pyi +4 -0
  80. gllm_inference/request_processor/lm_request_processor.pyi +101 -0
  81. gllm_inference/request_processor/uses_lm_mixin.pyi +130 -0
  82. gllm_inference/schema/__init__.pyi +14 -0
  83. gllm_inference/schema/attachment.pyi +88 -0
  84. gllm_inference/schema/code_exec_result.pyi +14 -0
  85. gllm_inference/schema/config.pyi +15 -0
  86. gllm_inference/schema/enums.pyi +29 -0
  87. gllm_inference/schema/lm_output.pyi +36 -0
  88. gllm_inference/schema/message.pyi +52 -0
  89. gllm_inference/schema/model_id.pyi +147 -0
  90. gllm_inference/schema/reasoning.pyi +15 -0
  91. gllm_inference/schema/token_usage.pyi +75 -0
  92. gllm_inference/schema/tool_call.pyi +14 -0
  93. gllm_inference/schema/tool_result.pyi +11 -0
  94. gllm_inference/schema/type_alias.pyi +11 -0
  95. gllm_inference/utils/__init__.pyi +5 -0
  96. gllm_inference/utils/io_utils.pyi +26 -0
  97. gllm_inference/utils/langchain.pyi +30 -0
  98. gllm_inference/utils/validation.pyi +12 -0
  99. gllm_inference.build/.gitignore +1 -0
  100. gllm_inference.cpython-312-darwin.so +0 -0
  101. gllm_inference.pyi +123 -0
  102. gllm_inference_binary-0.5.9b1.dist-info/METADATA +71 -0
  103. gllm_inference_binary-0.5.9b1.dist-info/RECORD +105 -0
  104. gllm_inference_binary-0.5.9b1.dist-info/WHEEL +6 -0
  105. gllm_inference_binary-0.5.9b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,248 @@
1
+ from _typeshed import Incomplete
2
+ from gllm_core.event import EventEmitter as EventEmitter
3
+ from gllm_core.schema.tool import Tool as Tool
4
+ from gllm_core.utils.retry import RetryConfig as RetryConfig
5
+ from gllm_inference.lm_invoker.openai_compatible_lm_invoker import OpenAICompatibleLMInvoker as OpenAICompatibleLMInvoker
6
+ from gllm_inference.lm_invoker.openai_lm_invoker import ReasoningEffort as ReasoningEffort
7
+ from gllm_inference.schema import AttachmentType as AttachmentType, LMOutput as LMOutput, ModelId as ModelId, ModelProvider as ModelProvider, ResponseSchema as ResponseSchema
8
+ from langchain_core.tools import Tool as LangChainTool
9
+ from typing import Any
10
+
11
+ SUPPORTED_ATTACHMENTS: Incomplete
12
+
13
+ class LiteLLMLMInvoker(OpenAICompatibleLMInvoker):
14
+ '''A language model invoker to interact with language models using LiteLLM.
15
+
16
+ Attributes:
17
+ model_id (str): The model ID of the language model.
18
+ model_provider (str): The provider of the language model.
19
+ model_name (str): The name of the language model.
20
+ completion (function): The LiteLLM\'s completion function.
21
+ default_hyperparameters (dict[str, Any]): Default hyperparameters for invoking the model.
22
+ tools (list[Tool]): The list of tools provided to the model to enable tool calling.
23
+ response_schema (ResponseSchema | None): The schema of the response. If provided, the model will output a
24
+ structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema dictionary.
25
+ output_analytics (bool): Whether to output the invocation analytics.
26
+
27
+ Basic usage:
28
+ The `LiteLLMLMInvoker` can be used as follows:
29
+ ```python
30
+ lm_invoker = LiteLLMLMInvoker(model_id="openai/gpt-4.1-nano")
31
+ result = await lm_invoker.invoke("Hi there!")
32
+ ```
33
+
34
+ Initialization:
35
+ The `LiteLLMLMInvoker` provides an interface to interact with multiple language model providers.
36
+ In order to use this class:
37
+ 1. The `model_id` parameter must be in the format of `provider/model_name`. e.g. `openai/gpt-4o-mini`.
38
+ 2. The required credentials must be provided via the environment variables.
39
+
40
+ Usage example:
41
+ ```python
42
+ os.environ["OPENAI_API_KEY"] = "your_openai_api_key"
43
+ lm_invoker = LiteLLMLMInvoker(model_id="openai/gpt-4o-mini")
44
+ ```
45
+
46
+ For the complete list of supported providers and their required credentials, please refer to the
47
+ LiteLLM documentation: https://docs.litellm.ai/docs/providers/
48
+
49
+ Input types:
50
+ The `LiteLLMLMInvoker` supports the following input types: text, audio, and image.
51
+ Non-text inputs can be passed as a `Attachment` object with the `user` role.
52
+
53
+ Usage example:
54
+ ```python
55
+ text = "What animal is in this image?"
56
+ image = Attachment.from_path("path/to/local/image.png")
57
+ result = await lm_invoker.invoke([text, image])
58
+ ```
59
+
60
+ Tool calling:
61
+ Tool calling is a feature that allows the language model to call tools to perform tasks.
62
+ Tools can be passed to the via the `tools` parameter as a list of `Tool` objects.
63
+ When tools are provided and the model decides to call a tool, the tool calls are stored in the
64
+ `tool_calls` attribute in the output.
65
+
66
+ Usage example:
67
+ ```python
68
+ lm_invoker = LiteLLMLMInvoker(..., tools=[tool_1, tool_2])
69
+ ```
70
+
71
+ Output example:
72
+ ```python
73
+ LMOutput(
74
+ response="Let me call the tools...",
75
+ tool_calls=[
76
+ ToolCall(id="123", name="tool_1", args={"key": "value"}),
77
+ ToolCall(id="456", name="tool_2", args={"key": "value"}),
78
+ ]
79
+ )
80
+ ```
81
+
82
+ Structured output:
83
+ Structured output is a feature that allows the language model to output a structured response.
84
+ This feature can be enabled by providing a schema to the `response_schema` parameter.
85
+
86
+ The schema must be either a JSON schema dictionary or a Pydantic BaseModel class.
87
+ If JSON schema is used, it must be compatible with Pydantic\'s JSON schema, especially for complex schemas.
88
+ For this reason, it is recommended to create the JSON schema using Pydantic\'s `model_json_schema` method.
89
+
90
+ The language model also doesn\'t need to stream anything when structured output is enabled. Thus, standard
91
+ invocation will be performed regardless of whether the `event_emitter` parameter is provided or not.
92
+
93
+ When enabled, the structured output is stored in the `structured_output` attribute in the output.
94
+ 1. If the schema is a JSON schema dictionary, the structured output is a dictionary.
95
+ 2. If the schema is a Pydantic BaseModel class, the structured output is a Pydantic model.
96
+
97
+ # Example 1: Using a JSON schema dictionary
98
+ Usage example:
99
+ ```python
100
+ schema = {
101
+ "title": "Animal",
102
+ "description": "A description of an animal.",
103
+ "properties": {
104
+ "color": {"title": "Color", "type": "string"},
105
+ "name": {"title": "Name", "type": "string"},
106
+ },
107
+ "required": ["name", "color"],
108
+ "type": "object",
109
+ }
110
+ lm_invoker = LiteLLMLMInvoker(..., response_schema=schema)
111
+ ```
112
+ Output example:
113
+ ```python
114
+ LMOutput(structured_output={"name": "Golden retriever", "color": "Golden"})
115
+ ```
116
+
117
+ # Example 2: Using a Pydantic BaseModel class
118
+ Usage example:
119
+ ```python
120
+ class Animal(BaseModel):
121
+ name: str
122
+ color: str
123
+
124
+ lm_invoker = LiteLLMLMInvoker(..., response_schema=Animal)
125
+ ```
126
+ Output example:
127
+ ```python
128
+ LMOutput(structured_output=Animal(name="Golden retriever", color="Golden"))
129
+ ```
130
+
131
+ Analytics tracking:
132
+ Analytics tracking is a feature that allows the module to output additional information about the invocation.
133
+ This feature can be enabled by setting the `output_analytics` parameter to `True`.
134
+ When enabled, the following attributes will be stored in the output:
135
+ 1. `token_usage`: The token usage.
136
+ 2. `duration`: The duration in seconds.
137
+ 3. `finish_details`: The details about how the generation finished.
138
+
139
+ Output example:
140
+ ```python
141
+ LMOutput(
142
+ response="Golden retriever is a good dog breed.",
143
+ token_usage=TokenUsage(input_tokens=100, output_tokens=50),
144
+ duration=0.729,
145
+ finish_details={"finish_reason": "stop"},
146
+ )
147
+ ```
148
+
149
+ When streaming is enabled, token usage is not supported. Therefore, the `token_usage` attribute will be `None`
150
+ regardless of the value of the `output_analytics` parameter.
151
+
152
+ Retry and timeout:
153
+ The `LiteLLMLMInvoker` supports retry and timeout configuration.
154
+ By default, the max retries is set to 0 and the timeout is set to 30.0 seconds.
155
+ They can be customized by providing a custom `RetryConfig` object to the `retry_config` parameter.
156
+
157
+ Retry config examples:
158
+ ```python
159
+ retry_config = RetryConfig(max_retries=0, timeout=0.0) # No retry, no timeout
160
+ retry_config = RetryConfig(max_retries=0, timeout=10.0) # No retry, 10.0 seconds timeout
161
+ retry_config = RetryConfig(max_retries=5, timeout=0.0) # 5 max retries, no timeout
162
+ retry_config = RetryConfig(max_retries=5, timeout=10.0) # 5 max retries, 10.0 seconds timeout
163
+ ```
164
+
165
+ Usage example:
166
+ ```python
167
+ lm_invoker = LiteLLMLMInvoker(..., retry_config=retry_config)
168
+ ```
169
+
170
+ Reasoning:
171
+ Some language models support advanced reasoning capabilities. When using such reasoning-capable models,
172
+ you can configure how much reasoning the model should perform before generating a final response by setting
173
+ reasoning-related parameters.
174
+
175
+ The reasoning effort of reasoning models can be set via the `reasoning_effort` parameter. This parameter
176
+ will guide the models on how many reasoning tokens it should generate before creating a response to the prompt.
177
+ The reasoning effort is only supported by some language models.
178
+ Available options include:
179
+ 1. "low": Favors speed and economical token usage.
180
+ 2. "medium": Favors a balance between speed and reasoning accuracy.
181
+ 3. "high": Favors more complete reasoning at the cost of more tokens generated and slower responses.
182
+ This may differ between models. When not set, the reasoning effort will be equivalent to None by default.
183
+
184
+ When using reasoning models, some providers might output the reasoning summary. These will be stored in the
185
+ `reasoning` attribute in the output.
186
+
187
+ Output example:
188
+ ```python
189
+ LMOutput(
190
+ response="Golden retriever is a good dog breed.",
191
+ reasoning=[Reasoning(id="", reasoning="Let me think about it...")],
192
+ )
193
+ ```
194
+
195
+ When streaming is enabled along with reasoning and the provider supports reasoning output, the reasoning token
196
+ will be streamed with the `EventType.DATA` event type.
197
+
198
+ Streaming output example:
199
+ ```python
200
+ {"type": "data", "value": \'{"data_type": "thinking_start", "data_value": ""}\', ...}
201
+ {"type": "data", "value": \'{"data_type": "thinking", "data_value": "Let me think "}\', ...}
202
+ {"type": "data", "value": \'{"data_type": "thinking", "data_value": "about it..."}\', ...}
203
+ {"type": "data", "value": \'{"data_type": "thinking_end", "data_value": ""}\', ...}
204
+ {"type": "response", "value": "Golden retriever ", ...}
205
+ {"type": "response", "value": "is a good dog breed.", ...}
206
+
207
+ Setting reasoning-related parameters for non-reasoning models will raise an error.
208
+
209
+
210
+ Output types:
211
+ The output of the `LiteLLMLMInvoker` can either be:
212
+ 1. `str`: The text response if no additional output is needed.
213
+ 2. `LMOutput`: A Pydantic model with the following attributes if any additional output is needed:
214
+ 2.1. response (str): The text response.
215
+ 2.2. tool_calls (list[ToolCall]): The tool calls, if the `tools` parameter is defined and the language
216
+ model decides to invoke tools. Defaults to an empty list.
217
+ 2.3. structured_output (dict[str, Any] | BaseModel | None): The structured output, if the `response_schema`
218
+ parameter is defined. Defaults to None.
219
+ 2.4. token_usage (TokenUsage | None): The token usage analytics, if the `output_analytics` parameter is
220
+ set to `True`. Defaults to None.
221
+ 2.5. duration (float | None): The duration of the invocation in seconds, if the `output_analytics`
222
+ parameter is set to `True`. Defaults to None.
223
+ 2.6. finish_details (dict[str, Any] | None): The details about how the generation finished, if the
224
+ `output_analytics` parameter is set to `True`. Defaults to None.
225
+ 2.7. reasoning (list[Reasoning]): The reasoning objects. Currently not supported. Defaults to an empty list.
226
+ 2.8. citations (list[Chunk]): The citations. Currently not supported. Defaults to an empty list.
227
+ 2.9. code_exec_results (list[CodeExecResult]): The code execution results. Currently not supported.
228
+ Defaults to an empty list.
229
+ '''
230
+ completion: Incomplete
231
+ def __init__(self, model_id: str, default_hyperparameters: dict[str, Any] | None = None, tools: list[Tool | LangChainTool] | None = None, response_schema: ResponseSchema | None = None, output_analytics: bool = False, retry_config: RetryConfig | None = None, reasoning_effort: ReasoningEffort | None = None) -> None:
232
+ """Initializes a new instance of the LiteLLMLMInvoker class.
233
+
234
+ Args:
235
+ model_id (str): The ID of the model to use. Must be in the format of `provider/model_name`.
236
+ default_hyperparameters (dict[str, Any] | None, optional): Default hyperparameters for invoking the model.
237
+ Defaults to None.
238
+ tools (list[Tool | LangChainTool] | None, optional): Tools provided to the model to enable tool calling.
239
+ Defaults to None.
240
+ response_schema (ResponseSchema | None, optional): The schema of the response. If provided, the model will
241
+ output a structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema
242
+ dictionary. Defaults to None.
243
+ output_analytics (bool, optional): Whether to output the invocation analytics. Defaults to False.
244
+ retry_config (RetryConfig | None, optional): The retry configuration for the language model.
245
+ Defaults to None, in which case a default config with no retry and 30.0 seconds timeout will be used.
246
+ reasoning_effort (ReasoningEffort | None, optional): The reasoning effort for reasoning models.
247
+ Defaults to None.
248
+ """
@@ -0,0 +1,152 @@
1
+ import abc
2
+ from _typeshed import Incomplete
3
+ from abc import ABC
4
+ from gllm_core.event import EventEmitter as EventEmitter
5
+ from gllm_core.schema.tool import Tool
6
+ from gllm_core.utils import RetryConfig
7
+ from gllm_inference.constants import DOCUMENT_MIME_TYPES as DOCUMENT_MIME_TYPES, INVOKER_DEFAULT_TIMEOUT as INVOKER_DEFAULT_TIMEOUT
8
+ from gllm_inference.exceptions import BaseInvokerError as BaseInvokerError, convert_to_base_invoker_error as convert_to_base_invoker_error
9
+ from gllm_inference.schema import Attachment as Attachment, AttachmentType as AttachmentType, EmitDataType as EmitDataType, LMOutput as LMOutput, Message as Message, MessageContent as MessageContent, MessageRole as MessageRole, ModelId as ModelId, Reasoning as Reasoning, ResponseSchema as ResponseSchema, ToolCall as ToolCall, ToolResult as ToolResult
10
+ from langchain_core.tools import Tool as LangChainTool
11
+ from typing import Any
12
+
13
+ class Key:
14
+ """Defines valid keys in LM invokers JSON schema."""
15
+ ADDITIONAL_PROPERTIES: str
16
+ ANY_OF: str
17
+ ARGS_SCHEMA: str
18
+ ARUN: str
19
+ COROUTINE: str
20
+ DATA_TYPE: str
21
+ DATA_VALUE: str
22
+ DEFAULT: str
23
+ DESCRIPTION: str
24
+ FUNC: str
25
+ NAME: str
26
+ PROPERTIES: str
27
+ REQUIRED: str
28
+ TITLE: str
29
+ TYPE: str
30
+
31
+ class InputType:
32
+ """Defines valid input types in LM invokers JSON schema."""
33
+ NULL: str
34
+
35
+ class BaseLMInvoker(ABC, metaclass=abc.ABCMeta):
36
+ """A base class for language model invokers used in Gen AI applications.
37
+
38
+ The `BaseLMInvoker` class provides a framework for invoking language models.
39
+ It handles both standard and streaming invocation.
40
+
41
+ Attributes:
42
+ model_id (str): The model ID of the language model.
43
+ model_provider (str): The provider of the language model.
44
+ model_name (str): The name of the language model.
45
+ default_hyperparameters (dict[str, Any]): Default hyperparameters for invoking the language model.
46
+ tools (list[Tool]): Tools provided to the language model to enable tool calling.
47
+ response_schema (ResponseSchema | None): The schema of the response. If provided, the model will output a
48
+ structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema dictionary.
49
+ output_analytics (bool): Whether to output the invocation analytics.
50
+ retry_config (RetryConfig): The retry configuration for the language model.
51
+ """
52
+ default_hyperparameters: Incomplete
53
+ tools: Incomplete
54
+ response_schema: Incomplete
55
+ output_analytics: Incomplete
56
+ retry_config: Incomplete
57
+ def __init__(self, model_id: ModelId, default_hyperparameters: dict[str, Any] | None = None, supported_attachments: set[str] | None = None, tools: list[Tool | LangChainTool] | None = None, response_schema: ResponseSchema | None = None, output_analytics: bool = False, retry_config: RetryConfig | None = None) -> None:
58
+ """Initializes a new instance of the BaseLMInvoker class.
59
+
60
+ Args:
61
+ model_id (ModelId): The model ID of the language model.
62
+ default_hyperparameters (dict[str, Any] | None, optional): Default hyperparameters for invoking the
63
+ language model. Defaults to None, in which case an empty dictionary is used.
64
+ supported_attachments (set[str] | None, optional): A set of supported attachment types. Defaults to None,
65
+ in which case an empty set is used (indicating that no attachments are supported).
66
+ tools (list[Tool | LangChainTool] | None, optional): Tools provided to the model to enable tool calling.
67
+ Defaults to None, in which case an empty list is used.
68
+ response_schema (ResponseSchema | None, optional): The schema of the response. If provided, the model will
69
+ output a structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema
70
+ dictionary. Defaults to None.
71
+ output_analytics (bool, optional): Whether to output the invocation analytics. Defaults to False.
72
+ retry_config (RetryConfig | None, optional): The retry configuration for the language model.
73
+ Defaults to None, in which case a default config with no retry and 30.0 seconds timeout will be used.
74
+ """
75
+ @property
76
+ def model_id(self) -> str:
77
+ """The model ID of the language model.
78
+
79
+ Returns:
80
+ str: The model ID of the language model.
81
+ """
82
+ @property
83
+ def model_provider(self) -> str:
84
+ """The provider of the language model.
85
+
86
+ Returns:
87
+ str: The provider of the language model.
88
+ """
89
+ @property
90
+ def model_name(self) -> str:
91
+ """The name of the language model.
92
+
93
+ Returns:
94
+ str: The name of the language model.
95
+ """
96
+ def set_tools(self, tools: list[Tool | LangChainTool]) -> None:
97
+ """Sets the tools for the language model.
98
+
99
+ This method sets the tools for the language model. Any existing tools will be replaced.
100
+
101
+ Args:
102
+ tools (list[Tool | LangChainTool]): The list of tools to be used.
103
+ """
104
+ def clear_tools(self) -> None:
105
+ """Clears the tools for the language model.
106
+
107
+ This method clears the tools for the language model by calling the `set_tools` method with an empty list.
108
+ """
109
+ def set_response_schema(self, response_schema: ResponseSchema | None) -> None:
110
+ """Sets the response schema for the language model.
111
+
112
+ This method sets the response schema for the language model. Any existing response schema will be replaced.
113
+
114
+ Args:
115
+ response_schema (ResponseSchema | None): The response schema to be used.
116
+ """
117
+ def clear_response_schema(self) -> None:
118
+ """Clears the response schema for the language model.
119
+
120
+ This method clears the response schema for the language model by calling the `set_response_schema` method with
121
+ None.
122
+ """
123
+ async def invoke(self, messages: list[Message] | list[MessageContent] | str, hyperparameters: dict[str, Any] | None = None, event_emitter: EventEmitter | None = None) -> str | LMOutput:
124
+ """Invokes the language model.
125
+
126
+ This method validates the messages and invokes the language model. It handles both standard
127
+ and streaming invocation. Streaming mode is enabled if an event emitter is provided.
128
+ The method includes retry logic with exponential backoff for transient failures.
129
+
130
+ Args:
131
+ messages (list[Message] | list[MessageContent] | str): The input messages for the language model.
132
+ 1. If a list of Message objects is provided, it is used as is.
133
+ 2. If a list of MessageContent or a string is provided, it is converted into a user message.
134
+ hyperparameters (dict[str, Any] | None, optional): A dictionary of hyperparameters for the language model.
135
+ Defaults to None, in which case the default hyperparameters are used.
136
+ event_emitter (EventEmitter | None, optional): The event emitter for streaming tokens. If provided,
137
+ streaming invocation is enabled. Defaults to None.
138
+
139
+ Returns:
140
+ str | LMOutput: The generated response from the language model.
141
+
142
+ Raises:
143
+ CancelledError: If the invocation is cancelled.
144
+ ModelNotFoundError: If the model is not found.
145
+ ProviderAuthError: If the model authentication fails.
146
+ ProviderInternalError: If the model internal error occurs.
147
+ ProviderInvalidArgsError: If the model parameters are invalid.
148
+ ProviderOverloadedError: If the model is overloaded.
149
+ ProviderRateLimitError: If the model rate limit is exceeded.
150
+ TimeoutError: If the invocation times out.
151
+ ValueError: If the messages are not in the correct format.
152
+ """
@@ -0,0 +1,265 @@
1
+ from _typeshed import Incomplete
2
+ from gllm_core.event import EventEmitter as EventEmitter
3
+ from gllm_core.schema.tool import Tool as Tool
4
+ from gllm_core.utils.retry import RetryConfig as RetryConfig
5
+ from gllm_inference.constants import INVOKER_PROPAGATED_MAX_RETRIES as INVOKER_PROPAGATED_MAX_RETRIES
6
+ from gllm_inference.lm_invoker.lm_invoker import BaseLMInvoker as BaseLMInvoker
7
+ from gllm_inference.lm_invoker.schema.openai_compatible import InputType as InputType, Key as Key, ReasoningEffort as ReasoningEffort
8
+ from gllm_inference.schema import Attachment as Attachment, AttachmentType as AttachmentType, EmitDataType as EmitDataType, LMOutput as LMOutput, Message as Message, MessageRole as MessageRole, ModelId as ModelId, ModelProvider as ModelProvider, Reasoning as Reasoning, ResponseSchema as ResponseSchema, TokenUsage as TokenUsage, ToolCall as ToolCall, ToolResult as ToolResult
9
+ from gllm_inference.utils import validate_string_enum as validate_string_enum
10
+ from langchain_core.tools import Tool as LangChainTool
11
+ from typing import Any
12
+
13
+ SUPPORTED_ATTACHMENTS: Incomplete
14
+
15
+ class OpenAICompatibleLMInvoker(BaseLMInvoker):
16
+ '''A language model invoker to interact with endpoints compatible with OpenAI\'s chat completion API contract.
17
+
18
+ Attributes:
19
+ model_id (str): The model ID of the language model.
20
+ model_provider (str): The provider of the language model.
21
+ model_name (str): The name of the language model.
22
+ client (AsyncOpenAI): The OpenAI client instance.
23
+ default_hyperparameters (dict[str, Any]): Default hyperparameters for invoking the model.
24
+ tools (list[Tool]): The list of tools provided to the model to enable tool calling.
25
+ response_schema (ResponseSchema | None): The schema of the response. If provided, the model will output a
26
+ structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema dictionary.
27
+ output_analytics (bool): Whether to output the invocation analytics.
28
+ retry_config (RetryConfig | None): The retry configuration for the language model.
29
+
30
+ When to use:
31
+ The `OpenAICompatibleLMInvoker` is designed to interact with endpoints that are compatible with OpenAI\'s chat
32
+ completion API contract. This includes but are not limited to:
33
+ 1. DeepInfra (https://deepinfra.com/)
34
+ 2. DeepSeek (https://deepseek.com/)
35
+ 3. Groq (https://groq.com/)
36
+ 4. OpenRouter (https://openrouter.ai/)
37
+ 5. Text Generation Inference (https://github.com/huggingface/text-generation-inference)
38
+ 6. Together.ai (https://together.ai/)
39
+ 7. vLLM (https://vllm.ai/)
40
+ When using this invoker, please note that the supported features and capabilities may vary between different
41
+ endpoints and language models. Using features that are not supported by the endpoint will result in an error.
42
+
43
+ Basic usage:
44
+ The `OpenAICompatibleLMInvoker` can be used as follows:
45
+ ```python
46
+ lm_invoker = OpenAICompatibleLMInvoker(
47
+ model_name="llama3-8b-8192",
48
+ base_url="https://api.groq.com/openai/v1",
49
+ api_key="<your-api-key>"
50
+ )
51
+ result = await lm_invoker.invoke("Hi there!")
52
+ ```
53
+
54
+ Input types:
55
+ The `OpenAICompatibleLMInvoker` supports the following input types: text, audio, document, and image.
56
+ Non-text inputs can be passed as an `Attachment` object with the `user` role.
57
+
58
+ Usage example:
59
+ ```python
60
+ text = "What animal is in this image?"
61
+ image = Attachment.from_path("path/to/local/image.png")
62
+ result = await lm_invoker.invoke([text, image])
63
+ ```
64
+
65
+ Tool calling:
66
+ Tool calling is a feature that allows the language model to call tools to perform tasks.
67
+ Tools can be passed to the via the `tools` parameter as a list of `Tool` objects.
68
+ When tools are provided and the model decides to call a tool, the tool calls are stored in the
69
+ `tool_calls` attribute in the output.
70
+
71
+ Usage example:
72
+ ```python
73
+ lm_invoker = OpenAICompatibleLMInvoker(..., tools=[tool_1, tool_2])
74
+ ```
75
+
76
+ Output example:
77
+ ```python
78
+ LMOutput(
79
+ response="Let me call the tools...",
80
+ tool_calls=[
81
+ ToolCall(id="123", name="tool_1", args={"key": "value"}),
82
+ ToolCall(id="456", name="tool_2", args={"key": "value"}),
83
+ ]
84
+ )
85
+ ```
86
+
87
+ Structured output:
88
+ Structured output is a feature that allows the language model to output a structured response.
89
+ This feature can be enabled by providing a schema to the `response_schema` parameter.
90
+
91
+ The schema must be either a JSON schema dictionary or a Pydantic BaseModel class.
92
+ If JSON schema is used, it must be compatible with Pydantic\'s JSON schema, especially for complex schemas.
93
+ For this reason, it is recommended to create the JSON schema using Pydantic\'s `model_json_schema` method.
94
+
95
+ The language model also doesn\'t need to stream anything when structured output is enabled. Thus, standard
96
+ invocation will be performed regardless of whether the `event_emitter` parameter is provided or not.
97
+
98
+ When enabled, the structured output is stored in the `structured_output` attribute in the output.
99
+ 1. If the schema is a JSON schema dictionary, the structured output is a dictionary.
100
+ 2. If the schema is a Pydantic BaseModel class, the structured output is a Pydantic model.
101
+
102
+ # Example 1: Using a JSON schema dictionary
103
+ Usage example:
104
+ ```python
105
+ schema = {
106
+ "title": "Animal",
107
+ "description": "A description of an animal.",
108
+ "properties": {
109
+ "color": {"title": "Color", "type": "string"},
110
+ "name": {"title": "Name", "type": "string"},
111
+ },
112
+ "required": ["name", "color"],
113
+ "type": "object",
114
+ }
115
+ lm_invoker = OpenAICompatibleLMInvoker(..., response_schema=schema)
116
+ ```
117
+ Output example:
118
+ ```python
119
+ LMOutput(structured_output={"name": "Golden retriever", "color": "Golden"})
120
+ ```
121
+
122
+ # Example 2: Using a Pydantic BaseModel class
123
+ Usage example:
124
+ ```python
125
+ class Animal(BaseModel):
126
+ name: str
127
+ color: str
128
+
129
+ lm_invoker = OpenAICompatibleLMInvoker(..., response_schema=Animal)
130
+ ```
131
+ Output example:
132
+ ```python
133
+ LMOutput(structured_output=Animal(name="Golden retriever", color="Golden"))
134
+ ```
135
+
136
+ Analytics tracking:
137
+ Analytics tracking is a feature that allows the module to output additional information about the invocation.
138
+ This feature can be enabled by setting the `output_analytics` parameter to `True`.
139
+ When enabled, the following attributes will be stored in the output:
140
+ 1. `token_usage`: The token usage.
141
+ 2. `duration`: The duration in seconds.
142
+ 3. `finish_details`: The details about how the generation finished.
143
+
144
+ Output example:
145
+ ```python
146
+ LMOutput(
147
+ response="Golden retriever is a good dog breed.",
148
+ token_usage=TokenUsage(input_tokens=100, output_tokens=50),
149
+ duration=0.729,
150
+ finish_details={"finish_reason": "stop"},
151
+ )
152
+ ```
153
+
154
+ When streaming is enabled, token usage is not supported. Therefore, the `token_usage` attribute will be `None`
155
+ regardless of the value of the `output_analytics` parameter.
156
+
157
+ Retry and timeout:
158
+ The `OpenAICompatibleLMInvoker` supports retry and timeout configuration.
159
+ By default, the max retries is set to 0 and the timeout is set to 30.0 seconds.
160
+ They can be customized by providing a custom `RetryConfig` object to the `retry_config` parameter.
161
+
162
+ Retry config examples:
163
+ ```python
164
+ retry_config = RetryConfig(max_retries=0, timeout=0.0) # No retry, no timeout
165
+ retry_config = RetryConfig(max_retries=0, timeout=10.0) # No retry, 10.0 seconds timeout
166
+ retry_config = RetryConfig(max_retries=5, timeout=0.0) # 5 max retries, no timeout
167
+ retry_config = RetryConfig(max_retries=5, timeout=10.0) # 5 max retries, 10.0 seconds timeout
168
+ ```
169
+
170
+ Usage example:
171
+ ```python
172
+ lm_invoker = OpenAICompatibleLMInvoker(..., retry_config=retry_config)
173
+ ```
174
+
175
+ Reasoning:
176
+ Some language models support advanced reasoning capabilities. When using such reasoning-capable models,
177
+ you can configure how much reasoning the model should perform before generating a final response by setting
178
+ reasoning-related parameters.
179
+
180
+ The reasoning effort of reasoning models can be set via the `reasoning_effort` parameter. This parameter
181
+ will guide the models on how many reasoning tokens it should generate before creating a response to the prompt.
182
+ The reasoning effort is only supported by some language models.
183
+ Available options include:
184
+ 1. "low": Favors speed and economical token usage.
185
+ 2. "medium": Favors a balance between speed and reasoning accuracy.
186
+ 3. "high": Favors more complete reasoning at the cost of more tokens generated and slower responses.
187
+ This may differ between models. When not set, the reasoning effort will be equivalent to None by default.
188
+
189
+ When using reasoning models, some providers might output the reasoning summary. These will be stored in the
190
+ `reasoning` attribute in the output.
191
+
192
+ Output example:
193
+ ```python
194
+ LMOutput(
195
+ response="Golden retriever is a good dog breed.",
196
+ reasoning=[Reasoning(id="", reasoning="Let me think about it...")],
197
+ )
198
+ ```
199
+
200
+ When streaming is enabled along with reasoning and the provider supports reasoning output, the reasoning token
201
+ will be streamed with the `EventType.DATA` event type.
202
+
203
+ Streaming output example:
204
+ ```python
205
+ {"type": "data", "value": \'{"data_type": "thinking_start", "data_value": ""}\', ...}
206
+ {"type": "data", "value": \'{"data_type": "thinking", "data_value": "Let me think "}\', ...}
207
+ {"type": "data", "value": \'{"data_type": "thinking", "data_value": "about it..."}\', ...}
208
+ {"type": "data", "value": \'{"data_type": "thinking_end", "data_value": ""}\', ...}
209
+ {"type": "response", "value": "Golden retriever ", ...}
210
+ {"type": "response", "value": "is a good dog breed.", ...}
211
+
212
+ Setting reasoning-related parameters for non-reasoning models will raise an error.
213
+
214
+ Output types:
215
+ The output of the `OpenAICompatibleLMInvoker` can either be:
216
+ 1. `str`: The text response if no additional output is needed.
217
+ 2. `LMOutput`: A Pydantic model with the following attributes if any additional output is needed:
218
+ 2.1. response (str): The text response.
219
+ 2.2. tool_calls (list[ToolCall]): The tool calls, if the `tools` parameter is defined and the language
220
+ model decides to invoke tools. Defaults to an empty list.
221
+ 2.3. structured_output (dict[str, Any] | BaseModel | None): The structured output, if the `response_schema`
222
+ parameter is defined. Defaults to None.
223
+ 2.4. token_usage (TokenUsage | None): The token usage analytics, if the `output_analytics` parameter is
224
+ set to `True`. Defaults to None.
225
+ 2.5. duration (float | None): The duration of the invocation in seconds, if the `output_analytics`
226
+ parameter is set to `True`. Defaults to None.
227
+ 2.6. finish_details (dict[str, Any] | None): The details about how the generation finished, if the
228
+ `output_analytics` parameter is set to `True`. Defaults to None.
229
+ 2.7. reasoning (list[Reasoning]): The reasoning objects. Currently not supported. Defaults to an empty list.
230
+ 2.8. citations (list[Chunk]): The citations. Currently not supported. Defaults to an empty list.
231
+ 2.9. code_exec_results (list[CodeExecResult]): The code execution results. Currently not supported.
232
+ Defaults to an empty list.
233
+ '''
234
+ client: Incomplete
235
+ def __init__(self, model_name: str, base_url: str, api_key: str | None = None, model_kwargs: dict[str, Any] | None = None, default_hyperparameters: dict[str, Any] | None = None, tools: list[Tool | LangChainTool] | None = None, response_schema: ResponseSchema | None = None, output_analytics: bool = False, retry_config: RetryConfig | None = None, reasoning_effort: ReasoningEffort | None = None) -> None:
236
+ '''Initializes a new instance of the OpenAICompatibleLMInvoker class.
237
+
238
+ Args:
239
+ model_name (str): The name of the language model hosted on the OpenAI compatible endpoint.
240
+ base_url (str): The base URL for the OpenAI compatible endpoint.
241
+ api_key (str | None, optional): The API key for authenticating with the OpenAI compatible endpoint.
242
+ Defaults to None, in which case the `OPENAI_API_KEY` environment variable will be used.
243
+ If the endpoint does not require an API key, a dummy value can be passed (e.g. "<empty>").
244
+ model_kwargs (dict[str, Any] | None, optional): Additional model parameters. Defaults to None.
245
+ default_hyperparameters (dict[str, Any] | None, optional): Default hyperparameters for invoking the model.
246
+ Defaults to None.
247
+ tools (list[Tool | LangChainTool] | None, optional): Tools provided to the model to enable tool calling.
248
+ Defaults to None.
249
+ response_schema (ResponseSchema | None, optional): The schema of the response. If provided, the model will
250
+ output a structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema
251
+ dictionary. Defaults to None.
252
+ output_analytics (bool, optional): Whether to output the invocation analytics. Defaults to False.
253
+ retry_config (RetryConfig | None, optional): The retry configuration for the language model.
254
+ Defaults to None, in which case a default config with no retry and 30.0 seconds timeout will be used.
255
+ reasoning_effort (str | None, optional): The reasoning effort for the language model. Defaults to None.
256
+ '''
257
+ def set_response_schema(self, response_schema: ResponseSchema | None) -> None:
258
+ """Sets the response schema for the language model hosted on the OpenAI compatible endpoint.
259
+
260
+ This method sets the response schema for the language model hosted on the OpenAI compatible endpoint. Any
261
+ existing response schema will be replaced.
262
+
263
+ Args:
264
+ response_schema (ResponseSchema | None): The response schema to be used.
265
+ """