cmem-plugin-llm 2.1.0__tar.gz → 2.2.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cmem-plugin-llm
3
- Version: 2.1.0
3
+ Version: 2.2.0
4
4
  Summary: Interact with Large Language Models (Execute Instructions, Create Embeddings).
5
5
  License: Apache-2.0
6
6
  License-File: LICENSE
@@ -14,7 +14,8 @@ Classifier: License :: OSI Approved :: Apache Software License
14
14
  Classifier: Programming Language :: Python :: 3
15
15
  Classifier: Programming Language :: Python :: 3.13
16
16
  Classifier: Programming Language :: Python :: 3.14
17
- Requires-Dist: cmem-plugin-base (>=4.15.0,<5.0.0)
17
+ Requires-Dist: cmem-client (>=0.10.0,<0.11.0)
18
+ Requires-Dist: cmem-plugin-base (>=4.16.0,<5.0.0)
18
19
  Requires-Dist: jinja2 (>=3.1.6,<4.0.0)
19
20
  Requires-Dist: openai (>=1.99.9,<2.0.0)
20
21
  Requires-Dist: pydantic (>=2.11.9,<3.0.0)
@@ -4,6 +4,7 @@ import re
4
4
  from enum import Enum
5
5
  from typing import TYPE_CHECKING, Any, ClassVar
6
6
 
7
+ from cmem_client.client import Client
7
8
  from cmem_plugin_base.dataintegration.context import (
8
9
  PluginContext,
9
10
  )
@@ -18,11 +19,19 @@ from jinja2 import Environment, meta
18
19
 
19
20
  if TYPE_CHECKING:
20
21
  from jinja2.nodes import Template
21
- from openai import AuthenticationError, NotFoundError, OpenAI
22
+ from openai import (
23
+ AsyncAzureOpenAI,
24
+ AsyncOpenAI,
25
+ AuthenticationError,
26
+ AzureOpenAI,
27
+ NotFoundError,
28
+ OpenAI,
29
+ )
22
30
 
23
31
  # Regex pattern to match Jinja2 template variables like {{ variable_name }}
24
32
  JINJA_PATTERN = r"{{\s*([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\s*}}"
25
33
  ANTHROPIC_BASE_URL = "https://api.anthropic.com/v1/"
34
+ CMEM_LLM_PROXY_URL = "proxy/llm/openai/v1"
26
35
 
27
36
 
28
37
  class APIType(Enum):
@@ -38,8 +47,19 @@ class SharedParams:
38
47
  base_url: PluginParameter = PluginParameter(
39
48
  name="base_url",
40
49
  label="Base URL",
41
- description="The base URL of the OpenAI compatible API (without endpoint path).",
42
- default_value="https://api.openai.com/v1/",
50
+ description="""The base URL of the OpenAI compatible API (without endpoint path).
51
+ If left empty CMEMs internal LLM proxy is used.""",
52
+ default_value="",
53
+ advanced=True,
54
+ )
55
+ api_key = PluginParameter(
56
+ name="api_key",
57
+ label="API key",
58
+ param_type=PasswordParameterType(),
59
+ description="""An optional API key for authentication. When using CMEMs internal LLM proxy
60
+ this parameter is ignored and `EXPLORE_AI_APIKEY` in `environments/config.env` is used.""",
61
+ default_value="",
62
+ advanced=True,
43
63
  )
44
64
  api_type = PluginParameter(
45
65
  name="api_type",
@@ -53,12 +73,7 @@ Consider using the API version advanced parameter in case you access Azure-hoste
53
73
  """,
54
74
  param_type=EnumParameterType(enum_type=APIType),
55
75
  default_value=APIType.OPENAI,
56
- )
57
- api_key = PluginParameter(
58
- name="api_key",
59
- label="API key",
60
- param_type=PasswordParameterType(),
61
- description="An optional API key for authentication.",
76
+ advanced=True,
62
77
  )
63
78
  api_version = PluginParameter(
64
79
  name="api_version",
@@ -124,7 +139,12 @@ def input_paths_to_list(paths: str) -> list[str]:
124
139
  class OpenAPIModel(StringParameterType):
125
140
  """OpenAPI Model Type"""
126
141
 
127
- autocompletion_depends_on_parameters: ClassVar[list[str]] = ["base_url", "api_key"]
142
+ autocompletion_depends_on_parameters: ClassVar[list[str]] = [
143
+ "base_url",
144
+ "api_key",
145
+ "api_type",
146
+ "api_version",
147
+ ]
128
148
 
129
149
  # auto complete for values
130
150
  allow_only_autocompleted_values: bool = False
@@ -139,12 +159,20 @@ class OpenAPIModel(StringParameterType):
139
159
  ) -> list[Autocompletion]:
140
160
  """Return all results that match ALL provided query terms."""
141
161
  _ = context
142
- url = depend_on_parameter_values[0]
162
+ base_url = depend_on_parameter_values[0]
143
163
  api_key = depend_on_parameter_values[1]
144
164
  api_key = api_key if isinstance(api_key, str) else api_key.decrypt()
145
- result = []
165
+ api_type = depend_on_parameter_values[2]
166
+ api_version = depend_on_parameter_values[3]
146
167
  try:
147
- api = OpenAI(api_key=api_key, base_url=url)
168
+ api = create_openai_client(
169
+ context=context,
170
+ base_url=base_url,
171
+ api_key=api_key,
172
+ timeout=None,
173
+ api_type=api_type,
174
+ api_version=api_version,
175
+ )
148
176
  models = api.models.list()
149
177
  filtered_models = set()
150
178
  if query_terms:
@@ -158,7 +186,7 @@ class OpenAPIModel(StringParameterType):
158
186
  except NotFoundError:
159
187
  result = []
160
188
  except AuthenticationError as error:
161
- if url == ANTHROPIC_BASE_URL:
189
+ if base_url == ANTHROPIC_BASE_URL:
162
190
  result = []
163
191
  else:
164
192
  raise ValueError(
@@ -175,3 +203,54 @@ def parameter_link(parameter: PluginParameter, text: str = "") -> str:
175
203
  advanced_note = " - Advanced Parameter" if parameter.advanced else ""
176
204
  text = f"{parameter.label} {advanced_note}"
177
205
  return f'<a id="parameter_doc_{parameter.name}">{text}</a>'
206
+
207
+
208
+ def resolve_cmem_llm_proxy(context: object) -> tuple[str, str]:
209
+ """Resolve the CMEM LLM proxy as base_url and api_key."""
210
+ cmem_client = Client.from_context(context=context)
211
+ explore_api_url = str(cmem_client.config.url_explore_api).rstrip("/")
212
+ base_url = f"{explore_api_url}/{CMEM_LLM_PROXY_URL.lstrip('/')}"
213
+ api_key = cmem_client.auth.get_access_token()
214
+ return base_url, api_key
215
+
216
+
217
+ def create_openai_client( # noqa: PLR0913
218
+ context: object,
219
+ base_url: str,
220
+ api_key: str,
221
+ timeout: float | None = None,
222
+ api_type: APIType = APIType.OPENAI,
223
+ api_version: str = "",
224
+ ) -> OpenAI | AzureOpenAI:
225
+ """Create an OpenAI/AzureOpenAI client."""
226
+ if api_type == APIType.AZURE_OPENAI:
227
+ return AzureOpenAI(
228
+ api_key=api_key,
229
+ api_version=api_version,
230
+ azure_endpoint=base_url,
231
+ timeout=timeout,
232
+ )
233
+ if not base_url:
234
+ base_url, api_key = resolve_cmem_llm_proxy(context)
235
+ return OpenAI(base_url=base_url, api_key=api_key, timeout=timeout)
236
+
237
+
238
+ def create_async_openai_client( # noqa: PLR0913
239
+ context: object,
240
+ base_url: str,
241
+ api_key: str,
242
+ timeout: float | None = None,
243
+ api_type: APIType = APIType.OPENAI,
244
+ api_version: str = "",
245
+ ) -> AsyncOpenAI | AsyncAzureOpenAI:
246
+ """Create an AsyncOpenAI/AsyncAzureOpenAI client."""
247
+ if api_type == APIType.AZURE_OPENAI:
248
+ return AsyncAzureOpenAI(
249
+ api_key=api_key,
250
+ api_version=api_version,
251
+ azure_endpoint=base_url,
252
+ timeout=timeout,
253
+ )
254
+ if not base_url:
255
+ base_url, api_key = resolve_cmem_llm_proxy(context)
256
+ return AsyncOpenAI(base_url=base_url, api_key=api_key, timeout=timeout)
@@ -21,19 +21,18 @@ from cmem_plugin_base.dataintegration.ports import (
21
21
  FlexibleSchemaPort,
22
22
  UnknownSchemaPort,
23
23
  )
24
- from openai import AzureOpenAI, OpenAI
25
24
 
26
25
  from cmem_plugin_llm.commons import (
27
26
  APIType,
28
27
  OpenAPIModel,
29
28
  SamePathError,
30
29
  SharedParams,
30
+ create_openai_client,
31
31
  input_paths_to_list,
32
32
  )
33
33
 
34
34
  DEFAULT_EMBEDDING_PATH = "_embedding"
35
35
  DEFAULT_EMBEDDING_SOURCE_PATH = "_embedding_source"
36
- MODEL_EXAMPLE = "text-embedding-3-small"
37
36
 
38
37
 
39
38
  @Plugin(
@@ -68,8 +67,8 @@ representations that capture semantic meaning.
68
67
  - Natural language processing pipelines""",
69
68
  parameters=[
70
69
  SharedParams.base_url,
71
- SharedParams.api_type,
72
70
  SharedParams.api_key,
71
+ SharedParams.api_type,
73
72
  SharedParams.api_version,
74
73
  PluginParameter(
75
74
  name="model",
@@ -138,7 +137,6 @@ class CreateEmbeddings(WorkflowPlugin):
138
137
  embedding_paths: list[str]
139
138
  forward_paths: list[str]
140
139
  embedding_report: ExecutionReport
141
- client: OpenAI | AzureOpenAI
142
140
 
143
141
  def __init__( # noqa: PLR0913
144
142
  self,
@@ -146,7 +144,7 @@ class CreateEmbeddings(WorkflowPlugin):
146
144
  api_type: APIType,
147
145
  api_key: Password | str = "",
148
146
  api_version: str = "",
149
- model: str = MODEL_EXAMPLE,
147
+ model: str = "",
150
148
  timout_single_request: int = 10000,
151
149
  entries_processing_buffer: int = 100,
152
150
  embedding_paths: str = "",
@@ -160,18 +158,8 @@ class CreateEmbeddings(WorkflowPlugin):
160
158
  if self.api_key == "":
161
159
  self.api_key = "dummy-key"
162
160
 
163
- # Initialize the appropriate client based on API type
164
- if api_type.value == APIType.AZURE_OPENAI.value:
165
- self.client = AzureOpenAI(
166
- api_key=self.api_key,
167
- api_version=api_version,
168
- azure_endpoint=self.base_url,
169
- timeout=self.timeout_single_request,
170
- )
171
- else: # api_type == "openai"
172
- self.client = OpenAI(
173
- base_url=self.base_url, api_key=self.api_key, timeout=self.timeout_single_request
174
- )
161
+ self.api_type = api_type
162
+ self.api_version = api_version
175
163
  self.model = model
176
164
  self.entries_processing_buffer = entries_processing_buffer
177
165
  self.embedding_output_text = embedding_output_text
@@ -312,7 +300,15 @@ class CreateEmbeddings(WorkflowPlugin):
312
300
  )
313
301
  embeddings_sources.append(embedding_source)
314
302
 
315
- embeddings_response = self.client.embeddings.create(
303
+ client = create_openai_client(
304
+ context=self.execution_context,
305
+ base_url=self.base_url,
306
+ api_key=self.api_key,
307
+ timeout=self.timeout_single_request,
308
+ api_type=self.api_type,
309
+ api_version=self.api_version,
310
+ )
311
+ embeddings_response = client.embeddings.create(
316
312
  input=embeddings_sources,
317
313
  model=self.model,
318
314
  )
@@ -29,13 +29,14 @@ from cmem_plugin_base.dataintegration.ports import (
29
29
  from cmem_plugin_base.dataintegration.types import EnumParameterType
30
30
  from cmem_plugin_base.dataintegration.utils.entity_builder import build_entities_from_data
31
31
  from jinja2 import Template, UndefinedError
32
- from openai import APIError, AsyncAzureOpenAI, AsyncOpenAI, NotGiven
32
+ from openai import APIError, NotGiven
33
33
  from pydantic import BaseModel
34
34
 
35
35
  from cmem_plugin_llm.commons import (
36
36
  APIType,
37
37
  OpenAPIModel,
38
38
  SharedParams,
39
+ create_async_openai_client,
39
40
  extract_variables_from_template,
40
41
  )
41
42
 
@@ -180,7 +181,6 @@ Available model IDs for some public providers can be found here:
180
181
  See [OpenAI Structured Outputs Guide](https://platform.openai.com/docs/guides/structured-outputs)
181
182
  for supported models.
182
183
  """,
183
- default_value="gpt-4o-mini",
184
184
  param_type=OpenAPIModel(),
185
185
  )
186
186
  instruct_prompt_template = PluginParameter(
@@ -307,8 +307,8 @@ allowing the workflow to continue processing other entities.
307
307
  icon=Icon(package=__package__, file_name="execute_instruction.svg"),
308
308
  parameters=[
309
309
  SharedParams.base_url,
310
- SharedParams.api_type,
311
310
  SharedParams.api_key,
311
+ SharedParams.api_type,
312
312
  SharedParams.api_version,
313
313
  *Params().as_list(),
314
314
  ],
@@ -437,7 +437,6 @@ class ExecuteInstruction(WorkflowPlugin):
437
437
  execution_report: ExecutionReport
438
438
  messages_template: str
439
439
  instruct_prompt_template: str
440
- client: AsyncOpenAI | AsyncAzureOpenAI
441
440
  model: str
442
441
  output_format: OutputFormat
443
442
  pydantic_schema: str
@@ -472,19 +471,8 @@ class ExecuteInstruction(WorkflowPlugin):
472
471
  self.api_key = "dummy-key"
473
472
  self.temperature = temperature
474
473
  self.timeout = timeout
475
-
476
- # Initialize the appropriate client based on API type
477
- if api_type.value == APIType.AZURE_OPENAI.value:
478
- self.client = AsyncAzureOpenAI(
479
- api_key=self.api_key,
480
- api_version=api_version,
481
- azure_endpoint=self.base_url,
482
- timeout=self.timeout,
483
- )
484
- else:
485
- self.client = AsyncOpenAI(
486
- base_url=self.base_url, api_key=self.api_key, timeout=self.timeout
487
- )
474
+ self.api_type = api_type
475
+ self.api_version = api_version
488
476
  self.instruction_output_path = instruction_output_path
489
477
  self.messages_template = str(messages_template)
490
478
  self.instruct_prompt_template = str(instruct_prompt_template)
@@ -790,17 +778,25 @@ class ExecuteInstruction(WorkflowPlugin):
790
778
  self, messages: list[dict], entity: Entity
791
779
  ) -> tuple[str | BaseModel | None, Entity]:
792
780
  """Execute LLM request based on output format and return result"""
781
+ client = create_async_openai_client(
782
+ context=self.execution_context,
783
+ base_url=self.base_url,
784
+ api_key=self.api_key,
785
+ timeout=self.timeout,
786
+ api_type=self.api_type,
787
+ api_version=self.api_version,
788
+ )
793
789
  try:
794
790
  result: str | BaseModel | None = ""
795
791
  typed_messages = cast("list[ChatCompletionMessageParam]", messages)
796
792
  match self.output_format.name:
797
793
  case OutputFormat.TEXT.name:
798
- completion = await self.client.chat.completions.create(
794
+ completion = await client.chat.completions.create(
799
795
  model=self.model, messages=typed_messages, temperature=self.temperature
800
796
  )
801
797
  result = completion.choices[0].message.content or ""
802
798
  case OutputFormat.JSON_MODE.name:
803
- completion = await self.client.chat.completions.create(
799
+ completion = await client.chat.completions.create(
804
800
  model=self.model,
805
801
  messages=typed_messages,
806
802
  temperature=self.temperature,
@@ -813,7 +809,7 @@ class ExecuteInstruction(WorkflowPlugin):
813
809
  if self.structured_output_cls is not None
814
810
  else NotGiven
815
811
  )
816
- completion = await self.client.beta.chat.completions.parse(
812
+ completion = await client.beta.chat.completions.parse(
817
813
  model=self.model,
818
814
  messages=typed_messages,
819
815
  temperature=self.temperature,
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "cmem-plugin-llm"
3
- version = "2.1.0"
3
+ version = "2.2.0"
4
4
  license = "Apache-2.0"
5
5
  description = "Interact with Large Language Models (Execute Instructions, Create Embeddings)."
6
6
  authors = ["eccenca GmbH <cmempy-developer@eccenca.com>"]
@@ -18,27 +18,27 @@ python = "^3.13"
18
18
  jinja2 = "^3.1.6"
19
19
  openai = "^1.99.9"
20
20
  pydantic = "^2.11.9"
21
+ cmem-client = "^0.10.0"
21
22
 
22
23
  [tool.poetry.dependencies.cmem-plugin-base]
23
- version = "^4.15.0"
24
+ version = "^4.16.0"
24
25
  allow-prereleases = false
25
26
 
26
27
  [tool.poetry.group.dev.dependencies.cmem-cmemc]
27
28
  version = "^25.3.0"
28
29
 
29
30
  [tool.poetry.group.dev.dependencies]
30
- deptry = "^0.23.1"
31
- genbadge = {extras = ["coverage"], version = "^1.1.2"}
32
- mypy = "^1.18.2"
33
- pip = "^25.2"
34
- pytest = "^8.4.2"
31
+ deptry = "^0.24.0"
32
+ genbadge = {extras = ["coverage"], version = "^1.1.3"}
33
+ mypy = "^1.19.1"
34
+ pip = "^26"
35
+ pytest = "^9.0.2"
35
36
  pytest-cov = "^7.0.0"
36
37
  pytest-dotenv = "^0.5.2"
37
- pytest-html = "^4.1.1"
38
+ pytest-html = "^4.2.0"
38
39
  pytest-memray = { version = "^1.8.0", markers = "platform_system != 'Windows'" }
39
- ruff = "^0.13.3"
40
- safety = "^1.10.3"
41
- types-requests = "^2.32.0.20240712"
40
+ ruff = "^0.15.0"
41
+ trivy-py-ecc = "^0.68.2.1"
42
42
 
43
43
  [build-system]
44
44
  requires = ["poetry-core>=1.0.0", "poetry-dynamic-versioning"]
File without changes