Send tasks and handle tool calls
To give an agent a task, send a message to a session. If the session is idle, the message starts a turn, one round of work. If a turn is already running, the agent uses the new message to adjust the work in progress.
The turn runs in the background. Your app can open an event stream, a connection over which the API sends updates as work happens. One of those updates can be a request to run a function tool, a function in your app that the agent can call.
Messages, function calls, and results
Your app uses /v1/agents/sessions/{session_id}/events in both directions. A GET opens the stream. Separate POST requests send messages and tool results.
- A message. Open the stream before posting
agent.session.input.messageso you receive the first updates. An idempotency key is a unique ID that lets the API recognize a retry. Save it with the message and send it in theIdempotency-Keyheader. If you miss the HTTP response, resend the same message and key to the same session. - A request for action. The event
agent.session.requires_actiontells you the agent needs something from your app. For a function call,session.required_actionslists the function name and arguments. Your app checks permissions and arguments before running the function. - A function result. Send the output or error as
agent.session.input.tool_result. Theturn_idandcall_idtell the API which pending call the result answers. Once all required results arrive, the turn can continue.
HTTP 202 confirms that the API accepted your input. The turn events report the outcome later. The turn’s final status can be completed, failed, or cancelled. If the stream disconnects, retrieve the saved work and pending actions. The stream doesn’t replay missed events.
Example: Find the request behind a finance report
Herringbone’s app sends an agent.session.input.message event to Customer A’s session (sess_a). In the diagram, the message with role: "user" contains the task from Herringbone. The agent requests get_integration_context to see how the job fetches payments. The function takes no arguments. Herringbone uses sess_a to identify the integration and checks that Customer A has authorized access to its records.
The lookup finds the request to Herringbone’s payments API, GET /v1/payments?limit=100, in exports/nightly.http. It also returns the column names finance expects, payment_id and amount. Herringbone saves the result and posts it to sess_a with turn_id set to turn_plan and call_id set to call_context. These IDs match the pending call in the diagram.
The integration notes show that the job makes just one request each night. In its reply, the agent recommends reading next_cursor after processing each page. If it has a value, the job should send it back as the cursor parameter on the next request. It should repeat until there’s no next cursor.
Saving the function result lets Herringbone resend it after a disconnect if the call is still pending. This matters especially for functions that write data. If a write may have succeeded but there’s no saved result, check what changed before running it again.
These Python excerpts follow one turn of the review. Full program combines them in one runnable file.
Here, sessions is OpenAI().beta.agents.sessions. Herringbone opens the event stream before sending the message. When the session needs a function result, the loop passes each pending call to answer_call and keeps listening until the turn ends.
def review_export(sessions, session_id, authorized_exports):
task = """Herringbone now returns payments one page at a time.
Send next_cursor back as cursor to fetch the next page.
Review Customer A's nightly export. What should the customer change?"""
message = {
"type": "agent.session.input.message",
"input": [{"role": "user", "content": [{"type": "input_text", "text": task}]}],
}
key = str(uuid4())
results = {}
with sessions.events.stream(session_id) as events:
sessions.events.create(session_id, events=[message], idempotency_key=key)
for event in events:
if event.type == "agent.session.requires_action":
for call in event.session.required_actions:
answer_call(sessions, session_id, call, authorized_exports, results)
elif event.type == "agent.session.turn.completed":
return event.turn.id
elif event.type in {
"agent.session.turn.failed",
"agent.session.turn.cancelled",
"agent.session.failed",
"error",
}:
raise RuntimeError(event.type)
raise RuntimeError("The stream closed before the turn finished.")authorized_exports maps each session ID to the export records Herringbone may read. The agent supplies no customer ID. Herringbone checks the function name, arguments, and access, then returns the result with the IDs from the pending call.
def answer_call(sessions, session_id, call, authorized_exports, results):
if call.type != "function_call":
raise ValueError("Unexpected action")
identity = (session_id, call.turn_id, call.call_id)
result = {
"type": "agent.session.input.tool_result",
"turn_id": call.turn_id,
"call_id": call.call_id,
}
if call.name != "get_integration_context" or call.arguments != {}:
result.update(success=False, error="Unknown function or unexpected arguments.")
elif session_id not in authorized_exports:
result.update(success=False, error="No export authorized for this session.")
else:
if identity not in results:
results[identity] = json.dumps(authorized_exports[session_id])
result.update(success=True, output=results[identity])
sessions.events.create(session_id, events=[result])Set OPENAI_API_KEY and copy the program into review-payment-export.py. With the Python package manager uv, run uv run --with openai==3.57.0 python review-payment-export.py.
The program creates a temporary session with an OpenAI-hosted workspace and disables network access from the workspace. Your Python process handles the lookup using sample records, so you don’t need GitHub credentials. The program prints the agent’s recommendation for exports/nightly.http and deletes the session.
The example keeps the message, key, and function results in memory. To recover after a restart, store them in your app’s database and keep the session.
import json
from uuid import uuid4
from openai import OpenAI
def review_export(sessions, session_id, authorized_exports):
task = """Herringbone now returns payments one page at a time.
Send next_cursor back as cursor to fetch the next page.
Review Customer A's nightly export. What should the customer change?"""
message = {
"type": "agent.session.input.message",
"input": [{"role": "user", "content": [{"type": "input_text", "text": task}]}],
}
key = str(uuid4())
results = {}
with sessions.events.stream(session_id) as events:
sessions.events.create(session_id, events=[message], idempotency_key=key)
for event in events:
if event.type == "agent.session.requires_action":
for call in event.session.required_actions:
answer_call(sessions, session_id, call, authorized_exports, results)
elif event.type == "agent.session.turn.completed":
return event.turn.id
elif event.type in {
"agent.session.turn.failed",
"agent.session.turn.cancelled",
"agent.session.failed",
"error",
}:
raise RuntimeError(event.type)
raise RuntimeError("The stream closed before the turn finished.")
def answer_call(sessions, session_id, call, authorized_exports, results):
if call.type != "function_call":
raise ValueError("Unexpected action")
identity = (session_id, call.turn_id, call.call_id)
result = {
"type": "agent.session.input.tool_result",
"turn_id": call.turn_id,
"call_id": call.call_id,
}
if call.name != "get_integration_context" or call.arguments != {}:
result.update(success=False, error="Unknown function or unexpected arguments.")
elif session_id not in authorized_exports:
result.update(success=False, error="No export authorized for this session.")
else:
if identity not in results:
results[identity] = json.dumps(authorized_exports[session_id])
result.update(success=True, output=results[identity])
sessions.events.create(session_id, events=[result])
def main():
sessions = OpenAI().beta.agents.sessions
session = sessions.create(
agent={
"model": "gpt-6.2-astra",
"instructions": """You are a forward-deployed engineer for Herringbone.
Call get_integration_context once before reviewing an API change.
Tell the customer which file is affected, why, and what to update.
Propose changes only. If the lookup fails, report the error.""",
"tools": [
{
"type": "function",
"name": "get_integration_context",
"description": "Read the integration records for this session.",
"parameters": {
"type": "object",
"properties": {},
"additionalProperties": False,
},
}
],
},
environment={"type": "openai_hosted", "network": {"access": "disabled"}},
)
try:
# Customer A authorized this session to read only its export.
authorized_exports = {
session.id: {
"path": "exports/nightly.http",
"code": "GET /v1/payments?limit=100",
"output_columns": ["payment_id", "amount"],
"notes": [
"The finance team's export makes this request once each night."
],
}
}
turn_id = review_export(sessions, session.id, authorized_exports)
items = sessions.turns.items.list(turn_id, session_id=session.id, order="desc")
for item in items:
if item.type == "message" and item.role == "assistant":
if item.phase != "commentary" and item.output_text:
print(item.output_text)
return
raise RuntimeError("The turn completed without a text reply.")
finally:
sessions.delete(session.id)
if __name__ == "__main__":
main()