File size: 13,964 Bytes
19ca162
 
 
 
 
1480a79
19ca162
 
 
 
 
 
 
1480a79
19ca162
 
 
 
 
d724402
 
19ca162
 
 
d724402
19ca162
1480a79
2e7ed44
d724402
19ca162
1480a79
2e7ed44
1480a79
19ca162
1480a79
19ca162
 
 
 
 
 
 
 
 
 
 
 
 
 
1480a79
19ca162
 
 
 
 
 
199bed8
19ca162
1480a79
19ca162
 
1480a79
19ca162
 
7fce5dd
19ca162
 
 
 
 
 
 
 
 
 
 
 
 
1480a79
19ca162
3ac5ff9
1480a79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19ca162
1480a79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19ca162
 
 
1480a79
 
 
 
 
 
 
19ca162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
299
300
301
302
303
from getpass import getpass
from langchain_openai import OpenAIEmbeddings

from pinecone import Pinecone

from pinecone_text.sparse import BM25Encoder
from langchain_community.retrievers import PineconeHybridSearchRetriever

import os

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableParallel, RunnablePassthrough, Runnable
from langchain_openai import ChatOpenAI
from langchain.retrievers import EnsembleRetriever

import streamlit as st

# Streamlit App Configuration (gets model_name, index_name, namespace_name before needed)
st.set_page_config(page_title="Chat with Langgraph and Autogen Repos", page_icon="🟩")
st.markdown("<h1 style='text-align: center;'>Select your repo and begin chatting:</h1>", unsafe_allow_html=True)



namespace_name = st.sidebar.selectbox("Choose a Repo", ("Langgraph", ""))

value = st.sidebar.slider('Files to retrieve', min_value=1.0, max_value=4.0, step=1.0)

namespace_name2 = st.sidebar.selectbox("Choose a Repo", ("Autogen", ""))

value2 = st.sidebar.slider('Files to retrieve', min_value=1.0, max_value=4.0, step=1.0, key='website2')

# namespace_name3 = st.sidebar.selectbox("Choose a Website", ("","Langchain","Apify", "AWS","Crawlee", "QDRANT", "Supabase", "Pinecone","Zapier","Perplexity", "TestingPDF"))

# value3 = st.sidebar.slider('Pages to retrieve', min_value=1.0, max_value=4.0, step=1.0, key='website3')

# ========== PART 1 ==========
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
PINE_API_KEY = os.getenv("PINE_API_KEY")

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


# ========== PART 2 ==========
index_name='autogen'
pc = Pinecone(api_key=PINE_API_KEY)
index = pc.Index(index_name)

# ========== PART 3 ==========


splade_encoder = BM25Encoder()
retriever1 = PineconeHybridSearchRetriever(
    embeddings=embed, sparse_encoder=splade_encoder, index=index, namespace='langgraph-main', top_k=value
)
retriever2 = PineconeHybridSearchRetriever(
    embeddings=embed, sparse_encoder=splade_encoder, index=index, namespace='lmsys', top_k=value2
)

retriever = EnsembleRetriever(retrievers=[retriever1, retriever2], weights=[0.5,0.5])


LANGCHAIN_TRACING_V2 = os.getenv('LANGCHAIN_TRACING_V2')

LANGCHAIN_ENDPOINT = os.getenv('LANGCHAIN_ENDPOINT')

LANGCHAIN_PROJECT = os.getenv('LANGCHAIN_PROJECT')

LANGCHAIN_API_KEY = os.getenv('LANGCHAIN_API_KEY')


# ========== PART 4 ==========
# RAG prompt
# prefix = f"You are an expert in {namespace_name} documentation. Your purpose is to provide concise, accurate assistance to the user's specific question using only the context provided from the official {namespace_name} documentation.\n"

autogen_template = """
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.

Remember to use the retriever_tool frequently—even for queries you feel you already know the answer to—since the AutoGen documentation and codebase are continuously updated.

IMPORTANT: Include relevant links (provided in context) within your responses wherever possible so users can navigate to the original resources. Format links in markdown as follows: '[AutoGen Documentation](https://microsoft.github.io/autogen/)'.

here's the relevant files given the user's query: <query>{question}</query><documentation_and_examples>{context}</documentation_and_examples>

Now, please help the user with their query: {question}
"""


langgraph_template = """
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:** Include relevant links (from the context provided) in your responses using markdown. For example: `[LangGraph Documentation](https://langchain.com/langgraph)`.

Here's the relevant context for the user's query:
<query>{question}</query>
<documentation_and_examples>{context}</documentation_and_examples>

Now, please help the user with their query: {question}
"""


if namespace_name2 == 'Autogen':
    prompt = ChatPromptTemplate.from_template(autogen_template)
else:
    prompt = ChatPromptTemplate.from_template(langgraph_templatetemplate)


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

class SourceDedup(Runnable):
    def invoke(self, input, config=None):
        assert isinstance(input, dict)
        documents = input["context"]
        unique_sources = set()
        unique_documents = []

        for doc in documents:
            source = doc.metadata["source"]
            if source not in unique_sources:
                unique_sources.add(source)
                unique_documents.append(doc)
        input["context"] = unique_documents
        return input

class PassParentContent(Runnable):
    def invoke(self, input, config=None):
        assert isinstance(input, dict)
        documents = input["context"]

        for doc in documents:
          if "parent_content" in doc.metadata:
            doc.page_content = doc.metadata["parent_content"]
        return input

rag_chain = (
    RunnablePassthrough()
    | SourceDedup()
    | PassParentContent()
    | prompt
    | model
    | StrOutputParser()
)

rag_chain_with_source = RunnableParallel(
    {"context": retriever, "question": RunnablePassthrough()}
).assign(answer=rag_chain)

def generate_response(prompt):
    start = ""
    st.session_state['generated'].append(start)
    yield start

    all_sources = []
    for chunk in rag_chain_with_source.stream(prompt):
    
            if list(chunk.keys())[0] == 'answer':
                st.session_state['generated'][-1] += chunk['answer']
                yield chunk['answer']
    
            elif list(chunk.keys())[0] == 'context':
                pass
                # Sources DO NOT work the same with this code... removing for now.
                sources = chunk['context']
                for thing in chunk['context']:
                    print()
                    print(thing.metadata)
                sources = [doc.metadata['source'] for doc in chunk['context']]
                all_sources.extend(sources)
    
    formatted_response = f"\n\nSources:\n" + "\n".join(all_sources)
    yield formatted_response

# question = "How can I do hybrid search with a pinecone database?"
# answer = generate_response(question)
# print(answer)

# ==================== THE REST OF THE STREAMLIT APP ====================

# Initialize session state variables if they don't exist
if 'generated' not in st.session_state:
    st.session_state['generated'] = []

if 'past' not in st.session_state:
    st.session_state['past'] = []

if 'messages' not in st.session_state:
    st.session_state['messages'] = [{"role": "system", "content": "You are a helpful assistant."}]

if 'total_cost' not in st.session_state:
    st.session_state['total_cost'] = 0.0

def refresh_text():
    with response_container:
        for i in range(len(st.session_state['past'])):
            try:
                user_message_content = st.session_state["past"][i]
                message = st.chat_message("user")
                message.write(user_message_content)
            except:
                print("Past error")
            
            try:
                ai_message_content = st.session_state["generated"][i]
                message = st.chat_message("assistant")
                message.write(ai_message_content)
            except:
                print("Generated Error")

response_container = st.container()
container = st.container()

if prompt := st.chat_input("Ask a question..."):
        st.session_state['past'].append(prompt)
        refresh_text()

        st.session_state['messages'].append({"role": "user", "content": prompt})
        with response_container:
            my_generator = generate_response(prompt)
            message = st.chat_message("assistant")
            message.write_stream(my_generator)

if __name__ == "__main__":
    #result = retriever.get_relevant_documents("foo")
    #print(result[0].page_content)
    pass