Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
commit
Vasek Mlejnskya7a99c9d0670
diff --git a/PromptExperiments/langchain_basics.ipynb b/PromptExperiments/langchain_basics.ipynbdeleted file mode 100644index 7f62aa8f1..000000000--- a/PromptExperiments/langchain_basics.ipynb+++ /dev/null@@ -1,401 +0,0 @@-{- "cells": [- {- "cell_type": "code",- "execution_count": 3,- "metadata": {},- "outputs": [],- "source": [- "OPENAI_API_KEY=\"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\""- ]- },- {- "cell_type": "code",- "execution_count": 11,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "What is a good name for a company that makes Coke Bears?\n"- ]- }- ],- "source": [- "# Create custom prompt template.\n",- "from langchain.prompts import PromptTemplate\n",- "\n",- "prompt = PromptTemplate(\n",- " input_variables=[\"product\"],\n",- " template=\"What is a good name for a company that makes {product}?\",\n",- ")\n",- "print(prompt.format(product=\"Coke Bears\"))\n"- ]- },- {- "cell_type": "code",- "execution_count": 12,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "\n",- "\n",- "FizzyFur Co.\n"- ]- }- ],- "source": [- "# Initialize a LLM.\n",- "from langchain.llms import OpenAIChat\n",- "from langchain.prompts import PromptTemplate\n",- "\n",- "prompt = PromptTemplate(\n",- " input_variables=[\"product\"],\n",- " template=\"What is a good name for a company that makes {product}?\",\n",- ")\n",- "\n",- "llm = OpenAIChat(openai_api_key=OPENAI_API_KEY, temperature=0.0)\n",- "print(llm(prompt.format(product=\"Coke Bears\")))\n"- ]- },- {- "cell_type": "code",- "execution_count": 6,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "\n",- "\n",- "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",- "Prompt after formatting:\n",- "\u001b[32;1m\u001b[1;3mWhat is a good name for a company that makes next generation IDE for building API powered by AI?\u001b[0m\n",- "\n",- "\u001b[1m> Finished chain.\u001b[0m\n"- ]- },- {- "data": {- "text/plain": [- "'\\n\\nAI-IDEAS (AI-powered IDE for API development)'"- ]- },- "execution_count": 6,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# Create a custom langchain chain.\n",- "# A chain in LangChain is made up of links, which can be either primitives like LLMs or other chains.\n",- "# The most core type of chain is an LLMChain, which consists of a PromptTemplate and an LLM.\n",- "\n",- "from langchain.llms import OpenAIChat\n",- "from langchain.prompts import PromptTemplate\n",- "from langchain.chains import LLMChain\n",- "\n",- "prompt = PromptTemplate(\n",- " input_variables=[\"product\"],\n",- " template=\"What is a good name for a company that makes {product}?\",\n",- ")\n",- "\n",- "llm = OpenAIChat(openai_api_key=OPENAI_API_KEY, temperature=0.5)\n",- "\n",- "chain = LLMChain(llm=llm, prompt=prompt, verbose=True)\n",- "chain.run(\"next generation IDE for building API powered by AI\")\n"- ]- },- {- "cell_type": "code",- "execution_count": 11,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Sure, here's an example Express server with a `handleGetRequests` function that responds with 'Ok' to incoming GET requests:\n",- "\n",- "```javascript\n",- "const express = require('express');\n",- "const app = express();\n",- "\n",- "function handleGetRequests(req, res) {\n",- " res.send('Ok');\n",- "}\n",- "\n",- "app.get('/', handleGetRequests);\n",- "\n",- "app.listen(3000, () => {\n",- " console.log('Server listening on port 3000');\n",- "});\n",- "```\n",- "\n",- "In this example, we create an Express app and define a `handleGetRequests` function that takes in a request (`req`) and response (`res`) object. When a GET request is made to the root route (`/`), the `handleGetRequests` function is called and sends back a response of 'Ok' using the `res.send()` method.\n",- "\n",- "Finally, we start the server listening on port 3000 using the `app.listen()` method."- ]- },- {- "data": {- "text/plain": [- "AIMessage(content=\"Sure, here's an example Express server with a `handleGetRequests` function that responds with 'Ok' to incoming GET requests:\\n\\n```javascript\\nconst express = require('express');\\nconst app = express();\\n\\nfunction handleGetRequests(req, res) {\\n res.send('Ok');\\n}\\n\\napp.get('/', handleGetRequests);\\n\\napp.listen(3000, () => {\\n console.log('Server listening on port 3000');\\n});\\n```\\n\\nIn this example, we create an Express app and define a `handleGetRequests` function that takes in a request (`req`) and response (`res`) object. When a GET request is made to the root route (`/`), the `handleGetRequests` function is called and sends back a response of 'Ok' using the `res.send()` method.\\n\\nFinally, we start the server listening on port 3000 using the `app.listen()` method.\", additional_kwargs={})"- ]- },- "execution_count": 11,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# OpenAIChat requires a different prompt template for effective use - https://platform.openai.com/docs/api-reference/chat\n",- "from langchain.chat_models import ChatOpenAI\n",- "from langchain.schema import ( \n",- " HumanMessage,\n",- " SystemMessage,\n",- ")\n",- "from langchain.callbacks.base import CallbackManager\n",- "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",- "\n",- "cm = CallbackManager([StreamingStdOutCallbackHandler()])\n",- "chat = ChatOpenAI(\n",- " openai_api_key=OPENAI_API_KEY, \n",- " streaming=True,\n",- " temperature=0, \n",- " verbose=True,\n",- " callback_manager=cm,\n",- ")\n",- "messages = [\n",- " SystemMessage(content=\"You are a skilled senior JavaScript developer that writes code based on the specified requirements of your boss.\"),\n",- " HumanMessage(content=\"Write an Expres server with a function called `handleGetRequests` that accepts incoming GET and respond back with 'Ok'.\"),\n",- "]\n",- "chat(messages)\n"- ]- },- {- "cell_type": "code",- "execution_count": 13,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Newtonian relativity laws are based on the assumption that space and time are absolute and independent of each other. However, on the quantum level, this assumption breaks down. According to quantum mechanics, particles do not have a definite position or momentum until they are observed, and the act of observation itself affects the outcome of the experiment. This means that the position and momentum of a particle are not independent of each other, and the concept of absolute space and time becomes meaningless.\n",- "\n",- "Additionally, on the quantum level, particles can be in a state of superposition, meaning they exist in multiple states simultaneously. This is not accounted for in Newtonian relativity laws, which assume that particles have a definite position and momentum at all times.\n",- "\n",- "Therefore, to accurately describe the behavior of particles on the quantum level, we need to use the principles of quantum mechanics, which take into account the probabilistic nature of particles and the interdependence of space and time."- ]- }- ],- "source": [- "# Same as the cell above but with prompt templates.\n",- "from langchain.chat_models import ChatOpenAI\n",- "from langchain.prompts import PromptTemplate\n",- "from langchain.prompts.chat import (\n",- " ChatPromptTemplate,\n",- " SystemMessagePromptTemplate,\n",- " HumanMessagePromptTemplate,\n",- ")\n",- "from langchain.callbacks.base import CallbackManager\n",- "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",- "\n",- "cm = CallbackManager([StreamingStdOutCallbackHandler()])\n",- "chat = ChatOpenAI(\n",- " openai_api_key=OPENAI_API_KEY, \n",- " streaming=True,\n",- " temperature=0, \n",- " verbose=True,\n",- " callback_manager=cm,\n",- ")\n",- "\n",- "system_template = \"You are {role} that {job}.\"\n",- "system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)\n",- "\n",- "human_template = \"{text}\"\n",- "human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n",- "\n",- "chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])\n",- "chat_messages = chat_prompt.format_prompt(\n",- " role=\"a Stanford physics scientist\",\n",- " job=\"answers student questions about relativity\",\n",- " text=\"How come Newtonian relativity laws stop working on the quantum level?\",\n",- ").to_messages()\n",- "chat(chat_messages)\n",- "\n",- "# Or creating the `MessagePromptTemplate` more directly:\n",- "prompt = PromptTemplate(\n",- " template=\"You are {role} that {job}.\",\n",- " input_variables=[\"role\", \"job\"],\n",- ")\n",- "# Notice there's no calling `from_template`, we pass `prompt` directly to the constructor.\n",- "system_message_prompt = SystemMessagePromptTemplate(prompt=prompt)"- ]- },- {- "cell_type": "code",- "execution_count": 14,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "\n",- "\n",- "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",- "Prompt after formatting:\n",- "\u001b[32;1m\u001b[1;3m[SystemMessage(content='You are a conspiracy theorist that is trying to find out about the origin of the universe.', additional_kwargs={}), HumanMessage(content=\"Why we don't have any proof that the universe is real?\", additional_kwargs={})]\u001b[0m\n",- "As a language model AI, I cannot hold any beliefs or opinions. However, I can provide you with some information on the topic. \n",- "\n",- "The idea that the universe may not be real is a philosophical concept known as solipsism. However, in terms of scientific evidence, there is overwhelming evidence that the universe is real. \n",- "\n",- "For example, we can observe the universe through telescopes and other instruments, and we can measure its properties such as its temperature, composition, and expansion rate. We can also observe the effects of the universe's gravity on objects within it, and we can make predictions about the behavior of the universe based on mathematical models and physical laws.\n",- "\n",- "While there may be some mysteries and unanswered questions about the universe, the evidence strongly suggests that it is real and that it has a physical existence.\n",- "\u001b[1m> Finished chain.\u001b[0m\n"- ]- },- {- "data": {- "text/plain": [- "\"As a language model AI, I cannot hold any beliefs or opinions. However, I can provide you with some information on the topic. \\n\\nThe idea that the universe may not be real is a philosophical concept known as solipsism. However, in terms of scientific evidence, there is overwhelming evidence that the universe is real. \\n\\nFor example, we can observe the universe through telescopes and other instruments, and we can measure its properties such as its temperature, composition, and expansion rate. We can also observe the effects of the universe's gravity on objects within it, and we can make predictions about the behavior of the universe based on mathematical models and physical laws.\\n\\nWhile there may be some mysteries and unanswered questions about the universe, the evidence strongly suggests that it is real and that it has a physical existence.\""- ]- },- "execution_count": 14,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# OpenAIChat model and prompts can be easily used with the `LLMChain`:\n",- "from langchain import LLMChain\n",- "from langchain.chat_models import ChatOpenAI\n",- "from langchain.prompts.chat import (\n",- " ChatPromptTemplate,\n",- " SystemMessagePromptTemplate,\n",- " HumanMessagePromptTemplate,\n",- ")\n",- "from langchain.callbacks.base import CallbackManager\n",- "from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler\n",- "\n",- "# Create model\n",- "cm = CallbackManager([StreamingStdOutCallbackHandler()])\n",- "chat = ChatOpenAI(\n",- " openai_api_key=OPENAI_API_KEY, \n",- " streaming=True,\n",- " temperature=0, \n",- " verbose=True,\n",- " callback_manager=cm,\n",- ")\n",- "\n",- "# Create prompt\n",- "system_template = \"You are {role} that {job}.\"\n",- "system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)\n",- "human_template = \"{text}\"\n",- "human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)\n",- "chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])\n",- "\n",- "chain = LLMChain(llm=chat, prompt=chat_prompt, verbose=True)\n",- "chain.run(role=\"a conspiracy theorist\", job=\"is trying to find out about the origin of the universe\", text=\"Why we don't have any proof that the universe is real?\")"- ]- },- {- "cell_type": "code",- "execution_count": 15,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "\n",- "\n",- "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",- "\u001b[32;1m\u001b[1;3m I need to use a calculator to solve this.\n",- "Action: Calculator\n",- "Action Input: 2 * 0.123\u001b[0m\n",- "Observation: \u001b[36;1m\u001b[1;3mAnswer: 0.246\u001b[0m\n",- "Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n",- "Final Answer: 0.246\u001b[0m\n",- "\n",- "\u001b[1m> Finished chain.\u001b[0m\n"- ]- },- {- "data": {- "text/plain": [- "'0.246'"- ]- },- "execution_count": 15,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "# Agents\n",- "# Chains run in predetermined order. Agents don't.\n",- "# Agents use an LLM to detemrine which actions to take and in what order. An action can either be using a tool and observits its output, or returning to the user.\n",- "from langchain.agents import load_tools\n",- "from langchain.agents import initialize_agent\n",- "from langchain.llms import OpenAI\n",- "\n",- "\n",- "llm = OpenAI(openai_api_key=OPENAI_API_KEY, temperature=0)\n",- "\n",- "# Load pre-defined tools.\n",- "# Because `llm-math` uses LLM under the hood, we need to pass that in.\n",- "tools = load_tools([\"llm-math\"], llm=llm)\n",- "\n",- "# Initialize the agent of the type \"zero-shot-react-description\"\n",- "agent = initialize_agent(tools, llm, agent=\"zero-shot-react-description\", verbose=True)\n",- "\n",- "agent.run(\"How much is 2 * 0.123?\")"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Custom agent from scratch"- ]- }- ],- "metadata": {- "kernelspec": {- "display_name": "Python 3",- "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.10.8"- },- "orig_nbformat": 4,- "vscode": {- "interpreter": {- "hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"- }- }- },- "nbformat": 4,- "nbformat_minor": 2-}