Promotingai commited on
Commit
8d48f61
·
verified ·
1 Parent(s): db4e83d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +170 -31
app.py CHANGED
@@ -1,44 +1,183 @@
 
1
  import streamlit as st
2
- import os # Import pour accéder aux variables d'environnement
 
 
 
3
 
4
- from langchain.agents import initialize_agent, AgentType
5
- from langchain.callbacks import StreamlitCallbackHandler
6
- from langchain.chat_models import ChatOpenAI
7
- from langchain.tools import DuckDuckGoSearchRun
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- # Récupérer la clé API de l'environnement
10
- openai_api_key = os.getenv("OPENAI_API_KEY")
 
 
 
11
 
12
- st.title("🔎 LangChain - Chat with search")
 
 
 
 
13
 
 
 
 
 
 
 
 
 
14
  """
15
- In this example, we're using `StreamlitCallbackHandler` to display the thoughts and actions of an agent in an interactive Streamlit app.
16
- Try more LangChain 🤝 Streamlit Agent examples at [github.com/langchain-ai/streamlit-agent](https://github.com/langchain-ai/streamlit-agent).
 
 
 
 
 
 
 
 
 
 
 
 
17
  """
18
 
19
- if "messages" not in st.session_state:
20
- st.session_state["messages"] = [
21
- {"role": "assistant", "content": "Hi, I'm a chatbot who can search the web. How can I help you?"}
22
- ]
 
 
 
23
 
24
- for msg in st.session_state.messages:
25
- st.chat_message(msg["role"]).write(msg["content"])
 
26
 
27
- if prompt := st.chat_input(placeholder="Who won the Women's U.S. Open in 2018?"):
28
- st.session_state.messages.append({"role": "user", "content": prompt})
29
- st.chat_message("user").write(prompt)
 
30
 
31
- if not openai_api_key:
32
- st.error("Please set the OPENAI_API_KEY environment variable.")
33
- st.stop()
34
 
35
- llm = ChatOpenAI(model_name="gpt-3.5-turbo", openai_api_key=openai_api_key, streaming=True)
36
- search = DuckDuckGoSearchRun(name="Search")
37
- search_agent = initialize_agent(
38
- [search], llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, handle_parsing_errors=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  )
40
- with st.chat_message("assistant"):
41
- st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
42
- response = search_agent.run(st.session_state.messages, callbacks=[st_cb])
43
- st.session_state.messages.append({"role": "assistant", "content": response})
44
- st.write(response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #Importing required packages
2
  import streamlit as st
3
+ import promptlayer
4
+ from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT
5
+ import uuid
6
+ import math
7
 
8
+ INIT_PROMPT = """
9
+ \n\nHuman: You are MapMentor a trainer in Wardley Mapping. You will help the users learn about Wardley Mapping
10
+ Here are some important rules for the interaction:
11
+ - Always stay in character, as MapMentor a Wardley Mapping trainer.
12
+ - If you are unsure how to respond, respond with another question.
13
+ - Always use a liberationism pedagogy training approach.
14
+ - Remember to state which module of the course we are currently learning.
15
+ """
16
+
17
+ TRAINING_PROMPT = """
18
+ Here is an outline for a training course that you will give to the user. It covers the key principles of Wardley Mapping:
19
+
20
+ Module 1 - Introduction to Wardley Mapping
21
+ Purpose and benefits of mapping
22
+ Understanding value chains and situational awareness
23
+ Overview of doctrine and foundational concepts
24
+
25
+ Module 2 - Structure of Wardley Maps
26
+ Components, activities, and the value chain
27
+ Evolution axis and commodity forms
28
+ Anchors, chains, and dependencies
29
+
30
+ Module 3 - Developing Wardley Maps
31
+ Gathering insight on activities, capabilities, and needs
32
+ Positioning and classifying map elements
33
+ Adding annotations and context
34
 
35
+ Module 4 - Using Maps for Decision Making
36
+ Identifying structural vs situational change
37
+ Applying doctrine to strategic planning
38
+ Mapping out competing value chains
39
+ Developing actionable insights from maps
40
 
41
+ Module 5 - Advanced Concepts
42
+ Ecosystem models and community maps
43
+ Climate patterns and their impact
44
+ Mapping organizational culture
45
+ Handling uncertainty and unknowns
46
 
47
+ Module 6 - Facilitating Wardley Mapping
48
+ Workshops for collaborative mapping
49
+ Engaging leadership and stakeholders
50
+ Promoting adoption and managing skeptics
51
+
52
+ For each module, we would provide concepts, examples, hands-on exercises, and practice activities to build skills.
53
+ Please let me know if you would like me to expand on any part of this high-level curriculum outline for a Wardley Mapping training course.
54
+ I'm happy to provide more details on how to effectively teach this methodology.
55
  """
56
+
57
+ INTRO_PROMPT = """
58
+ Hello, I'm MapMentor \n
59
+ This course is designed as an interactive learning experience to build your skills in Wardley Mapping from the ground up. We will cover the key principles, components, and steps for creating powerful maps. \n
60
+
61
+ The course is organized into 6 modules: \n
62
+ Module 1 provides an introduction to the purpose, benefits, and foundational concepts of mapping. We discuss how it helps with situational awareness and strategic planning. \n
63
+ Module 2 focuses on the structure of Wardley Maps - the components like activities, evolution axis, dependencies. You'll learn how to visualize your value chain. \n
64
+ Module 3 is all about developing maps hands-on. We'll practice gathering insights, positioning elements, adding annotations to create meaningful maps. \n
65
+ Module 4 shifts to using completed maps for strategic analysis and decision making. You'll apply doctrine to interpret maps and generate insights. \n
66
+ Module 5 covers more advanced concepts like mapping ecosystems, organizational culture, and handling uncertainty. \n
67
+ Finally Module 6 is on facilitating mapping workshops and driving adoption. \n
68
+ Each module includes concepts, examples, exercises, and practice activities to build your skills. You'll have opportunities to create maps, iterate on them, and apply them to scenario-based challenges. \n
69
+ I'm looking forward to exploring all aspects of Wardley Mapping with you in this course! Please let me know if you would like me to elaborate on any part of the curriculum.
70
  """
71
 
72
+ REG_PROMPT = """
73
+ \n\nHuman: Here is the user's question about Wardley Mapping:
74
+ <question>
75
+ {QUESTION}
76
+ </question>
77
+ \n\nAssistant: [MapMentor] <response>
78
+ """
79
 
80
+ # Anthropic Claude pricing: https://cdn2.assets-servd.host/anthropic-website/production/images/model_pricing_may2023.pdf
81
+ PRICE_PROMPT = 1.102E-5
82
+ PRICE_COMPLETION = 3.268E-5
83
 
84
+ #MODEL = "claude-1"
85
+ #MODEL = "claude-2.1"
86
+ MODEL = "claude-3-opus-20240229"
87
+ #MODEL = "claude-v1-100k"
88
 
89
+ new_prompt = []
 
 
90
 
91
+ if "session_id" not in st.session_state:
92
+ st.session_state.session_id = str(uuid.uuid4())
93
+
94
+ st.set_page_config(page_title="Anthropic - ChatBot")
95
+ st.sidebar.title("Anthropic - ChatBot")
96
+ st.sidebar.title("Wardley Mapping Mentor")
97
+ st.sidebar.divider()
98
+ st.sidebar.markdown("Developed by Mark Craddock](https://twitter.com/mcraddock)", unsafe_allow_html=True)
99
+ st.sidebar.markdown("Current Version: 0.0.2")
100
+ st.sidebar.markdown("Using claude-2 API")
101
+ st.sidebar.markdown(st.session_state.session_id)
102
+ st.sidebar.divider()
103
+
104
+ # Check if the user has provided an API key, otherwise default to the secret
105
+ user_claude_api_key = st.sidebar.text_input("Enter your Anthropic API Key:", placeholder="sk-...", type="password")
106
+
107
+ st.sidebar.markdown("Tokens")
108
+ total_tokens = st.sidebar.empty()
109
+
110
+ if "claude_model" not in st.session_state:
111
+ st.session_state["claude_model"] = MODEL
112
+
113
+ if "messages" not in st.session_state:
114
+ st.session_state["messages"] = []
115
+ st.session_state.messages.append({"role": "assistant", "content": INTRO_PROMPT})
116
+
117
+ if "all_prompts" not in st.session_state:
118
+ st.session_state["all_prompts"] = INIT_PROMPT + TRAINING_PROMPT
119
+
120
+ def count_used_tokens(prompt, completion):
121
+ prompt_token_count = client.count_tokens(prompt)
122
+ completion_token_count = client.count_tokens(completion)
123
+ prompt_cost = prompt_token_count * PRICE_PROMPT
124
+ completion_cost = completion_token_count * PRICE_COMPLETION
125
+ total_cost = prompt_cost + completion_cost
126
+ total_cost = math.ceil(total_cost * 100) / 100
127
+ return (
128
+ prompt_token_count,
129
+ completion_token_count,
130
+ total_cost
131
+ )
132
+
133
+ if user_claude_api_key:
134
+ # If the user has provided an API key, use it
135
+ # Swap out Anthropic for promptlayer
136
+ promptlayer.api_key = st.secrets["PROMPTLAYER"]
137
+ anthropic = promptlayer.anthropic
138
+ client=anthropic.Anthropic(
139
+ defaults to os.environ.get("ANTHROPIC_API_KEY")
140
  )
141
+
142
+
143
+ for message in st.session_state.messages:
144
+ if message["role"] in ["user", "assistant"]:
145
+ with st.chat_message(message["role"]):
146
+ new_prompt.append(message["content"])
147
+ st.markdown(message["content"])
148
+
149
+ if user_claude_api_key:
150
+ if user_input := st.chat_input("How can I help with Wardley Mapping?"):
151
+ prompt = REG_PROMPT.format(QUESTION = user_input)
152
+ st.session_state.all_prompts += prompt
153
+ st.session_state.messages.append({"role": "user", "content": user_input})
154
+ with st.chat_message("user"):
155
+ st.markdown(user_input)
156
+ with st.chat_message("assistant"):
157
+ message_placeholder = st.empty()
158
+ full_response = ""
159
+ try:
160
+ for response in client.completions.create(
161
+ prompt=st.session_state.all_prompts,
162
+ stop_sequences=["</response>"],
163
+ model=MODEL,
164
+ max_tokens_to_sample=500,
165
+ stream=True,
166
+ pl_tags=["anthropic-chatbot", st.session_state.session_id]
167
+ ):
168
+ full_response += response.completion
169
+ message_placeholder.markdown(full_response + "▌")
170
+ message_placeholder.markdown(full_response)
171
+ except anthropic.APIConnectionError as e:
172
+ st.error("The server could not be reached")
173
+ print(e.__cause__) # an underlying Exception, likely raised within httpx.
174
+ except anthropic.RateLimitError as e:
175
+ st.error("A 429 status code was received; we should back off a bit.")
176
+ except anthropic.APIStatusError as e:
177
+ st.error("Another non-200-range status code was received")
178
+ st.error(e.status_code)
179
+ st.error(e.response)
180
+ st.session_state.messages.append({"role": "assistant", "content": full_response})
181
+ st.session_state.all_prompts += full_response
182
+ prompt_token_count, completion_token_count, total_cost = count_used_tokens(prompt, full_response)
183
+ total_tokens.markdown("Prompt: " + str(prompt_token_count) + " \nCompletion: " + str(completion_token_count) + " \nTotal Cost: $" + str(total_cost))