File size: 15,413 Bytes
640609e
 
 
 
 
 
 
 
 
 
 
 
e90009f
a5622a1
 
 
 
 
0fc43fd
640609e
 
5de9f50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74e472c
 
5de9f50
74e472c
5de9f50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74e472c
5de9f50
 
 
 
 
 
74e472c
5de9f50
 
 
 
 
74e472c
5de9f50
 
74e472c
 
 
5de9f50
 
640609e
 
c08f768
0fc43fd
5de9f50
 
74e472c
 
 
 
0fc43fd
640609e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c08f768
640609e
 
 
 
 
 
5de9f50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74e472c
 
5de9f50
74e472c
5de9f50
74e472c
 
 
 
640609e
 
 
 
5de9f50
640609e
 
 
c08f768
 
 
5de9f50
bf24cbc
0fc43fd
c08f768
 
74e472c
bf24cbc
06f2846
c08f768
0fc43fd
5de9f50
c08f768
640609e
0fc43fd
640609e
 
 
 
 
 
 
c08f768
640609e
 
 
 
 
 
 
 
 
 
 
0998f81
640609e
 
 
75b08cc
 
640609e
 
 
9bf709f
e90009f
 
03550bb
 
 
 
e90009f
03550bb
 
640609e
9bf709f
640609e
e90009f
640609e
03550bb
640609e
e90009f
26cb132
640609e
e90009f
 
 
 
 
 
 
 
 
 
 
 
640609e
03550bb
640609e
e90009f
03550bb
 
 
 
9bf709f
e90009f
 
 
 
 
 
03550bb
26cb132
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import os
import time
import streamlit as st
import nltk

from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from pinecone import Pinecone
from pinecone_text.sparse import BM25Encoder
from langchain_community.retrievers import PineconeHybridSearchRetriever
from langchain.tools.retriever import create_retriever_tool
from langgraph.prebuilt import create_react_agent

LANGCHAIN_API_KEY = os.environ['LANGCHAIN_API_KEY']

os.environ['LANGCHAIN_TRACING_V2'] = "true"

os.environ['LANGCHAIN_ENDPOINT'] = "https://api.smith.langchain.com"

# Download the NLTK tokenizer (if not already downloaded)
nltk.download('punkt_tab')

# ----------------- System Prompts ----------------- #
# Autogen system prompt (used if "autogen" is selected in either dropdown)
autogen_system_prompt = """
You are an AI assistant specializing in the AutoGen framework. Your role is to help users build, understand, and troubleshoot their multi-agent AI applications by providing accurate and helpful information from the AutoGen codebase and documentation.
You have access to a powerful tool called 'retriever_tool' that functions as a search engine for the AutoGen documentation and codebase. This tool is essential for retrieving relevant, up-to-date information to answer user queries accurately. Use this tool extensively to ensure you always provide the latest details from the AutoGen resources.
When using the retriever_tool, formulate your search queries using these key terms to find specific information from the documentation:
- "Getting started" for installation, setup, and configuration instructions.
- "Agents" for creating, managing, and customizing AI agents.
- "Multi-agent workflows" for establishing conversations and collaborations among agents.
- "API Reference" for detailed documentation on classes, methods, and functions.
- "Code execution" for instructions on running code snippets or managing code-based tasks.
- "Extensions" for integrating third-party services or adding custom tools.
- "AutoGen Studio" for guidance on using the no-code interface and prototyping applications.
- "Core API" for understanding the low-level components and event-driven architectures.
- "AgentChat" for best practices in multi-agent interaction and conversation patterns.
- "Tool use" for incorporating external functionalities and custom integrations.
- "Configuration" for customizing the framework’s behavior.
- "Migration" for upgrading between AutoGen versions.
- "Examples" for practical code samples and real-world use cases.
- "FAQ" for common questions, troubleshooting tips, and clarifications.
NOTE: Append the word "example" to any of the above terms to search for an illustrative example. Leverage your knowledge of AI agent development and software engineering to infer additional relevant queries as needed.
When responding to user queries:
1. Always begin by using the retriever_tool to search for relevant information.
2. Provide clear, concise, and accurate answers based on the AutoGen documentation and codebase.
3. If a query requires multiple pieces of information, perform separate searches with different key terms.
4. Include code snippets or API usage examples when relevant.
5. Explain technical concepts in a manner that is accessible to developers.
Format your responses as follows:
1. Start with a brief introduction addressing the user's query.
2. Present the main answer or explanation.
3. Include any relevant code snippets or API examples.
4. Offer additional context or related information when applicable.
5. Conclude with suggestions for next steps or related topics the user might explore further.
If a user’s query is unclear or falls outside the scope of AutoGen, politely ask for clarification or direct them to more appropriate resources.
IMPORTANT: Be concise with your code generation to adhere to AutoGen's framework.
"""

# LangGraph system prompt (for LangGraph’s codebase)
langgraph_system_prompt = """
You are an AI assistant specializing in the LangGraph framework. Your role is to help users build, understand, and troubleshoot their multi-agent AI applications by providing accurate and helpful information from the LangGraph documentation, source code, and examples.
You have access to a powerful tool called `retriever_tool` that functions as a search engine for LangGraph’s resources. This tool is essential for retrieving up-to-date information to answer user queries accurately. Use it extensively to ensure your responses reflect the latest details from LangGraph.
When using the `retriever_tool`, formulate your search queries with these key terms:
- **Getting started**: for installation, setup, and configuration instructions.
- **Nodes**: for creating, managing, and customizing workflow nodes.
- **Multi-agent workflows**: for establishing interactions and collaborations among agents.
- **API Reference**: for detailed documentation on classes, methods, and functions.
- **Code execution**: for instructions on running code snippets or managing code-based tasks.
- **Extensions**: for integrating third-party services or adding custom tools.
- **LangGraph Studio**: for guidance on using the graphical interface and prototyping applications.
- **Core API**: for understanding low-level components and event-driven architectures.
- **Tool use**: for incorporating external functionalities and custom integrations.
- **Configuration**: for customizing the framework’s behavior.
- **Migration**: for upgrading between LangGraph versions.
- **Examples**: for practical code samples and real-world use cases.
- **FAQ**: for common questions, troubleshooting tips, and clarifications.
*Note:* Append “example” to any key term (e.g., “Nodes example”) to search for illustrative examples. Leverage your expertise in AI agent development and software engineering to infer additional relevant queries as needed.
When responding to user queries:
1. **Begin** by using the `retriever_tool` to search for relevant information.
2. **Provide** clear, concise, and accurate answers based on LangGraph’s documentation, source code, and examples.
3. **Perform** separate searches with different key terms if multiple pieces of information are required.
4. **Include** code snippets or API usage examples when relevant.
5. **Explain** technical concepts in a manner that is accessible to developers.
**Response Format:**
- Start with a brief introduction addressing the user's query.
- Present the main answer or explanation.
- Include any relevant code snippets or API examples.
- Offer additional context or related information when applicable.
- Conclude with suggestions for next steps or related topics to explore further.
If a user’s query is unclear or falls outside the scope of LangGraph, politely ask for clarification or direct them to more appropriate resources.
Always use the `retriever_tool` frequently—even for queries you think you know well—since LangGraph’s resources are continuously updated.
IMPORTANT: Be concise with your code generation to adhere to LangGraph's framework.
"""

def convert_namespace(ns: str) -> str:
    """
    Convert the UI namespace option to the actual namespace used.
    If the user selects "autogen", return "lmsys" instead.
    Otherwise, return the option as-is.
    """
    return "lmsys" if ns == "autogen" else ns

def get_description(actual_namespace: str, top_k: int) -> str:
    """
    Generate a dynamic description for a retriever tool based on the actual namespace and top_k value.
    """
    if actual_namespace == "lmsys":
        return f"Search and return information from AutoGen's codebase using namespace '{actual_namespace}' with top_k = {top_k}."
    elif actual_namespace == "llm-cli":
        return f"Search and return information using the LLM CLI interface with namespace '{actual_namespace}' with top_k = {top_k}."
    else:
        return f"Search and return information from LangGraph's documentation using namespace '{actual_namespace}' with top_k = {top_k}."

@st.cache_resource
def init_agent(namespace1: str, top_k1: int, namespace2: str, top_k2: int):
    """
    Initialize the LangGraph agent with up to two Pinecone retriever tools.
    Only add a retriever tool if a non-empty namespace is provided.
    Choose the system prompt based on the active namespaces:
      - If either dropdown is set to "autogen", use autogen_system_prompt.
      - Else if any non-empty namespace is "langgraph-main", use langgraph_system_prompt.
      - Else if the only active namespace is "llm-cli", use an empty string as the prompt.
    """
    # Retrieve API keys from environment variables
    OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
    PINE_API_KEY = os.environ.get("PINE_API_KEY")
    if not OPENAI_API_KEY or not PINE_API_KEY:
        raise ValueError("Please set the OPENAI_API_KEY and PINE_API_KEY environment variables.")

    # --- Embeddings ---
    embed = OpenAIEmbeddings(
        model='text-embedding-3-small',
        openai_api_key=OPENAI_API_KEY,
        dimensions=768
    )

    # --- Pinecone Setup ---
    index_name = 'autogen'
    pc = Pinecone(api_key=PINE_API_KEY)
    index = pc.Index(index_name)
    # Allow a moment for the index to connect
    time.sleep(1)
    index.describe_index_stats()

    # --- BM25 Sparse Encoder ---
    bm25_encoder = BM25Encoder().default()

    tools = []  # Initialize empty list of tools

    # Create first retriever tool if a namespace is selected.
    if namespace1:
        actual_namespace1 = convert_namespace(namespace1)
        retriever1 = PineconeHybridSearchRetriever(
            embeddings=embed,
            sparse_encoder=bm25_encoder,
            index=index,
            namespace=actual_namespace1,
            top_k=top_k1
        )
        description1 = get_description(actual_namespace1, top_k1)
        retriever_tool1 = create_retriever_tool(
            retriever1,
            "retrieve_context_1",
            description1,
        )
        tools.append(retriever_tool1)

    # Create second retriever tool if a namespace is selected.
    if namespace2:
        actual_namespace2 = convert_namespace(namespace2)
        retriever2 = PineconeHybridSearchRetriever(
            embeddings=embed,
            sparse_encoder=bm25_encoder,
            index=index,
            namespace=actual_namespace2,
            top_k=top_k2
        )
        description2 = get_description(actual_namespace2, top_k2)
        retriever_tool2 = create_retriever_tool(
            retriever2,
            "retrieve_context_2",
            description2,
        )
        tools.append(retriever_tool2)

    # --- Choose the System Prompt Based on Namespace Selections ---
    active_ns = [ns for ns in [namespace1, namespace2] if ns != ""]
    if "autogen" in active_ns:
        prompt = autogen_system_prompt
    elif any(ns == "langgraph-main" for ns in active_ns):
        prompt = langgraph_system_prompt
    elif active_ns and all(ns == "llm-cli" for ns in active_ns):
        prompt = ""  # Empty system prompt when only llm-cli is active.
    else:
        prompt = ""

    # --- Chat Model ---
    model = ChatOpenAI(model_name="o3-mini-2025-01-31", openai_api_key=OPENAI_API_KEY)

    # --- Create the React Agent with the selected prompt ---
    graph = create_react_agent(model, tools=tools, messages_modifier=prompt)
    return graph

# ----------------- Sidebar: Namespace & Top_K Selection ----------------- #
st.sidebar.header("Retriever Tool Settings")

# Dropdown and slider for Retriever Tool 1 (empty option available)
namespace_options = ["langgraph-main", "autogen", "llm-cli", "smolagents", ""]
namespace1 = st.sidebar.selectbox("Select namespace for Retriever Tool 1:", namespace_options, index=0)
top_k1 = st.sidebar.slider("Select top_k for Retriever Tool 1:", min_value=1, max_value=4, value=1, step=1)

# For Retriever Tool 2, we limit the options (if desired) or leave the same.
namespace_options2 = ["autogen", "smolagents", "llm-cli", ""]
namespace2 = st.sidebar.selectbox("Select namespace for Retriever Tool 2:", namespace_options2, index=0)
top_k2 = st.sidebar.slider("Select top_k for Retriever Tool 2:", min_value=1, max_value=4, value=1, step=1)

# Initialize the agent with the selected namespaces (after conversion) and top_k values.
graph = init_agent(namespace1, top_k1, namespace2, top_k2)

# ----------------- Main Chat App UI ----------------- #
st.title("LangGraph Coding Chat Assistant")

# Initialize conversation history in session state
if "chat_history" not in st.session_state:
    st.session_state.chat_history = []  # Each entry is a tuple: (role, message)

def display_conversation():
    """Display the chat conversation."""
    for role, message in st.session_state.chat_history:
        if role == "user":
            st.markdown(f"**You:** {message}")
        else:
            st.markdown(f"**Assistant:** {message}")

# Display the existing conversation
display_conversation()

# --- Chat Input Form ---
with st.form("chat_form", clear_on_submit=True):
    user_input = st.text_area("Enter your message:", height=150)
    submitted = st.form_submit_button("Send")
    if submitted and user_input:
        st.session_state.chat_history.append(("user", user_input))
        # No need to force a rerun—Streamlit re-runs automatically on widget interaction.

# --- Generate Assistant Response ---
if st.session_state.chat_history and st.session_state.chat_history[-1][0] == "user":
    inputs = {"messages": st.session_state.chat_history}

    # Create separate placeholders for each section.
    tool_calls_placeholder = st.empty()
    tool_output_placeholder = st.empty()
    final_answer_placeholder = st.empty()

    # Accumulators for each section.
    tool_calls_text = ""
    tool_output_text = ""
    final_answer_text = ""

    # Stream the agent's response chunk-by-chunk.
    for s in graph.stream(inputs, stream_mode="values"):
        # Extract the last message from the current chunk.
        message = s["messages"][-1]
        
        if isinstance(message, tuple):
            # This is a tool-related message.
            # We use a simple heuristic: if the text contains "call_" (case-insensitive), we treat it as a tool call.
            role, text = message
            if "call_" in text.lower():
                tool_calls_text += text + "\n\n"
                tool_calls_placeholder.markdown(
                    f"### Tool Calls\n\n{tool_calls_text}",
                    unsafe_allow_html=True
                )
            else:
                tool_output_text += text + "\n\n"
                tool_output_placeholder.markdown(
                    f"### Tool Output\n\n{tool_output_text}",
                    unsafe_allow_html=True
                )
        else:
            # This is the final answer generated by the AI.
            text = message.content
            final_answer_text += text + "\n\n"
            final_answer_placeholder.markdown(
                f"### Final Answer\n\n{final_answer_text}",
                unsafe_allow_html=True
            )

    # Once complete, combine all sections into one record for persistence.
    combined_response = (
        f"**Tool Calls:**\n\n{tool_calls_text}\n\n"
        f"**Tool Output:**\n\n{tool_output_text}\n\n"
        f"**Final Answer:**\n\n{final_answer_text}"
    )
    st.session_state.chat_history.append(("assistant", combined_response))