MistralChatGenerator — Mistral 채팅 생성

MistralChatGenerator — Mistral 채팅 생성

이 컴포넌트는 Mistral의 텍스트 생성 모델을 이용해 채팅 완성(chat completion)을 만들 수 있게 해 줘요. Haystack 파이프라인에서 Mistral 모델과 대화를 주고받는 한 조각이라고 보시면 돼요.

출처: 공식 문서 — MistralChatGenerator

개요 (Overview)

이 통합은 생성 엔드포인트(generative endpoint)를 통해 제공되는 Mistral의 모델을 지원해요. 사용 가능한 모델의 전체 목록은 Mistral 문서에서 확인할 수 있어요.

MistralChatGenerator는 동작하려면 Mistral API 키가 필요해요. 키는 다음 두 가지 방법으로 설정할 수 있어요.

  • Secret API를 이용한 api_key 초기화 파라미터
  • MISTRAL_API_KEY 환경 변수 (권장)

현재 사용 가능한 모델은 다음과 같아요.

  • mistral-small-latest (기본값)
  • mistral-medium-latest
  • mistral-large-latest
  • codestral-latest

이 컴포넌트는 ChatMessage 객체의 리스트를 받아서 동작해요. ChatMessage는 메시지와 역할(누가 만들었는지 — user, assistant, system, tool 등), 선택적 메타데이터를 담는 데이터 클래스예요.

컴포넌트를 실행할 때 generation_kwargs로 넘길 수 있는 Mistral API 지원 파라미터에 대한 자세한 내용은 Mistral API 문서를 참고하세요.

도구 지원 (Tool Support)

MistralChatGeneratortools 파라미터를 통해 함수 호출(function calling)을 지원해요. 이 파라미터는 유연한 도구 구성을 받아들여요.

  • Tool 객체 리스트: 개별 도구를 리스트로 전달
  • 단일 Toolset: Toolset 하나를 통째로 전달
  • Tool과 Toolset 혼합: 여러 Toolset과 단독 도구를 한 리스트에 섞어서 전달

이렇게 하면 관련된 도구들을 논리적인 그룹으로 묶으면서, 필요할 때 단독 도구도 같이 포함할 수 있어요.

from haystack.tools import Tool, Toolset
from haystack_integrations.components.generators.mistral import MistralChatGenerator

# Create individual tools
weather_tool = Tool(
    name="weather", description="Get weather info", parameters=..., function=...
)
news_tool = Tool(
    name="news", description="Get latest news", parameters=..., function=...
)

# Group related tools into a toolset
math_toolset = Toolset([add_tool, subtract_tool, multiply_tool])

# Pass mixed tools and toolsets to the generator
generator = MistralChatGenerator(
    tools=[math_toolset, weather_tool, news_tool]  # Mix of Toolset and Tool objects
)

도구를 다루는 더 자세한 내용은 ToolToolset 문서를 참고하세요.

스트리밍 (Streaming)

이 Generator는 LLM의 토큰을 출력에 바로 스트리밍하는 스트리밍을 지원해요. streaming_callback 초기화 파라미터에 함수를 넘기면 됩니다.

사용법 (Usage)

MistralChatGenerator를 쓰려면 mistral-haystack 패키지를 설치해야 해요.

pip install mistral-haystack

단독 사용 (On its own)

from haystack_integrations.components.generators.mistral import MistralChatGenerator
from haystack.components.generators.utils import print_streaming_chunk
from haystack.dataclasses import ChatMessage
from haystack.utils import Secret

generator = MistralChatGenerator(
    api_key=Secret.from_env_var("MISTRAL_API_KEY"),
    streaming_callback=print_streaming_chunk,
)
message = ChatMessage.from_user("What's Natural Language Processing? Be brief.")
print(generator.run([message]))

멀티모달 입력으로 사용:

from haystack.dataclasses import ChatMessage, ImageContent
from haystack_integrations.components.generators.mistral import MistralChatGenerator

llm = MistralChatGenerator(model="pixtral-12b-2409")

image = ImageContent.from_file_path("apple.jpg")
user_message = ChatMessage.from_user(
    content_parts=["What does the image show? Max 5 words.", image],
)

response = llm.run([user_message])["replies"][0].text
print(response)

# Red apple on straw.

파이프라인에서 사용 (In a Pipeline)

아래는 URL 콘텐츠를 바탕으로 질문에 답하는 RAG 파이프라인 예시예요. URL의 콘텐츠를 ChatPromptBuildermessages에 넣고, MistralChatGenerator로 답변을 생성해요.

from haystack import Document
from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.utils import print_streaming_chunk
from haystack.components.fetchers import LinkContentFetcher
from haystack.components.converters import HTMLToDocument
from haystack.dataclasses import ChatMessage

from haystack_integrations.components.generators.mistral import MistralChatGenerator

fetcher = LinkContentFetcher()
converter = HTMLToDocument()
prompt_builder = ChatPromptBuilder(variables=["documents"])
llm = MistralChatGenerator(
    streaming_callback=print_streaming_chunk,
    model="mistral-small",
)

message_template = """Answer the following question based on the contents of the article: {{query}}\n
               Article: {{documents[0].content}} \n
           """
messages = [ChatMessage.from_user(message_template)]

rag_pipeline = Pipeline()
rag_pipeline.add_component(name="fetcher", instance=fetcher)
rag_pipeline.add_component(name="converter", instance=converter)
rag_pipeline.add_component("prompt_builder", prompt_builder)
rag_pipeline.add_component("llm", llm)

rag_pipeline.connect("fetcher.streams", "converter.sources")
rag_pipeline.connect("converter.documents", "prompt_builder.documents")
rag_pipeline.connect("prompt_builder.prompt", "llm.messages")

question = "What are the capabilities of Mixtral?"

result = rag_pipeline.run(
    {
        "fetcher": {"urls": ["https://mistral.ai/news/mixtral-of-experts"]},
        "prompt_builder": {
            "template_variables": {"query": question},
            "template": messages,
        },
        "llm": {"generation_kwargs": {"max_tokens": 165}},
    },
)

더 알아보기 (Learn more)