#openai-api #chat-bot #openai #ChatGPT #gpt-3 #gpt-4

ChatGPT-functions

这个crate提供对OpenAI API的封装,以便使用GPT-3.5和GPT-4进行聊天机器人。它还提供了一种定义可以从聊天机器人中调用的函数的方法。

13个版本

0.3.6 2023年7月3日
0.3.5 2023年7月2日
0.3.1 2023年6月30日
0.2.0 2023年6月27日
0.1.4 2023年6月26日

#838 in Web编程

每月 24 次下载
macro-gpt 中使用

MIT 许可证

75KB
1.5K SLoC

ChatGPT-functions

这个crate提供对OpenAI API的封装,以便使用GPT-3.5和GPT-4进行聊天机器人。它还提供了一种定义可以从聊天机器人中调用的函数的方法。

免责声明

这是一个正在进行中的项目。API 不稳定,将会更改。

要求

使用方法

将以下内容添加到您的 Cargo.toml

[dependencies]
chatgpt-functions = "0.3.1"

文档

文档可在 https://docs.rs/ChatGPT-functions 找到

功能

  • 与GPT-3.5和GPT-4聊天
  • 定义可以从聊天机器人中调用的函数

示例

您可以在 examples 文件夹中找到示例。

无函数的示例

use anyhow::{Context, Result};
use dotenv::dotenv;

use chatgpt_functions::chat_gpt::ChatGPTBuilder;

#[tokio::main]
async fn main() -> Result<()> {
    dotenv().ok();
    let key = std::env::var("OPENAI_API_KEY")?;

    let mut gpt = ChatGPTBuilder::new().openai_api_token(key).build()?;

    println!("Initialised chatbot. Enter your message to start a conversation.");
    println!("Using:");
    println!("- Model: {}", gpt.chat_context.model);
    println!("- Session ID: {}", gpt.session_id);
    println!("You can quit by pressing Ctrl+C (linux), or Cmd+C (Mac).");
    println!("--------------------------------------");
    loop {
        println!("- Enter your message and press Enter:");
        let mut input = String::new();
        std::io::stdin()
            .read_line(&mut input)
            .context("Failed to read your input")?;
        input.pop(); // Remove the trailing newline

        println!("- AI:");
        let answer = gpt.completion_managed(input).await?;
        println!("{}", answer.content().expect("Failed to get the content"));
        println!("--------------------------------------");
    }
}

带函数的示例

use anyhow::{Context, Result};
use chatgpt_functions::{
    chat_gpt::ChatGPTBuilder,
    function_specification::{FunctionSpecification},
};
use dotenv::dotenv;

#[tokio::main]
async fn main() -> Result<()> {
    dotenv().ok();
    let key = std::env::var("OPENAI_API_KEY")?;

    let mut gpt = ChatGPTBuilder::new().openai_api_token(key).build()?;

    let json = r#"
        {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"]
                    }
                },
                "required": ["location"]
            }
        }
        "#;
    let function: FunctionSpecification =
        serde_json::from_str(json).expect("Could not parse correctly the function specification");

    gpt.push_function(function);

    println!("Initialised chatbot. Enter your message to start a conversation.");
    println!("Using:");
    println!("- Model: {}", gpt.chat_context.model);
    println!("- Session ID: {}", gpt.session_id);
    println!("You can quit by pressing Ctrl+C (linux), or Cmd+C (Mac).");
    println!("--------------------------------------");
    loop {
        println!("- Enter your message and press Enter:");
        let mut input = String::new();
        std::io::stdin()
            .read_line(&mut input)
            .context("Failed to read your input")?;
        input.pop(); // Remove the trailing newline

        println!("- AI:");
        let answer = gpt.completion_managed(input).await?;
        println!("{}", answer.content().expect("Failed to get the content"));
        println!("--------------------------------------");
    }
}

bash中与GPT交互的示例

curl https://api.openai.com/v1/chat/completions   -H "Content-Type: application/json"   -H "Authorization: Bearer $OPENAI_API_KEY"   -d '{
    "model": "gpt-3.5-turbo-0613",
    "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is the weather like in Madrid, Spain?"}],
    "functions": [{
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA"
                    },
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                },
                "required": ["location"]
            }
        }],
    "function_call": "auto"
}'



{
  "id": "chatcmpl-7Ut7jsNlTUO9k9L5kBF0uDAyG19pK",
  "object": "chat.completion",
  "created": 1687596091,
  "model": "gpt-3.5-turbo-0613",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "function_call": {
          "name": "get_current_weather",
          "arguments": "{\n  \"location\": \"Madrid, Spain\"\n}"
        }
      },
      "finish_reason": "function_call"
    }
  ],
  "usage": {
    "prompt_tokens": 90,
    "completion_tokens": 19,
    "total_tokens": 109
  }
}

贡献

欢迎贡献!请打开一个issue或pull request。

依赖项

~4–16MB
~236K SLoC