@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.mjs CHANGED
@@ -22,6 +22,9 @@ var XacheChatMessageHistory = class extends BaseListChatMessageHistory {
22
22
  apiUrl: config.apiUrl || "https://api.xache.xyz",
23
23
  did,
24
24
  privateKey: config.privateKey,
25
+ signer: config.signer,
26
+ walletProvider: config.walletProvider,
27
+ encryptionKey: config.encryptionKey,
25
28
  timeout: config.timeout,
26
29
  debug: config.debug
27
30
  });
@@ -216,7 +219,10 @@ var XacheRetriever = class extends BaseRetriever {
216
219
  this.client = new XacheClient2({
217
220
  apiUrl: config.apiUrl || "https://api.xache.xyz",
218
221
  did,
219
- privateKey: config.privateKey
222
+ privateKey: config.privateKey,
223
+ signer: config.signer,
224
+ walletProvider: config.walletProvider,
225
+ encryptionKey: config.encryptionKey
220
226
  });
221
227
  this.k = config.k ?? 5;
222
228
  this.filterContext = config.context;
@@ -262,6 +268,9 @@ var XacheExtractor = class {
262
268
  apiUrl: config.apiUrl || "https://api.xache.xyz",
263
269
  did,
264
270
  privateKey: config.privateKey,
271
+ signer: config.signer,
272
+ walletProvider: config.walletProvider,
273
+ encryptionKey: config.encryptionKey,
265
274
  timeout: config.timeout,
266
275
  debug: config.debug
267
276
  });
@@ -350,7 +359,10 @@ function createClient(config) {
350
359
  return new XacheClient4({
351
360
  apiUrl: config.apiUrl || "https://api.xache.xyz",
352
361
  did,
353
- privateKey: config.privateKey
362
+ privateKey: config.privateKey,
363
+ signer: config.signer,
364
+ walletProvider: config.walletProvider,
365
+ encryptionKey: config.encryptionKey
354
366
  });
355
367
  }
356
368
  function createCollectiveContributeTool(config) {
@@ -459,7 +471,10 @@ function createClient2(config) {
459
471
  return new XacheClient5({
460
472
  apiUrl: config.apiUrl || "https://api.xache.xyz",
461
473
  did,
462
- privateKey: config.privateKey
474
+ privateKey: config.privateKey,
475
+ signer: config.signer,
476
+ walletProvider: config.walletProvider,
477
+ encryptionKey: config.encryptionKey
463
478
  });
464
479
  }
465
480
  function createReputationTool(config) {
@@ -541,18 +556,421 @@ var XacheReputationChecker = class {
541
556
  return result.score >= minScore;
542
557
  }
543
558
  };
559
+
560
+ // src/graph.ts
561
+ import { DynamicStructuredTool as DynamicStructuredTool3 } from "@langchain/core/tools";
562
+ import { BaseRetriever as BaseRetriever2 } from "@langchain/core/retrievers";
563
+ import { Document as Document2 } from "@langchain/core/documents";
564
+ import { z as z3 } from "zod";
565
+ import {
566
+ XacheClient as XacheClient6
567
+ } from "@xache/sdk";
568
+ function createClient3(config) {
569
+ const chainPrefix = config.chain === "solana" ? "sol" : "evm";
570
+ const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}`;
571
+ return new XacheClient6({
572
+ apiUrl: config.apiUrl || "https://api.xache.xyz",
573
+ did,
574
+ privateKey: config.privateKey,
575
+ signer: config.signer,
576
+ walletProvider: config.walletProvider,
577
+ encryptionKey: config.encryptionKey
578
+ });
579
+ }
580
+ function getSubject(config) {
581
+ return config.subject || { scope: "GLOBAL" };
582
+ }
583
+ function buildLLMConfig(config) {
584
+ if (config.llmEndpoint) {
585
+ return {
586
+ type: "endpoint",
587
+ url: config.llmEndpoint,
588
+ authToken: config.llmAuthToken,
589
+ format: config.llmFormat || "openai",
590
+ model: config.llmModel
591
+ };
592
+ } else if (config.llmApiKey && config.llmProvider) {
593
+ return {
594
+ type: "api-key",
595
+ provider: config.llmProvider,
596
+ apiKey: config.llmApiKey,
597
+ model: config.llmModel
598
+ };
599
+ } else {
600
+ return {
601
+ type: "xache-managed",
602
+ provider: "anthropic",
603
+ model: config.llmModel
604
+ };
605
+ }
606
+ }
607
+ function createGraphExtractTool(config) {
608
+ const client = createClient3(config);
609
+ const subject = getSubject(config);
610
+ return new DynamicStructuredTool3({
611
+ name: "xache_graph_extract",
612
+ description: "Extract entities and relationships from text into the knowledge graph. Identifies people, organizations, tools, concepts and their connections.",
613
+ schema: z3.object({
614
+ trace: z3.string().describe("The text/trace to extract entities from"),
615
+ contextHint: z3.string().optional().describe('Domain hint (e.g., "engineering", "customer-support")')
616
+ }),
617
+ func: async ({ trace, contextHint }) => {
618
+ const result = await client.graph.extract({
619
+ trace,
620
+ llmConfig: buildLLMConfig(config),
621
+ subject,
622
+ options: {
623
+ contextHint,
624
+ confidenceThreshold: 0.7
625
+ }
626
+ });
627
+ const entities = result.entities || [];
628
+ const relationships = result.relationships || [];
629
+ if (entities.length === 0 && relationships.length === 0) {
630
+ return "No entities or relationships extracted.";
631
+ }
632
+ let output = `Extracted ${entities.length} entities, ${relationships.length} relationships.
633
+ `;
634
+ for (const e of entities) {
635
+ output += ` Entity: ${e.name} [${e.type}]${e.isNew ? " (new)" : ""}
636
+ `;
637
+ }
638
+ for (const r of relationships) {
639
+ output += ` Rel: ${r.from} \u2192 ${r.type} \u2192 ${r.to}
640
+ `;
641
+ }
642
+ return output;
643
+ }
644
+ });
645
+ }
646
+ function createGraphQueryTool(config) {
647
+ const client = createClient3(config);
648
+ const subject = getSubject(config);
649
+ return new DynamicStructuredTool3({
650
+ name: "xache_graph_query",
651
+ description: "Query the knowledge graph around a specific entity. Returns connected entities and relationships within the specified depth.",
652
+ schema: z3.object({
653
+ startEntity: z3.string().describe("Name of the entity to start from"),
654
+ depth: z3.number().optional().default(2).describe("Number of hops (default: 2)")
655
+ }),
656
+ func: async ({ startEntity, depth }) => {
657
+ const graph = await client.graph.query({
658
+ subject,
659
+ startEntity,
660
+ depth: depth || 2
661
+ });
662
+ const data = graph.toJSON();
663
+ if (data.entities.length === 0) {
664
+ return `No entities found connected to "${startEntity}".`;
665
+ }
666
+ let output = `Subgraph: ${data.entities.length} entities, ${data.relationships.length} relationships
667
+ `;
668
+ for (const e of data.entities) {
669
+ output += ` ${e.name} [${e.type}]`;
670
+ if (e.summary) output += ` \u2014 ${e.summary.substring(0, 80)}`;
671
+ output += "\n";
672
+ }
673
+ return output;
674
+ }
675
+ });
676
+ }
677
+ function createGraphAskTool(config) {
678
+ const client = createClient3(config);
679
+ const subject = getSubject(config);
680
+ return new DynamicStructuredTool3({
681
+ name: "xache_graph_ask",
682
+ description: "Ask a natural language question about the knowledge graph. Uses LLM to analyze entities and relationships and provide an answer.",
683
+ schema: z3.object({
684
+ question: z3.string().describe("The question to ask about the knowledge graph")
685
+ }),
686
+ func: async ({ question }) => {
687
+ const answer = await client.graph.ask({
688
+ subject,
689
+ question,
690
+ llmConfig: buildLLMConfig(config)
691
+ });
692
+ let output = `Answer: ${answer.answer}
693
+ Confidence: ${(answer.confidence * 100).toFixed(0)}%`;
694
+ if (answer.sources?.length > 0) {
695
+ output += "\nSources: " + answer.sources.map((s) => `${s.name} [${s.type}]`).join(", ");
696
+ }
697
+ return output;
698
+ }
699
+ });
700
+ }
701
+ function createGraphAddEntityTool(config) {
702
+ const client = createClient3(config);
703
+ const subject = getSubject(config);
704
+ return new DynamicStructuredTool3({
705
+ name: "xache_graph_add_entity",
706
+ description: "Add an entity to the knowledge graph. Creates a person, organization, tool, concept, or other entity type.",
707
+ schema: z3.object({
708
+ name: z3.string().describe("Entity name"),
709
+ type: z3.string().describe("Entity type (person, organization, tool, concept, etc.)"),
710
+ summary: z3.string().optional().describe("Brief description"),
711
+ attributes: z3.record(z3.string(), z3.unknown()).optional().describe("Key-value attributes")
712
+ }),
713
+ func: async ({ name, type, summary, attributes }) => {
714
+ const entity = await client.graph.addEntity({
715
+ subject,
716
+ name,
717
+ type,
718
+ summary,
719
+ attributes
720
+ });
721
+ return `Created entity "${entity.name}" [${entity.type}], key: ${entity.key}`;
722
+ }
723
+ });
724
+ }
725
+ function createGraphAddRelationshipTool(config) {
726
+ const client = createClient3(config);
727
+ const subject = getSubject(config);
728
+ return new DynamicStructuredTool3({
729
+ name: "xache_graph_add_relationship",
730
+ description: "Create a relationship between two entities in the knowledge graph.",
731
+ schema: z3.object({
732
+ from: z3.string().describe("Source entity name"),
733
+ to: z3.string().describe("Target entity name"),
734
+ type: z3.string().describe("Relationship type (works_at, knows, uses, manages, etc.)"),
735
+ description: z3.string().optional().describe("Relationship description")
736
+ }),
737
+ func: async ({ from, to, type, description }) => {
738
+ const rel = await client.graph.addRelationship({
739
+ subject,
740
+ from,
741
+ to,
742
+ type,
743
+ description
744
+ });
745
+ return `Created relationship: ${from} \u2192 ${rel.type} \u2192 ${to}`;
746
+ }
747
+ });
748
+ }
749
+ function createGraphLoadTool(config) {
750
+ const client = createClient3(config);
751
+ const subject = getSubject(config);
752
+ return new DynamicStructuredTool3({
753
+ name: "xache_graph_load",
754
+ description: "Load the full knowledge graph. Returns all entities and relationships. Optionally filter by entity type or load a historical snapshot.",
755
+ schema: z3.object({
756
+ entityTypes: z3.array(z3.string()).optional().describe("Filter to specific entity types"),
757
+ validAt: z3.string().optional().describe("Load graph as it existed at this time (ISO8601)")
758
+ }),
759
+ func: async ({ entityTypes, validAt }) => {
760
+ const graph = await client.graph.load({
761
+ subject,
762
+ entityTypes,
763
+ validAt
764
+ });
765
+ const data = graph.toJSON();
766
+ if (data.entities.length === 0) {
767
+ return "Knowledge graph is empty.";
768
+ }
769
+ let output = `Knowledge graph: ${data.entities.length} entities, ${data.relationships.length} relationships
770
+ `;
771
+ for (const e of data.entities) {
772
+ output += ` ${e.name} [${e.type}]`;
773
+ if (e.summary) output += ` \u2014 ${e.summary.substring(0, 80)}`;
774
+ output += "\n";
775
+ }
776
+ return output;
777
+ }
778
+ });
779
+ }
780
+ function createGraphMergeEntitiesTool(config) {
781
+ const client = createClient3(config);
782
+ const subject = getSubject(config);
783
+ return new DynamicStructuredTool3({
784
+ name: "xache_graph_merge_entities",
785
+ description: "Merge two entities into one. The source entity is superseded and the target entity is updated with merged attributes. Relationships are transferred.",
786
+ schema: z3.object({
787
+ sourceName: z3.string().describe("Entity to merge FROM (will be superseded)"),
788
+ targetName: z3.string().describe("Entity to merge INTO (will be updated)")
789
+ }),
790
+ func: async ({ sourceName, targetName }) => {
791
+ const merged = await client.graph.mergeEntities({
792
+ subject,
793
+ sourceName,
794
+ targetName
795
+ });
796
+ return `Merged "${sourceName}" into "${targetName}". Result: ${merged.name} [${merged.type}] (v${merged.version})`;
797
+ }
798
+ });
799
+ }
800
+ function createGraphEntityHistoryTool(config) {
801
+ const client = createClient3(config);
802
+ const subject = getSubject(config);
803
+ return new DynamicStructuredTool3({
804
+ name: "xache_graph_entity_history",
805
+ description: "Get the full version history of an entity. Shows how the entity has changed over time.",
806
+ schema: z3.object({
807
+ name: z3.string().describe("Entity name to look up history for")
808
+ }),
809
+ func: async ({ name }) => {
810
+ const versions = await client.graph.getEntityHistory({
811
+ subject,
812
+ name
813
+ });
814
+ if (versions.length === 0) {
815
+ return `No history found for entity "${name}".`;
816
+ }
817
+ let output = `History for "${name}": ${versions.length} version(s)
818
+ `;
819
+ for (const v of versions) {
820
+ output += ` v${v.version} \u2014 ${v.name} [${v.type}]`;
821
+ if (v.summary) output += ` | ${v.summary.substring(0, 80)}`;
822
+ output += `
823
+ Valid: ${v.validFrom}${v.validTo ? ` \u2192 ${v.validTo}` : " \u2192 current"}
824
+ `;
825
+ }
826
+ return output;
827
+ }
828
+ });
829
+ }
830
+ var XacheGraphExtractTool = class {
831
+ constructor(config) {
832
+ this.tool = createGraphExtractTool(config);
833
+ }
834
+ asTool() {
835
+ return this.tool;
836
+ }
837
+ };
838
+ var XacheGraphQueryTool = class {
839
+ constructor(config) {
840
+ this.tool = createGraphQueryTool(config);
841
+ }
842
+ asTool() {
843
+ return this.tool;
844
+ }
845
+ };
846
+ var XacheGraphAskTool = class {
847
+ constructor(config) {
848
+ this.tool = createGraphAskTool(config);
849
+ }
850
+ asTool() {
851
+ return this.tool;
852
+ }
853
+ };
854
+ var XacheGraphLoadTool = class {
855
+ constructor(config) {
856
+ this.tool = createGraphLoadTool(config);
857
+ }
858
+ asTool() {
859
+ return this.tool;
860
+ }
861
+ };
862
+ var XacheGraphMergeEntitiesTool = class {
863
+ constructor(config) {
864
+ this.tool = createGraphMergeEntitiesTool(config);
865
+ }
866
+ asTool() {
867
+ return this.tool;
868
+ }
869
+ };
870
+ var XacheGraphEntityHistoryTool = class {
871
+ constructor(config) {
872
+ this.tool = createGraphEntityHistoryTool(config);
873
+ }
874
+ asTool() {
875
+ return this.tool;
876
+ }
877
+ };
878
+ var XacheGraphRetriever = class extends BaseRetriever2 {
879
+ constructor(config) {
880
+ super(config);
881
+ this.lc_namespace = ["xache", "graph_retriever"];
882
+ const chainPrefix = config.chain === "solana" ? "sol" : "evm";
883
+ const did = `did:agent:${chainPrefix}:${config.walletAddress.toLowerCase()}`;
884
+ this.client = new XacheClient6({
885
+ apiUrl: config.apiUrl || "https://api.xache.xyz",
886
+ did,
887
+ privateKey: config.privateKey,
888
+ signer: config.signer,
889
+ walletProvider: config.walletProvider,
890
+ encryptionKey: config.encryptionKey
891
+ });
892
+ this.subject = config.subject || { scope: "GLOBAL" };
893
+ this.startEntity = config.startEntity;
894
+ this.depth = config.depth ?? 2;
895
+ this.k = config.k ?? 10;
896
+ }
897
+ static lc_name() {
898
+ return "XacheGraphRetriever";
899
+ }
900
+ async _getRelevantDocuments(query, _runManager) {
901
+ let graph;
902
+ if (this.startEntity) {
903
+ graph = await this.client.graph.query({
904
+ subject: this.subject,
905
+ startEntity: this.startEntity,
906
+ depth: this.depth
907
+ });
908
+ } else {
909
+ graph = await this.client.graph.load({ subject: this.subject });
910
+ }
911
+ const data = graph.toJSON();
912
+ const queryLower = query.toLowerCase();
913
+ const scored = data.entities.map((entity) => {
914
+ let score = 0;
915
+ const nameLower = entity.name.toLowerCase();
916
+ const summaryLower = (entity.summary || "").toLowerCase();
917
+ if (nameLower.includes(queryLower)) score += 3;
918
+ if (summaryLower.includes(queryLower)) score += 2;
919
+ const terms = queryLower.split(/\s+/);
920
+ for (const term of terms) {
921
+ if (nameLower.includes(term)) score += 1;
922
+ if (summaryLower.includes(term)) score += 0.5;
923
+ }
924
+ return { entity, score };
925
+ });
926
+ scored.sort((a, b) => b.score - a.score);
927
+ const topEntities = scored.slice(0, this.k);
928
+ return topEntities.map(({ entity }) => {
929
+ const content = [
930
+ `Name: ${entity.name}`,
931
+ `Type: ${entity.type}`,
932
+ entity.summary ? `Summary: ${entity.summary}` : null
933
+ ].filter(Boolean).join("\n");
934
+ return new Document2({
935
+ pageContent: content,
936
+ metadata: {
937
+ source: "xache-graph",
938
+ entityKey: entity.key,
939
+ entityName: entity.name,
940
+ entityType: entity.type,
941
+ storageKey: entity.storageKey
942
+ }
943
+ });
944
+ });
945
+ }
946
+ };
544
947
  export {
545
948
  XacheChatMessageHistory,
546
949
  XacheCollectiveContributeTool,
547
950
  XacheCollectiveQueryTool,
548
951
  XacheConversationBufferMemory,
549
952
  XacheExtractor,
953
+ XacheGraphAskTool,
954
+ XacheGraphEntityHistoryTool,
955
+ XacheGraphExtractTool,
956
+ XacheGraphLoadTool,
957
+ XacheGraphMergeEntitiesTool,
958
+ XacheGraphQueryTool,
959
+ XacheGraphRetriever,
550
960
  XacheMemory,
551
961
  XacheReputationChecker,
552
962
  XacheReputationTool,
553
963
  XacheRetriever,
554
964
  createCollectiveContributeTool,
555
965
  createCollectiveQueryTool,
966
+ createGraphAddEntityTool,
967
+ createGraphAddRelationshipTool,
968
+ createGraphAskTool,
969
+ createGraphEntityHistoryTool,
970
+ createGraphExtractTool,
971
+ createGraphLoadTool,
972
+ createGraphMergeEntitiesTool,
973
+ createGraphQueryTool,
556
974
  createReputationTool
557
975
  };
558
976
  //# sourceMappingURL=index.mjs.map