阿川私房教材:
學 JavaScript 前端,帶作品集去面試!

63 個專案實戰,寫出作品集,讓面試官眼前一亮!

立即開始免費試讀!

<!--

AutoView - 將您的藍圖轉換為 UI 元件(AI 程式碼產生器)

-->

  1. 前言

自動查看遊樂場

@autoview是一個自動前端建構器,它使用類型資訊產生程式碼。

@autoview是一個程式碼產生器,它根據模式資訊產生 TypeScript 前端元件。此模式資訊可以從 TypeScript 類型或 Swagger/OpenAPI 文件中衍生而來。

前端開發人員可以使用@autoview來顯著提高生產力。只需定義 TypeScript 類型,前端程式碼就會立即產生。然後,您可以完善和增強此程式碼以完成您的應用程式。

對於後端開發人員,只需將您的swagger.json檔案帶到@autoview 。如果你的API包含200個函數,它將自動產生200個前端元件。如果有300個API函數,就會自動產生300個前端元件。

  1. 如何使用

2.1.操場

https://wrtnlabs.io/autoview

造訪我們的主頁直接體驗@autoview

在程式碼編輯器標籤(由StackBlitz提供支援)中,導覽至env.ts檔案並輸入您的 OpenAI 金鑰。在終端機中執行npm run generate以查看@autoview如何從源自 TypeScript 類型和 OpenAPI 文件的範例模式產生 TypeScript 前端程式碼。

您可以用自己的模式替換提供的模式,以產生自訂的 TypeScript 前端程式碼,而無需在本機安裝@autoview 。由於這種遊樂場方法很方便,因此我們推薦使用。

2.2. TypeScript 類型

import { AutoViewAgent } from "@autoview/agent";
import fs from "fs";
import OpenAI from "openai";
import typia, { tags } from "typia";

interface IMember {
  id: string & tags.Format<"uuid">;
  name: string;
  age: number & tags.Minimum<0> & tags.Maximum<100>;
  thumbnail: string & tags.Format<"uri"> & tags.ContentMediaType;
}

const agent: AutoViewAgent = new AutoViewAgent({
  vendor: {
    api: new OpenAI({ apiKey: "********" }),
    model: "o3-mini",
  },
  inputSchema: {
    parameters: typia.llm.parameters<
      IMember, 
      "chatgpt", 
      { reference: true }
    >(),
  },
});
const result: IAutoViewResult = await agent.generate();

await fs.promises.writeFile(
  "./src/transformers/transformMember.ts",
  result.transformTsCode,
  "utf8",
);

若要從 TypeScript 類型產生前端程式碼,請使用typia.llm.parameters<Schema, Model, Config>()函數。

使用typia.llm.parameters<Schema, Model>()指定IMember類型建立一個AutoViewAgent實例,然後呼叫AutoViewAgent.generate()函數。 TypeScript 程式碼將被產生並在IAutoViewResult.transformTsCode屬性中可用。

程式碼產生後,將其儲存到所需位置以供將來使用。這就是@autoview如何使用 AI 從 TypeScript 類型產生 TypeScript 前端程式碼。

import { AutoViewAgent } from "@autoview/agent";
import fs from "fs";
import OpenAI from "openai";
import typia, { tags } from "typia";

interface IMember {
  id: string & tags.Format<"uuid">;
  name: string;
  age: number & tags.Minimum<0> & tags.Maximum<100>;
  thumbnail: string & tags.Format<"uri"> & tags.ContentMediaType;
}

// LLM SCHEMA GENERATION
const $defs: Record<string, IChatGptSchema> = {};
const schema: IChatGptSchema = typia.llm.schema<
  Array<IMember>,
  "chatgpt",
  { reference: true }
>({ $defs });

// CODE GENERATION
const agent: AutoViewAgent = new AutoViewAgent({
  vendor: {
    api: new OpenAI({ apiKey: "********" }),
    model: "o3-mini",
  },
  inputSchema: {
    $defs,
    schema,
  },
  transformFunctionName: "transformMember",
});
const result: IAutoViewResult = await agent.execute();

await fs.promises.writeFile(
  "./src/transformers/transformMember.ts",
  result.transformTsCode,
  "utf8",
);

請注意, typia.llm.parameters<Schema, Model, Config>()函數僅支援沒有動態鍵的靜態物件類型。如果您需要為非物件類型(如Array<IMember>產生前端程式碼,則必須使用typia.llm.schema<Schema, Model, Config>()函數。

使用typia.llm.schema<Schema, Model, Config>()函數產生模式時,預先定義並指派Record<string, IChatGptSchema>類型的$defs變數至關重要。

2.3. Swagger/OpenAPI 文件

import { AutoViewAgent } from "@autoview/agent";
import { OpenApi } from "@samchon/openapi";
import fs from "fs";
import OpenAI from "openai";
import typia, { tags } from "typia";

const app: IHttpLlmApplication<"chatgpt"> = HttpLlm.application({
  model: "chatgpt",
  document,
  options: {
    reference: true,
  },
});
const func: IHttpLlmFunction<"chatgpt"> | undefined = app.functions.find(
  (func) =>
    func.path === "/shoppings/customers/sales/{id}" && 
    func.method === "get",
);
if (func === undefined) throw new Error("Function not found");
else if (func.output === undefined) throw new Error("No return type");

const agent: AutoViewAgent = new AutoViewAgent({
  vendor: {
    api: new OpenAI({ apiKey: "********" }),
    model: "o3-mini",
  },
  inputSchema: {
    $defs: func.parameters.$defs,
    schema: func.output!,
  },
  transformFunctionName: "transformSale",
});
const result: IAutoViewResult = await agent.generate();

await fs.promises.writeFile(
  "./src/transformers/transformSale.ts",
  result.typescript,
  "utf8",
);

如果你有swagger.json文件,你就可以大量生產前端程式碼元件。

使用HttpLlm.application()函數將 Swagger/OpenAPI 文件轉換為 LLM 函數呼叫模式,並將其中一個提供給AutoViewAgent類別。這使您可以為每個 API 函數自動建立前端元件。

此外,您可以將後端伺服器與@agentica (一個專門用於 LLM 函數呼叫的 Agentic AI 框架)整合。透過從@agentica取得參數值並使用@autoview自動返回值檢視器,您可以完全自動化前端應用程式開發:

2.4.前端渲染

//----
// GENERATED CODE
//----
// src/transformSale.ts
import { IAutoViewComponentProps } from "@autoview/interface";

export function transformSale(sale: IShoppingSale): IAutoViewComponentProps;

//----
// RENDERING CODE
//----
// src/SaleView.tsx
import { IAutoViewComponentProps } from "@autoview/interface";
import { renderComponent } from "@autoview/ui";

import { transformSale } from "./transformSale";

export const SaleView = (props: {
  sale: IShoppingSale
}) => {
  const comp: IAutoViewComponentProps = transformSale(sale);
  return <div>
    {renderComponent(comp)}
  </div>;
};
export default SaleView;

//----
// MAIN APPLICATION
//----
// src/main.tsx
import ReactDOM from "react-dom";

import SaleView from "./SaleView";

const sale: IShoppingSale = { ... };
ReactDOM.render(<SaleView sale={sale} />, document.body);

您可以使用@autoview/ui包呈現自動產生的程式碼。

@autoview/ui導入renderComponent()函數並將其渲染為 React 元件,如上圖所示。

  1. 原則

import { FunctionCall } from "pseudo";
import { IValidation } from "typia";

export const correctCompile = <T>(ctx: {
  call: FunctionCall;
  compile: (src: string) => Promise<IValidation<(v: T) => IAutoViewComponentProps>>;
  random: () => T;
  repeat: number;
  retry: (reason: string, errors?: IValidation.IError[]) => Promise<unknown>;
}): Promise<(v: T) => IAutoViewComponentProps>> => {
  // FIND FUNCTION
  if (ctx.call.name !== "render")
    return ctx.retry("Unable to find function. Try it again");

  //----
  // COMPILER FEEDBACK
  //----
  const result: IValidation<(v: T) => IAutoViewComponentProps>> = 
    await ctx.compile(call.arguments.source);
  if (result.success === false)
    return ctx.retry("Correct compilation errors", result.errors);

  //----
  // VALIDATION FEEDBACK
  //----
  for (let i: number = 0; i < ctx.repeat; ++i) {
    const value: T = ctx.random(); // random value generation
    try {
      const props: IAutoViewComponentProps = result.data(value);
      const validation: IValidation<IAutoViewComponentProps> = 
        func.validate(props); //validate AI generated function
      if (validation.success === false)
        return ctx.retry(
          "Type errors are detected. Correct it through validation errors",
          {
            errors: validation.errors,
          },
        );
    } catch (error) {
      //----
      // EXCEPTION FEEDBACK
      //----
      return ctx.retry(
        "Runtime error occurred. Correct by the error message",
        {
          errors: [
            {
              path: "$input",
              name: error.name,
              reason: error.message,
              stack: error.stack,
            }
          ]
        }
      )
    }
  }
  return result.data;
}

@autoview讀取使用者定義的模式(TypeScript 類型或 Swagger/OpenAPI 模式)並指導 AI 根據這些模式編寫 TypeScript 前端程式碼。

然而,AI生成的前端程式碼並不完美。為了指導 AI 編寫正確的前端程式碼, @autoview採用了多種驗證回饋策略:

第一個策略涉及向 AI 代理提供編譯錯誤。人工智慧從編譯器回饋中學習,並在後續嘗試中產生正確的 TypeScript 程式碼。

第二種策略是驗證回饋。 @autoview使用typia.random<T>()函數為給定的模式類型產生隨機值,並測試 AI 產生的 TypeScript 渲染函數是否產生有效的輸出。如果驗證失敗, @autoview將使用詳細的追蹤資訊指導 AI 代理程式糾正該功能。

最後一個策略是異常回饋。即使 AI 產生的 TypeScript 程式碼編譯時沒有錯誤,仍可能會出現執行時期異常。在這種情況下, @autoview會使用異常訊息來指導 AI 代理程式糾正功能。

  1. 路線圖

4.1.截圖回饋

從渲染結果中學習。

@autoview目前版本實作了三種回饋策略:「編譯器」、「驗證」和「異常」。在下一次更新中, @autoview將加入「截圖回饋」。

當 AI 為使用者定義類型建立新的 TypeScript 轉換器函數時, @autoview將請求該類型的範例值,捕獲結果的螢幕截圖,並允許 AI 代理程式查看螢幕截圖。

由於 AI 代理擅長分析和解釋圖像, @autoview的下一個版本將提供更令人興奮的體驗。

4.2.人工回饋

與使用者對話渲染結果。

@autoview的當前版本不是聊天機器人,而是一個僅使用使用者定義類型模式的前端程式碼產生器。

在下一次更新中,它將支援用於聊天機器人開發的AutoViewAgent.conversate()函數。在這個聊天機器人中,使用者可以透過對話引導AI產生前端程式碼。在查看渲染結果時,使用者可以請求AI修改前端程式碼,具體指令如下:

  • 太狹窄了。使其更寬

  • 我想增強頭銜。放大

  • 太多細節。請使其更簡潔。

4.3.主題系統

@autoview支援主題系統,讓您可以用自訂選項取代預設渲染器@autoview/ui

但是,此自訂主題功能尚未記錄。

在下一次更新中,將提供自訂主題的全面文件。

  1. 代理

@agentica是一個專門用於 LLM 函數呼叫的 Agentic AI 框架。

當您向@agentica提供 TypeScript 類別時,其類別函數會在 AI 聊天機器人中正確呼叫。如果您提供Swagger/OpenAPI文件,它就會變成與後端API函數互動的聊天機器人。

透過將@agentica@autoview結合起來,您可以體驗轉變的開發工作流程。用@agentica驅動的 AI 聊天機器人取代參數輸入元件,並使用@autoview自動執行返回值檢視器。這是基於人工智慧的前端自動化最有前景的方法之一:

下面是範例程式碼片段和此程式碼執行的示範影片。這些例子說明了 Agentic AI 未來的潛力。

import { Agentica } from "@agentica/agent";
import { HttpLlm, OpenApi } from "@samchon/openapi";
import typia from "typia";

const agent = new Agentica({
  model: "chatgpt",
  vendor: {
    api: new OpenAI({ apiKey: "*****" }),
    model: "gpt-4o-mini",
  },
  controllers: [
    {
      protocol: "http",
      name: "shopping",
      application: HttpLlm.application({
        model: "chatgpt",
        document: await fetch(
          "https://shopping-be.wrtn.ai/editor/swagger.json",
        ).then((r) => r.json()),
      }),
      connection: {
        host: "https://shopping-be.wrtn.ai",
        headers: {
          Authorization: "Bearer *****",
        },
      },
    },
    {
      protocol: "class",
      name: "counselor",
      application: typia.llm.application<ShoppingCounselor, "chatgpt">(),
      execute: new ShoppingCounselor(),
    },
    {
      protocol: "class",
      name: "policy",
      application: typia.llm.application<ShoppingPolicy, "chatgpt">(),
      execute: new ShoppingPolicy(),
    },
    {
      protocol: "class",
      name: "rag",
      application: typia.llm.application<ShoppingSearchRag, "chatgpt">(),
      execute: new ShoppingSearchRag(),
    },
  ],
});
await agent.conversate("I want to buy a MacBook Pro");

{% youtube RAzYo02HTXA %}


原文出處:https://dev.to/samchon/autoview-turning-your-blueprint-into-ui-components-ai-code-generator-fp


共有 0 則留言


精選技術文章翻譯,幫助開發者持續吸收新知。

阿川私房教材:
學 JavaScript 前端,帶作品集去面試!

63 個專案實戰,寫出作品集,讓面試官眼前一亮!

立即開始免費試讀!