gllm-inference-binary 0.5.9__cp312-cp312-win_amd64.whl → 0.5.9b1__cp312-cp312-win_amd64.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.
- gllm_inference/builder/build_em_invoker.pyi +17 -2
- gllm_inference/builder/build_lm_invoker.pyi +13 -2
- gllm_inference/constants.pyi +2 -2
- gllm_inference/em_invoker/__init__.pyi +2 -1
- gllm_inference/em_invoker/azure_openai_em_invoker.pyi +7 -5
- gllm_inference/em_invoker/bedrock_em_invoker.pyi +106 -0
- gllm_inference/em_invoker/em_invoker.pyi +11 -4
- gllm_inference/em_invoker/google_em_invoker.pyi +8 -3
- gllm_inference/em_invoker/langchain/em_invoker_embeddings.pyi +25 -3
- gllm_inference/em_invoker/langchain_em_invoker.pyi +7 -2
- gllm_inference/em_invoker/openai_compatible_em_invoker.pyi +6 -2
- gllm_inference/em_invoker/openai_em_invoker.pyi +5 -1
- gllm_inference/em_invoker/schema/bedrock.pyi +22 -0
- gllm_inference/em_invoker/schema/google.pyi +2 -0
- gllm_inference/em_invoker/schema/langchain.pyi +1 -0
- gllm_inference/em_invoker/twelevelabs_em_invoker.pyi +5 -3
- gllm_inference/em_invoker/voyage_em_invoker.pyi +5 -2
- gllm_inference/exceptions/__init__.pyi +3 -3
- gllm_inference/exceptions/error_parser.pyi +26 -33
- gllm_inference/exceptions/exceptions.pyi +40 -28
- gllm_inference/exceptions/provider_error_map.pyi +23 -0
- gllm_inference/lm_invoker/__init__.pyi +2 -1
- gllm_inference/lm_invoker/azure_openai_lm_invoker.pyi +12 -13
- gllm_inference/lm_invoker/bedrock_lm_invoker.pyi +2 -0
- gllm_inference/lm_invoker/google_lm_invoker.pyi +8 -1
- gllm_inference/lm_invoker/langchain_lm_invoker.pyi +2 -0
- gllm_inference/lm_invoker/lm_invoker.pyi +7 -6
- gllm_inference/lm_invoker/openai_compatible_lm_invoker.pyi +1 -1
- gllm_inference/lm_invoker/openai_lm_invoker.pyi +7 -6
- gllm_inference/lm_invoker/schema/bedrock.pyi +5 -0
- gllm_inference/lm_invoker/schema/langchain.pyi +1 -0
- gllm_inference/lm_invoker/schema/openai.pyi +1 -0
- gllm_inference/lm_invoker/schema/openai_compatible.pyi +4 -0
- gllm_inference/lm_invoker/schema/xai.pyi +31 -0
- gllm_inference/lm_invoker/xai_lm_invoker.pyi +305 -0
- gllm_inference/request_processor/lm_request_processor.pyi +12 -3
- gllm_inference/request_processor/uses_lm_mixin.pyi +109 -29
- gllm_inference/schema/__init__.pyi +5 -4
- gllm_inference/schema/config.pyi +15 -0
- gllm_inference/schema/enums.pyi +5 -0
- gllm_inference/schema/model_id.pyi +10 -1
- gllm_inference/schema/token_usage.pyi +66 -2
- gllm_inference/schema/type_alias.pyi +1 -5
- gllm_inference/utils/__init__.pyi +2 -1
- gllm_inference/utils/io_utils.pyi +26 -0
- gllm_inference.cp312-win_amd64.pyd +0 -0
- gllm_inference.pyi +25 -12
- {gllm_inference_binary-0.5.9.dist-info → gllm_inference_binary-0.5.9b1.dist-info}/METADATA +71 -108
- {gllm_inference_binary-0.5.9.dist-info → gllm_inference_binary-0.5.9b1.dist-info}/RECORD +51 -43
- {gllm_inference_binary-0.5.9.dist-info → gllm_inference_binary-0.5.9b1.dist-info}/WHEEL +2 -1
- gllm_inference_binary-0.5.9b1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,305 @@
|
|
|
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 GRPC_ENABLE_RETRIES_KEY as GRPC_ENABLE_RETRIES_KEY, INVOKER_PROPAGATED_MAX_RETRIES as INVOKER_PROPAGATED_MAX_RETRIES
|
|
6
|
+
from gllm_inference.exceptions import BaseInvokerError as BaseInvokerError, InvokerRuntimeError as InvokerRuntimeError, build_debug_info as build_debug_info
|
|
7
|
+
from gllm_inference.exceptions.provider_error_map import GRPC_STATUS_CODE_MAPPING as GRPC_STATUS_CODE_MAPPING
|
|
8
|
+
from gllm_inference.lm_invoker.lm_invoker import BaseLMInvoker as BaseLMInvoker
|
|
9
|
+
from gllm_inference.lm_invoker.schema.xai import Key as Key, ReasoningEffort as ReasoningEffort
|
|
10
|
+
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
|
|
11
|
+
from gllm_inference.utils.validation import validate_string_enum as validate_string_enum
|
|
12
|
+
from langchain_core.tools import Tool as LangChainTool
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
SUPPORTED_ATTACHMENTS: Incomplete
|
|
16
|
+
|
|
17
|
+
class XAILMInvoker(BaseLMInvoker):
|
|
18
|
+
'''A language model invoker to interact with xAI language models.
|
|
19
|
+
|
|
20
|
+
Attributes:
|
|
21
|
+
model_id (str): The model ID of the language model.
|
|
22
|
+
model_provider (str): The provider of the language model.
|
|
23
|
+
model_name (str): The name of the language model.
|
|
24
|
+
client_params (dict[str, Any]): The xAI client initialization parameters.
|
|
25
|
+
default_hyperparameters (dict[str, Any]): Default hyperparameters for invoking the model.
|
|
26
|
+
tools (list[Tool]): The list of tools provided to the model to enable tool calling.
|
|
27
|
+
response_schema (ResponseSchema | None): The schema of the response. If provided, the model will output a
|
|
28
|
+
structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema dictionary.
|
|
29
|
+
output_analytics (bool): Whether to output the invocation analytics.
|
|
30
|
+
retry_config (RetryConfig | None): The retry configuration for the language model.
|
|
31
|
+
reasoning_effort (ReasoningEffort | None): The reasoning effort level for reasoning models ("low" or "high").
|
|
32
|
+
web_search (bool): Whether to enable the web search.
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
Basic usage:
|
|
36
|
+
The `XAILMInvoker` can be used as follows:
|
|
37
|
+
```python
|
|
38
|
+
lm_invoker = XAILMInvoker(model_name="grok-3")
|
|
39
|
+
result = await lm_invoker.invoke("Hi there!")
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Input types:
|
|
43
|
+
The `XAILMInvoker` supports the following input types: text and image.
|
|
44
|
+
Non-text inputs can be passed as an `Attachment` object with the `user` role.
|
|
45
|
+
|
|
46
|
+
Usage example:
|
|
47
|
+
```python
|
|
48
|
+
text = "What animal is in this image?"
|
|
49
|
+
image = Attachment.from_path("path/to/local/image.png")
|
|
50
|
+
result = await lm_invoker.invoke([text, image])
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Tool calling:
|
|
54
|
+
Tool calling is a feature that allows the language model to call tools to perform tasks.
|
|
55
|
+
Tools can be passed to the via the `tools` parameter as a list of `Tool` objects.
|
|
56
|
+
When tools are provided and the model decides to call a tool, the tool calls are stored in the
|
|
57
|
+
`tool_calls` attribute in the output.
|
|
58
|
+
|
|
59
|
+
Usage example:
|
|
60
|
+
```python
|
|
61
|
+
lm_invoker = XAILMInvoker(..., tools=[tool_1, tool_2])
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Output example:
|
|
65
|
+
```python
|
|
66
|
+
LMOutput(
|
|
67
|
+
response="Let me call the tools...",
|
|
68
|
+
tool_calls=[
|
|
69
|
+
ToolCall(id="123", name="tool_1", args={"key": "value"}),
|
|
70
|
+
ToolCall(id="456", name="tool_2", args={"key": "value"}),
|
|
71
|
+
]
|
|
72
|
+
)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Structured output:
|
|
76
|
+
Structured output is a feature that allows the language model to output a structured response.
|
|
77
|
+
This feature can be enabled by providing a schema to the `response_schema` parameter.
|
|
78
|
+
|
|
79
|
+
The schema must be either a JSON schema dictionary or a Pydantic BaseModel class.
|
|
80
|
+
If JSON schema is used, it must be compatible with Pydantic\'s JSON schema, especially for complex schemas.
|
|
81
|
+
For this reason, it is recommended to create the JSON schema using Pydantic\'s `model_json_schema` method.
|
|
82
|
+
|
|
83
|
+
The language model also doesn\'t need to stream anything when structured output is enabled. Thus, standard
|
|
84
|
+
invocation will be performed regardless of whether the `event_emitter` parameter is provided or not.
|
|
85
|
+
|
|
86
|
+
When enabled, the structured output is stored in the `structured_output` attribute in the output.
|
|
87
|
+
1. If the schema is a JSON schema dictionary, the structured output is a dictionary.
|
|
88
|
+
2. If the schema is a Pydantic BaseModel class, the structured output is a Pydantic model.
|
|
89
|
+
|
|
90
|
+
# Example 1: Using a JSON schema dictionary
|
|
91
|
+
Usage example:
|
|
92
|
+
```python
|
|
93
|
+
schema = {
|
|
94
|
+
"title": "Animal",
|
|
95
|
+
"description": "A description of an animal.",
|
|
96
|
+
"properties": {
|
|
97
|
+
"color": {"title": "Color", "type": "string"},
|
|
98
|
+
"name": {"title": "Name", "type": "string"},
|
|
99
|
+
},
|
|
100
|
+
"required": ["name", "color"],
|
|
101
|
+
"type": "object",
|
|
102
|
+
}
|
|
103
|
+
lm_invoker = XAILMInvoker(..., response_schema=schema)
|
|
104
|
+
```
|
|
105
|
+
Output example:
|
|
106
|
+
```python
|
|
107
|
+
LMOutput(structured_output={"name": "Golden retriever", "color": "Golden"})
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
# Example 2: Using a Pydantic BaseModel class
|
|
111
|
+
Usage example:
|
|
112
|
+
```python
|
|
113
|
+
class Animal(BaseModel):
|
|
114
|
+
name: str
|
|
115
|
+
color: str
|
|
116
|
+
|
|
117
|
+
lm_invoker = XAILMInvoker(..., response_schema=Animal)
|
|
118
|
+
```
|
|
119
|
+
Output example:
|
|
120
|
+
```python
|
|
121
|
+
LMOutput(structured_output=Animal(name="Golden retriever", color="Golden"))
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Reasoning:
|
|
125
|
+
Reasoning effort is a feature specific to xAI\'s reasoning models that allows you to control the level
|
|
126
|
+
of reasoning performed by the model. This feature can be enabled by setting the `reasoning_effort` parameter.
|
|
127
|
+
Valid values are "low" and "high".
|
|
128
|
+
|
|
129
|
+
Please note that Grok 4 does not have a `reasoning_effort` parameter. If a `reasoning_effort` is provided,
|
|
130
|
+
the request will return error.
|
|
131
|
+
|
|
132
|
+
Usage example:
|
|
133
|
+
```python
|
|
134
|
+
lm_invoker = XAILMInvoker(
|
|
135
|
+
model_name="grok-3",
|
|
136
|
+
reasoning_effort="high" # Enable high reasoning effort
|
|
137
|
+
)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
When reasoning effort is enabled, the model\'s internal reasoning process is captured and stored in the
|
|
141
|
+
`reasoning` attribute in the output.
|
|
142
|
+
|
|
143
|
+
Output example:
|
|
144
|
+
```python
|
|
145
|
+
LMOutput(
|
|
146
|
+
response="The answer is 42",
|
|
147
|
+
reasoning=[
|
|
148
|
+
Reasoning(
|
|
149
|
+
id="reasoning_1",
|
|
150
|
+
reasoning="First, I need to understand the question. The user is asking about..."
|
|
151
|
+
)
|
|
152
|
+
]
|
|
153
|
+
)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
When streaming is enabled along with reasoning summary, the reasoning summary token will be streamed with the
|
|
157
|
+
`EventType.DATA` event type.
|
|
158
|
+
|
|
159
|
+
Streaming output example:
|
|
160
|
+
```python
|
|
161
|
+
{"type": "data", "value": \'{"data_type": "thinking_start", "data_value": ""}\', ...}
|
|
162
|
+
{"type": "data", "value": \'{"data_type": "thinking", "data_value": "Let me think "}\', ...}
|
|
163
|
+
{"type": "data", "value": \'{"data_type": "thinking", "data_value": "about it..."}\', ...}
|
|
164
|
+
{"type": "data", "value": \'{"data_type": "thinking_end", "data_value": ""}\', ...}
|
|
165
|
+
{"type": "response", "value": "Golden retriever ", ...}
|
|
166
|
+
{"type": "response", "value": "is a good dog breed.", ...}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Setting reasoning-related parameters for non-reasoning models will raise an error.
|
|
170
|
+
|
|
171
|
+
Analytics tracking:
|
|
172
|
+
Analytics tracking is a feature that allows the module to output additional information about the invocation.
|
|
173
|
+
This feature can be enabled by setting the `output_analytics` parameter to `True`.
|
|
174
|
+
When enabled, the following attributes will be stored in the output:
|
|
175
|
+
1. `token_usage`: The token usage.
|
|
176
|
+
2. `finish_details`: The details about how the generation finished.
|
|
177
|
+
|
|
178
|
+
Output example:
|
|
179
|
+
```python
|
|
180
|
+
LMOutput(
|
|
181
|
+
response="Golden retriever is a good dog breed.",
|
|
182
|
+
token_usage=TokenUsage(input_tokens=100, output_tokens=50),
|
|
183
|
+
finish_details={"finish_reason": "stop"},
|
|
184
|
+
)
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
When streaming is enabled, token usage is not supported. Therefore, the `token_usage` attribute will be `None`
|
|
188
|
+
regardless of the value of the `output_analytics` parameter.
|
|
189
|
+
|
|
190
|
+
Retry and timeout:
|
|
191
|
+
The `XAILMInvoker` supports retry and timeout configuration.
|
|
192
|
+
By default, the max retries is set to 0 and the timeout is set to 30.0 seconds.
|
|
193
|
+
They can be customized by providing a custom `RetryConfig` object to the `retry_config` parameter.
|
|
194
|
+
|
|
195
|
+
Retry config examples:
|
|
196
|
+
```python
|
|
197
|
+
retry_config = RetryConfig(max_retries=0, timeout=0.0) # No retry, no timeout
|
|
198
|
+
retry_config = RetryConfig(max_retries=0, timeout=10.0) # No retry, 10.0 seconds timeout
|
|
199
|
+
retry_config = RetryConfig(max_retries=5, timeout=0.0) # 5 max retries, no timeout
|
|
200
|
+
retry_config = RetryConfig(max_retries=5, timeout=10.0) # 5 max retries, 10.0 seconds timeout
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Usage example:
|
|
204
|
+
```python
|
|
205
|
+
lm_invoker = XAILMInvoker(..., retry_config=retry_config)
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Web Search:
|
|
209
|
+
The web search is a feature that allows the language model to search the web for relevant information.
|
|
210
|
+
This feature can be enabled by setting the `web_search` parameter to `True`.
|
|
211
|
+
|
|
212
|
+
Usage example:
|
|
213
|
+
```python
|
|
214
|
+
lm_invoker = XAILMInvoker(
|
|
215
|
+
model_name="grok-3",
|
|
216
|
+
web_search=True
|
|
217
|
+
)
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
When web search is enabled, the language model will search for relevant information and may cite the
|
|
221
|
+
relevant sources (including from X platform). The citations will be stored as `Chunk` objects in the `citations`
|
|
222
|
+
attribute in the output.
|
|
223
|
+
|
|
224
|
+
Output example:
|
|
225
|
+
```python
|
|
226
|
+
LMOutput(
|
|
227
|
+
response="According to recent reports, the latest AI developments include... ([Source](https://example.com)).",
|
|
228
|
+
citations=[
|
|
229
|
+
Chunk(
|
|
230
|
+
id="search_result_1",
|
|
231
|
+
content="Latest AI developments report",
|
|
232
|
+
metadata={
|
|
233
|
+
"start_index": 164,
|
|
234
|
+
"end_index": 275,
|
|
235
|
+
"title": "Example title",
|
|
236
|
+
"url": "https://www.example.com",
|
|
237
|
+
"type": "url_citation",
|
|
238
|
+
},
|
|
239
|
+
),
|
|
240
|
+
],
|
|
241
|
+
)
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
When streaming is enabled, the live search activities will be streamed with the `EventType.DATA` event type.
|
|
245
|
+
This allows you to track the search process in real-time.
|
|
246
|
+
|
|
247
|
+
Streaming output example:
|
|
248
|
+
```python
|
|
249
|
+
{"type": "data", "value": \'{"data_type": "activity", "data_value": "{\\"query\\": \\"search query\\"}", ...}\', ...}
|
|
250
|
+
{"type": "response", "value": "According to recent reports, ", ...}
|
|
251
|
+
{"type": "response", "value": "the latest AI developments include...", ...}
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
Output types:
|
|
255
|
+
The output of the `XAILMInvoker` can either be:
|
|
256
|
+
1. `str`: The text response if no additional output is needed.
|
|
257
|
+
2. `LMOutput`: A Pydantic model with the following attributes if any additional output is needed:
|
|
258
|
+
2.1. response (str): The text response.
|
|
259
|
+
2.2. tool_calls (list[ToolCall]): The tool calls, if the `tools` parameter is defined and the language
|
|
260
|
+
model decides to invoke tools. Defaults to an empty list.
|
|
261
|
+
2.3. structured_output (dict[str, Any] | BaseModel | None): The structured output, if the `response_schema`
|
|
262
|
+
parameter is defined. Defaults to None.
|
|
263
|
+
2.4. token_usage (TokenUsage | None): The token usage analytics, if the `output_analytics` parameter is
|
|
264
|
+
set to `True`. Defaults to None.
|
|
265
|
+
2.5. duration (float | None): The duration of the invocation in seconds, if the `output_analytics`
|
|
266
|
+
parameter is set to `True`. Defaults to None.
|
|
267
|
+
2.6. finish_details (dict[str, Any] | None): The details about how the generation finished, if the
|
|
268
|
+
`output_analytics` parameter is set to `True`. Defaults to None.
|
|
269
|
+
2.7. reasoning (list[Reasoning]): The reasoning objects, if the `reasoning_effort` parameter is set.
|
|
270
|
+
Defaults to an empty list.
|
|
271
|
+
2.8. citations (list[Chunk]): The citations, if the web_search is enabled and the language model decides
|
|
272
|
+
to cite the relevant sources. Defaults to an empty list.
|
|
273
|
+
2.9. code_exec_results (list[CodeExecResult]): The code execution results. Currently not supported.
|
|
274
|
+
Defaults to an empty list.
|
|
275
|
+
'''
|
|
276
|
+
reasoning_effort: Incomplete
|
|
277
|
+
web_search: Incomplete
|
|
278
|
+
client_params: Incomplete
|
|
279
|
+
def __init__(self, model_name: 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, web_search: bool = False) -> None:
|
|
280
|
+
"""Initializes a new instance of the XAILMInvoker class.
|
|
281
|
+
|
|
282
|
+
Args:
|
|
283
|
+
model_name (str): The name of the xAI model.
|
|
284
|
+
api_key (str | None, optional): The API key for authenticating with xAI. Defaults to None, in which
|
|
285
|
+
case the `XAI_API_KEY` environment variable will be used.
|
|
286
|
+
model_kwargs (dict[str, Any] | None, optional): Additional model parameters. Defaults to None.
|
|
287
|
+
default_hyperparameters (dict[str, Any] | None, optional): Default hyperparameters for invoking the model.
|
|
288
|
+
Defaults to None.
|
|
289
|
+
tools (list[Tool | LangChainTool] | None, optional): Tools provided to the language model to enable tool
|
|
290
|
+
calling.
|
|
291
|
+
Defaults to None.
|
|
292
|
+
response_schema (ResponseSchema | None, optional): The schema of the response. If provided, the model will
|
|
293
|
+
output a structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema
|
|
294
|
+
dictionary. Defaults to None.
|
|
295
|
+
output_analytics (bool, optional): Whether to output the invocation analytics. Defaults to False.
|
|
296
|
+
retry_config (RetryConfig | None, optional): The retry configuration for the language model.
|
|
297
|
+
Defaults to None, in which case a default config with no retry and 30.0 seconds timeout is used.
|
|
298
|
+
reasoning_effort (ReasoningEffort | None, optional): The reasoning effort for reasoning models. Not allowed
|
|
299
|
+
for non-reasoning models. If None, the model will perform medium reasoning effort. Defaults to None.
|
|
300
|
+
web_search (bool, optional): Whether to enable the web search. Defaults to False.
|
|
301
|
+
|
|
302
|
+
Raises:
|
|
303
|
+
ValueError:
|
|
304
|
+
1. `reasoning_effort` is provided, but is not a valid ReasoningEffort.
|
|
305
|
+
"""
|
|
@@ -60,7 +60,7 @@ class LMRequestProcessor:
|
|
|
60
60
|
|
|
61
61
|
This method clears the response schema for the LM invoker.
|
|
62
62
|
"""
|
|
63
|
-
async def process(self, prompt_kwargs: dict[str, Any] | None = None, history: list[Message] | None = None, extra_contents: list[MessageContent] | None = None, hyperparameters: dict[str, Any] | None = None, event_emitter: EventEmitter | None = None, auto_execute_tools: bool = True, max_lm_calls: int = 5) -> Any:
|
|
63
|
+
async def process(self, prompt_kwargs: dict[str, Any] | None = None, history: list[Message] | None = None, extra_contents: list[MessageContent] | None = None, hyperparameters: dict[str, Any] | None = None, event_emitter: EventEmitter | None = None, auto_execute_tools: bool = True, max_lm_calls: int = 5, **kwargs: Any) -> Any:
|
|
64
64
|
"""Processes a language model inference request.
|
|
65
65
|
|
|
66
66
|
This method processes the language model inference request as follows:
|
|
@@ -72,8 +72,8 @@ class LMRequestProcessor:
|
|
|
72
72
|
LMOutput object, the output parser will process the `response` attribute of the LMOutput object.
|
|
73
73
|
|
|
74
74
|
Args:
|
|
75
|
-
prompt_kwargs (dict[str, Any], optional):
|
|
76
|
-
|
|
75
|
+
prompt_kwargs (dict[str, Any], optional): Deprecated parameter for passing prompt kwargs.
|
|
76
|
+
Replaced by **kwargs. Defaults to None
|
|
77
77
|
history (list[Message] | None, optional): A list of conversation history to be included in the prompt.
|
|
78
78
|
Defaults to None.
|
|
79
79
|
extra_contents (list[MessageContent] | None, optional): A list of extra contents to be included in the
|
|
@@ -86,6 +86,15 @@ class LMRequestProcessor:
|
|
|
86
86
|
tool calls. Defaults to True.
|
|
87
87
|
max_lm_calls (int, optional): The maximum number of times the language model can be invoked
|
|
88
88
|
when `auto_execute_tools` is True. Defaults to 5.
|
|
89
|
+
**kwargs (Any): Keyword arguments that will be passed to format the prompt builder.
|
|
90
|
+
Values must be either a string or an object that can be serialized to a string.
|
|
91
|
+
Reserved keyword arguments that cannot be passed to the prompt builder include:
|
|
92
|
+
1. `history`
|
|
93
|
+
2. `extra_contents`
|
|
94
|
+
3. `hyperparameters`
|
|
95
|
+
4. `event_emitter`
|
|
96
|
+
5. `auto_execute_tools`
|
|
97
|
+
6. `max_lm_calls`
|
|
89
98
|
|
|
90
99
|
Returns:
|
|
91
100
|
Any: The result of the language model invocation, optionally parsed by the output parser.
|
|
@@ -1,40 +1,104 @@
|
|
|
1
|
+
from gllm_inference.builder.build_lm_invoker import build_lm_invoker as build_lm_invoker
|
|
1
2
|
from gllm_inference.lm_invoker.lm_invoker import BaseLMInvoker as BaseLMInvoker
|
|
2
3
|
from gllm_inference.output_parser.output_parser import BaseOutputParser as BaseOutputParser
|
|
3
4
|
from gllm_inference.prompt_builder.prompt_builder import PromptBuilder as PromptBuilder
|
|
4
5
|
from gllm_inference.request_processor.lm_request_processor import LMRequestProcessor as LMRequestProcessor
|
|
6
|
+
from gllm_inference.schema import LMOutput as LMOutput
|
|
7
|
+
from pydantic import BaseModel as BaseModel
|
|
5
8
|
from typing import Any
|
|
6
9
|
|
|
7
10
|
class UsesLM:
|
|
8
|
-
'''A mixin to
|
|
9
|
-
|
|
10
|
-
This mixin should be extended by
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
11
|
+
'''A mixin to be extended by components that use LMRequestProcessor.
|
|
12
|
+
|
|
13
|
+
This mixin should be extended by components that use LMRequestProcessor. Components that extend this mixin
|
|
14
|
+
must have a constructor that accepts the LMRequestProcessor instance as its first argument.
|
|
15
|
+
|
|
16
|
+
LM based components can be categorized into two types:
|
|
17
|
+
1. Components that do not utilize structured output.
|
|
18
|
+
2. Components that utilize structured output.
|
|
19
|
+
|
|
20
|
+
Building a component without structured output:
|
|
21
|
+
As defined above, the component must accepts an LMRequestProcessor instance as its first argument, e.g.:
|
|
22
|
+
```python
|
|
23
|
+
class LMBasedComponent(Component, UsesLM):
|
|
24
|
+
def __init__(self, lm_request_processor: LMRequestProcessor, custom_kwarg: str):
|
|
25
|
+
self.lm_request_processor = lm_request_processor
|
|
26
|
+
self.custom_kwarg = custom_kwarg
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Using the `from_lm_components` method provided by this mixin, the component can be instantiated as follows:
|
|
30
|
+
```python
|
|
31
|
+
component = LMBasedComponent.from_lm_components(
|
|
32
|
+
prompt_builder,
|
|
33
|
+
lm_invoker,
|
|
34
|
+
output_parser,
|
|
35
|
+
custom_kwarg="custom_value",
|
|
36
|
+
)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Building a component with structured output:
|
|
40
|
+
When the component utilizes structured output, the `_parse_structured_output` method can be used
|
|
41
|
+
to simplify the process of extracting the structured output in the component\'s runtime methods, e.g.:
|
|
42
|
+
```python
|
|
43
|
+
class LMBasedComponent(Component, UsesLM):
|
|
44
|
+
def __init__(self, lm_request_processor: LMRequestProcessor, custom_kwarg: str):
|
|
45
|
+
self.lm_request_processor = lm_request_processor
|
|
46
|
+
self.custom_kwarg = custom_kwarg
|
|
47
|
+
|
|
48
|
+
def runtime_method(self, param1: str, param2: str) -> str:
|
|
49
|
+
lm_output = self.lm_request_processor.process(param1=param1, param2=param2)
|
|
50
|
+
return self._parse_structured_output(lm_output, "target_key", "fallback_output")
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Notice that in the above example, the LMRequestProcessor is configured to take `param1` and `param2`
|
|
54
|
+
as keyword arguments and output a structured output that contains the `target_key` key. Hence,
|
|
55
|
+
these conditions must be fulfilled when instantiating the component.
|
|
56
|
+
|
|
57
|
+
This mixin also provides the `with_structured_output` method to simplify the process of instantiating
|
|
58
|
+
the component with structured output. Let\'s take a look at an example that meets the above conditions:
|
|
59
|
+
```python
|
|
60
|
+
class Schema(BaseModel):
|
|
61
|
+
target_key: str
|
|
62
|
+
|
|
63
|
+
component = LMBasedComponent.with_structured_output(
|
|
64
|
+
model_id="openai/gpt-4.1-mini",
|
|
65
|
+
response_schema=Schema,
|
|
66
|
+
system_template="system_template {param1}",
|
|
67
|
+
user_template="user_template {param2}",
|
|
68
|
+
custom_kwarg="custom_value",
|
|
69
|
+
)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Building a structured output preset:
|
|
73
|
+
If desired, the component can also define a quick preset. This can be done by providing default prompts
|
|
74
|
+
as response schema. Here\'s an example:
|
|
75
|
+
```python
|
|
76
|
+
class Schema(BaseModel):
|
|
77
|
+
target_key: str
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def from_preset(cls, model_id: str, custom_kwarg: str) -> "LMBasedComponent":
|
|
81
|
+
return cls.with_structured_output(
|
|
82
|
+
model_id=model_id,
|
|
83
|
+
response_schema=Schema,
|
|
84
|
+
system_template=PRESET_SYSTEM_TEMPLATE,
|
|
85
|
+
user_template=PRESET_USER_TEMPLATE,
|
|
86
|
+
custom_kwarg=custom_kwarg,
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Then, the preset can be instantiated as follows:
|
|
92
|
+
```python
|
|
93
|
+
component = LMBasedComponent.from_preset(
|
|
94
|
+
model_id="openai/gpt-4.1-mini",
|
|
95
|
+
custom_kwarg="custom_value",
|
|
96
|
+
)
|
|
97
|
+
```
|
|
34
98
|
'''
|
|
35
99
|
@classmethod
|
|
36
|
-
def from_lm_components(cls, prompt_builder: PromptBuilder, lm_invoker: BaseLMInvoker, output_parser: BaseOutputParser | None = None, **kwargs: Any):
|
|
37
|
-
"""Creates an instance
|
|
100
|
+
def from_lm_components(cls, prompt_builder: PromptBuilder, lm_invoker: BaseLMInvoker, output_parser: BaseOutputParser | None = None, **kwargs: Any) -> UsesLM:
|
|
101
|
+
"""Creates an instance from LMRequestProcessor components directly.
|
|
38
102
|
|
|
39
103
|
This method is a shortcut to initialize the class by providing the LMRequestProcessor components directly.
|
|
40
104
|
|
|
@@ -46,5 +110,21 @@ class UsesLM:
|
|
|
46
110
|
**kwargs (Any): Additional keyword arguments to be passed to the class constructor.
|
|
47
111
|
|
|
48
112
|
Returns:
|
|
49
|
-
An instance of the class that mixes in this mixin.
|
|
113
|
+
UsesLM: An instance of the class that mixes in this mixin.
|
|
114
|
+
"""
|
|
115
|
+
@classmethod
|
|
116
|
+
def with_structured_output(cls, model_id: str, response_schema: type[BaseModel], system_template: str = '', user_template: str = '', **kwargs: Any) -> UsesLM:
|
|
117
|
+
"""Creates an instance with structured output configuration.
|
|
118
|
+
|
|
119
|
+
This method is a shortcut to initialize the class with structured output configuration.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
model_id (str): The model ID of the language model.
|
|
123
|
+
response_schema (type[BaseModel]): The response schema of the language model.
|
|
124
|
+
system_template (str, optional): The system template of the language model. Defaults to an empty string.
|
|
125
|
+
user_template (str, optional): The user template of the language model. Defaults to an empty string.
|
|
126
|
+
**kwargs (Any): Additional keyword arguments to be passed to the class constructor.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
UsesLM: An instance of the class that mixes in this mixin with structured output configuration.
|
|
50
130
|
"""
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
from gllm_inference.schema.attachment import Attachment as Attachment
|
|
2
2
|
from gllm_inference.schema.code_exec_result import CodeExecResult as CodeExecResult
|
|
3
|
-
from gllm_inference.schema.
|
|
3
|
+
from gllm_inference.schema.config import TruncationConfig as TruncationConfig
|
|
4
|
+
from gllm_inference.schema.enums import AttachmentType as AttachmentType, EmitDataType as EmitDataType, MessageRole as MessageRole, TruncateSide as TruncateSide
|
|
4
5
|
from gllm_inference.schema.lm_output import LMOutput as LMOutput
|
|
5
6
|
from gllm_inference.schema.message import Message as Message
|
|
6
7
|
from gllm_inference.schema.model_id import ModelId as ModelId, ModelProvider as ModelProvider
|
|
7
8
|
from gllm_inference.schema.reasoning import Reasoning as Reasoning
|
|
8
|
-
from gllm_inference.schema.token_usage import TokenUsage as TokenUsage
|
|
9
|
+
from gllm_inference.schema.token_usage import InputTokenDetails as InputTokenDetails, OutputTokenDetails as OutputTokenDetails, TokenUsage as TokenUsage
|
|
9
10
|
from gllm_inference.schema.tool_call import ToolCall as ToolCall
|
|
10
11
|
from gllm_inference.schema.tool_result import ToolResult as ToolResult
|
|
11
|
-
from gllm_inference.schema.type_alias import EMContent as EMContent,
|
|
12
|
+
from gllm_inference.schema.type_alias import EMContent as EMContent, MessageContent as MessageContent, ResponseSchema as ResponseSchema, Vector as Vector
|
|
12
13
|
|
|
13
|
-
__all__ = ['Attachment', 'AttachmentType', 'CodeExecResult', 'EMContent', 'EmitDataType', '
|
|
14
|
+
__all__ = ['Attachment', 'AttachmentType', 'CodeExecResult', 'EMContent', 'EmitDataType', 'InputTokenDetails', 'MessageContent', 'LMOutput', 'ModelId', 'ModelProvider', 'Message', 'MessageRole', 'OutputTokenDetails', 'Reasoning', 'ResponseSchema', 'TokenUsage', 'ToolCall', 'ToolResult', 'TruncateSide', 'TruncationConfig', 'Vector']
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from gllm_inference.schema.enums import TruncateSide as TruncateSide
|
|
2
|
+
from pydantic import BaseModel
|
|
3
|
+
|
|
4
|
+
class TruncationConfig(BaseModel):
|
|
5
|
+
"""Configuration for text truncation behavior.
|
|
6
|
+
|
|
7
|
+
Attributes:
|
|
8
|
+
max_length (int): Maximum length of text content. Required.
|
|
9
|
+
truncate_side (TruncateSide | None): Side to truncate from when max_length is exceeded.
|
|
10
|
+
1. TruncateSide.RIGHT: Keep the beginning of the text, truncate from the end (default)
|
|
11
|
+
2. TruncateSide.LEFT: Keep the end of the text, truncate from the beginning
|
|
12
|
+
If None, defaults to TruncateSide.RIGHT
|
|
13
|
+
"""
|
|
14
|
+
max_length: int
|
|
15
|
+
truncate_side: TruncateSide | None
|
gllm_inference/schema/enums.pyi
CHANGED
|
@@ -19,6 +19,7 @@ class ModelProvider(StrEnum):
|
|
|
19
19
|
OPENAI_COMPATIBLE = 'openai-compatible'
|
|
20
20
|
TWELVELABS = 'twelvelabs'
|
|
21
21
|
VOYAGE = 'voyage'
|
|
22
|
+
XAI = 'xai'
|
|
22
23
|
|
|
23
24
|
class ModelId(BaseModel):
|
|
24
25
|
'''Defines a representation of a valid model id.
|
|
@@ -56,7 +57,7 @@ class ModelId(BaseModel):
|
|
|
56
57
|
|
|
57
58
|
# Using Azure OpenAI
|
|
58
59
|
```python
|
|
59
|
-
model_id = ModelId.from_string("azure-openai/https://my-resource.openai.azure.com:my-deployment")
|
|
60
|
+
model_id = ModelId.from_string("azure-openai/https://my-resource.openai.azure.com/openai/v1:my-deployment")
|
|
60
61
|
```
|
|
61
62
|
|
|
62
63
|
# Using OpenAI compatible endpoints (e.g. Groq)
|
|
@@ -88,12 +89,20 @@ class ModelId(BaseModel):
|
|
|
88
89
|
For the list of supported providers, please refer to the following page:
|
|
89
90
|
https://docs.litellm.ai/docs/providers/
|
|
90
91
|
|
|
92
|
+
# Using XAI
|
|
93
|
+
```python
|
|
94
|
+
model_id = ModelId.from_string("xai/grok-4-0709")
|
|
95
|
+
```
|
|
96
|
+
For the list of supported models, please refer to the following page:
|
|
97
|
+
https://docs.x.ai/docs/models
|
|
98
|
+
|
|
91
99
|
Custom model name validation example:
|
|
92
100
|
```python
|
|
93
101
|
validation_map = {
|
|
94
102
|
ModelProvider.ANTHROPIC: {"claude-3-5-sonnet-latest"},
|
|
95
103
|
ModelProvider.GOOGLE: {"gemini-1.5-flash", "gemini-1.5-pro"},
|
|
96
104
|
ModelProvider.OPENAI: {"gpt-4o", "gpt-4o-mini"},
|
|
105
|
+
}
|
|
97
106
|
|
|
98
107
|
model_id = ModelId.from_string("...", validation_map)
|
|
99
108
|
```
|
|
@@ -1,11 +1,75 @@
|
|
|
1
1
|
from pydantic import BaseModel
|
|
2
2
|
|
|
3
|
+
class InputTokenDetails(BaseModel):
|
|
4
|
+
"""Defines the input token details schema.
|
|
5
|
+
|
|
6
|
+
Attributes:
|
|
7
|
+
cached_tokens (int): The number of cached tokens. Defaults to 0.
|
|
8
|
+
uncached_tokens (int): The number of uncached tokens. Defaults to 0.
|
|
9
|
+
"""
|
|
10
|
+
cached_tokens: int
|
|
11
|
+
uncached_tokens: int
|
|
12
|
+
def __add__(self, other: InputTokenDetails) -> InputTokenDetails:
|
|
13
|
+
"""Add two InputTokenDetails objects together.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
other (InputTokenDetails): The other InputTokenDetails object to add.
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
InputTokenDetails: A new InputTokenDetails object with summed values.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
class OutputTokenDetails(BaseModel):
|
|
23
|
+
"""Defines the output token details schema.
|
|
24
|
+
|
|
25
|
+
Attributes:
|
|
26
|
+
reasoning_tokens (int): The number of reasoning tokens. Defaults to 0.
|
|
27
|
+
response_tokens (int): The number of response tokens. Defaults to 0.
|
|
28
|
+
"""
|
|
29
|
+
reasoning_tokens: int
|
|
30
|
+
response_tokens: int
|
|
31
|
+
def __add__(self, other: OutputTokenDetails) -> OutputTokenDetails:
|
|
32
|
+
"""Add two OutputTokenDetails objects together.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
other (OutputTokenDetails): The other OutputTokenDetails object to add.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
OutputTokenDetails: A new OutputTokenDetails object with summed values.
|
|
39
|
+
"""
|
|
40
|
+
|
|
3
41
|
class TokenUsage(BaseModel):
|
|
4
42
|
"""Defines the token usage data structure of a language model.
|
|
5
43
|
|
|
6
44
|
Attributes:
|
|
7
|
-
input_tokens (int): The number of input tokens.
|
|
8
|
-
output_tokens (int): The number of output tokens.
|
|
45
|
+
input_tokens (int): The number of input tokens. Defaults to 0.
|
|
46
|
+
output_tokens (int): The number of output tokens. Defaults to 0.
|
|
47
|
+
input_token_details (InputTokenDetails | None): The details of the input tokens. Defaults to None.
|
|
48
|
+
output_token_details (OutputTokenDetails | None): The details of the output tokens. Defaults to None.
|
|
9
49
|
"""
|
|
10
50
|
input_tokens: int
|
|
11
51
|
output_tokens: int
|
|
52
|
+
input_token_details: InputTokenDetails | None
|
|
53
|
+
output_token_details: OutputTokenDetails | None
|
|
54
|
+
@classmethod
|
|
55
|
+
def from_token_details(cls, input_tokens: int | None = None, output_tokens: int | None = None, cached_tokens: int | None = None, reasoning_tokens: int | None = None) -> TokenUsage:
|
|
56
|
+
"""Creates a TokenUsage from token details.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
input_tokens (int | None): The number of input tokens. Defaults to None.
|
|
60
|
+
output_tokens (int | None): The number of output tokens. Defaults to None.
|
|
61
|
+
cached_tokens (int | None): The number of cached tokens. Defaults to None.
|
|
62
|
+
reasoning_tokens (int | None): The number of reasoning tokens. Defaults to None.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
TokenUsage: The instantiated TokenUsage.
|
|
66
|
+
"""
|
|
67
|
+
def __add__(self, other: TokenUsage) -> TokenUsage:
|
|
68
|
+
"""Add two TokenUsage objects together.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
other (TokenUsage): The other TokenUsage object to add.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
TokenUsage: A new TokenUsage object with summed values.
|
|
75
|
+
"""
|