미분류
ollama generate 예제
nick-p
2024. 12. 20. 08:59
----------------------------------------
import requests
url = 'http://localhost:11434/api/generate'
payload = {
'model': 'llama3',
'prompt': '왜 하늘은 파란가요?'
}
response = requests.post(url, json=payload)
print(response.json()['response'])
NotOpenSSLWarning 문제를 해결하고도 제대로 실행이 되지 않았다
Traceback (most recent call last):
File "/Users/{}/python_sample/ollama/ollama_test.py", line 11, in <module>
print(response.json()['response'])
File "/Users/{}/python_sample/venv/lib/python3.9/site-packages/requests/models.py", line 971, in json
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
response 가 Json 형태가 아니라서 Content-typed 을 확인하였다
print(f"Content-Type:{response.headers.get('Content-Type')}")
Content-Type:application/x-ndjson 형태고 응답이 오고 있어서, 출력문을 수정하였다
# 응답 상태 확인
if response.status_code == 200:
# NDJSON 데이터 처리
ndjson_data = response.text.strip().split("\n") # 줄바꿈으로 데이터 분리
for line in ndjson_data:
json_obj = json.loads(line) # 각 줄을 JSON 객체로 변환
print(json_obj)
else:
print(f"HTTP Error: {response.status_code}")
문구 있는 부분만 발췌하는 형식으로 구문 수정
responseStr = ""
# 응답 상태 확인
if response.status_code == 200:
# NDJSON 데이터 처리
ndjson_data = response.text.strip().split("\n") # 줄바꿈으로 데이터 분리
for line in ndjson_data:
json_obj = json.loads(line) # 각 줄을 JSON 객체로 변환
responseStr += json_obj['response']
else:
print(f"HTTP Error: {response.status_code}")
print(responseStr)