lionagi 0.9.5__py3-none-any.whl → 0.9.6__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.
@@ -5,7 +5,13 @@
5
5
  import inspect
6
6
  from typing import Any, Literal
7
7
 
8
- from .extract_docstring import extract_docstring
8
+ from pydantic import Field, field_validator
9
+
10
+ from lionagi.libs.schema.extract_docstring import extract_docstring
11
+ from lionagi.libs.validate.common_field_validators import (
12
+ validate_model_to_type,
13
+ )
14
+ from lionagi.operatives.models.schema_model import SchemaModel
9
15
 
10
16
  py_json_msp = {
11
17
  "str": "string",
@@ -18,12 +24,60 @@ py_json_msp = {
18
24
  }
19
25
 
20
26
 
27
+ class FunctionSchema(SchemaModel):
28
+ name: str
29
+ description: str | None = Field(
30
+ None,
31
+ description=(
32
+ "A description of what the function does, used by the "
33
+ "model to choose when and how to call the function."
34
+ ),
35
+ )
36
+ parameters: dict[str, Any] | None = Field(
37
+ None,
38
+ description=(
39
+ "The parameters the functions accepts, described as a JSON Schema object. "
40
+ "See the guide (https://platform.openai.com/docs/guides/function-calling) "
41
+ "for examples, and the JSON Schema reference for documentation about the "
42
+ "format. Omitting parameters defines a function with an empty parameter list."
43
+ ),
44
+ validation_alias="request_options",
45
+ )
46
+ strict: bool | None = Field(
47
+ None,
48
+ description=(
49
+ "Whether to enable strict schema adherence when generating the function call. "
50
+ "If set to true, the model will follow the exact schema defined in the parameters "
51
+ "field. Only a subset of JSON Schema is supported when strict is true."
52
+ ),
53
+ )
54
+
55
+ @field_validator("parameters", mode="before")
56
+ def _validate_parameters(cls, v):
57
+ if v is None:
58
+ return None
59
+ if isinstance(v, dict):
60
+ return v
61
+ try:
62
+ model_type = validate_model_to_type(cls, v)
63
+ return model_type.model_json_schema()
64
+ except Exception:
65
+ raise ValueError(f"Invalid model type: {v}")
66
+
67
+ def to_dict(self):
68
+ dict_ = super().to_dict()
69
+ return {"type": "function", "function": dict_}
70
+
71
+
21
72
  def function_to_schema(
22
73
  f_,
23
74
  style: Literal["google", "rest"] = "google",
24
75
  *,
76
+ request_options: dict[str, Any] | None = None,
77
+ strict: bool = None,
25
78
  func_description: str = None,
26
79
  parametert_description: dict[str, str] = None,
80
+ return_obj: bool = False,
27
81
  ) -> dict:
28
82
  """
29
83
  Generate a schema description for a given function. in openai format
@@ -78,27 +132,33 @@ def function_to_schema(
78
132
  "required": [],
79
133
  }
80
134
 
81
- for name, param in sig.parameters.items():
82
- # Default type to string and update if type hint is available
83
- param_type = "string"
84
- if param.annotation is not inspect.Parameter.empty:
85
- param_type = py_json_msp[param.annotation.__name__]
86
-
87
- # Extract parameter description from docstring, if available
88
- param_description = parametert_description.get(name)
89
-
90
- # Assuming all parameters are required for simplicity
91
- parameters["required"].append(name)
92
- parameters["properties"][name] = {
93
- "type": param_type,
94
- "description": param_description,
95
- }
96
-
97
- return {
98
- "type": "function",
99
- "function": {
100
- "name": func_name,
101
- "description": func_description,
102
- "parameters": parameters,
103
- },
135
+ if not request_options:
136
+ for name, param in sig.parameters.items():
137
+ # Default type to string and update if type hint is available
138
+ param_type = "string"
139
+ if param.annotation is not inspect.Parameter.empty:
140
+ param_type = py_json_msp[param.annotation.__name__]
141
+
142
+ # Extract parameter description from docstring, if available
143
+ param_description = parametert_description.get(name)
144
+
145
+ # Assuming all parameters are required for simplicity
146
+ parameters["required"].append(name)
147
+ parameters["properties"][name] = {
148
+ "type": param_type,
149
+ "description": param_description,
150
+ }
151
+ else:
152
+ parameters = request_options
153
+
154
+ params = {
155
+ "name": func_name,
156
+ "description": func_description,
157
+ "parameters": parameters,
104
158
  }
159
+ if strict:
160
+ params["strict"] = strict
161
+
162
+ if return_obj:
163
+ return FunctionSchema(**params)
164
+ return FunctionSchema(**params).to_dict()
@@ -80,6 +80,7 @@ class EndpointConfig(BaseModel):
80
80
  api_version: str | None = None
81
81
  allowed_roles: list[str] | None = None
82
82
  request_options: type | None = Field(None, exclude=True)
83
+ invoke_with_endpoint: bool | None = None
83
84
 
84
85
 
85
86
  class EndPoint(ABC):
@@ -91,19 +92,28 @@ class EndPoint(ABC):
91
92
  HTTP requests.
92
93
  """
93
94
 
94
- def __init__(self, config: dict) -> None:
95
+ def __init__(
96
+ self, config: dict | EndpointConfig | type[EndpointConfig], **kwargs
97
+ ) -> None:
95
98
  """Initializes the EndPoint with a given configuration.
96
99
 
97
100
  Args:
98
- config (dict): Configuration data that matches the EndpointConfig
101
+ config (dict | EndpointConfig): Configuration data that matches the EndpointConfig
99
102
  schema.
100
103
  """
101
- self.config = EndpointConfig(**config)
104
+ if isinstance(config, dict):
105
+ self.config = EndpointConfig(**config)
106
+ if isinstance(config, EndpointConfig):
107
+ self.config = config
108
+ if isinstance(config, type) and issubclass(config, EndpointConfig):
109
+ self.config = config()
110
+ if kwargs:
111
+ self.update_config(**kwargs)
102
112
 
103
113
  def update_config(self, **kwargs):
104
114
  config = self.config.model_dump()
105
115
  config.update(kwargs)
106
- self.config = EndpointConfig(**config)
116
+ self.config = self.config.model_validate(config)
107
117
 
108
118
  @property
109
119
  def name(self) -> str | None:
@@ -354,6 +364,7 @@ class APICalling(Event):
354
364
  exclude=True,
355
365
  description="Whether to include token usage information into instruction messages",
356
366
  )
367
+ response_obj: BaseModel | None = Field(None, exclude=True)
357
368
 
358
369
  @model_validator(mode="after")
359
370
  def _validate_streaming(self) -> Self:
@@ -648,7 +659,12 @@ class APICalling(Event):
648
659
  f"API call to {self.endpoint.full_url} failed: {e1}"
649
660
  )
650
661
  else:
651
- self.execution.response = response
662
+ self.response_obj = response
663
+ self.execution.response = (
664
+ response.model_dump()
665
+ if isinstance(response, BaseModel)
666
+ else response
667
+ )
652
668
  self.execution.status = EventStatus.COMPLETED
653
669
 
654
670
  def __str__(self) -> str:
@@ -48,6 +48,13 @@ def match_endpoint(
48
48
 
49
49
  return OpenRouterChatCompletionEndPoint()
50
50
 
51
+ if provider == "ollama":
52
+ from ..providers.ollama_.chat_completions import (
53
+ OllamaChatCompletionEndPoint,
54
+ )
55
+
56
+ return OllamaChatCompletionEndPoint()
57
+
51
58
  return OpenAIChatCompletionEndPoint(
52
59
  config={
53
60
  "provider": provider,
lionagi/service/imodel.py CHANGED
@@ -51,7 +51,7 @@ class iModel:
51
51
  interval: float | None = None,
52
52
  limit_requests: int = None,
53
53
  limit_tokens: int = None,
54
- invoke_with_endpoint: bool = False,
54
+ invoke_with_endpoint: bool = None,
55
55
  concurrency_limit: int | None = None,
56
56
  streaming_process_func: Callable = None,
57
57
  requires_api_key: bool = True,
@@ -95,6 +95,16 @@ class iModel:
95
95
  Additional keyword arguments, such as `model`, or any other
96
96
  provider-specific fields.
97
97
  """
98
+ model = kwargs.get("model", None)
99
+ if model:
100
+ if not provider:
101
+ if "/" in model:
102
+ provider = model.split("/")[0]
103
+ model = model.replace(provider + "/", "")
104
+ kwargs["model"] = model
105
+ else:
106
+ raise ValueError("Provider must be provided")
107
+
98
108
  if api_key is None:
99
109
  provider = str(provider or "").strip().lower()
100
110
  match provider:
@@ -110,6 +120,8 @@ class iModel:
110
120
  api_key = "GROQ_API_KEY"
111
121
  case "exa":
112
122
  api_key = "EXA_API_KEY"
123
+ case "ollama":
124
+ api_key = "ollama"
113
125
  case "":
114
126
  if requires_api_key:
115
127
  raise ValueError("API key must be provided")
@@ -121,16 +133,6 @@ class iModel:
121
133
  api_key = os.getenv(api_key)
122
134
 
123
135
  kwargs["api_key"] = api_key
124
- model = kwargs.get("model", None)
125
- if model:
126
- if not provider:
127
- if "/" in model:
128
- provider = model.split("/")[0]
129
- model = model.replace(provider + "/", "")
130
- kwargs["model"] = model
131
- else:
132
- raise ValueError("Provider must be provided")
133
-
134
136
  if isinstance(endpoint, EndPoint):
135
137
  self.endpoint = endpoint
136
138
  else:
@@ -145,7 +147,13 @@ class iModel:
145
147
  if base_url:
146
148
  self.endpoint.config.base_url = base_url
147
149
 
148
- self.should_invoke_endpoint = invoke_with_endpoint
150
+ if (
151
+ invoke_with_endpoint is None
152
+ and self.endpoint.config.invoke_with_endpoint is True
153
+ ):
154
+ invoke_with_endpoint = True
155
+
156
+ self.should_invoke_endpoint = invoke_with_endpoint or False
149
157
  self.kwargs = kwargs
150
158
  self.executor = RateLimitedAPIExecutor(
151
159
  queue_capacity=queue_capacity,
@@ -0,0 +1,3 @@
1
+ # Copyright (c) 2023 - 2025, HaiyangLi <quantocean.li at gmail dot com>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,134 @@
1
+ # Copyright (c) 2023 - 2025, HaiyangLi <quantocean.li at gmail dot com>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from collections.abc import AsyncGenerator
6
+
7
+ from lionagi.service.endpoints.chat_completion import ChatCompletionEndPoint
8
+
9
+ CHAT_COMPLETION_CONFIG = {
10
+ "provider": "ollama",
11
+ "base_url": "http://localhost:11434/v1",
12
+ "endpoint": "chat",
13
+ "method": "post",
14
+ "openai_compatible": True,
15
+ "is_invokeable": True,
16
+ "requires_tokens": True,
17
+ "is_streamable": True,
18
+ "required_kwargs": {
19
+ "messages",
20
+ "model",
21
+ },
22
+ "optional_kwargs": {
23
+ "frequency_penalty",
24
+ "presence_penalty",
25
+ "response_format",
26
+ "seed",
27
+ "stop",
28
+ "stream",
29
+ "stream_options",
30
+ "temperature",
31
+ "top_p",
32
+ "max_tokens",
33
+ "tools",
34
+ # "tool_choice",
35
+ # "logit_bias",
36
+ # "user",
37
+ # "n",
38
+ # "logprobs",
39
+ },
40
+ "allowed_roles": ["user", "assistant", "system"],
41
+ "invoke_with_endpoint": True,
42
+ }
43
+
44
+
45
+ class OllamaChatCompletionEndPoint(ChatCompletionEndPoint):
46
+ """
47
+ Documentation: https://platform.openai.com/docs/api-reference/chat/create
48
+ """
49
+
50
+ def __init__(self, config: dict = CHAT_COMPLETION_CONFIG):
51
+ from lionagi.libs.package.imports import check_import
52
+
53
+ check_import("openai")
54
+ check_import("ollama")
55
+
56
+ from ollama import list, pull
57
+ from openai import AsyncOpenAI
58
+
59
+ super().__init__(config)
60
+ self.client = AsyncOpenAI(
61
+ base_url=self.config.base_url,
62
+ api_key="ollama",
63
+ )
64
+ self._pull = pull
65
+ self._list = list
66
+
67
+ async def _invoke(
68
+ self,
69
+ payload: dict,
70
+ headers: dict,
71
+ **kwargs,
72
+ ):
73
+ self._check_model(payload["model"])
74
+ params = {**payload, **kwargs}
75
+ headers.pop("Authorization", None)
76
+ params["extra_headers"] = headers
77
+
78
+ if "response_format" in payload:
79
+ return await self.client.beta.chat.completions.parse(**params)
80
+ params.pop("response_format", None)
81
+ return await self.client.chat.completions.create(**params)
82
+
83
+ async def _stream(
84
+ self,
85
+ payload: dict,
86
+ headers: dict,
87
+ **kwargs,
88
+ ) -> AsyncGenerator:
89
+
90
+ self._check_model(payload["model"])
91
+ params = {**payload, **kwargs}
92
+ headers.pop("Authorization", None)
93
+ params["extra_headers"] = headers
94
+
95
+ async for chunk in self.client.beta.chat.completions.stream(**params):
96
+ yield chunk
97
+
98
+ @property
99
+ def allowed_roles(self):
100
+ return ["system", "user", "assistant"]
101
+
102
+ def _pull_model(self, model: str):
103
+ from tqdm import tqdm
104
+
105
+ current_digest, bars = "", {}
106
+ for progress in self._pull(model, stream=True):
107
+ digest = progress.get("digest", "")
108
+ if digest != current_digest and current_digest in bars:
109
+ bars[current_digest].close()
110
+
111
+ if not digest:
112
+ print(progress.get("status"))
113
+ continue
114
+
115
+ if digest not in bars and (total := progress.get("total")):
116
+ bars[digest] = tqdm(
117
+ total=total,
118
+ desc=f"pulling {digest[7:19]}",
119
+ unit="B",
120
+ unit_scale=True,
121
+ )
122
+
123
+ if completed := progress.get("completed"):
124
+ bars[digest].update(completed - bars[digest].n)
125
+
126
+ current_digest = digest
127
+
128
+ def _list_local_models(self) -> set:
129
+ response = self._list()
130
+ return {i.model for i in response.models}
131
+
132
+ def _check_model(self, model: str):
133
+ if model not in self._list_local_models():
134
+ self._pull_model(model)
lionagi/version.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.9.5"
1
+ __version__ = "0.9.6"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lionagi
3
- Version: 0.9.5
3
+ Version: 0.9.6
4
4
  Summary: An Intelligence Operating System.
5
5
  Author-email: HaiyangLi <quantocean.li@gmail.com>
6
6
  License: Apache License
@@ -4,7 +4,7 @@ lionagi/_errors.py,sha256=JlBTFJnRWtVYcRxKb7fWFiJHLbykl1E19mSJ8sXYVxg,455
4
4
  lionagi/_types.py,sha256=9g7iytvSj3UjZxD-jL06_fxuNfgZyWT3Qnp0XYp1wQU,63
5
5
  lionagi/settings.py,sha256=W52mM34E6jXF3GyqCFzVREKZrmnUqtZm_BVDsUiDI_s,1627
6
6
  lionagi/utils.py,sha256=K36D9AAGiMPR4eM9tYoiVgvH-NdPPSeMQPls09s7keQ,73223
7
- lionagi/version.py,sha256=ORAtCCI2THBDcdzIbh6oBsoshDvkkmXUWpmO4Q5McAk,22
7
+ lionagi/version.py,sha256=IgVHjr-TeioZYLJSkvpT80LLGi6U3ONzR1cfYfd5XNQ,22
8
8
  lionagi/libs/__init__.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFCJM,112
9
9
  lionagi/libs/parse.py,sha256=JRS3bql0InHJqATnAatl-hQv4N--XXw4P77JHhTFnrc,1011
10
10
  lionagi/libs/file/__init__.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFCJM,112
@@ -32,7 +32,7 @@ lionagi/libs/schema/__init__.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFC
32
32
  lionagi/libs/schema/as_readable.py,sha256=W4fi98WVkP5rfZ6A-iWqP5YFJexYCjt9Hf-l0iNs-2Q,5916
33
33
  lionagi/libs/schema/extract_code_block.py,sha256=PuJbJj1JnqR5fSZudowPcVPpEoKISLr0MjTOOVXSzwY,2394
34
34
  lionagi/libs/schema/extract_docstring.py,sha256=aYyLSRlB8lTH9QF9-6a56uph3AAkNuTyZ0S_duf5-fw,5729
35
- lionagi/libs/schema/function_to_schema.py,sha256=xAHFYPcrny1HDK9gfd42nmg0h2MftWUYPrIPeN1seJM,3393
35
+ lionagi/libs/schema/function_to_schema.py,sha256=qLsM-_1ERlLdP_zBwz7ttxMZQ8jr5eTJN8IX1QSkSig,5560
36
36
  lionagi/libs/schema/json_schema.py,sha256=cuHcaMr748O9g6suNGmRx4tRXcidd5-c7AMGjTIZyHM,7670
37
37
  lionagi/libs/token_transform/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
38
38
  lionagi/libs/token_transform/llmlingua.py,sha256=DkeLUlrb7rGx3nZ04aADU9HXXu5mZTf_DBwT0xhzIv4,7
@@ -161,13 +161,13 @@ lionagi/protocols/messages/templates/instruction_message.jinja2,sha256=L-ptw5OHx
161
161
  lionagi/protocols/messages/templates/system_message.jinja2,sha256=JRKJ0aFpYfaXSFouKc_N4unZ35C3yZTOWhIrIdCB5qk,215
162
162
  lionagi/protocols/messages/templates/tool_schemas.jinja2,sha256=ozIaSDCRjIAhLyA8VM6S-YqS0w2NcctALSwx4LjDwII,126
163
163
  lionagi/service/__init__.py,sha256=DMGXIqPsmut9H5GT0ZeSzQIzYzzPwI-2gLXydpbwiV8,21
164
- lionagi/service/imodel.py,sha256=TcqjpkRkPEEny6uaY383tL_45GcLvjju3-NVZS4EbLU,14907
164
+ lionagi/service/imodel.py,sha256=GIb0v0gSa9WJA5fmif8nAe-y-j8qHlZNb8FEIuzgE9s,15157
165
165
  lionagi/service/manager.py,sha256=FkuqAtLErqLmXNnDtuAdTUFo4uuE_VL660BBGBhzInU,1435
166
166
  lionagi/service/types.py,sha256=CHPi8Bxl_yJ1pl2jYZBOrTHbT8_oO9sK75d4LMB651g,486
167
167
  lionagi/service/endpoints/__init__.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFCJM,112
168
- lionagi/service/endpoints/base.py,sha256=nr53A1Z6zGmP5aqkyG-Gc-vbKG22CqvOj1x4nPwnBJ8,24763
168
+ lionagi/service/endpoints/base.py,sha256=sArF7dpSfer3OsBLMFqHGslAd4dgJUkCLtYkBWRmxOM,25441
169
169
  lionagi/service/endpoints/chat_completion.py,sha256=nihV7kCYm7ixdm8dH0JW7vKjqH9yIom4QDXGeDwuO6E,2964
170
- lionagi/service/endpoints/match_endpoint.py,sha256=hPCqFwVirj5g9Husec980OCUynjRmr0zQzrs7O4yP74,1874
170
+ lionagi/service/endpoints/match_endpoint.py,sha256=x2T-ftzdqCrdITRLkH8UNRDY2Pm359DnX2RDXTBnbpc,2082
171
171
  lionagi/service/endpoints/rate_limited_processor.py,sha256=P0CsMyhuG8OHCPYe2qez92Bm7v2ZRq4L5I6LOiAoGYs,5199
172
172
  lionagi/service/endpoints/token_calculator.py,sha256=-AKwDvV7C8k8MTmd62ymT0ETSUPWBJ_DQKLZUutlyfg,6161
173
173
  lionagi/service/providers/__init__.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFCJM,112
@@ -180,6 +180,8 @@ lionagi/service/providers/exa_/search.py,sha256=Z3pyJH8KiWiquJSJw8Rd6D7x43BwTFHb
180
180
  lionagi/service/providers/exa_/types.py,sha256=8ODjXpFajBE9-DGqBJNS--GObwmLSDi667xS84z_AgA,139
181
181
  lionagi/service/providers/groq_/__init__.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFCJM,112
182
182
  lionagi/service/providers/groq_/chat_completions.py,sha256=q1p_1qus4vduWWBzs9V_KbNrqU2Tu2o8TZm6Fh09fw4,1343
183
+ lionagi/service/providers/ollama_/__init__.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFCJM,112
184
+ lionagi/service/providers/ollama_/chat_completions.py,sha256=gPemTJO9dPd68l60kDYppO29uYqmLole4JGkv9Fz1Us,3764
183
185
  lionagi/service/providers/openai_/__init__.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFCJM,112
184
186
  lionagi/service/providers/openai_/chat_completions.py,sha256=y3RAgI5WQH5EwT1wZxp5ttnkCxUJEcOM3Cta6u9cpQo,2867
185
187
  lionagi/service/providers/openrouter_/__init__.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFCJM,112
@@ -211,7 +213,7 @@ lionagi/tools/file/writer.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFCJM,
211
213
  lionagi/tools/file/providers/__init__.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFCJM,112
212
214
  lionagi/tools/file/providers/docling_.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFCJM,112
213
215
  lionagi/tools/query/__init__.py,sha256=5y5joOZzfFWERl75auAcNcKC3lImVJ5ZZGvvHZUFCJM,112
214
- lionagi-0.9.5.dist-info/METADATA,sha256=RgrktdGFQrMKZn0BfHReT-JQ03IVXAkvTvqq6C5g_is,18053
215
- lionagi-0.9.5.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
216
- lionagi-0.9.5.dist-info/licenses/LICENSE,sha256=VXFWsdoN5AAknBCgFqQNgPWYx7OPp-PFEP961zGdOjc,11288
217
- lionagi-0.9.5.dist-info/RECORD,,
216
+ lionagi-0.9.6.dist-info/METADATA,sha256=WGUAokWhfSlKKpws48WJRgBmwQJ1MTBAQd3o_EVdPdg,18053
217
+ lionagi-0.9.6.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
218
+ lionagi-0.9.6.dist-info/licenses/LICENSE,sha256=VXFWsdoN5AAknBCgFqQNgPWYx7OPp-PFEP961zGdOjc,11288
219
+ lionagi-0.9.6.dist-info/RECORD,,