메뉴
BL
MarkTechPost 53일 전

구글 코랩에서 오픈웹UI와 OpenAI API 연동하기

IMP
7/10
핵심 요약

본 튜토리얼은 구글 코랩(Colab) 환경에서 오픈웹UI(Open WebUI)를 설치하고 파이썬을 이용해 안전하게 OpenAI API를 연동하는 방법을 다룹니다. API 키 유출을 방지하는 보안 입력부터 외부 접속을 위한 퍼블릭 터널(Cloudflare) 생성까지 브라우저 기반 챗봇 구축의 전 과정을 실무 중심으로 제공합니다.

번역된 본문

에디터 추천 | 에이전트 AI | 인공지능 | AI 인프라 | 애플리케이션 | 기술 | 생성형 AI | 언어 모델 | 스태프 튜토리얼

이 튜토리얼에서는 구글 코랩(Colab) 환경에서 파이썬(Python)을 사용하여 실용적이고 직접적인 방식으로 오픈웹UI(Open WebUI)를 완벽하게 구축하는 방법을 다룹니다.

먼저 필수 종속성(dependencies)을 설치한 다음, 민감한 자격 증명이 노트북에 직접 노출되지 않도록 터미널 기반의 비밀 입력을 통해 OpenAI API 키를 안전하게 제공합니다. 그런 다음 오픈웹UI가 OpenAI API와 통신하는 데 필요한 환경 변수를 구성하고, 기본 모델을 정의하며, 런타임 스토리지를 위한 데이터 디렉토리를 준비하여 코랩 환경 내에서 오픈웹UI 서버를 실행합니다.

인터페이스를 노트북 외부에서도 접근할 수 있도록 퍼블릭 터널(public tunnel)을 생성하고, 브라우저에서 바로 애플리케이션을 열고 사용할 수 있는 공유 가능한 URL을 캡처합니다. 이 과정을 통해 오픈웹UI를 엔드투엔드로 실행해 보며, 코랩 기반 워크플로우에서 배포, 구성, 액세스 및 런타임 관리의 핵심 요소들이 어떻게 결합되는지 이해할 수 있습니다.

코드 복사 완료 import os import re import time import json import shutil import signal import secrets import subprocess import urllib.request from getpass import getpass from pathlib import Path

print("오픈웹UI 및 헬퍼 패키지 설치 중...") subprocess.check_call([ "python", "-m", "pip", "install", "-q", "open-webui", "requests", "nest_asyncio" ])

print("\nOpenAI API 키를 안전하게 입력하세요.") openai_api_key = getpass("OpenAI API Key: ").strip() if not openai_api_key: raise ValueError("OpenAI API 키는 비워둘 수 없습니다.")

default_model = input("오픈웹UI에서 사용할 기본 모델 [gpt-4o-mini]: ").strip() if not default_model: default_model = "gpt-4o-mini"

시스템 작업 관리, 입력 보안, 파일 경로 처리, 서브프로세스 실행 및 네트워크 액세스를 위해 필요한 모든 파이썬 모듈을 가져오는 것으로 시작합니다. 그런 다음 구글 코랩 내부에서 애플리케이션을 원활하게 실행하는 데 필요한 오픈웹UI와 지원 패키지를 설치합니다. 그 후, 터미널 입력을 통해 OpenAI API 키를 안전하게 입력하고 오픈웹UI가 사용하도록 설정할 기본 모델을 정의합니다.

코드 복사 완료 os.environ["ENABLE_OPENAI_API"] = "True" os.environ["OPENAI_API_KEY"] = openai_api_key os.environ["OPENAI_API_BASE_URL"] = "https://api.openai.com/v1" os.environ["WEBUI_SECRET_KEY"] = secrets.token_hex(32) os.environ["WEBUI_NAME"] = "Open WebUI on Colab" os.environ["DEFAULT_MODELS"] = default_model

data_dir = Path("/content/open-webui-data") data_dir.mkdir(parents=True, exist_ok=True) os.environ["DATA_DIR"] = str(data_dir)

오픈웹UI가 OpenAI API와 제대로 연결될 수 있도록 환경 변수를 구성합니다. API 키를 저장하고, OpenAI 기본 엔드포인트(endpoint)를 정의하며, 웹 인터페이스용 비밀 키를 생성하고, 세션의 기본 모델과 인터페이스 이름을 할당합니다. 또한 오픈웹UI가 런타임 데이터를 저장할 체계적인 위치를 가질 수 있도록 코랩 환경에 전용 데이터 디렉토리를 생성합니다.

코드 복사 완료 cloudflared_path = Path("/content/cloudflared") if not cloudflared_path.exists(): print("\ncloudflared 다운로드 중...") url = "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64" urllib.request.urlretrieve(url, cloudflared_path) cloudflared_path.chmod(0o755)

print("\n오픈웹UI 서버 시작 중...") server_log = open("/content/open-webui-server.log", "w") server_proc = subprocess.Popen( ["open-webui", "serve"], stdout=server_log, stderr=subprocess.STDOUT, env=os.environ.copy() )

코랩 환경에 클라우드플레어(Cloudflare) 바이너리가 없는 경우 터널 구성 요소를 다운로드하여 준비합니다. 준비가 완료되면 오픈웹UI 서버를 시작하고 필요할 경우 동작을 점검할 수 있도록 출력을 로그 파일로 리디렉션합니다. 이 튜토리얼의 이 부분은 브라우저 기반 인터페이스를 구동하는 핵심 애플리케이션 프로세스를 설정하는 과정입니다.

코드 복사 완료 (Use...)

원문 보기
원문 보기 (영어)
Editors Pick Agentic AI Artificial Intelligence AI Infrastructure Applications Technology Generative AI Language Model Staff Tutorials In this tutorial, we build a complete Open WebUI setup in Colab, in a practical, hands-on way, using Python. We begin by installing the required dependencies, then securely provide our OpenAI API key through terminal-based secret input so that sensitive credentials are not exposed directly in the notebook. From there, we configure the environment variables needed for Open WebUI to communicate with the OpenAI API, define a default model, prepare a data directory for runtime storage, and launch the Open WebUI server inside the Colab environment. To make the interface accessible outside the notebook, we also create a public tunnel and capture a shareable URL that lets us open and use the application directly in the browser. Through this process, we get Open WebUI running end-to-end and understand how the key pieces of deployment, configuration, access, and runtime management fit together in a Colab-based workflow. Copy Code Copied Use a different Browser import os import re import time import json import shutil import signal import secrets import subprocess import urllib.request from getpass import getpass from pathlib import Path print("Installing Open WebUI and helper packages...") subprocess.check_call([ "python", "-m", "pip", "install", "-q", "open-webui", "requests", "nest_asyncio" ]) print("\nEnter your OpenAI API key securely.") openai_api_key = getpass("OpenAI API Key: ").strip() if not openai_api_key: raise ValueError("OpenAI API key cannot be empty.") default_model = input("Default model to use inside Open WebUI [gpt-4o-mini]: ").strip() if not default_model: default_model = "gpt-4o-mini" We begin by importing all the required Python modules for managing system operations, securing input, handling file paths, running subprocesses, and accessing the network. We then install Open WebUI and the supporting packages needed to run the application smoothly inside Google Colab. After that, we securely enter our OpenAI API key through terminal input and define the default model that we want Open WebUI to use. Copy Code Copied Use a different Browser os.environ["ENABLE_OPENAI_API"] = "True" os.environ["OPENAI_API_KEY"] = openai_api_key os.environ["OPENAI_API_BASE_URL"] = "https://api.openai.com/v1" os.environ["WEBUI_SECRET_KEY"] = secrets.token_hex(32) os.environ["WEBUI_NAME"] = "Open WebUI on Colab" os.environ["DEFAULT_MODELS"] = default_model data_dir = Path("/content/open-webui-data") data_dir.mkdir(parents=True, exist_ok=True) os.environ["DATA_DIR"] = str(data_dir) We configure the environment variables that allow Open WebUI to connect properly with the OpenAI API. We store the API key, define the OpenAI base endpoint, generate a secret key for the web interface, and assign a default model and interface name for the session. We also create a dedicated data directory in the Colab environment so that Open WebUI has a structured location to store its runtime data. Copy Code Copied Use a different Browser cloudflared_path = Path("/content/cloudflared") if not cloudflared_path.exists(): print("\nDownloading cloudflared...") url = "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64" urllib.request.urlretrieve(url, cloudflared_path) cloudflared_path.chmod(0o755) print("\nStarting Open WebUI server...") server_log = open("/content/open-webui-server.log", "w") server_proc = subprocess.Popen( ["open-webui", "serve"], stdout=server_log, stderr=subprocess.STDOUT, env=os.environ.copy() ) We prepare the tunnel component by downloading the CloudFlare binary if it is not already available in the Colab environment. Once that is ready, we start the Open WebUI server and direct its output into a log file so that we can inspect its behavior if needed. This part of the tutorial sets up the core application process that powers the browser-based interface. Copy Code Copied Use a different Browser local_url = "http://127.0.0.1:8080" ready = False for _ in range(120): try: import requests r = requests.get(local_url, timeout=2) if r.status_code < 500: ready = True break except Exception: pass time.sleep(2) if not ready: server_log.close() with open("/content/open-webui-server.log", "r") as f: logs = f.read()[-4000:] raise RuntimeError( "Open WebUI did not start successfully.\n\n" "Recent logs:\n" f"{logs}" ) print("Open WebUI is running locally at:", local_url) print("\nCreating public tunnel...") tunnel_proc = subprocess.Popen( [str(cloudflared_path), "tunnel", "--url", local_url, "--no-autoupdate"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True ) We repeatedly check whether the Open WebUI server has started successfully on the local Colab port. If the server does not start properly, we read the recent logs and raise a clear error so that we can understand what went wrong. Once the server is confirmed to be running, we create a public tunnel to make the local interface accessible from outside Colab. Copy Code Copied Use a different Browser public_url = None start_time = time.time() while time.time() - start_time < 90: line = tunnel_proc.stdout.readline() if not line: time.sleep(1) continue match = re.search(r"https://[-a-zA-Z0-9]+\.trycloudflare\.com", line) if match: public_url = match.group(0) break if not public_url: with open("/content/open-webui-server.log", "r") as f: server_logs = f.read()[-3000:] raise RuntimeError( "Tunnel started but no public URL was captured.\n\n" "Open WebUI server logs:\n" f"{server_logs}" ) print("\n" + "=" * 80) print("Open WebUI is ready.") print("Public URL:", public_url) print("Local URL :", local_url) print("=" * 80) print("\nWhat to do next:") print("1. Open the Public URL.") print("2. Create your admin account the first time you open it.") print("3. Go to the model selector and choose:", default_model) print("4. Start chatting with OpenAI through Open WebUI.") print("\nUseful notes:") print("- Your OpenAI API key was passed through environment variables.") print("- Data persists only for the current Colab runtime unless you mount Drive.") print("- If the tunnel stops, rerun the cell.") def tail_open_webui_logs(lines=80): log_path = "/content/open-webui-server.log" if not os.path.exists(log_path): print("No server log found.") return with open(log_path, "r") as f: content = f.readlines() print("".join(content[-lines:])) def stop_open_webui(): global server_proc, tunnel_proc, server_log for proc in [tunnel_proc, server_proc]: try: if proc and proc.poll() is None: proc.terminate() except Exception: pass try: server_log.close() except Exception: pass print("Stopped Open WebUI and tunnel.") print("\nHelpers available:") print("- tail_open_webui_logs()") print("- stop_open_webui()") We capture the public tunnel URL and print the final access details so that we can open Open WebUI directly in the browser. We also display the next steps for using the interface, including creating an admin account and selecting the configured model. Also, we define helper functions for checking logs and stopping the running processes, which makes the overall setup easier for us to manage and reuse. In conclusion, we created a fully functional Open WebUI deployment on Colab and connected it to OpenAI in a secure, structured manner. We installed the application and its supporting packages, provided authentication details via protected input, configured the backend connection to the OpenAI API, and started the local web server powering the interface. We then exposed that server through a public tunnel, making the application usable through a browser without requiring local installation on our machine. In addition, we included helper functions for viewing logs and stopping the running services, which makes the setup easier to manage and troubleshoot during experimentation. Overall, we established a reusable, practical workflow that helps us quickly spin up Open WebUI in Colab,