Skip to content

Commit

Permalink
Update everything
Browse files Browse the repository at this point in the history
  • Loading branch information
llrs-roche committed Nov 4, 2024
1 parent 5d90577 commit 0749ad3
Show file tree
Hide file tree
Showing 8 changed files with 344 additions and 39 deletions.
78 changes: 78 additions & 0 deletions .github/workflows/main_finance-roche.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions
# More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions

name: Build and deploy Python app to Azure Web App - finance-roche

on:
push:
branches:
- main
workflow_dispatch:

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- name: Set up Python version
uses: actions/setup-python@v5
with:
python-version: '3.12'

- name: Create and start virtual environment
run: |
python -m venv venv
source venv/bin/activate
- name: Install dependencies
run: pip install -r requirements.txt

# Optional: Add step to run tests here (PyTest, Django test suites, etc.)

- name: Zip artifact for deployment
run: zip release.zip ./* -r

- name: Upload artifact for deployment jobs
uses: actions/upload-artifact@v4
with:
name: python-app
path: |
release.zip
!venv/
deploy:
runs-on: ubuntu-latest
needs: build
environment:
name: 'Production'
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
permissions:
id-token: write #This is required for requesting the JWT

steps:
- name: Download artifact from build job
uses: actions/download-artifact@v4
with:
name: python-app

- name: Unzip artifact for deployment
run: unzip release.zip


- name: Login to Azure
uses: azure/login@v2
with:
client-id: ${{ secrets.AZUREAPPSERVICE_CLIENTID_F6E3B347211743898CECFB3B6BC10AE6 }}
tenant-id: ${{ secrets.AZUREAPPSERVICE_TENANTID_0507CE3ED08D40448C3605EBF9937DFD }}
subscription-id: ${{ secrets.AZUREAPPSERVICE_SUBSCRIPTIONID_5B2433701C1344578C4A9EB0E957CF3C }}

- name: 'Deploy to Azure Web App'
uses: azure/webapps-deploy@v3
id: deploy-to-webapp
with:
app-name: 'finance-roche'
slot-name: 'Production'

78 changes: 78 additions & 0 deletions .github/workflows/main_roche-finance-chatbot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions
# More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions

name: Build and deploy Python app to Azure Web App - roche-finance-chatbot

on:
push:
branches:
- main
workflow_dispatch:

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- name: Set up Python version
uses: actions/setup-python@v5
with:
python-version: '3.12'

- name: Create and start virtual environment
run: |
python -m venv venv
source venv/bin/activate
- name: Install dependencies
run: pip install -r requirements.txt

# Optional: Add step to run tests here (PyTest, Django test suites, etc.)

- name: Zip artifact for deployment
run: zip release.zip ./* -r

- name: Upload artifact for deployment jobs
uses: actions/upload-artifact@v4
with:
name: python-app
path: |
release.zip
!venv/
deploy:
runs-on: ubuntu-latest
needs: build
environment:
name: 'Production'
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
permissions:
id-token: write #This is required for requesting the JWT

steps:
- name: Download artifact from build job
uses: actions/download-artifact@v4
with:
name: python-app

- name: Unzip artifact for deployment
run: unzip release.zip


- name: Login to Azure
uses: azure/login@v2
with:
client-id: ${{ secrets.AZUREAPPSERVICE_CLIENTID_B71F863252414000B105CC9CED5BF862 }}
tenant-id: ${{ secrets.AZUREAPPSERVICE_TENANTID_149C416FEB0D44C68A0091B004996DB7 }}
subscription-id: ${{ secrets.AZUREAPPSERVICE_SUBSCRIPTIONID_55EEE99C13E0473587DAB74E957E4E0B }}

- name: 'Deploy to Azure Web App'
uses: azure/webapps-deploy@v3
id: deploy-to-webapp
with:
app-name: 'roche-finance-chatbot'
slot-name: 'Production'

1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ frontend/node_modules
.azure/
__pycache__/
.ipynb_checkpoints/
.Rproj.user
153 changes: 153 additions & 0 deletions Finance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import os
import matplotlib.pyplot as plt
import streamlit as st
from openai import AzureOpenAI
import base64
from PIL import Image

# Configuraciones - API de Azure OpenAI
endpoint = os.getenv("ENDPOINT_URL", "https://cog-aoai-team-es6-ac4f.openai.azure.com/")
deployment = os.getenv("DEPLOYMENT_NAME", "gpt-4o")
search_endpoint = os.getenv("SEARCH_ENDPOINT", "https://srch-team-es6-ac4f.search.windows.net")
search_key = os.getenv("SEARCH_KEY", "NULL")
subscription_key = os.getenv("AZURE_OPENAI_API_KEY", "NULL")

# Inicializar el cliente de Azure OpenAI con autenticación basada en clave
client = AzureOpenAI(
azure_endpoint=endpoint,
api_key=subscription_key,
api_version="2024-05-01-preview",
)


#### Config Page Streamlit
imagen = Image.open('./images/blue_logo.png')

def set_bg_hack(main_bg):
'''
A function to unpack an image from root folder and set as bg.
Returns
-------
The background.
'''
# set bg name
main_bg_ext = "png"

st.markdown(
f"""
<style>
.stApp {{
background: url(data:image/{main_bg_ext};base64,{base64.b64encode(open(main_bg, "rb").read()).decode()});
background-size: cover
}}
</style>
""",
unsafe_allow_html=True
)

st.set_page_config(page_title="Finance Roche ChatBot", page_icon=imagen,layout="centered")

st.logo(
image="./images/white_logo.png" #/app/Design/blue_logo.png
)

set_bg_hack("./images/Finance_Background.png")

##################################################################
# Generación de resumen de salida
def output_generation_summary(input_text, search_endpoint, search_key):
if not search_endpoint or not search_key:
return "Error: search_endpoint o search_key no están configurados correctamente."

try:
# Generar la respuesta
completion = client.chat.completions.create(
model=deployment,
messages=input_text,
max_tokens=800,
temperature=0.7, # 0.0
top_p=0.95,
frequency_penalty=0,
presence_penalty=0,
stream=False,
extra_body={
"data_sources": [
{
"type": "azure_search",
"parameters": {
"endpoint": search_endpoint,
"index_name": "finance-group6-index-v2",
"semantic_configuration": "default",
"query_type": "semantic",
"fields_mapping": {},
"in_scope": True,
"role_information": (
"You are a finance expert assisting with data inquiries. If clarification is needed, "
"prompt the user directly."
),
"filter": None,
"strictness": 3,
"top_n_documents": 10,
"authentication": {
"type": "api_key",
"key": search_key,
},
},
}
]
},
)
if completion and completion.choices:
content = completion.choices[0].message.content
return content
else:
return "Error: No se pudo generar la respuesta."

except Exception as e:
return f"Error al generar la respuesta: {e}"

def test (input_text, search_endpoint, search_key):
return input_text

messages = [
{
"role": "system",
"content": (
"You are an AI assistant, expert in finance and help people find information about Roche.\n"
"Your responses must be concise and limited to one line wherever possible. Provide only the exact "
"answer to the user’s question without additional explanations. If the input lacks detail, prompt "
"for more specifics, e.g., \"Could you provide more details on…?\".\n"
"Answer in the user's language and avoid topics outside Roche's financial data."
),
},
]

st.title("Finance Roche ChatBot")
st.write("Welcome to this Chatbot to manage Roche financial data.")

# Inicializar el historial de preguntas y respuestas
if 'messages' not in st.session_state:
st.session_state.messages = []

# Mostrar el cuadro de texto con marcador de posición
#user_input = st.text_area("Type your financial question here:", placeholder="None")
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])

#user input
if prompt := st.chat_input("Please enter a query to get started"):
st.chat_message("user").markdown(prompt)
st.session_state.messages.append({"role": "user", "content":prompt})
messages.append({"role": "user","content":prompt})

#st.write(messages)

response = output_generation_summary(messages, search_endpoint, search_key)
#st.write(messages)

with st.chat_message("assistant"):
st.markdown(response)

st.session_state.messages.append({"role":"assistant","content":response})
16 changes: 16 additions & 0 deletions app-aoai-chatGPT.Rproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
Version: 1.0

RestoreWorkspace: Default
SaveWorkspace: Default
AlwaysSaveHistory: Default

EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8

RnwWeave: Sweave
LaTeX: XeLaTeX

AutoAppendNewline: Yes
StripTrailingWhitespace: Yes
14 changes: 13 additions & 1 deletion app.py
Original file line number Diff line number Diff line change
Expand Up @@ -861,7 +861,19 @@ async def ensure_cosmos():

async def generate_title(conversation_messages) -> str:
## make sure the messages are sorted by _ts descending
title_prompt = "Summarize the conversation so far into a 4-word or less title. Do not use any quotation marks or punctuation. Do not include any other commentary or description."
title_prompt = (
"You are an AI assistant, expert in finance and helps people find information about this topic.\n"
"Your responses must be concise and brief so you should limit responses to one line whenever possible, "
"avoid adding unnecessary details or contextual information.\n"
"Provide only the exact answer to the user’s question or request, without additional explanations.\n"
"If the input lacks sufficient detail for an accurate response, ask specifically for missing information "
"using prompts like 'Could you provide more details on…?', 'Do you mean [brief context]?'\n"
"For ambiguous queries, clarify details with direct questions before responding.\n"
"If a topic requires extensive information, summarize in one line and offer the user the choice to request more.\n"
"If a question has already been answered or the user requests clarification, avoid repeating information, "
"responding instead with the precise data needed.\n"
"Detect the language of the user's question and respond in the same language, ensuring seamless communication across languages."
)

messages = [
{"role": msg["role"], "content": msg["content"]}
Expand Down
17 changes: 4 additions & 13 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,13 +1,4 @@
azure-identity==1.15.0
# Flask[async]==2.3.2
openai==1.6.1
azure-search-documents==11.4.0b6
azure-storage-blob==12.17.0
python-dotenv==1.0.0
azure-cosmos==4.5.0
quart==0.19.4
uvicorn==0.24.0
aiohttp==3.9.2
gunicorn==20.1.0
pydantic-settings==2.2.1
matplotlib
openai
streamlit


Loading

0 comments on commit 0749ad3

Please sign in to comment.