### Initialize and Run LightAgent - Hello World Source: https://github.com/wanxingai/lightagent/blob/main/README.md Demonstrates the basic initialization of a LightAgent instance with a specified model and API key, followed by running a simple query and printing the response. This is the fundamental 'Hello World' example. ```python from LightAgent import LightAgent # Initialize Agent agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url") # Run Agent response = agent.run("Hello, who are you?") print(response) ``` -------------------------------- ### Install LightAgent using pip Source: https://github.com/wanxingai/lightagent/blob/main/README.fr.md Installs the latest version of the LightAgent library using pip. This is the primary method for setting up the framework in a Python environment. ```bash pip install lightagent ``` -------------------------------- ### Set Agent Persona with System Prompt Source: https://github.com/wanxingai/lightagent/blob/main/README.md Shows how to initialize LightAgent with a system prompt to define the agent's role or persona. This influences the agent's behavior and responses. The example sets the agent's role to be a helpful assistant. ```python from LightAgent import LightAgent # Initialize Agent agent = LightAgent( role="Please remember that you are LightAgent, a useful assistant that helps users use multiple tools.", # system role description model="gpt-4.1", # Supported models: openai, chatglm, deepseek, qwen, etc. api_key="your_api_key", # Replace with your large model provider API Key base_url="your_base_url", # Replace with your large model provider api url ) # Run Agent response = agent.run("Who are you?") print(response) ``` -------------------------------- ### Agent Routing Example with LightAgent Source: https://context7.com/wanxingai/lightagent/llms.txt Demonstrates how to use `light_swarm.run` to automatically route a query to a specific agent, such as a receptionist, for handling tasks like booking appointments. This functionality simplifies the distribution of requests within a multi-agent system. ```python response = light_swarm.run( agent=receptionist, query="I need to book meeting room 2 for tomorrow at 3pm.", stream=False ) print(response) ``` -------------------------------- ### Install Mem0 Memory Module Source: https://github.com/wanxingai/lightagent/blob/main/README.fr.md Installs the optional Mem0 package via pip, which provides memory capabilities for the LightAgent. Alternatively, Mem0 can be used via a hosting platform. ```bash pip install mem0ai ``` -------------------------------- ### Create Git Branch Source: https://github.com/wanxingai/lightagent/blob/main/README.fr.md This command demonstrates how to create a new Git branch for feature development. Ensure you have Git installed and initialized in your local repository. ```bash git checkout -b feature/YourFeature ``` -------------------------------- ### Python: Define and Integrate Custom Tools with LightAgent Source: https://github.com/wanxingai/lightagent/blob/main/README.fr.md Demonstrates how to define custom Python functions as tools for LightAgent. Each tool includes type-hinted parameters and a `tool_info` attribute specifying its name, description, and parameters. The example shows integrating `get_weather`, `search_news`, and `get_user_info` tools into an agent instance. ```python import requests from LightAgent import LightAgent # Define Tool def get_weather( city_name: str ) -> str: """ Get the weather information for a city :param city_name: The name of the city :return: Weather information """ if not isinstance(city_name, str): raise TypeError("City name must be a string") key_selection = { "current_condition": ["temp_C", "FeelsLikeC", "humidity", "weatherDesc", "observation_time"], } try: resp = requests.get(f"https://wttr.in/{city_name}?format=j1") resp.raise_for_status() resp = resp.json() ret = {k: {_v: resp[k][0][_v] for _v in v} for k, v in key_selection.items()} except: import traceback ret = "Error encountered while fetching weather data!\n" + traceback.format_exc() return str(ret) # Define Tool Information within the function get_weather.tool_info = { "tool_name": "get_weather", "tool_description": "Get the current weather information for a specified city", "tool_params": [ {"name": "city_name", "description": "The name of the city to query", "type": "string", "required": True}, ] } def search_news( keyword: str, max_results: int = 5 ) -> str: """ Search for news by keyword :param keyword: Search keyword :param max_results: Maximum number of results to return, default is 5 :return: News search results """ results = f"Through searching {keyword}, I found {max_results} related information." return str(results) # Define Tool Information within the function search_news.tool_info = { "tool_name": "search_news", "tool_description": "Search for news by keyword", "tool_params": [ {"name": "keyword", "description": "Search keyword", "type": "string", "required": True}, {"name": "max_results", "description": "Maximum results to return", "type": "int", "required": False}, ] } def get_user_info( user_id: str ) -> str: """ Get information of a user :param user_id: User ID :return: User information """ if not isinstance(user_id, str): raise TypeError("User ID must be a string") try: # Assuming using a user information API, here is a sample URL url = f"https://api.example.com/users/{user_id}" response = requests.get(url) response.raise_for_status() user_data = response.json() user_info = { "name": user_data.get("name"), "email": user_data.get("email"), "created_at": user_data.get("created_at") } except: import traceback user_info = "Error encountered while fetching user data!\n" + traceback.format_exc() return str(user_info) # Define Tool Information within the function get_user_info.tool_info = { "tool_name": "get_user_info", "tool_description": "Get information of a specified user", "tool_params": [ {"name": "user_id", "description": "User ID", "type": "string", "required": True}, ] } # Custom Tools tools = [get_weather, search_news, get_user_info] # Include all tools # Initialize the Agent # Replace with your model parameters: model, api_key, base_url agent = LightAgent(model="qwen-turbo-2024-11-01", api_key="your_api_key", base_url="your_base_url", tools=tools) query = "What is the current weather like in Sanya?" response = agent.run(query, stream=False) # Use agent to run the query print(response) ``` -------------------------------- ### LightAgent with Custom Memory Module (Python) Source: https://github.com/wanxingai/lightagent/blob/main/README.fr.md Illustrates how to enable and integrate a custom memory module with LightAgent. This example uses `mem0` for storing and retrieving conversational history, allowing the agent to maintain context across multiple interactions. It shows initialization of `mem0` and its integration into the agent. ```python # Enable Memory Module # Or use a custom memory module, here we use mem0 as an example https://github.com/mem0ai/mem0/ from mem0 import Memory from LightAgent import LightAgent import os from loguru import logger class CustomMemory: def __init__(self): self.memories = [] os.environ["OPENAI_API_KEY"] = "your_api_key" os.environ["OPENAI_API_BASE"] = "your_base_url" # Initialize Mem0 config = { "version": "v1.1" } # If using qdrant as a vector database in mem0 to store memories, change config to the code below # config = { # "vector_store": { # "provider": "qdrant", # "config": { # "host": "localhost", # "port": 6333, # } # }, # "version": "v1.1" # } self.m = Memory.from_config(config_dict=config) def store(self, data: str, user_id): """Store memory developers can modify the internal implementation of the storage method, the current example is mem0's memory addition method""" result = self.m.add(data, user_id=user_id) return result def retrieve(self, query: str, user_id): """Retrieve related memory developers can modify the internal implementation of the retrieval method, the current example is mem0's memory searching method""" result = self.m.search(query, user_id=user_id) return result agent = LightAgent( role="Please remember you are LightAgent, a helpful assistant that can help users utilize multiple tools.", # system role description model="deepseek-chat", # Supported models: openai, chatglm, deepseek, qwen, etc. api_key="your_api_key", # Replace with your large model service provider API Key base_url="your_base_url", # Replace with your large model service provider api url memory=CustomMemory(), # Enable memory functionality tree_of_thought=False, # Enable Thought Chain ) ``` -------------------------------- ### Integrate LightAgent with Langfuse for Monitoring in Python Source: https://github.com/wanxingai/lightagent/blob/main/README.md This Python code illustrates how to integrate LightAgent with Langfuse for enhanced monitoring and log tracking. It configures the agent with Langfuse specific settings, including enabling tracing and providing API credentials and host information. This setup allows for real-time tracking of metrics and visualization of the agent's decision-making processes. ```python from LightAgent import LightAgent tracetools = { "TraceTool": "langfuse", "TraceToolConfig": { "langfuse_enabled": True, "langfuse_host": "https://cloud.langfuse.com", "langfuse_public_key": "pk-lf-9fedb073-a*86-4**5-b**2-52****1b1**7", "langfuse_secret_key": "sk-lf-27bdbdec-c**6-4**3-a**2-28**0140**c7" } } agent = LightAgent( name="Agent A", # Agent Name instructions="You are a helpful agent.", # Role Description role="Please remember that you are LightAgent, a useful assistant to help users use multiple tools.", # system role description model="gpt-4o-mini", # Supported models: openai, chatglm, deepseek, qwen, etc. qwen-turbo-2024-11-01 \ step-1-flash api_key="your_api_key", # Replace with your API Key base_url="http://your_base_url/v1", # API URL debug=True, log_level="DEBUG", log_file="example.log", tracetools=tracetools ) ``` -------------------------------- ### MCP Protocol Integration with LightAgent Source: https://context7.com/wanxingai/lightagent/llms.txt Demonstrates how to integrate LightAgent with Model Context Protocol (MCP) servers. This allows the agent to leverage extended tool capabilities by connecting to external services like weather APIs. The example shows setting up MCP server configurations and then using the integrated tools in an agent's run method. ```python import asyncio import json from LightAgent import LightAgent agent = LightAgent( model="gpt-4o-mini", api_key="sk-your-api-key-here", base_url="https://api.openai.com/v1", debug=True, log_level="DEBUG", log_file="mcp_agent.log" ) mcp_settings = { "mcpServers": { "weather_server": { "command": "python", "args": ["./mcp/mcpServers/mcpServer_weather_sse.py"], "disabled": False }, "search_server": { "url": "http://localhost:8080/sse", "headers": {"Authorization": "Bearer token"}, "disabled": False } } } asyncio.run(agent.setup_mcp(mcp_setting=mcp_settings)) response = agent.run( "Search the weather in Shanghai and tell me if I need an umbrella.", stream=False ) print(response) ``` -------------------------------- ### Generate Tool Code with LightAgent Tools Generator (Python) Source: https://github.com/wanxingai/lightagent/blob/main/README.fr.md This snippet demonstrates how to initialize LightAgent with specific roles and model configurations to generate Python tool code based on a textual description of an API. It includes setup for agent instructions, saving generated code to a 'tools' directory, and handling directory creation if it doesn't exist. The output is two Python files for specific API functionalities. ```python import json import os import sys from LightAgent import LightAgent # Initialize LightAgent agent = LightAgent( name="Agent A", # Agent name instructions="You are a helpful agent.", # Role description role="Please remember you are a tool generator, your task is to automatically generate corresponding tool code based on the text description provided by the user and save it to the specified directory. Please ensure that the generated code is accurate, usable, and meets the user's needs.", # Tool generator's role description model="deepseek-chat", # Replace with your model. Supported models: openai, chatglm, deepseek, qwen, etc. api_key="your_api_key", # Replace with your API Key base_url="your_base_url", # Replace with your API URL ) # Sample text description text = """ The Sina Stock API provides functionality for obtaining stock market data, including stock quotes, real-time trading data, K-line data, etc. Sina Stock API Functional Introduction 1. Get Stock Quote Data: Real-time quote data: Use the real-time quote API to obtain the latest quotes, transaction volumes, price changes, and other information for stocks. Minute line quote data: Use the minute line API to obtain the minute-by-minute trading data for stocks, including opening price, closing price, highest price, lowest price, etc. 2. Get Historical K-line Data for Stocks: K-line data: Through the K-line API, you can obtain historical transaction data for stocks, including opening price, closing price, highest price, lowest price, transaction volume, etc. You can choose different time periods and moving average cycles as needed. Stock dividends data: You can choose to get stock price data adjusted for dividends, including forward and backward adjustments, to analyze stock price changes more accurately. Sample of Getting Data from the Sina Stock API 1. Get Stock Quote Data: API Address: http://hq.sinajs.cn/list=[Stock Code] Example: To get the real-time quote data for the stock code "sh600519" (Kweichou Moutai), you can use the following API address: http://hq.sinajs.cn/list=sh600519 By sending an HTTP GET request to the above API address, you will receive a response containing the real-time quote data for the stock. 2. Get Historical K-line Data for Stocks: API Address: http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=[Stock Code]&scale=[Time Period]&ma=[Moving Average Period]&datalen=[Data Length] Example: To get the daily K-line data for the stock code "sh600519" (Kweichou Moutai), you can use the following API address: http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=sh600519&scale=240&ma=no&datalen=1023 By sending an HTTP GET request to the above API address, you will receive a response containing the historical K-line data for the stock. """ # Build the path to the tools directory project_root = os.path.dirname(os.path.abspath(__file__)) tools_directory = os.path.join(project_root, "tools") # If the tools directory does not exist, create it if not os.path.exists(tools_directory): os.makedirs(tools_directory) print(f"Tools directory created: {tools_directory}") # Use the agent to generate tool code agent.create_tool(text, tools_directory=tools_directory) ``` -------------------------------- ### Initialize and Run LightAgent Source: https://github.com/wanxingai/lightagent/blob/main/README.fr.md Demonstrates the basic initialization of a LightAgent with a role, model, API key, and base URL. It then shows how to run the agent with a simple query. ```python from LightAgent import LightAgent agent = LightAgent( role="Please remember you are LightAgent, a helpful assistant that can help users utilize multiple tools.", # system role description model="deepseek-chat", # Supported models: openai, chatglm, deepseek, qwen, etc. api_key="your_api_key", # Replace with your large model service provider API Key base_url="your_base_url", # Replace with your large model service provider api url ) response = agent.run("May I ask who you are?") print(response) ``` -------------------------------- ### Initialize and Run LightAgent Source: https://github.com/wanxingai/lightagent/blob/main/README.fr.md Demonstrates how to initialize a LightAgent instance with a specified model and API key, and then run a simple query. This forms the basic interaction pattern with the agent. ```python from LightAgent import LightAgent # Initialize the Agent agent = LightAgent(model="gpt-4o-mini", api_key="your_api_key", base_url="your_base_url") # Run the Agent response = agent.run("Hello, who are you?") print(response) ``` -------------------------------- ### Setting Up and Running LightAgent and LightSwarm Source: https://github.com/wanxingai/lightagent/blob/main/README.fr.md This snippet demonstrates how to set environment variables, initialize a LightSwarm instance, create multiple LightAgents with specific roles and instructions, register them to the swarm, and run an interaction between agents. It showcases a typical workflow for multi-agent communication. ```python # Set the environment variables OPENAI_API_KEY and OPENAI_BASE_URL # The model defaults to gpt-4o-mini # Create a LightSwarm instance light_swarm = LightSwarm() # Create multiple agents agent_a = LightAgent( name="Agent A", instructions="I am Agent A, a front desk receptionist", role="Front desk receptionist responsible for receiving visitors and providing basic information guidance. Please introduce your identity before each response, and you may only guide users to other roles, not directly answer customers' business questions. If you cannot resolve the user's question, please reply: I'm sorry, I cannot provide help at the moment!", ) agent_b = LightAgent( name="Agent B", instructions="I am Agent B, responsible for booking meeting rooms", role="Meeting room reservation administrator, responsible for processing reservations, cancellations, and inquiries for rooms 1, 2, and 3. Please introduce your identity before each response and politely respond to users' queries.", ) agent_c = LightAgent( name="Agent C", instructions="I am Agent C, a technical support specialist responsible for technical issues. Please introduce your identity before each response and provide detailed answers to users' technical questions. If the question exceeds my abilities, please guide the user to contact higher-level technical support.", role="Technical support specialist responsible for handling inquiries and solutions regarding hardware, software, network issues, etc.", ) agent_d = LightAgent( name="Agent D", instructions="I am Agent D, a human resources specialist responsible for handling HR-related issues. Please introduce your identity before each response and provide detailed answers to users' questions. If the issue requires further processing, please guide the user to contact the HR department.", role="HR specialist responsible for handling employee onboarding, resignations, leave, benefits, etc.", ) # Automatically register agents to the LightSwarm instance light_swarm.register_agent(agent_a, agent_b, agent_c, agent_d) # Run Agent A res = light_swarm.run(agent=agent_a, query="Hello, I am Alice. I need to check if Wang Xiaoming has completed his onboarding.", stream=False) print(res) ``` -------------------------------- ### Multi-Agent Collaboration with LightSwarm in Python Source: https://github.com/wanxingai/lightagent/blob/main/README.md Demonstrates setting up and running multiple agents for collaborative task completion using the LightSwarm class. It requires setting OPENAI_API_KEY and OPENAI_BASE_URL environment variables. The snippet shows agent instantiation, role definition, and swarm registration, culminating in running a query through a specific agent. ```python from LightAgent import LightAgent, LightSwarm # Set Environment Variables OPENAI_API_KEY and OPENAI_BASE_URL # The default model uses gpt-4o-mini # Create an instance of LightSwarm light_swarm = LightSwarm() # Create multiple agents agent_a = LightAgent( name="Agent A", instructions="I am Agent A, the front desk receptionist.", role="Receptionist responsible for welcoming visitors and providing basic information guidance. Before each reply, please state your identity and that you can only guide users to other roles, not directly answer business questions. If you cannot help the user, please respond: Sorry, I am currently unable to assist!" ) agent_b = LightAgent( name="Agent B", instructions="I am Agent B, responsible for the reservation of meeting rooms.", role="Meeting room reservation administrator in charge of handling reservations, cancellations, and inquiries for meeting rooms 1, 2, and 3." ) agent_c = LightAgent( name="Agent C", instructions="I am Agent C, a technical support specialist, responsible for handling technical issues. Please state your identity before each reply, offering detailed responses to technical inquiries, and guide users to contact higher-level technical support for issues beyond your capability." ) agent_d = LightAgent( name="Agent D", instructions="I am Agent D, an HR specialist, responsible for handling HR-related questions.", role="HR specialist managing inquiries and processes related to employee onboarding, offboarding, leave, and benefits." ) # Automatically register agents to the LightSwarm instance light_swarm.register_agent(agent_a, agent_b, agent_c, agent_d) # Run Agent A res = light_swarm.run(agent=agent_a, query="Hello, I am Alice. I need to check if Wang Xiaoming has completed onboarding.", stream=False) print(res) ``` -------------------------------- ### Run Conversation with Memory - Python Source: https://github.com/wanxingai/lightagent/blob/main/README.fr.md Executes a conversation with the LightAgent, demonstrating its ability to recall previous queries and user preferences. It logs the start and end of each conversation turn and prints the agent's responses, highlighting memory-based suggestions. ```python user_id = "user_01" logger.info("\n=========== next conversation ===========") query = "Introduce some fun attractions in Sanya, many of my friends have traveled to Sanya, and I also want to go play." print(agent.run(query, stream=False, user_id=user_id)) logger.info("\n=========== next conversation ===========") query = "Where do I want to travel?" print(agent.run(query, stream=False, user_id=user_id)) ``` -------------------------------- ### Generate Tool Code with LightAgent Tool Generator (Python) Source: https://github.com/wanxingai/lightagent/blob/main/README.md This Python script demonstrates how to use the LightAgent Tool Generator to automatically create tool code based on a text description. It initializes the LightAgent, defines a sample text description for stock data interfaces, sets up a directory for saving the generated tools, and then calls the `create_tool` method. The generated tools (e.g., `get_stock_kline_data.py`, `get_stock_realtime_data.py`) will be saved in the specified 'tools' directory. ```python import json import os import sys from LightAgent import LightAgent # Initialize LightAgent agent = LightAgent( name="Agent A", # Agent name instructions="You are a helpful agent.", # Role description role="Please remember that you are a tool generator; your task is to automatically generate corresponding tool code based on the text description provided by the user and save it to the specified directory. Please ensure that the generated code is accurate, usable, and meets the user's needs.", # Tool generator's role description model="gpt-4.1", # Replace with your model. Supported models: openai, chatglm, deepseek, qwen, etc. api_key="your_api_key", # Replace with your API Key base_url="your_base_url", # Replace with your API URL ) # Sample text description text = """ The Sina stock interface provides functionalities for obtaining stock market data, including stock quotes, real-time trading data, and K-line chart data. Introduction to Sina stock interface functions 1. Get stock quote data: Realtime quote data: Using the real-time quote API, you can obtain the latest prices, trading volume, and changes for stocks. Minute line quote data: Using the minute line quote API, you can obtain the minute-by-minute trading data for stocks, including opening price, closing price, highest price, and lowest price. 2. Obtain historical K-line chart data: K-line chart data: Through the K-line chart API, you can obtain the historical trading data for stocks, including opening price, closing price, highest price, lowest price, trading volume, etc. You can choose different time periods and moving average periods as needed. Adjusted data: You can choose to retrieve adjusted K-line data, including pre-adjusted and post-adjusted data, for more accurate analysis of stock price changes. Example of obtaining data from the Sina stock interface 1. Get stock quote data: API address: http://hq.sinajs.cn/list=[stock_code] Example: To obtain real-time quote data for the stock code "sh600519" (Kweichow Moutai), you can use the following API address: http://hq.sinajs.cn/list=sh600519 By sending an HTTP GET request to the above API address, you will receive a response containing the real-time data for that stock. 2. Get historical K-line chart data: API address: http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=[stock_code]&scale=[time_period]&ma=[average_period]&datalen=[data_length] Example: To obtain daily K-line chart data for the stock code "sh600519" (Kweichow Moutai), you can use the following API address: http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=sh600519&scale=240&ma=no&datalen=1023 By sending an HTTP GET request to the above API address, you will receive a response containing the historical K-line chart data for that stock. """ # Build the path to the tools directory project_root = os.path.dirname(os.path.abspath(__file__)) tools_directory = os.path.join(project_root, "tools") # Create tools directory if it does not exist if not os.path.exists(tools_directory): os.makedirs(tools_directory) print(f"Tools directory has been created: {tools_directory}") # Use agent to generate tool code agent.create_tool(text, tools_directory=tools_directory) ``` -------------------------------- ### Python: Define and Integrate Custom Tools with LightAgent Source: https://github.com/wanxingai/lightagent/blob/main/README.md Demonstrates defining custom Python functions (get_weather, search_news, get_user_info) as tools for LightAgent. It shows how to attach tool metadata (name, title, description, parameters) to each function and then initialize the LightAgent with these tools to run queries. ```python import requests from LightAgent import LightAgent # Define Tool def get_weather( city_name: str ) -> str: """ Get weather information for a city :param city_name: Name of the city :return: Weather information """ if not isinstance(city_name, str): raise TypeError("City name must be a string") key_selection = { "current_condition": ["temp_C", "FeelsLikeC", "humidity", "weatherDesc", "observation_time"], } try: resp = requests.get(f"https://wttr.in/{city_name}?format=j1") resp.raise_for_status() resp = resp.json() ret = {k: {_v: resp[k][0][_v] for _v in v} for k, v in key_selection.items()} except: import traceback ret = "Error encountered while fetching weather data!\n" + traceback.format_exc() return str(ret) # Define tool information inside the function get_weather.tool_info = { "tool_name": "get_weather", "tool_title": "get weather", "tool_description": "Get current weather information for the specified city.", "tool_params": [ {"name": "city_name", "description": "The name of the city to query", "type": "string", "required": True}, ] } def search_news( keyword: str, max_results: int = 5 ) -> str: """ Search news based on keywords :param keyword: Search keyword :param max_results: Maximum number of results to return, default is 5 :return: News search results """ results = f"By searching for {keyword}, I've found {max_results} related pieces of information." return str(results) # Define tool information inside the function search_news.tool_info = { "tool_name": "search_news", "tool_title": "search news", "tool_description": "Search news based on keywords.", "tool_params": [ {"name": "keyword", "description": "Search keyword", "type": "string", "required": True}, {"name": "max_results", "description": "Maximum number of results to return", "type": "int", "required": False}, ] } def get_user_info( user_id: str ) -> str: """ Get user information :param user_id: User ID :return: User information """ if not isinstance(user_id, str): raise TypeError("User ID must be a string") try: # Assume using a user info API; this is a sample URL url = f"https://api.example.com/users/{user_id}" response = requests.get(url) response.raise_for_status() user_data = response.json() user_info = { "name": user_data.get("name"), "email": user_data.get("email"), "created_at": user_data.get("created_at") } except: import traceback user_info = "Error encountered while fetching user data!\n" + traceback.format_exc() return str(user_info) # Define tool information inside the function get_user_info.tool_info = { "tool_name": "get_user_info", "tool_description": "Retrieve information for the specified user.", "tool_params": [ {"name": "user_id", "description": "User ID", "type": "string", "required": True}, ] } # Custom Tools tools = [get_weather, search_news, get_user_info] # including all tools # Initialize Agent # Replace with your model parameters, API key, and base URL agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url", tools=tools) query = "How is the weather in Sanya today?" response = agent.run(query, stream=False) # Use agent to run the query print(response) ``` -------------------------------- ### Integrate a Single Tool with LightAgent Source: https://github.com/wanxingai/lightagent/blob/main/README.md Illustrates how to define a custom tool (e.g., `get_weather`) with its description and parameters, and then integrate it into the LightAgent. This allows the agent to perform specific tasks by calling these tools. ```python from LightAgent import LightAgent # Define Tool def get_weather(city_name: str) -> str: """ Get the current weather for `city_name` """ return f"Query result: {city_name} is sunny." # Define tool information inside the function get_weather.tool_info = { "tool_name": "get_weather", "tool_description": "Get current weather information for the specified city.", "tool_params": [ {"name": "city_name", "description": "The name of the city to query", "type": "string", "required": True}, ] } tools = [get_weather] # Initialize Agent agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url", tools=tools) # Run Agent response = agent.run("Please check the weather in Shanghai.") print(response) ``` -------------------------------- ### Agent Self-Learning with LightAgent Source: https://context7.com/wanxingai/lightagent/llms.txt Illustrates how to enable and utilize the self-learning capability of LightAgent. By setting `self_learning=True` and providing a `memory` instance, agents can learn from conversations and build domain knowledge. The example shows an agent learning a new company policy and then applying it to subsequent user queries. ```python from LightAgent import LightAgent agent = LightAgent( name="SupportAgent", instructions="You are a helpful support agent.", role="You help users with company policies and procedures.", model="gpt-4o-mini", api_key="sk-your-api-key-here", base_url="https://api.openai.com/v1", memory=CustomMemory(), self_learning=True, # Enable self-learning debug=True, log_level="DEBUG", log_file="agent.log" ) user_id = "admin_user" # Agent learns new company policy response = agent.run( "What is the approval process for procurement payments?", stream=False, user_id=user_id ) print(response) # Admin teaches agent new policy response = agent.run( "Please remember: According to new company regulations effective January 2025, all procurement payments must be signed by Manager Ding (procurement), then approved by finance manager, then general manager, before cashier can process payment.", stream=False, user_id=user_id ) print(response) # Different user benefits from learned knowledge user_id = "employee_002" response = agent.run( "How do I apply for a procurement payment transfer?", stream=False, user_id=user_id ) print(response) ``` -------------------------------- ### Configure LightAgent with Self-Learning in Python Source: https://github.com/wanxingai/lightagent/blob/main/README.md This snippet demonstrates how to initialize a LightAgent with self-learning enabled. It sets up agent parameters, memory, and enables the self-learning feature. The agent is then used to process user queries, with the self-learning capability continuously optimizing its responses. ```python agent = LightAgent( name="Agent A", # Agent name instructions="You are a helpful agent.", # Role description role="Please remember that you are LightAgent, a useful assistant to help users use multiple tools.", # system role description model="gpt-4.1", # Supported models: openai, chatglm, deepseek, qwen, etc. qwen-turbo-2024-11-01 \ step-1-flash api_key="your_api_key", # Replace with your API Key base_url="http://your_base_url/v1", # API URL memory=CustomMemory(), # Enable memory function self_learning=True, # Enable agent self-learning debug=True, log_level="DEBUG", log_file="example.log" ) user_id = "test_user_1" query = "I now have a procurement payment that needs to be transferred. What is my approval process?" agent.run(query, stream=False, user_id=user_id) query = "Please remember: According to the new company regulations, starting from January 2025, all procurement payments must first be signed by Manager Ding, who is responsible for procurement, then submitted to the finance manager for approval. After the finance manager's approval, the general manager of the company must also approve before the cashier can make the payment." agent.run(query, stream=False, user_id=user_id) user_id = "test_user_2" query = "Hello, I have a procurement payment to transfer to the other party. How do I apply for the transfer?" agent.run(query, stream=False, user_id=user_id) ``` -------------------------------- ### Initialize LightAgent with System Role and Instructions Source: https://context7.com/wanxingai/lightagent/llms.txt Shows how to configure a LightAgent with a specific name, custom instructions, and a defined role to shape its personality and behavior. This allows for more tailored agent responses suitable for specific applications like customer service. It utilizes parameters like `name`, `instructions`, and `role` during initialization. ```python from LightAgent import LightAgent agent = LightAgent( name="CustomerServiceBot", instructions="You are a helpful customer service assistant.", role="You specialize in answering product questions and helping customers with technical issues. Always be polite and provide detailed explanations.", model="gpt-4o-mini", api_key="sk-your-api-key-here", base_url="https://api.openai.com/v1" ) response = agent.run("What can you help me with?") print(response) # Output: As a customer service assistant, I can help you with product questions, technical issues, order tracking... ``` -------------------------------- ### Run Agent with Memory and Tool Calls (Python) Source: https://github.com/wanxingai/lightagent/blob/main/README.md This Python code snippet demonstrates how to use an agent with memory-enabled tool calls. It initializes an agent and runs two conversational queries. The first query asks for attractions in Sanya, and the second asks for general travel recommendations. The agent uses its memory of the first query to inform its response to the second, showing contextual awareness. ```python user_id = "user_01" logger.info("\n=========== next conversation ===========") query = "Introduce me to the attractions in Sanya. Many of my friends have traveled to Sanya, and I want to visit too." print(agent.run(query, stream=False, user_id=user_id)) logger.info("\n=========== next conversation ===========") query = "Where should I travel?" print(agent.run(query, stream=False, user_id=user_id)) ``` -------------------------------- ### Python: Implement Custom Memory for LightAgent using Mem0 Source: https://github.com/wanxingai/lightagent/blob/main/README.md This Python code defines a `CustomMemory` class that integrates with mem0 for memory persistence in LightAgent. It initializes mem0, sets necessary environment variables for the API, and provides `store` and `retrieve` methods. The `store` method adds data to memory, while `retrieve` searches for relevant information based on a query. It can be configured to use different vector stores like Qdrant by modifying the `config` dictionary. ```python from mem0 import Memory from LightAgent import LightAgent import os from loguru import logger class CustomMemory: def __init__(self): self.memories = [] os.environ["OPENAI_API_KEY"] = "your_api_key" os.environ["OPENAI_API_BASE"] = "your_base_url" # Initialize Mem0 config = { "version": "v1.1" } # Use qdrant as a vector database for storing memories in mem0, change config to the code below # config = { # "vector_store": { # "provider": "qdrant", # "config": { # "host": "localhost", # "port": 6333, # } # }, # "version": "v1.1" # } self.m = Memory.from_config(config_dict=config) def store(self, data: str, user_id): """Store memory. Developers can modify the internal implementation of the storage method; the current example is the mem0 method for adding memory.""" result = self.m.add(data, user_id=user_id) return result def retrieve(self, query: str, user_id): """Retrieve related memory. Developers can modify the internal implementation of the retrieval method; the current example is the mem0 method for searching memory.""" result = self.m.search(query, user_id=user_id) return result agent = LightAgent( role="Please remember that you are LightAgent, a useful assistant to help users use multiple tools.", # system role description model="gpt-4.1", # Supported models: openai, chatglm, deepseek, qwen, etc. api_key="your_api_key", # Replace with your large model provider API Key base_url="your_base_url", # Replace with your large model provider api url memory=CustomMemory(), # Enable memory function tree_of_thought=False, # Enable Chain of Thought ) ``` -------------------------------- ### Initialize Basic LightAgent Source: https://context7.com/wanxingai/lightagent/llms.txt Demonstrates the basic initialization of a LightAgent instance using a specified model, API key, and base URL. This is the fundamental step to create an agent capable of running queries. It requires the `LightAgent` class from the `LightAgent` library. ```python from LightAgent import LightAgent # Basic initializationagent = LightAgent( model="gpt-4o-mini", api_key="sk-your-api-key-here", base_url="https://api.openai.com/v1" ) # Query the agent response = agent.run("Hello, who are you?") print(response) # Output: I am LightAgent, an AI assistant designed to help you with various tasks... ``` -------------------------------- ### Basic Agent Initialization Source: https://context7.com/wanxingai/lightagent/llms.txt Initializes a simple LightAgent with basic model configuration and demonstrates how to query the agent. ```APIDOC ## Basic Agent Initialization ### Description Initializes a simple LightAgent with model configuration and demonstrates how to query the agent. ### Method ```python LightAgent(model: str, api_key: str, base_url: str) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from LightAgent import LightAgent agent = LightAgent( model="gpt-4o-mini", api_key="sk-your-api-key-here", base_url="https://api.openai.com/v1" ) response = agent.run("Hello, who are you?") print(response) ``` ### Response #### Success Response (200) - **response** (str) - The agent's textual response to the query. #### Response Example ```json { "response": "I am LightAgent, an AI assistant designed to help you with various tasks..." } ``` ``` -------------------------------- ### LightAgent with Tool Usage (Python) Source: https://github.com/wanxingai/lightagent/blob/main/README.fr.md Shows how to define a custom tool (get_weather) with its schema and integrate it into a LightAgent for handling specific requests like checking weather conditions. The agent is initialized with the tool and then run with a query. ```python from LightAgent import LightAgent # Define Tool def get_weather(city_name: str) -> str: """ Get the current weather for `city_name` """ return f"Query result: {city_name} Weather is clear" # Define tool information within the function get_weather.tool_info = { "tool_name": "get_weather", "tool_description": "Get the current weather information for a specified city", "tool_params": [ {"name": "city_name", "description": "The name of the city to query", "type": "string", "required": True}, ] } tools = [get_weather] # Initialize the Agent agent = LightAgent(model="qwen-turbo-2024-11-01", api_key="your_api_key", base_url="your_base_url", tools=tools) # Run the Agent response = agent.run("Please help me check the weather condition in Shanghai") print(response) ``` -------------------------------- ### Streaming API Output in Python with LightAgent Source: https://github.com/wanxingai/lightagent/blob/main/README.md Shows how to enable and utilize streaming output from the agent, which is compatible with OpenAI's streaming format. This is useful for real-time responses in chat applications. The 'stream=True' parameter is crucial for activating this feature. ```python # Enable streaming output response = agent.run("Please generate an article about AI.", stream=True) for chunk in response: print(chunk) ``` -------------------------------- ### Implement Multi-Agent Collaboration with LightSwarm (Python) Source: https://context7.com/wanxingai/lightagent/llms.txt This Python code illustrates how to set up and utilize LightSwarm for multi-agent collaboration. It involves creating specialized LightAgent instances (e.g., Receptionist, HR Specialist), registering them to a LightSwarm instance, and then running a query. The swarm automatically routes the query to the most appropriate agent based on their roles and instructions, enabling task delegation and specialization. ```python import os from LightAgent import LightAgent, LightSwarm # Set environment variables os.environ["OPENAI_API_KEY"] = "sk-your-api-key-here" os.environ["OPENAI_API_BASE"] = "https://api.openai.com/v1" # Create LightSwarm instance light_swarm = LightSwarm() # Create specialized agents receptionist = LightAgent( name="Receptionist", instructions="I am the front desk receptionist.", role="Responsible for welcoming visitors and providing basic information guidance. Guide users to appropriate specialists." ) hr_specialist = LightAgent( name="HR_Specialist", instructions="I am an HR specialist.", role="HR specialist managing employee onboarding, offboarding, leave, and benefits inquiries." ) tech_support = LightAgent( name="TechSupport", instructions="I am a technical support specialist.", role="Handle technical issues and provide detailed solutions. Escalate complex issues when needed." ) meeting_admin = LightAgent( name="MeetingAdmin", instructions="I am responsible for meeting room reservations.", role="Meeting room reservation administrator for rooms 1, 2, and 3. Handle bookings, cancellations, and inquiries." ) # Register all agents to swarm light_swarm.register_agent(receptionist, hr_specialist, tech_support, meeting_admin) # Run query - swarm automatically routes to appropriate agent response = light_swarm.run( agent=receptionist, query="I need to check if John Smith completed his onboarding process.", stream=False ) print(response) # Output: [HR_Specialist responds] According to our records, John Smith completed his onboarding on January 15, 2025... ```