내장 Document QnA로 문서와 대화하기

내장 Document QnA로 문서와 대화하기 (Chat with your Documents with built-in Document QnA)

Mistral OCR의 내장 Document QnA 기능을 사용해 PDF, 사진, 스크린샷 같은 문서와 대화하는 방법을 배우는 문서예요. URL에서 문서를 추출해 모델에 전달하는 방식으로 동작해요.

출처: 문서

본문

광학 문자 인식(OCR, Optical Character Recognition)은 텍스트 기반 문서와 이미지를 순수한 텍스트 출력과 마크다운으로 변환해요. 이 기능을 활용하면 어떤 LLM이든 문서를 효율적이고 비용 효과적으로 안정적으로 이해하도록 만들 수 있습니다.

이 가이드에서는 OCR을 모델과 함께 사용해 PDF, 사진, 스크린샷 같은 텍스트 기반 문서에 대해 URL과 내장 기능을 통해 대화하는 방법을 보여드릴게요.

Method

이 방법은 OCR을 활용한 내장 기능을 사용해요. 정규식(regex)으로 URL을 추출하고 이 기능과 함께 모델을 호출할 겁니다.

내장 기능 (Built-In)

Mistral은 모든 모델과 함께 OCR을 활용하는 내장 기능을 제공해요. 문서를 가리키는 URL을 제공하면 모델에 전달될 텍스트 데이터를 추출할 수 있습니다.

아래는 정규식으로 PDF URL을 추출해 document_url로 업로드하는 간단한 예시예요. Document QnA에 대해 더 알고 싶다면 [여기]를 참고하세요.

설정 (Setup)

먼저 mistralai를 설치해요.

!pip install mistralai

이제 클라이언트를 설정해요. API 키는 [AI Studio]에서 만들 수 있어요.

from mistralai.client import Mistral

api_key = "API_KEY"
client = Mistral(api_key=api_key)
text_model = "mistral-small-latest"

시스템 프롬프트와 정규식 (System and Regex)

이 데모에는 도구 호출이 필요 없으므로 간단한 시스템 프롬프트를 정의해요.

system = "You are an AI Assistant with document understanding via URLs. You may be provided with URLs, followed by their corresponding OCR."

URL을 추출하기 위해 사용자 질문에서 URL 패턴을 뽑아내는 정규식을 사용해요. (단순함을 위해 PDF 파일만 있다고 가정할게요.)

import re

def extract_urls(text: str) -> list:
    url_pattern = r'\b((?:https?|ftp)://(?:www\.)?[^\s/$.?#].[^\s]*)\b'
    urls = re.findall(url_pattern, text)
    return urls

# Example
extract_urls("Hi there, you can visit our docs in our website https://docs.mistral.ai/, we cannot wait to see what you will build with us.")

테스트 (Test)

이제 직접 사용해 볼게요. 각 질문에 대해 모든 URL을 추출해 쿼리에 적절히 추가하도록 설정했어요.

예시 프롬프트 (PDF):

import json

messages = [{"role": "system", "content": system}]
while True:
    user_input = input("User > ")
    if user_input.lower() == "quit":
        break

    # Extract URLs from the user input, assuming they are always PDFs
    document_urls = extract_urls(user_input)
    user_message_content = [{"type": "text", "text": user_input}]
    for url in document_urls:
        user_message_content.append({"type": "document_url", "document_url": url})
    messages.append({"role": "user", "content": user_message_content})

    # Send the messages to the model and get a response
    response = client.chat.complete(
        model=text_model,
        messages=messages,
        temperature=0
    )
    messages.append({"role": "assistant", "content": response.choices[0].message.content})

    print("Assistant >", response.choices[0].message.content)

채팅 루프가 돌면서 사용자 입력에서 URL을 추출해 document_url 타입으로 메시지에 추가하고, 모델이 해당 문서의 내용(OCR)을 이해한 뒤 답변을 주는 구조예요.

더 알아보기 (Learn more)