mlx-augllm 1.5__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.
mlx_augllm-1.5/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: mlx_augllm
3
+ Version: 1.5
4
+ Summary: ('A library for augmenting large language models using MLX',)
5
+ Home-page: https://github.com/ToPo-ToPo-ToPo/mlx_augllm
6
+ Author: Creator name
7
+ License: Apache License Version 2.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Requires-Python: >=3.13.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: mlx-lm>=0.30.0
14
+ Requires-Dist: mlx-vlm>=0.3.9
15
+ Requires-Dist: transformers>=5.0.0rc1
16
+ Requires-Dist: torch>=2.9.1
17
+ Requires-Dist: torchvision>=0.24.1
18
+ Requires-Dist: pyyaml
19
+ Requires-Dist: Pillow
20
+ Dynamic: author
21
+ Dynamic: classifier
22
+ Dynamic: description
23
+ Dynamic: description-content-type
24
+ Dynamic: home-page
25
+ Dynamic: license
26
+ Dynamic: license-file
27
+ Dynamic: requires-dist
28
+ Dynamic: requires-python
29
+ Dynamic: summary
30
+
31
+ # mlx_augllm
32
+ MLX(Apple Silicon向け機械学習フレームワーク)を用いた、
33
+ ローカルで動作する LLM / VLM のための統一インターフェースライブラリです。
34
+
35
+ 本ライブラリは以下を目的としています。
36
+ - ローカルLLM/VLMを簡単かつ一貫したAPIで扱える
37
+ - Tool Use(関数呼び出し)に対応
38
+ - 会話履歴の管理を自動化
39
+ - Apple Siliconに最適化
40
+
41
+ ## インストール
42
+ ```
43
+ pip install -U mlx_augllm
44
+ ```
45
+ - Apple Silicon必須
46
+
47
+ ## サンプル
48
+ ```python
49
+ from mlx_augllm import MlxAugmentedLLM, MlxLLMInterface, PromptBuilder
50
+
51
+ def run_test():
52
+
53
+ # モデルの準備
54
+ model_path = "mlx-community/gemma-3-27b-it-4bit"
55
+ augmented_llm = MlxAugmentedLLM(
56
+ llm_interface=MlxLLMInterface(
57
+ model_path=model_path,
58
+ use_vision=False,
59
+ temp=0.7,
60
+ top_k=50,
61
+ top_p=0.9,
62
+ min_p=0.05,
63
+ max_tokens=8192
64
+ ),
65
+ prompt_builder=PromptBuilder(system_prompt_text="あなたは有能なアシスタントです。"),
66
+ )
67
+
68
+ # 実行テスト
69
+ user_query = "トポロジー最適化について教えてください。"
70
+
71
+ print(f"\nユーザーの問いかけ: {user_query}")
72
+ print("-" * 50)
73
+ print("AIの応答 (Streaming):")
74
+
75
+ # respond の呼び出し (contextを渡す)
76
+ response_generator = augmented_llm.respond(
77
+ user_text=user_query,
78
+ stream=True,
79
+ temp=0.7
80
+ )
81
+
82
+ full_response = ""
83
+ for chunk in response_generator:
84
+ print(chunk, end="", flush=True)
85
+ full_response += chunk
86
+
87
+ print("\n" + "-" * 50)
88
+ print("【内部レポート】")
89
+ if augmented_llm.report_text:
90
+ print(f"最終回答の文字数: {len(augmented_llm.report_text)}")
91
+
92
+ if __name__ == "__main__":
93
+ run_test()
94
+ ```
@@ -0,0 +1,64 @@
1
+ # mlx_augllm
2
+ MLX(Apple Silicon向け機械学習フレームワーク)を用いた、
3
+ ローカルで動作する LLM / VLM のための統一インターフェースライブラリです。
4
+
5
+ 本ライブラリは以下を目的としています。
6
+ - ローカルLLM/VLMを簡単かつ一貫したAPIで扱える
7
+ - Tool Use(関数呼び出し)に対応
8
+ - 会話履歴の管理を自動化
9
+ - Apple Siliconに最適化
10
+
11
+ ## インストール
12
+ ```
13
+ pip install -U mlx_augllm
14
+ ```
15
+ - Apple Silicon必須
16
+
17
+ ## サンプル
18
+ ```python
19
+ from mlx_augllm import MlxAugmentedLLM, MlxLLMInterface, PromptBuilder
20
+
21
+ def run_test():
22
+
23
+ # モデルの準備
24
+ model_path = "mlx-community/gemma-3-27b-it-4bit"
25
+ augmented_llm = MlxAugmentedLLM(
26
+ llm_interface=MlxLLMInterface(
27
+ model_path=model_path,
28
+ use_vision=False,
29
+ temp=0.7,
30
+ top_k=50,
31
+ top_p=0.9,
32
+ min_p=0.05,
33
+ max_tokens=8192
34
+ ),
35
+ prompt_builder=PromptBuilder(system_prompt_text="あなたは有能なアシスタントです。"),
36
+ )
37
+
38
+ # 実行テスト
39
+ user_query = "トポロジー最適化について教えてください。"
40
+
41
+ print(f"\nユーザーの問いかけ: {user_query}")
42
+ print("-" * 50)
43
+ print("AIの応答 (Streaming):")
44
+
45
+ # respond の呼び出し (contextを渡す)
46
+ response_generator = augmented_llm.respond(
47
+ user_text=user_query,
48
+ stream=True,
49
+ temp=0.7
50
+ )
51
+
52
+ full_response = ""
53
+ for chunk in response_generator:
54
+ print(chunk, end="", flush=True)
55
+ full_response += chunk
56
+
57
+ print("\n" + "-" * 50)
58
+ print("【内部レポート】")
59
+ if augmented_llm.report_text:
60
+ print(f"最終回答の文字数: {len(augmented_llm.report_text)}")
61
+
62
+ if __name__ == "__main__":
63
+ run_test()
64
+ ```
@@ -0,0 +1,14 @@
1
+
2
+ from .mlx_llm import MlxLLM
3
+ from .mlx_augmented_llm import MlxAugmentedLLM, MlxLLMInterface, PromptBuilder, ChatMemory
4
+ from .test_tools import CalculatorTool, UserGreetingTool
5
+
6
+ __all__ = [
7
+ "MlxLLM",
8
+ "MlxAugmentedLLM",
9
+ "MlxLLMInterface",
10
+ "PromptBuilder",
11
+ "ChatMemory",
12
+ "CalculatorTool",
13
+ "UserGreetingTool"
14
+ ]
@@ -0,0 +1,73 @@
1
+ import copy
2
+ import pickle
3
+ from typing import List, Dict, Tuple
4
+ from mlx_vlm.utils import load_image
5
+
6
+ #--------------------------------------------------------------------------------------------
7
+ #
8
+ #--------------------------------------------------------------------------------------------
9
+ class ChatMemory:
10
+
11
+ def __init__(self, max_memory: int = 5):
12
+ self.max_memory = max_memory
13
+ self.history: List[Tuple[Dict, Dict]] = []
14
+
15
+ def add(self, user_text: str, assistant_text: str, user_image_paths: List[str] = None):
16
+ """新しい会話セットを追加"""
17
+ if self.max_memory <= 0:
18
+ return
19
+
20
+ user_msg = {"role": "user", "content": user_text}
21
+ if user_image_paths:
22
+ user_msg["images"] = user_image_paths
23
+
24
+ assistant_msg = {"role": "assistant", "content": assistant_text}
25
+
26
+ self.history.append((user_msg, assistant_msg))
27
+
28
+ # 最大数を超えたら古いものを削除
29
+ if len(self.history) > self.max_memory:
30
+ self.history = self.history[-self.max_memory:]
31
+
32
+ def clear(self):
33
+ """履歴をリセット"""
34
+ self.history = []
35
+
36
+ def get_messages(self, use_vision: bool = False) -> Tuple[List[Dict], List]:
37
+ """
38
+ LLMに渡すためのメッセージリストと、対応するPIL画像のリストを生成
39
+ return: (flattened_messages, all_pils)
40
+ """
41
+ flattened = []
42
+ all_pils = []
43
+
44
+ for user_msg, assistant_msg in self.history:
45
+ # ユーザーメッセージの処理
46
+ u_msg = copy.deepcopy(user_msg)
47
+ if use_vision and "images" in u_msg:
48
+ paths = u_msg["images"]
49
+ pils = [load_image(str(p)) for p in paths]
50
+
51
+ # VLM形式への変換
52
+ content = [{"type": "text", "text": u_msg["content"]}]
53
+ for _ in pils:
54
+ content.append({"type": "image"})
55
+
56
+ u_msg["content"] = content
57
+ all_pils.extend(pils)
58
+ del u_msg["images"]
59
+
60
+ flattened.append(u_msg)
61
+ flattened.append(copy.deepcopy(assistant_msg))
62
+
63
+ return flattened, all_pils
64
+
65
+ def save_to_file(self, filepath: str):
66
+ """現在の記憶をファイルに保存"""
67
+ with open(filepath, 'wb') as f:
68
+ pickle.dump(self.history, f)
69
+
70
+ def load_from_file(self, filepath: str):
71
+ """ファイルから記憶を復元"""
72
+ with open(filepath, 'rb') as f:
73
+ self.history = pickle.load(f)
@@ -0,0 +1,212 @@
1
+
2
+
3
+ # Author: Shun Ogawa (a.k.a. "ToPo")
4
+ # Copyright (c) 2025 Shun Ogawa (a.k.a. "ToPo")
5
+ # License: Apache License Version 2.0
6
+
7
+ import inspect
8
+ from typing import Callable, Any, Dict, List, Optional
9
+ import yaml
10
+ import re
11
+ from .tool import Tool
12
+ #------------------------------------------------------------------------------------
13
+ # 関数 (ツール) を名前にマッピングして登録します。
14
+ #------------------------------------------------------------------------------------
15
+ def register_tools(tools: List[Tool]) -> Dict[str, Tool]:
16
+ return {tool.name(): tool for tool in tools}
17
+
18
+ #------------------------------------------------------------------------------------
19
+ # 呼び出し可能なターゲット (関数やメソッド) を取得します。
20
+ # 関数、クラス、インスタンスを受け取って、signatureを取得可能な対象を返す
21
+ #------------------------------------------------------------------------------------
22
+ def get_callable_target(fn_or_instance: Any) -> Callable:
23
+ #
24
+ if inspect.isfunction(fn_or_instance):
25
+ return fn_or_instance
26
+ # ツールインスタンスの場合、_runメソッドを優先
27
+ elif hasattr(fn_or_instance, "_run") and callable(getattr(fn_or_instance, "_run")):
28
+ return getattr(fn_or_instance, "_run")
29
+ elif hasattr(fn_or_instance, "run") and callable(getattr(fn_or_instance, "run")):
30
+ return getattr(fn_or_instance, "run")
31
+ elif inspect.isclass(fn_or_instance):
32
+ if hasattr(fn_or_instance, "run") and callable(getattr(fn_or_instance, "run")): # クラスメソッド run
33
+ return getattr(fn_or_instance, "run")
34
+ # クラスの __call__ (通常は __init__) はツールの実行シグネチャとは異なるため、ここでは対象外とする
35
+ raise TypeError(f"クラス {fn_or_instance} から実行可能なターゲットメソッド (run または _run) を特定できませんでした。")
36
+ elif callable(fn_or_instance): # その他の callable オブジェクト
37
+ return fn_or_instance
38
+ else:
39
+ raise TypeError(f"{fn_or_instance} は関数、クラス、または適切な callable ではありません。")
40
+
41
+ #------------------------------------------------------------------------------------
42
+ # LLMにツール呼び出しのルールと関数一覧を伝えるシステムプロンプトを生成します。(YAML版)
43
+ #------------------------------------------------------------------------------------
44
+ def generate_system_prompt(functions: Dict[str, Callable]) -> str:
45
+ #
46
+ descriptions = []
47
+ for name, tool_instance in functions.items():
48
+ try:
49
+ # tool_instanceの_runメソッドのシグネチャを取得する
50
+ target_callable = get_callable_target(tool_instance)
51
+ sig = inspect.signature(target_callable)
52
+
53
+ params_list = []
54
+ for k, v in sig.parameters.items():
55
+ if k == 'self': # 'self' パラメータは除外
56
+ continue
57
+ param_type = v.annotation.__name__ if v.annotation != inspect.Parameter.empty else 'Any'
58
+ if v.default != inspect.Parameter.empty:
59
+ params_list.append(f"{k}: {param_type} (optional, default={v.default})")
60
+ else:
61
+ params_list.append(f"{k}: {param_type}")
62
+ params = ", ".join(params_list)
63
+
64
+ # ツールのdescriptionを使用
65
+ docstring = tool_instance.description().strip()
66
+ descriptions.append(f"- `{name}({params})`: {docstring}")
67
+ except Exception as e:
68
+ descriptions.append(f"- `{name}()`: <定義情報の取得に失敗: {e}>")
69
+
70
+ # Function calling用のプロンプトを作成
71
+ prompt = f"""ユーザーの指示に応じて、以下のツールを呼び出します。
72
+ ### ツール呼び出しのルール(厳守):
73
+
74
+ 1. ユーザーの指示に基づいてツールが必要な場合、以下の**厳密な YAML 形式**のみで返答してください:
75
+
76
+ ```yaml
77
+ tool_calls:
78
+ - tool:
79
+ name: <ツール名>
80
+ arguments:
81
+ <引数名1>: <値1>
82
+ <引数名2>: <値2>
83
+ ...
84
+ ```
85
+ - `tool_calls` はリストです。
86
+ - 各要素は `tool` オブジェクトを含みます。
87
+ - `tool` オブジェクトは `name` と `arguments` を含みます。
88
+ - `arguments` は引数名をキー、値をバリューとするマップ(辞書)です。
89
+ - YAMLコードブロック (```yaml ... ```) で囲んでください。
90
+
91
+ ツール一覧:
92
+ {chr(10).join(descriptions)}
93
+
94
+ 2. 関数を使う必要がないときは通常の自然言語で返答してください。
95
+
96
+ この2つのルールを厳守して、ユーザーの要求に最適な形で応答してください。
97
+ """
98
+ return prompt
99
+
100
+ #------------------------------------------------------------------------------------
101
+ # 関数のシグネチャに基づいて、生の引数辞書を適切な型にキャストします。
102
+ #------------------------------------------------------------------------------------
103
+ def cast_arguments(func_callable: Callable, raw_args: dict) -> dict:
104
+ sig = inspect.signature(func_callable)
105
+ casted_args = {}
106
+
107
+ valid_param_names = {name for name in sig.parameters if name != 'self'}
108
+
109
+ for name, value in raw_args.items():
110
+ if name not in valid_param_names:
111
+ print(f"Warning: Argument '{name}' is not a valid parameter for {func_callable.__name__}. It will be ignored.")
112
+ continue
113
+
114
+ param = sig.parameters[name]
115
+ target_type = param.annotation
116
+
117
+ if target_type == inspect.Parameter.empty or target_type == Any:
118
+ casted_args[name] = value
119
+ continue
120
+
121
+ try:
122
+ if target_type == str:
123
+ casted_args[name] = str(value)
124
+ elif target_type == int:
125
+ casted_args[name] = int(value)
126
+ elif target_type == float:
127
+ casted_args[name] = float(value)
128
+ elif target_type == bool:
129
+ if isinstance(value, str):
130
+ casted_args[name] = value.lower() in ['true', 'yes', 'on', '1']
131
+ else:
132
+ casted_args[name] = bool(value)
133
+ else: # リスト、辞書などはYAMLパーサーが適切に変換していることを期待
134
+ casted_args[name] = value
135
+ except (ValueError, TypeError) as e:
136
+ print(f"Warning: Failed to cast argument '{name}' (value: '{value}') to type {target_type.__name__}. Using original value. Error: {e}")
137
+ casted_args[name] = value
138
+
139
+ # デフォルト値を持つ引数が省略された場合の処理
140
+ for name, param in sig.parameters.items():
141
+ if name == 'self':
142
+ continue
143
+ if name not in casted_args and param.default is not inspect.Parameter.empty:
144
+ casted_args[name] = param.default
145
+ elif name not in casted_args and param.default is inspect.Parameter.empty : #必須引数が指定されてない
146
+ print(f"Warning: Required argument '{name}' for {func_callable.__name__} was not provided by LLM.")
147
+ # ここでエラーをraiseするか、Noneを設定するかは設計による
148
+ # casted_args[name] = None # またはエラー
149
+
150
+ return casted_args
151
+
152
+ #------------------------------------------------------------------------------------
153
+ # LLMの応答からYAML形式のtool_callsセクションを抽出・解析します。
154
+ #------------------------------------------------------------------------------------
155
+ def extract_tool_calls_from_yaml(content: str) -> List[Dict[str, Any]]:
156
+ content = content.strip()
157
+
158
+ # YAMLコードブロックの検出
159
+ match = re.search(r"```yaml\s*(.*?)\s*```", content, re.DOTALL)
160
+
161
+ yaml_str: Optional[str]
162
+ if match:
163
+ yaml_str = match.group(1).strip()
164
+ elif content.startswith("tool_calls:"): # YAMLブロックなしで直接YAMLが始まる場合も許容
165
+ yaml_str = content
166
+ else:
167
+ yaml_str = None
168
+
169
+ if not yaml_str:
170
+ raise ValueError("YAMLコードブロックまたはtool_callsで始まるYAML文字列が見つかりませんでした。")
171
+
172
+ try:
173
+ parsed = yaml.safe_load(yaml_str)
174
+
175
+ if not isinstance(parsed, dict) or "tool_calls" not in parsed:
176
+ raise ValueError("YAMLのルートが辞書型でなく、'tool_calls'キーが含まれていません。")
177
+
178
+ calls = parsed["tool_calls"] # 修正: キー名からコロンを削除
179
+ if not isinstance(calls, list):
180
+ # LLMが単一のツールコールをリストでなく直接記述した場合を許容する(例:tool_calls: {tool: ...})
181
+ if isinstance(calls, dict) and "tool" in calls:
182
+ calls = [calls] # リストに変換
183
+ else:
184
+ raise ValueError("'tool_calls'の値はリストである必要があります。")
185
+
186
+ extracted_tool_calls = []
187
+ for item in calls:
188
+ if not isinstance(item, dict) or "tool" not in item:
189
+ raise ValueError("各tool_callエントリは辞書型で、'tool'キーを含む必要があります。")
190
+
191
+ tool_data = item["tool"] # 修正: キー名からコロンを削除
192
+ if not isinstance(tool_data, dict):
193
+ raise ValueError("'tool'の値は辞書型である必要があります。")
194
+
195
+ name = tool_data.get("name") # 修正: .getを使用し、キー名からコロンを削除
196
+ arguments = tool_data.get("arguments", {}) # 修正: .getを使用し、引数がない場合は空の辞書をデフォルトに
197
+
198
+ if not isinstance(name, str) or not name: # 名前が文字列で、空でないことを確認
199
+ raise ValueError(f"無効なツール名です: '{name}'。ツール名は文字列である必要があります。")
200
+ if not isinstance(arguments, dict):
201
+ raise ValueError(f"ツールの引数 ('arguments') は辞書型である必要がありますが、'{type(arguments)}'でした (ツール: {name})。")
202
+
203
+ # OpenAI互換の形式に少し寄せる
204
+ extracted_tool_calls.append({
205
+ "function": {"name": name, "arguments": arguments}
206
+ })
207
+ return extracted_tool_calls
208
+
209
+ except yaml.YAMLError as e:
210
+ raise ValueError(f"YAML解析エラー: {e}\n解析対象のYAML文字列:\n---\n{yaml_str}\n---")
211
+ except Exception as e: # その他のパース関連エラー
212
+ raise ValueError(f"tool_callsの解析中に予期せぬエラーが発生しました: {e}\n解析対象のYAML文字列:\n---\n{yaml_str}\n---")