본문 바로가기
AI 딥러닝/DLA

[LLM] Ollama 모델에서 OpenAI Chat API 사용하기

by 깊은대학 2025. 2. 15.

Ollama에서도 OpenAI의 chat completions API를 사용할 수 있게 되어서 OpenAI용으로 구축된 기존 툴을 Ollam를 통해 이용할 수 있다.

기존의 Ollama 파이썬 라이브러리를 이용하는 방법과 OpenAI의 client.chat.completions.create()를이용하는 방법을 비교해 보기 위하여 Llama3.2:3B에게 피보나치(Fibonacci) 수열을 생성하는 파이썬 함수를 코딩해 보라고 했다. 먼저 파이썬 라이브러리를 이용하는 방법은 다음과 같다.

 

import ollama

response = ollama.chat(
    model="llama3.2:3b",
    #model = 'deepseek-r1:8b',
    messages=[
        {
            "role": "system",
            "content": "You are a python expert."
        },
        {
            "role": "user",
            "content": "Code a Python function to generate a Fibonacci sequence."
               
        }
    ])
print(response['message']['content'])

 

다음은 OpenAI의 client.chat.completions.create()를 이용하는 방법이다.

 

from openai import OpenAI

client = OpenAI(
    base_url = 'http://localhost:11434/v1',
    api_key='ollama', 
)

response = client.chat.completions.create(
    model="llama3.2:3b",
    #model = 'deepseek-r1:8b',
    messages=[
        {
            "role": "system",
            "content": [
            {
                "type": "text",
                "text": "You are a python expert."
            }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                "type": "text",
                "text":  "Code a Python function to generate a Fibonacci sequence."
                }
            ]
        }
    ],
)
result = response.choices[0].message.content
print(result)

 

만약 Llama를 OpenAI의 gpt-4o 모델로 바꾸려면 다음과 같이 위 코드에서 앞부분만 수정하면 된다.

 

from openai import OpenAI

from dotenv import load_dotenv
load_dotenv()

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o",

 

참고로 messages 파라미터는 주요 입력으로서 'role'과 'content'라는 두 가지 정보로 구성된다. 이 예제에서는 두 가지 고유한 역할이 있음을 알 수 있다 (실제로는 assistant 포함 세 가지 역할이 있다).

"role": "system": system 역할은 'content'의 내용대로 LLM의 동작을 설정하는 것이다. content의 내용을 수정하여 행동과 성격을 변경할 수 있다.

"role": "user": user 역할은 'content' 를 통해 사용자가 LLM에게 질의하거나 메시지를 전달하는 것이다.

"role": "assistant": assistant는 LLM 의 응답이다.

다음은 Llama3.2가 짜준 파이썬 코드다.

 

import math

def fibonacci_binet(n):
    """
    Generate the first n numbers in the Fibonacci sequence using Binet's formula.

    Args:
        n (int): The number of Fibonacci numbers to generate.

    Returns:
        list: A list of the first n Fibonacci numbers.
    """

    # Handle edge cases where n is 0 or less
    if n <= 0:
        return []

    # Define constants
    sqrt_5 = math.sqrt(5)

    # Initialize the Fibonacci sequence with the first two numbers
    fib_sequence = [0, 1]

    # Generate the rest of the Fibonacci sequence using Binet's formula
    for i in range(2, n):
        phi = (1 + sqrt_5) / 2
        psi = (1 - sqrt_5) / 2
        next_number = int((phi ** i - psi ** i) / sqrt_5)
        fib_sequence.append(next_number)

    return fib_sequence

 

다음은 gpt-4o가 짜준 파이썬 코드다.

 

def generate_fibonacci_sequence(n):
    if n <= 0:
        return []

    # Initialize the sequence with the first two Fibonacci numbers
    fibonacci_sequence = [0, 1]

    # Generate the sequence up to the nth term
    while len(fibonacci_sequence) < n:
        next_value = fibonacci_sequence[-1] + fibonacci_sequence[-2]
        fibonacci_sequence.append(next_value)

    return fibonacci_sequence[:n]

 

참고로 deepseek-r1:8B 가 짜준 코드는 아래와 같다.

 

def generate_fibonacci_sequence(n):
    if n < 0:
        return []
    fib = []
    if n >= 1:
        fib.append(0)
    if n >= 2:
        fib.append(1)
    for i in range(2, n):
        next_num = fib[i-1] + fib[i-2]
        fib.append(next_num)
    return fib

 

 

 

최근 Ollama 기반 llama3.2-vision 이 공개됐다. 11B와 90B 모델을 모두 사용할 수 있다. 그 중 11B의 성능을 테스트해 보기 위해서 아래와 같은 자동차 사진을 주고, 차종과 차량 번호를 알려달라고 했다.

 

 

import ollama
import os

img_path = "img/cha.png"
print(os.path.exists(img_path))

response = ollama.chat(
    model = 'llama3.2-vision',
    #model = 'deepseek-r1:8b',
    messages=[
        {
            "role": "user",
            "content": "사진 속 승용차의 차종과 번호를 알려줘.",
            "images": [img_path]
        }
    ]
)

print(response['message']['content'])

 

위 코드를 실행하면 다음과 같은 텍스트가 생성된다. 사진 내용을 아주 잘 설명하고 있다.

 

사진 속 차는 BMW 5 시리즈입니다. 차량 번호판은 19오 7777이며, 이 번호판은 대한민국에서 사용하는 번호판인 것으로 보입니다. 이 번호판은 2016년부터 적용된 새로운 형식의 번호판으로, 차종 정보를 담고 있습니다. 사진 속 차는 BMW 5 시리즈 중 하나로, 사진의 일부만 나타나기에 정확한 차종을 파악하기 어려우므로, 이에 대한 명확한 답변을 내리기 어렵습니다. 그러나 BMW 5 시리즈 중에서 가장 많이 팔리는 것은 G30으로, 사진 속 차와 비슷한 디자인과 형태를 가지고 있습니다. 또한 번호판의 뒤판이 없고, 앞면에만 표시되어 있는 점을 볼 때, 사진 속 차는 경차가 아닌 일반 자동차로 보입니다.

 

딥시크는 어떻게 설명할 지 궁금해서 시도해 보았는데 결과는 다음과 같이 엉망이다.

 

Alright, the user provided an image with a luxury sedan and asked for its model and number. I can't view images, so I need to think about how to respond. I should acknowledge that I can't see the image and ask them to describe or provide more details. Maybe they can give the brand logo, specific features, or any unique characteristics. I'll make sure my response is helpful and guides them to provide enough information for me to identify the car accurately. 이미지를 확인할 수 없습니다. 차종과 번호를 알려드리기 위해 이미지에 대한 더 많은 정보를 필요로 합니다. 차의 브랜드 로고, 특정特徴,或者其他 유용한 정보를 제공해주세요. 이 way I can help identify the car and its model number accurately.

 

다음은 Ollama OpenAI 호환성과 Ollama python library의 다양한 사용 예제가 있는 사이트다.

 

https://ollama.com/blog/openai-compatibility

 

https://github.com/ollama/ollama-python

 

댓글