watsonx.ai에서 텍스트 생성하기
watsonx.ai에서 텍스트 생성하기
파운데이션 모델을 코드에서 불러 텍스트를 만들어 내는 게 추론(inference)이에요. watsonx.ai에서는 REST API부터 파이썬, Node.js, LangChain, LlamaIndex까지 여러 방법으로 텍스트 생성 요청을 보낼 수 있어요. 이번엔 그 흐름과 REST 예시를 살펴볼게요.
권한과 자격 증명
프롬프트를 실행하려면 프로젝트에서 Admin 또는 Editor 역할이 필요해요. 또 watsonx.ai API로 인증하려면 자격 증명(베어러 토큰)을 미리 만들어 둬야 해요.
추론 방식 두 가지
파운데이션 모델에 프롬프트를 보내는 방법은 두 가지예요.
- Infer text — 모델이 생성한 출력을 한 번에 끝까지 기다렸다가 반환해요.
- Infer text event stream — 모델이 생성하는 대로 출력을 스트리밍으로 반환해요. 챗봇처럼 실제 대화처럼 자연스럽게 응답하고 싶을 때 유용해요.
⚠️ 텍스트 생성 API는 지원 중단(deprecated) 되어 2027년 3월 14일에 제거될 예정이에요. 챗 형태로 사용할 거라면 챗 API를 쓰는 걸 권장해요.
개발 방법
파운데이션 모델을 추론하는 프로그래밍 방식은 다양해요.
- REST API
- Python
- Node.js
- LangChain (Python)
- LangChain (JS)
- LlamaIndex
GUI 툴을 선호한다면 watsonx.ai UI의 Prompt Lab에서도 추론할 수 있어요.
REST API로 텍스트 생성
사용하는 추론 방법은 모델이 watsonx.ai에 제공된 모델인지, 배포(deployment)와 연결된 모델인지에 따라 달라져요.
watsonx.ai에 제공된 파운데이션 모델은 Text generation 메서드를 써요.
curl -X POST 'https://<region>.<cloud-provider-domain>/ml/v1/text/generation?version=2025-02-11' \
-H 'Authorization: Bearer ***' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
--data-raw '{
"input": "Tell me about interest rates",
"parameters": {
"max_new_tokens": 200
},
"model_id": "ibm/granite-3-8b-instruct",
"project_id": "<project_id>"
}'
튜닝했거나 커스텀한 파운데이션 모델은 Deployments의 Infer text 메서드를 사용해요. 배포에는 모델 하나만 연결되므로 {model_id}는 필요 없어요.
추론 시 AI 가드레일 적용
API로 프롬프트를 보낼 때 moderations 필드를 사용하면 모델 입력·출력에 AI 가드레일을 적용할 수 있어요. 자세한 내용은 "Removing harmful language from model input and output" 문서를 참고해요.
프롬프트 템플릿으로 추론하기
프롬프트 템플릿이 정의한 패턴에 따라 입력 텍스트를 만들어 추론할 수도 있어요. 텍스트 생성 메서드의 입력으로 쓸 프롬프트 템플릿 텍스트를 뽑는 절차는 다음과 같아요.
먼저 Watson Data API의 Search asset types 메서드로 프롬프트 템플릿 ID를 가져와요. 반환되는 metadata.asset_id가 바로 템플릿 ID예요.
curl -X POST \
'https://api.dataplatform.cloud.ibm.com/v2/asset_types/wx_prompt/search?version=2024-07-29&project_id=<project_id>' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer ***' \
--data '{
"query": "asset.name:<template_name>"
}'
그다음 Get the inference input string for a given prompt 메서드로 프롬프트 템플릿 텍스트를 가져와요.
curl -X POST \
'https://api.dataplatform.cloud.ibm.com/wx/v1/prompts/<prompt-template-id>/input?version=2024-07-29&project_id=<project_id>'
...
이렇게 뽑은 프롬프트 텍스트를 Generate text 메서드의 input으로 그대로 제출하면 돼요.
추론 요청 암호화하기
클라우드 제공자 계정에서 관리하는 커스텀 키로 추론 요청을 암호화하고 모델 응답을 복호화할 수 있어요. 단, 커스텀 암호화 키는 Dallas 리전에서만 사용할 수 있어요.
먼저 key_manager_api_key 타입의 작업 자격 증명(task credential)을 만들고,
curl --request POST 'https://<region>.<cloud-provider-domain>/ml/v1/task_credentials' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer ***' \
--data '{
"name": "Key manager task credentials",
"description": "This is my task credentials",
"type": "key_manager_api_key"
}'
외부 키 관리 서비스(예: IBM Key Protect)에서 래핑된 커스텀 데이터 암호화 키(DEK)를 생성해요. DEK의 base-64 인코딩 cipher text는 꼭 저장해 두세요.
그 키 참조(key reference)를 만들 때는 DEK의 cipher text를 키의 cloud resource name(CRN)에 붙여 넣어요. 형식은 이렇게 돼요.
export DEK_REF="crn:v1:bluemix:public:kms:<region>:a/<account-id>:<service-instance>:key:<key-id>:wdek:<cipher-text-for-DEK>"
마지막으로 텍스트 생성 REST 요청의 crypto.key_ref에 DEK 참조를 지정하면 추론 요청이 암호화돼요.
curl -X POST 'https://<region>.<cloud-provider-domain>/ml/v1/text/generation?version=2025-12-11' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer ***' \
--data-raw '{
"input": "Tell me about interest rates",
"model_id": "ibm/granite-3-8b-instruct",
"project_id": "<project_id>",
"parameters": {
"max_new_tokens": 200
},
"crypto": {
"key_ref": ${DEK_REF}
}
}'
다른 언어에서 쓰기
파이썬에서는 watsonx.ai 파이썬 라이브러리의 ModelInference 클래스를 사용해요. Node.js는 Text Generation / Text Generation Stream 파라미터 인터페이스를 참고하면 돼요. 실제 실행은 각 언어별 예제 노트북과 예시를 따라가면 부담이 없어요.