mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-17 21:25:46 +02:00
[Docs] Add ruff linting to .ipynb files (#645)
This commit is contained in:
@@ -94,9 +94,9 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from langchain_openai import ChatOpenAI\n",
|
||||
"from langchain_core.prompts import ChatPromptTemplate\n",
|
||||
"from langchain_core.pydantic_v1 import BaseModel, Field\n",
|
||||
"from langchain_openai import ChatOpenAI\n",
|
||||
"\n",
|
||||
"### OpenAI\n",
|
||||
"\n",
|
||||
@@ -125,6 +125,7 @@
|
||||
" code: str = Field(description=\"Code block not including import statements\")\n",
|
||||
" description = \"Schema for code solutions to questions about LCEL.\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"expt_llm = \"gpt-4-0125-preview\"\n",
|
||||
"llm = ChatOpenAI(temperature=0, model=expt_llm)\n",
|
||||
"code_gen_chain = code_gen_prompt | llm.with_structured_output(code)\n",
|
||||
@@ -181,6 +182,7 @@
|
||||
"\n",
|
||||
"structured_llm_claude = llm.with_structured_output(code, include_raw=True)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Optional: Check for errors in case tool use is flaky\n",
|
||||
"def check_claude_output(tool_output):\n",
|
||||
" \"\"\"Check for parse error or failure to call the tool\"\"\"\n",
|
||||
@@ -189,7 +191,7 @@
|
||||
" if tool_output[\"parsing_error\"]:\n",
|
||||
" # Report back output and parsing errors\n",
|
||||
" print(\"Parsing error!\")\n",
|
||||
" raw_output = str(code_output[\"raw\"].content)\n",
|
||||
" raw_output = str(tool_output[\"raw\"].content)\n",
|
||||
" error = tool_output[\"parsing_error\"]\n",
|
||||
" raise ValueError(\n",
|
||||
" f\"Error parsing your output! Be sure to invoke the tool. Output: {raw_output}. \\n Parse error: {error}\"\n",
|
||||
@@ -199,15 +201,17 @@
|
||||
" elif not tool_output[\"parsed\"]:\n",
|
||||
" print(\"Failed to invoke tool!\")\n",
|
||||
" raise ValueError(\n",
|
||||
" f\"You did not use the provided tool! Be sure to invoke the tool to structure the output.\"\n",
|
||||
" \"You did not use the provided tool! Be sure to invoke the tool to structure the output.\"\n",
|
||||
" )\n",
|
||||
" return tool_output\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Chain with output check\n",
|
||||
"code_chain_claude_raw = (\n",
|
||||
" code_gen_prompt_claude | structured_llm_claude | check_claude_output\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def insert_errors(inputs):\n",
|
||||
" \"\"\"Insert errors for tool parsing in the messages\"\"\"\n",
|
||||
"\n",
|
||||
@@ -240,6 +244,7 @@
|
||||
"\n",
|
||||
" return solution[\"parsed\"]\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Optional: With re-try to correct for failure to invoke tool\n",
|
||||
"code_gen_chain = code_gen_chain_re_try | parse_output\n",
|
||||
"\n",
|
||||
@@ -281,7 +286,7 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from typing import Dict, TypedDict, List\n",
|
||||
"from typing import List, TypedDict\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"class GraphState(TypedDict):\n",
|
||||
@@ -318,10 +323,7 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from operator import itemgetter\n",
|
||||
"from langchain_core.pydantic_v1 import BaseModel, Field\n",
|
||||
"from langchain_core.runnables import RunnablePassthrough\n",
|
||||
"from langchain_core.prompts import PromptTemplate\n",
|
||||
"\n",
|
||||
"### Parameter\n",
|
||||
"\n",
|
||||
@@ -396,7 +398,6 @@
|
||||
" iterations = state[\"iterations\"]\n",
|
||||
"\n",
|
||||
" # Get solution components\n",
|
||||
" prefix = code_solution.prefix\n",
|
||||
" imports = code_solution.imports\n",
|
||||
" code = code_solution.code\n",
|
||||
"\n",
|
||||
@@ -457,14 +458,6 @@
|
||||
" code_solution = state[\"generation\"]\n",
|
||||
"\n",
|
||||
" # Prompt reflection\n",
|
||||
" reflection_message = [\n",
|
||||
" (\n",
|
||||
" \"user\",\n",
|
||||
" \"\"\"You tried to solve this problem and failed a unit test. Reflect on this failure\n",
|
||||
" given the provided documentation. Write a few key suggestions based on the \n",
|
||||
" documentation to avoid making this mistake again.\"\"\",\n",
|
||||
" )\n",
|
||||
" ]\n",
|
||||
"\n",
|
||||
" # Add reflection\n",
|
||||
" reflections = code_gen_chain.invoke(\n",
|
||||
@@ -613,7 +606,7 @@
|
||||
" try:\n",
|
||||
" exec(imports)\n",
|
||||
" return {\"key\": \"import_check\", \"score\": 1}\n",
|
||||
" except:\n",
|
||||
" except Exception:\n",
|
||||
" return {\"key\": \"import_check\", \"score\": 0}\n",
|
||||
"\n",
|
||||
"\n",
|
||||
@@ -623,7 +616,7 @@
|
||||
" try:\n",
|
||||
" exec(imports + \"\\n\" + code)\n",
|
||||
" return {\"key\": \"code_execution_check\", \"score\": 1}\n",
|
||||
" except:\n",
|
||||
" except Exception:\n",
|
||||
" return {\"key\": \"code_execution_check\", \"score\": 0}"
|
||||
]
|
||||
},
|
||||
@@ -754,7 +747,7 @@
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.8"
|
||||
"version": "3.12.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
@@ -55,8 +55,9 @@
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"os.environ['TOKENIZERS_PARALLELISM'] = 'true'\n",
|
||||
"mistral_api_key = os.getenv(\"MISTRAL_API_KEY\") # Ensure this is set"
|
||||
"\n",
|
||||
"os.environ[\"TOKENIZERS_PARALLELISM\"] = \"true\"\n",
|
||||
"mistral_api_key = os.getenv(\"MISTRAL_API_KEY\") # Ensure this is set"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -76,19 +77,9 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"os.environ['LANGCHAIN_TRACING_V2'] = 'true'\n",
|
||||
"os.environ['LANGCHAIN_ENDPOINT'] = 'https://api.smith.langchain.com'\n",
|
||||
"os.environ['LANGCHAIN_API_KEY'] = <your-api-key>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"id": "949efd30-44c7-4a4c-a05f-eca4e2769a61",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
|
||||
"os.environ[\"LANGCHAIN_ENDPOINT\"] = \"https://api.smith.langchain.com\"\n",
|
||||
"os.environ[\"LANGCHAIN_API_KEY\"] = \"<your-api-key>\"\n",
|
||||
"os.environ[\"LANGCHAIN_PROJECT\"] = \"Mistral-code-gen-testing\""
|
||||
]
|
||||
},
|
||||
@@ -110,18 +101,18 @@
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Select LLM\n",
|
||||
"from langchain_mistralai import ChatMistralAI\n",
|
||||
"from langchain_core.prompts import ChatPromptTemplate\n",
|
||||
"from langchain_core.pydantic_v1 import BaseModel, Field\n",
|
||||
"from langchain_mistralai import ChatMistralAI\n",
|
||||
"\n",
|
||||
"mistral_model = \"mistral-large-latest\"\n",
|
||||
"llm = ChatMistralAI(model=mistral_model, temperature=0)\n",
|
||||
"\n",
|
||||
"# Prompt \n",
|
||||
"# Prompt\n",
|
||||
"code_gen_prompt_claude = ChatPromptTemplate.from_messages(\n",
|
||||
" [\n",
|
||||
" (\n",
|
||||
" \"system\", \n",
|
||||
" \"system\",\n",
|
||||
" \"\"\"You are a coding assistant. Ensure any code you provide can be executed with all required imports and variables \\n\n",
|
||||
" defined. Structure your answer: 1) a prefix describing the code solution, 2) the imports, 3) the functioning code block.\n",
|
||||
" \\n Here is the user question:\"\"\",\n",
|
||||
@@ -130,6 +121,7 @@
|
||||
" ]\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Data model\n",
|
||||
"class code(BaseModel):\n",
|
||||
" \"\"\"Code output\"\"\"\n",
|
||||
@@ -139,6 +131,7 @@
|
||||
" code: str = Field(description=\"Code block not including import statements\")\n",
|
||||
" description = \"Schema for code solutions to questions about LCEL.\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# LLM\n",
|
||||
"code_gen_chain = llm.with_structured_output(code, include_raw=False)"
|
||||
]
|
||||
@@ -192,10 +185,11 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from typing import Annotated\n",
|
||||
"from typing import Dict, TypedDict, List\n",
|
||||
"from typing import Annotated, TypedDict\n",
|
||||
"\n",
|
||||
"from langgraph.graph.message import AnyMessage, add_messages\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"class GraphState(TypedDict):\n",
|
||||
" \"\"\"\n",
|
||||
" Represents the state of our graph.\n",
|
||||
@@ -228,14 +222,14 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from operator import itemgetter\n",
|
||||
"import uuid\n",
|
||||
"\n",
|
||||
"from langchain_core.pydantic_v1 import BaseModel, Field\n",
|
||||
"from langchain_core.runnables import RunnablePassthrough\n",
|
||||
"from langchain_core.prompts import PromptTemplate\n",
|
||||
"\n",
|
||||
"### Parameters\n",
|
||||
"max_iterations = 3\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"### Nodes\n",
|
||||
"def generate(state: GraphState):\n",
|
||||
" \"\"\"\n",
|
||||
@@ -253,7 +247,6 @@
|
||||
" # State\n",
|
||||
" messages = state[\"messages\"]\n",
|
||||
" iterations = state[\"iterations\"]\n",
|
||||
" error = state[\"error\"]\n",
|
||||
"\n",
|
||||
" # Solution\n",
|
||||
" code_solution = code_gen_chain.invoke(messages)\n",
|
||||
@@ -268,6 +261,7 @@
|
||||
" iterations = iterations + 1\n",
|
||||
" return {\"generation\": code_solution, \"messages\": messages, \"iterations\": iterations}\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def code_check(state: GraphState):\n",
|
||||
" \"\"\"\n",
|
||||
" Check code\n",
|
||||
@@ -287,7 +281,6 @@
|
||||
" iterations = state[\"iterations\"]\n",
|
||||
"\n",
|
||||
" # Get solution components\n",
|
||||
" prefix = code_solution.prefix\n",
|
||||
" imports = code_solution.imports\n",
|
||||
" code = code_solution.code\n",
|
||||
"\n",
|
||||
@@ -296,7 +289,12 @@
|
||||
" exec(imports)\n",
|
||||
" except Exception as e:\n",
|
||||
" print(\"---CODE IMPORT CHECK: FAILED---\")\n",
|
||||
" error_message = [(\"user\", f\"Your solution failed the import test. Here is the error: {e}. Reflect on this error and your prior attempt to solve the problem. (1) State what you think went wrong with the prior solution and (2) try to solve this problem again. Return the FULL SOLUTION. Use the code tool to structure the output with a prefix, imports, and code block:\")]\n",
|
||||
" error_message = [\n",
|
||||
" (\n",
|
||||
" \"user\",\n",
|
||||
" f\"Your solution failed the import test. Here is the error: {e}. Reflect on this error and your prior attempt to solve the problem. (1) State what you think went wrong with the prior solution and (2) try to solve this problem again. Return the FULL SOLUTION. Use the code tool to structure the output with a prefix, imports, and code block:\",\n",
|
||||
" )\n",
|
||||
" ]\n",
|
||||
" messages += error_message\n",
|
||||
" return {\n",
|
||||
" \"generation\": code_solution,\n",
|
||||
@@ -314,7 +312,12 @@
|
||||
" exec(combined_code, global_scope)\n",
|
||||
" except Exception as e:\n",
|
||||
" print(\"---CODE BLOCK CHECK: FAILED---\")\n",
|
||||
" error_message = [(\"user\", f\"Your solution failed the code execution test: {e}) Reflect on this error and your prior attempt to solve the problem. (1) State what you think went wrong with the prior solution and (2) try to solve this problem again. Return the FULL SOLUTION. Use the code tool to structure the output with a prefix, imports, and code block:\")]\n",
|
||||
" error_message = [\n",
|
||||
" (\n",
|
||||
" \"user\",\n",
|
||||
" f\"Your solution failed the code execution test: {e}) Reflect on this error and your prior attempt to solve the problem. (1) State what you think went wrong with the prior solution and (2) try to solve this problem again. Return the FULL SOLUTION. Use the code tool to structure the output with a prefix, imports, and code block:\",\n",
|
||||
" )\n",
|
||||
" ]\n",
|
||||
" messages += error_message\n",
|
||||
" return {\n",
|
||||
" \"generation\": code_solution,\n",
|
||||
@@ -332,8 +335,10 @@
|
||||
" \"error\": \"no\",\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"### Conditional edges\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def decide_to_finish(state: GraphState):\n",
|
||||
" \"\"\"\n",
|
||||
" Determines whether to finish.\n",
|
||||
@@ -354,14 +359,14 @@
|
||||
" print(\"---DECISION: RE-TRY SOLUTION---\")\n",
|
||||
" return \"generate\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"### Utilities\n",
|
||||
"\n",
|
||||
"import uuid \n",
|
||||
"\n",
|
||||
"def _print_event(event: dict, _printed: set, max_length=1500):\n",
|
||||
" current_state = event.get(\"dialog_state\")\n",
|
||||
" if current_state:\n",
|
||||
" print(f\"Currently in: \", current_state[-1])\n",
|
||||
" print(\"Currently in: \", current_state[-1])\n",
|
||||
" message = event.get(\"messages\")\n",
|
||||
" if message:\n",
|
||||
" if isinstance(message, list):\n",
|
||||
@@ -428,7 +433,7 @@
|
||||
"\n",
|
||||
"try:\n",
|
||||
" display(Image(graph.get_graph(xray=True).draw_mermaid_png()))\n",
|
||||
"except:\n",
|
||||
"except Exception:\n",
|
||||
" # This requires some extra dependencies and is optional\n",
|
||||
" pass"
|
||||
]
|
||||
@@ -554,6 +559,7 @@
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import uuid\n",
|
||||
"\n",
|
||||
"_printed = set()\n",
|
||||
"thread_id = str(uuid.uuid4())\n",
|
||||
"config = {\n",
|
||||
@@ -563,7 +569,7 @@
|
||||
" }\n",
|
||||
"}\n",
|
||||
"\n",
|
||||
"question = '''I want to vectorize a function\n",
|
||||
"question = \"\"\"I want to vectorize a function\n",
|
||||
"\n",
|
||||
" frame = np.zeros((out_h, out_w, 3), dtype=np.uint8)\n",
|
||||
" for i, val1 in enumerate(rows):\n",
|
||||
@@ -574,7 +580,7 @@
|
||||
"\n",
|
||||
" out.write(np.array(frame))\n",
|
||||
"\n",
|
||||
"with a simple numpy function that does something like this what is it called. Show me a test case with this working.'''\n",
|
||||
"with a simple numpy function that does something like this what is it called. Show me a test case with this working.\"\"\"\n",
|
||||
"\n",
|
||||
"events = graph.stream(\n",
|
||||
" {\"messages\": [(\"user\", question)], \"iterations\": 0}, config, stream_mode=\"values\"\n",
|
||||
|
||||
Reference in New Issue
Block a user