기본 콘텐츠로 건너뛰기

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)

댓글

이 블로그의 인기 게시물

DELL의 새게이밍 노트북, Inspiron 15 7000 Gaming, Dual Display 문제

Dell New 게이밍노트북 7567  I7 Notebook http://www.dell.com/kr/p/inspiron-15-7567-laptop/pd?ref=PD_OC 7th Generation Intel® Core™ i7 프로세서 8GB 메모리 1TB 하드 드라이브 + 128GB 솔리드 스테이트 드라이브 NVIDIA® GeForce® GTX 1050 Ti (4GB GDDR5 그래픽 메모리 포함) 상세 사양 리눅스 개발환경이 필요해서 여러대 구매한 노트북입니다. 기본적으로 ubuntu 16.04 가 설치되어 있는데, 필요한 개발환경이 ubuntu 이고 별도의 windows 개발용 PC가 있기 때문에 구매를 결정하게 되었습니다. Slim하지 않지만 I7 HQ CPU와 1050TI spec 이 결정하는데 주요했고, 받은 후에 빌드환경 구축후 8 thread compile을 만끽하던중 치명적인 문제를 Display쪽 문제를 발견하고, Dell express 쪽과 전화통화도 하고 문의 메일도 보내서 지원을 받고(진행)중입니다. 추가 :  시간낭비하지 말라고 중간에 업데이트합니다.  해결되었고, 해결방법은  Windows 을 설치한 후 Fn+F8을 눌러서 모드를 확장모드를 선택합니다. 디스플레이 설정이나 드라이버 재설치 같은 방법으로는 조정이 불가능했습니다. --------------------------------------------------------------------- 요즘 다들 Dual monitor 환경일텐데, Dual Monitor를 복제형태로만 지원을 합니다. 14.04 설치후 업데이트시 375.66 Driver가 설치됩니다. nVidia driver가 설치되었으나, 모니터 인식에 문제가 있어서 해상도 확장설정자체를 할 수 없습니다. 기본 ubuntu라서 driver 문제인가 확인하기 위해서 우분투 64bit 환경 NVIDIA...

우분투에서 성가신 자동 실행 처리

우분투운서비스는 종료된지 예전인데 script에 남아 있어서 항상 실행된다 apt-get 패키지가 제거되어도 etc/xdg/autostart 폴더에서 삭제해야 실행되지 않는다. /etc/xdg/autostart$ ls at-spi-dbus-bus.desktop              gnome-settings-daemon.desktop                print-applet.desktop bluetooth-applet-unity.desktop       gnome-sound-applet.desktop                   pulseaudio-kde.desktop bluetooth-applet.desktop             gnome-user-share.desktop                     pulseaudio.desktop deja-dup-monitor.desktop             gsettings-data-convert.desktop               telepathy-indicator.desktop gdu-notification-daemon.desktop      gwibber.desktop                             ...

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...