agent-common 0.4.22__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.
Files changed (27) hide show
  1. agent_common-0.4.22/LICENSE +201 -0
  2. agent_common-0.4.22/MANIFEST.in +9 -0
  3. agent_common-0.4.22/PKG-INFO +215 -0
  4. agent_common-0.4.22/README.md +204 -0
  5. agent_common-0.4.22/pyproject.toml +20 -0
  6. agent_common-0.4.22/setup.cfg +4 -0
  7. agent_common-0.4.22/src/agent_common/__init__.py +34 -0
  8. agent_common-0.4.22/src/agent_common/clients.py +758 -0
  9. agent_common-0.4.22/src/agent_common/config/default_agent_common.yml +29 -0
  10. agent_common-0.4.22/src/agent_common/config/llmpool.yml +136 -0
  11. agent_common-0.4.22/src/agent_common/config/logging_messages.yml +322 -0
  12. agent_common-0.4.22/src/agent_common/config_loader.py +495 -0
  13. agent_common-0.4.22/src/agent_common/error_handler.py +149 -0
  14. agent_common-0.4.22/src/agent_common/llm.py +431 -0
  15. agent_common-0.4.22/src/agent_common/logger.py +674 -0
  16. agent_common-0.4.22/src/agent_common/logging_config.py +13 -0
  17. agent_common-0.4.22/src/agent_common/schemas/sys.json +6 -0
  18. agent_common-0.4.22/src/agent_common/tool/__init__.py +8 -0
  19. agent_common-0.4.22/src/agent_common/tool/date/__init__.py +14 -0
  20. agent_common-0.4.22/src/agent_common/tool/date/date_time_utils.py +54 -0
  21. agent_common-0.4.22/src/agent_common/tool_parser.py +361 -0
  22. agent_common-0.4.22/src/agent_common/utils.py +115 -0
  23. agent_common-0.4.22/src/agent_common.egg-info/PKG-INFO +215 -0
  24. agent_common-0.4.22/src/agent_common.egg-info/SOURCES.txt +25 -0
  25. agent_common-0.4.22/src/agent_common.egg-info/dependency_links.txt +1 -0
  26. agent_common-0.4.22/src/agent_common.egg-info/requires.txt +2 -0
  27. agent_common-0.4.22/src/agent_common.egg-info/top_level.txt +1 -0
@@ -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,9 @@
1
+ graft src/agent_common/config
2
+ graft src/agent_common/schemas
3
+ recursive-include src/agent_common/config *.yml
4
+ recursive-include src/agent_common/schemas *.json
5
+
6
+ prune whls
7
+ prune dist
8
+ prune build
9
+ global-exclude *.py[cod] __pycache__ *.so
@@ -0,0 +1,215 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent_common
3
+ Version: 0.4.22
4
+ Summary: 중앙 에이전트 및 하위 SQL 생성 서비스를 위한 공통 로깅/설정 모듈
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: pyyaml>=6.0
9
+ Requires-Dist: requests
10
+ Dynamic: license-file
11
+
12
+ # agent_common 패키지
13
+
14
+ 중앙 에이전트 및 데이터 이관/생성 서비스를 위한 공통 로깅, 설정 로더, 인프라 클라이언트, 동적 도구(Tool) 파서 및 에러 처리 라이브러리 패키지입니다.
15
+
16
+ ---
17
+
18
+ ## 📌 주요 제공 기능
19
+
20
+ ### 1. 설정 로더 및 불변 설정 객체 (`agent_common.config_loader`)
21
+ - **계층적 YAML 설정 해석 및 병합 (Deep Merge)**: 패키지 기본 설정(`agent_common/config/*.yml`)과 개별 프로젝트 설정(`config/*.yml`) 동적 병합.
22
+ - **불변 점 표기법 조회 (`ReadOnlyConfig`)**: `config.ecs.endpoint_url`, `config.transfer.max_workers_int` 형태로 직관적 속성 접근 및 런타임 변조 방지.
23
+ - **타입 접미사 자동 형 변환 및 타입 보증 (Type Guarantee & Coercion - v0.4.14)**:
24
+ - `_int`: `int` 정수형 자동 형 변환 및 보증
25
+ - `_float`: `float` 실수형 자동 형 변환 및 보증
26
+ - `_bool`: `bool` 불리언형 자동 변환 (`"true"`, `"false"`, `1`, `0` 등 완벽 대응)
27
+ - `_str`: `str` 문자열 변환 및 `.strip()` 공백 자동 정제
28
+ - `_list` / `_dict`: 리스트 / 불변 딕셔너리(`ReadOnlyConfig`) 래핑 보증
29
+ - **Fail-Fast 필수 설정 검증 (`require_setting()`)**: 프로그램 시작 시 필수 설정값 누락 시 상세 원인 출력 후 프로세스 즉시 종료.
30
+ - **네트워크 프록시 제어**: `proxy.no_proxy` 설정의 `NO_PROXY` 환경변수 자동 반영.
31
+ - **설정 파일 템플릿 보정 (`ensure_config_file()`)**: 프로젝트 설정 누락 시 기본 스키마 기반 자동 생성 및 자가 치유(Self-healing).
32
+
33
+ ### 2. 단일 행 로깅 포매터 및 로거 (`agent_common.logger`)
34
+ - `SingleLineFlattenFormatter`: 모든 로그 및 Traceback 예외 메시지를 1줄로 평탄화하여 중앙 로그 수집(Logstash, Fluentd 등)에 최적화
35
+ - `ProjectLogger`: 콘솔 및 파일 로그 핸들러 동적 생성 및 일자별 로그 분리 관리
36
+ - **프로그램별 차등 로깅 레벨 지원 (`logging.level.<app_name>`)**: 설정 파일에서 프로그램별로 세분화된 로그 레벨 지정 지원
37
+ - `logging_messages.yml` 사전 기반 한글 포맷 템플릿 연동 로깅 지원
38
+
39
+ ### 3. 스토리지 및 데이터베이스 클라이언트 (`agent_common.clients`)
40
+ - `EcsClient`: Dell ECS S3 저장소 접속, 목록 조회, 메타데이터 해석 및 파일 메모리 스트리밍 획득
41
+ - `GcsClient`: Google Cloud Storage 연결, 파일 존재 검증 및 대용량 멀티스레드 스트리밍 업로드
42
+ - `BigQueryClient`: Google Cloud BigQuery 연결, JSON 데이터 스트리밍 입력(`insert_rows_json`), 배치 로드(`load_table_from_json_data`), 인라인 MERGE(`merge_table_from_json_data` - 한글/특수문자/예약어 컬럼 백틱 지원 및 413 방지 기본 청크 100건 분할), 범용 SQL 쿼리(`query`)
43
+
44
+ ### 4. 동적 도구 로더 및 템플릿 평가기 (`agent_common.tool_parser`) & 내장 도구 (`agent_common.tool`)
45
+ - **이원화된 Tool 디렉터리 계층 탐색**:
46
+ - **1순위 (내장 도구)**: `agent_common/tool/` 하위 모듈 (전사 표준 내장 도구)
47
+ - **2순위 (프로젝트 도구)**: `config.yml`의 `transfer.tool_dir`에 지정된 로컬 경로 (예: `medallion/tool/`)
48
+ - **선언적 템플릿 치환 및 표현식 평가 (`ToolParser.eval`)**:
49
+ - 변수 네임스페이스 바인딩: `{ecs.key}`, `{sys.today}`, `{json.title}`
50
+ - 동적 도구 함수 호출: `"{code.date_check_to_code(contentInfo.enddate)}"`, `"{path.get_json_name(ecs.key)}"`
51
+ - 문자열 슬라이싱/메서드: `"{raw_key.lstrip('/')}"`, `"{raw_size|0}"`
52
+ - **안전한 네임스페이스 탐색 (`_SafeNamespace`)**:
53
+ - 대소문자 무관 탐색 및 누락된 필드에 대해 KeyError 없이 안전하게 빈 문자열(`""`) 반환
54
+ - **내장 공통 도구 (`agent_common.tool.date.DateTimeUtils`)**:
55
+ - `get_today_yyyymmdd()`: `YYYYMMDD` 형식 8자리 일자 반환 (예: `20260824`)
56
+ - `get_now_compact()`: `YYYYMMDDHHMMSS` 형식 14자리 압축 일시 반환 (예: `20260824110500`)
57
+ - `get_now_formatted(fmt)`: `YYYY-MM-DD HH:MM:SS+09:00` 표준 KST 포맷 일시 반환
58
+ - **시스템 컨텍스트 스키마 (`agent_common.schemas.sys.json`)**:
59
+ - `{sys.today}`, `{sys.now_compact}`, `{sys.timestamp_compact}`, `{sys.env}` 등 기본 자동 제공
60
+
61
+ ### 5. 진행률 트래커 및 공용 유틸리티 (`agent_common.utils`)
62
+ - `ProgressTracker`: 멀티스레드 실시간 진행률 추적(`[N/Total] (P%)`), 처리 속도 및 남은 시간 예측, 마일스톤 경고 승격 로깅, 최종 요약 리포트(Summary Report) 생성
63
+ - `DateTimeUtils`: 전역 일시 헬퍼 함수군
64
+
65
+ ### 6. 공용 에러 및 예외 핸들러 (`agent_common.error_handler`)
66
+ - 네트워크 장애, 설정 오류, 런타임 예외에 대한 일관된 로깅 및 핸들링 제공
67
+
68
+ ### 7. 통합 LLM 클라이언트 및 추론 엔진 (`agent_common.llm`)
69
+ - **다중 프로바이더 통합 지원 (`LlmClient`)**:
70
+ - **외부 LLM API**: OpenAI 호환 표준 API (`/chat/completions`) 및 Fabrix 전용 API 형식 지원
71
+ - **로컬 GGUF 모델**: `llama-cpp-python` 기반 로컬 CPU/GPU 가속 추론 및 인메모리 모델 캐싱(`_LOCAL_LLMS`)
72
+ - **설정 풀(Pool) 기반 모델 프로필 관리**:
73
+ - `llmpool.yml` 및 `config.yml`을 통해 모델명, 토큰 수(`max_tokens`), 온도(`temperature`), 타임아웃, 컨텍스트 크기(`n_ctx`), 스레드 수(`n_threads`), GPU 레이어(`n_gpu_layers`) 등 동적 구성
74
+ - **자동 장애 복구 (Auto Failover)**:
75
+ - `provider: auto` 설정 시 외부 LLM API 호출 실패 시 로컬 GGUF 모델로 무중단 자동 전환
76
+ - **추론 예외 통일 관리 (`LlmInferenceError`)**:
77
+ - API 키 누락, 타임아웃, 모델 로드 실패 등에 대한 통합 예외 처리
78
+
79
+ ---
80
+
81
+ ## 🛠️ 사용 예시 (Usage Examples)
82
+
83
+ ### 1. 전역 `config` 점 표기법 및 타입 보증 활용
84
+ ```python
85
+ from agent_common.config_loader import config
86
+
87
+ # 1) 타입 접미사에 따른 자동 형 변환 보증
88
+ max_workers: int = config.transfer.max_workers_int # int 타입 보증
89
+ prefix: str = config.gcs.prefix_str # str 타입 및 .strip() 정제 보증
90
+ is_ecscopy: bool = config.gcs.ecscopy_bool # bool 타입 보증
91
+
92
+ # 2) 계층적 속성 접근
93
+ ecs_url: str = config.ecs.endpoint_url
94
+ table_id: str = config.bigquery.table_id
95
+ ```
96
+
97
+ ### 2. ToolParser를 통한 동적 룰 평가
98
+ ```python
99
+ from agent_common.tool_parser import ToolParser
100
+
101
+ # ToolParser 인스턴스 생성 (설정 파일 기반으로 내장/로컬 Tool 자동 탐색)
102
+ tool_parser = ToolParser()
103
+
104
+ # 컨텍스트 데이터 준비
105
+ context_dict = {
106
+ "ecs": {"key": "/unstr_data/PAK/contentInfo/orgfile/20260804/12345.html.json"},
107
+ "contentInfo": {"enddate": "2024-12-31"},
108
+ "sys": tool_parser.build_sys_context(),
109
+ }
110
+
111
+ # 1) 도구 함수 호출 템플릿 평가
112
+ date_code = tool_parser.eval("{code.date_check_to_code(contentInfo.enddate)}", context_dict)
113
+ # -> "09" (만료 판정)
114
+
115
+ # 2) 네임스페이스 및 내장 일시 템플릿 평가
116
+ today_val = tool_parser.eval("{sys.today}", context_dict)
117
+ # -> "20260824"
118
+ ```
119
+
120
+ ### 3. ProgressTracker 실시간 진행률 추적
121
+ ```python
122
+ from agent_common.utils import ProgressTracker
123
+ from agent_common.logger import ProjectLogger
124
+
125
+ logger = ProjectLogger("MyTask")
126
+ tracker = ProgressTracker(total_items_int=1000, logger_obj=logger, item_name_str="파일")
127
+
128
+ for file_info in file_list:
129
+ try:
130
+ # 처리 로직 수행
131
+ tracker.increment_success(bytes_int=len(data))
132
+ except Exception as e:
133
+ tracker.increment_failure(error_msg_str=str(e))
134
+
135
+ # 최종 결과 요약 리포트 출력
136
+ tracker.log_summary()
137
+ ```
138
+
139
+ ### 4. LlmClient를 통한 통합 텍스트/SQL 생성
140
+ ```python
141
+ from agent_common.llm import LlmClient
142
+
143
+ # 1) 설정 풀에 정의된 모델명 또는 용도로 클라이언트 초기화
144
+ llm_client = LlmClient(purpose="sql_generator")
145
+
146
+ # 2) 프롬프트 기반 텍스트 생성 (외부 API -> 로컬 GGUF 자동 폴백)
147
+ prompt_str = "사용자 요청: 2026년 8월 일일 가입자 수 통계 쿼리를 작성해줘."
148
+ response_str = llm_client.generate(
149
+ prompt=prompt_str,
150
+ system_prompt="당신은 BigQuery 전문 SQL 생성 AI입니다."
151
+ )
152
+
153
+ print(f"생성된 결과 ({llm_client.last_generated_by}):\n{response_str}")
154
+ ```
155
+
156
+ ---
157
+
158
+ ## 🚀 설치 및 빌드 방법
159
+
160
+ ### 📦 Wheel 패키지 빌드 (.whl 생성)
161
+
162
+ 새로운 버전으로 패키징하여 `.whl` 파일을 빌드할 경우 `scripts/build_agent_common_whl.py` 또는 `agent_common` 디렉터리 내에서 아래 명령을 실행합니다.
163
+
164
+ #### 1. 사내 폐쇄망 환경 (인터넷 차단, 완전히 오프라인 빌드)
165
+ 외부 PyPI 접속을 완전히 차단하기 위해 `--no-index`, `--no-build-isolation`, `--no-deps` 옵션을 지정합니다.
166
+
167
+ ```bash
168
+ # 루트 디렉터리에서 자동 빌드 스크립트 실행 (권장)
169
+ python scripts/build_agent_common_whl.py
170
+
171
+ # 또는 pip wheel 직접 실행
172
+ pip wheel ./agent_common --no-index --no-build-isolation --no-deps -w whls/
173
+ ```
174
+
175
+ #### 2. 인터넷 연동망 환경 (온라인 빌드)
176
+
177
+ ```bash
178
+ # pip wheel 이용
179
+ pip wheel ./agent_common --no-deps -w whls/
180
+
181
+ # 또는 build 모듈 이용
182
+ python -m build agent_common --wheel -o whls/
183
+ ```
184
+
185
+ ### Wheel 패키지 설치
186
+ ```bash
187
+ # 개발 환경 (Editable 모드)
188
+ pip install -e agent_common
189
+
190
+ # 배포 환경 (Wheel 패키지 설치)
191
+ pip install dist/agent_common-0.4.22-py3-none-any.whl
192
+ ```
193
+
194
+ ### PyPI 공공 배포 가이드
195
+ 본 패키지는 표준 `src/` 레이아웃으로 구성되어 소스 배포판(`sdist`) 및 휠(`wheel`) 파일 용량이 약 50KB 수준으로 최소화되어 있습니다.
196
+
197
+ ```bash
198
+ # 1. 빌드 도구 설치
199
+ pip install build twine
200
+
201
+ # 2. 패키지 빌드 (sdist 및 wheel 동시 생성)
202
+ python -m build
203
+
204
+ # 3. 배포 아카이브 검증
205
+ python -m twine check dist/*
206
+
207
+ # 4. PyPI 업로드
208
+ python -m twine upload dist/agent_common-0.4.22*
209
+ ```
210
+
211
+ ---
212
+
213
+ ## 📋 버전 변경 이력 (Changelog)
214
+
215
+ 자세한 버전 변경 이력은 [CHANGELOG.md](CHANGELOG.md) 파일을 참고하세요.
@@ -0,0 +1,204 @@
1
+ # agent_common 패키지
2
+
3
+ 중앙 에이전트 및 데이터 이관/생성 서비스를 위한 공통 로깅, 설정 로더, 인프라 클라이언트, 동적 도구(Tool) 파서 및 에러 처리 라이브러리 패키지입니다.
4
+
5
+ ---
6
+
7
+ ## 📌 주요 제공 기능
8
+
9
+ ### 1. 설정 로더 및 불변 설정 객체 (`agent_common.config_loader`)
10
+ - **계층적 YAML 설정 해석 및 병합 (Deep Merge)**: 패키지 기본 설정(`agent_common/config/*.yml`)과 개별 프로젝트 설정(`config/*.yml`) 동적 병합.
11
+ - **불변 점 표기법 조회 (`ReadOnlyConfig`)**: `config.ecs.endpoint_url`, `config.transfer.max_workers_int` 형태로 직관적 속성 접근 및 런타임 변조 방지.
12
+ - **타입 접미사 자동 형 변환 및 타입 보증 (Type Guarantee & Coercion - v0.4.14)**:
13
+ - `_int`: `int` 정수형 자동 형 변환 및 보증
14
+ - `_float`: `float` 실수형 자동 형 변환 및 보증
15
+ - `_bool`: `bool` 불리언형 자동 변환 (`"true"`, `"false"`, `1`, `0` 등 완벽 대응)
16
+ - `_str`: `str` 문자열 변환 및 `.strip()` 공백 자동 정제
17
+ - `_list` / `_dict`: 리스트 / 불변 딕셔너리(`ReadOnlyConfig`) 래핑 보증
18
+ - **Fail-Fast 필수 설정 검증 (`require_setting()`)**: 프로그램 시작 시 필수 설정값 누락 시 상세 원인 출력 후 프로세스 즉시 종료.
19
+ - **네트워크 프록시 제어**: `proxy.no_proxy` 설정의 `NO_PROXY` 환경변수 자동 반영.
20
+ - **설정 파일 템플릿 보정 (`ensure_config_file()`)**: 프로젝트 설정 누락 시 기본 스키마 기반 자동 생성 및 자가 치유(Self-healing).
21
+
22
+ ### 2. 단일 행 로깅 포매터 및 로거 (`agent_common.logger`)
23
+ - `SingleLineFlattenFormatter`: 모든 로그 및 Traceback 예외 메시지를 1줄로 평탄화하여 중앙 로그 수집(Logstash, Fluentd 등)에 최적화
24
+ - `ProjectLogger`: 콘솔 및 파일 로그 핸들러 동적 생성 및 일자별 로그 분리 관리
25
+ - **프로그램별 차등 로깅 레벨 지원 (`logging.level.<app_name>`)**: 설정 파일에서 프로그램별로 세분화된 로그 레벨 지정 지원
26
+ - `logging_messages.yml` 사전 기반 한글 포맷 템플릿 연동 로깅 지원
27
+
28
+ ### 3. 스토리지 및 데이터베이스 클라이언트 (`agent_common.clients`)
29
+ - `EcsClient`: Dell ECS S3 저장소 접속, 목록 조회, 메타데이터 해석 및 파일 메모리 스트리밍 획득
30
+ - `GcsClient`: Google Cloud Storage 연결, 파일 존재 검증 및 대용량 멀티스레드 스트리밍 업로드
31
+ - `BigQueryClient`: Google Cloud BigQuery 연결, JSON 데이터 스트리밍 입력(`insert_rows_json`), 배치 로드(`load_table_from_json_data`), 인라인 MERGE(`merge_table_from_json_data` - 한글/특수문자/예약어 컬럼 백틱 지원 및 413 방지 기본 청크 100건 분할), 범용 SQL 쿼리(`query`)
32
+
33
+ ### 4. 동적 도구 로더 및 템플릿 평가기 (`agent_common.tool_parser`) & 내장 도구 (`agent_common.tool`)
34
+ - **이원화된 Tool 디렉터리 계층 탐색**:
35
+ - **1순위 (내장 도구)**: `agent_common/tool/` 하위 모듈 (전사 표준 내장 도구)
36
+ - **2순위 (프로젝트 도구)**: `config.yml`의 `transfer.tool_dir`에 지정된 로컬 경로 (예: `medallion/tool/`)
37
+ - **선언적 템플릿 치환 및 표현식 평가 (`ToolParser.eval`)**:
38
+ - 변수 네임스페이스 바인딩: `{ecs.key}`, `{sys.today}`, `{json.title}`
39
+ - 동적 도구 함수 호출: `"{code.date_check_to_code(contentInfo.enddate)}"`, `"{path.get_json_name(ecs.key)}"`
40
+ - 문자열 슬라이싱/메서드: `"{raw_key.lstrip('/')}"`, `"{raw_size|0}"`
41
+ - **안전한 네임스페이스 탐색 (`_SafeNamespace`)**:
42
+ - 대소문자 무관 탐색 및 누락된 필드에 대해 KeyError 없이 안전하게 빈 문자열(`""`) 반환
43
+ - **내장 공통 도구 (`agent_common.tool.date.DateTimeUtils`)**:
44
+ - `get_today_yyyymmdd()`: `YYYYMMDD` 형식 8자리 일자 반환 (예: `20260824`)
45
+ - `get_now_compact()`: `YYYYMMDDHHMMSS` 형식 14자리 압축 일시 반환 (예: `20260824110500`)
46
+ - `get_now_formatted(fmt)`: `YYYY-MM-DD HH:MM:SS+09:00` 표준 KST 포맷 일시 반환
47
+ - **시스템 컨텍스트 스키마 (`agent_common.schemas.sys.json`)**:
48
+ - `{sys.today}`, `{sys.now_compact}`, `{sys.timestamp_compact}`, `{sys.env}` 등 기본 자동 제공
49
+
50
+ ### 5. 진행률 트래커 및 공용 유틸리티 (`agent_common.utils`)
51
+ - `ProgressTracker`: 멀티스레드 실시간 진행률 추적(`[N/Total] (P%)`), 처리 속도 및 남은 시간 예측, 마일스톤 경고 승격 로깅, 최종 요약 리포트(Summary Report) 생성
52
+ - `DateTimeUtils`: 전역 일시 헬퍼 함수군
53
+
54
+ ### 6. 공용 에러 및 예외 핸들러 (`agent_common.error_handler`)
55
+ - 네트워크 장애, 설정 오류, 런타임 예외에 대한 일관된 로깅 및 핸들링 제공
56
+
57
+ ### 7. 통합 LLM 클라이언트 및 추론 엔진 (`agent_common.llm`)
58
+ - **다중 프로바이더 통합 지원 (`LlmClient`)**:
59
+ - **외부 LLM API**: OpenAI 호환 표준 API (`/chat/completions`) 및 Fabrix 전용 API 형식 지원
60
+ - **로컬 GGUF 모델**: `llama-cpp-python` 기반 로컬 CPU/GPU 가속 추론 및 인메모리 모델 캐싱(`_LOCAL_LLMS`)
61
+ - **설정 풀(Pool) 기반 모델 프로필 관리**:
62
+ - `llmpool.yml` 및 `config.yml`을 통해 모델명, 토큰 수(`max_tokens`), 온도(`temperature`), 타임아웃, 컨텍스트 크기(`n_ctx`), 스레드 수(`n_threads`), GPU 레이어(`n_gpu_layers`) 등 동적 구성
63
+ - **자동 장애 복구 (Auto Failover)**:
64
+ - `provider: auto` 설정 시 외부 LLM API 호출 실패 시 로컬 GGUF 모델로 무중단 자동 전환
65
+ - **추론 예외 통일 관리 (`LlmInferenceError`)**:
66
+ - API 키 누락, 타임아웃, 모델 로드 실패 등에 대한 통합 예외 처리
67
+
68
+ ---
69
+
70
+ ## 🛠️ 사용 예시 (Usage Examples)
71
+
72
+ ### 1. 전역 `config` 점 표기법 및 타입 보증 활용
73
+ ```python
74
+ from agent_common.config_loader import config
75
+
76
+ # 1) 타입 접미사에 따른 자동 형 변환 보증
77
+ max_workers: int = config.transfer.max_workers_int # int 타입 보증
78
+ prefix: str = config.gcs.prefix_str # str 타입 및 .strip() 정제 보증
79
+ is_ecscopy: bool = config.gcs.ecscopy_bool # bool 타입 보증
80
+
81
+ # 2) 계층적 속성 접근
82
+ ecs_url: str = config.ecs.endpoint_url
83
+ table_id: str = config.bigquery.table_id
84
+ ```
85
+
86
+ ### 2. ToolParser를 통한 동적 룰 평가
87
+ ```python
88
+ from agent_common.tool_parser import ToolParser
89
+
90
+ # ToolParser 인스턴스 생성 (설정 파일 기반으로 내장/로컬 Tool 자동 탐색)
91
+ tool_parser = ToolParser()
92
+
93
+ # 컨텍스트 데이터 준비
94
+ context_dict = {
95
+ "ecs": {"key": "/unstr_data/PAK/contentInfo/orgfile/20260804/12345.html.json"},
96
+ "contentInfo": {"enddate": "2024-12-31"},
97
+ "sys": tool_parser.build_sys_context(),
98
+ }
99
+
100
+ # 1) 도구 함수 호출 템플릿 평가
101
+ date_code = tool_parser.eval("{code.date_check_to_code(contentInfo.enddate)}", context_dict)
102
+ # -> "09" (만료 판정)
103
+
104
+ # 2) 네임스페이스 및 내장 일시 템플릿 평가
105
+ today_val = tool_parser.eval("{sys.today}", context_dict)
106
+ # -> "20260824"
107
+ ```
108
+
109
+ ### 3. ProgressTracker 실시간 진행률 추적
110
+ ```python
111
+ from agent_common.utils import ProgressTracker
112
+ from agent_common.logger import ProjectLogger
113
+
114
+ logger = ProjectLogger("MyTask")
115
+ tracker = ProgressTracker(total_items_int=1000, logger_obj=logger, item_name_str="파일")
116
+
117
+ for file_info in file_list:
118
+ try:
119
+ # 처리 로직 수행
120
+ tracker.increment_success(bytes_int=len(data))
121
+ except Exception as e:
122
+ tracker.increment_failure(error_msg_str=str(e))
123
+
124
+ # 최종 결과 요약 리포트 출력
125
+ tracker.log_summary()
126
+ ```
127
+
128
+ ### 4. LlmClient를 통한 통합 텍스트/SQL 생성
129
+ ```python
130
+ from agent_common.llm import LlmClient
131
+
132
+ # 1) 설정 풀에 정의된 모델명 또는 용도로 클라이언트 초기화
133
+ llm_client = LlmClient(purpose="sql_generator")
134
+
135
+ # 2) 프롬프트 기반 텍스트 생성 (외부 API -> 로컬 GGUF 자동 폴백)
136
+ prompt_str = "사용자 요청: 2026년 8월 일일 가입자 수 통계 쿼리를 작성해줘."
137
+ response_str = llm_client.generate(
138
+ prompt=prompt_str,
139
+ system_prompt="당신은 BigQuery 전문 SQL 생성 AI입니다."
140
+ )
141
+
142
+ print(f"생성된 결과 ({llm_client.last_generated_by}):\n{response_str}")
143
+ ```
144
+
145
+ ---
146
+
147
+ ## 🚀 설치 및 빌드 방법
148
+
149
+ ### 📦 Wheel 패키지 빌드 (.whl 생성)
150
+
151
+ 새로운 버전으로 패키징하여 `.whl` 파일을 빌드할 경우 `scripts/build_agent_common_whl.py` 또는 `agent_common` 디렉터리 내에서 아래 명령을 실행합니다.
152
+
153
+ #### 1. 사내 폐쇄망 환경 (인터넷 차단, 완전히 오프라인 빌드)
154
+ 외부 PyPI 접속을 완전히 차단하기 위해 `--no-index`, `--no-build-isolation`, `--no-deps` 옵션을 지정합니다.
155
+
156
+ ```bash
157
+ # 루트 디렉터리에서 자동 빌드 스크립트 실행 (권장)
158
+ python scripts/build_agent_common_whl.py
159
+
160
+ # 또는 pip wheel 직접 실행
161
+ pip wheel ./agent_common --no-index --no-build-isolation --no-deps -w whls/
162
+ ```
163
+
164
+ #### 2. 인터넷 연동망 환경 (온라인 빌드)
165
+
166
+ ```bash
167
+ # pip wheel 이용
168
+ pip wheel ./agent_common --no-deps -w whls/
169
+
170
+ # 또는 build 모듈 이용
171
+ python -m build agent_common --wheel -o whls/
172
+ ```
173
+
174
+ ### Wheel 패키지 설치
175
+ ```bash
176
+ # 개발 환경 (Editable 모드)
177
+ pip install -e agent_common
178
+
179
+ # 배포 환경 (Wheel 패키지 설치)
180
+ pip install dist/agent_common-0.4.22-py3-none-any.whl
181
+ ```
182
+
183
+ ### PyPI 공공 배포 가이드
184
+ 본 패키지는 표준 `src/` 레이아웃으로 구성되어 소스 배포판(`sdist`) 및 휠(`wheel`) 파일 용량이 약 50KB 수준으로 최소화되어 있습니다.
185
+
186
+ ```bash
187
+ # 1. 빌드 도구 설치
188
+ pip install build twine
189
+
190
+ # 2. 패키지 빌드 (sdist 및 wheel 동시 생성)
191
+ python -m build
192
+
193
+ # 3. 배포 아카이브 검증
194
+ python -m twine check dist/*
195
+
196
+ # 4. PyPI 업로드
197
+ python -m twine upload dist/agent_common-0.4.22*
198
+ ```
199
+
200
+ ---
201
+
202
+ ## 📋 버전 변경 이력 (Changelog)
203
+
204
+ 자세한 버전 변경 이력은 [CHANGELOG.md](CHANGELOG.md) 파일을 참고하세요.
@@ -0,0 +1,20 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "agent_common"
7
+ version = "0.4.22"
8
+ description = "중앙 에이전트 및 하위 SQL 생성 서비스를 위한 공통 로깅/설정 모듈"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ dependencies = [
12
+ "pyyaml>=6.0",
13
+ "requests"
14
+ ]
15
+
16
+ [tool.setuptools.packages.find]
17
+ where = ["src"]
18
+
19
+ [tool.setuptools.package-data]
20
+ agent_common = ["*.yml", "config/*.yml", "schemas/*.json", "tool/**/*.py"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+