Skip to content

Commit 6206e8e

Browse files
Merge branch 'main' into GitHub-Analytics-Update
2 parents 2dfb168 + 0cc8e29 commit 6206e8e

File tree

44 files changed

+1571
-676
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+1571
-676
lines changed

ai-and-app-modernisation/ai-services/generative-ai-service/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ Reviewed: 30.01.2024
1111

1212
# Team Publications
1313

14+
- [Enable a Low Code Modular LLM App Engine using Oracle Integration and OCI Generative AI](https://docs.oracle.com/en/solutions/oci-generative-ai-integration/index.html)
15+
- This reference architecture lets you understand the necessary considerations and recommendations to enable an AI-based, modular and event-driven LLM App Engine using a low-code approach with Oracle Integration as the LLM orchestrator, OCI Generative AI and other OCI services
16+
- Build enterprise-grade, modular, scalable, secure & maintainable LLM Apps
1417
- [Oracle Generative AI webinar](https://go.oracle.com/LP=138234?elqCampaignId=489428&src1=:so:ch:or:dg::::&SC=:so:ch:or:dg::::&pcode=WWMK230822P00010)
1518
- Deep dive into Oracle Generative AI platform
1619
- [Creating a RAG (Retrieval-Augmented Generation) with Oracle Generative AI Service in just 21 lines of code](https://github.com/oracle-devrel/technology-engineering/tree/main/ai-and-app-modernisation/ai-services/generative-ai-service/rag-genai)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from langchain_community.embeddings import OCIGenAIEmbeddings
2+
from langchain.chains import RetrievalQA
3+
from langchain_community.vectorstores import Qdrant
4+
from langchain_core.prompts import PromptTemplate
5+
from langchain_community.llms import OCIGenAI
6+
from langchain_community.document_loaders import UnstructuredURLLoader
7+
compartment_id = "ocid1.compartment.oc1..aaaaaaaa7ggqkd4ptkeb7ugk6ipsl3gqjofhkr6yacluwj4fitf2ufrdm65q"
8+
embeddings = OCIGenAIEmbeddings(model_id="cohere.embed-english-light-v3.0",service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",compartment_id= compartment_id,)
9+
testurls = ['https://docs.oracle.com/iaas/odsaz/odsa-rotate-wallet.html', 'https://docs.oracle.com/iaas/odsaz/odsa-change-password.html', 'https://docs.oracle.com/iaas/odsaz/odsa-database-actions.html']
10+
loader = UnstructuredURLLoader(urls=testurls)
11+
docs = loader.load()
12+
vectorstore = Qdrant.from_documents(docs,embeddings,location=":memory:",prefer_grpc=False,collection_name="test_db")
13+
retriever = vectorstore.as_retriever()
14+
rag_prompt_template = """Answer the question based only on the following context:
15+
{context}
16+
Question: {question}"""
17+
rag_prompt = PromptTemplate.from_template(rag_prompt_template)
18+
llm = OCIGenAI(model_id="cohere.command",service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",compartment_id= compartment_id,model_kwargs={"temperature": 0, "max_tokens": 300})
19+
rag = RetrievalQA.from_chain_type(llm=llm,retriever=retriever,chain_type_kwargs={"prompt": rag_prompt,},)
20+
data = rag.invoke("What is rotate a wallet")
21+
print(data['result'])

ai-and-app-modernisation/ai-services/generative-ai-service/rag-genai/files/README.md

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,30 +3,27 @@
33
## Introduction
44
In this article, we'll explore how to create a Retrieval-Augmented Generation (RAG) model using Oracle Gen AI, llama index, Qdrant Vector Database, and SentenceTransformerEmbeddings. This 21-line code will allow you to scrape through web pages, use llama index for indexing, Oracle Generative AI Service for question generation, and Qdrant for vector indexing.
55

6+
Find below the code of building a RAG using llamaIndex with Oracle Generative AI Service.
7+
Also check the file LangChainRAG.py which allows you to create an application (implementing RAG) using Langchain and the file langChainRagWithUI.py which includes a UI build with Streamlit.
8+
69
<img src="./RagArchitecture.svg">
710
</img>
811

9-
## Limited Availability
10-
11-
Oracle Generative AI Service is in Limited Availability as of today when we are creating this repo.
12-
13-
Customers can easily enter in the LA programs. To test these functionalities you need to enrol in the LA programs and install the proper versions of software libraries.
14-
15-
Code and functionalities can change, as a result of changes and new features
16-
1712
## Prerequisites
1813

1914
Before getting started, make sure you have the following installed:
2015

2116
- Oracle Generative AI Service
22-
- llama index
23-
- qdrant client
17+
- Llama index
18+
- Langchain
19+
- Qdrant client
2420
- SentenceTransformerEmbeddings
2521

2622
## Setting up the Environment
2723
1. Install the required packages:
2824
```bash
29-
pip install oci==2.118.1+preview.1.1697 llama-index qdrant-client sentence-transformers
25+
pip install -U langchain oci
26+
pip install langchain llama-index qdrant-client sentence-transformers transformers
3027
```
3128

3229
## Loading data
@@ -41,26 +38,26 @@ sitemap used : https://objectstorage.eu-frankfurt-1.oraclecloud.com/n/frpj5kvxry
4138
## Entire code
4239

4340
```bash
44-
from genai_langchain_integration.langchain_oci import OCIGenAI
4541
from llama_index import VectorStoreIndex
4642
from llama_index import ServiceContext
4743
from llama_index.vector_stores.qdrant import QdrantVectorStore
4844
from llama_index.storage.storage_context import StorageContext
4945
from qdrant_client import qdrant_client
50-
from langchain.embeddings import SentenceTransformerEmbeddings
46+
from langchain_community.embeddings import SentenceTransformerEmbeddings
5147
from llama_hub.web.sitemap import SitemapReader
48+
from langchain_community.llms import OCIGenAI
5249
loader = SitemapReader()
53-
documents = loader.load_data(sitemap_url='https://objectstorage.eu-frankfurt-1.oraclecloud.com/n/frpj5kvxryk1/b/thisIsThePlace/o/combined.xml')
50+
documents = loader.load_data(sitemap_url='https://objectstorage.eu-frankfurt-1.oraclecloud.com/n/frpj5kvxryk1/b/thisIsThePlace/o/latest.xml')
5451
client = qdrant_client.QdrantClient(location=":memory:")
5552
embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
56-
llm = OCIGenAI(model_id="cohere.command",service_endpoint="https://generativeai.aiservice.us-chicago-1.oci.oraclecloud.com",compartment_id = "ocid1.tenancy.oc1..aaaaaaaa5hwtrus75rauufcfvtnjnz3mc4xm2bzibbigva2bw4ne7ezkvzha",temperature=0.0)
53+
llm = OCIGenAI(model_id="cohere.command",service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",model_kwargs={"temperature": 0.0, "max_tokens": 300},compartment_id = "ocid1.compartment.oc1..aaaaaaaa7ggqkd4ptkeb7ugk6ipsl3gqjofhkr6yacluwj4fitf2ufrdm65q")
5754
system_prompt="As a support engineer, your role is to leverage the information in the context provided. Your task is to respond to queries based strictly on the information available in the provided context. Do not create new information under any circumstances. Refrain from repeating yourself. Extract your response solely from the context mentioned above. If the context does not contain relevant information for the question, respond with 'How can I assist you with questions related to the document?"
5855
service_context = ServiceContext.from_defaults(llm=llm, chunk_size=1000, chunk_overlap=100, embed_model=embeddings,system_prompt=system_prompt)
5956
vector_store = QdrantVectorStore(client=client, collection_name="ansh")
6057
storage_context = StorageContext.from_defaults(vector_store=vector_store)
6158
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context, service_context=service_context)
6259
query_engine = index.as_query_engine()
63-
response = query_engine.query("can i use OCI document understanding for files in french ?")
60+
response = query_engine.query('What is activity auditing report?')
6461
print(response)
6562
```
6663

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import streamlit as st
2+
from langchain_community.embeddings import OCIGenAIEmbeddings
3+
from langchain.chains import RetrievalQA
4+
from langchain_community.vectorstores import Qdrant
5+
from langchain_core.prompts import PromptTemplate
6+
from langchain_community.llms import OCIGenAI
7+
from langchain_community.document_loaders import UnstructuredURLLoader
8+
st.title("Oracle QA Chatbot")
9+
st.text_input("Ask a question:", key="question") # Input field for questions
10+
# Data loading (outside any function)
11+
compartment_id = "ocid1.compartment.oc1..aaaaaaaa7ggqkd4ptkeb7ugk6ipsl3gqjofhkr6yacluwj4fitf2ufrdm65q"
12+
embeddings = OCIGenAIEmbeddings(model_id="cohere.embed-english-light-v3.0",service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",compartment_id=compartment_id,)
13+
testurls = ['https://docs.oracle.com/iaas/odsaz/odsa-rotate-wallet.html','https://docs.oracle.com/iaas/odsaz/odsa-change-password.html','https://docs.oracle.com/iaas/odsaz/odsa-database-actions.html',]
14+
# Cache the loaded documents (outside any function)
15+
@st.cache_data
16+
def load_documents():
17+
docs = UnstructuredURLLoader(urls=testurls).load()
18+
print("Loading data")
19+
print(docs)
20+
return docs # Return the loaded documents
21+
docs = load_documents()
22+
vectorstore = Qdrant.from_documents(docs, embeddings, location=":memory:", prefer_grpc=False, collection_name="test_db")
23+
retriever = vectorstore.as_retriever()
24+
rag_prompt_template = """Answer the question based only on the following context:
25+
{context}
26+
Question: {question}"""
27+
rag_prompt = PromptTemplate.from_template(rag_prompt_template)
28+
llm = OCIGenAI(
29+
model_id="cohere.command",
30+
service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",
31+
compartment_id=compartment_id,
32+
model_kwargs={"temperature": 0, "max_tokens": 300},
33+
)
34+
rag = RetrievalQA.from_chain_type(llm=llm, retriever=retriever, chain_type_kwargs={"prompt": rag_prompt})
35+
# Answer generation when a question is asked
36+
if st.button("Get Answer"):
37+
question = st.session_state.question
38+
# Ensure correct access to cached documents
39+
docs = load_documents() # Call the cached function to retrieve documents
40+
data = rag.invoke(question, context=docs) # Pass documents as context
41+
answer = data["result"]
42+
st.write("Answer:", answer)
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Document Summarization Using Oracle Generative AI
2+
3+
Text summarization, a core NLP task, unlocks the ability to distill lengthy content into concise, informative summaries. Large Language Models (LLMs) serve as powerful tools for summarizing a wide array of texts, including news articles, research papers, and technical documents. However, summarizing large documents comes with its own set of challenges, necessitating the application of specialized summarization strategies to indexed content.
4+
5+
In this article, we'll delve into the creation of a powerful document summarization solution leveraging Oracle Generative AI. Through the integration of Oracle Gen AI's advanced capabilities with cutting-edge technologies such as langchain. This codebase empowers users to effortlessly summarize extensive documents, harnessing the power of Oracle Generative AI Service.
6+
7+
<img src="./files/docSummarize.png">
8+
</img>
9+
10+
# When to use this asset?
11+
12+
See the README document in the /files folder.
13+
14+
# How to use this asset?
15+
16+
See the README document in the /files folder.
17+
18+
# License
19+
20+
Copyright (c) 2024 Oracle and/or its affiliates.
21+
22+
Licensed under the Universal Permissive License (UPL), Version 1.0.
23+
24+
See [LICENSE](https://github.com/oracle-devrel/technology-engineering/blob/main/LICENSE) for more details.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Prerequisites
2+
You need the latest versions of LangChain and the OCI software developer kit (SDK). To install and upgrade these two Python packages, use the following command:
3+
4+
pip install -U langchain oci
5+
pip install -r requirements. txt
6+
7+
# Running the application
8+
9+
You need to have your compartment id ready to use that
10+
11+
just run the command to launch the application
12+
13+
streamlit run ocidocumentSummarizeUpload.py
14+
15+
# More Info Links
16+
17+
How to run the application : https://www.youtube.com/watch?v=6A3KGyKy91Q&t=21s
18+
19+
Different methods of sumarization : https://medium.com/@anshuman4luv/revolutionizing-document-summarization-innovative-methods-with-langchain-and-large-language-models-f12272c7e8cd
20+
21+
22+
# License
23+
24+
Copyright (c) 2024 Oracle and/or its affiliates.
25+
26+
Licensed under the Universal Permissive License (UPL), Version 1.0.
27+
28+
See [LICENSE](https://github.com/oracle-devrel/technology-engineering/blob/main/LICENSE) for more details.
107 KB
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
#Author: Anshuman Panda
2+
import streamlit as st
3+
import os
4+
from langchain.document_loaders import PyPDFLoader
5+
from langchain.prompts import PromptTemplate
6+
from langchain.text_splitter import RecursiveCharacterTextSplitter
7+
from langchain.chains.summarize import load_summarize_chain
8+
from langchain_community.llms import OCIGenAI
9+
from pypdf import PdfReader
10+
from io import BytesIO
11+
from typing import Any, Dict, List
12+
import re
13+
from langchain.docstore.document import Document
14+
15+
16+
17+
@st.cache_data
18+
def parse_pdf(file: BytesIO) -> List[str]:
19+
pdf = PdfReader(file)
20+
output = []
21+
for page in pdf.pages:
22+
text = page.extract_text()
23+
# Merge hyphenated words
24+
text = re.sub(r"(\w+)-\n(\w+)", r"\1\2", text)
25+
# Fix newlines in the middle of sentences
26+
text = re.sub(r"(?<!\n\s)\n(?!\s\n)", " ", text.strip())
27+
# Remove multiple newlines
28+
text = re.sub(r"\n\s*\n", "\n\n", text)
29+
output.append(text)
30+
return output
31+
32+
@st.cache_data
33+
def text_to_docs(text: str,chunk_size,chunk_overlap) -> List[Document]:
34+
"""Converts a string or list of strings to a list of Documents
35+
with metadata."""
36+
print("I am here Ansh")
37+
print(chunk_size)
38+
print(chunk_overlap)
39+
if isinstance(text, str):
40+
# Take a single string as one page
41+
text = [text]
42+
page_docs = [Document(page_content=page) for page in text]
43+
44+
# Add page numbers as metadata
45+
for i, doc in enumerate(page_docs):
46+
doc.metadata["page"] = i + 1
47+
48+
# Ansh Split pages into chunks
49+
doc_chunks = []
50+
51+
for doc in page_docs:
52+
text_splitter = RecursiveCharacterTextSplitter(
53+
chunk_size=chunk_size,
54+
separators=["\n\n", "\n", ".", "!", "?", ",", " ", ""],
55+
chunk_overlap=chunk_overlap,
56+
)
57+
chunks = text_splitter.split_text(doc.page_content)
58+
for i, chunk in enumerate(chunks):
59+
doc = Document(
60+
page_content=chunk, metadata={"page": doc.metadata["page"], "chunk": i}
61+
)
62+
# Ansh Add sources a metadata
63+
doc.metadata["source"] = f"{doc.metadata['page']}-{doc.metadata['chunk']}"
64+
doc_chunks.append(doc)
65+
return doc_chunks
66+
67+
68+
def custom_summary(docs, llm, custom_prompt, chain_type, num_summaries):
69+
print("I am inside custom summary")
70+
custom_prompt = custom_prompt + """:\n {text}"""
71+
print("Ansh custom Prompt is ------>")
72+
print(custom_prompt)
73+
COMBINE_PROMPT = PromptTemplate(template=custom_prompt, input_variables = ["text"])
74+
print("Ansh combine Prompt is ------>")
75+
print(COMBINE_PROMPT)
76+
MAP_PROMPT = PromptTemplate(template="Summarize:\n{text}", input_variables=["text"])
77+
print("Ansh MAP_PROMPT Prompt is ------>")
78+
print(MAP_PROMPT)
79+
if chain_type == "map_reduce":
80+
chain = load_summarize_chain(llm,chain_type=chain_type,
81+
map_prompt=MAP_PROMPT,
82+
combine_prompt=COMBINE_PROMPT)
83+
else:
84+
chain = load_summarize_chain(llm,chain_type=chain_type)
85+
print("Chain is --->")
86+
print(chain)
87+
summaries = []
88+
for i in range(num_summaries):
89+
summary_output = chain({"input_documents": docs}, return_only_outputs=True)["output_text"]
90+
print("Summaries------------->")
91+
print(summary_output)
92+
summaries.append(summary_output)
93+
94+
return summaries
95+
96+
97+
def main():
98+
st.set_page_config(layout="wide")
99+
hide_streamlit_style = """
100+
<style>
101+
[data-testid="stToolbar"] {visibility: hidden !important;}
102+
footer {visibility: hidden !important;}
103+
</style>
104+
"""
105+
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
106+
st.title("Document Summarization App")
107+
108+
llm_name = st.sidebar.selectbox("LLM",["cohere.command","meta.llama-2-70b-chat"])
109+
110+
chain_type = st.sidebar.selectbox("Chain Type", ["map_reduce", "stuff", "refine"])
111+
chunk_size = st.sidebar.slider("Chunk Size", min_value=20, max_value = 5000,
112+
step=10, value=2000)
113+
chunk_overlap = st.sidebar.slider("Chunk Overlap", min_value=5, max_value = 5000,
114+
step=10, value=200)
115+
user_prompt = st.text_input("Enter the document summary prompt", value= "Compose a brief summary of this text. ")
116+
temperature = st.sidebar.number_input("Set the GenAI Temperature",
117+
min_value = 0.0,
118+
max_value=1.0,
119+
step=0.1,
120+
value=0.5)
121+
max_token = st.sidebar.slider("Max Output size", min_value=200, max_value = 1000,step=10, value=200)
122+
compartment_id = st.sidebar.text_input("Enter the compartment id", value= "")
123+
124+
opt = "Upload-own-file"
125+
pages = None
126+
if opt == "Upload-own-file":
127+
uploaded_file = st.file_uploader(
128+
"**Upload a Pdf file :**",
129+
type=["pdf"],
130+
)
131+
if uploaded_file:
132+
if uploaded_file.name.endswith(".txt"):
133+
doc = parse_txt(uploaded_file)
134+
elif uploaded_file.name.endswith(".pdf"):
135+
doc = parse_pdf(uploaded_file)
136+
pages = text_to_docs(doc, chunk_size, chunk_overlap)
137+
print("Pages are here")
138+
print(pages)
139+
140+
141+
page_holder = st.empty()
142+
if pages:
143+
print("Inside if PAges")
144+
st.write("PDF loaded successfully")
145+
with page_holder.expander("File Content", expanded=False):
146+
pages
147+
148+
149+
llm = OCIGenAI(
150+
model_id=llm_name,
151+
service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",
152+
compartment_id = compartment_id,
153+
model_kwargs={"temperature": temperature, "max_tokens": max_token}
154+
)
155+
156+
if st.button("Summarize"):
157+
with st.spinner('Summarizing....'):
158+
result = custom_summary(pages, llm, user_prompt, chain_type, 1)
159+
st.write("Summary:")
160+
for summary in result:
161+
st.write(summary)
162+
else:
163+
st.warning("No file found. Upload a file to summarize!")
164+
165+
if __name__=="__main__":
166+
main()
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
streamlit
2+
langchain
3+
unstructured
4+
langchain_community
5+
pypdf
6+
transformers

ai-and-app-modernisation/app-integration-and-automation/shared-assets/README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ This section contains various examples related to Application Integration: demo
66

77
## Architecture Center
88

9+
- [Enable a Low Code Modular LLM App Engine using Oracle Integration and OCI Generative AI](https://docs.oracle.com/en/solutions/oci-generative-ai-integration/index.html)
10+
- This reference architecture lets you understand the necessary considerations and recommendations to enable an AI-based, modular and event-driven LLM App Engine using a low-code approach with Oracle Integration as the LLM orchestrator, OCI Generative AI and other OCI services
11+
- Build enterprise-grade, modular, scalable, secure & maintainable LLM Apps
12+
913
- [Enable multicloud integrations from Oracle Cloud ERP to Microsoft Azure SQL Database](https://docs.oracle.com/en/solutions/oci-multicloud-erp-azure/index.html)
1014
- Reference Architecture on the Oracle Architecture Center, which provides the necessary considerations and recommendations to enable a multicloud, event-driven, and no-code integration solution to receive real-time feeds from Oracle Cloud ERP and send those to a private Microsoft Azure SQL Database, leveraging a component Oracle Integration provides called the connectivity agent, to facilitate on-premises/multicloud integrations
1115
- [Implement message-level encryption in Oracle Integration Cloud using OCI Vault](https://docs.oracle.com/en/solutions/oic-message-level-encryption/index.html#GUID-5C843938-A470-4584-9048-4361025358C6)

0 commit comments

Comments
 (0)