OpenAiAgent Implementation
Overview
The OpenAiAgent is an implementation of the BaseAgent that connects to the OpenAI API. This agent allows users to interact with OpenAI's GPT models via an API, enabling AI-driven conversations and completions.
What is OpenAI?
OpenAI provides advanced AI models, including GPT-4, for various natural language processing tasks. Developers can integrate these models via OpenAI's API, requiring an API key for authentication.
Why Use OpenAiAgent?
- Access to OpenAI's AI Models: Leverage state-of-the-art AI capabilities.
- Seamless Integration: Works within the framework using BaseAgent.
- Customizable: Supports different parameters and configurations.
- Reliable API Access: Official OpenAI support ensures stability and performance.
Implementation Details
The OpenAiAgent is structured as follows:
pub struct OpenAiAgent {
base: BaseAgent,
}
impl OpenAiAgent {
pub fn new(name : &str, api_key : &str) -> Self {
let api_url = "https://api.openai.com/v1/chat/completions";
let base = BaseAgent::new_with_param(
name,
api_url,
Some(api_key.to_string()),
None,
Some("gpt-4".to_string()),
None,
);
Self { base }
}
pub fn new_with_sys(name : &str, system_content: &str, api_key : &str) -> Self {
let api_url = "https://api.openai.com/v1/chat/completions";
let base = BaseAgent::new_with_param(
name,
api_url,
Some(api_key.to_string()),
Some(system_content.to_string()),
Some("gpt-4".to_string()),
None,
);
Self { base }
}
}
Setting Up OpenAI API
To use OpenAiAgent, you need to obtain an API key from OpenAI. Follow the official documentation for setup and authentication: OpenAI API Documentation.
Example Request
curl -X POST "https://api.openai.com/v1/chat/completions" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4",
"messages": [{"role": "user", "content": "Hello!"}]
}'
Conclusion
The OpenAiAgent provides an efficient and structured way to integrate OpenAI's AI capabilities into applications. By leveraging BaseAgent, it maintains modularity and flexibility while utilizing OpenAI's advanced AI models. This makes it a great choice for developers seeking high-quality AI interactions with official API support.