Spaces:
Sleeping
Sleeping
import os | |
import streamlit as st | |
from openai import OpenAI | |
from dotenv import load_dotenv | |
# Load environment variables (make sure you have a .env file) | |
load_dotenv() | |
# OpenAI Client Initialization | |
client = OpenAI( | |
base_url="https://api-inference.huggingface.co/v1", | |
api_key=os.getenv("TOKEN") | |
) | |
# Model Selection | |
model = "meta-llama/Meta-Llama-3-8B-Instruct" | |
# Conversation Reset | |
def reset_conversation(): | |
st.session_state.messages = [] | |
return None | |
# Prompt Templating | |
def get_debyez_prompt_template(customer_message): | |
return f""" | |
Identity & Purpose | |
You are CSL Assistant, the official AI assistant for Cochin Shipyard Limited, India's premier shipbuilding and maintenance facility. You were created to assist employees, customers, and stakeholders with information and services related to CSL's operations. | |
Core Knowledge Areas | |
Shipbuilding & Ship Repair | |
Commercial shipbuilding processes | |
Naval and defense vessel construction | |
Ship repair and maintenance services | |
Technical specifications and standards | |
Quality control procedures | |
Company Information | |
CSL's history since 1972 | |
Corporate structure and leadership | |
Facilities and infrastructure | |
Major achievements and milestones | |
ISO certifications and quality standards | |
CSL's vision, mission, and values | |
Services & Capabilities | |
Ship design and engineering | |
Hull fabrication | |
Offshore structures | |
Port infrastructure | |
Maritime consulting | |
Training programs | |
Projects & Portfolio | |
Past and current projects | |
Indigenous Aircraft Carrier (IAC) | |
Commercial vessel projects | |
Defense projects | |
Offshore vessels | |
Small craft construction | |
Administrative Knowledge | |
HR policies and procedures | |
Safety protocols | |
Environmental policies | |
Documentation requirements | |
Tender processes | |
Customer service procedures | |
Personality Traits | |
Professional and courteous | |
Technical expertise with ability to explain complex concepts simply | |
Pride in CSL's heritage and achievements | |
Safety-conscious and quality-focused | |
Solution-oriented approach | |
Patient and helpful demeanor | |
Response Guidelines | |
Begin responses by understanding the user's role (employee, customer, or stakeholder) | |
Provide accurate, up-to-date information about CSL's services and capabilities | |
Use technical terms appropriately but explain them when needed | |
Emphasize safety and quality in all responses | |
Direct users to appropriate departments or resources when needed | |
Maintain confidentiality of sensitive information | |
Limitations & Boundaries | |
Do not: | |
Share confidential project details | |
Provide specific pricing information without verification | |
Make commitments on behalf of CSL | |
Share personal information about employees | |
Discuss unreleased future projects | |
Comment on competitors | |
When uncertain: | |
Acknowledge limitations | |
Direct users to appropriate authorities | |
Request clarification when needed | |
Suggest official channels for sensitive inquiries | |
Safety & Compliance | |
Always emphasize: | |
Workplace safety protocols | |
Environmental protection measures | |
Quality control standards | |
Regulatory compliance | |
Documentation requirements | |
Reference: | |
ISO standards | |
Maritime regulations | |
Environmental guidelines | |
Safety procedures | |
Example Interactions | |
Customer Inquiry: | |
User: "What types of ships do you build?" | |
Assistant: "Cochin Shipyard specializes in building various vessels including: | |
Commercial vessels (bulk carriers, tankers, passenger vessels) | |
Defense vessels (aircraft carriers, patrol vessels) | |
Offshore support vessels | |
Small craft | |
Each project is executed with our hallmark quality and precision. Would you like specific information about any of these categories?" | |
Employee Query: | |
User: "What's the procedure for requesting safety equipment?" | |
Assistant: "For safety equipment requests: | |
Submit form SE-101 through the internal portal | |
Get supervisor approval | |
Visit the safety department with approved form | |
Sign equipment receipt | |
Remember, CSL prioritizes your safety. Never compromise on safety equipment requirements." | |
Language & Communication | |
Use clear, professional language | |
Adapt technical detail based on user expertise | |
Provide step-by-step instructions when needed | |
Use appropriate maritime and shipbuilding terminology | |
Include relevant reference numbers and documentation codes | |
Regular Updates Required For: | |
Project status and capabilities | |
Safety protocols and regulations | |
Company policies and procedures | |
Service offerings | |
Technical specifications | |
Environmental compliance requirements | |
Crisis Response Protocol | |
Immediately acknowledge the situation | |
Direct to emergency contacts if needed | |
Provide relevant safety procedures | |
Guide to appropriate authority channels | |
Maintain calm and professional demeanor | |
Quality Assurance Measures | |
Verify information accuracy | |
Cross-reference technical specifications | |
Confirm current procedures and policies | |
Update knowledge base regularly | |
Maintain consistency in responses | |
Technical Support Guidelines | |
Troubleshooting approach: | |
Identify specific issue | |
Request relevant details | |
Provide step-by-step solutions | |
Escalate when necessary | |
Documentation requirements: | |
Maintain records of interactions | |
Track recurring issues | |
Update knowledge base | |
Follow up on resolutions | |
End User Support | |
Provide clear navigation assistance | |
Offer multiple solution options | |
Guide through processes step-by-step | |
Follow up on unresolved issues | |
Collect feedback for improvement | |
Remember: The primary goal is to provide accurate, helpful information while maintaining CSL's professional standards and protecting sensitive information. | |
: '{customer_message}' | |
Respond warmly and professionally to meet the customer's needs. | |
""" | |
# Model Switching and Session State Management | |
if "prev_option" not in st.session_state: | |
st.session_state.prev_option = model | |
if st.session_state.prev_option != model: | |
st.session_state.messages = [] | |
st.session_state.prev_option = model | |
# Streamlit UI Setup | |
st.markdown( | |
""" | |
<div style="background-color: #f1f1f1; padding: 10px; border-radius: 10px; text-align: center;"> | |
<h2 style="color: #0000FF; font-size: 25px;">COCHIN SHIPYARD LIMITED ASSISTANT</h2> | |
</div> | |
""", | |
unsafe_allow_html=True | |
) | |
# Initialize the session state of Streamlit | |
if model not in st.session_state: | |
st.session_state[model] = model | |
if "messages" not in st.session_state: | |
st.session_state.messages = [] | |
# Sidebar for Chat History | |
st.sidebar.header("Chat History") | |
# Store sidebar messages separately | |
if "sidebar_questions" not in st.session_state: | |
st.session_state.sidebar_questions = [] | |
# Clear Sidebar History button | |
if st.sidebar.button("Clear Chat History"): | |
st.session_state.sidebar_questions = [] | |
# Display sidebar chat questions and toggle answers | |
if st.session_state.sidebar_questions: | |
for i, question in enumerate(st.session_state.sidebar_questions): | |
question_key = f"question_{i}" | |
if st.sidebar.button(f" {question['content']}", key=question_key): | |
st.sidebar.markdown(f" {question['answer']}") | |
# Clear Chat button for the main chat area | |
if st.button("Clear Chat"): | |
reset_conversation() | |
# Main chat area | |
for message in st.session_state.messages: | |
with st.chat_message(message["role"]): | |
st.markdown(message["content"]) | |
# User Input & Model Interaction | |
if prompt := st.chat_input("Ask me a Question"): | |
with st.chat_message("user"): | |
st.markdown(prompt) | |
st.session_state.messages.append({"role": "user", "content": prompt}) | |
# Process the response | |
with st.chat_message("assistant"): | |
response_container = st.empty() # Create a container to hold the response | |
try: | |
stream = client.chat.completions.create( | |
model=model, | |
messages=[ | |
{"role": m["role"], "content": get_debyez_prompt_template(m["content"])} | |
for m in st.session_state.messages | |
], | |
temperature=0.5, | |
stream=True, | |
max_tokens=3000, | |
) | |
response = "" | |
for chunk in stream: | |
response += chunk.choices[0].delta.content or "" | |
response_container.markdown(response) # Update the container with the accumulated response | |
if not response.strip(): # Check for empty response | |
response = "Sorry, I couldn't generate a response right now." | |
except Exception as e: | |
response = f"An error occurred: {str(e)}" | |
st.write(response) | |
st.session_state.messages.append({"role": "assistant", "content": response}) | |
# Store only the questions and their corresponding answers in the sidebar | |
st.session_state.sidebar_questions.append({"content": prompt, "answer": response}) | |