백엔드 개발 파이썬 튜토리얼 Llama B를 사용하여 Repos(PR)와 채팅

Llama B를 사용하여 Repos(PR)와 채팅

Sep 07, 2024 pm 02:30 PM

토비에이

소개:

대규모 저장소로 작업할 때 끌어오기 요청(PR), 특히 수천 줄의 코드가 포함된 PR을 따라가는 것은 정말 어려울 수 있습니다. 특정 변경 사항의 영향을 이해하든 대규모 업데이트를 탐색하든 관계없이 PR 검토는 빠르게 부담스러울 수 있습니다. 이 문제를 해결하기 위해 저는 이러한 대규모 PR의 변화를 빠르고 효율적으로 이해할 수 있는 프로젝트를 구축하기 시작했습니다.

Langtrace의 관찰 도구와 결합된 RAG(Retrieval-Augmented Generation)를 사용하여 대규모 PR 검토 프로세스를 단순화하기 위한 도구인 "Chat with Repo(PR)"를 개발했습니다. 또한 Llama 3.1B와 GPT-4o의 성능을 문서화하고 비교했습니다. 이 프로젝트를 통해 이러한 모델이 코드 설명 및 요약을 처리하는 방법과 이 사용 사례에 대한 속도와 정확성의 최상의 균형을 제공하는 모델이 무엇인지 살펴보았습니다. 

이 블로그에 사용된 모든 코드는 여기에서 확인할 수 있습니다

Chat With Repos(PRs) Using Llama B

자세히 알아보기 전에 이 프로젝트에 사용된 주요 도구를 간략히 살펴보겠습니다.
LLM 서비스:

  • OpenAI API
  • 그로크 API
  • Ollama(현지 LLM용)

임베딩 모델:

  • SentenceTransformers(구체적으로 'all-mpnet-base-v2')

벡터 데이터베이스:

  • FAISS(페이스북 AI 유사성 검색)

LLM 관찰 가능성:

  • 엔드 투 엔드 추적 및 측정을 위한 Langtrace

Repo와의 채팅 작동 방식:

Chat with Repo(PR) 시스템은 PR 분석을 위한 간단한 RAG 아키텍처를 구현합니다. GitHub의 API를 통해 PR 데이터를 수집하고 대용량 파일을 청크하여 토큰 제한을 관리하는 것으로 시작됩니다. 이러한 청크는 SentenceTransformers를 사용하여 벡터화되어 코드 의미를 캡처하는 조밀한 임베딩을 생성합니다. FAISS 인덱스를 사용하면 이러한 임베딩에 대한 하위 선형 시간 유사성 검색이 가능합니다. 쿼리는 동일한 임베딩 프로세스를 거치므로 코드 인덱스에 대한 의미론적 일치가 용이해집니다. 검색된 청크는 선택한 LLM(OpenAI, Groq 또는 Ollama를 통해)에 대한 동적 컨텍스트를 형성한 다음 컨텍스트화된 추론을 수행합니다. 이 접근 방식은 벡터 검색의 효율성과 LLM의 생성 능력을 모두 활용하여 다양한 PR 복잡성에 적응하는 미묘한 코드 이해를 허용합니다. 마지막으로 Langtrace 통합은 임베딩 및 LLM 작업에 대한 세부적인 관찰 기능을 제공하여 RAG 파이프라인의 성능 병목 현상 및 잠재적 최적화에 대한 통찰력을 제공합니다. 주요 구성 요소를 자세히 살펴보겠습니다.

청킹 프로세스:

이 시스템의 청킹 프로세스는 대규모 끌어오기 요청을 관리 가능하고 컨텍스트가 풍부한 조각으로 나누도록 설계되었습니다. 이 프로세스의 핵심은 IngestionService 클래스, 특히 Chunks_large_file 및 create_chunks_from_patch 메소드에서 구현됩니다.
PR이 수집되면 각 파일의 패치가 개별적으로 처리됩니다. Chunk_large_file 메소드는 대용량 파일 분할을 담당합니다:

def chunk_large_file(self, file_patch: str, chunk_size: int = config.CHUNK_SIZE) -> List[str]:
    lines = file_patch.split('\n')
    chunks = []
    current_chunk = []
    current_chunk_size = 0

    for line in lines:
        line_size = len(line)
        if current_chunk_size + line_size > chunk_size and current_chunk:
            chunks.append('\n'.join(current_chunk))
            current_chunk = []
            current_chunk_size = 0
        current_chunk.append(line)
        current_chunk_size += line_size

    if current_chunk:
        chunks.append('\n'.join(current_chunk))

    return chunks
로그인 후 복사

이 방법은 구성된 청크 크기에 따라 파일을 분할하여 각 청크가 이 제한을 초과하지 않도록 합니다. 크기 제약 내에서 코드의 논리적 단위를 최대한 함께 유지하려고 하는 줄 기반 접근 방식입니다.
파일이 청크로 분할되면 create_chunks_from_patch 메서드가 각 청크를 처리합니다. 이 방법은 상황에 맞는 정보로 각 청크를 강화합니다.

def create_chunks_from_patch(self, repo_info, pr_info, file_info, repo_explanation, pr_explanation):

    code_blocks = self.chunk_large_file(file_info['patch'])
    chunks = []

    for i, block in enumerate(code_blocks):
        chunk_explanation = self.generate_safe_explanation(f"Explain this part of the code and its changes: {block}")

        chunk = {
            "code": block,
            "explanations": {
                "repository": repo_explanation,
                "pull_request": pr_explanation,
                "file": file_explanation,
                "code": chunk_explanation
            },
            "metadata": {
                "repo": repo_info["name"],
                "pr_number": pr_info["number"],
                "file": file_info["filename"],
                "chunk_number": i + 1,
                "total_chunks": len(code_blocks),
                "timestamp": pr_info["updated_at"]
            }
        }
        chunks.append(chunk)
로그인 후 복사

LLM 서비스를 이용하여 각 코드 블록에 대한 설명을 생성합니다.
저장소 이름, PR 번호, 파일 이름, 청크 번호, 타임스탬프를 포함한 메타데이터를 첨부합니다.
여기에는 저장소 및 풀 요청 설명과 같은 더 광범위한 컨텍스트가 포함됩니다.
이 접근 방식을 사용하면 각 청크가 단순한 코드 조각이 아니라 풍부한 컨텍스트 인식 단위가 됩니다.

Chat With Repos(PRs) Using Llama B
여기에는 다음이 포함됩니다.

  • 실제 코드 변경
  • 변경 사항에 대한 설명
  • 파일 수준 컨텍스트
  • 홍보 수준의 맥락
  • 저장소 수준 컨텍스트

임베딩 및 유사성 검색:

EmbeddingService 클래스는 임베딩 생성 및 유사성 검색을 처리합니다.
1. 임베딩 생성:
각 청크에 대해 SentenceTransformer를 사용하여 임베딩을 생성합니다:

text_to_embed = self.get_full_context(chunk)
embedding = self.model.encode([text_to_embed])[0]
로그인 후 복사

임베딩은 코드 내용, 코드 설명, 파일 설명, PR 설명, 저장소 설명을 결합합니다.
2. 색인 생성:
FAISS를 사용하여 이러한 임베딩을 색인화합니다.

self.index.add(np.array([embedding]))
로그인 후 복사

3. 쿼리 처리:
질문이 있으면 해당 쿼리에 대한 임베딩을 생성하고 유사성 검색을 수행합니다.

query_vector = self.model.encode([query])

D, I = self.index.search(query_vector, k)
로그인 후 복사

4. Chunk Selection:
The system selects the top k chunks (default 3) with the highest similarity scores.
This captures both code structure and semantic meaning, allowing for relevant chunk retrieval even when queries don't exactly match code syntax. FAISS enables efficient similarity computations, making it quick to find relevant chunks in large repositories.

Langtrace Integration:

To ensure comprehensive observability and performance monitoring, we've integrated Langtrace into our "Chat with Repo(PRs)" application. Langtrace provides real-time tracing, evaluations, and metrics for our LLM interactions, vector database operations, and overall application performance.

Model Performance Evaluation: Llama 3.1 70b Open-Source vs. GPT-4o Closed-Source LLMs in Large-Scale Code Review:

To explore how open-source models compare to their closed-source counterparts in handling large PRs, I conducted a comparative analysis between Llama 3.1b (open-source) and GPT-4o (closed-source). The test case involved a significant update to the Langtrace's repository, with over 2,300 additions, nearly 200 deletions, 250 commits, and changes across 47 files. My goal was to quickly understand these specific changes and assess how each model performs in code review tasks.
Methodology:
I posed a set of technical questions related to the pull request (PR), covering:

  • Specific code change explanations
  • Broader architectural impacts
  • Potential performance issues
  • Compatibility concerns

Both models were provided with the same code snippets and contextual information. Their responses were evaluated based on:

  • Technical accuracy
  • Depth of understanding
  • Ability to infer broader system impacts

Key Findings:

Code Understanding:

  • Llama 3.1b performed well in understanding individual code changes, especially with workflow updates and React component changes.
  • GPT-4o had a slight edge in connecting changes to the overall system architecture, such as identifying the ripple effect of modifying API routes on Prisma schema updates.

Knowledge of Frameworks:

  • Both models demonstrated strong understanding of frameworks like React, Next.js, and Prisma.
  • Llama 3.1b's versatility is impressive, particularly in web development knowledge, showing that open-source models are closing the gap on specialized domain expertise.

Architectural Insights:

  • GPT-4o excelled in predicting the broader implications of local changes, such as how adjustments to token-counting methods could affect the entire application.
  • Llama 3.1b, while precise in explaining immediate code impacts, was less adept at extrapolating these changes to system-wide consequences.

Handling Uncertainty:

  • Both models appropriately acknowledged uncertainty when presented with incomplete data, which is crucial for reliable code review.
  • Llama 3.1b's ability to express uncertainty highlights the progress open-source models have made in mimicking sophisticated reasoning.

Technical Detail vs. Broader Context:

  • Llama 3.1b provided highly focused and technically accurate explanations for specific code changes.
  • GPT-4o offered broader system context, though sometimes at the expense of missing finer technical details.

Question Comparison:

Below are examples of questions posed to both models, the expected output, and their respective answers:

Chat With Repos(PRs) Using Llama B

Conclusion:

While GPT-4o remains stronger in broader architectural insights, Llama 3.1b's rapid progress and versatility in code comprehension make it a powerful option for code review. Open-source models are catching up quickly, and as they continue to improve, they could play a significant role in democratizing AI-assisted software development. The ability to tailor and integrate these models into specific development workflows could soon make them indispensable tools for reviewing, debugging, and managing large codebases.

We'd love to hear your thoughts! Join our community on Discord or reach out at support@langtrace.ai to share your experiences, insights, and suggestions. Together, we can continue advancing observability in LLM development and beyond.

Happy tracing!

役立つリソース
Langtrace の概要 https://docs.langtrace.ai/introduction
ラングトレース Twitter(X) https://x.com/langtrace_ai
Langtrace Linkedin https://www.linkedin.com/company/langtrace/about/
ラングトレースウェブサイト https://langtrace.ai/
ラングトレース Discord https://discord.langtrace.ai/
Langtrace Github https://github.com/Scale3-Labs/langtrace

위 내용은 Llama B를 사용하여 Repos(PR)와 채팅의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Python vs. C : 학습 곡선 및 사용 편의성 Python vs. C : 학습 곡선 및 사용 편의성 Apr 19, 2025 am 12:20 AM

Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.

파이썬과 시간 : 공부 시간을 최대한 활용 파이썬과 시간 : 공부 시간을 최대한 활용 Apr 14, 2025 am 12:02 AM

제한된 시간에 Python 학습 효율을 극대화하려면 Python의 DateTime, Time 및 Schedule 모듈을 사용할 수 있습니다. 1. DateTime 모듈은 학습 시간을 기록하고 계획하는 데 사용됩니다. 2. 시간 모듈은 학습과 휴식 시간을 설정하는 데 도움이됩니다. 3. 일정 모듈은 주간 학습 작업을 자동으로 배열합니다.

Python vs. C : 성능과 효율성 탐색 Python vs. C : 성능과 효율성 탐색 Apr 18, 2025 am 12:20 AM

Python은 개발 효율에서 C보다 낫지 만 C는 실행 성능이 높습니다. 1. Python의 간결한 구문 및 풍부한 라이브러리는 개발 효율성을 향상시킵니다. 2.C의 컴파일 유형 특성 및 하드웨어 제어는 실행 성능을 향상시킵니다. 선택할 때는 프로젝트 요구에 따라 개발 속도 및 실행 효율성을 평가해야합니다.

Python vs. C : 주요 차이점 이해 Python vs. C : 주요 차이점 이해 Apr 21, 2025 am 12:18 AM

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.

Python 학습 : 2 시간의 일일 연구가 충분합니까? Python 학습 : 2 시간의 일일 연구가 충분합니까? Apr 18, 2025 am 12:22 AM

하루에 2 시간 동안 파이썬을 배우는 것으로 충분합니까? 목표와 학습 방법에 따라 다릅니다. 1) 명확한 학습 계획을 개발, 2) 적절한 학습 자원 및 방법을 선택하고 3) 실습 연습 및 검토 및 통합 연습 및 검토 및 통합,이 기간 동안 Python의 기본 지식과 고급 기능을 점차적으로 마스터 할 수 있습니다.

Python Standard Library의 일부는 무엇입니까? 목록 또는 배열은 무엇입니까? Python Standard Library의 일부는 무엇입니까? 목록 또는 배열은 무엇입니까? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.

파이썬 : 자동화, 스크립팅 및 작업 관리 파이썬 : 자동화, 스크립팅 및 작업 관리 Apr 16, 2025 am 12:14 AM

파이썬은 자동화, 스크립팅 및 작업 관리가 탁월합니다. 1) 자동화 : 파일 백업은 OS 및 Shutil과 같은 표준 라이브러리를 통해 실현됩니다. 2) 스크립트 쓰기 : PSUTIL 라이브러리를 사용하여 시스템 리소스를 모니터링합니다. 3) 작업 관리 : 일정 라이브러리를 사용하여 작업을 예약하십시오. Python의 사용 편의성과 풍부한 라이브러리 지원으로 인해 이러한 영역에서 선호하는 도구가됩니다.

웹 개발을위한 파이썬 : 주요 응용 프로그램 웹 개발을위한 파이썬 : 주요 응용 프로그램 Apr 18, 2025 am 12:20 AM

웹 개발에서 Python의 주요 응용 프로그램에는 Django 및 Flask 프레임 워크 사용, API 개발, 데이터 분석 및 시각화, 머신 러닝 및 AI 및 성능 최적화가 포함됩니다. 1. Django 및 Flask 프레임 워크 : Django는 복잡한 응용 분야의 빠른 개발에 적합하며 플라스크는 소형 또는 고도로 맞춤형 프로젝트에 적합합니다. 2. API 개발 : Flask 또는 DjangorestFramework를 사용하여 RESTFULAPI를 구축하십시오. 3. 데이터 분석 및 시각화 : Python을 사용하여 데이터를 처리하고 웹 인터페이스를 통해 표시합니다. 4. 머신 러닝 및 AI : 파이썬은 지능형 웹 애플리케이션을 구축하는 데 사용됩니다. 5. 성능 최적화 : 비동기 프로그래밍, 캐싱 및 코드를 통해 최적화

See all articles