안녕하십니까! 강의 잘 듣고 있습니다. pyzerox를 gpt-4o-mini 모델을 사용하하는 중 아래와 같은 에러가 발생을 합니다. ``` ModuleNotFoundError Traceback (most recent call last) Cell In[13], line 1----> 1 from pyzerox import zerox 2 import asyncio 4 ### Model Setup (Use only Vision Models) Refer: https://docs.litellm.ai/docs/providers ### 56 ## placeholder for additional model kwargs which might be required for some models File ~/desktop/langgraph/.venv/lib/python3.12/site-packages/pyzerox/__init__.py:1----> 1 from .core import zerox 2 from .constants.prompts import Prompts 4 DEFAULT_SYSTEM_PROMPT = Prompts.DEFAULT_SYSTEM_PROMPT File ~/desktop/langgraph/.venv/lib/python3.12/site-packages/pyzerox/core/__init__.py:1----> 1 from .zerox import zerox 3 all = [ 4 "zerox" , 5 ] File ~/desktop/langgraph/.venv/lib/python3.12/site-packages/pyzerox/core/zerox.py:1310 from ..constants import PDFConversionDefaultOptions 12 # Package Imports ---> 13 from ..processor import ( 14 convert_pdf_to_images, ... 12 ) 13 from litellm.caching import InMemoryCache 14 from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj ModuleNotFoundError : No module named 'enterprise' ``` !uv pip install py-zerox from pyzerox import zerox import asyncio ### Model Setup (Use only Vision Models) Refer: https://docs.litellm.ai/docs/providers ### ## placeholder for additional model kwargs which might be required for some models kwargs = {} ## system prompt to use for the vision model custom_system_prompt = None # to override # custom_system_prompt = "For the below PDF page, do something..something..." ## example ###################### Example for OpenAI ###################### model = "gpt-4o-mini" ## openai model # Define main async entrypoint async def main(): file_path = "./income_tax.pdf" ## local filepath and file URL supported ## process only some pages or all select_pages = None ## None for all, but could be int or list(int) page numbers (1 indexed) output_dir = "./documents" ## directory to save the consolidated markdown file result = await zerox(file_path=file_path, model=model, output_dir=output_dir, custom_system_prompt=custom_system_prompt,select_pages=select_pages, **kwargs) return result # run the main function: result = asyncio.run(main()) # print markdown result print(result) 코드는 위와 같습니다. pyzerox 가 수업 중 litellm 을 사용한다고 하셨는데 (py-zerox 설치시 1.67.4 버전으로 같이 설치됨) Enterprise용 littellm을 사용하면서 생긴 문제인 것 같은데요 기존 설치된 littellm 을 upgrade 하니 다른 오류인 ModelAccessError : Your provided model can't be accessed. Please make sure you have access to the model and also required environment variables are setup correctly including valid api key(s). Refer: https://docs.litellm.ai/docs/providers (Extra Info: {'model': 'gpt-4o-mini'}) 이런 오류가 발생합니다. 현재 사용중인 OPENAI_API_KEY 를 이용해 llm.invoke 시 응답이 잘 오는 걸 봐서는 해당 모델을 사용하는데 문제는 없는 것으로 보입니다. 혹시 지금까지 어떤 문제점이 있는지 알 수 있을지요?
강사님 안녕하세요! 하단의 generate함수는 파라미터로 AgentState를 받고 AgentState를 리턴하는데 함수의 리턴값이 "context"를 key로 가지는 딕셔너리형태인데, 어떻게 AgentState가 되는지 궁금합니다.. ㅠㅠ class AgentState(TypedDict): query: str context: List[Document] answer: str def retrieve(state: AgentState) -> AgentState: """ 사용자의 질문에 기반하여 벡터 스토어에서 관련 문서를 검색합니다. Args: state (AgentState): 사용자의 질문을 포함한 에이전트의 현재 state. Returns: AgentState: 검색된 문서가 추가된 state를 반환합니다. """ query = state['query'] docs = retriever.invoke(query) return {'context': docs}
안녕하세요 강사님 강의가 거의 대부분 이해가 될 듯 말듯합니다. 강의코드를 다 잘 아시니까, 이게 이런거고 저게저런거다라고 쭈욱 빠르게 얘기해주시는데, 이해시키기보단 강사님이 아시는걸 설명하시는 느낌이에요. 근데, 반쯤 이해되는 상태이고, 코드 따라 안써봐도 되겠죠? 커서로 짜주는 코드를 해석하는 능력을 기르는게 중요하다고 하셨으니까요..!! 일단 정주행해도 될지, 아니면 제가 방향을 잘못잡고있는지 궁금해서 질문남겼습니다!! 열의있게 강의해주셔서 감사합니다.
안녕하세요 강사님 정해져있는 문서를 Rag로 가져오는것이 아닌 openAPI에서 필요한 정보를 호출해서 가져오도록 만들고 싶습니다. openAPI에 requests로 호출해서 데이터를 가져오는 부분까지 완성했습니다. 수업중에 llm에게 dictionary 지정해주는것처럼 openAPI에서 호출한 정보를 rag로 가져오도록 하는 방법을 가르쳐주세요 감사합니다
안녕하세요 선생님 수업 잘 듣고 열심히 만들고 있는데 한가지 해결이 안되는 부분이 있어 이렇게 글 남깁니다. 문서를 100개를 넣고, LLM이 대답할 때 인사규정에 따르면 혹은 인사규정을 참조하여 규정명을 나오게 하고 싶은데, 매칭이 잘안되거나 잘못된 규정명을 알려주곤 하는데 정확한 방법이 있을까요? 백터 DB에서 메타 데이터 지정하는 방식 이거나 document에 정의해 호출하는 방식 등을 사용하는데 .. 선생님도 이렇게 하실까요??
강의 시점: 섹션1 > 실습을 위한 환경 설정 방법에서 약 1분 16초 내용: 제공해주신 pyproject.toml에서 저는 파이썬 3.13 버전으로 설치되어 이 부분만 수정해 install하였습니다. 그랬더니 아래와 같이 numpy 설치 에러 문구가 뜨는데 왜 그런걸까요? 해결 방법이 있을까요? 에러 메시지 - Installing numpy (1.26.4): Failed PEP517 build of a dependency failed Backend subprocess exited when trying to invoke build_wheel Note: This error originates from the build backend, and is likely not a problem with poetry but one of the following issues with numpy (1.26.4) - not supporting PEP 517 builds - not specifying PEP 517 build requirements correctly - the build requirements are incompatible with your operating system or Python version - the build requirements are missing system dependencies (eg: compilers, libraries, headers). You can verify this by running pip wheel --no-cache-dir --use-pep517 "numpy (==1.26.4)".
안녕하십니까 강의 잘 듣고있습니다.! from langchain_ollama import OllamaEmbeddings embeddings = OllamaEmbeddings(model="llama3.2") import os from pinecone import Pinecone from langchain_pinecone import PineconeVectorStore index_name = "tax-table-index" pinecone_api_key = os.environ.get("PINECONE_API_KEY") pc = Pinecone(api_key=pinecone_api_key) database = PineconeVectorStore.from_documents(document_list, embedding=embeddings, index_name=index_name) Embedding 후 PinecondVectorStore 저장 할떄 아래와 같은 예외가 발생합니다. ``` PineconeApiException: (400) Reason: Bad Request HTTP response headers: HTTPHeaderDict({'Date': 'Thu, 17 Apr 2025 02:53:26 GMT', 'Content-Type': 'application/json', 'Content-Length': '118', 'Connection': 'keep-alive', 'x-pinecone-request-latency-ms': '2664', 'x-pinecone-request-id': '9090329298438964680', 'x-envoy-upstream-service-time': '2', 'server': 'envoy'}) HTTP response body: {"code":11,"message":"Error, message length too large: found 4194738 bytes, the limit is: 4194304 bytes","details":[]} Output is truncated. View as a scrollable element or open in a text editor. ``` OllamaEmbeddings(model="llama3.2") 를 사용하고 있는데요. 해당 모델로 임베딩을 하면 Pinecone에서 허용하는 데이터를 초과하는 것 으로 보이는데요 이러한 경우 처리하는 방법이 있을까요? 아니면 모델을 변경해야하는 걸까요?
'벡터 저장소(Vector Store)를 도구로 변환하기' 강의에서 'from langchain_chroma import Chroma' 부분 실행 시 아래와 같은 오류가 발생합니다. ValueError: The onnxruntime python package is not installed. Please install it with pip install onnxruntime pip install을 수행해도 에러는 동일하게 발생합니다. 구글 검색으로 Microsoft Visual C++ Redistributable 설치도 시도해 보았으나 여전히 동일합니다. 어떻게 해결해야할까요? 필요한 정보가 있다면 알려주세요.
from langgraph.graph import MessagesState, StateGraph, START, END from langchain_core.messages import HumanMessage, SystemMessage from langgraph.prebuilt import ToolNode from IPython.display import Image, display # LangGraph MessagesState 사용 class GraphState(MessagesState): pass # 노드 구성 def call_model(state: GraphState): system_message = SystemMessage(content=system_prompt) messages = [system_message] + state['messages'] response = llm_with_tools.invoke(messages) return {"messages": [response]} def should_continue(state: GraphState): last_message = state["messages"][-1] # 도구 호출이 있으면 도구 실행 노드로 이동 if last_message.tool_calls: return "execute_tools" # 도구 호출이 없으면 답변 생성하고 종료 return END # 그래프 구성 builder = StateGraph(GraphState) builder.add_node("call_model", call_model) builder.add_node("execute_tools", ToolNode(tools)) builder.add_edge(START, "call_model") builder.add_conditional_edges( "call_model", should_continue, { "execute_tools": "execute_tools", END: END } ) builder.add_edge("execute_tools", "call_model") graph = builder.compile() # 그래프 출력 display(Image(graph.get_graph().draw_mermaid_png())) # 그래프 실행 inputs = {"messages": [HumanMessage(content="스테이크 메뉴의 가격은 얼마인가요?")]} messages = graph.invoke(inputs) 위 코드는 강사님께서 제공해주신 코드를 가져온 것입니다. 제가 궁금한 것은 Tool 노드를 사용하고 다시 call_model 노드로 왔을 때 SytemMessage가 중복되지 않을까? 라는 생각을 했습니다. 예를 들어 message : [유저 인풋] 가 처음으로 그래프에 들어오게된다면 def call_model(state: GraphState): system_message = SystemMessage(content=system_prompt) messages = [system_message] + state['messages'] response = llm_with_tools.invoke(messages) return {"messages": [response]} message : SystemMessage + [유저 인풋] 이 될것입니다. 그 이후 response를 호출하여 message : SystemMessage + [유저 인풋] + toolMessage 이 되어 상태를 업데이트 하고, 그리고 tool 콜이 있어서 툴노드를 마무리 한 이후 돌아왔을 땐 GraphState에 있는 message는 SystemMessage + [유저 인풋] + toolMessage + [툴이보낸 메세지] 일테니 call model 노드에서 SystemMessage + SystemMessage + [유저 인풋] + toolMessage + [툴이보낸 메세지] 가 적용되어 툴 콜 할때마다 SytemMessage가 쌓이는 구조가 되지 않을까 생각이 들었는데 맞을까요?
OpenAI API랑 upstage 말고 hugging face에서 제공하는 LLM 모델을 사용하고 싶은데요 streamlit을 사용해서 출력된 response를 보니 아래와 같은 형태로 출력 되더라구요 사용한 모델명 : microsoft/Phi-3-mini-4k-instruct 인데.. 이 경우, 코드에서 전처리 해줘야 하나요? 제 코드는 아래와 같습니다 [llm.py] def get_llm(): model_id="microsoft/Phi-3-mini-4k-instruct" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained( model_id, device_map="auto", torch_dtype="auto" ) pipe = pipeline( "text-generation", model=model, tokenizer=tokenizer, max_new_tokens=512, do_sample=False, repetition_penalty=1.03 ) llm = HuggingFacePipeline(pipeline=pipe) # llm = HuggingFacePipeline.from_model_id( # model_id="microsoft/Phi-3-mini-4k-instruct", # task="text-generation", # model_kwargs=dict( # device_map="auto" # ), # pipeline_kwargs=dict( # max_new_tokens=512, # do_sample=False, # repetition_penalty=1.03, # ) # ) chat_model = ChatHuggingFace(llm=llm) return chat_model store = {} def get_session_history(session_id: str)->BaseChatMessageHistory: if session_id not in store: store[session_id] = ChatMessageHistory() return store[session_id] def get_template(): template = """ You are a helpful assistant. Answer the following questions considering the history of the conversation: Chat history : {chat_history} User question : {user_message} Assistant : """ prompt = ChatPromptTemplate.from_template(template) return prompt def get_ai_response(user_message,chat_history): llm = get_llm() prompt = get_template() chain = prompt | llm | StrOutputParser() ai_response = chain.invoke({ "chat_history": chat_history, "user_message": user_message, }) return ai_response [chat.py] if "chat_history" not in st.session_state: st.session_state.chat_history = [ {"role": "ai", "content": "Hello, I am a mini bot. How can I help you?"} ] for message in st.session_state.chat_history: with st.chat_message(message["role"]): st.write(message["content"]) user_question = st.chat_input(placeholder="Tell me a simple question!") if user_question is not None and user_question != "": st.session_state.chat_history.append({"role":"user", "content":user_question}) with st.chat_message("user"): st.markdown(user_question) with st.spinner("Generating response"): ai_response = get_ai_response(user_question, st.session_state.chat_history) with st.chat_message("ai"): st.markdown(ai_response) st.session_state.chat_history.append({"role":"ai", "content":ai_response})
OpenAI API를 활용하여 LLM Chain 구현하기 (실습) 에서 All attempts to connect to pypi.org failed. Probable Causes: - the server is not responding to requests at the moment - the hostname cannot be resolved by your DNS - your network is not connected to the internet You can also run your poetry command with -v to see more information. 이런 에러가뜹니다.. 미치겠네요..
강의중에 들어가시는 langchain 홈페이지가 지금이랑 version이 다른것 같은데 현재 version 홈페이지에서는 강의 내용에 나오는 곳을 찾을 수가 없습니다. 혹시 version이 달라도 괜찮을까요? 예를 들어 Microsoft Word Document loaders를 찾고 싶습니다.
안녕하세요 변정현 강사님. 강의 잘 듣고있습니다. 실습 수업 때는 주피터 노트북 형식으로 강의자료 다운로드가 가능한데, 혹시 이론강의 자료도 공유가 가능하신가해서 질문을 드립니다. 내용만 볼수있으면 pdf형식이나 워터마크가 추가되어도 크게 문제가 없을것 같은데, 혹시 가능하실까요?