RegexTextExtractor
RegexTextExtractor
정규 표현식 패턴을 사용해 채팅 메시지나 문자열에서 텍스트를 추출하는 컴포넌트예요.
출처: 문서
본문
| 항목 | 내용 |
|---|---|
| 파이프라인에서 가장 흔한 위치 | Chat Generator 다음에서 LLM 응답의 구조화된 출력을 파싱할 때 |
| 필수 init 변수 | regex_pattern: 텍스트 추출에 사용하는 정규 표현식 패턴 |
| 필수 run 변수 | text_or_messages: 검색할 문자열 또는 ChatMessage 객체 목록 |
| 출력 변수 | captured_text: 첫 번째 캡처 그룹에서 추출한 텍스트 |
| API reference | Extractors |
| GitHub 링크 | regex_text_extractor.py |
| 패키지 이름 | haystack-ai |
개요
RegexTextExtractor는 정규 표현식 패턴으로 텍스트 입력이나 ChatMessage 객체를 파싱해 캡처 그룹이 포착한 텍스트를 추출해요. XML 형태의 태그나 다른 패턴처럼 특정 형식을 따르는 LLM 출력에서 구조화된 정보를 추출할 때 유용하죠.
이 컴포넌트는 일반 문자열과 ChatMessage 객체 목록 모두에서 동작해요. 메시지 목록이 주어지면 마지막 메시지만 처리해요.
정규 표현식 패턴은 추출할 텍스트를 지정하도록 캡처 그룹(괄호 안의 텍스트)을 최소 하나 포함해야 해요. 캡처 그룹이 없으면 전체 매치가 대신 반환돼요.
매치가 없을 때 처리
패턴이 매치되지 않으면 컴포넌트는 captured_text를 빈 문자열로 반환해요:
from haystack.components.extractors import RegexTextExtractor
extractor = RegexTextExtractor(regex_pattern=r"<answer>(.*?)</answer>")
result = extractor.run(text_or_messages="No answer tags here")
print(result) # >> {'captured_text': ''}
사용법
단독으로 사용하기
이 예제는 XML 형태의 태그 구조에서 URL을 추출해요:
from haystack.components.extractors import RegexTextExtractor
# Create extractor with a pattern that captures the URL value
extractor = RegexTextExtractor(regex_pattern='<issue url="(.+?)">')
# Extract from a string
result = extractor.run(
text_or_messages='<issue url="github.com/example/issue/123">Issue description</issue>',
)
print(result)
# >> {'captured_text': 'github.com/example/issue/123'}
ChatMessages와 함께 사용하기
채팅 파이프라인에서 LLM 출력을 다룰 때 ChatMessage 객체에서 구조화된 데이터를 추출할 수 있어요:
from haystack.components.extractors import RegexTextExtractor
from haystack.dataclasses import ChatMessage
extractor = RegexTextExtractor(regex_pattern=r"```json\s*(.*?)\s*```")
# Simulating an LLM response with JSON in a code block
messages = [
ChatMessage.from_user("Extract the data"),
ChatMessage.from_assistant(
'Here is the data:\n```json\n{"name": "Alice", "age": 30}\n```',
),
]
result = extractor.run(text_or_messages=messages)
print(result)
# >> {'captured_text': '{"name": "Alice", "age": 30}'}
파이프라인에서 사용하기
이 예제는 구조화된 LLM 응답에서 특정 섹션을 추출하는 방법을 보여줘요. 파이프라인이 LLM에게 주제를 분석하고 각 섹션에 XML 형태의 태그로 응답을 서식 지정하도록 요청해요. 그러면 RegexTextExtractor가 요약 부분만 뽑아내고 나머지 응답은 버리죠.
LLM은 <analysis>와 <summary> 섹션을 모두 담은 전체 응답을 생성하지만, <summary> 태그 안의 콘텐츠만 추출되어 반환돼요.
from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.components.extractors import RegexTextExtractor
from haystack.dataclasses import ChatMessage
pipe = Pipeline()
pipe.add_component("prompt_builder", ChatPromptBuilder())
pipe.add_component("llm", OpenAIChatGenerator())
pipe.add_component(
"extractor",
RegexTextExtractor(regex_pattern=r"<summary>(.*?)</summary>"),
)
pipe.connect("prompt_builder.prompt", "llm.messages")
pipe.connect("llm.replies", "extractor.text_or_messages")
# Instruct the LLM to use a specific structured format
messages = [
ChatMessage.from_system(
"Respond using this exact format:\n"
"<analysis>Your detailed analysis here</analysis>\n"
"<summary>A one-sentence summary</summary>",
),
ChatMessage.from_user("What are the main benefits and drawbacks of remote work?"),
]
# Run the pipeline (requires OPENAI_API_KEY environment variable)
result = pipe.run({"prompt_builder": {"template": messages}})
print(result["extractor"]["captured_text"])
# >> 'Remote work offers flexibility and eliminates commuting but can lead to isolation and blurred work-life boundaries.'