import httpx
import json
from openai import OpenAI
def update_base_url(request: httpx.Request) -> None:
request.url = httpx.URL(str(request.url).replace("chat/completions", "agent/responses"))
client = OpenAI(
base_url="https://your-gateway-url",
api_key="your-tfy-api-token",
http_client=httpx.Client(
event_hooks={"request": [update_base_url]}
)
)
def handle_tool_calls(delta):
"""Handle tool calls from assistant."""
global current_tool_calls
tool_calls = delta.tool_calls
for tool_call in tool_calls:
index = tool_call.index
# Initialize tool call if it's new
if index not in current_tool_calls:
current_tool_calls[index] = {
'id': '',
'function': {'name': '', 'arguments': ''},
'integration_id': '',
'tool_name': '',
'name_printed': False
}
# Update tool call with new data
if hasattr(tool_call, 'id') and tool_call.id:
current_tool_calls[index]['id'] = tool_call.id
if hasattr(tool_call, 'mcp_server_integration_id'):
current_tool_calls[index]['integration_id'] = tool_call.mcp_server_integration_id
if hasattr(tool_call, 'tool_name'):
current_tool_calls[index]['tool_name'] = tool_call.tool_name
if hasattr(tool_call, 'function') and tool_call.function:
function_data = tool_call.function
if hasattr(function_data, 'name') and function_data.name and not current_tool_calls[index]['name_printed']:
current_tool_calls[index]['function']['name'] = function_data.name
current_tool_calls[index]['name_printed'] = True
# Print tool call header
tool_call_id = current_tool_calls[index]['id'] or 'pending'
integration_id = current_tool_calls[index]['integration_id']
tool_name = current_tool_calls[index]['tool_name']
integration_info = f" (Integration: {integration_id}), Tool Name: {tool_name}" if integration_id else ""
print(f"\n[Tool Call: {tool_call_id}:{function_data.name}{integration_info}]")
print("Args: ", end='', flush=True)
if hasattr(function_data, 'arguments') and function_data.arguments:
current_tool_calls[index]['function']['arguments'] += function_data.arguments
print(function_data.arguments, end='', flush=True)
def handle_tool_result(delta):
"""Handle tool result messages."""
integration_id = getattr(delta, 'mcp_server_integration_id', '')
tool_name = getattr(delta, 'tool_name', '')
tool_call_id = getattr(delta, 'tool_call_id', '')
integration_info = f" (Integration: {integration_id}), Tool Name: {tool_name}" if integration_id else ""
print(f"\n[Tool Result: {tool_call_id}:{tool_name}{integration_info}]: ", end='', flush=True)
content = getattr(delta, 'content', '')
if content:
try:
# Try to parse the JSON to extract the actual result
result_json = json.loads(content)
if 'content' in result_json:
for item in result_json['content']:
if item.get('type') == 'text':
text = item.get('text', '')
print(text, end='', flush=True)
else:
# Just print the content as is if we can't extract text
print(content, end='', flush=True)
except json.JSONDecodeError:
# If not valid JSON, just print as is
print(content, end='', flush=True)
print() # Add newline after tool result
# Initialize tracking variables
current_tool_calls = {}
messages = []
# Stream the response
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Your message"}],
stream=True,
extra_body={
"mcp_servers": [
{
"integration_fqn": "truefoundry:hosted-mcp-server:hosted-devtest-mcp-servers:mcp-server:slack",
"enable_all_tools": False,
"tools": [{"name": "getSlackUsers"}, {"name": "findUserByEmail"}]
}
],
"iteration_limit": 10
}
)
print("Assistant: ", end='', flush=True)
for chunk in stream:
if chunk.choices:
choice = chunk.choices[0]
delta = choice.delta
finish_reason = choice.finish_reason
# Handle tool results
if hasattr(delta, 'role') and delta.role == 'tool':
handle_tool_result(delta)
continue
# Handle tool calls
if hasattr(delta, 'tool_calls') and delta.tool_calls:
handle_tool_calls(delta)
# Handle regular content
if hasattr(delta, 'content') and delta.content:
print(delta.content, end='', flush=True)
# Handle message completion
if finish_reason:
if current_tool_calls:
print() # Add newline after tool call arguments
current_tool_calls = {} # Reset for next iteration
print() # Final newline