Skip to main content

agent_common

📦 PyPI 패키지 · 💻 GitHub 소스 및 매뉴얼

KO 한국어 | EN English | ZH 中文 | JA 日本語


agent_common 패키지 (한국어)

중앙 에이전트 및 데이터 이관/생성 서비스를 위한 공통 로깅, 설정 로더, 인프라 클라이언트, 동적 도구(Tool) 파서 및 에러 처리 라이브러리 패키지입니다.


📌 주요 제공 기능

1. 설정 로더 및 불변 설정 객체 (agent_common.config_loader)

  • 1.1. 계층적 YAML 설정 해석 및 병합 (Deep Merge): 패키지 기본 설정(agent_common/config/*.yml)과 개별 프로젝트 설정(config/*.yml) 동적 병합.
  • 1.2. 불변 점 표기법 조회 (ReadOnlyConfig): config.ecs.endpoint_url, config.transfer.max_workers_int 형태로 직관적 속성 접근 및 런타임 변조 방지.
  • 1.3. 타입 접미사 자동 형 변환 및 타입 보증 (Type Guarantee & Coercion):
    • _int: int 정수형 자동 형 변환 및 보증
    • _float: float 실수형 자동 형 변환 및 보증
    • _bool: bool 불리언형 자동 변환 및 타입 보증 (파이썬 bool 또는 대소문자 무관 "true", "false" 지원, 0, 1 등 비지원 값 유입 시 Fail-Fast 차단)
    • _str: str 문자열 변환 및 .strip() 공백 자동 정제
    • _list / _dict: 리스트 / 불변 딕셔너리(ReadOnlyConfig) 래핑 보증
    • 범용 함수 coerce_type_by_key_suffix 및 중첩 딕셔너리 일괄 변환 coerce_dict_by_key_suffix 제공으로 임의의 외부 설정 파일(rule.yml, mapping.yml 등) 및 데이터 파이프라인 완벽 지원
    • 타입 불일치 시 침묵하지 않고 상세 안내와 함께 즉시 조기 실패(Fail-Fast, ValueError/TypeError) 발생 보증
  • 1.4. Fail-Fast 필수 설정 검증 (require_setting()): 프로그램 시작 시 필수 설정값 누락 시 상세 원인 출력 후 프로세스 즉시 종료.
  • 1.5. 네트워크 프록시 제어 (_apply_no_proxy): proxy.no_proxy 설정의 NO_PROXY 환경변수 자동 반영.
  • 1.6. 모든 상수의 설정 파일화 및 템플릿 보정 (ensure_config_file()): 코드 내 모든 상수의 설정 파일화(외부화), config.yml 자동 생성 및 누락 상수 강제 주입·보정. agent_common 클래스의 기본 설정은 config_loader.config_file_auto_repair_dict에서 true로 켠 클래스만 기록.

2. 단일 행 로깅 포매터 및 로거 (agent_common.logger)

3. 스토리지 및 데이터베이스 클라이언트 (agent_common.clients)

  • 3.1. AWS S3 및 Dell ECS 오브젝트 스토리지 클라이언트 (S3Client): AWS S3 및 Dell ECS(S3 호환) 저장소 접속, 초기화 즉시 head_bucket Fail-Fast 검증, 대용량 페이징 제너레이터(list_objects), 메타데이터 빠른 조회(get_object_size), 메모리 스트리밍 획득(get_object_stream), GCS 실시간 파일 전송 및 동일 파일 스마트 스킵(transfer_to_gcs).
  • 3.2. Google Cloud Storage 스트리밍 클라이언트 및 멀티 계층 인증 (GcsClient): 4단계 GCP 인증 우선순위(GOOGLE_APPLICATION_CREDENTIALS_JSON 인메모리 JSON -> GOOGLE_APPLICATION_CREDENTIALS 파일 -> credentials_path_str -> Google ADC) 지원, 연결 및 버킷 권한 조기 검증, 블롭 메타데이터 및 크기 조회(get_blob_size), 메모리 낭비 없는 청크 단위 스트림 직접 업로드(upload_stream).
  • 3.3. BigQuery 배치 및 스트리밍 적재 클라이언트 (BigQueryClient): 연결 및 테이블 스키마 사전 캐싱(get_table), JSON 배치 로드 Job(load_table_from_json_data) 및 중첩 에러(errors, location, reason) 상세 분해, 실시간 스트리밍 인서트(insert_rows_json_data), 범용 동기 SQL 쿼리(query), 중복 전송 방지용 기존 키 집합 추출(get_existing_keys), 기존 레코드 메타데이터 일괄 조회(get_existing_records_metadata).
  • 3.4. BigQuery 고성능 인라인 MERGE (Upsert) 쿼리 엔진 (merge_table_from_json_data): 스테이징 임시 테이블 생성 없이 직접 UNNEST(JSON_QUERY_ARRAY(@json_payload)) 기반 인라인 MERGE INTO 수행, 기본키(PK) 기준 자동 UPDATE/INSERT 분기, 생성일시 등 최초 값 보존(preserve_columns_list), 컬럼 데이터 타입 자동 추론 및 명시적 캐스팅(column_types_dict), 한글/특수문자/예약어 백틱(`) 완벽 보호, HTTP 413 페이로드 초과 방지 기본 100건 청크 자동 분할.
  • 3.5. BigQuery TIMESTAMP·DATETIME 일시 문자열 변환 (convert_to_bigquery_timestamp, convert_to_bigquery_datetime): ISO 8601, 공백 구분, 14자리/8자리 숫자 등 다양한 원천 날짜 문자열을 TIMESTAMP 컬럼용(타임존 오프셋 포함, 우선순위 timezone_offset_str)과 DATETIME 컬럼용(오프셋 없는 벽시계 시각 YYYY-MM-DD HH:MM:SS) 표준 문자열로 정규화.
  • 3.6. GCP 서비스 계정 인증 해석기 (GcpCredentialResolver): 4단계 우선순위(환경변수 JSON → 환경변수 파일 경로 → 설정 파일 경로 → ADC)에 따른 GCP 인증 해석을 전담하는 독립 클래스. GcsClient·BigQueryClient가 합성(Composition)으로 사용하며, 그 외 GCP 서비스에서도 단독으로 재사용 가능.

4. 동적 도구 로더 및 템플릿 평가기 (agent_common.tool_parser) & 내장 도구 (agent_common.tool)

5. 진행률 트래커, 테이블 포매터 및 시간 유틸리티 (agent_common.progress_tracker, agent_common.table_formatter, agent_common.time_utils)

6. 공용 에러 및 예외 핸들러 (agent_common.error_handler)

  • 네트워크 장애, 설정 오류, 런타임 예외에 대한 일관된 로깅 및 핸들링 제공.

7. 통합 LLM 클라이언트 및 추론 엔진 (agent_common.llm)

8. 언어 로컬라이저 (agent_common.localizer)


🛠️ 사용 예시 (Usage Examples)

1. 전역 config 점 표기법 및 타입 보증 활용

from agent_common.config_loader import config

# 1) 타입 접미사에 따른 자동 형 변환 보증
max_workers: int = config.transfer.max_workers_int       # int 타입 보증
host: str = config.database.host_str                     # str 타입 및 .strip() 정제 보증
is_active: bool = config.transfer.is_active_bool         # bool 타입 보증

# 2) 계층적 속성 접근
api_url: str = config.services.api_endpoint_url
db_port: int = config.database.port_int

2. ToolParser를 통한 동적 룰 평가

from agent_common.tool_parser import ToolParser

tool_parser = ToolParser()

context_dict = {
    "storage": {"key": "/data/incoming/20260804/sample_document.json"},
    "document": {"expiry_date": "2024-12-31"},
    "sys": tool_parser.build_sys_context(),
}

# 1) 도구 함수 호출 템플릿 평가
date_val = tool_parser.eval("{date.get_today_yyyymmdd()}", context_dict)

# 2) 네임스페이스 및 내장 일시 템플릿 평가
today_val = tool_parser.eval("{sys.today}", context_dict)

3. ProgressTracker 실시간 진행률 추적

from agent_common import ProgressTracker
from agent_common.logger import ProjectLogger

logger = ProjectLogger("MyTask")
tracker = ProgressTracker(total_items_int=1000, logger_obj=logger, item_name_str="파일")

for file_info in file_list:
    try:
        tracker.increment_success(bytes_int=len(data))
    except Exception as e:
        tracker.increment_failure(error_msg_str=str(e))

tracker.log_summary()

4. LlmClient를 통한 통합 텍스트/SQL 생성

from agent_common.llm import LlmClient

llm_client = LlmClient(purpose_str="sql_generator")
response_str = llm_client.generate(
    prompt_str="사용자 요청: 2026년 8월 일일 가입자 수 통계 쿼리를 작성해줘.",
    system_prompt_str="당신은 BigQuery 전문 SQL 생성 AI입니다."
)
print(f"생성된 결과 ({llm_client.last_generated_by_str}):\n{response_str}")

5. 스토리지 및 BigQuery 클라이언트 활용

from agent_common.clients import S3Client, GcsClient, BigQueryClient

# S3 -> GCS 스마트 전송
s3_client = S3Client(bucket_name_str="source-lake")
gcs_client = GcsClient(bucket_name_str="target-lake")

for obj in s3_client.list_objects(prefix_str="raw/events/"):
    s3_client.transfer_to_gcs(
        gcs_client_obj=gcs_client,
        s3_key_str=obj["Key"],
        gcs_blob_name_str=f"lake/{obj['Key'].lstrip('/')}",
        size_int=obj["Size"],
    )

# BigQuery 인라인 MERGE (Upsert)
bq_client = BigQueryClient(project_id_str="my-project", dataset_id_str="dw", table_id_str="tb_user")
bq_client.merge_table_from_json_data(
    json_data_any=[{"user_id": "U01", "name": "홍길동", "created_at": "2026-01-01 00:00:00+09:00"}],
    pk_key_str="user_id",
    preserve_columns_list=["created_at"],
)

6. GcpCredentialResolver로 다른 GCP 서비스 인증하기

from google.cloud import pubsub_v1

from agent_common import ConfigLoader, GcpCredentialResolver

# 환경변수 JSON → 환경변수 파일 경로 → 지정 경로 순으로 해석하고, 모두 없으면 None(ADC)을 반환
credentials = GcpCredentialResolver(
    credentials_path_str="config/secrets/gcp_sa_key.json",
    config_loader_obj=ConfigLoader(),
).resolve()

# GCS·BigQuery 외의 GCP 클라이언트에도 그대로 전달
publisher_client = pubsub_v1.PublisherClient(credentials=credentials)

📖 상세 기능 매뉴얼 (User Manuals)

번호 모듈 / 주제 상세 매뉴얼 링크 주요 내용 요약
1.1 계층적 YAML 해석 & 딥 머지 01_hierarchical_yaml_merge_ko.md 5단계 계층 병합 순서, _deep_merge 재귀 알고리즘, 루트 디렉터리 자동 탐색
1.2 불변 점 표기법 조회 (ReadOnlyConfig) 02_readonly_dot_notation_ko.md 점 표기법 속성 접근, 런타임 변조 원천 차단(Read-Only), 불변 객체 설계
1.3 타입 접미사 자동 형 변환 & 타입 보증 03_type_coercion_and_guarantee_ko.md _int, _float, _bool, _str, _list, _dict 런타임 자동 캐스팅 및 타입 안전성 보증
1.4 Fail-Fast 필수 설정 검증 04_fail_fast_require_setting_ko.md 기동 초기 필수 설정 누락 감지, 상세 진단 로그 및 프로세스 안전 조기 종료
1.5 네트워크 프록시 제어 05_network_proxy_control_ko.md proxy.no_proxy 설정의 NO_PROXY 환경변수 자동 반영 및 내부 통신 프록시 우회
1.6 모든 상수의 설정 파일화 및 템플릿 보정 06_ensure_config_self_healing_ko.md 코드 내 모든 상수의 설정 파일화(외부화), config.yml 자동 생성 및 누락 상수 강제 주입·보정
2.1 단일 행 평탄화 포매터 & 원천 추적 01_single_line_flatten_formatter_ko.md SingleLineFlattenFormatter, [Origin: ...] 프레임 추출, 중앙 로그 수집기 연동 최적화
2.2 로깅 환경 일괄 구성 & 핸들러 제어 02_project_logger_configure_ko.md ProjectLogger.configure(), 콘솔/파일 핸들러 분기, 레벨별 파일 분리, 단일 표준 경로 템플릿
2.3 다국어 메시지 사전 & 코드 기반 로깅 03_multilingual_message_catalog_ko.md logging_messages_*.yml, 런타임 언어 전환, safe_kwargs 템플릿 치환
2.4 작업 통계 & 에러/제외 실시간 집계 04_execution_result_and_error_tracking_ko.md 성공/실패/제외(Skip) 3단계 상태 분류, 인스턴스 및 클래스 전역 멀티스레드 집계
2.5 작업 결과 요약 리포트 자동 생성 05_summary_report_generation_ko.md ProjectLogger.log_summary(), 80열 표준 요약 블록, 처리 속도/전송률, 에러 상세 해석
3.1 AWS S3 & Dell ECS 스토리지 연동 01_s3_ecs_storage_client_ko.md S3/ECS 연결, Fail-Fast 검증, 페이징 목록 조회, GCS 스트리밍 전송 및 동일 파일 스킵
3.2 GCS 스트리밍 업로드 & 4단계 인증 02_gcs_cloud_storage_client_ko.md 4단계 서비스 계정 인증 우선순위, 연결 검증, 메타데이터 조회, 메모리 파이프라인 업로드
3.3 BigQuery 배치 적재 & 스트리밍 인서트 03_bigquery_batch_and_streaming_load_ko.md JSON 배치 로드 Job vs 스트리밍 API, 중첩 에러 상세 분해, 중복 방지 키 집합 조회
3.4 BigQuery 인라인 MERGE (Upsert) 엔진 04_bigquery_inline_merge_upsert_ko.md 임시 테이블 없는 인라인 MERGE, UNNEST 파라미터 바인딩, 동적 타입 캐스팅, 100건 청크 분할
3.5 BigQuery TIMESTAMP·DATETIME 변환 05_bigquery_timestamp_and_datetime_conversion_ko.md ISO/압축 일시 정규화, 타임존 오프셋 결정 우선순위, 컬럼 타입별 메서드 선택 기준
3.6 GCP 서비스 계정 인증 해석기 06_gcp_credential_resolver_ko.md GcpCredentialResolver, 4단계 인증 우선순위, 다른 GCP 서비스에서의 단독 재사용, 합성(Composition) 구조
4.1 이원화된 Tool 디렉터리 계층 탐색 & 동적 로딩 01_dual_tool_hierarchy_discovery_ko.md 내장(1순위) vs 로컬(2순위) 탐색 계층, 3단계 함수 탐색, _tool_cache, 사전 검증
4.2 선언적 템플릿 치환 & 표현식 평가 02_declarative_template_eval_ko.md ToolParser.eval(), 도구 함수 직통 호출, 점(.) 네임스페이스 바인딩, 파이프(|) 폴백
4.3 안전한 네임스페이스 탐색 (_SafeNamespace) 03_safe_namespace_navigation_ko.md 점(.)/인덱스 통합 접근, 대소문자 무관 탐색, 누락 필드 "" 반환, 중첩 래핑
4.4 내장 공통 일시 도구 (DateTimeUtils) 04_builtin_datetime_utils_ko.md 테이블 룰/템플릿 전용 날짜 도구, YYYYMMDD, ISO 타임스탬프, 압축 일시 생성
5.1 호스트 타임존 감지 & 세계 표준시 해석 01_time_utils_and_timezone_resolution_ko.md TimeUtils, OS/컨테이너 타임존 감지, 전 세계 30여 개 표준시 해석, datetime 정규화
5.2 멀티스레드 실시간 진행률 추적 & 마일스톤 02_progress_tracker_and_milestones_ko.md ProgressTracker, 실시간 진행률(%), 처리 속도, ETA 계산, WARNING 승격 로깅
5.3 유니코드 전각 폭 계산 & 마크다운 표 칼맞춤 03_unicode_table_formatter_ko.md TableFormatter, 동아시아 문자 폭(east_asian_width) 정밀 계산, 마크다운 표 정렬
7.1 모델 프로필 관리 및 텍스트 생성 01_model_profiles_and_generation_ko.md agent_common.llm
7.2 외부 채팅 API 및 Fabrix 연동 02_external_api_and_fabrix_ko.md agent_common.llm
7.3 로컬 GGUF 추론 및 모델 캐싱 03_local_gguf_inference_ko.md agent_common.llm
7.4 실행 모드 및 조건부 로컬 전환 04_provider_and_local_fallback_ko.md agent_common.llm
7.5 추론 결과 및 예외 처리 05_inference_results_and_errors_ko.md agent_common.llm
7.6 Groq 감독관 AI 및 Antigravity Stop 훅 06_groq_supervisor_and_stop_hook_ko.md agent_common.llm
8.1 언어 코드 정규화 & 언어별 리소스 탐색 01_language_codes_and_resource_lookup_ko.md Localizer, 지원 언어 코드와 별칭, 언어 결정 우선순위, 언어별 파일 탐색 및 기본 언어 대체 규칙

🚀 설치 및 빌드 가이드 (Installation and Build Guide)

📦 Wheel 패키지 빌드 (.whl)

새로운 버전으로 패키징하여 .whl 파일을 빌드할 경우 scripts/build_agent_common_whl.py 또는 agent_common 디렉터리 내에서 아래 명령을 실행합니다.

1. 사내 폐쇄망 환경 (인터넷 차단, 완전히 오프라인 빌드)
# 루트 디렉터리에서 자동 빌드 스크립트 실행 (권장)
python scripts/build_agent_common_whl.py

# 또는 pip wheel 직접 실행
pip wheel ./agent_common --no-index --no-build-isolation --no-deps -w whls/
2. 인터넷 연동망 환경 (온라인 빌드)
# pip wheel 이용
pip wheel ./agent_common --no-deps -w whls/

# 또는 build 모듈 이용
python -m build agent_common --wheel -o whls/

Wheel 패키지 설치

# 개발 환경 (Editable 모드 - 기본 경량 설치)
pip install -e agent_common

# 개발 환경 (클라우드 클라이언트 extras 포함)
pip install -e "agent_common[clients]"

# 배포 환경 (Wheel 패키지 설치)
pip install dist/agent_common-0.4.99-py3-none-any.whl

🌐 PyPI 공식 배포 (관리자 전용)

# 1. 빌드 도구 최신화
pip install build twine

# 2. 패키지 빌드 (sdist 및 wheel 동시 생성)
python -m build

# 3. 배포 아카이브 검증
python -m twine check dist/*

# 4. PyPI 업로드
python -m twine upload dist/agent_common-0.4.99*

📋 버전 변경 이력 (Changelog)

전체 상세 버전 변경 이력은 CHANGELOG_KO.md 파일을 참고하세요.


agent_common Package (English)

A comprehensive Python common library providing unified logging, hierarchical configuration loaders, cloud and database infrastructure clients, dynamic tool parsers, and centralized error handling for enterprise agent services and data migration pipelines.


📌 Key Features

1. Configuration Loader & Immutable Config Object (agent_common.config_loader)

  • 1.1. Hierarchical YAML Parsing & Deep Merge: Dynamically merges base package configurations (agent_common/config/*.yml) with project-specific configurations (config/*.yml).
  • 1.2. Immutable Dot-Notation Access (ReadOnlyConfig): Intuitive attribute-based lookup (config.ecs.endpoint_url, config.transfer.max_workers_int) while preventing unintended runtime mutations.
  • 1.3. Type Guarantee & Automatic Coercion via Type Suffixes:
    • _int: Automatic integer conversion and type guarantee.
    • _float: Automatic floating-point conversion and type guarantee.
    • _bool: Strict boolean conversion and type guarantee (Python bool or case-insensitive "true", "false"; unsupported values like 0, 1 fail fast).
    • _str: Automatic string conversion and .strip() whitespace trimming.
    • _list / _dict: Guaranteed list / immutable dictionary (ReadOnlyConfig) wrapping.
    • Standalone functions coerce_type_by_key_suffix and recursive batch coercion coerce_dict_by_key_suffix for arbitrary external configuration files (rule.yml, mapping.yml) and data mappings.
    • Strict Fail-Fast guarantee: type-suffix mismatches immediately raise diagnostic exceptions (ValueError/TypeError) instead of silently falling back to raw values.
  • 1.4. Fail-Fast Required Setting Validation (require_setting()): Immediate process termination with diagnostic output if required settings are missing during startup.
  • 1.5. Network Proxy Control (_apply_no_proxy): Automatic synchronization of NO_PROXY environment variable from proxy.no_proxy configuration.
  • 1.6. Externalizing All Constants & Self-Healing Templates (ensure_config_file()): Materializing all in-code constants to configuration files, automatic scaffolding, and in-place missing key injection. Defaults of agent_common classes are written only for classes set to true in config_loader.config_file_auto_repair_dict.

2. Single-Line Log Formatter & Project Logger (agent_common.logger)

3. Storage and Database Infrastructure Clients (agent_common.clients)

  • 3.1. AWS S3 & Dell ECS Object Storage Client (S3Client): Connects to AWS S3 and Dell ECS (S3-compatible) storage, early head_bucket Fail-Fast verification, high-throughput paginated iterator (list_objects), fast header metadata lookup (get_object_size), in-memory streaming body extraction (get_object_stream), real-time streaming pipeline upload to GCS with smart duplicate skipping (transfer_to_gcs).
  • 3.2. Google Cloud Storage Streaming Client & Multi-Tier Auth (GcsClient): Four-tier GCP credential resolution hierarchy (GOOGLE_APPLICATION_CREDENTIALS_JSON in-memory JSON -> GOOGLE_APPLICATION_CREDENTIALS file -> credentials_path_str -> Google ADC), instant bucket reachability validation, blob metadata lookup (get_blob_size), zero-disk chunked streaming uploads (upload_stream).
  • 3.3. BigQuery Batch Loading & Streaming Ingestion (BigQueryClient): Fail-fast schema caching (get_table), JSON batch load jobs (load_table_from_json_data) with unpacked nested error diagnostics, real-time streaming ingestion (insert_rows_json_data), general SQL query execution (query), unique key deduplication set lookup (get_existing_keys).
  • 3.4. BigQuery High-Performance Inline MERGE (Upsert) Engine (merge_table_from_json_data): Executes direct inline MERGE INTO via UNNEST(JSON_QUERY_ARRAY(@json_payload)) without temporary staging tables, automatic primary key routing, original column preservation (preserve_columns_list), schema type inference and casting (column_types_dict), reserved keyword and Unicode column backtick escaping, HTTP 413 payload limit protection via default 100-row chunking.
  • 3.5. BigQuery TIMESTAMP and DATETIME String Conversion (convert_to_bigquery_timestamp, convert_to_bigquery_datetime): Normalizes ISO 8601, whitespace-separated, and 14-digit/8-digit date strings into standard strings for TIMESTAMP columns (with a time zone offset, precedence via timezone_offset_str) and for DATETIME columns (wall-clock YYYY-MM-DD HH:MM:SS without an offset).
  • 3.6. GCP Service Account Credential Resolver (GcpCredentialResolver): Standalone class dedicated to resolving GCP credentials by a four-tier precedence (environment JSON → environment file path → configured file path → ADC). Used by GcsClient and BigQueryClient through composition, and reusable on its own for other GCP services.

4. Dynamic Tool Loader & Template Evaluator (agent_common.tool_parser) & Built-in Tools (agent_common.tool)

5. Progress Tracker & Common Utilities (agent_common.progress_tracker, agent_common.table_formatter, agent_common.time_utils)

6. Common Error & Exception Handler (agent_common.error_handler)

  • Consistent exception logging and handling for network failures, configuration errors, and runtime exceptions.

7. Unified LLM Client & Inference Engine (agent_common.llm)

8. Language Localizer (agent_common.localizer)

  • 8.1. Language Code Normalization & Localized Resource Lookup (Localizer): Normalizes ISO 639-1 language codes (KO, EN, ZH, JA), decides the language from an explicit argument, the global setting, and environment variables, and finds per-language resource files named {prefix}_{language}.yml. Separate from logging, so it can be reused for any multilingual resource such as labels and notices.

🛠️ Usage Examples

1. Dot-Notation Global config & Type Guarantees

from agent_common.config_loader import config

# 1) Guaranteed type coercion via type suffixes
max_workers: int = config.transfer.max_workers_int       # Guaranteed int
host: str = config.database.host_str                     # Guaranteed str with .strip()
is_active: bool = config.transfer.is_active_bool         # Guaranteed bool

# 2) Hierarchical attribute access
api_url: str = config.services.api_endpoint_url
db_port: int = config.database.port_int

2. Dynamic Rule Evaluation via ToolParser

from agent_common.tool_parser import ToolParser

tool_parser = ToolParser()

context_dict = {
    "storage": {"key": "/data/incoming/20260804/sample_document.json"},
    "document": {"expiry_date": "2024-12-31"},
    "sys": tool_parser.build_sys_context(),
}

date_val = tool_parser.eval("{date.get_today_yyyymmdd()}", context_dict)
today_val = tool_parser.eval("{sys.today}", context_dict)

3. Real-time Progress Tracking with ProgressTracker

from agent_common import ProgressTracker
from agent_common.logger import ProjectLogger

logger = ProjectLogger("MyTask")
tracker = ProgressTracker(total_items_int=1000, logger_obj=logger, item_name_str="file")

for file_info in file_list:
    try:
        tracker.increment_success(bytes_int=len(data))
    except Exception as e:
        tracker.increment_failure(error_msg_str=str(e))

tracker.log_summary()

4. Unified Text/SQL Generation with LlmClient

from agent_common.llm import LlmClient

llm_client = LlmClient(purpose_str="sql_generator")
prompt_str = "User request: Generate daily subscriber statistics SQL for August 2026."
response_str = llm_client.generate(
    prompt_str=prompt_str,
    system_prompt_str="You are an expert AI for BigQuery SQL generation."
)
print(f"Generated result ({llm_client.last_generated_by_str}):\n{response_str}")

5. Storage and BigQuery Client Usage

from agent_common.clients import S3Client, GcsClient, BigQueryClient

# S3 -> GCS Smart Transfer
s3_client = S3Client(bucket_name_str="source-lake")
gcs_client = GcsClient(bucket_name_str="target-lake")

for obj in s3_client.list_objects(prefix_str="raw/events/"):
    s3_client.transfer_to_gcs(
        gcs_client_obj=gcs_client,
        s3_key_str=obj["Key"],
        gcs_blob_name_str=f"lake/{obj['Key'].lstrip('/')}",
        size_int=obj["Size"],
    )

# BigQuery Inline MERGE (Upsert)
bq_client = BigQueryClient(project_id_str="my-project", dataset_id_str="dw", table_id_str="tb_user")
bq_client.merge_table_from_json_data(
    json_data_any=[{"user_id": "U01", "name": "John Doe", "created_at": "2026-01-01 00:00:00+09:00"}],
    pk_key_str="user_id",
    preserve_columns_list=["created_at"],
)

6. Authenticating Other GCP Services with GcpCredentialResolver

from google.cloud import pubsub_v1

from agent_common import ConfigLoader, GcpCredentialResolver

# Resolves environment JSON -> environment file path -> given path, and returns None (ADC) when none apply
credentials = GcpCredentialResolver(
    credentials_path_str="config/secrets/gcp_sa_key.json",
    config_loader_obj=ConfigLoader(),
).resolve()

# Pass it straight to GCP clients other than GCS and BigQuery
publisher_client = pubsub_v1.PublisherClient(credentials=credentials)

📖 Detailed Feature Manuals

# Module / Topic User Manual Link Key Highlights
1.1 Hierarchical YAML Parsing & Deep Merge 01_hierarchical_yaml_merge_en.md 5-stage merge order, recursive _deep_merge algorithm, auto project root discovery
1.2 Immutable Dot-Notation Access (ReadOnlyConfig) 02_readonly_dot_notation_en.md Dot-notation attribute lookup, strict runtime mutation prevention (Read-Only)
1.3 Type Guarantee & Automatic Coercion 03_type_coercion_and_guarantee_en.md _int, _float, _bool, _str, _list, _dict runtime casting and type safety
1.4 Fail-Fast Required Setting Validation 04_fail_fast_require_setting_en.md Startup phase mandatory validation, diagnostic output, and fail-fast termination
1.5 Network Proxy Control 05_network_proxy_control_en.md Automatic synchronization of NO_PROXY from proxy.no_proxy configuration
1.6 Constant Externalization & Self-Healing Templates 06_ensure_config_self_healing_en.md Materializing all in-code constants, automatic scaffolding, and in-place missing key injection
2.1 Single-Line Formatter & Origin Tracking 01_single_line_flatten_formatter_en.md SingleLineFlattenFormatter, [Origin: ...] frame extraction, centralized log collector optimization
2.2 Batch Logging Setup & Handler Control 02_project_logger_configure_en.md ProjectLogger.configure(), console/file handler routing, level-based paths, unified path template
2.3 Multilingual Catalog & Code-Based Logging 03_multilingual_message_catalog_en.md logging_messages_*.yml, runtime language switching, safe template variable formatting
2.4 Result Telemetry & Error Classification 04_execution_result_and_error_tracking_en.md Success/Failure/Exclusion 3-tier classification, instance & class-global multithreaded counters
2.5 Automatic Summary Report Generation 05_summary_report_generation_en.md ProjectLogger.log_summary(), 80-column summary block, throughput/bandwidth, decoded error explanations
3.1 AWS S3 & Dell ECS Storage Integration 01_s3_ecs_storage_client_en.md S3/ECS connection, Fail-Fast verification, paginated listing, direct GCS streaming and duplicate skip
3.2 GCS Streaming Upload & 4-Tier Auth 02_gcs_cloud_storage_client_en.md 4-tier GCP credential precedence, connection validation, metadata retrieval, in-memory stream upload
3.3 BigQuery Batch Loading & Streaming Ingestion 03_bigquery_batch_and_streaming_load_en.md JSON batch load jobs vs streaming API, nested error diagnostics unpacking, deduplication key lookup
3.4 BigQuery Inline MERGE (Upsert) Engine 04_bigquery_inline_merge_upsert_en.md Pure inline MERGE without staging tables, UNNEST parameter binding, dynamic type casting, 100-row chunks
3.5 BigQuery TIMESTAMP & DATETIME Conversion 05_bigquery_timestamp_and_datetime_conversion_en.md ISO/compact datetime normalization, time zone offset precedence, choosing a method by column type
3.6 GCP Service Account Credential Resolver 06_gcp_credential_resolver_en.md GcpCredentialResolver, 4-tier credential precedence, standalone reuse for other GCP services, composition design
4.1 Dual Tool Hierarchy Discovery & Dynamic Loading 01_dual_tool_hierarchy_discovery_en.md Built-in (Priority 1) vs Local (Priority 2) discovery, 3-step function introspection, _tool_cache, scan_rules_for_tool_functions pre-flight validation
4.2 Declarative Template Evaluation & Expression Resolution 02_declarative_template_eval_en.md ToolParser.eval(), direct tool calls, dot-notation namespaces, pipe (|) fallbacks, signature-aware parameter binding, and automatic context injection
4.3 Safe Namespace Lookup & Case-Insensitive Access 03_safe_namespace_navigation_en.md _SafeNamespace, case-insensitive lookups, silent empty-string ("") fallback on missing keys, recursive nested collection wrapping
4.4 Built-in DateTime Tool (DateTimeUtils) 04_builtin_datetime_utils_en.md Business template formatting tool, TimeUtils delegation architecture, YYYYMMDD, BigQuery ISO timestamps, and compact datetime strings
5.1 System Timezone Detection & Global Timezone Resolution 01_time_utils_and_timezone_resolution_en.md TimeUtils, dynamic host OS/container timezone detection, 30+ global timezone abbreviation parser, timezone-aware datetime normalization
5.2 Multithreaded Progress Tracking & Milestone Telemetry 02_progress_tracker_and_milestones_en.md ProgressTracker, real-time percentage (%), throughput, ETA, standard INFO vs 10% milestone WARNING level elevation
5.3 Unicode East Asian Width Alignment & Table Formatter 03_unicode_table_formatter_en.md TableFormatter, precise East Asian character display width calculation, monospace and Markdown table vertical border alignment
7.1 Model Profiles and Text Generation 01_model_profiles_and_generation_en.md agent_common.llm
7.2 External Chat APIs and Fabrix 02_external_api_and_fabrix_en.md agent_common.llm
7.3 Local GGUF Inference and Model Caching 03_local_gguf_inference_en.md agent_common.llm
7.4 Provider Selection and Conditional Local Fallback 04_provider_and_local_fallback_en.md agent_common.llm
7.5 Inference Results and Error Handling 05_inference_results_and_errors_en.md agent_common.llm
7.6 Groq Supervisor and Antigravity Stop Hook 06_groq_supervisor_and_stop_hook_en.md agent_common.llm
8.1 Language Code Normalization & Localized Resource Lookup 01_language_codes_and_resource_lookup_en.md Localizer, supported language codes and aliases, language precedence, per-language file lookup with default-language fallback

🚀 Installation and Build Guide

📦 Wheel Package Build (.whl)

# Offline environment
python scripts/build_agent_common_whl.py

# Online environment
python -m build agent_common --wheel -o whls/

Installing the Wheel Package

# Development (Editable mode - lightweight core)
pip install -e agent_common

# Development (With cloud client extras)
pip install -e "agent_common[clients]"

# Production (Wheel package)
pip install dist/agent_common-0.4.99-py3-none-any.whl

🌐 Official PyPI Distribution (Maintainers Only)

# 1. Update build tools
pip install build twine

# 2. Build distributions (sdist & wheel)
python -m build

# 3. Validate distribution archives
python -m twine check dist/*

# 4. Upload to PyPI
python -m twine upload dist/agent_common-0.4.99*

📋 Version History (Changelog)

For detailed version history, please refer to CHANGELOG_EN.md.


agent_common 软件包 (中文)

面向企业级智能体(Agent)服务与数据迁移/生成管道的通用 Python 核心库,提供统一日志记录、分层配置加载、云端与数据库基础设施客户端、动态工具解析器及集中异常处理。


📌 核心功能

1. 配置加载器与不可变配置对象 (agent_common.config_loader)

  • 1.1. 分层 YAML 解析与深度合并 (Deep Merge): 动态合并包内置默认配置 (agent_common/config/*.yml) 与各独立项目配置 (config/*.yml)。
  • 1.2. 不可变点属性访问 (ReadOnlyConfig): 直观的点操作符属性访问 (config.ecs.endpoint_url, config.transfer.max_workers_int),彻底杜绝运行时配置意外篡改。
  • 1.3. 基于类型后缀的自动类型转换与类型保证:
    • _int: 自动整型转换与类型保证。
    • _float: 自动浮点型转换与类型保证。
    • _bool: 严格布尔型转换与类型保证(支持 Python bool 或不区分大小写的 "true"/"false",传入 0、1 等非布尔值时快速失败拦截)。
    • _str: 自动字符串转换与 .strip() 空格清理。
    • _list / _dict: 保证列表 / 不可变字典 (ReadOnlyConfig) 包装。
    • 提供独立函数 coerce_type_by_key_suffix 与嵌套字典批量转换 coerce_dict_by_key_suffix,全面支持任意外部配置文件 (rule.yml, mapping.yml) 和数据流。
    • 严格快速失败 (Fail-Fast) 保证:类型不匹配时立即抛出详细诊断异常 (ValueError/TypeError),绝不静默降级为原始值。
  • 1.4. 快速失败必需配置验证 (require_setting()): 程序启动阶段若缺少必要配置项,立即输出详细诊断日志并安全终止进程。
  • 1.5. 网络代理控制 (_apply_no_proxy): 自动将 proxy.no_proxy 配置同步至 NO_PROXY 环境变量,绕过内部通信代理。
  • 1.6. 常量外部化与自愈模板校正 (ensure_config_file()): 将代码中所有常量外部化为配置文件,自动生成 config.yml 并强制注入/补齐缺失的配置键。agent_common 各类的默认配置仅写入在 config_loader.config_file_auto_repair_dict 中设为 true 的类。

2. 单行日志格式化器与项目日志器 (agent_common.logger)

3. 存储与数据库基础设施客户端 (agent_common.clients)

4. 动态工具加载器与模板评估器 (agent_common.tool_parser) & 内置工具 (agent_common.tool)

5. 进度跟踪器、表格格式化器与时间工具 (agent_common.progress_tracker, agent_common.table_formatter, agent_common.time_utils)

6. 通用错误与异常处理器 (agent_common.error_handler)

  • 提供网络中断、配置缺失及运行时异常的一致日志记录与规范处理。

7. 统一 LLM 客户端与推理引擎 (agent_common.llm)

8. 语言本地化器 (agent_common.localizer)

  • 8.1. 语言代码规范化与多语言资源文件查找 (Localizer): 规范化 ISO 639-1 语言代码 (KO, EN, ZH, JA),基于显式参数、全局设置与环境变量决定语言,并查找 {前缀}_{语言}.yml 形式的多语言资源文件。与日志功能相互独立,可复用于标签、提示文案等任意多语言资源。

🛠️ 使用示例 (Usage Examples)

1. 点属性访问全局 config 与类型保证

from agent_common.config_loader import config

# 1) 基于类型后缀自动强制转换保证
max_workers: int = config.transfer.max_workers_int       # 保证 int 类型
host: str = config.database.host_str                     # 保证 str 类型并自动执行 .strip()
is_active: bool = config.transfer.is_active_bool         # 保证 bool 类型

# 2) 分层属性点访问
api_url: str = config.services.api_endpoint_url
db_port: int = config.database.port_int

2. 通过 ToolParser 动态评估规则

from agent_common.tool_parser import ToolParser

tool_parser = ToolParser()

context_dict = {
    "storage": {"key": "/data/incoming/20260804/sample_document.json"},
    "document": {"expiry_date": "2024-12-31"},
    "sys": tool_parser.build_sys_context(),
}

date_val = tool_parser.eval("{date.get_today_yyyymmdd()}", context_dict)
today_val = tool_parser.eval("{sys.today}", context_dict)

3. 使用 ProgressTracker 实时追踪进度

from agent_common import ProgressTracker
from agent_common.logger import ProjectLogger

logger = ProjectLogger("MyTask")
tracker = ProgressTracker(total_items_int=1000, logger_obj=logger, item_name_str="文件")

for file_info in file_list:
    try:
        tracker.increment_success(bytes_int=len(data))
    except Exception as e:
        tracker.increment_failure(error_msg_str=str(e))

tracker.log_summary()

4. 使用 LlmClient 进行统一文本/SQL生成

from agent_common.llm import LlmClient

llm_client = LlmClient(purpose_str="sql_generator")
prompt_str = "用户需求: 请编写统计 2026 年 8 月每日新增订阅用户数的 SQL 查询。"
response_str = llm_client.generate(
    prompt_str=prompt_str,
    system_prompt_str="你是一名精通 BigQuery SQL 编写的专业 AI 助手。"
)
print(f"生成结果 ({llm_client.last_generated_by_str}):\n{response_str}")

5. 存储与 BigQuery 客户端操作示例

from agent_common.clients import S3Client, GcsClient, BigQueryClient

# S3 -> GCS 智能流式传输
s3_client = S3Client(bucket_name_str="source-lake")
gcs_client = GcsClient(bucket_name_str="target-lake")

for obj in s3_client.list_objects(prefix_str="raw/events/"):
    s3_client.transfer_to_gcs(
        gcs_client_obj=gcs_client,
        s3_key_str=obj["Key"],
        gcs_blob_name_str=f"lake/{obj['Key'].lstrip('/')}",
        size_int=obj["Size"],
    )

# BigQuery 高性能内联 MERGE (Upsert)
bq_client = BigQueryClient(project_id_str="my-project", dataset_id_str="dw", table_id_str="tb_user")
bq_client.merge_table_from_json_data(
    json_data_any=[{"user_id": "U01", "name": "张三", "created_at": "2026-01-01 00:00:00+09:00"}],
    pk_key_str="user_id",
    preserve_columns_list=["created_at"],
)

6. 使用 GcpCredentialResolver 为其他 GCP 服务认证

from google.cloud import pubsub_v1

from agent_common import ConfigLoader, GcpCredentialResolver

# 按 环境变量 JSON → 环境变量文件路径 → 指定路径 的顺序解析,均不存在时返回 None (ADC)
credentials = GcpCredentialResolver(
    credentials_path_str="config/secrets/gcp_sa_key.json",
    config_loader_obj=ConfigLoader(),
).resolve()

# 可直接传给 GCS、BigQuery 以外的 GCP 客户端
publisher_client = pubsub_v1.PublisherClient(credentials=credentials)

📖 详细功能用户手册 (User Manuals)

编号 模块 / 主题 详细手册链接 核心要点说明
1.1 分层 YAML 解析 & 深度合并 01_hierarchical_yaml_merge_zh.md 5 阶段配置加载合并顺序,递归 _deep_merge 算法,项目根目录自动探测
1.2 不可变点属性访问 (ReadOnlyConfig) 02_readonly_dot_notation_zh.md 点属性操作符访问,严格杜绝运行时篡改 (Read-Only),不可变结构设计
1.3 类型后缀自动转换 & 类型安全保证 03_type_coercion_and_guarantee_zh.md _int, _float, _bool, _str, _list, _dict 运行时自动类型转换及安全保证
1.4 快速失败必需配置验证 04_fail_fast_require_setting_zh.md 启动阶段检测缺失配置,输出清晰诊断日志并即时中止进程
1.5 网络代理控制 05_network_proxy_control_zh.md 自动将 proxy.no_proxy 配置同步至 NO_PROXY 环境变量并绕过代理
1.6 常量外部化与自愈模板校正 06_ensure_config_self_healing_zh.md 代码中所有常量配置化(外部化),自动生成 config.yml 并强制注入缺失配置项
2.1 单行扁平化格式化器 & 根源追踪 01_single_line_flatten_formatter_zh.md SingleLineFlattenFormatter,[Origin: ...] 堆栈调用帧提取,适配日志收集器
2.2 批量日志配置 & 处理器控制 02_project_logger_configure_zh.md ProjectLogger.configure(),控制台/文件处理器动态分配,按日志级别路径归档
2.3 多语言消息字典 & 基于代码的日志 03_multilingual_message_catalog_zh.md logging_messages_*.yml,运行时语言平滑切换,safe_kwargs 安全模板占位符
2.4 执行结果统计 & 错误分类实时汇总 04_execution_result_and_error_tracking_zh.md 成功/失败/跳过 (Skip) 三级状态分类,实例与类全局多线程统计指标汇总
2.5 任务执行总结报告自动生成 05_summary_report_generation_zh.md ProjectLogger.log_summary(),80 列标准对齐摘要块,吞吐量/带宽,错误归因解析
3.1 AWS S3 & Dell ECS 存储集成 01_s3_ecs_storage_client_zh.md S3/ECS 连接连通性早验,海量对象分页遍历,流式直传 GCS 与相同文件跳过
3.2 GCS 流式上传 & 4 级认证体系 02_gcs_cloud_storage_client_zh.md 4 级服务账号凭证优先级,连接验证,元数据获取,零磁盘暂存分块流式上传
3.3 BigQuery 批量加载 & 流式插入 03_bigquery_batch_and_streaming_load_zh.md JSON 批量加载 vs 流式 API,嵌套错误解包,防重已有唯一键集合提取
3.4 BigQuery 内联 MERGE (Upsert) 引擎 04_bigquery_inline_merge_upsert_zh.md 无需中间临时表的内联 MERGE,UNNEST 参数化绑定,动态类型转换,100 条分片
3.5 BigQuery TIMESTAMP 与 DATETIME 转换 05_bigquery_timestamp_and_datetime_conversion_zh.md ISO 与压缩日期时间规范化,时区偏移量决定优先级,按列类型选择方法
3.6 GCP 服务账号认证解析器 06_gcp_credential_resolver_zh.md GcpCredentialResolver、4 级认证优先级、在其他 GCP 服务中单独复用、组合 (Composition) 结构
4.1 双层 Tool 目录结构发现 & 动态加载 01_dual_tool_hierarchy_discovery_zh.md 内置 (优先 1) 与项目本地 (优先 2) 发现机制,3 阶段函数内省,_tool_cache 预校验
4.2 声明式模板替换 & 表达式评估 02_declarative_template_eval_zh.md ToolParser.eval(),工具函数直调,点号命名空间绑定,管道符 (|) 兜底降级
4.3 安全命名空间导航 (_SafeNamespace) 03_safe_namespace_navigation_zh.md 点/中括号通用解析,不区分大小写,缺字段静默返回 "",递归封装嵌套容器
4.4 内置通用日期时间工具 (DateTimeUtils) 04_builtin_datetime_utils_zh.md 规则与模板专用日期工具,时区底层计算委托 TimeUtils,生成 ISO 与紧凑日期
5.1 主机时区探测 & 全球标准时区解析 01_time_utils_and_timezone_resolution_zh.md TimeUtils,动态探测系统/容器时区,解析全球 30+ 标准时区,datetime 规范化
5.2 多线程实时进度跟踪 & 里程碑记录 02_progress_tracker_and_milestones_zh.md ProgressTracker,实时百分比 (%)、吞吐率、预计剩余时间,WARNING 里程碑
5.3 Unicode 全角字符宽度计算与表格对齐 03_unicode_table_formatter_zh.md TableFormatter,基于 east_asian_width 计算,汉字全角(2格)与英文(1格)对齐
7.1 模型配置文件管理与文本生成 01_model_profiles_and_generation_zh.md agent_common.llm
7.2 外部聊天 API 与 Fabrix 集成 02_external_api_and_fabrix_zh.md agent_common.llm
7.3 本地 GGUF 推理与模型缓存 03_local_gguf_inference_zh.md agent_common.llm
7.4 执行模式与条件化本地切换 04_provider_and_local_fallback_zh.md agent_common.llm
7.5 推理结果与异常处理 05_inference_results_and_errors_zh.md agent_common.llm
7.6 Groq 监督员 AI 与 Antigravity Stop 钩子 06_groq_supervisor_and_stop_hook_zh.md agent_common.llm
8.1 语言代码规范化 & 多语言资源查找 01_language_codes_and_resource_lookup_zh.md Localizer、支持的语言代码与别名、语言决定优先级、多语言文件查找及默认语言回退规则

🚀 安装与构建指南 (Installation and Build Guide)

📦 构建 Wheel 安装包 (.whl)

# 离线环境
python scripts/build_agent_common_whl.py

# 联网环境
python -m build agent_common --wheel -o whls/

安装 Wheel 软件包

# 开发环境 (Editable 可编辑模式 - 核心轻量安装)
pip install -e agent_common

# 开发环境 (包含云端客户端 extras)
pip install -e "agent_common[clients]"

# 生产环境 (安装 Wheel 包)
pip install dist/agent_common-0.4.99-py3-none-any.whl

🌐 官方 PyPI 镜像分发(仅限维护者)

# 1. 更新构建工具
pip install build twine

# 2. 构建分发包 (同时生成 sdist 与 wheel)
python -m build

# 3. 校验分发归档完整性
python -m twine check dist/*

# 4. 上传至 PyPI
python -m twine upload dist/agent_common-0.4.99*

📋 版本变更历史 (Changelog)

详细版本变更历史请参阅 CHANGELOG_ZH.md 文件。


agent_common パッケージ (日本語)

エンタープライズ AI エージェントサービスおよびデータ移行・生成パイプラインのための共通 Python コアライブラリです。統合ロギング、階層型設定ローダー、クラウドおよびデータベースインフラクライアント、動的ツールパーサー、集中エラー処理を提供します。


📌 主な機能

1. 設定ローダーおよび不変設定オブジェクト (agent_common.config_loader)

  • 1.1. 階層型 YAML 解析およびディープマージ (Deep Merge): パッケージ組み込みデフォルト設定 (agent_common/config/*.yml) とプロジェクト固有設定 (config/*.yml) を動的にマージ。
  • 1.2. 不変ドット記法アクセス (ReadOnlyConfig): config.ecs.endpoint_url, config.transfer.max_workers_int 形式の直感的な属性アクセスとランタイム改ざん防止。
  • 1.3. 型サフィックス自動型変換および型保証:
    • _int: 自動整数変換および型保証。
    • _float: 自動浮動小数点数変換および型保証。
    • _bool: 厳格なブール型変換および型保証(Python bool または大文字小文字不問の "true", "false" をサポートし、0, 1 など非ブール値流入時は Fail-Fast 遮断)。
    • _str: 自動文字列変換および .strip() 空白トリミング。
    • _list / _dict: リスト / 不変辞書 (ReadOnlyConfig) ラッピング保証。
    • 汎用関数 coerce_type_by_key_suffix およびネスト辞書一括変換 coerce_dict_by_key_suffix により、外部設定ファイル (rule.yml, mapping.yml) やデータパイプラインを完全サポート。
    • 厳格な Fail-Fast 保証: 型不一致時は詳細な診断例外 (ValueError/TypeError) を即座に発生。
  • 1.4. Fail-Fast 必須設定検証 (require_setting()): プログラム起動時に必須設定値が欠落している場合、詳細原因を出力してプロセスを即座に終了。
  • 1.5. ネットワークプロキシ制御 (_apply_no_proxy): proxy.no_proxy 設定を NO_PROXY 環境変数に自動反映し、内部通信プロキシをバイパス。
  • 1.6. 全定数の設定ファイル外部化および自己修復テンプレート補正 (ensure_config_file()): コード内の全定数を設定ファイル化、config.yml の自動生成および欠落キーの強制補正。agent_common クラスの既定設定は config_loader.config_file_auto_repair_dict で true にしたクラスのみ書き込む。

2. 単一行ログフォーマッターおよびロガー (agent_common.logger)

3. ストレージおよびデータベースクライアント (agent_common.clients)

4. 動的ツールローダーおよびテンプレート評価器 (agent_common.tool_parser) & 組み込みツール (agent_common.tool)

5. 進捗トラッカー、テーブルフォーマッターおよび時間ユーティリティ (agent_common.progress_tracker, agent_common.table_formatter, agent_common.time_utils)

6. 共通エラーおよび例外ハンドラー (agent_common.error_handler)

  • ネットワーク障害、設定エラー、実行時例外の一貫したログ記録と標準処理を提供。

7. 統合 LLM クライアントおよび推論エンジン (agent_common.llm)

8. 言語ローカライザー (agent_common.localizer)

  • 8.1. 言語コードの正規化と言語別リソースファイル探索 (Localizer): ISO 639-1 言語コード (KO, EN, ZH, JA) の正規化、明示引数・グローバル設定・環境変数に基づく言語決定、{接頭辞}_{言語}.yml 形式の言語別リソースファイル探索。ロギングから分離されており、ラベルや案内文など任意の多言語リソースに再利用可能。

🛠️ 使用例 (Usage Examples)

1. グローバル config ドットアクセスおよび型保証

from agent_common.config_loader import config

# 1) 型サフィックスによる自動キャスト保証
max_workers: int = config.transfer.max_workers_int       # int 型保証
host: str = config.database.host_str                     # str 型および .strip() 保証
is_active: bool = config.transfer.is_active_bool         # bool 型保証

# 2) 階層的プロパティアクセス
api_url: str = config.services.api_endpoint_url
db_port: int = config.database.port_int

2. ToolParser による動的ルール評価

from agent_common.tool_parser import ToolParser

tool_parser = ToolParser()

context_dict = {
    "storage": {"key": "/data/incoming/20260804/sample_document.json"},
    "document": {"expiry_date": "2024-12-31"},
    "sys": tool_parser.build_sys_context(),
}

date_val = tool_parser.eval("{date.get_today_yyyymmdd()}", context_dict)
today_val = tool_parser.eval("{sys.today}", context_dict)

3. ProgressTracker リアルタイム進捗追跡

from agent_common import ProgressTracker
from agent_common.logger import ProjectLogger

logger = ProjectLogger("MyTask")
tracker = ProgressTracker(total_items_int=1000, logger_obj=logger, item_name_str="ファイル")

for file_info in file_list:
    try:
        tracker.increment_success(bytes_int=len(data))
    except Exception as e:
        tracker.increment_failure(error_msg_str=str(e))

tracker.log_summary()

4. LlmClient による統合テキスト/SQL生成

from agent_common.llm import LlmClient

llm_client = LlmClient(purpose_str="sql_generator")
prompt_str = "ユーザー要求: 2026年8月の日次新規加入者統計クエリを作成してください。"
response_str = llm_client.generate(
    prompt_str=prompt_str,
    system_prompt_str="あなたは BigQuery SQL 専門の生成 AI です。"
)
print(f"生成結果 ({llm_client.last_generated_by_str}):\n{response_str}")

5. ストレージおよび BigQuery クライアント使用例

from agent_common.clients import S3Client, GcsClient, BigQueryClient

# S3 -> GCS スマート転送 (同一ファイルスキップ)
s3_client = S3Client(bucket_name_str="source-lake")
gcs_client = GcsClient(bucket_name_str="target-lake")

for obj in s3_client.list_objects(prefix_str="raw/events/"):
    s3_client.transfer_to_gcs(
        gcs_client_obj=gcs_client,
        s3_key_str=obj["Key"],
        gcs_blob_name_str=f"lake/{obj['Key'].lstrip('/')}",
        size_int=obj["Size"],
    )

# BigQuery インライン MERGE (Upsert)
bq_client = BigQueryClient(project_id_str="my-project", dataset_id_str="dw", table_id_str="tb_user")
bq_client.merge_table_from_json_data(
    json_data_any=[{"user_id": "U01", "name": "山田太郎", "created_at": "2026-01-01 00:00:00+09:00"}],
    pk_key_str="user_id",
    preserve_columns_list=["created_at"],
)

6. GcpCredentialResolver で他の GCP サービスを認証する

from google.cloud import pubsub_v1

from agent_common import ConfigLoader, GcpCredentialResolver

# 環境変数 JSON → 環境変数のファイルパス → 指定パス の順に解決し、いずれもなければ None (ADC) を返却
credentials = GcpCredentialResolver(
    credentials_path_str="config/secrets/gcp_sa_key.json",
    config_loader_obj=ConfigLoader(),
).resolve()

# GCS・BigQuery 以外の GCP クライアントにもそのまま渡せます
publisher_client = pubsub_v1.PublisherClient(credentials=credentials)

📖 詳細機能マニュアル (User Manuals)

番号 モジュール / テーマ マニュアルリンク 主な内容要約
1.1 階層型 YAML 解析 & ディープマージ 01_hierarchical_yaml_merge_ja.md 5段階マージ順序、再帰 _deep_merge アルゴリズム、ルート自動探索
1.2 不変ドット記法アクセス (ReadOnlyConfig) 02_readonly_dot_notation_ja.md ドット記法アクセス、ランタイム改ざん防止 (Read-Only)、不変オブジェクト設計
1.3 型サフィックス自動型変換 & 型保証 03_type_coercion_and_guarantee_ja.md _int, _float, _bool, _str, _list, _dict 自動キャストおよび安全性保証
1.4 Fail-Fast 必須設定検証 04_fail_fast_require_setting_ja.md 起動時必須設定の欠落検知、診断ログおよびプロセスの安全な早期終了
1.5 ネットワークプロキシ制御 05_network_proxy_control_ja.md proxy.no_proxy 設定の NO_PROXY 環境変数自動反映とプロキシバイパス
1.6 全定数の設定ファイル外部化とテンプレート補正 06_ensure_config_self_healing_ja.md コード内全定数の外部化、config.yml 自動生成および欠落設定の強制補正
2.1 単一行フラット化フォーマッター & 発生源追跡 01_single_line_flatten_formatter_ja.md SingleLineFlattenFormatter、[Origin: ...] 抽出、集中ログ収集最適化
2.2 一括ロギング構成 & ハンドラー制御 02_project_logger_configure_ja.md ProjectLogger.configure()、コンソール/ファイル振り分け、レベル別ディレクトリ分離
2.3 多言語メッセージカタログ & コードベースロギング 03_multilingual_message_catalog_ja.md logging_messages_*.yml、ランタイム言語切り替え、安全な変数置換
2.4 タスク統計 & エラー/除外リアルタイム集計 04_execution_result_and_error_tracking_ja.md 成功/失敗/除外の3段階分類、マルチスレッド環境での指標集計
2.5 タスク結果要約レポート自動生成 05_summary_report_generation_ja.md ProjectLogger.log_summary()、80列整形要約ブロック、スループットとエラー診断
3.1 AWS S3 & Dell ECS ストレージ連携 01_s3_ecs_storage_client_ja.md S3/ECS 接続検証、ページネーション一覧取得、GCS ストリーミング転送と重複スキップ
3.2 GCS ストリーミングアップロード & 4段階認証 02_gcs_cloud_storage_client_ja.md 4段階認証優先順位、バケット検証、メモリパイプラインによるゼロディスク転送
3.3 BigQuery バッチロード & ストリーミング挿入 03_bigquery_batch_and_streaming_load_ja.md JSON バッチロード vs ストリーミング API、ネストエラー展開、既存キー重複防止
3.4 BigQuery インライン MERGE (Upsert) エンジン 04_bigquery_inline_merge_upsert_ja.md 一時テーブル不要のインライン MERGE、UNNEST パラメータバインディング、100件分割
3.5 BigQuery TIMESTAMP・DATETIME 変換 05_bigquery_timestamp_and_datetime_conversion_ja.md ISO/圧縮日時の正規化、タイムゾーンオフセットの決定優先順位、列の型ごとのメソッド選択基準
3.6 GCP サービスアカウント認証リゾルバー 06_gcp_credential_resolver_ja.md GcpCredentialResolver、4段階の認証優先順位、他の GCP サービスでの単独再利用、コンポジション構造
4.1 二元化 Tool ディレクトリ探索 & 動的ロード 01_dual_tool_hierarchy_discovery_ja.md 組み込み(優先1) vs ローカル(優先2) 探索、3段階関数内省、キャッシュ機構
4.2 宣言的テンプレート置換 & 式評価 02_declarative_template_eval_ja.md ToolParser.eval()、関数直接呼び出し、名前空間バインド、パイプ (|) フォールバック
4.3 安全な名前空間探索 (_SafeNamespace) 03_safe_namespace_navigation_ja.md ドット/インデックス統一、大文字小文字不問、欠落時 "" 返却、再帰ラッピング
4.4 組み込み共通日時ツール (DateTimeUtils) 04_builtin_datetime_utils_ja.md ルール/テンプレート専用日時ツール、TimeUtils 連携、ISO タイムスタンプ生成
5.1 ホストタイムゾーン検出 & 世界標準時解決 01_time_utils_and_timezone_resolution_ja.md TimeUtils、OS/コンテナタイムゾーン検出、30+標準時解析、datetime 正規化
5.2 マルチスレッド進捗追跡 & マイルストーン 02_progress_tracker_and_milestones_ja.md ProgressTracker、進捗率 (%)、スループット、ETA 計算、WARNING 昇格ログ
5.3 Unicode 全角幅計算 & テーブル縦線整列 03_unicode_table_formatter_ja.md TableFormatter、east_asian_width に基づく全角(2幅)・半角(1幅)整列
7.1 モデルプロファイル管理およびテキスト生成 01_model_profiles_and_generation_ja.md agent_common.llm
7.2 外部チャット API および Fabrix 連携 02_external_api_and_fabrix_ja.md agent_common.llm
7.3 ローカル GGUF 推論およびモデルキャッシュ 03_local_gguf_inference_ja.md agent_common.llm
7.4 実行モードおよび条件付きローカル切り替え 04_provider_and_local_fallback_ja.md agent_common.llm
7.5 推論結果および例外処理 05_inference_results_and_errors_ja.md agent_common.llm
7.6 Groq 監督官 AI および Antigravity Stop フック 06_groq_supervisor_and_stop_hook_ja.md agent_common.llm
8.1 言語コード正規化 & 言語別リソース探索 01_language_codes_and_resource_lookup_ja.md Localizer、対応言語コードと別名、言語決定の優先順位、言語別ファイル探索とデフォルト言語への代替ルール

🚀 インストールおよびビルドガイド (Installation and Build Guide)

📦 Wheel パッケージビルド (.whl)

# クローズドネットワーク環境
python scripts/build_agent_common_whl.py

# インターネット接続環境
python -m build agent_common --wheel -o whls/

Wheel パッケージのインストール

# 開発環境(Editable モード - 軽量コアインストール)
pip install -e agent_common

# 開発環境(クラウドクライアント extras 含む)
pip install -e "agent_common[clients]"

# 本番環境(Wheel パッケージのインストール)
pip install dist/agent_common-0.4.99-py3-none-any.whl

🌐 公式 PyPI 配布(管理者専用)

# 1. ビルドツールの更新
pip install build twine

# 2. パッケージビルド(sdist および wheel 同時作成)
python -m build

# 3. 配布アーカイブの検証
python -m twine check dist/*

# 4. PyPI アップロード
python -m twine upload dist/agent_common-0.4.99*

📋 バージョン変更履歴 (Changelog)

詳細なバージョン変更履歴は CHANGELOG_JA.md をご参照ください。

Metadata

Release files for agent-common 0.4.99

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for agent-common 0.4.99
File Size Uploaded Provenance
agent_common-0.4.99.tar.gz 559.1 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for agent-common 0.4.99
File Interpreter ABI Platform
agent_common-0.4.99-py3-none-any.whl Python 3 none any Details

Total release size: 694.0 kB

Release files / agent_common-0.4.99.tar.gz

Download URL agent_common-0.4.99.tar.gz
Size 559.1 kB
Tags Source
SHA-256 checksum
How to use checksums
4f7a579e8a5bd5566ed4b19cfe7bb37cc60a8e2b0655e26a3b34f40dad38cbd1
BLAKE2b-256 checksum
How to use checksums
67927938ecaa71cd13489a23fb20a9e238cd827fde591aaa141ea9193673d58b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.15

Release files / agent_common-0.4.99-py3-none-any.whl

Download URL agent_common-0.4.99-py3-none-any.whl
Size 134.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
93b54c914d3935614c6d5465590f18de732f6142eb90bbc57b4ba2d9c6e35087
BLAKE2b-256 checksum
How to use checksums
1d72de065cbca9a5a510e70ec2a2a35e1eb4426ebb221992c5e457ba15d3daa8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.15

Security for agent-common 0.4.99

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.4.99 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page