Rafii commited on
Commit
c903056
·
1 Parent(s): d920053

added langchain

Browse files
Files changed (2) hide show
  1. app.py +82 -29
  2. requirements.txt +1 -0
app.py CHANGED
@@ -2,42 +2,95 @@ import streamlit as st
2
  from mlx_lm import load, generate
3
  from huggingface_hub import login
4
  import os
 
5
 
6
- # os.environ["HF_HOME"] = "your_huggingface_token"
 
 
 
 
 
 
7
 
8
- token = os.getenv("HF_TOKEN")
9
 
10
- login(token=token)
 
11
 
12
- # Load your model and tokenizer
 
 
 
 
 
 
 
13
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- # response = generate(model, tokenizer, prompt=prompt, verbose=True)
16
-
17
- st.title("Your F1 Asli")
18
-
19
- # User input
20
- user_input = st.text_input("Enter text:")
21
-
22
-
23
- if st.button("Submit"):
24
- print("Habibi mereko dhundti kya")
25
- st.write("mai print toh ho hi raha hu na bantai")
26
-
27
- # Tokenize input and make predictions
28
- # inputs = tokenizer(user_input, return_tensors="pt")
29
- # outputs = model(**inputs)
30
- # model, tokenizer = load("Rafii/f1llama")
31
- model, tokenizer = load("mlx-community/Meta-Llama-3.1-8B-Instruct-bf16")
 
32
 
33
- prompt="hello"
34
 
35
- if hasattr(tokenizer, "apply_chat_template") and tokenizer.chat_template is not None:
36
- messages = [{"role": "user", "content": prompt}]
37
- prompt = tokenizer.apply_chat_template(
38
- messages, tokenize=False, add_generation_prompt=True
39
- )
40
 
41
- response = generate(model, tokenizer, prompt=user_input, verbose=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- st.write(response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from mlx_lm import load, generate
3
  from huggingface_hub import login
4
  import os
5
+ from langchain.memory import ConversationBufferMemory
6
 
7
+ @st.cache_resource
8
+ def init_model():
9
+ token = os.getenv("HF_TOKEN")
10
+ if token:
11
+ login(token=token)
12
+ # return load("Rafii/f1llama")
13
+ return load("mlx-community/Mixtral-8x7B-Instruct-v0.1")
14
 
15
+ model, tokenizer = init_model()
16
 
17
+ if "memory" not in st.session_state:
18
+ st.session_state.memory = ConversationBufferMemory(return_messages=True)
19
 
20
+ def format_chat_history(messages):
21
+ formatted = ""
22
+ for msg in messages:
23
+ if "input" in msg:
24
+ formatted += f"Human: {msg['input']}\n"
25
+ if "output" in msg:
26
+ formatted += f"Assistant: {msg['output']}\n"
27
+ return formatted
28
 
29
+ def generate_response(user_input, max_tokens=100):
30
+ try:
31
+ # Get chat history
32
+ chat_history = st.session_state.memory.load_memory_variables({})
33
+ history = chat_history.get("history", "")
34
+
35
+ # Create contextual prompt
36
+ context = format_chat_history(history)
37
+ full_prompt = f"""Previous conversation:
38
+ {context}
39
+ Human: {user_input}
40
+ Assistant:"""
41
 
42
+ if hasattr(tokenizer, "apply_chat_template") and tokenizer.chat_template is not None:
43
+ messages = [{"role": "user", "content": full_prompt}]
44
+ prompt = tokenizer.apply_chat_template(
45
+ messages, tokenize=False, add_generation_prompt=True
46
+ )
47
+ else:
48
+ prompt = full_prompt
49
+
50
+ response = generate(
51
+ model,
52
+ tokenizer,
53
+ prompt=prompt,
54
+ verbose=True
55
+ )
56
+ return response
57
+ except Exception as e:
58
+ st.error(f"Error generating response: {str(e)}")
59
+ return "Sorry, I encountered an error."
60
 
61
+ st.title("F1 Chatbot 🏎️")
62
 
63
+ user_input = st.text_input("Ask me anything:", key="user_input")
 
 
 
 
64
 
65
+ # Add debug prints and modified display logic
66
+ if st.button("Send", key="send"):
67
+ if user_input:
68
+ with st.spinner("Thinking..."):
69
+ response = generate_response(user_input)
70
+ # Debug print
71
+ st.write(f"Debug - Response: {response}")
72
+
73
+ st.session_state.memory.save_context(
74
+ {"input": user_input},
75
+ {"output": response}
76
+ )
77
+ # Debug print
78
+ st.write("Debug - Context saved")
79
 
80
+ # Modified display section
81
+ if "memory" in st.session_state:
82
+ st.write("### Conversation")
83
+ try:
84
+ chat_history = st.session_state.memory.load_memory_variables({})
85
+ st.write(f"Debug - Full history: {chat_history}") # Debug print
86
+
87
+ if "history" in chat_history:
88
+ for msg in chat_history["history"]:
89
+ st.write(f"Debug - Message: {msg}") # Debug print
90
+ if isinstance(msg, dict):
91
+ if "input" in msg:
92
+ st.info(f"You: {msg['input']}")
93
+ if "output" in msg:
94
+ st.success(f"Assistant: {msg['output']}")
95
+ except Exception as e:
96
+ st.error(f"Error displaying conversation: {str(e)}")
requirements.txt CHANGED
@@ -9,3 +9,4 @@ huggingface-hub==0.26.3
9
  numpy
10
  pandas
11
  mlx-lm==0.18.2
 
 
9
  numpy
10
  pandas
11
  mlx-lm==0.18.2
12
+ langchain==0.3.13