Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sakovmaster #2

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions LangChainAgents/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
OPENAI_API_KEY=
TAVILY_API_KEY=
LANGCHAIN_API_KEY=
CLIENT_ID=
CLIENT_SECRET=
TENANT_ID=
USERNAME=
AZURE_OPENAI_API_KEY=
AZURE_OPENAI_ENDPOINT=
GRAPH_ACCESS_TOKEN=
442 changes: 442 additions & 0 deletions LangChainAgents/Clippy2.ipynb

Large diffs are not rendered by default.

76 changes: 76 additions & 0 deletions LangChainAgents/azureAI.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 4,
"id": "afdec5df-fad2-48fe-a3f5-0bc92b70db98",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Sure! Here's one for you:\n",
"\n",
"Why don’t skeletons fight each other?\n",
"\n",
"Because they don’t have the guts! 😄\n"
]
}
],
"source": [
"from dotenv import load_dotenv\n",
"import os\n",
"from langchain_openai import AzureChatOpenAI\n",
"\n",
"#load the environment\n",
"load_dotenv(override=True)\n",
"\n",
"os.environ[\"AZURE_OPENAI_API_KEY\"] = os.getenv(\"AZURE_OPENAI_API_KEY\")\n",
"os.environ[\"AZURE_OPENAI_ENDPOINT\"] = os.getenv(\"AZURE_OPENAI_ENDPOINT\")\n",
"\n",
"llm = AzureChatOpenAI(\n",
" azure_deployment=\"gpt-4o\", # or your deployment\n",
" api_version=\"2024-08-01-preview\", # or your api version\n",
" temperature=0,\n",
" max_tokens=None,\n",
" timeout=None,\n",
" max_retries=2,\n",
" # other params...\n",
")\n",
"\n",
"ai_msg = llm.invoke(\"Tell me a joke\")\n",
"print(ai_msg.content)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f8d35630-cb56-4491-8c4d-641708fee5f5",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
265 changes: 265 additions & 0 deletions LangChainAgents/finalRAG.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "cb8c1438-3bfb-4241-a522-b127d54ae19d",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"----------------------------------------------------------\n",
"User prompt: Do I Need a Pizza Den Login to Sign into Pizza Den Wi-Fi?\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m\n",
"Invoking: `ragforPizzaDen` with `{'query': 'Do I Need a Pizza Den Login to Sign into Pizza Den Wi-Fi?'}`\n",
"\n",
"\n",
"\u001b[0mStatus Code 401\n",
"\u001b[38;5;200m\u001b[1;3m<Response [401]>\u001b[0m\u001b[32;1m\u001b[1;3mI'm unable to retrieve the information about signing into Pizza Den Wi-Fi at the moment. You might want to check directly with Pizza Den's customer service or their official website for accurate details.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"---------------------------------------------------------------------------------------------------------\n",
"User prompt: Which Internet Provider does Pizza Den use for its wifi?\n",
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m\n",
"Invoking: `ragforPizzaDen` with `{'query': 'Internet Provider used by Pizza Den for Wifi'}`\n",
"\n",
"\n",
"\u001b[0mStatus Code 401\n",
"\u001b[38;5;200m\u001b[1;3m<Response [401]>\u001b[0m\u001b[32;1m\u001b[1;3mI'm unable to retrieve the information about the Internet Provider used by Pizza Den for its WiFi at the moment. Is there anything else related to Pizza Den that I can assist you with?\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"{'input': 'Which Internet Provider does Pizza Den use for its wifi?',\n",
" 'chat_history': [HumanMessage(content='Do I Need a Pizza Den Login to Sign into Pizza Den Wi-Fi?', additional_kwargs={}, response_metadata={}),\n",
" AIMessage(content=\"I'm unable to retrieve the information about signing into Pizza Den Wi-Fi at the moment. You might want to check directly with Pizza Den's customer service or their official website for accurate details.\", additional_kwargs={}, response_metadata={})],\n",
" 'output': \"I'm unable to retrieve the information about the Internet Provider used by Pizza Den for its WiFi at the moment. Is there anything else related to Pizza Den that I can assist you with?\"}"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Import relevant functionality\n",
"import os\n",
"import asyncio\n",
"import requests\n",
"import urllib.parse\n",
"import json\n",
"import configparser\n",
"from datetime import date\n",
"from msgraph.generated.models.o_data_errors.o_data_error import ODataError\n",
"from configparser import SectionProxy\n",
"from langchain_core.messages import HumanMessage\n",
"from langgraph.checkpoint.memory import MemorySaver\n",
"from langgraph.prebuilt import create_react_agent\n",
"from langchain_openai import ChatOpenAI\n",
"from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"from langgraph.graph import START, MessagesState, StateGraph\n",
"from langchain.agents import AgentType, initialize_agent, load_tools\n",
"from langchain.tools import BaseTool, StructuredTool, tool\n",
"from langchain_openai import OpenAI\n",
"from langchain_core.runnables import ConfigurableField\n",
"from langchain.agents import create_tool_calling_agent, AgentExecutor\n",
"from langchain_core.runnables.history import RunnableWithMessageHistory\n",
"from langchain.agents import AgentExecutor, create_react_agent\n",
"from langchain.memory import ChatMessageHistory\n",
"from dotenv import load_dotenv\n",
"from configparser import SectionProxy\n",
"from azure.identity import DeviceCodeCredential\n",
"from langgraph.types import interrupt\n",
"from msgraph_beta import GraphServiceClient\n",
"from langchain_core.messages import HumanMessage\n",
"from langgraph.checkpoint.memory import MemorySaver\n",
"from langgraph.prebuilt import create_react_agent\n",
"from langchain_openai import ChatOpenAI\n",
"from langchain_core.prompts import ChatPromptTemplate\n",
"from typing import Annotated, Sequence\n",
"from langchain_core.messages import BaseMessage\n",
"from langchain_core.runnables import RunnableConfig\n",
"from langchain_core.tools import tool\n",
"from langgraph.graph import END, StateGraph\n",
"from langgraph.graph.message import add_messages\n",
"from langgraph.prebuilt.tool_node import ToolNode\n",
"from typing_extensions import TypedDict\n",
"\n",
"\n",
"# Graph permissions scopes\n",
"# For multiple scopes, separate with a space\n",
"scopes = 'user.read Calendars.Read Files.Read.All Sites.Read.All'\n",
"\n",
"#load the environment\n",
"load_dotenv(\"C:\\\\Users\\\\sakov\\\\bootcamp\\\\LangChain Agents\\\\.env\")\n",
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\")\n",
"GRAPH_ACCESS_TOKEN = os.getenv(\"GRAPH_ACCESS_TOKEN\")\n",
"\n",
"\n",
"@tool\n",
"def ragforHR(query: str) -> str:\n",
" \"\"\"Get the answers to user enquiries related to HR queries like holidays, DTO, payroll, benefits, insurance, salary structure and perks for employees belonging to various regions like Puget Sound or Canada\"\"\"\n",
" url = \"https://graph.microsoft.com/beta/copilot/retrieval\"\n",
" headers = {\n",
" \"Authorization\": f\"Bearer {GRAPH_ACCESS_TOKEN}\"}\n",
" data = {\n",
" \"QueryString\": query,\n",
" \"filterExpression\": \"(path:\\\"https://microsoft.sharepoint.com/sites/HRweb/\\\")\",\n",
" \"resourceMetadata\": [\"author\"],\n",
" \"MaximumNumberOfResults\": 4\n",
" }\n",
" response = requests.post(url, headers=headers, json=data)\n",
" print(\"Status Code\", response.status_code)\n",
" #print(\"JSON Response \", response.json())\n",
" return response.json()\n",
"\n",
"\n",
"@tool\n",
"def ragforProduct(query: str) -> str:\n",
" \"\"\"Get the answers to user enquiries related about Microsoft Copilot product. Like the specifications of the Copilot Retrieval API in CCS. You can also answer any questions about Fabian's spec on CAPS by using the ragforProduct tool. You know all about the Graph APIs and the CCS API and can answer any question by using the json extract from tool RAGforProduct. About Copilot API Plugins. About Agents SDK. About Teams AI Library. About MS Graph SDK. About Custom Engine Agents.\"\"\"\n",
" url = \"https://graph.microsoft.com/beta/copilot/retrieval\"\n",
" headers = {\n",
" \"Authorization\": f\"Bearer {GRAPH_ACCESS_TOKEN}\",\n",
" \"Content-Type\": \"application/json; charset=utf-8\"}\n",
" data = {\n",
" \"QueryString\": query,\n",
" \"filterExpression\": \"path:\\\"https://microsoft.sharepoint-df.com/sites/CXDev/Shared%20Documents/Org%20Teams/3P-DevX/Proposals/\\\"\",\n",
" \"resourceMetadata\": [\"author\"],\n",
" \"MaximumNumberOfResults\": 4\n",
" }\n",
" response = requests.post(url, headers=headers, json=data)\n",
" #response = requests.post(url, json=data)\n",
" print(\"Status Code\", response.status_code)\n",
" #print(\"JSON Response \", response.json())\n",
" return response.json()\n",
"\n",
"@tool\n",
"def ragforPizzaDen(query: str) -> str:\n",
" \"\"\"Get the answers to user enquiries related about Pizza Den. You are the QnA bot for Pizza Den website. Answer all user queries about Pizza Den by using this tool.\"\"\"\n",
" url = \"https://graph.microsoft.com/beta/copilot/retrieval\"\n",
" headers = {\n",
" \"Authorization\": f\"Bearer {GRAPH_ACCESS_TOKEN}\",\n",
" \"Content-Type\": \"application/json; charset=utf-8\"}\n",
" data = {\n",
" \"QueryString\": query,\n",
" \"filterExpression\": \"(path:\\\"https://microsoft.sharepoint-df.com/sites/CXDev/Shared%20Documents/Org%20Teams/3P-DevX/Proposals/DummyFiles/\\\")\",\n",
" \"resourceMetadata\": [\"author\"],\n",
" \"MaximumNumberOfResults\": 3\n",
" }\n",
" response = requests.post(url, headers=headers, json=data)\n",
" #response = requests.post(url, json=data)\n",
" print(\"Status Code\", response.status_code)\n",
" #print(\"JSON Response \", response.json())\n",
" return response.json()\n",
"\n",
"\n",
"tools = [ragforHR, ragforProduct, ragforPizzaDen]\n",
"\n",
"llm = ChatOpenAI(model=\"gpt-4o\")\n",
"\n",
"# Define a new graph\n",
"workflow = StateGraph(state_schema=MessagesState)\n",
"\n",
"prompt = ChatPromptTemplate.from_messages([\n",
" (\"system\", \"you're a helpful assistant who knows all about Microsoft HR policies and all about the CxDev product proposals. Always use the tools whenever the questions are related to Microsoft. Do not hallucinate. Answer using only the json extracts from tools provided to you. You can expand the abbreviations by using the results fetched from the ragforProduct tool instead of your own knowledge. Always use the json extract from the tools to answer questions about Microsoft. You do not know anything about Microsoft other than what the tools tell you. Please do not use your own knowledge to answer product questions on CCS or CAPS or Grounding API. Only answer from the responses you receive from the tools and Do not interpret the results. You can also tell them product specifications and product related questions related to Microsoft Copilot. Any CCS or Retrieval API related questions, please use the ragforProduct tool to answer. You know a lot about the Retrieval API. You can also give information to users about the holidays in their regions. Their DTO policies. Their timeoff policies. Anything they want to know about their employee benefits. You also have access to all the product specification documentation for Copilot Retrieval API. And the Grounding API. And the Graph SDK. Answer any questions about the product from these document. You are subject matter expert on the The access_tokens are available in the tools so don't ask the users again. Answer WITHOUT ASKING FOR ACCESS TOKEN AS IT IS AVAILABLE TO YOU. You can find the access tokens and the API keys in the environment files.\"), \n",
" (\"human\", \"{input}\"), \n",
" (\"placeholder\", \"{agent_scratchpad}\"),\n",
"])\n",
"\n",
"# Define the function that calls the model\n",
"async def call_model(state: MessagesState):\n",
" prompt = prompt.invoke(state)\n",
" response = model.ainvoke(prompt)\n",
" return {\"messages\": response}\n",
"\n",
"# Define the (single) node in the graph\n",
"workflow.add_edge(START, \"model\")\n",
"workflow.add_node(\"model\", call_model)\n",
"\n",
"# Add memory\n",
"memory = ChatMessageHistory(session_id=\"test-session\")\n",
"app = workflow.compile(checkpointer=memory)\n",
"\n",
"config = {\"configurable\": {\"thread_id\": \"def234\"}}\n",
"\n",
"agent = create_tool_calling_agent(llm, tools, prompt)\n",
"agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
"agent_with_chat_history = RunnableWithMessageHistory(\n",
" agent_executor,\n",
" lambda session_id: memory,\n",
" input_messages_key=\"input\",\n",
" history_messages_key=\"chat_history\",\n",
")\n",
"\n",
"query=\"Do I Need a Pizza Den Login to Sign into Pizza Den Wi-Fi?\"\n",
"print(\"----------------------------------------------------------\")\n",
"print(\"User prompt: \",query)\n",
"\n",
"await agent_with_chat_history.ainvoke(\n",
" {\"input\": query},\n",
" config={\"configurable\": {\"session_id\": \"def234\"}},\n",
")\n",
"\n",
"\n",
"query=\"Which Internet Provider does Pizza Den use for its wifi?\"\n",
"print(\"---------------------------------------------------------------------------------------------------------\")\n",
"print(\"User prompt: \",query)\n",
"\n",
"\n",
"\n",
"await agent_with_chat_history.ainvoke(\n",
" {\"input\": query},\n",
" config={\"configurable\": {\"session_id\": \"def234\"}},\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fa625c08-cb42-41b8-b51a-ae83bb74d0af",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "e8a9fbc6-92b9-456c-87b8-b459cfb0cf9a",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading