mirror of https://github.com/hwchase17/langchain
community[minor]: CogniSwitch Agent Toolkit for LangChain (#17312)
**Description**: CogniSwitch focusses on making GenAI usage more reliable. It abstracts out the complexity & decision making required for tuning processing, storage & retrieval. Using simple APIs documents / URLs can be processed into a Knowledge Graph that can then be used to answer questions. **Dependencies**: No dependencies. Just network calls & API key required **Tag maintainer**: @hwchase17 **Twitter handle**: https://github.com/CogniSwitch **Documentation**: Please check `docs/docs/integrations/toolkits/cogniswitch.ipynb` **Tests**: The usual tool & toolkits tests using `test_imports.py` PR has passed linting and testing before this submission. --------- Co-authored-by: Saicharan Sridhara <145636106+saiCogniswitch@users.noreply.github.com>pull/17750/head
parent
6275d8b1bf
commit
919ebcc596
@ -0,0 +1,326 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "19062701",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Cogniswitch Tools\n",
|
||||
"\n",
|
||||
"**Use CogniSwitch to build production ready applications that can consume, organize and retrieve knowledge flawlessly. Using the framework of your choice, in this case Langchain CogniSwitch helps alleviate the stress of decision making when it comes to, choosing the right storage and retrieval formats. It also eradicates reliability issues and hallucinations when it comes to responses that are generated. Get started by interacting with your knowledge in just two simple steps.**\n",
|
||||
"\n",
|
||||
"visit [https://www.cogniswitch.ai/developer to register](https://www.cogniswitch.ai/developer?utm_source=langchain&utm_medium=langchainbuild&utm_id=dev).\n\n",
|
||||
"**Registration:** \n\n",
|
||||
"- Signup with your email and verify your registration \n\n",
|
||||
"- You will get a mail with a platform token and oauth token for using the services.\n\n\n",
|
||||
"\n",
|
||||
"**step 1: Instantiate the toolkit and get the tools:**\n\n",
|
||||
"- Instantiate the cogniswitch toolkit with the cogniswitch token, openAI API key and OAuth token and get the tools. \n",
|
||||
"\n",
|
||||
"**step 2: Instantiate the agent with the tools and llm:**\n",
|
||||
"- Instantiate the agent with the list of cogniswitch tools and the llm, into the agent executor.\n",
|
||||
"\n",
|
||||
"**step 3: CogniSwitch Store Tool:** \n",
|
||||
"\n",
|
||||
"***CogniSwitch knowledge source file tool***\n",
|
||||
"- Use the agent to upload a file by giving the file path.(formats that are currently supported are .pdf, .docx, .doc, .txt, .html) \n",
|
||||
"- The content from the file will be processed by the cogniswitch and stored in your knowledge store. \n",
|
||||
"\n",
|
||||
"***CogniSwitch knowledge source url tool***\n",
|
||||
"- Use the agent to upload a URL. \n",
|
||||
"- The content from the url will be processed by the cogniswitch and stored in your knowledge store. \n",
|
||||
"\n",
|
||||
"**step 4: CogniSwitch Status Tool:**\n",
|
||||
"- Use the agent to know the status of the document uploaded with a document name.\n",
|
||||
"- You can also check the status of document processing in cogniswitch console. \n",
|
||||
"\n",
|
||||
"**step 5: CogniSwitch Answer Tool:**\n",
|
||||
"- Use the agent to ask your question.\n",
|
||||
"- You will get the answer from your knowledge as the response. \n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1435b193",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Import necessary libraries"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"id": "8d86323b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import warnings\n",
|
||||
"\n",
|
||||
"warnings.filterwarnings(\"ignore\")\n",
|
||||
"\n",
|
||||
"import os\n",
|
||||
"\n",
|
||||
"from langchain.agents.agent_toolkits import create_conversational_retrieval_agent\n",
|
||||
"from langchain.chat_models import ChatOpenAI\n",
|
||||
"from langchain_community.agent_toolkits import CogniswitchToolkit"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "6e6acf0e",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Cogniswitch platform token, OAuth token and OpenAI API key"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"id": "3d2dfc9f",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"cs_token = \"Your CogniSwitch token\"\n",
|
||||
"OAI_token = \"Your OpenAI API token\"\n",
|
||||
"oauth_token = \"Your CogniSwitch authentication token\"\n",
|
||||
"\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = OAI_token"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "320e02fc",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Instantiate the cogniswitch toolkit with the credentials"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"id": "89f58167",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"cogniswitch_toolkit = CogniswitchToolkit(\n",
|
||||
" cs_token=cs_token, OAI_token=OAI_token, apiKey=oauth_token\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "16901682",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Get the list of cogniswitch tools"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"id": "288d07f6",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"tool_lst = cogniswitch_toolkit.get_tools()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "4aae43a3",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Instantiate the llm"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"id": "4d67e5bb",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"llm = ChatOpenAI(\n",
|
||||
" temperature=0,\n",
|
||||
" openai_api_key=OAI_token,\n",
|
||||
" max_tokens=1500,\n",
|
||||
" model_name=\"gpt-3.5-turbo-0613\",\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "04179282",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Create a agent executor"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"id": "2153e758",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agent_executor = create_conversational_retrieval_agent(llm, tool_lst, verbose=False)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "42c9890e",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Invoke the agent to upload a URL"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"id": "794b4fba",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"The URL https://cogniswitch.ai/developer has been uploaded successfully. The status of the document is currently being processed. You will receive an email notification once the processing is complete.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"response = agent_executor.invoke(\"upload this url https://cogniswitch.ai/developer\")\n",
|
||||
"\n",
|
||||
"print(response[\"output\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "544fe8f9",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Invoke the agent to upload a File"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 10,
|
||||
"id": "fd0addfc",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"The file example_file.txt has been uploaded successfully. The status of the document is currently being processed. You will receive an email notification once the processing is complete.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"response = agent_executor.invoke(\"upload this file example_file.txt\")\n",
|
||||
"\n",
|
||||
"print(response[\"output\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "02827e1b",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Invoke the agent to get the status of a document"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 11,
|
||||
"id": "f424e6c5",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"The status of the document example_file.txt is as follows:\n",
|
||||
"\n",
|
||||
"- Created On: 2024-01-22T19:07:42.000+00:00\n",
|
||||
"- Modified On: 2024-01-22T19:07:42.000+00:00\n",
|
||||
"- Document Entry ID: 153\n",
|
||||
"- Status: 0 (Processing)\n",
|
||||
"- Original File Name: example_file.txt\n",
|
||||
"- Saved File Name: 1705950460069example_file29393011.txt\n",
|
||||
"\n",
|
||||
"The document is currently being processed.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"response = agent_executor.invoke(\"Tell me the status of this document example_file.txt\")\n",
|
||||
"\n",
|
||||
"print(response[\"output\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "0ba9aca9",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Invoke the agent with query and get the answer"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 12,
|
||||
"id": "e73e963f",
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"CogniSwitch can help develop GenAI applications in several ways:\n",
|
||||
"\n",
|
||||
"1. Knowledge Extraction: CogniSwitch can extract knowledge from various sources such as documents, websites, and databases. It can analyze and store data from these sources, making it easier to access and utilize the information for GenAI applications.\n",
|
||||
"\n",
|
||||
"2. Natural Language Processing: CogniSwitch has advanced natural language processing capabilities. It can understand and interpret human language, allowing GenAI applications to interact with users in a more conversational and intuitive manner.\n",
|
||||
"\n",
|
||||
"3. Sentiment Analysis: CogniSwitch can analyze the sentiment of text data, such as customer reviews or social media posts. This can be useful in developing GenAI applications that can understand and respond to the emotions and opinions of users.\n",
|
||||
"\n",
|
||||
"4. Knowledge Base Integration: CogniSwitch can integrate with existing knowledge bases or create new ones. This allows GenAI applications to access a vast amount of information and provide accurate and relevant responses to user queries.\n",
|
||||
"\n",
|
||||
"5. Document Analysis: CogniSwitch can analyze documents and extract key information such as entities, relationships, and concepts. This can be valuable in developing GenAI applications that can understand and process large amounts of textual data.\n",
|
||||
"\n",
|
||||
"Overall, CogniSwitch provides a range of AI-powered capabilities that can enhance the development of GenAI applications by enabling knowledge extraction, natural language processing, sentiment analysis, knowledge base integration, and document analysis.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"response = agent_executor.invoke(\"How can cogniswitch help develop GenAI applications?\")\n",
|
||||
"\n",
|
||||
"print(response[\"output\"])"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "langchain_repo",
|
||||
"language": "python",
|
||||
"name": "langchain_repo"
|
||||
},
|
||||
"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.9.17"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
@ -0,0 +1 @@
|
||||
"""CogniSwitch Toolkit"""
|
@ -0,0 +1,40 @@
|
||||
from typing import List
|
||||
|
||||
from langchain_community.agent_toolkits.base import BaseToolkit
|
||||
from langchain_community.tools import BaseTool
|
||||
from langchain_community.tools.cogniswitch.tool import (
|
||||
CogniswitchKnowledgeRequest,
|
||||
CogniswitchKnowledgeSourceFile,
|
||||
CogniswitchKnowledgeSourceURL,
|
||||
CogniswitchKnowledgeStatus,
|
||||
)
|
||||
|
||||
|
||||
class CogniswitchToolkit(BaseToolkit):
|
||||
"""
|
||||
Toolkit for CogniSwitch.
|
||||
|
||||
Use the toolkit to get all the tools present in the cogniswitch and
|
||||
use them to interact with your knowledge
|
||||
"""
|
||||
|
||||
cs_token: str # cogniswitch token
|
||||
OAI_token: str # OpenAI API token
|
||||
apiKey: str # Cogniswitch OAuth token
|
||||
|
||||
def get_tools(self) -> List[BaseTool]:
|
||||
"""Get the tools in the toolkit."""
|
||||
return [
|
||||
CogniswitchKnowledgeStatus(
|
||||
cs_token=self.cs_token, OAI_token=self.OAI_token, apiKey=self.apiKey
|
||||
),
|
||||
CogniswitchKnowledgeRequest(
|
||||
cs_token=self.cs_token, OAI_token=self.OAI_token, apiKey=self.apiKey
|
||||
),
|
||||
CogniswitchKnowledgeSourceFile(
|
||||
cs_token=self.cs_token, OAI_token=self.OAI_token, apiKey=self.apiKey
|
||||
),
|
||||
CogniswitchKnowledgeSourceURL(
|
||||
cs_token=self.cs_token, OAI_token=self.OAI_token, apiKey=self.apiKey
|
||||
),
|
||||
]
|
@ -0,0 +1 @@
|
||||
"Cogniswitch Tools"
|
@ -0,0 +1,399 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
import requests
|
||||
from langchain_core.callbacks import CallbackManagerForToolRun
|
||||
from langchain_core.tools import BaseTool
|
||||
|
||||
|
||||
class CogniswitchKnowledgeRequest(BaseTool):
|
||||
"""
|
||||
A tool for interacting with the Cogniswitch service to answer questions.
|
||||
name: str = "cogniswitch_knowledge_request"
|
||||
description: str = (
|
||||
"A wrapper around cogniswitch service to answer the question
|
||||
from the knowledge base."
|
||||
"Input should be a search query."
|
||||
)
|
||||
"""
|
||||
|
||||
name: str = "cogniswitch_knowledge_request"
|
||||
description: str = """A wrapper around cogniswitch service to
|
||||
answer the question from the knowledge base."""
|
||||
cs_token: str
|
||||
OAI_token: str
|
||||
apiKey: str
|
||||
api_url = "https://api.cogniswitch.ai:8243/cs-api/0.0.1/cs/knowledgeRequest"
|
||||
|
||||
def _run(
|
||||
self,
|
||||
query: str,
|
||||
run_manager: Optional[CallbackManagerForToolRun] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Use the tool to answer a query.
|
||||
|
||||
Args:
|
||||
query (str): Natural language query,
|
||||
that you would like to ask to your knowledge graph.
|
||||
run_manager (Optional[CallbackManagerForChainRun]):
|
||||
Manager for chain run callbacks.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: Output dictionary containing
|
||||
the 'response' from the service.
|
||||
"""
|
||||
response = self.answer_cs(self.cs_token, self.OAI_token, query, self.apiKey)
|
||||
return response
|
||||
|
||||
def answer_cs(self, cs_token: str, OAI_token: str, query: str, apiKey: str) -> dict:
|
||||
"""
|
||||
Send a query to the Cogniswitch service and retrieve the response.
|
||||
|
||||
Args:
|
||||
cs_token (str): Cogniswitch token.
|
||||
OAI_token (str): OpenAI token.
|
||||
apiKey (str): OAuth token.
|
||||
query (str): Query to be answered.
|
||||
|
||||
Returns:
|
||||
dict: Response JSON from the Cogniswitch service.
|
||||
"""
|
||||
if not cs_token:
|
||||
raise ValueError("Missing cs_token")
|
||||
if not OAI_token:
|
||||
raise ValueError("Missing OpenAI token")
|
||||
if not apiKey:
|
||||
raise ValueError("Missing cogniswitch OAuth token")
|
||||
if not query:
|
||||
raise ValueError("Missing input query")
|
||||
|
||||
headers = {
|
||||
"apiKey": apiKey,
|
||||
"platformToken": cs_token,
|
||||
"openAIToken": OAI_token,
|
||||
}
|
||||
|
||||
data = {"query": query}
|
||||
response = requests.post(self.api_url, headers=headers, verify=False, data=data)
|
||||
return response.json()
|
||||
|
||||
|
||||
class CogniswitchKnowledgeStatus(BaseTool):
|
||||
"""
|
||||
A cogniswitch tool for interacting with the Cogniswitch services to know the
|
||||
status of the document or url uploaded.
|
||||
name: str = "cogniswitch_knowledge_status"
|
||||
description: str = (
|
||||
"A wrapper around cogniswitch services to know the status of
|
||||
the document uploaded from a url or a file. "
|
||||
"Input should be a file name or the url link"
|
||||
)
|
||||
"""
|
||||
|
||||
name: str = "cogniswitch_knowledge_status"
|
||||
description: str = """A wrapper around cogniswitch services to know
|
||||
the status of the document uploaded from a url or a file."""
|
||||
cs_token: str
|
||||
OAI_token: str
|
||||
apiKey: str
|
||||
knowledge_status_url = (
|
||||
"https://api.cogniswitch.ai:8243/cs-api/0.0.1/cs/knowledgeSource/status"
|
||||
)
|
||||
|
||||
def _run(
|
||||
self,
|
||||
document_name: str,
|
||||
run_manager: Optional[CallbackManagerForToolRun] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Use the tool to know the status of the document uploaded.
|
||||
|
||||
Args:
|
||||
document_name (str): name of the document or
|
||||
the url uploaded
|
||||
run_manager (Optional[CallbackManagerForChainRun]):
|
||||
Manager for chain run callbacks.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: Output dictionary containing
|
||||
the 'response' from the service.
|
||||
"""
|
||||
response = self.knowledge_status(document_name)
|
||||
return response
|
||||
|
||||
def knowledge_status(self, document_name: str) -> dict:
|
||||
"""
|
||||
Use this function to know the status of the document or the URL uploaded
|
||||
Args:
|
||||
document_name (str): The document name or the url that is uploaded.
|
||||
|
||||
Returns:
|
||||
dict: Response JSON from the Cogniswitch service.
|
||||
"""
|
||||
|
||||
params = {"docName": document_name, "platformToken": self.cs_token}
|
||||
headers = {
|
||||
"apiKey": self.apiKey,
|
||||
"openAIToken": self.OAI_token,
|
||||
"platformToken": self.cs_token,
|
||||
}
|
||||
response = requests.get(
|
||||
self.knowledge_status_url,
|
||||
headers=headers,
|
||||
params=params,
|
||||
verify=False,
|
||||
)
|
||||
if response.status_code == 200:
|
||||
source_info = response.json()
|
||||
source_data = dict(source_info[-1])
|
||||
status = source_data.get("status")
|
||||
if status == 0:
|
||||
source_data["status"] = "SUCCESS"
|
||||
elif status == 1:
|
||||
source_data["status"] = "PROCESSING"
|
||||
elif status == 2:
|
||||
source_data["status"] = "UPLOADED"
|
||||
elif status == 3:
|
||||
source_data["status"] = "FAILURE"
|
||||
elif status == 4:
|
||||
source_data["status"] = "UPLOAD_FAILURE"
|
||||
elif status == 5:
|
||||
source_data["status"] = "REJECTED"
|
||||
|
||||
if "filePath" in source_data.keys():
|
||||
source_data.pop("filePath")
|
||||
if "savedFileName" in source_data.keys():
|
||||
source_data.pop("savedFileName")
|
||||
if "integrationConfigId" in source_data.keys():
|
||||
source_data.pop("integrationConfigId")
|
||||
if "metaData" in source_data.keys():
|
||||
source_data.pop("metaData")
|
||||
if "docEntryId" in source_data.keys():
|
||||
source_data.pop("docEntryId")
|
||||
return source_data
|
||||
else:
|
||||
# error_message = response.json()["message"]
|
||||
return {
|
||||
"message": response.status_code,
|
||||
}
|
||||
|
||||
|
||||
class CogniswitchKnowledgeSourceFile(BaseTool):
|
||||
"""
|
||||
A cogniswitch tool for interacting with the Cogniswitch services to store data.
|
||||
name: str = "cogniswitch_knowledge_source_file"
|
||||
description: str = (
|
||||
"This calls the CogniSwitch services to analyze & store data from a file.
|
||||
If the input looks like a file path, assign that string value to file key.
|
||||
Assign document name & description only if provided in input."
|
||||
)
|
||||
"""
|
||||
|
||||
name: str = "cogniswitch_knowledge_source_file"
|
||||
description: str = """
|
||||
This calls the CogniSwitch services to analyze & store data from a file.
|
||||
If the input looks like a file path, assign that string value to file key.
|
||||
Assign document name & description only if provided in input.
|
||||
"""
|
||||
cs_token: str
|
||||
OAI_token: str
|
||||
apiKey: str
|
||||
knowledgesource_file = (
|
||||
"https://api.cogniswitch.ai:8243/cs-api/0.0.1/cs/knowledgeSource/file"
|
||||
)
|
||||
|
||||
def _run(
|
||||
self,
|
||||
file: Optional[str] = None,
|
||||
document_name: Optional[str] = None,
|
||||
document_description: Optional[str] = None,
|
||||
run_manager: Optional[CallbackManagerForToolRun] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute the tool to store the data given from a file.
|
||||
This calls the CogniSwitch services to analyze & store data from a file.
|
||||
If the input looks like a file path, assign that string value to file key.
|
||||
Assign document name & description only if provided in input.
|
||||
|
||||
Args:
|
||||
file Optional[str]: The file path of your knowledge
|
||||
document_name Optional[str]: Name of your knowledge document
|
||||
document_description Optional[str]: Description of your knowledge document
|
||||
run_manager (Optional[CallbackManagerForChainRun]):
|
||||
Manager for chain run callbacks.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: Output dictionary containing
|
||||
the 'response' from the service.
|
||||
"""
|
||||
if not file:
|
||||
return {
|
||||
"message": "No input provided",
|
||||
}
|
||||
else:
|
||||
response = self.store_data(
|
||||
file=file,
|
||||
document_name=document_name,
|
||||
document_description=document_description,
|
||||
)
|
||||
return response
|
||||
|
||||
def store_data(
|
||||
self,
|
||||
file: Optional[str],
|
||||
document_name: Optional[str],
|
||||
document_description: Optional[str],
|
||||
) -> dict:
|
||||
"""
|
||||
Store data using the Cogniswitch service.
|
||||
This calls the CogniSwitch services to analyze & store data from a file.
|
||||
If the input looks like a file path, assign that string value to file key.
|
||||
Assign document name & description only if provided in input.
|
||||
|
||||
Args:
|
||||
file (Optional[str]): file path of your file.
|
||||
the current files supported by the files are
|
||||
.txt, .pdf, .docx, .doc, .html
|
||||
document_name (Optional[str]): Name of the document you are uploading.
|
||||
document_description (Optional[str]): Description of the document.
|
||||
|
||||
Returns:
|
||||
dict: Response JSON from the Cogniswitch service.
|
||||
"""
|
||||
headers = {
|
||||
"apiKey": self.apiKey,
|
||||
"openAIToken": self.OAI_token,
|
||||
"platformToken": self.cs_token,
|
||||
}
|
||||
data: Dict[str, Any]
|
||||
if not document_name:
|
||||
document_name = ""
|
||||
if not document_description:
|
||||
document_description = ""
|
||||
|
||||
if file is not None:
|
||||
files = {"file": open(file, "rb")}
|
||||
|
||||
data = {
|
||||
"documentName": document_name,
|
||||
"documentDescription": document_description,
|
||||
}
|
||||
response = requests.post(
|
||||
self.knowledgesource_file,
|
||||
headers=headers,
|
||||
verify=False,
|
||||
data=data,
|
||||
files=files,
|
||||
)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
return {"message": "Bad Request"}
|
||||
|
||||
|
||||
class CogniswitchKnowledgeSourceURL(BaseTool):
|
||||
"""
|
||||
A cogniswitch tool for interacting with the Cogniswitch services to store data.
|
||||
name: str = "cogniswitch_knowledge_source_url"
|
||||
description: str = (
|
||||
"This calls the CogniSwitch services to analyze & store data from a url.
|
||||
the URL is provided in input, assign that value to the url key.
|
||||
Assign document name & description only if provided in input"
|
||||
)
|
||||
"""
|
||||
|
||||
name: str = "cogniswitch_knowledge_source_url"
|
||||
description: str = """
|
||||
This calls the CogniSwitch services to analyze & store data from a url.
|
||||
the URL is provided in input, assign that value to the url key.
|
||||
Assign document name & description only if provided in input"""
|
||||
cs_token: str
|
||||
OAI_token: str
|
||||
apiKey: str
|
||||
knowledgesource_url = (
|
||||
"https://api.cogniswitch.ai:8243/cs-api/0.0.1/cs/knowledgeSource/url"
|
||||
)
|
||||
|
||||
def _run(
|
||||
self,
|
||||
url: Optional[str] = None,
|
||||
document_name: Optional[str] = None,
|
||||
document_description: Optional[str] = None,
|
||||
run_manager: Optional[CallbackManagerForToolRun] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute the tool to store the data given from a url.
|
||||
This calls the CogniSwitch services to analyze & store data from a url.
|
||||
the URL is provided in input, assign that value to the url key.
|
||||
Assign document name & description only if provided in input.
|
||||
|
||||
Args:
|
||||
url Optional[str]: The website/url link of your knowledge
|
||||
document_name Optional[str]: Name of your knowledge document
|
||||
document_description Optional[str]: Description of your knowledge document
|
||||
run_manager (Optional[CallbackManagerForChainRun]):
|
||||
Manager for chain run callbacks.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: Output dictionary containing
|
||||
the 'response' from the service.
|
||||
"""
|
||||
if not url:
|
||||
return {
|
||||
"message": "No input provided",
|
||||
}
|
||||
response = self.store_data(
|
||||
url=url,
|
||||
document_name=document_name,
|
||||
document_description=document_description,
|
||||
)
|
||||
return response
|
||||
|
||||
def store_data(
|
||||
self,
|
||||
url: Optional[str],
|
||||
document_name: Optional[str],
|
||||
document_description: Optional[str],
|
||||
) -> dict:
|
||||
"""
|
||||
Store data using the Cogniswitch service.
|
||||
This calls the CogniSwitch services to analyze & store data from a url.
|
||||
the URL is provided in input, assign that value to the url key.
|
||||
Assign document name & description only if provided in input.
|
||||
|
||||
Args:
|
||||
url (Optional[str]): URL link.
|
||||
document_name (Optional[str]): Name of the document you are uploading.
|
||||
document_description (Optional[str]): Description of the document.
|
||||
|
||||
Returns:
|
||||
dict: Response JSON from the Cogniswitch service.
|
||||
"""
|
||||
headers = {
|
||||
"apiKey": self.apiKey,
|
||||
"openAIToken": self.OAI_token,
|
||||
"platformToken": self.cs_token,
|
||||
}
|
||||
data: Dict[str, Any]
|
||||
if not document_name:
|
||||
document_name = ""
|
||||
if not document_description:
|
||||
document_description = ""
|
||||
if not url:
|
||||
return {
|
||||
"message": "No input provided",
|
||||
}
|
||||
else:
|
||||
data = {"url": url}
|
||||
response = requests.post(
|
||||
self.knowledgesource_url,
|
||||
headers=headers,
|
||||
verify=False,
|
||||
data=data,
|
||||
)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
return {"message": "Bad Request"}
|
Loading…
Reference in New Issue