Joshua Sundance Bailey commited on
Commit
ad0c8c1
Β·
unverified Β·
2 Parent(s): 917e947 47a54a5

Merge pull request #16 from joshuasundance-swca/dev

Browse files
langchain-streamlit-demo/app.py CHANGED
@@ -1,30 +1,21 @@
1
  import os
 
2
  from typing import Union
3
 
4
  import anthropic
5
  import openai
6
  import streamlit as st
 
 
7
  from langchain.callbacks.tracers.langchain import wait_for_all_tracers
8
  from langchain.callbacks.tracers.run_collector import RunCollectorCallbackHandler
 
 
 
 
9
  from langchain.schema.runnable import RunnableConfig
10
  from langsmith.client import Client
11
-
12
- from llm_stuff import (
13
- _STMEMORY,
14
- _MODEL_DICT,
15
- _SUPPORTED_MODELS,
16
- _DEFAULT_MODEL,
17
- _DEFAULT_SYSTEM_PROMPT,
18
- _DEFAULT_TEMPERATURE,
19
- _MIN_TEMPERATURE,
20
- _MAX_TEMPERATURE,
21
- _DEFAULT_MAX_TOKENS,
22
- _MIN_TOKENS,
23
- _MAX_TOKENS,
24
- get_llm_chain,
25
- StreamHandler,
26
- feedback_component,
27
- )
28
 
29
  st.set_page_config(
30
  page_title="langchain-streamlit-demo",
@@ -33,6 +24,124 @@ st.set_page_config(
33
 
34
  st.sidebar.markdown("# Menu")
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  # Initialize State
37
  if "trace_link" not in st.session_state:
38
  st.session_state.trace_link = None
 
1
  import os
2
+ from datetime import datetime
3
  from typing import Union
4
 
5
  import anthropic
6
  import openai
7
  import streamlit as st
8
+ from langchain import LLMChain
9
+ from langchain.callbacks.base import BaseCallbackHandler
10
  from langchain.callbacks.tracers.langchain import wait_for_all_tracers
11
  from langchain.callbacks.tracers.run_collector import RunCollectorCallbackHandler
12
+ from langchain.chat_models import ChatOpenAI, ChatAnyscale, ChatAnthropic
13
+ from langchain.chat_models.base import BaseChatModel
14
+ from langchain.memory import ConversationBufferMemory, StreamlitChatMessageHistory
15
+ from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
16
  from langchain.schema.runnable import RunnableConfig
17
  from langsmith.client import Client
18
+ from streamlit_feedback import streamlit_feedback
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  st.set_page_config(
21
  page_title="langchain-streamlit-demo",
 
24
 
25
  st.sidebar.markdown("# Menu")
26
 
27
+
28
+ _STMEMORY = StreamlitChatMessageHistory(key="langchain_messages")
29
+ _MEMORY = ConversationBufferMemory(
30
+ chat_memory=_STMEMORY,
31
+ return_messages=True,
32
+ memory_key="chat_history",
33
+ )
34
+
35
+ _DEFAULT_SYSTEM_PROMPT = os.environ.get(
36
+ "DEFAULT_SYSTEM_PROMPT",
37
+ "You are a helpful chatbot.",
38
+ )
39
+
40
+ _MODEL_DICT = {
41
+ "gpt-3.5-turbo": "OpenAI",
42
+ "gpt-4": "OpenAI",
43
+ "claude-instant-v1": "Anthropic",
44
+ "claude-2": "Anthropic",
45
+ "meta-llama/Llama-2-7b-chat-hf": "Anyscale Endpoints",
46
+ "meta-llama/Llama-2-13b-chat-hf": "Anyscale Endpoints",
47
+ "meta-llama/Llama-2-70b-chat-hf": "Anyscale Endpoints",
48
+ }
49
+ _SUPPORTED_MODELS = list(_MODEL_DICT.keys())
50
+ _DEFAULT_MODEL = os.environ.get("DEFAULT_MODEL", "gpt-3.5-turbo")
51
+
52
+ _DEFAULT_TEMPERATURE = float(os.environ.get("DEFAULT_TEMPERATURE", 0.7))
53
+ _MIN_TEMPERATURE = float(os.environ.get("MIN_TEMPERATURE", 0.0))
54
+ _MAX_TEMPERATURE = float(os.environ.get("MAX_TEMPERATURE", 1.0))
55
+
56
+ _DEFAULT_MAX_TOKENS = int(os.environ.get("DEFAULT_MAX_TOKENS", 1000))
57
+ _MIN_TOKENS = int(os.environ.get("MIN_MAX_TOKENS", 1))
58
+ _MAX_TOKENS = int(os.environ.get("MAX_MAX_TOKENS", 100000))
59
+
60
+
61
+ def get_llm(
62
+ model: str,
63
+ provider_api_key: str,
64
+ temperature: float,
65
+ max_tokens: int = _DEFAULT_MAX_TOKENS,
66
+ ) -> BaseChatModel:
67
+ if _MODEL_DICT[model] == "OpenAI":
68
+ return ChatOpenAI(
69
+ model=model,
70
+ openai_api_key=provider_api_key,
71
+ temperature=temperature,
72
+ streaming=True,
73
+ max_tokens=max_tokens,
74
+ )
75
+ elif _MODEL_DICT[model] == "Anthropic":
76
+ return ChatAnthropic(
77
+ model_name=model,
78
+ anthropic_api_key=provider_api_key,
79
+ temperature=temperature,
80
+ streaming=True,
81
+ max_tokens_to_sample=max_tokens,
82
+ )
83
+ elif _MODEL_DICT[model] == "Anyscale Endpoints":
84
+ return ChatAnyscale(
85
+ model=model,
86
+ anyscale_api_key=provider_api_key,
87
+ temperature=temperature,
88
+ streaming=True,
89
+ max_tokens=max_tokens,
90
+ )
91
+ else:
92
+ raise NotImplementedError(f"Unknown model {model}")
93
+
94
+
95
+ def get_llm_chain(
96
+ model: str,
97
+ provider_api_key: str,
98
+ system_prompt: str = _DEFAULT_SYSTEM_PROMPT,
99
+ temperature: float = _DEFAULT_TEMPERATURE,
100
+ max_tokens: int = _DEFAULT_MAX_TOKENS,
101
+ ) -> LLMChain:
102
+ """Return a basic LLMChain with memory."""
103
+ prompt = ChatPromptTemplate.from_messages(
104
+ [
105
+ (
106
+ "system",
107
+ system_prompt + "\nIt's currently {time}.",
108
+ ),
109
+ MessagesPlaceholder(variable_name="chat_history"),
110
+ ("human", "{input}"),
111
+ ],
112
+ ).partial(time=lambda: str(datetime.now()))
113
+ llm = get_llm(model, provider_api_key, temperature, max_tokens)
114
+ return LLMChain(prompt=prompt, llm=llm, memory=_MEMORY)
115
+
116
+
117
+ class StreamHandler(BaseCallbackHandler):
118
+ def __init__(self, container, initial_text=""):
119
+ self.container = container
120
+ self.text = initial_text
121
+
122
+ def on_llm_new_token(self, token: str, **kwargs) -> None:
123
+ self.text += token
124
+ self.container.markdown(self.text)
125
+
126
+
127
+ def feedback_component(client):
128
+ scores = {"πŸ˜€": 1, "πŸ™‚": 0.75, "😐": 0.5, "πŸ™": 0.25, "😞": 0}
129
+ if feedback := streamlit_feedback(
130
+ feedback_type="faces",
131
+ optional_text_label="[Optional] Please provide an explanation",
132
+ key=f"feedback_{st.session_state.run_id}",
133
+ ):
134
+ score = scores[feedback["score"]]
135
+ feedback = client.create_feedback(
136
+ st.session_state.run_id,
137
+ feedback["type"],
138
+ score=score,
139
+ comment=feedback.get("text", None),
140
+ )
141
+ st.session_state.feedback = {"feedback_id": str(feedback.id), "score": score}
142
+ st.toast("Feedback recorded!", icon="πŸ“")
143
+
144
+
145
  # Initialize State
146
  if "trace_link" not in st.session_state:
147
  st.session_state.trace_link = None
langchain-streamlit-demo/llm_stuff.py DELETED
@@ -1,127 +0,0 @@
1
- import os
2
- from datetime import datetime
3
-
4
- import streamlit as st
5
- from langchain import LLMChain
6
- from langchain.callbacks.base import BaseCallbackHandler
7
- from langchain.chat_models import ChatOpenAI, ChatAnyscale, ChatAnthropic
8
- from langchain.chat_models.base import BaseChatModel
9
- from langchain.memory import ConversationBufferMemory, StreamlitChatMessageHistory
10
- from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
11
- from streamlit_feedback import streamlit_feedback
12
-
13
- _STMEMORY = StreamlitChatMessageHistory(key="langchain_messages")
14
- _MEMORY = ConversationBufferMemory(
15
- chat_memory=_STMEMORY,
16
- return_messages=True,
17
- memory_key="chat_history",
18
- )
19
-
20
- _DEFAULT_SYSTEM_PROMPT = os.environ.get(
21
- "DEFAULT_SYSTEM_PROMPT",
22
- "You are a helpful chatbot.",
23
- )
24
-
25
- _MODEL_DICT = {
26
- "gpt-3.5-turbo": "OpenAI",
27
- "gpt-4": "OpenAI",
28
- "claude-instant-v1": "Anthropic",
29
- "claude-2": "Anthropic",
30
- "meta-llama/Llama-2-7b-chat-hf": "Anyscale Endpoints",
31
- "meta-llama/Llama-2-13b-chat-hf": "Anyscale Endpoints",
32
- "meta-llama/Llama-2-70b-chat-hf": "Anyscale Endpoints",
33
- }
34
- _SUPPORTED_MODELS = list(_MODEL_DICT.keys())
35
- _DEFAULT_MODEL = os.environ.get("DEFAULT_MODEL", "gpt-3.5-turbo")
36
-
37
- _DEFAULT_TEMPERATURE = float(os.environ.get("DEFAULT_TEMPERATURE", 0.7))
38
- _MIN_TEMPERATURE = float(os.environ.get("MIN_TEMPERATURE", 0.0))
39
- _MAX_TEMPERATURE = float(os.environ.get("MAX_TEMPERATURE", 1.0))
40
-
41
- _DEFAULT_MAX_TOKENS = int(os.environ.get("DEFAULT_MAX_TOKENS", 1000))
42
- _MIN_TOKENS = int(os.environ.get("MIN_MAX_TOKENS", 1))
43
- _MAX_TOKENS = int(os.environ.get("MAX_MAX_TOKENS", 100000))
44
-
45
-
46
- def get_llm(
47
- model: str,
48
- provider_api_key: str,
49
- temperature: float,
50
- max_tokens: int = _DEFAULT_MAX_TOKENS,
51
- ) -> BaseChatModel:
52
- if _MODEL_DICT[model] == "OpenAI":
53
- return ChatOpenAI(
54
- model=model,
55
- openai_api_key=provider_api_key,
56
- temperature=temperature,
57
- streaming=True,
58
- max_tokens=max_tokens,
59
- )
60
- elif _MODEL_DICT[model] == "Anthropic":
61
- return ChatAnthropic(
62
- model_name=model,
63
- anthropic_api_key=provider_api_key,
64
- temperature=temperature,
65
- streaming=True,
66
- max_tokens_to_sample=max_tokens,
67
- )
68
- elif _MODEL_DICT[model] == "Anyscale Endpoints":
69
- return ChatAnyscale(
70
- model=model,
71
- anyscale_api_key=provider_api_key,
72
- temperature=temperature,
73
- streaming=True,
74
- max_tokens=max_tokens,
75
- )
76
- else:
77
- raise NotImplementedError(f"Unknown model {model}")
78
-
79
-
80
- def get_llm_chain(
81
- model: str,
82
- provider_api_key: str,
83
- system_prompt: str = _DEFAULT_SYSTEM_PROMPT,
84
- temperature: float = _DEFAULT_TEMPERATURE,
85
- max_tokens: int = _DEFAULT_MAX_TOKENS,
86
- ) -> LLMChain:
87
- """Return a basic LLMChain with memory."""
88
- prompt = ChatPromptTemplate.from_messages(
89
- [
90
- (
91
- "system",
92
- system_prompt + "\nIt's currently {time}.",
93
- ),
94
- MessagesPlaceholder(variable_name="chat_history"),
95
- ("human", "{input}"),
96
- ],
97
- ).partial(time=lambda: str(datetime.now()))
98
- llm = get_llm(model, provider_api_key, temperature, max_tokens)
99
- return LLMChain(prompt=prompt, llm=llm, memory=_MEMORY)
100
-
101
-
102
- class StreamHandler(BaseCallbackHandler):
103
- def __init__(self, container, initial_text=""):
104
- self.container = container
105
- self.text = initial_text
106
-
107
- def on_llm_new_token(self, token: str, **kwargs) -> None:
108
- self.text += token
109
- self.container.markdown(self.text)
110
-
111
-
112
- def feedback_component(client):
113
- scores = {"πŸ˜€": 1, "πŸ™‚": 0.75, "😐": 0.5, "πŸ™": 0.25, "😞": 0}
114
- if feedback := streamlit_feedback(
115
- feedback_type="faces",
116
- optional_text_label="[Optional] Please provide an explanation",
117
- key=f"feedback_{st.session_state.run_id}",
118
- ):
119
- score = scores[feedback["score"]]
120
- feedback = client.create_feedback(
121
- st.session_state.run_id,
122
- feedback["type"],
123
- score=score,
124
- comment=feedback.get("text", None),
125
- )
126
- st.session_state.feedback = {"feedback_id": str(feedback.id), "score": score}
127
- st.toast("Feedback recorded!", icon="πŸ“")