Skip to content

Commit d8fa3a6

Browse files
authored
Create chatbot.py
1 parent 825bae7 commit d8fa3a6

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

ai-chatbot/chatbot.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import streamlit as st
2+
import openai
3+
4+
# Default backend URL
5+
DEFAULT_BACKEND_URL = "http://localhost:11434/v1"
6+
7+
# UI for setting the backend URL
8+
st.title("Chatbot using Ollama")
9+
st.sidebar.header("Settings")
10+
backend_url = st.sidebar.text_input("Backend URL", DEFAULT_BACKEND_URL)
11+
12+
# Initialize OpenAI client with user-defined backend URL
13+
client = openai.OpenAI(base_url=backend_url)
14+
15+
# Chat session state
16+
if "messages" not in st.session_state:
17+
st.session_state.messages = []
18+
19+
# Display chat history
20+
for message in st.session_state.messages:
21+
with st.chat_message(message["role"]):
22+
st.markdown(message["content"])
23+
24+
# User input
25+
if prompt := st.chat_input("Ask something..."):
26+
# Add user message to session state
27+
st.session_state.messages.append({"role": "user", "content": prompt})
28+
with st.chat_message("user"):
29+
st.markdown(prompt)
30+
31+
# Call the backend API
32+
try:
33+
response = client.chat.completions.create(
34+
model="llama3.2:1b", # Change this based on available models
35+
messages=st.session_state.messages
36+
)
37+
reply = response.choices[0].message.content
38+
except Exception as e:
39+
reply = f"Error: {e}"
40+
41+
# Display assistant response
42+
with st.chat_message("assistant"):
43+
st.markdown(reply)
44+
st.session_state.messages.append({"role": "assistant", "content": reply})

0 commit comments

Comments
 (0)