Added new demo
This commit is contained in:
parent
aaf5b72fe9
commit
a91e3be9ea
6 changed files with 431 additions and 0 deletions
49
Cursor AI Experiments/ai_web_scrapper.py
Normal file
49
Cursor AI Experiments/ai_web_scrapper.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import streamlit as st
|
||||
from scrapegraphai.graphs import SmartScraperGraph
|
||||
|
||||
# Streamlit app title
|
||||
st.title("AI Web Scraper")
|
||||
|
||||
# Input fields for user prompt and source URL
|
||||
prompt = st.text_input("Enter the information you want to extract:")
|
||||
source_url = st.text_input("Enter the source URL:")
|
||||
|
||||
# Input field for OpenAI API key
|
||||
api_key = st.text_input("Enter your OpenAI API key:", type="password")
|
||||
|
||||
# Configuration for the scraping pipeline
|
||||
graph_config = {
|
||||
"llm": {
|
||||
"api_key": api_key,
|
||||
"model": "openai/gpt-4o-mini",
|
||||
},
|
||||
"verbose": True,
|
||||
"headless": False,
|
||||
}
|
||||
|
||||
# Button to start the scraping process
|
||||
if st.button("Scrape"):
|
||||
if prompt and source_url and api_key:
|
||||
# Create the SmartScraperGraph instance
|
||||
smart_scraper_graph = SmartScraperGraph(
|
||||
prompt=prompt,
|
||||
source=source_url,
|
||||
config=graph_config
|
||||
)
|
||||
|
||||
# Run the pipeline
|
||||
result = smart_scraper_graph.run()
|
||||
|
||||
# Display the result
|
||||
st.write(result)
|
||||
else:
|
||||
st.error("Please provide all the required inputs.")
|
||||
|
||||
# Instructions for the user
|
||||
st.markdown("""
|
||||
### Instructions
|
||||
1. Enter the information you want to extract in the first input box.
|
||||
2. Enter the source URL from which you want to extract the information.
|
||||
3. Enter your OpenAI API key.
|
||||
4. Click on the "Scrape" button to start the scraping process.
|
||||
""")
|
||||
40
Cursor AI Experiments/chatgpt_clone_llama3.py
Normal file
40
Cursor AI Experiments/chatgpt_clone_llama3.py
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import streamlit as st
|
||||
from ollama import Client
|
||||
|
||||
# Initialize Ollama client
|
||||
client = Client()
|
||||
|
||||
# Set up Streamlit page
|
||||
st.set_page_config(page_title="Local ChatGPT Clone", page_icon="🤖", layout="wide")
|
||||
st.title("🤖 Local ChatGPT Clone")
|
||||
|
||||
# Initialize chat history
|
||||
if "messages" not in st.session_state:
|
||||
st.session_state.messages = []
|
||||
|
||||
# Display chat messages
|
||||
for message in st.session_state.messages:
|
||||
with st.chat_message(message["role"]):
|
||||
st.markdown(message["content"])
|
||||
|
||||
# User input
|
||||
if prompt := st.chat_input("What's on your mind?"):
|
||||
st.session_state.messages.append({"role": "user", "content": prompt})
|
||||
with st.chat_message("user"):
|
||||
st.markdown(prompt)
|
||||
|
||||
# Generate AI response
|
||||
with st.chat_message("assistant"):
|
||||
message_placeholder = st.empty()
|
||||
full_response = ""
|
||||
for response in client.chat(model="llama3.1:latest", messages=st.session_state.messages, stream=True):
|
||||
full_response += response['message']['content']
|
||||
message_placeholder.markdown(full_response + "▌")
|
||||
message_placeholder.markdown(full_response)
|
||||
st.session_state.messages.append({"role": "assistant", "content": full_response})
|
||||
|
||||
# Add a sidebar with information
|
||||
st.sidebar.title("About")
|
||||
st.sidebar.info("This is a local ChatGPT clone using Ollama's llama3.1:latest model and Streamlit.")
|
||||
st.sidebar.markdown("---")
|
||||
st.sidebar.markdown("Made with ❤️ by Your Name")
|
||||
135
Cursor AI Experiments/multi_agent_researcher.py
Normal file
135
Cursor AI Experiments/multi_agent_researcher.py
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
import streamlit as st
|
||||
from crewai import Agent, Task, Crew, Process
|
||||
from langchain_openai import ChatOpenAI
|
||||
import os
|
||||
|
||||
# Initialize the GPT-4 model
|
||||
gpt4_model = None
|
||||
|
||||
def create_article_crew(topic):
|
||||
# Create agents
|
||||
researcher = Agent(
|
||||
role='Researcher',
|
||||
goal='Conduct thorough research on the given topic',
|
||||
backstory='You are an expert researcher with a keen eye for detail',
|
||||
verbose=True,
|
||||
allow_delegation=False,
|
||||
llm=gpt4_model
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
role='Writer',
|
||||
goal='Write a detailed and engaging article based on the research, using proper markdown formatting',
|
||||
backstory='You are a skilled writer with expertise in creating informative content and formatting it beautifully in markdown',
|
||||
verbose=True,
|
||||
allow_delegation=False,
|
||||
llm=gpt4_model
|
||||
)
|
||||
|
||||
editor = Agent(
|
||||
role='Editor',
|
||||
goal='Review and refine the article for clarity, accuracy, engagement, and proper markdown formatting',
|
||||
backstory='You are an experienced editor with a sharp eye for quality content and excellent markdown structure',
|
||||
verbose=True,
|
||||
allow_delegation=False,
|
||||
llm=gpt4_model
|
||||
)
|
||||
|
||||
# Create tasks
|
||||
research_task = Task(
|
||||
description=f"Conduct comprehensive research on the topic: {topic}. Gather key information, statistics, and expert opinions.",
|
||||
agent=researcher,
|
||||
expected_output="A comprehensive research report on the given topic, including key information, statistics, and expert opinions."
|
||||
)
|
||||
|
||||
writing_task = Task(
|
||||
description="""Using the research provided, write a detailed and engaging article.
|
||||
Ensure proper structure, flow, and clarity. Format the article using markdown, including:
|
||||
1. A main title (H1)
|
||||
2. Section headings (H2)
|
||||
3. Subsection headings where appropriate (H3)
|
||||
4. Bullet points or numbered lists where relevant
|
||||
5. Emphasis on key points using bold or italic text
|
||||
Make sure the content is well-organized and easy to read.""",
|
||||
agent=writer,
|
||||
expected_output="A well-structured, detailed, and engaging article based on the provided research, formatted in markdown with proper headings and subheadings."
|
||||
)
|
||||
|
||||
editing_task = Task(
|
||||
description="""Review the article for clarity, accuracy, engagement, and proper markdown formatting.
|
||||
Ensure that:
|
||||
1. The markdown formatting is correct and consistent
|
||||
2. Headings and subheadings are used appropriately
|
||||
3. The content flow is logical and engaging
|
||||
4. Key points are emphasized correctly
|
||||
Make necessary edits and improvements to both content and formatting.""",
|
||||
agent=editor,
|
||||
expected_output="A final, polished version of the article with improved clarity, accuracy, engagement, and proper markdown formatting."
|
||||
)
|
||||
|
||||
# Create the crew
|
||||
crew = Crew(
|
||||
agents=[researcher, writer, editor],
|
||||
tasks=[research_task, writing_task, editing_task],
|
||||
verbose=2,
|
||||
process=Process.sequential
|
||||
)
|
||||
|
||||
return crew
|
||||
|
||||
# Streamlit app
|
||||
st.set_page_config(page_title="Multi Agent AI Researcher", page_icon="📝")
|
||||
|
||||
# Custom CSS for better appearance
|
||||
st.markdown("""
|
||||
<style>
|
||||
.stApp {
|
||||
max-width: 1800px;
|
||||
margin: 0 auto;
|
||||
font-family: Arial, sans-serif;
|
||||
}
|
||||
.st-bw {
|
||||
background-color: #f0f2f6;
|
||||
}
|
||||
.stButton>button {
|
||||
background-color: #4CAF50;
|
||||
color: white;
|
||||
font-weight: bold;
|
||||
}
|
||||
.stTextInput>div>div>input {
|
||||
background-color: #ffffff;
|
||||
}
|
||||
</style>
|
||||
""", unsafe_allow_html=True)
|
||||
|
||||
st.title("📝 Multi Agent AI Researcher")
|
||||
|
||||
# Sidebar for API key input
|
||||
with st.sidebar:
|
||||
st.header("Configuration")
|
||||
api_key = st.text_input("Enter your OpenAI API Key:", type="password")
|
||||
if api_key:
|
||||
os.environ["OPENAI_API_KEY"] = api_key
|
||||
gpt4_model = ChatOpenAI(model_name="gpt-4o-mini")
|
||||
st.success("API Key set successfully!")
|
||||
else:
|
||||
st.info("Please enter your OpenAI API Key to proceed.")
|
||||
|
||||
# Main content
|
||||
st.markdown("Generate detailed articles on any topic using AI agents!")
|
||||
|
||||
topic = st.text_input("Enter the topic for the article:", placeholder="e.g., The Impact of Artificial Intelligence on Healthcare")
|
||||
|
||||
if st.button("Generate Article"):
|
||||
if not api_key:
|
||||
st.error("Please enter your OpenAI API Key in the sidebar.")
|
||||
elif not topic:
|
||||
st.warning("Please enter a topic for the article.")
|
||||
else:
|
||||
with st.spinner("🤖 AI agents are working on your article..."):
|
||||
crew = create_article_crew(topic)
|
||||
result = crew.kickoff()
|
||||
st.markdown(result)
|
||||
|
||||
st.markdown("---")
|
||||
st.markdown("Powered by CrewAI and OpenAI :heart:")
|
||||
38
ai_customer_support_agent/README.md
Normal file
38
ai_customer_support_agent/README.md
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
## 🛒 AI Customer Support Agent with Memory
|
||||
This Streamlit app implements an AI-powered customer support agent for TechGadgets.com, an online electronics store. The agent uses OpenAI's GPT-4 model and maintains a memory of past interactions using the Mem0 library with Qdrant as the vector store.
|
||||
|
||||
### Features
|
||||
|
||||
- Chat interface for interacting with the AI customer support agent
|
||||
- Persistent memory of customer interactions and profiles
|
||||
- Synthetic data generation for testing and demonstration
|
||||
- Utilizes OpenAI's GPT-4o model for intelligent responses
|
||||
|
||||
### How to get Started?
|
||||
|
||||
1. Clone the GitHub repository
|
||||
```bash
|
||||
git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
|
||||
```
|
||||
|
||||
2. Install the required dependencies:
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. Ensure Qdrant is running:
|
||||
The app expects Qdrant to be running on localhost:6333. Adjust the configuration in the code if your setup is different.
|
||||
|
||||
```bash
|
||||
docker pull qdrant/qdrant
|
||||
|
||||
docker run -p 6333:6333 -p 6334:6334 \
|
||||
-v $(pwd)/qdrant_storage:/qdrant/storage:z \
|
||||
qdrant/qdrant
|
||||
```
|
||||
|
||||
4. Run the Streamlit App
|
||||
```bash
|
||||
streamlit run customer_support_agent.py
|
||||
```
|
||||
166
ai_customer_support_agent/customer_support_agent.py
Normal file
166
ai_customer_support_agent/customer_support_agent.py
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
import streamlit as st
|
||||
from openai import OpenAI
|
||||
from mem0 import Memory
|
||||
import os
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# Set up the Streamlit App
|
||||
st.title("AI Customer Support Agent with Memory 🛒")
|
||||
st.caption("Chat with a customer support assistant who remembers your past interactions.")
|
||||
|
||||
# Set the OpenAI API key
|
||||
openai_api_key = st.text_input("Enter OpenAI API Key", type="password")
|
||||
|
||||
if openai_api_key:
|
||||
os.environ['OPENAI_API_KEY'] = openai_api_key
|
||||
|
||||
class CustomerSupportAIAgent:
|
||||
def __init__(self):
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "qdrant",
|
||||
"config": {
|
||||
"model": "gpt-4o-mini",
|
||||
"host": "localhost",
|
||||
"port": 6333,
|
||||
}
|
||||
},
|
||||
}
|
||||
self.memory = Memory.from_config(config)
|
||||
self.client = OpenAI()
|
||||
self.app_id = "customer-support"
|
||||
|
||||
def handle_query(self, query, user_id=None):
|
||||
relevant_memories = self.memory.search(query=query, user_id=user_id)
|
||||
context = "Relevant past information:\n"
|
||||
for mem in relevant_memories:
|
||||
context += f"- {mem['text']}\n"
|
||||
|
||||
full_prompt = f"{context}\nCustomer: {query}\nSupport Agent:"
|
||||
|
||||
response = self.client.chat.completions.create(
|
||||
model="gpt-4o-mini",
|
||||
messages=[
|
||||
{"role": "system", "content": "You are a customer support AI agent for TechGadgets.com, an online electronics store."},
|
||||
{"role": "user", "content": full_prompt}
|
||||
]
|
||||
)
|
||||
answer = response.choices[0].message.content
|
||||
|
||||
self.memory.add(query, user_id=user_id, metadata={"app_id": self.app_id, "role": "user"})
|
||||
self.memory.add(answer, user_id=user_id, metadata={"app_id": self.app_id, "role": "assistant"})
|
||||
|
||||
return answer
|
||||
|
||||
def get_memories(self, user_id=None):
|
||||
return self.memory.get_all(user_id=user_id)
|
||||
|
||||
def generate_synthetic_data(self, user_id):
|
||||
today = datetime.now()
|
||||
order_date = (today - timedelta(days=10)).strftime("%B %d, %Y")
|
||||
expected_delivery = (today + timedelta(days=2)).strftime("%B %d, %Y")
|
||||
|
||||
prompt = f"""Generate a detailed customer profile and order history for a TechGadgets.com customer with ID {user_id}. Include:
|
||||
1. Customer name and basic info
|
||||
2. A recent order of a high-end electronic device (placed on {order_date}, to be delivered by {expected_delivery})
|
||||
3. Order details (product, price, order number)
|
||||
4. Customer's shipping address
|
||||
5. 2-3 previous orders from the past year
|
||||
6. 2-3 customer service interactions related to these orders
|
||||
7. Any preferences or patterns in their shopping behavior
|
||||
|
||||
Format the output as a JSON object."""
|
||||
|
||||
response = self.client.chat.completions.create(
|
||||
model="gpt-4o-mini",
|
||||
messages=[
|
||||
{"role": "system", "content": "You are a data generation AI that creates realistic customer profiles and order histories. Always respond with valid JSON."},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
response_format={"type": "json_object"}
|
||||
)
|
||||
|
||||
customer_data = json.loads(response.choices[0].message.content)
|
||||
|
||||
# Add generated data to memory
|
||||
for key, value in customer_data.items():
|
||||
if isinstance(value, list):
|
||||
for item in value:
|
||||
self.memory.add(json.dumps(item), user_id=user_id, metadata={"app_id": self.app_id, "role": "system"})
|
||||
else:
|
||||
self.memory.add(f"{key}: {json.dumps(value)}", user_id=user_id, metadata={"app_id": self.app_id, "role": "system"})
|
||||
|
||||
return customer_data
|
||||
|
||||
# Initialize the CustomerSupportAIAgent
|
||||
support_agent = CustomerSupportAIAgent()
|
||||
|
||||
# Sidebar for customer ID and memory view
|
||||
st.sidebar.title("Enter your Customer ID:")
|
||||
previous_customer_id = st.session_state.get("previous_customer_id", None)
|
||||
customer_id = st.sidebar.text_input("Enter your Customer ID")
|
||||
|
||||
if customer_id != previous_customer_id:
|
||||
st.session_state.messages = []
|
||||
st.session_state.previous_customer_id = customer_id
|
||||
st.session_state.customer_data = None
|
||||
|
||||
# Add button to generate synthetic data
|
||||
if st.sidebar.button("Generate Synthetic Data"):
|
||||
if customer_id:
|
||||
with st.spinner("Generating customer data..."):
|
||||
st.session_state.customer_data = support_agent.generate_synthetic_data(customer_id)
|
||||
st.sidebar.success("Synthetic data generated successfully!")
|
||||
else:
|
||||
st.sidebar.error("Please enter a customer ID first.")
|
||||
|
||||
if st.sidebar.button("View Customer Profile"):
|
||||
if st.session_state.customer_data:
|
||||
st.sidebar.json(st.session_state.customer_data)
|
||||
else:
|
||||
st.sidebar.info("No customer data generated yet. Click 'Generate Synthetic Data' first.")
|
||||
|
||||
if st.sidebar.button("View Memory Info"):
|
||||
if customer_id:
|
||||
memories = support_agent.get_memories(user_id=customer_id)
|
||||
if memories:
|
||||
st.sidebar.write(f"Memory for customer **{customer_id}**:")
|
||||
for mem in memories:
|
||||
st.sidebar.write(f"- {mem['text']}")
|
||||
else:
|
||||
st.sidebar.info("No memory found for this customer ID.")
|
||||
else:
|
||||
st.sidebar.error("Please enter a customer ID to view memory info.")
|
||||
|
||||
# Initialize the chat history
|
||||
if "messages" not in st.session_state:
|
||||
st.session_state.messages = []
|
||||
|
||||
# Display the chat history
|
||||
for message in st.session_state.messages:
|
||||
with st.chat_message(message["role"]):
|
||||
st.markdown(message["content"])
|
||||
|
||||
# Accept user input
|
||||
query = st.chat_input("How can I assist you today?")
|
||||
|
||||
if query and customer_id:
|
||||
# Add user message to chat history
|
||||
st.session_state.messages.append({"role": "user", "content": query})
|
||||
with st.chat_message("user"):
|
||||
st.markdown(query)
|
||||
|
||||
# Generate and display response
|
||||
answer = support_agent.handle_query(query, user_id=customer_id)
|
||||
|
||||
# Add assistant response to chat history
|
||||
st.session_state.messages.append({"role": "assistant", "content": answer})
|
||||
with st.chat_message("assistant"):
|
||||
st.markdown(answer)
|
||||
|
||||
elif not customer_id:
|
||||
st.error("Please enter a customer ID to start the chat.")
|
||||
|
||||
else:
|
||||
st.warning("Please enter your OpenAI API key to use the customer support agent.")
|
||||
3
ai_customer_support_agent/requirements.txt
Normal file
3
ai_customer_support_agent/requirements.txt
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
streamlit
|
||||
openai
|
||||
mem0ai
|
||||
Loading…
Reference in a new issue