-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcustom_connector_example.py
More file actions
72 lines (56 loc) · 1.76 KB
/
custom_connector_example.py
File metadata and controls
72 lines (56 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from eth_account import Account
from mscp import Chat2Web3
from custom_connector import CustomConnector
from dotenv import load_dotenv
import os
try:
from openai import OpenAI
except ImportError:
raise ImportError(
"you need to install openai, please run `pip install openai`"
)
load_dotenv()
# Create a connector to connect to the component
custom_connector = CustomConnector(
"http://localhost:8545", # RPC of the component network
"0xE5BA7084738747631baFb38b1226C501784c90c2", # component address
Account.from_key(os.getenv("EVM_PRIVATE_KEY")),
)
# Create a Chat2Web3 instance
chat2web3 = Chat2Web3([custom_connector])
# Create a client for OpenAI
client = OpenAI(api_key=os.getenv("OPENAI_KEY"), base_url=os.getenv("OPENAI_API_BASE"))
# Set up the conversation
messages = [
{
"role": "user",
"content": "get eth price",
}
]
# Add the chat2web3 to the tools
params = {
"model": "gpt-3.5-turbo",
"messages": messages,
"tools": chat2web3.functions,
}
# Start the conversation
response = client.chat.completions.create(**params)
# Get the function message
func_msg = response.choices[0].message
# fliter out chat2web3 function
if func_msg.tool_calls and chat2web3.has(func_msg.tool_calls[0].function.name):
# execute the function from llm
function_result = chat2web3.call(func_msg.tool_calls[0].function)
messages.extend(
[
func_msg,
{
"role": "tool",
"tool_call_id": func_msg.tool_calls[0].id,
"content": function_result,
},
]
)
# Model responds with final answer
response = client.chat.completions.create(model="gpt-4o", messages=messages)
print(response.choices[0].message.content)