gllm-inference-binary 0.5.55__cp313-cp313-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 (137) hide show
  1. gllm_inference/__init__.pyi +0 -0
  2. gllm_inference/builder/__init__.pyi +6 -0
  3. gllm_inference/builder/_build_invoker.pyi +28 -0
  4. gllm_inference/builder/build_em_invoker.pyi +130 -0
  5. gllm_inference/builder/build_lm_invoker.pyi +213 -0
  6. gllm_inference/builder/build_lm_request_processor.pyi +88 -0
  7. gllm_inference/builder/build_output_parser.pyi +29 -0
  8. gllm_inference/catalog/__init__.pyi +4 -0
  9. gllm_inference/catalog/catalog.pyi +121 -0
  10. gllm_inference/catalog/lm_request_processor_catalog.pyi +112 -0
  11. gllm_inference/catalog/prompt_builder_catalog.pyi +82 -0
  12. gllm_inference/constants.pyi +12 -0
  13. gllm_inference/em_invoker/__init__.pyi +12 -0
  14. gllm_inference/em_invoker/azure_openai_em_invoker.pyi +88 -0
  15. gllm_inference/em_invoker/bedrock_em_invoker.pyi +118 -0
  16. gllm_inference/em_invoker/cohere_em_invoker.pyi +128 -0
  17. gllm_inference/em_invoker/em_invoker.pyi +90 -0
  18. gllm_inference/em_invoker/google_em_invoker.pyi +129 -0
  19. gllm_inference/em_invoker/jina_em_invoker.pyi +103 -0
  20. gllm_inference/em_invoker/langchain/__init__.pyi +3 -0
  21. gllm_inference/em_invoker/langchain/em_invoker_embeddings.pyi +84 -0
  22. gllm_inference/em_invoker/langchain_em_invoker.pyi +46 -0
  23. gllm_inference/em_invoker/openai_compatible_em_invoker.pyi +41 -0
  24. gllm_inference/em_invoker/openai_em_invoker.pyi +118 -0
  25. gllm_inference/em_invoker/schema/__init__.pyi +0 -0
  26. gllm_inference/em_invoker/schema/bedrock.pyi +29 -0
  27. gllm_inference/em_invoker/schema/cohere.pyi +20 -0
  28. gllm_inference/em_invoker/schema/google.pyi +9 -0
  29. gllm_inference/em_invoker/schema/jina.pyi +29 -0
  30. gllm_inference/em_invoker/schema/langchain.pyi +5 -0
  31. gllm_inference/em_invoker/schema/openai.pyi +7 -0
  32. gllm_inference/em_invoker/schema/openai_compatible.pyi +7 -0
  33. gllm_inference/em_invoker/schema/twelvelabs.pyi +17 -0
  34. gllm_inference/em_invoker/schema/voyage.pyi +15 -0
  35. gllm_inference/em_invoker/twelevelabs_em_invoker.pyi +101 -0
  36. gllm_inference/em_invoker/voyage_em_invoker.pyi +104 -0
  37. gllm_inference/exceptions/__init__.pyi +4 -0
  38. gllm_inference/exceptions/error_parser.pyi +41 -0
  39. gllm_inference/exceptions/exceptions.pyi +132 -0
  40. gllm_inference/exceptions/provider_error_map.pyi +24 -0
  41. gllm_inference/lm_invoker/__init__.pyi +14 -0
  42. gllm_inference/lm_invoker/anthropic_lm_invoker.pyi +318 -0
  43. gllm_inference/lm_invoker/azure_openai_lm_invoker.pyi +237 -0
  44. gllm_inference/lm_invoker/batch/__init__.pyi +3 -0
  45. gllm_inference/lm_invoker/batch/batch_operations.pyi +127 -0
  46. gllm_inference/lm_invoker/bedrock_lm_invoker.pyi +212 -0
  47. gllm_inference/lm_invoker/datasaur_lm_invoker.pyi +157 -0
  48. gllm_inference/lm_invoker/google_lm_invoker.pyi +327 -0
  49. gllm_inference/lm_invoker/langchain_lm_invoker.pyi +239 -0
  50. gllm_inference/lm_invoker/litellm_lm_invoker.pyi +224 -0
  51. gllm_inference/lm_invoker/lm_invoker.pyi +165 -0
  52. gllm_inference/lm_invoker/openai_chat_completions_lm_invoker.pyi +253 -0
  53. gllm_inference/lm_invoker/openai_compatible_lm_invoker.pyi +52 -0
  54. gllm_inference/lm_invoker/openai_lm_invoker.pyi +404 -0
  55. gllm_inference/lm_invoker/portkey_lm_invoker.pyi +296 -0
  56. gllm_inference/lm_invoker/schema/__init__.pyi +0 -0
  57. gllm_inference/lm_invoker/schema/anthropic.pyi +56 -0
  58. gllm_inference/lm_invoker/schema/bedrock.pyi +53 -0
  59. gllm_inference/lm_invoker/schema/datasaur.pyi +14 -0
  60. gllm_inference/lm_invoker/schema/google.pyi +24 -0
  61. gllm_inference/lm_invoker/schema/langchain.pyi +23 -0
  62. gllm_inference/lm_invoker/schema/openai.pyi +106 -0
  63. gllm_inference/lm_invoker/schema/openai_chat_completions.pyi +62 -0
  64. gllm_inference/lm_invoker/schema/portkey.pyi +31 -0
  65. gllm_inference/lm_invoker/schema/xai.pyi +31 -0
  66. gllm_inference/lm_invoker/xai_lm_invoker.pyi +253 -0
  67. gllm_inference/model/__init__.pyi +12 -0
  68. gllm_inference/model/em/__init__.pyi +0 -0
  69. gllm_inference/model/em/cohere_em.pyi +17 -0
  70. gllm_inference/model/em/google_em.pyi +16 -0
  71. gllm_inference/model/em/jina_em.pyi +22 -0
  72. gllm_inference/model/em/openai_em.pyi +15 -0
  73. gllm_inference/model/em/twelvelabs_em.pyi +13 -0
  74. gllm_inference/model/em/voyage_em.pyi +20 -0
  75. gllm_inference/model/lm/__init__.pyi +0 -0
  76. gllm_inference/model/lm/anthropic_lm.pyi +22 -0
  77. gllm_inference/model/lm/google_lm.pyi +18 -0
  78. gllm_inference/model/lm/openai_lm.pyi +27 -0
  79. gllm_inference/model/lm/xai_lm.pyi +19 -0
  80. gllm_inference/output_parser/__init__.pyi +3 -0
  81. gllm_inference/output_parser/json_output_parser.pyi +60 -0
  82. gllm_inference/output_parser/output_parser.pyi +27 -0
  83. gllm_inference/prompt_builder/__init__.pyi +3 -0
  84. gllm_inference/prompt_builder/format_strategy/__init__.pyi +4 -0
  85. gllm_inference/prompt_builder/format_strategy/format_strategy.pyi +55 -0
  86. gllm_inference/prompt_builder/format_strategy/jinja_format_strategy.pyi +45 -0
  87. gllm_inference/prompt_builder/format_strategy/string_format_strategy.pyi +20 -0
  88. gllm_inference/prompt_builder/prompt_builder.pyi +69 -0
  89. gllm_inference/prompt_formatter/__init__.pyi +7 -0
  90. gllm_inference/prompt_formatter/agnostic_prompt_formatter.pyi +49 -0
  91. gllm_inference/prompt_formatter/huggingface_prompt_formatter.pyi +55 -0
  92. gllm_inference/prompt_formatter/llama_prompt_formatter.pyi +59 -0
  93. gllm_inference/prompt_formatter/mistral_prompt_formatter.pyi +53 -0
  94. gllm_inference/prompt_formatter/openai_prompt_formatter.pyi +35 -0
  95. gllm_inference/prompt_formatter/prompt_formatter.pyi +30 -0
  96. gllm_inference/realtime_chat/__init__.pyi +3 -0
  97. gllm_inference/realtime_chat/google_realtime_chat.pyi +205 -0
  98. gllm_inference/realtime_chat/input_streamer/__init__.pyi +4 -0
  99. gllm_inference/realtime_chat/input_streamer/input_streamer.pyi +36 -0
  100. gllm_inference/realtime_chat/input_streamer/keyboard_input_streamer.pyi +27 -0
  101. gllm_inference/realtime_chat/input_streamer/linux_mic_input_streamer.pyi +36 -0
  102. gllm_inference/realtime_chat/output_streamer/__init__.pyi +4 -0
  103. gllm_inference/realtime_chat/output_streamer/console_output_streamer.pyi +21 -0
  104. gllm_inference/realtime_chat/output_streamer/linux_speaker_output_streamer.pyi +42 -0
  105. gllm_inference/realtime_chat/output_streamer/output_streamer.pyi +33 -0
  106. gllm_inference/realtime_chat/realtime_chat.pyi +28 -0
  107. gllm_inference/request_processor/__init__.pyi +4 -0
  108. gllm_inference/request_processor/lm_request_processor.pyi +101 -0
  109. gllm_inference/request_processor/uses_lm_mixin.pyi +130 -0
  110. gllm_inference/schema/__init__.pyi +18 -0
  111. gllm_inference/schema/activity.pyi +64 -0
  112. gllm_inference/schema/attachment.pyi +88 -0
  113. gllm_inference/schema/code_exec_result.pyi +14 -0
  114. gllm_inference/schema/config.pyi +15 -0
  115. gllm_inference/schema/enums.pyi +80 -0
  116. gllm_inference/schema/events.pyi +105 -0
  117. gllm_inference/schema/lm_input.pyi +4 -0
  118. gllm_inference/schema/lm_output.pyi +188 -0
  119. gllm_inference/schema/mcp.pyi +31 -0
  120. gllm_inference/schema/message.pyi +52 -0
  121. gllm_inference/schema/model_id.pyi +176 -0
  122. gllm_inference/schema/reasoning.pyi +15 -0
  123. gllm_inference/schema/token_usage.pyi +75 -0
  124. gllm_inference/schema/tool_call.pyi +14 -0
  125. gllm_inference/schema/tool_result.pyi +11 -0
  126. gllm_inference/schema/type_alias.pyi +11 -0
  127. gllm_inference/utils/__init__.pyi +5 -0
  128. gllm_inference/utils/io_utils.pyi +26 -0
  129. gllm_inference/utils/langchain.pyi +30 -0
  130. gllm_inference/utils/validation.pyi +12 -0
  131. gllm_inference.build/.gitignore +1 -0
  132. gllm_inference.cpython-313-darwin.so +0 -0
  133. gllm_inference.pyi +154 -0
  134. gllm_inference_binary-0.5.55.dist-info/METADATA +138 -0
  135. gllm_inference_binary-0.5.55.dist-info/RECORD +137 -0
  136. gllm_inference_binary-0.5.55.dist-info/WHEEL +5 -0
  137. gllm_inference_binary-0.5.55.dist-info/top_level.txt +1 -0
@@ -0,0 +1,224 @@
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_chat_completions_lm_invoker import OpenAIChatCompletionsLMInvoker as OpenAIChatCompletionsLMInvoker
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(OpenAIChatCompletionsLMInvoker):
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-5-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
+ Text output:
61
+ The `LiteLLMLMInvoker` generates text outputs by default.
62
+ Text outputs are stored in the `outputs` attribute of the `LMOutput` object and can be accessed
63
+ via the `texts` (all text outputs) or `text` (first text output) properties.
64
+
65
+ Output example:
66
+ ```python
67
+ LMOutput(outputs=[LMOutputItem(type="text", output="Hello, there!")])
68
+ ```
69
+
70
+ Structured output:
71
+ The `LiteLLMLMInvoker` can be configured to generate structured outputs.
72
+ This feature can be enabled by providing a schema to the `response_schema` parameter.
73
+
74
+ Structured outputs are stored in the `outputs` attribute of the `LMOutput` object and can be accessed
75
+ via the `structureds` (all structured outputs) or `structured` (first structured output) properties.
76
+
77
+ The schema must either be one of the following:
78
+ 1. A Pydantic BaseModel class
79
+ The structured output will be a Pydantic model.
80
+ 2. A JSON schema dictionary
81
+ JSON dictionary schema must be compatible with Pydantic\'s JSON schema, especially for complex schemas.
82
+ Thus, it is recommended to create the JSON schema using Pydantic\'s `model_json_schema` method.
83
+ The structured output will be a dictionary.
84
+
85
+ Usage example:
86
+ ```python
87
+ class Animal(BaseModel):
88
+ name: str
89
+ color: str
90
+
91
+ json_schema = Animal.model_json_schema()
92
+
93
+ lm_invoker = LiteLLMLMInvoker(..., response_schema=Animal) # Using Pydantic BaseModel class
94
+ lm_invoker = LiteLLMLMInvoker(..., response_schema=json_schema) # Using JSON schema dictionary
95
+ ```
96
+
97
+ Output example:
98
+ ```python
99
+ # Using Pydantic BaseModel class outputs a Pydantic model
100
+ LMOutput(outputs=[LMOutputItem(type="structured", output=Animal(name="dog", color="white"))])
101
+
102
+ # Using JSON schema dictionary outputs a dictionary
103
+ LMOutput(outputs=[LMOutputItem(type="structured", output={"name": "dog", "color": "white"})])
104
+ ```
105
+
106
+ When structured output is enabled, streaming is disabled.
107
+
108
+ Tool calling:
109
+ The `LiteLLMLMInvoker` can be configured to call tools to perform certain tasks.
110
+ This feature can be enabled by providing a list of `Tool` objects to the `tools` parameter.
111
+
112
+ Tool calls outputs are stored in the `outputs` attribute of the `LMOutput` object and
113
+ can be accessed via the `tool_calls` property.
114
+
115
+ Usage example:
116
+ ```python
117
+ lm_invoker = LiteLLMLMInvoker(..., tools=[tool_1, tool_2])
118
+ ```
119
+
120
+ Output example:
121
+ ```python
122
+ LMOutput(
123
+ outputs=[
124
+ LMOutputItem(type="text", output="I\'m using tools..."),
125
+ LMOutputItem(type="tool_call", output=ToolCall(id="123", name="tool_1", args={"key": "value"})),
126
+ LMOutputItem(type="tool_call", output=ToolCall(id="456", name="tool_2", args={"key": "value"})),
127
+ ]
128
+ )
129
+ ```
130
+
131
+ Reasoning:
132
+ The `LiteLLMLMInvoker` performs step-by-step reasoning before generating a response when reasoning
133
+ models are used, such as GPT-5 models and o-series models.
134
+
135
+ The reasoning effort can be set via the `reasoning_effort` parameter, which guides the models on the amount
136
+ of reasoning tokens to generate. Available options include `minimal`, `low`, `medium`, and `high`.
137
+
138
+ Some models may also output the reasoning tokens. In this case, the reasoning tokens are stored in
139
+ the `outputs` attribute of the `LMOutput` object and can be accessed via the `thinkings` property.
140
+
141
+ Output example:
142
+ ```python
143
+ LMOutput(
144
+ outputs=[
145
+ LMOutputItem(type="thinking", output=Reasoning(reasoning="I\'m thinking...", ...)),
146
+ LMOutputItem(type="text", output="Golden retriever is a good dog breed."),
147
+ ]
148
+ )
149
+ ```
150
+
151
+ Streaming output example:
152
+ ```python
153
+ {"type": "thinking_start", "value": "", ...}
154
+ {"type": "thinking", "value": "I\'m ", ...}
155
+ {"type": "thinking", "value": "thinking...", ...}
156
+ {"type": "thinking_end", "value": "", ...}
157
+ {"type": "response", "value": "Golden retriever ", ...}
158
+ {"type": "response", "value": "is a good dog breed.", ...}
159
+ ```
160
+ Note: By default, the thinking token will be streamed with the legacy `EventType.DATA` event type.
161
+ To use the new simplified streamed event format, set the `simplify_events` parameter to `True` during
162
+ LM invoker initialization. The legacy event format support will be removed in v0.6.
163
+
164
+ Setting reasoning-related parameters for non-reasoning models will raise an error.
165
+
166
+ Analytics tracking:
167
+ The `LiteLLMLMInvoker` can be configured to output additional information about the invocation.
168
+ This feature can be enabled by setting the `output_analytics` parameter to `True`.
169
+
170
+ When enabled, the following attributes will be stored in the output:
171
+ 1. `token_usage`: The token usage.
172
+ 2. `duration`: The duration in seconds.
173
+ 3. `finish_details`: The details about how the generation finished.
174
+
175
+ Output example:
176
+ ```python
177
+ LMOutput(
178
+ outputs=[...],
179
+ token_usage=TokenUsage(input_tokens=100, output_tokens=50),
180
+ duration=0.729,
181
+ finish_details={"stop_reason": "end_turn"},
182
+ )
183
+ ```
184
+
185
+ When streaming is enabled, token usage is not supported.
186
+
187
+ Retry and timeout:
188
+ The `LiteLLMLMInvoker` supports retry and timeout configuration.
189
+ By default, the max retries is set to 0 and the timeout is set to 30.0 seconds.
190
+ They can be customized by providing a custom `RetryConfig` object to the `retry_config` parameter.
191
+
192
+ Retry config examples:
193
+ ```python
194
+ retry_config = RetryConfig(max_retries=0, timeout=None) # No retry, no timeout
195
+ retry_config = RetryConfig(max_retries=5, timeout=10.0) # 5 max retries, 10.0 seconds timeout
196
+ ```
197
+
198
+ Usage example:
199
+ ```python
200
+ lm_invoker = LiteLLMLMInvoker(..., retry_config=retry_config)
201
+ ```
202
+ '''
203
+ completion: Incomplete
204
+ 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, simplify_events: bool = False) -> None:
205
+ """Initializes a new instance of the LiteLLMLMInvoker class.
206
+
207
+ Args:
208
+ model_id (str): The ID of the model to use. Must be in the format of `provider/model_name`.
209
+ default_hyperparameters (dict[str, Any] | None, optional): Default hyperparameters for invoking the model.
210
+ Defaults to None.
211
+ tools (list[Tool | LangChainTool] | None, optional): Tools provided to the model to enable tool calling.
212
+ Defaults to None.
213
+ response_schema (ResponseSchema | None, optional): The schema of the response. If provided, the model will
214
+ output a structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema
215
+ dictionary. Defaults to None.
216
+ output_analytics (bool, optional): Whether to output the invocation analytics. Defaults to False.
217
+ retry_config (RetryConfig | None, optional): The retry configuration for the language model.
218
+ Defaults to None, in which case a default config with no retry and 30.0 seconds timeout will be used.
219
+ reasoning_effort (ReasoningEffort | None, optional): The reasoning effort for reasoning models.
220
+ Defaults to None.
221
+ simplify_events (bool, optional): Temporary parameter to control the streamed events format.
222
+ When True, uses the simplified events format. When False, uses the legacy events format for
223
+ backward compatibility. Will be removed in v0.6. Defaults to False.
224
+ """
@@ -0,0 +1,165 @@
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 import Event as Event, 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.lm_invoker.batch import BatchOperations as BatchOperations
10
+ from gllm_inference.schema import Attachment as Attachment, AttachmentType as AttachmentType, BatchStatus as BatchStatus, LMInput as LMInput, 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
11
+ from langchain_core.tools import Tool as LangChainTool
12
+ from typing import Any
13
+
14
+ class Key:
15
+ """Defines valid keys in LM invokers JSON schema."""
16
+ ADDITIONAL_PROPERTIES: str
17
+ ANY_OF: str
18
+ ARGS_SCHEMA: str
19
+ ARUN: str
20
+ COROUTINE: str
21
+ DATA_TYPE: str
22
+ DATA_VALUE: str
23
+ DEFAULT: str
24
+ DEFS: str
25
+ DESCRIPTION: str
26
+ FUNC: str
27
+ ID: str
28
+ NAME: str
29
+ PROPERTIES: str
30
+ REQUIRED: str
31
+ TITLE: str
32
+ TYPE: str
33
+
34
+ class InputType:
35
+ """Defines valid input types in LM invokers JSON schema."""
36
+ NULL: str
37
+
38
+ class BaseLMInvoker(ABC, metaclass=abc.ABCMeta):
39
+ """A base class for language model invokers used in Gen AI applications.
40
+
41
+ The `BaseLMInvoker` class provides a framework for invoking language models.
42
+ It handles both standard and streaming invocation.
43
+
44
+ Attributes:
45
+ model_id (str): The model ID of the language model.
46
+ model_provider (str): The provider of the language model.
47
+ model_name (str): The name of the language model.
48
+ default_hyperparameters (dict[str, Any]): Default hyperparameters for invoking the language model.
49
+ tools (list[Tool]): Tools provided to the language model to enable tool calling.
50
+ response_schema (ResponseSchema | None): The schema of the response. If provided, the model will output a
51
+ structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema dictionary.
52
+ output_analytics (bool): Whether to output the invocation analytics.
53
+ retry_config (RetryConfig): The retry configuration for the language model.
54
+ """
55
+ default_hyperparameters: Incomplete
56
+ tools: Incomplete
57
+ response_schema: Incomplete
58
+ output_analytics: Incomplete
59
+ retry_config: Incomplete
60
+ 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, simplify_events: bool = False) -> None:
61
+ """Initializes a new instance of the BaseLMInvoker class.
62
+
63
+ Args:
64
+ model_id (ModelId): The model ID of the language model.
65
+ default_hyperparameters (dict[str, Any] | None, optional): Default hyperparameters for invoking the
66
+ language model. Defaults to None, in which case an empty dictionary is used.
67
+ supported_attachments (set[str] | None, optional): A set of supported attachment types. Defaults to None,
68
+ in which case an empty set is used (indicating that no attachments are supported).
69
+ tools (list[Tool | LangChainTool] | None, optional): Tools provided to the model to enable tool calling.
70
+ Defaults to None, in which case an empty list is used.
71
+ response_schema (ResponseSchema | None, optional): The schema of the response. If provided, the model will
72
+ output a structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema
73
+ dictionary. Defaults to None.
74
+ output_analytics (bool, optional): Whether to output the invocation analytics. Defaults to False.
75
+ retry_config (RetryConfig | None, optional): The retry configuration for the language model.
76
+ Defaults to None, in which case a default config with no retry and 30.0 seconds timeout will be used.
77
+ simplify_events (bool, optional): Temporary parameter to control the streamed events format.
78
+ When True, uses the simplified events format. When False, uses the legacy events format for
79
+ backward compatibility. Will be removed in v0.6. Defaults to False.
80
+ """
81
+ @property
82
+ def model_id(self) -> str:
83
+ """The model ID of the language model.
84
+
85
+ Returns:
86
+ str: The model ID of the language model.
87
+ """
88
+ @property
89
+ def model_provider(self) -> str:
90
+ """The provider of the language model.
91
+
92
+ Returns:
93
+ str: The provider of the language model.
94
+ """
95
+ @property
96
+ def model_name(self) -> str:
97
+ """The name of the language model.
98
+
99
+ Returns:
100
+ str: The name of the language model.
101
+ """
102
+ @property
103
+ def batch(self) -> BatchOperations:
104
+ """The batch operations for the language model.
105
+
106
+ Returns:
107
+ BatchOperations: The batch operations for the language model.
108
+ """
109
+ def set_tools(self, tools: list[Tool | LangChainTool]) -> None:
110
+ """Sets the tools for the language model.
111
+
112
+ This method sets the tools for the language model. Any existing tools will be replaced.
113
+
114
+ Args:
115
+ tools (list[Tool | LangChainTool]): The list of tools to be used.
116
+ """
117
+ def clear_tools(self) -> None:
118
+ """Clears the tools for the language model.
119
+
120
+ This method clears the tools for the language model by calling the `set_tools` method with an empty list.
121
+ """
122
+ def set_response_schema(self, response_schema: ResponseSchema | None) -> None:
123
+ """Sets the response schema for the language model.
124
+
125
+ This method sets the response schema for the language model. Any existing response schema will be replaced.
126
+
127
+ Args:
128
+ response_schema (ResponseSchema | None): The response schema to be used.
129
+ """
130
+ def clear_response_schema(self) -> None:
131
+ """Clears the response schema for the language model.
132
+
133
+ This method clears the response schema for the language model by calling the `set_response_schema` method with
134
+ None.
135
+ """
136
+ async def invoke(self, messages: LMInput, hyperparameters: dict[str, Any] | None = None, event_emitter: EventEmitter | None = None) -> str | LMOutput:
137
+ """Invokes the language model.
138
+
139
+ This method validates the messages and invokes the language model. It handles both standard
140
+ and streaming invocation. Streaming mode is enabled if an event emitter is provided.
141
+ The method includes retry logic with exponential backoff for transient failures.
142
+
143
+ Args:
144
+ messages (LMInput): The input messages for the language model.
145
+ 1. If a list of Message objects is provided, it is used as is.
146
+ 2. If a list of MessageContent or a string is provided, it is converted into a user message.
147
+ hyperparameters (dict[str, Any] | None, optional): A dictionary of hyperparameters for the language model.
148
+ Defaults to None, in which case the default hyperparameters are used.
149
+ event_emitter (EventEmitter | None, optional): The event emitter for streaming tokens. If provided,
150
+ streaming invocation is enabled. Defaults to None.
151
+
152
+ Returns:
153
+ str | LMOutput: The generated response from the language model.
154
+
155
+ Raises:
156
+ CancelledError: If the invocation is cancelled.
157
+ ModelNotFoundError: If the model is not found.
158
+ ProviderAuthError: If the model authentication fails.
159
+ ProviderInternalError: If the model internal error occurs.
160
+ ProviderInvalidArgsError: If the model parameters are invalid.
161
+ ProviderOverloadedError: If the model is overloaded.
162
+ ProviderRateLimitError: If the model rate limit is exceeded.
163
+ TimeoutError: If the invocation times out.
164
+ ValueError: If the messages are not in the correct format.
165
+ """
@@ -0,0 +1,253 @@
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, OPENAI_DEFAULT_URL as OPENAI_DEFAULT_URL
6
+ from gllm_inference.lm_invoker.lm_invoker import BaseLMInvoker as BaseLMInvoker
7
+ from gllm_inference.lm_invoker.schema.openai_chat_completions import InputType as InputType, Key as Key, ReasoningEffort as ReasoningEffort
8
+ from gllm_inference.schema import Attachment as Attachment, AttachmentType as AttachmentType, LMOutput as LMOutput, Message as Message, MessageRole as MessageRole, ModelId as ModelId, ModelProvider as ModelProvider, Reasoning as Reasoning, ResponseSchema as ResponseSchema, ThinkingEvent as ThinkingEvent, 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 OpenAIChatCompletionsLMInvoker(BaseLMInvoker):
16
+ '''A language model invoker to interact with OpenAI language models using the Chat Completions API.
17
+
18
+ This class provides support for OpenAI\'s Chat Completions API schema. Use this class only when you have
19
+ a specific reason to use the Chat Completions API over the Responses API, as OpenAI recommends using
20
+ the Responses API whenever possible. The Responses API schema is supported through the `OpenAILMInvoker` class.
21
+
22
+ Attributes:
23
+ model_id (str): The model ID of the language model.
24
+ model_provider (str): The provider of the language model.
25
+ model_name (str): The name of the language model.
26
+ client_kwargs (dict[str, Any]): The keyword arguments for the OpenAI client.
27
+ default_hyperparameters (dict[str, Any]): Default hyperparameters for invoking the model.
28
+ tools (list[Tool]): The list of tools provided to the model to enable tool calling.
29
+ response_schema (ResponseSchema | None): The schema of the response. If provided, the model will output a
30
+ structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema dictionary.
31
+ output_analytics (bool): Whether to output the invocation analytics.
32
+ retry_config (RetryConfig | None): The retry configuration for the language model.
33
+
34
+ Basic usage:
35
+ The `OpenAIChatCompletionsLMInvoker` can be used as follows:
36
+ ```python
37
+ lm_invoker = OpenAIChatCompletionsLMInvoker(model_name="gpt-5-nano")
38
+ result = await lm_invoker.invoke("Hi there!")
39
+ ```
40
+
41
+ OpenAI compatible endpoints:
42
+ The `OpenAIChatCompletionsLMInvoker` can also be used to interact with endpoints that are compatible with
43
+ OpenAI\'s Chat Completions API schema. This includes but are not limited to:
44
+ 1. DeepInfra (https://deepinfra.com/)
45
+ 2. DeepSeek (https://deepseek.com/)
46
+ 3. Groq (https://groq.com/)
47
+ 4. OpenRouter (https://openrouter.ai/)
48
+ 5. Text Generation Inference (https://github.com/huggingface/text-generation-inference)
49
+ 6. Together.ai (https://together.ai/)
50
+ 7. vLLM (https://vllm.ai/)
51
+ Please note that the supported features and capabilities may vary between different endpoints and
52
+ language models. Using features that are not supported by the endpoint will result in an error.
53
+
54
+ This customization can be done by setting the `base_url` parameter to the base URL of the endpoint:
55
+ ```python
56
+ lm_invoker = OpenAIChatCompletionsLMInvoker(
57
+ model_name="llama3-8b-8192",
58
+ api_key="<your-api-key>",
59
+ base_url="https://api.groq.com/openai/v1",
60
+ )
61
+ result = await lm_invoker.invoke("Hi there!")
62
+ ```
63
+
64
+ Input types:
65
+ The `OpenAIChatCompletionsLMInvoker` supports the following input types: text, audio, document, and image.
66
+ Non-text inputs can be passed as an `Attachment` object with the `user` role.
67
+
68
+ Usage example:
69
+ ```python
70
+ text = "What animal is in this image?"
71
+ image = Attachment.from_path("path/to/local/image.png")
72
+ result = await lm_invoker.invoke([text, image])
73
+ ```
74
+
75
+ Text output:
76
+ The `OpenAIChatCompletionsLMInvoker` generates text outputs by default.
77
+ Text outputs are stored in the `outputs` attribute of the `LMOutput` object and can be accessed
78
+ via the `texts` (all text outputs) or `text` (first text output) properties.
79
+
80
+ Output example:
81
+ ```python
82
+ LMOutput(outputs=[LMOutputItem(type="text", output="Hello, there!")])
83
+ ```
84
+
85
+ Structured output:
86
+ The `OpenAIChatCompletionsLMInvoker` can be configured to generate structured outputs.
87
+ This feature can be enabled by providing a schema to the `response_schema` parameter.
88
+
89
+ Structured outputs are stored in the `outputs` attribute of the `LMOutput` object and can be accessed
90
+ via the `structureds` (all structured outputs) or `structured` (first structured output) properties.
91
+
92
+ The schema must either be one of the following:
93
+ 1. A Pydantic BaseModel class
94
+ The structured output will be a Pydantic model.
95
+ 2. A JSON schema dictionary
96
+ JSON dictionary schema must be compatible with Pydantic\'s JSON schema, especially for complex schemas.
97
+ Thus, it is recommended to create the JSON schema using Pydantic\'s `model_json_schema` method.
98
+ The structured output will be a dictionary.
99
+
100
+ Usage example:
101
+ ```python
102
+ class Animal(BaseModel):
103
+ name: str
104
+ color: str
105
+
106
+ json_schema = Animal.model_json_schema()
107
+
108
+ lm_invoker = OpenAIChatCompletionsLMInvoker(..., response_schema=Animal) # Using Pydantic BaseModel class
109
+ lm_invoker = OpenAIChatCompletionsLMInvoker(..., response_schema=json_schema) # Using JSON schema dictionary
110
+ ```
111
+
112
+ Output example:
113
+ ```python
114
+ # Using Pydantic BaseModel class outputs a Pydantic model
115
+ LMOutput(outputs=[LMOutputItem(type="structured", output=Animal(name="dog", color="white"))])
116
+
117
+ # Using JSON schema dictionary outputs a dictionary
118
+ LMOutput(outputs=[LMOutputItem(type="structured", output={"name": "dog", "color": "white"})])
119
+ ```
120
+
121
+ When structured output is enabled, streaming is disabled.
122
+
123
+ Tool calling:
124
+ The `OpenAIChatCompletionsLMInvoker` can be configured to call tools to perform certain tasks.
125
+ This feature can be enabled by providing a list of `Tool` objects to the `tools` parameter.
126
+
127
+ Tool calls outputs are stored in the `outputs` attribute of the `LMOutput` object and
128
+ can be accessed via the `tool_calls` property.
129
+
130
+ Usage example:
131
+ ```python
132
+ lm_invoker = OpenAIChatCompletionsLMInvoker(..., tools=[tool_1, tool_2])
133
+ ```
134
+
135
+ Output example:
136
+ ```python
137
+ LMOutput(
138
+ outputs=[
139
+ LMOutputItem(type="text", output="I\'m using tools..."),
140
+ LMOutputItem(type="tool_call", output=ToolCall(id="123", name="tool_1", args={"key": "value"})),
141
+ LMOutputItem(type="tool_call", output=ToolCall(id="456", name="tool_2", args={"key": "value"})),
142
+ ]
143
+ )
144
+ ```
145
+
146
+ Reasoning:
147
+ The `OpenAILMInvoker` performs step-by-step reasoning before generating a response when reasoning
148
+ models are used, such as GPT-5 models and o-series models.
149
+
150
+ The reasoning effort can be set via the `reasoning_effort` parameter, which guides the models on the amount
151
+ of reasoning tokens to generate. Available options include `minimal`, `low`, `medium`, and `high`.
152
+
153
+ Some models may also output the reasoning tokens. In this case, the reasoning tokens are stored in
154
+ the `outputs` attribute of the `LMOutput` object and can be accessed via the `thinkings` property.
155
+
156
+ Output example:
157
+ ```python
158
+ LMOutput(
159
+ outputs=[
160
+ LMOutputItem(type="thinking", output=Reasoning(reasoning="I\'m thinking...", ...)),
161
+ LMOutputItem(type="text", output="Golden retriever is a good dog breed."),
162
+ ]
163
+ )
164
+ ```
165
+
166
+ Streaming output example:
167
+ ```python
168
+ {"type": "thinking_start", "value": "", ...}
169
+ {"type": "thinking", "value": "I\'m ", ...}
170
+ {"type": "thinking", "value": "thinking...", ...}
171
+ {"type": "thinking_end", "value": "", ...}
172
+ {"type": "response", "value": "Golden retriever ", ...}
173
+ {"type": "response", "value": "is a good dog breed.", ...}
174
+ ```
175
+ Note: By default, the thinking token will be streamed with the legacy `EventType.DATA` event type.
176
+ To use the new simplified streamed event format, set the `simplify_events` parameter to `True` during
177
+ LM invoker initialization. The legacy event format support will be removed in v0.6.
178
+
179
+ Setting reasoning-related parameters for non-reasoning models will raise an error.
180
+
181
+ Analytics tracking:
182
+ The `OpenAIChatCompletionsLMInvoker` can be configured to output additional information about the invocation.
183
+ This feature can be enabled by setting the `output_analytics` parameter to `True`.
184
+
185
+ When enabled, the following attributes will be stored in the output:
186
+ 1. `token_usage`: The token usage.
187
+ 2. `duration`: The duration in seconds.
188
+ 3. `finish_details`: The details about how the generation finished.
189
+
190
+ Output example:
191
+ ```python
192
+ LMOutput(
193
+ outputs=[...],
194
+ token_usage=TokenUsage(input_tokens=100, output_tokens=50),
195
+ duration=0.729,
196
+ finish_details={"stop_reason": "end_turn"},
197
+ )
198
+ ```
199
+
200
+ When streaming is enabled, token usage is not supported.
201
+
202
+ Retry and timeout:
203
+ The `OpenAIChatCompletionsLMInvoker` supports retry and timeout configuration.
204
+ By default, the max retries is set to 0 and the timeout is set to 30.0 seconds.
205
+ They can be customized by providing a custom `RetryConfig` object to the `retry_config` parameter.
206
+
207
+ Retry config examples:
208
+ ```python
209
+ retry_config = RetryConfig(max_retries=0, timeout=None) # No retry, no timeout
210
+ retry_config = RetryConfig(max_retries=5, timeout=10.0) # 5 max retries, 10.0 seconds timeout
211
+ ```
212
+
213
+ Usage example:
214
+ ```python
215
+ lm_invoker = OpenAIChatCompletionsLMInvoker(..., retry_config=retry_config)
216
+ ```
217
+ '''
218
+ client_kwargs: Incomplete
219
+ def __init__(self, model_name: str, api_key: str | None = None, base_url: str = ..., 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, simplify_events: bool = False) -> None:
220
+ '''Initializes a new instance of the OpenAIChatCompletionsLMInvoker class.
221
+
222
+ Args:
223
+ model_name (str): The name of the OpenAI model.
224
+ api_key (str | None, optional): The API key for authenticating with OpenAI. Defaults to None, in which
225
+ case the `OPENAI_API_KEY` environment variable will be used. If the endpoint does not require an
226
+ API key, a dummy value can be passed (e.g. "<empty>").
227
+ base_url (str, optional): The base URL of a custom endpoint that is compatible with OpenAI\'s
228
+ Chat Completions API schema. Defaults to OpenAI\'s default URL.
229
+ model_kwargs (dict[str, Any] | None, optional): Additional model parameters. Defaults to None.
230
+ default_hyperparameters (dict[str, Any] | None, optional): Default hyperparameters for invoking the model.
231
+ Defaults to None.
232
+ tools (list[Tool | LangChainTool] | None, optional): Tools provided to the model to enable tool calling.
233
+ Defaults to None.
234
+ response_schema (ResponseSchema | None, optional): The schema of the response. If provided, the model will
235
+ output a structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema
236
+ dictionary. Defaults to None.
237
+ output_analytics (bool, optional): Whether to output the invocation analytics. Defaults to False.
238
+ retry_config (RetryConfig | None, optional): The retry configuration for the language model.
239
+ Defaults to None, in which case a default config with no retry and 30.0 seconds timeout will be used.
240
+ reasoning_effort (str | None, optional): The reasoning effort for the language model. Defaults to None.
241
+ simplify_events (bool, optional): Temporary parameter to control the streamed events format.
242
+ When True, uses the simplified events format. When False, uses the legacy events format for
243
+ backward compatibility. Will be removed in v0.6. Defaults to False.
244
+ '''
245
+ def set_response_schema(self, response_schema: ResponseSchema | None) -> None:
246
+ """Sets the response schema for the OpenAI language model.
247
+
248
+ This method sets the response schema for the OpenAI language model.
249
+ Any existing response schema will be replaced.
250
+
251
+ Args:
252
+ response_schema (ResponseSchema | None): The response schema to be used.
253
+ """