# 채팅 프로젝트 이 채팅 프로젝트는 GitHub Models를 사용하여 채팅 어시스턴트를 구축하는 방법을 보여줍니다. 완성된 프로젝트는 다음과 같습니다:
채팅 앱
생성형 AI를 사용하여 채팅 어시스턴트를 만드는 것은 AI를 배우는 훌륭한 시작점입니다. 이번 레슨에서는 생성형 AI를 웹 앱에 통합하는 방법을 배울 것입니다. 시작해봅시다. ## 생성형 AI 연결하기 백엔드로는 GitHub Models를 사용합니다. 이 서비스는 무료로 AI를 사용할 수 있게 해주는 훌륭한 도구입니다. GitHub Models Playground로 이동하여 선택한 백엔드 언어에 해당하는 코드를 가져오세요. [GitHub Models Playground](https://github.com/marketplace/models/azure-openai/gpt-4o-mini/playground)에서 확인할 수 있습니다.
GitHub Models AI Playground
"Code" 탭과 원하는 런타임을 선택하세요.
playground choice
### Python 사용하기 이 경우 Python을 선택하면 다음 코드를 가져오게 됩니다: ```python """Run this model in Python > pip install openai """ import os from openai import OpenAI # To authenticate with the model you will need to generate a personal access token (PAT) in your GitHub settings. # Create your PAT token by following instructions here: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens client = OpenAI( base_url="https://models.github.ai/inference", api_key=os.environ["GITHUB_TOKEN"], ) response = client.chat.completions.create( messages=[ { "role": "system", "content": "", }, { "role": "user", "content": "What is the capital of France?", } ], model="openai/gpt-4o-mini", temperature=1, max_tokens=4096, top_p=1 ) print(response.choices[0].message.content) ``` 이 코드를 조금 정리하여 재사용 가능하게 만들어봅시다: ```python def call_llm(prompt: str, system_message: str): response = client.chat.completions.create( messages=[ { "role": "system", "content": system_message, }, { "role": "user", "content": prompt, } ], model="openai/gpt-4o-mini", temperature=1, max_tokens=4096, top_p=1 ) return response.choices[0].message.content ``` 이 `call_llm` 함수는 프롬프트와 시스템 프롬프트를 받아 결과를 반환합니다. ### AI 어시스턴트 커스터마이징 AI 어시스턴트를 커스터마이징하려면 시스템 프롬프트를 채워서 원하는 동작을 지정할 수 있습니다: ```python call_llm("Tell me about you", "You're Albert Einstein, you only know of things in the time you were alive") ``` ## 웹 API로 노출하기 좋습니다, AI 부분은 완료되었습니다. 이제 이를 웹 API에 통합하는 방법을 살펴봅시다. 웹 API로는 Flask를 사용하지만, 다른 웹 프레임워크도 괜찮습니다. 코드를 살펴봅시다: ### Python 사용하기 ```python # api.py from flask import Flask, request, jsonify from llm import call_llm from flask_cors import CORS app = Flask(__name__) CORS(app) # * example.com @app.route("/", methods=["GET"]) def index(): return "Welcome to this API. Call POST /hello with 'message': 'my message' as JSON payload" @app.route("/hello", methods=["POST"]) def hello(): # get message from request body { "message": "do this taks for me" } data = request.get_json() message = data.get("message", "") response = call_llm(message, "You are a helpful assistant.") return jsonify({ "response": response }) if __name__ == "__main__": app.run(host="0.0.0.0", port=5000) ``` 여기서는 Flask API를 생성하고 기본 경로 "/"와 "/chat"을 정의합니다. "/chat"은 프론트엔드에서 질문을 전달하는 데 사용됩니다. *llm.py*를 통합하려면 다음을 수행해야 합니다: - `call_llm` 함수 가져오기: ```python from llm import call_llm from flask import Flask, request ``` - "/chat" 경로에서 호출하기: ```python @app.route("/hello", methods=["POST"]) def hello(): # get message from request body { "message": "do this taks for me" } data = request.get_json() message = data.get("message", "") response = call_llm(message, "You are a helpful assistant.") return jsonify({ "response": response }) ``` 여기서는 들어오는 요청을 파싱하여 JSON 본문에서 `message` 속성을 가져옵니다. 그런 다음 LLM을 호출합니다: ```python response = call_llm(message, "You are a helpful assistant") # return the response as JSON return jsonify({ "response": response }) ``` 좋습니다, 필요한 작업을 완료했습니다. ## Cors 설정 백엔드와 프론트엔드가 다른 포트에서 실행되기 때문에 프론트엔드가 백엔드에 호출할 수 있도록 CORS(교차 출처 리소스 공유)를 설정해야 합니다. ### Python 사용하기 *api.py*에 다음 코드가 포함되어 있습니다: ```python from flask_cors import CORS app = Flask(__name__) CORS(app) # * example.com ``` 현재는 모든 출처를 허용하는 "*"로 설정되어 있는데, 이는 안전하지 않으므로 프로덕션 환경에서는 제한해야 합니다. ## 프로젝트 실행하기 프로젝트를 실행하려면 먼저 백엔드를 시작한 다음 프론트엔드를 시작해야 합니다. ### Python 사용하기 *llm.py*와 *api.py*를 가지고 백엔드를 실행하려면 다음을 수행해야 합니다: - 종속성 설치: ```sh cd backend python -m venv venv source ./venv/bin/activate pip install openai flask flask-cors openai ``` - API 시작하기: ```sh python api.py ``` Codespaces를 사용하는 경우 편집기 하단의 Ports로 이동하여 오른쪽 클릭 후 "Port Visibility"를 선택하고 "Public"을 선택하세요. ### 프론트엔드 작업하기 API가 실행 중이라면 이제 프론트엔드를 만들어봅시다. 최소한의 프론트엔드를 단계적으로 개선해 나갈 것입니다. *frontend* 폴더를 생성하고 다음을 추가하세요: ```text backend/ frontend/ index.html app.js styles.css ``` 먼저 **index.html**을 살펴봅시다: ```html