AI Python for Beginners之我见

作为一个十级互联网冲浪选手,当看到吴恩达老师出新课的时候就已经无脑冲了。

传送门:

https://learn.deeplearning.ai/courses/ai-python-for-beginners/lesson/1/introduction

国内可以无压力打开,并且全免费!

[图片上传失败...(image-99393c-1723252979634)]
新课叫AI python for Beginners,我昨天也花了点时间把整个课程过了一遍。

冲浪回来给大家做一下总结。

先说结论:
这个课程确实是给Beginners,但凡有点python基础,这个课程就并不适合你。

首先,这是一个Short Courses,本身的体量就不大,感觉很像是一个大佬亲自下场的引流课程,主要是推荐这个DeepLearning.AI平台。感受一下这种新颖的视频 + 在线写代码 + AI辅助的编程语言入门的模式。

其次,就国内环境而言,前几年刮的那阵全民学代码学python的潮流,基本已经把新用户转化得差不多了,受众群体已经少了很多了。这种从python数据结构和如何变量赋值等基础从头教起的课程,受众可能已经不多了。

但是从这短短的课程中我也获得了一些有意思的东西

基于Jupyter Notebook的AI对话模块

在第九课,也就是倒数第二课,吴恩达老师介绍了如何用Jupyter Notebook引入一个大模型回答的模块。
[图片上传失败...(image-667cb8-1723252979634)]
引入的命令是:

from helper_functions import print_llm_response

之后提了一个问题:

print_llm_response("What is the capital of France?")

AI的回复是:

The capital of France is Paris.

也可以让AI根据你写的引导词(prompt)描述一只三岁大的狗狗的生活方式。
[图片上传失败...(image-37d873-1723252979634)]
从课程举的例子中你就能看出来,这个课程的对象确确实实是纯新手纯Beginners。😂

另外,最开始引入的这个from helper_functions import print_llm_response一看就不是公共的模块或者功能。大概率是一个私有的,也就是自己写的模块。模块的全文我附在这个推文的最后了。

我感觉这个模块稍微配置一下就能在日常的Jupyter Notebook中使用了。

这个反而是我上这门课最大的收获。

一些细节

顺便唠唠一些细节:
1. 为什么每次回答可以比较稳定?

使用过课程提供的AI机器人之后发现每次回答都是比较稳定的。

查看了一下模块代码发现了端倪。

模块代码里设置的temperature=0.0,这个参数是用来设置大模型回复的“天马行空”程度的,范围在0.0到1.0之间,设置成0.0,就能获得较为稳定的结果,发散程度最低。

当然,稳定不代表一模一样,多刷新几次还是能刷出细微的差别的。

2. 调用的模型是什么?

目前模块里调用的模型还是gpt-3.5-turbo-0125,是今年2月16日上线的,实际上的体验比较一般,现在官方已经用GPT-4o代替3.5模型了,也包括升级后的3.5-turbo。

AI chatbox的引导词

这个课程还配了一个AI机器人辅助回答问题
[图片上传失败...(image-297dc0-1723252979634)]
我觉得调教得还蛮好的。机器人会在回答完你的提问之后,给出下一步的引导,确实新手比较友好。

例如上面的截图,吴老师问传统上来说学习一个新的语言的第一个程序是什么,AI回答是打印“Hallo World”,并且还问你是否需要帮你用python写出这个代码。

下面是AI机器人的引导词,有需要的同学可以学习一下类似的场景如何写引导词。

这段引导词总结起来做了这么几件事情:

  • 你是一位友好的AI助教,帮助初学者学习Python编程。
  • 你假设学习者几乎没有编程经验。
  • 只使用Python语言回答问题,除非涉及计算机工作原理时,可以提及汇编或机器码。
  • 只有在学习者直接要求时才编写代码,代码应尽量简单易读,不使用复杂的Python惯用法。
  • 回答问题时尽量简短,只提供必要的解释,让学习者自行提出进一步问题。
  • 如果学习者问不相关的问题,提醒他们专注于编程学习。
You are the friendly AI assistant for a beginner python programming class. 
You are available to help learners with questions they might have about computer programming, 
python, artificial intelligence, the internet, and other related topics. 

You should assume zero to very little prior experience of coding when you reply to questions. 
You should only use python and not mention other programming languages (unless the question is 
about how computers work, where you may mention assembly or machine code if it is relevant to 
the answer). 

Only write code if you are asked directly by the learner. If you do write any code, it should
be as simple and easy to read as possible - name variables things that are easy to understand,
and avoid pythonic conventions like list comprehensions to help the learner stick to foundations 
like for loops and if statements. 

Keep your answers to questions short, offering as little explanation as is necessary to answer
the question. Let the learner ask follow up questions to dig deeper.

If the learner asks unrelated questions, respond with a brief reminder: "Please, focus on your programming for AI journey"

好啦。基本内容就聊到这里。感谢你的阅读。祝你今天愉快。


helper_functions.py

这个脚本叫helper_functions.py,但凡你会用Jupyter Notebook,获取全文对你而言应该不是什么难事 : )

# import gradio as gr
import os

from openai import OpenAI
from dotenv import load_dotenv

import random

#Get the OpenAI API key from the .env file
load_dotenv('.env', override=True)
openai_api_key = os.getenv('OPENAI_API_KEY')

# Set up the OpenAI client
client = OpenAI(api_key=openai_api_key)


def print_llm_response(prompt):
    """This function takes as input a prompt, which must be a string enclosed in quotation marks,
    and passes it to OpenAI's GPT3.5 model. The function then prints the response of the model.
    """
    llm_response = get_llm_response(prompt)
    print(llm_response)


def get_llm_response(prompt):
    """This function takes as input a prompt, which must be a string enclosed in quotation marks,
    and passes it to OpenAI's GPT3.5 model. The function then saves the response of the model as
    a string.
    """
    try:
        if not isinstance(prompt, str):
            raise ValueError("Input must be a string enclosed in quotes.")
        completion = client.chat.completions.create(
            model="gpt-3.5-turbo-0125",
            messages=[
                {
                    "role": "system",
                    "content": "You are a helpful but terse AI assistant who gets straight to the point.",
                },
                {"role": "user", "content": prompt},
            ],
            temperature=0.0,
        )
        response = completion.choices[0].message.content
        return response
    except TypeError as e:
        print("Error:", str(e))


def get_chat_completion(prompt, history):
    history_string = "\n\n".join(["\n".join(turn) for turn in history])
    prompt_with_history = f"{history_string}\n\n{prompt}"
    completion = client.chat.completions.create(
        model="gpt-3.5-turbo-0125",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful but terse AI assistant who gets straight to the point.",
            },
            {"role": "user", "content": prompt_with_history},
        ],
        temperature=0.0,
    )
    response = completion.choices[0].message.content
    return response


# def open_chatbot():
#     """This function opens a Gradio chatbot window that is connected to OpenAI's GPT3.5 model."""
#     gr.close_all()
#     gr.ChatInterface(fn=get_chat_completion).launch(quiet=True)

def get_dog_age(human_age):
    """This function takes one parameter: a person's age as an integer and returns their age if
    they were a dog, which is their age divided by 7. """
    return human_age / 7

def get_goldfish_age(human_age):
    """This function takes one parameter: a person's age as an integer and returns their age if
    they were a dog, which is their age divided by 5. """
    return human_age / 5

def get_cat_age(human_age):
    if human_age <= 14:
        # For the first 14 human years, we consider the age as if it's within the first two cat years.
        cat_age = human_age / 7
    else:
        # For human ages beyond 14 years:
        cat_age = 2 + (human_age - 14) / 4
    return cat_age

def get_random_ingredient():
    """
    Returns a random ingredient from a list of 20 smoothie ingredients.
    
    The ingredients are a bit wacky but not gross, making for an interesting smoothie combination.
    
    Returns:
        str: A randomly selected smoothie ingredient.
    """
    ingredients = [
        "rainbow kale", "glitter berries", "unicorn tears", "coconut", "starlight honey",
        "lunar lemon", "blueberries", "mermaid mint", "dragon fruit", "pixie dust",
        "butterfly pea flower", "phoenix feather", "chocolate protein powder", "grapes", "hot peppers",
        "fairy floss", "avocado", "wizard's beard", "pineapple", "rosemary"
    ]
    
    return random.choice(ingredients)

def get_random_number(x, y):
    """
        Returns a random integer between x and y, inclusive.
        
        Args:
            x (int): The lower bound (inclusive) of the random number range.
            y (int): The upper bound (inclusive) of the random number range.
        
        Returns:
            int: A randomly generated integer between x and y, inclusive.

        """
    return random.randint(x, y)

def calculate_llm_cost(characters, price_per_1000_tokens=0.015):
    tokens = characters / 4
    cost = (tokens / 1000) * price_per_1000_tokens
    return f"${cost:.4f}"
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,812评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,626评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,144评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,052评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,925评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,035评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,461评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,150评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,413评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,501评论 2 307
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,277评论 1 325
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,159评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,528评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,868评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,143评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,407评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,615评论 2 335

推荐阅读更多精彩内容