https://www.boundaryml.com logo
Hello, how do I handle function calling
# questions
c
Hello, how do I handle function calling in the context of BAML? Also like below? [ { "role": "system", "content": "You are a helpful assistant..." }, { "role": "user", "content": "Can you deploy the backend?" }, { "role": "assistant", "content": null, "tool_calls": [ { "id": "1", "name": "list_git_tags", "arguments": "{}" } ] }, { "role": "tool", "name": "list_git_tags", "content": "{\"tags\": [{\"name\": \"v1.2.3\", \"commit\": \"abc123\", \"date\": \"2024-03-15T10:00:00Z\"}, {\"name\": \"v1.2.2\", \"commit\": \"def456\", \"date\": \"2024-03-14T15:30:00Z\"}, {\"name\": \"v1.2.1\", \"commit\": \"abe033d\", \"date\": \"2024-03-13T09:15:00Z\"}]}", "tool_call_id": "1" } ]
v
c
I don't find anything about function context process
v
In BAML, function calling is handled by defining a class that represents your tool/function and then creating a BAML function that returns that class. Here's how you'd do it:
Copy code
// Define your tool schema
class GitTool {
  // Specify the tool name
  action "list_git_tags"
  // Add any parameters your tool needs
  tags Tag[]
}

class Tag {
  name string
  commit string
  date string
}

class Message {
  role "user" | "assistant" | "tool"
  content string?
  tool_calls GitTool?
}

class Reply {
   action "reply"
   message string
}

function ChatWithTools(messages: Message[]) -> GitTool | Reply {
  client "openai/gpt-4o"
  prompt #"
    You are a helpful assistant that can use tools.
    {{ ctx.output_format }}

    {% for m in messages %}
    {{ _.role(m.role) }}
    {{ m.content }}
    {{ m.tool_calls }}
    {% endfor %}
  "#
}
You can then use this in your code to handle the conversation flow.
then in python you just do something like this: Here's a basic Python loop for handling tool-based conversations in BAML:
Copy code
python
from baml_client import b
from baml_client.types import Message, GitTool

def handle_git_tool(tool: GitTool):
    # Implement your git tool logic here
    return {"tags": [{"name": "v1.2.3", "commit": "abc123", "date": "2024-03-15T10:00:00Z"}]}

def main():
    messages = []
    while True:
        user_input = input("You: ")
        if user_input.lower() == 'exit':
            break

        # Add user message
        messages.append({"role": "user", "content": user_input})
        
        # Get assistant response
        response = b.ChatWithTools(messages)
        
        # If tool was called, handle it
        if isinstance(response, GitTool):
            tool_result = handle_git_tool(response)
            messages.append({"role": "tool", "tool_calls": response})                    messages.append({"role": "tool", "content": str(tool_result)})
        else:
            messages.append({"role": "assistant", "content": response})
        
        print(f"Assistant: {response}")

if __name__ == "__main__":
    main()
c
Got it! Thank you!