|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""Uses JSON Processor from ALTK to extract data from long JSON responses. |
| 3 | +
|
| 4 | +Copyright 2025 |
| 5 | +SPDX-License-Identifier: Apache-2.0 |
| 6 | +Authors: Jason Tsay |
| 7 | +
|
| 8 | +This module loads configurations for plugins. |
| 9 | +""" |
| 10 | + |
| 11 | +# Standard |
| 12 | +import json |
| 13 | +import os |
| 14 | +from typing import cast |
| 15 | + |
| 16 | +# Third-Party |
| 17 | +from altk.core.llm import get_llm |
| 18 | + |
| 19 | +# Third-party |
| 20 | +from altk.core.toolkit import AgentPhase |
| 21 | +from altk.post_tool.code_generation.code_generation import CodeGenerationComponent, CodeGenerationComponentConfig |
| 22 | +from altk.post_tool.core.toolkit import CodeGenerationRunInput, CodeGenerationRunOutput |
| 23 | + |
| 24 | +# First-Party |
| 25 | +from mcpgateway.plugins.framework import ( |
| 26 | + Plugin, |
| 27 | + PluginConfig, |
| 28 | + PluginContext, |
| 29 | + ToolPostInvokePayload, |
| 30 | + ToolPostInvokeResult, |
| 31 | +) |
| 32 | +from mcpgateway.services.logging_service import LoggingService |
| 33 | + |
| 34 | +# Initialize logging service first |
| 35 | +logging_service = LoggingService() |
| 36 | +logger = logging_service.get_logger(__name__) |
| 37 | + |
| 38 | + |
| 39 | +class ALTKJsonProcessor(Plugin): |
| 40 | + """Uses JSON Processor from ALTK to extract data from long JSON responses.""" |
| 41 | + |
| 42 | + def __init__(self, config: PluginConfig): |
| 43 | + """Entry init block for plugin. |
| 44 | +
|
| 45 | + Args: |
| 46 | + config: the plugin configuration |
| 47 | + """ |
| 48 | + super().__init__(config) |
| 49 | + if config.config: |
| 50 | + self._cfg = config.config |
| 51 | + else: |
| 52 | + self._cfg = {} |
| 53 | + |
| 54 | + async def tool_post_invoke(self, payload: ToolPostInvokePayload, context: PluginContext) -> ToolPostInvokeResult: |
| 55 | + """Plugin hook run after a tool is invoked. |
| 56 | +
|
| 57 | + Args: |
| 58 | + payload: The tool result payload to be analyzed. |
| 59 | + context: Contextual information about the hook call. |
| 60 | +
|
| 61 | + Raises: |
| 62 | + ValueError: if a provider api key is not provided in either config or env var |
| 63 | +
|
| 64 | + Returns: |
| 65 | + The result of the plugin's analysis, including whether the tool result should proceed. |
| 66 | + """ |
| 67 | + provider = self._cfg["llm_provider"] |
| 68 | + llm_client = None |
| 69 | + if provider == "watsonx": |
| 70 | + watsonx_client = get_llm("watsonx") |
| 71 | + if len(self._cfg["watsonx"]["wx_api_key"]) > 0: |
| 72 | + api_key = self._cfg["watsonx"]["wx_api_key"] |
| 73 | + else: |
| 74 | + api_key = os.getenv("WX_API_KEY") |
| 75 | + if not api_key: |
| 76 | + raise ValueError("WatsonX api key not found, provide WX_API_KEY either in the plugin config or as an env var.") |
| 77 | + if len(self._cfg["watsonx"]["wx_project_id"]) > 0: |
| 78 | + project_id = self._cfg["watsonx"]["wx_project_id"] |
| 79 | + else: |
| 80 | + project_id = os.getenv("WX_PROJECT_ID") |
| 81 | + if not project_id: |
| 82 | + raise ValueError("WatsonX project id not found, project WX_PROJECT_ID either in the plugin config or as an env var.") |
| 83 | + llm_client = watsonx_client(model_id=self._cfg["model_id"], api_key=api_key, project_id=project_id, url=self._cfg["watsonx"]["wx_url"]) |
| 84 | + elif provider == "openai": |
| 85 | + openai_client = get_llm("openai.sync") |
| 86 | + if len(self._cfg["openai"]["api_key"]) > 0: |
| 87 | + api_key = self._cfg["openai"]["api_key"] |
| 88 | + else: |
| 89 | + api_key = os.getenv("OPENAI_API_KEY") |
| 90 | + if not api_key: |
| 91 | + raise ValueError("OpenAI api key not found, provide OPENAI_API_KEY either in the plugin config or as an env var.") |
| 92 | + llm_client = openai_client(api_key=api_key, model=self._cfg["model_id"]) |
| 93 | + elif provider == "ollama": |
| 94 | + ollama_client = get_llm("litellm.ollama") |
| 95 | + llm_client = ollama_client(api_url=self._cfg["ollama"]["ollama_url"], model_name=self._cfg["model_id"]) |
| 96 | + elif provider == "anthropic": |
| 97 | + anthropic_client = get_llm("litellm") |
| 98 | + model_path = f"anthropic/{self._cfg['model_id']}" |
| 99 | + if len(self._cfg["anthropic"]["api_key"]) > 0: |
| 100 | + api_key = self._cfg["anthropic"]["api_key"] |
| 101 | + else: |
| 102 | + api_key = os.getenv("ANTHROPIC_API_KEY") |
| 103 | + if not api_key: |
| 104 | + raise ValueError("Anthropic api key not found, provide ANTHROPIC_API_KEY either in the plugin config or as an env var.") |
| 105 | + llm_client = anthropic_client(model_name=model_path, api_key=api_key) |
| 106 | + elif provider == "pytestmock": |
| 107 | + # only meant to be used for unit tests |
| 108 | + llm_client = None |
| 109 | + else: |
| 110 | + raise ValueError("Unknown provider given for 'llm_provider' in plugin config!") |
| 111 | + |
| 112 | + config = CodeGenerationComponentConfig(llm_client=llm_client, use_docker_sandbox=False) |
| 113 | + |
| 114 | + response_json = None |
| 115 | + response_str = None |
| 116 | + if "content" in payload.result: |
| 117 | + if len(payload.result["content"]) > 0: |
| 118 | + content = payload.result["content"][0] |
| 119 | + if "type" in content and content["type"] == "text": |
| 120 | + response_str = content["text"] |
| 121 | + |
| 122 | + if len(response_str) > self._cfg["length_threshold"]: |
| 123 | + try: |
| 124 | + response_json = json.loads(response_str) |
| 125 | + except json.decoder.JSONDecodeError: |
| 126 | + # ignore anything that's not json |
| 127 | + pass |
| 128 | + |
| 129 | + # Should only get here if response is long enough and is valid JSON |
| 130 | + if response_json: |
| 131 | + logger.info("Long JSON response detected, using ALTK JSON Processor...") |
| 132 | + if provider == "pytestmock": |
| 133 | + # only meant for unit testing |
| 134 | + payload.result["content"][0]["text"] = "(filtered response)" |
| 135 | + else: |
| 136 | + codegen = CodeGenerationComponent(config=config) |
| 137 | + nl_query = self._cfg.get("jsonprocessor_query", "") |
| 138 | + input_data = CodeGenerationRunInput(messages=[], nl_query=nl_query, tool_response=response_json) |
| 139 | + output = codegen.process(input_data, AgentPhase.RUNTIME) |
| 140 | + output = cast(CodeGenerationRunOutput, output) |
| 141 | + payload.result["content"][0]["text"] = output.result |
| 142 | + logger.debug(f"ALTK processed response: {output.result}") |
| 143 | + return ToolPostInvokeResult(continue_processing=True, modified_payload=payload) |
| 144 | + |
| 145 | + return ToolPostInvokeResult(continue_processing=True) |
0 commit comments