Notebooks
M
Mistral AI
Langgraph Code Assistant Mistral

Langgraph Code Assistant Mistral

mistral-cookbookthird_partylangchain

Codestral with self-correction

Codestral is a cutting-edge generative model that has been specifically designed and optimized for code generation tasks, including fill-in-the-middle and code completion. Codestral was trained on 80+ programming languages, enabling it to perform well on both common and less common languages

We can combine the code generation capabilities of Codestral the self-correction approach presented in the AlphaCodium paper, constructing an answer to a coding question iteratively.

We will implement some of these ideas from scratch using LangGraph to 1) produce structured code generation output from Codestral-instruct, 2) perform inline unit tests to confirm imports and code execution work, 3) feed back any errors for Codestral for self-correction.

Screenshot 2024-05-23 at 2.17.51 PM.png

[ ]

LLM

We'll use the Mistral API and Codestral instruct model, which support tool use!

[2]

Optionally, you can use LangSmith for tracing.

[3]

Code Generation

Test with structured output.

[6]
[7]
[8]
code(prefix='A function to calculate the nth Fibonacci number.', imports='', code='def fibonacci(n):\n    if n <= 0:\n        return "Input should be positive integer"\n    elif n == 1:\n        return 0\n    elif n == 2:\n        return 1\n    else:\n        a, b = 0, 1\n        for _ in range(2, n):\n            a, b = b, a + b\n        return b')

Graph

We build the above workflow as a graph using LangGraph.

Graph state

The graph state schema contains keys that we want to:

  • Pass to each node in our graph
  • Optionally, modify in each node of our graph

See conceptual docs here.

[9]

Graph

[17]

We'll add persistence to the graph using a checkpointer.

[18]
Output
[19]
{'messages': [HumanMessage(content="Write a Python program that prints 'Hello, World!' to the console.", additional_kwargs={}, response_metadata={}, id='9dd8d0c4-50f7-4b1d-8377-82e16ff0261d')], 'iterations': 0}
---GENERATING CODE SOLUTION---
{'messages': [HumanMessage(content="Write a Python program that prints 'Hello, World!' to the console.", additional_kwargs={}, response_metadata={}, id='9dd8d0c4-50f7-4b1d-8377-82e16ff0261d'), AIMessage(content="Here is my attempt to solve the problem: The task is to write a simple Python program that prints 'Hello, World!' to the console. There are no specific imports required for this task. \n Imports:  \n Code: print('Hello, World!')", additional_kwargs={}, response_metadata={}, id='4f9368ca-af4e-44c6-9473-330d8c9000ee'), AIMessage(content="Here is my attempt to solve the problem: The task is to write a simple Python program that prints 'Hello, World!' to the console. There are no specific imports required for this task. \n Imports:  \n Code: print('Hello, World!')", additional_kwargs={}, response_metadata={}, id='7a9bcea4-e55b-4ceb-afa4-5b5fb9a2149d')], 'generation': code(prefix="The task is to write a simple Python program that prints 'Hello, World!' to the console. There are no specific imports required for this task.", imports='', code="print('Hello, World!')"), 'iterations': 1}
---CHECKING CODE---
Hello, World!
---NO CODE TEST FAILURES---
---DECISION: FINISH---
{'error': 'no', 'messages': [HumanMessage(content="Write a Python program that prints 'Hello, World!' to the console.", additional_kwargs={}, response_metadata={}, id='9dd8d0c4-50f7-4b1d-8377-82e16ff0261d'), AIMessage(content="Here is my attempt to solve the problem: The task is to write a simple Python program that prints 'Hello, World!' to the console. There are no specific imports required for this task. \n Imports:  \n Code: print('Hello, World!')", additional_kwargs={}, response_metadata={}, id='4f9368ca-af4e-44c6-9473-330d8c9000ee'), AIMessage(content="Here is my attempt to solve the problem: The task is to write a simple Python program that prints 'Hello, World!' to the console. There are no specific imports required for this task. \n Imports:  \n Code: print('Hello, World!')", additional_kwargs={}, response_metadata={}, id='7a9bcea4-e55b-4ceb-afa4-5b5fb9a2149d')], 'generation': code(prefix="The task is to write a simple Python program that prints 'Hello, World!' to the console. There are no specific imports required for this task.", imports='', code="print('Hello, World!')"), 'iterations': 1}
[21]
{'messages': [HumanMessage(content='Create a Python program that allows two players to play a game of Tic-Tac-Toe. The game should be played on a 3x3 grid. The program should:\n\n- Allow players to take turns to input their moves.\n- Check for invalid moves (e.g., placing a marker on an already occupied space).\n- Determine and announce the winner or if the game ends in a draw.\n\nRequirements:\n- Use a 2D list to represent the Tic-Tac-Toe board.\n- Use functions to modularize the code.\n- Validate player input.\n- Check for win conditions and draw conditions after each move.', additional_kwargs={}, response_metadata={}, id='8950badb-d5f4-4ccf-b55f-f52a74ad3e68')], 'iterations': 0}
---GENERATING CODE SOLUTION---
{'messages': [HumanMessage(content='Create a Python program that allows two players to play a game of Tic-Tac-Toe. The game should be played on a 3x3 grid. The program should:\n\n- Allow players to take turns to input their moves.\n- Check for invalid moves (e.g., placing a marker on an already occupied space).\n- Determine and announce the winner or if the game ends in a draw.\n\nRequirements:\n- Use a 2D list to represent the Tic-Tac-Toe board.\n- Use functions to modularize the code.\n- Validate player input.\n- Check for win conditions and draw conditions after each move.', additional_kwargs={}, response_metadata={}, id='8950badb-d5f4-4ccf-b55f-f52a74ad3e68'), AIMessage(content="Here is my attempt to solve the problem: The program will use a 2D list to represent the Tic-Tac-Toe board. It will have functions to display the board, check for win conditions, check for draw conditions, and validate player input. The game will be played in a loop until a win condition is met or the board is full. \n Imports:  \n Code: board = [[' ' for _ in range(3)] for _ in range(3)]\n\ndef display_board():\n    for row in board:\n        print('|'.join(row))\n        print('-' * 5)\n\ndef check_win(player):\n    for row in board:\n        if all(cell == player for cell in row):\n            return True\n    for col in range(3):\n        if all(board[row][col] == player for row in range(3)):\n            return True\n    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):\n        return True\n    return False\n\ndef check_draw():\n    return all(cell != ' ' for row in board for cell in row)\n\ndef validate_input(move):\n    try:\n        row, col = map(int, move.split(','))\n        if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == ' ':\n            return row, col\n    except:\n        pass\n    return None\n\nplayers = ['X', 'O']\ncurrent_player = 0\n\nwhile True:\n    display_board()\n    move = input(f'Player {players[current_player]}, enter your move (row,col): ')\n    move = validate_input(move)\n    if move is None:\n        print('Invalid move. Try again.')\n        continue\n    row, col = move\n    board[row][col] = players[current_player]\n    if check_win(players[current_player]):\n        display_board()\n        print(f'Player {players[current_player]} wins!')\n        break\n    if check_draw():\n        display_board()\n        print('The game is a draw.')\n        break\n    current_player = (current_player + 1) % 2", additional_kwargs={}, response_metadata={}, id='d82552ee-3ecd-4174-8c19-adb7895d7226'), AIMessage(content="Here is my attempt to solve the problem: The program will use a 2D list to represent the Tic-Tac-Toe board. It will have functions to display the board, check for win conditions, check for draw conditions, and validate player input. The game will be played in a loop until a win condition is met or the board is full. \n Imports:  \n Code: board = [[' ' for _ in range(3)] for _ in range(3)]\n\ndef display_board():\n    for row in board:\n        print('|'.join(row))\n        print('-' * 5)\n\ndef check_win(player):\n    for row in board:\n        if all(cell == player for cell in row):\n            return True\n    for col in range(3):\n        if all(board[row][col] == player for row in range(3)):\n            return True\n    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):\n        return True\n    return False\n\ndef check_draw():\n    return all(cell != ' ' for row in board for cell in row)\n\ndef validate_input(move):\n    try:\n        row, col = map(int, move.split(','))\n        if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == ' ':\n            return row, col\n    except:\n        pass\n    return None\n\nplayers = ['X', 'O']\ncurrent_player = 0\n\nwhile True:\n    display_board()\n    move = input(f'Player {players[current_player]}, enter your move (row,col): ')\n    move = validate_input(move)\n    if move is None:\n        print('Invalid move. Try again.')\n        continue\n    row, col = move\n    board[row][col] = players[current_player]\n    if check_win(players[current_player]):\n        display_board()\n        print(f'Player {players[current_player]} wins!')\n        break\n    if check_draw():\n        display_board()\n        print('The game is a draw.')\n        break\n    current_player = (current_player + 1) % 2", additional_kwargs={}, response_metadata={}, id='a801bf87-9ae6-4de0-8163-b1a37f2aee65')], 'generation': code(prefix='The program will use a 2D list to represent the Tic-Tac-Toe board. It will have functions to display the board, check for win conditions, check for draw conditions, and validate player input. The game will be played in a loop until a win condition is met or the board is full.', imports='', code="board = [[' ' for _ in range(3)] for _ in range(3)]\n\ndef display_board():\n    for row in board:\n        print('|'.join(row))\n        print('-' * 5)\n\ndef check_win(player):\n    for row in board:\n        if all(cell == player for cell in row):\n            return True\n    for col in range(3):\n        if all(board[row][col] == player for row in range(3)):\n            return True\n    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):\n        return True\n    return False\n\ndef check_draw():\n    return all(cell != ' ' for row in board for cell in row)\n\ndef validate_input(move):\n    try:\n        row, col = map(int, move.split(','))\n        if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == ' ':\n            return row, col\n    except:\n        pass\n    return None\n\nplayers = ['X', 'O']\ncurrent_player = 0\n\nwhile True:\n    display_board()\n    move = input(f'Player {players[current_player]}, enter your move (row,col): ')\n    move = validate_input(move)\n    if move is None:\n        print('Invalid move. Try again.')\n        continue\n    row, col = move\n    board[row][col] = players[current_player]\n    if check_win(players[current_player]):\n        display_board()\n        print(f'Player {players[current_player]} wins!')\n        break\n    if check_draw():\n        display_board()\n        print('The game is a draw.')\n        break\n    current_player = (current_player + 1) % 2"), 'iterations': 1}
---CHECKING CODE---
 | | 
-----
 | | 
-----
 | | 
-----
Invalid move. Try again.
 | | 
-----
 | | 
-----
 | | 
-----
X| | 
-----
 | | 
-----
 | | 
-----
X| | 
-----
O| | 
-----
 | | 
-----
X| | 
-----
O| | 
-----
X| | 
-----
X| | 
-----
O| | 
-----
X|O| 
-----
X| | 
-----
O|X| 
-----
X|O| 
-----
X|O| 
-----
O|X| 
-----
X|O| 
-----
X|O|X
-----
O|X| 
-----
X|O| 
-----
Player X wins!
---NO CODE TEST FAILURES---
---DECISION: FINISH---
{'error': 'no', 'messages': [HumanMessage(content='Create a Python program that allows two players to play a game of Tic-Tac-Toe. The game should be played on a 3x3 grid. The program should:\n\n- Allow players to take turns to input their moves.\n- Check for invalid moves (e.g., placing a marker on an already occupied space).\n- Determine and announce the winner or if the game ends in a draw.\n\nRequirements:\n- Use a 2D list to represent the Tic-Tac-Toe board.\n- Use functions to modularize the code.\n- Validate player input.\n- Check for win conditions and draw conditions after each move.', additional_kwargs={}, response_metadata={}, id='8950badb-d5f4-4ccf-b55f-f52a74ad3e68'), AIMessage(content="Here is my attempt to solve the problem: The program will use a 2D list to represent the Tic-Tac-Toe board. It will have functions to display the board, check for win conditions, check for draw conditions, and validate player input. The game will be played in a loop until a win condition is met or the board is full. \n Imports:  \n Code: board = [[' ' for _ in range(3)] for _ in range(3)]\n\ndef display_board():\n    for row in board:\n        print('|'.join(row))\n        print('-' * 5)\n\ndef check_win(player):\n    for row in board:\n        if all(cell == player for cell in row):\n            return True\n    for col in range(3):\n        if all(board[row][col] == player for row in range(3)):\n            return True\n    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):\n        return True\n    return False\n\ndef check_draw():\n    return all(cell != ' ' for row in board for cell in row)\n\ndef validate_input(move):\n    try:\n        row, col = map(int, move.split(','))\n        if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == ' ':\n            return row, col\n    except:\n        pass\n    return None\n\nplayers = ['X', 'O']\ncurrent_player = 0\n\nwhile True:\n    display_board()\n    move = input(f'Player {players[current_player]}, enter your move (row,col): ')\n    move = validate_input(move)\n    if move is None:\n        print('Invalid move. Try again.')\n        continue\n    row, col = move\n    board[row][col] = players[current_player]\n    if check_win(players[current_player]):\n        display_board()\n        print(f'Player {players[current_player]} wins!')\n        break\n    if check_draw():\n        display_board()\n        print('The game is a draw.')\n        break\n    current_player = (current_player + 1) % 2", additional_kwargs={}, response_metadata={}, id='d82552ee-3ecd-4174-8c19-adb7895d7226'), AIMessage(content="Here is my attempt to solve the problem: The program will use a 2D list to represent the Tic-Tac-Toe board. It will have functions to display the board, check for win conditions, check for draw conditions, and validate player input. The game will be played in a loop until a win condition is met or the board is full. \n Imports:  \n Code: board = [[' ' for _ in range(3)] for _ in range(3)]\n\ndef display_board():\n    for row in board:\n        print('|'.join(row))\n        print('-' * 5)\n\ndef check_win(player):\n    for row in board:\n        if all(cell == player for cell in row):\n            return True\n    for col in range(3):\n        if all(board[row][col] == player for row in range(3)):\n            return True\n    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):\n        return True\n    return False\n\ndef check_draw():\n    return all(cell != ' ' for row in board for cell in row)\n\ndef validate_input(move):\n    try:\n        row, col = map(int, move.split(','))\n        if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == ' ':\n            return row, col\n    except:\n        pass\n    return None\n\nplayers = ['X', 'O']\ncurrent_player = 0\n\nwhile True:\n    display_board()\n    move = input(f'Player {players[current_player]}, enter your move (row,col): ')\n    move = validate_input(move)\n    if move is None:\n        print('Invalid move. Try again.')\n        continue\n    row, col = move\n    board[row][col] = players[current_player]\n    if check_win(players[current_player]):\n        display_board()\n        print(f'Player {players[current_player]} wins!')\n        break\n    if check_draw():\n        display_board()\n        print('The game is a draw.')\n        break\n    current_player = (current_player + 1) % 2", additional_kwargs={}, response_metadata={}, id='a801bf87-9ae6-4de0-8163-b1a37f2aee65')], 'generation': code(prefix='The program will use a 2D list to represent the Tic-Tac-Toe board. It will have functions to display the board, check for win conditions, check for draw conditions, and validate player input. The game will be played in a loop until a win condition is met or the board is full.', imports='', code="board = [[' ' for _ in range(3)] for _ in range(3)]\n\ndef display_board():\n    for row in board:\n        print('|'.join(row))\n        print('-' * 5)\n\ndef check_win(player):\n    for row in board:\n        if all(cell == player for cell in row):\n            return True\n    for col in range(3):\n        if all(board[row][col] == player for row in range(3)):\n            return True\n    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):\n        return True\n    return False\n\ndef check_draw():\n    return all(cell != ' ' for row in board for cell in row)\n\ndef validate_input(move):\n    try:\n        row, col = map(int, move.split(','))\n        if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == ' ':\n            return row, col\n    except:\n        pass\n    return None\n\nplayers = ['X', 'O']\ncurrent_player = 0\n\nwhile True:\n    display_board()\n    move = input(f'Player {players[current_player]}, enter your move (row,col): ')\n    move = validate_input(move)\n    if move is None:\n        print('Invalid move. Try again.')\n        continue\n    row, col = move\n    board[row][col] = players[current_player]\n    if check_win(players[current_player]):\n        display_board()\n        print(f'Player {players[current_player]} wins!')\n        break\n    if check_draw():\n        display_board()\n        print('The game is a draw.')\n        break\n    current_player = (current_player + 1) % 2"), 'iterations': 1}
[ ]