You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.4 KiB

11 months ago
  1. // You can only run this example from within the websocket/ directory.
  2. // NODE_ENV=development node websock-multi-turn-chat.js
  3. // Scraping is enabled, but search requires AGENT_GSE_* keys.
  4. const express = require("express");
  5. const chalk = require("chalk");
  6. const AIbitat = require("../../index.js");
  7. const {
  8. websocket,
  9. webBrowsing,
  10. webScraping,
  11. } = require("../../plugins/index.js");
  12. const path = require("path");
  13. const port = 3000;
  14. const app = express();
  15. require("@mintplex-labs/express-ws").default(app); // load WebSockets in non-SSL mode.
  16. require("dotenv").config({ path: `../../../../../.env.development` });
  17. // Debugging echo function if this is working for you.
  18. // app.ws('/echo', function (ws, req) {
  19. // ws.on('message', function (msg) {
  20. // ws.send(msg);
  21. // });
  22. // });
  23. // Set up WSS sockets for listening.
  24. app.ws("/ws", function (ws, _response) {
  25. try {
  26. ws.on("message", function (msg) {
  27. if (ws?.handleFeedback) ws.handleFeedback(msg);
  28. });
  29. ws.on("close", function () {
  30. console.log("Socket killed");
  31. return;
  32. });
  33. console.log("Socket online and waiting...");
  34. runAIbitat(ws).catch((error) => {
  35. ws.send(
  36. JSON.stringify({
  37. from: Agent.AI,
  38. to: Agent.HUMAN,
  39. content: error.message,
  40. })
  41. );
  42. });
  43. } catch (error) {}
  44. });
  45. app.all("*", function (_, response) {
  46. response.sendFile(path.join(__dirname, "index.html"));
  47. });
  48. app.listen(port, () => {
  49. console.log(`Testing HTTP/WSS server listening at http://localhost:${port}`);
  50. });
  51. const Agent = {
  52. HUMAN: "🧑",
  53. AI: "🤖",
  54. };
  55. async function runAIbitat(socket) {
  56. if (!process.env.OPEN_AI_KEY)
  57. throw new Error(
  58. "This example requires a valid OPEN_AI_KEY in the env.development file"
  59. );
  60. console.log(chalk.blue("Booting AIbitat class & starting agent(s)"));
  61. const aibitat = new AIbitat({
  62. provider: "openai",
  63. model: "gpt-4o",
  64. })
  65. .use(websocket.plugin({ socket }))
  66. .use(webBrowsing.plugin())
  67. .use(webScraping.plugin())
  68. .agent(Agent.HUMAN, {
  69. interrupt: "ALWAYS",
  70. role: "You are a human assistant.",
  71. })
  72. .agent(Agent.AI, {
  73. role: "You are a helpful ai assistant who likes to chat with the user who an also browse the web for questions it does not know or have real-time access to.",
  74. functions: ["web-browsing"],
  75. });
  76. await aibitat.start({
  77. from: Agent.HUMAN,
  78. to: Agent.AI,
  79. content: `How are you doing today?`,
  80. });
  81. }