이 문서는 Contextual AI의 Grounded Language Model chat models를 시작하는 데 도움을 드립니다. Contextual AI에 대해 자세히 알아보려면 문서를 방문하세요. 이 통합은 contextual-client Python SDK가 필요합니다. 자세한 내용은 여기에서 확인하세요.

개요

이 통합은 Contextual AI의 Grounded Language Model을 호출합니다.

통합 세부 정보

ClassPackageLocalSerializableJS supportDownloadsVersion
ChatContextuallangchain-contextualbetaPyPI - DownloadsPyPI - Version

모델 기능

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

설정

Contextual 모델에 액세스하려면 Contextual AI 계정을 생성하고 API 키를 받은 다음 langchain-contextual 통합 패키지를 설치해야 합니다.

자격 증명

app.contextual.ai로 이동하여 Contextual에 가입하고 API 키를 생성하세요. 완료되면 CONTEXTUAL_AI_API_KEY 환경 변수를 설정하세요:
import getpass
import os

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

설치

LangChain Contextual 통합은 langchain-contextual 패키지에 있습니다:
pip install -qU langchain-contextual

인스턴스화

이제 모델 객체를 인스턴스화하고 chat completion을 생성할 수 있습니다. chat client는 다음과 같은 추가 설정으로 인스턴스화할 수 있습니다:
ParameterTypeDescriptionDefault
temperatureOptional[float]응답의 무작위성에 영향을 주는 샘플링 온도입니다. 높은 temperature 값은 근거성을 감소시킬 수 있습니다.0
top_pOptional[float]nucleus sampling을 위한 파라미터로, temperature의 대안이며 응답의 무작위성에도 영향을 줍니다. 높은 top_p 값은 근거성을 감소시킬 수 있습니다.0.9
max_new_tokensOptional[int]모델이 응답에서 생성할 수 있는 최대 토큰 수입니다. 최소값은 1이고 최대값은 2048입니다.1024
from langchain_contextual import ChatContextual

llm = ChatContextual(
    model="v1",  # defaults to `v1`
    api_key="",
    temperature=0,  # defaults to 0
    top_p=0.9,  # defaults to 0.9
    max_new_tokens=1024,  # defaults to 1024
)

호출

Contextual Grounded Language Model은 ChatContextual.invoke 메서드를 호출할 때 추가 kwargs를 허용합니다. 이러한 추가 입력은 다음과 같습니다:
ParameterTypeDescription
knowledgelist[str]필수: grounded language model이 응답을 생성할 때 사용할 수 있는 지식 소스의 문자열 목록입니다.
system_promptOptional[str]선택 사항: 모델이 응답을 생성할 때 따라야 하는 지침입니다. 모델이 이러한 지침을 정확히 따른다는 보장은 없습니다.
avoid_commentaryOptional[bool]선택 사항 (기본값: False): 모델이 응답에서 추가 논평을 피해야 하는지 여부를 나타내는 플래그입니다. 논평은 대화적 성격을 가지며 검증 가능한 주장을 포함하지 않습니다. 따라서 논평은 사용 가능한 컨텍스트에 엄격하게 근거하지 않습니다. 그러나 논평은 응답의 유용성을 향상시키는 유용한 컨텍스트를 제공할 수 있습니다.
# include a system prompt (optional)
system_prompt = "You are a helpful assistant that uses all of the provided knowledge to answer the user's query to the best of your ability."

# provide your own knowledge from your knowledge-base here in an array of string
knowledge = [
    "There are 2 types of dogs in the world: good dogs and best dogs.",
    "There are 2 types of cats in the world: good cats and best cats.",
]

# create your message
messages = [
    ("human", "What type of cats are there in the world and what are the types?"),
]

# invoke the GLM by providing the knowledge strings, optional system prompt
# if you want to turn off the GLM's commentary, pass True to the `avoid_commentary` argument
ai_msg = llm.invoke(
    messages, knowledge=knowledge, system_prompt=system_prompt, avoid_commentary=True
)

print(ai_msg.content)

체이닝

Contextual Model을 output parser와 체이닝할 수 있습니다.
from langchain_core.output_parsers import StrOutputParser

chain = llm | StrOutputParser

chain.invoke(
    messages, knowledge=knowledge, systemp_prompt=system_prompt, avoid_commentary=True
)

API 참조

모든 ChatContextual 기능 및 구성에 대한 자세한 문서는 Github 페이지를 참조하세요: github.com/ContextualAI//langchain-contextual
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I