OpenAI 통합
OpenAI 통합 (OpenAI integration)
LangChain JavaScript로 OpenAI 툴과 통합해요.
@langchain/openai 패키지는 OpenAI의 내장 툴에 대한 LangChain 호환 래퍼를 제공해요. 이 툴들은 bindTools()나 createAgent를 사용해 ChatOpenAI에 바인딩할 수 있어요.
웹 검색 툴 (Web search tool)
웹 검색 툴은 OpenAI 모델이 응답을 생성하기 전에 최신 정보를 위해 웹을 검색할 수 있게 해줘요. 웹 검색은 세 가지 주요 유형을 지원해요:
- 추론 없는 웹 검색 (Non-reasoning web search): 모델이 쿼리를 검색 툴에 직접 전달하는 빠른 조회
- 추론 모델을 사용한 에이전트 검색 (Agentic search with reasoning models): 모델이 검색 과정을 적극적으로 관리하며 결과를 분석하고 계속 검색할지 결정
- 딥 리서치 (Deep research):
o3-deep-research나gpt-5같은 모델을 높은 추론 노력으로 사용하는 확장 조사
import { ChatOpenAI, tools } from "@langchain/openai";
const model = new ChatOpenAI({
model: "gpt-5.5",
});
// Basic usage
const response = await model.invoke(
"What was a positive news story from today?",
{
tools: [tools.webSearch()],
}
);
도메인 필터링 - 검색 결과를 특정 도메인으로 제한 (최대 100개):
const response = await model.invoke("Latest AI research news", {
tools: [
tools.webSearch({
filters: {
allowedDomains: ["arxiv.org", "nature.com", "science.org"],
},
}),
],
});
사용자 위치 - 지리 기반으로 검색 결과를 정밀화:
const response = await model.invoke("What are the best restaurants near me?", {
tools: [
tools.webSearch({
userLocation: {
type: "approximate",
country: "US",
city: "San Francisco",
region: "California",
timezone: "America/Los_Angeles",
},
}),
],
});
캐시 전용 모드 - 실시간 인터넷 접근 비활성화:
const response = await model.invoke("Find information about OpenAI", {
tools: [
tools.webSearch({
externalWebAccess: false,
}),
],
});
자세한 내용은 OpenAI의 Web Search Documentation을 참고하세요.
MCP 툴 (Model context protocol)
MCP 툴은 OpenAI 모델이 원격 MCP 서버와 OpenAI가 관리하는 서비스 커넥터에 연결해, 모델이 외부 툴과 서비스에 접근할 수 있게 해줘요.
MCP 툴을 사용하는 방법은 두 가지예요:
- 원격 MCP 서버 (Remote MCP servers): URL을 통해 공개 MCP 서버에 연결
- 커넥터 (Connectors): Google Workspace, Dropbox 같은 인기 서비스에 대한 OpenAI 관리 래퍼 사용
원격 MCP 서버 - MCP 호환 서버에 연결:
import { ChatOpenAI, tools } from "@langchain/openai";
const model = new ChatOpenAI({ model: "gpt-5.5" });
const response = await model.invoke("Roll 2d4+1", {
tools: [
tools.mcp({
serverLabel: "dmcp",
serverDescription: "A D&D MCP server for dice rolling",
serverUrl: "https://dmcp-server.deno.dev/sse",
requireApproval: "never",
}),
],
});
서비스 커넥터 - 인기 서비스용 OpenAI 관리 커넥터 사용:
const response = await model.invoke("What's on my calendar today?", {
tools: [
tools.mcp({
serverLabel: "google_calendar",
connectorId: "connector_googlecalendar",
authorization: "<oauth-access-token>",
requireApproval: "never",
}),
],
});
자세한 내용은 OpenAI의 MCP Documentation을 참고하세요.
코드 인터프리터 툴 (Code interpreter tool)
Code Interpreter 툴은 모델이 샌드박스 환경에서 Python 코드를 작성·실행해 복잡한 문제를 해결할 수 있게 해줘요.
Code Interpreter는 다음에 사용하세요:
- 데이터 분석: 다양한 데이터와 포맷을 가진 파일 처리
- 파일 생성: 데이터와 그래프 이미지가 포함된 파일 생성
- 반복적 코딩: 문제 해결을 위해 코드를 반복적으로 작성·실행
- 시각 지능: 이미지 자르기, 확대, 회전, 변환
import { ChatOpenAI, tools } from "@langchain/openai";
const model = new ChatOpenAI({ model: "gpt-5.5" });
// Basic usage with auto container (default 1GB memory)
const response = await model.invoke("Solve the equation 3x + 11 = 14", {
tools: [tools.codeInterpreter()],
});
메모리 구성 - 1GB(기본), 4GB, 16GB, 64GB 중 선택:
const response = await model.invoke(
"Analyze this large dataset and create visualizations",
{
tools: [
tools.codeInterpreter({
container: { memoryLimit: "4g" },
}),
],
}
);
파일과 함께 - 업로드된 파일을 코드에서 사용할 수 있도록:
const response = await model.invoke("Process the uploaded CSV file", {
tools: [
tools.codeInterpreter({
container: {
memoryLimit: "4g",
fileIds: ["file-abc123", "file-def456"],
},
}),
],
});
명시적 컨테이너 - 사전 생성된 컨테이너 ID 사용:
const response = await model.invoke("Continue working with the data", {
tools: [
tools.codeInterpreter({
container: "cntr_abc123",
}),
],
});
Note: 컨테이너는 비활성 상태 20분 후 만료돼요. 이름이 "Code Interpreter"지만 모델은 이를 "python tool"로 알고 있어요. 명시적으로 프롬프트하려면 "the python tool"을 요청하세요.
자세한 내용은 OpenAI의 Code Interpreter Documentation을 참고하세요.
파일 검색 툴 (File search tool)
File Search 툴은 모델이 의미론적·키워드 검색으로 파일에서 관련 정보를 검색할 수 있게 해줘요. 벡터 스토어에 저장된 이전에 업로드한 파일의 지식 베이스에서 검색을 가능하게 해요.
전제 조건: File Search를 사용하기 전에 다음을 해야 해요:
purpose: "assistants"로 File API에 파일을 업로드- 벡터 스토어 생성
- 벡터 스토어에 파일 추가
import { ChatOpenAI, tools } from "@langchain/openai";
const model = new ChatOpenAI({ model: "gpt-5.5" });
const response = await model.invoke("What is deep research by OpenAI?", {
tools: [
tools.fileSearch({
vectorStoreIds: ["vs_abc123"],
// maxNumResults: 5, // Limit results for lower latency
// filters: { type: "eq", key: "category", value: "blog" }, // Metadata filtering
// filters: { type: "and", filters: [ // Compound filters (AND/OR)
// { type: "eq", key: "category", value: "technical" },
// { type: "gte", key: "year", value: 2024 },
// ]},
// rankingOptions: { scoreThreshold: 0.8, ranker: "auto" }, // Customize scoring
}),
],
});
필터 연산자: eq(같음), ne(다름), gt(보다 큼), gte(이상), lt(보다 작음), lte(이하).
자세한 내용은 OpenAI의 File Search Documentation을 참고하세요.
이미지 생성 툴 (Image generation tool)
Image Generation 툴은 모델이 텍스트 프롬프트와 선택적 이미지 입력을 사용해 이미지를 생성·편집할 수 있게 해줘요. GPT Image 모델을 활용하며 성능 향상을 위해 텍스트 입력을 자동으로 최적화해요.
Image Generation은 다음에 사용하세요:
- 텍스트에서 이미지 생성: 상세한 텍스트 설명에서 이미지 생성
- 기존 이미지 편집: 텍스트 지침을 기반으로 이미지 수정
- 다중 턴 이미지 편집: 대화 턴에 걸쳐 이미지를 반복적으로 정교화
- 다양한 출력 포맷: PNG, JPEG, WebP 포맷 지원
import { ChatOpenAI, tools } from "@langchain/openai";
const model = new ChatOpenAI({ model: "gpt-5.5" });
// Basic usage - generate an image
const response = await model.invoke(
"Generate an image of a gray tabby cat hugging an otter with an orange scarf",
{ tools: [tools.imageGeneration()] }
);
// Access the generated image (base64-encoded)
const imageOutput = response.additional_kwargs.tool_outputs?.find(
(output) => output.type === "image_generation_call"
);
if (imageOutput?.result) {
const fs = await import("fs");
fs.writeFileSync("output.png", Buffer.from(imageOutput.result, "base64"));
}
커스텀 크기와 품질 - 출력 크기와 품질 구성:
const response = await model.invoke("Draw a beautiful sunset over mountains", {
tools: [
tools.imageGeneration({
size: "1536x1024", // Landscape format (also: "1024x1024", "1024x1536", "auto")
quality: "high", // Quality level (also: "low", "medium", "auto")
}),
],
});
출력 포맷과 압축 - 포맷과 압축 수준 선택:
const response = await model.invoke("Create a product photo", {
tools: [
tools.imageGeneration({
outputFormat: "jpeg", // Format (also: "png", "webp")
outputCompression: 90, // Compression 0-100 (for JPEG/WebP)
}),
],
});
투명 배경 - 투명도가 있는 이미지 생성:
const response = await model.invoke(
"Create a logo with transparent background",
{
tools: [
tools.imageGeneration({
background: "transparent", // Background type (also: "opaque", "auto")
outputFormat: "png",
}),
],
}
);
부분 이미지 스트리밍 - 생성 중 시각적 피드백 받기:
const response = await model.invoke("Draw a detailed fantasy castle", {
tools: [
tools.imageGeneration({
partialImages: 2, // Number of partial images (0-3)
}),
],
});
이미지 생성 강제 - 모델이 이미지 생성 툴을 사용하도록 보장:
const response = await model.invoke("A serene lake at dawn", {
tools: [tools.imageGeneration()],
tool_choice: { type: "image_generation" },
});
다중 턴 편집 - 대화 턴에 걸쳐 이미지 정교화:
import { HumanMessage } from "@langchain/core/messages";
// First turn: generate initial image
const response1 = await model.invoke("Draw a red car", {
tools: [tools.imageGeneration()],
});
// Second turn: edit the image
const response2 = await model.invoke(
[response1, new HumanMessage("Now change the car color to blue")],
{ tools: [tools.imageGeneration()] }
);
프롬프트 팁: 최상의 결과를 위해 "draw"나 "edit" 같은 용어를 사용하세요. 이미지를 합칠 때는 "combine"이나 "merge" 대신 "edit the first image by adding this element"라고 말하세요.
지원 모델: gpt-4o, gpt-4o-mini, gpt-5.5, gpt-5.4-mini, gpt-5.4-nano, o3
자세한 내용은 OpenAI의 Image Generation Documentation을 참고하세요.
컴퓨터 사용 툴 (Computer use tool)
Computer Use 툴은 모델이 마우스 클릭, 키보드 입력, 스크롤 등을 시뮬레이션해 컴퓨터 인터페이스를 제어할 수 있게 해줘요. OpenAI의 Computer-Using Agent(CUA) 모델을 사용해 스크린샷을 이해하고 동작을 제안해요.
Beta: 컴퓨터 사용은 베타 상태예요. 샌드박스 환경에서만 사용하고 높은 위험이 있거나 인증이 필요한 작업에는 사용하지 마세요. 중요한 결정에는 항상 human-in-the-loop을 구현하세요.
작동 방식: 툴은 지속적 루프로 작동해요:
- 모델이 컴퓨터 동작(클릭, 타이핑, 스크롤 등)을 보냄
- 코드가 제어된 환경에서 이 동작들을 실행
- 결과의 스크린샷을 캡처
- 스크린샷을 모델에 다시 보냄
- 작업이 완료될 때까지 반복
import { ChatOpenAI, tools } from "@langchain/openai";
const model = new ChatOpenAI({ model: "computer-use-preview" });
// With execute callback for automatic action handling
const computer = tools.computerUse({
displayWidth: 1024,
displayHeight: 768,
environment: "browser",
execute: async (action) => {
if (action.type === "screenshot") {
return captureScreenshot();
}
if (action.type === "click") {
await page.mouse.click(action.x, action.y, { button: action.button });
return captureScreenshot();
}
if (action.type === "type") {
await page.keyboard.type(action.text);
return captureScreenshot();
}
if (action.type === "scroll") {
await page.mouse.move(action.x, action.y);
await page.evaluate(
`window.scrollBy(${action.scroll_x}, ${action.scroll_y})`
);
return captureScreenshot();
}
// Handle other actions...
return captureScreenshot();
},
});
const llmWithComputer = model.bindTools([computer]);
const response = await llmWithComputer.invoke(
"Check the latest news on bing.com"
);
자세한 내용은 OpenAI의 Computer Use Documentation을 참고하세요.
로컬 셸 툴 (Local shell tool)
Local Shell 툴은 모델이 사용자가 제공한 머신에서 셸 명령을 로컬로 실행할 수 있게 해줘요. 명령은 사용자 자신의 런타임에서 실행되며, API는 지침만 반환해요.
보안 경고: 임의의 셸 명령 실행은 위험할 수 있어요. 명령을 시스템 셸로 전달하기 전에 항상 샌드박스 실행을 하거나 엄격한 허용/거부 목록을 추가하세요. Note: 이 툴은 Codex CLI와
codex-mini-latest모델과 함께 작동하도록 설계됐어요.
import { ChatOpenAI, tools } from "@langchain/openai";
import { exec } from "child_process";
import { promisify } from "util";
const execAsync = promisify(exec);
const model = new ChatOpenAI({ model: "codex-mini-latest" });
// With execute callback for automatic command handling
const shell = tools.localShell({
execute: async (action) => {
const { command, env, working_directory, timeout_ms } = action;
const result = await execAsync(command.join(" "), {
cwd: working_directory ?? process.cwd(),
env: { ...process.env, ...env },
timeout: timeout_ms ?? undefined,
});
return result.stdout + result.stderr;
},
});
const llmWithShell = model.bindTools([shell]);
const response = await llmWithShell.invoke(
"List files in the current directory"
);
동작 속성: 모델은 다음 속성들을 가진 동작을 반환해요:
command- 실행할 argv 토큰 배열env- 설정할 환경 변수working_directory- 명령을 실행할 디렉터리timeout_ms- 권장 타임아웃 (자체 한도를 적용하세요)user- 명령을 실행할 선택적 사용자
자세한 내용은 OpenAI의 Local Shell Documentation을 참고하세요.
셸 툴 (Shell tool)
Shell 툴은 모델이 통합을 통해 셸 명령을 실행할 수 있게 해줘요. Local Shell과 달리 여러 명령을 동시에 실행하는 것을 지원하며 gpt-5.1용으로 설계됐어요.
보안 경고: 임의의 셸 명령 실행은 위험할 수 있어요. 명령을 시스템 셸로 전달하기 전에 항상 샌드박스 실행을 하거나 엄격한 허용/거부 목록을 추가하세요.
사용 사례:
- 파일시스템·프로세스 진단 자동화 – 예: "~/Documents 아래의 가장 큰 PDF 찾기"
- 모델 기능 확장 – 내장 UNIX 유틸리티, Python 런타임, 기타 CLI 사용
- 다단계 빌드·테스트 흐름 실행 –
pip install과pytest같은 명령 체이닝 - 복잡한 에이전트 코딩 워크플로 – 파일 작업에
apply_patch와 함께 사용
import { ChatOpenAI, tools } from "@langchain/openai";
import { exec } from "node:child_process/promises";
const model = new ChatOpenAI({ model: "gpt-5.1" });
// With execute callback for automatic command handling
const shellTool = tools.shell({
execute: async (action) => {
const outputs = await Promise.all(
action.commands.map(async (cmd) => {
try {
const { stdout, stderr } = await exec(cmd, {
timeout: action.timeout_ms ?? undefined,
});
return {
stdout,
stderr,
outcome: { type: "exit" as const, exit_code: 0 },
};
} catch (error) {
const timedOut = error.killed && error.signal === "SIGTERM";
return {
stdout: error.stdout ?? "",
stderr: error.stderr ?? String(error),
outcome: timedOut
? { type: "timeout" as const }
: { type: "exit" as const, exit_code: error.code ?? 1 },
};
}
})
);
return {
output: outputs,
maxOutputLength: action.max_output_length,
};
},
});
const llmWithShell = model.bindTools([shellTool]);
const response = await llmWithShell.invoke(
"Find the largest PDF file in ~/Documents"
);
동작 속성: 모델은 다음 속성들을 가진 동작을 반환해요:
commands- 실행할 셸 명령 배열 (동시에 실행 가능)timeout_ms- 선택적 타임아웃(밀리초) (자체 한도를 적용하세요)max_output_length- 명령당 반환할 선택적 최대 문자 수
반환 포맷: execute 함수는 ShellResult를 반환해야 해요:
interface ShellResult {
output: Array<{
stdout: string;
stderr: string;
outcome: { type: "exit"; exit_code: number } | { type: "timeout" };
}>;
maxOutputLength?: number | null; // Pass back from action if provided
}
Note:
gpt-5.1과 함께 Responses API에서만 사용할 수 있어요. 모델의timeout_ms는 단지 힌트일 뿐이므로 항상 자체 한도를 적용하세요.
자세한 내용은 OpenAI의 Shell Documentation을 참고하세요.
Apply patch 툴
Apply Patch 툴은 모델이 통합에서 적용할 구조화된 diff를 제안할 수 있게 해줘요. 이를 통해 모델이 코드베이스에서 파일을 생성·업데이트·삭제할 수 있는 반복적 다단계 코드 편집 워크플로가 가능해요.
언제 사용하나:
- 다중 파일 리팩터 – 심볼 이름 바꾸기, 헬퍼 추출, 모듈 재구성
- 버그 수정 – 모델이 문제를 진단하고 정밀한 패치를 생성하도록
- 테스트·문서 생성 – 새 테스트 파일, 픽스처, 문서 생성
- 마이그레이션·기계적 편집 – 반복적이고 구조화된 업데이트 적용
보안 경고: 패치 적용은 코드베이스의 파일을 수정할 수 있어요. 항상 경로를 검증하고, 백업을 구현하고, 샌드박스를 고려하세요. Note: 이 툴은
gpt-5.1모델과 함께 작동하도록 설계됐어요.
import { ChatOpenAI, tools } from "@langchain/openai";
import { applyDiff } from "@openai/agents";
import * as fs from "fs/promises";
const model = new ChatOpenAI({ model: "gpt-5.1" });
// With execute callback for automatic patch handling
const patchTool = tools.applyPatch({
execute: async (operation) => {
if (operation.type === "create_file") {
const content = applyDiff("", operation.diff, "create");
await fs.writeFile(operation.path, content);
return `Created ${operation.path}`;
}
if (operation.type === "update_file") {
const current = await fs.readFile(operation.path, "utf-8");
const newContent = applyDiff(current, operation.diff);
await fs.writeFile(operation.path, newContent);
return `Updated ${operation.path}`;
}
if (operation.type === "delete_file") {
await fs.unlink(operation.path);
return `Deleted ${operation.path}`;
}
return "Unknown operation type";
},
});
const llmWithPatch = model.bindTools([patchTool]);
const response = await llmWithPatch.invoke(
"Rename the fib() function to fibonacci() in lib/fib.py"
);
동작 유형: 모델은 다음 속성들을 가진 동작을 반환해요:
create_file–path에diff의 콘텐츠로 새 파일 생성update_file–path의 기존 파일을diff의 V4A diff 포맷으로 수정delete_file–path의 파일 제거
모범 사례:
- 경로 검증: 디렉터리 트래버설을 막고 허용된 디렉터리로 편집을 제한
- 백업: 패치를 적용하기 전에 파일을 백업하는 것 고려
- 오류 처리: 모델이 복구할 수 있도록 설명적인 오류 메시지 반환
- 원자성: "all-or-nothing" 의미론(어떤 패치가 실패하면 롤백) 여부 결정
자세한 내용은 OpenAI의 Apply Patch Documentation을 참고하세요.
출처: 문서
본문
@langchain/openai의 tools 네임스페이스는 OpenAI 내장 툴(webSearch, mcp, codeInterpreter, fileSearch, imageGeneration, computerUse, localShell, shell, applyPatch)을 제공해요. 이 툴들은 tools.webSearch({...}) 같은 팩토리로 생성해 model.invoke(..., { tools: [...] })의 tools 옵션이나 bindTools()로 ChatOpenAI에 바인딩할 수 있어요. shell·applyPatch·computerUse 같은 툴은 execute 콜백을 받아 명령/패치/동작을 실제로 실행하며, 보안 경고에 주의해 샌드박스 실행을 권장해요.