Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -75,16 +75,24 @@
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.index.IndexNotFoundException;
import org.opensearch.ml.common.FunctionName;
import org.opensearch.ml.common.agent.LLMSpec;
import org.opensearch.ml.common.agent.MLAgent;
import org.opensearch.ml.common.agent.MLMemorySpec;
import org.opensearch.ml.common.agent.MLToolSpec;
import org.opensearch.ml.common.connector.Connector;
import org.opensearch.ml.common.connector.HttpConnector;
import org.opensearch.ml.common.connector.McpConnector;
import org.opensearch.ml.common.connector.McpStreamableHttpConnector;
import org.opensearch.ml.common.dataset.remote.RemoteInferenceInputDataSet;
import org.opensearch.ml.common.input.remote.RemoteInferenceMLInput;
import org.opensearch.ml.common.output.model.ModelTensor;
import org.opensearch.ml.common.output.model.ModelTensorOutput;
import org.opensearch.ml.common.output.model.ModelTensors;
import org.opensearch.ml.common.spi.tools.Tool;
import org.opensearch.ml.common.transport.MLTaskResponse;
import org.opensearch.ml.common.transport.prediction.MLPredictionTaskAction;
import org.opensearch.ml.common.transport.prediction.MLPredictionTaskRequest;
import org.opensearch.ml.common.utils.StringUtils;
import org.opensearch.ml.engine.MLEngineClassLoader;
import org.opensearch.ml.engine.algorithms.remote.McpConnectorExecutor;
Expand Down Expand Up @@ -1178,4 +1186,96 @@ private static Map<String, String> parseStringMapParameter(String rawValue, Stri
return null;
}
}

public static String extractSummaryFromResponse(MLTaskResponse response, Map<String, String> parameters) {
ModelTensorOutput output = (ModelTensorOutput) response.getOutput();
if (output == null || output.getMlModelOutputs() == null || output.getMlModelOutputs().isEmpty()) {
throw new IllegalStateException("No model output available in response");
}

ModelTensors tensors = output.getMlModelOutputs().getFirst();
if (tensors == null || tensors.getMlModelTensors() == null || tensors.getMlModelTensors().isEmpty()) {
throw new IllegalStateException("No model tensors available in response");
}

ModelTensor tensor = tensors.getMlModelTensors().getFirst();
if (tensor.getResult() != null) {
return tensor.getResult().trim();
}

if (tensor.getDataAsMap() == null) {
throw new IllegalStateException("No data map available in tensor");
}

Map<String, ?> dataMap = tensor.getDataAsMap();
if (dataMap.containsKey(RESPONSE_FIELD)) {
return String.valueOf(dataMap.get(RESPONSE_FIELD)).trim();
}

if (dataMap.containsKey("output")) {
try {
Object outputObj = JsonPath.read(dataMap, parameters.get(LLM_RESPONSE_FILTER));
if (outputObj != null) {
return String.valueOf(outputObj).trim();
}
} catch (PathNotFoundException e) {
throw new IllegalStateException("Failed to extract output using filter path", e);
}
}

throw new IllegalStateException("No result/response field found. Available fields: " + dataMap.keySet());
}

public static void generateMaxStepSummary(
Client client,
LLMSpec llmSpec,
String promptContent,
String systemPrompt,
Map<String, String> allParams,
String tenantId,
ActionListener<String> listener
) {
if (promptContent == null || promptContent.isEmpty()) {
listener.onFailure(new IllegalArgumentException("Prompt content cannot be null or empty"));
return;
}

try {
Map<String, String> summaryParams = new HashMap<>();
if (llmSpec.getParameters() != null) {
summaryParams.putAll(llmSpec.getParameters());
}
summaryParams.putAll(allParams);
summaryParams.put(MLPlanExecuteAndReflectAgentRunner.PROMPT_FIELD, promptContent);
summaryParams.put(MLPlanExecuteAndReflectAgentRunner.SYSTEM_PROMPT_FIELD, systemPrompt);

MLPredictionTaskRequest request = new MLPredictionTaskRequest(
llmSpec.getModelId(),
RemoteInferenceMLInput
.builder()
.algorithm(FunctionName.REMOTE)
.inputDataset(RemoteInferenceInputDataSet.builder().parameters(summaryParams).build())
.build(),
null,
tenantId
);

client.execute(MLPredictionTaskAction.INSTANCE, request, ActionListener.wrap(response -> {
try {
String summary = extractSummaryFromResponse(response, summaryParams);
if (summary == null || summary.isEmpty()) {
listener.onFailure(new RuntimeException("Empty LLM summary response"));
return;
}
listener.onResponse(summary);
} catch (IllegalStateException e) {
log.error("Failed to extract summary, using fallback", e);
listener.onFailure(e);
}
}, listener::onFailure));
} catch (IllegalStateException e) {
log.error("Failed to generate summary", e);
listener.onFailure(e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import static org.opensearch.ml.common.utils.ToolUtils.parseResponse;
import static org.opensearch.ml.engine.algorithms.agent.AgentUtils.DISABLE_TRACE;
import static org.opensearch.ml.engine.algorithms.agent.AgentUtils.INTERACTIONS_PREFIX;
import static org.opensearch.ml.engine.algorithms.agent.AgentUtils.LLM_RESPONSE_FILTER;
import static org.opensearch.ml.engine.algorithms.agent.AgentUtils.PROMPT_CHAT_HISTORY_PREFIX;
import static org.opensearch.ml.engine.algorithms.agent.AgentUtils.PROMPT_PREFIX;
import static org.opensearch.ml.engine.algorithms.agent.AgentUtils.PROMPT_SUFFIX;
Expand Down Expand Up @@ -67,25 +66,20 @@
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.common.Strings;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.ml.common.FunctionName;
import org.opensearch.ml.common.MLMemoryType;
import org.opensearch.ml.common.agent.LLMSpec;
import org.opensearch.ml.common.agent.MLAgent;
import org.opensearch.ml.common.agent.MLToolSpec;
import org.opensearch.ml.common.contextmanager.ContextManagerContext;
import org.opensearch.ml.common.conversation.Interaction;
import org.opensearch.ml.common.dataset.remote.RemoteInferenceInputDataSet;
import org.opensearch.ml.common.hooks.HookRegistry;
import org.opensearch.ml.common.input.remote.RemoteInferenceMLInput;
import org.opensearch.ml.common.memory.Memory;
import org.opensearch.ml.common.memory.Message;
import org.opensearch.ml.common.output.model.ModelTensor;
import org.opensearch.ml.common.output.model.ModelTensorOutput;
import org.opensearch.ml.common.output.model.ModelTensors;
import org.opensearch.ml.common.spi.tools.Tool;
import org.opensearch.ml.common.transport.MLTaskResponse;
import org.opensearch.ml.common.transport.prediction.MLPredictionTaskAction;
import org.opensearch.ml.common.transport.prediction.MLPredictionTaskRequest;
import org.opensearch.ml.common.utils.StringUtils;
import org.opensearch.ml.engine.agents.AgentContextUtil;
import org.opensearch.ml.engine.encryptor.Encryptor;
Expand All @@ -100,7 +94,6 @@

import com.google.common.annotations.VisibleForTesting;
import com.google.gson.reflect.TypeToken;
import com.jayway.jsonpath.JsonPath;

import lombok.Data;
import lombok.NoArgsConstructor;
Expand Down Expand Up @@ -502,7 +495,11 @@ private void runReAct(
);
toolParams.put(TENANT_ID_FIELD, tenantId);
lastToolParams.clear();
lastToolParams.putAll(toolParams);
toolParams
.entrySet()
.stream()
.filter(e -> e.getValue() != null)
.forEach(e -> lastToolParams.put(e.getKey(), e.getValue()));
runTool(
tools,
toolSpecMap,
Expand Down Expand Up @@ -1128,12 +1125,6 @@ void generateLLMSummary(
}

try {
Map<String, String> summaryParams = new HashMap<>();
if (llmSpec.getParameters() != null) {
summaryParams.putAll(llmSpec.getParameters());
}
summaryParams.putAll(parameter);

// Convert ModelTensors to strings before joining, skip session/interaction IDs
List<String> stepStrings = new ArrayList<>();
for (ModelTensors tensor : stepsSummary) {
Expand All @@ -1152,74 +1143,24 @@ void generateLLMSummary(
}
}
}
String steps = String.format(Locale.ROOT, "Question: %s\n\nCompleted Steps:\n%s", question, String.join("\n", stepStrings));
summaryParams.put(PROMPT, steps);
summaryParams.put(SYSTEM_PROMPT_FIELD, MAX_STEP_SUMMARY_CHAT_AGENT_SYSTEM_PROMPT);

ActionRequest request = new MLPredictionTaskRequest(
llmSpec.getModelId(),
RemoteInferenceMLInput
.builder()
.algorithm(FunctionName.REMOTE)
.inputDataset(RemoteInferenceInputDataSet.builder().parameters(summaryParams).build())
.build(),
null,
tenantId
);
client.execute(MLPredictionTaskAction.INSTANCE, request, ActionListener.wrap(response -> {
String summary = extractSummaryFromResponse(response, summaryParams);
if (summary == null) {
listener.onFailure(new RuntimeException("Empty or invalid LLM summary response"));
return;
}
listener.onResponse(summary);
}, listener::onFailure));
String promptContent = String
.format(Locale.ROOT, "Question: %s\n\nCompleted Steps:\n%s", question, String.join("\n", stepStrings));

AgentUtils
.generateMaxStepSummary(
client,
llmSpec,
promptContent,
MAX_STEP_SUMMARY_CHAT_AGENT_SYSTEM_PROMPT,
parameter,
tenantId,
listener
);
} catch (Exception e) {
listener.onFailure(e);
}
}

public String extractSummaryFromResponse(MLTaskResponse response, Map<String, String> params) {
try {
ModelTensorOutput output = (ModelTensorOutput) response.getOutput();
if (output == null || output.getMlModelOutputs() == null || output.getMlModelOutputs().isEmpty()) {
return null;
}

ModelTensors tensors = output.getMlModelOutputs().getFirst();
if (tensors == null || tensors.getMlModelTensors() == null || tensors.getMlModelTensors().isEmpty()) {
return null;
}

ModelTensor tensor = tensors.getMlModelTensors().getFirst();
if (tensor.getResult() != null) {
return tensor.getResult().trim();
}

if (tensor.getDataAsMap() == null) {
return null;
}

Map<String, ?> dataMap = tensor.getDataAsMap();
if (dataMap.containsKey("response")) {
return String.valueOf(dataMap.get("response")).trim();
}

if (dataMap.containsKey("output")) {
Object outputObj = JsonPath.read(dataMap, params.get(LLM_RESPONSE_FILTER));
if (outputObj != null) {
return String.valueOf(outputObj).trim();
}
}

log.error("Summary generate error. No result/response field found. Available fields: {}", dataMap.keySet());
return null;
} catch (Exception e) {
log.error("Failed to extract summary from response", e);
throw new RuntimeException("Failed to extract summary from response", e);
}
}

private void saveMessage(
Memory memory,
String question,
Expand Down
Loading