File size: 3,170 Bytes
abcc796 ce628a0 abcc796 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
import streamlit as st
from huggingface_hub import InferenceClient
import random
# Replace with your desired model ID from Hugging Face Hub
client = InferenceClient("unsloth/Llama-3.2-1B-Instruct")
words = [
"apple", "pear", "banana", "strawberry", "mad"
]
class WordGame:
def __init__(self):
self.points = 0
self.target_word = ""
self.attempts = 3
self.generate_task()
def generate_task(self):
self.attempts = 3
self.target_word = random.choice(words)
st.session_state["target_word"] = self.target_word # Store in session state
st.title(f'The Game - Current score: {self.points}, remaining attempts: {self.attempts}')
def check_input_for_word(self, user_input):
if self.target_word in user_input.lower():
self.generate_task()
self.points -= 1
st.write(f"You input the target word yourself, so you lost one point and the game reset.")
return True
else:
return False
def check_output_for_word(self, response):
if self.target_word in response.lower():
self.points += self.attempts
score_gained = self.attempts
self.generate_task()
return f"Success! You earned {score_gained} points!"
else:
self.attempts -= 1
if self.attempts <= 0:
self.generate_task()
return f"You did not win in three attempts. Generating new target word."
else:
return "That didn't quite hit the mark. Try again!"
def respond(self, user_message):
messages = [{"role": "system", "content": st.session_state["system_message"]}]
for val in st.session_state["history"]:
if val[0]:
messages.append({"role": "user", "content": val[0]})
if val[1]:
messages.append({"role": "assistant", "content": val[1]})
messages.append({"role": "user", "content": user_message})
response = ""
for message in client.chat_completion(
messages, max_tokens=st.session_state["max_tokens"], stream=True,
temperature=st.session_state["temperature"], top_p=st.session_state["top_p"]
):
token = message.choices[0].delta.content
response += token
output_check_result = self.check_output_for_word(response)
st.write(response + f"\n\n---\n\n{output_check_result}")
st.write(f'Current score: {self.points}, remaining attempts: {self.attempts}')
# Update session state with history and system message
st.session_state["history"].append((user_message, response))
st.session_state["system_message"] = response
game = WordGame()
# Session state variables to store dynamic information
st.session_state["history"] = [] # List of tuples (user message, response)
st.session_state["system_message"] = "You are a friendly Chatbot." # Initial system message
# Update session state with user input for system message
st.session_state["system_message"] = system_message_input
user_message = st.text_ |