### Install Project Dependencies Source: https://github.com/victorm-lc/assistants-demo/blob/main/README.md Instructions to set up the Python virtual environment and install required packages using pip. This ensures all necessary libraries for the LangGraph demo are available. ```bash # Create and activate a virtual environment python3 -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate # Install dependencies pip install -r requirements.txt ``` -------------------------------- ### Setup LangGraph SDK Client and Environment Variables Source: https://github.com/victorm-lc/assistants-demo/blob/main/notebooks/assistant_test.ipynb This snippet initializes the environment by loading dotenv and setting up essential variables like `DEPLOYMENT_URL`, `API_KEY`, and `GRAPH_ID`. These variables are crucial for connecting to the LangGraph API and identifying the target graph, preparing the system for subsequent interactions. ```python from langgraph_sdk import get_client from dotenv import load_dotenv import os load_dotenv() # ---- SETUP ---- # Replace with your deployed LangGraph API URL and API key DEPLOYMENT_URL = os.getenv("DEPLOYMENT_URL") # e.g. "http://localhost:2024" or your cloud URL API_KEY = os.getenv("API_KEY") # If using deployed graph GRAPH_ID = "react_agent" # Name of the graph, normally set in your langgraph.json file. ``` -------------------------------- ### Configure Multiple LangGraph Sub-Agents Source: https://github.com/victorm-lc/assistants-demo/blob/main/README.md This Python example illustrates how to apply the same configuration pattern to orchestrate multiple sub-agents within a supervisor-style architecture. Each sub-agent receives its own `RunnableConfig` for independent setup. ```python async def create_subagents(): # Each subagent gets its own configuration finance_config = RunnableConfig( configurable={ "model": supervisor_config.finance_model, "system_prompt": supervisor_config.finance_system_prompt, "selected_tools": supervisor_config.finance_tools } ) finance_agent = await make_graph(finance_config) # ... more agents using same pattern ``` -------------------------------- ### Connect to LangGraph and Create a New Assistant Configuration Source: https://github.com/victorm-lc/assistants-demo/blob/main/notebooks/assistant_test.ipynb This code connects to the LangGraph server using the `get_client` function with the configured URL and API key. It then proceeds to create a new assistant configuration, defining its system prompt, model, and selected tools. The snippet concludes by printing the details of the newly created assistant, including its ID, name, version, model, and tools. ```python # 1. Connect to the LangGraph server client = get_client(url=DEPLOYMENT_URL, api_key=API_KEY) print("๐Ÿ”— Connected to LangGraph server") # 2. Create a new assistant configuration print("๐Ÿค– Creating a new assistant configuration...") assistant = await client.assistants.create( graph_id = GRAPH_ID, config={ "configurable": { "system_prompt": "You are a helpful AI assistant that can help with research.", "model": "openai/gpt-4.1", "selected_tools": ["get_todays_date", "advanced_research"] } }, name="Demo Assistant" ) print("โœ… Assistant created successfully!") print(f" ๐Ÿ“ Assistant ID: {assistant['assistant_id']}") print(f" ๐Ÿ“ Name: {assistant['name']}") print(f" ๐Ÿ”ข Version: {assistant['version']}") print(f" ๐Ÿง  Model: {assistant['config']['configurable']['model']}") print(f" ๐Ÿ› ๏ธ Tools: {', '.join(assistant['config']['configurable']['selected_tools'])}") ``` -------------------------------- ### Initialize Environment Configuration File Source: https://github.com/victorm-lc/assistants-demo/blob/main/README.md Command to create a `.env` file from a template, which is used to store API keys and other sensitive configurations for the project. ```bash cp .env.example .env ``` -------------------------------- ### Set OpenAI API Key in Environment Source: https://github.com/victorm-lc/assistants-demo/blob/main/README.md Instructions for setting the OpenAI API key in the `.env` file, enabling the use of OpenAI's chat models within the LangGraph application. ```bash OPENAI_API_KEY=your-api-key ``` -------------------------------- ### Create Thread and Invoke Assistant with a Question Source: https://github.com/victorm-lc/assistants-demo/blob/main/notebooks/assistant_test.ipynb This snippet demonstrates how to initiate a new conversation thread using `client.threads.create()`. Following thread creation, it prepares an input message containing a human query. This input is then used to invoke the assistant, showcasing a basic interaction flow with the configured LangGraph agent. ```python from langchain_core.messages import AIMessage, HumanMessage, ToolMessage import json # 3. Create a new thread for the conversation thread = await client.threads.create() print(f"๐Ÿงต Thread created: {thread['thread_id']}") # 4. Use the assistant: ask a silly question print("๐Ÿค– Invoking the assistant with a question...") input_data = {"messages": [{"role": "human", "content": "research the latest news in the art world"}]} ``` -------------------------------- ### Configure Single LangGraph Agent with Runtime Parameters Source: https://github.com/victorm-lc/assistants-demo/blob/main/README.md This Python function demonstrates how to create a LangGraph agent whose model, system prompt, and tools are dynamically configured at runtime using `RunnableConfig`. It shows direct extraction of configurable values and their application. ```python async def make_graph(config: RunnableConfig): # Extract configuration values directly configurable = config.get("configurable", {}) model = configurable.get("model", "anthropic/claude-3-5-sonnet-latest") system_prompt = configurable.get("system_prompt", "You are a helpful AI assistant.") selected_tools = configurable.get("selected_tools", ["get_todays_date"]) # Use the configuration llm = load_chat_model(model) tools = get_tools(config) return create_react_agent(model=llm, tools=tools, prompt=system_prompt) ``` -------------------------------- ### Set Anthropic API Key in Environment Source: https://github.com/victorm-lc/assistants-demo/blob/main/README.md Instructions for setting the Anthropic API key in the `.env` file, enabling the use of Anthropic's chat models within the LangGraph application. ```bash ANTHROPIC_API_KEY=your-api-key ``` -------------------------------- ### Stream AI Assistant Responses and Handle Events Source: https://github.com/victorm-lc/assistants-demo/blob/main/notebooks/assistant_test.ipynb This snippet demonstrates how to stream responses from an AI assistant run, processing different event types. It shows how to extract metadata, handle AI messages (including tool calls with their arguments), and process tool responses, providing summaries of the tool's output. ```python async for event in client.runs.stream( thread2["thread_id"], updated_assistant["assistant_id"], input=input_data2, stream_mode="updates" ): if event.event == "metadata": print(f"๐Ÿ“‹ Run started (ID: {event.data.get('run_id', 'Unknown')[:8]}...)") elif event.event == "updates": # Handle agent updates (AI messages and tool calls) if "agent" in event.data: for msg in event.data["agent"]["messages"]: if msg["type"] == "ai": # Check if AI is making tool calls if msg.get("tool_calls"): for tool_call in msg["tool_calls"]: tool_name = tool_call.get("name", "Unknown") print(f"๐Ÿ”ง Calling tool: {tool_name}") # Show tool arguments in a clean way if "args" in tool_call and tool_call["args"]: args_str = str(tool_call["args"]) if len(args_str) > 100: args_str = args_str[:100] + "..." print(f" โ””โ”€ Args: {args_str}") # Show AI response content (if not just tool calls) elif msg.get("content") and msg["content"].strip(): print(f"๐Ÿ˜„ Funny Assistant Response:") # Show full response for final answers content = msg["content"] print(f"{content}\n") # Handle tool responses elif "tools" in event.data: for msg in event.data["tools"]["messages"]: if msg["type"] == "tool": tool_name = msg.get("name", "Unknown tool") print(f"โœ… Tool '{tool_name}' completed") # Show brief summary of tool response content = msg.get("content", "") if content: # For research tool, try to count results try: import json results = json.loads(content) if isinstance(results, list): print(f" โ””โ”€ Found {len(results)} results") else: print(f" โ””โ”€ Result: {str(content)[:150]}...") except: print(f" โ””โ”€ Result: {str(content)[:150]}...") print("\n" + "="*50) print("๐ŸŽ‰ Funny assistant conversation completed!") print("="*50) ``` -------------------------------- ### Stream OpenAI Assistant Run Updates and Handle Events Source: https://github.com/victorm-lc/assistants-demo/blob/main/notebooks/assistant_test.ipynb This Python snippet demonstrates how to stream real-time updates from an OpenAI Assistant run. It processes various event types, including run metadata, agent messages (AI responses and tool calls), and tool outputs. It includes logic to display tool names, arguments, and summarize tool results. ```python async for event in client.runs.stream( thread["thread_id"], assistant["assistant_id"], input=input_data, stream_mode="updates", ): if event.event == "metadata": print(f"๐Ÿ“‹ Run started (ID: {event.data.get('run_id', 'Unknown')[:8]}...)") elif event.event == "updates": # Handle agent updates (AI messages and tool calls) if "agent" in event.data: for msg in event.data["agent"]["messages"]: if msg["type"] == "ai": # Check if AI is making tool calls if msg.get("tool_calls"): for tool_call in msg["tool_calls"]: tool_name = tool_call.get("name", "Unknown") print(f"๐Ÿ”ง Calling tool: {tool_name}") # Show tool arguments in a clean way if "args" in tool_call and tool_call["args"]: args_str = str(tool_call["args"]) if len(args_str) > 100: args_str = args_str[:100] + "..." print(f" โ””โ”€ Args: {args_str}") # Show AI response content (if not just tool calls) elif msg.get("content") and msg["content"].strip(): print(f"๐Ÿ’ฌ Assistant Response:") # Show full response for final answers content = msg["content"] if len(content) > 500: print(f"{content}\n") else: print(f"{content}\n") # Handle tool responses elif "tools" in event.data: for msg in event.data["tools"]["messages"]: if msg["type"] == "tool": tool_name = msg.get("name", "Unknown tool") print(f"โœ… Tool '{tool_name}' completed") # Show brief summary of tool response content = msg.get("content", "") if content: # For research tool, try to count results try: import json results = json.loads(content) if isinstance(results, list): print(f" โ””โ”€ Found {len(results)} results") else: print(f" โ””โ”€ Result: {str(content)[:150]}...") except: print(f" โ””โ”€ Result: {str(content)[:150]}...") print("\n" + "="*50) print("๐ŸŽ‰ Assistant conversation completed!") print("="*50) ``` -------------------------------- ### Use Updated OpenAI Assistant with New Thread Source: https://github.com/victorm-lc/assistants-demo/blob/main/notebooks/assistant_test.ipynb This Python snippet demonstrates how to create a new conversation thread and then invoke an OpenAI Assistant that has been previously updated. It prepares the input data with a user message to initiate a conversation with the assistant's new configuration. ```python thread2 = await client.threads.create() print(f"๐Ÿงต New thread created: {thread2['thread_id']}") print("๐Ÿ˜„ Invoking the updated funny assistant...") input_data2 = {"messages": [{"role": "user", "content": "If you could be any animal, which one would you be and why?"}]} ``` -------------------------------- ### Agent Configuration Schema Source: https://github.com/victorm-lc/assistants-demo/blob/main/README.md Defines the structure for configuring an agent, including the language model to use and associated environment variables. It specifies available models from Anthropic and OpenAI, along with their required API keys. ```APIDOC { "config_schemas": { "agent": { "type": "object", "properties": { "model": { "type": "string", "default": "anthropic/claude-3-5-sonnet-20240620", "description": "The name of the language model to use for the agent's main interactions. Should be in the form: provider/model-name.", "environment": [ { "value": "anthropic/claude-1.2", "variables": "ANTHROPIC_API_KEY" }, { "value": "anthropic/claude-2.0", "variables": "ANTHROPIC_API_KEY" }, { "value": "anthropic/claude-2.1", "variables": "ANTHROPIC_API_KEY" }, { "value": "anthropic/claude-3-5-sonnet-20240620", "variables": "ANTHROPIC_API_KEY" }, { "value": "anthropic/claude-3-haiku-20240307", "variables": "ANTHROPIC_API_KEY" }, { "value": "anthropic/claude-3-opus-20240229", "variables": "ANTHROPIC_API_KEY" }, { "value": "anthropic/claude-3-sonnet-20240229", "variables": "ANTHROPIC_API_KEY" }, { "value": "anthropic/claude-instant-1.2", "variables": "ANTHROPIC_API_KEY" }, { "value": "openai/gpt-3.5-turbo", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-3.5-turbo-0125", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-3.5-turbo-0301", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-3.5-turbo-0613", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-3.5-turbo-1106", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-3.5-turbo-16k", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-3.5-turbo-16k-0613", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4-0125-preview", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4-0314", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4-0613", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4-1106-preview", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4-32k", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4-32k-0314", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4-32k-0613", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4-turbo", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4-turbo-preview", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4-vision-preview", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4o", "variables": "OPENAI_API_KEY" }, { "value": "openai/gpt-4o-mini", "variables": "OPENAI_API_KEY" } ] } }, "environment": [ "TAVILY_API_KEY" ] } } } ``` -------------------------------- ### Revert AI Assistant to a Previous Version Source: https://github.com/victorm-lc/assistants-demo/blob/main/notebooks/assistant_test.ipynb This snippet demonstrates how to revert an AI assistant to a specific previous version using the `set_latest` method. This is useful for managing different configurations or rolling back to a known stable state of an assistant. ```python print("โช Reverting assistant to version 1...") await client.assistants.set_latest(assistant['assistant_id'], 1) print("โœ… Assistant reverted successfully!") print(" ๐Ÿ”ข Now using: Version 1 (Original research assistant)") print(" ๐Ÿ“ Back to: Helpful AI assistant for research") ``` -------------------------------- ### Update OpenAI Assistant Configuration Source: https://github.com/victorm-lc/assistants-demo/blob/main/notebooks/assistant_test.ipynb This Python snippet demonstrates how to programmatically update an existing OpenAI Assistant's configuration. It shows how to change the model name and system prompt, providing a new 'personality' for the assistant. The snippet also prints confirmation details about the updated assistant, including its ID, new version, and updated personality. ```python print("๐Ÿ”„ Creating a new version for your assistant...") updated_assistant = await client.assistants.update( assistant["assistant_id"], config={ "configurable": { "model_name": "openai/gpt-4.1", "system_prompt": "You are a funny assistant who likes to include puns in your responses." } }, ) print("โœ… Assistant updated successfully!") print(f" ๐Ÿ“ Assistant ID: {updated_assistant['assistant_id']}") print(f" ๐Ÿ”ข New Version: {updated_assistant['version']}") print(f" ๐Ÿ˜„ New Personality: Funny assistant with puns") print(f" ๐Ÿ“… Updated: {updated_assistant['updated_at'][:19].replace('T', ' ')}") ``` -------------------------------- ### Default LangGraph Model Configuration Source: https://github.com/victorm-lc/assistants-demo/blob/main/README.md Specifies the default large language model used in the LangGraph configuration, which can be overridden by environment variables or explicit settings. ```yaml model: anthropic/claude-3-5-sonnet-latest ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.