File size: 4,582 Bytes
c6c8587
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/**
 * Prompt Service Client
 * Handles communication with the Python prompt service for real model generation
 */

export interface PromptComparisonRequest {
  type: 'prompt_comparison';
  prompt_a: string;
  prompt_b: string;
}

export interface SinglePromptRequest {
  type: 'single_prompt';
  prompt: string;
  prompt_id?: string;
  max_tokens?: number;
  temperature?: number;
}

export interface AttentionTrace {
  type: 'attention';
  layer: string;
  weights: number[][];
  max_weight: number;
  entropy?: number;
  prompt_id: string;
  comparison_group?: 'prompt_a' | 'prompt_b';
  timestamp: number;
}

export interface ComparisonSummary {
  type: 'prompt_comparison';
  prompt_a: {
    id: string;
    text: string;
    generated: string;
    num_traces: number;
  };
  prompt_b: {
    id: string;
    text: string;
    generated: string;
    num_traces: number;
  };
  timestamp: number;
}

export class PromptServiceClient {
  private ws: WebSocket | null = null;
  private readonly url: string;
  private messageHandlers: Map<string, (data: Record<string, unknown>) => void> = new Map();
  private connectionPromise: Promise<void> | null = null;

  constructor(url: string = 'ws://localhost:8767') {
    this.url = url;
  }

  /**
   * Connect to the prompt service
   */
  async connect(): Promise<void> {
    if (this.ws?.readyState === WebSocket.OPEN) {
      return;
    }

    if (this.connectionPromise) {
      return this.connectionPromise;
    }

    this.connectionPromise = new Promise((resolve, reject) => {
      const timeout = setTimeout(() => {
        if (this.ws?.readyState !== WebSocket.OPEN) {
          console.log('⏱️ Connection timeout - using demo mode');
          this.ws?.close();
          reject(new Error('Connection timeout'));
        }
      }, 3000); // 3 second timeout

      try {
        this.ws = new WebSocket(this.url);

        this.ws.onopen = () => {
          clearTimeout(timeout);
          console.log('✅ Connected to prompt service');
          resolve();
        };

        this.ws.onerror = (error) => {
          clearTimeout(timeout);
          console.log('⚠️ Prompt service not available - will use demo mode');
          reject(new Error('Prompt service not available'));
        };

        this.ws.onclose = () => {
          console.log('🔌 Disconnected from prompt service');
          this.ws = null;
          this.connectionPromise = null;
        };

        this.ws.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data);
            this.handleMessage(data);
          } catch (error) {
            console.error('Error parsing message:', error);
          }
        };
      } catch (error) {
        reject(error);
      }
    });

    return this.connectionPromise;
  }

  /**
   * Handle incoming messages from the prompt service
   */
  private handleMessage(data: Record<string, unknown>) {
    // Notify all registered handlers
    this.messageHandlers.forEach((handler) => {
      handler(data);
    });
  }

  /**
   * Register a message handler
   */
  onMessage(id: string, handler: (data: Record<string, unknown>) => void) {
    this.messageHandlers.set(id, handler);
  }

  /**
   * Unregister a message handler
   */
  offMessage(id: string) {
    this.messageHandlers.delete(id);
  }

  /**
   * Request prompt comparison from the service
   */
  async comparePrompts(promptA: string, promptB: string): Promise<void> {
    await this.connect();

    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      throw new Error('Not connected to prompt service');
    }

    const request: PromptComparisonRequest = {
      type: 'prompt_comparison',
      prompt_a: promptA,
      prompt_b: promptB
    };

    this.ws.send(JSON.stringify(request));
  }

  /**
   * Generate for a single prompt
   */
  async generateSingle(
    prompt: string,
    options?: {
      prompt_id?: string;
      max_tokens?: number;
      temperature?: number;
    }
  ): Promise<void> {
    await this.connect();

    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      throw new Error('Not connected to prompt service');
    }

    const request: SinglePromptRequest = {
      type: 'single_prompt',
      prompt,
      ...options
    };

    this.ws.send(JSON.stringify(request));
  }

  /**
   * Disconnect from the service
   */
  disconnect() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
  }

  /**
   * Check if connected
   */
  isConnected(): boolean {
    return this.ws?.readyState === WebSocket.OPEN;
  }
}