▶ ChatGPT

출처: https://www.nature.com/immersive/d41586-023-03919-1

 

국제학술지 '네이처(Nature)'에서 올 한 해 과학계에 큰 화제를 불러일으킨 10명의 인물을 선정하는 '네이처 10(Nature's 10)'을 발표했는데, 역대 최초로 인간이 아닌 생성형 인공지능(AI) 챗봇 '챗GPT(ChatGPT)'를 포함시켰다.

 

ChatGPT라고는 하지만, 크게 바라보면 '생성형 인공지능' 자체가 우리 생활에 정말 큰 영향을 미치게 된 것이다.

지금은 시작일 것이다. 앞으로는 정말 생활 이곳 저곳에서 우리와 함께하게 될 것이다.

 

▶ RAG

 

ChatGPT는 정말 대단한 기능 및 성능을 보여주고 있지만, 한계점도 분명히 있다.

 

일단 ChatGPT가 이것 저것 골고루 많이 아는 똑똑한 아이이긴 하지만,

특정 분야에 대해서 전문적인 지식을 갖고 있다고 하기에는 조금 부족하다.

 

그리고 최신 정보를 알지 못한다는 점도 있고 장기 기억을 유지하기에 어렵다는 점도 있고,

할루시네이션(Hallucination)과 같은 문제도 있는 등

 

ChatGPT는 여러가지 한계점이 분명히 있고 이러한 한계점을 다양한 방법으로 해결하고자 발전하고 있다.

 

이러한 ChatGPT의 한계점을 극복하는 방법 중 하나로

RAG(Retrieval-Augmented Generation, 검색 증강 생성)이라는 것이 최근 엄청난 화두가 되고 있다.

 

출처: https://docs.aws.amazon.com/sagemaker/latest/dg/jumpstart-foundation-models-customize-rag.html

 

위 그림에서 오른쪽 위를 잘 살펴보기 바란다.

'Knowledge Source'를 별도로 구성하고 이를 일종의 보조 기억장치처럼 사용하는 것이다.

 

어?! 뭔가 떠오르지 않는가!?

그렇다!!! 바로 "데이터베이스(Database)"이다.

 

▶ Embedding

ChatGPT의 경우 기본적으로 사용되는 데이터는 '자연어(Natural Language)'이다.

 

이러한 자연어를 문자 그대로 사용한다고 하면 그 안에 담겨있는 의미나 가치를 다루기가 어렵기 때문에

단어 또는 문장들을 다른 방식으로 표현을 해야하는데

현재 가장 보편적인 표현 방식이 바로 'Vector Embedding'이다.

 

출처: https://www.pinecone.io/learn/vector-embeddings/

 

Vector 형식으로 데이터가 저장이 되기 때문에

Vector 연산을 통해 검색을 한다거나 "king + queen = princess or prince"와 같은 연산도 가능하게 된다.

 

이제 이렇게 임베딩된 데이터들을 데이터베이스에 저장해놓고 쿼리를 해서 사용을 하면 되는데,

PostgreSQL이나 MySQL과 같은 기존 RDB를 이용하기에는 좀 어려움과 불편함이 한 가득이다.

 

▶ Vector Database

그렇다. 말 그대로 Vector 데이터들을 저장하고 제공하는데에 특화된 데이터베이스이다.

예전에도 있었던 데이터베이스 유형이지만, 최근 AI 시대가 되면서 엄청난 대박이 났다.

 

출처: https://techcrunch.com/2023/04/27/pinecone-drops-100m-investment-on-750m-valuation-as-vector-database-demand-grows/?utm_source=oneoneone

 

2021년도에 출시된 Pinecone은 1억 달러 규모의 시리즈 B 투자를 받았다고 한다. 기업 가치는 무려 7억 5천만 달러.

그 외에도 Weaviate, Chroma, Qdrant 等 다양한 Vector Database들이 모두 다 많은 투자를 받았다.

 

이렇게 돈이 쏠린다는 것은 이 분야에 대해서 많은 분들이 성공할거라 믿는다라는 의미일 것이고

그렇다면 우리는 이 부분에 대해서 공부해볼 가치가 충분히 있다!!!

 

▶ Pinecone

최근 가장 많은 인기를 얻고 있는(돈을 투자 받은?!) Pinecone에 대해서 알아보자.

 

출처: https://www.pinecone.io/

 

비용은 어떻게 될까!? (너무 돈! 돈! 하는 것 같아서 조금 그렇지만... 현실이... ^^)

 

출처: https://www.pinecone.io/pricing/

 

비용 부분을 살펴보면서 눈치 챘어야 한다.

그렇다! Pinecone은 On-Premise 형태로 제공되지 않는다. 무조건 SaaS 이다!

그나마 다행인 것은 Free 제공 부분이 있다는 점! ^^

 

출처:  https://www.pinecone.io/

 

Sign-Up은 편하게 되어있다.

 

출처:  https://www.pinecone.io/

 

무료 요금제에서는 Index 1개를 사용할 수 있다.

기존 RDB에서 table 정도로 생각하면 될 것 같다.

 

출처:  https://www.pinecone.io/

 

Python을 이용해서 접근하기 위해서는 API Key 값을 알아야 한다.

왼쪽 메뉴탭에서 'API Keys'를 눌러보면 하나 이미 만들어진 것을 확인할 수 있다.

 

출처:  https://www.pinecone.io/

 

▶ Hello-whatwant

이제 Pinecone을 사용해보자.

 

출처: https://www.pinecone.io/learn/vector-database/

 

Knowledge를 임베딩해서 저장을 하고,

질문을 다시 임베딩해서 쿼리를 던지면 그와 유사도가 높은 것들을 답해주는 과정을 해보고자 한다.

 

기본적인 간단한 workflow이지만, 그래도 다음의 두 가지 사항은 미리 확인/준비 해야 한다.

 

① Python에서 Pinecone을 사용하기 위한 방법

② Embedding Model 선정 및 사용 방법

 

 

 Python에서 Pinecone을 사용하기 위한 방법

  - 앞에서 이미 Pinecone API Key 및 Env 값은 확보(?)했으니 이 부분은 Pass

  - 그리고, 친절하게도 Pinecone 라이브러리를 제공해주니 이를 사용하면 OK

    . https://docs.pinecone.io/docs/quickstart

 

> pip install pinecone-client

 

② Embedding Model 선정 및 사용 방법

  - 이 부분은 정해진 것이 없기에 필요에 따라 각자의 취향/상황에 맞춰서 하면 된다.

    . 지금은 보통 적은 리소스로 괜찮은 성능을 보여준다고 하는 all-MiniLM-L6-v2 모델을 사용해보겠다.

 

출처: https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2

 

 

이제 코드로 풀어보자.

설명을 위해 Colab 환경에서 진행한 내용으로 진행하겠다.

  - https://colab.research.google.com/

 

Colab

 

CPU 환경에서도 실행 가능하긴 하지만, 이왕이면 GPU 환경이 빠르니... 선택하자.

 

 

pinecone-client, sentence-transformer 2개의 패키지 설치가 필요하다.

 

 

앞에서 확인한 pinecone API key 값 및 Env 값을 넣어주면 된다.

warning은 가뿐히 무시하자 ^^

 

 

굳이 torch를 import까지 할 것은 아닌 것 같아서 주석처리했고 ^^

all-MiniLM-L6-v2 모델을 불러왔는데, 출력된 내역을 보면 간단하게나마 spec을 확인할 수 있다.

 

잠시 현재 Pinecone의 Index 상태를 살펴보자면 다음과 같이 아무 것도 없다.

 

 

그러면, 우리는 Index를 하나 만들어보자.

 

 

이렇게 만들면 Pinecone에서는 다음과 같이 결과가 보인다.

 

 

내용물을 살펴보면 다음과 같이 아무 것도 없다 ^^

 

 

테스트하기 위해 넣어줄 데이터는 ChatGPT로 만들어봤다.

프로그래밍 언어를 한 문장으로 정리해달라고 했다.

 

출처: ChatGPT

 

입력을 열심히 해주면 된다.

 

 

그 다음에는 Pinecone으로 넣어줄 형태로 변환을 해야 한다.

'일련번호, 임베딩된 내용, 원본 내용'의 조합으로 생각하면 된다.

 

 

준비가 되었으면 upsert 해주면 된다.

upsert가 뭐냐고? update or insert !!!

 

 

Pinecone에서 확인해보자.

 

 

Pinecone의 상태를 직접 확인해볼 수도 있다.

 

 

query를 요청할 용도의 function을 하나 만들어 보자.

 

 

이제 질문을 해보자.

 

 

잘 나온다 !!!

다른 식으로 질문을 해볼까?

 

 

잘 찾아준다 !!!

 

 

여기까지~~~~ ^^

반응형

알고리즘을 구현하기 위한 소스 코드의 소요 시간(실행에 필요한 시간)은 어떻게 측정할 수 있을까?

 

출처: chatgpt

 

 

실행을 시켜서 완료될 때 까지 걸린 시간을 측정하면 될까?

 

실행하는 컴퓨터의 CPU가 무엇인지, HDD 또는 SSD를 사용하는 지와 같은 여러 상황에 따라서

똑같은 알고리즘도 시간이 다르게 나올 수 있을텐데...

 

그리고 작성하는 프로그래밍 언어에 따라서도 실행 시간은 천차만별일 수 있다.

 

즉, 실제 시간을 측정해서 알고리즘의 성능을 비교 평가하는 것은 어렵다.

 

 

그래서, 보통은 Pseudo code의 라인별 수행하는 횟수를 카운트 하는 방식으로 소요 시간을 측정한다.

 

 

Insertion sort의 pseudo code는 다음과 같다.

 

insertion pseudo code

 

한 줄씩 살펴보자.

 

line #1

 

입력값 A의 길이가 n이라고 해보자.

보통의 프로그래밍 언어에서 배열은 0부터 시작하지만 pseudo code에서는 1부터 시작한다.

그러면 1번 라인은 총 몇 번 수행이 될까?!

 

지금 대답을 하지 못하는 분은 개발자로서 조금 문제가 있는 상태이고 (^^)

"n - 1"번이라고 대답하신 분은 보통의 개발자 수준이고

"n"번이라고 대답하신 분은 정말 훌륭한 개발자 이거나 아니면 운으로 맞춘 분일 것이다 ^^

 

"j = 2"라고 되어 있기에 for문 자체는 "n - 1"번 수행한다고 말하는 것이 일반적이지만

실제 for문 자체는 마지막 조건 체크를 위해 한 번 더 수행을 하기 때문에 "n - 1 + 1"번 수행을 하게 된다.

하지만, 그냥 "n - 1"번 수행한다고 해도 무방하지 싶다.

 

line #2 ~ #4

 

2번 ~ 4번 라인은 각각 "n - 1"번 수행한다.

 

line #5 ~ #7

 

5번 ~ 7번 라인이 핵심인데...

처음 "j = 2" 상황에서는 1번 위치에 있는 값하고만 비교하면 되기에 1번만 실행이 될 것이고,

그다음 "j = 3" 상황에서는 2번 위치하고 비교하고 그 다음 1번 위치하고 비교를 하게 된다.

그렇게 해서 "j = A.length" 상황에 되면, 즉 "j = n" 상황이 되면 "n - 1"번 비교를 하게 된다.

이걸 그림으로 표현해보면 아래와 같다.

 

while문 상황

 

그래서, while문이 있는 5번 라인은 "1 + 2 + 3 + ... + n"번 실행을 하게 되고 (값 비교를 위해 한 번 더)

6번, 7번 라인은 "1 + 2 + 3 + ... + (n -1)"번 실행을 하게 된다.

 

line #8

 

8번 라인은 당연히 "n - 1"번 수행한다.

 

 

잘 이해가 되시나요?!

여기에서 "예"라고 대답을 하신 분은 .... No! No!! No!!!

 

중간에서 끝

 

8번째 값을 정렬할 차례가 와서

첫번째로 7번 위치랑 비교 =  pass, 6번 위치 비교 = pass

5번 위치랑 비교했더니 여기에서 break

 

8번째 값을 정렬할 때에는 7번의 비교가 필요한 줄 알았는데,

실제 입력값 상황에 따라 수행 횟수가 가변적이다.

 

그래서 이를 t변수를 이용해서 표현한다고 하면, 전체적으로 다음과 같이 정리해볼 수 있다.

 

running time

 

C 변수는 각 라인을 실행할 때 드는 비용(시간)을 의미한다.

그래서 위 내용을 정리해서 총 실행 시간은 다음과 같이 정리할 수 있다.

 

The sum of product of cost and times of each line

 

여기에서 뭔가 답답하게 만드는 것이 t 변수 값인데,

best/average/worst case에 따라서 값이 달라질 수가 있다.

 

best / worst cases

 

위 그림에서 왼쪽이 best case이고, 오른쪽은 worst case이다.

다시 말해 이미 정렬이 되어 있는 경우는 best case이고, 역으로 정렬된 경우가 worst case이다.

 

best case에 대해서 정리해보면 다음과 같다.

 

best case

 

결론적으로는 an + b 형식의 식으로 나오고 이는 선형적인 모습을 보인다.

 

이번에는 worst case를 살펴보자.

 

worst case

 

정리된 식을 살펴보면,

worst case는 an^2 + bn + c 와 같은 2차 함수 형태로 나타난다.

 

 

best case는 입력값 n의 크기가 커짐에 따라 선형적으로 실행 시간이 증가하게 되고

worst case는 입력값 n의 크기가 커짐에 따라 제곱으로 증가하게 된다는 것을 알 수 있다.

 

 

그런데, 모든 알고리즘들에 대해서 이렇게 분석하는 것은 너무 어렵다.

이와 같은 과정을 뭔가 단순하면서 명확하게 표현하는 것에 대해서 알아보도록 하자.

지금 말고 다음에.... ^^

반응형

Youtube를 보다가 갑작스레 보게 된 재미난 영상 하나가 있었다.

 

출처: https://www.youtube.com/watch?v=y-xopqwEe3I&t=13s&ab_channel=GoogleforDevelopers

 

으잉?! IT 뉴스를 이런 감성으로 전달한다고!?

위 영상의 출처는 다음과 같다.

  - https://www.youtube.com/@GoogleDevelopers

 

출처: https://www.youtube.com/@GoogleDevelopers

 

여기에서 특히 재미있는 것은 "Google Developer News tl;dr"인데,

Web, Mobile, AI, Cloud 관련 소식들을 정말 깔끔하고 재미있게 소개해주고 있다.

 

지루하고 어렵지 않냐고!?

영상에서는 정말 간략하고 핵심적인 내용만 소개하고 자세한 소식은 각자 찾아볼 수 있도록 링크로 제공해준다.

 

출처: https://www.youtube.com/watch?v=coZ6VVJZ2R0&ab_channel=GoogleforDevelopers

 

구글 관련된 소식만 알려주는 것 아니냐고!?

뭐 맞는 말이긴 한데.... 개발자 세상에서 Google이 관여 안된 것을 찾는 것이 더 어렵지 않을까!?

출처: https://www.youtube.com/watch?v=coZ6VVJZ2R0&ab_channel=GoogleforDevelopers

 

TensorFlow도 Google 거다. (이거 모르는 사람 많지 않나!? 나만 몰랐나?! ^^)

Chrome에서 3rd-party Cookie 지원을 24년 1분기부터 순차적으로 종료할건데, 웹 개발하는 사람 모두 알아야 하지 않나!?

AWS를 더 많이 쓰긴 하지만, GCP 기반으로 개발하는 사람들도 많지 않나!?

 

뭐, 구글 소식만 알아도 훌륭한 개발자이지 않을까 한다 ^^

 

그러니, 구독과 좋아요~..... ^^

(Google에서 따로 후원 받지 않았습니다!!!! 아! 애드센스..... 받은건가?????)

 

영어가 부담스러우면 자동 번역하면 되니까 부담 없이 구독해서 정보를 얻으면 좋을 것 같다.

 

한글 좋아하는 저같은 개발자들을 위해 추가적으로 공유하자면

한국 개발자를 위한 블로그도 별도로 운영되고 있다. 최신 업데이트도 꾸준히 되고 있다.

  - https://developers-kr.googleblog.com/

 

출처: https://developers-kr.googleblog.com/

 

한국 개발자를 위한 페이스북도 운영하고 있다.

  - https://www.facebook.com/googlefordevskr/

 

출처: https://www.facebook.com/googlefordevskr/

 

한국 개발자들을 위한 공식 사이트는 다음과 같다.

  - https://sites.google.com/view/gdeveloperskorea/홈

 

출처: https://sites.google.com/view/gdeveloperskorea/홈

 

국내에서는 공식적으로 14개 GDG(Google Developer Groups)가 굴러가고 있는데,

최근에는 GDG SongDo가 이벤트도 많이 하면서 활발한 것 같다.

 

Google for Developers Korea의 공식 유튜브 채널도 있긴한데, 최근 업데이트는 잘 안되고 있다.

  - https://www.youtube.com/channel/UCZU3wmgRuH9gc2E3jhvEE_g

 

출처: https://www.youtube.com/channel/UCZU3wmgRuH9gc2E3jhvEE_g

 

이 글을 포스팅하는 시점에서 유용한 정보 하나 더!

Devfest Cloud 2023이 23년 12월 9일에 있다.

  - https://festa.io/events/4385?fbclid=IwAR12BFTRSFTI9LUbLd8eclbtvm_jIAJ82reVs-8mbECKtWTdzbeuKRoVtnw

 

출처: https://festa.io/

 

개발자 여러분들에게 조금이나마 도움이 되기를 기원해보며 포스팅합니다!!!

반응형

'Programming' 카테고리의 다른 글

개발자들을 위한 AI 검색엔진 - phind  (0) 2023.04.30

이제와서 왠 알고리즘 !? ^^

나름의 이유로 알고리즘을 차분히 조금은 깊게 살펴볼 이유가 있어서 정리를 해보고자 한다.

 

우선 알고리즘에서 가장 대표적인 문제 유형은 바로 정렬(sort)이다.

크기가 다른 여러 개의 입력값이 있을 때, 이를 크기 순서대로 줄을 세워야 하는 문제이다.

 

<made by ChatGPT>

 

정렬 문제(Sorting Problem)를 해결할 수 있는 알고리즘(Algorithm)은 상당히 다양한데,

그 중에서 가장 첫번째로 언급되는 것이 바로 '삽입 정렬(Insertion Sort)'이다.

 

삽입 정렬을 한 번에 확인하기 위한 가장 좋은 예시는

위키피디아에서 보여주는 에니메이션이다.

<출처: https://en.wikipedia.org/wiki/Insertion_sort>

 

찬찬히 잘 살펴보면 어떻게 하겠다라는 것인지 충분히 이해할 수 있겠지만

그래도 좀 더 설명을 해보자면 다음과 같다.

 

<출처: https://www.whatwant.com>

 

6번째까지 정렬이 된 상태에서 (1, 3, 5, 6, 7, 8), 7번째 '2' 순서가 되었을 때를 설명해보려고 한다.

일단, 자기 자신의 앞에 있는 '8'과 비교했더니 나(2)보다 큰 값이기에 '8'을 한 칸 앞으로 옮긴다.

그 다음에는 하나 더 앞에 있는 '7'과 비교를 하고 옮기고 ... 그렇게 진행하다가

'1'을 만나게 되는데, 이번에는 '2'보다 작은 값이기에 자기 자신(2)이 '1' 뒤에 위치하면 된다.

 

'Pseudo Code'는 다음과 같다.

 
 for j = 2 to A.length
     key = A[j]
     i = j - 1
     while i > 0 and A[i] > key
         A[i+1] = A[i]
         i = i - 1
     A[i+1] = key
 

 

2번째 입력값부터 시작해서 마지막 입력까지 수행을 해야 하는 것이고

기준이 되는 값을 일단 'key'에 저장해놓고,

key랑 비교를 시작할 위치는 key보다 하나 앞선 값이다.

이제 앞에 있는 값들과 비교를 해보고 비교한 값이 크면 비교한 값을 뒤로 한 칸 옮기고

같거나 작으면 비교를 멈추고 거기에 key값을 넣어주면 된다.

 

Python으로 작성해본 코드는 다음과 같다.

Pseudo code와 거의 동일하다.

 
def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and key < arr[j]:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
 
    return arr

numbers = [6, 5, 3, 1, 8, 7, 2, 4]
sorted_numbers = insertion_sort(numbers)
print(sorted_numbers)
 

 

뭐 당연히 결과는 잘 나온다.

 

 

자~ 이제 시작이다.

살펴봐야할 많은 것들이 있다.

 

과연 이 알고리즘은 얼마의 시간이 걸릴 것이며, 얼마의 메모리가 필요하고,

Best Case일 때와 Worst Case일 때 어떻게 되는지를 살펴봐야 한다.

거기에다가 하나 더 알아봐야 할 것은 입력값들의 순서가 유지되는지에 대해서도 알아봐야 한다.

 

하지만, 벌써부터 지칠 수 있으니

다음 기회로.... ^^ (절대 귀찮아서 미루는 것이 아니다! 절대로! 절대로?)

 

반응형

집에서 문득 인터넷이 느리다고 느껴지면

갑자기 우리집 통신사 서비스 품질이 낮아진 것이 아닌지 의심이 들곤 한다.

 

그럴 때 사용해볼만한 네트워크(인터넷) 속도 측정 사이트들을 알아보자.

아! 별도의 설치 없이 웹브라우저만으로 사용가능한 사이트만 리스팅했다.

 

 

1. 클라우드플레어

   - IT에 종사하는 분들이 아니라면 모르실 수도 있지만,

     CDN/DNS 서비스 분야에 있어서는 전세계의 1/5 이상이 사용하고 있다는 클라우드플레어의 속도 측정 서비스

   - 규모가 있기에 당연히 우리나라에도 데이터센터가 있다.

   - https://speed.cloudflare.com/

 

 

2. 넷플릭스

   - 넷플릭스 고객들이 OTT 스트리밍을 받아야 하기에 이와 관련하여 운영하는 서비스

   - 결과가 너무 심플해보일 수도 있는데, 상세 정보 보기를 선택하면 조금 더 자세한 정보 확인 가능

   - https://fast.com/ko/

 

 

3. OOKLA

   - 미국 회사로써 웹 테스트 및 네트워크 진단 관련 업체에서 제공하는 서비스

   - 인터넷 서비스 제공 업체가 아니기에 조금 더 신뢰할 수 있을 거라 기대

   - 광고 때문에 조금 지저분해 보이기는 함

   - https://www.speedtest.net/

 

 

4. Google

   - 구글도 구글파이버라는 이름으로 인터넷서비스 사업을 하고 있고, 그래서 운영하는 서비스

   - 아마도 미국에서만 서비스를 하고 있기에 측정 결과가 좀 낮게 나오는 것으로 추정

   - https://fiber.google.com/speedtest/

 

 

5. OpenSpeedTest

   - HTML5를 이용한 네트워크 스피드 테스트를 하는 서비스

   - 다양한 디바이스를 모두 지원

   - https://openspeedtest.com/

 

 

6. 벤치비

   - 인터넷 속도 측정을 하는데에 있어서 빼놓지 못하는 벤치비 (아재 인증?)

   - http://speed.benchbee.co.kr/

 

 

7. Etrality GmbH

   - 주로 모바일 앱으로 인터넷 속도 측정 어플을 개발하는 것으로 여겨지는 업체

   - https://www.speedcheck.org/

 

 

이 정도로 측정하면 어느 정도 추세는 충분히 파악할 수 있을 것 같다.

반응형

얼마전 회사에서 일을 하다가 우연히(?) 사용하게 된 "Base64"에 대해서 알아보고자 한다.

 

처음에는 암호화(encryption)를 한다고 생각했었다가 엄청 큰일 날뻔해서

더더욱 그 정체에 대해서 명확하게 파악해야겠다고 생각했었는데... 게으름에 이제서야 정리해본다.

 

 

▶ RFC 4648

base64는 base16, base32와 함께 2006년도에 'RFC 4648'에서 정의가 되어 있다.

https://datatracker.ietf.org/doc/html/rfc4648

RFC 4648

 

- RFC (Request for Comments)

   : 컴퓨터 네트워크 공학 등에서 인터넷 기술에 적용 가능한 새로운 연구, 혁신, 기법 등에 대한 문서

 

▶ base64

base16, base32도 있지만 여기에서는 base64에 대해서만 살펴보겠다.

그러면, base64에서 64는 무엇을 의미할까!?

 

하나의 코드로 encoding할 수 있는 문자가 64개라는 의미이다.

64 = 2^6 이므로 base64의 하나의 코드는 6비트의 데이터를 표현할 수 있는 것이다. (64진수로 생각하면 된다)

 

그러면 base64의 하나의 코드는 64종류를 어떤 기호로 구분할까!?

 

일단 base64는 ASCII 텍스트로 표현하는데, 아래와 같이 총 64종의 문자를 사용한다.

 - 문자 A-Z    = 26

 - 문자 a-z     = 26

 - 숫자 0-9     = 10

 - 기호 '+', '/'   = 2

 

▶ Sample

실제로 어떻게 되는지 돌려볼까!?

우리의 친구 python으로 한 번 해보자!

python

 

string(text)을 binary 형태로 변경 후 base64 encoding 하고,

base64 encoding 된 결과물이 binary 형태이므로 print하기 위해서 string 형태로 변환해서 출력한다.

 

binary 형태인 base64 encoding 된 결과물을 가지고 base64 decoding을 하고,

마찬가지로 print하기 위해 string 형태로 변환해서 출력한다.

 

실행결과는 다음과 같다.

result

 

▶ base64 encoding

base64 encoding 과정을 수작업으로 훑어보자.

일단 몇 가지 문자에 대해 ascii code 값을 알아보자.

 

symbol DEC HEX BIN
w 119 77 0111 0111
h 104 68 0110 1000
a 97 61 0110 0001
t 116 74 0111 0100

 

그러면 다음과 같이 나열이 된다.

 

w             h               a               t

01110111 01101000 01100001 01110100

 

base64이므로 6bit 단위로 그룹핑 하고, 이것을 다시 십진수로 변경하면 다음과 같다.

 

011101     110110    100001    100001    011101    00

29             54           33            33            29

 

이 값을 변환할 기준은 RFC 4648 문서에 있는 table을 참고해서 변환하면 된다.

The Base 64 Alphabet

 

그러면 다음과 같다.

 

29   54   33   33   29

d     2     h     h     d

 

Python으로 작업한 결과와 동일하게 나오는 것을 확인할 수 있다.

 

여기에서도 뒤에 6개로 떨어지지 않는 부분이 있는 것을 알 수 있는데,

이것은 padding 처리해서 '='로 표기하게 된다.

 

(그러면 실제로는 65개 문자를 사용하니 Base65라고 해야하는 것 아닌가?! ^^)

 

▶ Usage

서두에서도 말을 했지만 Base64를 encryption 용도로 착각하기 쉽다.

하지만, encoding 과정을 잘 살펴보면 느꼈을 수도 있을텐데

Base64의 주요 용도는 binary 형태의 파일을 text 형태로 표현하는데에 있다.

 

즉, HTML 페이지를 구성할 때 jpg와 같은 그림 파일을 링크 형태가 아니라

HTML 파일 안에 text 형태로 저장할 수도 있게 되는 것이다.

 

그리고, 자주 봤을 아주 유용한 사례를 보자면, URL에 데이터를 포함해서 던질 때이다.

 

- https://app.whatwant.com/push?data=xxxxxxx 

 

위와 같이 URL 형식으로 binay 파일 내용을 전달하고 싶은 경우

Base64 encoding을 통해 가능해진다 !!!

 

▶ Base64URL

여기에서 여러분은 질문을 해야 한다 !!!

 

Base64 encoding 결과물을 URL에 정말 사용해도 되나요?

특수문자 '+', '/'를 사용하는데, 문제가 없나요?

 

그렇다!!!

 

URL에서 '+'는 공백을 위해 사용되고, '/'는 폴더 구분 용도로 사용된다.

 

그래서 그 2개의 특수문자를 변경한 Base64URL encoding이 따로 있다.

- '+' → '-'

- '/' → '_'

 

나머지는 똑같다.

 

 

여기까지~~~~~!!!

 

반응형

AI를 이용한 코딩을 한다고 할 때, 제일 먼저 떠오르는 것은 GitHub의 Copilot이다.

개인적으로도 정말 애정하는 것이 바로 Copilot이다.

 

그러던 중, 요즘 많은 관심을 받고 있다는 'GPT Pilot'이라는 것을 알게 되었다.

응?! ChatGPT + Copilot ????

- https://github.com/Pythagora-io/gpt-pilot

GPT Pilot

 

타이틀만 보면 왠지 짝퉁 느낌이 많이 들지만, 사람들의 엄청난 관심을 받은 것을 보면 사짜는 아닌 것 같다 ^^

Star 숫자를 보면 거의 1만5천 ... 부럽다.

Fork, Star

 

정체를 설명한 글을 살펴보면

무려 개발 속도를 20배나 빠르게 해준단다!!!

20x faster

 

그런데, 설명을 보면 Copilot의 아류작이 아니라 Auto-GPT의 아류작인 것으로 보인다.

Copilot처럼 IDE Extension 방식으로 인터페이스 하는 것이 아니라 CLI 환경에서의 티키타카 방식이다.

 

그러면 이 프로젝트는 왜 만들어진 것일까? 목적이 무엇일까? 그리고 한계점을 무엇일까?

aim

 

GPT-4를 이용해서 개발자가 실무에서 얼마나 도움을 받을 수 있는지를 확인하고자 하는 목적이며,

결국 5% 정도는 개발자가 관여를 해야한다는 점을 밝히고 있다.

 

 

지금까지 배경에 대해서는 충분히 알아봤으니 일단 한 번 부딪혀보자 !!!

 

▶ Requirements

   - Python 3.9-3.12

   - PostgreSQL (선택 사항, 기본값은 SQLite)

 

티키타카를 하면서 진행을 하기 위해서는 진행되고 있는 내용을 기억해야할 저장소가 필요하기에 DB가 필수라고 한다.

 

① Python

   - 원하는 버전의 Python을 편하게 사용하려면 pyenv를 활용하는 것을 추천한다.

      . https://www.whatwant.com/entry/pyenv

❯ pyenv versions      
  system
* 3.8.16 (set by /home/chani22/.pyenv/version)

❯ pyenv install --list | grep 3.9.
...
  3.9.15
  3.9.16
...

❯ pyenv install 3.9.16
Downloading Python-3.9.16.tar.xz...
-> https://www.python.org/ftp/python/3.9.16/Python-3.9.16.tar.xz
Installing Python-3.9.16...

❯ pyenv global 3.9.16

❯ python --version  
Python 3.9.16

 

② PostgreSQL

   - 음... 기본값으로 SQLite를 사용하게 되어있으므로, 일단 빠른 진행을 위해 지금은 생략 ^^ (절대 귀찮아서가 아닙... ^^)

 

▶ install / clone

GPT Pilot 사용하기 위해 clone 및 설정을 진행해보자.

 

① clone

❯ git clone https://github.com/Pythagora-io/gpt-pilot.git
'gpt-pilot'에 복제합니다...

❯ cd gpt-pilot

 

② 필요 패키지 설치

❯ python -m venv pilot-env

❯ source pilot-env/bin/activate

❯ pip install -r requirements.txt

 

③  환경 파일 생성

❯ cd pilot

❯ mv .env.example .env

 

▶ Key 등록

OPENAI가 아닌 AZURE, OPENROUTER도 사용할 수 있다는데, 우린 그냥 OPENAI를 사용하는 것으로 하자.

- https://platform.openai.com/api-keys

API keys

 

새로 secret key를 생성해보자.

Create

 

생성된 key 복사 잘 해서 입력하고, 저장하자.

.env

 

▶ DB Init

사실 지금은 별게 없는데, 나중에 PostgreSQL을 사용하게 되면 보충해야할 영역인 것 같다.

❯ python db_init.py

 

▶ Start (#1)

일단 시작해보자.

Start #1

 

GPT 4 API를 사용할 수 없단다!

 

어!? 나는 유료 사용자인데?!

세금 포함해서 무려 22$를 지불하고 있는데, 이게 뭔 헛소리야!?

 

▶ GPT4 API

그동안 채팅만 했지 API를 사용하지를 않았더니.... 이런 무식한 상황이 ^^

결재 정보를 등록해야 GPT4 API를 사용할 수 있다.

- https://platform.openai.com/account/billing/payment-methods

Payment methods

 

Payment 정보를 등록하자.

Add payment details

 

"Add payment details"를 클릭하면 된다.

card info

 

최소 5$ 결제를 해야 한다.

치사한 XX

purchase

 

통장에 돈을 넣어놔야 뭔가 사용권을 주는 그런 느낌...

5$

 

사용할 수 있는 API들은 다음과 같이 확인할 수 있다.

- https://platform.openai.com/account/limits

limits

 

▶ Start (#2)

아까 에러난 상황에서 위와 같이 GPT4 API를 사용할 수 있게 해놓고

이어서 시작하려고 하면 ... 그래도 안된다.

 

시간이 좀 지나면 되는 걸 수도 있지만 잘 안되어서 사용하던 터미널 종료 하고

secret key 재발급 받고, .env 파일에 다시 입력한 뒤에 다음과 같이 다시 진입하였다.

 

❯ cd /path/gpt-pilot   # gpt-pilot 루트 경로

❯ source pilot-env/bin/activate

❯ cd pilot

❯ python main.py

 

만들어보고자 하는 사례는 "GitHub 관련 뉴스를 수집해서 보여주는 웹페이지"로 해봤다.

 

❯ python main.py

------------------ STARTING NEW PROJECT ----------------------
If you wish to continue with this project in future run:
python main.py app_id=448522d6-d6d2-4fe3-be2b-33c731dac5eb
--------------------------------------------------------------

? What is the project name? GitHub_News


? Describe your app in as much detail as possible. Develop a webpage that aggregates and displays news about GitHub.

? Which platforms do you want to support with this application: web, mobile or both? web

? Does the content need to be updated in real-time? Or is a daily/weekly update sufficient? daily

? Do you have specific sources in mind that the application should scrape for GitHub news or should it search widely across the internet? no

? Do you want to include a user login system or should the webpage be publicly accessible to anyone without login? no

{"technologies": ["Node.js", "MongoDB", "Mongoose", "Bootstrap", "Javascript", "cronjob", "Socket.io"]}

? Please set up your local environment so that the technologies listed can be utilized. When you're done, write "DONE" 

 

물어보는 것에 대답을 해주면 된다.

그런데 ...

 

...

🚀 Now for the actual development...

Implementing task #1:  Setup Node.js server

To complete task one, let's outline the steps necessary. We need to:

1. Initialize NPM and download the necessary packages. 
2. Build a basic Express app and put it in server.js.

**Step 1: Initialize NPM and download necessary packages.**

To initialize NPM in your current directory and fetch necessary libraries, run the following commands in your terminal:

```
npm init -y
npm install express
```

...

--------- EXECUTE COMMAND ----------
Can I execute the command: `node --version` with 2000ms timeout?
? If yes, just press ENTER

 

잘 진행하다가 갑자기 node 관련해서 에러가 발생했는데...

뭔가 무한루프에 빠진 느낌으로 계속 node 관련해서 벗어나지를 못하는 것이다!

 

▶ node

GPT Pilot은 기본적으로 node를 아주 선호한다.

그런데, node를 설치까지는 해주지 못하는 것으로 보인다.

그러면, 직접 설치를 해줘야지.... ㅠㅠ

 

pyenv처럼 여러 버전의 node를 관리할 수 있는 nvm을 이용해서 node를 설치하자.

- https://www.whatwant.com/entry/npm

 

그리고 지금 사용하고 있는 터미널을 종료하고,

다시 GPT Pilot을 시작하자.

 

❯ cd /path/gpt-pilot   # gpt-pilot 루트 경로

❯ source pilot-env/bin/activate

❯ cd pilot

❯ python main.py

 

▶ Start (#3)

같은 설명을 줘도 뒤에 따라오는 질문들은 바뀐다.

그것에 따라 진행하는 소스코드 내용도 바뀐다.

즉, 할 때 마다 다른 결과물이 나올 수 있다는 말이다.

 

❯ python db_init.py 

------------------ STARTING NEW PROJECT ----------------------
If you wish to continue with this project in future run:
python main.py app_id=c06e0511-9f0f-4b1f-9c49-1347fc82d116
--------------------------------------------------------------

? What is the project name? GitHub_News


? Describe your app in as much detail as possible. Develop a webpage that aggregates news about GitHub.

? Should the news aggregation be real-time or periodically updated? daily

? Should the aggregated news be categorized based on specific topics or tags associated with GitHub? no

? Do you have any specific sources in mind from where the news about GitHub should be aggregated? no

? Is there a limit to the number of news items to be displayed or stored at any given time? 15

? Would you like the app to have an archive feature where older news can be accessed? no

Project Summary:

The "GitHub_News" app will be a webpage designed to aggregate news about GitHub. The content on this webpage will be updated daily without categorizing into specific topics or tags. There are no prescribed sources from where the news about GitHub should be aggregated. The number of news items displayed or stored at any given time will be limited to 15. There will be no archive feature, hence older news items won't be accessible.

{"technologies": ["Node.js", "MongoDB", "Mongoose", "Jest", "Bootstrap", "Vanilla JavaScript", "cronjob"]}

? Please set up your local environment so that the technologies listed can be utilized. When you're done, write "DONE" 

 

"DONE"을 하고 나면 스스로 뭔가 코딩을 시작한다.

필요한 패키지들 설치도 하고 DB도 생성하고....

 

 ...

Dev step 1

First, you need to initialize npm for your new Node.js project. Run the following command:

```bash
npm init -y
```

This will create a file 'package.json' in your project directory and will be used to store metadata about your app and also track the dependencies of your app such as Express, Mongoose, etc. 

Next, you'll require several Node.js packages to develop the app, and for the current task, you need to install Express, Mongoose, and node-cron. Run the following command to install these dependencies:

```
npm install express mongoose node-cron
```

Next, you also need to set up your main application file. Let's call it 'app.js'. 

/app.js
```javascript
const express = require('express');
const mongoose = require('mongoose');
const cron = require('node-cron');

const app = express();

//Express body parser middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.get('/', (req, res) => {
    res.send('Hello World!');
});

// Define your port
const PORT = process.env.PORT || 3000;

// Starting the server
app.listen(PORT, () => {
    console.log(`App running on port ${PORT}`);
});
```

To test the set up, run the server with the command:

```
node app.js
```

Dev step 2

{"tasks": [{"type": "command", "command": {"command": "npm init -y", "timeout": 2500, "success_message": "created a new package.json file"}}, {"type": "command", "command": {"command": "npm install express mongoose node-cron", "timeout": 10000, "success_message": "added packages"}}, {"type": "code_change", "code_change": {"name": "app.js", "path": "app.js", "content": "const express = require('express');\nconst mongoose = require('mongoose');\nconst cron = require('node-cron');\n\nconst app = express();\n\n//Express body parser middleware\napp.use(express.json());\napp.use(express.urlencoded({ extended: false }));\n\napp.get('/', (req, res) => {\n    res.send('Hello World!');\n});\n\n// Define your port\nconst PORT = process.env.PORT || 3000;\n\n// Starting the server\napp.listen(PORT, () => {\n    console.log(`App running on port ${PORT}`);\n});"}}, {"type": "command", "command": {"command": "node app.js", "timeout": 5000, "success_message": "App running on port 3000", "command_id": "run_server"}}]}


--------- EXECUTE COMMAND ----------
Can I execute the command: `npm init -y` with 2500ms timeout?
? If yes, just press ENTER 


answer: 
CLI OUTPUT:Wrote to /srv/workspace/gpt-pilot/workspace/GitHub_News/package.json:
CLI OUTPUT:{
CLI OUTPUT:  "name": "github_news",
CLI OUTPUT:  "version": "1.0.0",
CLI OUTPUT:  "description": "",
CLI OUTPUT:  "main": "index.js",
CLI OUTPUT:  "directories": {
CLI OUTPUT:    "test": "tests"
CLI OUTPUT:  },
CLI OUTPUT:  "scripts": {
CLI OUTPUT:    "test": "echo \"Error: no test specified\" && exit 1"
CLI OUTPUT:  "keywords": [],
CLI OUTPUT:  "author": "",
CLI OUTPUT:  "license": "ISC"
Saving file /package.json

Dev step 3

DONE


--------- EXECUTE COMMAND ----------
Can I execute the command: `npm install express mongoose node-cron` with 10000ms timeout?
? If yes, just press ENTER 


answer: 

Saving file /package.json

Saving file /package.json

Dev step 5

{"thoughts": "From developer's description, they say the 'npm install' command took longer than 10,000 milliseconds to execute and was therefore terminated. This could be due to slow network speeds or the npm registry taking a longer time to respond. It could be a transient issue that could be resolved by trying again.  Or it could be a more persistent issue related to firewall restrictions or other network related issues.", "reasoning": "First, we want to confirm that we have network connection, then we can try testing the npm service by attempting to install a small, commonly used package (like 'lodash') to see if it also hangs. If the 'lodash' package installation succeeds without hanging, we can then try re-running the initial command as it may have been a transient npm registry issue.", "steps": [{"type": "command", "command": {"command": "ping -c 5 npmjs.com", "timeout": 5000, "success_message": "5 packets transmitted, 5 received"}, "check_if_fixed": false}, {"type": "command", "command": {"command": "npm install lodash", "timeout": 10000, "success_message": "+ lodash"}, "check_if_fixed": false}, {"type": "command", "command": {"command": "npm install express mongoose node-cron", "timeout": 30000, "success_message": "+ express\n + mongoose\n + node-cron"}, "check_if_fixed": true}]}


--------- EXECUTE COMMAND ----------
Can I execute the command: `ping -c 5 npmjs.com` with 5000ms timeout?
? If yes, just press ENTER 


answer: 
CLI OUTPUT:PING npmjs.com (104.19.154.92) 56(84) bytes of data.
CLI OUTPUT:64 바이트 (104.19.154.92 (104.19.154.92)에서): icmp_seq=1 ttl=51 시간=3.70 ms
CLI OUTPUT:64 바이트 (104.19.154.92 (104.19.154.92)에서): icmp_seq=2 ttl=51 시간=6.01 ms
CLI OUTPUT:64 바이트 (104.19.154.92 (104.19.154.92)에서): icmp_seq=3 ttl=51 시간=3.63 ms
CLI OUTPUT:64 바이트 (104.19.154.92 (104.19.154.92)에서): icmp_seq=4 ttl=51 시간=3.58 ms
CLI OUTPUT:64 바이트 (104.19.154.92 (104.19.154.92)에서): icmp_seq=5 ttl=51 시간=5.32 ms
CLI OUTPUT:--- npmjs.com 핑 통계 ---
CLI OUTPUT:5 패킷이 전송되었습니다, 5 수신되었습니다, 0% 패킷 손실, 시간 4005ms
Saving file /package.json

Dev step 6

DONE


--------- EXECUTE COMMAND ----------
Can I execute the command: `npm install lodash` with 10000ms timeout?
? If yes, just press ENTER 


answer: 
CLI OUTPUT:
CLI OUTPUT:added 1 package, and audited 2 packages in 573ms
Saving file /package.json

Dev step 7

DONE


--------- EXECUTE COMMAND ----------
Can I execute the command: `npm install express mongoose node-cron` with 30000ms timeout?
? If yes, just press ENTER 


answer: 
CLI OUTPUT:
CLI OUTPUT:added 86 packages, and audited 88 packages in 3s
CLI OUTPUT:12 packages are looking for funding
CLI OUTPUT:  run `npm fund` for details
Saving file /package.json

Dev step 8

DONE
Saving file /package.json

Dev step 9

NO
Saving file /package.json
Saving file /app.js
Can you check if the app works please? Here is a description of what should be working: 

Testing this task doesn't involve any API requests or writing any code. Instead, we will check whether the server is running properly and dependencies are installed correctly via npm. 

To do this, a human user should perform the following steps:

1. In the terminal, navigate to the project directory using the command `cd /path-to-your-project-directory`.

2. To test if the server runs without any issues, type the following command in your terminal:

```bash
node app.js
```

You should see a response saying 'App running on port 3000'. This verifies that the server is running properly with the specified dependencies.

3. Press `Ctrl + C` to stop the server.

4. Next, verify that the dependencies are installed correctly. Open the 'package.json' file and under 'dependencies', it should list the following:

```json
"dependencies": {
    "express": "version-number",
    "mongoose": "version-number",
    "node-cron": "version-number"
}
```
The 'version-number' should represent the installed version of each package.

If the server runs correctly and the 'package.json' file lists the correct dependencies, the task has been successfully completed.


If you want to run the app, just type "r" and press ENTER and that will run `node app.js`
? If something is wrong, tell me or type "continue" to continue. 


Can you check if the app works please? Here is a description of what should be working: 

Testing this task doesn't involve any API requests or writing any code. Instead, we will check whether the server is running properly and dependencies are installed correctly via npm. 

To do this, a human user should perform the following steps:

1. In the terminal, navigate to the project directory using the command `cd /path-to-your-project-directory`.

2. To test if the server runs without any issues, type the following command in your terminal:

```bash
node app.js
```

You should see a response saying 'App running on port 3000'. This verifies that the server is running properly with the specified dependencies.

3. Press `Ctrl + C` to stop the server.

4. Next, verify that the dependencies are installed correctly. Open the 'package.json' file and under 'dependencies', it should list the following:

```json
"dependencies": {
    "express": "version-number",
    "mongoose": "version-number",
    "node-cron": "version-number"
}
```
The 'version-number' should represent the installed version of each package.

If the server runs correctly and the 'package.json' file lists the correct dependencies, the task has been successfully completed.


If you want to run the app, just type "r" and press ENTER and that will run `node app.js`
? If something is wrong, tell me or type "continue" to continue. r


CLI OUTPUT:App running on port 3000

^C
CTRL+C detected. Stopping command execution...
Can you check if the app works please? Here is a description of what should be working: 

Testing this task doesn't involve any API requests or writing any code. Instead, we will check whether the server is running properly and dependencies are installed correctly via npm. 

To do this, a human user should perform the following steps:

1. In the terminal, navigate to the project directory using the command `cd /path-to-your-project-directory`.

2. To test if the server runs without any issues, type the following command in your terminal:

```bash
node app.js
```

You should see a response saying 'App running on port 3000'. This verifies that the server is running properly with the specified dependencies.

3. Press `Ctrl + C` to stop the server.

4. Next, verify that the dependencies are installed correctly. Open the 'package.json' file and under 'dependencies', it should list the following:

```json
"dependencies": {
    "express": "version-number",
    "mongoose": "version-number",
    "node-cron": "version-number"
}
```
The 'version-number' should represent the installed version of each package.

If the server runs correctly and the 'package.json' file lists the correct dependencies, the task has been successfully completed.


If you want to run the app, just type "r" and press ENTER and that will run `node app.js`
? If something is wrong, tell me or type "continue" to continue. r


CLI OUTPUT:App running on port 3000
^C
CTRL+C detected. Stopping command execution...
? If something is wrong, tell me or type "continue" to continue. continue


Implementing task #2:  Set up MongoDB and create a Mongoose schema for storing the GitHub news

To complete the task "Set up MongoDB and create a Mongoose schema for storing the GitHub news", we need to make some changes to the existing file and create new ones.

Here is the required code.


**/config/db.js**
```
const mongoose = require('mongoose');

// Replace this with your MONGOURI.
const MONGOURI = "mongodb://localhost:27017/github_news_db";

const InitiateMongoServer = async () => {
  try {
    await mongoose.connect(MONGOURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log("Connected to the Database :: MongoDB");
  } catch (e) {
    console.log(e);
    throw e;
  }
};

module.exports = InitiateMongoServer;
```

The MONGOURI should be replaced with the actual address where MongoDB is running.

Next, a schema for the news needs to be created.

**/models/News.js**
```
const mongoose = require('mongoose');

const NewsSchema = mongoose.Schema({
  title: String,
Saving file /package.json
Saving file /app.js

Dev step 12

To complete the task "Set up MongoDB and create a Mongoose schema for storing the GitHub news", we need to make some changes to the existing file and create new ones.

Here is the required code.


**/config/db.js**
```
const mongoose = require('mongoose');

// Replace this with your MONGOURI.
const MONGOURI = "mongodb://localhost:27017/github_news_db";

const InitiateMongoServer = async () => {
  try {
    await mongoose.connect(MONGOURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log("Connected to the Database :: MongoDB");
  } catch (e) {
    console.log(e);
    throw e;
  }
};

module.exports = InitiateMongoServer;
```

The MONGOURI should be replaced with the actual address where MongoDB is running.

Next, a schema for the news needs to be created.

**/models/News.js**
```
const mongoose = require('mongoose');

const NewsSchema = mongoose.Schema({
  title: String,
  description: String,
  url: String,
  date: Date
});

module.exports = mongoose.model('News', NewsSchema);
```

Finally, we should call the function to connect to the database at the start of our application.

**/app.js**
```
const express = require('express');
const cron = require('node-cron');
const InitiateMongoServer = require('./config/db');

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

InitiateMongoServer();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`App running on port ${PORT}`);
});
```

In the above code we required the db.js file and initiated the Mongo server using the function "InitiateMongoServer". dB.js file handles the connection to MongoDB.

To test this task, you can just run the server and if server logs "Connected to the Database :: MongoDB" message, that means MongoDB is connected successfully. If there are any errors in connection, it will also be logged to console.
Use the following command to start the server:

```bash
node app.js
```
Saving file /package.json
Saving file /app.js

Dev step 13

{"tasks": [{"type": "code_change", "code_change": {"name": "db.js", "path": "/config/db.js", "content": "const mongoose = require('mongoose');\n\nconst MONGOURI = \"mongodb://localhost:27017/github_news_db\";\n\nconst InitiateMongoServer = async () => {\n  try {\n    await mongoose.connect(MONGOURI, {\n      useNewUrlParser: true,\n      useUnifiedTopology: true\n    });\n    console.log(\"Connected to the Database :: MongoDB\");\n  } catch (e) {\n    console.log(e);\n    throw e;\n  }\n};\n\nmodule.exports = InitiateMongoServer;"}}, {"type": "code_change", "code_change": {"name": "News.js", "path": "/models/News.js", "content": "const mongoose = require('mongoose');\n\nconst NewsSchema = mongoose.Schema({\n  title: String,\n  description: String,\n  url: String,\n  date: Date\n});\n\nmodule.exports = mongoose.model('News', NewsSchema);"}}, {"type": "code_change", "code_change": {"name": "app.js", "path": "/app.js", "content": "const express = require('express');\nconst cron = require('node-cron');\nconst InitiateMongoServer = require('./config/db');\n\nconst app = express();\napp.use(express.json());\napp.use(express.urlencoded({ extended: false }));\n\nInitiateMongoServer();\n\napp.get('/', (req, res) => {\n  res.send('Hello World!');\n});\n\nconst PORT = process.env.PORT || 3000;\n\napp.listen(PORT, () => {\n  console.log(`App running on port ${PORT}`);\n});"}}, {"type": "command", "command": {"command": "node app.js", "timeout": 10000, "success_message": "Connected to the Database :: MongoDB"}}]}

Updated file /srv/workspace/gpt-pilot/workspace/GitHub_News/config/db.js
Updated file /srv/workspace/gpt-pilot/workspace/GitHub_News/models/News.js
Updated file /srv/workspace/gpt-pilot/workspace/GitHub_News/app.js

--------- EXECUTE COMMAND ----------
Can I execute the command: `node app.js` with 10000ms timeout?
? If yes, just press ENTER 


answer: 
CLI OUTPUT:App running on port 3000
CLI ERROR:(node:26226) [MONGODB DRIVER] Warning: useNewUrlParser is a deprecated option: useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version
CLI ERROR:(Use `node --trace-warnings ...` to show where the warning was created)
CLI ERROR:(node:26226) [MONGODB DRIVER] Warning: useUnifiedTopology is a deprecated option: useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version

Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 14

NEEDS_DEBUGGING

Got incorrect CLI response:
stderr:
```
(node:26226) [MONGODB DRIVER] Warning: useNewUrlParser is a deprecated option: useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version
Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 15

{"thoughts": "From error messages, it looks like an issue with the database connection. May happen due an unaccessible or inactive MongoDB server or incorrect MONGOURI. Furthermore, there are warnings related to `useNewUrlParser` and `useUnifiedTopology` that have no effect since MongoDB driver version 4.0. First, we need to ensure MongoDB server is running and accessible.", "reasoning": "By checking if MongoDB server is running, and if the URI is correct, we will verify whether the issue exists with the database connection. Also, we can safely remove the warnings by updating the options in the mongoose.connect call as these options are deprecated and have no effect with the updated MongoDB driver version.", "steps": [{"type": "command", "command": {"command": "service mongod status | grep active", "timeout": 3000, "success_message": "active (running)"}, "need_to_see_output": true, "check_if_fixed": false}, {"type": "code_change", "code_change_description": "/config/db.js: Change the 'mongoose.connect' part of the code to `await mongoose.connect(MONGOURI);` This will create a basic connection without the deprecated flags.", "check_if_fixed": false}, {"type": "command", "command": {"command": "node app.js", "timeout": 10000, "success_message": "Connected to the Database :: MongoDB"}, "check_if_fixed": true}]}


--------- EXECUTE COMMAND ----------
Can I execute the command: `service mongod status | grep active` with 3000ms timeout?
? If yes, just press ENTER 

Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 16

{"thoughts": "The deprecated options warning itself won't cause the connection to MongoDB to hang. The initial thoughts are that MongoDB is not running as it's supposed to, or the connection string, MONGOURI, is not correct", "reasoning": "To verify the initial thoughts, we should in order first check the mongo service status and then check if MongoDB is lSaving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 17

{"thoughts": "It seems like the MongoDB connection is taking longer than expected. This may be due to a misconfiguration in the Database URL.", "reasoning": "We need to check the MongoDB server status and ensure it's up and running. If the MongoDB server is up then the issue might be in the database connection string or MongoDB deprecation warnings. RemoviSaving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 18

{"thoughts": "It seems that the MongoDB server might not be running or the connection string might be incorrectly specified. Adjusting the connection string and checking if MongoDB service is running should solve the problem.", "reasoning": "In the output logs, we see that the app started but there is no logs on database connection, we need to confirm the Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 19

{"thoughts": "The existing MongoDB connection seems to be failing. The timeouts and deprecation warnings suggest an issue with the connection method or the provided MongoDB URI. There also could be network or firewall issue preventing the connection to MongoDB.", "reasoning": "Looking at the initial output and warnings, it seems to be related to the MongoDB URI or the connection settings. Both warnings are related to deprecated configurations so we should adjust the connection configuration to be compatible with MongoDB 4.0+.", "stSaving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 20

{"thoughts": "Looking at the error, it seems that there are deprecation warnings for the `useNewUrlParser` and `useUnifiedTopology` flags. We also don't see the 'Connected to the Database :: MongoDB' message which means MongoDB may not be running or there's an issue with connection settings.", "reasoning": "We need to ensure MongoDB is running and connected to successfully start the application. Additionally, because `useNewUrlParser` and `useUnifiedTopology` options are deprecated, we need to update the MongoDB connection options in our code accordingly.", "steps": [{"type": "command", "command": {"command": "service mongod start", "timeout": 3000, "success_message": "Starting MongoDB"}, "need_to_see_output": true, "check_if_fixed": false}, {"type": "code_change", "code_change_description": "Change the MongoDB connection code in the '/config/db.js' file to be `await mongoose.connect(MONGOURI);`. This will establish a basic connection without the deprecated options.", "check_if_fixed": false}, {"type": "command", "command": {"command": "node app.js", "timeout": 10000, "success_message": "Connected to the Database :: MongoDB"}, "check_if_fixed": true}]}


--------- EXECUTE COMMAND ----------
Can I execute the command: `service mongod start` with 3000ms timeout?
? If yes, just press ENTER 


answer: 
Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 21

{"thoughts": "The node server takes a long time to finish indicating that it is waiting for some resource. As we are trying to connect to mongodb at the startup, it indicates that it might not be able to establish a successful connection to mongodb.", "reasoning": "The deprecated warnings are due to outdated mongoose connection settings. However, it should not affect the connection itself. There might be issues with the MongoDB instance (like it's not running or misconfigured). Hence started MongoDB service and checked the connection.", "steps": [{"type": "command", "command": {"command": "service mongod start", "timeout": 3000, "success_message": "Starting MongoDB"}, "need_to_see_output": true, "check_if_fixed": false}, {"type": "command", "command": {"command": "mongo --eval 'db.runCommand({ connectionStatus: 1 })'", "timeout": 3000, "success_message": "'ok' : 1"}, "need_to_see_output": true, "check_if_fixed": false}, {"type": "code_change", "code_change_description": "In the '/config/db.js' file, Change the 'mongoose.connect' part of the code to `await moSaving file /package.json
Saving file /app.js
Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 23
Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js

Dev step 24

{"files": [{"name": "db.js", "path": "/config/db.js", "content": "const mongoose = require('mongoose');\n\nconst MONGOURI = \"mongodb://localhost:27017/github_news_db\";\n\nconst InitiateMongoServer = async () => {\n  try {\n    await mongoose.connect(MONGOURI);\n    console.log(\"Connected to the Database :: MongoDB\");\n  } catch (e) {\n    console.log(e);\n    throw e;\n  }\n};\n\nmodule.exports = InitiateMongoServer;"}]}

Updated file /srv/workspace/gpt-pilot/workspace/GitHub_News/config/db.js
{"type": "command", "command": {"command": "node app.js", "timeout": 10000, "success_message": "Connected to the Database :: MongoDB"}}

 

중간에 에러가 발생하면, 자기가 스스로 그 에러를 해결하기 위해서 또 뭔가를 계속 한다.

 

▶ Quota

계속 이렇게 저렇게 하면서 놀다 보니, 다음과 같은 에러 메시지가 나왔다.

 

...

There was a problem with request to openai API:
API responded with status code: 429. Response text: {
    "error": {
        "message": "You exceeded your current quota, please check your plan and billing details.",
        "type": "insufficient_quota",
        "param": null,
        "code": "insufficient_quota"
    }
}

? Do you want to try make the same request again? If yes, just press ENTER. Otherwise, type 'no'. no


Saving file /package.json
Saving file /app.js
Saving file /config/db.js
Saving file /models/News.js
---------- GPT PILOT EXITING WITH ERROR ----------
Traceback (most recent call last):
  File "/srv/workspace/gpt-pilot/pilot/main.py", line 71, in 
    project.start()
  File "/srv/workspace/gpt-pilot/pilot/helpers/Project.py", line 138, in start
    self.developer.start_coding()
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 52, in start_coding
    self.implement_task(i, dev_task)
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 98, in implement_task
    result = self.execute_task(convo_dev_task,
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 339, in execute_task
    result = self.step_command_run(convo, step, i, success_with_cli_response=need_to_see_output)
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 157, in step_command_run
    return run_command_until_success(convo, data['command'],
  File "/srv/workspace/gpt-pilot/pilot/helpers/cli.py", line 480, in run_command_until_success
    success = convo.agent.debugger.debug(convo, {
  File "/srv/workspace/gpt-pilot/pilot/helpers/Debugger.py", line 63, in debug
    result = self.agent.project.developer.execute_task(
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 344, in execute_task
    result = self.step_code_change(convo, step, i, test_after_code_changes)
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 130, in step_code_change
    return self.test_code_changes(code_monkey, updated_convo)
  File "/srv/workspace/gpt-pilot/pilot/helpers/agents/Developer.py", line 551, in test_code_changes
    llm_response = convo.send_message('development/task/step_check.prompt', {}, GET_TEST_TYPE)
  File "/srv/workspace/gpt-pilot/pilot/helpers/AgentConvo.py", line 99, in send_message
    raise Exception("OpenAI API error happened.")
Exception: OpenAI API error happened.
--------------------------------------------------
? We would appreciate if you let us store your initial app prompt. If you are OK with that, please just press ENTER 

 

이런 !!! 돈이다 !!!

- https://platform.openai.com/usage

Usage

 

API는 돈이다 !!! ㅠㅠ

중간에 쓸데 없이 이것 저것 하다보니..... 돈이다 !!!!

 

 

음... 완제품까지 달려보지는 못했지만, 적당히 잘 가지고 놀아본 것 같다.

 

Copilot Chat 또는 ChatGPT를 이용해서 대화 형식으로 코딩을 해볼 수는 있지만,

그 느낌과는 확실히 다르다는 것은 알 수 있었다.

AutoGPT와 같은 느낌이었는데, 그것보다는 조금 더 고급스러운(진화한) 느낌이다.

 

다만, 필요한 패키지들을 설치한다던지 MongoDB 같은 것을 설치한다던지 해주는 것은 좋았지만

버전간의 호환성이나 deprecated 된 함수들을 사용한다거나 하는 등의 문제는 좀 있는 것 같다.

 

자기 스스로 그런 에러들을 해결하는 방법을 찾아서 해결해나가는 과정이 있기는 하지만

그러기 위해서 API call을 남발하는 모습을 보면 !!! ㅠㅠ

 

그런데, 한 step 씩 뭔가 만들어 나가는 과정을 지켜보면 AI Developer가 멀지 않은 것 같다.

다행인 것은 아직은 AI Assistant 수준을 벗어나지 못한 것 같다는.... ^^

 

아~ 내 돈 !!!!

반응형

최근 나오는 IT 서적의 상당수는 챗GPT에 대한 것들이다.

순위권들을 전부 씹어먹고 있다는...

 

처음에는 LLM에 대한 역사부터 설명하는 그런 책들이 트렌드였다가

최근에는 프롬프트에 대한 것들로 채워진 책들이 트렌드를 이끌고 있다.

 

이런 책 시장에 또 하나의 챗GPT 서적이 등장했다,

표지

 

다른 챗GPT 책들과의 차별점이 보인다.

 

"개발자"

 

개발자를 위한 챗GPT 가이드인 것이다!!!

지은이

 

글로벌한 인재라는 느낌이 팍!팍! 드는 소개가 보인다.

 

그리고,

"마이크로소프트 본사의 Copilot Applied AI팀에서 Senior Data Scientist"

 

Copilot 활용에 대해서는 전문가일 것이라는 느낌이 팍! 팍!

일러두기

 

바로 이 부분이 다른 챗GPT 서적들과의 차별점이다.

개발자에게 어떤 도움이 되는지에 대해서 설명해주는 책인 것이다.

개발자를 위한

 

이 책의 정체성이기에 계속 강조해본다!

초판

 

7월의 마지막날에 등장한 따끈따끈한 책이다.

 

그런데, 펴낸곳은 "한빛미디어"인데, 책 표지를 보면 "디코딩"이라는 명칭만 보인다.

 

임프린트가 뭔가 해서 위키를 찾아봤다. (https://ko.wikipedia.org/wiki/임프린트)

임프린트(imprint)는 출판 회사에서 유능한 편집자 등에게 별도의 하위 브랜드를 내어주고 기획, 제작, 판매 등 독자적인 운영을 맡기는 방식이다. 단일 출판 회사 아래에 여러 개의 임프린트가 있을 수 있다.

임프린트 브랜드를 사용하면 출판사 등은 각각의 특정 소비자 계층에게 집중적인 마케팅이 가능하다. 출판사 뿐 아니라 게임 회사에서도 독자적인 임프린트 브랜드를 운용할 수 있다.

 

호오.... 유능한 편집자 분의 닉네임이 "디코딩"이신가 보다. 고지연님?

설명서

 

실습을 위한 자료를 받을 수 있는 정확한 경로는 다음과 같다.

- https://github.com/decodingbook/ChatGPTforDev

실습 자료

 

뭔가 여러 파일들이 있을 것 같았는데, PDF 파일 하나만 덩그러니 있다.

그래도 이렇게 GitHub.com을 이용한 실습 자료 제공은 개인적으로 참 좋다!

목차

 

목차를 보다가, 랭체인까지 설명해주는 것을 보고는 깜짝 놀랐다.

 

사실 책 제목만 보고는 챗GPT를 이용한 프롬프트 수준의 내용들일 것이라고 기대했는데,

Copilot을 이용하는 부분과 Colab을 활용하는 부분들, 그리고 랭체인까지 설명해주는 것을 보고는 정말 깜짝 놀랐다.

랭체인

 

지은이가 마이크로스프트 소속이다 보니

Azure 환경을 이용한다던지, 아니면 GitHub의 codespaces를 이용한다던지 할 줄 알았는데

Colab에서 이렇게 예제들을 설명하는 것을 보고 감동 받았다.

duckduckgo

 

거기에다가

Bing 검색이 아니라 구글 검색을 언급하고, 예제는 duckduckgo를 이용하다니...

우와~ 정말 개발자 친화적이다!!!

 

 

그리고, 개인적으로 정말 좋아하는.... 풀컬러 책이다!!!

 

 

결론적으로,

SW개발자들이라면 한 번쯤 구매해서 읽어보면

책 값 이상으로 개발 효율성을 높일 수 있을만한 내용들을 담고있다고 생각한다.

 

 

"한빛미디어 <나는 리뷰어다> 활동을 위해서 책을 제공받아 작성된 서평입니다."

반응형

+ Recent posts