import os
import openai
# Securely fetch the API key from environment variables
= os.getenv('OPENAI_API_KEY')
api_key
= api_key
openai.api_key
from langchain.embeddings.openai import OpenAIEmbeddings
= OpenAIEmbeddings()
embed_object
from langchain.vectorstores import Chroma
= "db/chroma_dbs"
chroma_store_directory
# Initialize Chroma with the specified directory and embedding function
= Chroma(persist_directory=chroma_store_directory, embedding_function=embed_object)
vectordb
# Now, you can proceed with using vectordb to store or retrieve embeddings
16 VectorDB with shiny
16.1 load vectorDB
16.2 shiny
for global
library(shiny)
library(reticulate)
library(rmarkdown)
library(httr)
library(jsonlite)
library(httr)
library(jsonlite)
source_python("pyscript/load_db.py")
source("source/translate_text_with_openai.R")
for ui
<- fluidPage(
ui titlePanel("업무관련성 지식서치"),
textInput("question_kr", "질문 (한국어):", ""),
actionButton("submit", "Ask"),
htmlOutput("answer")
)
for server
<- function(input, output) {
server observeEvent(input$submit, {
<- input$question_kr
question_kr
# 한국어 질문을 영어로 번역 (httr 사용, 오류 처리 포함)
<- tryCatch(
question_en translate_to_english_httr(question_kr, api_key),
error = function(e) {
sprintf("번역 오류 (한국어 -> 영어): %s", e$message)
}
)
# 번역 오류 처리
if (grepl("Error", question_en)) {
$answer <- renderUI({
outputHTML(paste("<b>오류:</b>", question_en))
})return()
}
# 영어 질문으로 답변 얻기 (오류 처리 포함)
<- tryCatch({
answer_en py_run_string(sprintf('
my_question = "%s"
sim_docs = vectordb.similarity_search(my_question)
mm_docs = vectordb.max_marginal_relevance_search(my_question, k = 3, fetch_k = 5)
from langchain.chat_models import ChatOpenAI
the_llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
from langchain.chains import RetrievalQA
qa_chain = RetrievalQA.from_chain_type(the_llm,retriever=vectordb.as_retriever())
answer = qa_chain.run(my_question)
', stringr::str_replace_all(question_en, '"', '\\"')))
error = function(e) {
}, sprintf("답변 생성 오류: %s", e$message)
$answer
})
# 답변 생성 오류 처리
if (grepl("Error", answer_en)) {
$answer <- renderUI({
outputHTML(paste("<b>오류:</b>", answer_en))
})return()
}
# 영어 답변을 한국어로 번역 (httr 사용, 오류 처리 포함)
<- tryCatch(
answer_kr translate_to_english_httr(answer_en, api_key, target_lang = "ko"),
error = function(e) {
sprintf("번역 오류 (영어 -> 한국어): %s", e$message)
}
)
# 번역 오류 처리
if (grepl("Error", answer_kr)) {
$answer <- renderUI({
outputHTML(paste("<b>오류:</b>", answer_kr))
})return()
}
# Format answer using Markdown
<- sprintf(
markdown_content "## 질문 (한국어):
%s
## 질문 (영어):
%s
## 답변 (한국어):
%s", question_kr, question_en, answer_kr)
# Convert Markdown to HTML
<- markdown::renderMarkdown(text = markdown_content)
html_content
# Display the HTML content
$answer <- renderUI({
outputHTML(html_content)
})
}) }