Skip to content

Add Python examples for SDK integration with AI frameworks #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -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`
48 changes: 48 additions & 0 deletions examples/python/README.md
Original file line number Diff line number Diff line change
@@ -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
92 changes: 92 additions & 0 deletions examples/python/agent_example.py
Original file line number Diff line number Diff line change
@@ -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()
79 changes: 79 additions & 0 deletions examples/python/langchain_example.py
Original file line number Diff line number Diff line change
@@ -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()
76 changes: 76 additions & 0 deletions examples/python/simple_demo.py
Original file line number Diff line number Diff line change
@@ -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()
Loading