# Tracking LLM Calls

AgentGPT automatically instruments LLM transactions when using supported providers, linking AI reasoning to on-chain execution. Key features:

* 🛠️ **Auto-Tracing**: Binds LLM decisions to smart contract calls via ERC-7645 Event NFTs.
* 🔗 **Blockchain-Verified Logs**: Stores LLM interaction hashes on IPFS + Filecoin.
* ⚙️ **Gas-Aware Optimization**: Adjusts model complexity based on real-time network fees.

***

#### **How It Works**

When AgentGPT detects these configured LLM providers, tracking starts automatically:

| Provider     | Supported Versions | Blockchain Anchoring Method        |
| ------------ | ------------------ | ---------------------------------- |
| OpenAI GPT-4 | ≥1.14.0            | ERC-7645 Event NFT Metadata        |
| Anthropic    | ≥0.18.0            | Polygon ID zkAttestations          |
| Llama-3-Web3 | Fork ≥2305         | Chainlink Offchain Reporting (OCR) |

***

#### **Setup Guide**

**Prerequisites**

1. Install AgentGPT SDK:

   ```bash
   pip install agentgpt[llm-tracking]  
   # OR  
   npm install @agentgpt/llm-monitor  
   ```
2. Initialize with GPT-4 + blockchain config:

   ```python
   from agentgpt import init, LlmConfig  

   init(  
       llm=LlmConfig(  
           provider="openai",  
           model="gpt-4-turbo-web3",  
           chain_id=137  # Polygon Mainnet  
       ),  
       auto_track=True,  
       gas_profile={"max_priority_fee": "30 gwei"}  
   )  
   ```

***

#### **Troubleshooting**

**Common Issues & Fixes**:

| Symptom                       | Solution                                                                                                                                                                     |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| LLM calls not logged on-chain | <p>1. Verify <code>init()</code> runs <strong>after</strong> LLM imports<br>2. Check <code>auto\_track=True</code> in config<br>3. Confirm gas fees are funded in wallet</p> |
| Delayed transaction anchoring | <p>1. Increase RPC provider timeout to 45s<br>2. Switch to premium Web3 gateway tier</p>                                                                                     |
| ZK proof generation failure   | <p>1. Update zkCircuit version ≥2.3<br>2. Allocate ≥4GB RAM for proving</p>                                                                                                  |

**Emergency Reset**:

```solidity
// Call on-chain via AgentGPT Governance Contract  
function resetLlmTrackingSession(bytes32 sessionId) external {  
    require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender));  
    delete llmSessions[sessionId];  
}  
```

***

#### **Advanced Configuration**

**Custom LLM Tracking Rules**

```yaml
# agentgpt-track.yml  
rules:  
  - pattern: "defi.*arbitrage"  
    storage:  
      layer: "polygon"  
      privacy: "zkRollup"  
    gas_priority: "high"  
  - pattern: "nft.*metadata"  
    storage:  
      layer: "ipfs"  
      privacy: "public"  
```

**Stop Tracking**

Pause LLM instrumentation while preserving workflow state:

```python
from agentgpt import stop_instrumenting  
  
# Halts tracking but continues execution  
stop_instrumenting(persist_session=True)  
```

> **Blockchain Note**: Stopping tracking requires 2 blockchain confirmations. Existing logs remain immutable.

***

#### **LLM Call Structure**

Each tracked interaction generates:

```json
{  
  "llm_call_id": "0x891a...",  
  "model": "gpt-4-turbo-web3",  
  "input_tokens": 1420,  
  "blockchain_anchor": {  
    "tx_hash": "0x5b42...",  
    "block": 19438271,  
    "zk_proof": "a1c8..."  
  },  
  "cost_breakdown": {  
    "compute": 0.024 ETH,  
    "storage": 0.0015 ETH  
  }  
}  
```

***

#### **Error Recovery**

**Common Scenarios**:

1. **Transaction Reverted but LLM Called**:

   ```python
   from agentgpt import recover_llm_credits  

   recover_llm_credits(  
       failed_tx_hash="0x...",  
       resubmit=True  
   )  
   ```
2. **Finality Dispute**:

   ```bash
   agentgpt disputes submit \  
     --chain polygon \  
     --proof-file audit_log.zkey \  
     --deposit 0.1 AGPT  
   ```

***

#### **Quick Start**

1. **Install**:

   ```bash
   pip install agentgpt  
   ```
2. **Initialize**:

   ```python
   from agentgpt import init  
   import openai  

   init(auto_track=True)  
   openai.ChatCompletion.create(...)  # Auto-tracked!  
   ```
3. **Verify**:

   ```python
   from agentgpt import get_llm_trace  

   trace = get_llm_trace("0x...")  
   print(f"Stored at IPFS: {trace.ipfs_cid}")  
   ```


---

# 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/tracking-llm-calls.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.
