process-gpt-agent-sdk 0.1.2__py3-none-any.whl
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 process-gpt-agent-sdk might be problematic. Click here for more details.
- process_gpt_agent_sdk-0.1.2.dist-info/METADATA +378 -0
- process_gpt_agent_sdk-0.1.2.dist-info/RECORD +15 -0
- process_gpt_agent_sdk-0.1.2.dist-info/WHEEL +5 -0
- process_gpt_agent_sdk-0.1.2.dist-info/top_level.txt +1 -0
- processgpt_agent_sdk/__init__.py +7 -0
- processgpt_agent_sdk/core/__init__.py +0 -0
- processgpt_agent_sdk/core/database.py +289 -0
- processgpt_agent_sdk/server.py +216 -0
- processgpt_agent_sdk/tools/__init__.py +0 -0
- processgpt_agent_sdk/tools/knowledge_tools.py +206 -0
- processgpt_agent_sdk/tools/safe_tool_loader.py +191 -0
- processgpt_agent_sdk/utils/__init__.py +0 -0
- processgpt_agent_sdk/utils/event_handler.py +27 -0
- processgpt_agent_sdk/utils/logger.py +30 -0
- processgpt_agent_sdk/utils/summarizer.py +122 -0
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from typing import Any, Dict
|
|
3
|
+
|
|
4
|
+
from a2a.server.agent_execution import AgentExecutor, RequestContext
|
|
5
|
+
from a2a.server.events import EventQueue, Event
|
|
6
|
+
|
|
7
|
+
from .core.database import (
|
|
8
|
+
initialize_db,
|
|
9
|
+
get_consumer_id,
|
|
10
|
+
polling_pending_todos,
|
|
11
|
+
fetch_done_data,
|
|
12
|
+
fetch_agent_data,
|
|
13
|
+
fetch_form_types,
|
|
14
|
+
fetch_task_status,
|
|
15
|
+
fetch_tenant_mcp_config,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
from .utils.logger import handle_error as _emit_error, log as _emit_log
|
|
19
|
+
from .utils.summarizer import summarize_async
|
|
20
|
+
from .utils.event_handler import route_event
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ProcessGPTAgentServer:
|
|
24
|
+
"""ProcessGPT 핵심 서버
|
|
25
|
+
|
|
26
|
+
- 단일 실행기 모델: 실행기는 하나이며, 작업별 분기는 실행기 내부 로직에 위임합니다.
|
|
27
|
+
- 폴링은 타입 필터 없이(빈 값) 가져온 뒤, 작업 레코드의 정보로 처리합니다.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, executor: AgentExecutor, polling_interval: int = 5, agent_orch: str = ""):
|
|
31
|
+
self.polling_interval = polling_interval
|
|
32
|
+
self.is_running = False
|
|
33
|
+
self._executor: AgentExecutor = executor
|
|
34
|
+
self.cancel_check_interval: float = 0.5
|
|
35
|
+
self.agent_orch: str = agent_orch or ""
|
|
36
|
+
initialize_db()
|
|
37
|
+
|
|
38
|
+
async def run(self) -> None:
|
|
39
|
+
self.is_running = True
|
|
40
|
+
_emit_log("ProcessGPT 서버 시작")
|
|
41
|
+
|
|
42
|
+
while self.is_running:
|
|
43
|
+
try:
|
|
44
|
+
todo = await polling_pending_todos(self.agent_orch, get_consumer_id())
|
|
45
|
+
if not todo:
|
|
46
|
+
await asyncio.sleep(self.polling_interval)
|
|
47
|
+
continue
|
|
48
|
+
|
|
49
|
+
todo_id = todo["id"]
|
|
50
|
+
_emit_log(f"[JOB START] todo_id={todo_id}")
|
|
51
|
+
|
|
52
|
+
prepared_data = await self._prepare_service_data(todo)
|
|
53
|
+
_emit_log(f"[RUN] 서비스 데이터 준비 완료 [todo_id={todo_id} agent={prepared_data.get('agent_orch','')}]")
|
|
54
|
+
|
|
55
|
+
await self._execute_with_cancel_watch(todo, prepared_data)
|
|
56
|
+
_emit_log(f"[RUN] 서비스 실행 완료 [todo_id={todo_id} agent={prepared_data.get('agent_orch','')}]")
|
|
57
|
+
|
|
58
|
+
except Exception as e:
|
|
59
|
+
_emit_error("폴링 루프 오류", e)
|
|
60
|
+
await asyncio.sleep(self.polling_interval)
|
|
61
|
+
|
|
62
|
+
def stop(self) -> None:
|
|
63
|
+
self.is_running = False
|
|
64
|
+
_emit_log("ProcessGPT 서버 중지")
|
|
65
|
+
|
|
66
|
+
async def _prepare_service_data(self, todo: Dict[str, Any]) -> Dict[str, Any]:
|
|
67
|
+
done_outputs = await fetch_done_data(todo.get("proc_inst_id"))
|
|
68
|
+
_emit_log(f"[PREP] done_outputs → {done_outputs}")
|
|
69
|
+
feedbacks = todo.get("feedback")
|
|
70
|
+
|
|
71
|
+
agent_list = await fetch_agent_data(str(todo.get("user_id", "")))
|
|
72
|
+
_emit_log(f"[PREP] agent_list → {agent_list}")
|
|
73
|
+
|
|
74
|
+
mcp_config = await fetch_tenant_mcp_config(str(todo.get("tenant_id", "")))
|
|
75
|
+
_emit_log(f"[PREP] mcp_config(툴) → {mcp_config}")
|
|
76
|
+
|
|
77
|
+
form_id, form_types = await fetch_form_types(
|
|
78
|
+
str(todo.get("tool", "")),
|
|
79
|
+
str(todo.get("tenant_id", ""))
|
|
80
|
+
)
|
|
81
|
+
_emit_log(f"[PREP] form → id={form_id} types={form_types}")
|
|
82
|
+
|
|
83
|
+
output_summary, feedback_summary = await summarize_async(
|
|
84
|
+
done_outputs or [], feedbacks or "", todo.get("description", "")
|
|
85
|
+
)
|
|
86
|
+
_emit_log(f"[PREP] summary → output={output_summary} feedback={feedback_summary}")
|
|
87
|
+
|
|
88
|
+
prepared: Dict[str, Any] = {
|
|
89
|
+
"todo_id": str(todo.get("id")),
|
|
90
|
+
"proc_inst_id": todo.get("proc_inst_id"),
|
|
91
|
+
"agent_list": agent_list or [],
|
|
92
|
+
"mcp_config": mcp_config,
|
|
93
|
+
"form_id": form_id,
|
|
94
|
+
"form_types": form_types or [],
|
|
95
|
+
"activity_name": str(todo.get("activity_name", "")),
|
|
96
|
+
"message": str(todo.get("description", "")),
|
|
97
|
+
"agent_orch": str(todo.get("agent_orch", "")),
|
|
98
|
+
"done_outputs": done_outputs or [],
|
|
99
|
+
"output_summary": output_summary or "",
|
|
100
|
+
"feedback_summary": feedback_summary or "",
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return prepared
|
|
104
|
+
|
|
105
|
+
async def _execute_with_cancel_watch(self, todo: Dict[str, Any], prepared_data: Dict[str, Any]) -> None:
|
|
106
|
+
executor = self._executor
|
|
107
|
+
|
|
108
|
+
context = ProcessGPTRequestContext(prepared_data)
|
|
109
|
+
event_queue = ProcessGPTEventQueue(todo)
|
|
110
|
+
|
|
111
|
+
_emit_log(f"[EXEC START] todo_id={todo.get('id')} agent={prepared_data.get('agent_orch','')}")
|
|
112
|
+
execute_task = asyncio.create_task(executor.execute(context, event_queue))
|
|
113
|
+
cancel_watch_task = asyncio.create_task(self._watch_cancellation(todo, executor, context, event_queue, execute_task))
|
|
114
|
+
|
|
115
|
+
try:
|
|
116
|
+
done, pending = await asyncio.wait(
|
|
117
|
+
[cancel_watch_task, execute_task],
|
|
118
|
+
return_when=asyncio.FIRST_COMPLETED
|
|
119
|
+
)
|
|
120
|
+
for task in pending:
|
|
121
|
+
task.cancel()
|
|
122
|
+
|
|
123
|
+
except Exception as e:
|
|
124
|
+
_emit_error("서비스 실행 오류", e)
|
|
125
|
+
cancel_watch_task.cancel()
|
|
126
|
+
execute_task.cancel()
|
|
127
|
+
finally:
|
|
128
|
+
try:
|
|
129
|
+
await event_queue.close()
|
|
130
|
+
except Exception as e:
|
|
131
|
+
_emit_error("이벤트 큐 종료 실패", e)
|
|
132
|
+
_emit_log(f"[EXEC END] todo_id={todo.get('id')} agent={prepared_data.get('agent_orch','')}")
|
|
133
|
+
|
|
134
|
+
async def _watch_cancellation(self, todo: Dict[str, Any], executor: AgentExecutor, context: RequestContext, event_queue: EventQueue, execute_task: asyncio.Task) -> None:
|
|
135
|
+
todo_id = str(todo.get("id"))
|
|
136
|
+
|
|
137
|
+
while True:
|
|
138
|
+
await asyncio.sleep(self.cancel_check_interval)
|
|
139
|
+
|
|
140
|
+
status = await fetch_task_status(todo_id)
|
|
141
|
+
normalized = (status or "").strip().lower()
|
|
142
|
+
if normalized in ("cancelled", "fb_requested"):
|
|
143
|
+
_emit_log(f"작업 취소 감지: {todo_id}, 상태: {status}")
|
|
144
|
+
|
|
145
|
+
try:
|
|
146
|
+
await executor.cancel(context, event_queue)
|
|
147
|
+
except Exception as e:
|
|
148
|
+
_emit_error("취소 처리 실패", e)
|
|
149
|
+
finally:
|
|
150
|
+
try:
|
|
151
|
+
execute_task.cancel()
|
|
152
|
+
except Exception as e:
|
|
153
|
+
_emit_error("실행 태스크 즉시 취소 실패", e)
|
|
154
|
+
try:
|
|
155
|
+
await event_queue.close()
|
|
156
|
+
except Exception as e:
|
|
157
|
+
_emit_error("취소 후 이벤트 큐 종료 실패", e)
|
|
158
|
+
break
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class ProcessGPTRequestContext(RequestContext):
|
|
162
|
+
def __init__(self, prepared_data: Dict[str, Any]):
|
|
163
|
+
self._prepared_data = prepared_data
|
|
164
|
+
self._message = prepared_data.get("message", "")
|
|
165
|
+
self._current_task = None
|
|
166
|
+
|
|
167
|
+
def get_user_input(self) -> str:
|
|
168
|
+
return self._message
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def message(self) -> str:
|
|
172
|
+
return self._message
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def current_task(self):
|
|
176
|
+
return getattr(self, "_current_task", None)
|
|
177
|
+
|
|
178
|
+
def get_context_data(self) -> Dict[str, Any]:
|
|
179
|
+
return self._prepared_data
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class ProcessGPTEventQueue(EventQueue):
|
|
183
|
+
def __init__(self, todo: Dict[str, Any]):
|
|
184
|
+
self.todo = todo
|
|
185
|
+
super().__init__()
|
|
186
|
+
|
|
187
|
+
def enqueue_event(self, event: Event):
|
|
188
|
+
try:
|
|
189
|
+
try:
|
|
190
|
+
super().enqueue_event(event)
|
|
191
|
+
except Exception as e:
|
|
192
|
+
_emit_error("이벤트 큐 삽입 실패", e)
|
|
193
|
+
|
|
194
|
+
self._create_bg_task(route_event(self.todo, event), "route_event")
|
|
195
|
+
except Exception as e:
|
|
196
|
+
_emit_error("이벤트 저장 실패", e)
|
|
197
|
+
|
|
198
|
+
def task_done(self) -> None:
|
|
199
|
+
try:
|
|
200
|
+
_emit_log(f"태스크 완료: {self.todo['id']}")
|
|
201
|
+
except Exception as e:
|
|
202
|
+
_emit_error("태스크 완료 처리 실패", e)
|
|
203
|
+
|
|
204
|
+
async def close(self) -> None:
|
|
205
|
+
pass
|
|
206
|
+
|
|
207
|
+
def _create_bg_task(self, coro: Any, label: str) -> None:
|
|
208
|
+
try:
|
|
209
|
+
task = asyncio.create_task(coro)
|
|
210
|
+
def _cb(t: asyncio.Task):
|
|
211
|
+
exc = t.exception()
|
|
212
|
+
if exc:
|
|
213
|
+
_emit_error(f"백그라운드 태스크 오류({label})", exc)
|
|
214
|
+
task.add_done_callback(_cb)
|
|
215
|
+
except Exception as e:
|
|
216
|
+
_emit_error(f"백그라운드 태스크 생성 실패({label})", e)
|
|
File without changes
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Optional, List, Type
|
|
3
|
+
from pydantic import BaseModel, Field, PrivateAttr, field_validator
|
|
4
|
+
from crewai.tools import BaseTool
|
|
5
|
+
from dotenv import load_dotenv
|
|
6
|
+
from mem0 import Memory
|
|
7
|
+
import requests
|
|
8
|
+
from ..utils.logger import log, handle_error
|
|
9
|
+
|
|
10
|
+
# ============================================================================
|
|
11
|
+
# 설정 및 초기화
|
|
12
|
+
# ============================================================================
|
|
13
|
+
|
|
14
|
+
load_dotenv()
|
|
15
|
+
|
|
16
|
+
DB_USER = os.getenv("DB_USER")
|
|
17
|
+
DB_PASSWORD = os.getenv("DB_PASSWORD")
|
|
18
|
+
DB_HOST = os.getenv("DB_HOST")
|
|
19
|
+
DB_PORT = os.getenv("DB_PORT")
|
|
20
|
+
DB_NAME = os.getenv("DB_NAME")
|
|
21
|
+
|
|
22
|
+
CONNECTION_STRING = None
|
|
23
|
+
if all([DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME]):
|
|
24
|
+
CONNECTION_STRING = f"postgresql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
|
|
25
|
+
else:
|
|
26
|
+
log("mem0 연결 문자열이 설정되지 않았습니다(DB_* env). 기능은 제한될 수 있습니다.")
|
|
27
|
+
|
|
28
|
+
# ============================================================================
|
|
29
|
+
# 스키마 정의
|
|
30
|
+
# ============================================================================
|
|
31
|
+
|
|
32
|
+
class KnowledgeQuerySchema(BaseModel):
|
|
33
|
+
query: str = Field(..., description="검색할 지식 쿼리")
|
|
34
|
+
|
|
35
|
+
@field_validator('query', mode='before')
|
|
36
|
+
@classmethod
|
|
37
|
+
def validate_query(cls, v):
|
|
38
|
+
import json
|
|
39
|
+
if isinstance(v, dict):
|
|
40
|
+
for k in ("description", "query", "q", "text", "message"):
|
|
41
|
+
if k in v and v[k]:
|
|
42
|
+
return str(v[k])
|
|
43
|
+
return "" if not v else json.dumps(v, ensure_ascii=False)
|
|
44
|
+
return v if isinstance(v, str) else str(v)
|
|
45
|
+
|
|
46
|
+
# ============================================================================
|
|
47
|
+
# 지식 검색 도구
|
|
48
|
+
# ============================================================================
|
|
49
|
+
|
|
50
|
+
class Mem0Tool(BaseTool):
|
|
51
|
+
"""Supabase 기반 mem0 지식 검색 도구 - 에이전트별"""
|
|
52
|
+
name: str = "mem0"
|
|
53
|
+
description: str = (
|
|
54
|
+
"🧠 에이전트별 개인 지식 저장소 검색 도구\n\n"
|
|
55
|
+
"🚨 필수 검색 순서: 작업 전 반드시 피드백부터 검색!\n\n"
|
|
56
|
+
"저장된 정보:\n"
|
|
57
|
+
"🔴 과거 동일한 작업에 대한 피드백 및 교훈 (최우선 검색 대상)\n"
|
|
58
|
+
"🔴 과거 실패 사례 및 개선 방안\n"
|
|
59
|
+
"• 객관적 정보 (사람명, 수치, 날짜, 사물 등)\n"
|
|
60
|
+
"검색 목적:\n"
|
|
61
|
+
"- 작업지시사항을 올바르게 수행하기 위해 필요한 정보(매개변수, 제약, 의존성)와\n"
|
|
62
|
+
" 안전 수행을 위한 피드백/주의사항을 찾기 위함\n"
|
|
63
|
+
"- 과거 실패 경험을 통한 실수 방지\n"
|
|
64
|
+
"- 정확한 객관적 정보 조회\n\n"
|
|
65
|
+
"사용 지침:\n"
|
|
66
|
+
"- 현재 작업 맥락(사용자 요청, 시스템/도구 출력, 최근 단계)을 근거로 자연어의 완전한 문장으로 질의하세요.\n"
|
|
67
|
+
"- 핵심 키워드 + 엔터티(고객명, 테이블명, 날짜 등) + 제약(환경/범위)을 조합하세요.\n"
|
|
68
|
+
"- 동의어/영문 용어를 섞어 2~3개의 표현으로 재질의하여 누락을 줄이세요.\n"
|
|
69
|
+
"- 필요한 경우 좁은 쿼리 → 넓은 쿼리 순서로 반복 검색하세요. (필요 시 기간/버전 범위 명시)\n"
|
|
70
|
+
"- 동일 정보를 다른 표현으로 재질의하며, 최신/가장 관련 결과를 우선 검토하세요.\n\n"
|
|
71
|
+
"⚡ 핵심: 어떤 작업이든 시작 전에, 해당 작업을 안전하게 수행하기 위한 피드백/주의사항과\n"
|
|
72
|
+
" 필수 매개변수를 먼저 질의하여 확보하세요!"
|
|
73
|
+
)
|
|
74
|
+
args_schema: Type[KnowledgeQuerySchema] = KnowledgeQuerySchema
|
|
75
|
+
_tenant_id: Optional[str] = PrivateAttr()
|
|
76
|
+
_user_id: Optional[str] = PrivateAttr()
|
|
77
|
+
_namespace: Optional[str] = PrivateAttr()
|
|
78
|
+
_memory: Optional[Memory] = PrivateAttr(default=None)
|
|
79
|
+
|
|
80
|
+
def __init__(self, tenant_id: str = None, user_id: str = None, **kwargs):
|
|
81
|
+
super().__init__(**kwargs)
|
|
82
|
+
self._tenant_id = tenant_id
|
|
83
|
+
self._user_id = user_id
|
|
84
|
+
self._namespace = user_id
|
|
85
|
+
self._memory = self._initialize_memory()
|
|
86
|
+
log(f"Mem0Tool 초기화: user_id={self._user_id}, namespace={self._namespace}")
|
|
87
|
+
|
|
88
|
+
def _initialize_memory(self) -> Optional[Memory]:
|
|
89
|
+
"""Memory 인스턴스 초기화 - 에이전트별"""
|
|
90
|
+
if not CONNECTION_STRING:
|
|
91
|
+
return None
|
|
92
|
+
config = {
|
|
93
|
+
"vector_store": {
|
|
94
|
+
"provider": "supabase",
|
|
95
|
+
"config": {
|
|
96
|
+
"connection_string": CONNECTION_STRING,
|
|
97
|
+
"collection_name": "memories",
|
|
98
|
+
"index_method": "hnsw",
|
|
99
|
+
"index_measure": "cosine_distance"
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return Memory.from_config(config_dict=config)
|
|
104
|
+
|
|
105
|
+
def _run(self, query: str) -> str:
|
|
106
|
+
"""지식 검색 및 결과 반환 - 에이전트별 메모리에서"""
|
|
107
|
+
if not query:
|
|
108
|
+
return "검색할 쿼리를 입력해주세요."
|
|
109
|
+
if not self._user_id:
|
|
110
|
+
return "개인지식 검색 비활성화: user_id 없음"
|
|
111
|
+
if not self._memory:
|
|
112
|
+
return "mem0 비활성화: DB 연결 정보(DB_*)가 설정되지 않았습니다."
|
|
113
|
+
|
|
114
|
+
try:
|
|
115
|
+
log(f"에이전트별 검색 시작: user_id={self._user_id}, query='{query}'")
|
|
116
|
+
results = self._memory.search(query, user_id=self._user_id)
|
|
117
|
+
hits = results.get("results", [])
|
|
118
|
+
|
|
119
|
+
THRESHOLD = 0.5
|
|
120
|
+
MIN_RESULTS = 5
|
|
121
|
+
hits_sorted = sorted(hits, key=lambda x: x.get("score", 0), reverse=True)
|
|
122
|
+
filtered_hits = [h for h in hits_sorted if h.get("score", 0) >= THRESHOLD]
|
|
123
|
+
if len(filtered_hits) < MIN_RESULTS:
|
|
124
|
+
filtered_hits = hits_sorted[:MIN_RESULTS]
|
|
125
|
+
hits = filtered_hits
|
|
126
|
+
|
|
127
|
+
log(f"에이전트별 검색 결과: {len(hits)}개 항목 발견")
|
|
128
|
+
|
|
129
|
+
if not hits:
|
|
130
|
+
return f"'{query}'에 대한 개인 지식이 없습니다."
|
|
131
|
+
|
|
132
|
+
return self._format_results(hits)
|
|
133
|
+
|
|
134
|
+
except Exception as e:
|
|
135
|
+
handle_error("지식검색오류", e, raise_error=False)
|
|
136
|
+
return f"지식검색오류: {e}"
|
|
137
|
+
|
|
138
|
+
def _format_results(self, hits: List[dict]) -> str:
|
|
139
|
+
"""검색 결과 포맷팅"""
|
|
140
|
+
items = []
|
|
141
|
+
for idx, hit in enumerate(hits, start=1):
|
|
142
|
+
memory_text = hit.get("memory", "")
|
|
143
|
+
score = hit.get("score", 0)
|
|
144
|
+
items.append(f"개인지식 {idx} (관련도: {score:.2f})\n{memory_text}")
|
|
145
|
+
|
|
146
|
+
return "\n\n".join(items)
|
|
147
|
+
|
|
148
|
+
# ============================================================================
|
|
149
|
+
# 사내 문서 검색 (memento) 도구
|
|
150
|
+
# ============================================================================
|
|
151
|
+
|
|
152
|
+
class MementoQuerySchema(BaseModel):
|
|
153
|
+
query: str = Field(..., description="검색 키워드 또는 질문")
|
|
154
|
+
|
|
155
|
+
class MementoTool(BaseTool):
|
|
156
|
+
"""사내 문서 검색을 수행하는 도구"""
|
|
157
|
+
name: str = "memento"
|
|
158
|
+
description: str = (
|
|
159
|
+
"🔒 보안 민감한 사내 문서 검색 도구\n\n"
|
|
160
|
+
"저장된 정보:\n"
|
|
161
|
+
"• 보안 민감한 사내 기밀 문서\n"
|
|
162
|
+
"• 대용량 사내 문서 및 정책 자료\n"
|
|
163
|
+
"• 객관적이고 정확한 회사 내부 지식\n"
|
|
164
|
+
"• 업무 프로세스, 규정, 기술 문서\n\n"
|
|
165
|
+
"검색 목적:\n"
|
|
166
|
+
"- 작업지시사항을 올바르게 수행하기 위한 회사 정책/규정/프로세스/매뉴얼 확보\n"
|
|
167
|
+
"- 최신 버전의 표준과 가이드라인 확인\n\n"
|
|
168
|
+
"사용 지침:\n"
|
|
169
|
+
"- 현재 작업/요청과 직접 연결된 문맥을 담아 자연어의 완전한 문장으로 질의하세요.\n"
|
|
170
|
+
"- 문서 제목/버전/담당조직/기간/환경(프로덕션·스테이징·모듈 등) 조건을 명확히 포함하세요.\n"
|
|
171
|
+
"- 약어·정식명칭, 한·영 용어를 함께 사용해 2~3회 재질의하며 누락을 줄이세요.\n"
|
|
172
|
+
"- 처음엔 좁게, 필요 시 점진적으로 범위를 넓혀 검색하세요.\n\n"
|
|
173
|
+
"⚠️ 보안 민감 정보 포함 - 적절한 권한과 용도로만 사용"
|
|
174
|
+
)
|
|
175
|
+
args_schema: Type[MementoQuerySchema] = MementoQuerySchema
|
|
176
|
+
_tenant_id: str = PrivateAttr()
|
|
177
|
+
|
|
178
|
+
def __init__(self, tenant_id: str = "localhost", **kwargs):
|
|
179
|
+
super().__init__(**kwargs)
|
|
180
|
+
self._tenant_id = tenant_id
|
|
181
|
+
log(f"MementoTool 초기화: tenant_id={self._tenant_id}")
|
|
182
|
+
|
|
183
|
+
def _run(self, query: str) -> str:
|
|
184
|
+
try:
|
|
185
|
+
log(f"Memento 문서 검색 시작: tenant_id='{self._tenant_id}', query='{query}'")
|
|
186
|
+
response = requests.post(
|
|
187
|
+
"http://memento.process-gpt.io/retrieve",
|
|
188
|
+
json={"query": query, "options": {"tenant_id": self._tenant_id}}
|
|
189
|
+
)
|
|
190
|
+
if response.status_code != 200:
|
|
191
|
+
return f"API 오류: {response.status_code}"
|
|
192
|
+
data = response.json()
|
|
193
|
+
if not data.get("response"):
|
|
194
|
+
return f"테넌트 '{self._tenant_id}'에서 '{query}' 검색 결과가 없습니다."
|
|
195
|
+
results = []
|
|
196
|
+
docs = data.get("response", [])
|
|
197
|
+
log(f"Memento 검색 결과 개수: {len(docs)}")
|
|
198
|
+
for doc in docs:
|
|
199
|
+
fname = doc.get('metadata', {}).get('file_name', 'unknown')
|
|
200
|
+
idx = doc.get('metadata', {}).get('chunk_index', 'unknown')
|
|
201
|
+
content = doc.get('page_content', '')
|
|
202
|
+
results.append(f"📄 파일: {fname} (청크 #{idx})\n내용: {content}\n---")
|
|
203
|
+
return f"테넌트 '{self._tenant_id}'에서 '{query}' 검색 결과:\n\n" + "\n".join(results)
|
|
204
|
+
except Exception as e:
|
|
205
|
+
handle_error("문서검색오류", e, raise_error=False)
|
|
206
|
+
return f"문서검색오류: {e}"
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import subprocess
|
|
3
|
+
import time
|
|
4
|
+
from typing import List, Dict, Optional
|
|
5
|
+
import anyio
|
|
6
|
+
from mcp.client.stdio import StdioServerParameters
|
|
7
|
+
from crewai_tools import MCPServerAdapter
|
|
8
|
+
from .knowledge_tools import Mem0Tool, MementoTool
|
|
9
|
+
from ..utils.logger import log, handle_error
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SafeToolLoader:
|
|
13
|
+
"""도구 로더 클래스"""
|
|
14
|
+
adapters = [] # MCPServerAdapter 인스턴스 등록
|
|
15
|
+
|
|
16
|
+
ANYIO_PATCHED: bool = False
|
|
17
|
+
|
|
18
|
+
def __init__(self, tenant_id: Optional[str] = None, user_id: Optional[str] = None, agent_name: Optional[str] = None, mcp_config: Optional[Dict] = None):
|
|
19
|
+
self.tenant_id = tenant_id
|
|
20
|
+
self.user_id = user_id
|
|
21
|
+
self.agent_name = agent_name
|
|
22
|
+
# 외부에서 전달된 MCP 설정 사용 (DB 접근 금지)
|
|
23
|
+
self._mcp_servers = (mcp_config or {}).get('mcpServers', {})
|
|
24
|
+
self.local_tools = ["mem0", "memento", "human_asked"]
|
|
25
|
+
log(f"SafeToolLoader 초기화 완료 (tenant_id: {tenant_id}, user_id: {user_id})")
|
|
26
|
+
|
|
27
|
+
def warmup_server(self, server_key: str):
|
|
28
|
+
"""npx 기반 서버의 패키지를 미리 캐시에 저장해 실제 실행을 빠르게."""
|
|
29
|
+
cfg = self._get_mcp_config(server_key)
|
|
30
|
+
if not cfg or cfg.get("command") != "npx":
|
|
31
|
+
return
|
|
32
|
+
|
|
33
|
+
npx = self._find_npx_command()
|
|
34
|
+
if not npx:
|
|
35
|
+
return
|
|
36
|
+
|
|
37
|
+
args = cfg.get("args", [])
|
|
38
|
+
if not (args and args[0] == "-y"):
|
|
39
|
+
return
|
|
40
|
+
|
|
41
|
+
pkg = args[1]
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
subprocess.run([npx, "-y", pkg, "--help"], capture_output=True, timeout=10, shell=True)
|
|
45
|
+
return
|
|
46
|
+
except subprocess.TimeoutExpired:
|
|
47
|
+
pass
|
|
48
|
+
except Exception:
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
try:
|
|
52
|
+
subprocess.run([npx, "-y", pkg, "--help"], capture_output=True, timeout=60, shell=True)
|
|
53
|
+
except Exception:
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
def _find_npx_command(self) -> str:
|
|
57
|
+
"""npx 명령어 경로 찾기"""
|
|
58
|
+
try:
|
|
59
|
+
import shutil
|
|
60
|
+
npx_path = shutil.which("npx") or shutil.which("npx.cmd")
|
|
61
|
+
if npx_path:
|
|
62
|
+
return npx_path
|
|
63
|
+
except Exception:
|
|
64
|
+
pass
|
|
65
|
+
return "npx"
|
|
66
|
+
|
|
67
|
+
def create_tools_from_names(self, tool_names: List[str]) -> List:
|
|
68
|
+
"""tool_names 리스트에서 실제 Tool 객체들 생성"""
|
|
69
|
+
if isinstance(tool_names, str):
|
|
70
|
+
tool_names = [tool_names]
|
|
71
|
+
log(f"도구 생성 요청: {tool_names}")
|
|
72
|
+
|
|
73
|
+
tools = []
|
|
74
|
+
|
|
75
|
+
tools.extend(self._load_mem0())
|
|
76
|
+
tools.extend(self._load_memento())
|
|
77
|
+
tools.extend(self._load_human_asked())
|
|
78
|
+
|
|
79
|
+
for name in tool_names:
|
|
80
|
+
key = name.strip().lower()
|
|
81
|
+
if key in self.local_tools:
|
|
82
|
+
continue
|
|
83
|
+
else:
|
|
84
|
+
self.warmup_server(key)
|
|
85
|
+
tools.extend(self._load_mcp_tool(key))
|
|
86
|
+
|
|
87
|
+
log(f"총 {len(tools)}개 도구 생성 완료")
|
|
88
|
+
return tools
|
|
89
|
+
|
|
90
|
+
def _load_mem0(self) -> List:
|
|
91
|
+
"""mem0 도구 로드 - 에이전트별 메모리"""
|
|
92
|
+
try:
|
|
93
|
+
if not self.user_id:
|
|
94
|
+
log("mem0 도구 로드 생략: user_id 없음")
|
|
95
|
+
return []
|
|
96
|
+
return [Mem0Tool(tenant_id=self.tenant_id, user_id=self.user_id)]
|
|
97
|
+
except Exception as e:
|
|
98
|
+
handle_error("툴mem0오류", e, raise_error=False)
|
|
99
|
+
return []
|
|
100
|
+
|
|
101
|
+
def _load_memento(self) -> List:
|
|
102
|
+
"""memento 도구 로드"""
|
|
103
|
+
try:
|
|
104
|
+
return [MementoTool(tenant_id=self.tenant_id)]
|
|
105
|
+
except Exception as e:
|
|
106
|
+
handle_error("툴memento오류", e, raise_error=False)
|
|
107
|
+
return []
|
|
108
|
+
|
|
109
|
+
def _load_human_asked(self) -> List:
|
|
110
|
+
"""human_asked 도구 로드 (선택사항: 사용 시 외부에서 주입)"""
|
|
111
|
+
try:
|
|
112
|
+
# 필요한 경우 외부에서 HumanQueryTool을 이 패키지에 추가하여 import하고 리턴하도록 변경 가능
|
|
113
|
+
return []
|
|
114
|
+
except Exception as e:
|
|
115
|
+
handle_error("툴human오류", e, raise_error=False)
|
|
116
|
+
return []
|
|
117
|
+
|
|
118
|
+
def _load_mcp_tool(self, tool_name: str) -> List:
|
|
119
|
+
"""MCP 도구 로드 (timeout & retry 지원)"""
|
|
120
|
+
self._apply_anyio_patch()
|
|
121
|
+
|
|
122
|
+
server_cfg = self._get_mcp_config(tool_name)
|
|
123
|
+
if not server_cfg:
|
|
124
|
+
return []
|
|
125
|
+
|
|
126
|
+
env_vars = os.environ.copy()
|
|
127
|
+
env_vars.update(server_cfg.get("env", {}))
|
|
128
|
+
timeout = server_cfg.get("timeout", 40)
|
|
129
|
+
|
|
130
|
+
max_retries = 2
|
|
131
|
+
retry_delay = 5
|
|
132
|
+
|
|
133
|
+
for attempt in range(1, max_retries + 1):
|
|
134
|
+
try:
|
|
135
|
+
cmd = server_cfg["command"]
|
|
136
|
+
if cmd == "npx":
|
|
137
|
+
cmd = self._find_npx_command() or cmd
|
|
138
|
+
|
|
139
|
+
params = StdioServerParameters(
|
|
140
|
+
command=cmd,
|
|
141
|
+
args=server_cfg.get("args", []),
|
|
142
|
+
env=env_vars,
|
|
143
|
+
timeout=timeout
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
adapter = MCPServerAdapter(params)
|
|
147
|
+
SafeToolLoader.adapters.append(adapter)
|
|
148
|
+
log(f"{tool_name} MCP 로드 성공 (툴 {len(adapter.tools)}개): {[tool.name for tool in adapter.tools]}")
|
|
149
|
+
return adapter.tools
|
|
150
|
+
|
|
151
|
+
except Exception as e:
|
|
152
|
+
if attempt < max_retries:
|
|
153
|
+
time.sleep(retry_delay)
|
|
154
|
+
else:
|
|
155
|
+
handle_error(f"툴{tool_name}오류", e, raise_error=False)
|
|
156
|
+
return []
|
|
157
|
+
|
|
158
|
+
def _apply_anyio_patch(self):
|
|
159
|
+
"""anyio stderr 패치 적용"""
|
|
160
|
+
if SafeToolLoader.ANYIO_PATCHED:
|
|
161
|
+
return
|
|
162
|
+
from anyio._core._subprocesses import open_process as _orig
|
|
163
|
+
|
|
164
|
+
async def patched_open_process(*args, **kwargs):
|
|
165
|
+
stderr = kwargs.get('stderr')
|
|
166
|
+
if not (hasattr(stderr, 'fileno') and stderr.fileno()):
|
|
167
|
+
kwargs['stderr'] = subprocess.PIPE
|
|
168
|
+
return await _orig(*args, **kwargs)
|
|
169
|
+
|
|
170
|
+
anyio.open_process = patched_open_process
|
|
171
|
+
anyio._core._subprocesses.open_process = patched_open_process
|
|
172
|
+
SafeToolLoader.ANYIO_PATCHED = True
|
|
173
|
+
|
|
174
|
+
def _get_mcp_config(self, tool_name: str) -> dict:
|
|
175
|
+
"""전달받은 mcp_config에서 툴별 설정을 조회."""
|
|
176
|
+
try:
|
|
177
|
+
return self._mcp_servers.get(tool_name, {}) if self._mcp_servers else {}
|
|
178
|
+
except Exception as e:
|
|
179
|
+
handle_error("툴설정오류", e, raise_error=False)
|
|
180
|
+
return {}
|
|
181
|
+
|
|
182
|
+
@classmethod
|
|
183
|
+
def shutdown_all_adapters(cls):
|
|
184
|
+
"""모든 MCPServerAdapter 연결 종료"""
|
|
185
|
+
for adapter in cls.adapters:
|
|
186
|
+
try:
|
|
187
|
+
adapter.stop()
|
|
188
|
+
except Exception as e:
|
|
189
|
+
handle_error("툴종료오류", e, raise_error=True)
|
|
190
|
+
log("모든 MCPServerAdapter 연결 종료 완료")
|
|
191
|
+
cls.adapters.clear()
|
|
File without changes
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict
|
|
4
|
+
|
|
5
|
+
from a2a.server.events import Event
|
|
6
|
+
from .logger import handle_error as _emit_error, log as _emit_log
|
|
7
|
+
from ..core.database import record_event
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _event_to_dict(event: Event) -> Dict[str, Any]:
|
|
11
|
+
try:
|
|
12
|
+
if hasattr(event, "__dict__"):
|
|
13
|
+
return {k: v for k, v in event.__dict__.items() if not k.startswith("_")}
|
|
14
|
+
return {"event": str(event)}
|
|
15
|
+
except Exception as e:
|
|
16
|
+
_emit_error("event dict 변환 실패", e)
|
|
17
|
+
return {"event": str(event)}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def route_event(todo: Dict[str, Any], event: Event) -> None:
|
|
21
|
+
"""이벤트를 dict으로 변환해 events 테이블에 기록.
|
|
22
|
+
|
|
23
|
+
- 복잡한 라우팅/분기는 추후 확장. 현재는 단일 events 테이블에 기록.
|
|
24
|
+
- event_type은 None으로 두거나, 필요 시 상위에서 지정하도록 추후 확장 가능.
|
|
25
|
+
"""
|
|
26
|
+
data = _event_to_dict(event)
|
|
27
|
+
await record_event(todo, data, event_type=None)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import traceback
|
|
4
|
+
from typing import Optional, Dict
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
# Configure root logger only once (idempotent)
|
|
8
|
+
if not logging.getLogger().handlers:
|
|
9
|
+
logging.basicConfig(
|
|
10
|
+
level=logging.INFO,
|
|
11
|
+
format="%(asctime)s %(levelname)s %(name)s - %(message)s",
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
_logger = logging.getLogger("process-gpt-agent-framework")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def log(message: str, level: int = logging.INFO) -> None:
|
|
18
|
+
spaced = os.getenv("LOG_SPACED", "1") != "0"
|
|
19
|
+
suffix = "\n" if spaced else ""
|
|
20
|
+
_logger.log(level, f"{message}{suffix}")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def handle_error(title: str, error: Exception, *, raise_error: bool = False, extra: Optional[Dict] = None) -> None:
|
|
24
|
+
spaced = os.getenv("LOG_SPACED", "1") != "0"
|
|
25
|
+
suffix = "\n" if spaced else ""
|
|
26
|
+
context = f" | extra={extra}" if extra else ""
|
|
27
|
+
_logger.error(f"{title}: {error}{context}{suffix}")
|
|
28
|
+
_logger.error(traceback.format_exc())
|
|
29
|
+
if raise_error:
|
|
30
|
+
raise error
|