### Example Usage: Initialize SearchLegalEngine in Python Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/guides/4.Legal_Assistant.ipynb Demonstrates the initialization of the SearchLegalEngine class. This setup configures the engine with specific parameters like top_k, temporary data path, database type, and embedding model, preparing it for document processing and searching. ```python search_legal_engine = SearchLegalEngine( top_k=5, temp_data_path=Path("data/test.parquet"), db_type="milvus", embedding_model="BAAI/bge-small-en-v1.5" ) search_legal_engine._initialize_document_processor() ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/datascienceworld-kan/vinagent/blob/main/vinagent/mcp/examples/math/README.md Installs the uv package manager and environment manager using a curl script. This is the first step in setting up the project environment. ```shell curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Start Math MCP Server Source: https://github.com/datascienceworld-kan/vinagent/blob/main/vinagent/mcp/examples/math/README.md Command to start the Math MCP server in development mode. This command assumes the server file is named 'main.py'. ```shell mcp dev main.py ``` -------------------------------- ### Initialize and Configure Math Project with uv Source: https://github.com/datascienceworld-kan/vinagent/blob/main/vinagent/mcp/examples/math/README.md Initializes a new project directory, creates and activates a virtual environment using uv, and installs the 'mcp[cli]' and 'httpx' dependencies. Finally, it creates the main server file. ```shell # Create a new directory for our project uv init add cd add # Create virtual environment and activate it uv venv source .venv/bin/activate # Install dependencies uv add "mcp[cli]" httpx # Create our server file touch math_server.py ``` -------------------------------- ### Example Usage: Query Fusion Search in Python Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/guides/4.Legal_Assistant.ipynb Executes a query fusion search using the initialized SearchLegalEngine. This example searches for documents related to 'claimed exemption from Sales Tax' and retrieves the top 5 results, with a semantic score weight of 0.7. ```python query = "claimed exemption from Sales Tax" search_legal_engine.query_fusion_score(query, top_k=5, w_semantic=0.7) ``` -------------------------------- ### Start and Connect to a Math MCP Server Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/get_started/add_tool.md This snippet outlines the process of starting a local MCP (Model Context Protocol) server using the provided example and then connecting to it from a Vinagent agent. It involves running the server locally and configuring the agent to recognize and utilize the tools exposed by the MCP server. ```bash cd vinagent/mcp/examples/math mcp dev main.py ``` -------------------------------- ### Start Math MCP Server Source: https://github.com/datascienceworld-kan/vinagent/blob/main/README.md This snippet demonstrates how to start the math MCP Server from the command line. It involves navigating to the server's directory and running the development server. ```bash cd vinagent/mcp/examples/math mcp dev main.py ``` -------------------------------- ### Install Vinagent Library Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/get_started/basic_agent.md Instructions for installing the Vinagent library. It covers both the development version from GitHub using poetry and the stable version from PyPI using pip. ```bash git clone git@github.com:datascienceworld-kan/vinagent.git cd vinagent pip install -r requirements.txt poetry install ``` ```bash pip install vinagent ``` -------------------------------- ### Install vinagent and Dependencies Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/guides/legal_assistant.md Installs the vinagent library and the datasets library using pip. This is a prerequisite for using the vinagent legal assistant. ```python %pip install vinagent==0.0.4.post7 datasets==4.0.0 ``` -------------------------------- ### Install MkDocs and Check Version Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/README.md Installs the MkDocs library, a static site generator, and then checks its installed version. This is a prerequisite for building and serving the project's documentation website. ```bash pip install mkdocs==1.6.1 # Check version mkdocs --version ``` -------------------------------- ### Install Pre-commit Hooks (Bash) Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/contributing/contributing.md This command installs the pre-commit framework, which ensures code formatting consistency before each commit. It automates code style checks and fixes. ```bash pre-commit install ``` -------------------------------- ### Install Development Dependencies (Bash) Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/contributing/contributing.md This command installs the necessary development and testing dependencies for the Vinagent project using Poetry. Ensure you have Poetry installed and configured. ```bash poetry install --with dev,test ``` -------------------------------- ### Install Vinagent from GitHub Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/get_started/basic_agent.ipynb Installs the development version of the Vinagent library from its GitHub repository. This method is suitable for obtaining the latest features and is done using poetry. ```shell git clone git@github.com:datascienceworld-kan/vinagent.git cd vinagent pip install -r requirements.txt poetry install ``` -------------------------------- ### Install Vinagent and Initialize LLM (Python) Source: https://github.com/datascienceworld-kan/vinagent/blob/main/cookbook/multi_agent_in_finance/04_institutional_portfolio_management.ipynb This snippet demonstrates how to install the vinagent package using pip and then initializes a ChatOpenAI LLM. It requires the 'vinagent' package, 'langchain-openai', and 'python-dotenv'. The LLM is configured to use the 'gpt-4o-mini' model and loads environment variables from a '.env' file for authentication. ```python %pip install vinagent==0.0.6.post3 from langchain_openai import ChatOpenAI from dotenv import load_dotenv, find_dotenv import os load_dotenv(find_dotenv('.env')) llm = ChatOpenAI(model="gpt-4o-mini") print("LLM initialized.") ``` -------------------------------- ### Install vinagent and Dependencies Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/get_started/bash_agent_guide.md Installs the necessary vinagent package along with other required libraries for Langchain, OpenAI integration, and sandbox environments. This setup is crucial for enabling the Bash Agent's functionalities. ```python %pip install vinagent==0.0.6.post6 %pip install langchain-core langchain-openai langchain-together langgraph python-dotenv PyYAML pydantic mlflow nest_asyncio %pip install e2b-code-interpreter ``` -------------------------------- ### Clone Vinagent Repository (Bash) Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/contributing/contributing.md This command clones the Vinagent repository to your local machine, allowing you to start working on it. Ensure you have Git installed and replace '' with your GitHub username. ```bash git clone https://github.com//vinagent.git ``` -------------------------------- ### Create and Write to a File in Python Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/get_started/ai_guardrail.md This snippet demonstrates how to create a file named 'example.txt' and write 'Hello World!' into it using a shell command within a Python environment. It's a basic example of file manipulation. ```python !echo Hello World! >> example.txt ``` -------------------------------- ### Initialize Vinagent Agent with LLM and Skills Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/get_started/basic_agent.md Demonstrates how to initialize a Vinagent Agent. It includes setting up the language model using `ChatTogether` and defining the agent's description and skills. ```python from langchain_together import ChatTogether from vinagent.agent.agent import Agent from dotenv import load_dotenv load_dotenv() llm = ChatTogether( model="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free" ) # Step 1: Create Agent with tools agent = Agent( description="You are a Financial Analyst", llm = llm, skills = [ "Deeply analyzing financial markets", "Searching information about stock price", "Visualization about stock price"] ) ``` -------------------------------- ### Configure MkDocs Navigation Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/README.md Defines the website's navigation structure in the mkdocs.yml file. It includes sections like 'Get started', 'Guidelines', 'Reference', and 'Contributing' with their respective markdown files. ```yaml nav: - Get started: - index.md - Quick Start: - Start with basic Agent: get_started/basic_agent.md - Build a customization: - 1. Add tools: get_started/add_tool.md - 2. Add memory: get_started/add_memory.md - 3. Async Invoking: get_started/async_invoke.md - 4. Streaming: get_started/streaming.md - 5. Prebuilt Agent: get_started/react_agent.md - 6. Security: get_started/authen_layer.md - 7. Observability: get_started/observability.md - Run local ReactJS App: get_started/local_run.md - Agent Development: - Workflow & Agent: get_started/workflow_and_agent.md - Agent RAG: get_started/agent_rag.md - Multi-Agent Development: - Start with basic Multi-Agent: get_started/multi_agent.md - Guidelines: - Financial Usercase: - Visualize and Analyze Stock: guides/analyze_stock_trending.md - Find Trending New: guides/trending_news.md - Banking Agent: - Banking SQL: guides/banking_agent.md - Research Usercase: - Research Agent: guides/paper_research.md - Legal Field: - Legal Agent: guides/legal_assistant.md - Ecommerce Usercase: - Customer Care Multi-Agent: guides/customer_care.md - RAG: - Agent RAG: guides/agent_rag.md - Reference: - Agent: reference/agent.md - Tool: reference/tool.md - Memory: reference/memory.md - Graph: reference/graph.md - MCP: reference/mcp.md - Tracing: reference/tracing.md - Authenticate: reference/authenticate.md - Contributing: - How to Contribute: contributing/contributing.md ``` -------------------------------- ### Initialize Vector Database Factory Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/guides/4.Legal_Assistant.ipynb Configures and initializes the VectorDatabaseFactory to create a vector database of a specified type ('milvus' in this example). It uses the previously initialized embedding model and document processor. ```python # 3. Initialize vector database factory db_type = "milvus" # Supported types: ['chroma', 'faiss', 'milvus', 'pgvector', 'pinecone', 'qdrant', 'weaviate'] vectordb_factory = VectorDatabaseFactory( db_type=db_type, embedding_model=embedding_model, doc_processor=doc_processor ) ``` -------------------------------- ### Initialize SQLDatabaseToolkit and Get Tools Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/guides/banking_agent.ipynb Initializes the `SQLDatabaseToolkit` with the database connection and LLM, then retrieves a list of available SQL-related tools. The output shows the name and description of each tool. ```python from vinagent.utilities import SQLDatabaseToolkit toolkit = SQLDatabaseToolkit(db=db, llm=llm) tools = toolkit.get_tools() for tool in tools: print(f"{tool.name}: {tool.description}\n") ``` -------------------------------- ### Copy File with Vinagent Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/get_started/bash_agent_guide.md This example illustrates how to instruct the Vinagent to create a copy of an existing file. It requires specifying both the source and destination paths for the file operation. The agent confirms the successful copy. ```python agent.invoke("Make a copy of 'bash_agent_demo/agent_note.txt' called 'bash_agent_demo/agent_note_backup.txt'.") ``` -------------------------------- ### Display First Five Documents Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/guides/4.Legal_Assistant.ipynb Prints the first five Document objects created in the previous step. This is useful for verifying the data transformation. ```python docs[:5] ``` -------------------------------- ### Define Get Current Time Tool Source: https://github.com/datascienceworld-kan/vinagent/blob/main/cookbook/multi_agent_in_finance/02_active_trading_advisory.ipynb Defines a tool to retrieve the current date and time. This function is decorated with @primary_function to make it compatible with the Vinagent tool registry and returns the time in a specific string format. ```python from datetime import datetime import requests from vinagent.register import primary_function @primary_function def get_current_time() -> str: """ Get the current date and time. Use this to know 'today's' date. Returns: str: Current date and time in YYYY-MM-DD HH:MM:SS format. """ return datetime.now().strftime("%Y-%m-%d %H:%M:%S") print("Custom time tool defined.") ``` -------------------------------- ### Start Neo4j Service with Docker Compose Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/get_started/add_memory.ipynb Defines the docker-compose.yml file to configure and run a Neo4j Docker service. It specifies the Neo4j image, container name, port mappings, and authentication credentials. This setup is essential for running the Neo4j database locally. ```yaml version: '3.8' services: neo4j: image: neo4j:latest container_name: neo4j ports: - "7474:7474" - "7687:7687" environment: - NEO4J_AUTH=neo4j/abc@12345 ``` -------------------------------- ### Serve MkDocs Website Locally Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/README.md Starts a local development server to preview the MkDocs website. It watches for changes in the 'docs' folder and 'mkdocs.yml' file, automatically rebuilding and reloading the site. ```bash mkdocs --serve ``` -------------------------------- ### Initialize Vector Database Components Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/guides/4.Legal_Assistant.ipynb Sets up the necessary components for creating a vector database. This includes initializing an embedding model, a text splitter for chunking documents, and a document processor. ```python from langchain_huggingface import HuggingFaceEmbeddings from aucodb.vectordb.factory import VectorDatabaseFactory from aucodb.vectordb.processor import DocumentProcessor from langchain.text_splitter import RecursiveCharacterTextSplitter # 1. Initialize embedding model embedding_model = HuggingFaceEmbeddings(model_name="BAAI/bge-small-en-v1.5") # 2. Initialize document processor text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200 ) doc_processor = DocumentProcessor(splitter=text_splitter) ``` -------------------------------- ### Execution Confirmation - Log Output Source: https://github.com/datascienceworld-kan/vinagent/blob/main/cookbook/multi_agent_in_finance/02_active_trading_advisory.ipynb This log output confirms that agents have been instantiated with standardized tool registration and that the 'Phase 2 Crew Assembled with Direct Parallel Flow' message has been printed, indicating successful crew setup. ```log Agents instantiated with standardized tool registration. Phase 2 Crew Assembled with Direct Parallel Flow. ``` -------------------------------- ### Create File Tool Example Source: https://github.com/datascienceworld-kan/vinagent/blob/main/cookbook/bash_agent_guide.ipynb This Python snippet demonstrates the direct programmatic usage of the `create_file` tool. It shows how to call the function with a filename and content, and prints the result of the operation. ```python result = create_file("examples/test_file.txt", "Hello from vinagent tools!") print(result) ``` -------------------------------- ### Python FlowStateGraph Assembly for Parallel Agents Source: https://github.com/datascienceworld-kan/vinagent/blob/main/cookbook/multi_agent_in_finance/02_active_trading_advisory.ipynb Demonstrates assembling instantiated agents (MarketDataProvider, BinanceTracker, RecommenderAgent) into a directed graph using Vinagent's FlowStateGraph. It highlights the use of START and END operators and the registration of global tools to all agents to ensure safe parallelism and prevent errors. ```python from vnstock_tools import fetch_stock_data_vn from vinagent.multi_agent import CrewAgent from vinagent.graph.operator import FlowStateGraph, START, END from langgraph.checkpoint.memory import MemorySaver instr = "CRITICAL: Format tool arguments as JSON object. NEVER use plain strings." market_agent = MarketDataProvider( name="market_agent", llm=llm, tools=[], instruction=instr ) crypto_agent = BinanceTracker( name="crypto_agent", llm=llm, tools=['vinagent.tools.websearch_tools'], instruction=instr ) # 1. FIX: Give the recommender a specific instruction so it stops trying to act like a data agent recommender = RecommenderAgent( name="recommender", llm=llm, tools=[], instruction="You are a Portfolio Manager. Synthesize the provided market insights into a final recommendation." \ " DO NOT fetch new data or use tools." ) global_tools = [ get_current_time, fetch_btc_market_data, primary_function(fetch_stock_data_vn) ] # 2. FIX: Register tools to ALL agents as a safety net to prevent NoneType crashes for agent in [market_agent, crypto_agent, recommender]: for tool in global_tools: agent.tools_manager.register_function_tool(tool) print("Agents instantiated with standardized tool registration.") # Example of graph construction (assuming llm and other necessary components are defined elsewhere) # graph = FlowStateGraph( # START >> market_agent >> END, # START >> crypto_agent >> END, # market_agent >> recommender, # crypto_agent >> recommender # ) # To run the graph: # compiled_graph = graph.compile(checkpointer=MemorySaver()) # result = compiled_graph.invoke(initial_state) ``` -------------------------------- ### Create and Append to a File using Shell Command Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/get_started/ai_guardrail.ipynb This snippet demonstrates how to create a file named 'example.txt' and append 'Hello World!' to it using a shell command within a Python environment. It's a basic example of file manipulation. ```python from vinagent.guardrail import OSPermissionGuardrail, GuardrailDecision # Assuming 'llm' is an initialized language model object # For demonstration, we'll mock it or assume it's available in the execution context. # If running this code, ensure 'llm' is properly defined. DecisionModel = GuardrailDecision.add_guardrails( [ OSPermissionGuardrail() ] ) list_input = [ "Let's read the example.txt", "Let's read the example_1.txt" ] for user_input in list_input: print("-------------------\n") print(user_input) # In a real scenario, 'llm' would be an actual language model instance. # decision = DecisionModel.validate(llm, user_input) # print(decision) # Mocking the output for demonstration purposes as 'llm' is not defined here. if "example.txt" in user_input: print("allowed=True action='allow' rewrite_prompt=None reason='OS permission granted for read action.' os_permission=OSPermissionGuardrail(name='example.txt', reason=\"Permission 'read' granted.\", file_name='example.txt', action='read')") else: print("allowed=False action='block' rewrite_prompt=None reason='Violate because OS permission is denied or path does not exist.' os_permission=OSPermissionGuardrail(name='example_1.txt', reason='Path does not exist.', file_name='example_1.txt', action='read')") ``` -------------------------------- ### Agent Tool Execution Logs for File Management Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/get_started/bash_agent_guide.ipynb These are example log outputs from the Vinagent system showing the agent's execution of tool calls for directory and file management. It details the iterations, tool names, arguments provided, and the results of each operation, such as creating a folder or file, or encountering an error. ```log INFO:vinagent.agent.agent:No authentication card provided, skipping authentication INFO:vinagent.agent.agent:I'am chatting with unknown_user INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK" INFO:vinagent.agent.agent:Tool calling iteration 1/10 INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK" INFO:vinagent.agent.agent:Executing tool call: {'tool_name': 'list_directory', 'arguments': {'directory_path': 'bash_agent_demo'}, 'return': 'typing.Union[typing.List[str], str]', 'module_path': '__runtime__', 'tool_type': 'function', 'tool_call_id': 'tool_b12f82a4-d24e-4002-85a7-338d3d9793b', 'is_runtime': True} INFO:vinagent.register.tool:Completed executing function tool list_directory({'directory_path': 'bash_agent_demo'}) INFO:root:Tool message: content="Completed executing function tool list_directory({'directory_path': 'bash_agent_demo'})" tool_call_id='tool_b12f82a4-d24e-4002-85a7-338d3d9793b' artifact='Error: Directory not found at bash_agent_demo' INFO:vinagent.agent.agent:Tool calling iteration 2/10 INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK" INFO:vinagent.agent.agent:Executing tool call: {'tool_name': 'create_folder', 'arguments': {'folder_path': 'bash_agent_demo'}, 'return': "", 'module_path': '__runtime__', 'tool_type': 'function', 'tool_call_id': 'tool_09d9c717-59b9-41a7-a8da-7ac56e810fb', 'is_runtime': True} INFO:vinagent.register.tool:Completed executing function tool create_folder({'folder_path': 'bash_agent_demo'}) INFO:root:Tool message: content="Completed executing function tool create_folder({'folder_path': 'bash_agent_demo'})" tool_call_id='tool_09d9c717-59b9-41a7-a8da-7ac56e810fb' artifact='Successfully created folder: bash_agent_demo' INFO:vinagent.agent.agent:Tool calling iteration 3/10 INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK" INFO:vinagent.agent.agent:Executing tool call: {'tool_name': 'create_file', 'arguments': {'file_path': 'bash_agent_demo/hello_world.txt', 'content': 'Hello, world! Welcome to the bash_agent_demo.'}, 'return': "", 'module_path': '__runtime__', 'tool_type': 'function', 'tool_call_id': 'tool_b46b5190-8574-476d-9674-4d8417e9b43', 'is_runtime': True} INFO:vinagent.register.tool:Completed executing function tool create_file({'file_path': 'bash_agent_demo/hello_world.txt', 'content': 'Hello, world! Welcome to the bash_agent_demo.'}) INFO:root:Tool message: content="Completed executing function tool create_file({'file_path': 'bash_agent_demo/hello_world.txt', 'content': 'Hello, world! Welcome to the bash_agent_demo.'})" tool_call_id='tool_b46b5190-8574-476d-9674-4d8417e9b43' artifact='Successfully created file: bash_agent_demo/hello_world.txt' INFO:vinagent.agent.agent:Tool calling iteration 4/10 INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK" INFO:vinagent.agent.agent:No more tool calls needed. Completed in 4 iterations. INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK" ``` -------------------------------- ### Initialize SearchLegalEngine with Vector Database Configuration Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/guides/4.Legal_Assistant.ipynb Initializes the SearchLegalEngine with parameters for top-k results, temporary data path, vector database type, and embedding model. It sets up the document processor and text splitter. ```python from pathlib import Path from typing import Literal from langchain_community.embeddings import HuggingFaceEmbeddings from langchain_text_splitters import RecursiveCharacterTextSplitter from aucodb.vectordb.processor import DocumentProcessor class SearchLegalEngine: def __init__(self, top_k: int=5, temp_data_path: Path = Path("data/test.parquet"), db_type: Literal['chroma', 'faiss', 'milvus', 'pgvector', 'pinecone', 'qdrant', 'weaviate'] = "milvus", embedding_model: str="BAAI/bge-small-en-v1.5" ): self.top_k = top_k self.embedding_model = HuggingFaceEmbeddings(model_name=embedding_model) self.temp_data_path = temp_data_path self.db_type = db_type self.text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200 ) self.doc_processor = DocumentProcessor(splitter=self.text_splitter) ``` -------------------------------- ### Install vinagent Package (Python) Source: https://github.com/datascienceworld-kan/vinagent/blob/main/cookbook/multi_agent_in_finance/02_active_trading_advisory.ipynb This command installs the vinagent package with a specific version (0.0.6.post6) using pip. It's a common way to manage Python project dependencies. The output shows that the package and its dependencies were already satisfied, indicating they were already installed in the environment. ```python %pip install vinagent==0.0.6.post6 ``` -------------------------------- ### Initialize LLM and Vinagent Agent Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/get_started/streaming.md Initializes the Large Language Model (LLM) using ChatTogether and then sets up the Vinagent Agent. The agent is configured with a description, LLM, specific skills, and web search tools. ```python from vinagent.agent.agent import Agent from langchain_together import ChatTogether from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv('.env')) # Step 1: Initialize LLM llm = ChatTogether( model="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free" ) # Step 2: Initialize Agent agent = Agent( description="You are a Weather Analyst", llm = llm, skills = [ "Update weather at anywhere", "Forecast weather in the futher", "Recommend picnic based on weather" ], tools=['vinagent.tools.websearch_tools'], tools_path = 'templates/tools.json', # Place to save tools. Default is 'templates/tools.json' is_reset_tools = True # If True, it will reset tools every time reinitializing an agent. Default is False ) ``` -------------------------------- ### SearchLegalEngine Class Initialization Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/guides/4.Legal_Assistant.ipynb Initializes the SearchLegalEngine class with parameters for top_k, data path, database type, and embedding model. It sets up text splitting and document processing. ```python import pandas as pd from datasets import load_dataset from pathlib import Path from langchain_core.documents import Document from langchain.text_splitter import RecursiveCharacterTextSplitter from typing import Literal from typing import Any, Dict, List class SearchLegalEngine: def __init__(self, top_k: int=5, temp_data_path: Path = Path("data/test.parquet"), db_type: Literal['chroma', 'faiss', 'milvus', 'pgvector', 'pinecone', 'qdrant', 'weaviate'] = "milvus", embedding_model: str="BAAI/bge-small-en-v1.5" ): self.top_k = top_k self.embedding_model = HuggingFaceEmbeddings(model_name=embedding_model) self.temp_data_path = temp_data_path self.db_type = db_type self.text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200 ) self.doc_processor = DocumentProcessor(splitter=self.text_splitter) ``` -------------------------------- ### Install Vinagent Package Source: https://github.com/datascienceworld-kan/vinagent/blob/main/cookbook/custom_deepsearch.ipynb This command installs version 0.0.6.post3 of the vinagent package using pip. It ensures that all necessary dependencies for the vinagent library are downloaded and installed in the current Python environment. ```python %pip install vinagent==0.0.6.post3 ``` -------------------------------- ### Install Vinagent and Dependencies (Python) Source: https://github.com/datascienceworld-kan/vinagent/blob/main/cookbook/financial_usercases/2.Trending_New.ipynb Installs the vinagent library along with necessary dependencies like tavily-python, googlenewsdecoder, and langchain-together. Ensure you have pip installed. ```python %pip install vinagent %pip install tavily-python=0.3.1 googlenewsdecoder=0.1.7 langchain-together=0.3.0 ``` -------------------------------- ### Initialize Vinagent Agent with Tools and LLM Source: https://github.com/datascienceworld-kan/vinagent/blob/main/README.md Demonstrates how to initialize a vinagent Agent, configuring it with a description, an LLM (either TogetherAI or OpenAI), specific skills, and a list of tools. It also shows options for tool path and resetting tools. ```python from langchain_together import ChatTogether from langchain_openai import ChatOpenAI from vinagent.agent.agent import Agent from dotenv import load_dotenv load_dotenv() # You can use togetherai model llm = ChatTogether( model="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free" ) # Or you can you OpenAI model llm = ChatOpenAI( model="gpt-4o-mini", temperature=0.7 ) # Step 1: Create Agent with tools agent = Agent( description="You are a Financial Analyst", llm = llm, skills = [ "Deeply analyzing financial markets", "Searching information about stock price", "Visualization about stock price"], tools = ['vinagent.tools.websearch_tools', 'vinagent.tools.yfinance_tools'], tools_path = 'templates/tools.json', # Place to save tools. Default is 'templates/tools.json' is_reset_tools = True # If True, it will reset tools every time reinitializing an agent. Default is False ) ``` -------------------------------- ### Install Vinagent Python Package Source: https://context7.com/datascienceworld-kan/vinagent/llms.txt Installs the Vinagent library using pip. Alternatively, it shows how to clone the repository, navigate to the directory, and install dependencies using requirements.txt and poetry. ```bash pip install vinagent ``` ```bash git clone https://github.com/datascienceworld-kan/vinagent.git cd vinagent pip install -r requirements.txt poetry install ``` -------------------------------- ### Install Vinagent Library Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/get_started/add_tool.md Installs the vinagent library using pip. This is a prerequisite for using Vinagent functionalities. ```python %pip install vinagent ``` -------------------------------- ### Create and Invoke a Basic Agent with Tools (Python) Source: https://github.com/datascienceworld-kan/vinagent/blob/main/README.md This snippet demonstrates how to initialize an agent with specific tools and memory settings, and then invoke it with a message. It highlights the use of `Agent`, `llm`, `description`, `skills`, `memory_path`, and `is_reset_memory` parameters. ```python agent = Agent( llm = llm, description="You are my close friend", skills=[ "You can remember all memory related to us", "You can remind the memory to answer questions", "You can remember the history of our relationship" ], memory_path='templates/memory.json', is_reset_memory=True # Will reset memory each time re-initialize agent. Default is False ) # Step 2: invoke the agent message = agent.invoke("Hello how are you?") message.content ``` -------------------------------- ### Install Vinagent Library Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/get_started/ai_guardrail.md Installs the vinagent library version 0.0.6.post4 using pip. This is a prerequisite for using the Vinagent functionalities. ```python %pip install vinagent==0.0.6.post4 ``` -------------------------------- ### SearchLegalEngine: Create Legal Cases Data Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/tutorials/guides/4.Legal_Assistant.ipynb Creates a dataset of legal case documents by downloading the data and processing it into Langchain Document objects. Each document includes page content, judgment case ID, dataset name, and summary. ```python def _create_legal_cases_data(self): self._download_legal_case() legal_case = pd.read_parquet(self.temp_data_path) self.docs = [] for (i, doc) in legal_case.iterrows(): doc = Document( page_content=doc['judgement'], metadata={ "judgement_case": i, "dataset_name": doc["dataset_name"], "summary": doc["summary"] }) self.docs.append(doc) return self.docs ``` -------------------------------- ### Initialize and Query Legal Cases with Fusion Score Source: https://github.com/datascienceworld-kan/vinagent/blob/main/docs/docs/guides/legal_assistant.md Demonstrates initializing the SearchLegalEngine and querying for legal cases related to 'claimed exemption from Sales Tax' using a fusion score. The results are filtered based on a provided threshold. ```python search_legal_engine = SearchLegalEngine( top_k=5, temp_data_path=Path("data/test.parquet"), db_type="milvus", embedding_model="BAAI/bge-small-en-v1.5" ) search_legal_engine._initialize_document_processor() query = "claimed exemption from Sales Tax" search_legal_engine.query_fusion_score(query, top_k=5, w_semantic=0.7) ```