|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Secure AI Agent with TEE Key Derivation |
| 4 | +
|
| 5 | +This agent demonstrates: |
| 6 | +- TEE-derived Ethereum wallet (deterministic, persistent) |
| 7 | +- Protected API credentials (encrypted at deploy) |
| 8 | +- Confidential LLM calls via redpill.ai |
| 9 | +- Attestation proof for execution verification |
| 10 | +""" |
| 11 | + |
| 12 | +import os |
| 13 | + |
| 14 | +from dstack_sdk import DstackClient |
| 15 | +from dstack_sdk.ethereum import to_account |
| 16 | +from eth_account.messages import encode_defunct |
| 17 | +from flask import Flask, jsonify, request |
| 18 | +from langchain_classic.agents import AgentExecutor, create_react_agent |
| 19 | +from langchain_classic.tools import Tool |
| 20 | +from langchain_openai import ChatOpenAI |
| 21 | +from langchain_core.prompts import PromptTemplate |
| 22 | + |
| 23 | +app = Flask(__name__) |
| 24 | + |
| 25 | +# Lazy initialization - only connect when needed |
| 26 | +_client = None |
| 27 | +_account = None |
| 28 | + |
| 29 | + |
| 30 | +def get_client(): |
| 31 | + """Get dstack client (lazy initialization).""" |
| 32 | + global _client |
| 33 | + if _client is None: |
| 34 | + _client = DstackClient() |
| 35 | + return _client |
| 36 | + |
| 37 | + |
| 38 | +def get_account(): |
| 39 | + """Get Ethereum account (lazy initialization).""" |
| 40 | + global _account |
| 41 | + if _account is None: |
| 42 | + client = get_client() |
| 43 | + eth_key = client.get_key("agent/wallet", "mainnet") |
| 44 | + _account = to_account(eth_key) |
| 45 | + print(f"Agent wallet address: {_account.address}") |
| 46 | + return _account |
| 47 | + |
| 48 | + |
| 49 | +def get_wallet_address(_: str = "") -> str: |
| 50 | + """Get the agent's wallet address.""" |
| 51 | + return f"Agent wallet: {get_account().address}" |
| 52 | + |
| 53 | + |
| 54 | +def get_attestation(nonce: str = "default") -> str: |
| 55 | + """Get TEE attestation quote.""" |
| 56 | + quote = get_client().get_quote(nonce.encode()[:64]) |
| 57 | + return f"TEE Quote (first 100 chars): {quote.quote[:100]}..." |
| 58 | + |
| 59 | + |
| 60 | +def sign_message(message: str) -> str: |
| 61 | + """Sign a message with the agent's wallet.""" |
| 62 | + signable = encode_defunct(text=message) |
| 63 | + signed = get_account().sign_message(signable) |
| 64 | + return f"Signature: {signed.signature.hex()}" |
| 65 | + |
| 66 | + |
| 67 | +# Define agent tools |
| 68 | +tools = [ |
| 69 | + Tool( |
| 70 | + name="GetWallet", |
| 71 | + func=get_wallet_address, |
| 72 | + description="Get the agent's Ethereum wallet address", |
| 73 | + ), |
| 74 | + Tool( |
| 75 | + name="GetAttestation", |
| 76 | + func=get_attestation, |
| 77 | + description="Get TEE attestation quote to prove secure execution", |
| 78 | + ), |
| 79 | + Tool( |
| 80 | + name="SignMessage", |
| 81 | + func=sign_message, |
| 82 | + description="Sign a message with the agent's wallet. Input: the message to sign", |
| 83 | + ), |
| 84 | +] |
| 85 | + |
| 86 | +# LangChain agent (lazy initialization) |
| 87 | +_agent_executor = None |
| 88 | + |
| 89 | + |
| 90 | +def get_agent_executor(): |
| 91 | + """Get LangChain agent executor (lazy initialization).""" |
| 92 | + global _agent_executor |
| 93 | + if _agent_executor is None: |
| 94 | + template = """You are a secure AI agent running in a Trusted Execution Environment (TEE). |
| 95 | +You have access to a deterministic Ethereum wallet derived from TEE keys. |
| 96 | +Your wallet address and signing capabilities are protected by hardware. |
| 97 | +
|
| 98 | +You have access to the following tools: |
| 99 | +{tools} |
| 100 | +
|
| 101 | +Use the following format: |
| 102 | +Question: the input question |
| 103 | +Thought: think about what to do |
| 104 | +Action: the action to take, should be one of [{tool_names}] |
| 105 | +Action Input: the input to the action |
| 106 | +Observation: the result of the action |
| 107 | +... (repeat Thought/Action/Action Input/Observation as needed) |
| 108 | +Thought: I now know the final answer |
| 109 | +Final Answer: the final answer |
| 110 | +
|
| 111 | +Question: {input} |
| 112 | +{agent_scratchpad}""" |
| 113 | + |
| 114 | + prompt = PromptTemplate.from_template(template) |
| 115 | + |
| 116 | + # Use redpill.ai for confidential LLM calls (OpenAI-compatible API) |
| 117 | + llm = ChatOpenAI( |
| 118 | + model=os.environ.get("LLM_MODEL", "openai/gpt-4o-mini"), |
| 119 | + base_url=os.environ.get("LLM_BASE_URL", "https://api.redpill.ai/v1"), |
| 120 | + api_key=os.environ.get("LLM_API_KEY", ""), |
| 121 | + temperature=0, |
| 122 | + ) |
| 123 | + |
| 124 | + agent = create_react_agent(llm, tools, prompt) |
| 125 | + _agent_executor = AgentExecutor( |
| 126 | + agent=agent, tools=tools, verbose=True, handle_parsing_errors=True |
| 127 | + ) |
| 128 | + return _agent_executor |
| 129 | + |
| 130 | + |
| 131 | +@app.route("/") |
| 132 | +def index(): |
| 133 | + """Agent info endpoint.""" |
| 134 | + try: |
| 135 | + info = get_client().info() |
| 136 | + return jsonify( |
| 137 | + { |
| 138 | + "status": "running", |
| 139 | + "wallet": get_account().address, |
| 140 | + "app_id": info.app_id, |
| 141 | + } |
| 142 | + ) |
| 143 | + except Exception: |
| 144 | + return jsonify({"status": "running", "error": "Failed to retrieve agent info"}) |
| 145 | + |
| 146 | + |
| 147 | +@app.route("/attestation") |
| 148 | +def attestation(): |
| 149 | + """Get TEE attestation.""" |
| 150 | + nonce = request.args.get("nonce", "default") |
| 151 | + quote = get_client().get_quote(nonce.encode()[:64]) |
| 152 | + return jsonify({"quote": quote.quote, "nonce": nonce}) |
| 153 | + |
| 154 | + |
| 155 | +@app.route("/chat", methods=["POST"]) |
| 156 | +def chat(): |
| 157 | + """Chat with the agent.""" |
| 158 | + data = request.get_json() |
| 159 | + message = data.get("message", "") |
| 160 | + |
| 161 | + if not message: |
| 162 | + return jsonify({"error": "No message provided"}), 400 |
| 163 | + |
| 164 | + try: |
| 165 | + result = get_agent_executor().invoke({"input": message}) |
| 166 | + return jsonify( |
| 167 | + { |
| 168 | + "response": result["output"], |
| 169 | + "wallet": get_account().address, |
| 170 | + } |
| 171 | + ) |
| 172 | + except Exception: |
| 173 | + return jsonify({"error": "Failed to process chat request"}), 500 |
| 174 | + |
| 175 | + |
| 176 | +@app.route("/sign", methods=["POST"]) |
| 177 | +def sign(): |
| 178 | + """Sign a message with the agent's wallet.""" |
| 179 | + data = request.get_json() |
| 180 | + message = data.get("message", "") |
| 181 | + |
| 182 | + if not message: |
| 183 | + return jsonify({"error": "No message provided"}), 400 |
| 184 | + |
| 185 | + signable = encode_defunct(text=message) |
| 186 | + signed = get_account().sign_message(signable) |
| 187 | + return jsonify( |
| 188 | + { |
| 189 | + "message": message, |
| 190 | + "signature": signed.signature.hex(), |
| 191 | + "signer": get_account().address, |
| 192 | + } |
| 193 | + ) |
| 194 | + |
| 195 | + |
| 196 | +if __name__ == "__main__": |
| 197 | + print("Starting agent server...") |
| 198 | + app.run(host="0.0.0.0", port=8080) |
0 commit comments