본문 바로가기
인공지능/ChatGPT

OpenAI API에서 사용하는 jsonl 파일 읽고 쓰기

by judy@ 2023. 8. 17.

OpenAI의 Fine-tuning API를 사용하려면 jsonl 확장자로 데이터를 준비해야 한다. 간단히 말하면 jsonl은 key, value 형태의 json을 개행문자(\n)로 구분해놓은 파일이다. openai 파인 튜닝 예제 데이터를 보면, prompt, completion이라는 key, value로 구성된 json이 하나의 샘플이며, 이 샘플을 나열할 때에는 개행문자를 통해 구분되게끔 하였다.

{"prompt": "<prompt text>", "completion": "<ideal generated text>"}
{"prompt": "<prompt text>", "completion": "<ideal generated text>"}
{"prompt": "<prompt text>", "completion": "<ideal generated text>"}
...

from openai platform

 

위와 같은 파일을 읽고 쓰려면, python의 I/O와 json 라이브러리를 적절히 믹스하면 되지만, jsonl에 특화된 라이브러리를 사용하면 더 편하다. https://jsonlines.readthedocs.io

 

jsonlines — jsonlines documentation

Read and decode a line. The optional type argument specifies the expected data type. Supported types are dict, list, str, int, float, and bool. When specified, non-conforming lines result in InvalidLineError. By default, input lines containing null (in JSO

jsonlines.readthedocs.io

상세한 사용 방법은 위 도큐먼트에 나와있는데, 간단히 파일을 읽고 쓰기 위해서는 다음과 같은 코드면 충분하다.

 

1. jsonlines 설치

pip install jsonlines

2. 파일 읽기

data는 딕셔너리의 리스트로 구성된다

import jsonlines

with jsonlines.open('input.jsonl') as reader:
    data = [line for line in reader.iter()]

3. 파일 쓰기

딕셔너리의 리스트를 jsonl로 쓰는 방법

import jsonlines

lines = [{'key1':'value11', 'key2':'value12'}, {'key2':'value21', 'key2':'value22'}]
with jsonlines.open('output.jsonl', mode='w') as writer:
	for line in lines:
		writer.write(line)

 

참고로 pandas에서는 파일을 jsonl로 저장할 수 있다!

df.to_json('df-output.jsonl', orient='records', lines=True)

 

반응형