Я пытаюсь интегрировать GoogleGenerativeAIEmbeddings из библиотеки langchain_google_genai в свое приложение Streamlit. Однако я сталкиваюсь с ошибкой ValidationError, связанной с отсутствующими полями, когда пытаюсь создать объект GoogleGenerativeAIEmbeddings. Вот сообщение об ошибке, которое я вижу:
ValidationError: 1 validation error for GoogleGenerativeAIEmbeddings
model field required (type=value_error.missing)
Traceback:
File "E:\Project_Gen_AI\chat-with-website\Lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 600, in _run_script
exec(code, module.__dict__)
File "E:\Project_Gen_AI\src\demo2.py", line 84, in
st.session_state.vector_store = get_vectorstore_from_url(website_URL)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Project_Gen_AI\src\demo2.py", line 31, in get_vectorstore_from_url
vectorstore = Chroma.from_documents(document_chunks, GoogleGenerativeAIEmbeddings(api_key=GOOGLE_API_KEY))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Project_Gen_AI\chat-with-website\Lib\site-packages\pydantic\v1\main.py", line 341, in __init__
raise validation_error
from dotenv import load_dotenv
import os
import streamlit as st
from langchain_core.messages import AIMessage, HumanMessage
from langchain_community.document_loaders import WebBaseLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import Chroma
from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
from dotenv import load_dotenv
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.chains import create_history_aware_retriever, create_retrieval_chain
from langchain.chains.combine_documents import create_stuff_documents_chain
load_dotenv()
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
def get_response(user_query):
return "First, please build me"
def get_vectorstore_from_url(url):
loader = WebBaseLoader(url)
document = loader.load()
# Split the document into chunks using the RecursiveCharacterTextSplitter
text_splitter = RecursiveCharacterTextSplitter()
document_chunks = text_splitter.split_documents(document)
# Create a vectorstore from the chunks
vectorstore = Chroma.from_documents(document_chunks, GoogleGenerativeAIEmbeddings(api_key=GOOGLE_API_KEY))
return vectorstore
def get_context_retriever_chains(vectorstore):
llm = ChatGoogleGenerativeAI(api_key=GOOGLE_API_KEY)
retriever = vectorstore.as_retriever()
prompt = ChatPromptTemplate.format_messages([
MessagesPlaceholder(variable_name="chat_history"),
("user", "{input}"),
("user", "Given the above conversation, generate a search query to look up in order to get information relevant to the conversation")
])
retriever_chain = create_history_aware_retriever(llm, retriever, prompt)
return retriever_chain
def get_conversational_rag_chain(retriever_chain):
llm = ChatGoogleGenerativeAI(api_key=GOOGLE_API_KEY)
prompt = ChatPromptTemplate.format_messages([
("system", "Answer the user's questions based on the below context:\n\n{context}\n"),
MessagesPlaceholder(variable_name="chat_history"),
("user", "{input}")
])
stuff_documents_chain = create_stuff_documents_chain(llm, prompt)
return create_retrieval_chain(retriever_chain, stuff_documents_chain)
# For the interface
st.set_page_config(page_title="Chat-with-website", page_icon="💬")
st.title("Chat with website")
# App Sidebar
with st.sidebar:
st.header("Settings")
website_URL = st.text_input("Website url")
# Check if the website URL is provided
if website_URL is None or website_URL == "":
st.info("Please enter a website url")
# Load documents from the provided URL using the WebBaseLoader
else:
# Session state
if "chat_history" not in st.session_state:
st.session_state.chat_history = [
AIMessage(content="Hello, I am a bot. How can I help you"),
]
if "vector_store" not in st.session_state:
st.session_state.vector_store = get_vectorstore_from_url(website_URL)
retriever_chain = get_context_retriever_chains(st.session_state.vector_store)
conversation_rag_chain = get_conversational_rag_chain(retriever_chain)
# CHAT HISTORY / AI response to User Input
user_query = st.chat_input("Type your message here... ")
if user_query is not None and user_query != "":
response = conversation_rag_chain.invoke({
"chat_history": st.session_state.chat_history,
"input": user_query
})
st.write(response)
st.session_state.chat_history.append(HumanMessage(content=user_query))
st.session_state.chat_history.append(AIMessage(content=response))
# Iterate through the chat history stored in the session state
for message in st.session_state.chat_history:
# Check if the message is an instance of AIMessage
if isinstance(message, AIMessage):
# Display the AI message in the chat interface
with st.chat_message("AI"):
st.write(message.content)
# Check if the message is an instance of HumanMessage
elif isinstance(message, HumanMessage):
# Display the Human message in the chat interface
with st.chat_message("Human"):
st.write(message.content)
Я подозреваю, что мне не хватает некоторых обязательных параметров при инициализации GoogleGenerativeAIEmbeddings, но я не могу найти никакой документации или примеров, показывающих, какими должны быть эти параметры.
Что может быть причиной этой ошибки проверки и как ее устранить?
Спасибо за помощь!
Я пытаюсь интегрировать GoogleGenerativeAIEmbeddings из библиотеки langchain_google_genai в свое приложение Streamlit. Однако я сталкиваюсь с ошибкой ValidationError, связанной с отсутствующими полями, когда пытаюсь создать объект GoogleGenerativeAIEmbeddings. Вот сообщение об ошибке, которое я вижу: [code]ValidationError: 1 validation error for GoogleGenerativeAIEmbeddings model field required (type=value_error.missing) Traceback: File "E:\Project_Gen_AI\chat-with-website\Lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 600, in _run_script exec(code, module.__dict__) File "E:\Project_Gen_AI\src\demo2.py", line 84, in st.session_state.vector_store = get_vectorstore_from_url(website_URL) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\Project_Gen_AI\src\demo2.py", line 31, in get_vectorstore_from_url vectorstore = Chroma.from_documents(document_chunks, GoogleGenerativeAIEmbeddings(api_key=GOOGLE_API_KEY)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\Project_Gen_AI\chat-with-website\Lib\site-packages\pydantic\v1\main.py", line 341, in __init__ raise validation_error [/code] [code]from dotenv import load_dotenv import os
import streamlit as st from langchain_core.messages import AIMessage, HumanMessage from langchain_community.document_loaders import WebBaseLoader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_community.vectorstores import Chroma from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI from dotenv import load_dotenv from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain.chains import create_history_aware_retriever, create_retrieval_chain from langchain.chains.combine_documents import create_stuff_documents_chain
load_dotenv()
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
def get_response(user_query): return "First, please build me"
# Split the document into chunks using the RecursiveCharacterTextSplitter text_splitter = RecursiveCharacterTextSplitter() document_chunks = text_splitter.split_documents(document)
# Create a vectorstore from the chunks vectorstore = Chroma.from_documents(document_chunks, GoogleGenerativeAIEmbeddings(api_key=GOOGLE_API_KEY))
prompt = ChatPromptTemplate.format_messages([ MessagesPlaceholder(variable_name="chat_history"), ("user", "{input}"), ("user", "Given the above conversation, generate a search query to look up in order to get information relevant to the conversation") ])
prompt = ChatPromptTemplate.format_messages([ ("system", "Answer the user's questions based on the below context:\n\n{context}\n"), MessagesPlaceholder(variable_name="chat_history"), ("user", "{input}") ])
# For the interface st.set_page_config(page_title="Chat-with-website", page_icon="💬") st.title("Chat with website")
# App Sidebar with st.sidebar: st.header("Settings") website_URL = st.text_input("Website url")
# Check if the website URL is provided if website_URL is None or website_URL == "": st.info("Please enter a website url")
# Load documents from the provided URL using the WebBaseLoader else: # Session state if "chat_history" not in st.session_state: st.session_state.chat_history = [ AIMessage(content="Hello, I am a bot. How can I help you"), ] if "vector_store" not in st.session_state: st.session_state.vector_store = get_vectorstore_from_url(website_URL)
# CHAT HISTORY / AI response to User Input user_query = st.chat_input("Type your message here... ") if user_query is not None and user_query != "": response = conversation_rag_chain.invoke({ "chat_history": st.session_state.chat_history, "input": user_query }) st.write(response) st.session_state.chat_history.append(HumanMessage(content=user_query)) st.session_state.chat_history.append(AIMessage(content=response))
# Iterate through the chat history stored in the session state for message in st.session_state.chat_history: # Check if the message is an instance of AIMessage if isinstance(message, AIMessage): # Display the AI message in the chat interface with st.chat_message("AI"): st.write(message.content) # Check if the message is an instance of HumanMessage elif isinstance(message, HumanMessage): # Display the Human message in the chat interface with st.chat_message("Human"): st.write(message.content) [/code] Я подозреваю, что мне не хватает некоторых обязательных параметров при инициализации GoogleGenerativeAIEmbeddings, но я не могу найти никакой документации или примеров, показывающих, какими должны быть эти параметры. Что может быть причиной этой ошибки проверки и как ее устранить? Спасибо за помощь!
Я пытаюсь интегрировать GoogleGenerativeAIEmbeddings из библиотеки langchain_google_genai в свое приложение Streamlit. Однако я сталкиваюсь с ошибкой ValidationError, связанной с отсутствующими полями, когда пытаюсь создать объект...
Я использую следующий код
const Ort::Value &img_file_to_tensor(std::string input_img_path) {
// Load the image using OpenCV
cv::Mat input_mat = cv::imread(input_img_path);
// Convert to float
cv::cvtColor(input_mat, input_mat, cv::COLOR_BGR2RGB);...
Я не понимаю, что использовать: использовать обновление или копию для изменения/обновления состояния пользовательского интерфейса в компоновке реактивного ранца
Некоторые говорят, что используют
_uiState.update {
it.copy()
}
Я не понимаю, что использовать: использовать обновление или копию для изменения/обновления состояния пользовательского интерфейса в компоновке реактивного ранца
Некоторые говорят, что используют
_uiState.update {
it.copy()
}
Я не понимаю, что использовать: использовать обновление или копию для изменения/обновления состояния пользовательского интерфейса в компоновке реактивного ранца
Некоторые говорят, что используют
_uiState.update {
it.copy()
}