# SDK Reference

**SDK Overview**

The AgentGPT SDK enables developers to:

* Deploy self-managing smart contracts powered by GPT-4 reasoning
* Automate cross-chain Web3 workflows with zero human intervention
* Integrate AI decision-making directly into dApp architecture

***

#### **Installation**

```bash
npm install @agentgpt/web3-sdk  
# OR  
pip install agentgpt-blockchain  
```

***

#### \*\*Core Functions

***

**init()**

Initialize the AgentGPT environment with blockchain and AI configurations.

**Parameters**:

| Name              | Type          | Default                         | Description                            |
| ----------------- | ------------- | ------------------------------- | -------------------------------------- |
| `api_key`         | `string`      | `process.env.AGENTGPT_KEY`      | API key for AgentGPT services          |
| `chain_config`    | `ChainConfig` | `Ethereum Mainnet`              | Blockchain network parameters          |
| `llm_model`       | `string`      | `"gpt-4-turbo-web3"`            | GPT-4 variant for task decomposition   |
| `auto_instrument` | `boolean`     | `true`                          | Auto-track smart contract interactions |
| `web3_providers`  | `string[]`    | `["https://agent-gpt.org/api"]` | Custom RPC endpoints                   |

**Example**:

```typescript
import { init } from '@agentgpt/web3-sdk';  

const sessionId = init({  
  chain_config: {  
    chainId: 137,  
    contracts: ['ERC7645', 'ERC4519']  
  },  
  llm_model: "gpt-4-defi-optimizer",  
  web3_providers: ["https://agent-gpt.org/poly"]  
});  
```

***

**start\_session()**

Launch an autonomous workflow session anchored on-chain.

**Parameters**:

| Name            | Type         | Description                                    |
| --------------- | ------------ | ---------------------------------------------- |
| `workflow_type` | `string`     | \[`DeFi`, `NFT`, `CrossChain`, `Custom`]       |
| `tags`          | `string[]`   | e.g., `["high_frequency", "zk_protected"]`     |
| `gas_strategy`  | `GasProfile` | Optimize for \[`speed`, `cost`, `reliability`] |

**Returns**:

* `Session` object with on-chain metadata (ERC-7612 NFT)

**Example**:

```solidity
// Start DeFi arbitrage session  
const session = start_session({  
  workflow_type: "DeFi",  
  tags: ["arbitrage", "multi_chain"],  
  gas_strategy: {  
    priority: "speed",  
    max_gwei: 45  
  }  
});  
```

***

**end\_session()**

Finalize workflow and record results on-chain.

**Parameters**:

| Name               | Type             | Description                         |
| ------------------ | ---------------- | ----------------------------------- |
| `outcome`          | `SessionOutcome` | \[`Success`, `Partial`, `Reverted`] |
| `performance_data` | `string`         | IPFS CID of execution analytics     |
| `proof`            | `bytes`          | ZK-SNARK validation proof           |

**Example**:

```javascript
end_session({  
  outcome: "Success",  
  performance_data: "QmXyZ...",  
  proof: "0xabcdef..."  
});  
```

***

**record()**

Log critical Web3 workflow events with AI-enhanced context.

**Event Types**:

| Event Class        | Blockchain Anchoring           |
| ------------------ | ------------------------------ |
| `ContractDeployed` | TX hash + constructor params   |
| `AssetSwap`        | DEX price + slippage proof     |
| `GovernanceVote`   | DAO proposal ID + voting power |

**Example**:

```python
from agentgpt_sdk import record, ContractEvent  

record(ContractEvent(  
  address="0x...",  
  abi="ERC20",  
  action="approve",  
  args={  
    "spender": "0x...",  
    "amount": "1e18"  
  },  
  gas_used: 45000  
))  
```

***

#### **Types & Interfaces**

***

**ChainConfig**

Blockchain network specification for autonomous agents.

**Properties**:

```typescript
interface ChainConfig {  
  chainId: number;  
  currency: string;  
  contracts: string[];  
  rpcFailoverOrder: string[];  
  complianceCheck: boolean;  
}  
```

***

**GasProfile**

Dynamic fee management for cross-chain operations.

**Properties**:

```solidity
struct GasProfile {  
  uint256 max_gwei;  
  PriorityLevel priority;  
  bool eip1559_enabled;  
  address gas_token;  
}  

enum PriorityLevel {  
  Standard,  
  Fast,  
  Instant  
}  
```

***

#### **Web3 Callback Handlers**

***

**ContractEventListener**

Handle smart contract events with AI-powered responses.

```python
class ContractHandler:  
    def on_event(self, event):  
        gpt_response = self.llm.analyze(event)  
        if gpt_response["action"] == "SWAP":  
            execute_swap(gpt_response["params"])  

# Register handler  
sdk.register_callback('contract_events', ContractHandler())  
```

***

**TransactionMonitor**

Real-time TX lifecycle management across EVM chains.

```javascript
const monitor = new TransactionMonitor({  
  onPending: (txHash) => {  
    agent.accelerateTransaction(txHash, {  
      bumpType: "replace-by-fee",  
      newGasPrice: currentGas * 1.3  
    });  
  },  
  onConfirmed: (receipt) => {  
    ai_post_analysis(receipt);  
  }  
});  
```

***

#### **SDK Performance Profile**

| Metric               | Value               |
| -------------------- | ------------------- |
| Event Throughput     | 2,300 events/sec    |
| Gas Estimation Error | <1.5%               |
| Cross-Chain Latency  | 890ms (p95)         |
| AI Response Time     | 420ms (GPT-4 Turbo) |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://agent-gpt.gitbook.io/agent-gpt/usage/sdk-reference.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
