From 8bf5d9087db1909880a109257798675a0ec6f71d Mon Sep 17 00:00:00 2001 From: Quincybob <74205675+Quincybob@users.noreply.github.com> Date: Wed, 23 Apr 2025 01:52:01 +0700 Subject: [PATCH] Add Python examples for SDK integration with AI frameworks --- examples/README.md | 17 ++++ examples/python/README.md | 48 +++++++++++ examples/python/agent_example.py | 92 ++++++++++++++++++++++ examples/python/langchain_example.py | 79 +++++++++++++++++++ examples/python/simple_demo.py | 76 ++++++++++++++++++ examples/python/thirdweb_ai_summary.py | 105 +++++++++++++++++++++++++ 6 files changed, 417 insertions(+) create mode 100644 examples/README.md create mode 100644 examples/python/README.md create mode 100644 examples/python/agent_example.py create mode 100644 examples/python/langchain_example.py create mode 100644 examples/python/simple_demo.py create mode 100644 examples/python/thirdweb_ai_summary.py diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..38277c5 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,17 @@ +# thirdweb AI SDK Examples + +This directory contains example code demonstrating how to use the thirdweb AI SDK. + +## Python Examples + +The [python](./python) directory contains examples of using the thirdweb AI SDK with Python: + +- `simple_demo.py`: A basic demo showing how to initialize the SDK, get tools, and prepare them for AI frameworks +- `agent_example.py`: Example integration with OpenAI Assistants API +- `langchain_example.py`: Example integration with LangChain +- `thirdweb_ai_summary.py`: Comprehensive overview of the SDK's capabilities and structure + +## Directory Structure + +- `final/` - Ready-to-use example scripts + - `simple_demo.py` diff --git a/examples/python/README.md b/examples/python/README.md new file mode 100644 index 0000000..874b237 --- /dev/null +++ b/examples/python/README.md @@ -0,0 +1,48 @@ +# thirdweb AI Python Examples + +This directory contains Python examples for the thirdweb AI SDK. + +## Examples + +- **simple_demo.py**: A basic demo script that shows how to initialize the SDK, get tools, and prepare them for use with different AI frameworks. + +- **agent_example.py**: Demonstrates how to integrate the thirdweb AI SDK with OpenAI Assistants API. + +- **langchain_example.py**: Shows how to use the thirdweb AI SDK with LangChain for building AI agents with blockchain capabilities. + +- **thirdweb_ai_summary.py**: A comprehensive overview of the SDK's capabilities, structure, and usage patterns. + +## Running the Examples + +These examples require: + +1. Python 3.9+ +2. thirdweb-ai package: `pip install "thirdweb-ai[all]"` +3. A thirdweb CLIENT_SECRET (set in a .env file or directly in the script) + +Create a `.env` file in the same directory as the example scripts with your secret: + +``` +CLIENT_SECRET=your_thirdweb_client_secret_here +``` + +Then run any example: + +```bash +python simple_demo.py +``` + +## Additional Requirements + +- For OpenAI examples: `pip install openai` +- For LangChain examples: `pip install langchain langchain-openai` + +## Key Concepts + +The thirdweb AI SDK is primarily designed as a toolkit for AI agents to interact with blockchains. The basic usage pattern is: + +1. Initialize a service (Insight, Nebula, Engine) +2. Get tools from the service +3. Convert tools to your AI framework format +4. Create an AI agent with these tools +5. Let the agent interact with blockchain data diff --git a/examples/python/agent_example.py b/examples/python/agent_example.py new file mode 100644 index 0000000..3e32b3e --- /dev/null +++ b/examples/python/agent_example.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +""" +thirdweb AI SDK - OpenAI Integration Example + +This script demonstrates how to use the thirdweb AI SDK with OpenAI Assistants API. + +Requirements: +- Python 3.9+ +- thirdweb-ai package +- openai package +- thirdweb CLIENT_SECRET (set in .env or directly) +- OpenAI API key (for actual usage) + +Usage: +python agent_example.py +""" + +import os +from dotenv import load_dotenv +from thirdweb_ai import Insight +from thirdweb_ai.adapters.openai import get_agents_tools + +# Load from .env file or set directly +load_dotenv() +CLIENT_SECRET = os.getenv("CLIENT_SECRET") +if not CLIENT_SECRET: + print("Error: CLIENT_SECRET not found. Set it in .env or directly in this script.") + exit(1) + +def main(): + print("thirdweb AI SDK - OpenAI Integration Example") + print("-" * 50) + + # Initialize Insight and get tools + insight = Insight(CLIENT_SECRET) + tools = insight.get_tools() + print(f"Got {len(tools)} blockchain tools from thirdweb") + + # Convert to OpenAI format + openai_tools = get_agents_tools(tools) + print(f"Converted to {len(openai_tools)} OpenAI-compatible tools") + + # Print example tool details + if openai_tools: + first_tool = openai_tools[0] + print(f"\nExample tool: {first_tool.name}") + print(f"Description: {first_tool.description[:100]}...") + + # Show how to use with OpenAI Assistants API + print("\nTo use with OpenAI Assistants API:") + print(""" +# Install the OpenAI Python SDK +# pip install openai + +from openai import OpenAI + +# Initialize OpenAI client +client = OpenAI(api_key="your_openai_api_key") + +# Create an Assistant with the tools +assistant = client.beta.assistants.create( + name="Blockchain Assistant", + instructions="You are a helpful assistant that can access blockchain data.", + model="gpt-4-turbo", + tools=openai_tools +) + +# Create a Thread +thread = client.beta.threads.create() + +# Add a message to the Thread +client.beta.threads.messages.create( + thread_id=thread.id, + role="user", + content="Show me Vitalik's ETH balance" +) + +# Run the Assistant on the Thread +run = client.beta.threads.runs.create( + thread_id=thread.id, + assistant_id=assistant.id +) + +# Get the response +# Note: In a real application, you would need to poll for completion +messages = client.beta.threads.messages.list(thread_id=thread.id) +""") + + print("\nExample complete!") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/examples/python/langchain_example.py b/examples/python/langchain_example.py new file mode 100644 index 0000000..0c9faf0 --- /dev/null +++ b/examples/python/langchain_example.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +""" +thirdweb AI SDK - LangChain Integration Example + +This script demonstrates how to use the thirdweb AI SDK with LangChain. + +Requirements: +- Python 3.9+ +- thirdweb-ai package +- langchain package +- thirdweb CLIENT_SECRET (set in .env or directly) +- OpenAI API key (for LangChain's ChatOpenAI) + +Usage: +python langchain_example.py +""" + +import os +from dotenv import load_dotenv +from thirdweb_ai import Insight +from thirdweb_ai.adapters.langchain import get_langchain_tools + +# Load from .env file or set directly +load_dotenv() +CLIENT_SECRET = os.getenv("CLIENT_SECRET") +if not CLIENT_SECRET: + print("Error: CLIENT_SECRET not found. Set it in .env or directly in this script.") + exit(1) + +def main(): + print("thirdweb AI SDK - LangChain Integration Example") + print("-" * 50) + + # Initialize Insight and get tools + insight = Insight(CLIENT_SECRET) + tools = insight.get_tools() + print(f"Got {len(tools)} blockchain tools from thirdweb") + + # Convert to LangChain format + langchain_tools = get_langchain_tools(tools) + print(f"Converted to {len(langchain_tools)} LangChain-compatible tools") + + # Print example tool details + if langchain_tools: + first_tool = langchain_tools[0] + print(f"\nExample tool: {first_tool.name}") + print(f"Description: {first_tool.description[:100]}...") + + # Show how to use with LangChain + print("\nTo use with LangChain:") + print(""" +# Install required packages +# pip install langchain langchain-openai + +from langchain.agents import AgentExecutor, create_tool_calling_agent +from langchain_core.prompts import ChatPromptTemplate +from langchain_openai import ChatOpenAI + +# Initialize LLM +llm = ChatOpenAI(model="gpt-4-turbo", temperature=0) + +# Create a prompt +prompt = ChatPromptTemplate.from_template( + "You are a blockchain assistant. Answer the following question: {input}" +) + +# Create an agent with the tools +agent = create_tool_calling_agent(llm, langchain_tools, prompt) +agent_executor = AgentExecutor(agent=agent, tools=langchain_tools) + +# Execute the agent +result = agent_executor.invoke({"input": "What's the current ETH price?"}) +print(result["output"]) +""") + + print("\nExample complete!") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/examples/python/simple_demo.py b/examples/python/simple_demo.py new file mode 100644 index 0000000..3594591 --- /dev/null +++ b/examples/python/simple_demo.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +""" +thirdweb AI SDK Simple Demo + +This script demonstrates basic usage of the thirdweb AI SDK and validates +that the installation is working correctly. + +Requirements: +- Python 3.9+ +- thirdweb-ai package +- thirdweb CLIENT_SECRET (set in .env or directly) + +Usage: +python simple_demo.py +""" + +import os +from dotenv import load_dotenv +from thirdweb_ai import Insight, Nebula + +# Load from .env file or set directly +load_dotenv() +CLIENT_SECRET = os.getenv("CLIENT_SECRET") +if not CLIENT_SECRET: + print("Error: CLIENT_SECRET not found. Set it in .env or directly in this script.") + exit(1) + +def main(): + print("thirdweb AI SDK Demo") + print("-" * 30) + + # 1. Initialize Insight + print("\n1. Initializing Insight service...") + insight = Insight(CLIENT_SECRET) + print("✓ Insight service initialized") + + # 2. Get tools + print("\n2. Getting blockchain tools...") + tools = insight.get_tools() + print(f"✓ Got {len(tools)} tools") + + # 3. List available tools + print("\n3. Available blockchain tools:") + for i, tool in enumerate(tools, 1): + print(f" {i}. {tool.name}") + + # 4. Framework adapters + print("\n4. Testing framework adapters...") + + # OpenAI adapter + try: + from thirdweb_ai.adapters.openai import get_agents_tools + openai_tools = get_agents_tools(tools) + print(f"✓ OpenAI adapter: {len(openai_tools)} tools") + except Exception as e: + print(f"✗ OpenAI adapter error: {str(e)[:60]}...") + + # LangChain adapter + try: + from thirdweb_ai.adapters.langchain import get_langchain_tools + langchain_tools = get_langchain_tools(tools) + print(f"✓ LangChain adapter: {len(langchain_tools)} tools") + except Exception as e: + print(f"✗ LangChain adapter error: {str(e)[:60]}...") + + # 5. Summary + print("\nHow to use with AI frameworks:") + print("1. Initialize service and get tools") + print("2. Convert tools to your framework's format") + print("3. Create an AI agent with the tools") + print("4. Let the agent interact with blockchain data") + + print("\nDemo complete!") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/examples/python/thirdweb_ai_summary.py b/examples/python/thirdweb_ai_summary.py new file mode 100644 index 0000000..acf3231 --- /dev/null +++ b/examples/python/thirdweb_ai_summary.py @@ -0,0 +1,105 @@ +""" +thirdweb AI SDK Usage Summary + +This script demonstrates how thirdweb-ai is intended to be used, based on our exploration. +""" + +import os +from dotenv import load_dotenv +from thirdweb_ai import Insight, Nebula +from thirdweb_ai.adapters.openai import get_agents_tools +from thirdweb_ai.adapters.langchain import get_langchain_tools + +# Load environment variables +load_dotenv() +client_secret = os.getenv("CLIENT_SECRET") + +print("=" * 50) +print("thirdweb AI SDK Usage Summary") +print("=" * 50) + +# 1. Initialization +print("\n1. Initialization") +print("-" * 30) +print("The SDK provides three main services:") +print("- Insight: For blockchain data intelligence") +print("- Engine: For wallet management and transactions") +print("- Nebula: For AI agent blockchain interaction") +print("\nInitializing with CLIENT_SECRET:") +insight = Insight(client_secret) +try: + nebula = Nebula(client_secret) + print("✓ Both Insight and Nebula initialized successfully") +except Exception as e: + print(f"✓ Insight initialized successfully") + print(f"✗ Nebula initialization failed: {e}") + +# 2. Tools +print("\n2. Tools") +print("-" * 30) +print("The SDK provides tools for AI agents to interact with blockchains:") +tools = insight.get_tools() +print(f"Number of tools from Insight: {len(tools)}") +print("\nAvailable tools:") +for i, tool in enumerate(tools, 1): + print(f"{i}. {tool.name}: {tool.description[:60]}..." if len(tool.description) > 60 else f"{i}. {tool.name}: {tool.description}") + +# 3. Framework Adapters +print("\n3. Framework Adapters") +print("-" * 30) +print("The SDK provides adapters for different AI frameworks:") + +# OpenAI +try: + openai_tools = get_agents_tools(tools) + print(f"✓ OpenAI: Converted {len(openai_tools)} tools") +except Exception as e: + print(f"✗ OpenAI adapter error: {e}") + +# LangChain +try: + langchain_tools = get_langchain_tools(tools) + print(f"✓ LangChain: Converted {len(langchain_tools)} tools") +except Exception as e: + print(f"✗ LangChain adapter error: {e}") + +# 4. Usage Pattern +print("\n4. Usage Pattern") +print("-" * 30) +print("The intended usage pattern is:") +print("1. Initialize the thirdweb-ai services") +print("2. Get tools from the services") +print("3. Convert tools to your AI framework format (OpenAI, LangChain, etc.)") +print("4. Create an AI agent with these tools") +print("5. Let the agent use these tools to interact with blockchain data") + +# 5. Example Usage (Pseudo-code) +print("\n5. Example Usage (Pseudo-code)") +print("-" * 30) +print(""" +# OpenAI Example +from openai import OpenAI + +client = OpenAI(api_key="your_openai_api_key") +assistant = client.beta.assistants.create( + name="Blockchain Assistant", + instructions="You are a helpful assistant that can access blockchain data.", + model="gpt-4-turbo", + tools=openai_tools +) + +# LangChain Example +from langchain.agents import AgentExecutor, create_tool_calling_agent +from langchain_core.prompts import ChatPromptTemplate +from langchain_openai import ChatOpenAI + +llm = ChatOpenAI() +prompt = ChatPromptTemplate.from_template("{input}") +agent = create_tool_calling_agent(llm, langchain_tools, prompt) +agent_executor = AgentExecutor(agent=agent, tools=langchain_tools) +result = agent_executor.invoke({"input": "Show me Vitalik's ETH balance"}) +""") + +print("\n" + "=" * 50) +print("End of Summary") +print("=" * 50) \ No newline at end of file