기본 콘텐츠로 건너뛰기

OpenAI API 대신 ollama API 서버 사용해보기


OPENAI는 경쟁자 대비 성능과 편의성에서 앞서 나가고 있기 때문에 후발주자는 OpenAI의 API형태를 산업표준처럼 지원하고 있다.


실제 서비스를 위해서는 성능 좋은 OpenAI API 서비스를 사용해야하지만 학습하는 입장에서API호출하는 방법을 연습하기 위해서 Ollama Server가 제공하는 호환 API로 동작테스트해본다.


일반적으로 설치한 Ollama 서버는 0.0.0.0:11434 port에서 통상 동작한다. 다르게 변경했다면 그에 맞게 수정필요하다.

"v1/chat/completions"

이 부분은 OpenAI 가 제공한 API endpoint인데 후발주자들도 이 형식을 지원한다.

Ollama 서버이용

import requests
import json

def classify_intent_llm(text):
    system_prompt = f"""You are a helpful assistant that classifies user intents based on a few examples.

Examples:
- User: 오늘 서울의 날씨는 어때? -> Intent: weather
- User: 가까운 커피숍 어디 있어? -> Intent: location_search
- User: 최근에 출시된 대출 상품에 대해 알려줘. -> Intent: product_info

Consideration: Only outputs the name of intent.
"""

    user_prompt = f"""Classify the following user input:
User: {text} -> Intent:
"""

    # Ollama API 엔드포인트
    url = "http://localhost:11434/v1/chat/completions"
   
    # API 요청 데이터
    payload = {
        # "model": "gemma2",
        # "model": "deepseek-r1:8b",
        "model": "llama3.1:8b",        
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt}
        ],
        "stream": False
    }

    headers = {"Content-Type": "application/json"}  # 헤더 추가

    try:
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()  # HTTP 에러 체크
       
        result = response.json()
        return result['choices'][0]['message']['content']

       
    except requests.exceptions.RequestException as e:
        print(f"API 요청 중 오류 발생: {e}")
        return None

# 테스트
text = "오늘 서울 날씨 어때?"
intent = classify_intent_llm(text)
print(f"Text: {text} -> Predicted Intent: {intent}")

OpenAI API 이용

def classify_intent_llm(text):
    system_prompt = f"""You are a helpful assistant that classifies user intents based on a few examples.

Examples:
- User: 오늘 서울의 날씨는 어때? -> Intent: weather
- User: 가까운 커피숍 어디 있어? -> Intent: location_search
- User: 최근에 출시된 대출 상품에 대해 알려줘. -> Intent: product_info

Consideration: Only outputs the name of intent.
"""

    user_prompt = """Classify the following user input:
User: {} -> Intent:
"""

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt.format(text)}
        ],
        max_tokens=15,
        temperature=0.,
    )
    return response.choices[0].message.content.strip()

목적

질문 "오늘 서울 날씨 어때?"문장의 의도가 무엇인지
LLM(model : gemma2, llama3.1:8b, deepseek-r1:8b)을 통해서
의도(intent)를 파악하여 분류했다.


p.s.

12월에는 GGUF 추가하는라 낑낑되었는데
2개월 지난 지금은 LLM 이나 Ollama 홈페이지에서 바로 다운로드 되는 쓸만한 Model이 추가되었고 

편의면에서 LLM을 사용하는 LM Studio나 open webui 같은 frontpage UI까지 접근성이 너무 좋아진것 같다.

Ollama API로 entity 추출

import requests
import json

def extract_entities(text):
    system_prompt = """You are a helpful assistant to extract entities from the given user input.

    ###Entity Categories
    - DATETIME
    - LOCATION
    - PERSON

    Output Consideration: Only return extracted entities as dict type and entity type for key and extracted entity as value.
    """

    user_prompt = text

    # Ollama API 엔드포인트
    url = "http://localhost:11434/v1/chat/completions"
   
    # API 요청 데이터
    payload = {
        # "model": "gemma2",
        # "model": "deepseek-r1:8b",
        # "model": "llama3.1:8b",        
        "model": "exaone3.5:2.4b",
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt}
        ],
        "stream": False
    }

    headers = {"Content-Type": "application/json"}  # 헤더 추가

    try:
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()  # HTTP 에러 체크
       
        result = response.json()
        return result['choices'][0]['message']['content']

       
    except requests.exceptions.RequestException as e:
        print(f"API 요청 중 오류 발생: {e}")
        return None

# 테스트
text = "내일 파리 근방에 있는 괜찮은 호텔 추천해줄 수 있어?"
entity = extract_entities(text)
print(f"Text: {text} -> extract entity: {entity}")

Ollama Model중 한국어 학습한 모델이라도 원하는 데이타 포맷으로 나오지 않는 경우가 종종 있다. OpenAI가 아니라서 그런것 같다

prompt를 조정해야하고 원하는 포맷에서 벗어나는 형태로 해주는 경우가 있으므로 LLM이 아니라 전통적인 방식(rule baed, nlp ner model)을 사용해서 추출하는게 정확한 output을 얻을 수 있는 것 같다.


   ###Output Instructions:
    1. Extract entities from the input text.
    2. Return ONLY a dict object with entity types as keys and extracted entities as values.
    3. For each entity type, extract only one value per one key (the most relevant or first occurrence)
    4. Do not include any explanations, markdown code blocks, or additional text.
    5. The output should be a valid dict object that can be directly parsed.
   

OpenAI API로 entity 추출

# LLM으로 엔티티 추출
system_prompt = """You are a helpful assistant to extract entities from the given user input.

###Entity Categories
- DATETIME
- LOCATION
- PERSON

Output Consideration: Only return extracted entities as dict type and entity type for key and extracted entity as value.
"""

user_prompt = text

response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt}
    ],
    temperature=0.,
)

print(response.choices[0].message.content)

댓글

이 블로그의 인기 게시물

llama 계열 gguf 제공되는 경우 가져와서 사용하는 예제

llama 계열의 모델이 친절하게 gguf 형태로 제공되는 경우 어떻게 다운받고 어떻게 ollama에 추가하는지 예전에 gguf 파일을 등록하는 유튜브 강의를 보고 메모해두것을 기반으로 2024년 12월31일 추운 겨울 밤 기억을 백업해 봅니다 수동으로 작성한 것은 지우고 copilot으로 포맷을 정리해서 업데이트합니다. Bllossom/llama-3.2-Korean-Bllossom-3B-gguf-Q4_K_M 한국어 모델 추가하기 시작 : MS Copilot과의 질의응답 중 llama 3.2 기반의 한국어 학습 모델을 발견. 현재 사용 모델 : EEVE-Korean-10.8B (약 7.7 GB) 모델 사용 중. llama 3.2 기반 한국어 모델 소개 : 모델 설명 링크 gguf 파일 다운로드 링크 deepseek-ai/DeepSeek-R1-Distill-Qwen-7B  기반 한국어 모델 소개 : 모델 설명 링크 gguf 파일 다운로드 링크 모델 설정 파일 (Modelfile) : FROM llama-3.2-Korean-Bllossom-3B-gguf-Q4_K_M.gguf PARAMETER temperature 0.6 PARAMETER top_p 0.9 TEMPLATE """<|start_header_id|>system<|end_header_id|> Cutting Knowledge Date : December 2023 {{ if .System }}{{ .System }} {{- end }} {{- if .Tools }} When you receive a tool call response, use the output to format an answer to the orginal user question. You are a helpful assistant with tool calling capabilities. {{- end }} <|eot_id|> {{- range $i , $_ := .Messa...

OS가 설치된 PM981A (512GB)를 A440Pro(2TB)로 NVME 마이그레이션 과정

조립대행으로 마춘 컴퓨터라 NVME 마이그레이션을 처음인데 무사히 마쳐서 2~3년뒤에 혹시 찾아볼까 싶어 기록으로 남깁니다. 사용하는 제품은 NVME 제품은 삼성전자 PM Pm981a M.2 NVME 512GB 인데 국내에서는 삼성전자 내장 SSD 970 EVO Plus NVMe M.2 500 GBMZ-V7S500BW https://www.samsung.com/sec/memory-storage/970-evo-plus-nvme-m2-ssd/MZ-V7S500BW/ 기존시스템 AMD 라이젠 3600 (마티스) MSI B450M 박격포 맥스 M2_1 은 PCI e3.0 M2_2 는 PCIe 2.0 삼성전자 PM Pm981a M.2 NVME 512GB C 드라이브가 점점 차올라서 TeamGroup A440 Pro PCIe 4.0x4 2TB 구입 11월25일 주문, 12월2일 배송 JEYI 방열패드 조립 https://youtu.be/idZ3ctqlpwo?si=Ade03n0afuMKTD9q 존스보 방열판보다는 더 두꺼우나 장착에는 문제가 없음. M.2 2nd slot에 장착 Migration Program 준비 여기서 시간소요 많이함, Free 버젼에서 Clone기능이 막혀있거나 Trial에서도 안되는 복제기능이 지원되지 않음. AOMEI backup Std Clone 미지원 AOMEI backup Pro Tirla Clone 미지원 Samsung Disk_Mirgration (지원하지 않는다는 이야기가 있어서 Skip) refect home trial 지원 refect home trial로 clone시 21분소요 PCIe 3.0 x4 에서 PCIe 2.0 x4 로 clone C: Pm981a spec상 속도가 3500MB/s, 쓰기 속도는 3200MB/s F: A440 Pro spec상 속도가 7400MB/s, 쓰기 속도는 7000MB/s 복제완료후 PCIe 3.0 의 PM981A와 PCIe 2.0 의 A440 Pro를 스왑 해매는 포인트 여기서 약간 해맸...

TUF Z390-PLUS GAMING 보드 불편한점

2018년 11월말에 PC를 새로 셋업했습니다. 사무실에서 사용하는 조건이라 구성은 단촐하게 CPU + BOARD + Memory 컴파일용이라 그래픽카드는 없습니다. CPU는 i7 9700K이고, Mainboard Model 은 TUF Z390-PLUS GAMING 입니다. 전에사용하던 CPU가 Haswell i5였었기 때문에 비교하면 2배는 좋아서 성능은 좋습니다. 이틀정도 설정하고 사용후 불편한점 0. 기존 DVI-I 인터페이스가 없어져서 구형 모니터의 DVI 포트를 사용하지 못합니다. DVI + VGA 조합이었는데 .. 변경후 DP + HDMI 조합이라서 애매하게 되었습니다. 1. 설치후에 ASUS Q-installer가 실행되고 설치가 끝나지 않는 현상이 있습니다. 혹시나 해서 BIOS는 현재 기준으로 최신버젼인 1004로 업데이트했습니다. 부팅때마다 저러고 있어서 , 일단 ASUS 홈페이지를 통해서 문의를 넣어놓은 상태입니다. 참고로 ASUS에 문의를 넣을때 MotherBoard 시리얼 번호가 필요합니다. cpuZ 프로그램으로 Report.txt를 출력해서 Ctrl+f로 찾아보면 Serial Number 와 문의시 필요한 CPU정보, DDR정보를 알아낼 수 있으니 cpuZ로 report.txt를 먼저 생성한후에 ASUS 문의를 시작하면 시간이 단축됩니다. Processors Information ------------------------------------------------------------------------- Socket 1 ID = 0 Number of cores 8 (max 8) Number of threads 8 (max 8) Name Intel Core i7 9700K Codename Coffee Lake Specification Intel(R) Core(TM) i7-9700K CPU @ 3.60GHz Package...