Skip to content
Merged
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
107 changes: 107 additions & 0 deletions apps/portal/src/app/ai/chat/openai-sdk/page.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# Usage with the OpenAI SDK

The thirdweb AI model can be accessed using the standard OpenAI Python/Typescript SDK by configuring it to use thirdweb's API endpoint. This allows you to leverage familiar OpenAI patterns while accessing thirdweb's blockchain-specific AI capabilities.

## Setup and Configuration

First, install the OpenAI Python SDK and configure it to use thirdweb's AI endpoint:

```bash
pip install openai
```

Configure the client with your thirdweb secret key:

```python
import os
from openai import OpenAI

client = OpenAI(
base_url="https://api.thirdweb.com/ai",
api_key=os.environ.get("THIRDWEB_SECRET_KEY")
)
```

**Important**: Store your `THIRDWEB_SECRET_KEY` as an environment variable for security. You can obtain your secret key from the [thirdweb dashboard](https://thirdweb.com/dashboard).

## Making AI Requests

The thirdweb AI model (`t0-latest`) can understand and execute blockchain operations through natural language. Use the `extra_body` parameter to provide blockchain context:

```python
chat_completion = client.chat.completions.create(
model="t0-latest",
messages=[{
"role": "user",
"content": "Swap 0.01 ETH to USDC, then transfer 10 USDC to vitalik.eth",
}],
stream=True,
extra_body={
"context": {
"from": "0x2247d5d238d0f9d37184d8332aE0289d1aD9991b",
"chain_ids": [8453],
"auto_execute_transactions": False
}
},
)
```

### Context Parameters

- **`from`**: The wallet address that will execute transactions
- **`chain_ids`**: Array of blockchain network IDs to operate on (e.g., `[1]` for Ethereum, `[8453]` for Base)
- **`auto_execute_transactions`**: Set to `true` to automatically execute transactions, or `false` to return transaction data for manual execution

## Handling Streaming Responses

The thirdweb AI model supports streaming responses with different event types. Here's how to handle them:

```python
import json

# Buffer message chunks and print once at the end
message_parts = []

for event in chat_completion:
event_type = getattr(event, "type", None)

# Handle thinking steps
if event_type == "presence":
data = getattr(event, "data", None)
print(f"[presence] {data}" if data is not None else "[presence]")
continue

# Handle actions (transaction preparations, chain changes, etc.)
if isinstance(event_type, str):
data = getattr(event, "data", None)
try:
data_str = json.dumps(data, separators=(",", ":"))
except Exception:
data_str = str(data)
print(f"\n\n[{event_type}] - {data_str if data_str is not None else ""}")
continue

# Handle message content
v = getattr(event, "v", None)
if v is not None:
message_parts.append(str(v))

# Print the final message
if message_parts:
print("\n\n[message] " + "".join(message_parts))
```

### Event Types

- **`init`**: Initializes the stream and provides session information
- **`presence`**: Indicates the AI is thinking or processing
- **`image`**: Contains image data
- **`context`**: Contains context data
- **`error`**: Contains error information if something goes wrong
- **Action events**:
- **`sign_transaction`**: Contains transaction data
- **`sign_swap`**: Contains swap data
- **`monitor_transaction`**: Contains queued transaction id
- **Message content**: The actual response text from the AI

The AI will return structured data for blockchain operations, including transaction details, gas estimates, and execution status when `auto_execute_transactions` is enabled.
10 changes: 5 additions & 5 deletions apps/portal/src/app/ai/chat/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ You can use the API with the HTTP API directly, the AI SDK or with any OpenAI-co
<TabsList>
<TabsTrigger value="api">HTTP API</TabsTrigger>
<TabsTrigger value="ai-sdk">Vercel AI SDK</TabsTrigger>
<TabsTrigger value="openai">OpenAI Client</TabsTrigger>
<TabsTrigger value="openai">OpenAI SDK</TabsTrigger>
</TabsList>
<TabsContent value="api">
<OpenApiEndpoint path="/ai/chat" method="POST" />
Expand Down Expand Up @@ -60,9 +60,9 @@ You can use the API with the HTTP API directly, the AI SDK or with any OpenAI-co

<TabsContent value="openai">

### Using the OpenAI Client
### Using the OpenAI SDK

You can use the standard OpenAI client library to interact with the thirdweb AI model.
You can use the standard OpenAI SDK library to interact with the thirdweb AI model.

```python
from openai import OpenAI
Expand All @@ -72,8 +72,8 @@ client = OpenAI(
api_key="<your-project-secret-key>",
)
chat_completion = client.chat.completions.create(
model="t0",
messages=[{"role": "user", "content": "Transfer 10 USDC to vitalik.eth"}],
model="t0-latest",
messages=[{ "role": "user", "content": "Transfer 10 USDC to vitalik.eth" }],
stream=False,
extra_body={ "context": { "from": "0x...", "chain_ids": [8453] }}
)
Expand Down
4 changes: 4 additions & 0 deletions apps/portal/src/app/ai/sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ export const sidebar: SideBar = {
name: "Vercel AI SDK",
href: "/ai/chat/ai-sdk",
},
{
name: "OpenAI SDK",
href: "/ai/chat/openai-sdk",
},
{
name: "API Reference",
href: "/reference#tag/ai/post/ai/chat",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,70 @@ async function getDelegationContractAddress(args: {
);
}

/**
* Creates an EIP-7702 account that enables EOA (Externally Owned Account) delegation
* to smart contract functionality. This allows an EOA to delegate its code execution
* to a minimal account contract, enabling features like batch transactions and sponsored gas.
*
* The minimal account leverages EIP-7702 authorization to delegate the EOA's code to a
* MinimalAccount contract, allowing the EOA to execute smart contract functions while
* maintaining its original address and private key control.
*
* @param args - Configuration object for creating the minimal account
* @param args.client - The thirdweb client instance for blockchain interactions
* @param args.adminAccount - The EOA account that will be delegated to the minimal account contract
* @param args.sponsorGas - Optional flag to enable sponsored gas transactions via bundler
*
* @returns An Account object with enhanced capabilities including batch transactions and EIP-5792 support
*
* @example
* ```typescript
* import { createThirdwebClient, sendBatchTransaction } from "thirdweb";
* import { privateKeyToAccount } from "thirdweb/wallets";
* import { create7702MinimalAccount } from "thirdweb/wallets/in-app";
* import { sepolia } from "thirdweb/chains";
*
* // Create a client
* const client = createThirdwebClient({
* clientId: "your-client-id"
* });
*
* // Create an EOA account
* const adminAccount = privateKeyToAccount({
* client,
* privateKey: "0x..."
* });
*
* // Wrap it with a EIP-7702 account
* const minimal7702Account = create7702MinimalAccount({
* client,
* adminAccount,
* sponsorGas: true // Enable sponsored transactions
* });
*
* // Send a batch of transactions
* const result = await sendBatchTransaction({
* account: minimal7702Account,
* transactions: [
* {
* to: "0x...",
* data: "0x...",
* value: 0n,
* chainId: sepolia.id
* },
* {
* to: "0x...",
* data: "0x...",
* value: 0n,
* chainId: sepolia.id
* }
* ]});
*
* console.log("Batch transaction hash:", result.transactionHash);
* ```
*
* @wallet
*/
export const create7702MinimalAccount = (args: {
client: ThirdwebClient;
adminAccount: Account;
Expand Down
Loading