SimpleLLMFunc 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ni Jingzhe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,457 @@
1
+ Metadata-Version: 2.3
2
+ Name: SimpleLLMFunc
3
+ Version: 0.1.0
4
+ Summary:
5
+ Author: Ni Jingzhe
6
+ Author-email: lildinosaurni@outlook.com
7
+ Requires-Python: >=3.10
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Requires-Dist: httpx[socks] (>=0.28.1,<0.29.0)
14
+ Requires-Dist: openai (>=1.72.0,<2.0.0)
15
+ Requires-Dist: pydantic (>=2.11.3,<3.0.0)
16
+ Requires-Dist: pydantic-settings (>=2.8.1,<3.0.0)
17
+ Requires-Dist: pyyaml (>=6.0.2,<7.0.0)
18
+ Requires-Dist: rich (>=14.0.0,<15.0.0)
19
+ Description-Content-Type: text/markdown
20
+
21
+ # SimpleLLMFunc
22
+
23
+ ![SimpleLLMFunc](img/repocover.png)
24
+
25
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
26
+ [![Python Version](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/)
27
+ [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/NiJingzhe/SimpleLLMFunc/graphs/commit-activity)
28
+ [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://makeapullrequest.com)
29
+
30
+ 一个轻量级的LLM调用和工具集成框架,支持类型安全的LLM函数装饰器、多种模型接口和强大的日志跟踪系统。
31
+
32
+ 做过LLM开发的同志们或许都经历过这样的困境:
33
+
34
+ 1. 为了一些定制化功能,不得不用一些抽象trick,于是让一个本身主打低代码好理解的流变得抽象
35
+ 2. 使用低代码框架制作Workflow一时爽,但是发现又没有类型定义又没有代码提示,复杂流到后面的时候忘记了前面返回的格式
36
+ 3. 我只想要一个非常非常简单的无状态功能,但是用LangChain还得阅读一堆文档,创建一堆节点。
37
+ 4. 不管是LangChain还是Dify,居然都不能构建有向有环的逻辑????(虽然Dify新出了Condition Loop但并不是理想的形式)
38
+ 5. 但是不用框架的话又要自己写LLM API Call,每次都要写一遍这个Call代码很麻烦。而且Prompt作为变量形式存在没有那么直观的体现逻辑和在程序中的作用。
39
+
40
+ **这时候就有人问了,啊主播主播这些框架啊什么的都太复杂了,而不用框架有又很麻烦,有没有一种又简单又方便又快速的方法呢?**
41
+
42
+ ### 有的兄弟,有的!!
43
+
44
+ **SimpleLLMFunc** 的目标就是提供一个简单的恰到好处的框架,帮你实现了繁琐的API CALL撰写,帮你做了一点点Prompt工程,同时保留最大的自由度。
45
+
46
+ 基础功能单元是函数,让你以最 “Coding” 的方式,快速集成LLM能力到你的应用中,同时不会受到只能创建DAG的约束,能自由的构建流程。
47
+
48
+ Prompt会以DocString的形式存在,一方面强制你撰写良好的函数功能说明,让其他协作者对于函数功能一目了然,另一方面这就好像是用自然语言写了一段代码,功能描述就这样出现在了最合适的位置上,再也不用为了看一个函数的功能而到处跳转找到Prompt变量了。
49
+
50
+
51
+ ## 特性
52
+
53
+ - **LLM函数装饰器**:简化LLM调用,支持类型安全的函数定义和返回值处理
54
+ - **多模型支持**:支持多种LLM提供商接口(目前支持智谱AI)
55
+ - **API密钥管理**:自动化API密钥负载均衡,优化资源利用
56
+ - **结构化输出**:使用Pydantic模型定义结构化返回类型
57
+ - **强大的日志系统**:支持trace_id跟踪和搜索,方便调试和监控
58
+ - **工具系统**:支持Agent与外部环境交互,易于扩展
59
+
60
+ ## 项目结构
61
+
62
+ ```
63
+ SimpleLLMFunc/
64
+ ├── SimpleLLMFunc/ # 核心包
65
+ │ ├── interface/ # LLM 接口
66
+ │ │ ├── llm_interface.py # LLM 接口抽象类
67
+ │ │ ├── key_pool.py # API 密钥管理
68
+ │ │ └── zhipu.py # 智谱 AI 接口实现
69
+ │ ├── llm_function/ # LLM函数装饰器
70
+ │ │ ├── llm_chat_decorator.py # 对话函数装饰器实现
71
+ │ │ └── llm_function_decorator.py # 无状态函数装饰器实现
72
+ │ ├── logger/ # 日志系统
73
+ │ │ ├── logger.py # 日志核心实现
74
+ │ │ └── logger_config.py # 日志配置
75
+ │ ├── tool/ # 工具系统
76
+ │ │ └── tool.py # 工具基类和工具函数装饰器定义
77
+ │ └── config.py # 全局配置
78
+ └── examples/ # 示例代码
79
+ ├── llm_function_example.py # LLM函数示例
80
+ └── llm_chat_example.py # 对话函数示例
81
+ ```
82
+ ## 配置管理
83
+
84
+ SimpleLLMFunc使用分层配置系统:
85
+
86
+ - 环境变量:最高优先级
87
+ - `.env` 文件:次优先级
88
+ - `config.py` 默认值:最低优先级
89
+
90
+ ### 配置示例 (.env)
91
+
92
+ ```
93
+ ZHIPU_API_KEYS=["your-api-key-1", "your-api-key-2"]
94
+ LOG_DIR=./
95
+ LOG_FILE=agent.log
96
+ LOG_LEVEL=DEBUG
97
+ ```
98
+
99
+ ## LLM函数装饰器
100
+
101
+ - #### llm function
102
+
103
+ SimpleLLMFunc的核心特性是LLM函数装饰器,它允许您只通过声明带有类型标注的函数和撰写DocString来实现一个函数。
104
+
105
+ ```python
106
+ """
107
+ 使用LLM函数装饰器的示例
108
+ """
109
+ from typing import Dict, List
110
+ from pydantic import BaseModel, Field
111
+
112
+ from SimpleLLMFunc.llm_decorator.llm_function_decorator import llm_function
113
+ from SimpleLLMFunc.interface import ZhipuAI_glm_4_flash_Interface
114
+ from SimpleLLMFunc.logger.logger import app_log
115
+ from SimpleLLMFunc.tool import tool
116
+
117
+ # 定义一个Pydantic模型作为返回类型
118
+ class ProductReview(BaseModel):
119
+ rating: int = Field(..., description="产品评分,1-5分")
120
+ pros: List[str] = Field(..., description="产品优点列表")
121
+ cons: List[str] = Field(..., description="产品缺点列表")
122
+ summary: str = Field(..., description="评价总结")
123
+
124
+ # 使用装饰器创建一个LLM函数
125
+ @llm_function(
126
+ llm_interface=ZhipuAI_glm_4_flash_Interface,
127
+ system_prompt="你是一个专业的产品评测专家,可以客观公正地评价各种产品。"
128
+ )
129
+ def analyze_product_review(product_name: str, review_text: str) -> ProductReview:
130
+ """
131
+ 分析产品评论,提取关键信息并生成结构化评测报告
132
+
133
+ Args:
134
+ product_name: 产品名称
135
+ review_text: 用户评论文本
136
+
137
+ Returns:
138
+ 包含评分、优缺点和总结的产品评测报告
139
+ """
140
+ pass # 函数体为空,实际执行由LLM完成
141
+
142
+
143
+ @tool(name="天气查询", description="获取指定城市的天气信息")
144
+ def get_weather(city: str) -> Dict[str, str]:
145
+ """
146
+ 获取指定城市的天气信息
147
+
148
+ Args:
149
+ city: 城市名称
150
+
151
+ Returns:
152
+ 包含温度、湿度和天气状况的字典
153
+ """
154
+ return {
155
+ "temperature": "32°C",
156
+ "humidity": "80%",
157
+ "condition": "Cloudy"
158
+ }
159
+
160
+ class WeatherInfo(BaseModel):
161
+ city: str = Field(..., description="城市名称")
162
+ temperature: str = Field(..., description="当前温度")
163
+ humidity: str = Field(..., description="当前湿度")
164
+ condition: str = Field(..., description="天气状况")
165
+
166
+ @llm_function(
167
+ llm_interface=ZhipuAI_glm_4_flash_Interface,
168
+ tools=[get_weather]
169
+ )
170
+ def weather(city: str) -> WeatherInfo:
171
+ """
172
+ 获取指定城市的天气信息
173
+
174
+ Args:
175
+ city: 城市名称
176
+
177
+ Returns:
178
+ WeatherInfo对象,包含温度、湿度和天气状况
179
+ 例如:{"city": "L.A.", "temperature": "25°C", "humidity": "60%", "condition": "晴天"}
180
+ """
181
+ pass
182
+
183
+
184
+ def main():
185
+
186
+ app_log("开始运行示例代码")
187
+ # 测试产品评测分析
188
+ product_name = "XYZ无线耳机"
189
+ review_text = """
190
+ 我买了这款XYZ无线耳机已经使用了一个月。音质非常不错,尤其是低音部分表现出色,
191
+ 佩戴也很舒适,可以长时间使用不感到疲劳。电池续航能力也很强,充满电后可以使用约8小时。
192
+ 不过连接偶尔会有些不稳定,有时候会突然断开。另外,触控操作不够灵敏,经常需要点击多次才能响应。
193
+ 总的来说,这款耳机性价比很高,适合日常使用,但如果你需要用于专业音频工作可能还不够。
194
+ """
195
+
196
+ try:
197
+ print("\n===== 产品评测分析 =====")
198
+ result = analyze_product_review(product_name, review_text)
199
+ print(f"评分: {result.rating}/5")
200
+ print("优点:")
201
+ for pro in result.pros:
202
+ print(f"- {pro}")
203
+ print("缺点:")
204
+ for con in result.cons:
205
+ print(f"- {con}")
206
+ print(f"总结: {result.summary}")
207
+ except Exception as e:
208
+ print(f"产品评测分析失败: {e}")
209
+
210
+ # 测试天气查询
211
+ city = "Hangzhou"
212
+ try:
213
+ print("\n===== 天气查询 =====")
214
+ weather_info = weather(city)
215
+ print(f"城市: {city}")
216
+ print(f"温度: {weather_info.temperature}")
217
+ print(f"湿度: {weather_info.humidity}")
218
+ print(f"天气状况: {weather_info.condition}")
219
+ except Exception as e:
220
+ print(f"天气查询失败: {e}")
221
+
222
+
223
+
224
+ if __name__ == "__main__":
225
+ main()
226
+
227
+ ```
228
+ Output:
229
+
230
+ ```text
231
+ ===== 产品评测分析 =====
232
+ 评分: 4/5
233
+ 优点:
234
+ - 音质非常不错,尤其是低音部分表现出色
235
+ - 佩戴也很舒适,可以长时间使用不感到疲劳
236
+ - 电池续航能力也很强,充满电后可以使用约8小时
237
+ - 性价比很高,适合日常使用
238
+ 缺点:
239
+ - 连接偶尔会有些不稳定,有时候会突然断开
240
+ - 触控操作不够灵敏,经常需要点击多次才能响应
241
+ - 如果需要用于专业音频工作可能还不够
242
+ 总结: 音质和续航表现优秀,佩戴舒适,但连接稳定性不足,触控操作不够灵敏,适合日常使用,但不适合专业音频工作。
243
+
244
+ ===== 天气查询 =====
245
+ 城市: Hangzhou
246
+ 温度: 32°C
247
+ 湿度: 80%
248
+ 天气状况: Cloudy
249
+ ```
250
+
251
+
252
+ 正如这个例子展现的,只需要声明一个函数,声明返回类型,写好DocString,剩下的交给装饰器即可。
253
+
254
+ - #### llm chat
255
+
256
+ 同样的我们也支持创建**对话类函数**,以下是一个简单的对话函数的例子:[Simple Manus](./examples/simple_manus.py)。
257
+
258
+ 这个例子实现了一些工具和一个对话函数,能够实现代码专精的Manus类似物
259
+
260
+
261
+ ### 装饰器特性
262
+
263
+ - **类型安全**:根据函数签名自动识别参数和返回类型
264
+ - **Pydantic集成**:支持Pydantic模型作为返回类型,确保结果符合预定义结构
265
+ - **提示词自动构建**:基于函数文档和类型标注自动构建提示词
266
+
267
+ ## LLM供应商接口
268
+
269
+ LLM接口的封装是为了能够分隔供应商,如果是OpenAI SDK Compatiable的模型,可以省去设置BASE URL的重复工作,同时具有更好的类型提示。
270
+
271
+ 同样的也能够支持某些非OpenAI SDK Compatiable的模型。
272
+
273
+ SimpleLLMFunc的LLM接口设计原则:
274
+
275
+ - 简单、无状态的函数调用
276
+ - 支持普通和流式两种调用模式
277
+ - 集成了基于小根堆的API密钥负载均衡
278
+
279
+ ### 示例用法
280
+
281
+ 这里展示了接口的两种暴露接口,但实际使用过程中用户并不会接触到这样的直接调用。用户只会将接口对象作为参数传入装饰器。
282
+
283
+ ```python
284
+ from SimpleLLMFunc.interface import ZhipuAI_glm_4_flash_Interface
285
+
286
+ # 非流式调用
287
+ response = ZhipuAI_glm_4_flash_Interface.chat(
288
+ trace_id="unique_trace_id",
289
+ messages=[{"role": "user", "content": "你好"}]
290
+ )
291
+
292
+ # 流式调用
293
+ for chunk in ZhipuAI_glm_4_flash_Interface.chat_stream(
294
+ trace_id="unique_trace_id",
295
+ messages=[{"role": "user", "content": "你好"}]
296
+ ):
297
+ print(chunk)
298
+ ```
299
+
300
+ ## 日志系统
301
+
302
+ SimpleLLMFunc包含强大的日志系统,支持:
303
+
304
+ - 不同级别的日志(DEBUG, INFO, WARNING, ERROR, CRITICAL)
305
+ - 按trace_id跟踪和搜索相关日志,在`log_indices/trace_index.json`中,log会被按照trace id分类聚合,便于针对某一次特定的函数调用进行log分析。
306
+ - 自动记录代码位置信息
307
+ - 彩色控制台输出
308
+ - JSON格式文件日志,便于解析
309
+
310
+ 后续计划加入对每个llm function的性能监控,让开发者能够更好的追踪输入输出与响应时间,以进行Prompt调优和工作流效率优化。
311
+
312
+ ### 日志使用示例
313
+
314
+ ```python
315
+ from SimpleLLMFunc.logger import app_log, push_error, search_logs_by_trace_id
316
+
317
+ # 记录信息日志
318
+ app_log("操作成功完成", trace_id="operation_123")
319
+
320
+ # 记录错误日志
321
+ push_error("操作失败", trace_id="operation_123", exc_info=True)
322
+
323
+ # 使用日志上下文注入统一字段
324
+ with log_context(trace_id = "unified traceid")
325
+
326
+ push_error("操作失败") # 不需要显式指定trace id,会自动获得上下文中的trace id
327
+
328
+ ```
329
+
330
+ ## 工具系统
331
+
332
+ SimpleLLMFunc实现了可扩展的工具系统,使LLM能够与外部环境交互。工具系统支持两种定义方式:函数装饰器方式(推荐)和类继承方式(向后兼容)。
333
+
334
+ ### 函数装饰器方式(推荐)
335
+
336
+ 使用`@tool`装饰器将普通Python函数转换为工具,非常简洁直观,对于参数的描述一部分可以来源于`Pydantic Model`的`description`字段,函数入参的`description`则来自DocString。你需要在DocString中包含`Args:`或者`Parameters:`字样,然后每一行写一个`[param name]: [description]`,正如你在下面的例子中看到的这样。
337
+
338
+ ```python
339
+ from pydantic import BaseModel, Field
340
+ from SimpleLLMFunc.tool import tool
341
+
342
+ # 定义复杂参数的Pydantic模型
343
+ class Location(BaseModel):
344
+ latitude: float = Field(..., description="纬度")
345
+ longitude: float = Field(..., description="经度")
346
+
347
+ # 使用装饰器创建工具
348
+ @tool(name="get_weather", description="获取指定位置的天气信息")
349
+ def get_weather(location: Location, days: int = 1) -> dict:
350
+ """
351
+ 获取指定位置的天气预报
352
+
353
+ Args:
354
+ location: 位置信息,包含经纬度
355
+ days: 预报天数,默认为1天
356
+
357
+ Returns:
358
+ 天气预报信息
359
+ """
360
+ # 实际实现会调用天气API
361
+ return {
362
+ "location": f"{location.latitude},{location.longitude}",
363
+ "forecast": [{"day": i, "temp": 25, "condition": "晴朗"} for i in range(days)]
364
+ }
365
+ ```
366
+
367
+ 这种方式具有以下优势:
368
+ - 直接使用Python原生类型和Pydantic模型进行参数标注
369
+ - 自动从函数签名和文档字符串提取参数信息
370
+ - 装饰后的函数仍可直接调用,便于测试
371
+
372
+ ### 类继承方式(向后兼容)
373
+
374
+ 也可以通过继承`Tool`类并实现`run`方法来创建工具:
375
+
376
+ ```python
377
+ from SimpleLLMFunc.tool import Tool
378
+
379
+ class WebSearchTool(Tool):
380
+ def __init__(self):
381
+ super().__init__(
382
+ name="web_search",
383
+ description="在互联网上搜索信息"
384
+ )
385
+
386
+ def run(self, query: str, max_results: int = 5):
387
+ """
388
+ 执行网络搜索
389
+
390
+ Args:
391
+ query: 搜索查询词
392
+ max_results: 返回结果数量,默认为5
393
+
394
+ Returns:
395
+ 搜索结果列表
396
+ """
397
+ # 搜索逻辑实现
398
+ return {"results": ["结果1", "结果2", "结果3"]}
399
+ ```
400
+
401
+ ### 与LLM函数集成
402
+
403
+ 使用装饰器方式定义的工具可以直接传递给LLM函数装饰器:
404
+
405
+ ```python
406
+ from SimpleLLMFunc.llm_decorator import llm_function
407
+ from SimpleLLMFunc.interface import ZhipuAI_glm_4_flash_Interface
408
+
409
+ @llm_function(
410
+ llm_interface=ZhipuAI_glm_4_flash_Interface,
411
+ tools=[get_weather, search_web], # 直接传递被@tool装饰的函数
412
+ system_prompt="你是一个助手,可以使用工具来帮助用户。"
413
+ )
414
+ def answer_with_tools(question: str) -> str:
415
+ """
416
+ 回答用户问题,必要时使用工具获取信息
417
+
418
+ Args:
419
+ question: 用户问题
420
+
421
+ Returns:
422
+ 回答内容
423
+ """
424
+ pass
425
+ ```
426
+
427
+ 两种方式可以混合使用:
428
+
429
+ ```python
430
+ @llm_function(
431
+ llm_interface=ZhipuAI_glm_4_flash_Interface,
432
+ tools=[get_weather, WebSearchTool()], # 混合使用两种方式定义的工具
433
+ system_prompt="你是一个助手,可以使用工具来帮助用户。"
434
+ )
435
+ def answer_with_mixed_tools(question: str) -> str:
436
+ """回答用户问题,必要时使用工具获取信息"""
437
+ pass
438
+ ```
439
+
440
+ ## API密钥管理
441
+
442
+ SimpleLLMFunc使用`APIKeyPool`类通过小根堆管理多个API密钥,实现负载均衡:
443
+
444
+ - 自动选择最少负载的API密钥
445
+ - 单例模式确保每个提供商只有一个密钥池,密钥池使用小根堆来进行负载均衡,每次取出load最低的KEY
446
+ - 自动跟踪每个密钥的使用情况
447
+
448
+ ## 安装和使用
449
+
450
+ 1. 克隆此仓库
451
+ 2. 根据`env_template`创建`.env`文件并配置您的API密钥
452
+ 3. 使用Poetry安装依赖:`poetry install`
453
+ 4. 导入并使用`SimpleLLMFunc`的各个组件
454
+
455
+ ## 许可证
456
+
457
+ MIT