from langchain_openai import ChatOpenAIllm = ChatOpenAI( model="gpt-5-nano", # stream_usage=True, # temperature=None, # max_tokens=None, # timeout=None, # reasoning_effort="low", # max_retries=2, # api_key="...", # if you prefer to pass api key in directly instaed of using env vars # base_url="...", # organization="...", # other params...)
사용 가능한 모델 매개변수의 전체 목록은 ChatOpenAI API Reference를 참조하세요.
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
OpenAI의 Chat Completions API는 기본적으로 토큰 사용 통계를 스트리밍하지 않습니다
(API 참조 여기 참조).
ChatOpenAI 또는 AzureChatOpenAI로 스트리밍할 때 토큰 수를 복구하려면
초기화 매개변수로 stream_usage=True를 설정하거나 호출 시 설정하세요:
Copy
from langchain_openai import ChatOpenAIllm = ChatOpenAI(model="gpt-4.1-mini", stream_usage=True)
OpenAI는 도구와 그 인수를 설명하고 모델이 호출할 도구와 해당 도구에 대한 입력이 포함된 JSON 객체를 반환하도록 하는 tool calling API를 제공합니다(여기서는 “tool calling”과 “function calling”을 같은 의미로 사용합니다). 도구 호출은 도구 사용 체인과 에이전트를 구축하고 모델에서 구조화된 출력을 얻는 데 매우 유용합니다.
from pydantic import BaseModel, Fieldclass GetWeather(BaseModel): """Get the current weather in a given location""" location: str = Field(..., description="The city and state, e.g. San Francisco, CA")llm_with_tools = llm.bind_tools([GetWeather])
Copy
ai_msg = llm_with_tools.invoke( "what is the weather like in San Francisco",)ai_msg
.with_structured_output 메서드를 사용하면 모델이 스키마에 맞는 출력을 반환하도록 할 수 있습니다. 스키마는 Pydantic 클래스 또는 JSON 스키마로 지정할 수 있습니다:
Copy
from langchain_openai import ChatOpenAIfrom pydantic import BaseModel, Fieldclass Joke(BaseModel): """Joke to tell user.""" setup: str = Field(description="The setup of the joke") punchline: str = Field(description="The punchline to the joke")# Pass `strict=True` to enable Structured Outputs for supported models.llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0)structured_llm = llm.with_structured_output(Joke, strict=True)structured_llm.invoke("Tell me a joke about cats")
Copy
Joke(setup='Why was the cat sitting on the computer?', punchline='To keep an eye on the mouse!')
OpenAI의 Responses API는 GPT-4o, GPT-4.1, GPT-5 시리즈 모델과 함께 사용할 수 있는 베타 API입니다. Responses API는 대화 상태를 관리하고, computer-use 및 code interpreter와 같은 고급 도구를 지원하며, reasoning을 활성화합니다.ChatOpenAI는 use_responses_api가 설정되거나 reasoning 또는 include 같은 Responses-only 매개변수가 지정된 경우 자동으로 Responses API를 사용합니다.
Copy
from langchain_openai import ChatOpenAIllm = ChatOpenAI( model="gpt-4.1-mini", use_responses_api=True, )
OpenAI는 샌드박스화된 코드 생성 및 실행을 지원하는 code interpreter 도구를 구현합니다.예제 사용:
Copy
from langchain_openai import ChatOpenAIllm = ChatOpenAI( model="gpt-4.1-mini", include=["code_interpreter_call.outputs"], # optionally include outputs)llm_with_tools = llm.bind_tools( [ { "type": "code_interpreter", # Create a new container "container": {"type": "auto"}, } ])response = llm_with_tools.invoke( "Write and run code to answer the question: what is 3^3?")
위 명령은 새 컨테이너를 생성했습니다. 기존 컨테이너 ID를 지정할 수도 있습니다:
Copy
code_interpreter_calls = [ item for item in response.content if item["type"] == "code_interpreter_call"]assert len(code_interpreter_calls) == 1container_id = code_interpreter_calls[0]["extras"]["container_id"] llm_with_tools = llm.bind_tools( [ { "type": "code_interpreter", # Use an existing container "container": container_id, } ])
일부 OpenAI 모델은 추론 프로세스를 설명하는 별도의 텍스트 콘텐츠를 생성합니다. 자세한 내용은 OpenAI의 reasoning documentation을 참조하세요.OpenAI는 모델의 추론 요약을 반환할 수 있습니다(원시 추론 토큰은 노출하지 않음). 이 요약을 반환하도록 ChatOpenAI를 구성하려면 reasoning 매개변수를 지정하세요. 이 매개변수가 설정되면 ChatOpenAI는 자동으로 Responses API로 라우팅됩니다.
Copy
from langchain_openai import ChatOpenAIreasoning = { "effort": "medium", # 'low', 'medium', or 'high' "summary": "auto", # 'detailed', 'auto', or None}llm = ChatOpenAI(model="gpt-5-nano", reasoning=reasoning)response = llm.invoke("What is 3^3?")# Outputresponse.text
Copy
'3³ = 3 × 3 × 3 = 27.'
Copy
# Reasoningfor block in response.content_blocks: if block["type"] == "reasoning": print(block["reasoning"])
Copy
**Calculating the power of three**The user is asking about 3 raised to the power of 3. That's a pretty simple calculation! I know that 3^3 equals 27, so I can say, "3 to the power of 3 equals 27." I might also include a quick explanation that it's 3 multiplied by itself three times: 3 × 3 × 3 = 27. So, the answer is definitely 27.
OpenAI에는 멀티모달 입력을 지원하는 모델이 있습니다. 이러한 모델에 이미지, PDF 또는 오디오를 전달할 수 있습니다. LangChain에서 이를 수행하는 방법에 대한 자세한 내용은 multimodal inputs 문서를 참조하세요.다양한 모달리티를 지원하는 모델 목록은 OpenAI’s documentation에서 확인할 수 있습니다.모든 모달리티에 대해 LangChain은 크로스 프로바이더 표준과 OpenAI의 네이티브 콘텐츠 블록 형식을 모두 지원합니다.멀티모달 데이터를 ChatOpenAI에 전달하려면 데이터를 포함하는 콘텐츠 블록을 생성하고 아래와 같이 메시지에 통합하세요:
Copy
message = { "role": "user", "content": [ { "type": "text", # Update prompt as desired "text": "Describe the (image / PDF / audio...)", }, content_block, ],}
일부 OpenAI 모델(gpt-4o 및 gpt-4o-mini 시리즈 등)은 LLM의 예상 출력 중 알려진 부분을 미리 전달하여 지연 시간을 줄일 수 있는 Predicted Outputs를 지원합니다. 이는 모델 출력의 일부만 변경되는 텍스트 또는 코드 편집과 같은 경우에 유용합니다.예제:
Copy
code = """/// <summary>/// Represents a user with a first name, last name, and username./// </summary>public class User{ /// <summary> /// Gets or sets the user's first name. /// </summary> public string FirstName { get; set; } /// <summary> /// Gets or sets the user's last name. /// </summary> public string LastName { get; set; } /// <summary> /// Gets or sets the user's username. /// </summary> public string Username { get; set; }}"""llm = ChatOpenAI(model="gpt-4o")query = ( "Replace the Username property with an Email property. " "Respond only with code, and with no markdown formatting.")response = llm.invoke( [{"role": "user", "content": query}, {"role": "user", "content": code}], prediction={"type": "content", "content": code},)print(response.content)print(response.response_metadata)
Copy
/// <summary>/// Represents a user with a first name, last name, and email./// </summary>public class User{ /// <summary> /// Gets or sets the user's first name. /// </summary> public string FirstName { get; set; } /// <summary> /// Gets or sets the user's last name. /// </summary> public string LastName { get; set; } /// <summary> /// Gets or sets the user's email. /// </summary> public string Email { get; set; }}{'token_usage': {'completion_tokens': 226, 'prompt_tokens': 166, 'total_tokens': 392, 'completion_tokens_details': {'accepted_prediction_tokens': 49, 'audio_tokens': None, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 107}, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_45cf54deae', 'finish_reason': 'stop', 'logprobs': None}
현재 예측은 추가 토큰으로 청구되며 지연 시간 감소 대신 사용량 및 비용이 증가할 수 있습니다.
형식은 model_kwargs['audio']['format']에 전달된 것입니다.OpenAI expires_at에 도달하기 전에 오디오 데이터가 포함된 이 메시지를 메시지 히스토리의 일부로 모델에 다시 전달할 수도 있습니다.
출력 오디오는 AIMessage.additional_kwargs의 audio 키 아래에 저장되지만, 입력 콘텐츠 블록은 HumanMessage.content 목록에서 input_audio 유형 및 키로 타입이 지정됩니다.자세한 내용은 OpenAI의 audio docs를 참조하세요.
Copy
history = [ ("human", "Are you made by OpenAI? Just answer yes or no"), output_message, ("human", "And what is your name? Just give your name."),]second_output_message = llm.invoke(history)
OpenAI는 다양한 service tiers를 제공합니다. “flex” 티어는 요청에 대해 더 저렴한 가격을 제공하지만 응답이 더 오래 걸리고 리소스가 항상 사용 가능하지 않을 수 있습니다. 이 접근 방식은 모델 테스트, 데이터 향상 또는 비동기적으로 실행할 수 있는 작업을 포함한 중요하지 않은 작업에 가장 적합합니다.사용하려면 service_tier="flex"로 모델을 초기화하세요: