How can I use function_tool with llm to call custo...
# ask-ai
a
How can I use function_tool with llm to call custom function and in chat_context how to add my messages of function call?
t
Thanks for reaching out, giri. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To use
function_tool
with LLM for calling custom functions and managing chat context, follow these steps: 1. Define Custom Functions: Use the
@function_tool
decorator to define your custom functions. For example:
Copy code
from livekit.agents import function_tool

@function_tool
def get_current_time(timezone: str = "UTC") -> str:
    """Get the current time in the specified timezone"""
    from datetime import datetime
    import pytz
    
    tz = pytz.timezone(timezone)
    return datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S %Z")
2. Use Functions with LLM: Pass your function tools to the LLM's chat method along with the chat context:
Copy code
# Create chat context
chat_ctx = ChatContext()
chat_ctx.add_message(role="user", content="What time is it in New York?")

# Get response with function calling
async with llm.chat(chat_ctx=chat_ctx, tools=[get_current_time]) as stream:
    async for chunk in stream:
        # Handle function calls and response chunks
        pass
3. Automatic Chat Context Management: Function calls and their outputs are automatically added to the chat context. The system tracks: • FunctionCall: Represents the LLM's request to call a function • FunctionCallOutput: Contains the result of the function execution • ChatMessage: Regular messages from users and assistants 4. Function Call Flow: 1. LLM receives chat context with function definitions 2. LLM decides to call a function and sends a function call request 3. Your application executes the function 4. Function result is sent back to the LLM 5. LLM continues with the function result to generate the final response 5. Adding Function Messages to Chat Context: Function calls and outputs are automatically included in the chat context:
Copy code
# Function calls and outputs are automatically added to chat_ctx.items
tool_messages = new_calls + new_fnc_outputs
if generate_tool_reply:
    chat_ctx.items.extend(tool_messages)
By following these steps, you can effectively integrate custom functions with LLM and manage their interactions within the chat context. Sources: LLM Integrations | livekit/livekit_composite | DeepWiki | livekit-agents/livekit/agents/llm/_provider_format/openai.py | complex-agents/personal_shopper/personal_shopper.py
a
At start while merging chat context function call message and output is set to false after making it true is this issue resolved
t
Hey there! I'd love to help you get to the bottom of this. Could you tell me a bit more about the specific parameters or settings you're looking to adjust? And what challenges are you running into when trying to merge the chat context? The more details you can share, the better I can support you. Sources: livekit-agents/livekit/agents/llm/_provider_format/openai.py | complex-agents/personal_shopper/personal_shopper.py
a
As the messages are maintained separately and created separately for different channels when they are merged some parameters are set to false and does created_at mentions the time of creation?
t
Hey there! Let me break down how merging messages from different channels works in a way that's super easy to understand. 1. Parameters Set to False During Merging: When you're using the
merge
method in the
ChatContext
class, you've got some cool options to filter what gets included: • `exclude_function_call`: Want to keep function calls out? Just set this to
True
. • `exclude_instructions`: If you'd rather not merge system or developer messages, this parameter has got your back. 2. The
created_at
Field:
Think of
created_at
like a timestamp that remembers exactly when a message was born. It's set up like this:
Copy code
created_at: float = Field(default_factory=time.time)
It uses
time.time()
to capture the precise moment of creation - pretty neat, right? 3. Merge Process and Chronological Ordering: The system is super smart about keeping things in order. Check out how it makes sure messages stay in the right sequence:
Copy code
if item.id not in existing_ids:
    idx = self.find_insertion_index(created_at=item.created_at)
    self._items.insert(idx, item)
This ensures your messages are always lined up just the way they should be, preserving their original timeline. By understanding these little details, you'll be a pro at managing message merges and keeping track of when things actually happened. Hope this helps make things crystal clear! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real...