|
| 1 | +from langfuse import Langfuse, propagate_attributes |
1 | 2 | from dataclasses import dataclass |
2 | 3 | from langfuse import Langfuse |
3 | 4 | from langchain.chat_models import BaseChatModel |
4 | 5 | from langgraph.runtime import Runtime |
5 | 6 | from langgraph.graph import END, START, MessagesState, StateGraph |
6 | 7 | from langgraph.checkpoint.memory import InMemorySaver |
7 | 8 | from langchain_ollama import ChatOllama |
| 9 | +from langchain_core.runnables import RunnableConfig |
8 | 10 |
|
9 | 11 |
|
10 | 12 | @dataclass |
11 | 13 | class ContextSchema: |
12 | | - prompt_registry: Langfuse |
| 14 | + langfuse: Langfuse |
13 | 15 | llm: BaseChatModel |
14 | 16 |
|
15 | 17 |
|
16 | | -def call_model(state: MessagesState, runtime: Runtime[ContextSchema]): |
17 | | - prompt_client = runtime.context.prompt_registry.get_prompt("hr_agent") |
18 | | - system_prompt = prompt_client.compile() |
19 | | - ai_msg = runtime.context.llm.invoke([system_prompt] + state["messages"]) |
20 | | - return {"messages": [ai_msg]} |
| 18 | +def call_model( |
| 19 | + state: MessagesState, runtime: Runtime[ContextSchema], config: RunnableConfig |
| 20 | +): |
| 21 | + langfuse = runtime.context.langfuse |
| 22 | + llm = runtime.context.llm |
| 23 | + thread_id = config["configurable"]["thread_id"] |
| 24 | + |
| 25 | + with propagate_attributes(session_id=thread_id): |
| 26 | + |
| 27 | + with langfuse.start_as_current_observation( |
| 28 | + as_type="span", name="call-model" |
| 29 | + ) as root_span: |
| 30 | + |
| 31 | + prompt_client = langfuse.get_prompt("hr_agent") |
| 32 | + system_prompt = prompt_client.compile() |
| 33 | + messages = [system_prompt] + state["messages"] |
| 34 | + |
| 35 | + with root_span.start_as_current_observation( |
| 36 | + as_type="generation", |
| 37 | + name="generate-response", |
| 38 | + model=runtime.context.llm.model, |
| 39 | + input=messages, |
| 40 | + prompt=prompt_client, |
| 41 | + model_parameters={"temperature": llm.temperature}, |
| 42 | + ) as gen: |
| 43 | + ai_msg = llm.invoke(messages) |
| 44 | + |
| 45 | + gen.update(output=ai_msg, usage_details=ai_msg.usage_metadata) |
| 46 | + |
| 47 | + return {"messages": [ai_msg]} |
21 | 48 |
|
22 | 49 |
|
23 | 50 | def build_model(): |
|
0 commit comments