|
import streamlit as st |
|
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings |
|
from llama_index.embeddings.huggingface import HuggingFaceEmbedding |
|
from llama_index.legacy.callbacks import CallbackManager |
|
from llama_index.llms.openai_like import OpenAILike |
|
|
|
|
|
callback_manager = CallbackManager() |
|
|
|
api_base_url = "https://internlm-chat.intern-ai.org.cn/puyu/api/v1/" |
|
model = "internlm2.5-latest" |
|
api_key = "eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJqdGkiOiIxNzAwMzA3OCIsInJvbCI6IlJPTEVfUkVHSVNURVIiLCJpc3MiOiJPcGVuWExhYiIsImlhdCI6MTczMzc1OTE4OCwiY2xpZW50SWQiOiJlYm1ydm9kNnlvMG5semFlazF5cCIsInBob25lIjoiMTg0MDY1MDk1NTgiLCJ1dWlkIjoiNzJhNWJhZmEtYjI3MC00NTVmLWJlYTgtYzViYmNiNDM3YWYxIiwiZW1haWwiOiIiLCJleHAiOjE3NDkzMTExODh9.D1Z-XG0-ZY7ZsSRAGq6V6hrzV8Pk9EgDHthSZZYCcK30-yiHPdRuB4kR4_96azWKbEO_G_nvhrNmKlHHCVAV1w" |
|
|
|
|
|
|
|
|
|
|
|
llm =OpenAILike(model=model, api_base=api_base_url, api_key=api_key, is_chat_model=True,callback_manager=callback_manager) |
|
|
|
|
|
|
|
st.set_page_config(page_title="llama_index_demo", page_icon="🦜🔗") |
|
st.title("llama_index_demo") |
|
|
|
|
|
@st.cache_resource |
|
def init_models(): |
|
embed_model = HuggingFaceEmbedding( |
|
model_name="model/sentence-transformer" |
|
) |
|
Settings.embed_model = embed_model |
|
|
|
|
|
Settings.llm = llm |
|
|
|
documents = SimpleDirectoryReader("data").load_data() |
|
index = VectorStoreIndex.from_documents(documents) |
|
query_engine = index.as_query_engine() |
|
|
|
return query_engine |
|
|
|
|
|
if 'query_engine' not in st.session_state: |
|
st.session_state['query_engine'] = init_models() |
|
|
|
def greet2(question): |
|
response = st.session_state['query_engine'].query(question) |
|
return response |
|
|
|
|
|
|
|
if "messages" not in st.session_state.keys(): |
|
st.session_state.messages = [{"role": "assistant", "content": "你好,我是你的助手,有什么我可以帮助你的吗?"}] |
|
|
|
|
|
for message in st.session_state.messages: |
|
with st.chat_message(message["role"]): |
|
st.write(message["content"]) |
|
|
|
def clear_chat_history(): |
|
st.session_state.messages = [{"role": "assistant", "content": "你好,我是你的助手,有什么我可以帮助你的吗?"}] |
|
|
|
st.sidebar.button('Clear Chat History', on_click=clear_chat_history) |
|
|
|
|
|
def generate_llama_index_response(prompt_input): |
|
return greet2(prompt_input) |
|
|
|
|
|
if prompt := st.chat_input(): |
|
st.session_state.messages.append({"role": "user", "content": prompt}) |
|
with st.chat_message("user"): |
|
st.write(prompt) |
|
|
|
|
|
if st.session_state.messages[-1]["role"] != "assistant": |
|
with st.chat_message("assistant"): |
|
with st.spinner("Thinking..."): |
|
response = generate_llama_index_response(prompt) |
|
placeholder = st.empty() |
|
placeholder.markdown(response) |
|
message = {"role": "assistant", "content": response} |
|
st.session_state.messages.append(message) |
|
|