sycommon-python-lib 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.

Potentially problematic release.


This version of sycommon-python-lib might be problematic. Click here for more details.

Files changed (40) hide show
  1. sycommon_python_lib-0.1.0/PKG-INFO +128 -0
  2. sycommon_python_lib-0.1.0/README.md +107 -0
  3. sycommon_python_lib-0.1.0/pyproject.toml +31 -0
  4. sycommon_python_lib-0.1.0/setup.cfg +4 -0
  5. sycommon_python_lib-0.1.0/src/sycommon/__init__.py +0 -0
  6. sycommon_python_lib-0.1.0/src/sycommon/config/Config.py +73 -0
  7. sycommon_python_lib-0.1.0/src/sycommon/config/DatabaseConfig.py +34 -0
  8. sycommon_python_lib-0.1.0/src/sycommon/config/EmbeddingConfig.py +16 -0
  9. sycommon_python_lib-0.1.0/src/sycommon/config/LLMConfig.py +16 -0
  10. sycommon_python_lib-0.1.0/src/sycommon/config/RerankerConfig.py +13 -0
  11. sycommon_python_lib-0.1.0/src/sycommon/config/__init__.py +0 -0
  12. sycommon_python_lib-0.1.0/src/sycommon/database/database_service.py +79 -0
  13. sycommon_python_lib-0.1.0/src/sycommon/health/__init__.py +0 -0
  14. sycommon_python_lib-0.1.0/src/sycommon/health/health_check.py +17 -0
  15. sycommon_python_lib-0.1.0/src/sycommon/health/ping.py +13 -0
  16. sycommon_python_lib-0.1.0/src/sycommon/logging/__init__.py +0 -0
  17. sycommon_python_lib-0.1.0/src/sycommon/logging/kafka_log.py +551 -0
  18. sycommon_python_lib-0.1.0/src/sycommon/logging/logger_wrapper.py +19 -0
  19. sycommon_python_lib-0.1.0/src/sycommon/middleware/__init__.py +0 -0
  20. sycommon_python_lib-0.1.0/src/sycommon/middleware/context.py +3 -0
  21. sycommon_python_lib-0.1.0/src/sycommon/middleware/cors.py +14 -0
  22. sycommon_python_lib-0.1.0/src/sycommon/middleware/exception.py +85 -0
  23. sycommon_python_lib-0.1.0/src/sycommon/middleware/middleware.py +32 -0
  24. sycommon_python_lib-0.1.0/src/sycommon/middleware/monitor_memory.py +22 -0
  25. sycommon_python_lib-0.1.0/src/sycommon/middleware/timeout.py +19 -0
  26. sycommon_python_lib-0.1.0/src/sycommon/middleware/traceid.py +138 -0
  27. sycommon_python_lib-0.1.0/src/sycommon/models/__init__.py +0 -0
  28. sycommon_python_lib-0.1.0/src/sycommon/models/log.py +30 -0
  29. sycommon_python_lib-0.1.0/src/sycommon/services.py +29 -0
  30. sycommon_python_lib-0.1.0/src/sycommon/synacos/__init__.py +0 -0
  31. sycommon_python_lib-0.1.0/src/sycommon/synacos/feign.py +307 -0
  32. sycommon_python_lib-0.1.0/src/sycommon/synacos/nacos_service.py +689 -0
  33. sycommon_python_lib-0.1.0/src/sycommon/tools/__init__.py +0 -0
  34. sycommon_python_lib-0.1.0/src/sycommon/tools/snowflake.py +11 -0
  35. sycommon_python_lib-0.1.0/src/sycommon/tools/timing.py +73 -0
  36. sycommon_python_lib-0.1.0/src/sycommon_python_lib.egg-info/PKG-INFO +128 -0
  37. sycommon_python_lib-0.1.0/src/sycommon_python_lib.egg-info/SOURCES.txt +38 -0
  38. sycommon_python_lib-0.1.0/src/sycommon_python_lib.egg-info/dependency_links.txt +1 -0
  39. sycommon_python_lib-0.1.0/src/sycommon_python_lib.egg-info/requires.txt +14 -0
  40. sycommon_python_lib-0.1.0/src/sycommon_python_lib.egg-info/top_level.txt +1 -0
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: sycommon-python-lib
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: aiohttp>=3.12.13
8
+ Requires-Dist: cx-oracle>=8.3.0
9
+ Requires-Dist: decorator>=5.2.1
10
+ Requires-Dist: fastapi>=0.115.14
11
+ Requires-Dist: kafka>=1.3.5
12
+ Requires-Dist: kafka-python>=2.2.14
13
+ Requires-Dist: loguru>=0.7.3
14
+ Requires-Dist: mysql-connector-python>=9.3.0
15
+ Requires-Dist: nacos-sdk-python>=2.0.6
16
+ Requires-Dist: pydantic>=2.11.7
17
+ Requires-Dist: python-dotenv>=1.1.1
18
+ Requires-Dist: pyyaml>=6.0.2
19
+ Requires-Dist: sqlalchemy>=2.0.41
20
+ Requires-Dist: uuid>=1.30
21
+
22
+ # sycommon-python-lib
23
+
24
+ 常用 python 依赖库
25
+
26
+ pip install sycommon-python-lib -i http://192.168.2.174:8081/repository/pypy-group/simple/ --trusted-host 192.168.2.174
27
+
28
+ ## Getting started
29
+
30
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
31
+
32
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
33
+
34
+ ## Add your files
35
+
36
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
37
+ - [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
38
+
39
+ ```
40
+ cd existing_repo
41
+ git remote add origin http://git.syf.com/syai/sycommon-python-lib.git
42
+ git branch -M main
43
+ git push -uf origin main
44
+ ```
45
+
46
+ ## Integrate with your tools
47
+
48
+ - [ ] [Set up project integrations](http://git.syf.com/syai/sycommon-python-lib/-/settings/integrations)
49
+
50
+ ## Collaborate with your team
51
+
52
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
53
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
54
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
55
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
56
+ - [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
57
+
58
+ ## Test and Deploy
59
+
60
+ Use the built-in continuous integration in GitLab.
61
+
62
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
63
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
64
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
65
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
66
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
67
+
68
+ ---
69
+
70
+ # Editing this README
71
+
72
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
73
+
74
+ ## Suggestions for a good README
75
+
76
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
77
+
78
+ ## Name
79
+
80
+ Choose a self-explaining name for your project.
81
+
82
+ ## Description
83
+
84
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
85
+
86
+ ## Badges
87
+
88
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
89
+
90
+ ## Visuals
91
+
92
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
93
+
94
+ ## Installation
95
+
96
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
97
+
98
+ ## Usage
99
+
100
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
101
+
102
+ ## Support
103
+
104
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
105
+
106
+ ## Roadmap
107
+
108
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
109
+
110
+ ## Contributing
111
+
112
+ State if you are open to contributions and what your requirements are for accepting them.
113
+
114
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
115
+
116
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
117
+
118
+ ## Authors and acknowledgment
119
+
120
+ Show your appreciation to those who have contributed to the project.
121
+
122
+ ## License
123
+
124
+ For open source projects, say how it is licensed.
125
+
126
+ ## Project status
127
+
128
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1,107 @@
1
+ # sycommon-python-lib
2
+
3
+ 常用 python 依赖库
4
+
5
+ pip install sycommon-python-lib -i http://192.168.2.174:8081/repository/pypy-group/simple/ --trusted-host 192.168.2.174
6
+
7
+ ## Getting started
8
+
9
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
10
+
11
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
12
+
13
+ ## Add your files
14
+
15
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
16
+ - [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
17
+
18
+ ```
19
+ cd existing_repo
20
+ git remote add origin http://git.syf.com/syai/sycommon-python-lib.git
21
+ git branch -M main
22
+ git push -uf origin main
23
+ ```
24
+
25
+ ## Integrate with your tools
26
+
27
+ - [ ] [Set up project integrations](http://git.syf.com/syai/sycommon-python-lib/-/settings/integrations)
28
+
29
+ ## Collaborate with your team
30
+
31
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
32
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
33
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
34
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
35
+ - [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
36
+
37
+ ## Test and Deploy
38
+
39
+ Use the built-in continuous integration in GitLab.
40
+
41
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
42
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
43
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
44
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
45
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
46
+
47
+ ---
48
+
49
+ # Editing this README
50
+
51
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
52
+
53
+ ## Suggestions for a good README
54
+
55
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
56
+
57
+ ## Name
58
+
59
+ Choose a self-explaining name for your project.
60
+
61
+ ## Description
62
+
63
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
64
+
65
+ ## Badges
66
+
67
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
68
+
69
+ ## Visuals
70
+
71
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
72
+
73
+ ## Installation
74
+
75
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
76
+
77
+ ## Usage
78
+
79
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
80
+
81
+ ## Support
82
+
83
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
84
+
85
+ ## Roadmap
86
+
87
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
88
+
89
+ ## Contributing
90
+
91
+ State if you are open to contributions and what your requirements are for accepting them.
92
+
93
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
94
+
95
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
96
+
97
+ ## Authors and acknowledgment
98
+
99
+ Show your appreciation to those who have contributed to the project.
100
+
101
+ ## License
102
+
103
+ For open source projects, say how it is licensed.
104
+
105
+ ## Project status
106
+
107
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1,31 @@
1
+ [project]
2
+ name = "sycommon-python-lib"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ dependencies = [
8
+ "aiohttp>=3.12.13",
9
+ "cx-oracle>=8.3.0",
10
+ "decorator>=5.2.1",
11
+ "fastapi>=0.115.14",
12
+ "kafka>=1.3.5",
13
+ "kafka-python>=2.2.14",
14
+ "loguru>=0.7.3",
15
+ "mysql-connector-python>=9.3.0",
16
+ "nacos-sdk-python>=2.0.6",
17
+ "pydantic>=2.11.7",
18
+ "python-dotenv>=1.1.1",
19
+ "pyyaml>=6.0.2",
20
+ "sqlalchemy>=2.0.41",
21
+ "uuid>=1.30",
22
+ ]
23
+
24
+ [tool.setuptools]
25
+ packages = {find = {where = ["src"]}}
26
+
27
+ [tool.index]
28
+ name = "testpypi"
29
+ url = "http://192.168.2.174:8081/repository/shengye/"
30
+ publish-url = "http://192.168.2.174:8081/repository/shengye/"
31
+ explicit = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,73 @@
1
+ import yaml
2
+
3
+
4
+ class SingletonMeta(type):
5
+ _instances = {}
6
+
7
+ def __call__(cls, *args, **kwargs):
8
+ if cls not in cls._instances:
9
+ cls._instances[cls] = super().__call__(*args, **kwargs)
10
+ return cls._instances[cls]
11
+
12
+
13
+ class Config(metaclass=SingletonMeta):
14
+ def __init__(self, config_file='app.yaml'):
15
+ with open(config_file, 'r') as f:
16
+ self.config = yaml.safe_load(f)
17
+ self.MaxBytes = self.config.get('MaxBytes', 209715200)
18
+ self.Timeout = self.config.get('Timeout', 300000)
19
+ self.OCR = self.config.get('OCR', None)
20
+ self.INVOICE_OCR = self.config.get('INVOICE_OCR', None)
21
+ self.UnstructuredAPI = self.config.get('UnstructuredAPI', None)
22
+ self.MaxRetries = self.config.get('MaxRetries', 3)
23
+ self.llm_configs = []
24
+ self.embedding_configs = []
25
+ self.reranker_configs = []
26
+ self._process_config()
27
+
28
+ def get_llm_config(self, model_name):
29
+ for llm in self.llm_configs:
30
+ if llm.get('model') == model_name:
31
+ return llm
32
+ raise ValueError(f"No configuration found for model: {model_name}")
33
+
34
+ def get_embedding_config(self, model_name):
35
+ for llm in self.embedding_configs:
36
+ if llm.get('model') == model_name:
37
+ return llm
38
+ raise ValueError(f"No configuration found for model: {model_name}")
39
+
40
+ def get_reranker_config(self, model_name):
41
+ for llm in self.reranker_configs:
42
+ if llm.get('model') == model_name:
43
+ return llm
44
+ raise ValueError(f"No configuration found for model: {model_name}")
45
+
46
+ def _process_config(self):
47
+ llm_config_list = self.config.get('LLMConfig', [])
48
+ for llm_config in llm_config_list:
49
+ try:
50
+ # 延迟导入 LLMConfigModel
51
+ from sycommon.config.LLMConfig import LLMConfig
52
+ validated_config = LLMConfig(**llm_config)
53
+ self.llm_configs.append(validated_config.model_dump())
54
+ except ValueError as e:
55
+ print(f"Invalid LLM configuration: {e}")
56
+
57
+ embedding_config_list = self.config.get('EmbeddingConfig', [])
58
+ for embedding_config in embedding_config_list:
59
+ try:
60
+ from sycommon.config.EmbeddingConfig import EmbeddingConfig
61
+ validated_config = EmbeddingConfig(**embedding_config)
62
+ self.embedding_configs.append(validated_config.model_dump())
63
+ except ValueError as e:
64
+ print(f"Invalid LLM configuration: {e}")
65
+
66
+ reranker_config_list = self.config.get('RerankerConfig', [])
67
+ for reranker_config in reranker_config_list:
68
+ try:
69
+ from sycommon.config.RerankerConfig import RerankerConfig
70
+ validated_config = RerankerConfig(**reranker_config)
71
+ self.reranker_configs.append(validated_config.model_dump())
72
+ except ValueError as e:
73
+ print(f"Invalid LLM configuration: {e}")
@@ -0,0 +1,34 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class HikariConfig(BaseModel):
5
+ minimum_idle: int
6
+ maximum_pool_size: int
7
+ idle_timeout: int
8
+
9
+
10
+ class DatabaseConfig(BaseModel):
11
+ url: str
12
+ username: str
13
+ password: str
14
+ driver_class_name: str
15
+ time_between_eviction_runs_millis: int
16
+ min_evictable_idle_time_millis: int
17
+ validation_query: str
18
+ test_while_idle: bool
19
+ test_on_borrow: bool
20
+ test_on_return: bool
21
+ hikari: HikariConfig
22
+
23
+
24
+ def convert_key_to_snake_case(key):
25
+ import re
26
+ # 处理驼峰命名转换为下划线命名
27
+ key = re.sub(r'(?<!^)(?=[A-Z])', '_', key).lower()
28
+ return key.replace('-', '_')
29
+
30
+
31
+ def convert_dict_keys(d):
32
+ if isinstance(d, dict):
33
+ return {convert_key_to_snake_case(k): convert_dict_keys(v) for k, v in d.items()}
34
+ return d
@@ -0,0 +1,16 @@
1
+
2
+ from pydantic import BaseModel
3
+
4
+
5
+ class EmbeddingConfig(BaseModel):
6
+ model: str
7
+ provider: str
8
+ baseUrl: str
9
+ maxTokens: int
10
+ dimension: int
11
+
12
+ @classmethod
13
+ def from_config(cls, model_name: str):
14
+ from sycommon.config.Config import Config
15
+ llm_config = Config().get_embedding_config(model_name)
16
+ return cls(**llm_config)
@@ -0,0 +1,16 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class LLMConfig(BaseModel):
5
+ model: str
6
+ provider: str
7
+ baseUrl: str
8
+ maxTokens: int
9
+ vision: bool
10
+ callFunction: bool
11
+
12
+ @classmethod
13
+ def from_config(cls, model_name: str):
14
+ from sycommon.config.Config import Config
15
+ llm_config = Config().get_llm_config(model_name)
16
+ return cls(**llm_config)
@@ -0,0 +1,13 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class RerankerConfig(BaseModel):
5
+ model: str
6
+ provider: str
7
+ baseUrl: str
8
+
9
+ @classmethod
10
+ def from_config(cls, model_name: str):
11
+ from sycommon.config.Config import Config
12
+ llm_config = Config().get_reranker_config(model_name)
13
+ return cls(**llm_config)
@@ -0,0 +1,79 @@
1
+ from sqlalchemy import create_engine, text
2
+
3
+ from sycommon.config.Config import SingletonMeta
4
+ from sycommon.config.DatabaseConfig import DatabaseConfig, convert_dict_keys
5
+ from sycommon.logging.kafka_log import SYLogger
6
+ from sycommon.synacos.nacos_service import NacosService
7
+
8
+
9
+ class DatabaseService(metaclass=SingletonMeta):
10
+ _engine = None
11
+
12
+ @staticmethod
13
+ def setup_database(config: dict, shareConfigKey: str):
14
+ common = NacosService(config).share_configs.get(shareConfigKey, {})
15
+ if common and common.get('spring', {}).get('datasource', None):
16
+ databaseConfig = common.get('spring', {}).get('datasource', None)
17
+ converted_dict = convert_dict_keys(databaseConfig)
18
+ db_config = DatabaseConfig.model_validate(converted_dict)
19
+ DatabaseService._engine = DatabaseConnector(db_config).engine
20
+
21
+ @staticmethod
22
+ def engine():
23
+ return DatabaseService._engine
24
+
25
+
26
+ class DatabaseConnector(metaclass=SingletonMeta):
27
+ def __init__(self, db_config: DatabaseConfig):
28
+ # 从 DatabaseConfig 中提取数据库连接信息
29
+ self.db_user = db_config.username
30
+ self.db_password = db_config.password
31
+ # 提取 URL 中的主机、端口和数据库名
32
+ url_parts = db_config.url.split('//')[1].split('/')
33
+ host_port = url_parts[0].split(':')
34
+ self.db_host = host_port[0]
35
+ self.db_port = host_port[1]
36
+ self.db_name = url_parts[1].split('?')[0]
37
+
38
+ # 提取 URL 中的参数
39
+ params_str = url_parts[1].split('?')[1] if len(
40
+ url_parts[1].split('?')) > 1 else ''
41
+ params = {}
42
+ for param in params_str.split('&'):
43
+ if param:
44
+ key, value = param.split('=')
45
+ params[key] = value
46
+
47
+ # 在params中去掉指定的参数
48
+ for key in ['useUnicode', 'characterEncoding', 'serverTimezone', 'zeroDateTimeBehavior']:
49
+ if key in params:
50
+ del params[key]
51
+
52
+ # 构建数据库连接 URL
53
+ self.db_url = f'mysql+mysqlconnector://{self.db_user}:{self.db_password}@{self.db_host}:{self.db_port}/{self.db_name}'
54
+
55
+ SYLogger.info(f"Database URL: {self.db_url}")
56
+
57
+ # 优化连接池配置
58
+ self.engine = create_engine(
59
+ self.db_url,
60
+ connect_args=params,
61
+ pool_size=10, # 连接池大小
62
+ max_overflow=20, # 最大溢出连接数
63
+ pool_timeout=30, # 连接超时时间(秒)
64
+ pool_recycle=3600, # 连接回收时间(秒)
65
+ pool_pre_ping=True # 每次获取连接前检查连接是否有效
66
+ )
67
+
68
+ # 测试
69
+ if not self.test_connection():
70
+ raise Exception("Database connection test failed")
71
+
72
+ def test_connection(self):
73
+ try:
74
+ with self.engine.connect() as connection:
75
+ connection.execute(text("SELECT 1"))
76
+ return True
77
+ except Exception as e:
78
+ SYLogger.error(f"Database connection test failed: {e}")
79
+ return False
@@ -0,0 +1,17 @@
1
+ from fastapi import FastAPI, APIRouter
2
+
3
+
4
+ def setup_health_handler(app: FastAPI):
5
+ health_router = APIRouter()
6
+
7
+ @health_router.get("/actuator/health")
8
+ async def health_check():
9
+ """返回应用的健康状态"""
10
+ return {
11
+ "status": "UP",
12
+ "groups": ["liveness", "readiness"]
13
+ }
14
+
15
+ app.include_router(health_router)
16
+
17
+ return app
@@ -0,0 +1,13 @@
1
+ from fastapi import FastAPI, APIRouter
2
+
3
+
4
+ def setup_ping_handler(app: FastAPI):
5
+ ping_router = APIRouter()
6
+
7
+ @ping_router.get("/ping")
8
+ async def ping():
9
+ return {"status": "alive"}
10
+
11
+ app.include_router(ping_router)
12
+
13
+ return app