>  기사  >  웹 프론트엔드  >  검색 및(LLM) 변환

검색 및(LLM) 변환

DDD
DDD원래의
2024-09-19 06:22:32888검색

Search And (LLM) Transform

이 글에서는 텍스트 편집기의 "검색 및 바꾸기" 기능이 진화한 모습을 보여줍니다.
여기서 "교체" 단계는 LLM 변환으로 대체되었습니다.
예제에서는 GenAISCript를 사용하고 있습니다.

쉽게 수행할 수 없는 텍스트 변환을 일괄 적용하는 데 유용할 수 있습니다
정규식.

예를 들어
에 문자열 명령을 사용하는 기능을 추가했을 때 exec 명령을 사용하려면 인수 배열을 사용하는 모든 호출을 다음과 같은 새로운 구문으로 변환해야 했습니다.

host.exec("cmd", ["arg0", "arg1", "arg2"])


host.exec(`cmd arg0 arg1 arg2`)`

이 함수 호출을 정규 표현식과 일치시키는 것이 가능합니다

host\.exec\s*\([^,]+,\s*\[[^\]]+\]\s*\)

대체 문자열을 공식화하는 것은 쉽지 않습니다... 자연어로 설명할 수 없으면

Convert the call to a single string command shell in TypeScript

다음은 LLM이 변수를 올바르게 처리한 변환의 몇 가지 예입니다.

  • 함수 호출의 인수를 단일 문자열로 연결합니다.
- const { stdout } = await host.exec("git", ["diff"])
+ const { stdout } = await host.exec(`git diff`)
  • 인수를 연결하고 ${} 구문을 사용하여 변수를 보간합니다.
- const { stdout: commits } = await host.exec("git", [
-     "log",
-     "--author",
-     author,
-     "--until",
-     until,
-     "--format=oneline",
- ])
+ const { stdout: commits } = 
+   await host.exec(`git log --author ${author} --until ${until} --format=oneline`)

찾다

검색 단계는 작업 공간.grep을 사용하여 수행됩니다
파일에서 패턴을 효율적으로 검색할 수 있는 기능입니다(동일한 검색 엔진입니다
Visual Studio Code 검색을 지원합니다.

const { pattern, glob } = env.vars
const patternRx = new RegExp(pattern, "g")
const { files } = await workspace.grep(patternRx, glob)

컴퓨팅 변환

두 번째 단계는 정규식을 파일 콘텐츠에 적용하는 것입니다
인라인 프롬프트를 사용하여 각 일치 항목의 LLM 변환을 미리 계산합니다.

const { transform } = env.vars
...
const patches = {} // map of match -> transformed
for (const file of files) {
    const { content } = await workspace.readText(file.filename)
    for (const match of content.matchAll(patternRx)) {
        const res = await runPrompt(
            (ctx) => {
                ctx.$`
            ## Task

            Your task is to transform the MATCH with the following TRANSFORM.
            Return the transformed text.
            - do NOT add enclosing quotes.

            ## Context
            `
                ctx.def("MATCHED", match[0])
                ctx.def("TRANSFORM", transform)
            },
            { label: match[0], system: [], cache: "search-and-transform" }
        )
        ...

LLM에서는 때때로 답변을 따옴표로 묶기로 결정하므로 이를 제거해야 합니다.

    ...
    const transformed = res.fences?.[0].content ?? res.text
    patches[match[0]] = transformed

변환

마지막으로 미리 계산된 변환을 사용하여 최종 정규식 대체를 적용합니다.
변환된 문자열로 이전 파일 내용을 패치합니다.

    const newContent = content.replace(
        patternRx,
        (match) => patches[match] ?? match
    )
    await workspace.writeText(file.filename, newContent)
}

매개변수

스크립트는 세 가지 매개변수, 즉 파일 글로브, 검색할 패턴, 적용할 LLM 변환을 사용합니다.
스크립트 메타데이터에서 이러한 매개변수를 선언하고 env.vars 객체에서 추출합니다.

script({ ...,
    parameters: {
        glob: {
            type: "string",
            description: "The glob pattern to filter files",
            default: "*",
        },
        pattern: {
            type: "string",
            description: "The text pattern (regular expression) to search for",
        },
        transform: {
            type: "string",
            description: "The LLM transformation to apply to the match",
        },
    },
})
const { pattern, glob, transform } = env.vars

달리기

이 스크립트를 실행하려면 --vars 옵션을 사용하여 패턴과 변환을 전달할 수 있습니다.

genaiscript run st --vars 'pattern=host\.exec\s*\([^,]+,\s*\[[^\]]+\]\s*\)' 'transform=Convert the call to a single string command shell in TypeScript'

위 내용은 검색 및(LLM) 변환의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:첫 번째 기여다음 기사:첫 번째 기여