@xache/langchain 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -25,12 +25,27 @@ __export(index_exports, {
25
25
  XacheCollectiveQueryTool: () => XacheCollectiveQueryTool,
26
26
  XacheConversationBufferMemory: () => XacheConversationBufferMemory,
27
27
  XacheExtractor: () => XacheExtractor,
28
+ XacheGraphAskTool: () => XacheGraphAskTool,
29
+ XacheGraphEntityHistoryTool: () => XacheGraphEntityHistoryTool,
30
+ XacheGraphExtractTool: () => XacheGraphExtractTool,
31
+ XacheGraphLoadTool: () => XacheGraphLoadTool,
32
+ XacheGraphMergeEntitiesTool: () => XacheGraphMergeEntitiesTool,
33
+ XacheGraphQueryTool: () => XacheGraphQueryTool,
34
+ XacheGraphRetriever: () => XacheGraphRetriever,
28
35
  XacheMemory: () => XacheMemory,
29
36
  XacheReputationChecker: () => XacheReputationChecker,
30
37
  XacheReputationTool: () => XacheReputationTool,
31
38
  XacheRetriever: () => XacheRetriever,
32
39
  createCollectiveContributeTool: () => createCollectiveContributeTool,
33
40
  createCollectiveQueryTool: () => createCollectiveQueryTool,
41
+ createGraphAddEntityTool: () => createGraphAddEntityTool,
42
+ createGraphAddRelationshipTool: () => createGraphAddRelationshipTool,
43
+ createGraphAskTool: () => createGraphAskTool,
44
+ createGraphEntityHistoryTool: () => createGraphEntityHistoryTool,
45
+ createGraphExtractTool: () => createGraphExtractTool,
46
+ createGraphLoadTool: () => createGraphLoadTool,
47
+ createGraphMergeEntitiesTool: () => createGraphMergeEntitiesTool,
48
+ createGraphQueryTool: () => createGraphQueryTool,
34
49
  createReputationTool: () => createReputationTool
35
50
  });
36
51
  module.exports = __toCommonJS(index_exports);
@@ -55,6 +70,9 @@ var XacheChatMessageHistory = class extends import_chat_history.BaseListChatMess
55
70
  apiUrl: config.apiUrl || "https://api.xache.xyz",
56
71
  did,
57
72
  privateKey: config.privateKey,
73
+ signer: config.signer,
74
+ walletProvider: config.walletProvider,
75
+ encryptionKey: config.encryptionKey,
58
76
  timeout: config.timeout,
59
77
  debug: config.debug
60
78
  });
@@ -249,7 +267,10 @@ var XacheRetriever = class extends import_retrievers.BaseRetriever {
249
267
  this.client = new import_sdk2.XacheClient({
250
268
  apiUrl: config.apiUrl || "https://api.xache.xyz",
251
269
  did,
252
- privateKey: config.privateKey
270
+ privateKey: config.privateKey,
271
+ signer: config.signer,
272
+ walletProvider: config.walletProvider,
273
+ encryptionKey: config.encryptionKey
253
274
  });
254
275
  this.k = config.k ?? 5;
255
276
  this.filterContext = config.context;
@@ -295,6 +316,9 @@ var XacheExtractor = class {
295
316
  apiUrl: config.apiUrl || "https://api.xache.xyz",
296
317
  did,
297
318
  privateKey: config.privateKey,
319
+ signer: config.signer,
320
+ walletProvider: config.walletProvider,
321
+ encryptionKey: config.encryptionKey,
298
322
  timeout: config.timeout,
299
323
  debug: config.debug
300
324
  });
@@ -383,7 +407,10 @@ function createClient(config) {
383
407
  return new import_sdk4.XacheClient({
384
408
  apiUrl: config.apiUrl || "https://api.xache.xyz",
385
409
  did,
386
- privateKey: config.privateKey
410
+ privateKey: config.privateKey,
411
+ signer: config.signer,
412
+ walletProvider: config.walletProvider,
413
+ encryptionKey: config.encryptionKey
387
414
  });
388
415
  }
389
416
  function createCollectiveContributeTool(config) {
@@ -492,7 +519,10 @@ function createClient2(config) {
492
519
  return new import_sdk5.XacheClient({
493
520
  apiUrl: config.apiUrl || "https://api.xache.xyz",
494
521
  did,
495
- privateKey: config.privateKey
522
+ privateKey: config.privateKey,
523
+ signer: config.signer,
524
+ walletProvider: config.walletProvider,
525
+ encryptionKey: config.encryptionKey
496
526
  });
497
527
  }
498
528
  function createReputationTool(config) {
@@ -574,6 +604,392 @@ var XacheReputationChecker = class {
574
604
  return result.score >= minScore;
575
605
  }
576
606
  };
607
+
608
+ // src/graph.ts
609
+ var import_tools3 = require("@langchain/core/tools");
610
+ var import_retrievers2 = require("@langchain/core/retrievers");
611
+ var import_documents2 = require("@langchain/core/documents");
612
+ var import_zod3 = require("zod");
613
+ var import_sdk6 = require("@xache/sdk");
614
+ function createClient3(config) {
615
+ const chainPrefix = config.chain === "solana" ? "sol" : "evm";
616
+ const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}`;
617
+ return new import_sdk6.XacheClient({
618
+ apiUrl: config.apiUrl || "https://api.xache.xyz",
619
+ did,
620
+ privateKey: config.privateKey,
621
+ signer: config.signer,
622
+ walletProvider: config.walletProvider,
623
+ encryptionKey: config.encryptionKey
624
+ });
625
+ }
626
+ function getSubject(config) {
627
+ return config.subject || { scope: "GLOBAL" };
628
+ }
629
+ function buildLLMConfig(config) {
630
+ if (config.llmEndpoint) {
631
+ return {
632
+ type: "endpoint",
633
+ url: config.llmEndpoint,
634
+ authToken: config.llmAuthToken,
635
+ format: config.llmFormat || "openai",
636
+ model: config.llmModel
637
+ };
638
+ } else if (config.llmApiKey && config.llmProvider) {
639
+ return {
640
+ type: "api-key",
641
+ provider: config.llmProvider,
642
+ apiKey: config.llmApiKey,
643
+ model: config.llmModel
644
+ };
645
+ } else {
646
+ return {
647
+ type: "xache-managed",
648
+ provider: "anthropic",
649
+ model: config.llmModel
650
+ };
651
+ }
652
+ }
653
+ function createGraphExtractTool(config) {
654
+ const client = createClient3(config);
655
+ const subject = getSubject(config);
656
+ return new import_tools3.DynamicStructuredTool({
657
+ name: "xache_graph_extract",
658
+ description: "Extract entities and relationships from text into the knowledge graph. Identifies people, organizations, tools, concepts and their connections.",
659
+ schema: import_zod3.z.object({
660
+ trace: import_zod3.z.string().describe("The text/trace to extract entities from"),
661
+ contextHint: import_zod3.z.string().optional().describe('Domain hint (e.g., "engineering", "customer-support")')
662
+ }),
663
+ func: async ({ trace, contextHint }) => {
664
+ const result = await client.graph.extract({
665
+ trace,
666
+ llmConfig: buildLLMConfig(config),
667
+ subject,
668
+ options: {
669
+ contextHint,
670
+ confidenceThreshold: 0.7
671
+ }
672
+ });
673
+ const entities = result.entities || [];
674
+ const relationships = result.relationships || [];
675
+ if (entities.length === 0 && relationships.length === 0) {
676
+ return "No entities or relationships extracted.";
677
+ }
678
+ let output = `Extracted ${entities.length} entities, ${relationships.length} relationships.
679
+ `;
680
+ for (const e of entities) {
681
+ output += ` Entity: ${e.name} [${e.type}]${e.isNew ? " (new)" : ""}
682
+ `;
683
+ }
684
+ for (const r of relationships) {
685
+ output += ` Rel: ${r.from} \u2192 ${r.type} \u2192 ${r.to}
686
+ `;
687
+ }
688
+ return output;
689
+ }
690
+ });
691
+ }
692
+ function createGraphQueryTool(config) {
693
+ const client = createClient3(config);
694
+ const subject = getSubject(config);
695
+ return new import_tools3.DynamicStructuredTool({
696
+ name: "xache_graph_query",
697
+ description: "Query the knowledge graph around a specific entity. Returns connected entities and relationships within the specified depth.",
698
+ schema: import_zod3.z.object({
699
+ startEntity: import_zod3.z.string().describe("Name of the entity to start from"),
700
+ depth: import_zod3.z.number().optional().default(2).describe("Number of hops (default: 2)")
701
+ }),
702
+ func: async ({ startEntity, depth }) => {
703
+ const graph = await client.graph.query({
704
+ subject,
705
+ startEntity,
706
+ depth: depth || 2
707
+ });
708
+ const data = graph.toJSON();
709
+ if (data.entities.length === 0) {
710
+ return `No entities found connected to "${startEntity}".`;
711
+ }
712
+ let output = `Subgraph: ${data.entities.length} entities, ${data.relationships.length} relationships
713
+ `;
714
+ for (const e of data.entities) {
715
+ output += ` ${e.name} [${e.type}]`;
716
+ if (e.summary) output += ` \u2014 ${e.summary.substring(0, 80)}`;
717
+ output += "\n";
718
+ }
719
+ return output;
720
+ }
721
+ });
722
+ }
723
+ function createGraphAskTool(config) {
724
+ const client = createClient3(config);
725
+ const subject = getSubject(config);
726
+ return new import_tools3.DynamicStructuredTool({
727
+ name: "xache_graph_ask",
728
+ description: "Ask a natural language question about the knowledge graph. Uses LLM to analyze entities and relationships and provide an answer.",
729
+ schema: import_zod3.z.object({
730
+ question: import_zod3.z.string().describe("The question to ask about the knowledge graph")
731
+ }),
732
+ func: async ({ question }) => {
733
+ const answer = await client.graph.ask({
734
+ subject,
735
+ question,
736
+ llmConfig: buildLLMConfig(config)
737
+ });
738
+ let output = `Answer: ${answer.answer}
739
+ Confidence: ${(answer.confidence * 100).toFixed(0)}%`;
740
+ if (answer.sources?.length > 0) {
741
+ output += "\nSources: " + answer.sources.map((s) => `${s.name} [${s.type}]`).join(", ");
742
+ }
743
+ return output;
744
+ }
745
+ });
746
+ }
747
+ function createGraphAddEntityTool(config) {
748
+ const client = createClient3(config);
749
+ const subject = getSubject(config);
750
+ return new import_tools3.DynamicStructuredTool({
751
+ name: "xache_graph_add_entity",
752
+ description: "Add an entity to the knowledge graph. Creates a person, organization, tool, concept, or other entity type.",
753
+ schema: import_zod3.z.object({
754
+ name: import_zod3.z.string().describe("Entity name"),
755
+ type: import_zod3.z.string().describe("Entity type (person, organization, tool, concept, etc.)"),
756
+ summary: import_zod3.z.string().optional().describe("Brief description"),
757
+ attributes: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).optional().describe("Key-value attributes")
758
+ }),
759
+ func: async ({ name, type, summary, attributes }) => {
760
+ const entity = await client.graph.addEntity({
761
+ subject,
762
+ name,
763
+ type,
764
+ summary,
765
+ attributes
766
+ });
767
+ return `Created entity "${entity.name}" [${entity.type}], key: ${entity.key}`;
768
+ }
769
+ });
770
+ }
771
+ function createGraphAddRelationshipTool(config) {
772
+ const client = createClient3(config);
773
+ const subject = getSubject(config);
774
+ return new import_tools3.DynamicStructuredTool({
775
+ name: "xache_graph_add_relationship",
776
+ description: "Create a relationship between two entities in the knowledge graph.",
777
+ schema: import_zod3.z.object({
778
+ from: import_zod3.z.string().describe("Source entity name"),
779
+ to: import_zod3.z.string().describe("Target entity name"),
780
+ type: import_zod3.z.string().describe("Relationship type (works_at, knows, uses, manages, etc.)"),
781
+ description: import_zod3.z.string().optional().describe("Relationship description")
782
+ }),
783
+ func: async ({ from, to, type, description }) => {
784
+ const rel = await client.graph.addRelationship({
785
+ subject,
786
+ from,
787
+ to,
788
+ type,
789
+ description
790
+ });
791
+ return `Created relationship: ${from} \u2192 ${rel.type} \u2192 ${to}`;
792
+ }
793
+ });
794
+ }
795
+ function createGraphLoadTool(config) {
796
+ const client = createClient3(config);
797
+ const subject = getSubject(config);
798
+ return new import_tools3.DynamicStructuredTool({
799
+ name: "xache_graph_load",
800
+ description: "Load the full knowledge graph. Returns all entities and relationships. Optionally filter by entity type or load a historical snapshot.",
801
+ schema: import_zod3.z.object({
802
+ entityTypes: import_zod3.z.array(import_zod3.z.string()).optional().describe("Filter to specific entity types"),
803
+ validAt: import_zod3.z.string().optional().describe("Load graph as it existed at this time (ISO8601)")
804
+ }),
805
+ func: async ({ entityTypes, validAt }) => {
806
+ const graph = await client.graph.load({
807
+ subject,
808
+ entityTypes,
809
+ validAt
810
+ });
811
+ const data = graph.toJSON();
812
+ if (data.entities.length === 0) {
813
+ return "Knowledge graph is empty.";
814
+ }
815
+ let output = `Knowledge graph: ${data.entities.length} entities, ${data.relationships.length} relationships
816
+ `;
817
+ for (const e of data.entities) {
818
+ output += ` ${e.name} [${e.type}]`;
819
+ if (e.summary) output += ` \u2014 ${e.summary.substring(0, 80)}`;
820
+ output += "\n";
821
+ }
822
+ return output;
823
+ }
824
+ });
825
+ }
826
+ function createGraphMergeEntitiesTool(config) {
827
+ const client = createClient3(config);
828
+ const subject = getSubject(config);
829
+ return new import_tools3.DynamicStructuredTool({
830
+ name: "xache_graph_merge_entities",
831
+ description: "Merge two entities into one. The source entity is superseded and the target entity is updated with merged attributes. Relationships are transferred.",
832
+ schema: import_zod3.z.object({
833
+ sourceName: import_zod3.z.string().describe("Entity to merge FROM (will be superseded)"),
834
+ targetName: import_zod3.z.string().describe("Entity to merge INTO (will be updated)")
835
+ }),
836
+ func: async ({ sourceName, targetName }) => {
837
+ const merged = await client.graph.mergeEntities({
838
+ subject,
839
+ sourceName,
840
+ targetName
841
+ });
842
+ return `Merged "${sourceName}" into "${targetName}". Result: ${merged.name} [${merged.type}] (v${merged.version})`;
843
+ }
844
+ });
845
+ }
846
+ function createGraphEntityHistoryTool(config) {
847
+ const client = createClient3(config);
848
+ const subject = getSubject(config);
849
+ return new import_tools3.DynamicStructuredTool({
850
+ name: "xache_graph_entity_history",
851
+ description: "Get the full version history of an entity. Shows how the entity has changed over time.",
852
+ schema: import_zod3.z.object({
853
+ name: import_zod3.z.string().describe("Entity name to look up history for")
854
+ }),
855
+ func: async ({ name }) => {
856
+ const versions = await client.graph.getEntityHistory({
857
+ subject,
858
+ name
859
+ });
860
+ if (versions.length === 0) {
861
+ return `No history found for entity "${name}".`;
862
+ }
863
+ let output = `History for "${name}": ${versions.length} version(s)
864
+ `;
865
+ for (const v of versions) {
866
+ output += ` v${v.version} \u2014 ${v.name} [${v.type}]`;
867
+ if (v.summary) output += ` | ${v.summary.substring(0, 80)}`;
868
+ output += `
869
+ Valid: ${v.validFrom}${v.validTo ? ` \u2192 ${v.validTo}` : " \u2192 current"}
870
+ `;
871
+ }
872
+ return output;
873
+ }
874
+ });
875
+ }
876
+ var XacheGraphExtractTool = class {
877
+ constructor(config) {
878
+ this.tool = createGraphExtractTool(config);
879
+ }
880
+ asTool() {
881
+ return this.tool;
882
+ }
883
+ };
884
+ var XacheGraphQueryTool = class {
885
+ constructor(config) {
886
+ this.tool = createGraphQueryTool(config);
887
+ }
888
+ asTool() {
889
+ return this.tool;
890
+ }
891
+ };
892
+ var XacheGraphAskTool = class {
893
+ constructor(config) {
894
+ this.tool = createGraphAskTool(config);
895
+ }
896
+ asTool() {
897
+ return this.tool;
898
+ }
899
+ };
900
+ var XacheGraphLoadTool = class {
901
+ constructor(config) {
902
+ this.tool = createGraphLoadTool(config);
903
+ }
904
+ asTool() {
905
+ return this.tool;
906
+ }
907
+ };
908
+ var XacheGraphMergeEntitiesTool = class {
909
+ constructor(config) {
910
+ this.tool = createGraphMergeEntitiesTool(config);
911
+ }
912
+ asTool() {
913
+ return this.tool;
914
+ }
915
+ };
916
+ var XacheGraphEntityHistoryTool = class {
917
+ constructor(config) {
918
+ this.tool = createGraphEntityHistoryTool(config);
919
+ }
920
+ asTool() {
921
+ return this.tool;
922
+ }
923
+ };
924
+ var XacheGraphRetriever = class extends import_retrievers2.BaseRetriever {
925
+ constructor(config) {
926
+ super(config);
927
+ this.lc_namespace = ["xache", "graph_retriever"];
928
+ const chainPrefix = config.chain === "solana" ? "sol" : "evm";
929
+ const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}`;
930
+ this.client = new import_sdk6.XacheClient({
931
+ apiUrl: config.apiUrl || "https://api.xache.xyz",
932
+ did,
933
+ privateKey: config.privateKey,
934
+ signer: config.signer,
935
+ walletProvider: config.walletProvider,
936
+ encryptionKey: config.encryptionKey
937
+ });
938
+ this.subject = config.subject || { scope: "GLOBAL" };
939
+ this.startEntity = config.startEntity;
940
+ this.depth = config.depth ?? 2;
941
+ this.k = config.k ?? 10;
942
+ }
943
+ static lc_name() {
944
+ return "XacheGraphRetriever";
945
+ }
946
+ async _getRelevantDocuments(query, _runManager) {
947
+ let graph;
948
+ if (this.startEntity) {
949
+ graph = await this.client.graph.query({
950
+ subject: this.subject,
951
+ startEntity: this.startEntity,
952
+ depth: this.depth
953
+ });
954
+ } else {
955
+ graph = await this.client.graph.load({ subject: this.subject });
956
+ }
957
+ const data = graph.toJSON();
958
+ const queryLower = query.toLowerCase();
959
+ const scored = data.entities.map((entity) => {
960
+ let score = 0;
961
+ const nameLower = entity.name.toLowerCase();
962
+ const summaryLower = (entity.summary || "").toLowerCase();
963
+ if (nameLower.includes(queryLower)) score += 3;
964
+ if (summaryLower.includes(queryLower)) score += 2;
965
+ const terms = queryLower.split(/\s+/);
966
+ for (const term of terms) {
967
+ if (nameLower.includes(term)) score += 1;
968
+ if (summaryLower.includes(term)) score += 0.5;
969
+ }
970
+ return { entity, score };
971
+ });
972
+ scored.sort((a, b) => b.score - a.score);
973
+ const topEntities = scored.slice(0, this.k);
974
+ return topEntities.map(({ entity }) => {
975
+ const content = [
976
+ `Name: ${entity.name}`,
977
+ `Type: ${entity.type}`,
978
+ entity.summary ? `Summary: ${entity.summary}` : null
979
+ ].filter(Boolean).join("\n");
980
+ return new import_documents2.Document({
981
+ pageContent: content,
982
+ metadata: {
983
+ source: "xache-graph",
984
+ entityKey: entity.key,
985
+ entityName: entity.name,
986
+ entityType: entity.type,
987
+ storageKey: entity.storageKey
988
+ }
989
+ });
990
+ });
991
+ }
992
+ };
577
993
  // Annotate the CommonJS export names for ESM import in node:
578
994
  0 && (module.exports = {
579
995
  XacheChatMessageHistory,
@@ -581,12 +997,27 @@ var XacheReputationChecker = class {
581
997
  XacheCollectiveQueryTool,
582
998
  XacheConversationBufferMemory,
583
999
  XacheExtractor,
1000
+ XacheGraphAskTool,
1001
+ XacheGraphEntityHistoryTool,
1002
+ XacheGraphExtractTool,
1003
+ XacheGraphLoadTool,
1004
+ XacheGraphMergeEntitiesTool,
1005
+ XacheGraphQueryTool,
1006
+ XacheGraphRetriever,
584
1007
  XacheMemory,
585
1008
  XacheReputationChecker,
586
1009
  XacheReputationTool,
587
1010
  XacheRetriever,
588
1011
  createCollectiveContributeTool,
589
1012
  createCollectiveQueryTool,
1013
+ createGraphAddEntityTool,
1014
+ createGraphAddRelationshipTool,
1015
+ createGraphAskTool,
1016
+ createGraphEntityHistoryTool,
1017
+ createGraphExtractTool,
1018
+ createGraphLoadTool,
1019
+ createGraphMergeEntitiesTool,
1020
+ createGraphQueryTool,
590
1021
  createReputationTool
591
1022
  });
592
1023
  //# sourceMappingURL=index.js.map