nvidia-nat 1.3.0a20250910__py3-none-any.whl → 1.4.0a20251112__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.
- nat/agent/base.py +13 -8
- nat/agent/prompt_optimizer/prompt.py +68 -0
- nat/agent/prompt_optimizer/register.py +149 -0
- nat/agent/react_agent/agent.py +6 -5
- nat/agent/react_agent/register.py +49 -39
- nat/agent/reasoning_agent/reasoning_agent.py +17 -15
- nat/agent/register.py +2 -0
- nat/agent/responses_api_agent/__init__.py +14 -0
- nat/agent/responses_api_agent/register.py +126 -0
- nat/agent/rewoo_agent/agent.py +304 -117
- nat/agent/rewoo_agent/prompt.py +19 -22
- nat/agent/rewoo_agent/register.py +51 -38
- nat/agent/tool_calling_agent/agent.py +75 -17
- nat/agent/tool_calling_agent/register.py +46 -23
- nat/authentication/api_key/api_key_auth_provider.py +6 -11
- nat/authentication/api_key/api_key_auth_provider_config.py +8 -5
- nat/authentication/credential_validator/__init__.py +14 -0
- nat/authentication/credential_validator/bearer_token_validator.py +557 -0
- nat/authentication/http_basic_auth/http_basic_auth_provider.py +1 -1
- nat/authentication/interfaces.py +5 -2
- nat/authentication/oauth2/oauth2_auth_code_flow_provider.py +69 -36
- nat/authentication/oauth2/oauth2_auth_code_flow_provider_config.py +2 -1
- nat/authentication/oauth2/oauth2_resource_server_config.py +125 -0
- nat/builder/builder.py +55 -23
- nat/builder/component_utils.py +9 -5
- nat/builder/context.py +54 -15
- nat/builder/eval_builder.py +14 -9
- nat/builder/framework_enum.py +1 -0
- nat/builder/front_end.py +1 -1
- nat/builder/function.py +370 -0
- nat/builder/function_info.py +1 -1
- nat/builder/intermediate_step_manager.py +38 -2
- nat/builder/workflow.py +5 -0
- nat/builder/workflow_builder.py +306 -54
- nat/cli/cli_utils/config_override.py +1 -1
- nat/cli/commands/info/info.py +16 -6
- nat/cli/commands/mcp/__init__.py +14 -0
- nat/cli/commands/mcp/mcp.py +986 -0
- nat/cli/commands/optimize.py +90 -0
- nat/cli/commands/start.py +1 -1
- nat/cli/commands/workflow/templates/config.yml.j2 +14 -13
- nat/cli/commands/workflow/templates/register.py.j2 +2 -2
- nat/cli/commands/workflow/templates/workflow.py.j2 +35 -21
- nat/cli/commands/workflow/workflow_commands.py +60 -18
- nat/cli/entrypoint.py +15 -11
- nat/cli/main.py +3 -0
- nat/cli/register_workflow.py +38 -4
- nat/cli/type_registry.py +72 -1
- nat/control_flow/__init__.py +0 -0
- nat/control_flow/register.py +20 -0
- nat/control_flow/router_agent/__init__.py +0 -0
- nat/control_flow/router_agent/agent.py +329 -0
- nat/control_flow/router_agent/prompt.py +48 -0
- nat/control_flow/router_agent/register.py +91 -0
- nat/control_flow/sequential_executor.py +166 -0
- nat/data_models/agent.py +34 -0
- nat/data_models/api_server.py +199 -69
- nat/data_models/authentication.py +23 -9
- nat/data_models/common.py +47 -0
- nat/data_models/component.py +2 -0
- nat/data_models/component_ref.py +11 -0
- nat/data_models/config.py +41 -17
- nat/data_models/dataset_handler.py +4 -3
- nat/data_models/function.py +34 -0
- nat/data_models/function_dependencies.py +8 -0
- nat/data_models/intermediate_step.py +9 -1
- nat/data_models/llm.py +15 -1
- nat/data_models/openai_mcp.py +46 -0
- nat/data_models/optimizable.py +208 -0
- nat/data_models/optimizer.py +161 -0
- nat/data_models/span.py +41 -3
- nat/data_models/thinking_mixin.py +2 -2
- nat/embedder/azure_openai_embedder.py +2 -1
- nat/embedder/nim_embedder.py +3 -2
- nat/embedder/openai_embedder.py +3 -2
- nat/eval/config.py +1 -1
- nat/eval/dataset_handler/dataset_downloader.py +3 -2
- nat/eval/dataset_handler/dataset_filter.py +34 -2
- nat/eval/evaluate.py +10 -3
- nat/eval/evaluator/base_evaluator.py +1 -1
- nat/eval/rag_evaluator/evaluate.py +7 -4
- nat/eval/register.py +4 -0
- nat/eval/runtime_evaluator/__init__.py +14 -0
- nat/eval/runtime_evaluator/evaluate.py +123 -0
- nat/eval/runtime_evaluator/register.py +100 -0
- nat/eval/swe_bench_evaluator/evaluate.py +1 -1
- nat/eval/trajectory_evaluator/register.py +1 -1
- nat/eval/tunable_rag_evaluator/evaluate.py +1 -1
- nat/eval/usage_stats.py +2 -0
- nat/eval/utils/output_uploader.py +3 -2
- nat/eval/utils/weave_eval.py +17 -3
- nat/experimental/decorators/experimental_warning_decorator.py +27 -7
- nat/experimental/test_time_compute/functions/execute_score_select_function.py +1 -1
- nat/experimental/test_time_compute/functions/plan_select_execute_function.py +7 -3
- nat/experimental/test_time_compute/functions/ttc_tool_orchestration_function.py +1 -1
- nat/experimental/test_time_compute/functions/ttc_tool_wrapper_function.py +3 -3
- nat/experimental/test_time_compute/models/strategy_base.py +2 -2
- nat/experimental/test_time_compute/selection/llm_based_output_merging_selector.py +1 -1
- nat/front_ends/console/authentication_flow_handler.py +82 -30
- nat/front_ends/console/console_front_end_plugin.py +19 -7
- nat/front_ends/fastapi/auth_flow_handlers/http_flow_handler.py +1 -1
- nat/front_ends/fastapi/auth_flow_handlers/websocket_flow_handler.py +52 -17
- nat/front_ends/fastapi/dask_client_mixin.py +65 -0
- nat/front_ends/fastapi/fastapi_front_end_config.py +25 -3
- nat/front_ends/fastapi/fastapi_front_end_plugin.py +140 -3
- nat/front_ends/fastapi/fastapi_front_end_plugin_worker.py +445 -265
- nat/front_ends/fastapi/job_store.py +518 -99
- nat/front_ends/fastapi/main.py +11 -19
- nat/front_ends/fastapi/message_handler.py +69 -44
- nat/front_ends/fastapi/message_validator.py +8 -7
- nat/front_ends/fastapi/utils.py +57 -0
- nat/front_ends/mcp/introspection_token_verifier.py +73 -0
- nat/front_ends/mcp/mcp_front_end_config.py +71 -3
- nat/front_ends/mcp/mcp_front_end_plugin.py +85 -21
- nat/front_ends/mcp/mcp_front_end_plugin_worker.py +248 -29
- nat/front_ends/mcp/memory_profiler.py +320 -0
- nat/front_ends/mcp/tool_converter.py +78 -25
- nat/front_ends/simple_base/simple_front_end_plugin_base.py +3 -1
- nat/llm/aws_bedrock_llm.py +21 -8
- nat/llm/azure_openai_llm.py +14 -5
- nat/llm/litellm_llm.py +80 -0
- nat/llm/nim_llm.py +23 -9
- nat/llm/openai_llm.py +19 -7
- nat/llm/register.py +4 -0
- nat/llm/utils/thinking.py +1 -1
- nat/observability/exporter/base_exporter.py +1 -1
- nat/observability/exporter/processing_exporter.py +29 -55
- nat/observability/exporter/span_exporter.py +43 -15
- nat/observability/exporter_manager.py +2 -2
- nat/observability/mixin/redaction_config_mixin.py +5 -4
- nat/observability/mixin/tagging_config_mixin.py +26 -14
- nat/observability/mixin/type_introspection_mixin.py +420 -107
- nat/observability/processor/batching_processor.py +1 -1
- nat/observability/processor/processor.py +3 -0
- nat/observability/processor/redaction/__init__.py +24 -0
- nat/observability/processor/redaction/contextual_redaction_processor.py +125 -0
- nat/observability/processor/redaction/contextual_span_redaction_processor.py +66 -0
- nat/observability/processor/redaction/redaction_processor.py +177 -0
- nat/observability/processor/redaction/span_header_redaction_processor.py +92 -0
- nat/observability/processor/span_tagging_processor.py +21 -14
- nat/observability/register.py +16 -0
- nat/profiler/callbacks/langchain_callback_handler.py +32 -7
- nat/profiler/callbacks/llama_index_callback_handler.py +36 -2
- nat/profiler/callbacks/token_usage_base_model.py +2 -0
- nat/profiler/decorators/framework_wrapper.py +61 -9
- nat/profiler/decorators/function_tracking.py +35 -3
- nat/profiler/forecasting/models/linear_model.py +1 -1
- nat/profiler/forecasting/models/random_forest_regressor.py +1 -1
- nat/profiler/inference_optimization/bottleneck_analysis/nested_stack_analysis.py +1 -1
- nat/profiler/inference_optimization/experimental/prefix_span_analysis.py +1 -1
- nat/profiler/parameter_optimization/__init__.py +0 -0
- nat/profiler/parameter_optimization/optimizable_utils.py +93 -0
- nat/profiler/parameter_optimization/optimizer_runtime.py +67 -0
- nat/profiler/parameter_optimization/parameter_optimizer.py +189 -0
- nat/profiler/parameter_optimization/parameter_selection.py +107 -0
- nat/profiler/parameter_optimization/pareto_visualizer.py +460 -0
- nat/profiler/parameter_optimization/prompt_optimizer.py +384 -0
- nat/profiler/parameter_optimization/update_helpers.py +66 -0
- nat/profiler/utils.py +3 -1
- nat/registry_handlers/pypi/register_pypi.py +5 -3
- nat/registry_handlers/rest/register_rest.py +5 -3
- nat/retriever/milvus/retriever.py +1 -1
- nat/retriever/nemo_retriever/register.py +2 -1
- nat/runtime/loader.py +1 -1
- nat/runtime/runner.py +111 -6
- nat/runtime/session.py +49 -3
- nat/settings/global_settings.py +2 -2
- nat/tool/chat_completion.py +4 -1
- nat/tool/code_execution/code_sandbox.py +3 -6
- nat/tool/code_execution/local_sandbox/Dockerfile.sandbox +19 -32
- nat/tool/code_execution/local_sandbox/local_sandbox_server.py +6 -1
- nat/tool/code_execution/local_sandbox/sandbox.requirements.txt +2 -0
- nat/tool/code_execution/local_sandbox/start_local_sandbox.sh +10 -4
- nat/tool/datetime_tools.py +1 -1
- nat/tool/github_tools.py +450 -0
- nat/tool/memory_tools/add_memory_tool.py +3 -3
- nat/tool/memory_tools/delete_memory_tool.py +3 -4
- nat/tool/memory_tools/get_memory_tool.py +4 -4
- nat/tool/register.py +2 -7
- nat/tool/server_tools.py +15 -2
- nat/utils/__init__.py +76 -0
- nat/utils/callable_utils.py +70 -0
- nat/utils/data_models/schema_validator.py +1 -1
- nat/utils/decorators.py +210 -0
- nat/utils/exception_handlers/automatic_retries.py +278 -72
- nat/utils/io/yaml_tools.py +73 -3
- nat/utils/log_levels.py +25 -0
- nat/utils/responses_api.py +26 -0
- nat/utils/string_utils.py +16 -0
- nat/utils/type_converter.py +12 -3
- nat/utils/type_utils.py +6 -2
- nvidia_nat-1.4.0a20251112.dist-info/METADATA +197 -0
- {nvidia_nat-1.3.0a20250910.dist-info → nvidia_nat-1.4.0a20251112.dist-info}/RECORD +199 -165
- {nvidia_nat-1.3.0a20250910.dist-info → nvidia_nat-1.4.0a20251112.dist-info}/entry_points.txt +1 -0
- nat/cli/commands/info/list_mcp.py +0 -461
- nat/data_models/temperature_mixin.py +0 -43
- nat/data_models/top_p_mixin.py +0 -43
- nat/observability/processor/header_redaction_processor.py +0 -123
- nat/observability/processor/redaction_processor.py +0 -77
- nat/tool/code_execution/test_code_execution_sandbox.py +0 -414
- nat/tool/github_tools/create_github_commit.py +0 -133
- nat/tool/github_tools/create_github_issue.py +0 -87
- nat/tool/github_tools/create_github_pr.py +0 -106
- nat/tool/github_tools/get_github_file.py +0 -106
- nat/tool/github_tools/get_github_issue.py +0 -166
- nat/tool/github_tools/get_github_pr.py +0 -256
- nat/tool/github_tools/update_github_issue.py +0 -100
- nvidia_nat-1.3.0a20250910.dist-info/METADATA +0 -373
- /nat/{tool/github_tools → agent/prompt_optimizer}/__init__.py +0 -0
- {nvidia_nat-1.3.0a20250910.dist-info → nvidia_nat-1.4.0a20251112.dist-info}/WHEEL +0 -0
- {nvidia_nat-1.3.0a20250910.dist-info → nvidia_nat-1.4.0a20251112.dist-info}/licenses/LICENSE-3rd-party.txt +0 -0
- {nvidia_nat-1.3.0a20250910.dist-info → nvidia_nat-1.4.0a20251112.dist-info}/licenses/LICENSE.md +0 -0
- {nvidia_nat-1.3.0a20250910.dist-info → nvidia_nat-1.4.0a20251112.dist-info}/top_level.txt +0 -0
|
@@ -14,9 +14,9 @@
|
|
|
14
14
|
# limitations under the License.
|
|
15
15
|
|
|
16
16
|
import asyncio
|
|
17
|
+
import json
|
|
17
18
|
import logging
|
|
18
19
|
import os
|
|
19
|
-
import time
|
|
20
20
|
import typing
|
|
21
21
|
from abc import ABC
|
|
22
22
|
from abc import abstractmethod
|
|
@@ -25,19 +25,21 @@ from collections.abc import Callable
|
|
|
25
25
|
from contextlib import asynccontextmanager
|
|
26
26
|
from pathlib import Path
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
import httpx
|
|
29
|
+
from authlib.common.errors import AuthlibBaseError as OAuthError
|
|
29
30
|
from fastapi import Body
|
|
30
31
|
from fastapi import FastAPI
|
|
32
|
+
from fastapi import HTTPException
|
|
31
33
|
from fastapi import Request
|
|
32
34
|
from fastapi import Response
|
|
33
35
|
from fastapi import UploadFile
|
|
34
|
-
from fastapi.exceptions import HTTPException
|
|
35
36
|
from fastapi.middleware.cors import CORSMiddleware
|
|
36
37
|
from fastapi.responses import StreamingResponse
|
|
37
38
|
from pydantic import BaseModel
|
|
38
39
|
from pydantic import Field
|
|
39
40
|
from starlette.websockets import WebSocket
|
|
40
41
|
|
|
42
|
+
from nat.builder.function import Function
|
|
41
43
|
from nat.builder.workflow_builder import WorkflowBuilder
|
|
42
44
|
from nat.data_models.api_server import ChatRequest
|
|
43
45
|
from nat.data_models.api_server import ChatResponse
|
|
@@ -58,18 +60,30 @@ from nat.front_ends.fastapi.fastapi_front_end_config import EvaluateRequest
|
|
|
58
60
|
from nat.front_ends.fastapi.fastapi_front_end_config import EvaluateResponse
|
|
59
61
|
from nat.front_ends.fastapi.fastapi_front_end_config import EvaluateStatusResponse
|
|
60
62
|
from nat.front_ends.fastapi.fastapi_front_end_config import FastApiFrontEndConfig
|
|
61
|
-
from nat.front_ends.fastapi.job_store import JobInfo
|
|
62
|
-
from nat.front_ends.fastapi.job_store import JobStore
|
|
63
63
|
from nat.front_ends.fastapi.message_handler import WebSocketMessageHandler
|
|
64
64
|
from nat.front_ends.fastapi.response_helpers import generate_single_response
|
|
65
65
|
from nat.front_ends.fastapi.response_helpers import generate_streaming_response_as_str
|
|
66
66
|
from nat.front_ends.fastapi.response_helpers import generate_streaming_response_full_as_str
|
|
67
67
|
from nat.front_ends.fastapi.step_adaptor import StepAdaptor
|
|
68
|
+
from nat.front_ends.fastapi.utils import get_config_file_path
|
|
68
69
|
from nat.object_store.models import ObjectStoreItem
|
|
70
|
+
from nat.runtime.loader import load_workflow
|
|
69
71
|
from nat.runtime.session import SessionManager
|
|
70
72
|
|
|
71
73
|
logger = logging.getLogger(__name__)
|
|
72
74
|
|
|
75
|
+
_DASK_AVAILABLE = False
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
from nat.front_ends.fastapi.job_store import JobInfo
|
|
79
|
+
from nat.front_ends.fastapi.job_store import JobStatus
|
|
80
|
+
from nat.front_ends.fastapi.job_store import JobStore
|
|
81
|
+
_DASK_AVAILABLE = True
|
|
82
|
+
except ImportError:
|
|
83
|
+
JobInfo = None
|
|
84
|
+
JobStatus = None
|
|
85
|
+
JobStore = None
|
|
86
|
+
|
|
73
87
|
|
|
74
88
|
class FastApiFrontEndPluginWorkerBase(ABC):
|
|
75
89
|
|
|
@@ -80,10 +94,29 @@ class FastApiFrontEndPluginWorkerBase(ABC):
|
|
|
80
94
|
FastApiFrontEndConfig), ("Front end config is not FastApiFrontEndConfig")
|
|
81
95
|
|
|
82
96
|
self._front_end_config = config.general.front_end
|
|
83
|
-
|
|
84
|
-
self.
|
|
85
|
-
self._cleanup_tasks_lock = asyncio.Lock()
|
|
97
|
+
self._dask_available = False
|
|
98
|
+
self._job_store = None
|
|
86
99
|
self._http_flow_handler: HTTPAuthenticationFlowHandler | None = HTTPAuthenticationFlowHandler()
|
|
100
|
+
self._scheduler_address = os.environ.get("NAT_DASK_SCHEDULER_ADDRESS")
|
|
101
|
+
self._db_url = os.environ.get("NAT_JOB_STORE_DB_URL")
|
|
102
|
+
self._config_file_path = get_config_file_path()
|
|
103
|
+
|
|
104
|
+
if self._scheduler_address is not None:
|
|
105
|
+
if not _DASK_AVAILABLE:
|
|
106
|
+
raise RuntimeError("Dask is not available, please install it to use the FastAPI front end with Dask.")
|
|
107
|
+
|
|
108
|
+
if self._db_url is None:
|
|
109
|
+
raise RuntimeError(
|
|
110
|
+
"NAT_JOB_STORE_DB_URL must be set when using Dask (configure a persistent JobStore database).")
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
self._job_store = JobStore(scheduler_address=self._scheduler_address, db_url=self._db_url)
|
|
114
|
+
self._dask_available = True
|
|
115
|
+
logger.debug("Connected to Dask scheduler at %s", self._scheduler_address)
|
|
116
|
+
except Exception as e:
|
|
117
|
+
raise RuntimeError(f"Failed to connect to Dask scheduler at {self._scheduler_address}: {e}") from e
|
|
118
|
+
else:
|
|
119
|
+
logger.debug("No Dask scheduler address provided, running without Dask support.")
|
|
87
120
|
|
|
88
121
|
@property
|
|
89
122
|
def config(self) -> Config:
|
|
@@ -107,20 +140,6 @@ class FastApiFrontEndPluginWorkerBase(ABC):
|
|
|
107
140
|
|
|
108
141
|
yield
|
|
109
142
|
|
|
110
|
-
# If a cleanup task is running, cancel it
|
|
111
|
-
async with self._cleanup_tasks_lock:
|
|
112
|
-
|
|
113
|
-
# Cancel all cleanup tasks
|
|
114
|
-
for task_name in self._cleanup_tasks:
|
|
115
|
-
cleanup_task: asyncio.Task | None = getattr(starting_app.state, task_name, None)
|
|
116
|
-
if cleanup_task is not None:
|
|
117
|
-
logger.info("Cancelling %s cleanup task", task_name)
|
|
118
|
-
cleanup_task.cancel()
|
|
119
|
-
else:
|
|
120
|
-
logger.warning("No cleanup task found for %s", task_name)
|
|
121
|
-
|
|
122
|
-
self._cleanup_tasks.clear()
|
|
123
|
-
|
|
124
143
|
logger.debug("Closing NAT server from process %s", os.getpid())
|
|
125
144
|
|
|
126
145
|
nat_app = FastAPI(lifespan=lifespan)
|
|
@@ -208,32 +227,6 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
208
227
|
self._outstanding_flows: dict[str, FlowState] = {}
|
|
209
228
|
self._outstanding_flows_lock = asyncio.Lock()
|
|
210
229
|
|
|
211
|
-
@staticmethod
|
|
212
|
-
async def _periodic_cleanup(name: str, job_store: JobStore, sleep_time_sec: int = 300):
|
|
213
|
-
while True:
|
|
214
|
-
try:
|
|
215
|
-
job_store.cleanup_expired_jobs()
|
|
216
|
-
logger.debug("Expired %s jobs cleaned up", name)
|
|
217
|
-
except Exception as e:
|
|
218
|
-
logger.exception("Error during %s job cleanup: %s", name, e)
|
|
219
|
-
await asyncio.sleep(sleep_time_sec)
|
|
220
|
-
|
|
221
|
-
async def create_cleanup_task(self, app: FastAPI, name: str, job_store: JobStore, sleep_time_sec: int = 300):
|
|
222
|
-
# Schedule periodic cleanup of expired jobs on first job creation
|
|
223
|
-
attr_name = f"{name}_cleanup_task"
|
|
224
|
-
|
|
225
|
-
# Cheap check, if it doesn't exist, we will need to re-check after we acquire the lock
|
|
226
|
-
if not hasattr(app.state, attr_name):
|
|
227
|
-
async with self._cleanup_tasks_lock:
|
|
228
|
-
if not hasattr(app.state, attr_name):
|
|
229
|
-
logger.info("Starting %s periodic cleanup task", name)
|
|
230
|
-
setattr(
|
|
231
|
-
app.state,
|
|
232
|
-
attr_name,
|
|
233
|
-
asyncio.create_task(
|
|
234
|
-
self._periodic_cleanup(name=name, job_store=job_store, sleep_time_sec=sleep_time_sec)))
|
|
235
|
-
self._cleanup_tasks.append(attr_name)
|
|
236
|
-
|
|
237
230
|
def get_step_adaptor(self) -> StepAdaptor:
|
|
238
231
|
|
|
239
232
|
return StepAdaptor(self.front_end_config.step_adaptor)
|
|
@@ -247,14 +240,15 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
247
240
|
|
|
248
241
|
async def add_routes(self, app: FastAPI, builder: WorkflowBuilder):
|
|
249
242
|
|
|
250
|
-
await self.add_default_route(app, SessionManager(builder.build()))
|
|
251
|
-
await self.add_evaluate_route(app, SessionManager(builder.build()))
|
|
243
|
+
await self.add_default_route(app, SessionManager(await builder.build()))
|
|
244
|
+
await self.add_evaluate_route(app, SessionManager(await builder.build()))
|
|
252
245
|
await self.add_static_files_route(app, builder)
|
|
253
246
|
await self.add_authorization_route(app)
|
|
247
|
+
await self.add_mcp_client_tool_list_route(app, builder)
|
|
254
248
|
|
|
255
249
|
for ep in self.front_end_config.endpoints:
|
|
256
250
|
|
|
257
|
-
entry_workflow = builder.build(entry_function=ep.function_name)
|
|
251
|
+
entry_workflow = await builder.build(entry_function=ep.function_name)
|
|
258
252
|
|
|
259
253
|
await self.add_route(app, endpoint=ep, session_manager=SessionManager(entry_workflow))
|
|
260
254
|
|
|
@@ -276,52 +270,72 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
276
270
|
},
|
|
277
271
|
}
|
|
278
272
|
|
|
279
|
-
#
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
273
|
+
# TODO: Find another way to limit the number of concurrent evaluations
|
|
274
|
+
async def run_evaluation(scheduler_address: str,
|
|
275
|
+
db_url: str,
|
|
276
|
+
workflow_config_file_path: str,
|
|
277
|
+
job_id: str,
|
|
278
|
+
eval_config_file: str,
|
|
279
|
+
reps: int):
|
|
285
280
|
"""Background task to run the evaluation."""
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
281
|
+
job_store = JobStore(scheduler_address=scheduler_address, db_url=db_url)
|
|
282
|
+
|
|
283
|
+
try:
|
|
284
|
+
# We have two config files, one for the workflow and one for the evaluation
|
|
285
|
+
# Create EvaluationRunConfig using the CLI defaults
|
|
286
|
+
eval_config = EvaluationRunConfig(config_file=Path(eval_config_file), dataset=None, reps=reps)
|
|
287
|
+
|
|
288
|
+
# Create a new EvaluationRun with the evaluation-specific config
|
|
289
|
+
await job_store.update_status(job_id, JobStatus.RUNNING)
|
|
290
|
+
eval_runner = EvaluationRun(eval_config)
|
|
291
|
+
|
|
292
|
+
async with load_workflow(workflow_config_file_path) as local_session_manager:
|
|
293
|
+
output: EvaluationRunOutput = await eval_runner.run_and_evaluate(
|
|
294
|
+
session_manager=local_session_manager, job_id=job_id)
|
|
295
|
+
|
|
296
|
+
if output.workflow_interrupted:
|
|
297
|
+
await job_store.update_status(job_id, JobStatus.INTERRUPTED)
|
|
298
|
+
else:
|
|
299
|
+
parent_dir = os.path.dirname(output.workflow_output_file) if output.workflow_output_file else None
|
|
300
|
+
|
|
301
|
+
await job_store.update_status(job_id, JobStatus.SUCCESS, output_path=str(parent_dir))
|
|
302
|
+
except Exception as e:
|
|
303
|
+
logger.exception("Error in evaluation job %s", job_id)
|
|
304
|
+
await job_store.update_status(job_id, JobStatus.FAILURE, error=str(e))
|
|
305
|
+
|
|
306
|
+
async def start_evaluation(request: EvaluateRequest, http_request: Request):
|
|
308
307
|
"""Handle evaluation requests."""
|
|
309
308
|
|
|
310
309
|
async with session_manager.session(http_connection=http_request):
|
|
311
310
|
|
|
312
311
|
# if job_id is present and already exists return the job info
|
|
312
|
+
# There is a race condition between this check and the actual job submission, however if the client is
|
|
313
|
+
# supplying their own job_ids, then it is their responsibility to ensure that the job_id is unique.
|
|
313
314
|
if request.job_id:
|
|
314
|
-
|
|
315
|
-
if
|
|
316
|
-
return EvaluateResponse(job_id=
|
|
317
|
-
|
|
318
|
-
job_id =
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
315
|
+
job_status = await self._job_store.get_status(request.job_id)
|
|
316
|
+
if job_status != JobStatus.NOT_FOUND:
|
|
317
|
+
return EvaluateResponse(job_id=request.job_id, status=job_status)
|
|
318
|
+
|
|
319
|
+
job_id = self._job_store.ensure_job_id(request.job_id)
|
|
320
|
+
|
|
321
|
+
await self._job_store.submit_job(job_id=job_id,
|
|
322
|
+
config_file=request.config_file,
|
|
323
|
+
expiry_seconds=request.expiry_seconds,
|
|
324
|
+
job_fn=run_evaluation,
|
|
325
|
+
job_args=[
|
|
326
|
+
self._scheduler_address,
|
|
327
|
+
self._db_url,
|
|
328
|
+
self._config_file_path,
|
|
329
|
+
job_id,
|
|
330
|
+
request.config_file,
|
|
331
|
+
request.reps
|
|
332
|
+
])
|
|
333
|
+
|
|
334
|
+
logger.info("Submitted evaluation job %s with config %s", job_id, request.config_file)
|
|
335
|
+
|
|
336
|
+
return EvaluateResponse(job_id=job_id, status=JobStatus.SUBMITTED)
|
|
337
|
+
|
|
338
|
+
def translate_job_to_response(job: "JobInfo") -> EvaluateStatusResponse:
|
|
325
339
|
"""Translate a JobInfo object to an EvaluateStatusResponse."""
|
|
326
340
|
return EvaluateStatusResponse(job_id=job.job_id,
|
|
327
341
|
status=job.status,
|
|
@@ -330,7 +344,7 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
330
344
|
output_path=str(job.output_path),
|
|
331
345
|
created_at=job.created_at,
|
|
332
346
|
updated_at=job.updated_at,
|
|
333
|
-
expires_at=
|
|
347
|
+
expires_at=self._job_store.get_expires_at(job))
|
|
334
348
|
|
|
335
349
|
async def get_job_status(job_id: str, http_request: Request) -> EvaluateStatusResponse:
|
|
336
350
|
"""Get the status of an evaluation job."""
|
|
@@ -338,7 +352,7 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
338
352
|
|
|
339
353
|
async with session_manager.session(http_connection=http_request):
|
|
340
354
|
|
|
341
|
-
job =
|
|
355
|
+
job = await self._job_store.get_job(job_id)
|
|
342
356
|
if not job:
|
|
343
357
|
logger.warning("Job %s not found", job_id)
|
|
344
358
|
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
|
@@ -351,7 +365,7 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
351
365
|
|
|
352
366
|
async with session_manager.session(http_connection=http_request):
|
|
353
367
|
|
|
354
|
-
job =
|
|
368
|
+
job = await self._job_store.get_last_job()
|
|
355
369
|
if not job:
|
|
356
370
|
logger.warning("No jobs found when requesting last job status")
|
|
357
371
|
raise HTTPException(status_code=404, detail="No jobs found")
|
|
@@ -365,61 +379,65 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
365
379
|
|
|
366
380
|
if status is None:
|
|
367
381
|
logger.info("Getting all jobs")
|
|
368
|
-
jobs =
|
|
382
|
+
jobs = await self._job_store.get_all_jobs()
|
|
369
383
|
else:
|
|
370
384
|
logger.info("Getting jobs with status %s", status)
|
|
371
|
-
jobs =
|
|
385
|
+
jobs = await self._job_store.get_jobs_by_status(JobStatus(status))
|
|
386
|
+
|
|
372
387
|
logger.info("Found %d jobs", len(jobs))
|
|
373
388
|
return [translate_job_to_response(job) for job in jobs]
|
|
374
389
|
|
|
375
390
|
if self.front_end_config.evaluate.path:
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
391
|
+
if self._dask_available:
|
|
392
|
+
# Add last job endpoint first (most specific)
|
|
393
|
+
app.add_api_route(
|
|
394
|
+
path=f"{self.front_end_config.evaluate.path}/job/last",
|
|
395
|
+
endpoint=get_last_job_status,
|
|
396
|
+
methods=["GET"],
|
|
397
|
+
response_model=EvaluateStatusResponse,
|
|
398
|
+
description="Get the status of the last created evaluation job",
|
|
399
|
+
responses={
|
|
400
|
+
404: {
|
|
401
|
+
"description": "No jobs found"
|
|
402
|
+
}, 500: response_500
|
|
403
|
+
},
|
|
404
|
+
)
|
|
389
405
|
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
406
|
+
# Add specific job endpoint (least specific)
|
|
407
|
+
app.add_api_route(
|
|
408
|
+
path=f"{self.front_end_config.evaluate.path}/job/{{job_id}}",
|
|
409
|
+
endpoint=get_job_status,
|
|
410
|
+
methods=["GET"],
|
|
411
|
+
response_model=EvaluateStatusResponse,
|
|
412
|
+
description="Get the status of an evaluation job",
|
|
413
|
+
responses={
|
|
414
|
+
404: {
|
|
415
|
+
"description": "Job not found"
|
|
416
|
+
}, 500: response_500
|
|
417
|
+
},
|
|
418
|
+
)
|
|
403
419
|
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
420
|
+
# Add jobs endpoint with optional status query parameter
|
|
421
|
+
app.add_api_route(
|
|
422
|
+
path=f"{self.front_end_config.evaluate.path}/jobs",
|
|
423
|
+
endpoint=get_jobs,
|
|
424
|
+
methods=["GET"],
|
|
425
|
+
response_model=list[EvaluateStatusResponse],
|
|
426
|
+
description="Get all jobs, optionally filtered by status",
|
|
427
|
+
responses={500: response_500},
|
|
428
|
+
)
|
|
413
429
|
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
430
|
+
# Add HTTP endpoint for evaluation
|
|
431
|
+
app.add_api_route(
|
|
432
|
+
path=self.front_end_config.evaluate.path,
|
|
433
|
+
endpoint=start_evaluation,
|
|
434
|
+
methods=[self.front_end_config.evaluate.method],
|
|
435
|
+
response_model=EvaluateResponse,
|
|
436
|
+
description=self.front_end_config.evaluate.description,
|
|
437
|
+
responses={500: response_500},
|
|
438
|
+
)
|
|
439
|
+
else:
|
|
440
|
+
logger.warning("Dask is not available, evaluation endpoints will not be added.")
|
|
423
441
|
|
|
424
442
|
async def add_static_files_route(self, app: FastAPI, builder: WorkflowBuilder):
|
|
425
443
|
|
|
@@ -526,21 +544,28 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
526
544
|
GenerateStreamResponseType = workflow.streaming_output_schema
|
|
527
545
|
GenerateSingleResponseType = workflow.single_output_schema
|
|
528
546
|
|
|
529
|
-
#
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
547
|
+
# Skip async generation for custom routes (those with function_name)
|
|
548
|
+
if self._dask_available and not hasattr(endpoint, 'function_name'):
|
|
549
|
+
# Append job_id and expiry_seconds to the input schema, this effectively makes these reserved keywords
|
|
550
|
+
# Consider prefixing these with "nat_" to avoid conflicts
|
|
551
|
+
|
|
552
|
+
class AsyncGenerateRequest(GenerateBodyType):
|
|
553
|
+
job_id: str | None = Field(default=None, description="Unique identifier for the evaluation job")
|
|
554
|
+
sync_timeout: int = Field(
|
|
555
|
+
default=0,
|
|
556
|
+
ge=0,
|
|
557
|
+
le=300,
|
|
558
|
+
description="Attempt to perform the job synchronously up until `sync_timeout` sectonds, "
|
|
559
|
+
"if the job hasn't been completed by then a job_id will be returned with a status code of 202.")
|
|
560
|
+
expiry_seconds: int = Field(default=JobStore.DEFAULT_EXPIRY,
|
|
561
|
+
ge=JobStore.MIN_EXPIRY,
|
|
562
|
+
le=JobStore.MAX_EXPIRY,
|
|
563
|
+
description="Optional time (in seconds) before the job expires. "
|
|
564
|
+
"Clamped between 600 (10 min) and 86400 (24h).")
|
|
565
|
+
|
|
566
|
+
def validate_model(self):
|
|
567
|
+
# Override to ensure that the parent class validator is not called
|
|
568
|
+
return self
|
|
544
569
|
|
|
545
570
|
# Ensure that the input is in the body. POD types are treated as query parameters
|
|
546
571
|
if (not issubclass(GenerateBodyType, BaseModel)):
|
|
@@ -560,12 +585,6 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
560
585
|
},
|
|
561
586
|
}
|
|
562
587
|
|
|
563
|
-
# Create job store for tracking async generation jobs
|
|
564
|
-
job_store = JobStore()
|
|
565
|
-
|
|
566
|
-
# Run up to max_running_async_jobs jobs at the same time
|
|
567
|
-
async_job_concurrency = asyncio.Semaphore(self._front_end_config.max_running_async_jobs)
|
|
568
|
-
|
|
569
588
|
def get_single_endpoint(result_type: type | None):
|
|
570
589
|
|
|
571
590
|
async def get_single(response: Response, request: Request):
|
|
@@ -675,10 +694,13 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
675
694
|
|
|
676
695
|
async def post_openai_api_compatible(response: Response, request: Request, payload: request_type):
|
|
677
696
|
# Check if streaming is requested
|
|
697
|
+
|
|
698
|
+
response.headers["Content-Type"] = "application/json"
|
|
678
699
|
stream_requested = getattr(payload, 'stream', False)
|
|
679
700
|
|
|
680
701
|
async with session_manager.session(http_connection=request):
|
|
681
702
|
if stream_requested:
|
|
703
|
+
|
|
682
704
|
# Return streaming response
|
|
683
705
|
return StreamingResponse(headers={"Content-Type": "text/event-stream; charset=utf-8"},
|
|
684
706
|
content=generate_streaming_response_as_str(
|
|
@@ -689,71 +711,48 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
689
711
|
result_type=ChatResponseChunk,
|
|
690
712
|
output_type=ChatResponseChunk))
|
|
691
713
|
|
|
692
|
-
|
|
693
|
-
try:
|
|
694
|
-
response.headers["Content-Type"] = "application/json"
|
|
695
|
-
return await generate_single_response(payload, session_manager, result_type=ChatResponse)
|
|
696
|
-
except ValueError as e:
|
|
697
|
-
if "Cannot get a single output value for streaming workflows" in str(e):
|
|
698
|
-
# Workflow only supports streaming, but client requested non-streaming
|
|
699
|
-
# Fall back to streaming and collect the result
|
|
700
|
-
chunks = []
|
|
701
|
-
async for chunk_str in generate_streaming_response_as_str(
|
|
702
|
-
payload,
|
|
703
|
-
session_manager=session_manager,
|
|
704
|
-
streaming=True,
|
|
705
|
-
step_adaptor=self.get_step_adaptor(),
|
|
706
|
-
result_type=ChatResponseChunk,
|
|
707
|
-
output_type=ChatResponseChunk):
|
|
708
|
-
if chunk_str.startswith("data: ") and not chunk_str.startswith("data: [DONE]"):
|
|
709
|
-
chunk_data = chunk_str[6:].strip() # Remove "data: " prefix
|
|
710
|
-
if chunk_data:
|
|
711
|
-
try:
|
|
712
|
-
chunk_json = ChatResponseChunk.model_validate_json(chunk_data)
|
|
713
|
-
if (chunk_json.choices and len(chunk_json.choices) > 0
|
|
714
|
-
and chunk_json.choices[0].delta
|
|
715
|
-
and chunk_json.choices[0].delta.content is not None):
|
|
716
|
-
chunks.append(chunk_json.choices[0].delta.content)
|
|
717
|
-
except Exception:
|
|
718
|
-
continue
|
|
719
|
-
|
|
720
|
-
# Create a single response from collected chunks
|
|
721
|
-
content = "".join(chunks)
|
|
722
|
-
single_response = ChatResponse.from_string(content)
|
|
723
|
-
response.headers["Content-Type"] = "application/json"
|
|
724
|
-
return single_response
|
|
725
|
-
raise
|
|
714
|
+
return await generate_single_response(payload, session_manager, result_type=ChatResponse)
|
|
726
715
|
|
|
727
716
|
return post_openai_api_compatible
|
|
728
717
|
|
|
729
|
-
|
|
730
|
-
"""Background task to run the evaluation."""
|
|
731
|
-
async with async_job_concurrency:
|
|
732
|
-
try:
|
|
733
|
-
result = await generate_single_response(payload=payload,
|
|
734
|
-
session_manager=session_manager,
|
|
735
|
-
result_type=result_type)
|
|
736
|
-
job_store.update_status(job_id, "success", output=result)
|
|
737
|
-
except Exception as e:
|
|
738
|
-
logger.exception("Error in evaluation job %s: %s", job_id, e)
|
|
739
|
-
job_store.update_status(job_id, "failure", error=str(e))
|
|
740
|
-
|
|
741
|
-
def _job_status_to_response(job: JobInfo) -> AsyncGenerationStatusResponse:
|
|
718
|
+
def _job_status_to_response(job: "JobInfo") -> AsyncGenerationStatusResponse:
|
|
742
719
|
job_output = job.output
|
|
743
720
|
if job_output is not None:
|
|
744
|
-
|
|
721
|
+
try:
|
|
722
|
+
job_output = json.loads(job_output)
|
|
723
|
+
except json.JSONDecodeError:
|
|
724
|
+
logger.error("Failed to parse job output as JSON: %s", job_output)
|
|
725
|
+
job_output = {"error": "Output parsing failed"}
|
|
726
|
+
|
|
745
727
|
return AsyncGenerationStatusResponse(job_id=job.job_id,
|
|
746
728
|
status=job.status,
|
|
747
729
|
error=job.error,
|
|
748
730
|
output=job_output,
|
|
749
731
|
created_at=job.created_at,
|
|
750
732
|
updated_at=job.updated_at,
|
|
751
|
-
expires_at=
|
|
733
|
+
expires_at=self._job_store.get_expires_at(job))
|
|
734
|
+
|
|
735
|
+
async def run_generation(scheduler_address: str,
|
|
736
|
+
db_url: str,
|
|
737
|
+
config_file_path: str,
|
|
738
|
+
job_id: str,
|
|
739
|
+
payload: typing.Any):
|
|
740
|
+
"""Background task to run the workflow."""
|
|
741
|
+
job_store = JobStore(scheduler_address=scheduler_address, db_url=db_url)
|
|
742
|
+
try:
|
|
743
|
+
async with load_workflow(config_file_path) as local_session_manager:
|
|
744
|
+
result = await generate_single_response(
|
|
745
|
+
payload, local_session_manager, result_type=local_session_manager.workflow.single_output_schema)
|
|
752
746
|
|
|
753
|
-
|
|
747
|
+
await job_store.update_status(job_id, JobStatus.SUCCESS, output=result)
|
|
748
|
+
except Exception as e:
|
|
749
|
+
logger.exception("Error in async job %s", job_id)
|
|
750
|
+
await job_store.update_status(job_id, JobStatus.FAILURE, error=str(e))
|
|
751
|
+
|
|
752
|
+
def post_async_generation(request_type: type):
|
|
754
753
|
|
|
755
754
|
async def start_async_generation(
|
|
756
|
-
request: request_type,
|
|
755
|
+
request: request_type, response: Response,
|
|
757
756
|
http_request: Request) -> AsyncGenerateResponse | AsyncGenerationStatusResponse:
|
|
758
757
|
"""Handle async generation requests."""
|
|
759
758
|
|
|
@@ -761,41 +760,30 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
761
760
|
|
|
762
761
|
# if job_id is present and already exists return the job info
|
|
763
762
|
if request.job_id:
|
|
764
|
-
job =
|
|
763
|
+
job = await self._job_store.get_job(request.job_id)
|
|
765
764
|
if job:
|
|
766
765
|
return AsyncGenerateResponse(job_id=job.job_id, status=job.status)
|
|
767
766
|
|
|
768
|
-
job_id =
|
|
769
|
-
await self.
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
now = time.time()
|
|
786
|
-
sync_timeout = now + request.sync_timeout
|
|
787
|
-
while time.time() < sync_timeout:
|
|
788
|
-
job = job_store.get_job(job_id)
|
|
789
|
-
if job is not None and job.status not in job_store.ACTIVE_STATUS:
|
|
790
|
-
# If the job is done, return the result
|
|
791
|
-
response.status_code = 200
|
|
792
|
-
return _job_status_to_response(job)
|
|
793
|
-
|
|
794
|
-
# Sleep for a short time before checking again
|
|
795
|
-
await asyncio.sleep(0.1)
|
|
767
|
+
job_id = self._job_store.ensure_job_id(request.job_id)
|
|
768
|
+
(_, job) = await self._job_store.submit_job(
|
|
769
|
+
job_id=job_id,
|
|
770
|
+
expiry_seconds=request.expiry_seconds,
|
|
771
|
+
job_fn=run_generation,
|
|
772
|
+
sync_timeout=request.sync_timeout,
|
|
773
|
+
job_args=[
|
|
774
|
+
self._scheduler_address,
|
|
775
|
+
self._db_url,
|
|
776
|
+
self._config_file_path,
|
|
777
|
+
job_id,
|
|
778
|
+
request.model_dump(mode="json", exclude=["job_id", "sync_timeout", "expiry_seconds"])
|
|
779
|
+
])
|
|
780
|
+
|
|
781
|
+
if job is not None:
|
|
782
|
+
response.status_code = 200
|
|
783
|
+
return _job_status_to_response(job)
|
|
796
784
|
|
|
797
785
|
response.status_code = 202
|
|
798
|
-
return AsyncGenerateResponse(job_id=job_id, status=
|
|
786
|
+
return AsyncGenerateResponse(job_id=job_id, status=JobStatus.SUBMITTED)
|
|
799
787
|
|
|
800
788
|
return start_async_generation
|
|
801
789
|
|
|
@@ -805,8 +793,8 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
805
793
|
|
|
806
794
|
async with session_manager.session(http_connection=http_request):
|
|
807
795
|
|
|
808
|
-
job =
|
|
809
|
-
if
|
|
796
|
+
job = await self._job_store.get_job(job_id)
|
|
797
|
+
if job is None:
|
|
810
798
|
logger.warning("Job %s not found", job_id)
|
|
811
799
|
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
|
812
800
|
|
|
@@ -934,30 +922,33 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
934
922
|
responses={500: response_500},
|
|
935
923
|
)
|
|
936
924
|
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
925
|
+
if self._dask_available and not hasattr(endpoint, 'function_name'):
|
|
926
|
+
app.add_api_route(
|
|
927
|
+
path=f"{endpoint.path}/async",
|
|
928
|
+
endpoint=post_async_generation(request_type=AsyncGenerateRequest),
|
|
929
|
+
methods=[endpoint.method],
|
|
930
|
+
response_model=AsyncGenerateResponse | AsyncGenerationStatusResponse,
|
|
931
|
+
description="Start an async generate job",
|
|
932
|
+
responses={500: response_500},
|
|
933
|
+
)
|
|
934
|
+
else:
|
|
935
|
+
logger.warning("Dask is not available, async generation endpoints will not be added.")
|
|
946
936
|
else:
|
|
947
937
|
raise ValueError(f"Unsupported method {endpoint.method}")
|
|
948
938
|
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
939
|
+
if self._dask_available and not hasattr(endpoint, 'function_name'):
|
|
940
|
+
app.add_api_route(
|
|
941
|
+
path=f"{endpoint.path}/async/job/{{job_id}}",
|
|
942
|
+
endpoint=get_async_job_status,
|
|
943
|
+
methods=["GET"],
|
|
944
|
+
response_model=AsyncGenerationStatusResponse,
|
|
945
|
+
description="Get the status of an async job",
|
|
946
|
+
responses={
|
|
947
|
+
404: {
|
|
948
|
+
"description": "Job not found"
|
|
949
|
+
}, 500: response_500
|
|
950
|
+
},
|
|
951
|
+
)
|
|
961
952
|
|
|
962
953
|
if (endpoint.openai_api_path):
|
|
963
954
|
if (endpoint.method == "GET"):
|
|
@@ -1060,8 +1051,13 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
1060
1051
|
code_verifier=verifier,
|
|
1061
1052
|
state=state)
|
|
1062
1053
|
flow_state.future.set_result(res)
|
|
1054
|
+
except OAuthError as e:
|
|
1055
|
+
flow_state.future.set_exception(
|
|
1056
|
+
RuntimeError(f"Authorization server rejected request: {e.error} ({e.description})"))
|
|
1057
|
+
except httpx.HTTPError as e:
|
|
1058
|
+
flow_state.future.set_exception(RuntimeError(f"Network error during token fetch: {e}"))
|
|
1063
1059
|
except Exception as e:
|
|
1064
|
-
flow_state.future.set_exception(e)
|
|
1060
|
+
flow_state.future.set_exception(RuntimeError(f"Authentication failed: {e}"))
|
|
1065
1061
|
|
|
1066
1062
|
return HTMLResponse(content=AUTH_REDIRECT_SUCCESS_HTML,
|
|
1067
1063
|
status_code=200,
|
|
@@ -1077,6 +1073,186 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
1077
1073
|
methods=["GET"],
|
|
1078
1074
|
description="Handles the authorization code and state returned from the Authorization Code Grant Flow.")
|
|
1079
1075
|
|
|
1076
|
+
async def add_mcp_client_tool_list_route(self, app: FastAPI, builder: WorkflowBuilder):
|
|
1077
|
+
"""Add the MCP client tool list endpoint to the FastAPI app."""
|
|
1078
|
+
from typing import Any
|
|
1079
|
+
|
|
1080
|
+
from pydantic import BaseModel
|
|
1081
|
+
|
|
1082
|
+
class MCPToolInfo(BaseModel):
|
|
1083
|
+
name: str
|
|
1084
|
+
description: str
|
|
1085
|
+
server: str
|
|
1086
|
+
available: bool
|
|
1087
|
+
|
|
1088
|
+
class MCPClientToolListResponse(BaseModel):
|
|
1089
|
+
mcp_clients: list[dict[str, Any]]
|
|
1090
|
+
|
|
1091
|
+
async def get_mcp_client_tool_list() -> MCPClientToolListResponse:
|
|
1092
|
+
"""
|
|
1093
|
+
Get the list of MCP tools from all MCP clients in the workflow configuration.
|
|
1094
|
+
Checks session health and compares with workflow function group configuration.
|
|
1095
|
+
"""
|
|
1096
|
+
mcp_clients_info = []
|
|
1097
|
+
|
|
1098
|
+
try:
|
|
1099
|
+
# Get all function groups from the builder
|
|
1100
|
+
function_groups = builder._function_groups
|
|
1101
|
+
|
|
1102
|
+
# Find MCP client function groups
|
|
1103
|
+
for group_name, configured_group in function_groups.items():
|
|
1104
|
+
if configured_group.config.type != "mcp_client":
|
|
1105
|
+
continue
|
|
1106
|
+
|
|
1107
|
+
from nat.plugins.mcp.client_config import MCPClientConfig
|
|
1108
|
+
|
|
1109
|
+
config = configured_group.config
|
|
1110
|
+
assert isinstance(config, MCPClientConfig)
|
|
1111
|
+
|
|
1112
|
+
# Reuse the existing MCP client session stored on the function group instance
|
|
1113
|
+
group_instance = configured_group.instance
|
|
1114
|
+
|
|
1115
|
+
client = group_instance.mcp_client
|
|
1116
|
+
if client is None:
|
|
1117
|
+
raise RuntimeError(f"MCP client not found for group {group_name}")
|
|
1118
|
+
|
|
1119
|
+
try:
|
|
1120
|
+
session_healthy = False
|
|
1121
|
+
server_tools: dict[str, Any] = {}
|
|
1122
|
+
|
|
1123
|
+
try:
|
|
1124
|
+
server_tools = await client.get_tools()
|
|
1125
|
+
session_healthy = True
|
|
1126
|
+
except Exception as e:
|
|
1127
|
+
logger.exception(f"Failed to connect to MCP server {client.server_name}: {e}")
|
|
1128
|
+
session_healthy = False
|
|
1129
|
+
|
|
1130
|
+
# Get workflow function group configuration (configured client-side tools)
|
|
1131
|
+
configured_short_names: set[str] = set()
|
|
1132
|
+
configured_full_to_fn: dict[str, Function] = {}
|
|
1133
|
+
try:
|
|
1134
|
+
# Pass a no-op filter function to bypass any default filtering that might check
|
|
1135
|
+
# health status, preventing potential infinite recursion during health status checks.
|
|
1136
|
+
async def pass_through_filter(fn):
|
|
1137
|
+
return fn
|
|
1138
|
+
|
|
1139
|
+
accessible_functions = await group_instance.get_accessible_functions(
|
|
1140
|
+
filter_fn=pass_through_filter)
|
|
1141
|
+
configured_full_to_fn = accessible_functions
|
|
1142
|
+
configured_short_names = {name.split('.', 1)[1] for name in accessible_functions.keys()}
|
|
1143
|
+
except Exception as e:
|
|
1144
|
+
logger.exception(f"Failed to get accessible functions for group {group_name}: {e}")
|
|
1145
|
+
|
|
1146
|
+
# Build alias->original mapping and override configs from overrides
|
|
1147
|
+
alias_to_original: dict[str, str] = {}
|
|
1148
|
+
override_configs: dict[str, Any] = {}
|
|
1149
|
+
try:
|
|
1150
|
+
if config.tool_overrides is not None:
|
|
1151
|
+
for orig_name, override in config.tool_overrides.items():
|
|
1152
|
+
if override.alias is not None:
|
|
1153
|
+
alias_to_original[override.alias] = orig_name
|
|
1154
|
+
override_configs[override.alias] = override
|
|
1155
|
+
else:
|
|
1156
|
+
override_configs[orig_name] = override
|
|
1157
|
+
except Exception:
|
|
1158
|
+
pass
|
|
1159
|
+
|
|
1160
|
+
# Create tool info list (always return configured tools; mark availability)
|
|
1161
|
+
tools_info: list[dict[str, Any]] = []
|
|
1162
|
+
available_count = 0
|
|
1163
|
+
for wf_fn, fn_short in zip(configured_full_to_fn.values(), configured_short_names):
|
|
1164
|
+
orig_name = alias_to_original.get(fn_short, fn_short)
|
|
1165
|
+
available = session_healthy and (orig_name in server_tools)
|
|
1166
|
+
if available:
|
|
1167
|
+
available_count += 1
|
|
1168
|
+
|
|
1169
|
+
# Prefer tool override description, then workflow function description,
|
|
1170
|
+
# then server description
|
|
1171
|
+
description = ""
|
|
1172
|
+
if fn_short in override_configs and override_configs[fn_short].description:
|
|
1173
|
+
description = override_configs[fn_short].description
|
|
1174
|
+
elif wf_fn.description:
|
|
1175
|
+
description = wf_fn.description
|
|
1176
|
+
elif available and orig_name in server_tools:
|
|
1177
|
+
description = server_tools[orig_name].description or ""
|
|
1178
|
+
|
|
1179
|
+
tools_info.append(
|
|
1180
|
+
MCPToolInfo(name=fn_short,
|
|
1181
|
+
description=description or "",
|
|
1182
|
+
server=client.server_name,
|
|
1183
|
+
available=available).model_dump())
|
|
1184
|
+
|
|
1185
|
+
# Sort tools_info by name to maintain consistent ordering
|
|
1186
|
+
tools_info.sort(key=lambda x: x['name'])
|
|
1187
|
+
|
|
1188
|
+
mcp_clients_info.append({
|
|
1189
|
+
"function_group": group_name,
|
|
1190
|
+
"server": client.server_name,
|
|
1191
|
+
"transport": config.server.transport,
|
|
1192
|
+
"session_healthy": session_healthy,
|
|
1193
|
+
"protected": True if config.server.auth_provider is not None else False,
|
|
1194
|
+
"tools": tools_info,
|
|
1195
|
+
"total_tools": len(configured_short_names),
|
|
1196
|
+
"available_tools": available_count
|
|
1197
|
+
})
|
|
1198
|
+
|
|
1199
|
+
except Exception as e:
|
|
1200
|
+
logger.error(f"Error processing MCP client {group_name}: {e}")
|
|
1201
|
+
mcp_clients_info.append({
|
|
1202
|
+
"function_group": group_name,
|
|
1203
|
+
"server": "unknown",
|
|
1204
|
+
"transport": config.server.transport if config.server else "unknown",
|
|
1205
|
+
"session_healthy": False,
|
|
1206
|
+
"protected": False,
|
|
1207
|
+
"error": str(e),
|
|
1208
|
+
"tools": [],
|
|
1209
|
+
"total_tools": 0,
|
|
1210
|
+
"workflow_tools": 0
|
|
1211
|
+
})
|
|
1212
|
+
|
|
1213
|
+
return MCPClientToolListResponse(mcp_clients=mcp_clients_info)
|
|
1214
|
+
|
|
1215
|
+
except Exception as e:
|
|
1216
|
+
logger.error(f"Error in MCP client tool list endpoint: {e}")
|
|
1217
|
+
raise HTTPException(status_code=500, detail=f"Failed to retrieve MCP client information: {str(e)}")
|
|
1218
|
+
|
|
1219
|
+
# Add the route to the FastAPI app
|
|
1220
|
+
app.add_api_route(
|
|
1221
|
+
path="/mcp/client/tool/list",
|
|
1222
|
+
endpoint=get_mcp_client_tool_list,
|
|
1223
|
+
methods=["GET"],
|
|
1224
|
+
response_model=MCPClientToolListResponse,
|
|
1225
|
+
description="Get list of MCP client tools with session health and workflow configuration comparison",
|
|
1226
|
+
responses={
|
|
1227
|
+
200: {
|
|
1228
|
+
"description": "Successfully retrieved MCP client tool information",
|
|
1229
|
+
"content": {
|
|
1230
|
+
"application/json": {
|
|
1231
|
+
"example": {
|
|
1232
|
+
"mcp_clients": [{
|
|
1233
|
+
"function_group": "mcp_tools",
|
|
1234
|
+
"server": "streamable-http:http://localhost:9901/mcp",
|
|
1235
|
+
"transport": "streamable-http",
|
|
1236
|
+
"session_healthy": True,
|
|
1237
|
+
"protected": False,
|
|
1238
|
+
"tools": [{
|
|
1239
|
+
"name": "tool_a",
|
|
1240
|
+
"description": "Tool A description",
|
|
1241
|
+
"server": "streamable-http:http://localhost:9901/mcp",
|
|
1242
|
+
"available": True
|
|
1243
|
+
}],
|
|
1244
|
+
"total_tools": 1,
|
|
1245
|
+
"available_tools": 1
|
|
1246
|
+
}]
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
},
|
|
1251
|
+
500: {
|
|
1252
|
+
"description": "Internal Server Error"
|
|
1253
|
+
}
|
|
1254
|
+
})
|
|
1255
|
+
|
|
1080
1256
|
async def _add_flow(self, state: str, flow_state: FlowState):
|
|
1081
1257
|
async with self._outstanding_flows_lock:
|
|
1082
1258
|
self._outstanding_flows[state] = flow_state
|
|
@@ -1084,3 +1260,7 @@ class FastApiFrontEndPluginWorker(FastApiFrontEndPluginWorkerBase):
|
|
|
1084
1260
|
async def _remove_flow(self, state: str):
|
|
1085
1261
|
async with self._outstanding_flows_lock:
|
|
1086
1262
|
del self._outstanding_flows[state]
|
|
1263
|
+
|
|
1264
|
+
|
|
1265
|
+
# Prevent Sphinx from documenting items not a part of the public API
|
|
1266
|
+
__all__ = ["FastApiFrontEndPluginWorkerBase", "FastApiFrontEndPluginWorker", "RouteInfo"]
|