Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions module2/chatbot/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# To run locally, add an OPENAI_API_KEY variable here with a valid API key
11 changes: 11 additions & 0 deletions module2/chatbot/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "chatbot"
version = "0.1.0"
edition = "2021"

[dependencies]
reqwest = {version = "0.11.3", features = ["json"]}
tokio = {version = "1.9.0", features = ["full"]}
serde = {version = "1.0.118", features = ["derive"]}
serde_json = "1.0.60"
dotenv = "0.15.0"
38 changes: 38 additions & 0 deletions module2/chatbot/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
SHELL := /bin/bash
.PHONY: help

help:
@grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'

clean: ## Clean the project using cargo
cargo clean

build: ## Build the project using cargo
cargo build

run: ## Run the project using cargo
cargo run

test: ## Run the tests using cargo
cargo test

lint: ## Run the linter using cargo
@rustup component add clippy 2> /dev/null
cargo clippy

format: ## Format the code using cargo
@rustup component add rustfmt 2> /dev/null
cargo fmt

release:
cargo build --release

all: format lint test run

bump: ## Bump the version of the project
@echo "Current version is $(shell cargo pkgid | cut -d# -f2)"
@read -p "Enter the new version: " version; \
updated_version=$$(cargo pkgid | cut -d# -f2 | sed "s/$(shell cargo pkgid | cut -d# -f2)/$$version/"); \
sed -i -E "s/^version = .*/version = \"$$updated_version\"/" Cargo.toml
@echo "Version bumped to $$(cargo pkgid | cut -d# -f2)"
rm Cargo.toml-e
76 changes: 76 additions & 0 deletions module2/chatbot/src/chatbot.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use reqwest::{header, Client};
use serde_json::json;
use serde_json::Value;
use std::io;
use std::io::Write;

pub async fn run_chat_loop(
client: &Client,
api_key: &str,
url: &str,
) -> Result<(), reqwest::Error> {
let mut conversation: String = String::from("The following is a conversation with an AI Assistant:");
loop {
print!("Human: ");
io::stdout().flush().unwrap();

let user_input: String = read_user_input();

if user_input.to_lowercase() == "exit" || user_input.to_lowercase() == "quit" {
break;
}

conversation.push_str("Human: ");
conversation.push_str(&user_input);
conversation.push_str("AI: ");

let json: Value = json!({
"model": "gpt-3.5-turbo-instruct",
"prompt": conversation,
"max_tokens": 150,
"temperature": 0.5,
"top_p": 1.0,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
"stop": ["Human:", "AI:"]
});

let body: Value = call_api(client, api_key, url, json).await?;
print!("{}", body);
let ai_response: &str = get_ai_response(&body);

print!("AI: {}", ai_response);

conversation.push_str(ai_response);
conversation.push_str("\n");
}
Ok(())
}

pub async fn call_api(
client: &Client,
api_key: &str,
url: &str,
json: Value,
) -> Result<Value, reqwest::Error> {
let response: reqwest::Response = client
.post(url)
.header(header::CONTENT_TYPE, "application/json")
.header(header::AUTHORIZATION, format!("Bearer {}", api_key))
.json(&json)
.send()
.await?;

let body: Value = response.json().await?;
Ok(body)
}

pub fn get_ai_response(body: &Value) -> &str {
body["choices"][0]["text"].as_str().unwrap().trim()
}

pub fn read_user_input() -> String {
let mut user_input: String = String::new();
io::stdin().read_line(&mut user_input).unwrap();
user_input.trim().to_string()
}
1 change: 1 addition & 0 deletions module2/chatbot/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod chatbot;
20 changes: 20 additions & 0 deletions module2/chatbot/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use chatbot::chatbot::run_chat_loop;
use reqwest::Client;

use dotenv::dotenv;
use std::env;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
// Load the .env file
dotenv().ok();
let client = Client::new();

// use env variable OPENAI_API_KEY
let api_key: String = env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY must be set");
let url: &str = "https://api.openai.com/v1/completions";

run_chat_loop(&client, &api_key, url).await?;

Ok(())
}
Loading