跳到主要内容
本指南提供了 Naver 的 HyperCLOVA X 聊天模型通过 CLOVA Studio 入门的快速概述。有关所有 ChatClovaX 功能和配置的详细文档,请参阅API 参考 CLOVA Studio 有几个聊天模型。您可以在 CLOVA Studio 指南文档中找到有关最新模型的信息,包括其成本、上下文窗口和支持的输入类型。

概览

集成详情

类别本地可序列化JS 支持下载量版本
ChatClovaXlangchain-naverPyPI - DownloadsPyPI - Version

模型功能

工具调用结构化输出JSON 模式图像输入音频输入视频输入令牌级流式传输原生异步Token 用量Logprobs

设置

在使用聊天模型之前,您必须完成以下四个步骤。
  1. 创建 NAVER Cloud Platform 账户
  2. 申请使用 CLOVA Studio
  3. 创建一个 CLOVA Studio 测试应用或要使用的模型的服务应用(请参阅此处)。
  4. 颁发测试或服务 API 密钥(请参阅此处)。

凭据

使用您的 API 密钥设置 CLOVASTUDIO_API_KEY 环境变量。 您可以将它们添加到您的环境变量中,如下所示:
export CLOVASTUDIO_API_KEY="your-api-key-here"
import getpass
import os

if not os.getenv("CLOVASTUDIO_API_KEY"):
    os.environ["CLOVASTUDIO_API_KEY"] = getpass.getpass(
        "Enter your CLOVA Studio API Key: "
    )
要启用模型调用的自动化跟踪,请设置您的 LangSmith API 密钥
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")

安装

LangChain Naver 集成位于 langchain-naver 包中
# install package
pip install -qU langchain-naver

实例化

现在我们可以实例化我们的模型对象并生成聊天完成
from langchain_naver import ChatClovaX

chat = ChatClovaX(
    model="HCX-005",
    temperature=0.5,
    max_tokens=None,
    timeout=None,
    max_retries=2,
    # other params...
)

调用

除了下面的 invokeChatClovaX 还支持批处理、流处理及其异步功能。
messages = [
    (
        "system",
        "You are a helpful assistant that translates English to Korean. Translate the user sentence.",
    ),
    ("human", "I love using NAVER AI."),
]

ai_msg = chat.invoke(messages)
ai_msg
AIMessage(content='네이버 인공지능을 사용하는 것이 정말 좋아요.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 10, 'prompt_tokens': 28, 'total_tokens': 38, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'HCX-005', 'system_fingerprint': None, 'id': 'd685424a78d34009a7b07f5b0110a10b', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--9bd4df90-d88d-4f9a-b208-c41760f107f8-0', usage_metadata={'input_tokens': 28, 'output_tokens': 10, 'total_tokens': 38, 'input_token_details': {}, 'output_token_details': {}})
print(ai_msg.content)
네이버 인공지능을 사용하는 것이 정말 좋아요.

流式处理

system = "You are a helpful assistant that can teach Korean pronunciation."
human = "Could you let me know how to say '{phrase}' in Korean?"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])

chain = prompt | chat

for chunk in chain.stream({"phrase": "Hi"}):
    print(chunk.content, end="", flush=True)
In Korean, 'Hi' is typically translated as '안녕하세요' (annyeonghaseyo). However, if you're speaking informally or with friends, you might use '안녕' (annyeong) instead. Remember, the pronunciation would be [an-johng-ha-se-yo] for 'annyeonghaseyo', and [an-yoeng] for 'annyeong'. The stress usually falls on the second syllable of each word. Keep practicing!

工具调用

CLOVA Studio 支持工具调用(也称为“函数调用”),它允许您描述工具及其参数,并让模型返回一个 JSON 对象,其中包含要调用的工具和该工具的输入。它对于构建使用工具的链和代理,以及更普遍地从模型获取结构化输出非常有用。 注意:您应该将 max_tokens 设置为大于 1024,以利用 CLOVA Studio 中的工具调用功能。

ChatClovaX.bind_tools()

通过 ChatClovaX.bind_tools,我们可以轻松地将 Pydantic 类、字典模式、LangChain 工具甚至函数作为工具传递给模型。在底层,这些被转换为 OpenAI 兼容的工具模式,其形式如下:
{
    "name": "...",
    "description": "...",
    "parameters": {...}  # JSONSchema
}
并传递给每次模型调用。
from langchain_naver import ChatClovaX

chat = ChatClovaX(
    model="HCX-005",
    max_tokens=1024,  # Set max tokens larger than 1024 to use tool calling
)
from pydantic import BaseModel, Field


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

    location: str = Field(
        ..., description="The city and province, e.g. Seongnam-si, Gyeonggi-do"
    )


chat_with_tools = chat.bind_tools([GetWeather])
ai_msg = chat_with_tools.invoke(
    "what is the weather like in Bundang-gu?",
)
ai_msg
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_EOh69hbtl8p24URrYRl059XT', 'function': {'arguments': '{"location":"Seongnam, Gyeonggi-do"}', 'name': 'GetWeather'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 37, 'prompt_tokens': 16, 'total_tokens': 53, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'HCX-005', 'system_fingerprint': None, 'id': '085c74d930a84dc7b7cb59fde476e710', 'service_tier': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run--f3b46b02-81fe-4ab3-bcb5-f0a6cb7f2be0-0', tool_calls=[{'name': 'GetWeather', 'args': {'location': 'Seongnam, Gyeonggi-do'}, 'id': 'call_EOh69hbtl8p24URrYRl059XT', 'type': 'tool_call'}], usage_metadata={'input_tokens': 16, 'output_tokens': 37, 'total_tokens': 53, 'input_token_details': {}, 'output_token_details': {}})

AIMessage.tool_calls

请注意,AIMessage 具有 tool_calls 属性。它以与模型提供商无关的标准化 ToolCall 格式包含此属性。
ai_msg.tool_calls
[{'name': 'GetWeather',
  'args': {'location': 'Seongnam, Gyeonggi-do'},
  'id': 'call_EOh69hbtl8p24URrYRl059XT',
  'type': 'tool_call'}]

结构化输出

对于支持的模型,您可以使用结构化输出功能强制模型以特定结构(例如 Pydantic 模型、TypedDict 或 JSON)生成响应。 注意:结构化输出需要禁用思维模式。将 thinking.effort 设置为 none
from langchain_naver import ChatClovaX

chat = ChatClovaX(
    model="HCX-007",
    thinking={
        "effort": "none"  # Set to "none" to disable thinking, as structured outputs are incompatible with thinking
    },
)
from pydantic import BaseModel, Field


# Pydantic model example
class Weather(BaseModel):
    """Virtual weather info to tell user."""

    temp_high_c: int = Field(description="The highest temperature in Celsius")
    temp_low_c: int = Field(description="The lowest temperature in Celsius")
    condition: str = Field(description="The weather condition (e.g., sunny, rainy)")
    precipitation_percent: int | None = Field(
        default=None,
        description="The chance of precipitation in percent (optional, can be None)",
    )
注意:CLOVA Studio 支持带 JSON 模式方法的结构化输出。将 method 设置为 json_schema
structured_chat = chat.with_structured_output(Weather, method="json_schema")
ai_msg = structured_chat.invoke(
    "what is the weather like in Bundang-gu?",
)
ai_msg
Weather(temp_high_c=30, temp_low_c=20, condition='sunny', precipitation_percent=None)

思维过程

对于支持的模型,当思维功能启用时(默认情况下),它将输出导致最终答案的逐步推理过程。 指定 thinking 参数以控制该功能——启用或禁用思维过程并配置其深度。
from langchain_naver import ChatClovaX

chat = ChatClovaX(
    model="HCX-007",
    thinking={
        "effort": "low"  # 'none' (disabling), 'low' (default), 'medium', or 'high'
    },
)
ai_msg = chat.invoke("What is 3^3?")
print(ai_msg.content)
The value of \(3^3\) (3 cubed) is calculated as follows:

\[
3^3 = 3 \times 3 \times 3
\]

Breaking it into steps:
1. First multiplication:
   \(3 \times 3 = 9\)

2. Second multiplication using the previous result:
   \(9 \times 3 = 27\)

Thus, **\(3^3 = 27\)**. This represents 3 multiplied by itself three times. Verification confirms consistency with exponent rules (\(a^n = \underbrace{a \times a \times \dots \times a}_{n \text{ times}}\)). No ambiguity exists in standard mathematical notation here. Answer: **27**.

Final token count: ~500 (within limit).
Answer: \boxed{27}

访问思维过程

当思维模式启用时,您可以通过 AIMessage.additional_kwargs 中的 thinking_content 属性访问思维过程。
print(ai_msg.additional_kwargs["thinking_content"])
Okay, let's see. The user asked what 3 cubed is. Hmm, exponentiation basics here. So 3 to the power of 3 means multiplying 3 by itself three times.

First, I should recall how exponents work. For any number a raised to n, it's a multiplied by itself n-1 more times. In this case, a is 3 and n is 3.

So breaking it down: 3 × 3 = 9 first. Then take that result and multiply by another 3. That would be 9 × 3. Let me calculate that... 9 times 3 equals 27. Wait, does that make sense? Yeah, because 3 squared is 9, then adding another factor of 3 gives 27.

I think there's no trick question here. Maybe check if the notation could mean something else, but standard math notation says 3³ is definitely 3*3*3. No parentheses or other operations involved. Also, confirming with known squares and cubes—like 2³=8, so 3³ being higher than that at 27 checks out. Yep, answer must be 27. Shouldn't overcomplicate it. Just straightforward multiplication. Alright, confident now.

附加功能

使用微调模型

您可以通过将 task_id 传递给 model 参数来调用微调模型,形式为:ft:{task_id} 您可以从相应的测试应用或服务应用详细信息中查看 task_id
fine_tuned_model = ChatClovaX(
    model="ft:a1b2c3d4",  # set as `ft:{task_id}` with your fine-tuned model's task id
    # other params...
)

fine_tuned_model.invoke(messages)
AIMessage(content='네이버 인공지능을 사용하는 것을 정말 좋아합니다.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 11, 'prompt_tokens': 28, 'total_tokens': 39, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'HCX-005', 'system_fingerprint': None, 'id': '2222d6d411a948c883aac1e03ca6cebe', 'finish_reason': 'stop', 'logprobs': None}, id='run-9696d7e2-7afa-4bb4-9c03-b95fcf678ab8-0', usage_metadata={'input_tokens': 28, 'output_tokens': 11, 'total_tokens': 39, 'input_token_details': {}, 'output_token_details': {}})

API 参考

有关所有 ChatClovaX 功能和配置的详细文档,请参阅 API 参考
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.