이 가이드는 WRITER chat 시작하기에 대한 간단한 개요를 제공합니다. WRITER는 여러 chat model을 제공합니다. 최신 모델과 비용, context window, 지원되는 입력 타입에 대한 정보는 WRITER 문서에서 확인할 수 있습니다.

개요

Integration 세부사항

ClassPackageLocalSerializableJS supportDownloadsVersion
ChatWriterlangchain-writerPyPI - DownloadsPyPI - Version

Model 기능

Tool callingStructured outputJSON modeImage inputAudio inputVideo inputToken-level streamingNative asyncToken usageLogprobs

인증 정보

WRITER AI Studio에 가입하고 이 Quickstart를 따라 API key를 발급받으세요. 그런 다음 WRITER_API_KEY 환경 변수를 설정하세요:
import getpass
import os

if not os.getenv("WRITER_API_KEY"):
    os.environ["WRITER_API_KEY"] = getpass.getpass("Enter your WRITER API key: ")
model 호출에 대한 자동 추적을 원하시면, 아래 주석을 해제하여 LangSmith API key를 설정할 수 있습니다:
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")

설치

ChatWriterlangchain-writer package에서 사용할 수 있습니다. 다음과 같이 설치하세요:
pip install -qU langchain-writer

인스턴스화

이제 chat completion을 생성하기 위해 model 객체를 인스턴스화할 수 있습니다:
from langchain_writer import ChatWriter

llm = ChatWriter(
    model="palmyra-x5",
    temperature=0,
    max_tokens=None,
    timeout=None,
    max_retries=2,
)

사용법

model을 사용하려면 message 목록을 전달하고 invoke method를 호출하세요:
messages = [
    (
        "system",
        "You are a helpful assistant that translates English to French. Translate the user sentence.",
    ),
    ("human", "I love programming."),
]
ai_msg = llm.invoke(messages)
ai_msg
그런 다음 message의 content에 접근할 수 있습니다:
print(ai_msg.content)

Streaming

응답을 stream으로 받을 수도 있습니다. 먼저 stream을 생성하세요:
messages = [
    (
        "system",
        "You are a helpful assistant that translates English to French. Translate the user sentence.",
    ),
    ("human", "I love programming. Sing a song about it"),
]
ai_stream = llm.stream(messages)
ai_stream
그런 다음 stream을 반복하여 chunk를 가져오세요:
for chunk in ai_stream:
    print(chunk.content, end="")

Tool calling

Palmyra X5와 같은 WRITER model은 tool calling을 지원하며, 이를 통해 tool과 그 인자를 설명할 수 있습니다. model은 호출할 tool과 해당 tool의 입력을 포함한 JSON 객체를 반환합니다.

Tool 바인딩

ChatWriter.bind_tools를 사용하면 Pydantic class, dictionary schema, LangChain tool, 또는 함수를 model의 tool로 쉽게 전달할 수 있습니다. 내부적으로 이들은 다음과 같은 tool schema로 변환됩니다:
{
    "name": "...",
    "description": "...",
    "parameters": {...}  # JSONSchema
}
이들은 모든 model 호출에 전달됩니다. 예를 들어, 특정 위치의 날씨를 가져오는 tool을 사용하려면 Pydantic class를 정의하고 ChatWriter.bind_tools에 전달할 수 있습니다:
from pydantic import BaseModel, Field


class GetWeather(BaseModel):
    """Get the current weather in a given location"""

    location: str = Field(..., description="The city and state, e.g. San Francisco, CA")


llm.bind_tools([GetWeather])
그런 다음 tool과 함께 model을 호출할 수 있습니다:
ai_msg = llm.invoke(
    "what is the weather like in New York City",
)
ai_msg
마지막으로 tool call에 접근하여 함수를 실행할 수 있습니다:
print(ai_msg.tool_calls)

Tool 바인딩에 대한 참고사항

ChatWriter.bind_tools() method는 바인딩된 tool을 가진 새 인스턴스를 생성하지 않고, 받은 toolstool_choice를 초기 class 인스턴스 속성에 저장하여 ChatWriter 호출 시 Palmyra LLM 호출 중에 parameter로 전달합니다. 이 접근 방식은 functiongraph와 같은 다양한 tool 타입을 지원합니다. Graph는 원격으로 호출되는 WRITER Palmyra tool 중 하나입니다. 자세한 내용은 문서를 참조하세요. LangChain에서의 tool 사용에 대한 자세한 내용은 LangChain tool calling 문서를 참조하세요.

Batching

요청을 batch로 처리하고 max_concurrency를 설정할 수도 있습니다:
ai_batch = llm.batch(
    [
        "How to cook pancakes?",
        "How to compose poem?",
        "How to run faster?",
    ],
    config={"max_concurrency": 3},
)
ai_batch
그런 다음 batch를 반복하여 결과를 가져오세요:
for batch in ai_batch:
    print(batch.content)
    print("-" * 100)

비동기 사용

위의 모든 기능(호출, streaming, batching, tool calling)은 비동기 사용도 지원합니다.

Prompt template

Prompt template은 사용자 입력과 parameter를 language model을 위한 instruction으로 변환하는 데 도움을 줍니다. 다음과 같이 ChatWriter를 prompt template과 함께 사용할 수 있습니다:
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate(
    [
        (
            "system",
            "You are a helpful assistant that translates {input_language} to {output_language}.",
        ),
        ("human", "{input}"),
    ]
)

chain = prompt | llm
chain.invoke(
    {
        "input_language": "English",
        "output_language": "German",
        "input": "I love programming.",
    }
)

API reference

모든 ChatWriter 기능과 설정에 대한 자세한 문서는 API reference를 참조하세요.

추가 리소스

WRITER의 model(비용, context window, 지원되는 입력 타입 포함)과 tool에 대한 정보는 WRITER 문서에서 확인할 수 있습니다.
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I