ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Ollama + Python 을 이용해 데이터 분석 시작하기.
    나도 궁금해서 해봄 2024. 1. 26. 15:46
    반응형

    올라마 블로그에서 Python, JavaScript 라이브러리를 공개했다. FastAPI를 붙여서 로컬에서 처리하려고 하던차에 의욕을 상실하고 ChatGPT 와 Copilot 을 열심히 사용중이었는데 잘됐다! 생각하고 바로 시작했다.

     

    https://ollama.ai/blog/python-javascript-libraries

     

    Python & JavaScript Libraries · Ollama Blog

    The initial versions of the Ollama Python and JavaScript libraries are now available, making it easy to integrate your Python or JavaScript, or Typescript app with Ollama in a few lines of code. Both libraries include all the features of the Ollama REST AP

    ollama.ai

     

    Python 은 pip, JavaScript는 npm 을 통해 간단하게 설치가 가능했다. (이렇게 쉬워도 되는 거냐고!) 

    해당 페이지 접근이 귀찮으신 분들을 위해 기왕 들어오신거 여기에서 내용을 추가하겠다.

     

    Python 라이브러리 설치법

    pip install ollama

     

    기본적으로 제공되는 샘플 소스는 아래와 같으며 사용중인 랩탑외에 설치를 해두고 사용중이라면 ollama.Client(host="호스트") 를 통해 변경을 해주면 된다.

     

    import ollama
    response = ollama.chat(model='llama2', messages=[
      {
        'role': 'user',
        'content': 'Why is the sky blue?',
      },
    ])
    print(response['message']['content'])

     

    이렇게 하고 실행하면 ollama 로컬 서버에서 열심히 동작을 한다.

    Ollama sample response screenshot

     

    현재 컴퓨터에 깔려있는 모델은 mistral 이고 아래내용으로 응답된다.

    The color of the sky appears blue due to a natural phenomenon called Rayleigh scattering. When the sun's rays reach Earth's atmosphere, they get scattered in all directions by the gases and particles in the air. Blue light gets scattered more easily than other colors because it has a shorter wavelength. As a result, when we look up at the sky, we predominantly see the blue light that got scattered, making the sky appear blue to our eyes.

     

    샘플을 구동하면 우리가 일반적으로 보던 형태로 응답받지 않고 생성이 완료된 형태를 받기 때문에 오랜시간을 기다려야 한다. 이럴 경우를 대비하기 위해 스트림(Stream)방식을 지원하며 앞서 작업했던 샘플을 아래처럼 변경하면 동작한다.

     

    import ollama
    messages=[
      {
        'role': 'user',
        'content': 'Why is the sky blue?',
      },
    ]
    for chunk in ollama.chat('mistral', messages=messages, stream=True):
      print(chunk['message']['content'], end='', flush=True)

     

    로컬 파일을 파이썬으로 읽어 전달 할 수 있는데 엑셀이나 CSV같은 경우는 pandas를 이용해 데이터프레임을 바로 넘겨주는 식으로 처리해도 동작했다.

     

    import ollama
    import pandas as pd
    
    boxSizeData = pd.read_table("box_size.csv", sep=",")
    stuff_in_string = f"Read the underlying data\r\n{boxSizeData}\r\nPlease tell me 우체국박스1호 size."
    
    response = ollama.chat(model='mistral', messages=[
        {
            'role': 'user',
            'content': stuff_in_string,
        },
    ])
    print(response['message']['content'])

     

    이미지나 파일등은 파이썬의 File을 읽어 전달하는 방식으로 처리가 가능했다.

     

    with open('image.png', 'rb') as file:
      response = ollama.chat(
        model='llava',
        messages=[
          {
            'role': 'user',
            'content': 'What is strange about this image?',
            'images': [file.read()],
          },
        ],
      )
    print(response['message']['content'])

     

     

    또한 텍스트 완성(text-completion) 기능을 사용 할 수 있었는데 예제를 사용해본 결과 C 언어로 사용가능한 결과물을 제공해주었다.

    import ollama
    
    result = ollama.generate(
      model='mistral',
      prompt='// A c function to reverse a string\n',
    )
    print(result['response'])

     

    결과물

    Here's an example of a C function that reverses a string:
    
    ```c
    #include <stdio.h>
    #include <string.h>
    
    // Function to reverse a given string
    void reverseString(char *str, int start, int end) {
      char temp;
    
      while (start < end) {
        // Swap characters at start and end positions
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;
    
        ++start;
        --end;
      }
    }
    
    // Function to reverse a string
    void reverse(char *str) {
      int len = strlen(str);
      reverseString(str, 0, len - 1);
    }
    
    int main() {
      char str[50];
      printf("Enter a string: ");
      scanf("%s", str);
    
      // Reverse the given string
      reverse(str);
    
      printf("Reversed string: %s\n", str);
      return 0;
    }
    ```
    
    The `reverseString()` function takes a pointer to the character array, an initial index (`start`) and an ending index (`end`). It swaps characters at the start and end positions until they meet in the middle. The `reverse()` function simply calls the `reverseString()` function with the given string as its argument. In the `main()` function, we take a string input from the user and reverse it using the provided functions.

     

    그 외에 사용자가 정의한 모델을 만들어 낼 수 있었고 이걸 활용해서 나만의 학습을 시킨 결과물을 계속해서 파생시킬 수 있을 거라 보였다.

     

    반응형
Designed by Tistory.