@traceai/cohere 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.
Files changed (58) hide show
  1. package/README.md +436 -0
  2. package/dist/esm/index.d.ts +3 -0
  3. package/dist/esm/index.d.ts.map +1 -0
  4. package/dist/esm/index.js +3 -0
  5. package/dist/esm/index.js.map +1 -0
  6. package/dist/esm/instrumentation.d.ts +34 -0
  7. package/dist/esm/instrumentation.d.ts.map +1 -0
  8. package/dist/esm/instrumentation.js +370 -0
  9. package/dist/esm/instrumentation.js.map +1 -0
  10. package/dist/esm/package.json +1 -0
  11. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -0
  12. package/dist/esm/typeUtils.d.ts +6 -0
  13. package/dist/esm/typeUtils.d.ts.map +1 -0
  14. package/dist/esm/typeUtils.js +10 -0
  15. package/dist/esm/typeUtils.js.map +1 -0
  16. package/dist/esm/version.d.ts +2 -0
  17. package/dist/esm/version.d.ts.map +1 -0
  18. package/dist/esm/version.js +2 -0
  19. package/dist/esm/version.js.map +1 -0
  20. package/dist/esnext/index.d.ts +3 -0
  21. package/dist/esnext/index.d.ts.map +1 -0
  22. package/dist/esnext/index.js +3 -0
  23. package/dist/esnext/index.js.map +1 -0
  24. package/dist/esnext/instrumentation.d.ts +34 -0
  25. package/dist/esnext/instrumentation.d.ts.map +1 -0
  26. package/dist/esnext/instrumentation.js +359 -0
  27. package/dist/esnext/instrumentation.js.map +1 -0
  28. package/dist/esnext/tsconfig.esnext.tsbuildinfo +1 -0
  29. package/dist/esnext/typeUtils.d.ts +6 -0
  30. package/dist/esnext/typeUtils.d.ts.map +1 -0
  31. package/dist/esnext/typeUtils.js +10 -0
  32. package/dist/esnext/typeUtils.js.map +1 -0
  33. package/dist/esnext/version.d.ts +2 -0
  34. package/dist/esnext/version.d.ts.map +1 -0
  35. package/dist/esnext/version.js +2 -0
  36. package/dist/esnext/version.js.map +1 -0
  37. package/dist/src/__tests__/instrumentation.test.d.ts +2 -0
  38. package/dist/src/__tests__/instrumentation.test.d.ts.map +1 -0
  39. package/dist/src/__tests__/instrumentation.test.js +259 -0
  40. package/dist/src/__tests__/instrumentation.test.js.map +1 -0
  41. package/dist/src/index.d.ts +3 -0
  42. package/dist/src/index.d.ts.map +1 -0
  43. package/dist/src/index.js +19 -0
  44. package/dist/src/index.js.map +1 -0
  45. package/dist/src/instrumentation.d.ts +34 -0
  46. package/dist/src/instrumentation.d.ts.map +1 -0
  47. package/dist/src/instrumentation.js +364 -0
  48. package/dist/src/instrumentation.js.map +1 -0
  49. package/dist/src/typeUtils.d.ts +6 -0
  50. package/dist/src/typeUtils.d.ts.map +1 -0
  51. package/dist/src/typeUtils.js +14 -0
  52. package/dist/src/typeUtils.js.map +1 -0
  53. package/dist/src/version.d.ts +2 -0
  54. package/dist/src/version.d.ts.map +1 -0
  55. package/dist/src/version.js +5 -0
  56. package/dist/src/version.js.map +1 -0
  57. package/dist/tsconfig.tsbuildinfo +1 -0
  58. package/package.json +75 -0
package/README.md ADDED
@@ -0,0 +1,436 @@
1
+ # @traceai/cohere
2
+
3
+ OpenTelemetry instrumentation for the [Cohere](https://cohere.com/) TypeScript/JavaScript SDK.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @traceai/cohere
9
+ # or
10
+ pnpm add @traceai/cohere
11
+ # or
12
+ yarn add @traceai/cohere
13
+ ```
14
+
15
+ ## Features
16
+
17
+ - Automatic instrumentation of Cohere API calls
18
+ - Supports chat, embed, and rerank APIs
19
+ - Captures request parameters, model information, and responses
20
+ - Configurable input/output hiding for privacy
21
+ - Compatible with OpenTelemetry ecosystem
22
+
23
+ ## Usage
24
+
25
+ ### Basic Setup
26
+
27
+ ```typescript
28
+ import { CohereInstrumentation } from "@traceai/cohere";
29
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
30
+ import { registerInstrumentations } from "@opentelemetry/instrumentation";
31
+
32
+ // Set up the tracer provider
33
+ const provider = new NodeTracerProvider();
34
+ provider.register();
35
+
36
+ // Register the Cohere instrumentation
37
+ registerInstrumentations({
38
+ instrumentations: [new CohereInstrumentation()],
39
+ });
40
+
41
+ // Now use the Cohere SDK as normal
42
+ import { CohereClient } from "cohere-ai";
43
+
44
+ const cohere = new CohereClient({
45
+ token: process.env.COHERE_API_KEY,
46
+ });
47
+
48
+ // Chat example
49
+ const chatResponse = await cohere.chat({
50
+ message: "Hello, how are you?",
51
+ model: "command-r-08-2024",
52
+ });
53
+
54
+ // Embed example
55
+ const embedResponse = await cohere.embed({
56
+ texts: ["hello", "goodbye"],
57
+ model: "embed-english-v3.0",
58
+ inputType: "search_document",
59
+ });
60
+
61
+ // Rerank example
62
+ const rerankResponse = await cohere.rerank({
63
+ query: "What is the capital of France?",
64
+ documents: [
65
+ "Paris is the capital of France.",
66
+ "Berlin is the capital of Germany.",
67
+ "London is the capital of the United Kingdom.",
68
+ ],
69
+ model: "rerank-english-v3.0",
70
+ });
71
+ ```
72
+
73
+ ### Manual Instrumentation
74
+
75
+ If automatic instrumentation doesn't work (e.g., with bundlers), you can manually instrument:
76
+
77
+ ```typescript
78
+ import { CohereInstrumentation } from "@traceai/cohere";
79
+ import * as CohereModule from "cohere-ai";
80
+
81
+ const instrumentation = new CohereInstrumentation();
82
+ instrumentation.manuallyInstrument(CohereModule);
83
+ ```
84
+
85
+ ### Configuration Options
86
+
87
+ ```typescript
88
+ const instrumentation = new CohereInstrumentation({
89
+ // OpenTelemetry instrumentation config
90
+ instrumentationConfig: {
91
+ enabled: true,
92
+ },
93
+ // TraceAI-specific config
94
+ traceConfig: {
95
+ hideInputs: false, // Set to true to hide input content in traces
96
+ hideOutputs: false, // Set to true to hide output content in traces
97
+ },
98
+ });
99
+ ```
100
+
101
+ ### With TraceAI Core
102
+
103
+ ```typescript
104
+ import { register, ProjectType } from "@traceai/fi-core";
105
+ import { CohereInstrumentation } from "@traceai/cohere";
106
+ import { registerInstrumentations } from "@opentelemetry/instrumentation";
107
+
108
+ // 1. Register TraceAI Core TracerProvider
109
+ const tracerProvider = register({
110
+ projectName: "my-cohere-app",
111
+ projectType: ProjectType.OBSERVE,
112
+ sessionName: "cohere-session-" + Date.now(),
113
+ });
114
+
115
+ // 2. Register instrumentation BEFORE importing Cohere SDK
116
+ registerInstrumentations({
117
+ tracerProvider: tracerProvider,
118
+ instrumentations: [new CohereInstrumentation()],
119
+ });
120
+
121
+ // 3. NOW import and use Cohere
122
+ const { CohereClient } = await import("cohere-ai");
123
+ const client = new CohereClient({ token: process.env.COHERE_API_KEY });
124
+
125
+ // 4. Use normally - all calls are traced
126
+ const response = await client.chat({
127
+ message: "Hello!",
128
+ model: "command-r-08-2024",
129
+ });
130
+
131
+ // 5. Shutdown when done
132
+ await tracerProvider.shutdown();
133
+ ```
134
+
135
+ ## Real-World Use Cases
136
+
137
+ ### 1. Conversational AI with Chat History
138
+
139
+ ```typescript
140
+ const { CohereClient } = await import("cohere-ai");
141
+ const client = new CohereClient({ token: process.env.COHERE_API_KEY });
142
+
143
+ async function chat(message: string, history: Array<{ role: string; message: string }>) {
144
+ const response = await client.chat({
145
+ message,
146
+ model: "command-r-08-2024",
147
+ chatHistory: history,
148
+ preamble: "You are a helpful customer support agent for an e-commerce platform.",
149
+ });
150
+
151
+ // Add to history
152
+ history.push({ role: "USER", message });
153
+ history.push({ role: "CHATBOT", message: response.text });
154
+
155
+ return response.text;
156
+ }
157
+
158
+ // Usage
159
+ const history: Array<{ role: string; message: string }> = [];
160
+ const answer1 = await chat("I have a problem with my order", history);
161
+ const answer2 = await chat("Order ID is 12345", history);
162
+ ```
163
+
164
+ ### 2. Semantic Search with Embeddings
165
+
166
+ ```typescript
167
+ async function semanticSearch(query: string, documents: string[]) {
168
+ // Get query embedding (use 'search_query' for queries)
169
+ const queryEmbedding = await client.embed({
170
+ texts: [query],
171
+ model: "embed-english-v3.0",
172
+ inputType: "search_query",
173
+ });
174
+
175
+ // Get document embeddings (use 'search_document' for documents)
176
+ const docEmbeddings = await client.embed({
177
+ texts: documents,
178
+ model: "embed-english-v3.0",
179
+ inputType: "search_document",
180
+ });
181
+
182
+ // Calculate cosine similarities
183
+ const queryVector = queryEmbedding.embeddings[0] as number[];
184
+ const similarities = (docEmbeddings.embeddings as number[][]).map((docVector, i) => ({
185
+ document: documents[i],
186
+ score: cosineSimilarity(queryVector, docVector),
187
+ }));
188
+
189
+ return similarities.sort((a, b) => b.score - a.score);
190
+ }
191
+ ```
192
+
193
+ ### 3. Document Reranking for RAG
194
+
195
+ ```typescript
196
+ async function rerankDocuments(query: string, documents: string[]) {
197
+ const response = await client.rerank({
198
+ query,
199
+ documents,
200
+ model: "rerank-english-v3.0",
201
+ topN: 5,
202
+ returnDocuments: true,
203
+ });
204
+
205
+ return response.results.map((result) => ({
206
+ document: result.document?.text,
207
+ score: result.relevanceScore,
208
+ originalIndex: result.index,
209
+ }));
210
+ }
211
+
212
+ // Usage in RAG pipeline
213
+ const retrievedDocs = await vectorSearch(userQuery, 20); // Get top 20 from vector DB
214
+ const rerankedDocs = await rerankDocuments(userQuery, retrievedDocs);
215
+ const topDocs = rerankedDocs.slice(0, 3); // Use top 3 for context
216
+ ```
217
+
218
+ ### 4. Tool-Augmented Chatbot
219
+
220
+ ```typescript
221
+ async function chatWithTools(message: string) {
222
+ const response = await client.chat({
223
+ message,
224
+ model: "command-r-08-2024",
225
+ tools: [
226
+ {
227
+ name: "search_database",
228
+ description: "Search the product database",
229
+ parameterDefinitions: {
230
+ query: { type: "str", description: "Search query", required: true },
231
+ category: { type: "str", description: "Product category", required: false },
232
+ },
233
+ },
234
+ {
235
+ name: "get_order_status",
236
+ description: "Get status of a customer order",
237
+ parameterDefinitions: {
238
+ orderId: { type: "str", description: "Order ID", required: true },
239
+ },
240
+ },
241
+ ],
242
+ });
243
+
244
+ if (response.toolCalls && response.toolCalls.length > 0) {
245
+ // Execute tool calls and continue conversation
246
+ for (const toolCall of response.toolCalls) {
247
+ console.log(`Tool: ${toolCall.name}, Args:`, toolCall.parameters);
248
+ }
249
+ }
250
+
251
+ return response;
252
+ }
253
+ ```
254
+
255
+ ### 5. Multilingual Embeddings
256
+
257
+ ```typescript
258
+ async function multilingualSearch(query: string, documents: string[]) {
259
+ // Use multilingual model for cross-language search
260
+ const queryEmbedding = await client.embed({
261
+ texts: [query],
262
+ model: "embed-multilingual-v3.0",
263
+ inputType: "search_query",
264
+ });
265
+
266
+ const docEmbeddings = await client.embed({
267
+ texts: documents,
268
+ model: "embed-multilingual-v3.0",
269
+ inputType: "search_document",
270
+ });
271
+
272
+ // Works across languages!
273
+ // Query in English can match documents in French, German, Spanish, etc.
274
+ return calculateSimilarities(queryEmbedding, docEmbeddings);
275
+ }
276
+ ```
277
+
278
+ ### 6. Streaming Chat Responses
279
+
280
+ ```typescript
281
+ async function streamChat(message: string) {
282
+ const stream = await client.chatStream({
283
+ message,
284
+ model: "command-r-08-2024",
285
+ });
286
+
287
+ let fullText = "";
288
+ for await (const event of stream) {
289
+ if (event.eventType === "text-generation") {
290
+ process.stdout.write(event.text);
291
+ fullText += event.text;
292
+ } else if (event.eventType === "stream-end") {
293
+ console.log("\n--- Stream complete ---");
294
+ console.log("Token usage:", event.response?.meta?.tokens);
295
+ }
296
+ }
297
+
298
+ return fullText;
299
+ }
300
+ ```
301
+
302
+ ## Traced Operations
303
+
304
+ ### Chat API
305
+
306
+ The instrumentation captures:
307
+
308
+ - Model name
309
+ - Input messages and chat history
310
+ - Preamble and connectors
311
+ - Temperature and other generation parameters
312
+ - Response text and metadata
313
+ - Token usage (prompt and completion tokens)
314
+
315
+ ### Embed API
316
+
317
+ The instrumentation captures:
318
+
319
+ - Model name
320
+ - Input texts
321
+ - Input type
322
+ - Truncation settings
323
+ - Output embeddings (unless hidden)
324
+ - Token usage
325
+
326
+ ### Rerank API
327
+
328
+ The instrumentation captures:
329
+
330
+ - Model name
331
+ - Query text
332
+ - Documents to rerank
333
+ - Top N parameter
334
+ - Reranked results with relevance scores
335
+
336
+ ## Semantic Conventions
337
+
338
+ This instrumentation follows OpenTelemetry semantic conventions and FutureAGI conventions for LLM observability:
339
+
340
+ - Span names follow the pattern: `cohere.{operation}` (e.g., `cohere.chat`, `cohere.embed`, `cohere.rerank`)
341
+ - Uses `LLM` span kind for chat operations
342
+ - Uses `EMBEDDING` span kind for embed operations
343
+ - Uses `RERANKER` span kind for rerank operations
344
+
345
+ ## Supported Models
346
+
347
+ ### Chat Models
348
+
349
+ - command
350
+ - command-r
351
+ - command-r-08-2024
352
+ - command-light
353
+ - command-nightly
354
+
355
+ ### Embedding Models
356
+
357
+ - embed-english-v3.0
358
+ - embed-multilingual-v3.0
359
+ - embed-english-light-v3.0
360
+ - embed-multilingual-light-v3.0
361
+
362
+ ### Rerank Models
363
+
364
+ - rerank-english-v3.0
365
+ - rerank-multilingual-v3.0
366
+ - rerank-english-v2.0
367
+ - rerank-multilingual-v2.0
368
+
369
+ ## Requirements
370
+
371
+ - Node.js >= 18
372
+ - cohere-ai SDK
373
+
374
+ ## Running Examples
375
+
376
+ The `examples/` directory contains real-world examples:
377
+
378
+ ```bash
379
+ cd examples
380
+ cp .env.example .env
381
+ # Edit .env with your API keys
382
+
383
+ pnpm install
384
+ pnpm run example
385
+ ```
386
+
387
+ ## E2E Testing
388
+
389
+ Run E2E tests with real API keys:
390
+
391
+ ```bash
392
+ COHERE_API_KEY=your_key pnpm test -- --testPathPattern=e2e
393
+ ```
394
+
395
+ ## Integration with TraceAI Platform
396
+
397
+ ```typescript
398
+ import { CohereInstrumentation } from "@traceai/cohere";
399
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
400
+ import { SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
401
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
402
+ import { Resource } from "@opentelemetry/resources";
403
+
404
+ const provider = new NodeTracerProvider({
405
+ resource: new Resource({
406
+ "service.name": "my-cohere-app",
407
+ "deployment.environment": "production",
408
+ }),
409
+ });
410
+
411
+ const exporter = new OTLPTraceExporter({
412
+ url: "https://api.traceai.com/v1/traces",
413
+ headers: {
414
+ Authorization: `Bearer ${process.env.TRACEAI_API_KEY}`,
415
+ },
416
+ });
417
+
418
+ provider.addSpanProcessor(new SimpleSpanProcessor(exporter));
419
+ provider.register();
420
+
421
+ const instrumentation = new CohereInstrumentation();
422
+ instrumentation.manuallyInstrument(require("cohere-ai"));
423
+ ```
424
+
425
+ ## License
426
+
427
+ Apache-2.0
428
+
429
+ ## Related Packages
430
+
431
+ - [@traceai/openai](../traceai_openai) - OpenAI instrumentation
432
+ - [@traceai/anthropic](../traceai_anthropic) - Anthropic instrumentation
433
+ - [@traceai/groq](../traceai_groq) - Groq instrumentation
434
+ - [@traceai/mistral](../traceai_mistral) - Mistral instrumentation
435
+ - [@traceai/google-genai](../traceai_google_genai) - Google GenAI instrumentation
436
+ - [@traceai/fi-core](../fi-core) - Core tracing utilities
@@ -0,0 +1,3 @@
1
+ export * from './instrumentation.js';
2
+ export * from './version.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from './instrumentation.js';
2
+ export * from './version.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC"}
@@ -0,0 +1,34 @@
1
+ import { InstrumentationBase, InstrumentationConfig, InstrumentationNodeModuleDefinition } from "@opentelemetry/instrumentation";
2
+ import { TraceConfigOptions } from "@traceai/fi-core";
3
+ /**
4
+ * Function to check if instrumentation is enabled / disabled
5
+ */
6
+ export declare function isPatched(): boolean;
7
+ /**
8
+ * @param instrumentationConfig The config for the instrumentation
9
+ * @param traceConfig The FI trace configuration for masking sensitive information
10
+ */
11
+ export declare class CohereInstrumentation extends InstrumentationBase {
12
+ private fiTracer;
13
+ private _traceConfig?;
14
+ readonly instrumentationName = "@traceai/cohere";
15
+ constructor({ instrumentationConfig, traceConfig, }?: {
16
+ instrumentationConfig?: InstrumentationConfig;
17
+ traceConfig?: TraceConfigOptions;
18
+ });
19
+ enable(): void;
20
+ protected init(): InstrumentationNodeModuleDefinition;
21
+ /**
22
+ * Manually instruments the Cohere module
23
+ */
24
+ manuallyInstrument(module: Record<string, unknown>): void;
25
+ /**
26
+ * Patches the Cohere module
27
+ */
28
+ private patch;
29
+ /**
30
+ * Un-patches the Cohere module
31
+ */
32
+ private unpatch;
33
+ }
34
+ //# sourceMappingURL=instrumentation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instrumentation.d.ts","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,mCAAmC,EAEpC,MAAM,gCAAgC,CAAC;AAmBxC,OAAO,EAGL,kBAAkB,EACnB,MAAM,kBAAkB,CAAC;AAU1B;;GAEG;AACH,wBAAgB,SAAS,YAExB;AAyGD;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,mBAAmB;IAC5D,OAAO,CAAC,QAAQ,CAAY;IAC5B,OAAO,CAAC,YAAY,CAAC,CAAqB;IAC1C,SAAgB,mBAAmB,qBAAqB;gBAE5C,EACV,qBAAqB,EACrB,WAAW,GACZ,GAAE;QACD,qBAAqB,CAAC,EAAE,qBAAqB,CAAC;QAC9C,WAAW,CAAC,EAAE,kBAAkB,CAAC;KAC7B;IASU,MAAM,IAAI,IAAI;IAK9B,SAAS,CAAC,IAAI;IAUd;;OAEG;IACH,kBAAkB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAIlD;;OAEG;IACH,OAAO,CAAC,KAAK;IAoPb;;OAEG;IACH,OAAO,CAAC,OAAO;CA2BhB"}