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.

90 lines
2.4 KiB

11 months ago
  1. const { v4 } = require("uuid");
  2. const { SystemSettings } = require("./systemSettings");
  3. const Telemetry = {
  4. // Write-only key. It can't read events or any of your other data, so it's safe to use in public apps.
  5. pubkey: "phc_9qu7QLpV8L84P3vFmEiZxL020t2EqIubP7HHHxrSsqS",
  6. stubDevelopmentEvents: true, // [DO NOT TOUCH] Core team only.
  7. label: "telemetry_id",
  8. id: async function () {
  9. const result = await SystemSettings.get({ label: this.label });
  10. return result?.value || null;
  11. },
  12. connect: async function () {
  13. const client = this.client();
  14. const distinctId = await this.findOrCreateId();
  15. return { client, distinctId };
  16. },
  17. isDev: function () {
  18. return process.env.NODE_ENV === "development" && this.stubDevelopmentEvents;
  19. },
  20. client: function () {
  21. if (process.env.DISABLE_TELEMETRY === "true" || this.isDev()) return null;
  22. const { PostHog } = require("posthog-node");
  23. return new PostHog(this.pubkey);
  24. },
  25. runtime: function () {
  26. if (process.env.ANYTHING_LLM_RUNTIME === "docker") return "docker";
  27. if (process.env.NODE_ENV === "production") return "production";
  28. return "other";
  29. },
  30. sendTelemetry: async function (
  31. event,
  32. eventProperties = {},
  33. subUserId = null,
  34. silent = false
  35. ) {
  36. try {
  37. const { client, distinctId: systemId } = await this.connect();
  38. if (!client) return;
  39. const distinctId = !!subUserId ? `${systemId}::${subUserId}` : systemId;
  40. const properties = { ...eventProperties, runtime: this.runtime() };
  41. // Silence some events to keep logs from being too messy in production
  42. // eg: Tool calls from agents spamming the logs.
  43. if (!silent) {
  44. console.log(`\x1b[32m[TELEMETRY SENT]\x1b[0m`, {
  45. event,
  46. distinctId,
  47. properties,
  48. });
  49. }
  50. client.capture({
  51. event,
  52. distinctId,
  53. properties,
  54. });
  55. } catch {
  56. return;
  57. }
  58. },
  59. flush: async function () {
  60. const client = this.client();
  61. if (!client) return;
  62. await client.shutdownAsync();
  63. },
  64. setUid: async function () {
  65. const newId = v4();
  66. await SystemSettings._updateSettings({ [this.label]: newId });
  67. return newId;
  68. },
  69. findOrCreateId: async function () {
  70. let currentId = await this.id();
  71. if (currentId) return currentId;
  72. currentId = await this.setUid();
  73. return currentId;
  74. },
  75. };
  76. module.exports = { Telemetry };