검색
검색
공개 노트 검색
회원가입로그인

[UCA울산코딩아카데미] 오픈라우터 AI OpenChat 모델 무한 토큰 API 코딩

파이썬 코드가 ulsancoding.com 블로그 하단에 제공됩니다.

models

오픈라우터AI에서 (Free)가 뒤에 붙은 모델은 일단 무한 토큰 방식이라서 토큰가격이 0달러로 과금이 전혀 되지않는다. 각종 테스트 코드를 이것저것 맘대로 던져보기 좋다. 그동안 구글 gemma, 미스트랄등 오픈라우터에서 제공하는 2개 Free 모델의 API 코딩 방법을 시리즈형태로 계속 소개하고있다.

openChat은 코딩을 잘한다고 알려진 모델이다. OpenChat-3.5-1210 , OpenChat-3.5-0106으로 연속 업데이트된 이 새로운 버전의 모델은 코딩 작업에 탁월하며, GPT-기반 응답의 다양한 대화형 데이터에 의해 파인튜닝되고 훈련이 되었다. 오픈 소스 LLM 벤치마크에서 곧잘 ChatGPT를 능가한다며, 높은 점수를 여러 번 받았던 전력이 있는 오픈 소스 모델 제품군이다.

ChatGPT 성능을 능가한다는 말은 하도 들어서 지겨울 정도인데, claude3 opus모델정도가 압도하는거지, 다른 모델들은 아직 갈길이 멀어보이는데, 업스테이지 솔라 Solar 같은 모델들이 오픈리더보드에서 하도 chatGPT를 능가하는 모델이니, KO 오픈리더보드 1등이니 하는 식으로 너무 남발되는 바람에 openChat처럼 초창기에 자리를 잡았던 좋은 모델들은 사실 너무 빠르게 잊혀진 거 같다. 전통적으로 코드 생성에선 llama2 (라마2 )등이 높은 성능을 냈고, openChat은 라마2 13B 모델을 기본으로 파인튜닝해서 만들었다.

라마2는 파이썬 언어 전문 모델도 있는등 개발자들의 선택을 받은 건 확실하다. OpenChat도 llama2 기반으로 오프라인 강화 학습에서 C-RLFT로 미세 조정된 오픈 소스 언어 모델 세트다.

그런데, 일단 오픈라우터 API 안내문에 올려진 cURL부터 파이썬 샘플코드등에 자잘한 문제가 있다. 누군가 고쳐야 제대로 쓸테니 필자가 완벽하게 고쳐서 응답 가능하게 바꾼 코드들을 블로그 말미에 전부 업로드해서 올려놓았다.

파이썬 에러 수정 코드

import requests
import json
import os

OPENROUTER_API_KEY = os.environ.get("openrouter_key")
# OPENROUTER_API_KEY = "sk-or-...."
# print(OPENROUTER_KEY)
YOUR_SITE_URL="ulsancoding.com"
YOUR_APP_NAME="OpenchatTEST"

response = requests.post(
  url="https://openrouter.ai/api/v1/chat/completions",
  headers={
    "Authorization": f"Bearer {OPENROUTER_API_KEY}",
    "HTTP-Referer": f"{YOUR_SITE_URL}", # Optional, for including your app on openrouter.ai rankings.
    "X-Title": f"{YOUR_APP_NAME}", # Optional. Shows in rankings on openrouter.ai.
  },
  data=json.dumps({
    "model": "openchat/openchat-7b:free", # Optional
    "messages": [
      {"role": "user", "content": "Do U know k-pop girlgroup ive ahn yoo jin?"}
    ]
  })
)


# print(response.json())
print(response.json()['choices'][0]['message']['content'] )

Response 응답 값

 Yes, I know Ahn Yoo-jin, a member of the K-pop girl group IVE. 

IVE is a South Korean girl group formed by Starship Entertainment and EDAM Entertainment. 

The group debuted on December 1, 2021, with the single album "Eleven." 

Ahn Yoo-jin, also known as Yujin, is one of the six members of the group. 

She was born on July 19, 2002, in South Korea. Before debuting with IVE, 

Yujin was a contestant on the survival show "Produce 101 Season 2" and "Produce 48."

openAI스타일 코드

아래처럼 조금 특이한 옵션들이 더 붙어있지만, 실제 파이썬 코딩에 영향을 크게 주는건 아니다.

OPENROUTER_KEY = os.environ.get("openrouter_key")

YOUR_SITE_URL="ulsancoding.com"

YOUR_APP_NAME="OpenchatTEST"

from openai import OpenAI
import os 

OPENROUTER_KEY = os.environ.get("openrouter_key")
# OPENROUTER_KEY = "sk-or-...."
# print(OPENROUTER_KEY)
YOUR_SITE_URL="ulsancoding.com"
YOUR_APP_NAME="OpenchatTEST"


# gets API Key from environment variable OPENAI_API_KEY
client = OpenAI(
  base_url="https://openrouter.ai/api/v1",
  api_key = OPENROUTER_KEY,
)

completion = client.chat.completions.create(
  extra_headers={
    "HTTP-Referer" : f"{YOUR_SITE_URL}", # Optional, for including your app on openrouter.ai rankings.
    "X-Title": f"{YOUR_APP_NAME}", # Optional. Shows in rankings on openrouter.ai.
  },
  model="openchat/openchat-7b:free",
  messages=[
    {
      "role": "user",
      "content": "make a python sourcecode for area of circle with radius is 5",
    },
  ],
)
print(completion.choices[0].message.content)

코드를 만들게 할 프롬프트는

"make a C# sourcecode for area of circle with radius is 5"

라고 <원의 넓이>를 구하는 파이썬과 C# 코드를 두 가지 만들어보게 시켰다.

Response응답값 -파이썬

Here's a simple Python source code to calculate the area of a circle with a radius of 5:

```python
import math

radius = 5
area = math.pi * (radius ** 2)

print("The area of the circle with radius 5 is:", area)

When you run this code, it will output:

The area of the circle with radius 5 is: 78.53981633974483

Response응답값 - C#

Here is a simple C# source code to calculate the area of a circle with radius 5:

```csharp
using System;

class Program
{
    static void Main()
    {
        double radius = 5;
        double area = Math.PI * radius * radius;
        Console.WriteLine("The area of the circle with radius 5 is: " + area);
    }
}

When you run this program, it will output: The area of the circle with radius 5 is: 78.53981633974483

코드 능력은 사실 흠잡을 데가 없다. AWS의 코드 위스퍼러나 허깅페이스의 스타코더2등의 떠오르는 샛별 같은 코드 생성 도우미나, 강력한 무료 버전의 AI 코딩 모델들도 많다.

필자는 ollama 서비스를 이용해서 openchat 모델과 continue 플러그인을 접목했다.

llama 34B가 돌아갈만한 32기가 이상의 메모리가 탑재되지않아서 아쉬운대로 로컬 노트북PC에서 openachat 모델을 통해 다양한 코드 생성을 무한 토큰 형태로 맡겨서 줄기차게 사용하고 있다.

파이썬코드 다운로드

[파이썬코드 1]

파이썬코드 (openAI스타일) 다운로드

[openAI스타일 코드 2]

아티클이 맘에 드시면 ulsancoding.com을 방문해 다른 게시물들도 참고해주세요

구글 제미나이, 클로드3, 미스트랄, 네이버클로바X, solar, ollama등의 API코딩기법이 소스코드와 함께 공개되어있습니다.

UCA울산코딩아카데미

ulsancoding.com

052-708-0001

공유하기
카카오로 공유하기
페이스북 공유하기
트위터로 공유하기
url 복사하기
조회수 : 273
heart
T
페이지 기반 대답
AI Chat