zyratlo commented on code in PR #5260:
URL: https://github.com/apache/texera/pull/5260#discussion_r3468842418


##########
frontend/src/app/workspace/service/notebook-migration/migration-llm.ts:
##########
@@ -0,0 +1,303 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { Injectable } from "@angular/core";
+import { GuiConfigService } from "../../../common/service/gui-config.service";
+import { createOpenAI } from "@ai-sdk/openai";
+import { generateText, type ModelMessage } from "ai";
+import { AppSettings } from "../../../common/app-setting";
+import { v4 as uuidv4 } from "uuid";
+import { WorkflowUtilService } from 
"../workflow-graph/util/workflow-util.service";
+import { OperatorPredicate } from "../../types/workflow-common.interface";
+import {
+  TEXERA_OVERVIEW,
+  TUPLE_DOCUMENTATION,
+  TABLE_DOCUMENTATION,
+  OPERATOR_DOCUMENTATION,
+  UDF_INPUT_PORT_DOCUMENTATION,
+  EXAMPLE_OF_GOOD_CONVERSION,
+  VISUALIZER_DOCUMENTATION,
+  EXAMPLE_OF_MULTIPLE_UDF_CONVERSION,
+  WORKFLOW_PROMPT,
+  MAPPING_PROMPT,
+} from "./migration-prompts";
+
+interface Cell {
+  cell_type: string;
+  metadata: { [key: string]: any };
+  source: string;
+}
+
+export interface Notebook {
+  cells: Cell[];
+}
+
+interface WorkflowJSON {
+  operators: OperatorPredicate[];
+  operatorPositions: Record<string, { x: number; y: number }>;
+  links: any[];
+  commentBoxes: any[];
+  settings: {
+    dataTransferBatchSize: number;
+  };
+}
+
+interface CombinedMapping {
+  operator_to_cell: Record<string, string[]>;
+  cell_to_operator: Record<string, string[]>;
+}
+
+@Injectable()
+export class NotebookMigrationLLM {
+  private model: any;
+  private messages: ModelMessage[] = [];
+  private initialized = false;
+
+  private static readonly DOCUMENTATION: string[] = [
+    TEXERA_OVERVIEW,
+    TUPLE_DOCUMENTATION,
+    TABLE_DOCUMENTATION,
+    OPERATOR_DOCUMENTATION,
+    EXAMPLE_OF_GOOD_CONVERSION,
+    VISUALIZER_DOCUMENTATION,
+    UDF_INPUT_PORT_DOCUMENTATION,
+    EXAMPLE_OF_MULTIPLE_UDF_CONVERSION,
+  ];
+
+  constructor(
+    private config: GuiConfigService,
+    private workflowUtilService: WorkflowUtilService
+  ) {}
+
+  private get enabled(): boolean {
+    return this.config.env.pythonNotebookMigrationEnabled;
+  }
+
+  private assertEnabled(): void {
+    if (!this.enabled) {
+      throw new Error("Notebook migration feature is disabled");
+    }
+  }
+
+  private parseJsonResponse(raw: string, context: string): any {
+    // Trim first, then strip optional markdown code fences (```json ... ``` 
or ``` ... ```)
+    const cleaned = raw
+      .trim()
+      .replace(/^```[a-zA-Z]*\s*/, "")
+      .replace(/\s*```$/, "")
+      .trim();
+    try {
+      return JSON.parse(cleaned);
+    } catch (err) {
+      throw new Error(`Failed to parse LLM ${context} response as JSON: ${(err 
as Error).message}`);
+    }
+  }
+
+  /**
+   * Initialize a new LLM session with Texera documentation
+   */
+  public initialize(modelType: string = "gpt-5-mini", apiKey: string = 
"dummy"): void {
+    this.assertEnabled();
+    this.model = createOpenAI({
+      baseURL: new URL(`${AppSettings.getApiEndpoint()}`, 
document.baseURI).toString(),
+      // apiKey is required by the library for creating the OpenAI compatible 
client;
+      // For security reason, we store the apiKey at the backend, thus the 
value is dummy here.
+      apiKey: apiKey,
+    }).chat(modelType);

Review Comment:
   Refactored in 
[4bb8623](https://github.com/apache/texera/pull/5260/commits/4bb8623e8c129c46869b46d0f4ceaac8bb9073c9)
   
   **Summary of Changes**
   `initialize()` now passes the user's Texera access token as the bearer token:
   - `public initialize(modelType = "gpt-5-mini", accessToken: string = 
AuthService.getAccessToken() ?? "")`
   
   The AI SDK sends it verbatim as `Authorization: Bearer <token>`, which is 
what `JwtAuthFilter` parses; the resource still substitutes the LiteLLM master 
key before forwarding upstream, so the JWT is only used for the Texera-side 
auth check. The token defaults to `AuthService.getAccessToken()` but stays 
overridable, so the spec passes an explicit token rather than depending on 
localStorage.
   
   The misleading "stored at the backend, dummy here" comment is replaced with 
the JWT/master-key explanation.
   
   One cross-PR note: the `apiKey` is threaded modal → 
`notebook-migration.service` → `initialize()`. That wiring will pass the JWT 
(or drop the arg and rely on the default), and the modal's user-entered API-key 
field becomes unnecessary for auth. I'll handle that in the #5273 / #5262 
reviews.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to