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
6 changes: 4 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@ agentkit/
│ ├── coinbase-agentkit/
│ ├── create-onchain-agent/
│ ├── framework-extensions/
│ │ └── langchain/
│ │ ├── langchain/
│ │ └── openai-agents-sdk/
│ └── examples/
│ ├── langchain-cdp-chatbot/
│ └── langchain-twitter-chatbot/
│ ├── langchain-twitter-chatbot/
│ └── openai-agents-sdk-cdp-chatbot/
```

## Language-Specific Guides
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,12 @@ agentkit/
│ ├── coinbase-agentkit/
│ ├── create-onchain-agent/
│ ├── framework-extensions/
│ │ └── langchain/
│ │ ├── langchain/
│ │ └── openai-agents-sdk/
│ └── examples/
│ ├── langchain-cdp-chatbot/
│ └── langchain-twitter-chatbot/
│ ├── langchain-twitter-chatbot/
│ └── openai-agents-sdk-cdp-chatbot/
```

## 🤝 Contributing
Expand Down
6 changes: 6 additions & 0 deletions python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ LangChain extension of AgentKit. Enables agentic workflows to interact with onch

See [AgentKit LangChain](./framework-extensions/langchain/README.md) to get started!

#### `coinbase-agentkit-openai-agents-sdk`

OpenAI Agents SDK extension of AgentKit. Enables agentic workflows to interact with onchain actions.

See [AgentKit OpenAI Agents SDK](./framework-extensions/openai-agents-sdk/README.md) to get started!

### `create-onchain-agent`

A quickstart CLI tool to scaffold out a chatbot using Coinbase AgentKit. Runnable via `pipx run create-onchain-agent`.
Expand Down
3 changes: 3 additions & 0 deletions python/examples/openai-agents-sdk-cdp-chatbot/.env.local
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
CDP_API_KEY_NAME= # Place your CDP API key name here
CDP_API_KEY_PRIVATE_KEY= # Place your CDP API key private key here
OPENAI_API_KEY= # Place your OpenAI API key here
29 changes: 29 additions & 0 deletions python/examples/openai-agents-sdk-cdp-chatbot/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
ifneq (,$(wildcard ./.env))
include .env
endif

export

.PHONY: install
install:
poetry install

.PHONY: run
run:
poetry run python chatbot.py

.PHONY: format
format:
poetry run ruff format .

.PHONY: format-check
format-check:
poetry run ruff format . --check

.PHONY: lint
lint:
poetry run ruff check .

.PHONY: lint-fix
lint-fix:
poetry run ruff check . --fix
42 changes: 42 additions & 0 deletions python/examples/openai-agents-sdk-cdp-chatbot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# CDP Agentkit OpenAI Agents SDK Extension Examples - Chatbot Python

This example demonstrates an agent setup as a terminal style chatbot using the OpenAI Agents SDK integration with CDP Agentkit actions.

## Ask the chatbot to engage in the Web3 ecosystem!
- "Transfer a portion of your ETH to a random address"
- "What is the price of BTC?"
- "Deploy an NFT that will go super viral!"
- "Deploy an ERC-20 token with total supply 1 billion"

## Requirements
- Python 3.10+
- Poetry for package management and tooling
- [Poetry Installation Instructions](https://python-poetry.org/docs/#installation)
- [CDP API Key](https://portal.cdp.coinbase.com/access/api)
- [OpenAI API Key](https://platform.openai.com/docs/quickstart#create-and-export-an-api-key)

### Checking Python Version
Before using the example, ensure that you have the correct version of Python installed. The example requires Python 3.10 or higher. You can check your Python version by running:

```bash
python --version
poetry --version
```

## Installation
```bash
poetry install
```

## Run the Chatbot

### Set ENV Vars
- Ensure the following ENV Vars are set:
- "CDP_API_KEY_NAME"
- "CDP_API_KEY_PRIVATE_KEY"
- "OPENAI_API_KEY"
- "NETWORK_ID" (Defaults to `base-sepolia`)

```bash
poetry run python chatbot.py
```
159 changes: 159 additions & 0 deletions python/examples/openai-agents-sdk-cdp-chatbot/chatbot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import json
import os
import sys
import time
import asyncio

from coinbase_agentkit import (
AgentKit,
AgentKitConfig,
CdpWalletProvider,
CdpWalletProviderConfig,
cdp_api_action_provider,
cdp_wallet_action_provider,
erc20_action_provider,
pyth_action_provider,
wallet_action_provider,
weth_action_provider,
)
from coinbase_agentkit_openai_agents_sdk import get_openai_agents_sdk_tools
from dotenv import load_dotenv
from agents.agent import Agent
from agents.run import Runner

# Configure a file to persist the agent's CDP API Wallet Data.
wallet_data_file = "wallet_data.txt"

load_dotenv()


def initialize_agent():
"""Initialize the agent with CDP Agentkit."""
# Initialize CDP Wallet Provider
wallet_data = None
if os.path.exists(wallet_data_file):
with open(wallet_data_file) as f:
wallet_data = f.read()

cdp_config = None
if wallet_data is not None:
cdp_config = CdpWalletProviderConfig(wallet_data=wallet_data)

wallet_provider = CdpWalletProvider(cdp_config)

agentkit = AgentKit(
AgentKitConfig(
wallet_provider=wallet_provider,
action_providers=[
cdp_api_action_provider(),
cdp_wallet_action_provider(),
erc20_action_provider(),
pyth_action_provider(),
wallet_action_provider(),
weth_action_provider(),
],
)
)

wallet_data_json = json.dumps(wallet_provider.export_wallet().to_dict())

with open(wallet_data_file, "w") as f:
f.write(wallet_data_json)

# use get_openai_agents_sdk_tools
tools = get_openai_agents_sdk_tools(agentkit)

# Create Agent using the OpenAI Agents SDK
agent = Agent(
name="CDP Agent",
instructions=(
"You are a helpful agent that can interact onchain using the Coinbase Developer Platform AgentKit. "
"You are empowered to interact onchain using your tools. If you ever need funds, you can request "
"them from the faucet if you are on network ID 'base-sepolia'. If not, you can provide your wallet "
"details and request funds from the user. Before executing your first action, get the wallet details "
"to see what network you're on. If there is a 5XX (internal) HTTP error code, ask the user to try "
"again later. If someone asks you to do something you can't do with your currently available tools, "
"you must say so, and encourage them to implement it themselves using the CDP SDK + Agentkit, "
"recommend they go to docs.cdp.coinbase.com for more information. Be concise and helpful with your "
"responses. Refrain from restating your tools' descriptions unless it is explicitly requested."
),
tools=tools
)

return agent


# Autonomous Mode
async def run_autonomous_mode(agent, interval=10):
"""Run the agent autonomously with specified intervals."""
print("Starting autonomous mode...")
while True:
try:
thought = (
"Be creative and do something interesting on the blockchain. "
"Choose an action or set of actions and execute it that highlights your abilities."
)

# Run agent in autonomous mode
output = await Runner.run(agent, thought)
print(output.final_output)
print("-------------------")

# Wait before the next action
await asyncio.sleep(interval)

except KeyboardInterrupt:
print("Goodbye Agent!")
sys.exit(0)


# Chat Mode
async def run_chat_mode(agent):
"""Run the agent interactively based on user input."""
print("Starting chat mode... Type 'exit' to end.")
while True:
try:
user_input = input("\nPrompt: ")
if user_input.lower() == "exit":
break

# Run agent with the user's input in chat mode
output = await Runner.run(agent, user_input)
print(output.final_output)
print("-------------------")

except KeyboardInterrupt:
print("Goodbye Agent!")
sys.exit(0)


# Mode Selection
def choose_mode():
"""Choose whether to run in autonomous or chat mode based on user input."""
while True:
print("\nAvailable modes:")
print("1. chat - Interactive chat mode")
print("2. auto - Autonomous action mode")

choice = input("\nChoose a mode (enter number or name): ").lower().strip()
if choice in ["1", "chat"]:
return "chat"
elif choice in ["2", "auto"]:
return "auto"
print("Invalid choice. Please try again.")


async def main():
"""Start the chatbot agent."""
agent = initialize_agent()

mode = choose_mode()
if mode == "chat":
await run_chat_mode(agent=agent)
elif mode == "auto":
await run_autonomous_mode(agent=agent)


if __name__ == "__main__":
print("Starting Agent...")
asyncio.run(main())
Loading