MCPcopy Create free account
hub / github.com/TanStack/ai / wrapAdapterForRecording

Function wrapAdapterForRecording

testing/panel/src/routes/api.chat.ts:68–146  ·  view source on GitHub ↗

* 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,
)

Source from the content-addressed store, hash-verified

66 * before they're processed by the stream processor.
67 */
68function 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)

Callers 1

api.chat.tsFile · 0.85

Calls 4

nowMethod · 0.80
logMethod · 0.80
errorMethod · 0.65
pushMethod · 0.45

Tested by

no test coverage detected