FastAPI 배포 Ollama 시각적 대화 인터페이스
I. 카탈로그 구조
리포지토리 노트북은 C6 폴더에 있습니다:
fastapi_chat_app/
│
├── app.py
├── websocket_handler.py
├── static/
│ └── index.html
└── requirements.txt
app.py
FastAPI 애플리케이션의 주요 설정 및 라우팅.websocket_handler.py
웹소켓 연결 및 메시지 스트림을 처리합니다.static/index.html
HTML 페이지.requirements.txt
필수 종속성은 pip install -r requirements.txt를 통해 설치됩니다.
II. 이 창고의 복제
git clone https://github.com/AXYZdong/handy-ollama
III. 종속성 설치
pip install -r requirements.txt
IV. 핵심 코드
app.py
파일의 핵심 코드는 다음과 같습니다:
import ollama
from fastapi import WebSocket
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept() # 接受WebSocket连接
user_input = await websocket.receive_text() # 接收用户输入的文本消息
stream = ollama.chat( # 使用ollama库与指定模型进行对话
model='llama3.1', # 指定使用的模型为llama3.1
messages=[{'role': 'user', 'content': user_input}], # 传入用户的输入消息
stream=True # 启用流式传输
)
try:
for chunk in stream: # 遍历流式传输的结果
model_output = chunk['message']['content'] # 获取模型输出的内容
await websocket.send_text(model_output) # 通过WebSocket发送模型输出的内容
except Exception as e: # 捕获异常
await websocket.send_text(f"Error: {e}") # 通过WebSocket发送错误信息
finally:
await websocket.close() # 关闭WebSocket连接
웹소켓 연결을 수락합니다:
await websocket.accept()
: 먼저 이 함수는 클라이언트로부터 웹소켓 연결 요청을 수락하고 클라이언트와 통신 채널을 설정합니다.
사용자 입력을 받습니다:
user_input = await websocket.receive_text()
웹소켓을 통해 클라이언트로부터 문자 메시지를 수신하여 사용자 입력을 받습니다.
대화 스트림을 초기화합니다:
stream = ollama.chat(...)
ollama 라이브러리에서 채팅 메서드를 호출하고 사용된 모델이 llama3.1임을 지정합니다. 사용자 입력을 메시지로 모델에 전달하고 스트리밍을 활성화(stream=True)하여 모델이 생성한 응답을 점진적으로 받도록 합니다.
모델 출력 처리:
for chunk in stream
모델에서 스트리밍된 데이터 블록을 반복합니다.model_output = chunk['message']['content']
각 데이터 블록에서 모델 생성 텍스트 콘텐츠를 추출합니다.await websocket.send_text(model_output)
추출된 모델 응답을 웹소켓을 통해 클라이언트로 다시 전송하여 실시간 대화를 진행합니다.
예외 처리:
except Exception as e
처리 중 예외가 발생하면(예: 네트워크 문제, 모델 오류 등) 예외를 포착하고 WebSocket을 통해 오류 메시지를 전송하여 클라이언트에게 오류가 발생했음을 알립니다.
웹소켓 연결을 닫습니다:
finally
예외 발생 여부와 관계없이 궁극적으로 WebSocket 연결이 종료되어 리소스를 확보하고 세션을 종료합니다.
V. 앱 실행
- 디렉토리(
fastapi_chat_app/
); - app.py 파일을 실행합니다.
uvicorn app:app --reload
페이지를 엽니다.

백그라운드에서 일반 출력이 표시됩니다.

© 저작권 정책
이 글은 저작권이 있으며 무단으로 복제해서는 안 됩니다.
관련 문서
댓글 없음...