@xache/langchain 0.1.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/README.md ADDED
@@ -0,0 +1,177 @@
1
+ # @xache/langchain
2
+
3
+ LangChain.js integration for [Xache Protocol](https://xache.xyz) - verifiable AI agent memory with cryptographic receipts, collective intelligence, and portable ERC-8004 reputation.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @xache/langchain @langchain/core langchain
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ### One-Line Memory Replacement
14
+
15
+ ```typescript
16
+ // Before (standard LangChain)
17
+ import { BufferMemory } from 'langchain/memory';
18
+ const memory = new BufferMemory();
19
+
20
+ // After (with Xache - one line change!)
21
+ import { XacheMemory } from '@xache/langchain';
22
+ const memory = new XacheMemory({
23
+ walletAddress: '0x...',
24
+ privateKey: '0x...',
25
+ });
26
+
27
+ // Everything else stays the same
28
+ const chain = new ConversationChain({ llm, memory });
29
+ ```
30
+
31
+ ## Features
32
+
33
+ ### Memory Storage
34
+
35
+ Persistent memory that survives across sessions with cryptographic receipts:
36
+
37
+ ```typescript
38
+ import { XacheMemory } from '@xache/langchain';
39
+
40
+ const memory = new XacheMemory({
41
+ walletAddress: '0xYourWallet',
42
+ privateKey: '0xYourPrivateKey',
43
+ apiUrl: 'https://api.xache.xyz', // optional
44
+ chain: 'base', // or 'solana'
45
+ });
46
+ ```
47
+
48
+ ### Retrieval (RAG)
49
+
50
+ Semantic search for retrieval-augmented generation:
51
+
52
+ ```typescript
53
+ import { XacheRetriever } from '@xache/langchain';
54
+ import { RetrievalQAChain } from 'langchain/chains';
55
+
56
+ const retriever = new XacheRetriever({
57
+ walletAddress: '0x...',
58
+ privateKey: '0x...',
59
+ k: 5, // number of documents
60
+ });
61
+
62
+ const qa = RetrievalQAChain.fromLLM(llm, retriever);
63
+ ```
64
+
65
+ ### Collective Intelligence
66
+
67
+ Query and contribute to shared knowledge:
68
+
69
+ ```typescript
70
+ import {
71
+ createCollectiveContributeTool,
72
+ createCollectiveQueryTool,
73
+ } from '@xache/langchain';
74
+
75
+ // Add to your agent's tools
76
+ const contributeTool = createCollectiveContributeTool({
77
+ walletAddress: '0x...',
78
+ privateKey: '0x...',
79
+ });
80
+
81
+ const queryTool = createCollectiveQueryTool({
82
+ walletAddress: '0x...',
83
+ privateKey: '0x...',
84
+ });
85
+
86
+ const tools = [contributeTool, queryTool];
87
+ ```
88
+
89
+ ### Memory Extraction
90
+
91
+ Auto-extract memories from conversations:
92
+
93
+ ```typescript
94
+ import { XacheExtractor } from '@xache/langchain';
95
+
96
+ const extractor = new XacheExtractor({
97
+ walletAddress: '0x...',
98
+ privateKey: '0x...',
99
+ mode: 'xache-managed', // or 'api-key' with your LLM key
100
+ });
101
+
102
+ const result = await extractor.extract(
103
+ 'User asked about quantum computing...',
104
+ { autoStore: true }
105
+ );
106
+
107
+ console.log(`Extracted ${result.count} memories`);
108
+ ```
109
+
110
+ ### Reputation
111
+
112
+ Check and verify agent reputation:
113
+
114
+ ```typescript
115
+ import { createReputationTool, XacheReputationChecker } from '@xache/langchain';
116
+
117
+ // As a tool for your agent
118
+ const repTool = createReputationTool({
119
+ walletAddress: '0x...',
120
+ privateKey: '0x...',
121
+ });
122
+
123
+ // Or check other agents
124
+ const checker = new XacheReputationChecker({
125
+ walletAddress: '0x...',
126
+ privateKey: '0x...',
127
+ });
128
+
129
+ const otherRep = await checker.check('did:agent:evm:0xOtherAgent...');
130
+ if (otherRep.score >= 0.5) {
131
+ console.log('Agent is trustworthy');
132
+ }
133
+ ```
134
+
135
+ ## Chat History
136
+
137
+ For more control over message history:
138
+
139
+ ```typescript
140
+ import { XacheChatMessageHistory } from '@xache/langchain';
141
+ import { BufferMemory } from 'langchain/memory';
142
+
143
+ const history = new XacheChatMessageHistory({
144
+ walletAddress: '0x...',
145
+ privateKey: '0x...',
146
+ sessionId: 'unique-session-id',
147
+ });
148
+
149
+ const memory = new BufferMemory({ chatHistory: history });
150
+ ```
151
+
152
+ ## Pricing
153
+
154
+ All operations use x402 micropayments (auto-handled):
155
+
156
+ | Operation | Price |
157
+ | -------------------- | ------ |
158
+ | Memory Store | $0.002 |
159
+ | Memory Retrieve | $0.003 |
160
+ | Collective Contribute| $0.002 |
161
+ | Collective Query | $0.011 |
162
+ | Extraction (managed) | $0.011 |
163
+
164
+ ## ERC-8004 Portable Reputation
165
+
166
+ Xache supports [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004) for portable, on-chain reputation. Enable it to make your agent's reputation verifiable across platforms.
167
+
168
+ ## Resources
169
+
170
+ - [Documentation](https://docs.xache.xyz)
171
+ - [API Reference](https://docs.xache.xyz/api)
172
+ - [GitHub](https://github.com/oliveskin/xache)
173
+ - [Discord](https://discord.gg/xache)
174
+
175
+ ## License
176
+
177
+ MIT
@@ -0,0 +1,457 @@
1
+ import { BaseMemory, InputValues, MemoryVariables, OutputValues } from '@langchain/core/memory';
2
+ import { BaseListChatMessageHistory } from '@langchain/core/chat_history';
3
+ import { BaseMessage } from '@langchain/core/messages';
4
+ import { BaseRetriever, BaseRetrieverInput } from '@langchain/core/retrievers';
5
+ import { Document } from '@langchain/core/documents';
6
+ import { CallbackManagerForRetrieverRun } from '@langchain/core/callbacks/manager';
7
+ import { DynamicStructuredTool } from '@langchain/core/tools';
8
+
9
+ /**
10
+ * Xache Chat Message History for LangChain.js
11
+ * Persistent message storage with cryptographic receipts
12
+ */
13
+
14
+ interface XacheChatMessageHistoryConfig {
15
+ /** Wallet address for authentication */
16
+ walletAddress: string;
17
+ /** Private key for signing */
18
+ privateKey: string;
19
+ /** Session ID to group messages */
20
+ sessionId?: string;
21
+ /** API URL (defaults to https://api.xache.xyz) */
22
+ apiUrl?: string;
23
+ /** Chain: 'base' or 'solana' */
24
+ chain?: 'base' | 'solana';
25
+ /** Maximum messages to load (default: 1000, set to -1 for unlimited) */
26
+ maxMessages?: number;
27
+ /** Page size for loading messages (default: 100) */
28
+ pageSize?: number;
29
+ /** Request timeout in milliseconds (default: 30000) */
30
+ timeout?: number;
31
+ /** Enable debug logging */
32
+ debug?: boolean;
33
+ }
34
+ /**
35
+ * Chat message history backed by Xache Protocol.
36
+ *
37
+ * Messages are stored with cryptographic receipts and can persist
38
+ * across sessions.
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * import { XacheChatMessageHistory } from '@xache/langchain';
43
+ *
44
+ * const history = new XacheChatMessageHistory({
45
+ * walletAddress: '0x...',
46
+ * privateKey: '0x...',
47
+ * sessionId: 'unique-session-id',
48
+ * });
49
+ *
50
+ * await history.addUserMessage('Hello!');
51
+ * await history.addAIMessage('Hi there!');
52
+ *
53
+ * const messages = await history.getMessages();
54
+ * ```
55
+ */
56
+ declare class XacheChatMessageHistory extends BaseListChatMessageHistory {
57
+ lc_namespace: string[];
58
+ private client;
59
+ private sessionId;
60
+ private messages;
61
+ private initialized;
62
+ private maxMessages;
63
+ private pageSize;
64
+ constructor(config: XacheChatMessageHistoryConfig);
65
+ /**
66
+ * Get all messages in the history
67
+ */
68
+ getMessages(): Promise<BaseMessage[]>;
69
+ /**
70
+ * Add a message to the history
71
+ */
72
+ addMessage(message: BaseMessage): Promise<void>;
73
+ /**
74
+ * Add a user message
75
+ */
76
+ addUserMessage(message: string): Promise<void>;
77
+ /**
78
+ * Add an AI message
79
+ */
80
+ addAIMessage(message: string): Promise<void>;
81
+ /**
82
+ * Clear all messages from history
83
+ */
84
+ clear(): Promise<void>;
85
+ /**
86
+ * Load messages from Xache storage with pagination support
87
+ */
88
+ private loadMessages;
89
+ private getMessageRole;
90
+ }
91
+
92
+ /**
93
+ * Xache Memory for LangChain.js
94
+ * Drop-in replacement for ConversationBufferMemory with verifiable receipts
95
+ */
96
+
97
+ interface XacheMemoryConfig extends XacheChatMessageHistoryConfig {
98
+ /** Memory key for input (default: 'input') */
99
+ inputKey?: string;
100
+ /** Memory key for output (default: 'output') */
101
+ outputKey?: string;
102
+ /** Key for returning memory (default: 'history') */
103
+ memoryKey?: string;
104
+ /** Return messages as list vs string */
105
+ returnMessages?: boolean;
106
+ }
107
+ /**
108
+ * Drop-in replacement for LangChain memory with Xache storage.
109
+ *
110
+ * Provides persistent, verifiable memory that survives across sessions.
111
+ *
112
+ * @example
113
+ * ```typescript
114
+ * import { XacheMemory } from '@xache/langchain';
115
+ * import { ChatOpenAI } from '@langchain/openai';
116
+ * import { ConversationChain } from 'langchain/chains';
117
+ *
118
+ * const memory = new XacheMemory({
119
+ * walletAddress: '0x...',
120
+ * privateKey: '0x...',
121
+ * });
122
+ *
123
+ * const chain = new ConversationChain({
124
+ * llm: new ChatOpenAI(),
125
+ * memory,
126
+ * });
127
+ *
128
+ * await chain.call({ input: 'Hello!' });
129
+ * ```
130
+ */
131
+ declare class XacheMemory extends BaseMemory {
132
+ lc_namespace: string[];
133
+ private chatHistory;
134
+ private inputKey;
135
+ private outputKey;
136
+ private memoryKey;
137
+ private returnMessages;
138
+ constructor(config: XacheMemoryConfig);
139
+ get memoryKeys(): string[];
140
+ /**
141
+ * Load memory variables
142
+ */
143
+ loadMemoryVariables(_values: InputValues): Promise<MemoryVariables>;
144
+ /**
145
+ * Save context from this conversation to buffer
146
+ */
147
+ saveContext(inputValues: InputValues, outputValues: OutputValues): Promise<void>;
148
+ /**
149
+ * Clear memory contents
150
+ */
151
+ clear(): Promise<void>;
152
+ }
153
+ /**
154
+ * Extended memory with conversation buffer capabilities
155
+ */
156
+ declare class XacheConversationBufferMemory extends XacheMemory {
157
+ lc_namespace: string[];
158
+ }
159
+
160
+ /**
161
+ * Xache Retriever for LangChain.js
162
+ * Memory retrieval for RAG pipelines with verifiable receipts
163
+ */
164
+
165
+ interface XacheRetrieverConfig extends BaseRetrieverInput {
166
+ /** Wallet address for authentication */
167
+ walletAddress: string;
168
+ /** Private key for signing */
169
+ privateKey: string;
170
+ /** Number of documents to retrieve */
171
+ k?: number;
172
+ /** Filter by context */
173
+ context?: string;
174
+ /** API URL (defaults to https://api.xache.xyz) */
175
+ apiUrl?: string;
176
+ /** Chain: 'base' or 'solana' */
177
+ chain?: 'base' | 'solana';
178
+ }
179
+ /**
180
+ * Retriever that fetches documents from Xache memory storage.
181
+ *
182
+ * Use this for RAG pipelines with persistent, verifiable document storage.
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * import { XacheRetriever } from '@xache/langchain';
187
+ * import { ChatOpenAI } from '@langchain/openai';
188
+ * import { RetrievalQAChain } from 'langchain/chains';
189
+ *
190
+ * const retriever = new XacheRetriever({
191
+ * walletAddress: '0x...',
192
+ * privateKey: '0x...',
193
+ * k: 5,
194
+ * });
195
+ *
196
+ * const qa = RetrievalQAChain.fromLLM(new ChatOpenAI(), retriever);
197
+ * const result = await qa.call({ query: 'What do you know about X?' });
198
+ * ```
199
+ */
200
+ declare class XacheRetriever extends BaseRetriever {
201
+ lc_namespace: string[];
202
+ static lc_name(): string;
203
+ private client;
204
+ private k;
205
+ private filterContext?;
206
+ constructor(config: XacheRetrieverConfig);
207
+ _getRelevantDocuments(_query: string, _runManager?: CallbackManagerForRetrieverRun): Promise<Document[]>;
208
+ }
209
+
210
+ /**
211
+ * Xache Memory Extraction for LangChain.js
212
+ * Auto-extract memories from conversations
213
+ */
214
+ interface ExtractedMemory {
215
+ /** Memory content */
216
+ content: string;
217
+ /** Suggested context/category */
218
+ context: string;
219
+ /** Suggested tags */
220
+ tags: string[];
221
+ /** Confidence score */
222
+ confidence: number;
223
+ /** Memory ID if stored */
224
+ memoryId?: string;
225
+ }
226
+ interface ExtractionResult {
227
+ /** Extracted memories */
228
+ memories: ExtractedMemory[];
229
+ /** Number of memories extracted */
230
+ count: number;
231
+ /** Total cost in USD */
232
+ cost: number;
233
+ /** Receipt ID for the operation */
234
+ receiptId?: string;
235
+ }
236
+ interface XacheExtractorConfig {
237
+ /** Wallet address for authentication */
238
+ walletAddress: string;
239
+ /** Private key for signing */
240
+ privateKey: string;
241
+ /** Extraction mode: 'xache-managed' uses Xache's LLM, 'api-key' uses your own */
242
+ mode?: 'xache-managed' | 'api-key';
243
+ /** Your LLM API key (required if mode is 'api-key') */
244
+ llmApiKey?: string;
245
+ /** LLM provider for api-key mode */
246
+ llmProvider?: 'anthropic' | 'openai';
247
+ /** API URL (defaults to https://api.xache.xyz) */
248
+ apiUrl?: string;
249
+ /** Chain: 'base' or 'solana' */
250
+ chain?: 'base' | 'solana';
251
+ /** Request timeout in milliseconds (default: 30000) */
252
+ timeout?: number;
253
+ /** Enable debug logging */
254
+ debug?: boolean;
255
+ }
256
+ /**
257
+ * Extract memories from conversation traces.
258
+ *
259
+ * Can auto-store extracted memories to Xache for later retrieval.
260
+ *
261
+ * @example
262
+ * ```typescript
263
+ * import { XacheExtractor } from '@xache/langchain';
264
+ *
265
+ * const extractor = new XacheExtractor({
266
+ * walletAddress: '0x...',
267
+ * privateKey: '0x...',
268
+ * mode: 'xache-managed',
269
+ * });
270
+ *
271
+ * const result = await extractor.extract(
272
+ * 'User: What is the capital of France?\nAI: Paris is the capital.',
273
+ * { autoStore: true }
274
+ * );
275
+ *
276
+ * console.log(`Extracted ${result.count} memories`);
277
+ * ```
278
+ */
279
+ declare class XacheExtractor {
280
+ private client;
281
+ private mode;
282
+ private llmApiKey?;
283
+ private llmProvider;
284
+ constructor(config: XacheExtractorConfig);
285
+ /**
286
+ * Extract memories from a conversation trace
287
+ */
288
+ extract(trace: string, options?: {
289
+ /** Automatically store extracted memories */
290
+ autoStore?: boolean;
291
+ /** Custom instructions for extraction */
292
+ instructions?: string;
293
+ /** Minimum confidence threshold (0-1) */
294
+ minConfidence?: number;
295
+ }): Promise<ExtractionResult>;
296
+ /**
297
+ * Extract from LangChain messages
298
+ */
299
+ extractFromMessages(messages: Array<{
300
+ role: string;
301
+ content: string;
302
+ }>, options?: {
303
+ autoStore?: boolean;
304
+ instructions?: string;
305
+ minConfidence?: number;
306
+ }): Promise<ExtractionResult>;
307
+ }
308
+
309
+ /**
310
+ * Xache Collective Intelligence for LangChain.js
311
+ * Share and learn from collective knowledge pools
312
+ */
313
+
314
+ interface CollectiveToolConfig {
315
+ /** Wallet address for authentication */
316
+ walletAddress: string;
317
+ /** Private key for signing */
318
+ privateKey: string;
319
+ /** API URL (defaults to https://api.xache.xyz) */
320
+ apiUrl?: string;
321
+ /** Chain: 'base' or 'solana' */
322
+ chain?: 'base' | 'solana';
323
+ }
324
+ /**
325
+ * Create a tool for contributing to collective intelligence.
326
+ *
327
+ * @example
328
+ * ```typescript
329
+ * import { createCollectiveContributeTool } from '@xache/langchain';
330
+ *
331
+ * const contributeTool = createCollectiveContributeTool({
332
+ * walletAddress: '0x...',
333
+ * privateKey: '0x...',
334
+ * });
335
+ *
336
+ * const tools = [contributeTool, ...];
337
+ * ```
338
+ */
339
+ declare function createCollectiveContributeTool(config: CollectiveToolConfig): DynamicStructuredTool;
340
+ /**
341
+ * Create a tool for querying collective intelligence.
342
+ *
343
+ * @example
344
+ * ```typescript
345
+ * import { createCollectiveQueryTool } from '@xache/langchain';
346
+ *
347
+ * const queryTool = createCollectiveQueryTool({
348
+ * walletAddress: '0x...',
349
+ * privateKey: '0x...',
350
+ * });
351
+ *
352
+ * const tools = [queryTool, ...];
353
+ * ```
354
+ */
355
+ declare function createCollectiveQueryTool(config: CollectiveToolConfig): DynamicStructuredTool;
356
+ /**
357
+ * Class-based collective contribute tool (alternative API)
358
+ */
359
+ declare class XacheCollectiveContributeTool {
360
+ private tool;
361
+ constructor(config: CollectiveToolConfig);
362
+ asTool(): DynamicStructuredTool;
363
+ }
364
+ /**
365
+ * Class-based collective query tool (alternative API)
366
+ */
367
+ declare class XacheCollectiveQueryTool {
368
+ private tool;
369
+ constructor(config: CollectiveToolConfig);
370
+ asTool(): DynamicStructuredTool;
371
+ }
372
+
373
+ /**
374
+ * Xache Reputation for LangChain.js
375
+ * Portable, verifiable agent reputation with ERC-8004 support
376
+ */
377
+
378
+ interface ReputationToolConfig {
379
+ /** Wallet address for authentication */
380
+ walletAddress: string;
381
+ /** Private key for signing */
382
+ privateKey: string;
383
+ /** API URL (defaults to https://api.xache.xyz) */
384
+ apiUrl?: string;
385
+ /** Chain: 'base' or 'solana' */
386
+ chain?: 'base' | 'solana';
387
+ }
388
+ interface ReputationResult {
389
+ /** Reputation score (0-1) */
390
+ score: number;
391
+ /** Reputation level */
392
+ level: string;
393
+ /** Total contributions made */
394
+ totalContributions: number;
395
+ /** Total payments made */
396
+ totalPayments: number;
397
+ /** Whether ERC-8004 is enabled */
398
+ erc8004Enabled: boolean;
399
+ /** ERC-8004 agent ID if enabled */
400
+ erc8004AgentId?: string;
401
+ }
402
+ /**
403
+ * Create a tool for checking your own reputation.
404
+ *
405
+ * @example
406
+ * ```typescript
407
+ * import { createReputationTool } from '@xache/langchain';
408
+ *
409
+ * const repTool = createReputationTool({
410
+ * walletAddress: '0x...',
411
+ * privateKey: '0x...',
412
+ * });
413
+ *
414
+ * const tools = [repTool, ...];
415
+ * ```
416
+ */
417
+ declare function createReputationTool(config: ReputationToolConfig): DynamicStructuredTool;
418
+ /**
419
+ * Class-based reputation tool (alternative API)
420
+ */
421
+ declare class XacheReputationTool {
422
+ private tool;
423
+ constructor(config: ReputationToolConfig);
424
+ asTool(): DynamicStructuredTool;
425
+ }
426
+ /**
427
+ * Utility class for checking reputation of any agent.
428
+ *
429
+ * @example
430
+ * ```typescript
431
+ * import { XacheReputationChecker } from '@xache/langchain';
432
+ *
433
+ * const checker = new XacheReputationChecker({
434
+ * walletAddress: '0x...',
435
+ * privateKey: '0x...',
436
+ * });
437
+ *
438
+ * const rep = await checker.check('did:agent:evm:0xOtherAgent...');
439
+ * if (rep.score >= 0.5) {
440
+ * console.log('Agent is trustworthy');
441
+ * }
442
+ * ```
443
+ */
444
+ declare class XacheReputationChecker {
445
+ private client;
446
+ constructor(config: ReputationToolConfig);
447
+ /**
448
+ * Check an agent's reputation
449
+ */
450
+ check(agentDid: string): Promise<ReputationResult>;
451
+ /**
452
+ * Check if an agent meets minimum reputation threshold
453
+ */
454
+ meetsThreshold(agentDid: string, minScore: number): Promise<boolean>;
455
+ }
456
+
457
+ export { type CollectiveToolConfig, type ExtractedMemory, type ExtractionResult, type ReputationResult, type ReputationToolConfig, XacheChatMessageHistory, type XacheChatMessageHistoryConfig, XacheCollectiveContributeTool, XacheCollectiveQueryTool, XacheConversationBufferMemory, XacheExtractor, type XacheExtractorConfig, XacheMemory, type XacheMemoryConfig, XacheReputationChecker, XacheReputationTool, XacheRetriever, type XacheRetrieverConfig, createCollectiveContributeTool, createCollectiveQueryTool, createReputationTool };