fetchai / ai-engine-sdk-js

Apache License 2.0
2 stars 9 forks source link

agent_json with type "options" is not supported #11

Open elsapolo opened 2 months ago

elsapolo commented 2 months ago

Prerequisites

Category

Bug (unexpected behavior)

Expected Behavior

No response

Observed Behavior

I was working on a react app using the SDK and the app would crash and print and UNKOWN JSON error that I have traced back to ai-engine-sdk-js/src/index.ts line 218. And by checking the network reponse I see it is because our agent sends a agent-json of type "options" which isn't supported by the SDK

looking at network tab and realised this issue

To Reproduce

No response

Version

0.1.0

Environment Details (Optional)

No response

Failure Logs (Optional)

No response

Additional Information (Optional)

No response

elsapolo commented 2 months ago

This is caused by our agent:

from uagents import Agent, Model, Context, Protocol
from ai_engine import UAgentResponse, UAgentResponseType

LearningAgent = Agent()

class LearningRequest(Model):
    subject : str
    answer: str

LearningAgent_Protocol = Protocol('Learning Agent protocol')

@LearningAgent_Protocol.on_message(model=LearningRequest, replies=UAgentResponse)
async def on_youtube_request(ctx: Context, sender: str, msg: LearningRequest):
    ctx.logger.info(f"Received Request from {sender} with subject request")
    ctx.logger.info(msg.subject)

LearningAgent.include(LearningAgent_Protocol)

LearningAgent.run()
Screenshot 2024-08-14 at 16 57 37

The code I used was very similar to the simple.ts example:

import * as readline from "node:readline";

import {
  AiEngine,
  isAgentMessage,
  isAiEngineMessage,
  isConfirmationMessage,
  isStopMessage,
  isTaskSelectionMessage,
} from "@fetchai/ai-engine-sdk";

const apiKey = process.env["AV_API_KEY"] ?? "";
console.log("api key: "+ apiKey);

const snooze = (ms: number) =>
  new Promise((resolve) => setTimeout(resolve, ms));

const main = async () => {
  const rl = readline.promises.createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  const aiEngine = new AiEngine(apiKey);

  const functionGroups = await aiEngine.getFunctionGroups();
  const publicGroup = functionGroups.find((g) => g.name === "My Functions");
  if (publicGroup === undefined) {
    throw new Error('Could not find "Public" function group.');
  }

  const session = await aiEngine.createSession(publicGroup.uuid);
  await session.start(await rl.question("What is your objective: "));

  try {
    let emptyCount = 0;
    let sessionEnded = false;
    while (emptyCount < 12) {
      const messages = await session.getMessages();
      if (messages.length === 0) {
        emptyCount++;
      } else {
        emptyCount = 0;
      }

      for (const message of messages) {
        if (isTaskSelectionMessage(message)) {
          console.log("Please select a task from the list below:");
          console.log("");
          for (const option of message.options) {
            console.log(`${option.key}: ${option.title}`);
          }

          const optionIndex = parseInt(
            await rl.question("\nEnter task number: "),
          );

          // check the index
          if (optionIndex < 0 || optionIndex >= message.options.length) {
            throw new Error("Invalid task number");
          }

          await session.submitTaskSelection(message, [
            message.options[optionIndex]!,
          ]);
        } else if (isAgentMessage(message)) {
          console.log("Agent: ", message.text);

          const response = await rl.question("User (enter to skip): ");
          if (response === "exit") {
            break;
          }

          if (response !== "") {
            await session.submitResponse(message, response);
          }
        } else if (isAiEngineMessage(message)) {
          console.log("Engine:", message.text);
        } else if (isConfirmationMessage(message)) {
          console.log("Confirm:", message.payload);

          const response = await rl.question(
            "\nPress enter to confirm, otherwise explain issue:\n",
          );

          if (response === "") {
            console.log("Sending confirmation...");
            await session.submitConfirmation(message);
          } else {
            await session.rejectConfirmation(message, response);
          }
        } else if (isStopMessage(message)) {
          console.log("\nSession has ended");
          sessionEnded = true;
          break;
        } else {
          console.error("???", message);
        }
      }

      // if the session has concluded then break
      if (sessionEnded) {
        break;
      }

      await snooze(1200);
    }
  } catch (e) {
    console.error("Error", e);
  } finally {
    // clean up the session
    await session.delete();

    // stop the readline interface
    rl.close();
  }
};

main();