communication between two uAgents and Flask API #494
Closed
Data-Scientist-Sahil
started this conversation in
General
Replies: 1 comment 1 reply
-
The code below is working fine for us, please make sure the version of the pip install uagents==0.14.0 from flask import Flask, render_template, request, jsonify
import asyncio
from uagents import Agent, Context, Model
from uagents.query import query
from uagents.envelope import Envelope
import json
app = Flask(__name__)
# Model classes for the agent
class Quote(Model):
feeling: str
context: str
class Response(Model):
response: str
# Hardcoded address of the quote agent
quote_address = "agent1q249x2snexu4f6am4rnk4e8dmuw9sqj7x886e7ydp35rnuqqgf9pu5p7yev"
# Route for the main page
@app.route('/')
def index():
return render_template('index.html')
# Route for handling user input and getting response from the agent
@app.route('/get_quote', methods=['POST'])
def get_quote():
feeling = request.form['feeling']
context = request.form.get('context', "")
# Sending and receiving response from the agent
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
response = loop.run_until_complete(query_agent(feeling, context))
# Debugging statement to print the response object
print(f"Response received: {response}")
# Check if the response has the expected structure
if isinstance(response, dict) and 'response' in response:
return jsonify({'response': response['response'], 'context': context})
else:
return jsonify({'response': 'No valid response received', 'context': ""})
# Function to interact with the agent
async def query_agent(feeling, context):
response = await query(destination=quote_address, message=Quote(feeling=feeling, context=context), timeout=15.0)
if isinstance(response, Envelope):
data = json.loads(response.decode_payload())
return data
return {"response": "Error occurred while querying the agent"}
if __name__ == '__main__':
app.run(debug=True, port=8004) Here are the logs:
quote.py import os
from uagents import Agent, Context, Model
class Quote(Model):
feeling: str # Represents the user's feeling or problem
context : str
class Response(Model):
response: str # Represents the response from the coach
quote = Agent(
name="quote",
port=8001,
seed="QuoteAgent - Team Clutch",
endpoint=["http://127.0.0.1:8001/submit"]
)
# Print the agent's address for reference
print(quote.address)
@quote.on_query(model=Quote)
async def handle_message(ctx: Context, sender: str, msg: Quote):
# Define the prompt template without context
ctx.logger.info(f"Received message from {sender}: {msg}")
coach_response = "I am working"
ctx.logger.info(f"Coach response: {coach_response}")
try:
# Send the coach's response back to the sender
await ctx.send(sender, Response(response=coach_response))
except Exception as e:
ctx.logger.error(f"Failed to send response: {e}")
# Run the agent
if __name__ == "__main__":
quote.run() Here are the logs:
Please reach out to us if you need further assistance! |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
We are stuck on this problem and therefore unable to integrate our backend and frontend services and the submission of hackathon round 1 is stuck. Fetach AI X IIT Guwahati.
When we hit the code with app.py it is not able to accept the message from flask server but the secondary uagent quote.py is working and even sending the message. We are confused.
this is my app.py
this is my quote.py
so after i run the quote.py and app.py , the logging information from quote.py informs that the message was received and the message was sent back to app.py , but the logging information from app.py says that initial user request never reached the app.py
Loggings of quote.py
-> INFO: [quote]: Almanac registration is up to date!
INFO: [quote]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit)
INFO: [quote]: recieved message : user1nu5nm9uvd9z3zd92k9ql00dvnf4kkpdkn3f99423d527j57tseusefvjam
INFO: [quote]: I am working
Loggings of app.py
-> ERROR: [dispenser]: Failed to deliver message to agent1q249x2snexu4f6am4rnk4e8dmuw9sqj7x886e7ydp35rnuqqgf9pu5p7yev @ ['http://127.0.0.1:8001/submit']: ['Failed to send message: Envelope signature is missing']
MsgStatus(status=<DeliveryStatus.FAILED: 'failed'>, detail='Message delivery failed', destination='agent1q249x2snexu4f6am4rnk4e8dmuw9sqj7x886e7ydp35rnuqqgf9pu5p7yev', endpoint='', session=UUID('3e8df0a8-85c2-4cef-9044-ac4e37b1b4aa'))
Response received: None
INFO:werkzeug:127.0.0.1 - - [09/Aug/2024 12:52:43] "POST /get_quote HTTP/1.1" 500 -
(traceback call info)
return jsonify({'response': response['response'], 'context': ""})
TypeError: 'NoneType' object is not subscriptable
please help us asap via connecting with us.
Beta Was this translation helpful? Give feedback.
All reactions