How can I add citations at the end of my AI assistant’s answers based on the sources it retrieves content from?

I’m developing an AI assistant that fetches information from various URLs and uses this information to answer user queries. I want to include citations or reference links at the end of each answer to credit the sources accurately. Currently, the assistant retrieves multiple URLs but doesn’t always use relevant ones in its responses. How can I modify my code to ensure that only relevant URLs are included in the citations at the end of the AI’s answers?

# Function to fetch URLs (sublinks) from the website and save them to urls.txt

# Function to fetch and extract text content from a website using Requests
    

def main():


    # Calling function
    website_urls = fetch_urls()

    if not website_urls:
        st.error("No URLs fetched from the CSUSB IT Knowledge Base.")
        return

    documents = []

    # Fetch content from each website in parallel
    with ThreadPoolExecutor(max_workers=5) as executor:
        futures = [executor.submit(fetch_website_content, url) for url in website_urls]
        for future in futures:
            text_content, image_urls, fetched_url = future.result()
            if text_content:
                documents.append(Document(page_content=text_content, metadata={"source": fetched_url, "images": image_urls}))

    if not documents:
        st.error("No content fetched from the websites.")
        return

    # Load, create vector store
    vector_store_path = "vectorstore.pkl"
    if os.path.exists(vector_store_path):
        with open(vector_store_path, "rb") as f:
            vectorstore = pickle.load(f)
    else:
        document_embedder = Embeddings(model="name", model_type="passage")
        vectorstore = FAISS.from_documents(documents, document_embedder)
        with open(vector_store_path, "wb") as f:
            pickle.dump(vectorstore, f)
        st.success("Vector store created successfully.")

    # Initialize models
    llm = Chat(model="name")
    prompt_template = ChatPromptTemplate.from_messages(
        [("system", "You are an AI Assistant..."), ("user", "{input}")]
    )
    chain = prompt_template | llm | StrOutputParser()


    # Input form
    with st.form(key='chat_form', clear_on_submit=True):
        user_input = st.text_input("Ask your question:", key="user_input")
        submitted = st.form_submit_button("Send")

    # Handle user input and generate response
    if submitted and user_input and vectorstore is not None:
        st.session_state.messages.insert(0, {"role": "user", "content": user_input})

        # Retrieve relevant documents from vectorstore
        retriever = vectorstore.as_retriever()
        relevant_docs = retriever.get_relevant_documents(user_input)

        # Combine relevant texts into context and collect unique sources
        relevant_sources = set()
        context = []
        for doc in relevant_docs:
            context.append(doc.page_content)
            relevant_sources.add(doc.metadata["source"])

        context = "nn".join(context)
        augmented_user_input = f"Context: {context}nnQuestion: {user_input}"

        # Invoke the AI assistant with augmented input
        response = chain.invoke({"input": augmented_user_input})

        if relevant_sources:
            response_content = f"{response}nnSources:n" + "n".join(relevant_sources)
        else:
            response_content = response

        st.session_state.messages.insert(0, {"role": "assistant", "content": response_content})

New contributor

Liam Mason is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật