Friday, May 31, 2024

Thursday, May 30, 2024

Write a Book with AI?

How to Write a Book with AI in 2024 (2 Best Methods) - YouTube


Amazon.com: Prompt Engineering for Everyone: A Comprehensive Guide to Unlock the Potential of ChatGPT and AI-Language Models eBook : Bernstein, David Scott: Kindle Store

This book teaches you the art of prompt writing that will revolutionize how you interact with artificial intelligence and give you access to the hidden power of ChatGPT. Co-authored by ChatGPT itself, the world’s leading expert on prompt engineering, this comprehensive book offers you a one-of-a-kind journey into the realm of AI language models.






Wednesday, May 29, 2024

The Big Book of Generative AI | Databricks (free)

 The Big Book of Generative AI | Databricks

Best practices for building production-quality GenAI applications


AI book: Co-Intelligence by Ethan Mollick

 Co-Intelligence by Ethan Mollick: 9780593716717 | PenguinRandomHouse.com: Books


Co-Intelligence: Living and Working with AI: Mollick, Ethan: 9780593716717: Amazon.com: Books

"Something new entered our world in November 2022 — the first general purpose AI that could pass for a human and do the kinds of creative, innovative work that only humans could do previously. Wharton professor Ethan Mollick immediately understood what ChatGPT meant: after millions of years on our own, humans had developed a kind of co-intelligence that could augment, or even replace, human thinking. Through his writing, speaking, and teaching, Mollick has become one of the most prominent and provocative explainers of AI, focusing on the practical aspects of how these new tools for thought can transform our world."

Ethan Mollick | LinkedIn

Associate Professor at The Wharton School (Business, UPenn)


Monday, May 27, 2024

node.js: native test runner

instead of Jest or similar popular libraries, node.js has embedded feature for running unit test

Test runner | Node.js v22.1.0 Documentation


Exploring the Node.js native test runner - LogRocket Blog

While some programming languages incorporate testing tools to the core language feature, this wasn’t the case in the JavaScript/Node.js ecosystem. Tools like Mocha, Jest, and Jasmine were created to help with elaborate testing mechanisms. A native test runner was added as an experimental feature to Node.js v18, and fully incorporated into the Node.js core in version 20.


Is NodeJS Test Runner “Dev-Ready”? - DEV Community


Node.js — Using Node.js's test runner



example of "AI" generating unit tests:

 Course: GitHub Copilot - The Complete Guide | Udemy Business





AI PCs vs Copilot+ vs AI Workstations

Copilot+ PCs Laptop Computers | Dell USA

new Qualcom ARM based CPU + NPU


AI PCs Laptop Computers | Dell USA

with designated NPU or AI Chip, with Microsoft Copilot Key


AI Workstations Laptop Computers | Dell USA

with NVIDIA RTX 5000 GPU or higher



Tesla Model X Dancing with Music

Someone's Going to Look at a Tesla Like That - Joe Rogan - YouTube

Tesla Model X 2018 Dancing - YouTube



Sunday, May 26, 2024

AI course: RAG with Llamaindex

 DLAI - Building Agentic RAG with Llamaindex @deeplearning.ai


What Is Retrieval-Augmented Generation aka RAG | NVIDIA Blogs

Retrieval-augmented generation (RAG) is a technique for enhancing the accuracy and reliability of generative AI models with facts fetched from external sources.


LlamaIndex, Data Framework for LLM Applications

LlamaIndex is the leading data framework for building LLM applications


AI LLMs: Tokens, Embeddings, Vector Databases

Strange as it may look after trying ChatGPT,
modern AI's don't "speak" English, or any other human language.

Vectors

Sequences of numbers, usually called arrays in programming, and "vectors" in mathematics.

i.e. like this,[123, 4,  56] or [0.34, 0.23, 0.01, 0.98], just much longer

Digital computers "speak" numbers, and numbers only.

In particular GPU and NPU components used to process data,
are optimized for very fast processing such data.

So all "text", images and other content needs to be "translated" to such arrays of numbers, 
processed, and results translated back to human-understandable form.

There are two different concepts related to this translation that look similar
while have different purpose: "tokens" and "embeddings".
To make any sense of AI APIs, one needs to understand those concepts. 

Tokens

are about usage and money. It is about "quantity" of text sent to and received from AI API.
Depending on API used, there are limits and costs about how much content, i.e. text,
can be sent at once, and price is calculated based on this. A token is an integer number, and 
usually is mapped to a few characters that is usually a small word, or part of larger word.
For example "Hello World!" is converted to [9906, 4435, 0] = ["Hello", "World", "!"]
and "Sequences" is [1542, 45045] = ["Se", "quences"]


To measure and estimate const of AI API calls we can use libraries, i.e OpenAI tiktoken 

openai/tiktoken: tiktoken is a fast BPE tokeniser for use with OpenAI's models. @GitHub (Python)

tiktoken - npm (JavaScript)

import { encoding_for_model } from 'tiktoken'
const encoder = encoding_for_model('gpt-3.5-turbo');
const words = encoder.encode(prompt);


Embeddings
 

are about "meaning" and "similarity" of content.

Through process of "training", AI "models" are able to map content to array of floating point numbers, usually between 0 and 1, and to compare such arrays, called vectors to find "similarity" or "distance".

For example, "Hello World" can be converted to vector of about 1500 numbers like this
"input": "Hello World!",
"embedding": [
-0.0030342294,
-0.056672804,
0.029482627,
0.042976152,
-0.040828794,
-0.025202423,
-0.012789831,
0.035228256,
-0.031571947,
...


import OpenAI from 'openai'
const openai = new OpenAI();
export async function createEmbeddings(input: string| string[]) {
    return await openai.embeddings.create({
        input: input,
        model: 'text-embedding-3-small'
    })
}


"An embedding is a numerical representation of a piece of information, for example, text, documents, images, audio, etc. The representation captures the semantic meaning of what is being embedded

Since the embeddings capture the semantic meaning of the questions, it is possible to compare different embeddings and see how different or similar they are. Thanks to this, you can get the most similar embedding to a query, which is equivalent to finding the most similar FAQ. Check out our semantic search tutorial for a more detailed explanation of how this mechanism works."



Calculating Similarity between Embeddings


export function calcDotProduct(a: number[], b: number[]) {
    return a.map((value, index) => value * b[index]).reduce((a, b) => a + b, 0);
}
function calcCosineSimilarity(a: number[], b: number[]) {
    const product = dotProduct(a, b);
    const aMagnitude = Math.sqrt(a.map(value => value * value).reduce((a, b) => a + b, 0));
    const bMagnitude = Math.sqrt(b.map(value => value * value).reduce((a, b) => a + b, 0));
    return product / (aMagnitude * bMagnitude);
}

The Building Blocks of LLMs: Vectors, Tokens and Embeddings @ TheNewStack

a vector is a single-dimensional array, in this case of numbers only

Tokens are the basic units of data processed by LLMs. In the context of text, a token can be a word, part of a word (subword), or even a character — depending on the tokenization process.

In LLMs, vectors are used to represent text or data in a numerical form that the model can understand and process. This representation is known as an embedding. Embeddings are high-dimensional vectors that capture the semantic meaning of words, sentences or even entire documents.

Vector Databases








Chroma: the AI-native open-source embedding database

EV fast charging startup funded by Google

Google funded company plan to beat Tesla with 1,000's of 500kW chargers - YouTube

Gravity to add 500 kW EV charger trees on streets, targets Tesla @electrek

NY-based startup and EV infrastructure specialist Gravity has launched a new line of universal EV charger “trees” it hopes will bring convenient charging sessions curbside on city streets. The deployment will start modestly, but Gravity is targeting a street charging network that is ” more expansive than Tesla’s current Supercharger network.”


Saturday, May 25, 2024

.NET Aspire: Cloud Native in Azure


"Learn about .NET Aspire, an opinionated, cloud ready stack for building observable, production ready, distributed applications."



".NET Aspire is an opinionated, cloud ready stack for building observable, production ready, distributed applications. .NET Aspire is delivered through a collection of NuGet packages that handle specific cloud-native concerns. Cloud-native apps often consist of small, interconnected pieces or microservices rather than a single, monolithic code base. Cloud-native apps generally consume a large number of services, such as databases, messaging, and caching."




"How do you build cloud-native applications in Azure? Carl and Richard talk to Scott Hunter about how Microsoft tooling is evolving to develop cloud-native applications - starting with the vital idea that all cloud-native apps are multiple applications! 

Scott talks about how most development tools focus on individual applications and how dealing with multiple applications, including cloud apps, can be challenging. Cloud apps need telemetry, resiliency, and service discovery - which brings the conversation to tooling like

.NET Aspire, designed to lead developers down the path to cloud-native applications with all these features and more..." 



Frequently asked questions about .NET Aspire | Microsoft Learn

more info





markdown syntax: new lines

useful, not obvious formatting options:

 How to add new line in Markdown presentation? - Stack Overflow

  • add two spaces to a line = new line

  • add backslash \ to a line = new line

  • add <br> to a line = new line

  • escape block with ``` = preserves new lines, but no formatting, not the same


Basic Syntax | Markdown Guide

CommonMark and a few other lightweight markup languages let you type a backslash (\) at the end of the line, but not all Markdown applications support this, so it isn’t a great option from a compatibility perspective. 


home architecture: hacienda arches

looks nice! not easy to make it...

www.jennasuedesign.com/hacienda-hideaway-porch-makeover/

inspirations


   

 process

   


web: UTM parameters

UTM parameters - Wikipedia

Urchin Tracking Module (UTM) parameters are five variants of URL parameters used by marketers to track the effectiveness of online marketing campaigns across traffic sources and publishing media. They were introduced by Google Analytics' predecessor Urchin and, consequently, are supported out of the box by Google Analytics. The UTM parameters in a URL identify the campaign that refers traffic to a specific website,[1] and attribute the browser's website session and the sessions after that until the campaign attribution window expires to it. The parameters can be parsed by analytics tools and used to populate reports.[2]

This example URL has four of the five UTM parameters highlighted:

https://www.example.com/page?utm_content=buffercf3b2&utm_medium=social&utm_source=snapchat.com&utm_campaign=buffer

Urchin (software) - Wikipedia

Urchin was a web statistics analysis program that was developed by Urchin Software Corporation. Urchin analyzed web server log file content and displayed the traffic information on that website based upon the log data.

Urchin Software Corp. was acquired by Google in April 2005, forming Google Analytics

Friday, May 24, 2024

EV: Kia EV3

NEW Kia EV3: The One We’ve Been Waiting For? - YouTube

2026 Kia EV3: What We Know So Far @ CarAndDriver

See Exterior Photos of the 2026 Kia EV3



The Kia EV3 is small but shares an undeniable family resemblance to the larger EV9. A base model and a GT-Line version will both be available. The EV3 will offer an 81.4-kWh battery and 350 miles of range.

serious fun about AI

Jerry Seinfeld | Duke's 2024 Commencement Address - YouTube

"...AI, ... is the most embarrassing thing
we've ever invented in mankind's time on Earth.


Oh, so you can't do the work?
Is that what you're telling me? You can't figure it out.

This seems to be the justification of AI - I couldn't do it.
This is something to be embarrassed about.
The ad campaign for ChatGPT GPT should be the opposite of Nike.
You just can't do it.

Making fake brains is risky.

Frankenstein proved that he was so dumb
he thought a monster needed a sport jacket...

What I like is we're smart enough to invent it and dumb enough to need it.
And still so stupid we can't figure out if we did the right thing.
Making work easier.
This is the problem.

So obsessed with getting to the answer,
completing the project, producing a result which are all valid things,
but not where the richness of the human experience lies.
The only two things you ever need to pay attention to in
life are work and love..."





plus similar, with LLM quote :)

I Gave A Commencement Speech! - YouTube by Marques Brownlee, NJ, tech-YouTuber



Chart.js

Chart.js | Open source HTML5 Charts for your website
Simple yet flexible JavaScript charting library for the modern web




MIT license




popular: 3+M downloads/week

Chart.js - Wikipedia

Chart.js is a free, open-source JavaScript library for data visualization, which supports eight chart types: bar, line, area, pie (doughnut), bubble, radar, polar, and scatter. Created by London-based web developer Nick Downie in 2013, now it is maintained by the community and is the second most popular JavaScript charting library on GitHub by the number of stars after D3.js, considered significantly easier to use though less customizable than the latter. Chart.js renders in HTML5 canvas and is widely covered as one of the best data visualization libraries. It is available under the MIT license




Thursday, May 23, 2024

AI interview: Geoffrey Hinton

Geoffrey Hinton | On working with Ilya, choosing problems, and the power of intuition - YouTube

conversation between Geoffrey Hinton and Joel Hellermark recorded in April 2024 at the Royal Institute of Great Britain in London. An edited version was premiered at Sana AI Summit on May 15 2024 in Stockholm, Sweden. 

Geoffrey Hinton has been called “the godfather of AI” and is considered one of the most prominent thought leaders on the emergence of artificial intelligence. He has served as a faculty member at Carnegie-Mellon and a fellow of the Canadian Institute for Advanced Research. He is now Emeritus Professor at the University of Toronto. In 2023, Geoffrey left his position at Google so that he could speak freely about AI’s impact on humankind.


JavaScript: Array.from()

 Array.from() - JavaScript | MDN


How to initialize an array's length in JavaScript? - Stack Overflow

Array.from('abcde'),

Array.from('x'.repeat(5))

Array.from({length: 5}, (v, i) => i) // gives [0, 1, 2, 3, 4]

const randomNumbers = Array.from({length: 10}, () => Math.floor(Math.random() * 100));

function getRandomColor() {
  var r = Math.floor(Math.random() * 256);
  var g = Math.floor(Math.random() * 256);
  var b = Math.floor(Math.random() * 256);
  return 'rgba(' + r + ', ' + g + ', ' + b + ', 0.2)';
}

const randomColors = Array.from({length: 10}, () => getRandomColor());

Wednesday, May 22, 2024

AI PCs: Dell AI factory, with Nvidia

AI@Edge: "AI PCs" with NPUs 
(neural processing unit)

Microsoft CEO Nadella on AI PC Plans, Taking on Apple, Fostering Competition - YouTube

from "Industrial Revolution" 
to "Intelligence Revolution"

Artificial Intelligence Solutions | Microsoft AI


"Dude, easy as Dell" :)

Michael Dell, Jensen Huang and Bill McDermott on New AI Factories - YouTube

exclusive joint interview with Dell Chairman and CEO Michael Dell, Nvidia CEO Jensen Huang, and ServiceNow Chairman and CEO Bill McDermott to talk about a new partnership to build artificial intelligence "factories" and computers, reliance on Taiwan and the growth of AI. They speak from the Dell World Conference in Las Vegas.




As part of the Dell AI Factory’s growing AI devices and infrastructure offerings
Dell expands our broad portfolio of AI PCs and workstations with the introduction of the 
most Copilot+ PCs powered by Snapdragon® X Elite and Snapdragon® X Plus processors.

his brand-new class of devices transforms your AI PC experience with extraordinary performance and battery life, upleveled productivity and powerful security. 

five new laptops, XPS 13, Inspiron 14 Plus, Inspiron 14, Latitude 7455 and Latitude 5455, 

AI processing locally on the device across the custom-integrated Qualcomm Oryon™ CPU,
premium GPU and neural processing unit (NPU)

interesting, no "Intel Inside" on those new models



new 3D performance hybrid architecture, built into every Intel® Core™ Ultra processor
integrates CPU, GPU, and NPU into a single package.

AI PCs for Business (Intel Core Ultra)






calc tool: Bytes to Gigabytes

 Convert Byte to Gigabyte

10,000,000,000 B = 9.31 GB


Tuesday, May 21, 2024

Microsoft Build 2024: AI PCs Copilot+

Microsoft Build 2024: Everything Revealed in 9 Minutes - YouTube

At Microsoft Build 2024, CEO Satya Nadella discusses with developers the company’s strategy to add AI throughout its product lineup, from the cloud to the desktop PC. In addition, Nadella talks about its recent partnerships with Nvidia and AMD.


Microsoft Build 2024: Day 1 #MSBuild - YouTube





Copilot+ PCs: These are only just two of what Microsoft is touting the new line of Copilot+ PCs — the next generation AI PCs. You can see more about what Asus, Acer, DellHP and Lenovo have up their sleeves for this.






book: Brave New Words: How AI Will Revolutionize Education

Brave New Words: How AI Will Revolutionize Education (and Why That's a Good Thing): Khan, Salman: 9780593656952: Amazon.com: Books

Brave New Words by Salman Khan: 9780593656952 | PenguinRandomHouse.com: Books


GPT-4o (Omni) math tutoring demo on Khan Academy - YouTube


GPT-4o (Omni) Human interaction demo w/ Sal Khan - YouTube


AI's impact on Education || Khan Academy CEO || Salman Khan - YouTube


How AI Could Save (Not Destroy) Education | Sal Khan | TED - YouTube


AI & GPT-4 Revolutionize Education With Sal Khan | EP #35 Moonshots and Mindsets - YouTube



Monday, May 20, 2024

WebGL: Warp Speed

Warp Speed

"Travel through the galaxy in the company of a shimmering spaceship and enjoy the view" in this stunning Pen from Matthias Hurrle.

The CodePen Spark

AI HW stocks: NVidia++

most of modern AI systems run on NVIDIA HW
So Nvidia stock is surging, and along with it a few related providers.

GET IN EARLY! Top 4 Stocks I'm Buying Thanks to OpenAI GPT-4o - YouTube
by Ticker Symbol YOU

  • Micron Tech: MU stock
  • Applied Materials: AMAT stock 
  • Taiwan Semiconductors: TSMC
  • ASML stock


Expected global AI market growth: 12x in next 8 years
= 36%/year = 3x S&P500
SW+Services: 75%; HW: 25%
 







Sunday, May 19, 2024

AI OSS UI: LibreChat

for DIY AI chat solutions

LibreChat


  • UI matching ChatGPT, including Dark mode, Streaming, and latest updates
  • AI model selection:
    • OpenAI, Azure OpenAI, BingAI, ChatGPT, Google Vertex AI, Anthropic (Claude), Plugins, Assistants API (including Azure Assistants)


MIT license





NVIDIA’s Jensen Huang: the greatest AI salesman in the world

very smart: "happiness comes from hard work"

Jensen Huang, Founder, President and CEO of NVIDIA
joins Stripe Cofounder and CEO Patrick Collison
for a fireside chat on leadership in the age of AI.


Jensen Huang - Wikipedia


A Conversation with the Jensen Huang of Nvidia: Who Will Shape the Future of AI? (Full Interview) - YouTube


Stripe Sessions 2024 | Opening keynote - YouTube





a good book!

The Greatest Salesman in the World is a book,
written by 
Og Mandino, that serves as a guide to a philosophy of salesmanship, and success


Saturday, May 18, 2024

OpenAI API: from bash, PowerShell, JS, Python, C#, Go, TypeScript

example of making simple OpenAI API (Chat) GPT request with various prog. languages,
including unusual one, PowerShell

to run examples must have env var set: OPENAI_API_KEY
as declared in first line of shell scripts examples

Examples:

API Reference - OpenAI API

OpenAI provides "official" (SDK) libs/modules for Python and JavaScript
There are some additional community and Microsoft supported packages.

Libraries - OpenAI API

bash shell, REST

Unix: Linux / Mac / Windows WSL2

> export OPENAI_API_KEY="your_api_key_here"

this is calling REST API endpoint directly

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "How tall is Acadia?"
      }
    ]
  }'

> ./openai1.sh
{
  "id": "chatcmpl-9QRuW3j2l9COgyf7oovTxeScMc7RN",
  "object": "chat.completion",
  "created": 1716090844,
  "model": "gpt-4o-2024-05-13",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Acadia National Park, located in Maine, doesn't have one specific height since it encompasses a variety of landscapes including mountains, forests, and coastline. However, the tallest peak in the park is Cadillac Mountain, which is 1,530 feet (466 meters) tall. Cadillac Mountain is also notable for being the highest point along the North Atlantic seaboard and one of the first places in the United States to see the sunrise, particularly from October through early March."
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 23,
    "completion_tokens": 93,
    "total_tokens": 116
  },
  "system_fingerprint": "fp_729ea513f7"
}

PowerShell, REST

Windows default shell

> $env:OPENAI_API_KEY = "your_api_key_here"

Observe backtick (`) on the end of line that continues on next line

$headers = @{
    "Content-Type" = "application/json"
    "Authorization" = "Bearer $env:OPENAI_API_KEY"
}

$body = @{
    "model" = "gpt-3.5-turbo"
    "messages" = @( @{
        "role" = "user"
        "content" = "How tall is Mount Everest, in meters, feet and miles?"
    } )
    "temperature" = 0.7
} | ConvertTo-Json

$response = Invoke-WebRequest -Uri "https://api.openai.com/v1/chat/completions" `
  -Method Post -Body $body -Headers $headers

$response.Content | Out-String -Width 4096

> .\openai1.ps1

{
  "id": "chatcmpl-9QRZh4zGi8LvepxDE0xNYdlmCVcM4",
  "object": "chat.completion",
  "created": 1716089553,
  "model": "gpt-3.5-turbo-0125",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Mount Everest is approximately 8,848 meters (29,029 feet) tall. In miles, it is approximately 5.5 miles high."
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 20,
    "completion_tokens": 30,
    "total_tokens": 50
  },
  "system_fingerprint": null
}

JavaScript, with official lib / npm module

to run, first install required module with

> npm init -y
> npm install -g openai

import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const completion = await openai.chat.completions.create({
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      {
        role: 'user',
        content: 'How tall is Mont Blanc?'
      },
    ],
    model: "gpt-3.5-turbo",
  });

  console.log(completion.choices[0]);
}

main();

> node openai1.js

{
  index: 0,
  message: {
    role: 'assistant',
    content: 'Mont Blanc is 4,808 meters (15,774 feet) tall.'
  },
  logprobs: null,
  finish_reason: 'stop'
}

Python, with official package/ lib

first install required package with

> pip install openai

from openai import OpenAI
client = OpenAI()

completion = client.chat.completions.create(
  model="gpt-4o",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "How tall is Mount Atlas!"}
  ]
)

print(completion.choices[0].message)

> python openai1.py

ChatCompletionMessage(content='Mount Atlas is not a specific mountain; rather, it is a mountain range known as the Atlas Mountains. The Atlas Mountains stretch across several countries in North Africa, including Morocco, Algeria, and Tunisia. The highest peak in the Atlas Mountains is Toubkal, which is located in southwestern Morocco. Mount Toubkal stands at 4,167 meters (13,671 feet) above sea level.', role='assistant', function_call=None, tool_calls=None)

DotNet: C#, REST

there is no "official" DotNet OpenAI SDK

here is an example using calling OpenAPI REST API call directly

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            var content = new StringContent(
                @"{
                    ""model"": ""gpt-4o"",
                    ""messages"": [
                        {
                            ""role"": ""system"",
                            ""content"": ""You are a helpful assistant.""
                        },
                        {
                            ""role"": ""user"",
                            ""content"": ""How tall are Appalachian Mountains""
                        }
                    ]
                }", Encoding.UTF8, "application/json");

            var response = await client.PostAsync("https://api.openai.com/v1/chat/completions", content);
            var responseString = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseString);
        }
    }
}

requires min. project file, i.e. openai.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
  </PropertyGroup>
</Project>

> dotnet run .\gpt1.cs
{
  "id": "chatcmpl-9QSCeSOzRawUxKRm8rqYmsQLVuJZF",
  "object": "chat.completion",
  "created": 1716091968,
  "model": "gpt-4o-2024-05-13",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The Appalachian Mountains vary in height along their length. The highest peak in the Appalachian range is Mount Mitchell, located in North Carolina, which stands at 6,684 feet (2,037 meters) above sea level. This mountain is the highest peak in the eastern United States. Other notable peaks in the range also reach substantial heights, typically between 3,000 to 6,000 feet (910 to 1,830 meters). The terrain generally decreases in elevation as the mountains extend northward towards Canada."   
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 22,
    "completion_tokens": 103,
    "total_tokens": 125
  },
  "system_fingerprint": "fp_729ea513f7"
}

C#, dotnet script CLI, REST

the same can be done even simpler, from a single file by using dotnet script tool


using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");

using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

    var content = new StringContent(
@"{
    ""model"": ""gpt-4o"",
    ""messages"": [
        {
            ""role"": ""system"",
            ""content"": ""You are a helpful assistant.""
        },
        {
            ""role"": ""user"",
            ""content"": ""How tall is Denali?""
        }
    ]
}", Encoding.UTF8, "application/json");

    var response = await client.PostAsync("https://api.openai.com/v1/chat/completions", content);
    var responseString = await response.Content.ReadAsStringAsync();

    Console.WriteLine(responseString);
}

dotnet tool install -g dotnet-script
dotnet script .\openai-cli.cs

{
  "id": "chatcmpl-9Qbnz6u6qLRheyf7qSIkd3k80JRLZ",
  "object": "chat.completion",
  "created": 1716128879,
  "model": "gpt-4o-2024-05-13",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Denali, also known as Mount McKinley, is the tallest peak in North America, standing at approximately 20,310 feet (6,190 meters) above sea level."      
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 23,
    "completion_tokens": 37,
    "total_tokens": 60
  },
  "system_fingerprint": "fp_729ea513f7"
}

Go Lang, REST

Example calling REST API directly

package main

import (
    "bytes"
    "fmt"
    "io"
    "net/http"
    "os"
)

func main() {
    apiKey := os.Getenv("OPENAI_API_KEY")

    client := &http.Client{}

    data := []byte(`{
        "model": "gpt-4o",
        "messages": [
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "How tall is Mount Washington?"
            }
        ]
    }`)

    req, _ := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewBuffer(data))
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    resp, _ := client.Do(req)
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)

    fmt.Println(string(body))
}


> go run .\openai1.go

{
  "id": "chatcmpl-9QSOwP8eg2db6uwQIDZWMa0Xv7Hw2",
  "object": "chat.completion",
  "created": 1716092730,
  "model": "gpt-4o-2024-05-13",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Mount Washington, located in New Hampshire, is the highest peak in the Northeastern United States. It stands at 6,288 feet (1,917 meters) above sea level."
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 23,
    "completion_tokens": 37,
    "total_tokens": 60
  },
  "system_fingerprint": "fp_729ea513f7"
}

TypeScript, REST

calling REST API directly

async function main() {
    const apiKey = process.env.OPENAI_API_KEY;

    // @ts-ignore // fetch() is natively supported in Node.js 18 and newer, no need for node-fetch  
    const response = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            model: 'gpt-4o',
            messages: [
                {
                    role: 'system',
                    content: 'You are a helpful assistant.'
                },
                {
                    role: 'user',
                    content: 'How tall is Grand Teton Mountain?'
                }
            ]
        })
    });
    const responseString = await response.text();
    console.log(responseString);
}

main();


to configure ts complier (tsc, tsnode) to support native fetch() function need tsconfig.json like this
{
    "include": ["**/*.ts"],
    "compilerOptions": {
        "target": "ES2020", // to support "native" fetch() in node.js
        "module": "commonjs",
        "lib": ["ES2020"],
    },
    "ts-node": {
        "compilerOptions": {
            "esModuleInterop": true
        },
        "transpileOnly": true,
        "files": true
    },
}

to run

> npm i -g typescript
> npm i -g ts-node
> ts-node openai1.ts

{
  "id": "chatcmpl-9Qaxo1brTFVc4wQMAVtxNfkP9RHVu",
  "object": "chat.completion",
  "created": 1716125644,
  "model": "gpt-4o-2024-05-13",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Grand Teton Mountain, located in the Teton Range of Wyoming, stands at an elevation of 13,775 feet (4,199 meters) above sea level. It is the second-highest peak in Wyoming, after Gannett Peak."
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 25,
    "completion_tokens": 50,
    "total_tokens": 75
  },
  "system_fingerprint": "fp_729ea513f7"
}