forked from boostcampwm-2024/web17-juchumjuchum
-
Notifications
You must be signed in to change notification settings - Fork 1
클로바 API 응답 형식 검증하기
김두종 edited this page Feb 13, 2025
·
1 revision
-
프롬프트 엔지니어링을 통해서 일차적으로 원하는 형태로 Clova 뉴스 요약 데이터를 받아올 수 있었지만, 항상 일정한 형식으로 온다는 보장이 없기 때문에 검증하는 로직을 추가할 필요성이 있었습니다.
-
JSON 형식에 대한 검증은 이미 이루어지고 있었지만, 각 필드 key값에 대한 검증이 이루어지지 않고 있었습니다.
-
주요 검증 내용
- JSON 데이터 안의 필드 key값들이 우리가 지정한 값과 일치하는지
{
"stock_id": "035720",
"stock_name": "카카오",
"link": "http://example1.com, http://example2.com",
"title": "카카오 실적 발표",
"summary": "실적 내용 요약...",
"positive_content": "긍정적 내용...",
"negative_content": "해당사항 없음"
}
- CreateStockNewsDto를 활용해서, 클로바로부터 받은 응답 객체를 CreateStockNewsDto 클래스 인스턴스로 변환하는 과정을 추가했습니다.
private async validateClovaResponse(response: any) {
try {
const content = response.data.result.message.content;
this.logger.info(`Summarized news: ${content}`);
const parsedContent = JSON.parse(content);
const fixedContent = this.fixFieldNames(parsedContent);
const summarizedNews = plainToInstance(CreateStockNewsDto, fixedContent);
await validateOrReject(summarizedNews);
return summarizedNews;
} catch (error) {
if (Array.isArray(error)) {
this.logger.error(
`Wrong field format from clova response: ${JSON.stringify(error, null, 2)}`,
);
} else {
this.logger.error('Failed to parse clova response', error);
}
return null;
}
}
- 응답 형식이 잘못되는 경우를 잡을 수 있는지 테스트하기 위해 프롬프트를 수정했습니다.
- 응답 필드 key값들 중에서
positive_content
와negative_content
를positive_contents
와negative_contents
로 변경하여 테스트 했습니다.
...
[응답 예시]
{
...
"positive_contents": "긍정적 내용...",
"negative_contens": "해당사항 없음"
}
- 다음과 같이 try-catch에서 잘 잡히는 것을 확인할 수 있었습니다.
- 매 상황별 테스트를 실제로 할 수는 없기 때문에 테스트 코드를 작성하게 되었습니다.
- 클로바 뉴스 요약이 성공하는 경우와 실패하는 경우, 그리고 토큰 계산 로직에 대한 테스트 코드를 작성했습니다.
- 뉴스 요약 성공
- 클로바가 정상적인 형식의 데이터를 응답하는 경우
- stock_id, stock_name 필드명이 stockId, stockName으로 대체된 경우
- 뉴스 요약 실패
- 클로바 응답에 필수 필드가 없는 경우
- 토큰 계산
- 토큰 계산 클로바 응답에 있는 count 필드를 잘 계산하는지 확인
- 뉴스 요약 성공
describe('클로바 뉴스 요약 실패', () => {
// 클로바 응답 content 예시
const contentExample = {
stock_id: '005930',
stock_name: '삼성전자',
link: 'http://example1.com',
title: '삼성전자 실적 호조',
summary: '실적이 좋습니다',
positive_content: '긍정적입니다',
negative_content: '해당사항 없음',
};
test.each([
['stock_id', { ...contentExample, stock_id: undefined }],
['stock_name', { ...contentExample, stock_name: undefined }],
['link', { ...contentExample, link: undefined }],
['title', { ...contentExample, title: undefined }],
['summary', { ...contentExample, summary: undefined }],
['positive_content', { ...contentExample, positive_content: undefined }],
['negative_content', { ...contentExample, negative_content: undefined }],
])(
'클로바 뉴스 요약의 필수 필드 중 %s 가 없는 경우 null을 반환한다',
async (_, responseContent) => {
// given
const textContent = JSON.stringify(responseContent);
const mockClovaResponse = createMockClovaResponse(textContent);
mockAxios.post.mockResolvedValue(mockClovaResponse);
// when
const result = await newsSummaryService.summarizeNews(mockCrwalingData);
// then
expect(result).toBeNull();
expect(mockLogger.error).toHaveBeenCalled();
},
);
- [1주 2일차 합동 개발 일지](marketCap 데이터 null 이슈 해결)
- 인터셉터를 이용한 로거 개발기
- 배포 환경에서 웹 소캣 연결 실패 문제 해결
- Github Actions를 이용한 CI CD 구축
- nGrinder 테스트 시나리오
- nGrinder TPS가 측정되지 않는 문제
- 메트릭 수집에 필요한 툴들 설치하기
- Node Exporter 연결 안되는 문제
- StockService에서 Repository 계층 분리하기
- Server와 Grafana연동하기
- Guest 로그인 중복 문제 해결
- 뉴스요약 AI 프롬프팅
- 주식 학습 도우미 AI 프롬프팅
- 뉴스 요약 클로바 API 연동하기
- 샘플 뉴스 데이터를 활용한 Clova 요약 성능 확인
- 공동 개발 일지 - 뉴스 요약 AI 기능 도입 시도
- [AI 뉴스 요약]네이버 뉴스 크롤링 기능을 구현해보자
- AI 요약결과 db 저장
- 크롤링시 뉴스 카테고리 필터링 기능 추가하기
- 클로바 API 응답 형식 오류 해결
- 클로바 API 응답 형식 검증하기
- 주식 상세 페이지 차트 버그 해결하기
- NewsSummaryService를 위한 커스텀 에러 구현
- 실시간 주식 데이터 스로틀링 구현
- AI 기반 주식 뉴스 처리 시스템의 안정성 개선