Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

langchain #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
302 changes: 302 additions & 0 deletions 02_langchain_simple_sequential_chains_agents.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,302 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "9424c6ac",
"metadata": {},
"source": [
"#### Simple Chains"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "70c3cab8",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.3.1\u001b[0m\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49m/opt/homebrew/opt/python@3.11/bin/python3.11 -m pip install --upgrade pip\u001b[0m\n",
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"pip install -r ./requirements.txt -q"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "2d60327e",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import os\n",
"from dotenv import load_dotenv, find_dotenv\n",
"load_dotenv(find_dotenv(), override=True)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "b7daf28c",
"metadata": {},
"outputs": [],
"source": [
"from langchain.chat_models import ChatOpenAI\n",
"from langchain import PromptTemplate\n",
"from langchain.chains import LLMChain\n",
"\n",
"llm = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=0.5)\n",
"template = '''You are an experienced virologist.\n",
"Write a few sentences about the following {virus} in {language}.'''\n",
"\n",
"prompt = PromptTemplate(\n",
" input_variables=['virus','language'],\n",
" template=template\n",
")\n",
"\n",
"chain = LLMChain(llm=llm, prompt=prompt)\n",
"output = chain.run({'virus': 'HSV', 'language': 'hindi'})"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "e49cb7f3",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"एचएसवी (HSV) एक वायरस है जो मनुष्यों में हेरपीस संक्रमण का कारण बनता है। यह वायरस दो प्रकार का होता है - एचएसवी-1 (ओरल हेरपीस) और एचएसवी-2 (जननांग हेरपीस)। यह संक्रमण संपर्क से फैलता है और त्वचा, मुंह और जननांगों पर घावों का कारण बनाता है। यह वायरस इलाज के लिए दवाओं द्वारा नियंत्रित किया जा सकता है, लेकिन इसका पूर्ण उपचार अभी तक मौजूद नहीं है।\n"
]
}
],
"source": [
"print(output)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "bace9b8a",
"metadata": {},
"outputs": [],
"source": [
"from langchain.chat_models import ChatOpenAI\n",
"from langchain import PromptTemplate\n",
"from langchain.chains import LLMChain\n",
"\n",
"llm = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=0.5)\n",
"template = '''You are an experienced virologist.\n",
"Write a few sentences about the following {virus}.'''\n",
"\n",
"prompt = PromptTemplate(\n",
" input_variables=['virus'],\n",
" template=template\n",
")\n",
"\n",
"chain = LLMChain(llm=llm, prompt=prompt)\n",
"#output = chain.run({'virus': 'HSV', 'language': 'hindi'})\n",
"output = chain.run('HSV')"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "d40b49f0",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"HSV, or Herpes Simplex Virus, is a common viral infection that affects humans. There are two types of HSV: HSV-1 and HSV-2. HSV-1 is primarily associated with oral herpes, causing cold sores or fever blisters around the mouth and on the face. On the other hand, HSV-2 is mainly responsible for genital herpes, characterized by painful sores in the genital area. Both types can be transmitted through direct contact with infected individuals, and the virus remains in the body for life, periodically causing outbreaks. While HSV infections are generally manageable with antiviral medications, they can pose complications for individuals with weakened immune systems.\n"
]
}
],
"source": [
"print(output)"
]
},
{
"cell_type": "markdown",
"id": "3a685a0e",
"metadata": {},
"source": [
"#### Sequential Chains"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "eba20aa9",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new SimpleSequentialChain chain...\u001b[0m\n",
"\u001b[36;1m\u001b[1;3m\n",
"\n",
"def linear_regression(x_values, y_values):\n",
" # Calculate the mean of x and y\n",
" x_mean = sum(x_values) / len(x_values)\n",
" y_mean = sum(y_values) / len(y_values)\n",
"\n",
" # Calculate the numerator and denominator of the slope\n",
" numerator = 0\n",
" denominator = 0\n",
" for i in range(len(x_values)):\n",
" numerator += (x_values[i] - x_mean) * (y_values[i] - y_mean)\n",
" denominator += (x_values[i] - x_mean) ** 2\n",
"\n",
" # Calculate the slope\n",
" slope = numerator / denominator\n",
"\n",
" # Calculate the y-intercept\n",
" intercept = y_mean - (slope * x_mean)\n",
"\n",
" return (slope, intercept)\u001b[0m\n",
"\u001b[33;1m\u001b[1;3mThe function linear_regression takes in two lists, x_values and y_values, representing the x and y values of a set of data points, respectively.\n",
"\n",
"First, the function calculates the mean (average) of the x and y values by summing all the values and dividing by the number of values in each list.\n",
"\n",
"Next, the function initializes two variables, numerator and denominator, to zero. These variables will be used to calculate the slope of the linear regression line.\n",
"\n",
"The function then iterates through each index in the x_values list using a for loop. For each index, it calculates the difference between the corresponding x value and the x_mean, and the difference between the corresponding y value and the y_mean. These differences are multiplied together and added to the numerator variable, while (x_values[i] - x_mean) squared is added to the denominator variable.\n",
"\n",
"After the loop, the function calculates the slope by dividing the numerator by the denominator.\n",
"\n",
"Finally, the function calculates the y-intercept by subtracting the product of the slope and x_mean from y_mean.\n",
"\n",
"The function returns a tuple (slope, intercept) representing the slope and y-intercept of the best-fit line obtained through linear regression.\n",
"\n",
"The linear regression line describes the relationship between the x and y values by providing a line that best fits the data points. The slope represents the rate of change of y with respect to x, while the y-intercept is the value of y when x is 0. These values can be used to make predictions or analyze the relationship between the variables in the dataset.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
}
],
"source": [
"from langchain.chat_models import ChatOpenAI\n",
"from langchain.llms import OpenAI\n",
"from langchain import PromptTemplate\n",
"from langchain.chains import LLMChain, SimpleSequentialChain\n",
"\n",
"llm1 = OpenAI(model_name='text-davinci-003', temperature=0.7, max_tokens=1024)\n",
"prompt1 = PromptTemplate(\n",
" input_variables=['concept'],\n",
" template='''You are an experienced scientist and Python programmer.\n",
" Write a function that implements the concept of {concept}.'''\n",
")\n",
"chain1=LLMChain(llm=llm1, prompt=prompt1)\n",
"\n",
"llm2 = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=1.2)\n",
"prompt2 = PromptTemplate(\n",
" input_variables=['function'],\n",
" template='''Given the Python function {function}, describe it as detailed as possible.'''\n",
")\n",
"chain2 = LLMChain(llm=llm2, prompt=prompt2)\n",
"\n",
"overall_chain = SimpleSequentialChain(chains=[chain1, chain2], verbose=True)\n",
"output = overall_chain.run('linear_regression')"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "5c3c50ed",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new SimpleSequentialChain chain...\u001b[0m\n",
"\u001b[36;1m\u001b[1;3m\n",
"\n",
"def softmax(x):\n",
" \"\"\"Compute the softmax of vector x.\"\"\"\n",
" e_x = np.exp(x - np.max(x))\n",
" return e_x / e_x.sum(axis=0)\u001b[0m\n",
"\u001b[33;1m\u001b[1;3mThe given Python function `softmax(x):` is a function that computes the softmax of a vector `x`. \n",
"\n",
"The softmax function is commonly used in machine learning and optimization algorithms to convert a vector of real numbers into a probability distribution. It is often used in multi-class classification tasks.\n",
"\n",
"The detailed steps in the function are as follows:\n",
"\n",
"1. Subtract the maximum value of the input vector `x` from each element of `x`. By subtracting the maximum value, we ensure numerical stability when exponentiating large numbers.\n",
"\n",
"2. Compute the element-wise exponential of the modified vector `x` using the `np.exp()` function from the NumPy library. This calculates the exponential value of each element.\n",
"\n",
"3. Calculate the sum of the exponential values obtained in step 2 along the specified axis (`axis=0`). The result is a scalar that represents the sum of all exponential values.\n",
"\n",
"4. Divide each exponential value obtained in step 2 by the sum calculated in step 3. This normalization step ensures that the resulting values sum up to 1 and represent probabilities.\n",
"\n",
"5. Return the resulting normalized vector.\n",
"\n",
"The output of the function is the softmax of the input vector `x`, which is a probability distribution over the elements of `x` that sums up to 1.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
}
],
"source": [
"output2 = overall_chain.run('softmax')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2d9d26b8",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}