How to implement and pass functions to the assistant? In the asynchronous streaming example from Azure

My problem is passing functions to the assistant, I don’t understand how to properly pass their result to the assistant. The results of the sending are visible in the logs, but the assistant receives that he did not receive the result and the function is currently unavailable json {"function_error": "find_and_get_doctors_info", "error": "Function is not available."}

import asyncio
import json
import os
import random

from azure.ai.assistant.management.async_assistant_client import AsyncAssistantClient
from azure.ai.assistant.management.ai_client_factory import AsyncAIClientType
from azure.ai.assistant.management.async_assistant_client_callbacks import AsyncAssistantClientCallbacks
from azure.ai.assistant.management.async_conversation_thread_client import AsyncConversationThreadClient
from azure.ai.assistant.management.async_message import AsyncConversationMessage
from azure.ai.assistant.management.text_message import TextMessage
from services.gpt_service.tools import available_functions, tools_any_b2c  # Import the available functions
from configs.openai.assistant_config import PHRASES
from services import tts_service

conversation_threads = {}

class MyAssistantClientCallbacks(AsyncAssistantClientCallbacks):
    def __init__(self, message_queue):
        self.message_queue = message_queue

    async def handle_message(self, action, message="hello"):
        await self.message_queue.put((action, message))

    async def on_run_update(self, assistant_name, run_identifier, run_status, thread_name, is_first_message=False,
                            message: AsyncConversationMessage = None):
        if run_status == "streaming":
            await self.handle_message("start" if is_first_message else "message", message.text_message.content)
        elif run_status == "completed":
            if message:
                text_message: TextMessage = message.text_message
                if text_message.file_citations:
                    for file_citation in text_message.file_citations:
                        print(
                            f"nFile citation, file_id: {file_citation.file_id}, file_name: {file_citation.file_name}")

    async def on_function_call_processed(self, assistant_name, run_identifier, function_name, arguments, response):
        await self.handle_message("function", function_name)

        if function_name in available_functions:
            try:
                args = json.loads(arguments)

                func = available_functions[function_name]
                result = await func(**args)

                await self.handle_message("function_result", json.dumps(result))
            except Exception as e:
                error_message = f"Error calling function {function_name}: {str(e)}"
                await self.handle_message("function_error", error_message)
        else:
            await self.handle_message("function_error", f"Unknown function: {function_name}")

async def display_streamed_messages(message_queue, assistant_name):
    while True:
        message_type, message = await message_queue.get()
        if message_type == "start":
            print(f"{assistant_name}: {message}", end="")
        elif message_type == "message":
            print(message, end="", flush=True)
        elif message_type == "function":
            print(f"{assistant_name}: called {message} function.")
        elif message_type == "function_result":
            print(f"Function result: {message}")
        elif message_type == "function_error":
            print(f"Function error: {message}")
        message_queue.task_done()`

`async def gpt_main(user_message, user_id):
    assistant_name = "b2c_camny"`

    try:
        with open(f"configs/azure_config/assistants/{assistant_name}_assistant_config.json", "r") as file:
            config = file.read()
    except FileNotFoundError:
        print(f"Configuration file for {assistant_name} not found.")
        return

    try:
        message_queue = asyncio.Queue()
        callbacks = MyAssistantClientCallbacks(message_queue)

        assistant_client = await AsyncAssistantClient.from_json(config, callbacks=callbacks,
                                                                api_key=os.environ["AZURE_OPENAI_API_KEY"])
        ai_client_type = AsyncAIClientType[assistant_client.assistant_config.ai_client_type]

        conversation_thread_client = AsyncConversationThreadClient.get_instance(ai_client_type)

        if user_id in conversation_threads:
            thread_name = conversation_threads[user_id]
            print(f"Reusing existing thread {thread_name} for user {user_id}")
        else:
            thread_name = await conversation_thread_client.create_conversation_thread()
            if not thread_name:
                print(f"Failed to create conversation thread for user {user_id}")
                return
            conversation_threads[user_id] = thread_name
            print(f"Created new thread {thread_name} for user {user_id}")

        await conversation_thread_client.create_conversation_thread_message(user_message, thread_name)

        print(f"Starting to process messages for thread: {thread_name}")
        await assistant_client.process_messages(thread_name=thread_name, stream=True)

        while True:
            try:
                message_type, message = await asyncio.wait_for(message_queue.get(), timeout=60)
                if message_type in ("start", "message"):
                    print(f"Message received: {message}")
                    yield message
                elif message_type == "function_result":
                    print(f"Function result received: {message}")
                    await MyAssistantClientCallbacks.on_function_call_processed()
                    await asyncio.create_task(display_streamed_messages(message_queue, assistant_name))
                elif message_type == "function_error":
                    print(f"Function error received: {message}")
                message_queue.task_done()
            except asyncio.TimeoutError:
                print(f"No messages received within the timeout period.")
                break

    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        print(f"Finished processing for thread: {thread_name}")


async def handle_message(user_message, user_id):
    async for response in gpt_main(user_message, user_id):
        print(response)

tools:

async def find_and_get_doctors_info(date: str, service: str, city: str) -> List[Dict[str, Any]]:
    print(f"ChatGPT call tool: find_and_get_doctors_info, date: {date}, service: {service}, city: {city}")

    if service == "Cardiologist":
        return [{
            "doctor_id": "12345",
            "full_name": "Dr. Olena Petrova",
            "doctor_type": "Cardiologist",
            "available_time": "10:00-14:00"
        }]
    elif service == "Dermatologist":
        return [{
            "doctor_id": "54321",
            "full_name": "Dr. Mykhaylo Ivanov",
            "doctor_type": "Dermatologist",
            "available_time": "13:00-18:00"
        }]
    elif service == "Dentist":
        return [{
            "doctor_id": "67890",
            "full_name": "Dr. Sofia Kovalenko",
            "doctor_type": "Dentist",
            "available_time": "09:00-12:00"
        }]
    elif service == "Ophthalmologist":
        return [{
            "doctor_id": "21436",
            "full_name": "Dr. Dmytro Bondarenko",
            "doctor_type": "Ophthalmologist",
            "available_time": "15:00-20:00"
        }]
    elif service == "Pediatrician":
        return [{
            "doctor_id": "85274",
            "full_name": "Dr. Anna Sidorenko",
            "doctor_type": "Pediatrician",
            "available_time": "11:00-16:00"
        }]
    elif service == "Neurologist":
        return [{
            "doctor_id": "93715",
            "full_name": "Dr. Andriy Shevchenko",
            "doctor_type": "Neurologist",
            "available_time": "14:00-19:00",
            "clinic_name": "Neuro Clinic",
        }]
    elif service == "Pulmonologist":
        return [{
            "doctor_id": "70192",
            "full_name": "Dr. Iryna Popel",
            "doctor_type": "Pulmonologist",
            "available_time": "12:00-17:00"
        }]
    elif service == "Gastroenterologist":
        return [{
            "doctor_id": "38651",
            "full_name": "Dr. Bohdan Kravchenko",
            "doctor_type": "Gastroenterologist",
            "available_time": "10:30-15:30",
            "clinic_name": "Gastro Clinic",
        }]
    elif service == "Orthopedist":
        return [{
            "doctor_id": "49573",
            "full_name": "Dr. Yulia Petrova",
            "doctor_type": "Orthopedist",
            "available_time": "08:00-13:00"
        }]
    elif service == "Urologist":
        return [{
            "doctor_id": "01289",
            "full_name": "Dr. Oleksandr Ivanov",
            "doctor_type": "Urologist",
            "available_time": "16:00-21:00"
        }]
    else:
        return [{ "result": "No doctors available for the selected service and date" }]



available_functions = {
    "find_and_get_doctors_info": find_and_get_doctors_info
}

Here is a link to the template

Description of functions was done in Azure Studio.

I tried to send the results immediately to the asynchronous message queue, but it didn’t work either, the assistant doesn’t see the results.

New contributor

TheCyberAngel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật