This project demonstrates the implementation of AI function calling using the OpenAI-compatible API interface. It allows you to create tools that can be invoked by an AI model during conversation, enabling the AI to perform specific tasks such as retrieving real-time weather information.
- Integration with OpenAI-compatible APIs (DashScope)
- Implementation of function calling with AI models
- Weather lookup tool for retrieving current weather and forecast information
- Conversation history management
- Multiple tool invocation in a single conversation
- Go (1.18 or higher)
- OpenAI-compatible API access (e.g., DashScope API key)
-
Clone the repository
git clone https://github.com/yourusername/function-calling.git cd function-calling -
Install dependencies
go mod download
-
Configure environment variables Copy the
.env.templatefile to.envand update with your API credentials:cp .env.template .env
Then modify the
.envfile with your specific values:DASH_SCOPE_API_KEY="your-api-key-here" DASH_SCOPE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1" DASH_SCOPE_MODEL="qwen-turbo"
Run the application:
go run main.goThe example in main.go demonstrates how to:
- Define a weather tool
- Send a user query to the AI
- Process the AI's decision to call a function
- Execute the function and return the results
- Generate a final response incorporating the function results
The provided example asks for the current weather in Shenzhen and whether it's suitable for outdoor activities. The AI:
- Recognizes that weather information is needed
- Calls the GetWeather function with appropriate parameters
- Receives the weather data
- Generates a response based on the weather conditions
- Retrieves current weather and forecast information from the OpenMeteo API
- Can request specific weather parameters (temperature, humidity, wind speed, etc.)
- Supports daily forecasts
To add new tools:
- Create a new file in the
toolsdirectory - Define your tool function and its OpenAI Tool definition
- Update the
toolsListinmain.goto include your new tool
Apache License 2.0
Contributions are welcome! Please feel free to submit a Pull Request.