-
Notifications
You must be signed in to change notification settings - Fork 76
feat: add AWS Bedrock function calling implementation #120
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+2,227
−1,769
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
9061d57
Add AWS Bedrock function calling implementation
d3xvn b1fca95
Update converse format. Verbose logging
Nash0x7E2 23f6d01
Clean up for LLM
Nash0x7E2 32cdc56
Working realtime function calling (pre cleanup)
Nash0x7E2 2dba995
Merge branch 'main' into feat/aws-fc
Nash0x7E2 eb31eaa
Squashed commit of the following:
Nash0x7E2 91732f2
Lint and formatting after merge
Nash0x7E2 babfe63
Remove resample_audio in favor of PCM.resample
Nash0x7E2 17839ea
Migrate RealtimeAudioOutputEvent to _emit_audio_output_event
Nash0x7E2 5914a7e
unused import
Nash0x7E2 e37f4b7
Merge remote-tracking branch 'origin/main' into feat/aws-fc
d3xvn 0828afe
Fix linting: remove unused imports
d3xvn 30637a4
Clean up excessive logging in AWS Bedrock realtime
d3xvn 9c0b4ee
Fix mypy type errors in AWS LLM plugin
d3xvn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import asyncio | ||
| import logging | ||
| from uuid import uuid4 | ||
|
|
||
| from dotenv import load_dotenv | ||
|
|
||
| from vision_agents.core import User | ||
| from vision_agents.core.agents import Agent | ||
| from vision_agents.plugins import aws, getstream, cartesia, deepgram | ||
|
|
||
| load_dotenv() | ||
|
|
||
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s [call_id=%(call_id)s] %(name)s: %(message)s") | ||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| async def start_agent() -> None: | ||
| agent = Agent( | ||
| edge=getstream.Edge(), | ||
| agent_user=User(name="Weather Bot"), | ||
| instructions="You are a helpful weather bot. Use the provided tools to answer questions.", | ||
| llm=aws.LLM( | ||
| model="anthropic.claude-3-sonnet-20240229-v1:0", | ||
| region_name="us-east-1" | ||
|
|
||
| ), | ||
| tts=cartesia.TTS(), | ||
| stt=deepgram.STT(), | ||
| # turn_detection=smart_turn.TurnDetection(buffer_duration=2.0, confidence_threshold=0.5), | ||
| ) | ||
|
|
||
| # Register custom functions | ||
| @agent.llm.register_function( | ||
| name="get_weather", | ||
| description="Get the current weather for a given city" | ||
| ) | ||
| def get_weather(city: str) -> dict: | ||
| """Get weather information for a city.""" | ||
| logger.info(f"Tool: get_weather called for city: {city}") | ||
| if city.lower() == "boulder": | ||
| return {"city": city, "temperature": 72, "condition": "Sunny"} | ||
| return {"city": city, "temperature": "unknown", "condition": "unknown"} | ||
|
|
||
| @agent.llm.register_function( | ||
| name="calculate", | ||
| description="Performs a mathematical calculation" | ||
| ) | ||
| def calculate(expression: str) -> dict: | ||
| """Performs a mathematical calculation.""" | ||
| logger.info(f"Tool: calculate called with expression: {expression}") | ||
| try: | ||
| result = eval(expression) # DANGER: In a real app, use a safer math evaluator! | ||
| return {"expression": expression, "result": result} | ||
| except Exception as e: | ||
| return {"expression": expression, "error": str(e)} | ||
|
|
||
| await agent.create_user() | ||
|
|
||
| call = agent.edge.client.video.call("default", str(uuid4())) | ||
| await agent.edge.open_demo(call) | ||
|
|
||
| with await agent.join(call): | ||
| # Give the agent a moment to connect | ||
| await asyncio.sleep(5) | ||
|
|
||
| # Test function calling with weather | ||
| logger.info("Testing weather function...") | ||
| await agent.llm.simple_response( | ||
| text="What's the weather like in Boulder? Please use the get_weather function." | ||
| ) | ||
|
|
||
| await asyncio.sleep(5) | ||
|
|
||
| # Test function calling with calculation | ||
| logger.info("Testing calculation function...") | ||
| await agent.llm.simple_response( | ||
| text="Can you calculate 25 multiplied by 4 using the calculate function?" | ||
| ) | ||
|
|
||
| await asyncio.sleep(5) | ||
|
|
||
| # Wait a bit before finishing | ||
| await asyncio.sleep(5) | ||
| await agent.finish() | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(start_agent()) | ||
|
|
||
128 changes: 128 additions & 0 deletions
128
plugins/aws/example/aws_realtime_function_calling_example.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| import asyncio | ||
| import logging | ||
| from uuid import uuid4 | ||
|
|
||
| from dotenv import load_dotenv | ||
|
|
||
| from vision_agents.core import User | ||
| from vision_agents.core.agents import Agent | ||
| from vision_agents.plugins import aws, getstream | ||
|
|
||
| load_dotenv() | ||
|
|
||
| logging.basicConfig( | ||
| level=logging.INFO, | ||
| format="%(asctime)s %(levelname)s [call_id=%(call_id)s] %(name)s: %(message)s" | ||
| ) | ||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| async def start_agent() -> None: | ||
| """Example demonstrating AWS Bedrock realtime with function calling. | ||
|
|
||
| This example creates an agent that can call custom functions to get | ||
| weather information and perform calculations. | ||
| """ | ||
|
|
||
| # Create the agent with AWS Bedrock Realtime | ||
| agent = Agent( | ||
| edge=getstream.Edge(), | ||
| agent_user=User(name="Weather Assistant AI"), | ||
| instructions="""You are a helpful weather assistant. When users ask about weather, | ||
| use the get_weather function to fetch current conditions. You can also help with | ||
| simple calculations using the calculate function.""", | ||
| llm=aws.Realtime( | ||
| model="amazon.nova-sonic-v1:0", | ||
| region_name="us-east-1", | ||
| ), | ||
| ) | ||
|
|
||
| # Register custom functions that the LLM can call | ||
| @agent.llm.register_function( | ||
| name="get_weather", | ||
| description="Get the current weather for a given city" | ||
| ) | ||
| def get_weather(city: str) -> dict: | ||
| """Get weather information for a city. | ||
|
|
||
| Args: | ||
| city: The name of the city | ||
|
|
||
| Returns: | ||
| Weather information including temperature and conditions | ||
| """ | ||
| # This is a mock implementation - in production you'd call a real weather API | ||
| weather_data = { | ||
| "Boulder": {"temp": 72, "condition": "Sunny", "humidity": 30}, | ||
| "Seattle": {"temp": 58, "condition": "Rainy", "humidity": 85}, | ||
| "Miami": {"temp": 85, "condition": "Partly Cloudy", "humidity": 70}, | ||
| } | ||
|
|
||
| city_weather = weather_data.get(city, {"temp": 70, "condition": "Unknown", "humidity": 50}) | ||
| return { | ||
| "city": city, | ||
| "temperature": city_weather["temp"], | ||
| "condition": city_weather["condition"], | ||
| "humidity": city_weather["humidity"], | ||
| "unit": "Fahrenheit" | ||
| } | ||
|
|
||
| @agent.llm.register_function( | ||
| name="calculate", | ||
| description="Perform a mathematical calculation" | ||
| ) | ||
| def calculate(operation: str, a: float, b: float) -> dict: | ||
| """Perform a calculation. | ||
|
|
||
| Args: | ||
| operation: The operation to perform (add, subtract, multiply, divide) | ||
| a: First number | ||
| b: Second number | ||
|
|
||
| Returns: | ||
| Result of the calculation | ||
| """ | ||
| operations = { | ||
| "add": lambda x, y: x + y, | ||
| "subtract": lambda x, y: x - y, | ||
| "multiply": lambda x, y: x * y, | ||
| "divide": lambda x, y: x / y if y != 0 else None, | ||
| } | ||
|
|
||
| if operation not in operations: | ||
| return {"error": f"Unknown operation: {operation}"} | ||
|
|
||
| result = operations[operation](a, b) | ||
| if result is None: | ||
| return {"error": "Cannot divide by zero"} | ||
|
|
||
| return { | ||
| "operation": operation, | ||
| "a": a, | ||
| "b": b, | ||
| "result": result | ||
| } | ||
|
|
||
| # Create and start the agent | ||
| await agent.create_user() | ||
|
|
||
| call = agent.edge.client.video.call("default", str(uuid4())) | ||
| await agent.edge.open_demo(call) | ||
|
|
||
| with await agent.join(call): | ||
| # Give the agent a moment to connect | ||
| await asyncio.sleep(5) | ||
|
|
||
| await agent.llm.simple_response( | ||
| text="What's the weather like in Boulder? Please use the get_weather function." | ||
| ) | ||
|
|
||
| # Wait for AWS Nova to process the request and call the function | ||
| await asyncio.sleep(15) | ||
|
|
||
| await agent.finish() | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(start_agent()) | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,22 +1,22 @@ | ||
| [project] | ||
| name = "gemini-live-realtime-example" | ||
| name = "aws-bedrock-realtime-example" | ||
| version = "0.0.0" | ||
| requires-python = ">=3.10" | ||
| requires-python = ">=3.12" | ||
d3xvn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # put only what this example needs | ||
| dependencies = [ | ||
| "python-dotenv>=1.0", | ||
| "vision-agents-plugins-gemini", | ||
| "vision-agents-plugins-aws", | ||
| "vision-agents-plugins-getstream", | ||
| "vision-agents", | ||
| "google-genai>=1.33.0", | ||
| "boto3>=1.26.0", | ||
| "opentelemetry-exporter-otlp>=1.37.0", | ||
| "opentelemetry-exporter-prometheus>=0.58b0", | ||
| "prometheus-client>=0.23.1", | ||
| "opentelemetry-sdk>=1.37.0", | ||
| ] | ||
|
|
||
| [tool.uv.sources] | ||
| "vision-agents-plugins-getstream" = {path = "../../../plugins/getstream", editable=true} | ||
| "vision-agents-plugins-gemini" = {path = "../../../plugins/gemini", editable=true} | ||
| "vision-agents-plugins-getstream" = {path = "../../getstream", editable=true} | ||
| "vision-agents-plugins-aws" = {path = "..", editable=true} | ||
| "vision-agents" = {path = "../../../agents-core", editable=true} | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.