gllm-inference-binary 0.5.9__py3-none-any.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 (94) 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 +122 -0
  4. gllm_inference/builder/build_lm_invoker.pyi +150 -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 +9 -0
  13. gllm_inference/em_invoker/azure_openai_em_invoker.pyi +86 -0
  14. gllm_inference/em_invoker/em_invoker.pyi +83 -0
  15. gllm_inference/em_invoker/google_em_invoker.pyi +124 -0
  16. gllm_inference/em_invoker/langchain/__init__.pyi +3 -0
  17. gllm_inference/em_invoker/langchain/em_invoker_embeddings.pyi +62 -0
  18. gllm_inference/em_invoker/langchain_em_invoker.pyi +41 -0
  19. gllm_inference/em_invoker/openai_compatible_em_invoker.pyi +92 -0
  20. gllm_inference/em_invoker/openai_em_invoker.pyi +86 -0
  21. gllm_inference/em_invoker/schema/__init__.pyi +0 -0
  22. gllm_inference/em_invoker/schema/google.pyi +7 -0
  23. gllm_inference/em_invoker/schema/langchain.pyi +4 -0
  24. gllm_inference/em_invoker/schema/openai.pyi +7 -0
  25. gllm_inference/em_invoker/schema/openai_compatible.pyi +7 -0
  26. gllm_inference/em_invoker/schema/twelvelabs.pyi +17 -0
  27. gllm_inference/em_invoker/schema/voyage.pyi +15 -0
  28. gllm_inference/em_invoker/twelevelabs_em_invoker.pyi +99 -0
  29. gllm_inference/em_invoker/voyage_em_invoker.pyi +101 -0
  30. gllm_inference/exceptions/__init__.pyi +4 -0
  31. gllm_inference/exceptions/error_parser.pyi +48 -0
  32. gllm_inference/exceptions/exceptions.pyi +120 -0
  33. gllm_inference/lm_invoker/__init__.pyi +11 -0
  34. gllm_inference/lm_invoker/anthropic_lm_invoker.pyi +275 -0
  35. gllm_inference/lm_invoker/azure_openai_lm_invoker.pyi +253 -0
  36. gllm_inference/lm_invoker/bedrock_lm_invoker.pyi +232 -0
  37. gllm_inference/lm_invoker/datasaur_lm_invoker.pyi +166 -0
  38. gllm_inference/lm_invoker/google_lm_invoker.pyi +310 -0
  39. gllm_inference/lm_invoker/langchain_lm_invoker.pyi +258 -0
  40. gllm_inference/lm_invoker/litellm_lm_invoker.pyi +248 -0
  41. gllm_inference/lm_invoker/lm_invoker.pyi +151 -0
  42. gllm_inference/lm_invoker/openai_compatible_lm_invoker.pyi +265 -0
  43. gllm_inference/lm_invoker/openai_lm_invoker.pyi +361 -0
  44. gllm_inference/lm_invoker/schema/__init__.pyi +0 -0
  45. gllm_inference/lm_invoker/schema/anthropic.pyi +50 -0
  46. gllm_inference/lm_invoker/schema/bedrock.pyi +48 -0
  47. gllm_inference/lm_invoker/schema/datasaur.pyi +12 -0
  48. gllm_inference/lm_invoker/schema/google.pyi +24 -0
  49. gllm_inference/lm_invoker/schema/langchain.pyi +22 -0
  50. gllm_inference/lm_invoker/schema/openai.pyi +90 -0
  51. gllm_inference/lm_invoker/schema/openai_compatible.pyi +56 -0
  52. gllm_inference/model/__init__.pyi +9 -0
  53. gllm_inference/model/em/__init__.pyi +0 -0
  54. gllm_inference/model/em/google_em.pyi +16 -0
  55. gllm_inference/model/em/openai_em.pyi +15 -0
  56. gllm_inference/model/em/twelvelabs_em.pyi +13 -0
  57. gllm_inference/model/em/voyage_em.pyi +20 -0
  58. gllm_inference/model/lm/__init__.pyi +0 -0
  59. gllm_inference/model/lm/anthropic_lm.pyi +20 -0
  60. gllm_inference/model/lm/google_lm.pyi +17 -0
  61. gllm_inference/model/lm/openai_lm.pyi +27 -0
  62. gllm_inference/output_parser/__init__.pyi +3 -0
  63. gllm_inference/output_parser/json_output_parser.pyi +60 -0
  64. gllm_inference/output_parser/output_parser.pyi +27 -0
  65. gllm_inference/prompt_builder/__init__.pyi +3 -0
  66. gllm_inference/prompt_builder/prompt_builder.pyi +56 -0
  67. gllm_inference/prompt_formatter/__init__.pyi +7 -0
  68. gllm_inference/prompt_formatter/agnostic_prompt_formatter.pyi +49 -0
  69. gllm_inference/prompt_formatter/huggingface_prompt_formatter.pyi +55 -0
  70. gllm_inference/prompt_formatter/llama_prompt_formatter.pyi +59 -0
  71. gllm_inference/prompt_formatter/mistral_prompt_formatter.pyi +53 -0
  72. gllm_inference/prompt_formatter/openai_prompt_formatter.pyi +35 -0
  73. gllm_inference/prompt_formatter/prompt_formatter.pyi +30 -0
  74. gllm_inference/request_processor/__init__.pyi +4 -0
  75. gllm_inference/request_processor/lm_request_processor.pyi +92 -0
  76. gllm_inference/request_processor/uses_lm_mixin.pyi +50 -0
  77. gllm_inference/schema/__init__.pyi +13 -0
  78. gllm_inference/schema/attachment.pyi +88 -0
  79. gllm_inference/schema/code_exec_result.pyi +14 -0
  80. gllm_inference/schema/enums.pyi +24 -0
  81. gllm_inference/schema/lm_output.pyi +36 -0
  82. gllm_inference/schema/message.pyi +52 -0
  83. gllm_inference/schema/model_id.pyi +138 -0
  84. gllm_inference/schema/reasoning.pyi +15 -0
  85. gllm_inference/schema/token_usage.pyi +11 -0
  86. gllm_inference/schema/tool_call.pyi +14 -0
  87. gllm_inference/schema/tool_result.pyi +11 -0
  88. gllm_inference/schema/type_alias.pyi +15 -0
  89. gllm_inference/utils/__init__.pyi +4 -0
  90. gllm_inference/utils/langchain.pyi +30 -0
  91. gllm_inference/utils/validation.pyi +12 -0
  92. gllm_inference_binary-0.5.9.dist-info/METADATA +108 -0
  93. gllm_inference_binary-0.5.9.dist-info/RECORD +94 -0
  94. gllm_inference_binary-0.5.9.dist-info/WHEEL +4 -0
@@ -0,0 +1,310 @@
1
+ from _typeshed import Incomplete
2
+ from gllm_core.event import EventEmitter as EventEmitter
3
+ from gllm_core.schema.tool import Tool
4
+ from gllm_core.utils.retry import RetryConfig as RetryConfig
5
+ from gllm_inference.constants import GOOGLE_SCOPES as GOOGLE_SCOPES, SECONDS_TO_MILLISECONDS as SECONDS_TO_MILLISECONDS
6
+ from gllm_inference.lm_invoker.lm_invoker import BaseLMInvoker as BaseLMInvoker
7
+ from gllm_inference.lm_invoker.schema.google import InputType as InputType, Key as Key
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 langchain_core.tools import Tool as LangChainTool
10
+ from typing import Any
11
+
12
+ SUPPORTED_ATTACHMENTS: Incomplete
13
+ DEFAULT_THINKING_BUDGET: int
14
+ REQUIRE_THINKING_MODEL_PREFIX: Incomplete
15
+ YOUTUBE_URL_PATTERN: Incomplete
16
+
17
+ class GoogleLMInvoker(BaseLMInvoker):
18
+ '''A language model invoker to interact with Google 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 Google client instance init parameters.
25
+ default_hyperparameters (dict[str, Any]): Default hyperparameters for invoking the model.
26
+ tools (list[Any]): 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
+ thinking (bool): Whether to enable thinking. Only allowed for thinking models.
32
+ thinking_budget (int): The tokens allowed for thinking process. Only allowed for thinking models.
33
+ If set to -1, the model will control the budget automatically.
34
+
35
+ Basic usage:
36
+ The `GoogleLMInvoker` can be used as follows:
37
+ ```python
38
+ lm_invoker = GoogleLMInvoker(model_name="gemini-2.5-flash")
39
+ result = await lm_invoker.invoke("Hi there!")
40
+ ```
41
+
42
+ Authentication:
43
+ The `GoogleLMInvoker` can use either Google Gen AI or Google Vertex AI.
44
+
45
+ Google Gen AI is recommended for quick prototyping and development.
46
+ It requires a Gemini API key for authentication.
47
+
48
+ Usage example:
49
+ ```python
50
+ lm_invoker = GoogleLMInvoker(
51
+ model_name="gemini-2.5-flash",
52
+ api_key="your_api_key"
53
+ )
54
+ ```
55
+
56
+ Google Vertex AI is recommended to build production-ready applications.
57
+ It requires a service account JSON file for authentication.
58
+
59
+ Usage example:
60
+ ```python
61
+ lm_invoker = GoogleLMInvoker(
62
+ model_name="gemini-2.5-flash",
63
+ credentials_path="path/to/service_account.json"
64
+ )
65
+ ```
66
+
67
+ If neither `api_key` nor `credentials_path` is provided, Google Gen AI will be used by default.
68
+ The `GOOGLE_API_KEY` environment variable will be used for authentication.
69
+
70
+ Input types:
71
+ The `GoogleLMInvoker` supports the following input types: text, audio, document, image, and video.
72
+ Non-text inputs can be passed as an `Attachment` object with either the `user` or `assistant` role.
73
+
74
+ Usage example:
75
+ ```python
76
+ text = "What animal is in this image?"
77
+ image = Attachment.from_path("path/to/local/image.png")
78
+ result = await lm_invoker.invoke([text, image])
79
+ ```
80
+
81
+ Tool calling:
82
+ Tool calling is a feature that allows the language model to call tools to perform tasks.
83
+ Tools can be passed to the via the `tools` parameter as a list of `Tool` objects.
84
+ When tools are provided and the model decides to call a tool, the tool calls are stored in the
85
+ `tool_calls` attribute in the output.
86
+
87
+ Usage example:
88
+ ```python
89
+ lm_invoker = GoogleLMInvoker(..., tools=[tool_1, tool_2])
90
+ ```
91
+
92
+ Output example:
93
+ ```python
94
+ LMOutput(
95
+ response="Let me call the tools...",
96
+ tool_calls=[
97
+ ToolCall(id="123", name="tool_1", args={"key": "value"}),
98
+ ToolCall(id="456", name="tool_2", args={"key": "value"}),
99
+ ]
100
+ )
101
+ ```
102
+
103
+ Structured output:
104
+ Structured output is a feature that allows the language model to output a structured response.
105
+ This feature can be enabled by providing a schema to the `response_schema` parameter.
106
+
107
+ The schema must be either a JSON schema dictionary or a Pydantic BaseModel class.
108
+ If JSON schema is used, it must be compatible with Pydantic\'s JSON schema, especially for complex schemas.
109
+ For this reason, it is recommended to create the JSON schema using Pydantic\'s `model_json_schema` method.
110
+
111
+ Structured output is not compatible with tool calling. The language model also doesn\'t need to stream
112
+ anything when structured output is enabled. Thus, standard invocation will be performed regardless of
113
+ whether the `event_emitter` parameter is provided or not.
114
+
115
+ When enabled, the structured output is stored in the `structured_output` attribute in the output.
116
+ 1. If the schema is a JSON schema dictionary, the structured output is a dictionary.
117
+ 2. If the schema is a Pydantic BaseModel class, the structured output is a Pydantic model.
118
+
119
+ # Example 1: Using a JSON schema dictionary
120
+ Usage example:
121
+ ```python
122
+ schema = {
123
+ "title": "Animal",
124
+ "description": "A description of an animal.",
125
+ "properties": {
126
+ "color": {"title": "Color", "type": "string"},
127
+ "name": {"title": "Name", "type": "string"},
128
+ },
129
+ "required": ["name", "color"],
130
+ "type": "object",
131
+ }
132
+ lm_invoker = GoogleLMInvoker(..., response_schema=schema)
133
+ ```
134
+ Output example:
135
+ ```python
136
+ LMOutput(structured_output={"name": "Golden retriever", "color": "Golden"})
137
+ ```
138
+
139
+ # Example 2: Using a Pydantic BaseModel class
140
+ Usage example:
141
+ ```python
142
+ class Animal(BaseModel):
143
+ name: str
144
+ color: str
145
+
146
+ lm_invoker = GoogleLMInvoker(..., response_schema=Animal)
147
+ ```
148
+ Output example:
149
+ ```python
150
+ LMOutput(structured_output=Animal(name="Golden retriever", color="Golden"))
151
+ ```
152
+
153
+ Analytics tracking:
154
+ Analytics tracking is a feature that allows the module to output additional information about the invocation.
155
+ This feature can be enabled by setting the `output_analytics` parameter to `True`.
156
+ When enabled, the following attributes will be stored in the output:
157
+ 1. `token_usage`: The token usage.
158
+ 2. `duration`: The duration in seconds.
159
+ 3. `finish_details`: The details about how the generation finished.
160
+
161
+ Output example:
162
+ ```python
163
+ LMOutput(
164
+ response="Golden retriever is a good dog breed.",
165
+ token_usage=TokenUsage(input_tokens=100, output_tokens=50),
166
+ duration=0.729,
167
+ finish_details={"finish_reason": "STOP", "finish_message": None},
168
+ )
169
+ ```
170
+
171
+ Retry and timeout:
172
+ The `GoogleLMInvoker` supports retry and timeout configuration.
173
+ By default, the max retries is set to 0 and the timeout is set to 30.0 seconds.
174
+ They can be customized by providing a custom `RetryConfig` object to the `retry_config` parameter.
175
+
176
+ Retry config examples:
177
+ ```python
178
+ retry_config = RetryConfig(max_retries=0, timeout=0.0) # No retry, no timeout
179
+ retry_config = RetryConfig(max_retries=0, timeout=10.0) # No retry, 10.0 seconds timeout
180
+ retry_config = RetryConfig(max_retries=5, timeout=0.0) # 5 max retries, no timeout
181
+ retry_config = RetryConfig(max_retries=5, timeout=10.0) # 5 max retries, 10.0 seconds timeout
182
+ ```
183
+
184
+ Usage example:
185
+ ```python
186
+ lm_invoker = GoogleLMInvoker(..., retry_config=retry_config)
187
+ ```
188
+
189
+ Thinking:
190
+ Thinking is a feature that allows the language model to have enhanced reasoning capabilities for complex tasks,
191
+ while also providing transparency into its step-by-step thought process before it delivers its final answer.
192
+ It can be enabled by setting the `thinking` parameter to `True`.
193
+
194
+ Thinking is only available for certain models, starting from Gemini 2.5 series, and is required for
195
+ Gemini 2.5 Pro models. Therefore, `thinking` defaults to `True` for Gemini 2.5 Pro models and `False`
196
+ for other models. Setting `thinking` to `False` for Gemini 2.5 Pro models will raise a `ValueError`.
197
+ When enabled, the reasoning is stored in the `reasoning` attribute in the output.
198
+
199
+ Usage example:
200
+ ```python
201
+ lm_invoker = GoogleLMInvoker(..., thinking=True, thinking_budget=1024)
202
+ ```
203
+
204
+ Output example:
205
+ ```python
206
+ LMOutput(
207
+ response="Golden retriever is a good dog breed.",
208
+ reasoning=[Reasoning(reasoning="Let me think about it...")],
209
+ )
210
+ ```
211
+
212
+ When streaming is enabled, the thinking token will be streamed with the `EventType.DATA` event type.
213
+
214
+ Streaming output example:
215
+ ```python
216
+ {"type": "data", "value": \'{"data_type": "thinking_start", "data_value": ""}\', ...}
217
+ {"type": "data", "value": \'{"data_type": "thinking", "data_value": "Let me think "}\', ...}
218
+ {"type": "data", "value": \'{"data_type": "thinking", "data_value": "about it..."}\', ...}
219
+ {"type": "data", "value": \'{"data_type": "thinking_end", "data_value": ""}\', ...}
220
+ {"type": "response", "value": "Golden retriever ", ...}
221
+ {"type": "response", "value": "is a good dog breed.", ...}
222
+ ```
223
+
224
+ When thinking is enabled, the amount of tokens allocated for the thinking process can be set via the
225
+ `thinking_budget` parameter. The `thinking_budget`:
226
+ 1. Defaults to -1, in which case the model will control the budget automatically.
227
+ 2. Must be greater than the model\'s minimum thinking budget.
228
+ For more details, please refer to https://ai.google.dev/gemini-api/docs/thinking
229
+
230
+ Output types:
231
+ The output of the `GoogleLMInvoker` can either be:
232
+ 1. `str`: The text response if no additional output is needed.
233
+ 2. `LMOutput`: A Pydantic model with the following attributes if any additional output is needed:
234
+ 2.1. response (str): The text response.
235
+ 2.2. tool_calls (list[ToolCall]): The tool calls, if the `tools` parameter is defined and the language
236
+ model decides to invoke tools. Defaults to an empty list.
237
+ 2.3. structured_output (dict[str, Any] | BaseModel | None): The structured output, if the `response_schema`
238
+ parameter is defined. Defaults to None.
239
+ 2.4. token_usage (TokenUsage | None): The token usage analytics, if the `output_analytics` parameter is
240
+ set to `True`. Defaults to None.
241
+ 2.5. duration (float | None): The duration of the invocation in seconds, if the `output_analytics`
242
+ parameter is set to `True`. Defaults to None.
243
+ 2.6. finish_details (dict[str, Any] | None): The details about how the generation finished, if the
244
+ `output_analytics` parameter is set to `True`. Defaults to None.
245
+ 2.7. reasoning (list[Reasoning]): The reasoning objects, if the `thinking` parameter is set to `True`.
246
+ Defaults to an empty list.
247
+ 2.8. citations (list[Chunk]): The citations. Currently not supported. Defaults to an empty list.
248
+ 2.9. code_exec_results (list[CodeExecResult]): The code execution results. Currently not supported.
249
+ Defaults to an empty list.
250
+ '''
251
+ client_params: Incomplete
252
+ thinking: Incomplete
253
+ thinking_budget: Incomplete
254
+ def __init__(self, model_name: str, api_key: str | None = None, credentials_path: str | None = None, project_id: str | None = None, location: str = 'us-central1', 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, thinking: bool | None = None, thinking_budget: int = ...) -> None:
255
+ '''Initializes a new instance of the GoogleLMInvoker class.
256
+
257
+ Args:
258
+ model_name (str): The name of the model to use.
259
+ api_key (str | None, optional): Required for Google Gen AI authentication. Cannot be used together
260
+ with `credentials_path`. Defaults to None.
261
+ credentials_path (str | None, optional): Required for Google Vertex AI authentication. Path to the service
262
+ account credentials JSON file. Cannot be used together with `api_key`. Defaults to None.
263
+ project_id (str | None, optional): The Google Cloud project ID for Vertex AI. Only used when authenticating
264
+ with `credentials_path`. Defaults to None, in which case it will be loaded from the credentials file.
265
+ location (str, optional): The location of the Google Cloud project for Vertex AI. Only used when
266
+ authenticating with `credentials_path`. Defaults to "us-central1".
267
+ model_kwargs (dict[str, Any] | None, optional): Additional keyword arguments for the Google Vertex AI
268
+ client.
269
+ default_hyperparameters (dict[str, Any] | None, optional): Default hyperparameters for invoking the model.
270
+ Defaults to None.
271
+ tools (list[Tool | LangChainTool] | None, optional): Tools provided to the model to enable tool calling.
272
+ Defaults to None.
273
+ response_schema (ResponseSchema | None, optional): The schema of the response. If provided, the model will
274
+ output a structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema
275
+ dictionary. Defaults to None.
276
+ output_analytics (bool, optional): Whether to output the invocation analytics. Defaults to False.
277
+ retry_config (RetryConfig | None, optional): The retry configuration for the language model.
278
+ Defaults to None, in which case a default config with no retry and 30.0 seconds timeout will be used.
279
+ thinking (bool | None, optional): Whether to enable thinking. Only allowed for thinking models.
280
+ Defaults to True for Gemini 2.5 Pro models and False for other models.
281
+ thinking_budget (int, optional): The tokens allowed for thinking process. Only allowed for thinking models.
282
+ Defaults to -1, in which case the model will control the budget automatically.
283
+
284
+ Note:
285
+ If neither `api_key` nor `credentials_path` is provided, Google Gen AI will be used by default.
286
+ The `GOOGLE_API_KEY` environment variable will be used for authentication.
287
+ '''
288
+ def set_tools(self, tools: list[Tool | LangChainTool]) -> None:
289
+ """Sets the tools for the Google language model.
290
+
291
+ This method sets the tools for the Google language model. Any existing tools will be replaced.
292
+
293
+ Args:
294
+ tools (list[Tool | LangChainTool]): The list of tools to be used.
295
+
296
+ Raises:
297
+ ValueError: If `response_schema` exists.
298
+ """
299
+ def set_response_schema(self, response_schema: ResponseSchema | None) -> None:
300
+ """Sets the response schema for the Google language model.
301
+
302
+ This method sets the response schema for the Google language model. Any existing response schema will be
303
+ replaced.
304
+
305
+ Args:
306
+ response_schema (ResponseSchema | None): The response schema to be used.
307
+
308
+ Raises:
309
+ ValueError: If `tools` exists.
310
+ """
@@ -0,0 +1,258 @@
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
5
+ from gllm_inference.constants import INVOKER_DEFAULT_TIMEOUT as INVOKER_DEFAULT_TIMEOUT, 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.langchain import InputType as InputType, Key as Key
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, ResponseSchema as ResponseSchema, TokenUsage as TokenUsage, ToolCall as ToolCall, ToolResult as ToolResult
9
+ from gllm_inference.utils import load_langchain_model as load_langchain_model, parse_model_data as parse_model_data
10
+ from langchain_core.language_models import BaseChatModel as BaseChatModel
11
+ from langchain_core.messages import BaseMessage as BaseMessage
12
+ from langchain_core.tools import Tool as LangChainTool
13
+ from typing import Any
14
+
15
+ SUPPORTED_ATTACHMENTS: Incomplete
16
+ MESSAGE_CLASS_MAP: Incomplete
17
+
18
+ class LangChainLMInvoker(BaseLMInvoker):
19
+ '''A language model invoker to interact with LangChain\'s BaseChatModel.
20
+
21
+ Attributes:
22
+ model_id (str): The model ID of the language model.
23
+ model_provider (str): The provider of the language model.
24
+ model_name (str): The name of the language model.
25
+ model (BaseChatModel): The LangChain\'s BaseChatModel instance.
26
+ default_hyperparameters (dict[str, Any]): Default hyperparameters for invoking the model.
27
+ tools (list[Any]): The list of tools provided to the model to enable tool calling.
28
+ response_schema (ResponseSchema | None): The schema of the response. If provided, the model will output a
29
+ structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema dictionary.
30
+ output_analytics (bool): Whether to output the invocation analytics.
31
+ retry_config (RetryConfig | None): The retry configuration for the language model.
32
+
33
+ Basic usage:
34
+ The `LangChainLMInvoker` can be used as follows:
35
+ ```python
36
+ lm_invoker = LangChainLMInvoker(
37
+ model_class_path="langchain_openai.ChatOpenAI",
38
+ model_name="gpt-4.1-nano",
39
+ )
40
+ result = await lm_invoker.invoke("Hi there!")
41
+ ```
42
+
43
+ Initialization:
44
+ The `LangChainLMInvoker` can be initialized by either passing:
45
+
46
+ 1. A LangChain\'s BaseChatModel instance:
47
+ Usage example:
48
+ ```python
49
+ from langchain_openai import ChatOpenAI
50
+
51
+ model = ChatOpenAI(model="gpt-4.1-nano", api_key="your_api_key")
52
+ lm_invoker = LangChainLMInvoker(model=model)
53
+ ```
54
+
55
+ 2. A model path in the format of "<package>.<class>":
56
+ Usage example:
57
+ ```python
58
+ lm_invoker = LangChainLMInvoker(
59
+ model_class_path="langchain_openai.ChatOpenAI",
60
+ model_name="gpt-4.1-nano",
61
+ model_kwargs={"api_key": "your_api_key"}
62
+ )
63
+ ```
64
+ For the list of supported providers, please refer to the following table:
65
+ https://python.langchain.com/docs/integrations/chat/#featured-providers
66
+
67
+ Input types:
68
+ The `LangChainLMInvoker` supports the following input types: text and image.
69
+ Non-text inputs can be passed as an `Attachment` object and with specific roles,
70
+ depending on the language model\'s capabilities.
71
+
72
+ Usage example:
73
+ ```python
74
+ text = "What animal is in this image?"
75
+ image = Attachment.from_path("path/to/local/image.png")
76
+ result = await lm_invoker.invoke([text, image])
77
+ ```
78
+
79
+ Tool calling:
80
+ Tool calling is a feature that allows the language model to call tools to perform tasks.
81
+ Tools can be passed to the via the `tools` parameter as a list of `Tool` objects.
82
+ When tools are provided and the model decides to call a tool, the tool calls are stored in the
83
+ `tool_calls` attribute in the output.
84
+
85
+ Usage example:
86
+ ```python
87
+ lm_invoker = LangChainLMInvoker(..., tools=[tool_1, tool_2])
88
+ ```
89
+
90
+ Output example:
91
+ ```python
92
+ LMOutput(
93
+ response="Let me call the tools...",
94
+ tool_calls=[
95
+ ToolCall(id="123", name="tool_1", args={"key": "value"}),
96
+ ToolCall(id="456", name="tool_2", args={"key": "value"}),
97
+ ]
98
+ )
99
+ ```
100
+
101
+ Structured output:
102
+ Structured output is a feature that allows the language model to output a structured response.
103
+ This feature can be enabled by providing a schema to the `response_schema` parameter.
104
+
105
+ The schema must be either a JSON schema dictionary or a Pydantic BaseModel class.
106
+ If JSON schema is used, it must be compatible with Pydantic\'s JSON schema, especially for complex schemas.
107
+ For this reason, it is recommended to create the JSON schema using Pydantic\'s `model_json_schema` method.
108
+
109
+ Structured output is not compatible with tool calling. The language model also doesn\'t need to stream
110
+ anything when structured output is enabled. Thus, standard invocation will be performed regardless of
111
+ whether the `event_emitter` parameter is provided or not.
112
+
113
+ When enabled, the structured output is stored in the `structured_output` attribute in the output.
114
+ 1. If the schema is a JSON schema dictionary, the structured output is a dictionary.
115
+ 2. If the schema is a Pydantic BaseModel class, the structured output is a Pydantic model.
116
+
117
+ # Example 1: Using a JSON schema dictionary
118
+ Usage example:
119
+ ```python
120
+ schema = {
121
+ "title": "Animal",
122
+ "description": "A description of an animal.",
123
+ "properties": {
124
+ "color": {"title": "Color", "type": "string"},
125
+ "name": {"title": "Name", "type": "string"},
126
+ },
127
+ "required": ["name", "color"],
128
+ "type": "object",
129
+ }
130
+ lm_invoker = LangChainLMInvoker(..., response_schema=schema)
131
+ ```
132
+ Output example:
133
+ ```python
134
+ LMOutput(structured_output={"name": "Golden retriever", "color": "Golden"})
135
+ ```
136
+
137
+ # Example 2: Using a Pydantic BaseModel class
138
+ Usage example:
139
+ ```python
140
+ class Animal(BaseModel):
141
+ name: str
142
+ color: str
143
+
144
+ lm_invoker = LangChainLMInvoker(..., response_schema=Animal)
145
+ ```
146
+ Output example:
147
+ ```python
148
+ LMOutput(structured_output=Animal(name="Golden retriever", color="Golden"))
149
+ ```
150
+
151
+ Analytics tracking:
152
+ Analytics tracking is a feature that allows the module to output additional information about the invocation.
153
+ This feature can be enabled by setting the `output_analytics` parameter to `True`.
154
+ When enabled, the following attributes will be stored in the output:
155
+ 1. `token_usage`: The token usage.
156
+ 2. `duration`: The duration in seconds.
157
+ 3. `finish_details`: The details about how the generation finished.
158
+
159
+ Output example:
160
+ ```python
161
+ LMOutput(
162
+ response="Golden retriever is a good dog breed.",
163
+ token_usage=TokenUsage(input_tokens=100, output_tokens=50),
164
+ duration=0.729,
165
+ finish_details={"finish_reason": "stop"},
166
+ )
167
+ ```
168
+
169
+ Retry and timeout:
170
+ The `LangChainLMInvoker` supports retry and timeout configuration.
171
+ By default, the max retries is set to 0 and the timeout is set to 30.0 seconds.
172
+ They can be customized by providing a custom `RetryConfig` object to the `retry_config` parameter.
173
+
174
+ Retry config examples:
175
+ ```python
176
+ retry_config = RetryConfig(max_retries=0, timeout=0.0) # No retry, no timeout
177
+ retry_config = RetryConfig(max_retries=0, timeout=10.0) # No retry, 10.0 seconds timeout
178
+ retry_config = RetryConfig(max_retries=5, timeout=0.0) # 5 max retries, no timeout
179
+ retry_config = RetryConfig(max_retries=5, timeout=10.0) # 5 max retries, 10.0 seconds timeout
180
+ ```
181
+
182
+ Usage example:
183
+ ```python
184
+ lm_invoker = LangChainLMInvoker(..., retry_config=retry_config)
185
+ ```
186
+
187
+ Output types:
188
+ The output of the `LangChainLMInvoker` can either be:
189
+ 1. `str`: The text response if no additional output is needed.
190
+ 2. `LMOutput`: A Pydantic model with the following attributes if any additional output is needed:
191
+ 2.1. response (str): The text response.
192
+ 2.2. tool_calls (list[ToolCall]): The tool calls, if the `tools` parameter is defined and the language
193
+ model decides to invoke tools. Defaults to an empty list.
194
+ 2.3. structured_output (dict[str, Any] | BaseModel | None): The structured output, if the `response_schema`
195
+ parameter is defined. Defaults to None.
196
+ 2.4. token_usage (TokenUsage | None): The token usage analytics, if the `output_analytics` parameter is
197
+ set to `True`. Defaults to None.
198
+ 2.5. duration (float | None): The duration of the invocation in seconds, if the `output_analytics`
199
+ parameter is set to `True`. Defaults to None.
200
+ 2.6. finish_details (dict[str, Any] | None): The details about how the generation finished, if the
201
+ `output_analytics` parameter is set to `True`. Defaults to None.
202
+ 2.7. reasoning (list[Reasoning]): The reasoning objects. Currently not supported. Defaults to an empty list.
203
+ 2.8. citations (list[Chunk]): The citations. Currently not supported. Defaults to an empty list.
204
+ 2.9. code_exec_results (list[CodeExecResult]): The code execution results. Currently not supported.
205
+ Defaults to an empty list.
206
+ '''
207
+ model: Incomplete
208
+ def __init__(self, model: BaseChatModel | None = None, model_class_path: str | None = None, model_name: 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) -> None:
209
+ '''Initializes a new instance of the LangChainLMInvoker class.
210
+
211
+ Args:
212
+ model (BaseChatModel | None, optional): The LangChain\'s BaseChatModel instance. If provided, will take
213
+ precedence over the `model_class_path` parameter. Defaults to None.
214
+ model_class_path (str | None, optional): The LangChain\'s BaseChatModel class path. Must be formatted as
215
+ "<package>.<class>" (e.g. "langchain_openai.ChatOpenAI"). Ignored if `model` is provided.
216
+ Defaults to None.
217
+ model_name (str | None, optional): The model name. Only used if `model_class_path` is provided.
218
+ Defaults to None.
219
+ model_kwargs (dict[str, Any] | None, optional): The additional keyword arguments. Only used if
220
+ `model_class_path` is provided. Defaults to None.
221
+ default_hyperparameters (dict[str, Any] | None, optional): Default hyperparameters for invoking the model.
222
+ Defaults to None.
223
+ tools (list[Tool | LangChainTool] | None, optional): Tools provided to the model to enable tool calling.
224
+ Defaults to None.
225
+ response_schema (ResponseSchema | None, optional): The schema of the response. If provided, the model will
226
+ output a structured response as defined by the schema. Supports both Pydantic BaseModel and JSON schema
227
+ dictionary. Defaults to None.
228
+ output_analytics (bool, optional): Whether to output the invocation analytics. Defaults to False.
229
+ retry_config (RetryConfig | None, optional): The retry configuration for the language model.
230
+ Defaults to None, in which case a default config with no retry and 30.0 seconds timeout will be used.
231
+
232
+ Raises:
233
+ ValueError: If `response_schema` is provided, but `tools` are also provided.
234
+ '''
235
+ tools: Incomplete
236
+ def set_tools(self, tools: list[Tool | LangChainTool]) -> None:
237
+ """Sets the tools for LangChain's BaseChatModel.
238
+
239
+ This method sets the tools for LangChain's BaseChatModel. Any existing tools will be replaced.
240
+
241
+ Args:
242
+ tools (list[Tool]): The list of tools to be used.
243
+
244
+ Raises:
245
+ ValueError: If `response_schema` exists.
246
+ """
247
+ def set_response_schema(self, response_schema: ResponseSchema | None) -> None:
248
+ """Sets the response schema for the LangChain's BaseChatModel.
249
+
250
+ This method sets the response schema for the LangChain's BaseChatModel. Any existing response schema will be
251
+ replaced.
252
+
253
+ Args:
254
+ response_schema (ResponseSchema | None): The response schema to be used.
255
+
256
+ Raises:
257
+ ValueError: If `tools` exists.
258
+ """