* Wraps an adapter to intercept chatStream and record raw chunks from the adapter * before they're processed by the stream processor.
( adapter: TAdapter, recordingFilePath: string, model: string, provider: string, )
| 66 | * before they're processed by the stream processor. |
| 67 | */ |
| 68 | function wrapAdapterForRecording<TAdapter extends AIAdapter>( |
| 69 | adapter: TAdapter, |
| 70 | recordingFilePath: string, |
| 71 | model: string, |
| 72 | provider: string, |
| 73 | ): TAdapter { |
| 74 | // Type guard to check if adapter has chatStream |
| 75 | if (!('chatStream' in adapter) || typeof adapter.chatStream !== 'function') { |
| 76 | return adapter |
| 77 | } |
| 78 | |
| 79 | const originalChatStream = adapter.chatStream.bind(adapter) |
| 80 | |
| 81 | // Track chunks for recording |
| 82 | const chunks: Array<{ |
| 83 | chunk: StreamChunk |
| 84 | timestamp: number |
| 85 | index: number |
| 86 | }> = [] |
| 87 | let chunkIndex = 0 |
| 88 | |
| 89 | // Create a wrapper that intercepts chatStream |
| 90 | const wrappedAdapter = { |
| 91 | ...adapter, |
| 92 | chatStream: async function* ( |
| 93 | options: Parameters<typeof originalChatStream>[0], |
| 94 | ): AsyncIterable<StreamChunk> { |
| 95 | const startTime = Date.now() |
| 96 | |
| 97 | try { |
| 98 | // Iterate over chunks from the original adapter |
| 99 | for await (const chunk of originalChatStream(options)) { |
| 100 | const timestamp = Date.now() |
| 101 | const index = chunkIndex++ |
| 102 | |
| 103 | // Record the chunk |
| 104 | chunks.push({ |
| 105 | chunk, |
| 106 | timestamp, |
| 107 | index, |
| 108 | }) |
| 109 | |
| 110 | // Yield the chunk to continue normal processing |
| 111 | yield chunk |
| 112 | } |
| 113 | } finally { |
| 114 | // Save recording when stream completes |
| 115 | try { |
| 116 | const recording: ChunkRecording = { |
| 117 | version: '1.0', |
| 118 | timestamp: startTime, |
| 119 | model, |
| 120 | provider, |
| 121 | chunks, |
| 122 | } |
| 123 | |
| 124 | // Ensure directory exists |
| 125 | const dir = path.dirname(recordingFilePath) |
no test coverage detected