-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.py
86 lines (63 loc) · 1.78 KB
/
app.py
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from web3_copilot.agent import Web3CopilotAgent
from council.agents import AgentResult
from flask import Flask, request
import json
app = Flask(__name__)
agent = Web3CopilotAgent()
@app.route("/")
def index():
return "Welcome to Web3 Copilot! Powered by Council AI from ChainML."
"""
Sample Request -
{
"prompt": "Why would one use the Cosmos SDK?"
}
Sample Response -
{
"best_message": {
"data": null,
"kind": "AGENT",
"message": "One would use the Cosmos SDK because ..."
},
"messages": [
{
"message": {
"data": null,
"kind": "AGENT",
"message": "One would use the Cosmos SDK because ..."
},
"score": 10
}
]
}
"""
@app.route("/chat", methods=["POST"])
def chat():
req_data = request.get_json()
prompt = req_data["prompt"]
print(f"request:\n{prompt}")
agent_response = agent.interact(prompt)
response = serialize_agent_response(agent_response)
print(f"response:\n{response}")
return response
def serialize_agent_response(agent_response: AgentResult):
response = {
"messages": [],
"best_message": {}
}
for scored_msg in agent_response.messages:
score = scored_msg.score
message = to_json(scored_msg.message)
response["messages"].append({
"score": score,
"message": message
})
best_message = agent_response.try_best_message.unwrap()
response["best_message"] = to_json(best_message)
return response
def to_json(obj):
serialized = json.dumps(obj, default=lambda o: o.__dict__,
sort_keys=True, indent=4)
return json.loads(serialized)
if __name__ == '__main__':
app.run(port=8000, debug=True)