-
Notifications
You must be signed in to change notification settings - Fork 0
/
lchain.py
30 lines (23 loc) · 982 Bytes
/
lchain.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# pip install langchain langchain-openai e2b-code-interpreter
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from e2b_code_interpreter import Sandbox
system_prompt = "You are a helpful assistant that can execute python code in a Jupyter notebook. Only respond with the code to be executed and nothing else. Strip backticks in code blocks."
prompt = "Calculate how many r's are in the word 'strawberry'"
# Create LangChain components
llm = ChatOpenAI(model="gpt-4o")
prompt_template = ChatPromptTemplate.from_messages([
("system", system_prompt),
("human", "{input}")
])
output_parser = StrOutputParser()
# Create the chain
chain = prompt_template | llm | output_parser
# Run the chain
code = chain.invoke({"input": prompt})
# Execute code in E2B Sandbox
with Sandbox() as sandbox:
execution = sandbox.run_code(code)
result = execution.text
print(result)